# Nouveautés (feature announcements) — backend specification

**For:** the backend developer (`fleet` repo, Laravel 10, PHP 8.1+, MySQL/MariaDB).
**Goal:** the API behind the admin section **"Nouveautés"** (already built in `dadycar-admin-next`, running on mock data today) and the API Fleet calls to show announcements to its users and report what they did.
**Status of the front-ends:**
- Admin: built. It calls exactly the routes and JSON shapes below. Switching it to the real API = `NEXT_PUBLIC_ANNOUNCEMENTS_MOCK=false`.
- Fleet (`fleet-react-app`): a prototype exists locally (menu pop-up, step card, guided tour on the live map, "NEW" badge), with hard-coded texts and state in `localStorage`. It must be switched to the Fleet API of section 7.

**References:** `docs/announcements/SPEC.md` (functional spec V2), `docs/announcements/README.md`, the admin types `src/domain/entities/announcement.ts` (the contract), and the admin mock `src/infrastructure/repositories/announcement.repository.mock.ts` (a working reference implementation of every rule below, in TypeScript).

> Naming: the backend already has an **"onboarding"** (new-account setup, `OnboardingProgress`). Don't touch it. This feature is **announcements** everywhere: tables, routes, classes.

---

## 0. Jira breakdown (suggested sub-tasks)

| # | Sub-task | Section |
|---|---|---|
| 1 | Migrations + models (announcements, steps, rounds, user states, events, history) | 2 |
| 2 | Catalogs (pages, anchors, sidebar paths, usage events) as config + endpoints | 3, 5.6 |
| 3 | Admin CRUD + validation (FormRequest) + locked fields | 4, 5.1 |
| 4 | Admin lifecycle: publish / unpublish / archive / duplicate / reset (rounds) + history | 5.2 |
| 5 | Audience engine (matching, count, eligibility "why", overlapping modals) | 6, 5.3 |
| 6 | Fleet API: active announcements for the current user, events, preview token | 7 |
| 7 | Statistics (funnel, per step, element not found, adoption) | 5.4 |
| 8 | Notification at publish + reminder job | 8 |
| 9 | Permissions `announcements.manage` / `announcements.publish` | 9 |
| 10 | Media upload | 5.5 |

---

## 1. Conventions to follow (same as the rest of the repo)

- Admin routes in `routes/api/admin/admin-routes.php`, inside the existing `auth.service` + `setUserLocale` + `admin.access` group, gated with `admin.permission:<code>,announcements`.
- Fleet routes in `routes/api/fleet/fleet-v1-routes.php`, with the Fleet auth middleware already used there.
- Controllers use `HttpResponseTrait` (`successHttpResponse` / `errorHttpResponse`). Envelope: `{ "status": true, "message": "...", "data": ... }`.
- Paginated `data`: `{ total, count, per_page, current_page, last_page, previous_page_url, next_page_url, items: [...] }` (same as the other admin lists).
- **Validation errors = Laravel's default 422** `{ "message": "...", "errors": { "title.fr": ["..."], "steps.0.anchor_key": ["..."] } }`. The admin shows each message under the matching field, so **keep the dotted field paths exactly as in this document**.
- Services under `app/Services/Admin/Announcements/` (admin) and `app/Services/Api/V1/Fleet/Announcements/` (Fleet).
- Timestamps that can be empty are **nullable** (MariaDB refuses NOT NULL timestamps without default).
- Dates are stored in UTC and sent in ISO 8601. The admin sends Paris time **with its offset** (e.g. `2026-11-02T09:00:00+01:00`): parse it with Carbon, store UTC.
- Notifications through the existing `NotificationCreator`. Links built with `config('app.frontend_url')`, never a hard-coded domain.
- Admin reads across clients: `withoutGlobalScopes()` on models that carry the site scope (`Vehicle`, …).

---

## 2. Data model

### 2.1 `announcements`

| Column | Type | Notes |
|---|---|---|
| id | bigint PK | |
| key | string(60) unique | slug `^[a-z0-9]+(-[a-z0-9]+)*$`, locked after first publish |
| format | string(20) | `badge`, `sidebar_spotlight`, `banner`, `modal`, `page_widget`, `tour` |
| status | string(12) index | `draft`, `published`, `archived` (stored). "scheduled / live / ended" are **derived** from the dates, never stored |
| title | json | `{fr, en}` |
| body | json | `{fr, en}` restricted HTML (see 4.3) |
| badge_text | json | `{fr, en}` |
| category | string(40) nullable | |
| icon | string(40) nullable | icon name from the fixed list (4.4) |
| media_url | string nullable | |
| media_alt | json | `{fr, en}` |
| cta_label | json | `{fr, en}` |
| cta_path | string nullable | internal path `/fleet/...` only |
| page_key | string(60) nullable | from the pages catalog; null = all pages (banner/modal) or none |
| target_sidebar_path | string nullable | the menu path behind a menu anchor |
| anchor_key | string(80) nullable | from the anchors catalog |
| placement | string(10) | `auto`, `top`, `right`, `bottom`, `left` |
| widget_corner | string(15) | `bottom_right`, `bottom_left` |
| audience | json | see 6.1 |
| starts_at | timestamp nullable index | null = from publication |
| ends_at | timestamp nullable index | null = no end |
| priority | tinyint unsigned | 1–10 |
| rules | json | `{dismissible, max_impressions, hide_after_page_visit, account_age_min_days, account_age_max_days}` |
| success_event | string(60) nullable | from the usage-events catalog |
| reminder | json | `{enabled, after_days, format: badge|banner, max_reminders}` |
| notify | json | `{enabled, channels: [in_app, email], message: {fr, en}}` |
| round | smallint unsigned default 0 | 0 = never published; 1 at first publish; +1 at each reset |
| first_published_at | timestamp nullable | |
| notified_at | timestamp nullable | the publish notification is sent once |
| created_by | bigint nullable | admin user id |
| created_at / updated_at | timestamps | |
| deleted_at | soft deletes | only drafts never published can be deleted |

### 2.2 `announcement_steps`

| Column | Type | Notes |
|---|---|---|
| id | bigint PK | returned to the admin as a **string** (`"id": "42"`) |
| announcement_id | FK cascade | |
| position | smallint | 0-based order |
| title, subtitle, body, media_alt, cta_label | json `{fr, en}` | |
| icon, media_url, cta_path | nullable strings | |
| anchor_key | string(80) nullable | |
| placement | string(10) | |

The admin sends steps as an ordered array. New steps carry a client id starting with `new-…`: create them. Steps whose id is absent from the array are deleted (only allowed before the first publish, see 4.5).

### 2.3 `announcement_rounds`

`id, announcement_id, number, started_at, ended_at (nullable)`. A round starts at publish (number 1) and at each reset; it ends at unpublish, archive or reset. Statistics are kept per round.

### 2.4 `announcement_user_states` (one row per user, announcement and round)

`id, announcement_id, round, user_id, company_id, impressions (int), first_seen_at, last_seen_at, clicked_at, dismissed_at, snoozed_until, completed_at, step_reached (smallint), reminders_shown (smallint), last_reminder_at, adopted_at` — all timestamps nullable; unique `(announcement_id, round, user_id)`.

### 2.5 `announcement_events` (append-only, feeds the statistics)

`id, announcement_id, round, user_id, company_id, type, step_id (nullable), anchor_key (nullable), created_at`. Index `(announcement_id, round, type)`.
Types: `seen`, `clicked`, `dismissed`, `snoozed`, `step_seen`, `step_completed`, `completed`, `anchor_missing`, `reminder_seen`, `adopted`.

### 2.6 `announcement_history`

`id, announcement_id, action (created|updated|published|unpublished|reset|archived|duplicated), user_id, user_name, detail (string nullable), created_at`.
`detail` = the changed field names for `updated` (e.g. "Titre, Audience"), the reason for `reset`, "Notification envoyée à N utilisateurs" for a publish with notification, the source title for `duplicated`.

---

## 3. Catalogs (pickers of the admin)

The admin never types a URL or a technical name: everything comes from these lists. Keep them in **`config/announcements.php`** (versioned with the code; a Fleet developer who adds a button adds one line here).

```php
return [
    // Pages of Fleet the admin can target. 'path' is what the preview opens (":id" = example vehicle).
    'pages' => [
        ['key' => 'dashboard',    'label' => 'Tableau de bord',                     'path' => '/fleet/dashboard',     'needs_vehicle' => false],
        ['key' => 'vehicles',     'label' => 'Liste des véhicules',                 'path' => '/fleet/vehicles',      'needs_vehicle' => false],
        ['key' => 'vehicle',      'label' => 'Fiche véhicule (tous les véhicules)', 'path' => '/fleet/vehicles/:id',  'needs_vehicle' => true],
        ['key' => 'car-location', 'label' => 'Localisation des véhicules',          'path' => '/fleet/car-location',  'needs_vehicle' => false],
        ['key' => 'completeness', 'label' => 'Complétude du parc',                  'path' => '/fleet/completeness',  'needs_vehicle' => false],
        // ...
    ],
    // Elements an announcement can point at. page_key null = a menu entry (offered on every page).
    // 'key' MUST equal the anchor name Fleet puts on the element (data-announcement-anchor / data-testid).
    'anchors' => [
        ['key' => 'sidebar.car-location',      'label' => 'Localisation des véhicules', 'page_key' => null, 'path' => '/fleet/car-location'],
        ['key' => 'header.map-icon',           'label' => 'Icône carte (barre du haut)', 'page_key' => null],
        ['key' => 'map-list-toggle',           'label' => 'Bouton Véhicules',           'page_key' => 'car-location'],
        ['key' => 'map-live-motion-toggle',    'label' => 'Mouvement en direct',        'page_key' => 'car-location'],
        ['key' => 'map-replay-button',         'label' => 'Rejouer 15 min',             'page_key' => 'car-location'],
        ['key' => 'map-zones-button',          'label' => 'Bouton Zones',               'page_key' => 'car-location'],
        ['key' => 'live-vehicle-panel',        'label' => 'Panneau du véhicule',        'page_key' => 'car-location'],
        // ...
    ],
    // Events that prove a feature is used (success event, adoption, reminders).
    'usage_events' => [
        ['value' => 'geofence_zone_created', 'label' => 'Zone de géorepérage créée'],
        ['value' => 'map_opened',            'label' => 'Carte ouverte'],
        // ...
    ],
    'preview_token_ttl_minutes' => 30,
    'max_modals_per_user_per_day' => 1,
    'posthog_dashboard_url' => env('ANNOUNCEMENTS_POSTHOG_URL'),
];
```

The anchor keys above are the ones of the current Fleet map tour (`data-testid` values). Agree the final list with the Fleet developer; the **same key** must be in this config and on the Fleet element.

Other catalogs come from what already exists:
- **plans** and **capabilities**: the entitlements module (`App\Entitlements\Entitlements`, same source as the admin's `/entitlements/catalogue`). Return `[{value, label}]`.
- **permissions** and **roles** of Fleet users: the same source as the Fleet role/permission matrix (the codes used by the Fleet middleware, e.g. `view_vehicles`). Return `[{value, label}]`.
- **companies**: the admin already calls the existing `GET /api/admin/companies/options` (`[{value: companies.id, label}]`). Nothing to add.

---

## 4. Rules (validation and behaviour)

The same rules are implemented in the admin (`src/shared/lib/announcements.ts`, `validateAnnouncement`) so the user sees them before saving; the backend is the authority.

### 4.1 What each format uses

| Format | page_key | anchor_key | placement | widget_corner | steps | body max | badge_text | media | CTA |
|---|---|---|---|---|---|---|---|---|---|
| badge | optional | **required** (menu entry or element) | — | — | — | — | yes (required to publish) | — | — |
| sidebar_spotlight | — | **required, menu entry only** (`page_key` of the anchor is null) | `right` / `bottom` | — | — | 200 | yes | — | yes |
| banner | optional (null = all pages) | — | — | — | — | 160 | yes | — | yes |
| modal | optional (null = all pages) | — | — | — | — | 400 | yes | yes | yes |
| page_widget | **required** | — | — | yes | **2–4**, anchor optional per step | — | — | per step | per step |
| tour | **required** | — | — | — | **1–8**, anchor **required** per step | — | — | per step | per step |

A one-step `tour` is what the admin calls "Info-bulle sur un élément". Fields a format doesn't use are cleared by the admin; ignore/null them server-side.

### 4.2 Field rules

| Field | Rule | Error path |
|---|---|---|
| key | required, slug, unique (among non-deleted), ≤ 60 | `key` |
| title.fr | required, ≤ 60 (title.en ≤ 60) | `title.fr`, `title.en` |
| body.fr | required **to publish** (not for badge), ≤ format max (plain-text length) | `body.fr` |
| badge_text | ≤ 12 each; badge: fr required to publish | `badge_text.fr` |
| cta_path | internal path only: matches `^/fleet(/…)?$`, no `//`, no `..`, no scheme/host | `cta_path` |
| cta_label + cta_path | to publish: both or neither | `cta_path` |
| media_alt.fr | required to publish when `media_url` is set | `media_alt.fr` |
| page_key / anchor_key / steps.*.anchor_key | must exist in the catalogs; anchor must be on the page or a menu entry | `page_key`, `anchor_key`, `steps.N.anchor_key` |
| steps.N.title.fr, steps.N.body.fr | required to publish; ≤ 60 / ≤ 400 | `steps.N.title.fr`, `steps.N.body.fr` |
| steps.N.subtitle | ≤ 80 | `steps.N.subtitle.fr` |
| steps count | per format (4.1) | `steps` |
| ends_at | after starts_at | `ends_at` |
| audience | to publish: at least one criterion, or `everyone_confirmed = true` | `audience` |
| notify.message.fr | required when notify.enabled, ≤ 160 | `notify.message.fr` |
| priority | 1–10 | `priority` |
| rules.max_impressions | 1–20 | `rules.max_impressions` |
| reminder | after_days 1–90, max_reminders 1–5, needs `success_event` when enabled | `reminder` |
| icon | in the fixed list (4.4) or null | `icon` |

**Two levels:** saving a draft refuses only what can never be saved (bad key, too long, external link, unknown catalog value). **Publishing** (and saving an announcement that is already published) also requires everything Fleet needs to show it.

### 4.3 Rich text

`body` and `steps.*.body` are HTML restricted to: `<b>`, `<i>`, `<br>`, `<a href="/fleet/...">`. Sanitise on save (strip every other tag/attribute, drop links that aren't internal). Length limits count visible characters (tags removed).

### 4.4 Icons

A fixed list of lucide icon names, shared by admin and Fleet (both use lucide): `Sparkles, Rocket, Gift, Star, Lightbulb, Zap, Bell, Megaphone, Map, MapPin, Car, Fuel, Wrench, ShieldCheck, FileText, BarChart3, Users, Calendar, Bot, Leaf` (extend with the ones the Fleet tour uses: `SlidersHorizontal, Activity, History, Gauge, Radio`). Keep the list in `config/announcements.php` too.

### 4.5 Locked after the first publish

Once `first_published_at` is set: `key`, `format`, the **number and order of steps** (step ids) cannot change → 422 on `key`, `format` or `steps`. Texts, media, CTA, step texts, step anchors/positions, schedule, priority, rules, audience stay editable. (Changing the audience of a live announcement is confirmed in the admin; the backend just saves it.) `notify` cannot be switched on after the first publish (it is sent once, at first publish).

### 4.6 Display state (derived)

```
draft    → status = draft
archived → status = archived
scheduled→ status = published and starts_at > now
ended    → status = published and ends_at < now
live     → status = published otherwise
```

---

## 5. Admin API — `/api/admin/announcements`

Response `data` of every announcement = the **Announcement resource** (5.0). All routes behind `admin.permission:announcements.manage,announcements`, except those marked **publish** (`announcements.publish`).

### 5.0 Announcement resource (JSON)

```json
{
  "id": 6, "key": "zones-de-georeperage", "format": "tour", "status": "draft",
  "title": {"fr": "Zones de géorepérage", "en": "Geofencing zones"},
  "body": {"fr": "", "en": ""}, "badge_text": {"fr": "Nouveau", "en": "New"},
  "category": "Télématique", "icon": "MapPin",
  "media_url": null, "media_alt": {"fr": "", "en": ""},
  "cta_label": {"fr": "", "en": ""}, "cta_path": null,
  "page_key": "car-location", "target_sidebar_path": null, "anchor_key": null,
  "placement": "auto", "widget_corner": "bottom_right",
  "steps": [{
    "id": "12", "title": {"fr": "Vos zones sur la carte", "en": "Your zones on the map"},
    "subtitle": {"fr": "", "en": ""}, "body": {"fr": "Affichez vos zones…", "en": "Show your zones…"},
    "icon": "MapPin", "media_url": null, "media_alt": {"fr": "", "en": ""},
    "anchor_key": "map-zones-button", "placement": "bottom",
    "cta_label": {"fr": "", "en": ""}, "cta_path": null
  }],
  "audience": {"plans": [], "capabilities_required": ["telematics"], "capabilities_missing": [],
    "permissions": ["view_map"], "roles": [], "companies_include": [], "companies_exclude": [],
    "languages": [], "new_users_only": false, "everyone_confirmed": false},
  "starts_at": null, "ends_at": null, "priority": 5,
  "rules": {"dismissible": true, "max_impressions": 3, "hide_after_page_visit": false,
    "account_age_min_days": null, "account_age_max_days": null},
  "success_event": "geofence_zone_created",
  "reminder": {"enabled": false, "after_days": 7, "format": "banner", "max_reminders": 2},
  "notify": {"enabled": false, "channels": ["in_app"], "message": {"fr": "", "en": ""}},
  "round": 0, "first_published_at": null,
  "counts": {"eligible": 256, "seen": 0, "clicked": 0, "dismissed": 0, "completed": 0},
  "created_by": "Mhamed B.", "updated_at": "2026-10-15T12:45:00+00:00", "created_at": "2026-10-14T12:45:00+00:00"
}
```

- `counts` = the **current round**: `eligible` = users matching the audience now (6.2); the others from `announcement_user_states` of the current round.
- `created_by` = the creator's display name.
- Texts are always `{fr, en}` objects (empty string, never null).

### 5.1 CRUD

| Method | Path | Body / params | Returns |
|---|---|---|---|
| GET | `/` | `page, per_page, order_by (updated_at|title|starts_at|seen), order (ASC|DESC), search (title fr/en, key), state (draft|scheduled|live|ended|archived), format` | paginated Announcement |
| GET | `/{id}` | | Announcement |
| POST | `/` | AnnouncementInput (= the resource without id, status, round, first_published_at, counts, created_by, dates) | Announcement (status draft) |
| PUT | `/{id}` | AnnouncementInput | Announcement |
| DELETE | `/{id}` | only a draft never published, else 422 | — |

`state` filters on the derived display state (4.6). Every save writes an `updated` history entry with the changed fields.

### 5.2 Lifecycle

| Method | Path | Rule | Effect |
|---|---|---|---|
| POST | `/{id}/publish` **publish** | full validation (4.2) → 422 if not ready | status=published; first_published_at ??= now; round 0→1; open the round; send the notification if `notify.enabled` and not yet sent (8.1); history `published` |
| POST | `/{id}/unpublish` **publish** | | status=draft; close the round; history |
| POST | `/{id}/archive` **publish** | | status=archived; close the round; history |
| POST | `/{id}/duplicate` | | new draft: key `<key>-copie` (made unique), title `… (copie)`, round 0, no stats, no first_published_at; history `duplicated` on the copy |
| POST | `/{id}/reset` **publish** | body `{reason?}` | close the current round, round+1, open the new one: everybody in the audience sees it again; history `reset` with the reason |

### 5.3 Audience tools (on an audience that may be unsaved)

| Method | Path | Body | Returns |
|---|---|---|---|
| POST | `/audience-count` | `{audience, rules}` | `{count, total}` — total = all active Fleet users |
| POST | `/eligibility` | `{company_id, audience, rules, starts_at, ends_at, status}` | `{eligible, matching_users, company_users, reasons: string[]}` |
| POST | `/overlapping-modals` | `{id?, starts_at, ends_at, audience}` | Announcement[] — published (not ended) modals, other than `id`, whose period overlaps and whose audience shares at least one user |

`reasons` are plain sentences in the request language (`setUserLocale`), e.g. "Offre « Gratuit » non incluse.", "12 utilisateurs sans le droit requis.", "L'annonce n'est pas publiée.", "En dehors de la période de diffusion." — see the full list in the admin `messages-fr.ts`, block `announcements.reasons`. `eligible` = published, inside its period, and `matching_users > 0`.

These three are called while the admin types (debounced): keep them fast (6.3).

### 5.4 Statistics and history

`GET /{id}/stats?round=N` — `round` absent = current round, `0` = all rounds.

```json
{
  "round": 2, "rounds": [1, 2],
  "counts": {"eligible": 158, "seen": 85, "clicked": 36, "dismissed": 19, "completed": 45},
  "dismiss_rate": 22.4,
  "steps": [{"step_id": "12", "title": "Tout votre véhicule…", "seen": 85, "completed": 73, "anchor_missing": 0}],
  "anchor_missing": 3,
  "adoption": {
    "event": "document_uploaded",
    "adopted_after_seen": 28, "adopted_not_seen": 4,
    "rate_seen": 33.3, "rate_not_seen": 5.2,
    "series": [{"date": "2026-10-02", "rate_seen": 4.1, "rate_not_seen": 3.0}]
  },
  "reminder_targets": 57,
  "posthog_url": null
}
```

Definitions:
- **eligible**: users matching the audience now. **seen**: ≥ 1 impression in the round. **clicked**: clicked the CTA. **completed**: reached the end (last step for step formats; = clicked for the others). **dismissed**: closed it.
- **dismiss_rate** = dismissed / seen × 100 (1 decimal).
- **steps**: per step, users who saw it / passed it, and `anchor_missing` events (Fleet couldn't find the element).
- **adoption** (only with a `success_event`): rate_seen = users who triggered the event after their first impression ÷ seen; rate_not_seen = eligible users who never saw it and triggered it ÷ (eligible − seen). `series` = last 14 days, one point per day.
- **reminder_targets**: users who saw it, did not adopt, and are still within `max_reminders` (when the reminder is on).
- **posthog_url**: `config('announcements.posthog_dashboard_url')`.

`GET /{id}/history` → `[{id, action, by, at, detail}]`, newest first.

### 5.5 Media and preview

| Method | Path | Body | Returns |
|---|---|---|---|
| POST | `/media` | multipart `file` (jpg/png/webp, ≤ 2 MB) | `{url}` — public URL on the existing storage |
| POST | `/{id}/preview-token` | `{example_vehicle_id?}` | `{token, preview_url, expires_at}` |

Preview: a random token (store hashed, TTL `preview_token_ttl_minutes`, linked to the announcement and the admin). `preview_url` = `config('app.frontend_url')` + the page path (`:id` replaced by the example vehicle; default: the anchor's menu path or `/fleet/dashboard`) + `?announcement_preview=<token>`. Fleet sends the token to 7.3; nothing is recorded during a preview.

### 5.6 Catalog endpoints

| Path | Returns |
|---|---|
| GET `/pages` | `[{key, label, path, needs_vehicle}]` |
| GET `/anchors` | all anchors `[{key, label, page_key}]` (the admin filters by page itself; also accept `?page=` and return that page's anchors + menu entries) |
| GET `/sidebar-paths` | `[{path, label, anchor_key}]` (the menu anchors) |
| GET `/plans`, `/capabilities`, `/permissions`, `/roles`, `/usage-events` | `[{value, label}]` |
| GET `/example-vehicles?search=` | `[{id, numberplate, make_model}]` — vehicles of the demo company (config `ANNOUNCEMENTS_DEMO_COMPANY_ID`), max 20, search on plate (ignore spaces/dashes) and make/model |

### 5.7 Route group (to paste)

```php
// Feature announcements ("Nouveautés"): written, targeted, published and measured by the product team.
Route::prefix('announcements')->middleware('admin.permission:announcements.manage,announcements')->group(function () {
    // Catalogs and tools first (literal segments before /{announcement}).
    Route::get('/pages', [AnnouncementCatalogController::class, 'pages']);
    Route::get('/anchors', [AnnouncementCatalogController::class, 'anchors']);
    Route::get('/sidebar-paths', [AnnouncementCatalogController::class, 'sidebarPaths']);
    Route::get('/plans', [AnnouncementCatalogController::class, 'plans']);
    Route::get('/capabilities', [AnnouncementCatalogController::class, 'capabilities']);
    Route::get('/permissions', [AnnouncementCatalogController::class, 'permissions']);
    Route::get('/roles', [AnnouncementCatalogController::class, 'roles']);
    Route::get('/usage-events', [AnnouncementCatalogController::class, 'usageEvents']);
    Route::get('/example-vehicles', [AnnouncementCatalogController::class, 'exampleVehicles']);
    Route::post('/media', [AnnouncementController::class, 'uploadMedia']);
    Route::post('/audience-count', [AnnouncementAudienceController::class, 'count']);
    Route::post('/eligibility', [AnnouncementAudienceController::class, 'eligibility']);
    Route::post('/overlapping-modals', [AnnouncementAudienceController::class, 'overlappingModals']);

    Route::get('/', [AnnouncementController::class, 'index']);
    Route::post('/', [AnnouncementController::class, 'store']);
    Route::get('/{announcement}', [AnnouncementController::class, 'show'])->whereNumber('announcement');
    Route::put('/{announcement}', [AnnouncementController::class, 'update'])->whereNumber('announcement');
    Route::delete('/{announcement}', [AnnouncementController::class, 'destroy'])->whereNumber('announcement');
    Route::post('/{announcement}/duplicate', [AnnouncementController::class, 'duplicate'])->whereNumber('announcement');
    Route::post('/{announcement}/preview-token', [AnnouncementController::class, 'previewToken'])->whereNumber('announcement');
    Route::get('/{announcement}/stats', [AnnouncementStatsController::class, 'show'])->whereNumber('announcement');
    Route::get('/{announcement}/history', [AnnouncementController::class, 'history'])->whereNumber('announcement');

    Route::middleware('admin.permission:announcements.publish,announcements')->group(function () {
        Route::post('/{announcement}/publish', [AnnouncementController::class, 'publish'])->whereNumber('announcement');
        Route::post('/{announcement}/unpublish', [AnnouncementController::class, 'unpublish'])->whereNumber('announcement');
        Route::post('/{announcement}/archive', [AnnouncementController::class, 'archive'])->whereNumber('announcement');
        Route::post('/{announcement}/reset', [AnnouncementController::class, 'reset'])->whereNumber('announcement');
    });
});
```

---

## 6. Audience engine

### 6.1 Audience JSON

```json
{"plans": ["premium"], "capabilities_required": ["telematics"], "capabilities_missing": [],
 "permissions": ["view_map"], "roles": ["owner", "fleet_manager"],
 "companies_include": [], "companies_exclude": [41],
 "languages": ["fr"], "new_users_only": false, "everyone_confirmed": false}
```

### 6.2 Matching (one function, used everywhere)

A Fleet user matches when **all** of these hold (empty list = no condition):
1. company in `companies_include` (if not empty) and not in `companies_exclude`;
2. the company's plan in `plans`;
3. the company has **every** capability of `capabilities_required` (entitlements, including per-company overrides);
4. the company has **none** of `capabilities_missing` (upsell);
5. the user has **every** permission of `permissions`;
6. the user's role is in `roles`;
7. the user's language is in `languages`;
8. account age (days since `users.created_at`) ≥ `rules.account_age_min_days` and ≤ `rules.account_age_max_days`; `new_users_only` = max 30 days.

Only active Fleet users of active companies count (no test accounts in the count, no deactivated users). Write it as one `AnnouncementAudience::matches(User, Company, array $audience, array $rules)` plus a query version for counts.

### 6.3 Performance

Counting runs while the admin types. Build the count as one SQL query (joins on users, companies, entitlements) rather than looping in PHP, and cache per audience hash for ~60 s.

---

## 7. Fleet API — `/api/v1/fleet/announcements` (current user)

### 7.1 `GET /active`

Returns the announcements the **current user** should get, already filtered and localized, ordered by priority (desc) then `starts_at`:

```json
[{
  "id": 6, "key": "zones-de-georeperage", "round": 1, "format": "tour",
  "title": "Zones de géorepérage", "body": null, "badge_text": "Nouveau",
  "icon": "MapPin", "media_url": null, "media_alt": null,
  "cta_label": null, "cta_path": null,
  "page_key": "car-location", "page_path": "/fleet/car-location",
  "anchor_key": null, "target_sidebar_path": null, "placement": "auto", "widget_corner": "bottom_right",
  "steps": [{"id": "12", "title": "Vos zones sur la carte", "subtitle": null, "body": "Affichez vos zones…",
             "icon": "MapPin", "media_url": null, "media_alt": null,
             "anchor_key": "map-zones-button", "placement": "bottom", "cta_label": null, "cta_path": null}],
  "rules": {"dismissible": true, "hide_after_page_visit": false},
  "state": {"impressions": 0, "step_reached": 0, "dismissed": false, "snoozed_until": null, "completed": false},
  "is_reminder": false
}]
```

Server-side filtering:
- published, inside `starts_at`–`ends_at`, user matches the audience (6.2);
- not dismissed / not completed in the current round, `impressions < max_impressions`, not snoozed;
- `hide_after_page_visit`: hide once Fleet reported a `seen` on the page (Fleet sends `page_visited`, 7.2);
- **max one modal per user per day** (`max_modals_per_user_per_day`): if a modal was already shown today, drop the other modals;
- texts in the user's language with **fallback to FR** when EN is empty;
- reminders (8.2): add the reminder entry with `"is_reminder": true` and the reminder's format.

**Preview:** `GET /active?announcement_preview=<token>` returns only that announcement (even draft, any audience) for the admin who opened the preview, and Fleet records nothing.

### 7.2 `POST /{id}/events`

Body: `{"round": 1, "type": "seen" | "clicked" | "dismissed" | "snoozed" | "step_seen" | "step_completed" | "completed" | "anchor_missing" | "page_visited", "step_id"?: "12", "anchor_key"?: "map-zones-button", "snooze_days"?: 3}`

Updates `announcement_user_states` (impressions, step_reached, timestamps, snoozed_until) and appends to `announcement_events`. Ignore events for another round (the user loaded it before a reset). Idempotent where it makes sense (e.g. `completed` twice = once). Rate-limit per user.

### 7.3 `POST /usage`

Body: `{"event": "geofence_zone_created"}` — Fleet calls it when the user really performs the action. For every announcement whose `success_event` is that event and that the user has seen in the current round, set `adopted_at` and log `adopted` (feeds adoption stats and stops reminders). Prefer, when it exists, a backend-side hook (e.g. on geofence creation) over a front-end ping.

### 7.4 Fleet front-end work (for the Fleet developer, not this ticket)

Replace the hard-coded `featureRegistry.ts` and the `localStorage` state with 7.1–7.3; put `data-announcement-anchor="<key>"` (or keep the existing `data-testid`) on every element of the anchors catalog; add the banner and modal renderers; send `anchor_missing` when a target is not on the page.

---

## 8. Notifications and reminders

### 8.1 Notification at publish

If `notify.enabled` and `notified_at` is null, at the first publish: send `notify.message` (in each user's language, FR fallback) to every matching user through `NotificationCreator::dispatchToUser`, on the chosen channels (`in_app`, `email`), with a link to the announcement's page. Use a new notification type slug `feature_announcement` (seeded like the other types, idempotent migration). Queue it (one job per chunk of users); set `notified_at`; history detail "Notification envoyée à N utilisateurs".

### 8.2 Reminder job

Command `announcements:reminders`, scheduled daily (e.g. `dailyAt('08:15')`): for announcements with `reminder.enabled` and a `success_event`, users who saw it (current round), haven't adopted, `reminders_shown < max_reminders`, and whose last impression/reminder is older than `after_days` → mark a reminder as due (Fleet gets it in 7.1 with `is_reminder: true` in the reminder format; `reminder_seen` increments `reminders_shown`).

---

## 9. Permissions

Seed two internal admin permissions, the same way the existing ones are seeded (they must appear in the internal-roles matrix):
- `announcements.manage` — see the section, create, edit, preview, duplicate, delete drafts;
- `announcements.publish` — publish, unpublish, archive, reset (and thus send the notification).

Until they are seeded the admin falls back to `companies.manage` (front-end only); once seeded, the admin uses them automatically.

---

## 10. Acceptance checklist (manual)

1. `php artisan migrate` runs on MariaDB (local) and MySQL (dev).
2. In the admin with `NEXT_PUBLIC_ANNOUNCEMENTS_MOCK=false`: the list loads; filters by state/format and search work.
3. Create a draft "Info-bulle sur un élément" on "Localisation des véhicules" → "Bouton Zones"; save; reload: everything is kept (FR/EN, steps, audience, rules).
4. Publish with a missing field → 422; the admin highlights the right fields (paths of 4.2).
5. Publish it → status live, round 1; history shows "Publication".
6. Change the key or the number of steps of a published announcement → 422 on `key` / `steps`.
7. "N users match" changes with the audience; "Why isn't it shown?" gives readable reasons.
8. Two modals over the same period and audience → the second shows the overlap warning.
9. In Fleet, a matching user gets it from `/active`, sees it on the map pointing at "Zones"; `seen`, `step_completed`, `completed` events arrive; the admin statistics move.
10. Reset → round 2; the user sees it again; stats have a round selector.
11. Notification at publish arrives in-app (and e-mail if chosen), once.
12. Preview from the admin opens Fleet with the announcement and records nothing.
13. A user without `announcements.publish` can edit but not publish.
