# Writing the reference data through the API

The referentials (stands, staff members, timeslots, game categories, locations, adjustments) follow the same CRUD scheme, partitioned by edition. You will know how identifiers are assigned, what a refused write returns (concurrent edit, solve under way), how to check and derive the timeslot grid, and how to import a file. [Stand hours](api-horaires-des-stands.md) and [input warnings](api-avertissements-de-saisie.md) have their own pages.

## Identifiers and codes

An identifier is never chosen by the caller ([ADR 0050](repo:docs/decisions/0050-identifiants-generes-par-edition.md)): the creation `POST` assigns and returns it (`A1`… for an animateur, `S…` stand, `T…` game category, `L…` location, `C…` adjustment, numbered per edition; `E1`… for an edition). An `id` in a creation body is ignored, and a number freed by a deletion is not reused. An adjustment is the exception: it is modified by sending its `POST` again with its identifier, which must exist (`400` otherwise). Stands, game categories and locations carry an optional `code` (`STRATEGIE`), unique in the edition (`409`) and never shaped like an identifier (`400`): it is the key import files cite. A game category cited by a stand or an animateur is written by identifier or by code; the identifier is stored. An edition name of the form `E` followed by a number is refused (`400`).

Game categories are referenced by foreign key: an unknown `id` answers `400`, and so does deleting a category still in use. `polyvalent` designates the polyvalent profiles' category, at most one at a time: setting it on another removes the previous one's flag.

## What a write requires

- A stand carries at least one game category: an empty `typologiesProposees` answers `400` naming the stand (the check applies only at write time: an old row without a category is still read and solved).
- A timeslot requires a date, a start and an end (`400` otherwise). An end before or equal to the start is accepted: that is how a timeslot crossing midnight is written (20:00 to 00:00 lasts four hours), and it alone reads a stand window dated the next day.
- Ad hoc constraints and locks are states: delete and recreate them. A pair of staff members cannot be both incompatible and affine (`400`); an already locked target returns `200` without a duplicate ([ad hoc exceptions](exceptions-ad-hoc.md), [locks](plan-verrous-et-publication.md)).

## Concurrent modification

Each row of the six referentials carries `modifieLe`, the date of its last write, which the `GET` returns and the form sends back as is: without a guard, two tabs saving the same record would let the second silently overwrite the first ([ADR 0023](repo:docs/decisions/0023-modification-concurrente-par-horodatage.md)).

| `modifieLe` sent | Effect |
| --- | --- |
| equal to the row's | written |
| different | `409` with nothing written, body `{ message, code: "MODIFICATION_CONCURRENTE", modifieLe }` with the current value |
| absent or `null` | written without a check (an import, a script, a deliberate overwrite) |

The `code` distinguishes this `409` from the busy-solver one. The UI offers Reload (nothing is written) or Overwrite anyway (the same payload goes again without `modifieLe`).

The other writes carrying the precondition:

- bulk edit sends one `PUT` per row: a row modified elsewhere is refused alone;
- `PUT /api/ouvertures-stands/grille` carries one per stand (`stands[].modifieLe`); `PUT /api/animateurs/competences/grille` one per record (`animateurs[].modifieLe`), but answers `200` with a per-row report: `WRITTEN`, `STALE` (the record's `409`) or `REJECTED` with its reason, a stale row not cancelling the others;
- a webhook reads it in `modifiedAt`, a consigne preset in `modifieLe`. A consigne set over several dates carries a `date → timestamp` table: a date without an entry is unchecked, an entry for a date the request does not set is refused (`400`), and refusing one date cancels the whole setting;
- the `PUT` of each of the four settings sections (`/api/parametres/legal`, `organisation`, `notifications`, `calcul`) reads `modifieLe` in the body; the old 3.x roots, which ignored it on write, left the API in 5.0;
- the `modifier_*` MCP tools accept it as an optional argument; omitted, they re-read the row just before writing.

Imports do not carry it: they replace or merge a whole referential. The check is part of the write: a single SQL statement whose `ON CONFLICT DO UPDATE` carries the precondition and returns no row when it fails (reading then writing would let two saves a millisecond apart through). A solve's persistence leaves `modifieLe` alone, otherwise every open record would conflict after each solve.

## Deleting, and what the deletion takes with it

`GET /api/stands/usages`, `GET /api/animateurs/usages` and `GET /api/creneaux/usages` count what references a selection, so the confirmation says it before deleting: filled seats of the saved plan, manual adjustments, locks, consignes (always zero for an animateur). Repeating `id` returns an aggregated total, leaving a bulk deletion to a single call. The count informs without blocking; an unknown `id` counts zero (no `404`); a request without `id`, or with a non-numeric timeslot `id`, answers `400`; an empty seat does not count. The four counters are not an inventory: zero everywhere never means "nothing references it", since other tables cascade without being counted (swaps, a stand's hours, competences and wishes).

Deleting a timeslot or a stand takes away the seats that were on it and only those. Deleting an animateur empties their seats without deleting them: a seat without an animateur is an unfilled place, visible in `postesNonPourvus` and the coverage screens instead of making the plan look better covered than it is. In bulk, each deletion is its own transaction.

## Writing during a solve

While a solve holds the edition's solver, writing is refused (`409`, the body carrying the job and a `message` readable as is) for: deleting and modifying a stand, an animateur or a timeslot, resetting the edition, importing a scenario, reassigning a seat (repair, day-of, `modifier_affectation`) and accepting a swap. The solve's landing deletes and reinserts all seats, rewrites timeslot dates and hours, and re-saves stands and staff members from the objects captured at start; creations go through, an entity absent at start being named by no seat of the result.

The landing of the solve deletes and reinserts all the seats from the starting plan, rewrites the date and hours of the timeslots, and saves the stands and staff again from the objects captured at the start. Creations go through: an entity absent at the start is named by no seat of the result.

- The refusal is confined to the job's edition: a solve launched on A blocks A even if the tab moved to B; a merely queued solve blocks nothing.
- It comes before everything else in the method: a `404`, a `400` or a `409 REFERENTIEL_FIGE` fade behind it.
- It sits on the service method through `@RefusedWhileSolving`, never in the resource: the REST route and the MCP tool meet the same guard.

Other writes go through (game categories, locations, ad hoc constraints, legal parameters, locks, constraint weights, creations): the landing does not undo them, but the running solve will not reflect them. The UI locks these entries during the solve (`editingLocked`); an MCP assistant, with no screen, receives `RESOLUTION_EN_COURS` in `avertissements` ([ADR 0020](repo:docs/decisions/0020-avertir-dans-la-reponse-d-ecriture.md)), with the same scope as the refusal. See [the MCP tools](mcp-outils.md) and [the solve](api-calcul.md).

## The timeslot grid

A timeslot is created alone (`POST /api/creneaux`) or in bulk by the **timeslot generator** ([ADR 0126](repo:docs/decisions/0126-un-generateur-de-creneaux-unique.md)), from one of three sources: templates (3.x typical days), stand hours, or a recurring pattern. Three gestures apply to all: `POST /api/generateur-creneaux/apercu` writes nothing and returns the verdict on the resulting grid, `.../application` writes, `.../retrait` removes dates from the templates' calendar (their timeslots stay).

```json
POST /api/generateur-creneaux/apercu
{ "source": "RECURRENCE",
  "recurrence": { "jours": "JOURS_SEMAINE", "dateDebut": "2026-07-06", "dateFin": "2026-07-19",
    "joursSemaine": ["MONDAY","TUESDAY","WEDNESDAY","THURSDAY","FRIDAY"],
    "exclusions": ["2026-07-14"],
    "fenetres": [ { "heureDebut": "09:00", "heureFin": "12:00" },
                  { "heureDebut": "14:00", "heureFin": "18:00" } ] } }
→ { "source": "RECURRENCE", "nombreGeneres": 18, "creneaux": [ … ], "controle": { … } }
```

`jours` reuses the stand-hours selector (`TOUS`, `JOURS_SEMAINE`, `PLAGE`, `DATES`); a recurrence adds and never replaces. A generation repeating an existing timeslot comes out as `DOUBLON` (`ERREUR`); `400` on a malformed request. A timeslot is a shift: an overlap on the same day is the normal form of two staggered handovers ([ADR 0037](repo:docs/decisions/0037-une-grille-est-toujours-des-vacations.md)). The 3.x routes (recurrence, derivation and day templates) left the API in 5.0: the generator is the only door.

`GET /api/creneaux/controle` returns the grid's anomalies (`severite` `ERREUR` or `AVERTISSEMENT`, `type`, `date`, `message`), those of stand openings and the feasibility report (`null` without stand or timeslot). Two duration ceilings read there: beyond `parametresLegaux.dureeVacationMaxMinutes` (6 h by default, art. L3121-16) a `VACATION_TROP_LONGUE` warning, beyond what daily rest allows a `REPOS_QUOTIDIEN_IMPOSSIBLE` error. `GET /api/creneaux/diagnostic` describes the grid in place (shifts, dates, `joursFeries`). **Public holidays**: the check adds `VACATION_JOUR_FERIE` (one line per date) when shifts fall on a holiday and the edition has at least one minor available that day (art. L3164-6); with no minor available it stays silent (a festival legitimately opens on 14 July), nothing is blocked, and the message counts the minors without naming them. `GET /api/jours-feries?debut=YYYY-MM-DD&fin=YYYY-MM-DD` returns a range's holidays.

**The `STANDS` source: derive the grid from stand hours.** Each hour at which a stand opens or closes is a cut, and each slice between two cuts where at least one stand is open becomes a timeslot. The request carries `derivation: { dateDebut, dateFin, heureFermeture, dureeMinimaleMinutes, remplacer }`:

- `heureFermeture` gives an end to the "until closing" windows (`00:00` for midnight: the last timeslot crosses midnight).
- A slice shorter than `dureeMinimaleMinutes` (15 by default) joins the next one, or the previous one failing that; a gap shorter than that is closed rather than splitting the timeslot in two.
- `remplacer` judges and, on writing, replaces the whole grid, the solved plan going with it; otherwise the timeslots are added.

Only the days a stand declares "open on these windows" participate: a stand silent on a day is open when the others are. The response carries the timeslots, the `coupures`, the `joursSansFenetre` and the `controle` verdict; `400` without any window.

**The `GABARITS` source.** Templates are managed under `/api/generateur-creneaux/gabarits` and their calendar under `PUT /api/generateur-creneaux/calendrier`; `GET /api/generateur-creneaux` returns both and the dates in breach. The application materialises the calendar by difference (timeslots kept, updated, created, deleted with their seats); a date without a template is never touched. `.../reconnaissance` does the reverse: it replaces the templates with those the grid implies. A timeslot created on a day the edition did not count unfolds the stands' model ([ADR 0104](repo:docs/decisions/0104-les-horaires-d-un-stand-sont-une-liste-de-plages-datees.md)).

## File imports

Imports are partial and previewed: `…/analyse` returns a report without opening a transaction, then the write route re-reads the same file, replays all checks and writes the accepted rows in one transaction. The write receives the file and never the displayed report (a replay or a forged body goes through the same checks); the file is never written to disk ([ADR 0021](repo:docs/decisions/0021-import-tabulaire-partiel-et-previsualise.md)). Only the animateur import has this contract since 4.0: the CSV imports of game categories, locations, stands, timeslots and typical days, and the stand-grid one, answer `410 Gone` pointing to the YAML import (`POST /api/reference-data/import-scenario-fichier`) ([ADR 0128](repo:docs/decisions/0128-le-yaml-est-le-classeur-complet-le-csv-ne-sert-qu-aux-animateurs.md)).

| Import | Routes | Body |
| --- | --- | --- |
| Staff | `POST /api/animateurs/import-csv/analyse`, `POST /api/animateurs/import-csv`, `GET /api/animateurs/import-csv/exemple` | `{ fileName, content, mapping, replaceAnimateurs, replaceJoursIndisponibles }` |

For staff members, `mapping` associates a field with a column index (`null`: field absent, never overwritten); an absent `mapping` asks for the correspondence proposed from the headers, a supplied but empty mapping is taken as is. The report is the same for preview and write (`applied` tells them apart): `rows[]` carries per row its physical number, its verdict (`CREATED`, `UPDATED`, `REJECTED`), its refusal reasons and its warnings.

Refusals on the whole file, before any write: `400` for an empty, `.xlsx`, `.xls`, `.ods` or binary file, one over 1,000,000 characters or 5,000 lines, non-UTF-8, for a mapping designating neither identifier, first name nor last name, and for a full replacement requested while a row is rejected; `409` without any timeslot in the edition or during a solve. File formats are in [the CSV imports](imports-csv.md).
