# Vehicle Compliance ("Conformité du Parc") — Audit & Implementation Plan

> Status: **DRAFT — awaiting approval**
> Scope: Super Admin (`dadycar-admin-next`) + shared Laravel backend (`fleetback`)
> Goal: one admin page that lists **every vehicle of every client** that is missing data or documents (CO2, LLD, carte grise, insurance, CT, telematics, driver…), scores it, and lets an admin alert the client.

---

## 0. Summary

| Question | Answer |
|---|---|
| Does the backend already **store** the data? | **Mostly yes.** Vehicle, leasing/loan, documents (CG/CA/CL/CT…), insurance, technical controls, service reminders, assignments, permits, fuel cards and the TAI CO2 rule all exist (seen through the fleet client API). |
| Does the backend already **expose** it to the admin, for all clients? | **No.** `GET /api/admin/vehicles` returns ~12 fields (plate, VIN, make/model, energy, status, telematics, odometer, company, site). Everything else is only on the client API `/api/v1/fleet/*`, which is **scoped to the logged-in company**. |
| What must be built? | A new, **read-only, additive** admin module in the backend (`/api/admin/compliance/*`) that reuses the existing models, plus the admin page. **No existing table, endpoint or behaviour changes.** |
| Order | **Frontend first** (against the API contract in §5, with a mock repository), then **backend**, then integration. |
| Prerequisite for the backend phases | Access to `fleetback` (push it to `Dadycar-organization` on GitHub, or run Claude Code locally on `D:\DadyCar-QA\Fleet\fleetback`). |

---

## 1. Audit

### 1.1 Admin frontend (`dadycar-admin-next`) — what we reuse

Clean layered architecture, followed by every module:

```
src/domain/entities/*.ts              pure types
src/domain/repositories/*.ts          repository interfaces
src/infrastructure/repositories/*.ts  axios implementations (api.get/post… unwrap {status,message,data})
src/di/container.ts                   singleton container → useRepositories()
src/app/(dashboard)/<route>/page.tsx  pages ("use client")
src/presentation/components/<feature> feature components
src/shared/i18n/messages-{fr,en}.ts   typed FR/EN dictionaries
src/shared/constants/index.ts         ROUTES + ROUTE_PERMISSION (sidebar + route guard)
```

Building blocks already available for this page:

| Need | Existing piece |
|---|---|
| Paginated, filterable, sortable table | `ServerDataTable` + `useServerPagination` (page, per_page, order_by, order, search, filters) |
| KPI tiles | `StatsCard` |
| Data fetching / mutations | `useApiQuery`, `useApiMutation` |
| Side panel / dialogs | `Sheet`, `Dialog`, `ConfirmationDialog` |
| Company picker | `SearchableSelect` + `companyRepository` options |
| Badges, progress bar, tabs, tooltips | `StatusBadge`, `Progress`, `Tabs`, `Tooltip` (shadcn) |
| Charts | `recharts` via `ui/chart.tsx` |
| Permission gate | `ROUTE_PERMISSION` + `hasPermission()` |
| Paginated envelope type | `BackendPaginatedData<T>` (`items`, `total`, `current_page`, `last_page`…) |

Admin-side constraints: no tests and no CI exist; lint has 41 pre-existing errors. The new code will be lint-clean and typed, and won't touch existing modules except the four registration points (container, routes, sidebar, i18n).

### 1.2 Backend (`fleetback`) — what exists, seen through its two API surfaces

The backend code isn't reachable from this session. The inventory below comes from the **typed client code** of `fleet-react-app` (calls `/api/v1/fleet/*`) and the admin app (calls `/api/admin/*`). Column and table names marked ⚠ must be confirmed in `fleetback` before backend work starts (task B0).

**Admin API (cross-client) today:** `GET /vehicles` → `id, numberplate, vin, mark, model, motor_type, status, connection_status, has_device, odometer, company, site, provider, created_at`; `GET /vehicles/stats` → `total, connected, not_connected, new_last_30_days`; `/antai/vehicles` (ANTAI state); `/installations` (IMEI, SIM, installer).

**Fleet client API (per company) — data that exists for a vehicle:**

| Domain | Backend data (client API) |
|---|---|
| Vehicle | `numberplate, vin, mark, model, version, type, vehicle_classification, current_vehicle_category, number_of_places, gearbox, fuel_type, crit_air, aen_declaration_type, first_circulation_date, construction_year, park_entry_date, parc_exit_date, purchase_date, purchase_price, vendor_id, site_id, operator_id (driver), odometer, assureur_id, connection_status, device_connection_status, next_technical_control_date, next_maintenance_date, duplicate_keys, transfer_certificate, archived, c1/c3 (registration-card payloads ⚠)` |
| Financing | `leasing { lease_number, renter_id, date_of_lease, lease_end_date, monthly_payment, number_of_payments, contract_km, residual_value, excess_km_charge, documents[] }`, `loan { loan_number, renter_id, … }`, plus computed `km_contractuel, date_fin_contrat, mois_restants, depassement_km` |
| Documents | `/uploadeddocuments` typed **`CG`** Carte grise · **`CJ`** Carte jaune · **`CA`** Contrat assurance · **`CL`** Contrat leasing · **`CT`** Contrôle technique · **`D`** Devis; plus `contract_documents` (with `expiration_date`, `expiration_status: overdue/due_soon/upcoming`) and `financial_documents` (expenses/invoices) via `/vehicles/{id}/documents` |
| Insurance | `/insurance`: `contract_number, start_date, expiration_date, vendor, document` |
| Technical control | `/technicalcontrols`: `date, expiration_date, provider, document` |
| Maintenance | `/servicereminders`: `due_date, meter_interval, status` |
| Driver | `/vehicleassignments` (driver, start/end) · permit documents: `licence_number, categories, expiry_date, status: active/expiring_soon/expired` |
| Cards | `/vehicles/{id}/cards`: `fuel_card`, `toll_badge` |
| Tax (CO2) | TAI report: per vehicle `co2_wltp`, `classification` (`a_completer` when CO2 is null) ⚠ CO2 column source to confirm |

### 1.3 Gap analysis — spec vs backend

| Spec item | Backend | Plan |
|---|---|---|
| Plate, VIN, make/model, type, 1st registration, fleet entry, site, odometer, company | ✅ exists | Rule in v1 |
| CO2 WLTP | ✅ exists (TAI) ⚠ column | Rule in v1, **reuse the TAI rule**, don't duplicate it |
| Crit'Air, energy, benefit-in-kind mode | ✅ exists | v1 |
| Fiscal power (CV) | ⚠ probably in `c1`/registration payload | v1 if found, else B3 |
| Legal owner | ⚠ `leasing.renter_id` (lessor) or the company itself | v1 (derived) |
| Financing mode | ✅ derived: leasing → LLD/LOA, loan → credit, purchase_price → cash, none → **missing** | v1 |
| Leasing fields (contract no., lessor, dates, rent, km limit, duration) | ✅ exists | v1 (only when leasing) |
| Telematics (status, box, provider, IMEI) | ✅ exists | v1 |
| Carte grise, insurance, leasing contract, CT | ✅ `CG`, `CA` / insurance record, `CL` / `leasing.documents`, `CT` / technical control | v1 |
| Insurance valid (not expired) | ✅ `expiration_date` | v1 |
| Driver assigned + valid licence | ✅ assignments + permit status | v1 |
| CT / servicing / contract-end deadlines | ✅ `next_technical_control_date`, `next_maintenance_date`, `lease_end_date` | v1 |
| Fuel card, toll badge, duplicate keys | ✅ exists | v1, severity LOW (informational) |
| Purchase invoice | ⚠ `financial_documents` / expenses | v1 if linkable, else B3 |
| PV de livraison / restitution, pollution check report, sale certificate (Cerfa 15776), accident report | ❌ no document type | **B3**: add new document types (additive enum values) + upload in the fleet app |

### 1.4 Corrections to the agent audit ("Dadycar Demo" account)

1. **Document keys don't match the backend.** The backend stores `CG/CA/CL/CT/CJ/D`, not `carte_grise/assurance/…`. "Sans carte grise: 10/10" is very likely a matching artefact. The dictionary in §3 maps to the real types.
2. **Telematics providers** are LinkByCar, Stellantis and Flespi (not Kuantic/Geotab).
3. **Sample size.** 10 vehicles from one account. Weights in §4 are a starting point, to be validated on all clients after B1 (the "dry run" in phase I1).
4. **CO2** is already classified by the TAI module (`a_completer`). The compliance rule reuses it, so both screens always agree.

### 1.5 Risks

| Risk | Mitigation |
|---|---|
| Computing ~40 rules × 6 relations per vehicle on every list request is too slow across all clients | **Snapshot table** (§5.3) recomputed by a queued job + model events + nightly command. The list reads one indexed table. |
| Alerts are outward-facing (emails to clients) | Preview → explicit confirm; rate limit (1 alert per vehicle per 7 days unless forced); every send stored in `compliance_alerts`; test accounts excluded by default. |
| Backend not accessible | Frontend built against a contract + mock; backend phase starts once access is given. |
| Showing mock data in production | The mock is enabled only by `NEXT_PUBLIC_COMPLIANCE_MOCK=true` and is never set in `.prod.env`; without the backend, the page shows a "module not deployed" state. |

---

## 2. Target architecture

```
                    dadycar-admin-next                                   fleetback (Laravel)
┌──────────────────────────────────────────────┐        ┌─────────────────────────────────────────────────────┐
│ /compliance/vehicles (page)                  │        │ routes: /api/admin/compliance/*  (admin guard +     │
│  ├ KPI row + category cards                  │  HTTP  │          permission)                                │
│  ├ tabs / filters / table                    │ ─────► │ Admin\ComplianceController  (read + alerts)         │
│  ├ vehicle sheet (checklist, docs, deadlines)│        │   └ reads vehicle_compliance_snapshots  (NEW table) │
│  ├ companies tab (ranking, digest)           │        │ Compliance\VehicleComplianceEvaluator (NEW)         │
│  └ alert preview dialog                      │        │   └ rules from config/compliance.php (NEW)          │
│ ComplianceRepository (interface)             │        │   └ reads EXISTING models: Vehicle, leasing, loan,  │
│  ├ ComplianceRepositoryImpl  (axios)         │        │     UploadedDocument, Insurance, TechnicalControl,  │
│  └ ComplianceRepositoryMock  (contract mock) │        │     ServiceReminder, VehicleAssignment, Permit…     │
└──────────────────────────────────────────────┘        │ Jobs: RecomputeVehicleCompliance (queued)           │
                                                        │ Observers on existing models → dispatch job         │
                                                        │ Command compliance:recompute (nightly + manual)     │
                                                        │ Notification VehicleComplianceAlert (mail+database) │
                                                        │ compliance_alerts (NEW table)                       │
                                                        └─────────────────────────────────────────────────────┘
```

Principles: **additive only** (new tables, routes, classes; existing code untouched except registering observers and routes), **one source of truth** (the backend scores; the frontend only displays), **the same rules everywhere** (the alert text is generated from the same "missing" list as the table).

---

## 3. Compliance dictionary (v1 rules)

Severity → weight: **CRITICAL = 3, HIGH = 2, MEDIUM = 1, LOW = 0** (LOW is shown but doesn't affect the score).
"Applies when" = the rule is skipped (not counted) when its condition is false.

| Key | Category | Check (missing when…) | Severity | Applies when | Source |
|---|---|---|---|---|---|
| `identity.numberplate` | identification | empty plate | CRITICAL | always | vehicle |
| `identity.vin` | identification | VIN empty or ≠ 17 chars | CRITICAL | always | vehicle |
| `identity.make_model` | identification | make or model empty | HIGH | always | vehicle |
| `identity.category` | identification | VP/VU/VF category empty | HIGH | always | vehicle ⚠ field |
| `identity.first_registration` | identification | `first_circulation_date` empty | HIGH | always | vehicle |
| `identity.park_entry` | identification | `park_entry_date` empty | MEDIUM | always | vehicle |
| `identity.site` | identification | no site | HIGH | always | vehicle |
| `identity.odometer` | identification | no odometer / older than 90 days | HIGH | always | vehicle / telematics |
| `fiscal.co2` | fiscal | CO2 null (TAI `a_completer`) | CRITICAL | combustion/hybrid (EV = 0 g/km auto) | TAI ⚠ column |
| `fiscal.energy` | fiscal | `fuel_type` empty | CRITICAL | always | vehicle |
| `fiscal.crit_air` | fiscal | `crit_air` empty | HIGH | always | vehicle |
| `fiscal.fiscal_power` | fiscal | fiscal power empty | HIGH | always | ⚠ c1 |
| `fiscal.aen_mode` | fiscal | benefit-in-kind mode empty | MEDIUM | a driver is assigned | vehicle |
| `telematics.connected` | telematics | status ≠ connected | HIGH | always | vehicle |
| `telematics.device` | telematics | no box and no OEM provider | MEDIUM | always | vehicle |
| `finance.mode` | finance | no leasing, no loan, no purchase price | CRITICAL | always | derived |
| `finance.lessor` | finance | `renter_id` empty | HIGH | leasing | leasing |
| `finance.contract_number` | finance | `lease_number` empty | HIGH | leasing | leasing |
| `finance.contract_dates` | finance | start or end date empty | HIGH | leasing | leasing |
| `finance.km_limit` | finance | `contract_km` empty | HIGH | leasing | leasing |
| `finance.monthly_rent` | finance | `monthly_payment` empty | HIGH | leasing | leasing |
| `finance.duration` | finance | `number_of_payments` empty | MEDIUM | leasing | leasing |
| `documents.carte_grise` | documents | no `CG` document | CRITICAL | always | uploaded docs |
| `documents.insurance` | documents | no `CA` doc **and** no insurance record with a file | CRITICAL | always | docs / insurance |
| `documents.insurance_valid` | documents | insurance `expiration_date` < today | CRITICAL | an insurance record exists | insurance |
| `documents.leasing_contract` | documents | no `CL` doc and no `leasing.documents` | HIGH | leasing | docs / leasing |
| `documents.purchase_invoice` | documents | no invoice linked | HIGH | purchase | ⚠ financial docs |
| `documents.technical_control` | documents | no `CT` doc / technical control record | CRITICAL | vehicle age ≥ 4 years | docs / CT |
| `driver.assigned` | driver | no current assignment | HIGH | always (except pool/car-sharing) | assignments |
| `driver.licence` | driver | assigned driver has no permit or it's `expired` | CRITICAL | a driver is assigned | permits |
| `deadline.technical_control` | deadlines | `next_technical_control_date` passed (or empty when ≥ 4 years) | CRITICAL | age ≥ 4 years | vehicle / CT |
| `deadline.maintenance` | deadlines | `next_maintenance_date` passed or no reminder | HIGH | always | vehicle / reminders |
| `deadline.contract_end` | deadlines | `lease_end_date` within 90 days (warning, not missing) | HIGH | leasing | leasing |
| `extras.fuel_card` | extras | no fuel card | LOW | combustion/hybrid | cards |
| `extras.toll_badge` | extras | no toll badge | LOW | always | cards |
| `extras.duplicate_keys` | extras | `duplicate_keys` empty | LOW | always | vehicle |
| `antai.binding` | antai | ANTAI exception open / not bound | HIGH | ANTAI enabled for the company | antai |

Excluded from scoring: archived vehicles, vehicles that have left the fleet (`parc_exit_date` set), `plan_locked` vehicles, and test accounts (shown behind a toggle).

Rules live in `config/compliance.php` (backend) and are served by `GET /compliance/rules`, so labels, severities and filters are never hard-coded twice. B3 adds `documents.delivery_report`, `documents.return_report`, `documents.pollution_check` (VU), `documents.sale_certificate` and `documents.accident_report` after their document types exist.

---

## 4. Scoring

```
score = round(100 × Σ weight(passed applicable rules) / Σ weight(applicable rules))

status:
  critical    → any CRITICAL rule missing, OR score < 60
  incomplete  → no CRITICAL missing and 60 ≤ score < 90   ("À compléter")
  compliant   → no CRITICAL missing and score ≥ 90        ("Conforme")
```

Also stored per vehicle: `missing[]` (rule keys), `warnings[]` (e.g. contract ending in under 90 days), `category_scores{identification, fiscal, telematics, finance, documents, driver, deadlines}`, `next_deadline_at`, `computed_at`.

---

## 5. Backend design (`fleetback`, additive)

> Class and table names follow Laravel conventions; final names will match `fleetback`'s existing style once read (B0).

### 5.1 Endpoints — `routes/api.php`, existing admin group (Sanctum + admin guard)

All responses use the existing envelope `{ status, message, data }`; lists use the existing paginated shape (`items, total, count, per_page, current_page, last_page, …`).

| Method | Path | Purpose | Permission |
|---|---|---|---|
| GET | `/api/admin/compliance/rules` | Rule dictionary (key, category, severity, label FR/EN, applies_when) | `compliance.view` |
| GET | `/api/admin/compliance/stats` | KPIs (filters: `company_id`, `site_id`) | `compliance.view` |
| GET | `/api/admin/compliance/vehicles` | Paginated list | `compliance.view` |
| GET | `/api/admin/compliance/vehicles/{id}` | Full checklist for one vehicle | `compliance.view` |
| GET | `/api/admin/compliance/companies` | Per-client ranking | `compliance.view` |
| GET | `/api/admin/compliance/vehicles/{id}/alert-preview` | Rendered alert (subject, body, recipients) | `compliance.alert` |
| POST | `/api/admin/compliance/vehicles/{id}/alerts` | Send the alert to one vehicle's client | `compliance.alert` |
| GET | `/api/admin/compliance/companies/{id}/alert-preview` | Rendered digest | `compliance.alert` |
| POST | `/api/admin/compliance/companies/{id}/alerts` | Send the digest (all incomplete vehicles) | `compliance.alert` |
| GET | `/api/admin/compliance/alerts` | Alert history (filters: company, vehicle, date) | `compliance.view` |
| POST | `/api/admin/compliance/recompute` | Queue a recompute (all or `company_id`) | `compliance.alert` |

**List query params:** `page, per_page, search` (plate/VIN/company), `company_id, site_id, status` (`critical|incomplete|compliant`), `category`, `missing` (rule key), `severity`, `fuel_type, vehicle_category, score_min, score_max, deadline_within` (days), `include_test` (bool), `order_by` (`score|numberplate|company|next_deadline_at|last_alert_at`), `order`.

**`GET /compliance/stats` → data**
```json
{
  "total_vehicles": 4120,
  "average_score": 71,
  "by_status": { "compliant": 830, "incomplete": 1912, "critical": 1378 },
  "by_category": {
    "identification": { "complete": 3900, "missing": 220 },
    "fiscal":         { "complete": 1700, "missing": 2420 },
    "telematics":     { "complete": 2600, "missing": 1520 },
    "finance":        { "complete": 1450, "missing": 2670 },
    "documents":      { "complete": 600,  "missing": 3520 },
    "driver":         { "complete": 2100, "missing": 2020 },
    "deadlines":      { "complete": 3300, "missing": 820 }
  },
  "by_rule": [ { "key": "fiscal.co2", "missing": 2610 }, { "key": "documents.carte_grise", "missing": 3104 } ],
  "deadlines": { "overdue": 140, "within_30": 95, "within_60": 160, "within_90": 210 },
  "tax_blocked": 2610,
  "alerts": { "sent_30d": 54, "resolved_after_alert_30d": 21 },
  "computed_at": "2026-10-05T03:00:00Z"
}
```

**`GET /compliance/vehicles` → item**
```json
{
  "vehicle_id": 812,
  "numberplate": "GC-673-QN",
  "vin": "VF3…",
  "make_model": "Peugeot 208 II",
  "fuel_type": "Diesel",
  "company": { "id": 41, "name": "Dadycar Demo" },
  "site": { "id": 7, "name": "Paris 15" },
  "score": 64,
  "status": "incomplete",
  "missing": ["fiscal.co2", "documents.carte_grise", "documents.leasing_contract"],
  "missing_count": { "critical": 2, "high": 1, "medium": 0 },
  "warnings": ["deadline.contract_end"],
  "category_scores": { "identification": 100, "fiscal": 50, "telematics": 100, "finance": 83, "documents": 33, "driver": 100, "deadlines": 100 },
  "next_deadline": { "type": "contract_end", "date": "2026-12-01" },
  "last_alert_at": null,
  "computed_at": "2026-10-05T03:00:00Z"
}
```

**`GET /compliance/vehicles/{id}`** = the item above plus `checks[]` (`{ key, category, severity, passed, applicable, value, detail }`), `documents[]` (`{ type, present, file_name, expiration_date, expiration_status }`), `deadlines[]`, `financing { mode, lessor, contract_number, start, end, km_limit, monthly_rent }`, `driver { name, licence_status, licence_expiry }`, `alerts[]` (history), `fleet_url` (`https://myfleet.dadycar.fr/fleet/vehicles/{id}`).

**`GET /compliance/companies` → item**: `{ company, vehicles, average_score, critical, incomplete, compliant, top_missing: [rule keys], last_alert_at }`.

**`POST …/alerts` body**: `{ channels: ["email","in_app"], message_override?: string, force?: bool }` → `{ alert_id, sent_to: [emails], channels }`. Returns `429` with `next_allowed_at` when the 7-day limit applies and `force` isn't set.

### 5.2 Rule evaluation — `app/Services/Compliance/`

- `ComplianceRule` (key, category, severity, `appliesTo(VehicleContext)`, `passes(VehicleContext)`)
- `VehicleContext`: loads a vehicle once with its relations (leasing, loan, uploaded documents grouped by type, latest insurance, latest technical control, reminders, current assignment + permit, cards, ANTAI), avoiding N+1 queries in batch jobs (chunked eager loading)
- `VehicleComplianceEvaluator::evaluate(Vehicle): ComplianceResult`. Pure: no writes, so it's unit-testable.
- `fiscal.co2` **calls the TAI classification service**, so both screens agree.
- Rule metadata (severity, labels FR/EN) in `config/compliance.php`.

### 5.3 New tables (migrations only; no changes to existing tables)

```
vehicle_compliance_snapshots
  id, vehicle_id (unique, FK), company_id (index), site_id (index),
  score tinyint (index), status varchar(12) (index),
  missing json, warnings json, category_scores json,
  critical_missing smallint, high_missing smallint, medium_missing smallint,
  next_deadline_type varchar, next_deadline_at date (index),
  last_alert_at timestamp null, computed_at timestamp, timestamps

compliance_alerts
  id, company_id (index), vehicle_id null (index; null = company digest),
  sent_by_admin_id, channels json, recipients json,
  missing_snapshot json, score_at_send tinyint null,
  subject, body text, sent_at, resolved_at null, timestamps
```

`missing` filtering: a `JSON_CONTAINS` query (MySQL) or a small `vehicle_compliance_missing (snapshot_id, rule_key)` pivot if volume needs it. That's decided in B0 after checking the DB engine and size.

### 5.4 Keeping snapshots fresh

- `RecomputeVehicleCompliance` job (queued, debounced per vehicle)
- Observers (registered, no model changes) on Vehicle, leasing/loan, UploadedDocument, Insurance, TechnicalControl, ServiceReminder, VehicleAssignment, Permit document → dispatch the job for the affected vehicle
- `php artisan compliance:recompute {--company=}` scheduled nightly (the time-based rules — expiries, deadlines — change without any write)
- `resolved_at` on `compliance_alerts` is set when a recompute shows the alerted rules are now passing (this powers "fixed after alert")

### 5.5 Alerts

- `VehicleComplianceAlert` / `CompanyComplianceDigest` notifications, using **the existing mail + database notification channels** of the fleet app, so the client sees them in its notification list
- Recipients: the company's fleet administrator(s) (main company user; site managers optional, decided in B0)
- The FR/EN template from the spec, filled from `missing[]` → rule labels; the link points to `https://myfleet.dadycar.fr/fleet/vehicles/{id}`
- Guards: 7-day limit per vehicle (and per company for digests), test accounts excluded, every send stored
- Permission codes `compliance.view` / `compliance.alert` added through a seeder in the existing internal-permissions system, and assigned to super admin

### 5.6 Backend tests

PHPUnit: unit tests per rule (applies/passes), evaluator scoring/status thresholds, a feature test per endpoint (auth, permission 403, filters, pagination, envelope shape), alert rate limit, and an observer → job dispatch test.

---

## 6. Frontend design (`dadycar-admin-next`)

### 6.1 New files

```
src/domain/entities/compliance.ts                       types matching §5.1 exactly
src/domain/repositories/compliance.repository.ts        interface
src/infrastructure/repositories/compliance.repository.impl.ts   axios (BASE = "/compliance")
src/infrastructure/repositories/compliance.repository.mock.ts   contract mock (realistic dataset)
src/app/(dashboard)/compliance/vehicles/page.tsx        the page
src/presentation/components/compliance/
  compliance-kpis.tsx            headline row + 7 category cards (clickable → filter)
  compliance-filters.tsx         tabs + company/site/energy/category/severity/score filters
  compliance-vehicles-table.tsx  ServerDataTable columns
  compliance-score.tsx           progress bar + % + status badge
  compliance-missing-tags.tsx    severity-coloured tags (+N overflow with tooltip)
  compliance-vehicle-sheet.tsx   side panel: checklist by category, documents ✓/✗, deadline timeline, alert history
  compliance-companies-tab.tsx   per-client ranking + digest action
  compliance-alert-dialog.tsx    preview → confirm → send (vehicle or company)
  compliance-alerts-tab.tsx      alert history
src/shared/constants/compliance.ts                      category order, icons, severity colours
```

### 6.2 Changes to existing files (registration only)

- `src/di/container.ts`: add `complianceRepository` (impl, or mock when `NEXT_PUBLIC_COMPLIANCE_MOCK=true`)
- `src/shared/constants/index.ts`: `ROUTES.complianceVehicles = "/compliance/vehicles"`; `ROUTE_PERMISSION` → `compliance.view` (fallback `admin_vehicles.manage` until B2 seeds the new code)
- `src/presentation/components/layout/admin-layout.tsx`: sidebar item "Conformité du Parc" (`ShieldAlert`), Technical category
- `src/shared/i18n/messages-fr.ts` / `messages-en.ts`: `pages.compliance.*`, `compliance.*` (rule labels fall back to the backend's `/rules` labels)

### 6.3 Page layout

```
Header: "Conformité du Parc" · last computed at … · [Recompute]

[Avg score 71%] [Conformes 830 | À compléter 1 912 | Critiques 1 378 (split bar)] [Taxe bloquée 2 610] [Échéances: 140 overdue · 95 < 30d]

[Identification] [Fiscalité & CO2] [Télématique] [Financement] [Documents] [Conducteur] [Échéances]   ← % complete + missing count, click = filter

Tabs: Véhicules | Entreprises | Alertes envoyées

Véhicules tab:
  Quick filters: Tous · 🚨 Critiques · 💨 Sans CO2 · 📡 Sans télématique · 📄 Documents manquants · 💶 Financement incomplet · ⏰ Échéances
  Filters: Entreprise · Site · Énergie · Catégorie · Gravité · Score min–max · [ ] inclure comptes test · search plate/VIN
  Table: Véhicule (plate, model, VIN) | Entreprise / Site | Score (bar) | Statut | Manques (tags) | Prochaine échéance | Dernière alerte | ⋯ (Voir le détail · Alerter · Ouvrir dans DCar Fleet)

Entreprises tab: ranking by avg score / critical count · top missing items · [Envoyer un récapitulatif]
Alertes tab: history, with resolved after alert ✓
```

States: loading skeletons, empty state, error with retry, "module not deployed" (404 from `/compliance/stats`). Filters live in the URL query, so a filtered view can be shared.

### 6.4 Frontend quality bar

`tsc` clean, **zero new lint errors**, FR/EN complete, keyboard-accessible tags and dialogs, and it works at 1280px and on mobile (the table scrolls horizontally inside its card).

---

## 7. Phased roadmap

| Phase | Deliverable | Repo | Est. | Done when |
|---|---|---|---|---|
| **F1 — Foundation + page on the contract** | Entities, repository interface, axios impl, **mock**, DI, route, sidebar, permission, i18n, KPI row, category cards, tabs, filters, table | admin | 3–4 d | Page fully usable with `NEXT_PUBLIC_COMPLIANCE_MOCK=true`; tsc + lint clean; PR |
| **F2 — Detail & actions UI** | Vehicle sheet, alert preview/send dialog, companies tab, alerts history tab, "module not deployed" state | admin | 2–3 d | All §5.1 calls wired; PR |
| **B0 — Backend discovery** | Read `fleetback`: confirm columns (CO2, fiscal power, category, owner), document storage, notification channels, DB engine, permission seeding; update §3/§5 | backend | 0.5–1 d | Plan v1.1 approved |
| **B1 — Read API** | Rules config, evaluator, snapshot table, job, observers, nightly command, `rules/stats/vehicles/vehicle/companies` endpoints, tests | backend | 4–5 d | Feature tests green; recompute on a prod-sized copy within the agreed time |
| **B2 — Alerts API** | `compliance_alerts`, previews, send (mail + in-app), rate limit, history, `resolved_at`, permission seeder | backend | 2–3 d | A test alert lands in a demo client's mailbox + notification list |
| **I1 — Integration & dry run** | Mock off, staging against real data, compare "Dadycar Demo" with the agent's results, tune weights | both | 1–2 d | Admin + product sign-off |
| **R1 — Release** | Deploy backend (migrations + initial recompute), deploy admin, monitor queue | both | 0.5 d | Live in prod |
| **B3 — Data gaps (follow-up)** | New document types (PV livraison/restitution, pollution check, sale certificate, accident report), upload UI in the fleet app, fiscal power if missing | backend + fleet app | 3–5 d | New rules active |
| **Later** | Score trend chart, CSV export, scheduled weekly digests, carte grise OCR to fill CO2/fiscal power, client-side "complete my fleet" checklist | — | — | — |

Critical path: F1 → F2 can run **while** B0/B1 wait for backend access. Total to production ≈ **3 weeks** of one full-stack developer.

---

## 8. Decisions to approve

1. **Route and name:** `/compliance/vehicles`, sidebar label "Conformité du Parc". ☐
2. **Permissions:** new `compliance.view` + `compliance.alert` (until seeded, `admin_vehicles.manage` gates the page). ☐
3. **Scoring:** weights 3/2/1/0 and thresholds critical < 60 or any CRITICAL missing, compliant ≥ 90. ☐
4. **Snapshot table** + queued recompute (instead of live computation). ☐
5. **Alert channels:** email + in-app, sent to the company's fleet admin, 7-day limit per vehicle. ☐
6. **Excluded by default:** archived / exited / plan-locked vehicles and test accounts. ☐
7. **B3 document types** (PV livraison, etc.) are a follow-up, not v1. ☐
8. **Backend access** for B0: push `fleetback` to GitHub (preferred) or run Claude Code locally. ☐
