Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8f8974d65e | ||
|
|
df130aedd9 | ||
|
|
0ac8526053 | ||
|
|
6419f4e8d3 | ||
|
|
af7d1b4da4 | ||
|
|
25d030601d | ||
|
|
8629b5dcbf | ||
|
|
90a2bc9ba6 | ||
|
|
a972285787 | ||
|
|
d84cc7e13e | ||
|
|
7f43dc1778 | ||
|
|
e9924ddef8 | ||
|
|
b2c0e12066 | ||
|
|
38af471054 | ||
|
|
f7ae13a909 | ||
|
|
9a74c8eefe | ||
|
|
14c24a51a4 | ||
|
|
35496741ce | ||
|
|
3c6f90d508 | ||
|
|
da024d997a | ||
|
|
ba6078feab | ||
|
|
9240d35d9e | ||
|
|
7a3ba178ec | ||
|
|
77832d53c4 | ||
|
|
d127ab4ecb | ||
|
|
f4fce0a1ef | ||
|
|
2daf6c9cda | ||
|
|
aeda636983 | ||
|
|
a7c0864279 | ||
|
|
aae2beeac8 | ||
|
|
f745079f0a | ||
|
|
5b83102a59 | ||
|
|
eb5e4aa915 | ||
|
|
d6d8b299dd | ||
|
|
ea0e97d930 | ||
|
|
84e46162fd | ||
|
|
14580c34e0 | ||
|
|
ae610733cc | ||
|
|
846afed86c | ||
|
|
99a6c17c23 | ||
|
|
04f49cb62f | ||
|
|
3c7f4f6e16 | ||
|
|
dcd407a3da | ||
|
|
fde63f8e72 | ||
|
|
1f8f1b9507 |
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",
|
||||
|
||||
@@ -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';
|
||||
@@ -58,6 +59,7 @@ import { SuppressionsModule } from './routes/suppressions/suppressions.module';
|
||||
AuthModule,
|
||||
AppConfigModule,
|
||||
DocumentsLegauxModule,
|
||||
ScheduleModule.forRoot(),
|
||||
EvenementsAgendaModule,
|
||||
CardsModule,
|
||||
RelaisModule,
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -14,16 +14,19 @@ 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' })
|
||||
@@ -83,6 +86,27 @@ export class CardInstance {
|
||||
@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[];
|
||||
|
||||
|
||||
@@ -47,6 +47,10 @@ export class CardResponse {
|
||||
@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;
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
} 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',
|
||||
@@ -21,12 +22,13 @@ 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. Ticket #205.
|
||||
* Les cartes collectent ; cette table historise. Tickets #205 / #214.
|
||||
*/
|
||||
@Entity('evenements_agenda', { schema: 'public' })
|
||||
export class EvenementsAgenda {
|
||||
@@ -74,13 +76,40 @@ export class EvenementsAgenda {
|
||||
@JoinColumn({ name: 'cree_par', referencedColumnName: 'id' })
|
||||
createdBy?: Users;
|
||||
|
||||
/** Réf. carte de collecte (FK quand module Cartes existera). */
|
||||
/** 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;
|
||||
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -79,6 +79,7 @@ export class CardsController {
|
||||
|
||||
@Post(':id/respond')
|
||||
@Roles(RoleType.PARENT, RoleType.ASSISTANTE_MATERNELLE)
|
||||
@HttpCode(HttpStatus.OK)
|
||||
@ApiOperation({ summary: 'Répondre (accept / refuse / ack) — #194' })
|
||||
@ApiBody({ type: RepondreCarteDto })
|
||||
repondre(
|
||||
|
||||
@@ -373,4 +373,80 @@ describe('CardsService (#194)', () => {
|
||||
]),
|
||||
);
|
||||
});
|
||||
|
||||
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),
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -92,11 +92,11 @@ export class CardsService {
|
||||
.leftJoinAndSelect('c.type', 'type')
|
||||
.leftJoinAndSelect('c.responses', 'responses')
|
||||
.where('c.purge_at > now()')
|
||||
.orderBy(
|
||||
`CASE c.statut WHEN 'refusee' THEN 0 WHEN 'ouverte' THEN 1 ELSE 2 END`,
|
||||
'ASC',
|
||||
)
|
||||
.addOrderBy('c.modifie_le', 'DESC');
|
||||
.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);
|
||||
@@ -251,6 +251,10 @@ export class CardsService {
|
||||
): 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');
|
||||
}
|
||||
@@ -285,8 +289,11 @@ export class CardsService {
|
||||
}),
|
||||
);
|
||||
|
||||
if (card.id_evenement) {
|
||||
if (dto.action === CardResponseActionType.ACCEPT || dto.action === CardResponseActionType.ACK) {
|
||||
// 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,
|
||||
});
|
||||
@@ -298,8 +305,6 @@ export class CardsService {
|
||||
});
|
||||
card.statut = CardInstanceStatutType.REFUSEE;
|
||||
}
|
||||
} else if (dto.action === CardResponseActionType.ACK) {
|
||||
card.statut = CardInstanceStatutType.TRAITEE;
|
||||
}
|
||||
|
||||
card.purge_at = this.purgeAt(card.type.retention_days, card.statut);
|
||||
@@ -456,22 +461,21 @@ export class CardsService {
|
||||
}
|
||||
|
||||
const audienceIds = await this.audienceUserIds(card);
|
||||
// Soft-cancel événement lié (matrice temporelle côté evenements) — #216
|
||||
if (card.id_evenement) {
|
||||
const absStatut =
|
||||
card.statut === CardInstanceStatutType.TRAITEE
|
||||
? null
|
||||
: card.id_evenement;
|
||||
// Supprime l’absence liée si pas encore acceptée définitivement (ou si soin_enfant dans les 24h)
|
||||
if (
|
||||
card.statut === CardInstanceStatutType.OUVERTE ||
|
||||
card.statut === CardInstanceStatutType.REFUSEE ||
|
||||
card.type_code === 'soin_enfant'
|
||||
) {
|
||||
await this.evenementsService.supprimer(userId, role, card.id_evenement);
|
||||
}
|
||||
void absStatut;
|
||||
await this.evenementsService.supprimer(userId, role, card.id_evenement);
|
||||
}
|
||||
await this.cardsRepo.delete({ id: cardId });
|
||||
// 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,
|
||||
});
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,7 @@ 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)' })
|
||||
@@ -63,6 +64,25 @@ export class MajEvenementAgendaDto {
|
||||
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;
|
||||
@@ -70,27 +90,82 @@ export class EvenementAgendaDto {
|
||||
@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()
|
||||
@ApiProperty({ example: '2026-10-01' })
|
||||
date_debut: string;
|
||||
|
||||
@ApiProperty()
|
||||
@ApiProperty({ example: '2026-10-05' })
|
||||
date_fin: string;
|
||||
|
||||
@ApiProperty({ enum: StatutEvenementAgendaType })
|
||||
@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()
|
||||
@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;
|
||||
|
||||
@@ -106,6 +181,9 @@ export class EvenementAgendaDto {
|
||||
@ApiPropertyOptional()
|
||||
nom_am?: string | null;
|
||||
|
||||
@ApiProperty({ type: EvenementAgendaActionsDto })
|
||||
actions: EvenementAgendaActionsDto;
|
||||
|
||||
@ApiProperty()
|
||||
cree_le: string;
|
||||
|
||||
|
||||
@@ -10,6 +10,7 @@ describe('EvenementsAgendaController (#172)', () => {
|
||||
let controller: EvenementsAgendaController;
|
||||
const serviceMock = {
|
||||
lister: jest.fn(),
|
||||
getById: jest.fn(),
|
||||
creer: jest.fn(),
|
||||
maj: jest.fn(),
|
||||
supprimer: jest.fn(),
|
||||
@@ -70,4 +71,14 @@ describe('EvenementsAgendaController (#172)', () => {
|
||||
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,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -47,16 +47,18 @@ export class EvenementsAgendaController {
|
||||
@Get()
|
||||
@Roles(RoleType.PARENT, RoleType.ASSISTANTE_MATERNELLE)
|
||||
@ApiOperation({
|
||||
summary: 'Lister les absences / congés / arrêts — ticket #205 / ex-#172',
|
||||
summary: 'Lister les événements agenda — #217 / #205',
|
||||
description:
|
||||
'Sans placementId : tous les placements du user (parent = famille multi-AM ; AM = tous accueils). ' +
|
||||
'Avec placementId : un couple enfant–AM.',
|
||||
'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' })
|
||||
@ApiQuery({ name: 'to', required: false, description: 'YYYY-MM-DD' })
|
||||
@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,
|
||||
@@ -76,6 +78,24 @@ export class EvenementsAgendaController {
|
||||
});
|
||||
}
|
||||
|
||||
@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' })
|
||||
|
||||
@@ -3,14 +3,23 @@ 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, AmChildren, ParentsChildren]),
|
||||
TypeOrmModule.forFeature([
|
||||
EvenementsAgenda,
|
||||
AgendaLots,
|
||||
CardInstance,
|
||||
AmChildren,
|
||||
ParentsChildren,
|
||||
]),
|
||||
JwtModule.registerAsync({
|
||||
imports: [ConfigModule],
|
||||
useFactory: (config: ConfigService) => ({
|
||||
@@ -21,7 +30,7 @@ import { EvenementsAgendaService } from './evenements-agenda.service';
|
||||
}),
|
||||
],
|
||||
controllers: [EvenementsAgendaController],
|
||||
providers: [EvenementsAgendaService],
|
||||
providers: [EvenementsAgendaService, AgendaExpirationCron],
|
||||
exports: [EvenementsAgendaService],
|
||||
})
|
||||
export class EvenementsAgendaModule {}
|
||||
|
||||
@@ -7,9 +7,22 @@ import {
|
||||
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;
|
||||
@@ -22,9 +35,19 @@ describe('EvenementsAgendaService (#172)', () => {
|
||||
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(),
|
||||
@@ -39,6 +62,8 @@ describe('EvenementsAgendaService (#172)', () => {
|
||||
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),
|
||||
@@ -48,6 +73,8 @@ describe('EvenementsAgendaService (#172)', () => {
|
||||
}).compile();
|
||||
service = module.get(EvenementsAgendaService);
|
||||
jest.clearAllMocks();
|
||||
lotsRepo.createQueryBuilder.mockImplementation(() => qbUpdateMock());
|
||||
cardsRepo.createQueryBuilder.mockImplementation(() => qbUpdateMock());
|
||||
});
|
||||
|
||||
it('should be defined', () => {
|
||||
@@ -165,4 +192,477 @@ describe('EvenementsAgendaService (#172)', () => {
|
||||
}),
|
||||
).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);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -2,35 +2,58 @@ import {
|
||||
BadRequestException,
|
||||
ForbiddenException,
|
||||
Injectable,
|
||||
Logger,
|
||||
NotFoundException,
|
||||
} from '@nestjs/common';
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
import { In, IsNull, Repository } from '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';
|
||||
|
||||
const TTL_EN_ATTENTE_MS = 15 * 24 * 60 * 60 * 1000;
|
||||
const TTL_REFUSE_MS = 7 * 24 * 60 * 60 * 1000;
|
||||
/** 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)
|
||||
@@ -48,10 +71,14 @@ export class EvenementsAgendaService {
|
||||
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: [] };
|
||||
@@ -63,15 +90,22 @@ export class EvenementsAgendaService {
|
||||
.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 });
|
||||
}
|
||||
@@ -80,7 +114,18 @@ export class EvenementsAgendaService {
|
||||
}
|
||||
|
||||
const rows = await qb.getMany();
|
||||
return { items: rows.map((r) => this.toDto(r)) };
|
||||
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(
|
||||
@@ -89,17 +134,23 @@ export class EvenementsAgendaService {
|
||||
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),
|
||||
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,
|
||||
});
|
||||
@@ -117,38 +168,76 @@ export class EvenementsAgendaService {
|
||||
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);
|
||||
// Parent : peut modifier ses absences enfant
|
||||
// AM : peut modifier congé/arrêt en_attente (avant accept) ou dates si créateur
|
||||
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;
|
||||
if (row.statut === StatutEvenementAgendaType.EN_ATTENTE) {
|
||||
row.expire_at = this.expireAtFor(StatutEvenementAgendaType.EN_ATTENTE);
|
||||
|
||||
// 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 && dto.statut !== row.statut) {
|
||||
this.assertCanChangeStatut(role, row, dto.statut, dto.motif);
|
||||
if (dto.statut !== undefined) {
|
||||
// Ack arrêt = informatif carte seulement — toute maj statut parent sur arrêt → 400
|
||||
if (
|
||||
dto.statut === StatutEvenementAgendaType.REFUSE &&
|
||||
(!dto.motif || !dto.motif.trim())
|
||||
role === RoleType.PARENT &&
|
||||
row.type === TypeEvenementAgendaType.ARRET_MALADIE_AM
|
||||
) {
|
||||
throw new BadRequestException(
|
||||
'Une motivation est obligatoire en cas de refus',
|
||||
'L’accusé de réception d’un arrêt maladie n’écrit pas sur l’événement',
|
||||
);
|
||||
}
|
||||
row.statut = dto.statut;
|
||||
row.expire_at = this.expireAtFor(dto.statut);
|
||||
if (dto.motif?.trim()) {
|
||||
row.motif = dto.motif.trim();
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -156,6 +245,10 @@ export class EvenementsAgendaService {
|
||||
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,
|
||||
@@ -176,7 +269,140 @@ export class EvenementsAgendaService {
|
||||
);
|
||||
}
|
||||
|
||||
await this.absencesRepo.delete({ id });
|
||||
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(
|
||||
@@ -186,31 +412,171 @@ export class EvenementsAgendaService {
|
||||
): Promise<EvenementAgendaDto> {
|
||||
const row = await this.absencesRepo.findOne({
|
||||
where: { id },
|
||||
relations: ['placement', 'placement.child', 'placement.am', 'placement.am.user'],
|
||||
relations: [
|
||||
'placement',
|
||||
'placement.child',
|
||||
'placement.am',
|
||||
'placement.am.user',
|
||||
'lot',
|
||||
],
|
||||
});
|
||||
if (!row) {
|
||||
throw new NotFoundException('Absence introuvable');
|
||||
throw new NotFoundException('Événement introuvable');
|
||||
}
|
||||
await this.assertCanAccessPlacement(userId, role, row.id_placement);
|
||||
return this.toDto(row);
|
||||
// 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 {
|
||||
if (type === TypeEvenementAgendaType.ABSENCE_ENFANT || type === TypeEvenementAgendaType.SOIN_ENFANT) {
|
||||
// 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): Date {
|
||||
const now = Date.now();
|
||||
if (statut === StatutEvenementAgendaType.ACCEPTE) {
|
||||
return EXPIRE_ACCEPTE;
|
||||
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(now + TTL_REFUSE_MS);
|
||||
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();
|
||||
}
|
||||
return new Date(now + TTL_EN_ATTENTE_MS);
|
||||
}
|
||||
|
||||
private assertDates(debut: string, fin: string): void {
|
||||
@@ -221,6 +587,33 @@ export class EvenementsAgendaService {
|
||||
}
|
||||
}
|
||||
|
||||
/** 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) {
|
||||
@@ -258,6 +651,9 @@ export class EvenementsAgendaService {
|
||||
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
|
||||
@@ -269,7 +665,6 @@ export class EvenementsAgendaService {
|
||||
) {
|
||||
throw new ForbiddenException('Statut incompatible avec une modification');
|
||||
}
|
||||
// Accepté : autorisé (S2b — re-validation via cartes plus tard ; API permet update dates)
|
||||
return;
|
||||
}
|
||||
throw new ForbiddenException('Type non modifiable par l’AM');
|
||||
@@ -284,25 +679,20 @@ export class EvenementsAgendaService {
|
||||
_motif?: string,
|
||||
): void {
|
||||
if (role === RoleType.PARENT) {
|
||||
// Accept / refuse congé ; ack arrêt (accepte)
|
||||
if (
|
||||
row.type === TypeEvenementAgendaType.CONGE_AM ||
|
||||
row.type === TypeEvenementAgendaType.ARRET_MALADIE_AM
|
||||
) {
|
||||
// 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.type === TypeEvenementAgendaType.ARRET_MALADIE_AM &&
|
||||
next === StatutEvenementAgendaType.REFUSE
|
||||
) {
|
||||
throw new BadRequestException(
|
||||
'Un arrêt maladie ne se refuse pas (accusé seulement)',
|
||||
);
|
||||
}
|
||||
if (row.statut !== StatutEvenementAgendaType.EN_ATTENTE) {
|
||||
throw new BadRequestException('Cette demande n’est plus en attente');
|
||||
}
|
||||
@@ -332,9 +722,12 @@ export class EvenementsAgendaService {
|
||||
userId: string,
|
||||
role: RoleType,
|
||||
placementId?: string,
|
||||
opts?: { includeEnded?: boolean },
|
||||
): Promise<string[]> {
|
||||
if (placementId) {
|
||||
await this.assertCanAccessPlacement(userId, role, placementId);
|
||||
await this.assertCanAccessPlacement(userId, role, placementId, {
|
||||
allowEnded: opts?.includeEnded === true,
|
||||
});
|
||||
return [placementId];
|
||||
}
|
||||
|
||||
@@ -346,7 +739,9 @@ export class EvenementsAgendaService {
|
||||
const enfantIds = liens.map((l) => l.enfantId);
|
||||
if (enfantIds.length === 0) return [];
|
||||
const placements = await this.amChildrenRepo.find({
|
||||
where: { enfantId: In(enfantIds), date_fin: IsNull() },
|
||||
where: opts?.includeEnded
|
||||
? { enfantId: In(enfantIds) }
|
||||
: { enfantId: In(enfantIds), date_fin: IsNull() },
|
||||
select: ['id'],
|
||||
});
|
||||
return placements.map((p) => p.id);
|
||||
@@ -354,7 +749,9 @@ export class EvenementsAgendaService {
|
||||
|
||||
if (role === RoleType.ASSISTANTE_MATERNELLE) {
|
||||
const placements = await this.amChildrenRepo.find({
|
||||
where: { amId: userId, date_fin: IsNull() },
|
||||
where: opts?.includeEnded
|
||||
? { amId: userId }
|
||||
: { amId: userId, date_fin: IsNull() },
|
||||
select: ['id'],
|
||||
});
|
||||
return placements.map((p) => p.id);
|
||||
@@ -367,12 +764,19 @@ export class EvenementsAgendaService {
|
||||
userId: string,
|
||||
role: RoleType,
|
||||
placementId: string,
|
||||
opts?: { allowEnded?: boolean },
|
||||
): Promise<AmChildren> {
|
||||
const placement = await this.amChildrenRepo.findOne({
|
||||
where: { id: placementId, date_fin: IsNull() },
|
||||
where: opts?.allowEnded
|
||||
? { id: placementId }
|
||||
: { id: placementId, date_fin: IsNull() },
|
||||
});
|
||||
if (!placement) {
|
||||
throw new NotFoundException('Placement / couple introuvable ou inactif');
|
||||
throw new NotFoundException(
|
||||
opts?.allowEnded
|
||||
? 'Placement / couple introuvable'
|
||||
: 'Placement / couple introuvable ou inactif',
|
||||
);
|
||||
}
|
||||
|
||||
if (role === RoleType.ASSISTANTE_MATERNELLE) {
|
||||
@@ -397,26 +801,187 @@ export class EvenementsAgendaService {
|
||||
throw new ForbiddenException('Rôle non autorisé');
|
||||
}
|
||||
|
||||
private toDto(row: EvenementsAgenda): EvenementAgendaDto {
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -157,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);
|
||||
|
||||
@@ -217,7 +217,7 @@ export class EnfantsService {
|
||||
}
|
||||
}
|
||||
|
||||
await this.childrenRepository.update(id, patch);
|
||||
await this.childrenRepository.update(id, patch as any);
|
||||
return this.findOne(id, currentUser);
|
||||
}
|
||||
|
||||
|
||||
@@ -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
|
||||
+43
-3
@@ -42,7 +42,12 @@ DO $$ BEGIN
|
||||
END IF;
|
||||
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'
|
||||
'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
|
||||
@@ -109,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
|
||||
@@ -321,9 +327,31 @@ CREATE TABLE avenants_contrats (
|
||||
modifie_le TIMESTAMPTZ DEFAULT now()
|
||||
);
|
||||
|
||||
-- ==========================================================
|
||||
-- Table : agenda_lots (cycles collectifs versionnés — #214)
|
||||
-- ==========================================================
|
||||
CREATE TABLE agenda_lots (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
type type_evenement_agenda_type NOT NULL,
|
||||
statut agenda_lot_statut_type NOT NULL DEFAULT 'en_attente',
|
||||
revision INT NOT NULL DEFAULT 1,
|
||||
soumis_le TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
verrouille_le TIMESTAMPTZ,
|
||||
refuse_le TIMESTAMPTZ,
|
||||
annule_le TIMESTAMPTZ,
|
||||
annule_par UUID REFERENCES utilisateurs(id) ON DELETE SET NULL,
|
||||
cree_par UUID REFERENCES utilisateurs(id) ON DELETE SET NULL,
|
||||
cree_le TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
modifie_le TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
CONSTRAINT chk_agenda_lots_revision CHECK (revision >= 1)
|
||||
);
|
||||
|
||||
CREATE INDEX idx_agenda_lots_type_statut ON agenda_lots (type, statut);
|
||||
CREATE INDEX idx_agenda_lots_soumis_le ON agenda_lots (soumis_le);
|
||||
|
||||
-- ==========================================================
|
||||
-- Table : evenements_agenda (vérité métier agenda (absences/congés/arrêt + futurs types))
|
||||
-- 1 ligne = 1 période ; rattachement = placement AM↔enfant (#193)
|
||||
-- 1 ligne = 1 période ; rattachement = placement AM↔enfant (#193 / #214)
|
||||
-- ==========================================================
|
||||
CREATE TABLE evenements_agenda (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
@@ -337,6 +365,12 @@ CREATE TABLE evenements_agenda (
|
||||
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)
|
||||
@@ -349,6 +383,12 @@ CREATE INDEX idx_evenements_agenda_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
|
||||
|
||||
+17
-2
@@ -119,7 +119,7 @@ Ce document recense **toutes les valeurs énumérées** utilisées dans la base
|
||||
|
||||
---
|
||||
|
||||
## 8) Statut d’absence de garde — `statut`
|
||||
## 8) Statut d’événement agenda — `statut`
|
||||
|
||||
**Tables/colonnes** : `evenements_agenda.statut`
|
||||
**Valeurs autorisées** :
|
||||
@@ -128,7 +128,22 @@ Ce document recense **toutes les valeurs énumérées** utilisées dans la base
|
||||
|---|---|
|
||||
| `en_attente` | En attente de validation / ack |
|
||||
| `accepte` | Accepté / acté (conservé en historique métier) |
|
||||
| `refuse` | Refusé (temporaire ; purge TTL) |
|
||||
| `refuse` | Refusé (temporaire ; visible barré puis soft-cancel) |
|
||||
| `annule` | Annulation douce (#214) — hors vues normales, auditable |
|
||||
|
||||
---
|
||||
|
||||
## 8bis) Statut de lot agenda — `agenda_lots.statut`
|
||||
|
||||
**Enum** : `agenda_lot_statut_type`
|
||||
**Valeurs** : `en_attente` · `accepte` · `refuse` · `annule` (issue globale du lot versionné, #214)
|
||||
|
||||
---
|
||||
|
||||
## 8ter) Cartes — soft-cancel / opération
|
||||
|
||||
**`card_instance_statut_type`** : `ouverte` · `refusee` · `traitee` · `annulee` (#214)
|
||||
**`card_operation_type`** : `create` · `update` · `cancel` (#214)
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -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';
|
||||
@@ -79,12 +79,42 @@ 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) Absences_garde (30 derniers jours) ====================='
|
||||
SELECT ag.id, ag.type, ag.id_placement, ag.date_debut, ag.date_fin, ag.statut, ag.expire_at
|
||||
\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
|
||||
FROM uploads up
|
||||
|
||||
+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}
|
||||
|
||||
+3
-1
@@ -12,6 +12,8 @@ Index de navigation du dépôt. Dernière révision : **septembre 2026** (CDC V1
|
||||
| [29 — Bilan version 0.1.0](./29_BILAN-VERSION-0.1.0.md) | Tickets livrés 0.1.0 |
|
||||
| [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 |
|
||||
|
||||
@@ -38,7 +40,7 @@ Index de navigation du dépôt. Dernière révision : **septembre 2026** (CDC V1
|
||||
| Doc | Contenu |
|
||||
|-----|---------|
|
||||
| [CHARTE_GRAPHIQUE.md](./CHARTE_GRAPHIQUE.md) | Charte UI |
|
||||
| [maquettes/](./maquettes/README.md) | Maquettes TdB quotidien (réf. v4 + historique) |
|
||||
| [maquettes/](./maquettes/README.md) | Maquettes TdB quotidien + Agenda semaine (réf. v4) |
|
||||
|
||||
## Projet & outillage
|
||||
|
||||
|
||||
@@ -63,6 +63,8 @@ Bandeau : **TdB** · **Agenda** · **Contrat** · menu user (recherche AM, param
|
||||
|
||||
## 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 |
|
||||
@@ -83,7 +85,7 @@ Bandeau : **TdB** · **Agenda** · **Contrat** · menu user (recherche AM, param
|
||||
## 6. Hors périmètre de ce jalon
|
||||
|
||||
- Page **Contrat** riche (Pajemploi, CP…) — stub bandeau OK
|
||||
- **Agenda** calendrier riche — stub bandeau OK
|
||||
- **Agenda** calendrier riche — voir [`33_MINI-SPEC-AGENDA.md`](./33_MINI-SPEC-AGENDA.md) (vue semaine)
|
||||
- Notifications CDC fourre-tout (paiement, dossier…)
|
||||
- Masquage messages ; posts blog parent
|
||||
- Carnet repas/sieste (roadmap Phase 4)
|
||||
|
||||
@@ -99,8 +99,8 @@ Clé = **choix front**, pas une valeur API.
|
||||
| **`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).
|
||||
Les **modifications d’absence** se font via l’**agenda / calendrier**, pas via une bulle dédiée. On rebranchera une notif éventuelle quand le calendrier sera implémenté.
|
||||
**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**
|
||||
|
||||
@@ -153,13 +153,15 @@ 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.
|
||||
- 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.
|
||||
- File courte : `purge_at` ; l’**agenda** conserve l’historique métier ; carte purgée reste adressable depuis l’Agenda (33).
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -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.
|
||||
+12
-10
@@ -1,29 +1,31 @@
|
||||
# Maquettes — espaces parent / AM (quotidien)
|
||||
# Maquettes — espaces parent / AM
|
||||
|
||||
Références visuelles issues de l’atelier de cadrage (sept. 2026).
|
||||
Références visuelles issues des ateliers de cadrage (sept.–oct. 2026).
|
||||
|
||||
## Organisation
|
||||
|
||||
| Dossier | Contenu |
|
||||
|---------|---------|
|
||||
| [`courantes/`](./courantes/) | **Référence active** — à utiliser pour tickets / implémentation |
|
||||
| [`historique/`](./historique/) | Itérations précédentes + croquis manuscrit (conservées pour traçabilité) |
|
||||
| [`historique/`](./historique/) | Itérations précédentes + croquis (traçabilité) |
|
||||
|
||||
## Référence active
|
||||
## Références actives
|
||||
|
||||
| Fichier | Description |
|
||||
|---------|-------------|
|
||||
| [`courantes/maquette-dashboard-parent-quotidien-v4.png`](./courantes/maquette-dashboard-parent-quotidien-v4.png) | TdB parent PC — **3 colonnes** : cartes + couple · blog (défaut) · messagerie (AM / RPE) |
|
||||
| [`courantes/maquette-dashboard-parent-quotidien-v4.png`](./courantes/maquette-dashboard-parent-quotidien-v4.png) | TdB parent PC — **3 colonnes** : cartes + couple · blog · messagerie |
|
||||
| [`courantes/maquette-agenda-semaine-v4.jpg`](./courantes/maquette-agenda-semaine-v4.jpg) | **Agenda vue semaine** — lignes = semaines ISO, maître + fantômes, illustres jours vides |
|
||||
|
||||
## Historique
|
||||
|
||||
| Fichier | Note |
|
||||
|---------|------|
|
||||
| [`historique/croquis-dashboard-parent-2026-09-23.jpg`](./historique/croquis-dashboard-parent-2026-09-23.jpg) | Wireframe manuscrit (WhatsApp) — point de départ layout |
|
||||
| `…-v1.png` | Première génération IA (~50/50) |
|
||||
| `…-v2.png` | Recadrage 1/3 + 2/3 (onglets Mess/Blog à droite) |
|
||||
| `…-v3.png` | Couple enfant–nounou (encore 2 colonnes) |
|
||||
| [`historique/croquis-dashboard-parent-2026-09-23.jpg`](./historique/croquis-dashboard-parent-2026-09-23.jpg) | Wireframe manuscrit TdB |
|
||||
| `…-quotidien-v1.png` … `v3.png` | Itérations TdB |
|
||||
| `historique/maquette-agenda-semaine-v2.jpg` | Première synthèse Agenda semaine |
|
||||
| `historique/maquette-agenda-semaine-v3.jpg` | En-têtes jour une seule fois |
|
||||
|
||||
## Suite éventuelle
|
||||
|
||||
- Maquette **TdB AM** (miroir : bandeau enfant \| parent(s)) — pas encore générée.
|
||||
- Maquette **vue mois** Agenda (grille + feed) — lot de spec séparé.
|
||||
- Maquette **TdB AM** (miroir couple) — pas encore générée.
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 208 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 204 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 194 KiB |
@@ -0,0 +1,89 @@
|
||||
# Mini-spec API — POST /parents/dossier (#129)
|
||||
|
||||
Contrat pour le **plan front** (wizard création dossier famille staff).
|
||||
|
||||
Miroir de **#156** (`POST /assistantes-maternelles/dossier`).
|
||||
|
||||
## Endpoint
|
||||
|
||||
| | |
|
||||
|--|--|
|
||||
| **Méthode** | `POST` |
|
||||
| **URL** | `{base}/parents/dossier` |
|
||||
| **Auth** | Bearer JWT |
|
||||
| **Rôles** | `gestionnaire`, `administrateur`, `super_admin` |
|
||||
| **Content-Type** | `application/json` |
|
||||
|
||||
Ne **pas** appeler `POST /auth/register/parent` depuis le dashboard.
|
||||
|
||||
## Body (JSON)
|
||||
|
||||
Aligné `RegisterParentCompletDto`, **sans** CGU/privacy obligatoires (acceptées serveur).
|
||||
|
||||
### Parent 1 (obligatoire)
|
||||
|
||||
| Champ | Type | Obligatoire | Notes |
|
||||
|-------|------|-------------|--------|
|
||||
| `email` | string | oui | unique |
|
||||
| `prenom` | string | oui | |
|
||||
| `nom` | string | oui | |
|
||||
| `telephone` | string | oui | `0X…` ou `+33…` |
|
||||
| `adresse` | string | non | |
|
||||
| `code_postal` | string | non | |
|
||||
| `ville` | string | non | |
|
||||
|
||||
### Co-parent (optionnel)
|
||||
|
||||
`co_parent_email`, `co_parent_prenom`, `co_parent_nom`, `co_parent_telephone`,
|
||||
`co_parent_meme_adresse`, `co_parent_adresse`, `co_parent_code_postal`, `co_parent_ville`.
|
||||
|
||||
Si co-parent fourni : e-mail distinct ; mêmes règles téléphone / adresse que register.
|
||||
|
||||
### Enfants (≥ 1)
|
||||
|
||||
| Champ | Type | Notes |
|
||||
|-------|------|--------|
|
||||
| `enfants` | `EnfantInscriptionDto[]` | `prenom`, `nom`, `date_naissance` / `date_previsionnelle_naissance`, `genre`, `photo_base64`, `photo_filename`, etc. |
|
||||
|
||||
### Présentation
|
||||
|
||||
| Champ | Type | Obligatoire |
|
||||
|-------|------|-------------|
|
||||
| `presentation_dossier` | string | non (max 2000) |
|
||||
|
||||
## Réponses
|
||||
|
||||
### 201 Created
|
||||
|
||||
```json
|
||||
{
|
||||
"message": "Dossier famille créé et validé. Un e-mail de création de mot de passe a été envoyé.",
|
||||
"numero_dossier": "2026-000043",
|
||||
"parent_user_id": "uuid-pivot",
|
||||
"co_parent_user_id": "uuid-ou-null",
|
||||
"statut": "actif",
|
||||
"enfant_ids": ["uuid", "..."]
|
||||
}
|
||||
```
|
||||
|
||||
Effets serveur : user(s) parent **actif**, fiches `parents`, enfants + foyer, n° dossier,
|
||||
**e-mail création MDP** pour chaque compte sans MDP (pas d’accusé « en attente »).
|
||||
|
||||
### Erreurs
|
||||
|
||||
| Code | Cas |
|
||||
|------|-----|
|
||||
| 400 | Validation DTO / métier (enfants vides, dates, etc.) |
|
||||
| 401 | Token manquant / invalide |
|
||||
| 403 | Rôle non staff |
|
||||
| 409 | Conflit e-mail (pivot et/ou co-parent) |
|
||||
|
||||
## Front
|
||||
|
||||
- `UserService.createParentDossier(body)` → cet endpoint
|
||||
- Wizard create basé sur `ValidationFamilyWizard`
|
||||
- Ne pas envoyer `acceptation_cgu` / `acceptation_privacy` (optionnels)
|
||||
|
||||
## Branche
|
||||
|
||||
`feature/129-creation-dossier-parent`
|
||||
@@ -0,0 +1,73 @@
|
||||
# Mini-spec API — POST /parents/:id/co-parent (#135)
|
||||
|
||||
Contrat back pour l’ajout d’un **2ᵉ parent** sur un foyer mono-parent (staff).
|
||||
|
||||
## Endpoint
|
||||
|
||||
| | |
|
||||
|--|--|
|
||||
| **Méthode** | `POST` |
|
||||
| **URL** | `{base}/api/v1/parents/{parentUserId}/co-parent` |
|
||||
| **Auth** | Bearer JWT |
|
||||
| **Rôles** | `gestionnaire`, `administrateur`, `super_admin` |
|
||||
| **Succès** | **201** |
|
||||
|
||||
`parentUserId` = UUID du **parent pivot** (déjà dans le dossier).
|
||||
|
||||
Ne **pas** appeler `POST /auth/register/parent` ni `POST /parents/dossier`.
|
||||
|
||||
---
|
||||
|
||||
## Body (JSON)
|
||||
|
||||
| Champ | Type | Obligatoire | Notes |
|
||||
|-------|------|-------------|--------|
|
||||
| `email` | string | oui | unique |
|
||||
| `prenom` | string | oui | |
|
||||
| `nom` | string | oui | |
|
||||
| `telephone` | string | oui | `0X…` ou `+33…` |
|
||||
| `meme_adresse` | bool | non | défaut **true** → copie adresse du pivot |
|
||||
| `adresse` | string | si `meme_adresse=false` | |
|
||||
| `code_postal` | string | si `meme_adresse=false` | |
|
||||
| `ville` | string | si `meme_adresse=false` | |
|
||||
|
||||
---
|
||||
|
||||
## Comportement 201
|
||||
|
||||
- User co-parent **actif** + token création MDP
|
||||
- Fiche `parents` + liens pivot ↔ co-parent + même `numero_dossier`
|
||||
- Enfants du foyer rattachés au co-parent
|
||||
- E-mail **création MDP** (pas mail « en attente »)
|
||||
|
||||
```json
|
||||
{
|
||||
"message": "Co-parent ajouté au foyer. Un e-mail de création de mot de passe a été envoyé.",
|
||||
"numero_dossier": "2026-000043",
|
||||
"parent_user_id": "uuid-pivot",
|
||||
"co_parent_user_id": "uuid-co",
|
||||
"statut": "actif"
|
||||
}
|
||||
```
|
||||
|
||||
## Erreurs
|
||||
|
||||
| Code | Cas |
|
||||
|------|-----|
|
||||
| 400 | Déjà un co-parent / 2 responsables / validation adresse |
|
||||
| 401 | Token invalide |
|
||||
| 403 | Rôle non staff |
|
||||
| 404 | Pivot introuvable |
|
||||
| 409 | Email déjà pris |
|
||||
|
||||
## Réemploi édition identité
|
||||
|
||||
| Endpoint | Usage |
|
||||
|----------|--------|
|
||||
| `GET /dossiers/:numero` | Préremplir wizard edit |
|
||||
| `PATCH /parents/:id/fiche` | Sauver identité pivot / co-parent existant |
|
||||
| `PATCH /assistantes-maternelles/:id/fiche` | Édition AM |
|
||||
|
||||
## Branche
|
||||
|
||||
`feature/135-edition-dossier`
|
||||
@@ -0,0 +1,83 @@
|
||||
# Mini-spec front — Mode édition dossier + ajout 2ᵉ parent (#135)
|
||||
|
||||
Branche : `feature/135-edition-dossier`
|
||||
Ticket : **#135** (full-stack)
|
||||
|
||||
Prérequis : **#153** (liste Dossiers) livré.
|
||||
|
||||
---
|
||||
|
||||
## Objectif
|
||||
|
||||
1. Clic sur un dossier (liste #153) → ouvrir le wizard en mode **`edit`**
|
||||
2. Foyer **mono-parent** : page co-parent → **switch** ajouter un 2ᵉ parent
|
||||
3. Sauvegarder les champs via APIs existantes + nouvel endpoint co-parent
|
||||
|
||||
---
|
||||
|
||||
## Modes wizard
|
||||
|
||||
| Mode | Famille | AM |
|
||||
|------|---------|-----|
|
||||
| `review` | déjà | déjà |
|
||||
| `create` | déjà (#129) | déjà (#156) |
|
||||
| **`edit`** | **à faire** | **à faire** |
|
||||
|
||||
Factories : `ParentDossierWizard.edit(...)` / `AmDossierWizard.edit(...)`
|
||||
Préremplir via `UserService.getDossierByNumero(numero)`.
|
||||
|
||||
---
|
||||
|
||||
## APIs
|
||||
|
||||
| Action | Endpoint |
|
||||
|--------|----------|
|
||||
| Charger | `GET /dossiers/:numero` |
|
||||
| Sauver parent | `PATCH /parents/:id/fiche` |
|
||||
| Sauver AM | `PATCH /assistantes-maternelles/:id/fiche` |
|
||||
| **Ajouter co-parent** | **`POST /parents/:pivotUserId/co-parent`** — voir `docs/tmp/135-contrat-api-ajout-co-parent.md` |
|
||||
|
||||
Body co-parent :
|
||||
|
||||
```json
|
||||
{
|
||||
"email": "thomas@…",
|
||||
"prenom": "Thomas",
|
||||
"nom": "MARTIN",
|
||||
"telephone": "0678456789",
|
||||
"meme_adresse": true
|
||||
}
|
||||
```
|
||||
|
||||
`UserService.addCoParent(pivotUserId, body)` → cet endpoint.
|
||||
|
||||
---
|
||||
|
||||
## UX
|
||||
|
||||
- Depuis `DossiersManagementWidget` / carte liste : clic → edit (plus seulement review pending)
|
||||
- Pending : garder validation (review) ; dossiers actifs → edit
|
||||
- Mono-parent : switch « Ajouter un co-parent » (comme create) → au save, `POST …/co-parent` si nouveau
|
||||
- Déjà 2 parents : éditer les deux fiches ; pas de 3ᵉ
|
||||
- Pas de bouton créer dans l’onglet Dossiers
|
||||
|
||||
---
|
||||
|
||||
## Hors scope
|
||||
|
||||
- Famille N responsables (#139)
|
||||
- Suppressions (#154)
|
||||
- Création dossier initial (#129 / #156)
|
||||
|
||||
---
|
||||
|
||||
## Critères d’acceptation
|
||||
|
||||
- [ ] Clic dossier actif → wizard edit prérempli
|
||||
- [ ] PATCH fiche enregistre les modifs
|
||||
- [ ] Mono-parent + switch → co-parent créé (actif + mail MDP)
|
||||
- [ ] review / create inchangés
|
||||
|
||||
## Branche
|
||||
|
||||
`feature/135-edition-dossier`
|
||||
@@ -0,0 +1,65 @@
|
||||
# Mini-spec — Suppression complète grossesse multiple / `est_multiple`
|
||||
|
||||
**Ticket** : **#152** — https://git.ptits-pas.fr/jmartin/petitspas/issues/152
|
||||
**Branche** : `feature/152-remove-est-multiple` (depuis `develop`)
|
||||
**Périmètre** : **full stack** — BDD + back + front + scripts + docs. **Aucun fantôme.**
|
||||
|
||||
---
|
||||
|
||||
## Décision
|
||||
|
||||
On **supprime tout**. Pas de DTO « ignorés », pas de compat payload.
|
||||
|
||||
`forbidNonWhitelisted: true` ⇒ back et front **partent ensemble** (même feature / même déploiement).
|
||||
|
||||
---
|
||||
|
||||
## Alias retirés
|
||||
|
||||
`est_multiple` · `is_multiple` · `grossesse_multiple` · `multipleBirth` · `estMultiple` · `isMultiple` · `jumeau_multiple`
|
||||
|
||||
---
|
||||
|
||||
## Back / BDD (fait sur la branche)
|
||||
|
||||
- [x] Migration `database/migrations/2026_drop_enfants_est_multiple.sql`
|
||||
- [x] `BDD.sql`, seeds, CSV test
|
||||
- [x] Entity `Children` sans colonne
|
||||
- [x] DTO create/inscription/réponse/dossier famille **sans** le champ
|
||||
- [x] Services auth / enfants / parents : plus de mapping
|
||||
- [x] Prisma legacy `isMultiple` retiré
|
||||
|
||||
## Front (fait sur la branche)
|
||||
|
||||
- [x] Modèles admin / dossier / inscription
|
||||
- [x] Payloads inscription + reprise
|
||||
- [x] Modale enfant + wizard dossier famille
|
||||
- [x] Step3 inscription parent
|
||||
|
||||
## Scripts / docs
|
||||
|
||||
- [x] `tests/scripts/register-parent-*.mjs`
|
||||
- [x] `docs/10_DATABASE.md`, `docs/99_REGLES-CODAGE.md`
|
||||
- Docs tmp/archive #112 : mentions historiques OK (archive)
|
||||
|
||||
---
|
||||
|
||||
## Déploiement
|
||||
|
||||
1. Appliquer la migration SQL sur la BDD vivante
|
||||
2. Deploy back **et** front de cette branche
|
||||
3. Smoke : création enfant staff, inscription parent, reprise, wizard famille
|
||||
|
||||
## Vérif
|
||||
|
||||
```bash
|
||||
rg -n 'est_multiple|is_multiple|grossesse_multiple|multipleBirth|estMultiple|isMultiple|jumeau_multiple' \
|
||||
backend/src frontend/lib database tests/scripts docs/10_DATABASE.md docs/99_REGLES-CODAGE.md
|
||||
```
|
||||
→ **0** hit (hors ce fichier mini-spec / archives).
|
||||
|
||||
## Hors scope
|
||||
|
||||
- Métier futur « fratrie / jumeaux » → nouveau ticket
|
||||
- #155 rename Admin*
|
||||
- Ticket modales staff
|
||||
@@ -0,0 +1,77 @@
|
||||
# Mini-spec API — GET /dossiers (#153)
|
||||
|
||||
Contrat pour le **plan front** (onglet permanent Dossiers).
|
||||
|
||||
## Endpoint
|
||||
|
||||
| | |
|
||||
|--|--|
|
||||
| **Méthode** | `GET` |
|
||||
| **URL** | `{base}/api/v1/dossiers` |
|
||||
| **Auth** | Bearer JWT |
|
||||
| **Rôles** | `gestionnaire`, `administrateur`, `super_admin` |
|
||||
| **Query** | `q` (optionnel) — recherche n° / libellé / email |
|
||||
|
||||
Complète `GET /dossiers/:numeroDossier` (#119) déjà existant.
|
||||
|
||||
---
|
||||
|
||||
## Réponse 200
|
||||
|
||||
Tableau de lignes (1 entrée = 1 `numero_dossier`) :
|
||||
|
||||
```json
|
||||
[
|
||||
{
|
||||
"type": "famille",
|
||||
"numero_dossier": "2026-000043",
|
||||
"libelle": "Claire MARTIN & Thomas MARTIN",
|
||||
"emails": ["claire@test.fr", "thomas@test.fr"],
|
||||
"user_ids": ["uuid-pivot", "uuid-co"],
|
||||
"statut": "actif",
|
||||
"a_valider": false,
|
||||
"date_reference": "2026-01-12T10:00:00.000Z"
|
||||
},
|
||||
{
|
||||
"type": "assistante_maternelle",
|
||||
"numero_dossier": "2026-000042",
|
||||
"libelle": "Marie DUPONT",
|
||||
"emails": ["marie@test.fr"],
|
||||
"user_ids": ["uuid-am"],
|
||||
"statut": "en_attente",
|
||||
"a_valider": true,
|
||||
"date_reference": "2026-02-01T08:00:00.000Z"
|
||||
}
|
||||
]
|
||||
```
|
||||
|
||||
### Champs
|
||||
|
||||
| Champ | Notes |
|
||||
|-------|--------|
|
||||
| `type` | `famille` \| `assistante_maternelle` |
|
||||
| `numero_dossier` | Clé d’unité |
|
||||
| `libelle` | Noms formatés (foyer : `A & B`) |
|
||||
| `emails` / `user_ids` | Membres du foyer ou AM |
|
||||
| `statut` | Agrégé : `en_attente` si au moins un user pending |
|
||||
| `a_valider` | `true` si pending → section haute UI |
|
||||
| `date_reference` | `MIN(cree_le)` des users |
|
||||
|
||||
**Tri** : `a_valider` d’abord, puis `numero_dossier` décroissant.
|
||||
|
||||
**Famille** : dédupliquée par `numero_dossier` (pivot + co-parent = 1 ligne).
|
||||
|
||||
---
|
||||
|
||||
## Front
|
||||
|
||||
- `UserService.getDossiers({ q? })` → cet endpoint
|
||||
- Section haute : filtrer `a_valider == true` **ou** continuer pending APIs existantes
|
||||
- Section basse : liste complète (ou hors pending selon règle UX)
|
||||
- Clic → `GET /dossiers/:numero` (détail) / validation review
|
||||
|
||||
Composition client `getParents`+`getAM` **plus nécessaire** si cet endpoint est déployé.
|
||||
|
||||
## Branche
|
||||
|
||||
`feature/153-onglet-dossiers`
|
||||
@@ -0,0 +1,167 @@
|
||||
# Mini-spec front — Onglet permanent « Dossiers » (#153)
|
||||
|
||||
Branche Git (front + back) : `feature/153-onglet-dossiers`
|
||||
Ticket Gitea : **#153** (ticket normal, plus epic)
|
||||
|
||||
> Suite prévue : **#135** = au clic, mode **édition** wizard + ajout 2ᵉ parent.
|
||||
> **#153** = onglet + listes + navigation / validation pending. **Pas** de création, **pas** d’édition complète.
|
||||
|
||||
---
|
||||
|
||||
## Contexte / objectif
|
||||
|
||||
Remplacer l’onglet conditionnel **« À valider »** (apparaît/disparaît selon pending) par un onglet **permanent « Dossiers »** dans le dashboard admin/gestionnaire.
|
||||
|
||||
Quand on ouvre **Dossiers** :
|
||||
|
||||
1. **En haut** — section **Dossiers à valider** (AM + familles pending)
|
||||
2. **En dessous** — liste de **tous les dossiers** (familles **et** AM), 1 ligne = 1 `numero_dossier`
|
||||
3. Différenciation visuelle famille vs AM : **couleur + icône**
|
||||
4. **Barre de recherche** (n° dossier, nom, email…)
|
||||
|
||||
**Pas** de bouton « Créer un dossier » ici (création via **+ Parents** #129 / **+ Asmat** #156).
|
||||
|
||||
---
|
||||
|
||||
## UX cible
|
||||
|
||||
### Onglets dashboard (`UserManagementPanel`)
|
||||
|
||||
| Avant (#107) | Après (#153) |
|
||||
|--------------|--------------|
|
||||
| « À valider » **conditionnel** si pending | **« Dossiers » toujours visible** (admin + gestionnaire) |
|
||||
| Contenu = seulement pending | Pending **en haut** + liste complète **en bas** |
|
||||
|
||||
Ordre suggéré des onglets :
|
||||
|
||||
`Dossiers` | `Parents` | `Enfants` | `Assistantes maternelles` | `Gestionnaires` | (`Administrateurs`)
|
||||
|
||||
### Section haute — À valider
|
||||
|
||||
- Réutiliser / adapter `PendingValidationWidget` (ou extraire la liste dans un sous-widget).
|
||||
- Sources déjà branchées :
|
||||
- `UserService.getPendingUsers(role: 'assistante_maternelle')`
|
||||
- `UserService.getPendingFamilies()`
|
||||
- Clic ligne pending → **`ValidationDossierModal`** / wizards `.review` (inchangé).
|
||||
- Si section vide : ne pas afficher de gros vide ; masquer la section ou message court « Aucun dossier en attente ».
|
||||
|
||||
### Section basse — Tous les dossiers
|
||||
|
||||
1 ligne = **1 dossier** (`numero_dossier`), type :
|
||||
|
||||
| Type | Libellé UI | Couleur (suggestion) |
|
||||
|------|------------|----------------------|
|
||||
| `famille` | Famille / Parents | teinte existante parents (ex. violet / rose dashboard) |
|
||||
| `assistante_maternelle` | AM | teinte existante AM (ex. teal / bleu) |
|
||||
|
||||
Colonnes / infos utiles (cartes style `AdminUserCard` ou lignes type pending) :
|
||||
|
||||
- n° dossier
|
||||
- type (pastille couleur + icône)
|
||||
- libellé (noms parents ou AM)
|
||||
- email(s) principal(aux)
|
||||
- statut user / dossier si dispo (`actif`, `en_attente`, …)
|
||||
- date utile si dispo
|
||||
|
||||
**Déduplication** : un foyer (pivot + co-parent) = **une** ligne famille (même `numero_dossier`). Idem AM.
|
||||
|
||||
### Recherche
|
||||
|
||||
- La search bar du panel (aujourd’hui désactivée / hint « pas de recherche » sur À valider) doit **filtrer la liste unifiée** (et idéalement aussi le pending affiché).
|
||||
- Critères **minimum** : `numero_dossier`, nom, prénom, email.
|
||||
- Harmoniser le hint : `Rechercher un dossier (n°, nom, email)…`
|
||||
|
||||
### État vide liste complète
|
||||
|
||||
Aide optionnelle : *« Pour créer un dossier → onglet Parents (+ Parents) ou Assistantes maternelles (+ Asmat) »*.
|
||||
|
||||
### Clic sur un dossier de la liste complète (#153)
|
||||
|
||||
| Cas | Comportement #153 |
|
||||
|-----|-------------------|
|
||||
| Pending | Ouvrir validation (review) — déjà en place |
|
||||
| Dossier **actif** / non pending | Ouvrir consultation via `GET /dossiers/:numeroDossier` (`UserService.getDossierByNumero`) en **lecture / review** si possible **sans** save édition |
|
||||
|
||||
**Ne pas** implémenter le mode `edit` ni le switch 2ᵉ parent → **#135**.
|
||||
|
||||
Si l’ouverture « review » d’un dossier actif est trop lourde pour ce ticket : clic peut temporairement no-op / snackbar *« Édition dossier : prochainement (#135) »* — **à éviter** si `getDossierByNumero` + wizard review marche déjà pour les deux types.
|
||||
|
||||
---
|
||||
|
||||
## Données / APIs (front)
|
||||
|
||||
### Déjà disponibles (préférer composer côté front pour #153)
|
||||
|
||||
| Besoin | API / service |
|
||||
|--------|----------------|
|
||||
| Pending AM | `getPendingUsers(role: assistante_maternelle)` |
|
||||
| Pending familles | `getPendingFamilies()` |
|
||||
| Parents (avec `numero_dossier`) | `getParents()` |
|
||||
| AM (avec `numero_dossier`) | `getAssistantesMaternelles()` |
|
||||
| Détail unifié | `getDossierByNumero(numero)` → `GET /dossiers/:numeroDossier` |
|
||||
|
||||
**Pas d’endpoint `GET /dossiers` liste** aujourd’hui. Pour #153 :
|
||||
|
||||
- Construire la liste unifiée **côté client** à partir de `getParents()` + `getAssistantesMaternelles()` (group by `numero_dossier`).
|
||||
- Exclure ou marquer les pending déjà dans la section haute (éviter doublons visuels, ou les laisser dans les deux avec badge « à valider » — **préférence** : pending **uniquement** en haut ; liste basse = tous **hors** pending **ou** tous avec badge ; choisir une règle claire et documenter dans le PR).
|
||||
|
||||
**Règle recommandée** :
|
||||
- Haut = pending only
|
||||
- Bas = **tous** les dossiers ayant un `numero_dossier` (y compris pending) **OU** bas = non-pending only
|
||||
→ **Recommandation produit** : bas = **tous** (vision complète), pending aussi en haut pour action rapide. Si doublon gênant : bas = non-pending only.
|
||||
|
||||
### Si le back ajoute plus tard `GET /dossiers`
|
||||
|
||||
Brancher `UserService.getDossiers()` — hors scope bloquant #153 front si composition client OK.
|
||||
|
||||
---
|
||||
|
||||
## Fichiers front probables
|
||||
|
||||
| Fichier | Rôle |
|
||||
|---------|------|
|
||||
| `frontend/lib/widgets/admin/user_management_panel.dart` | Onglet permanent **Dossiers** ; retirer logique conditionnelle À valider ; search sur cet onglet |
|
||||
| `frontend/lib/widgets/admin/pending_validation_widget.dart` | Réemploi section haute (ou refactor léger) |
|
||||
| **Nouveau** `…/dossiers_management_widget.dart` (nom libre) | Shell onglet : pending + liste unifiée + refresh |
|
||||
| **Nouveau** modèle léger `DossierListItem` (type, numero, libelle, emails, statut…) | Mapping parents/AM → ligne |
|
||||
| `user_service.dart` / `api_config.dart` | Seulement si helper `getDossiersUnified()` côté client (pas forcément nouvel endpoint) |
|
||||
| `validation_dossier_modal.dart` | Réemploi ouverture pending / détail |
|
||||
|
||||
Réutiliser look & feel cartes / hover « Ouvrir » de `_PendingValidationRow` / `AdminUserCard`.
|
||||
|
||||
---
|
||||
|
||||
## Hors scope (#153)
|
||||
|
||||
- Bouton créer dossier
|
||||
- Mode `edit` wizard + ajout 2ᵉ parent → **#135**
|
||||
- Suppressions → **#154**
|
||||
- Famille N responsables → **#139**
|
||||
- Changer les onglets Parents / AM / Enfants (restent)
|
||||
|
||||
---
|
||||
|
||||
## Critères d’acceptation front
|
||||
|
||||
- [ ] Onglet **Dossiers** toujours visible (même 0 pending)
|
||||
- [ ] Plus d’onglet conditionnel **« À valider »**
|
||||
- [ ] Section haute pending si non vide ; validation au clic OK
|
||||
- [ ] Liste unifiée familles + AM en dessous ; 1 ligne / `numero_dossier`
|
||||
- [ ] Couleur + icône différencient famille / AM
|
||||
- [ ] Recherche filtre (n° + nom + email minimum)
|
||||
- [ ] **Aucun** bouton créer dans cet onglet
|
||||
- [ ] Pas de régression validation pending (valider / refuser)
|
||||
|
||||
---
|
||||
|
||||
## Back (info — Cursor back séparé si besoin)
|
||||
|
||||
- Liste unifiée : **pas bloquante** si composition front
|
||||
- Optionnel : `GET /api/v1/dossiers` (liste) pour perf / pagination plus tard
|
||||
- `GET /dossiers/:numero` déjà là (#119)
|
||||
|
||||
---
|
||||
|
||||
## Branche
|
||||
|
||||
`feature/153-onglet-dossiers` (depuis `develop`)
|
||||
@@ -0,0 +1,35 @@
|
||||
# Matrice suppression — #154 / back **#159** / front **#160**
|
||||
|
||||
**Statut** : cadrage PO validé (sept. 2026)
|
||||
**Milestone** : 0.1.0
|
||||
**Email** : pas d’email de suppression (cas rare)
|
||||
|
||||
## Droits
|
||||
|
||||
| Cible | Qui peut supprimer |
|
||||
|-------|-------------------|
|
||||
| Dossier / parent / enfant / AM | `GESTIONNAIRE`, `ADMINISTRATEUR`, `SUPER_ADMIN` |
|
||||
| Gestionnaire (user) | `ADMINISTRATEUR`, `SUPER_ADMIN` |
|
||||
| Administrateur (user) | Autre admin OK ; **self interdit** ; **dernier admin** = `SUPER_ADMIN` only ; `SUPER_ADMIN` non supprimable |
|
||||
|
||||
## Matrice métier
|
||||
|
||||
| Point d’entrée | Action | Effet |
|
||||
|----------------|--------|--------|
|
||||
| Dossiers | Delete dossier **famille** | Tous **parents** + tous **enfants** ; clore placements AM des enfants |
|
||||
| Dossiers / AM | Delete dossier **AM** ou compte AM | **Compte AM + dossier AM** ; enfants **conservés** ; placements **clos** |
|
||||
| Parents | Co-parent (autre parent reste) | Compte parent seul ; dossier + enfants restent |
|
||||
| Parents | Dernier parent | Parent + **enfants** rattachés |
|
||||
| Enfants | Pas dernier | Enfant seul (retiré du dossier) |
|
||||
| Enfants | Dernier + `deleteDossier=true` | Cascade dossier famille (parents + enfants) |
|
||||
| Enfants | Dernier + `deleteDossier=false` | Enfant seul ; dossier peut apparaître **`sans_enfant`** |
|
||||
| Pending / validé | — | **Mêmes règles** (pas de différenciation) |
|
||||
|
||||
## Warning
|
||||
|
||||
- `sans_enfant` sur liste `GET /dossiers` (dossier famille sans enfant lié).
|
||||
- Miroir de `sans_responsable` (#157) côté enfants.
|
||||
|
||||
## Hors scope
|
||||
|
||||
Soft-delete RGPD, audit (#128), famille N (#139), restriction admin-only métier (plus tard).
|
||||
@@ -0,0 +1,169 @@
|
||||
# Mini-spec front — Suppressions dashboard
|
||||
|
||||
**Ticket front** : **#160** — https://git.ptits-pas.fr/jmartin/petitspas/issues/160
|
||||
**Ticket back** : **#159** — https://git.ptits-pas.fr/jmartin/petitspas/issues/159
|
||||
**Epic** : #154 (complète #133)
|
||||
**Branche back** : `feature/159-suppressions-backend`
|
||||
**Doc matrice** : [154-matrice-suppression.md](./154-matrice-suppression.md)
|
||||
|
||||
Travail **en parallèle** : ce contrat est la source de vérité UI ↔ API.
|
||||
|
||||
---
|
||||
|
||||
## UX commune
|
||||
|
||||
Sur chaque ligne / carte des listes :
|
||||
|
||||
- Icône **poubelle** en bout de ligne
|
||||
- Clic → **dialog de confirmation** (texte d’impact) → DELETE → **refresh** liste
|
||||
- Pending = **mêmes** règles que validés
|
||||
- **Pas** d’email
|
||||
|
||||
| Liste | Poubelle visible si |
|
||||
|-------|---------------------|
|
||||
| Dossiers, Parents, Enfants, AM | gestionnaire **ou** admin |
|
||||
| Gestionnaires | **admin** only |
|
||||
| Administrateurs | admin+ ; **pas** sur sa propre ligne ; dernier admin : UI warning + réservé super_admin |
|
||||
|
||||
---
|
||||
|
||||
## Contrat API
|
||||
|
||||
Base : auth Bearer. Erreurs : `400` / `403` / `404` / `409` avec `message` FR.
|
||||
|
||||
### 1. `DELETE /dossiers/:numeroDossier`
|
||||
|
||||
- **Famille** → supprime tous parents + enfants du n° ; clos placements AM des enfants.
|
||||
- **AM** → compte AM + dossier AM ; enfants gardés ; placements clos.
|
||||
|
||||
**Réponse 200** (exemple) :
|
||||
|
||||
```json
|
||||
{
|
||||
"type": "famille",
|
||||
"numero_dossier": "2026-000043",
|
||||
"deleted_user_ids": ["…"],
|
||||
"deleted_enfant_ids": ["…"],
|
||||
"message": "Dossier famille supprimé."
|
||||
}
|
||||
```
|
||||
|
||||
ou
|
||||
|
||||
```json
|
||||
{
|
||||
"type": "assistante_maternelle",
|
||||
"numero_dossier": "2026-000015",
|
||||
"deleted_user_ids": ["…"],
|
||||
"deleted_enfant_ids": [],
|
||||
"message": "Dossier assistante maternelle supprimé."
|
||||
}
|
||||
```
|
||||
|
||||
**Dialog UI** : lister libellé + n° + « X parent(s), Y enfant(s) » (ou « compte AM, enfants conservés »).
|
||||
|
||||
---
|
||||
|
||||
### 2. `DELETE /users/:id`
|
||||
|
||||
Comportement selon le **rôle** de la cible :
|
||||
|
||||
| Cible | Effet |
|
||||
|-------|--------|
|
||||
| Parent **co-parent** | Delete ce user seul |
|
||||
| Parent **dernier** du dossier | Delete user + enfants du foyer |
|
||||
| AM | Delete user AM + dossier AM ; enfants conservés ; placements clos |
|
||||
| Gestionnaire | Admin only ; self → 403 |
|
||||
| Administrateur | Self → 403 ; dernier admin → super_admin only sinon 403 ; super_admin → 403 |
|
||||
|
||||
**Réponse 200** :
|
||||
|
||||
```json
|
||||
{
|
||||
"deleted_user_ids": ["…"],
|
||||
"deleted_enfant_ids": ["…"],
|
||||
"message": "…"
|
||||
}
|
||||
```
|
||||
|
||||
**Dialogs** :
|
||||
|
||||
- Co-parent : « Ce parent sera retiré / supprimé du dossier {n°}. Les enfants restent avec le co-parent. »
|
||||
- Dernier parent : « Dernier parent du dossier {n°}. Les enfants rattachés seront aussi supprimés. »
|
||||
- AM : « Le compte et le dossier AM seront supprimés. Les enfants accueillis ne seront pas supprimés. »
|
||||
|
||||
Optionnel (si exposé) : `GET /users/:id/suppression-impact` — sinon calculer depuis données déjà en liste / détail dossier.
|
||||
|
||||
---
|
||||
|
||||
### 3. `DELETE /enfants/:id?deleteDossier=true|false`
|
||||
|
||||
- Pas dernier enfant → delete enfant (`deleteDossier` ignoré ou false).
|
||||
- Dernier enfant + `deleteDossier=false` → delete enfant ; dossier famille peut passer `sans_enfant`.
|
||||
- Dernier enfant + `deleteDossier=true` → cascade dossier famille (parents + enfants).
|
||||
|
||||
**Réponse 200** :
|
||||
|
||||
```json
|
||||
{
|
||||
"deleted_enfant_ids": ["…"],
|
||||
"deleted_user_ids": ["…"],
|
||||
"dossier_supprime": false,
|
||||
"message": "…"
|
||||
}
|
||||
```
|
||||
|
||||
**Dialog** :
|
||||
|
||||
- Standard : « L’enfant sera supprimé du dossier de {famille} ({n°}). »
|
||||
- Dernier : proposer **deux actions** :
|
||||
1. Supprimer l’enfant seulement (`deleteDossier=false`)
|
||||
2. Supprimer aussi le dossier / parents (`deleteDossier=true`)
|
||||
|
||||
Pour savoir si dernier : compter enfants du `numero_dossier` (détail dossier ou champ impact API).
|
||||
|
||||
---
|
||||
|
||||
### 4. `GET /dossiers` — flag `sans_enfant`
|
||||
|
||||
Chaque item famille peut exposer :
|
||||
|
||||
```json
|
||||
"sans_enfant": true
|
||||
```
|
||||
|
||||
- `true` si dossier **famille** sans enfant lié.
|
||||
- AM : `false` ou omis.
|
||||
|
||||
**UI** : badge / warning vigilance (comme `sans_responsable` / alertes AM).
|
||||
|
||||
---
|
||||
|
||||
## UserService (Flutter) — signatures cibles
|
||||
|
||||
```dart
|
||||
Future<void> deleteDossier(String numeroDossier);
|
||||
Future<Map<String, dynamic>> deleteUser(String userId);
|
||||
Future<Map<String, dynamic>> deleteEnfant(String enfantId, {bool deleteDossier = false});
|
||||
```
|
||||
|
||||
(Adapter le parsing au JSON réel une fois le back mergé ; en parallèle, stubber sur ce contrat.)
|
||||
|
||||
---
|
||||
|
||||
## Fichiers front probables
|
||||
|
||||
- Cartes listes : `admin_user_card.dart`, `admin_enfant_user_card.dart`, cartes dossiers
|
||||
- Listes : `dossiers_management_widget.dart`, `parent_managmant_widget.dart`, `enfant_management_widget.dart`, `assistante_maternelle_management_widget.dart`, `gestionnaire_management_widget.dart`, `admin_management_widget.dart`
|
||||
- `user_service.dart`
|
||||
|
||||
---
|
||||
|
||||
## Critères front (#160)
|
||||
|
||||
- [ ] Poubelle selon droits
|
||||
- [ ] Confirmations avec impact
|
||||
- [ ] Refresh après succès
|
||||
- [ ] Dernier enfant : choix dossier oui/non
|
||||
- [ ] Warning `sans_enfant`
|
||||
- [ ] Self-admin / dernier admin gérés côté UI (masquer ou message 403)
|
||||
@@ -0,0 +1,54 @@
|
||||
# Mini-spec — Rename préfixe `Admin*` dashboard partagé (#155)
|
||||
|
||||
**Ticket** : **#155**
|
||||
**Branche** : `feature/155-rename-admin-prefix-dashboard` (depuis `develop`)
|
||||
**Décision naming** : **option C** — dossier neutre `widgets/dashboard/` + noms **sans** préfixe `Admin`.
|
||||
|
||||
---
|
||||
|
||||
## Principe
|
||||
|
||||
Les widgets partagés **admin + gestionnaire** ne doivent plus s’appeler `Admin*`.
|
||||
On garde `Admin*` seulement là où c’est vraiment le rôle administrateur.
|
||||
|
||||
## Gardé `Admin*` (hors rename)
|
||||
|
||||
| Élément | Raison |
|
||||
|---------|--------|
|
||||
| `AdminManagementWidget` | Onglet **Administrateurs** |
|
||||
| `screens/administrateurs/*` | `AdminDashboardScreen`, `AdminCreateDialog`, `AdminUserFormDialog` |
|
||||
| `EnfantAdminModel` | Modèle API (pas un widget) — hors scope ticket |
|
||||
|
||||
## Renames faits
|
||||
|
||||
| Avant | Après |
|
||||
|-------|--------|
|
||||
| `widgets/admin/common/admin_child_detail_modal.dart` → `AdminChildDetailModal` | `widgets/dashboard/child_detail_modal.dart` → `ChildDetailModal` |
|
||||
| `admin_am_edit_modal` → `AdminAmEditModal` | `am_edit_modal` → `AmEditModal` |
|
||||
| `admin_parent_edit_modal` → `AdminParentEditModal` | `parent_edit_modal` → `ParentEditModal` |
|
||||
| `admin_user_card` → `AdminUserCard` | `user_card` → `UserCard` |
|
||||
| `admin_enfant_user_card` → `AdminEnfantUserCard` | `enfant_user_card` → `EnfantUserCard` |
|
||||
| `admin_am_photo_frame` → `AdminAmPhotoFrame` | `am_photo_frame` → `AmPhotoFrame` |
|
||||
| `admin_am_children_capacity_grid` | `am_children_capacity_grid` → `AmChildrenCapacityGrid` |
|
||||
| `admin_children_affiliation_panel` | `children_affiliation_panel` → `ChildrenAffiliationPanel` |
|
||||
| `admin_select_*` / `AdminSelect*` / `AdminFamilleFoyer` | `select_*` / `Select*` / `FamilleFoyer` |
|
||||
| `admin_status_capsule` | `status_capsule` → `StatusCapsule` |
|
||||
| `admin_list_state` → `AdminListState` | `user_list_state` → `UserListState` |
|
||||
| `admin_detail_modal` → `AdminDetailModal` / `AdminDetailField` | `detail_modal` → `DetailModal` / `DetailField` |
|
||||
| `dashboard_admin.dart` | `user_management_sub_bar.dart` (`DashboardUserManagementSubBar` inchangé) |
|
||||
|
||||
Dossier `widgets/admin/` conserve encore les panels métier (`user_management_panel`, wizards, etc.) + `AdminManagementWidget`.
|
||||
|
||||
**Phase 2** (même ticket #155) : déplacer ces panels → `widgets/dashboard/` — voir [155-suite-move-admin-panels-to-dashboard.md](./155-suite-move-admin-panels-to-dashboard.md).
|
||||
|
||||
## Hors scope
|
||||
|
||||
- Refonte UX modales (ticket dédié)
|
||||
- Rename API / back
|
||||
- Déplacer tout `widgets/admin/` → `widgets/dashboard/` (panels) — possible follow-up
|
||||
|
||||
## Critères
|
||||
|
||||
- [x] Plus de préfixe `Admin` sur les composants **partagés** listés
|
||||
- [ ] Build Flutter / recette dashboard admin + gestionnaire OK
|
||||
- [x] Pas de changement comportemental (rename mécanique)
|
||||
@@ -0,0 +1,203 @@
|
||||
# Mini-spec — Déplacer les panels `widgets/admin/` → `widgets/dashboard/`
|
||||
|
||||
**Ticket** : **#155** (phase 2 — même ticket que le rename `Admin*`)
|
||||
**Phase 1** : widgets `Admin*` → `widgets/dashboard/` (déjà sur `feature/155-rename-admin-prefix-dashboard`)
|
||||
**Branche** : poursuivre / rebaser `feature/155-rename-admin-prefix-dashboard` (ou nouvelle branche depuis `develop` après merge phase 1)
|
||||
**Nature** : rename / move mécanique — **zéro** changement UX / métier
|
||||
|
||||
---
|
||||
|
||||
## Contexte
|
||||
|
||||
Après la phase 1 (#155), la situation est **hybride** :
|
||||
|
||||
| Emplacement | Contenu |
|
||||
|-------------|---------|
|
||||
| `widgets/dashboard/` | Composants partagés sans préfixe `Admin*` (modales, cartes, selects, sub-bar…) |
|
||||
| `widgets/admin/` | **Panels** du dashboard staff (listes, wizards, validation, shell `UserManagementPanel`…) + `AdminManagementWidget` |
|
||||
|
||||
Le dossier `admin/` laisse encore croire « réservé administrateur », alors que **gestionnaire** consomme les mêmes panels (`GestionnaireDashboardScreen` → `UserManagementPanel`).
|
||||
|
||||
Ce ticket **termine l’option C** au niveau dossier : tout le dashboard staff vit sous `widgets/dashboard/`, sauf ce qui est **vraiment** rôle admin.
|
||||
|
||||
---
|
||||
|
||||
## Objectif
|
||||
|
||||
```
|
||||
frontend/lib/widgets/admin/<panels & common partagés>
|
||||
↓ git mv + update imports
|
||||
frontend/lib/widgets/dashboard/…
|
||||
```
|
||||
|
||||
Critère : un nouveau dev ne doit plus ouvrir `widgets/admin/` pour du code partagé admin+gestionnaire.
|
||||
|
||||
---
|
||||
|
||||
## Cible d’arborescence (proposée)
|
||||
|
||||
```
|
||||
widgets/dashboard/
|
||||
├── (déjà là #155) child_detail_modal.dart, am_edit_modal.dart, user_card.dart, …
|
||||
├── user_management_panel.dart ← shell onglets
|
||||
├── user_management_sub_bar.dart ← déjà déplacé #155
|
||||
├── dossiers_management_widget.dart
|
||||
├── dossier_list_card.dart
|
||||
├── parent_management_widget.dart ← corriger le typo managmant au passage ?
|
||||
├── enfant_management_widget.dart
|
||||
├── assistante_maternelle_management_widget.dart
|
||||
├── gestionnaire_management_widget.dart
|
||||
├── pending_validation_widget.dart
|
||||
├── parent_dossier_create_modal.dart
|
||||
├── parent_dossier_wizard.dart
|
||||
├── am_dossier_create_modal.dart
|
||||
├── am_dossier_wizard.dart
|
||||
├── validation_*.dart ← family/am wizards, refus, theme, confirm
|
||||
├── parametres_panel.dart ← utilisé par écran admin (OK dans dashboard)
|
||||
├── relais_management_panel.dart
|
||||
├── common/ ← sous-dossier optionnel
|
||||
│ ├── suppression_confirm_dialog.dart
|
||||
│ ├── user_list.dart
|
||||
│ └── validation_detail_section.dart
|
||||
└── …
|
||||
|
||||
widgets/admin/ ← mince, rôle admin seulement
|
||||
└── admin_management_widget.dart ← onglet Administrateurs
|
||||
```
|
||||
|
||||
### Variante B (plus stricte)
|
||||
|
||||
`AdminManagementWidget` + éventuels helpers purement admin →
|
||||
`screens/administrateurs/widgets/`
|
||||
et **suppression** du dossier `widgets/admin/`.
|
||||
|
||||
**Reco** : **variante A** (garder `widgets/admin/` minimal avec seulement `AdminManagementWidget`) — moins de churn screens, clair.
|
||||
|
||||
---
|
||||
|
||||
## Inventaire à déplacer (état actuel)
|
||||
|
||||
### Racine `widgets/admin/` → `widgets/dashboard/`
|
||||
|
||||
| Fichier actuel | Notes |
|
||||
|----------------|--------|
|
||||
| `user_management_panel.dart` | Shell partagé admin + gestionnaire |
|
||||
| `dossiers_management_widget.dart` | |
|
||||
| `dossier_list_card.dart` | |
|
||||
| `parent_managmant_widget.dart` | Typo historique `managmant` — **option** : renommer → `parent_management_widget.dart` dans le même ticket ou ticket typo séparé |
|
||||
| `enfant_management_widget.dart` | |
|
||||
| `assistante_maternelle_management_widget.dart` | |
|
||||
| `gestionnaire_management_widget.dart` | |
|
||||
| `pending_validation_widget.dart` | |
|
||||
| `parent_dossier_create_modal.dart` | |
|
||||
| `parent_dossier_wizard.dart` | |
|
||||
| `am_dossier_create_modal.dart` | |
|
||||
| `am_dossier_wizard.dart` | |
|
||||
| `validation_am_wizard.dart` | |
|
||||
| `validation_family_wizard.dart` | |
|
||||
| `validation_dossier_modal.dart` | |
|
||||
| `validation_modal_theme.dart` | |
|
||||
| `validation_refus_form.dart` | |
|
||||
| `validation_valider_confirm_dialog.dart` | |
|
||||
| `parametres_panel.dart` | Écran admin seulement, mais pas préfixé Admin — OK dashboard |
|
||||
| `relais_management_panel.dart` | |
|
||||
|
||||
### `widgets/admin/common/` → `widgets/dashboard/common/` (ou plat)
|
||||
|
||||
| Fichier | Notes |
|
||||
|---------|--------|
|
||||
| `suppression_confirm_dialog.dart` | Partagé (y compris `screens/administrateurs/creation/*`) |
|
||||
| `user_list.dart` | |
|
||||
| `validation_detail_section.dart` | |
|
||||
|
||||
### **Ne pas** déplacer
|
||||
|
||||
| Fichier | Destination |
|
||||
|---------|-------------|
|
||||
| `admin_management_widget.dart` | Reste `widgets/admin/` (ou variante B → screens) |
|
||||
|
||||
### Déjà fait (#155) — ne pas retraiter
|
||||
|
||||
Tout ce qui est déjà sous `widgets/dashboard/` (`child_detail_modal`, `am_edit_modal`, `user_card`, `select_*`, `user_management_sub_bar`, …).
|
||||
|
||||
---
|
||||
|
||||
## Consommateurs d’imports (à mettre à jour)
|
||||
|
||||
### Screens
|
||||
- `screens/administrateurs/admin_dashboardScreen.dart` — `UserManagementPanel`, `ParametresPanel`
|
||||
- `screens/gestionnaire/gestionnaire_dashboard_screen.dart` — `UserManagementPanel`
|
||||
- `screens/administrateurs/creation/admin_create.dart` — `suppression_confirm_dialog`
|
||||
- `screens/administrateurs/creation/gestionnaires_create.dart` — idem
|
||||
|
||||
### Widgets déjà en `dashboard/`
|
||||
- `am_edit_modal`, `child_detail_modal`, `parent_edit_modal`, `select_*` — imports vers `widgets/admin/common/*` ou panels
|
||||
|
||||
### Divers
|
||||
- `widgets/common/identity_block.dart` (si import admin)
|
||||
- Tous les fichiers **déplacés** entre eux (imports relatifs / package)
|
||||
|
||||
### Hors scope rename classes
|
||||
Sauf décision explicite sur le typo `parent_managmant_widget` → pas de rename de **classes** métier dans ce ticket (seulement chemins de fichiers + imports).
|
||||
`AdminManagementWidget` **conserve** son nom.
|
||||
|
||||
---
|
||||
|
||||
## Plan d’exécution
|
||||
|
||||
1. Partir de `feature/155-rename-admin-prefix-dashboard` (phase 1) **ou** `develop` si phase 1 déjà mergée
|
||||
2. `git mv` fichiers selon inventaire
|
||||
3. Remplacer globalement
|
||||
`package:p_tits_pas/widgets/admin/` → `package:p_tits_pas/widgets/dashboard/`
|
||||
**sauf** `…/widgets/admin/admin_management_widget.dart`
|
||||
4. Corriger imports relatifs cassés
|
||||
5. Grep de contrôle (ci-dessous)
|
||||
6. Build Flutter web (Docker) + smoke dashboard admin **et** gestionnaire
|
||||
7. Merge → squash master si flux habituel
|
||||
|
||||
---
|
||||
|
||||
## Vérifs
|
||||
|
||||
```bash
|
||||
# Plus de panels partagés sous admin (seul AdminManagement attendu)
|
||||
find frontend/lib/widgets/admin -name '*.dart'
|
||||
|
||||
# Plus d’imports panels vers l’ancien chemin (sauf AdminManagement)
|
||||
rg -n "widgets/admin/(user_management|dossiers_|parent_|enfant_|assistante|gestionnaire|pending|validation_|parametres|relais|am_dossier|parent_dossier|dossier_list|common/)" frontend/lib
|
||||
|
||||
# Screens OK
|
||||
rg -n "widgets/admin/" frontend/lib/screens
|
||||
```
|
||||
|
||||
Attendu screens : **0** hit vers panels ; éventuellement plus aucun hit `widgets/admin/` sauf si import explicite `AdminManagementWidget` depuis `user_management_panel` (chemin `widgets/admin/admin_management_widget.dart`).
|
||||
|
||||
---
|
||||
|
||||
## Hors scope
|
||||
|
||||
- Refonte UX des modales / panels (ticket dédié annoncé)
|
||||
- Rename `EnfantAdminModel`
|
||||
- Rename `screens/administrateurs/`
|
||||
- Rename `AdminUserFormDialog` / `AdminCreateDialog`
|
||||
- Changement API / back
|
||||
- #152 (`est_multiple`) — autre branche
|
||||
|
||||
---
|
||||
|
||||
## Critères d’acceptation
|
||||
|
||||
- [ ] Inventaire déplacé selon tableau
|
||||
- [ ] `widgets/admin/` ne contient plus que `admin_management_widget.dart` (variante A)
|
||||
- [ ] Imports screens + widgets à jour
|
||||
- [ ] Build Flutter OK
|
||||
- [ ] Recette : dashboard **administrateur** et **gestionnaire** (listes, ouverture fiches, validation, création dossier) sans régression
|
||||
- [ ] Aucun changement comportemental volontaire
|
||||
|
||||
---
|
||||
|
||||
## Risques / notes
|
||||
|
||||
- **Conflits de merge** si d’autres features touchent les panels → faire ce ticket quand la surface dashboard est calme (fin 0.1.0 OK)
|
||||
- Typo `parent_managmant_widget` : soit inclus (bonus), soit ticket cleanup 1-ligne séparé
|
||||
- Docs d’archive citant `widgets/admin/…` : pas obligatoire de mettre à jour ; `docs/27_BRIEFING-FRONTEND.md` oui si encore listé
|
||||
@@ -0,0 +1,75 @@
|
||||
# Mini-spec API — POST /assistantes-maternelles/dossier (#156)
|
||||
|
||||
Contrat pour le **plan front** (wizard création AM staff).
|
||||
|
||||
## Endpoint
|
||||
|
||||
| | |
|
||||
|--|--|
|
||||
| **Méthode** | `POST` |
|
||||
| **URL** | `{base}/assistantes-maternelles/dossier` |
|
||||
| **Auth** | Bearer JWT |
|
||||
| **Rôles** | `gestionnaire`, `administrateur`, `super_admin` |
|
||||
| **Content-Type** | `application/json` |
|
||||
|
||||
Ne **pas** appeler `POST /auth/register/am` depuis le dashboard.
|
||||
|
||||
## Body (JSON)
|
||||
|
||||
Aligné inscription AM publique, **sans** CGU/privacy obligatoires (acceptées serveur).
|
||||
|
||||
| Champ | Type | Obligatoire | Notes |
|
||||
|-------|------|-------------|--------|
|
||||
| `email` | string | oui | unique |
|
||||
| `prenom` | string | oui | |
|
||||
| `nom` | string | oui | |
|
||||
| `telephone` | string | oui | `0X…` ou `+33…` |
|
||||
| `adresse` | string | non | |
|
||||
| `code_postal` | string | non | |
|
||||
| `ville` | string | non | |
|
||||
| `photo_base64` | string | non | data-URL `data:image/…;base64,…` |
|
||||
| `photo_filename` | string | non | hint nom fichier |
|
||||
| `consentement_photo` | bool | oui | |
|
||||
| `date_naissance` | date ISO | non | `YYYY-MM-DD` |
|
||||
| `lieu_naissance_ville` | string | oui | |
|
||||
| `lieu_naissance_pays` | string | oui | |
|
||||
| `nir` | string | oui | 15 car. (Corse 2A/2B OK) |
|
||||
| `numero_agrement` | string | oui | unique |
|
||||
| `date_agrement` | date ISO | non | |
|
||||
| `capacite_accueil` | int | oui | 1–10 |
|
||||
| `places_disponibles` | int | oui | 0–10, ≤ capacité |
|
||||
| `biographie` | string | non | max 2000 |
|
||||
|
||||
## Réponses
|
||||
|
||||
### 201 Created
|
||||
|
||||
```json
|
||||
{
|
||||
"message": "Dossier AM créé et validé. Un e-mail de création de mot de passe a été envoyé.",
|
||||
"user_id": "uuid",
|
||||
"statut": "actif",
|
||||
"numero_dossier": "2026-000042"
|
||||
}
|
||||
```
|
||||
|
||||
Effets serveur : user AM **actif**, fiche `assistantes_maternelles`, n° dossier, **e-mail création MDP** (pas d’accusé « en attente »).
|
||||
|
||||
### Erreurs
|
||||
|
||||
| Code | Cas |
|
||||
|------|-----|
|
||||
| 400 | Validation / NIR / places > capacité |
|
||||
| 403 | Rôle non staff |
|
||||
| 409 | Email, NIR ou agrément déjà pris |
|
||||
| 401 | Token manquant / invalide |
|
||||
|
||||
## Front
|
||||
|
||||
- `UserService.createAmDossier(body)` → cet endpoint
|
||||
- Après 201 : refresh liste AM ; snackbar OK
|
||||
- Wizard create : ne pas envoyer `acceptation_cgu` / `acceptation_privacy` (optionnels)
|
||||
|
||||
## Branche
|
||||
|
||||
`feature/156-creation-dossier-am`
|
||||
@@ -0,0 +1,14 @@
|
||||
# Mini-spec — Uniformisation modale staff (Gestionnaire / Administrateur)
|
||||
|
||||
**Ticket** : **#164** — https://git.ptits-pas.fr/jmartin/petitspas/issues/164
|
||||
**Branche** : `feature/164-staff-modal-uniformisation` (depuis `develop`)
|
||||
**Périmètre** : **front only** — pas d’API / BDD
|
||||
**Milestone** : **0.1.0**
|
||||
|
||||
Voir le corps du ticket #164 pour la spec complète.
|
||||
|
||||
## Livré
|
||||
|
||||
- `frontend/lib/widgets/dashboard/staff_user_form_modal.dart` → `StaffUserFormModal`
|
||||
- Ancien `AdminUserFormDialog` / `gestionnaires_create.dart` retiré
|
||||
- Imports : `user_management_panel`, `gestionnaire_management_widget`, `admin_management_widget`
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 261 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 158 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 276 KiB |
@@ -442,17 +442,7 @@ class _CartesFeedState extends State<CartesFeed> {
|
||||
);
|
||||
}
|
||||
if (_items.isEmpty) {
|
||||
return Center(
|
||||
child: Text(
|
||||
'Aucune bulle pour le moment.\nLa file d’attention est vide — c’est normal.',
|
||||
textAlign: TextAlign.center,
|
||||
style: GoogleFonts.merriweather(
|
||||
fontSize: 13,
|
||||
color: QuotidienTheme.muted,
|
||||
height: 1.4,
|
||||
),
|
||||
),
|
||||
);
|
||||
return const _CartesEmptyState();
|
||||
}
|
||||
|
||||
return NotificationListener<ScrollMetricsNotification>(
|
||||
@@ -1191,6 +1181,65 @@ class _RefuseDialogState extends State<_RefuseDialog> {
|
||||
}
|
||||
}
|
||||
|
||||
/// État vide de la file d'attention — ours endormi (#212).
|
||||
class _CartesEmptyState extends StatelessWidget {
|
||||
const _CartesEmptyState();
|
||||
|
||||
static const _asset = 'assets/images/ours_endormi.png';
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return LayoutBuilder(
|
||||
builder: (context, constraints) {
|
||||
final maxW = constraints.maxWidth;
|
||||
// ~160–200 px, réduit si colonne étroite.
|
||||
final imgW =
|
||||
maxW.isFinite ? maxW.clamp(100.0, 200.0) : 180.0;
|
||||
return Center(
|
||||
child: SingleChildScrollView(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
|
||||
child: ConstrainedBox(
|
||||
constraints: BoxConstraints(maxWidth: maxW),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Image.asset(
|
||||
_asset,
|
||||
width: imgW,
|
||||
fit: BoxFit.contain,
|
||||
filterQuality: FilterQuality.high,
|
||||
semanticLabel: 'Ours endormi',
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
Text(
|
||||
'File d’attention au repos.',
|
||||
textAlign: TextAlign.center,
|
||||
style: GoogleFonts.merienda(
|
||||
fontSize: 16,
|
||||
fontWeight: FontWeight.w600,
|
||||
color: QuotidienTheme.ink,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 6),
|
||||
Text(
|
||||
'Pas de bulle en attente — on respire.',
|
||||
textAlign: TextAlign.center,
|
||||
style: GoogleFonts.merriweather(
|
||||
fontSize: 13,
|
||||
color: QuotidienTheme.muted,
|
||||
height: 1.4,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// CTA « Ajouter une carte » — pilule aquarelle en bas du feed (#175).
|
||||
class _AjouterCarteCta extends StatelessWidget {
|
||||
final VoidCallback onTap;
|
||||
|
||||
@@ -0,0 +1,144 @@
|
||||
/**
|
||||
* Liste les issues Gitea ouvertes pour un milestone donné (ex. 0.1.0).
|
||||
* Usage : node scripts/gitea-list-open-issues-by-milestone.js [milestone]
|
||||
* Token : .gitea-token (racine), GITEA_TOKEN, ou docs/27_BRIEFING-FRONTEND.md
|
||||
*/
|
||||
const https = require('https');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
const repoRoot = path.join(__dirname, '..');
|
||||
const REPO = 'jmartin/petitspas';
|
||||
const milestoneWanted = (process.argv[2] || '0.1.0').trim();
|
||||
|
||||
let token = process.env.GITEA_TOKEN;
|
||||
if (!token) {
|
||||
try {
|
||||
const tokenFile = path.join(repoRoot, '.gitea-token');
|
||||
if (fs.existsSync(tokenFile)) token = fs.readFileSync(tokenFile, 'utf8').trim();
|
||||
} catch (_) {}
|
||||
}
|
||||
if (!token) {
|
||||
try {
|
||||
const briefing = fs.readFileSync(
|
||||
path.join(repoRoot, 'docs/27_BRIEFING-FRONTEND.md'),
|
||||
'utf8',
|
||||
);
|
||||
const m = briefing.match(/Token:\s*(giteabu_[a-f0-9]+)/);
|
||||
if (m) token = m[1].trim();
|
||||
} catch (_) {}
|
||||
}
|
||||
if (!token) {
|
||||
console.error('Token non trouvé : .gitea-token ou GITEA_TOKEN');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
function getJson(apiPath) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const opts = {
|
||||
hostname: 'git.ptits-pas.fr',
|
||||
path: `/api/v1/repos/${REPO}${apiPath}`,
|
||||
method: 'GET',
|
||||
headers: {
|
||||
Authorization: 'token ' + token,
|
||||
Accept: 'application/json',
|
||||
},
|
||||
};
|
||||
const req = https.request(opts, (res) => {
|
||||
let d = '';
|
||||
res.on('data', (c) => (d += c));
|
||||
res.on('end', () => {
|
||||
if (res.statusCode !== 200) {
|
||||
reject(new Error(`HTTP ${res.statusCode}: ${d.slice(0, 500)}`));
|
||||
return;
|
||||
}
|
||||
try {
|
||||
resolve(JSON.parse(d));
|
||||
} catch (e) {
|
||||
reject(e);
|
||||
}
|
||||
});
|
||||
});
|
||||
req.on('error', reject);
|
||||
req.end();
|
||||
});
|
||||
}
|
||||
|
||||
async function fetchAllOpenIssues() {
|
||||
const out = [];
|
||||
let page = 1;
|
||||
const limit = 50;
|
||||
for (;;) {
|
||||
const qs = new URLSearchParams({
|
||||
state: 'open',
|
||||
type: 'all',
|
||||
page: String(page),
|
||||
limit: String(limit),
|
||||
});
|
||||
const batch = await getJson(`/issues?${qs}`);
|
||||
if (!Array.isArray(batch) || batch.length === 0) break;
|
||||
out.push(...batch);
|
||||
if (batch.length < limit) break;
|
||||
page += 1;
|
||||
if (page > 40) break;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function milestoneMatches(m, wanted) {
|
||||
if (!m) return false;
|
||||
const t = (m.title || '').trim();
|
||||
return t === wanted || t === `v${wanted}`;
|
||||
}
|
||||
|
||||
async function main() {
|
||||
let milestones;
|
||||
try {
|
||||
milestones = await getJson('/milestones?state=all');
|
||||
} catch (e) {
|
||||
milestones = [];
|
||||
console.warn('Milestones non lisibles:', e.message);
|
||||
}
|
||||
|
||||
const known = Array.isArray(milestones)
|
||||
? milestones.map((m) => m.title).filter(Boolean)
|
||||
: [];
|
||||
if (known.length) {
|
||||
console.log('Milestones connus sur le dépôt :', known.join(', '));
|
||||
}
|
||||
|
||||
const issues = await fetchAllOpenIssues();
|
||||
const filtered = issues.filter((i) => milestoneMatches(i.milestone, milestoneWanted));
|
||||
|
||||
console.log('');
|
||||
console.log(`## Issues ouvertes — milestone « ${milestoneWanted} » (${filtered.length})`);
|
||||
console.log('');
|
||||
if (filtered.length === 0) {
|
||||
console.log(
|
||||
'Aucune issue ouverte avec ce milestone. Vérifier sur Gitea que les tickets ' +
|
||||
'0.1.0 portent bien le milestone, ou élargir la requête.',
|
||||
);
|
||||
console.log('');
|
||||
console.log(`(Total issues ouvertes sans filtre milestone : ${issues.length})`);
|
||||
const withM = issues.filter((i) => i.milestone);
|
||||
if (withM.length) {
|
||||
console.log('');
|
||||
console.log('Issues ouvertes qui ont *un* milestone :');
|
||||
for (const i of withM) {
|
||||
console.log(`- #${i.number} [${i.milestone.title}] ${i.title}`);
|
||||
}
|
||||
}
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
for (const i of filtered.sort((a, b) => a.number - b.number)) {
|
||||
const labels = (i.labels || []).map((l) => l.name).join(', ');
|
||||
console.log(`- **#${i.number}** — ${i.title}`);
|
||||
if (labels) console.log(` - Labels : ${labels}`);
|
||||
}
|
||||
}
|
||||
|
||||
main().catch((e) => {
|
||||
console.error(e);
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -0,0 +1,103 @@
|
||||
/**
|
||||
* POST /api/v1/auth/register/parent — foyer mono-parent (1 parent + 1 enfant).
|
||||
* Inspiré de register-parent-lecomte-test.mjs.
|
||||
* Email : sophie.bernard@example.com
|
||||
*
|
||||
* Usage : node tests/scripts/register-parent-bernard-test.mjs [BASE_URL]
|
||||
*/
|
||||
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import https from 'https';
|
||||
import http from 'http';
|
||||
import { fileURLToPath } from 'url';
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
const photosDir = path.join(__dirname, '..', 'ressources', 'photos');
|
||||
|
||||
function toDataUri(filePath) {
|
||||
const buf = fs.readFileSync(filePath);
|
||||
return `data:image/png;base64,${buf.toString('base64')}`;
|
||||
}
|
||||
|
||||
const presentationDossier =
|
||||
"Je suis Sophie BERNARD, mère isolée de Jules. J'ai la garde complète de mon fils. " +
|
||||
"Je recherche une assistante maternelle bienveillante à Bezons. " +
|
||||
"Merci pour l'étude de notre dossier.";
|
||||
|
||||
const body = {
|
||||
email: 'sophie.bernard@example.com',
|
||||
prenom: 'Sophie',
|
||||
nom: 'BERNARD',
|
||||
telephone: '0611223344',
|
||||
adresse: '12 Rue des Lilas',
|
||||
code_postal: '95870',
|
||||
ville: 'Bezons',
|
||||
// Pas de co-parent (mono-parent).
|
||||
enfants: [
|
||||
{
|
||||
prenom: 'Jules',
|
||||
nom: 'BERNARD',
|
||||
date_naissance: '2024-06-10',
|
||||
genre: 'H',
|
||||
// Réutilise une photo de test existante.
|
||||
photo_base64: toDataUri(path.join(photosDir, 'lecomte-maxime.png')),
|
||||
photo_filename: 'jules_bernard.png',
|
||||
},
|
||||
],
|
||||
presentation_dossier: presentationDossier,
|
||||
acceptation_cgu: true,
|
||||
acceptation_privacy: true,
|
||||
};
|
||||
|
||||
const json = JSON.stringify(body);
|
||||
const baseArg = process.argv[2] || 'https://app.ptits-pas.fr';
|
||||
const base = new URL(baseArg.endsWith('/') ? baseArg.slice(0, -1) : baseArg);
|
||||
const url = new URL('/api/v1/auth/register/parent', `${base.protocol}//${base.host}`);
|
||||
|
||||
const opts = {
|
||||
hostname: url.hostname,
|
||||
port: url.port || (url.protocol === 'https:' ? 443 : 80),
|
||||
path: url.pathname,
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Accept: 'application/json',
|
||||
'Content-Length': Buffer.byteLength(json, 'utf8'),
|
||||
},
|
||||
};
|
||||
|
||||
const lib = url.protocol === 'https:' ? https : http;
|
||||
|
||||
console.error(`POST ${url.href} (payload ~${Math.round(json.length / 1024)} Ko)`);
|
||||
|
||||
const req = lib.request(opts, (res) => {
|
||||
let data = '';
|
||||
res.on('data', (c) => {
|
||||
data += c;
|
||||
});
|
||||
res.on('end', () => {
|
||||
console.log('HTTP', res.statusCode);
|
||||
try {
|
||||
const j = JSON.parse(data);
|
||||
console.log(JSON.stringify(j, null, 2));
|
||||
} catch {
|
||||
console.log(data.slice(0, 4000));
|
||||
}
|
||||
if (res.statusCode < 200 || res.statusCode >= 300) process.exit(1);
|
||||
});
|
||||
});
|
||||
|
||||
req.on('error', (e) => {
|
||||
console.error('Erreur réseau:', e.message);
|
||||
process.exit(1);
|
||||
});
|
||||
|
||||
req.setTimeout(120000, () => {
|
||||
req.destroy();
|
||||
console.error('Timeout 120s');
|
||||
process.exit(1);
|
||||
});
|
||||
|
||||
req.write(json);
|
||||
req.end();
|
||||
Reference in New Issue
Block a user