# Integrating the application: journal, alerts, webhooks, exports and backup

You will know how to read the action journal and what it refuses to contain, how to set the overnight sends and the weather alert, how to plug an outside tool into the webhooks while checking their signature, and the API-side boundaries of branding, exports, backup and scenario import.

## Action journal

`GET /api/historique?limite=200` returns what was done in the current edition, newest first, in pages of at most 500 lines. Filters: `nature=exports` (files that left), `nature=donnees` (modifications a solve would receive), `nature=regles` (a rule's activation, weight or level, without the value), `depuis`/`jusqua` (**`depuis` excluded, `jusqua` included**) and `avant`, the cursor (the id of the last line shown).

| Parameter | Effect |
| --- | --- |
| `nature=exports` | returns only the files that left the application |
| `nature=donnees` | returns only the changes a solve would receive |
| `nature=regles` | returns only the changes of a rule's activation, weight or level (`entiteId`: the rule), without the value |
| `depuis`, `jusqua` | bound a period (two ISO-8601 instants), **`depuis` excluded, `jusqua` included** |
| `avant` | cursor: the id of the last line displayed, for the next page |

The search by `nature` is **done by the database** and covers the whole retention: an export buried under two hundred newer modifications is found. The bounds are those of `GET /api/historique/changements`: `nature=donnees&depuis=<solve end>` returns exactly the lines the Calculate tab counted (successful only). A cursor whose line has disappeared returns an empty page rather than a refusal (only the nightly purge removes a line, and all older ones with it). `GET /api/historique/actions` returns the inventory of described actions, including the `export` flag held by `CatalogueActions`. The journal is read-only, definitively; the table is bounded by a **retention** (`JOURNAL_RETENTION`, 90 days by default) applied by the nightly task.

### What a line carries, and what it never will

A line says when, who, the action and its sentence in French, what it targeted, **the names of the fields a change actually changed** (for the referentials CSV archive, the names of the referentials taken) and whether it succeeded or was refused, with its HTTP code. The author is:

| Author | When |
| --- | --- |
| `ADMIN` | an action from the administration |
| `ANIMATEUR` | the call **proved** it was one: a session opened with the e-mail code, a correct code exchanged for it, an address attested by the proxy, or the dedicated subscription token |
| `ANONYME` | a route opened without that proof |
| `ASSISTANT` | an MCP call |
| `SYSTEME` | the overnight task |

The author is decided on that proof, never on the HTTP code: a wrong code is a 400, a throttled code request a 429. The espace link alone does not prove who holds it; the staff member designated by the token remains the target of the line.

Two things do not appear there, and that is the contract:

- **no value**: "nom, email" says what moved, never what it became;
- **no identity**: the table stores an identifier; `acteurNom` and `entiteNom` are resolved from the reference data **at read time**, so a deleted record leaves a line that no longer names anyone.

### What is traced

Writes and data outputs (PDF, ICS, CSV exports, archive, YAML scenario, dump, mail sends) are traced, never plain reads. A `POST` that only computes is declared **untraced, with its reason**, in `CatalogueActions`. A download is a `GET` traced all the same, since it carries personal data; the `EXPORT_*` and `TELECHARGEMENT_ESPACE_*` actions do **not** count in `/api/historique/changements`: taking out a copy outdates no solve.

A space download is traced **only once identity is proven**: refused before (404, 401), it writes nothing, since a line per attempt would hand the table to the first comer. Two families of `GET` stay untraced, with their reason: sample files, and `/api/abonnements/{token}/planning.ics`, re-read alone by the calendar every few hours.

## Scheduled notifications

`GET` and `PUT /api/parametres/notifications` set the delays of the overnight sends **for this edition**. Whether they go out at all is not set here: only the active edition sends ([ADR 0072](repo:docs/decisions/0072-une-seule-edition-active.md)).

| Field | Role |
| --- | --- |
| `heureRappelVeille` | local time from which the D-1 reminder may leave, **23:00 at the latest**: the task runs once an hour and the window closes at midnight; a later time would never leave, it is refused (`400`) |
| `delaiRelanceHeures` | silence tolerated after publication before a chase (1 to 720) |
| `ancienneteEchangeJours` | waiting time of a swap request before alert (1 to 60) |

A new, duplicated or imported edition is born inactive. The machine's rhythm is not in the API: `NOTIFICATIONS_CRON` and `NOTIFICATIONS_TIMEZONE`, see [operations](../installer/exploitation.md). How the tasks work is described in [background tasks and notifications](taches-de-fond-et-notifications.md).

`GET /api/alertes` returns what these tasks left on the desk, newest first. `limite` applies **per type** (50 by default, 500 at most): a global ceiling would let a handful of records without address (one alert each evening) bury the `ALERTE_ECHANGE`, the only ones calling for a **decision**. An alert closes by dealing with what it signals. **Each send is reserved in the database before leaving**, on a primary key `(edition_id, type, cle)`: the task inserts and sends only if the insert wrote a row; running every hour, restarting or replaying by hand therefore writes to nobody twice, and a swap request is signalled **only once**.

## Weather alert

`GET` and `PUT /api/parametres/meteo` carry the edition's settings: `actif`, `horizonJours` (1 to 14), temperature and gust thresholds, storm and a suggested consigne preset per phenomenon, plus the state of the last query (`state.outcome`: `READ`, `OUT_OF_FORECAST`, `NO_PLACE`, `UNREACHABLE`), `serviceEnabled` (`METEO_ENABLED`) and `editionMayEmit`. The `PUT` carries `modifieLe` as precondition. `POST /api/parametres/meteo/test` queries **now**, with the edition's thresholds, alert active or not, and summarises the forecast per date without raising an alert: it is the only way to try the alert on a simulated date, the morning task keeping only the dates Open-Meteo forecasts (the next sixteen days), so an acceptance run frozen far from the real date answers `outOfForecast`.

An alert never lays down a consigne. It is a line of `GET /api/alertes` (`type` `METEO_ALERTE`, key `date|PHÉNOMÈNE|palier`) whose `lien` leads to `/regles?onglet=consignes&date=…&nouvelle=1&prereglage=…`: the form opens filled in, and the admin rereads the stands and saves it themselves.

- A consigne already in place on the date is named by the alert instead of a suggestion.
- An alert on **today** (by the event-day clock) suggests nothing and has no `lien`: a consigne can only be laid down on a future day.
- A stable forecast raises no alert; a forecast that worsens by one step (two degrees, ten km/h, hail with the thunderstorm) raises a new one.

The MCP tool `consulter_alertes_meteo` reads the same alerts. The choice of these two tasks: [ADR 0074](repo:docs/decisions/0074-deux-jobs-planifies-de-plus-webhooks-et-meteo.md).

## Outgoing webhooks

`/api/webhooks` (administration) configures what the application announces to an outside tool. The configuration is **per instance**, not per edition: the payload says which edition it speaks of, and only the active edition emits ([ADR 0072](repo:docs/decisions/0072-une-seule-edition-active.md)). The formats and the SSRF guard are in [security of outgoing calls](../installer/securite-appels-sortants.md).

| Event code | When | `donnees` |
| --- | --- | --- |
| `planning.publie` | a publication went out | `instantaneId` (the id of the published version: the key keeps its 3.x name, which outside integrations read), `destinataires`, `envoyes`, `sansEmail`, `echecs`, `differes`, `planningsChanges` |
| `echange.soumis` | a swap request reaches the desk | `nombre` |
| `echanges.en_attente` | the overnight task flags requests that are sleeping | `nombre`, `ancienneteMaxJours` |
| `disponibilites.declaree` | a declaration is waiting to be applied | `joursIndisponibles`, `souhaits` |
| `resolution.terminee` | a solve is finished (screen, MCP or queue) | `score`, `faisable` |
| `sauvegarde.echec` | the overnight backup failed (instance event, `edition` is `null`) | `tentativeLe`, `raison`, `echecsConsecutifs` |
| `meteo.alerte` | the morning query raised alerts | `nombre`, `alertes`: for each, `date`, `phenomene` (`chaleur`, `rafales`, `orage`), `valeur`, `seuil`, `palier`, `lieux` (a number), `prereglageSuggere` |
| `absence.signalee` | an animateur reported from their espace that they will not come | `jour`, `portee` (`journee` or `siege`), `poste` (the stand and hours of the seat, `null` for the whole day) |
| `absence.traitee` | the organisation filed or accepted a report (two distinct events if both happen) | `jour`, `portee`, `poste`, `issue` (`classee` or `acceptee`) |
| `echange.arbitre` | the organisation accepted or refused a swap request | `issue` (`acceptee` or `refusee`) |
| `remplacement.applique` | a seat was handed to somebody by hand (repair assistant, Seat panel, MCP); emptying a seat is not one | `jour`, `poste` |
| `consigne.posee` | consignes were laid down or lifted, one message per operation | `issue` (`posee` or `levee`), `jours` |
| `envois.echec` | a batch of e-mails (publication, confirmation reminders) had failures; a batch with none emits nothing | `modele` (`publication` or `relance`), `echecs`, `total` |
| `test` | "Send a test" | none |

An n8n flow filters on these codes: they are not renamed. **None carries a person**, only counts and identifiers. A webhook picks its events one by one: those added in a release are never sent to an existing webhook until the organiser ticks them. Each fact leaves in a message of its own, bursts are not grouped; a failing webhook never prevents the action it announces. The weather service being unreachable emits no event. The `raison` of a failed backup is a **category** ("pg_dump failed"), never `pg_dump`'s message, which names the host, user and server paths.

### Generic format and signature

```http
POST /webhook/planning HTTP/1.1
Content-Type: application/json
X-Planning-Evenement: planning.publie
X-Planning-Livraison: 7d1e…-…
X-Planning-Horodatage: 1752343380
X-Planning-Signature: sha256=2c6d5dd0…

{"id":"7d1e…","evenement":"planning.publie","survenuLe":"2026-07-12T18:03:00Z",
 "edition":{"id":"2026","nom":"Année 2026"},"donnees":{…},"lien":"https://…/publication?edition=2026"}
```

- `X-Planning-Signature` is `sha256=` followed by the hexadecimal HMAC-SHA256 of `horodatage + "." + corps`, with the secret shown **once** when the webhook is created or its secret regenerated. The signed body is, byte for byte, the one received: verify on the raw body, never on re-serialised JSON.
- `X-Planning-Horodatage` is in Unix seconds and is part of what is signed. **Refuse anything more than five minutes off**: a body replayed later no longer passes.
- `X-Planning-Livraison` (and `id` in the body) identifies the delivery, **not the attempt**: a retry and a "Resend" keep the same one. It is the receiver's idempotency key.
- `survenuLe` is the **real** time of the event, even when the instance simulates another date (demonstration event-day mode).

Verification in Python:

```python
import hashlib, hmac, time

def verifier(secret: str, horodatage: str, signature: str, corps: bytes) -> bool:
    if abs(time.time() - int(horodatage)) > 300:
        return False
    attendu = hmac.new(secret.encode(), horodatage.encode() + b"." + corps,
                       hashlib.sha256).hexdigest()
    return hmac.compare_digest("sha256=" + attendu, signature)
```

### Delivery and journal

Each event creates one delivery per active subscribed webhook. A first attempt goes out immediately, off the operation's thread. After that, a network error, a `408`, a `429` (whose `Retry-After` is honoured, capped at 12 h) or a `5xx` are retried after 1 min, 5 min, 30 min, 2 h and 12 h: six attempts at most, then `FAILED`. A name that does not resolve (DNS) is retried the same way.

Any other response, a redirect included, is final: `ABANDONED`. The same goes for an address the guard refuses, a secret the key no longer opens, and a delivery on an edition that is no longer active: every attempt, retry and "Resend" included, asks the question again.

| Route | Role |
| --- | --- |
| `GET /api/webhooks/{id}/livraisons` | the journal: the last 100, kept 30 days (status, attempt, code, duration, a fixed sentence on error, never the response body) |
| `POST /api/webhooks/livraisons/{id}/renvoi` | puts a delivery back at the start of its schedule, under the same identifier |
| `POST /api/webhooks/{id}/test` | sends the `test` event and waits for the response, with no retry: the only synchronous call (`maxAttempts` is `1`) |
| `POST /api/webhooks/{id}/secret` | regenerates the HMAC secret |

Secrets are never read back: the HMAC secret is in the response of the call that generated it (`POST /api/webhooks`, `POST /api/webhooks/{id}/secret`, or a `PUT` switching a webhook to the generic format), and a Slack, Discord or Matrix webhook's address comes back reduced to its host. On a `PUT`, an address or token left empty **keeps** the previous one.

## Branding and legal notice

`GET /api/branding` and `GET /api/mentions-legales` are **public**, like `/api/config`: a legal notice reserved to signed-in users misses its readers (whoever decides whether to trust the site, the animateur whose link expired). The frontend reads the branding **once, before starting**.

- `productName` is never empty; **an empty `logoUrl` means "no logo"**, never "the default logo": no client inherits another's branding.
- The legal fields are the empty string when the `LEGAL_MENTIONS` key is missing, and the page then shows **what is missing** rather than an invented publisher. They live in configuration, not in code: the repository is public, and a natural-person publisher's address is personal data.
- `mesureAudience` and `suiviErreurs` are true when the Cloudflare token and the Sentry DSN have a value; the privacy policy hangs the paragraphs naming Cloudflare and Bugsink on them. They go through this endpoint rather than `/api/config`, whose read fails silently to a disabled configuration and would **hide** these paragraphs where the tools run.
- `demoInstance` says whether the instance declared itself a demo (`LEGAL_DEMO_INSTANCE`): `scripts/verifier-deploiement.sh` asks the instance to know whether empty mandatory notices are a defect.

## Exports

Generation is server-side. The planning is sent in the request body (`POST /api/planning/export/pdf/animateur/{animateurId}`, `.../ics/animateur/{animateurId}`, `.../pdf/all`, `.../ics/all`, `.../bundle/all`), **except the global export** `GET /api/planning/export/pdf/global` and the two archives `GET /api/planning/export/pdf/all` and `GET /api/planning/export/bundle/all` (same paths, no body): an event-sized planning weighs several megabytes in JSON, which the caller need not upload, so these exports read the same source as the calendars. Mail sending is the individual resend `POST /api/planning/envoi/animateur/{animateurId}`; the collective send is the publication ([publication API](api-planning-et-publication.md)). Formats and end-of-event archive: [exports and archives](exports-et-archives.md).

## Automatic backup

The nightly backup is set by the host, not by the API. `GET /api/backups` returns the full state (location and retention, switch, next run, last attempt, dumps present); `PUT /api/backups/active` with `{ "active": false }` **suspends** the backup, `true` resumes it: it is the only value the screen writes. Like the SQL dump, these routes ignore `X-Edition-Id`: a backup takes the whole instance.

Three absences are deliberate and lasting ([ADR 0015](repo:docs/decisions/0015-sauvegarde-par-pg-dump-restauration-hors-application.md)): no download of a dump (it carries the names, birth dates and addresses of every animateur, minors included), no restore ([backup and restore](../installer/sauvegarde-et-restauration.md)), no write of the location or the retention (`BACKUP_DIR`, `BACKUP_RETENTION`).

## Scenario import

The import is a diff, not a blind replacement. The stands and staff of the file are updated **in place**: a staff member who is kept keeps their `access_token` (printed links survive), their sessions, their requests outside the replaced timeslots and their e-mail if the file carries none. Only those absent from the file are deleted, in cascade. By contrast, the solved schedule, the locks, the ad hoc constraints and the solve trace are **always** erased; the timeslots are replaced by those of the file.

`GET /api/reference-data/impact-import` quantifies this scope **before** importing: it is what the confirmation dialog displays, which also records a snapshot when a solved schedule exists. The optional sections of the file (`parametresLegaux`, `parametresSolveur`, `typologies`, `contraintes`, `edition`) are applied if present and left as they are otherwise. `edition:` routes the import to the designated edition, created empty if need be. The import routes are `POST /api/reference-data/import-scenario` and `POST /api/reference-data/import-scenario-fichier`; the format is described in [the YAML scenario](scenario-yaml.md).

The validator, `POST /api/reference-data/valider-scenario-fichier`, runs everything an import checks before writing, cross-references included, without importing anything, and **always answers 200**, including for an empty or malformed file: the verdict is in the body. `erreurs` says what the import would refuse; `avertissements` what it would accept while reporting it, including the signs of a truncated file (a last line without a line break, mandatory sections missing after the last one present, a last list entry that stops before the keys all the others carry). The import returns the same warnings. A cut that falls exactly between two entries or two optional sections leaves no sign. The other import formats are in [CSV imports](imports-csv.md) and the recovery of an edition in [restoring an edition](restaurer-une-edition.md).

## Two traps

**A dump taken before migration `V52` can no longer be re-imported.** The dump names its columns one by one, and `V52` renamed `animateur.jeton_acces` to `access_token`: the import refuses with `column "jeton_acces" ... does not exist`. To recover such a file, replace that string before loading it: it is its only occurrence.

**`POST /api/planning/reset` empties the current edition**, not the database. The other editions are not touched.
