diff --git a/CLAUDE.md b/CLAUDE.md index 41a1f4d..c3591b8 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -57,10 +57,12 @@ les tables sauf les tables d'association. - **`Edition`** : `year`, `name` (opt.), `start_date`, `end_date`, `retention_days` (durée de rétention des données nominatives en jours, `NULL` = pas de purge). -- **`DayPart`** : découpage d'une journée propre à l'édition (nombre et bornes - libres, paramétrable par la coordination). `code`, `label`, `start_time`, - `end_time` (`end_time < start_time` ⇒ passe minuit), `order`. Unique - (`edition_id`, `code`). +- **`DayPart`** (« créneau type ») : découpage d'une journée propre à l'édition + (nombre et bornes libres). `code`, `label`, `start_time`, `end_time` + (`end_time < start_time` ⇒ passe minuit), `order`. Unique (`edition_id`, + `code`) ; `code` figé après création (clé de l'import des disponibilités). + CRUD `GET/POST/PATCH/DELETE /editions/{id}/day-parts` (COORDINATION pour + l'écriture). - **`Volunteer`** : `email` (unique **par édition**, nullable pour les bénévoles créés à la main — plusieurs `NULL` autorisés), `first_name`, `last_name`, `phone`, `tshirt_size`, `diet`, `comment`. Pas de date de @@ -69,8 +71,13 @@ les tables sauf les tables d'association. (`volunteer_skill`). N-N `Shift` (`shift_required_skill`). - **`Position`** : `name`, `location`, `category` (`PositionCategory`), `lead_account_id` (→ `Account`, `SET NULL` à la suppression du compte). -- **`Shift`** : `position_id`, `starts_at`, `ends_at` (peut finir le - lendemain), `min_staff`, `ideal_staff`, compétences requises (N-N `Skill`). +- **`Shift`** : `position_id`, `day_part_id` (nullable ; le créneau type dont + il est issu, `SET NULL` si le type est supprimé), `starts_at`, `ends_at` + (peut finir le lendemain), `min_staff`, `ideal_staff`, compétences requises + (N-N `Skill`). À la création d'un `Position`, un `Shift` à 0/0 est généré par + jour de l'édition et par `DayPart` ; + `POST /editions/{id}/positions/{pid}/generate-shifts` recrée les manquants + (après ajout d'un créneau type ou extension des dates). - **`Availability`** : `volunteer_id`, `date`, `day_part_id`, `status` (`AvailabilityStatus`). Unique (`volunteer_id`, `date`, `day_part_id`). - **`Assignment`** : `volunteer_id`, `shift_id`, `source` (`AssignmentSource`, @@ -253,9 +260,10 @@ fonctions d'IA. *(L'envoi d'emails par SMTP est en place — voir § 2.)* │ │ ├── db.py # engine + session │ │ ├── logging_config.py # RGPD : pas de PII dans les logs │ │ ├── api/ # routers + schemas Pydantic + deps -│ │ │ # health, auth, accounts, imports, -│ │ │ # volunteers, positions, shifts, -│ │ │ # assignments, matrix, notifications +│ │ │ # health, auth, accounts, editions, +│ │ │ # day_parts, imports, volunteers, +│ │ │ # positions, shifts, assignments, +│ │ │ # matrix, notifications │ │ ├── auth/ # mot de passe + lien magique + JWT + rôles │ │ ├── email/ # SMTP (sender) + rendu des emails (templates) │ │ ├── importing/ # import CSV/Excel (parser, values, service) @@ -342,7 +350,8 @@ Aucune dépendance locale requise hors Docker. | 8 | Second système : connexion mot de passe (bcrypt) pour la coordination | validée | | 9 | Suppression du statut d'affectation (plus d'étape de confirmation) | validée | | 10 | Envoi d'emails par SMTP : lien magique + récapitulatif de planning | validée | -| 11 | `GET`/`PATCH /editions/{id}` (nom, dates) — ajouter/retirer des jours ; UX config front | à valider | +| 11 | `GET`/`PATCH /editions/{id}` (nom, dates) — ajouter/retirer des jours ; UX config front | validée | +| 12 | Créneaux types (`DayPart` CRUD) + génération auto des créneaux 0/0 à la création d'un poste ; case « à définir » / « sureffectif » sur la grille | à valider | **Reste hors périmètre** (modèle prêt à les accueillir) : solveur OR-Tools, SMS, constructeur de formulaire, pointage sur site, IA. Frontend : diff --git a/backend/app/api/_shiftgen.py b/backend/app/api/_shiftgen.py new file mode 100644 index 0000000..077d9fc --- /dev/null +++ b/backend/app/api/_shiftgen.py @@ -0,0 +1,55 @@ +"""Génération des créneaux d'un poste à partir des créneaux types (DayPart).""" + +import datetime as dt + +from sqlmodel import Session, select + +from app.models import DayPart, Edition, Position, Shift + + +def _dates(edition: Edition) -> list[dt.date]: + span = (edition.end_date - edition.start_date).days + return [edition.start_date + dt.timedelta(days=i) for i in range(span + 1)] + + +def _window(day: dt.date, part: DayPart) -> tuple[dt.datetime, dt.datetime]: + start = dt.datetime.combine(day, part.start_time) + end_day = ( + day if part.end_time > part.start_time else day + dt.timedelta(days=1) + ) + return start, dt.datetime.combine(end_day, part.end_time) + + +def generate_missing_shifts( + session: Session, edition: Edition, position: Position +) -> int: + """Crée, pour chaque jour de l'édition et chaque créneau type, un créneau à + besoin 0/0 s'il n'existe pas déjà. Retourne le nombre créé.""" + day_parts = list( + session.exec(select(DayPart).where(DayPart.edition_id == edition.id)) + ) + existing = { + (s.day_part_id, s.starts_at.date()) + for s in session.exec( + select(Shift).where(Shift.position_id == position.id) + ) + } + created = 0 + for day in _dates(edition): + for part in day_parts: + if (part.id, day) in existing: + continue + start, end = _window(day, part) + session.add( + Shift( + edition_id=edition.id, + position_id=position.id, + day_part_id=part.id, + starts_at=start, + ends_at=end, + min_staff=0, + ideal_staff=0, + ) + ) + created += 1 + return created diff --git a/backend/app/api/day_parts.py b/backend/app/api/day_parts.py new file mode 100644 index 0000000..1e31dfb --- /dev/null +++ b/backend/app/api/day_parts.py @@ -0,0 +1,100 @@ +"""CRUD des créneaux types (`DayPart`) d'une édition. + +Un poste, à sa création, reçoit un créneau (besoin 0/0) par jour et par créneau +type. Le `code` sert de clé stable pour l'import des disponibilités : il est +figé après création.""" + +import uuid + +from fastapi import APIRouter, Depends, HTTPException, Response, status +from sqlalchemy.exc import IntegrityError +from sqlmodel import Session, select + +from app.api._common import owned_or_404 +from app.api.deps import get_edition +from app.api.schemas import DayPartCreate, DayPartRead, DayPartUpdate +from app.auth.deps import current_account_in_edition, require_coordinator +from app.db import get_session +from app.importing.text import slug_code +from app.models import Account, DayPart, Edition + +router = APIRouter( + prefix="/editions/{edition_id}/day-parts", tags=["day-parts"] +) + + +@router.get("", response_model=list[DayPartRead]) +def list_day_parts( + edition: Edition = Depends(get_edition), + _account: Account = Depends(current_account_in_edition), + session: Session = Depends(get_session), +) -> list[DayPart]: + return list( + session.exec( + select(DayPart) + .where(DayPart.edition_id == edition.id) + .order_by(DayPart.order, DayPart.start_time) + ) + ) + + +@router.post("", response_model=DayPartRead, status_code=status.HTTP_201_CREATED) +def create_day_part( + payload: DayPartCreate, + edition: Edition = Depends(get_edition), + _guard: Account = Depends(require_coordinator), + session: Session = Depends(get_session), +) -> DayPart: + code = (payload.code or slug_code(payload.label)).strip() + if not code: + raise HTTPException( + status_code=422, detail={"code": "day_part.code_required"} + ) + day_part = DayPart( + edition_id=edition.id, + code=code, + label=payload.label.strip(), + start_time=payload.start_time, + end_time=payload.end_time, + order=payload.order, + ) + session.add(day_part) + try: + session.commit() + except IntegrityError as exc: + session.rollback() + raise HTTPException( + status_code=409, detail={"code": "day_part.duplicate_code"} + ) from exc + session.refresh(day_part) + return day_part + + +@router.patch("/{day_part_id}", response_model=DayPartRead) +def update_day_part( + day_part_id: uuid.UUID, + payload: DayPartUpdate, + edition: Edition = Depends(get_edition), + _guard: Account = Depends(require_coordinator), + session: Session = Depends(get_session), +) -> DayPart: + day_part = owned_or_404(session.get(DayPart, day_part_id), edition.id) + for field, value in payload.model_dump(exclude_unset=True).items(): + setattr(day_part, field, value) + session.commit() + session.refresh(day_part) + return day_part + + +@router.delete("/{day_part_id}", status_code=status.HTTP_204_NO_CONTENT) +def delete_day_part( + day_part_id: uuid.UUID, + edition: Edition = Depends(get_edition), + _guard: Account = Depends(require_coordinator), + session: Session = Depends(get_session), +) -> Response: + day_part = owned_or_404(session.get(DayPart, day_part_id), edition.id) + # Cascade base : disponibilités supprimées, day_part_id des créneaux -> NULL. + session.delete(day_part) + session.commit() + return Response(status_code=status.HTTP_204_NO_CONTENT) diff --git a/backend/app/api/positions.py b/backend/app/api/positions.py index 6d02cf3..9b70ca9 100644 --- a/backend/app/api/positions.py +++ b/backend/app/api/positions.py @@ -6,8 +6,14 @@ from fastapi import APIRouter, Depends, Response, status from sqlmodel import Session, select from app.api._common import owned_or_404 +from app.api._shiftgen import generate_missing_shifts from app.api.deps import get_edition -from app.api.schemas import PositionCreate, PositionRead, PositionUpdate +from app.api.schemas import ( + GenerateShiftsResult, + PositionCreate, + PositionRead, + PositionUpdate, +) from app.auth.deps import ( current_account_in_edition, ensure_can_write_position, @@ -31,6 +37,9 @@ def create_position( ) -> Position: position = Position(edition_id=edition.id, **payload.model_dump()) session.add(position) + session.flush() + # Un créneau à besoin 0/0 par jour et par créneau type de l'édition. + generate_missing_shifts(session, edition, position) session.commit() session.refresh(position) return position @@ -78,6 +87,24 @@ def update_position( return position +@router.post( + "/{position_id}/generate-shifts", response_model=GenerateShiftsResult +) +def generate_shifts( + position_id: uuid.UUID, + edition: Edition = Depends(get_edition), + account: Account = Depends(current_account_in_edition), + session: Session = Depends(get_session), +) -> GenerateShiftsResult: + """(Re)génère les créneaux manquants du poste après un ajout de créneau + type ou une extension des dates de l'édition. N'écrase rien d'existant.""" + position = owned_or_404(session.get(Position, position_id), edition.id) + ensure_can_write_position(account, position) + created = generate_missing_shifts(session, edition, position) + session.commit() + return GenerateShiftsResult(created=created) + + @router.delete("/{position_id}", status_code=status.HTTP_204_NO_CONTENT) def delete_position( position_id: uuid.UUID, diff --git a/backend/app/api/schemas.py b/backend/app/api/schemas.py index 723e7e7..6c2c363 100644 --- a/backend/app/api/schemas.py +++ b/backend/app/api/schemas.py @@ -135,6 +135,7 @@ class ShiftRead(ApiModel): id: uuid.UUID edition_id: uuid.UUID position_id: uuid.UUID + day_part_id: uuid.UUID | None starts_at: dt.datetime ends_at: dt.datetime min_staff: int @@ -144,6 +145,41 @@ class ShiftRead(ApiModel): updated_at: dt.datetime +class GenerateShiftsResult(ApiModel): + created: int + + +# --------------------------------------------------------------------------- # +# DayPart (créneau type) # +# --------------------------------------------------------------------------- # +class DayPartRead(ApiModel): + id: uuid.UUID + edition_id: uuid.UUID + code: str + label: str + start_time: dt.time + end_time: dt.time + order: int + created_at: dt.datetime + updated_at: dt.datetime + + +class DayPartCreate(ApiModel): + label: str + start_time: dt.time + end_time: dt.time + # Déduit du label si absent. Immuable ensuite (référencé par l'import). + code: str | None = None + order: int = 0 + + +class DayPartUpdate(ApiModel): + label: str | None = None + start_time: dt.time | None = None + end_time: dt.time | None = None + order: int | None = None + + # --------------------------------------------------------------------------- # # Assignment # # --------------------------------------------------------------------------- # diff --git a/backend/app/i18n/locales/fr.json b/backend/app/i18n/locales/fr.json index 13244c2..4ed4395 100644 --- a/backend/app/i18n/locales/fr.json +++ b/backend/app/i18n/locales/fr.json @@ -6,6 +6,8 @@ "error.validation_failed": "La validation a échoué", "error.conflict": "Conflit avec une ressource existante.", "edition.dates_inconsistent": "La date de fin doit être postérieure ou égale à la date de début.", + "day_part.code_required": "Le code du créneau type ne peut pas être vide.", + "day_part.duplicate_code": "Un créneau type porte déjà ce code dans l'édition.", "shift.ends_not_after_starts": "La fin du créneau doit être postérieure à son début.", "shift.position_wrong_edition": "Le poste n'appartient pas à cette édition.", "volunteer.duplicate_email": "Un bénévole avec cet email existe déjà dans l'édition.", diff --git a/backend/app/main.py b/backend/app/main.py index aa5bde1..27fedc2 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -4,6 +4,7 @@ from fastapi.middleware.cors import CORSMiddleware from app.api.accounts import router as account_router from app.api.assignments import router as assignment_router from app.api.auth import router as auth_router +from app.api.day_parts import router as day_part_router from app.api.editions import router as edition_router from app.api.health import router as health_router from app.api.imports import router as import_router @@ -32,6 +33,7 @@ app.add_middleware( app.include_router(health_router) app.include_router(auth_router) app.include_router(edition_router) +app.include_router(day_part_router) app.include_router(account_router) app.include_router(import_router) app.include_router(volunteer_router) diff --git a/backend/app/migrations/versions/0004_shift_day_part.py b/backend/app/migrations/versions/0004_shift_day_part.py new file mode 100644 index 0000000..bbd21b0 --- /dev/null +++ b/backend/app/migrations/versions/0004_shift_day_part.py @@ -0,0 +1,34 @@ +"""Créneau : lien optionnel vers le créneau type (day_part) + +Revision ID: 0004_shift_day_part +Revises: 0003_drop_assignment_status +Create Date: 2026-09-10 + +""" + +from collections.abc import Sequence + +import sqlalchemy as sa +from alembic import op + +revision: str = "0004_shift_day_part" +down_revision: str | None = "0003_drop_assignment_status" +branch_labels: str | Sequence[str] | None = None +depends_on: str | Sequence[str] | None = None + + +_FK = "shift_day_part_id_fkey" + + +def upgrade() -> None: + op.add_column("shift", sa.Column("day_part_id", sa.Uuid(), nullable=True)) + op.create_index("ix_shift_day_part_id", "shift", ["day_part_id"]) + op.create_foreign_key( + _FK, "shift", "day_part", ["day_part_id"], ["id"], ondelete="SET NULL" + ) + + +def downgrade() -> None: + op.drop_constraint(_FK, "shift", type_="foreignkey") + op.drop_index("ix_shift_day_part_id", table_name="shift") + op.drop_column("shift", "day_part_id") diff --git a/backend/app/models/domain.py b/backend/app/models/domain.py index 767a39c..cb00be6 100644 --- a/backend/app/models/domain.py +++ b/backend/app/models/domain.py @@ -238,6 +238,15 @@ class Shift(TimestampMixin, table=True): starts_at: dt.datetime # Peut être le lendemain de starts_at (créneau à cheval sur minuit). ends_at: dt.datetime + # Créneau type dont ce créneau est issu (génération à la création d'un + # poste). NULL = créneau ad hoc. SET NULL si le type est supprimé. + day_part_id: uuid.UUID | None = Field( + default=None, + foreign_key="day_part.id", + ondelete="SET NULL", + nullable=True, + index=True, + ) min_staff: int = Field( default=0, sa_column=Column(Integer, nullable=False, server_default="0") ) diff --git a/backend/tests/test_api_day_parts.py b/backend/tests/test_api_day_parts.py new file mode 100644 index 0000000..b3c1af5 --- /dev/null +++ b/backend/tests/test_api_day_parts.py @@ -0,0 +1,82 @@ +import datetime as dt + +from sqlmodel import select + +from app.models import Availability, AvailabilityStatus, Role, Shift +from tests.factories import dt_at, make_position, make_shift, make_volunteer + + +def _url(edition, suffix=""): + return f"/editions/{edition.id}/day-parts{suffix}" + + +def test_list_returns_the_three_fixture_types(client, edition): + body = client.get(_url(edition)).json() + assert [d["code"] for d in body] == ["MORNING", "AFTERNOON", "EVENING"] + + +def test_create_slugs_the_code_from_the_label(client, edition): + resp = client.post( + _url(edition), + json={"label": "Nuit profonde", "start_time": "02:00", "end_time": "06:00", "order": 3}, + ) + assert resp.status_code == 201 + assert resp.json()["code"] == "NUIT_PROFONDE" + + +def test_create_duplicate_code_conflicts(client, edition): + body = { + "code": "MORNING", + "label": "Matin bis", + "start_time": "06:00", + "end_time": "13:00", + } + resp = client.post(_url(edition), json=body) + assert resp.status_code == 409 + assert resp.json()["detail"]["code"] == "day_part.duplicate_code" + + +def test_update_day_part(client, edition): + dp_id = client.get(_url(edition)).json()[0]["id"] + resp = client.patch( + _url(edition, f"/{dp_id}"), json={"label": "Tôt le matin", "end_time": "12:00"} + ) + assert resp.status_code == 200 + assert resp.json()["label"] == "Tôt le matin" + assert resp.json()["end_time"] == "12:00:00" + + +def test_delete_unlinks_shifts_and_removes_availabilities( + client, edition, session, day_parts +): + morning = day_parts["MORNING"] + position = make_position(session, edition) + shift = make_shift( + session, edition, position, start=dt_at(10, 6), end=dt_at(10, 13) + ) + shift.day_part_id = morning.id + volunteer = make_volunteer(session, edition, email="v@e.fr") + session.add( + Availability( + edition_id=edition.id, volunteer_id=volunteer.id, + date=dt.date(2026, 7, 10), day_part_id=morning.id, + status=AvailabilityStatus.AVAILABLE, + ) + ) + session.commit() + + assert client.delete(_url(edition, f"/{morning.id}")).status_code == 204 + session.expire_all() + assert session.get(Shift, shift.id).day_part_id is None + assert session.exec(select(Availability)).all() == [] + + +def test_write_is_coordinator_only(edition, make_account, as_account): + lead = make_account(Role.LEAD, email="lead@e.fr") + client = as_account(lead) + assert client.get(_url(edition)).status_code == 200 + resp = client.post( + _url(edition), + json={"label": "X", "start_time": "08:00", "end_time": "09:00"}, + ) + assert resp.status_code == 403 diff --git a/backend/tests/test_shift_generation.py b/backend/tests/test_shift_generation.py new file mode 100644 index 0000000..a6baf8e --- /dev/null +++ b/backend/tests/test_shift_generation.py @@ -0,0 +1,72 @@ +"""Génération des créneaux d'un poste à partir des créneaux types.""" + + +def _positions_url(edition): + return f"/editions/{edition.id}/positions" + + +def _create_position(client, edition, name="Bar"): + return client.post( + _positions_url(edition), json={"name": name, "category": "BAR"} + ).json() + + +def test_creating_a_position_generates_one_shift_per_day_and_type(client, edition): + position = _create_position(client, edition) + shifts = client.get( + f"/editions/{edition.id}/shifts", params={"position_id": position["id"]} + ).json() + # 4 jours (2026-07-09..12) x 3 créneaux types. + assert len(shifts) == 12 + assert all(s["min_staff"] == 0 and s["ideal_staff"] == 0 for s in shifts) + assert all(s["day_part_id"] is not None for s in shifts) + + +def test_generate_is_idempotent(client, edition): + position = _create_position(client, edition) + resp = client.post( + f"{_positions_url(edition)}/{position['id']}/generate-shifts" + ) + assert resp.status_code == 200 + assert resp.json()["created"] == 0 + + +def test_extending_the_edition_then_generating_adds_the_new_days(client, edition): + position = _create_position(client, edition) + client.patch(f"/editions/{edition.id}", json={"end_date": "2026-07-14"}) + + resp = client.post( + f"{_positions_url(edition)}/{position['id']}/generate-shifts" + ) + # 2 jours de plus x 3 créneaux types. + assert resp.json()["created"] == 6 + shifts = client.get( + f"/editions/{edition.id}/shifts", params={"position_id": position["id"]} + ).json() + assert len(shifts) == 18 + + +def test_adding_a_day_part_then_generating_adds_it_everywhere(client, edition): + position = _create_position(client, edition) + client.post( + f"/editions/{edition.id}/day-parts", + json={"label": "Nuit", "start_time": "02:00", "end_time": "05:00"}, + ) + resp = client.post( + f"{_positions_url(edition)}/{position['id']}/generate-shifts" + ) + assert resp.json()["created"] == 4 # 1 par jour + + +def test_generation_does_not_touch_staffing_already_set(client, edition): + position = _create_position(client, edition) + shift = client.get( + f"/editions/{edition.id}/shifts", params={"position_id": position["id"]} + ).json()[0] + client.patch( + f"/editions/{edition.id}/shifts/{shift['id']}", + json={"min_staff": 3, "ideal_staff": 5}, + ) + client.post(f"{_positions_url(edition)}/{position['id']}/generate-shifts") + again = client.get(f"/editions/{edition.id}/shifts/{shift['id']}").json() + assert again["min_staff"] == 3 and again["ideal_staff"] == 5 diff --git a/frontend/src/api/hooks.ts b/frontend/src/api/hooks.ts index 1b0a02b..b565c8e 100644 --- a/frontend/src/api/hooks.ts +++ b/frontend/src/api/hooks.ts @@ -10,6 +10,8 @@ import type { AssignmentCreate, AssignmentUpdate, AssignmentValidateResult, + DayPartCreate, + DayPartUpdate, EditionUpdate, PlanningNotificationRequest, PositionCreate, @@ -41,6 +43,10 @@ export function useEdition() { return useQuery({ queryKey: queryKeys.edition, queryFn: () => api.editions.get(edition) }); } +export function useDayParts() { + return useQuery({ queryKey: ['dayParts', edition], queryFn: () => api.dayParts.list(edition) }); +} + export function useVolunteers(options?: { enabled?: boolean }) { return useQuery({ queryKey: queryKeys.volunteers, @@ -122,6 +128,47 @@ export function useUpdateEdition() { }); } +export function useCreateDayPart() { + const client = useQueryClient(); + return useMutation({ + mutationFn: (body: DayPartCreate) => api.dayParts.create(edition, body), + onSuccess: () => client.invalidateQueries({ queryKey: ['dayParts', edition] }), + }); +} + +export function useUpdateDayPart() { + const client = useQueryClient(); + return useMutation({ + mutationFn: ({ id, body }: { id: string; body: DayPartUpdate }) => + api.dayParts.update(edition, id, body), + onSuccess: () => client.invalidateQueries({ queryKey: ['dayParts', edition] }), + }); +} + +export function useDeleteDayPart() { + const client = useQueryClient(); + const invalidate = useInvalidate(); + return useMutation({ + mutationFn: (id: string) => api.dayParts.remove(edition, id), + onSuccess: () => { + client.invalidateQueries({ queryKey: ['dayParts', edition] }); + invalidate.shifts(); + invalidate.planning(); + }, + }); +} + +export function useGenerateShifts() { + const invalidate = useInvalidate(); + return useMutation({ + mutationFn: (positionId: string) => api.positions.generateShifts(edition, positionId), + onSuccess: () => { + invalidate.shifts(); + invalidate.planning(); + }, + }); +} + export function useCreateVolunteer() { const invalidate = useInvalidate(); return useMutation({ @@ -156,6 +203,7 @@ export function useCreatePosition() { mutationFn: (body: PositionCreate) => api.positions.create(edition, body), onSuccess: () => { invalidate.positions(); + invalidate.shifts(); invalidate.planning(); }, }); diff --git a/frontend/src/api/http-client.ts b/frontend/src/api/http-client.ts index 05b74e4..9acd193 100644 --- a/frontend/src/api/http-client.ts +++ b/frontend/src/api/http-client.ts @@ -2,6 +2,8 @@ import type { AssignmentCreate, AssignmentUpdate, AssignmentValidateRequest, + DayPartCreate, + DayPartUpdate, EditionUpdate, LoginRequest, MagicLinkRequest, @@ -72,6 +74,15 @@ export function createHttpApi(baseUrl: string): PlanningApi { update: (editionId, body: EditionUpdate) => request(base(editionId), { method: 'PATCH', body: JSON.stringify(body) }), }, + dayParts: { + list: (editionId) => request(`${base(editionId)}/day-parts`), + create: (editionId, body: DayPartCreate) => + request(`${base(editionId)}/day-parts`, { method: 'POST', body: JSON.stringify(body) }), + update: (editionId, id, body: DayPartUpdate) => + request(`${base(editionId)}/day-parts/${id}`, { method: 'PATCH', body: JSON.stringify(body) }), + remove: (editionId, id) => + request(`${base(editionId)}/day-parts/${id}`, { method: 'DELETE' }), + }, volunteers: { list: (editionId) => request(`${base(editionId)}/volunteers`), get: (editionId, id) => request(`${base(editionId)}/volunteers/${id}`), @@ -91,6 +102,8 @@ export function createHttpApi(baseUrl: string): PlanningApi { request(`${base(editionId)}/positions/${id}`, { method: 'PATCH', body: JSON.stringify(body) }), remove: (editionId, id) => request(`${base(editionId)}/positions/${id}`, { method: 'DELETE' }), + generateShifts: (editionId, id) => + request(`${base(editionId)}/positions/${id}/generate-shifts`, { method: 'POST' }), }, shifts: { list: (editionId, params) => diff --git a/frontend/src/api/mock/dataset.ts b/frontend/src/api/mock/dataset.ts index c6725ae..d63d9a4 100644 --- a/frontend/src/api/mock/dataset.ts +++ b/frontend/src/api/mock/dataset.ts @@ -3,6 +3,7 @@ import { hoursBetween } from '@/lib/time'; import type { AccountRead, AssignmentRead, + DayPartRead, EditionRead, PositionCategory, PositionRead, @@ -10,6 +11,10 @@ import type { VolunteerRead, } from '../schema'; +const PART_LABELS: Record = { M: 'Matin', A: 'Après-midi', S: 'Soirée', N: 'Nuit' }; +const PART_CODES: Record = { M: 'MATIN', A: 'APRES_MIDI', S: 'SOIREE', N: 'NUIT' }; +const hhmm = (h: number) => `${String(h % 24).padStart(2, '0')}:00:00`; + // Jeu de démonstration déterministe, mis en forme comme les réponses de l'API. // Sert quand `VITE_API_MODE=mock` (défaut tant que le back-end n'a pas de seed). @@ -21,6 +26,7 @@ export const DEMO_COORDINATOR_PASSWORD = 'demo'; export interface MockState { edition: EditionRead; + dayParts: DayPartRead[]; volunteers: VolunteerRead[]; positions: PositionRead[]; shifts: ShiftRead[]; @@ -126,6 +132,18 @@ export function buildMockState(): MockState { updated_at: NOW, })); + const dayParts: DayPartRead[] = PART_BOUNDS.map(([code, start, end], i) => ({ + id: `dp_${code}`, + edition_id, + code: PART_CODES[code] ?? code, + label: PART_LABELS[code] ?? code, + start_time: hhmm(start), + end_time: hhmm(end), + order: i, + created_at: NOW, + updated_at: NOW, + })); + const shifts: ShiftRead[] = []; let shiftSeq = 1; for (const raw of RAW_POSITIONS) { @@ -136,6 +154,7 @@ export function buildMockState(): MockState { id: `s${shiftSeq}`, edition_id, position_id: raw.id, + day_part_id: `dp_${code}`, starts_at: iso(dateStr, bounds[1]), ends_at: iso(dateStr, bounds[2]), min_staff, @@ -341,6 +360,7 @@ export function buildMockState(): MockState { return { edition, + dayParts, volunteers, positions, shifts, diff --git a/frontend/src/api/mock/mock-client.ts b/frontend/src/api/mock/mock-client.ts index 02e7eb9..f1c25e4 100644 --- a/frontend/src/api/mock/mock-client.ts +++ b/frontend/src/api/mock/mock-client.ts @@ -4,6 +4,9 @@ import type { AccountRead, AssignmentRead, AssignmentValidateResult, + DayPartCreate, + DayPartRead, + DayPartUpdate, EditionUpdate, MatrixResponse, PlanningNotificationRequest, @@ -67,6 +70,57 @@ const notFound = (): never => { const touch = () => new Date().toISOString().replace(/\.\d+Z$/, ''); +const addDays = (day: string, n: number): string => { + const [y, m, d] = day.split('-').map(Number); + return new Date(Date.UTC(y, m - 1, d + n)).toISOString().slice(0, 10); +}; + +const slugCode = (label: string): string => + label + .trim() + .toUpperCase() + .normalize('NFD') + .replace(/[^A-Z0-9]+/g, '_') + .replace(/^_+|_+$/g, ''); + +function shiftWindow(day: string, dp: DayPartRead): [string, string] { + const endDay = dp.end_time <= dp.start_time ? addDays(day, 1) : day; + return [`${day}T${dp.start_time}`, `${endDay}T${dp.end_time}`]; +} + +function generateMissingShifts(positionId: string): number { + const existing = new Set( + state.shifts + .filter((s) => s.position_id === positionId) + .map((s) => `${s.day_part_id}|${s.starts_at.slice(0, 10)}`), + ); + let created = 0; + let day = state.edition.start_date; + while (day <= state.edition.end_date) { + for (const dp of state.dayParts) { + if (existing.has(`${dp.id}|${day}`)) continue; + const [starts_at, ends_at] = shiftWindow(day, dp); + const now = touch(); + state.shifts.push({ + id: `s${state.seq++}`, + edition_id: state.edition.id, + position_id: positionId, + day_part_id: dp.id, + starts_at, + ends_at, + min_staff: 0, + ideal_staff: 0, + required_skill_codes: [], + created_at: now, + updated_at: now, + }); + created += 1; + } + day = addDays(day, 1); + } + return created; +} + function shiftById(id: string): ShiftRead { const shift = state.shifts.find((s) => s.id === id); if (!shift) return notFound(); @@ -228,6 +282,50 @@ export function createMockApi(): PlanningApi { return delay(state.edition); }, }, + dayParts: { + list: () => + delay([...state.dayParts].sort((a, b) => a.order - b.order || a.start_time.localeCompare(b.start_time))), + create: (_edition, body: DayPartCreate) => { + const code = (body.code ?? slugCode(body.label)).trim(); + if (!code) throw new ApiError(422, 'day_part.code_required'); + if (state.dayParts.some((d) => d.code === code)) { + throw new ApiError(409, 'day_part.duplicate_code'); + } + const now = touch(); + const dp: DayPartRead = { + id: `dp_${state.seq++}`, + edition_id: state.edition.id, + code, + label: body.label.trim(), + start_time: body.start_time, + end_time: body.end_time, + order: body.order ?? 0, + created_at: now, + updated_at: now, + }; + state.dayParts.push(dp); + return delay(dp); + }, + update: (_edition, id, body: DayPartUpdate) => { + const dp = state.dayParts.find((d) => d.id === id) ?? notFound(); + Object.assign(dp, { + ...('label' in body ? { label: body.label } : {}), + ...('start_time' in body ? { start_time: body.start_time } : {}), + ...('end_time' in body ? { end_time: body.end_time } : {}), + ...('order' in body ? { order: body.order } : {}), + updated_at: touch(), + }); + return delay(dp); + }, + remove: (_edition, id) => { + state.dayParts = state.dayParts.filter((d) => d.id !== id); + state.shifts.forEach((s) => { + if (s.day_part_id === id) s.day_part_id = null; + }); + return delay(undefined); + }, + }, + volunteers: { list: () => delay( @@ -301,6 +399,7 @@ export function createMockApi(): PlanningApi { updated_at: now, }; state.positions.push(position); + generateMissingShifts(position.id); return delay(position); }, update: (_edition, id, body) => { @@ -321,6 +420,10 @@ export function createMockApi(): PlanningApi { state.assignments = state.assignments.filter((a) => !shiftIds.has(a.shift_id)); return delay(undefined); }, + generateShifts: (_edition, id) => { + if (!state.positions.some((x) => x.id === id)) return notFound(); + return delay({ created: generateMissingShifts(id) }); + }, }, shifts: { @@ -343,6 +446,7 @@ export function createMockApi(): PlanningApi { id: `s${state.seq++}`, edition_id: state.positions[0].edition_id, position_id: body.position_id, + day_part_id: null, starts_at: body.starts_at, ends_at: body.ends_at, min_staff: body.min_staff ?? 0, diff --git a/frontend/src/api/schema.ts b/frontend/src/api/schema.ts index 29320aa..81400e4 100644 --- a/frontend/src/api/schema.ts +++ b/frontend/src/api/schema.ts @@ -58,6 +58,42 @@ export interface EditionUpdate { retention_days?: number | null; } +// --------------------------------------------------------------------------- // +// DayPart (créneau type) // +// --------------------------------------------------------------------------- // +export interface DayPartRead { + id: string; + edition_id: string; + code: string; + label: string; + /** Heures « HH:MM:SS ». end < start ⇒ passe minuit. */ + start_time: string; + end_time: string; + order: number; + created_at: string; + updated_at: string; +} + +export interface DayPartCreate { + label: string; + start_time: string; + end_time: string; + /** Déduit du label si absent ; figé ensuite. */ + code?: string; + order?: number; +} + +export interface DayPartUpdate { + label?: string; + start_time?: string; + end_time?: string; + order?: number; +} + +export interface GenerateShiftsResult { + created: number; +} + // --------------------------------------------------------------------------- // // Volunteer // // --------------------------------------------------------------------------- // @@ -134,6 +170,8 @@ export interface ShiftRead { id: string; edition_id: string; position_id: string; + /** Créneau type d'origine, ou null pour un créneau ad hoc. */ + day_part_id: string | null; /** Datetime naïf, heure locale Europe/Paris (ISO sans fuseau). */ starts_at: string; ends_at: string; diff --git a/frontend/src/api/types.ts b/frontend/src/api/types.ts index 82e0d4b..2a73211 100644 --- a/frontend/src/api/types.ts +++ b/frontend/src/api/types.ts @@ -6,8 +6,12 @@ import type { AssignmentValidateRequest, AssignmentValidateResult, AssignmentWriteResult, + DayPartCreate, + DayPartRead, + DayPartUpdate, EditionRead, EditionUpdate, + GenerateShiftsResult, LoginRequest, MagicLinkRequest, MatrixResponse, @@ -36,6 +40,12 @@ export interface PlanningApi { get(editionId: string): Promise; update(editionId: string, body: EditionUpdate): Promise; }; + dayParts: { + list(editionId: string): Promise; + create(editionId: string, body: DayPartCreate): Promise; + update(editionId: string, id: string, body: DayPartUpdate): Promise; + remove(editionId: string, id: string): Promise; + }; volunteers: { list(editionId: string): Promise; get(editionId: string, id: string): Promise; @@ -49,6 +59,8 @@ export interface PlanningApi { create(editionId: string, body: PositionCreate): Promise; update(editionId: string, id: string, body: PositionUpdate): Promise; remove(editionId: string, id: string): Promise; + /** (Re)crée les créneaux manquants (0/0) d'après les créneaux types. */ + generateShifts(editionId: string, id: string): Promise; }; shifts: { list(editionId: string, params?: { positionId?: string }): Promise; diff --git a/frontend/src/i18n/locales/fr.json b/frontend/src/i18n/locales/fr.json index f8cf445..6af68ed 100644 --- a/frontend/src/i18n/locales/fr.json +++ b/frontend/src/i18n/locales/fr.json @@ -86,6 +86,7 @@ "grille.legend.incomplete": "INCOMPLET", "grille.legend.complete": "COMPLET", "grille.legend.overstaffed": "SUREFFECTIF", + "grille.legend.undefined": "À DÉFINIR", "grille.positionsCount": "{count} POSTES", "grille.assignedRequired": "AFFECTÉS / IDÉAL", "grille.footnote": "Chaque cellule est un créneau. Nombre = bénévoles affectés, / = effectif idéal. Cliquer ouvre le panneau d'affectation à droite.", @@ -168,6 +169,8 @@ "config.grid.emptyDay": "Aucun créneau ce jour.", "config.grid.deletePosition": "SUPPRIMER LE POSTE", "config.grid.deletePositionConfirm": "Supprimer ce poste et tous ses créneaux ?", + "config.grid.generateShifts": "GÉNÉRER LES CRÉNEAUX", + "config.grid.generated": "{count} créneau(x) ajouté(s).", "config.grid.note": "Effectifs, créneaux, nom et catégorie du poste sont enregistrés immédiatement via l'API. Pour ajouter ou retirer des jours, modifiez les dates de l'édition dans l'onglet « Règles & édition ».", "config.vol.importTitle": "IMPORTER DES INSCRIPTIONS", @@ -218,6 +221,12 @@ "config.rules.positionsCount": "Postes", "config.rules.shiftsCount": "Créneaux", "edition.dates_inconsistent": "La date de fin doit être postérieure ou égale à la date de début.", + "day_part.code_required": "Le libellé du créneau type est requis.", + "day_part.duplicate_code": "Un créneau type porte déjà ce libellé.", + "config.rules.slotsTitle": "CRÉNEAUX TYPES", + "config.rules.slotLabel": "Libellé", + "config.rules.slotAdd": "AJOUTER", + "config.rules.slotsNote": "Ces créneaux sont ajoutés à besoin 0/0 sur chaque jour à la création d'un poste. Après un ajout ici (ou une extension des dates), utilisez « Générer les créneaux » sur le poste.", "config.rules.thresholdsTitle": "MOTEUR DE VALIDATION", "config.rules.maxDaily": "Maximum d'heures par journée", "config.rules.minRest": "Repos minimum entre deux créneaux", diff --git a/frontend/src/pages/GrillePage.tsx b/frontend/src/pages/GrillePage.tsx index 4b4f8bb..2b6aa26 100644 --- a/frontend/src/pages/GrillePage.tsx +++ b/frontend/src/pages/GrillePage.tsx @@ -86,6 +86,9 @@ export function GrillePage() { {t('grille.legend.overstaffed')} + + {t('grille.legend.undefined')} + @@ -214,11 +217,20 @@ function PositionRow({ return
; } const assigned = shift.assigned; - const isCrit = assigned < shift.min_staff; - const isOver = assigned > shift.ideal_staff; - const isInc = !isCrit && !isOver && assigned < shift.ideal_staff; - const isOk = !isCrit && !isOver && !isInc; - const glyph = isCrit ? '▲' : isOver ? '▼' : isInc ? '◧' : '✓'; + const undefinedNeed = shift.min_staff === 0 && shift.ideal_staff === 0; + const isCrit = !undefinedNeed && assigned < shift.min_staff; + const isOver = !undefinedNeed && assigned > shift.ideal_staff; + const isInc = !undefinedNeed && !isCrit && !isOver && assigned < shift.ideal_staff; + const isOk = !undefinedNeed && !isCrit && !isOver && !isInc; + const glyph = undefinedNeed + ? '·' + : isCrit + ? '▲' + : isOver + ? '▼' + : isInc + ? '◧' + : '✓'; const selected = selectedShiftId === shift.shift_id; return (
onSelect(shift.shift_id)} className={cx( 'relative flex h-9 cursor-pointer items-center justify-center gap-[3px] border-b border-r border-ink', + undefinedNeed && 'bg-sand-dark hover:bg-sand', isCrit && 'bg-hatch-orange', isOver && 'bg-mauve hover:bg-mauve-hover', isInc && 'bg-yellow-soft hover:bg-yellow', diff --git a/frontend/src/pages/config/ConfigGrid.tsx b/frontend/src/pages/config/ConfigGrid.tsx index 3edd66b..feb0c75 100644 --- a/frontend/src/pages/config/ConfigGrid.tsx +++ b/frontend/src/pages/config/ConfigGrid.tsx @@ -6,6 +6,7 @@ import { useDeletePosition, useDeleteShift, useEdition, + useGenerateShifts, usePositions, useShifts, useUpdatePosition, @@ -233,6 +234,7 @@ function PositionHeader({ }) { const updatePosition = useUpdatePosition(); const deletePosition = useDeletePosition(); + const generate = useGenerateShifts(); const [name, setName] = useState(position.name); const commitName = () => { @@ -269,6 +271,14 @@ function PositionHeader({ ))} +
+ {generate.isSuccess ? ( +
+ {t('config.grid.generated', { count: generate.data.created })} +
+ ) : null} {updatePosition.isError ? : null} + {generate.isError ? : null}
diff --git a/frontend/src/pages/config/ConfigRules.tsx b/frontend/src/pages/config/ConfigRules.tsx index 0133d0b..0fd23a0 100644 --- a/frontend/src/pages/config/ConfigRules.tsx +++ b/frontend/src/pages/config/ConfigRules.tsx @@ -2,9 +2,13 @@ import { useEffect, useState } from 'react'; import { API_MODE } from '@/api'; import { + useCreateDayPart, + useDayParts, + useDeleteDayPart, useEdition, usePositions, useShifts, + useUpdateDayPart, useUpdateEdition, useVolunteers, } from '@/api/hooks'; @@ -12,6 +16,8 @@ import { ErrorNote } from '@/components/state'; import { Btn, Panel, PanelHeader } from '@/components/ui'; import { t } from '@/i18n'; +const hm = (time: string) => time.slice(0, 5); // "HH:MM:SS" -> "HH:MM" + const RULE_CODES = [ 'SHIFT_OVERLAP', 'OUTSIDE_AVAILABILITY', @@ -42,6 +48,16 @@ export function ConfigRules() {
+ + {t('config.rules.slotsTitle')} +
+ +
+ {t('config.rules.slotsNote')} +
+
+
+ {t('config.rules.thresholdsTitle')}
@@ -152,6 +168,107 @@ function EditionForm() { ); } +function DayPartsForm() { + const dayParts = useDayParts(); + const create = useCreateDayPart(); + const update = useUpdateDayPart(); + const remove = useDeleteDayPart(); + const [label, setLabel] = useState(''); + const [start, setStart] = useState('09:00'); + const [end, setEnd] = useState('13:00'); + + if (dayParts.isLoading) return
…
; + if (dayParts.error) return ; + + const rows = [...(dayParts.data ?? [])].sort( + (a, b) => a.order - b.order || a.start_time.localeCompare(b.start_time), + ); + + return ( +
+ {rows.map((dp) => ( +
+ { + const v = e.target.value.trim(); + if (v && v !== dp.label) update.mutate({ id: dp.id, body: { label: v } }); + }} + className="min-w-0 flex-1 border-2 border-ink bg-paper px-2 py-1 font-display text-[12px] font-bold" + /> + + e.target.value && + update.mutate({ id: dp.id, body: { start_time: `${e.target.value}:00` } }) + } + className="border-2 border-ink bg-paper px-1 py-1 font-mono text-[11px]" + /> + + e.target.value && + update.mutate({ id: dp.id, body: { end_time: `${e.target.value}:00` } }) + } + className="border-2 border-ink bg-paper px-1 py-1 font-mono text-[11px]" + /> + +
+ ))} + +
+ setLabel(e.target.value)} + placeholder={t('config.rules.slotLabel')} + className="min-w-0 flex-1 border-2 border-ink bg-yellow px-2 py-1 font-display text-[12px] font-bold" + /> + setStart(e.target.value)} + className="border-2 border-ink bg-paper px-1 py-1 font-mono text-[11px]" + /> + setEnd(e.target.value)} + className="border-2 border-ink bg-paper px-1 py-1 font-mono text-[11px]" + /> + +
+ {create.isError ? : null} + {update.isError ? : null} +
+ ); +} + function InfoRow({ label, value, mono = false }: { label: string; value: string; mono?: boolean }) { return (