SPB Git forge

spb/lou-ka

Public

Lou·Ka — tous les logements à louer du Québec, un seul endroit.

232commits 1branches 0releases
172.9 MBsize
maindefault branch
2 days agolast push
HTML 98.9% Python 0.6%

Stats v2 : dashboard ultra complet + 5 rapports PDF (module Groupe KA v2)

- louka/statsdash.py : jauges de couverture (geo/prix/photos/publiees/completude),
  sparklines KPI, serie des retraits + loyer moyen d entree (area), multi-courbes
  loyer median par taille, barres empilees par source, distribution des loyers,
  heatmap horaire 7x24, calendrier 26 semaines, tables loyers par taille et
  baisses de loyer, records enrichis (villes chere/abordable, hausse, heure de
  pointe) - donnees reelles seulement, cache 5 min conserve
- louka/kapdf.py + frontend/src/ka/stats/* : module canonique v2 (5 modes PDF)
- /api/stats/report : mode=complet|synthese|tendances|repartitions|donnees,
  filename(mode) ; inconnu -> complet (retrocompatible v1)
- pages/Stats.tsx : rendu des nouvelles sections dans l ordre du SPEC v2 +
  PdfButton menu 5 rapports

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Simon-Pierre Boucher committed 1 mo ago (Aug 19, 2026) parent 2f7a2cd

7 changed files +1,757 −306

modified frontend/src/ka/stats/SPEC.md +128 −66
@@ -1,53 +1,88 @@
1 −# ka-stats — module Stats commun Groupe KA (spec v1)
1 +# ka-stats — module Stats commun Groupe KA (spec v2)
2 2
3 −Contrat partagé par les 12 plateformes pour leurs pages **/stats** (tableau de
4 −bord analytique) et l'**export PDF** estampillé Groupe-KA. Le visuel suit le
5 −design system ka-ui (tokens.css) avec l'accent de la marque.
3 +Contrat partagé par les plateformes pour leurs pages **/stats** (tableau de
4 +bord analytique) et les **exports PDF** estampillés Groupe-KA. Le visuel suit
5 +le design system ka-ui (tokens.css) avec l'accent de la marque.
6 +
7 +**v2 (2026-08-19)** : sparklines dans les KPI, jauges, multi-courbes,
8 +barres empilées, distributions (histogrammes), heatmap horaire 7×24, deltas
9 +sur les répartitions, statistiques de séries (min/max/moy/méd/σ), et **5
10 +rapports PDF** au lieu de 2. Tous les nouveaux champs sont **optionnels** :
11 +un dashboard v1 reste valide et se rend tel quel.
6 12
7 13 ## 1. Page /stats — structure obligatoire (dans cet ordre)
8 14
9 −1. **Bandeau KPI** : 4–6 grandes cartes (`KpiCard`) — valeur, libellé,
10 − variation vs période précédente (▲/▼ + %, vert `--green` / rouge `--danger`).
15 +1. **Bandeau KPI** : 6–10 grandes cartes (`KpiCard`) — valeur, libellé,
16 + variation vs période précédente (▲/▼ + %, vert `--green` / rouge
17 + `--danger`), **sparkline** de tendance quand une série existe.
11 18 2. **Sélecteur de période global** (`PeriodSelector`) : `aujourd'hui · 7 j ·
12 19 30 j · 3 m · 6 m · 12 m · année en cours · tout` + plage personnalisée
13 20 (2 champs date). Toute la page se recalcule (state → refetch dashboard).
14 −3. **Graphiques** : courbes d'évolution (`LineChart`, survol = infobulle,
15 − légende cliquable pour masquer une série, comparaison N vs N-1 en
16 − pointillé), barres (`BarChart`), anneaux (`Donut`), calendrier de chaleur
17 − (`CalendarHeatmap`) quand pertinent.
18 −4. **Répartition géographique** (par ville/région) quand pertinent — barres
19 − horizontales triées (pas besoin de vraie carte).
20 −5. **Tableaux détaillés** (`DataTable`) : tri par colonne, recherche interne,
21 +3. **Jauges** (`GaugeCard`) quand pertinent : taux, couvertures, complétude.
22 +4. **Graphiques d'évolution** : courbes/aires (`LineChart`, survol =
23 + infobulle, légende cliquable, comparaison N vs N-1 en pointillé), barres
24 + verticales (`VBarChart` — volumes quotidiens), **multi-courbes ≤ 4 séries**
25 + (`MultiLineChart` — motifs de trait distincts, jamais la couleur seule),
26 + **barres empilées** (`StackedBarChart` — composition dans le temps).
27 + Sous les courbes clés : `StatSummary` (min/max/moyenne/médiane/écart-type).
28 +5. **Répartitions** : barres horizontales (`BarChart`, deltas optionnels),
29 + anneaux (`Donut`), **distributions/histogrammes** (`Histogram`).
30 +6. **Répartition géographique** (par ville/région) — barres horizontales
31 + triées (pas besoin de vraie carte).
32 +7. **Calendriers** : `CalendarHeatmap` (26 semaines) et, quand l'activité
33 + horaire est journalisée, `HourHeatmap` (7 jours × 24 h).
34 +8. **Tableaux détaillés** (`DataTable`) : tri par colonne, recherche interne,
21 35 pagination (25/pg), débordement horizontal propre sur mobile (.tbl-wrap).
22 −6. **Records & faits marquants** : générés depuis les données (jour record,
23 − plus forte croissance, meilleure entrée…) — cartes compactes.
24 −7. **Fraîcheur** : « Mis à jour le {date heure} » + bouton Rafraîchir.
25 −8. **Bouton PDF** bien visible en haut : « Télécharger le rapport PDF » avec
26 − deux choix (Rapport complet / Synthèse 2 pages). Indicateur de progression
27 − si > 2 s.
36 + Viser 3 à 5 tableaux par plateforme.
37 +9. **Records & faits marquants** : générés depuis les données (jour record,
38 + plus forte croissance, meilleure entrée…) — cartes compactes, 6–12.
39 +10. **Fraîcheur** : « Mis à jour le {date heure} » + bouton Rafraîchir.
40 +11. **Bouton PDF** bien visible en haut (`PdfButton`) : bouton principal
41 + « Rapport PDF complet » + menu « Autres rapports ▾ » listant les
42 + **5 rapports** (voir §3). Indicateur de progression si > 2 s.
28 43
29 44 Responsive : KPI empilés < 768 px, graphiques pleine largeur redimensionnés
30 45 (SVG viewBox), tableaux en défilement horizontal contenu, tactile ≥ 44 px.
31 46 AUCUNE donnée inventée : une stat indisponible = bloc « Pas encore mesuré »
32 47 (carte grise propre), jamais un faux chiffre.
33 48
49 +Accessibilité (règles fermes) : un seul axe Y par graphique (jamais de
50 +double échelle) ; ≥ 2 séries ⇒ légende obligatoire ; l'identité d'une série
51 +multi-courbes passe par le **motif de trait** en plus de la couleur ; le
52 +texte reste en encre (jamais coloré à la couleur de série) ; chaque
53 +graphique a son infobulle de survol et un équivalent tableau existe.
54 +
34 55 ## 2. API — contrat commun
35 56
36 57 `GET /api/stats/dashboard?period=7j|30j|3m|6m|12m|annee|tout|auj&from=YYYY-MM-DD&to=YYYY-MM-DD`
37 58
38 59 ```jsonc
39 60 {
40 − "updated": "2026-08-17T21:04:00-04:00",
41 − "period": { "from": "2026-07-18", "to": "2026-08-17", "label": "30 jours" },
61 + "updated": "2026-08-19T01:00:00-04:00",
62 + "period": { "from": "2026-07-20", "to": "2026-08-19", "label": "30 jours" },
42 63 "kpis": [ { "id": "total", "label": "Annonces actives", "value": 33744,
43 − "unit": "", "delta_pct": 4.2, "direction": "up" } ],
64 + "unit": "", "delta_pct": 4.2, "direction": "up",
65 + "spark": [{ "t": "2026-08-01", "v": 31200 }] } ], // spark optionnel
66 + "gauges": [ { "id": "geo", "label": "Fiches géolocalisées", "value": 92,
67 + "max": 100, "unit": "%" } ], // optionnel
44 68 "series": [ { "id": "vol", "title": "Annonces actives par jour", "unit": "annonces",
45 − "kind": "line", "points": [{ "t": "2026-07-18", "v": 31200 }],
46 − "compare": [{ "t": "2025-07-18", "v": 24100 }] } ],
47 − "breakdowns": [ { "id": "types", "title": "Par type", "kind": "donut",
48 − "items": [{ "label": "4½", "value": 9120 }] } ],
69 + "kind": "line", // line | bar | area
70 + "points": [{ "t": "2026-07-20", "v": 31200 }],
71 + "compare": [{ "t": "2025-07-20", "v": 24100 }] } ],
72 + "multiseries": [ { "id": "seg", "title": "Prix médian par taille", "unit": "$",
73 + "series": [ { "label": "3½", "points": [/* … */] },
74 + { "label": "4½", "points": [/* … */] } ] } ], // ≤ 4
75 + "stacked": [ { "id": "src", "title": "Ajouts par source", "unit": "ajouts",
76 + "keys": ["Kijiji", "Centris", "Autres"],
77 + "points": [{ "t": "2026-08-01", "values": [120, 80, 30] }] } ],
78 + "breakdowns": [ { "id": "types", "title": "Par type", "kind": "donut", // donut | bars
79 + "items": [{ "label": "4½", "value": 9120, "delta_pct": 2.1 }] } ],
80 + "distributions": [ { "id": "prix", "title": "Distribution des loyers", "unit": "annonces",
81 + "bins": [{ "label": "800-1000$", "value": 3120 }] } ],
49 82 "geo": { "title": "Par région", "items": [{ "label": "Montréal", "value": 15680 }] },
50 83 "heatmap": { "title": "Activité", "cells": [{ "date": "2026-08-01", "value": 210 }] },
84 + "hourly": { "title": "Activité par heure",
85 + "cells": [{ "dow": 0, "hour": 9, "value": 40 }] }, // dow 0=lun … 6=dim
51 86 "tables": [ { "id": "top", "title": "Top villes", "columns": ["Ville", "Annonces", "Δ 30 j"],
52 87 "rows": [["Montréal", 15680, "+3,1 %"]] } ],
53 88 "records": [ { "label": "Jour record d'ajouts", "value": "412 annonces", "date": "2026-08-09" } ]
@@ -56,23 +91,40 @@ AUCUNE donnée inventée : une stat indisponible = bloc « Pas encore mesuré »
56 91
57 92 Champs absents = section masquée. Cache serveur recommandé (≥ 5 min par
58 93 période). Les valeurs proviennent des données réelles (DB de la plateforme,
59 −journaux de sync des connecteurs, /api/v1/runs d'API-KA…).
94 +journaux de sync des connecteurs, /api/v1/runs d'API-KA…). Arrondir les
95 +`delta_pct` à 1 décimale côté serveur.
60 96
61 −`GET /api/stats/report?period=…&from=&to=&mode=complet|synthese`
97 +## 3. Rapports PDF — 5 modes
98 +
99 +`GET /api/stats/report?period=…&from=&to=&mode=complet|synthese|tendances|repartitions|donnees`
62 100 → `application/pdf`, en-tête `Content-Disposition: attachment; filename=
63 −groupe-ka_<plateforme>_stats_<periode>_<YYYY-MM-DD>.pdf`.
101 +groupe-ka_<plateforme>_stats_<periode>[_<mode>]_<YYYY-MM-DD>.pdf`
102 +(pas de suffixe pour `complet` — rétrocompatible v1 ; `kapdf.filename()`
103 +accepte maintenant `mode` en 3e argument).
104 +
105 +| Mode | Contenu |
106 +|---|---|
107 +| `complet` | tout : sommaire, KPI, jauges, séries + stats de séries, multi-séries, empilées, répartitions, distributions, géo, heatmap horaire, tableaux (200 lignes), records |
108 +| `synthese` | couverture + KPI + jauges + records (2–3 pages) |
109 +| `tendances` | KPI + toutes les séries temporelles + min/max/moy/méd/σ + records |
110 +| `repartitions` | breakdowns, distributions, géo, activité horaire |
111 +| `donnees` | tous les tableaux en version longue (400 lignes) |
64 112
65 −## 3. PDF — gabarit Groupe-KA (implémentations : `kapdf.py` fpdf2 pour les
66 −apps Python ; les apps Next portent le même gabarit en pdfkit)
113 +Un `mode` inconnu retombe sur `complet`. Le gabarit (implémentations :
114 +`kapdf.py` fpdf2 pour les apps Python ; les apps Next portent le même
115 +gabarit en pdfkit) :
67 116
68 117 - **Couverture** : cadre encre, kicker « GROUPE KA · RAPPORT STATISTIQUE »,
69 − wordmark de la plateforme (boîte encre + accent), sous-titre, période
70 − couverte, date/heure de génération, bande encre au pied avec
118 + wordmark de la plateforme (boîte encre + accent), **type de rapport**,
119 + période couverte, date/heure de génération, bande encre au pied avec
71 120 « par Groupe KA — groupe-ka.com ».
72 −- **Sommaire** avec numéros de pages (mode complet).
73 −- **KPI** : grille de cartes (bordure encre, valeur en gros, delta coloré).
121 +- **Sommaire** avec numéros de pages (modes complet et donnees).
122 +- **KPI** : grille de cartes (bordure encre, valeur en gros, delta coloré
123 + arrondi à 1 décimale). **Jauges** : demi-arcs accent.
74 124 - **Graphiques VECTORIELS** (dessinés en primitives, jamais de capture) :
75 − courbes, barres, anneaux — accent de la plateforme, axes/graduations encre.
125 + courbes/aires, barres verticales, multi-courbes (motifs distincts),
126 + empilées (nuances d'accent), anneaux, heatmap horaire — accent de la
127 + plateforme, axes/graduations encre.
76 128 - **Tableaux** paginés proprement (lignes zébrées `--surface-2`, jamais
77 129 coupés en deux à cheval sur une ligne).
78 130 - **Records** puis **page de fin** : coordonnées Groupe KA (3 courriels +
@@ -81,43 +133,53 @@ apps Python ; les apps Next portent le même gabarit en pdfkit)
81 133 - **Chaque page** : en-tête discret (« Groupe KA · {Plateforme} », filet
82 134 encre) + pied (« © Groupe-KA — {année} — groupe-ka.com · {période} · p. X/Y »).
83 135 - A4 portrait, marges 18 mm, typo : Helvetica (fallback sûr) ou fonts TTF du
84 − DS si présentes. Mode « synthese » = couverture + 1 page KPI/records.
136 + DS si présentes.
85 137
86 138 ## 4. Spécifique par plateforme (sections métier attendues)
87 139
88 −- **groupe-ka** : tableau de bord maître — consolidation des 12 (volume total,
89 − croissance), classement des plateformes, bloc résumé par plateforme + lien
140 +- **groupe-ka** : tableau de bord maître — consolidation des plateformes
141 + (volume total, croissance), classement, bloc résumé par plateforme + lien
90 142 vers sa page /stats ; « Rapport écosystème complet » = PDF consolidé.
91 143 - **lou-ka** : annonces actives/nouvelles/retirées, loyers moyens/médians par
92 − ville & taille, évolution, répartition par type, top villes.
93 −- **immo-ka** : annonces actives/nouvelles/vendues-retirées, prix moyen/médian
94 − par ville/région/type, délai de présence, top villes, tension du marché.
144 + ville & taille (multiseries), distribution des loyers, évolution,
145 + répartition par type, top villes, sources (stacked).
146 +- **immo-ka** : annonces actives/nouvelles/vendues-retirées, prix
147 + moyen/médian par ville/région/type (multiseries), distribution des prix,
148 + délai de présence, top villes, tension du marché.
95 149 - **vrai-prix** : couverture du rôle (unités, valeur totale), estimations
96 − servies si journalisées, répartitions par municipalité/type, indices marché.
97 −- **auto-ka** : volume par marque/modèle/année/carburant/boîte, prix moyens et
98 − km moyens par segment, top marques/modèles.
99 −- **fabri-ka** : produits par catégorie/région/boutique, fourchettes de prix,
100 − nouveautés par période, top catégories.
101 −- **food-ka** : produits suivis, relevés de prix, soldes détectés (baisses/
102 − hausses, amplitude), top produits en solde, prix moyens par catégorie.
103 −- **resto-ka** : restos par cuisine/ville/gamme, menus & plats, nouveautés/
104 − fermetures détectées, top établissements.
150 + servies si journalisées, répartitions par municipalité/type, distribution
151 + des valeurs, indices marché.
152 +- **auto-ka** : volume par marque/modèle/année/carburant/boîte, prix moyens
153 + et km moyens par segment (multiseries), distributions prix/km/année,
154 + top marques/modèles.
155 +- **fabri-ka** : produits par catégorie/région/boutique, fourchettes de prix
156 + (distribution), nouveautés par période, top catégories.
157 +- **food-ka** : produits suivis, relevés de prix, soldes détectés
158 + (baisses/hausses, amplitude — stacked), top produits en solde, prix moyens
159 + par catégorie, distribution des rabais.
160 +- **resto-ka** : restos par cuisine/ville/gamme, menus & plats, distribution
161 + des prix de plats, nouveautés/fermetures détectées, top établissements.
105 162 - **sorti-ka** : événements à venir/passés par catégorie/ville, gratuits vs
106 − payants, heatmap calendrier, top lieux.
107 −- **crea-ka** : créateurs par plateforme/niche/tier, comptes reliés, top
108 − créateurs, croissance du répertoire.
109 −- **trouve-ka** : pages indexées, domaines, rythme de crawl (indexées/h),
110 − erreurs, file frontier, tendances si les requêtes sont journalisées.
111 −- **api-ka** : appels par endpoint/jour/heure, latences moyennes + p95, taux
112 − d'erreur, top endpoints, uptime (données des middlewares de logging + runs).
113 −- **Transverse (tous)** : volume total agrégé + croissance, connecteurs actifs
114 − et éléments ajoutés/mis à jour par période (journaux de sync), complétude/
115 − fraîcheur moyenne des fiches quand mesurable. Trafic web : seulement si des
116 − journaux d'accès existent — sinon état vide propre.
163 + payants (stacked), heatmap calendrier + horaire, top lieux.
164 +- **crea-ka** : créateurs par plateforme/niche/tier, comptes reliés
165 + (stacked par plateforme), distribution des audiences, top créateurs,
166 + croissance du répertoire.
167 +- **trouve-ka** : pages indexées, domaines, rythme de crawl (indexées/h —
168 + hourly), erreurs, file frontier, tendances des requêtes journalisées.
169 +- **api-ka** : appels par endpoint/jour/heure (hourly), latences moyennes +
170 + p95 (multiseries), taux d'erreur, top endpoints/clés, uptime.
171 +- **job-ka** : offres actives/nouvelles/expirées par catégorie/ville/
172 + entreprise, distribution des salaires affichés, top employeurs.
173 +- **Transverse (tous)** : volume total agrégé + croissance, connecteurs
174 + actifs et éléments ajoutés/mis à jour par période (journaux de sync —
175 + stacked par source quand possible), complétude/fraîcheur moyenne des
176 + fiches quand mesurable (jauges). Trafic web : seulement si des journaux
177 + d'accès existent — sinon état vide propre.
117 178
118 179 ## 5. Ajouter une métrique / un graphique / une plateforme
119 180
120 −1 métrique = 1 entrée `kpis[]` ou `series[]` côté API (requête SQL agrégée +
121 −cache) — le front la rend automatiquement. 1 plateforme = implémenter les 2
122 −endpoints du contrat + une page /stats montée sur les composants du kit +
123 −`kapdf.py` (ou gabarit pdfkit) branché sur le même JSON de dashboard.
181 +1 métrique = 1 entrée `kpis[]`, `series[]`, `multiseries[]`, `stacked[]`,
182 +`distributions[]` ou `gauges[]` côté API (requête SQL agrégée + cache) — le
183 +front la rend automatiquement. 1 plateforme = implémenter les 2 endpoints du
184 +contrat + une page /stats montée sur les composants du kit + `kapdf.py` (ou
185 +gabarit pdfkit) branché sur le même JSON de dashboard.
modified frontend/src/ka/stats/kacharts.tsx +393 −30
@@ -2,22 +2,39 @@
2 2 // ka-ui/stats/kacharts.tsx — kit de graphiques SVG du module Stats commun
3 3 // Groupe KA (zéro dépendance, React 18+). Style : design system ka-ui
4 4 // (bordures encre, accent de la plateforme via var(--accent)).
5 −// Composants : KpiCard, PeriodSelector, LineChart (infobulle + légende
6 −// cliquable + comparaison N-1), BarChart, Donut, CalendarHeatmap, DataTable
7 −// (tri/recherche/pagination), RecordCard, PdfButton, EmptyBlock, Fraicheur.
8 −import { useMemo, useState } from "react";
5 +// v2 — composants : KpiCard (+sparkline), PeriodSelector, LineChart (ligne/
6 +// aire, infobulle + légende cliquable + comparaison N-1), MultiLineChart
7 +// (≤4 séries, pointillés distincts = jamais la couleur seule), VBarChart
8 +// (barres verticales / histogrammes), StackedBarChart, BarChart (horizontal,
9 +// deltas), Donut, GaugeCard, CalendarHeatmap, HourHeatmap (7×24),
10 +// StatSummary (min/max/moy/méd/σ), DataTable (tri/recherche/pagination),
11 +// RecordCard, PdfButton (menu de rapports), EmptyBlock, Fraicheur.
12 +import { useEffect, useMemo, useRef, useState } from "react";
9 13
10 −/* ---------- types (contrat SPEC.md) ---------- */
14 +/* ---------- types (contrat SPEC.md v2) ---------- */
11 15 export type Kpi = {
12 16 id: string; label: string; value: number | string; unit?: string;
13 17 delta_pct?: number | null; direction?: "up" | "down";
18 + spark?: Point[]; help?: string;
14 19 };
15 20 export type Point = { t: string; v: number };
16 21 export type Serie = {
17 − id: string; title: string; unit?: string; kind?: "line" | "bar";
22 + id: string; title: string; unit?: string;
23 + kind?: "line" | "bar" | "area";
18 24 points: Point[]; compare?: Point[];
19 25 };
20 −export type BreakItem = { label: string; value: number };
26 +export type MultiSerie = {
27 + id: string; title: string; unit?: string;
28 + series: { label: string; points: Point[] }[]; // ≤ 4 séries
29 +};
30 +export type StackedSerie = {
31 + id: string; title: string; unit?: string;
32 + keys: string[]; points: { t: string; values: number[] }[];
33 +};
34 +export type BreakItem = { label: string; value: number; delta_pct?: number | null };
35 +export type Distribution = { id: string; title: string; unit?: string; bins: { label: string; value: number }[] };
36 +export type Gauge = { id: string; label: string; value: number; max: number; unit?: string; help?: string };
37 +export type HourCell = { dow: number; hour: number; value: number }; // dow 0=lun … 6=dim
21 38 export type TableSpec = { id: string; title: string; columns: string[]; rows: (string | number)[][] };
22 39 export type RecordFact = { label: string; value: string; date?: string };
23 40
@@ -32,25 +49,63 @@ export const PERIODS: { id: string; label: string }[] = [
32 49 { id: "tout", label: "Tout" },
33 50 ];
34 51
52 +export const REPORT_MODES: { id: string; label: string; desc: string }[] = [
53 + { id: "complet", label: "Rapport complet", desc: "Toutes les sections — KPI, tendances, répartitions, tableaux, records" },
54 + { id: "synthese", label: "Synthèse exécutive", desc: "2 pages — indicateurs clés et faits marquants" },
55 + { id: "tendances", label: "Tendances & évolution", desc: "Courbes, comparaisons N-1 et statistiques de séries" },
56 + { id: "repartitions", label: "Répartitions & géographie", desc: "Catégories, distributions, régions et activité" },
57 + { id: "donnees", label: "Données détaillées", desc: "Tous les tableaux, en version longue" },
58 +];
59 +
35 60 export const fmtInt = (n: number) => n.toLocaleString("fr-CA");
36 61 export const fmtNum = (n: number) =>
37 62 Number.isInteger(n) ? fmtInt(n) : n.toLocaleString("fr-CA", { maximumFractionDigits: 2 });
63 +const fmtPct = (n: number) => `${n >= 0 ? "+" : ""}${fmtNum(n)} %`;
38 64
39 −/* ---------- KPI ---------- */
65 +/* Styles des séries multiples : couleur + motif de trait (l'identité n'est
66 + jamais portée par la couleur seule — règle d'accessibilité). */
67 +const MULTI_STYLES = [
68 + { stroke: "var(--accent)", dash: undefined, width: 2.4 },
69 + { stroke: "var(--ink)", dash: undefined, width: 1.6 },
70 + { stroke: "var(--accent-deep, var(--accent))", dash: "6 3", width: 2 },
71 + { stroke: "var(--ink-3)", dash: "2 3", width: 2 },
72 +];
73 +
74 +/* ---------- KPI (+ sparkline) ---------- */
40 75 export function KpiCard({ k }: { k: Kpi }) {
41 76 const up = (k.direction ?? ((k.delta_pct ?? 0) >= 0 ? "up" : "down")) === "up";
77 + const sp = (k.spark ?? []).filter((p) => typeof p.v === "number");
78 + const spark = useMemo(() => {
79 + if (sp.length < 2) return null;
80 + const w = 120, h = 30;
81 + const vmax = Math.max(...sp.map((p) => p.v));
82 + const vmin = Math.min(...sp.map((p) => p.v));
83 + const rng = vmax - vmin || 1;
84 + const X = (i: number) => (w * i) / (sp.length - 1);
85 + const Y = (v: number) => 2 + (h - 4) * (1 - (v - vmin) / rng);
86 + const d = sp.map((p, i) => `${i ? "L" : "M"}${X(i).toFixed(1)},${Y(p.v).toFixed(1)}`).join("");
87 + return { w, h, d, area: `${d}L${w},${h}L0,${h}Z` };
88 + }, [k.spark]);
42 89 return (
43 − <article className="card" style={{ padding: "14px 16px", minWidth: 0 }}>
90 + <article className="card" style={{ padding: "14px 16px", minWidth: 0 }} title={k.help}>
44 91 <p style={{ margin: 0, fontFamily: "var(--font-display)", fontWeight: 700, fontSize: "clamp(22px,2.4vw,30px)", letterSpacing: "-0.02em" }}>
45 92 {typeof k.value === "number" ? fmtNum(k.value) : k.value}
46 93 {k.unit ? <span style={{ fontSize: "0.6em", color: "var(--ink-2)" }}> {k.unit}</span> : null}
47 94 </p>
48 95 <p className="klabel" style={{ margin: "6px 0 0" }}>{k.label}</p>
49 − {k.delta_pct !== undefined && k.delta_pct !== null && (
50 − <p style={{ margin: "8px 0 0", fontFamily: "var(--font-mono)", fontSize: 11, fontWeight: 700, color: up ? "var(--green)" : "var(--danger)" }}>
51 − {up ? "▲" : "▼"} {k.delta_pct >= 0 ? "+" : ""}{fmtNum(k.delta_pct)} % <span style={{ color: "var(--ink-3)", fontWeight: 500 }}>vs période préc.</span>
52 − </p>
53 − )}
96 + <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-end", gap: 8 }}>
97 + {k.delta_pct !== undefined && k.delta_pct !== null ? (
98 + <p style={{ margin: "8px 0 0", fontFamily: "var(--font-mono)", fontSize: 11, fontWeight: 700, color: up ? "var(--green)" : "var(--danger)" }}>
99 + {up ? "▲" : "▼"} {fmtPct(k.delta_pct)} <span style={{ color: "var(--ink-3)", fontWeight: 500 }}>vs période préc.</span>
100 + </p>
101 + ) : <span />}
102 + {spark && (
103 + <svg viewBox={`0 0 ${spark.w} ${spark.h}`} style={{ width: 96, height: 24, flex: "none" }} aria-hidden="true">
104 + <path d={spark.area} fill="var(--accent)" opacity={0.14} />
105 + <path d={spark.d} fill="none" stroke="var(--accent)" strokeWidth={1.8} />
106 + </svg>
107 + )}
108 + </div>
54 109 </article>
55 110 );
56 111 }
@@ -84,12 +139,13 @@ export function PeriodSelector({
84 139 );
85 140 }
86 141
87 −/* ---------- Courbe ---------- */
142 +/* ---------- Courbe / aire ---------- */
88 143 export function LineChart({ serie, height = 240 }: { serie: Serie; height?: number }) {
89 144 const [hide, setHide] = useState<{ cur: boolean; cmp: boolean }>({ cur: false, cmp: false });
90 145 const [hover, setHover] = useState<number | null>(null);
91 146 const W = 720, H = height, PL = 54, PR = 10, PT = 14, PB = 26;
92 147 const pts = serie.points ?? [];
148 + if (serie.kind === "bar") return <VBarChart serie={serie} height={height} />;
93 149 if (pts.length < 2) return <EmptyBlock title={serie.title} />;
94 150 const all = [...(hide.cur ? [] : pts), ...(!hide.cmp && serie.compare ? serie.compare : [])];
95 151 const vmax = Math.max(...all.map((p) => p.v), 1);
@@ -127,6 +183,9 @@ export function LineChart({ serie, height = 240 }: { serie: Serie; height?: numb
127 183 {[0, Math.floor(pts.length / 2), pts.length - 1].map((i) => (
128 184 <text key={i} x={X(i, pts.length)} y={H - 8} textAnchor="middle" fontSize={10} fill="var(--ink-3)" fontFamily="var(--font-mono)">{pts[i].t}</text>
129 185 ))}
186 + {serie.kind === "area" && !hide.cur && (
187 + <path d={`${path(pts)}L${X(pts.length - 1, pts.length)},${Y(0)}L${X(0, pts.length)},${Y(0)}Z`} fill="var(--accent)" opacity={0.13} />
188 + )}
130 189 {!hide.cmp && serie.compare && serie.compare.length > 1 && (
131 190 <path d={path(serie.compare)} fill="none" stroke="var(--ink-3)" strokeWidth={1.4} strokeDasharray="4 4" />
132 191 )}
@@ -148,17 +207,211 @@ export function LineChart({ serie, height = 240 }: { serie: Serie; height?: numb
148 207 );
149 208 }
150 209
151 −function LegendChip({ label, color, off, dashed, onClick }: { label: string; color: string; off: boolean; dashed?: boolean; onClick: () => void }) {
210 +function LegendChip({ label, color, off, dashed, onClick }: { label: string; color: string; off?: boolean; dashed?: boolean; onClick?: () => void }) {
152 211 return (
153 − <button type="button" onClick={onClick} aria-pressed={!off}
154 − style={{ display: "inline-flex", alignItems: "center", gap: 6, border: 0, background: "none", cursor: "pointer", opacity: off ? 0.4 : 1, fontFamily: "var(--font-mono)", fontSize: 10.5, fontWeight: 700, textTransform: "uppercase", letterSpacing: "0.06em", minHeight: 44 }}>
212 + <button type="button" onClick={onClick} aria-pressed={!off} disabled={!onClick}
213 + style={{ display: "inline-flex", alignItems: "center", gap: 6, border: 0, background: "none", cursor: onClick ? "pointer" : "default", opacity: off ? 0.4 : 1, fontFamily: "var(--font-mono)", fontSize: 10.5, fontWeight: 700, textTransform: "uppercase", letterSpacing: "0.06em", minHeight: 44 }}>
155 214 <span style={{ width: 18, height: 0, borderTop: `3px ${dashed ? "dashed" : "solid"} ${color}` }} />
156 215 {label}
157 216 </button>
158 217 );
159 218 }
160 219
161 −/* ---------- Barres horizontales (répartitions, géo) ---------- */
220 +/* ---------- Multi-courbes (≤ 4 séries, motifs distincts) ---------- */
221 +export function MultiLineChart({ ms, height = 260 }: { ms: MultiSerie; height?: number }) {
222 + const series = (ms.series ?? []).filter((s) => (s.points ?? []).length > 1).slice(0, 4);
223 + const [off, setOff] = useState<Record<string, boolean>>({});
224 + const [hover, setHover] = useState<number | null>(null);
225 + if (!series.length) return <EmptyBlock title={ms.title} />;
226 + const W = 720, H = height, PL = 54, PR = 10, PT = 14, PB = 26;
227 + const n = Math.max(...series.map((s) => s.points.length));
228 + const shown = series.filter((s) => !off[s.label]);
229 + const all = shown.flatMap((s) => s.points.map((p) => p.v));
230 + const vmax = Math.max(...(all.length ? all : [1]), 1);
231 + const vmin = Math.min(0, ...(all.length ? all : [0]));
232 + const X = (i: number, len: number) => PL + ((W - PL - PR) * i) / (len - 1);
233 + const Y = (v: number) => PT + (H - PT - PB) * (1 - (v - vmin) / (vmax - vmin || 1));
234 + const ref = series[0].points;
235 + const hi = hover !== null ? Math.min(n - 1, Math.max(0, hover)) : null;
236 + return (
237 + <figure className="card" style={{ margin: 0, padding: 16 }}>
238 + <figcaption style={{ display: "flex", justifyContent: "space-between", flexWrap: "wrap", gap: 8 }}>
239 + <b style={{ fontFamily: "var(--font-display)", fontSize: 15 }}>{ms.title}</b>
240 + <span style={{ display: "flex", gap: 10, flexWrap: "wrap" }}>
241 + {series.map((s, i) => (
242 + <LegendChip key={s.label} label={s.label} color={MULTI_STYLES[i].stroke}
243 + dashed={!!MULTI_STYLES[i].dash} off={!!off[s.label]}
244 + onClick={() => setOff((o) => ({ ...o, [s.label]: !o[s.label] }))} />
245 + ))}
246 + </span>
247 + </figcaption>
248 + <svg viewBox={`0 0 ${W} ${H}`} style={{ width: "100%", height: "auto", marginTop: 10, touchAction: "pan-y" }} role="img" aria-label={ms.title}
249 + onMouseMove={(e) => {
250 + const r = (e.currentTarget as SVGSVGElement).getBoundingClientRect();
251 + const fx = ((e.clientX - r.left) / r.width) * W;
252 + setHover(Math.round(((fx - PL) / (W - PL - PR)) * (n - 1)));
253 + }}
254 + onMouseLeave={() => setHover(null)}>
255 + {[0, 1, 2, 3, 4].map((g) => {
256 + const y = PT + ((H - PT - PB) * g) / 4;
257 + const v = vmax - ((vmax - vmin) * g) / 4;
258 + return (
259 + <g key={g}>
260 + <line x1={PL} x2={W - PR} y1={y} y2={y} stroke="var(--line)" strokeWidth={1} />
261 + <text x={PL - 6} y={y + 3} textAnchor="end" fontSize={10} fill="var(--ink-3)" fontFamily="var(--font-mono)">{fmtInt(Math.round(v))}</text>
262 + </g>
263 + );
264 + })}
265 + {[0, Math.floor(ref.length / 2), ref.length - 1].map((i) => (
266 + <text key={i} x={X(i, ref.length)} y={H - 8} textAnchor="middle" fontSize={10} fill="var(--ink-3)" fontFamily="var(--font-mono)">{ref[i]?.t}</text>
267 + ))}
268 + {series.map((s, i) => off[s.label] ? null : (
269 + <path key={s.label}
270 + d={s.points.map((p, j) => `${j ? "L" : "M"}${X(j, s.points.length)},${Y(p.v)}`).join("")}
271 + fill="none" stroke={MULTI_STYLES[i].stroke} strokeWidth={MULTI_STYLES[i].width}
272 + strokeDasharray={MULTI_STYLES[i].dash} />
273 + ))}
274 + {hi !== null && (
275 + <line x1={X(hi, n)} x2={X(hi, n)} y1={PT} y2={H - PB} stroke="var(--ink)" strokeWidth={1} strokeDasharray="2 3" />
276 + )}
277 + </svg>
278 + {hi !== null && (
279 + <p className="chip" style={{ marginTop: 8, display: "inline-flex", gap: 12, flexWrap: "wrap" }}>
280 + <b>{ref[hi]?.t}</b>
281 + {shown.map((s, i) => (
282 + <span key={s.label}>{s.label} : <b>{s.points[hi] ? fmtNum(s.points[hi].v) : "—"}{ms.unit ? ` ${ms.unit}` : ""}</b></span>
283 + ))}
284 + </p>
285 + )}
286 + </figure>
287 + );
288 +}
289 +
290 +/* ---------- Barres verticales (volumes quotidiens, histogrammes) ---------- */
291 +export function VBarChart({ serie, height = 240 }: { serie: Serie; height?: number }) {
292 + const [hover, setHover] = useState<number | null>(null);
293 + const pts = serie.points ?? [];
294 + if (!pts.length) return <EmptyBlock title={serie.title} />;
295 + const W = 720, H = height, PL = 54, PR = 10, PT = 14, PB = 26;
296 + const vmax = Math.max(...pts.map((p) => p.v), 1);
297 + const bw = Math.max(2, (W - PL - PR) / pts.length - 2);
298 + return (
299 + <figure className="card" style={{ margin: 0, padding: 16 }}>
300 + <figcaption><b style={{ fontFamily: "var(--font-display)", fontSize: 15 }}>{serie.title}</b></figcaption>
301 + <svg viewBox={`0 0 ${W} ${H}`} style={{ width: "100%", height: "auto", marginTop: 10 }} role="img" aria-label={serie.title}
302 + onMouseLeave={() => setHover(null)}>
303 + {[0, 1, 2, 3, 4].map((g) => {
304 + const y = PT + ((H - PT - PB) * g) / 4;
305 + const v = vmax - (vmax * g) / 4;
306 + return (
307 + <g key={g}>
308 + <line x1={PL} x2={W - PR} y1={y} y2={y} stroke="var(--line)" strokeWidth={1} />
309 + <text x={PL - 6} y={y + 3} textAnchor="end" fontSize={10} fill="var(--ink-3)" fontFamily="var(--font-mono)">{fmtInt(Math.round(v))}</text>
310 + </g>
311 + );
312 + })}
313 + {pts.map((p, i) => {
314 + const x = PL + ((W - PL - PR) * i) / pts.length;
315 + const h = (H - PT - PB) * (p.v / vmax);
316 + return (
317 + <rect key={i} x={x + 1} y={H - PB - h} width={bw} height={Math.max(h, p.v > 0 ? 1.5 : 0)} rx={2}
318 + fill="var(--accent)" opacity={hover === null || hover === i ? 1 : 0.45}
319 + stroke="var(--ink)" strokeWidth={0.5}
320 + onMouseEnter={() => setHover(i)}>
321 + <title>{`${p.t} — ${fmtNum(p.v)}${serie.unit ? ` ${serie.unit}` : ""}`}</title>
322 + </rect>
323 + );
324 + })}
325 + {[0, Math.floor(pts.length / 2), pts.length - 1].filter((v, i, a) => a.indexOf(v) === i).map((i) => (
326 + <text key={i} x={PL + ((W - PL - PR) * (i + 0.5)) / pts.length} y={H - 8} textAnchor="middle" fontSize={10} fill="var(--ink-3)" fontFamily="var(--font-mono)">{pts[i].t}</text>
327 + ))}
328 + </svg>
329 + {hover !== null && (
330 + <p className="chip" style={{ marginTop: 8 }}>{pts[hover].t} — <b>{fmtNum(pts[hover].v)}{serie.unit ? ` ${serie.unit}` : ""}</b></p>
331 + )}
332 + </figure>
333 + );
334 +}
335 +
336 +/* ---------- Histogramme (distribution) ---------- */
337 +export function Histogram({ dist }: { dist: Distribution }) {
338 + const serie: Serie = {
339 + id: dist.id, title: dist.title, unit: dist.unit, kind: "bar",
340 + points: (dist.bins ?? []).map((b) => ({ t: b.label, v: b.value })),
341 + };
342 + return <VBarChart serie={serie} height={220} />;
343 +}
344 +
345 +/* ---------- Barres empilées (composition dans le temps) ---------- */
346 +export function StackedBarChart({ st, height = 260 }: { st: StackedSerie; height?: number }) {
347 + const [hover, setHover] = useState<number | null>(null);
348 + const keys = (st.keys ?? []).slice(0, 6);
349 + const pts = st.points ?? [];
350 + if (!keys.length || !pts.length) return <EmptyBlock title={st.title} />;
351 + const W = 720, H = height, PL = 54, PR = 10, PT = 14, PB = 26;
352 + const totals = pts.map((p) => p.values.slice(0, keys.length).reduce((s, v) => s + (v || 0), 0));
353 + const vmax = Math.max(...totals, 1);
354 + const bw = Math.max(2, (W - PL - PR) / pts.length - 2);
355 + const shades = [1, 0.72, 0.5, 0.34, 0.22, 0.13];
356 + return (
357 + <figure className="card" style={{ margin: 0, padding: 16 }}>
358 + <figcaption style={{ display: "flex", justifyContent: "space-between", flexWrap: "wrap", gap: 8 }}>
359 + <b style={{ fontFamily: "var(--font-display)", fontSize: 15 }}>{st.title}</b>
360 + <span style={{ display: "flex", gap: 10, flexWrap: "wrap" }}>
361 + {keys.map((k, i) => (
362 + <span key={k} style={{ display: "inline-flex", alignItems: "center", gap: 5, fontFamily: "var(--font-mono)", fontSize: 10.5, fontWeight: 700, textTransform: "uppercase", letterSpacing: "0.06em" }}>
363 + <span style={{ width: 11, height: 11, borderRadius: 3, border: "1px solid var(--ink)", background: "var(--accent)", opacity: shades[i] }} />
364 + {k}
365 + </span>
366 + ))}
367 + </span>
368 + </figcaption>
369 + <svg viewBox={`0 0 ${W} ${H}`} style={{ width: "100%", height: "auto", marginTop: 10 }} role="img" aria-label={st.title}
370 + onMouseLeave={() => setHover(null)}>
371 + {[0, 1, 2, 3, 4].map((g) => {
372 + const y = PT + ((H - PT - PB) * g) / 4;
373 + return (
374 + <g key={g}>
375 + <line x1={PL} x2={W - PR} y1={y} y2={y} stroke="var(--line)" strokeWidth={1} />
376 + <text x={PL - 6} y={y + 3} textAnchor="end" fontSize={10} fill="var(--ink-3)" fontFamily="var(--font-mono)">{fmtInt(Math.round(vmax - (vmax * g) / 4))}</text>
377 + </g>
378 + );
379 + })}
380 + {pts.map((p, i) => {
381 + const x = PL + ((W - PL - PR) * i) / pts.length;
382 + let yAcc = H - PB;
383 + return (
384 + <g key={i} onMouseEnter={() => setHover(i)} opacity={hover === null || hover === i ? 1 : 0.5}>
385 + {keys.map((k, j) => {
386 + const v = p.values[j] || 0;
387 + const h = (H - PT - PB) * (v / vmax);
388 + yAcc -= h;
389 + return v > 0 ? (
390 + <rect key={k} x={x + 1} y={yAcc} width={bw} height={Math.max(h - 1, 0.8)} rx={1.5}
391 + fill="var(--accent)" opacity={shades[j]} stroke="var(--ink)" strokeWidth={0.4}>
392 + <title>{`${p.t} · ${k} — ${fmtNum(v)}${st.unit ? ` ${st.unit}` : ""}`}</title>
393 + </rect>
394 + ) : null;
395 + })}
396 + </g>
397 + );
398 + })}
399 + {[0, Math.floor(pts.length / 2), pts.length - 1].filter((v, i, a) => a.indexOf(v) === i).map((i) => (
400 + <text key={i} x={PL + ((W - PL - PR) * (i + 0.5)) / pts.length} y={H - 8} textAnchor="middle" fontSize={10} fill="var(--ink-3)" fontFamily="var(--font-mono)">{pts[i].t}</text>
401 + ))}
402 + </svg>
403 + {hover !== null && (
404 + <p className="chip" style={{ marginTop: 8, display: "inline-flex", gap: 12, flexWrap: "wrap" }}>
405 + <b>{pts[hover].t}</b>
406 + {keys.map((k, j) => <span key={k}>{k} : <b>{fmtNum(pts[hover].values[j] || 0)}</b></span>)}
407 + <span style={{ color: "var(--ink-3)" }}>total {fmtNum(totals[hover])}</span>
408 + </p>
409 + )}
410 + </figure>
411 + );
412 +}
413 +
414 +/* ---------- Barres horizontales (répartitions, géo) — deltas optionnels ---------- */
162 415 export function BarChart({ title, items, unit }: { title: string; items: BreakItem[]; unit?: string }) {
163 416 const rows = (items ?? []).slice(0, 14);
164 417 if (!rows.length) return <EmptyBlock title={title} />;
@@ -169,9 +422,16 @@ export function BarChart({ title, items, unit }: { title: string; items: BreakIt
169 422 <div style={{ marginTop: 12, display: "grid", gap: 9 }}>
170 423 {rows.map((r) => (
171 424 <div key={r.label} title={`${r.label} — ${fmtNum(r.value)}${unit ? ` ${unit}` : ""}`}>
172 − <div style={{ display: "flex", justifyContent: "space-between", fontSize: 12.5 }}>
425 + <div style={{ display: "flex", justifyContent: "space-between", gap: 8, fontSize: 12.5 }}>
173 426 <span style={{ overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{r.label}</span>
174 − <b style={{ fontFamily: "var(--font-mono)", fontSize: 11.5 }}>{fmtNum(r.value)}{unit ? ` ${unit}` : ""}</b>
427 + <span style={{ display: "inline-flex", gap: 8, alignItems: "baseline", flex: "none" }}>
428 + {r.delta_pct !== undefined && r.delta_pct !== null && (
429 + <span style={{ fontFamily: "var(--font-mono)", fontSize: 10, fontWeight: 700, color: r.delta_pct >= 0 ? "var(--green)" : "var(--danger)" }}>
430 + {r.delta_pct >= 0 ? "▲" : "▼"} {fmtPct(r.delta_pct)}
431 + </span>
432 + )}
433 + <b style={{ fontFamily: "var(--font-mono)", fontSize: 11.5 }}>{fmtNum(r.value)}{unit ? ` ${unit}` : ""}</b>
434 + </span>
175 435 </div>
176 436 <div style={{ marginTop: 3, height: 12, background: "rgba(20,24,20,0.06)", borderRadius: "0 3px 3px 0" }}>
177 437 <div style={{ height: "100%", width: `${Math.max((r.value / max) * 100, 1)}%`, background: "var(--accent)", border: "1px solid var(--ink)", borderRadius: "0 3px 3px 0", boxSizing: "border-box" }} />
@@ -224,6 +484,26 @@ export function Donut({ title, items }: { title: string; items: BreakItem[] }) {
224 484 );
225 485 }
226 486
487 +/* ---------- Jauge (taux, complétude, couverture) ---------- */
488 +export function GaugeCard({ g }: { g: Gauge }) {
489 + const frac = Math.max(0, Math.min(1, g.max ? g.value / g.max : 0));
490 + const R = 60, C = Math.PI * R;
491 + return (
492 + <article className="card" style={{ padding: "14px 16px", minWidth: 0 }} title={g.help}>
493 + <svg viewBox="0 0 150 84" style={{ width: "100%", maxWidth: 190, display: "block", margin: "0 auto" }} role="img" aria-label={`${g.label} : ${fmtNum(g.value)}${g.unit ?? ""} sur ${fmtNum(g.max)}`}>
494 + <path d={`M15,75 A${R},${R} 0 0 1 135,75`} fill="none" stroke="rgba(20,24,20,0.08)" strokeWidth={13} strokeLinecap="round" />
495 + <path d={`M15,75 A${R},${R} 0 0 1 135,75`} fill="none" stroke="var(--accent)" strokeWidth={13} strokeLinecap="round"
496 + strokeDasharray={`${frac * C} ${C}`} />
497 + <text x={75} y={66} textAnchor="middle" fontFamily="var(--font-display)" fontWeight={700} fontSize={22} fill="var(--ink)">
498 + {fmtNum(g.value)}{g.unit ? <tspan fontSize={12} fill="var(--ink-2)"> {g.unit}</tspan> : null}
499 + </text>
500 + <text x={75} y={80} textAnchor="middle" fontSize={9} fill="var(--ink-3)" fontFamily="var(--font-mono)">{(frac * 100).toFixed(0)} % de {fmtNum(g.max)}{g.unit ? ` ${g.unit}` : ""}</text>
501 + </svg>
502 + <p className="klabel" style={{ margin: "8px 0 0", textAlign: "center" }}>{g.label}</p>
503 + </article>
504 + );
505 +}
506 +
227 507 /* ---------- Calendrier de chaleur ---------- */
228 508 export function CalendarHeatmap({ title, cells }: { title: string; cells: { date: string; value: number }[] }) {
229 509 if (!cells?.length) return <EmptyBlock title={title} />;
@@ -261,6 +541,64 @@ export function CalendarHeatmap({ title, cells }: { title: string; cells: { date
261 541 );
262 542 }
263 543
544 +/* ---------- Heatmap horaire 7 × 24 (activité par heure) ---------- */
545 +const DOW = ["Lun", "Mar", "Mer", "Jeu", "Ven", "Sam", "Dim"];
546 +export function HourHeatmap({ title, cells }: { title: string; cells: HourCell[] }) {
547 + if (!cells?.length) return <EmptyBlock title={title} />;
548 + const grid = new Map(cells.map((c) => [`${c.dow}-${c.hour}`, c.value]));
549 + const max = Math.max(...cells.map((c) => c.value), 1);
550 + const CW = 24, CH = 20, LX = 34, LY = 16;
551 + return (
552 + <figure className="card" style={{ margin: 0, padding: 16 }}>
553 + <figcaption><b style={{ fontFamily: "var(--font-display)", fontSize: 15 }}>{title}</b> <span className="klabel">jour × heure</span></figcaption>
554 + <div className="tbl-wrap" style={{ marginTop: 12 }}>
555 + <svg viewBox={`0 0 ${LX + 24 * CW} ${LY + 7 * CH}`} style={{ minWidth: 520, width: "100%", height: "auto" }} role="img" aria-label={title}>
556 + {[0, 6, 12, 18, 23].map((h) => (
557 + <text key={h} x={LX + h * CW + CW / 2} y={11} textAnchor="middle" fontSize={9} fill="var(--ink-3)" fontFamily="var(--font-mono)">{h} h</text>
558 + ))}
559 + {DOW.map((d, i) => (
560 + <text key={d} x={LX - 6} y={LY + i * CH + CH / 2 + 3} textAnchor="end" fontSize={9} fill="var(--ink-3)" fontFamily="var(--font-mono)">{d}</text>
561 + ))}
562 + {Array.from({ length: 7 }, (_, d) => Array.from({ length: 24 }, (_, h) => {
563 + const v = grid.get(`${d}-${h}`) ?? 0;
564 + return (
565 + <rect key={`${d}-${h}`} x={LX + h * CW} y={LY + d * CH} width={CW - 2} height={CH - 2} rx={2.5}
566 + fill={v ? "var(--accent)" : "rgba(20,24,20,0.07)"} fillOpacity={v ? 0.22 + 0.78 * (v / max) : 1}
567 + stroke="rgba(20,24,20,0.15)" strokeWidth={0.5}>
568 + <title>{`${DOW[d]} ${h} h — ${fmtNum(v)}`}</title>
569 + </rect>
570 + );
571 + }))}
572 + </svg>
573 + </div>
574 + </figure>
575 + );
576 +}
577 +
578 +/* ---------- Statistiques de série (min/max/moy/méd/σ) ---------- */
579 +export function StatSummary({ serie }: { serie: Serie }) {
580 + const vs = (serie.points ?? []).map((p) => p.v).filter((v) => typeof v === "number");
581 + if (vs.length < 2) return null;
582 + const sorted = [...vs].sort((a, b) => a - b);
583 + const mean = vs.reduce((s, v) => s + v, 0) / vs.length;
584 + const med = sorted[Math.floor(sorted.length / 2)];
585 + const sd = Math.sqrt(vs.reduce((s, v) => s + (v - mean) ** 2, 0) / vs.length);
586 + const items: [string, number][] = [
587 + ["Min", sorted[0]], ["Max", sorted[sorted.length - 1]],
588 + ["Moyenne", Math.round(mean * 100) / 100], ["Médiane", med],
589 + ["Écart-type", Math.round(sd * 100) / 100],
590 + ];
591 + return (
592 + <div style={{ display: "flex", flexWrap: "wrap", gap: 8, marginTop: 8 }}>
593 + {items.map(([l, v]) => (
594 + <span key={l} className="chip" style={{ fontSize: 11 }}>
595 + <span style={{ color: "var(--ink-3)" }}>{l}</span> <b style={{ fontFamily: "var(--font-mono)" }}>{fmtNum(v)}</b>
596 + </span>
597 + ))}
598 + </div>
599 + );
600 +}
601 +
264 602 /* ---------- Tableau : tri, recherche, pagination ---------- */
265 603 export function DataTable({ spec, pageSize = 25 }: { spec: TableSpec; pageSize?: number }) {
266 604 const [q, setQ] = useState("");
@@ -338,9 +676,19 @@ export function RecordCard({ r }: { r: RecordFact }) {
338 676 );
339 677 }
340 678
341 −/* ---------- Bouton PDF ---------- */
679 +/* ---------- Menu de rapports PDF (5 rapports) ---------- */
342 680 export function PdfButton({ period, from, to, endpoint = "/api/stats/report" }: { period: string; from?: string; to?: string; endpoint?: string }) {
343 − const [busy, setBusy] = useState(false);
681 + const [open, setOpen] = useState(false);
682 + const [busy, setBusy] = useState<string | null>(null);
683 + const box = useRef<HTMLSpanElement>(null);
684 + useEffect(() => {
685 + if (!open) return;
686 + const close = (e: MouseEvent) => {
687 + if (box.current && !box.current.contains(e.target as Node)) setOpen(false);
688 + };
689 + document.addEventListener("mousedown", close);
690 + return () => document.removeEventListener("mousedown", close);
691 + }, [open]);
344 692 const url = (mode: string) => {
345 693 const p = new URLSearchParams({ period, mode });
346 694 if (from) p.set("from", from);
@@ -348,23 +696,38 @@ export function PdfButton({ period, from, to, endpoint = "/api/stats/report" }:
348 696 return `${endpoint}?${p}`;
349 697 };
350 698 const dl = (mode: string) => {
351 − setBusy(true);
699 + setBusy(mode);
700 + setOpen(false);
352 701 const a = document.createElement("a");
353 702 a.href = url(mode);
354 703 a.download = "";
355 704 document.body.appendChild(a);
356 705 a.click();
357 706 a.remove();
358 − setTimeout(() => setBusy(false), 2500);
707 + setTimeout(() => setBusy(null), 3000);
359 708 };
360 709 return (
361 − <span style={{ display: "inline-flex", gap: 8, flexWrap: "wrap" }}>
362 − <button type="button" className="btn btn-primary" onClick={() => dl("complet")} disabled={busy}>
363 − {busy ? "Génération…" : "⬇ Télécharger le rapport PDF"}
710 + <span ref={box} style={{ position: "relative", display: "inline-flex", gap: 8, flexWrap: "wrap" }}>
711 + <button type="button" className="btn btn-primary" onClick={() => dl("complet")} disabled={!!busy}>
712 + {busy ? "Génération…" : "⬇ Rapport PDF complet"}
364 713 </button>
365 − <button type="button" className="btn btn-ghost" onClick={() => dl("synthese")} disabled={busy}>
366 − Synthèse (2 p.)
714 + <button type="button" className="btn btn-ghost" onClick={() => setOpen((o) => !o)} disabled={!!busy}
715 + aria-haspopup="menu" aria-expanded={open}>
716 + Autres rapports ▾
367 717 </button>
718 + {open && (
719 + <div role="menu" className="card" style={{ position: "absolute", top: "calc(100% + 6px)", right: 0, zIndex: 50, minWidth: 300, padding: 6, background: "var(--surface)", boxShadow: "0 10px 28px rgba(20,24,20,0.18)" }}>
720 + {REPORT_MODES.map((m) => (
721 + <button key={m.id} type="button" role="menuitem" onClick={() => dl(m.id)}
722 + style={{ display: "block", width: "100%", textAlign: "left", border: 0, background: "none", cursor: "pointer", padding: "9px 10px", borderRadius: 6 }}
723 + onMouseEnter={(e) => (e.currentTarget.style.background = "var(--surface-2)")}
724 + onMouseLeave={(e) => (e.currentTarget.style.background = "none")}>
725 + <b style={{ display: "block", fontSize: 13, fontFamily: "var(--font-display)" }}>{m.label}</b>
726 + <span className="klabel" style={{ fontSize: 11 }}>{m.desc}</span>
727 + </button>
728 + ))}
729 + </div>
730 + )}
368 731 </span>
369 732 );
370 733 }
modified frontend/src/ka/stats/kapdf.py +390 −71
@@ -1,10 +1,17 @@
1 1 # Auteur : Simon-Pierre Boucher — contact@spboucher.ai
2 −# ka-ui/stats/kapdf.py — moteur PDF commun Groupe KA (fpdf2).
2 +# ka-ui/stats/kapdf.py — moteur PDF commun Groupe KA (fpdf2). v2
3 3 # Consomme le JSON du contrat /api/stats/dashboard (voir SPEC.md) et produit
4 −# le rapport estampillé Groupe-KA : couverture, sommaire, KPI, graphiques
5 −# VECTORIELS (courbes/barres/anneaux), tableaux paginés, records, page de fin.
4 +# les rapports estampillés Groupe-KA. 5 modes :
5 +# complet — toutes les sections (KPI, jauges, séries + stats, multi-
6 +# séries, empilées, distributions, répartitions, géo,
7 +# heatmap horaire, tableaux, records)
8 +# synthese — couverture + KPI + records (2-3 pages)
9 +# tendances — KPI + toutes les séries temporelles + stats de séries
10 +# repartitions — breakdowns, distributions, géo, activité horaire
11 +# donnees — tous les tableaux en version longue (400 lignes max)
12 +# Graphiques VECTORIELS uniquement (primitives fpdf), accent de la marque.
6 13 # Usage :
7 −# from kapdf import GroupeKAReport
14 +# from kapdf import GroupeKAReport, REPORT_MODES, filename
8 15 # pdf_bytes = GroupeKAReport(site={"wordmark":"Lou·Ka","accent":"#ff6a00",
9 16 # "domain":"www.lou-ka.com","tagline":"…"}, dashboard=dash_json,
10 17 # mode="complet").build()
@@ -26,6 +33,14 @@ GREEN = (28, 92, 65)
26 33 DANGER = (179, 66, 58)
27 34 WHITE = (255, 255, 255)
28 35
36 +REPORT_MODES = {
37 + "complet": "Rapport complet",
38 + "synthese": "Synthèse exécutive",
39 + "tendances": "Tendances & évolution",
40 + "repartitions": "Répartitions & géographie",
41 + "donnees": "Données détaillées",
42 +}
43 +
29 44 EMAILS = [
30 45 ("contact@groupe-ka.com", "Projets, partenariats & données"),
31 46 ("info@groupe-ka.com", "Médias & questions générales"),
@@ -52,7 +67,8 @@ def _fr(n) -> str:
52 67 _SUBST = {
53 68 "—": "-", "–": "-", "→": "->", "▲": "+", "▼": "-",
54 69 "…": "...", "’": "'", "‘": "'", "“": '"', "”": '"',
55 − "œ": "oe", "Œ": "OE", "−": "-", " ": " ", " ": " ",
70 + "œ": "oe", "Œ": "OE", "−": "-", " ": " ", " ": " ",
71 + "×": "x", "·": ".", "σ": "sigma", "Δ": "delta",
56 72 }
57 73
58 74
@@ -79,7 +95,7 @@ class _PDF(FPDF):
79 95 self.set_auto_page_break(True, margin=22)
80 96
81 97 def header(self):
82 − if self.cover_mode:
98 + if self.cover_mode or self.page_no() == 1:
83 99 return
84 100 self.set_font("helvetica", "B", 8.5)
85 101 self.set_text_color(*INK)
@@ -95,7 +111,9 @@ class _PDF(FPDF):
95 111 self.set_y(20)
96 112
97 113 def footer(self):
98 − if self.cover_mode:
114 + # page 1 = couverture (le flag cover_mode est déjà retombé quand
115 + # add_page() clôt la page 1 → tester aussi le numéro de page)
116 + if self.cover_mode or self.page_no() == 1:
99 117 return
100 118 self.set_y(-15)
101 119 self.set_draw_color(*INK3)
@@ -112,7 +130,7 @@ class GroupeKAReport:
112 130 def __init__(self, site: dict, dashboard: dict, mode: str = "complet"):
113 131 self.site = site
114 132 self.d = dashboard
115 − self.mode = mode
133 + self.mode = mode if mode in REPORT_MODES else "complet"
116 134 self.accent = _hex(site.get("accent", "#d9f26b"))
117 135 period = dashboard.get("period", {}) or {}
118 136 self.period_label = period.get("label") or "toute la période"
@@ -127,6 +145,11 @@ class GroupeKAReport:
127 145 p.set_fill_color(*fill)
128 146 p.rect(x, y, w, h, style="DF", round_corners=True, corner_radius=2.2)
129 147
148 + def _shade(self, i, n=8):
149 + shades = [1.0, 0.78, 0.58, 0.42, 0.30, 0.22, 0.15, 0.10]
150 + f = shades[i % len(shades)]
151 + return tuple(int(PAPER[j] + (self.accent[j] - PAPER[j]) * f) for j in range(3))
152 +
130 153 def _kicker(self, text):
131 154 p = self.pdf
132 155 p.set_font("helvetica", "B", 8)
@@ -150,6 +173,14 @@ class GroupeKAReport:
150 173 self.toc.append((title, self.pdf.page_no()))
151 174 self.pdf.ln(11)
152 175
176 + def _chart_title(self, title):
177 + p = self.pdf
178 + p.set_font("helvetica", "B", 10)
179 + p.set_text_color(*INK)
180 + p.set_x(p.l_margin)
181 + p.cell(0, 6, title)
182 + p.ln(7)
183 +
153 184 # ---------- pages ----------
154 185 def _cover(self):
155 186 p = self.pdf
@@ -161,12 +192,10 @@ class GroupeKAReport:
161 192 p.set_draw_color(*INK)
162 193 p.set_line_width(1.0)
163 194 p.rect(10, 10, 190, 277)
164 − # kicker
165 195 p.set_font("helvetica", "B", 10)
166 196 p.set_text_color(*GREEN)
167 197 p.set_xy(24, 34)
168 198 p.cell(0, 6, "GROUPE KA · RAPPORT STATISTIQUE")
169 − # wordmark : partie gauche + boîte encre/accent
170 199 wm = self.site.get("wordmark", "")
171 200 left, boxed = (wm.split("·") + [None])[:2] if "·" in wm else (wm, None)
172 201 p.set_xy(24, 70)
@@ -184,7 +213,7 @@ class GroupeKAReport:
184 213 p.set_xy(24, 100)
185 214 p.set_font("helvetica", "", 13)
186 215 p.set_text_color(*INK2)
187 − p.multi_cell(150, 7, f"Rapport statistique — {wm}")
216 + p.multi_cell(150, 7, f"{REPORT_MODES[self.mode]} — {wm}")
188 217 now = datetime.now(ZoneInfo("America/Toronto"))
189 218 per = self.d.get("period", {}) or {}
190 219 p.set_xy(24, 125)
@@ -193,7 +222,7 @@ class GroupeKAReport:
193 222 ("Période couverte", self.period_label + (f" ({per.get('from')} → {per.get('to')})" if per.get("from") else "")),
194 223 ("Généré le", now.strftime("%Y-%m-%d à %H:%M") + " (heure de l'Est)"),
195 224 ("Plateforme", "https://" + self.site.get("domain", "")),
196 − ("Mode", "Rapport complet" if self.mode == "complet" else "Synthèse"),
225 + ("Type de rapport", REPORT_MODES[self.mode]),
197 226 ]
198 227 y = 128
199 228 for k, v in rows:
@@ -205,7 +234,6 @@ class GroupeKAReport:
205 234 p.cell(0, 6, str(v))
206 235 p.set_font("helvetica", "", 10.5)
207 236 y += 8
208 − # bande encre au pied
209 237 p.set_fill_color(*INK)
210 238 p.rect(10, 262, 190, 25, style="F")
211 239 p.set_xy(24, 270)
@@ -230,7 +258,7 @@ class GroupeKAReport:
230 258 p = self.pdf
231 259 cols, gw, gh, gap = 3, 56, 26, 3
232 260 x0, y = p.l_margin, p.get_y()
233 − for i, k in enumerate(kpis[:9]):
261 + for i, k in enumerate(kpis[:12]):
234 262 x = x0 + (i % cols) * (gw + gap)
235 263 if i and i % cols == 0:
236 264 y += gh + gap
@@ -252,20 +280,81 @@ class GroupeKAReport:
252 280 p.set_font("helvetica", "B", 8)
253 281 p.set_text_color(*(GREEN if up else DANGER))
254 282 arrow = "+" if k["delta_pct"] >= 0 else ""
255 − p.cell(gw - 8, 4, f"{'▲' if up else '▼'} {arrow}{str(k['delta_pct']).replace('.', ',')} % vs période préc.")
283 + dv = round(float(k["delta_pct"]), 1)
284 + dv = int(dv) if float(dv).is_integer() else dv
285 + p.cell(gw - 8, 4, f"{'▲' if up else '▼'} {arrow}{str(dv).replace('.', ',')} % vs période préc.")
256 286 p.set_y(y + gh + 8)
257 287
258 − def _line_chart(self, s):
288 + def _gauges(self):
289 + gs = self.d.get("gauges") or []
290 + gs = [g for g in gs if isinstance(g.get("value"), (int, float)) and g.get("max")]
291 + if not gs:
292 + return
293 + self._section_title("Taux & couvertures")
294 + p = self.pdf
295 + cols, gw, gh, gap = 3, 56, 34, 3
296 + x0, y = p.l_margin, p.get_y()
297 + for i, g in enumerate(gs[:9]):
298 + x = x0 + (i % cols) * (gw + gap)
299 + if i and i % cols == 0:
300 + y += gh + gap
301 + if y > 240:
302 + p.add_page(); y = p.get_y()
303 + self._card(x, y, gw, gh)
304 + frac = max(0.0, min(1.0, g["value"] / g["max"]))
305 + cx, cy, r = x + gw / 2, y + 20, 14
306 + # arc de fond + arc de valeur (demi-cercle en petits segments)
307 + for pass_col, pass_frac, lw in (((225, 223, 217), 1.0, 2.6), (self.accent, frac, 2.6)):
308 + p.set_draw_color(*pass_col)
309 + p.set_line_width(lw)
310 + steps = max(2, int(60 * pass_frac))
311 + last = None
312 + for st in range(steps + 1):
313 + a = math.pi + math.pi * pass_frac * st / steps
314 + pt = (cx + r * math.cos(a), cy + r * math.sin(a))
315 + if last:
316 + p.line(last[0], last[1], pt[0], pt[1])
317 + last = pt
318 + p.set_font("helvetica", "B", 11)
319 + p.set_text_color(*INK)
320 + p.set_xy(x + 4, cy - 5)
321 + p.cell(gw - 8, 6, f"{_fr(g['value'])}{' ' + g['unit'] if g.get('unit') else ''}", align="C")
322 + p.set_font("helvetica", "", 6.6)
323 + p.set_text_color(*INK3)
324 + p.set_xy(x + 4, cy + 1.5)
325 + p.cell(gw - 8, 4, f"{frac * 100:.0f} % de {_fr(g['max'])}", align="C")
326 + p.set_xy(x + 3, y + gh - 7)
327 + p.set_font("helvetica", "", 7)
328 + p.set_text_color(*INK2)
329 + p.multi_cell(gw - 6, 3.3, str(g.get("label", ""))[:60], align="C")
330 + p.set_y(y + gh + 8)
331 +
332 + def _serie_stats_row(self, s):
333 + """Ligne min/max/moyenne/médiane sous un graphique de série."""
334 + p = self.pdf
335 + vs = [pt["v"] for pt in (s.get("points") or []) if isinstance(pt.get("v"), (int, float))]
336 + if len(vs) < 2:
337 + return
338 + sv = sorted(vs)
339 + mean = sum(vs) / len(vs)
340 + med = sv[len(sv) // 2]
341 + sd = math.sqrt(sum((v - mean) ** 2 for v in vs) / len(vs))
342 + p.set_font("helvetica", "", 6.8)
343 + p.set_text_color(*INK3)
344 + p.cell(0, 4, f"min {_fr(sv[0])} · max {_fr(sv[-1])} · moyenne {_fr(round(mean, 2))} · médiane {_fr(med)} · écart-type {_fr(round(sd, 2))}")
345 + p.ln(5.5)
346 +
347 + def _line_chart(self, s, with_stats=False):
259 348 p = self.pdf
260 349 pts = s.get("points") or []
261 350 if len(pts) < 2:
262 351 return
352 + if s.get("kind") == "bar":
353 + self._vbars(s)
354 + return
263 355 if p.get_y() > 200:
264 356 p.add_page()
265 − p.set_font("helvetica", "B", 10)
266 − p.set_text_color(*INK)
267 − p.cell(0, 6, s.get("title", ""))
268 − p.ln(7)
357 + self._chart_title(s.get("title", ""))
269 358 x0, y0, w, h = p.l_margin, p.get_y(), 174, 52
270 359 self._card(x0, y0, w, h, fill=WHITE)
271 360 cx, cy, cw, ch = x0 + 12, y0 + 6, w - 20, h - 16
@@ -273,7 +362,6 @@ class GroupeKAReport:
273 362 vmax = max(vals) or 1
274 363 vmin = min(0, min(vals))
275 364 rng = (vmax - vmin) or 1
276 − # grille + graduations
277 365 p.set_font("helvetica", "", 6.3)
278 366 p.set_text_color(*INK3)
279 367 p.set_draw_color(200, 200, 195)
@@ -284,6 +372,20 @@ class GroupeKAReport:
284 372 p.set_xy(x0 + 1, gy - 1.6)
285 373 p.cell(10, 3, _fr(vmin + rng * g / 4), align="R")
286 374
375 + def xy(i, n, v):
376 + return (cx + cw * (i / (n - 1)), cy + ch - ch * ((v - vmin) / rng))
377 +
378 + # aire sous la courbe (kind=area) : petits trapèzes accent pâle
379 + if s.get("kind") == "area":
380 + fill = tuple(int(PAPER[j] + (self.accent[j] - PAPER[j]) * 0.18) for j in range(3))
381 + p.set_fill_color(*fill)
382 + p.set_draw_color(*fill)
383 + n = len(pts)
384 + for i in range(n - 1):
385 + x1, y1 = xy(i, n, pts[i]["v"])
386 + x2, y2 = xy(i + 1, n, pts[i + 1]["v"])
387 + p.polygon([(x1, y1), (x2, y2), (x2, cy + ch), (x1, cy + ch)], style="DF")
388 +
287 389 def draw(series, color, width, dash=None):
288 390 n = len(series)
289 391 p.set_draw_color(*color)
@@ -292,8 +394,7 @@ class GroupeKAReport:
292 394 p.set_dash_pattern(dash=1.2, gap=1.2)
293 395 last = None
294 396 for i, pt in enumerate(series):
295 − px = cx + cw * (i / (n - 1))
296 − py = cy + ch - ch * ((pt["v"] - vmin) / rng)
397 + px, py = xy(i, n, pt["v"])
297 398 if last:
298 399 p.line(last[0], last[1], px, py)
299 400 last = (px, py)
@@ -302,7 +403,6 @@ class GroupeKAReport:
302 403 if s.get("compare"):
303 404 draw(s["compare"], INK3, 0.35, dash=True)
304 405 draw(pts, self.accent, 0.7)
305 − # libellés d'axe X (premier / milieu / dernier)
306 406 p.set_text_color(*INK3)
307 407 for frac, idx in ((0, 0), (0.5, len(pts) // 2), (1, -1)):
308 408 p.set_xy(cx + cw * frac - 9, cy + ch + 1.5)
@@ -312,9 +412,166 @@ class GroupeKAReport:
312 412 p.set_font("helvetica", "", 6.8)
313 413 p.set_text_color(*INK3)
314 414 p.cell(0, 4, "— période courante (accent) · ---- période comparée")
315 − p.ln(6)
316 − else:
317 − p.ln(2)
415 + p.ln(5.5)
416 + if with_stats:
417 + self._serie_stats_row(s)
418 + p.ln(1.5)
419 +
420 + def _vbars(self, s):
421 + """Barres verticales : série kind=bar ou distribution (bins)."""
422 + p = self.pdf
423 + pts = s.get("points") or [{"t": b.get("label"), "v": b.get("value")} for b in (s.get("bins") or [])]
424 + pts = [pt for pt in pts if isinstance(pt.get("v"), (int, float))]
425 + if not pts:
426 + return
427 + if p.get_y() > 205:
428 + p.add_page()
429 + self._chart_title(s.get("title", ""))
430 + x0, y0, w, h = p.l_margin, p.get_y(), 174, 48
431 + self._card(x0, y0, w, h, fill=WHITE)
432 + cx, cy, cw, ch = x0 + 12, y0 + 5, w - 20, h - 14
433 + vmax = max(pt["v"] for pt in pts) or 1
434 + p.set_font("helvetica", "", 6.3)
435 + p.set_text_color(*INK3)
436 + p.set_draw_color(200, 200, 195)
437 + p.set_line_width(0.15)
438 + for g in range(5):
439 + gy = cy + ch - ch * g / 4
440 + p.line(cx, gy, cx + cw, gy)
441 + p.set_xy(x0 + 1, gy - 1.6)
442 + p.cell(10, 3, _fr(vmax * g / 4), align="R")
443 + n = len(pts)
444 + bw = max(0.8, cw / n - 0.6)
445 + p.set_fill_color(*self.accent)
446 + p.set_draw_color(*INK)
447 + p.set_line_width(0.15)
448 + for i, pt in enumerate(pts):
449 + bh = ch * (pt["v"] / vmax)
450 + p.rect(cx + cw * i / n + 0.3, cy + ch - bh, bw, max(bh, 0.4 if pt["v"] > 0 else 0), style="DF")
451 + p.set_text_color(*INK3)
452 + for frac, idx in ((0, 0), (0.5, n // 2), (1, -1)):
453 + p.set_xy(cx + cw * frac - 10, cy + ch + 1.5)
454 + p.cell(20, 3, str(pts[idx].get("t", ""))[:12], align="C")
455 + p.set_y(y0 + h + 5)
456 +
457 + def _multiline(self, ms):
458 + """Multi-séries (≤4) : accent plein / encre fin / accent pointillé /
459 + gris pointillé — l'identité passe par le motif, pas la couleur seule."""
460 + p = self.pdf
461 + series = [s for s in (ms.get("series") or []) if len(s.get("points") or []) > 1][:4]
462 + if not series:
463 + return
464 + if p.get_y() > 195:
465 + p.add_page()
466 + self._chart_title(ms.get("title", ""))
467 + x0, y0, w, h = p.l_margin, p.get_y(), 174, 52
468 + self._card(x0, y0, w, h, fill=WHITE)
469 + cx, cy, cw, ch = x0 + 12, y0 + 6, w - 20, h - 16
470 + vals = [pt["v"] for s in series for pt in s["points"]]
471 + vmax = max(vals) or 1
472 + vmin = min(0, min(vals))
473 + rng = (vmax - vmin) or 1
474 + p.set_font("helvetica", "", 6.3)
475 + p.set_text_color(*INK3)
476 + p.set_draw_color(200, 200, 195)
477 + p.set_line_width(0.15)
478 + for g in range(5):
479 + gy = cy + ch - ch * g / 4
480 + p.line(cx, gy, cx + cw, gy)
481 + p.set_xy(x0 + 1, gy - 1.6)
482 + p.cell(10, 3, _fr(vmin + rng * g / 4), align="R")
483 + styles = [
484 + (self.accent, 0.7, None),
485 + (INK, 0.45, None),
486 + (self.accent, 0.55, True),
487 + (INK3, 0.5, True),
488 + ]
489 + for si, s in enumerate(series):
490 + col, lw, dash = styles[si]
491 + p.set_draw_color(*col)
492 + p.set_line_width(lw)
493 + if dash:
494 + p.set_dash_pattern(dash=1.4, gap=1.2)
495 + n = len(s["points"])
496 + last = None
497 + for i, pt in enumerate(s["points"]):
498 + px = cx + cw * (i / (n - 1))
499 + py = cy + ch - ch * ((pt["v"] - vmin) / rng)
500 + if last:
501 + p.line(last[0], last[1], px, py)
502 + last = (px, py)
503 + p.set_dash_pattern()
504 + ref = series[0]["points"]
505 + p.set_text_color(*INK3)
506 + for frac, idx in ((0, 0), (0.5, len(ref) // 2), (1, -1)):
507 + p.set_xy(cx + cw * frac - 9, cy + ch + 1.5)
508 + p.cell(18, 3, str(ref[idx].get("t", ""))[:10], align="C")
509 + p.set_y(y0 + h + 4)
510 + p.set_font("helvetica", "", 6.8)
511 + p.set_text_color(*INK3)
512 + marks = ["—", "—", "----", "----"]
513 + leg = " · ".join(f"{marks[i]} {s.get('label', '')}" for i, s in enumerate(series))
514 + p.cell(0, 4, leg[:120])
515 + p.ln(6)
516 +
517 + def _stacked(self, st):
518 + p = self.pdf
519 + keys = (st.get("keys") or [])[:6]
520 + pts = st.get("points") or []
521 + if not keys or not pts:
522 + return
523 + if p.get_y() > 195:
524 + p.add_page()
525 + self._chart_title(st.get("title", ""))
526 + x0, y0, w, h = p.l_margin, p.get_y(), 174, 52
527 + self._card(x0, y0, w, h, fill=WHITE)
528 + cx, cy, cw, ch = x0 + 12, y0 + 6, w - 20, h - 16
529 + totals = [sum(v or 0 for v in pt.get("values", [])[: len(keys)]) for pt in pts]
530 + vmax = max(totals) or 1
531 + p.set_font("helvetica", "", 6.3)
532 + p.set_text_color(*INK3)
533 + p.set_draw_color(200, 200, 195)
534 + p.set_line_width(0.15)
535 + for g in range(5):
536 + gy = cy + ch - ch * g / 4
537 + p.line(cx, gy, cx + cw, gy)
538 + p.set_xy(x0 + 1, gy - 1.6)
539 + p.cell(10, 3, _fr(vmax * g / 4), align="R")
540 + n = len(pts)
541 + bw = max(0.8, cw / n - 0.6)
542 + p.set_draw_color(*WHITE)
543 + p.set_line_width(0.12)
544 + for i, pt in enumerate(pts):
545 + yacc = cy + ch
546 + for j, k in enumerate(keys):
547 + v = (pt.get("values") or [0] * len(keys))[j] if j < len(pt.get("values", [])) else 0
548 + if not v:
549 + continue
550 + bh = ch * (v / vmax)
551 + yacc -= bh
552 + p.set_fill_color(*self._shade(j))
553 + p.rect(cx + cw * i / n + 0.3, yacc, bw, max(bh - 0.15, 0.3), style="DF")
554 + p.set_text_color(*INK3)
555 + for frac, idx in ((0, 0), (0.5, n // 2), (1, -1)):
556 + p.set_xy(cx + cw * frac - 10, cy + ch + 1.5)
557 + p.cell(20, 3, str(pts[idx].get("t", ""))[:12], align="C")
558 + p.set_y(y0 + h + 4)
559 + # légende
560 + p.set_font("helvetica", "", 6.8)
561 + lx = p.l_margin
562 + for j, k in enumerate(keys):
563 + p.set_fill_color(*self._shade(j))
564 + p.set_draw_color(*INK)
565 + p.set_line_width(0.2)
566 + p.rect(lx, p.get_y() + 0.6, 3, 3, style="DF")
567 + p.set_xy(lx + 4, p.get_y())
568 + p.set_text_color(*INK2)
569 + txt = str(k)[:22]
570 + p.cell(p.get_string_width(txt) + 3, 4, txt)
571 + lx = p.get_x() + 3
572 + if lx > 165:
573 + break
574 + p.ln(7)
318 575
319 576 def _bars(self, title, items, unit=""):
320 577 p = self.pdf
@@ -324,10 +581,8 @@ class GroupeKAReport:
324 581 need = 10 + len(items) * 7
325 582 if p.get_y() + need > 265:
326 583 p.add_page()
327 − p.set_font("helvetica", "B", 10)
328 − p.set_text_color(*INK)
329 − p.cell(0, 6, title)
330 − p.ln(8)
584 + self._chart_title(title)
585 + p.ln(1)
331 586 vmax = max(it["value"] for it in items) or 1
332 587 for it in items:
333 588 y = p.get_y()
@@ -335,19 +590,23 @@ class GroupeKAReport:
335 590 p.set_text_color(*INK)
336 591 p.set_x(p.l_margin)
337 592 p.cell(46, 5, str(it["label"])[:34])
338 − bw = 96 * (it["value"] / vmax)
593 + bw = 86 * (it["value"] / vmax)
339 594 p.set_fill_color(*self.accent)
340 595 p.set_draw_color(*INK)
341 596 p.set_line_width(0.25)
342 597 p.rect(p.l_margin + 48, y + 0.7, max(bw, 0.8), 3.6, style="DF")
343 − p.set_xy(p.l_margin + 148, y)
598 + p.set_xy(p.l_margin + 136, y)
344 599 p.set_font("helvetica", "B", 7.6)
345 − p.cell(26, 5, _fr(it["value"]) + (" " + unit if unit else ""), align="R")
600 + p.cell(24, 5, _fr(it["value"]) + (" " + unit if unit else ""), align="R")
601 + if it.get("delta_pct") is not None:
602 + up = it["delta_pct"] >= 0
603 + p.set_font("helvetica", "B", 6.6)
604 + p.set_text_color(*(GREEN if up else DANGER))
605 + p.cell(14, 5, f"{'+' if up else ''}{str(round(it['delta_pct'], 1)).replace('.', ',')} %", align="R")
346 606 p.ln(6.4)
347 607 p.ln(3)
348 608
349 609 def _donut(self, b):
350 − # anneau vectoriel simple (arcs) + légende
351 610 p = self.pdf
352 611 items = [it for it in (b.get("items") or []) if it.get("value")][:8]
353 612 total = sum(it["value"] for it in items)
@@ -355,17 +614,13 @@ class GroupeKAReport:
355 614 return
356 615 if p.get_y() > 210:
357 616 p.add_page()
358 − p.set_font("helvetica", "B", 10)
359 − p.set_text_color(*INK)
360 − p.cell(0, 6, b.get("title", ""))
361 − p.ln(8)
617 + self._chart_title(b.get("title", ""))
618 + p.ln(1)
362 619 cx, cy, r = p.l_margin + 26, p.get_y() + 24, 20
363 − shades = [1.0, 0.78, 0.58, 0.42, 0.30, 0.22, 0.15, 0.10]
364 620 start = -90.0
365 621 for i, it in enumerate(items):
366 622 frac = it["value"] / total
367 − f = shades[i % len(shades)]
368 − col = tuple(int(PAPER[j] + (self.accent[j] - PAPER[j]) * f) for j in range(3))
623 + col = self._shade(i)
369 624 steps = max(2, int(72 * frac))
370 625 p.set_fill_color(*col)
371 626 p.set_draw_color(*col)
@@ -384,11 +639,9 @@ class GroupeKAReport:
384 639 p.set_line_width(0.4)
385 640 p.ellipse(cx - 11, cy - 11, 22, 22, style="DF")
386 641 p.ellipse(cx - r, cy - r, 2 * r, 2 * r, style="D")
387 − # légende
388 642 ly = cy - 22
389 643 for i, it in enumerate(items):
390 − f = shades[i % len(shades)]
391 − col = tuple(int(PAPER[j] + (self.accent[j] - PAPER[j]) * f) for j in range(3))
644 + col = self._shade(i)
392 645 p.set_fill_color(*col)
393 646 p.set_draw_color(*INK)
394 647 p.rect(p.l_margin + 60, ly + 0.8, 4, 4, style="DF")
@@ -400,7 +653,39 @@ class GroupeKAReport:
400 653 ly += 5.6
401 654 p.set_y(max(cy + r, ly) + 6)
402 655
403 − def _table(self, t):
656 + def _hourly(self):
657 + hh = self.d.get("hourly") or {}
658 + cells = hh.get("cells") or []
659 + if not cells:
660 + return
661 + p = self.pdf
662 + if p.get_y() > 190:
663 + p.add_page()
664 + self._chart_title(hh.get("title", "Activité par jour et heure"))
665 + x0, y0 = p.l_margin, p.get_y()
666 + cw, chh, lx, ly = 6.4, 6.4, 12, 5
667 + vmax = max((c.get("value") or 0) for c in cells) or 1
668 + grid = {(c.get("dow"), c.get("hour")): c.get("value") or 0 for c in cells}
669 + dows = ["Lun", "Mar", "Mer", "Jeu", "Ven", "Sam", "Dim"]
670 + p.set_font("helvetica", "", 5.8)
671 + p.set_text_color(*INK3)
672 + for h in (0, 6, 12, 18, 23):
673 + p.set_xy(x0 + lx + h * cw, y0)
674 + p.cell(cw, 3, f"{h}h", align="C")
675 + for d in range(7):
676 + p.set_xy(x0, y0 + ly + d * chh + 1.5)
677 + p.cell(lx - 1, 3, dows[d], align="R")
678 + for h in range(24):
679 + v = grid.get((d, h), 0)
680 + f = 0.1 + 0.9 * (v / vmax) if v else 0.0
681 + col = tuple(int(PAPER[j] + (self.accent[j] - PAPER[j]) * f) for j in range(3)) if v else (235, 233, 228)
682 + p.set_fill_color(*col)
683 + p.set_draw_color(215, 213, 207)
684 + p.set_line_width(0.1)
685 + p.rect(x0 + lx + h * cw, y0 + ly + d * chh, cw - 0.5, chh - 0.5, style="DF")
686 + p.set_y(y0 + ly + 7 * chh + 5)
687 +
688 + def _table(self, t, max_rows=200):
404 689 p = self.pdf
405 690 cols = t.get("columns") or []
406 691 rows = t.get("rows") or []
@@ -417,7 +702,7 @@ class GroupeKAReport:
417 702 p.ln(6)
418 703 head()
419 704 p.set_text_color(*INK)
420 − for i, row in enumerate(rows[:200]):
705 + for i, row in enumerate(rows[:max_rows]):
421 706 if p.get_y() > 262:
422 707 p.add_page()
423 708 head()
@@ -428,10 +713,10 @@ class GroupeKAReport:
428 713 txt = _fr(cell) if isinstance(cell, (int, float)) else str(cell)
429 714 p.cell(w, 5.4, " " + txt[:34], fill=True)
430 715 p.ln(5.4)
431 − if len(rows) > 200:
716 + if len(rows) > max_rows:
432 717 p.set_font("helvetica", "", 7)
433 718 p.set_text_color(*INK3)
434 − p.cell(0, 5, f"… {len(rows) - 200} lignes supplémentaires non imprimées")
719 + p.cell(0, 5, f"… {len(rows) - max_rows} lignes supplémentaires non imprimées")
435 720 p.ln(6)
436 721
437 722 def _records(self):
@@ -440,7 +725,7 @@ class GroupeKAReport:
440 725 return
441 726 self._section_title("Records & faits marquants")
442 727 p = self.pdf
443 − for r in recs[:10]:
728 + for r in recs[:14]:
444 729 if p.get_y() > 258:
445 730 p.add_page()
446 731 y = p.get_y()
@@ -498,43 +783,76 @@ class GroupeKAReport:
498 783 "groupe-ka.com/conditions · /confidentialite · /loi-25.",
499 784 )
500 785
501 − def _toc_page(self):
502 − # insérée après coup ? fpdf ne réordonne pas : on écrit le sommaire en
503 − # page 2 en réservant la page lors du build (voir build()).
504 − pass
786 + # ---------- groupes de sections ----------
787 + def _all_series(self, with_stats=True):
788 + for s in self.d.get("series") or []:
789 + self._line_chart(s, with_stats=with_stats)
790 + for ms in self.d.get("multiseries") or []:
791 + self._multiline(ms)
792 + for st in self.d.get("stacked") or []:
793 + self._stacked(st)
794 +
795 + def _all_breakdowns(self):
796 + for b in self.d.get("breakdowns") or []:
797 + if b.get("kind") == "donut":
798 + self._donut(b)
799 + else:
800 + self._bars(b.get("title", ""), b.get("items"))
801 + for dist in self.d.get("distributions") or []:
802 + self._vbars(dist)
803 + geo = self.d.get("geo")
804 + if geo:
805 + self._bars(geo.get("title", "Répartition géographique"), geo.get("items"))
806 + self._hourly()
505 807
506 808 def build(self) -> bytes:
507 809 p = self.pdf
508 810 p.alias_nb_pages()
509 811 self._cover()
812 + with_toc = self.mode in ("complet", "donnees")
813 + toc_page_no = None
510 814 if self.mode == "synthese":
511 815 p.add_page()
512 816 self._kpis()
817 + self._gauges()
818 + self._records()
819 + self._final_page()
820 + elif self.mode == "tendances":
821 + p.add_page()
822 + self._kpis()
823 + self._section_title("Évolution & tendances")
824 + self._all_series(with_stats=True)
513 825 self._records()
514 826 self._final_page()
515 − else:
827 + elif self.mode == "repartitions":
828 + p.add_page()
829 + self._section_title("Répartitions, distributions & géographie")
830 + self._all_breakdowns()
831 + self._final_page()
832 + elif self.mode == "donnees":
833 + p.add_page()
834 + toc_page_no = p.page_no()
835 + for t in self.d.get("tables") or []:
836 + self._table(t, max_rows=400)
837 + self._final_page()
838 + else: # complet
516 839 p.add_page()
517 840 toc_page_no = p.page_no()
518 841 p.add_page()
519 842 self._kpis()
520 − for s in self.d.get("series") or []:
521 − if s.get("kind") == "bar":
522 − self._bars(s.get("title", ""), [{"label": pt.get("t"), "value": pt.get("v")} for pt in (s.get("points") or [])], s.get("unit", ""))
523 − else:
524 − self._line_chart(s)
525 − for b in self.d.get("breakdowns") or []:
526 − if b.get("kind") == "donut":
527 − self._donut(b)
528 − else:
529 − self._bars(b.get("title", ""), b.get("items"))
530 − geo = self.d.get("geo")
531 − if geo:
532 − self._bars(geo.get("title", "Répartition géographique"), geo.get("items"))
843 + self._gauges()
844 + if (self.d.get("series") or self.d.get("multiseries") or self.d.get("stacked")):
845 + self._section_title("Évolution & tendances")
846 + self._all_series(with_stats=True)
847 + if (self.d.get("breakdowns") or self.d.get("distributions") or self.d.get("geo") or self.d.get("hourly")):
848 + self._section_title("Répartitions, distributions & géographie")
849 + self._all_breakdowns()
533 850 for t in self.d.get("tables") or []:
534 851 self._table(t)
535 852 self._records()
536 853 self._final_page()
537 − # sommaire écrit sur la page réservée (page 2)
854 + # sommaire écrit sur la page réservée
855 + if toc_page_no is not None:
538 856 last_page = p.page
539 857 p.page = toc_page_no
540 858 p.set_y(22)
@@ -553,6 +871,7 @@ class GroupeKAReport:
553 871 return bytes(p.output())
554 872
555 873
556 −def filename(platform_id: str, period: str) -> str:
874 +def filename(platform_id: str, period: str, mode: str = "complet") -> str:
557 875 today = datetime.now(ZoneInfo("America/Toronto")).strftime("%Y-%m-%d")
558 − return f"groupe-ka_{platform_id}_stats_{period}_{today}.pdf"
876 + suffix = "" if mode in ("", "complet") else f"_{mode}"
877 + return f"groupe-ka_{platform_id}_stats_{period}{suffix}_{today}.pdf"
modified frontend/src/pages/Stats.tsx +43 −12
@@ -2,25 +2,34 @@
2 2 // Lou-Ka — Agrégateur de logements à louer (province de Québec)
3 3 // Auteur : Simon-Pierre Boucher — contact@spboucher.ai
4 4 // pages/Stats.tsx : tableau de bord analytique — module Stats commun Groupe KA
5 −// (contrat ../ka/stats/SPEC.md, composants ../ka/stats/kacharts.tsx).
6 −// KPI + sélecteur de période + courbes (comparaison N-1) + répartitions +
7 −// géographie + calendrier de chaleur + tableaux + records + export PDF.
5 +// v2 (contrat ../ka/stats/SPEC.md, composants ../ka/stats/kacharts.tsx).
6 +// KPI + sparklines + jauges + sélecteur de période + courbes (compare N-1,
7 +// stats de séries) + multi-courbes + barres empilées + répartitions +
8 +// distributions + géographie + calendrier & heatmap horaire + tableaux +
9 +// records + export PDF (5 rapports).
8 10 // -----------------------------------------------------------------------------
9 11 import { useCallback, useEffect, useState } from "react";
10 12 import {
11 − BarChart, BreakItem, CalendarHeatmap, DataTable, Donut, EmptyBlock,
12 − Fraicheur, Kpi, KpiCard, LineChart, PdfButton, PeriodSelector, RecordCard,
13 − RecordFact, Serie, TableSpec,
13 + BarChart, BreakItem, CalendarHeatmap, DataTable, Distribution, Donut,
14 + EmptyBlock, Fraicheur, Gauge, GaugeCard, Histogram, HourCell, HourHeatmap,
15 + Kpi, KpiCard, LineChart, MultiLineChart, MultiSerie, PdfButton,
16 + PeriodSelector, RecordCard, RecordFact, Serie, StackedBarChart,
17 + StackedSerie, StatSummary, TableSpec,
14 18 } from "../ka/stats/kacharts";
15 19
16 20 interface Dashboard {
17 21 updated: string;
18 22 period: { from: string | null; to: string | null; label: string };
19 23 kpis: Kpi[];
24 + gauges?: Gauge[];
20 25 series: Serie[];
26 + multiseries?: MultiSerie[];
27 + stacked?: StackedSerie[];
21 28 breakdowns: { id: string; title: string; kind?: string; items: BreakItem[] }[];
29 + distributions?: Distribution[];
22 30 geo?: { title: string; items: BreakItem[] };
23 31 heatmap?: { title: string; cells: { date: string; value: number }[] };
32 + hourly?: { title: string; cells: HourCell[] };
24 33 tables: TableSpec[];
25 34 records: RecordFact[];
26 35 }
@@ -62,7 +71,7 @@ export default function StatsPage() {
62 71
63 72 return (
64 73 <div className="container" style={{ display: "grid", gap: 18, paddingBottom: 40 }}>
65 − {/* --- en-tête : titre + PDF + fraîcheur ------------------------------ */}
74 + {/* --- en-tête : titre + PDF (5 rapports) + fraîcheur ------------------ */}
66 75 <header style={{ display: "flex", flexWrap: "wrap", gap: 14, alignItems: "flex-end", justifyContent: "space-between", marginTop: 8 }}>
67 76 <div style={{ minWidth: 0 }}>
68 77 <p className="klabel" style={{ margin: 0 }}>Groupe KA · Lou·Ka</p>
@@ -90,7 +99,7 @@ export default function StatsPage() {
90 99 </div>
91 100 )}
92 101
93 − {/* --- bandeau KPI ----------------------------------------------------- */}
102 + {/* --- bandeau KPI (sparklines) ---------------------------------------- */}
94 103 {dash && dash.kpis.length > 0 && (
95 104 <section aria-label="Indicateurs clés" style={{ display: "grid", gap: 12, gridTemplateColumns: "repeat(auto-fit, minmax(170px, 1fr))", opacity: loading ? 0.55 : 1, transition: "opacity .2s" }}>
96 105 {dash.kpis.map((k) => <KpiCard key={k.id} k={k} />)}
@@ -114,14 +123,32 @@ export default function StatsPage() {
114 123
115 124 {dash && (
116 125 <div style={{ display: "grid", gap: 18, opacity: loading ? 0.55 : 1, transition: "opacity .2s" }}>
117 − {/* --- courbes ----------------------------------------------------- */}
126 + {/* --- jauges : couverture & complétude ----------------------------- */}
127 + {dash.gauges && dash.gauges.length > 0 && (
128 + <section aria-label="Jauges" style={{ display: "grid", gap: 12, gridTemplateColumns: "repeat(auto-fit, minmax(min(190px, 100%), 1fr))" }}>
129 + {dash.gauges.map((g) => <GaugeCard key={g.id} g={g} />)}
130 + </section>
131 + )}
132 +
133 + {/* --- évolution : courbes / barres + stats de séries --------------- */}
118 134 {dash.series?.length ? (
119 − dash.series.map((s) => <LineChart key={s.id} serie={s} />)
135 + dash.series.map((s) => (
136 + <div key={s.id} style={{ display: "grid", gap: 0 }}>
137 + <LineChart serie={s} />
138 + {s.kind !== "bar" && <StatSummary serie={s} />}
139 + </div>
140 + ))
120 141 ) : (
121 142 <EmptyBlock title="Évolution quotidienne" />
122 143 )}
123 144
124 − {/* --- répartitions (anneau + barres) ------------------------------ */}
145 + {/* --- multi-courbes (loyer médian par taille…) ---------------------- */}
146 + {dash.multiseries?.map((ms) => <MultiLineChart key={ms.id} ms={ms} />)}
147 +
148 + {/* --- barres empilées (composition par source) ---------------------- */}
149 + {dash.stacked?.map((st) => <StackedBarChart key={st.id} st={st} />)}
150 +
151 + {/* --- répartitions (anneaux + barres) ------------------------------ */}
125 152 {(donuts.length > 0 || barBreaks.length > 0) && (
126 153 <div style={{ display: "grid", gap: 18, gridTemplateColumns: "repeat(auto-fit, minmax(min(340px, 100%), 1fr))" }}>
127 154 {donuts.map((b) => <Donut key={b.id} title={b.title} items={b.items} />)}
@@ -129,11 +156,15 @@ export default function StatsPage() {
129 156 </div>
130 157 )}
131 158
159 + {/* --- distributions (histogrammes) ---------------------------------- */}
160 + {dash.distributions?.map((d) => <Histogram key={d.id} dist={d} />)}
161 +
132 162 {/* --- géographie --------------------------------------------------- */}
133 163 {dash.geo && <BarChart title={dash.geo.title} items={dash.geo.items} unit="annonces" />}
134 164
135 − {/* --- calendrier de chaleur ---------------------------------------- */}
165 + {/* --- calendriers : 26 semaines + heatmap horaire 7×24 -------------- */}
136 166 {dash.heatmap && <CalendarHeatmap title={dash.heatmap.title} cells={dash.heatmap.cells} />}
167 + {dash.hourly && <HourHeatmap title={dash.hourly.title} cells={dash.hourly.cells} />}
137 168
138 169 {/* --- tableaux détaillés ------------------------------------------- */}
139 170 {dash.tables?.map((t) => <DataTable key={t.id} spec={t} />)}
modified louka/kapdf.py +389 −72
@@ -1,10 +1,17 @@
1 1 # Auteur : Simon-Pierre Boucher — contact@spboucher.ai
2 −# ka-ui/stats/kapdf.py — moteur PDF commun Groupe KA (fpdf2).
2 +# ka-ui/stats/kapdf.py — moteur PDF commun Groupe KA (fpdf2). v2
3 3 # Consomme le JSON du contrat /api/stats/dashboard (voir SPEC.md) et produit
4 −# le rapport estampillé Groupe-KA : couverture, sommaire, KPI, graphiques
5 −# VECTORIELS (courbes/barres/anneaux), tableaux paginés, records, page de fin.
4 +# les rapports estampillés Groupe-KA. 5 modes :
5 +# complet — toutes les sections (KPI, jauges, séries + stats, multi-
6 +# séries, empilées, distributions, répartitions, géo,
7 +# heatmap horaire, tableaux, records)
8 +# synthese — couverture + KPI + records (2-3 pages)
9 +# tendances — KPI + toutes les séries temporelles + stats de séries
10 +# repartitions — breakdowns, distributions, géo, activité horaire
11 +# donnees — tous les tableaux en version longue (400 lignes max)
12 +# Graphiques VECTORIELS uniquement (primitives fpdf), accent de la marque.
6 13 # Usage :
7 −# from kapdf import GroupeKAReport
14 +# from kapdf import GroupeKAReport, REPORT_MODES, filename
8 15 # pdf_bytes = GroupeKAReport(site={"wordmark":"Lou·Ka","accent":"#ff6a00",
9 16 # "domain":"www.lou-ka.com","tagline":"…"}, dashboard=dash_json,
10 17 # mode="complet").build()
@@ -26,6 +33,14 @@ GREEN = (28, 92, 65)
26 33 DANGER = (179, 66, 58)
27 34 WHITE = (255, 255, 255)
28 35
36 +REPORT_MODES = {
37 + "complet": "Rapport complet",
38 + "synthese": "Synthèse exécutive",
39 + "tendances": "Tendances & évolution",
40 + "repartitions": "Répartitions & géographie",
41 + "donnees": "Données détaillées",
42 +}
43 +
29 44 EMAILS = [
30 45 ("contact@groupe-ka.com", "Projets, partenariats & données"),
31 46 ("info@groupe-ka.com", "Médias & questions générales"),
@@ -52,7 +67,8 @@ def _fr(n) -> str:
52 67 _SUBST = {
53 68 "—": "-", "–": "-", "→": "->", "▲": "+", "▼": "-",
54 69 "…": "...", "’": "'", "‘": "'", "“": '"', "”": '"',
55 − "œ": "oe", "Œ": "OE", "−": "-", " ": " ", " ": " ",
70 + "œ": "oe", "Œ": "OE", "−": "-", " ": " ", " ": " ",
71 + "×": "x", "·": ".", "σ": "sigma", "Δ": "delta",
56 72 }
57 73
58 74
@@ -79,7 +95,7 @@ class _PDF(FPDF):
79 95 self.set_auto_page_break(True, margin=22)
80 96
81 97 def header(self):
82 − if self.cover_mode:
98 + if self.cover_mode or self.page_no() == 1:
83 99 return
84 100 self.set_font("helvetica", "B", 8.5)
85 101 self.set_text_color(*INK)
@@ -95,8 +111,8 @@ class _PDF(FPDF):
95 111 self.set_y(20)
96 112
97 113 def footer(self):
98 − # page 1 = couverture : son footer est déclenché à l ouverture de la
99 − # page 2, après la sortie du mode couverture — on l exclut aussi.
114 + # page 1 = couverture (le flag cover_mode est déjà retombé quand
115 + # add_page() clôt la page 1 → tester aussi le numéro de page)
100 116 if self.cover_mode or self.page_no() == 1:
101 117 return
102 118 self.set_y(-15)
@@ -114,7 +130,7 @@ class GroupeKAReport:
114 130 def __init__(self, site: dict, dashboard: dict, mode: str = "complet"):
115 131 self.site = site
116 132 self.d = dashboard
117 − self.mode = mode
133 + self.mode = mode if mode in REPORT_MODES else "complet"
118 134 self.accent = _hex(site.get("accent", "#d9f26b"))
119 135 period = dashboard.get("period", {}) or {}
120 136 self.period_label = period.get("label") or "toute la période"
@@ -129,6 +145,11 @@ class GroupeKAReport:
129 145 p.set_fill_color(*fill)
130 146 p.rect(x, y, w, h, style="DF", round_corners=True, corner_radius=2.2)
131 147
148 + def _shade(self, i, n=8):
149 + shades = [1.0, 0.78, 0.58, 0.42, 0.30, 0.22, 0.15, 0.10]
150 + f = shades[i % len(shades)]
151 + return tuple(int(PAPER[j] + (self.accent[j] - PAPER[j]) * f) for j in range(3))
152 +
132 153 def _kicker(self, text):
133 154 p = self.pdf
134 155 p.set_font("helvetica", "B", 8)
@@ -152,6 +173,14 @@ class GroupeKAReport:
152 173 self.toc.append((title, self.pdf.page_no()))
153 174 self.pdf.ln(11)
154 175
176 + def _chart_title(self, title):
177 + p = self.pdf
178 + p.set_font("helvetica", "B", 10)
179 + p.set_text_color(*INK)
180 + p.set_x(p.l_margin)
181 + p.cell(0, 6, title)
182 + p.ln(7)
183 +
155 184 # ---------- pages ----------
156 185 def _cover(self):
157 186 p = self.pdf
@@ -163,12 +192,10 @@ class GroupeKAReport:
163 192 p.set_draw_color(*INK)
164 193 p.set_line_width(1.0)
165 194 p.rect(10, 10, 190, 277)
166 − # kicker
167 195 p.set_font("helvetica", "B", 10)
168 196 p.set_text_color(*GREEN)
169 197 p.set_xy(24, 34)
170 198 p.cell(0, 6, "GROUPE KA · RAPPORT STATISTIQUE")
171 − # wordmark : partie gauche + boîte encre/accent
172 199 wm = self.site.get("wordmark", "")
173 200 left, boxed = (wm.split("·") + [None])[:2] if "·" in wm else (wm, None)
174 201 p.set_xy(24, 70)
@@ -186,7 +213,7 @@ class GroupeKAReport:
186 213 p.set_xy(24, 100)
187 214 p.set_font("helvetica", "", 13)
188 215 p.set_text_color(*INK2)
189 − p.multi_cell(150, 7, f"Rapport statistique — {wm}")
216 + p.multi_cell(150, 7, f"{REPORT_MODES[self.mode]} — {wm}")
190 217 now = datetime.now(ZoneInfo("America/Toronto"))
191 218 per = self.d.get("period", {}) or {}
192 219 p.set_xy(24, 125)
@@ -195,7 +222,7 @@ class GroupeKAReport:
195 222 ("Période couverte", self.period_label + (f" ({per.get('from')} → {per.get('to')})" if per.get("from") else "")),
196 223 ("Généré le", now.strftime("%Y-%m-%d à %H:%M") + " (heure de l'Est)"),
197 224 ("Plateforme", "https://" + self.site.get("domain", "")),
198 − ("Mode", "Rapport complet" if self.mode == "complet" else "Synthèse"),
225 + ("Type de rapport", REPORT_MODES[self.mode]),
199 226 ]
200 227 y = 128
201 228 for k, v in rows:
@@ -207,7 +234,6 @@ class GroupeKAReport:
207 234 p.cell(0, 6, str(v))
208 235 p.set_font("helvetica", "", 10.5)
209 236 y += 8
210 − # bande encre au pied
211 237 p.set_fill_color(*INK)
212 238 p.rect(10, 262, 190, 25, style="F")
213 239 p.set_xy(24, 270)
@@ -232,7 +258,7 @@ class GroupeKAReport:
232 258 p = self.pdf
233 259 cols, gw, gh, gap = 3, 56, 26, 3
234 260 x0, y = p.l_margin, p.get_y()
235 − for i, k in enumerate(kpis[:9]):
261 + for i, k in enumerate(kpis[:12]):
236 262 x = x0 + (i % cols) * (gw + gap)
237 263 if i and i % cols == 0:
238 264 y += gh + gap
@@ -254,20 +280,81 @@ class GroupeKAReport:
254 280 p.set_font("helvetica", "B", 8)
255 281 p.set_text_color(*(GREEN if up else DANGER))
256 282 arrow = "+" if k["delta_pct"] >= 0 else ""
257 − p.cell(gw - 8, 4, f"{'▲' if up else '▼'} {arrow}{str(k['delta_pct']).replace('.', ',')} % vs période préc.")
283 + dv = round(float(k["delta_pct"]), 1)
284 + dv = int(dv) if float(dv).is_integer() else dv
285 + p.cell(gw - 8, 4, f"{'▲' if up else '▼'} {arrow}{str(dv).replace('.', ',')} % vs période préc.")
286 + p.set_y(y + gh + 8)
287 +
288 + def _gauges(self):
289 + gs = self.d.get("gauges") or []
290 + gs = [g for g in gs if isinstance(g.get("value"), (int, float)) and g.get("max")]
291 + if not gs:
292 + return
293 + self._section_title("Taux & couvertures")
294 + p = self.pdf
295 + cols, gw, gh, gap = 3, 56, 34, 3
296 + x0, y = p.l_margin, p.get_y()
297 + for i, g in enumerate(gs[:9]):
298 + x = x0 + (i % cols) * (gw + gap)
299 + if i and i % cols == 0:
300 + y += gh + gap
301 + if y > 240:
302 + p.add_page(); y = p.get_y()
303 + self._card(x, y, gw, gh)
304 + frac = max(0.0, min(1.0, g["value"] / g["max"]))
305 + cx, cy, r = x + gw / 2, y + 20, 14
306 + # arc de fond + arc de valeur (demi-cercle en petits segments)
307 + for pass_col, pass_frac, lw in (((225, 223, 217), 1.0, 2.6), (self.accent, frac, 2.6)):
308 + p.set_draw_color(*pass_col)
309 + p.set_line_width(lw)
310 + steps = max(2, int(60 * pass_frac))
311 + last = None
312 + for st in range(steps + 1):
313 + a = math.pi + math.pi * pass_frac * st / steps
314 + pt = (cx + r * math.cos(a), cy + r * math.sin(a))
315 + if last:
316 + p.line(last[0], last[1], pt[0], pt[1])
317 + last = pt
318 + p.set_font("helvetica", "B", 11)
319 + p.set_text_color(*INK)
320 + p.set_xy(x + 4, cy - 5)
321 + p.cell(gw - 8, 6, f"{_fr(g['value'])}{' ' + g['unit'] if g.get('unit') else ''}", align="C")
322 + p.set_font("helvetica", "", 6.6)
323 + p.set_text_color(*INK3)
324 + p.set_xy(x + 4, cy + 1.5)
325 + p.cell(gw - 8, 4, f"{frac * 100:.0f} % de {_fr(g['max'])}", align="C")
326 + p.set_xy(x + 3, y + gh - 7)
327 + p.set_font("helvetica", "", 7)
328 + p.set_text_color(*INK2)
329 + p.multi_cell(gw - 6, 3.3, str(g.get("label", ""))[:60], align="C")
258 330 p.set_y(y + gh + 8)
259 331
260 − def _line_chart(self, s):
332 + def _serie_stats_row(self, s):
333 + """Ligne min/max/moyenne/médiane sous un graphique de série."""
334 + p = self.pdf
335 + vs = [pt["v"] for pt in (s.get("points") or []) if isinstance(pt.get("v"), (int, float))]
336 + if len(vs) < 2:
337 + return
338 + sv = sorted(vs)
339 + mean = sum(vs) / len(vs)
340 + med = sv[len(sv) // 2]
341 + sd = math.sqrt(sum((v - mean) ** 2 for v in vs) / len(vs))
342 + p.set_font("helvetica", "", 6.8)
343 + p.set_text_color(*INK3)
344 + p.cell(0, 4, f"min {_fr(sv[0])} · max {_fr(sv[-1])} · moyenne {_fr(round(mean, 2))} · médiane {_fr(med)} · écart-type {_fr(round(sd, 2))}")
345 + p.ln(5.5)
346 +
347 + def _line_chart(self, s, with_stats=False):
261 348 p = self.pdf
262 349 pts = s.get("points") or []
263 350 if len(pts) < 2:
264 351 return
352 + if s.get("kind") == "bar":
353 + self._vbars(s)
354 + return
265 355 if p.get_y() > 200:
266 356 p.add_page()
267 − p.set_font("helvetica", "B", 10)
268 − p.set_text_color(*INK)
269 − p.cell(0, 6, s.get("title", ""))
270 − p.ln(7)
357 + self._chart_title(s.get("title", ""))
271 358 x0, y0, w, h = p.l_margin, p.get_y(), 174, 52
272 359 self._card(x0, y0, w, h, fill=WHITE)
273 360 cx, cy, cw, ch = x0 + 12, y0 + 6, w - 20, h - 16
@@ -275,7 +362,6 @@ class GroupeKAReport:
275 362 vmax = max(vals) or 1
276 363 vmin = min(0, min(vals))
277 364 rng = (vmax - vmin) or 1
278 − # grille + graduations
279 365 p.set_font("helvetica", "", 6.3)
280 366 p.set_text_color(*INK3)
281 367 p.set_draw_color(200, 200, 195)
@@ -286,6 +372,20 @@ class GroupeKAReport:
286 372 p.set_xy(x0 + 1, gy - 1.6)
287 373 p.cell(10, 3, _fr(vmin + rng * g / 4), align="R")
288 374
375 + def xy(i, n, v):
376 + return (cx + cw * (i / (n - 1)), cy + ch - ch * ((v - vmin) / rng))
377 +
378 + # aire sous la courbe (kind=area) : petits trapèzes accent pâle
379 + if s.get("kind") == "area":
380 + fill = tuple(int(PAPER[j] + (self.accent[j] - PAPER[j]) * 0.18) for j in range(3))
381 + p.set_fill_color(*fill)
382 + p.set_draw_color(*fill)
383 + n = len(pts)
384 + for i in range(n - 1):
385 + x1, y1 = xy(i, n, pts[i]["v"])
386 + x2, y2 = xy(i + 1, n, pts[i + 1]["v"])
387 + p.polygon([(x1, y1), (x2, y2), (x2, cy + ch), (x1, cy + ch)], style="DF")
388 +
289 389 def draw(series, color, width, dash=None):
290 390 n = len(series)
291 391 p.set_draw_color(*color)
@@ -294,8 +394,7 @@ class GroupeKAReport:
294 394 p.set_dash_pattern(dash=1.2, gap=1.2)
295 395 last = None
296 396 for i, pt in enumerate(series):
297 − px = cx + cw * (i / (n - 1))
298 − py = cy + ch - ch * ((pt["v"] - vmin) / rng)
397 + px, py = xy(i, n, pt["v"])
299 398 if last:
300 399 p.line(last[0], last[1], px, py)
301 400 last = (px, py)
@@ -304,7 +403,6 @@ class GroupeKAReport:
304 403 if s.get("compare"):
305 404 draw(s["compare"], INK3, 0.35, dash=True)
306 405 draw(pts, self.accent, 0.7)
307 − # libellés d'axe X (premier / milieu / dernier)
308 406 p.set_text_color(*INK3)
309 407 for frac, idx in ((0, 0), (0.5, len(pts) // 2), (1, -1)):
310 408 p.set_xy(cx + cw * frac - 9, cy + ch + 1.5)
@@ -314,9 +412,166 @@ class GroupeKAReport:
314 412 p.set_font("helvetica", "", 6.8)
315 413 p.set_text_color(*INK3)
316 414 p.cell(0, 4, "— période courante (accent) · ---- période comparée")
317 − p.ln(6)
318 − else:
319 − p.ln(2)
415 + p.ln(5.5)
416 + if with_stats:
417 + self._serie_stats_row(s)
418 + p.ln(1.5)
419 +
420 + def _vbars(self, s):
421 + """Barres verticales : série kind=bar ou distribution (bins)."""
422 + p = self.pdf
423 + pts = s.get("points") or [{"t": b.get("label"), "v": b.get("value")} for b in (s.get("bins") or [])]
424 + pts = [pt for pt in pts if isinstance(pt.get("v"), (int, float))]
425 + if not pts:
426 + return
427 + if p.get_y() > 205:
428 + p.add_page()
429 + self._chart_title(s.get("title", ""))
430 + x0, y0, w, h = p.l_margin, p.get_y(), 174, 48
431 + self._card(x0, y0, w, h, fill=WHITE)
432 + cx, cy, cw, ch = x0 + 12, y0 + 5, w - 20, h - 14
433 + vmax = max(pt["v"] for pt in pts) or 1
434 + p.set_font("helvetica", "", 6.3)
435 + p.set_text_color(*INK3)
436 + p.set_draw_color(200, 200, 195)
437 + p.set_line_width(0.15)
438 + for g in range(5):
439 + gy = cy + ch - ch * g / 4
440 + p.line(cx, gy, cx + cw, gy)
441 + p.set_xy(x0 + 1, gy - 1.6)
442 + p.cell(10, 3, _fr(vmax * g / 4), align="R")
443 + n = len(pts)
444 + bw = max(0.8, cw / n - 0.6)
445 + p.set_fill_color(*self.accent)
446 + p.set_draw_color(*INK)
447 + p.set_line_width(0.15)
448 + for i, pt in enumerate(pts):
449 + bh = ch * (pt["v"] / vmax)
450 + p.rect(cx + cw * i / n + 0.3, cy + ch - bh, bw, max(bh, 0.4 if pt["v"] > 0 else 0), style="DF")
451 + p.set_text_color(*INK3)
452 + for frac, idx in ((0, 0), (0.5, n // 2), (1, -1)):
453 + p.set_xy(cx + cw * frac - 10, cy + ch + 1.5)
454 + p.cell(20, 3, str(pts[idx].get("t", ""))[:12], align="C")
455 + p.set_y(y0 + h + 5)
456 +
457 + def _multiline(self, ms):
458 + """Multi-séries (≤4) : accent plein / encre fin / accent pointillé /
459 + gris pointillé — l'identité passe par le motif, pas la couleur seule."""
460 + p = self.pdf
461 + series = [s for s in (ms.get("series") or []) if len(s.get("points") or []) > 1][:4]
462 + if not series:
463 + return
464 + if p.get_y() > 195:
465 + p.add_page()
466 + self._chart_title(ms.get("title", ""))
467 + x0, y0, w, h = p.l_margin, p.get_y(), 174, 52
468 + self._card(x0, y0, w, h, fill=WHITE)
469 + cx, cy, cw, ch = x0 + 12, y0 + 6, w - 20, h - 16
470 + vals = [pt["v"] for s in series for pt in s["points"]]
471 + vmax = max(vals) or 1
472 + vmin = min(0, min(vals))
473 + rng = (vmax - vmin) or 1
474 + p.set_font("helvetica", "", 6.3)
475 + p.set_text_color(*INK3)
476 + p.set_draw_color(200, 200, 195)
477 + p.set_line_width(0.15)
478 + for g in range(5):
479 + gy = cy + ch - ch * g / 4
480 + p.line(cx, gy, cx + cw, gy)
481 + p.set_xy(x0 + 1, gy - 1.6)
482 + p.cell(10, 3, _fr(vmin + rng * g / 4), align="R")
483 + styles = [
484 + (self.accent, 0.7, None),
485 + (INK, 0.45, None),
486 + (self.accent, 0.55, True),
487 + (INK3, 0.5, True),
488 + ]
489 + for si, s in enumerate(series):
490 + col, lw, dash = styles[si]
491 + p.set_draw_color(*col)
492 + p.set_line_width(lw)
493 + if dash:
494 + p.set_dash_pattern(dash=1.4, gap=1.2)
495 + n = len(s["points"])
496 + last = None
497 + for i, pt in enumerate(s["points"]):
498 + px = cx + cw * (i / (n - 1))
499 + py = cy + ch - ch * ((pt["v"] - vmin) / rng)
500 + if last:
501 + p.line(last[0], last[1], px, py)
502 + last = (px, py)
503 + p.set_dash_pattern()
504 + ref = series[0]["points"]
505 + p.set_text_color(*INK3)
506 + for frac, idx in ((0, 0), (0.5, len(ref) // 2), (1, -1)):
507 + p.set_xy(cx + cw * frac - 9, cy + ch + 1.5)
508 + p.cell(18, 3, str(ref[idx].get("t", ""))[:10], align="C")
509 + p.set_y(y0 + h + 4)
510 + p.set_font("helvetica", "", 6.8)
511 + p.set_text_color(*INK3)
512 + marks = ["—", "—", "----", "----"]
513 + leg = " · ".join(f"{marks[i]} {s.get('label', '')}" for i, s in enumerate(series))
514 + p.cell(0, 4, leg[:120])
515 + p.ln(6)
516 +
517 + def _stacked(self, st):
518 + p = self.pdf
519 + keys = (st.get("keys") or [])[:6]
520 + pts = st.get("points") or []
521 + if not keys or not pts:
522 + return
523 + if p.get_y() > 195:
524 + p.add_page()
525 + self._chart_title(st.get("title", ""))
526 + x0, y0, w, h = p.l_margin, p.get_y(), 174, 52
527 + self._card(x0, y0, w, h, fill=WHITE)
528 + cx, cy, cw, ch = x0 + 12, y0 + 6, w - 20, h - 16
529 + totals = [sum(v or 0 for v in pt.get("values", [])[: len(keys)]) for pt in pts]
530 + vmax = max(totals) or 1
531 + p.set_font("helvetica", "", 6.3)
532 + p.set_text_color(*INK3)
533 + p.set_draw_color(200, 200, 195)
534 + p.set_line_width(0.15)
535 + for g in range(5):
536 + gy = cy + ch - ch * g / 4
537 + p.line(cx, gy, cx + cw, gy)
538 + p.set_xy(x0 + 1, gy - 1.6)
539 + p.cell(10, 3, _fr(vmax * g / 4), align="R")
540 + n = len(pts)
541 + bw = max(0.8, cw / n - 0.6)
542 + p.set_draw_color(*WHITE)
543 + p.set_line_width(0.12)
544 + for i, pt in enumerate(pts):
545 + yacc = cy + ch
546 + for j, k in enumerate(keys):
547 + v = (pt.get("values") or [0] * len(keys))[j] if j < len(pt.get("values", [])) else 0
548 + if not v:
549 + continue
550 + bh = ch * (v / vmax)
551 + yacc -= bh
552 + p.set_fill_color(*self._shade(j))
553 + p.rect(cx + cw * i / n + 0.3, yacc, bw, max(bh - 0.15, 0.3), style="DF")
554 + p.set_text_color(*INK3)
555 + for frac, idx in ((0, 0), (0.5, n // 2), (1, -1)):
556 + p.set_xy(cx + cw * frac - 10, cy + ch + 1.5)
557 + p.cell(20, 3, str(pts[idx].get("t", ""))[:12], align="C")
558 + p.set_y(y0 + h + 4)
559 + # légende
560 + p.set_font("helvetica", "", 6.8)
561 + lx = p.l_margin
562 + for j, k in enumerate(keys):
563 + p.set_fill_color(*self._shade(j))
564 + p.set_draw_color(*INK)
565 + p.set_line_width(0.2)
566 + p.rect(lx, p.get_y() + 0.6, 3, 3, style="DF")
567 + p.set_xy(lx + 4, p.get_y())
568 + p.set_text_color(*INK2)
569 + txt = str(k)[:22]
570 + p.cell(p.get_string_width(txt) + 3, 4, txt)
571 + lx = p.get_x() + 3
572 + if lx > 165:
573 + break
574 + p.ln(7)
320 575
321 576 def _bars(self, title, items, unit=""):
322 577 p = self.pdf
@@ -326,10 +581,8 @@ class GroupeKAReport:
326 581 need = 10 + len(items) * 7
327 582 if p.get_y() + need > 265:
328 583 p.add_page()
329 − p.set_font("helvetica", "B", 10)
330 − p.set_text_color(*INK)
331 − p.cell(0, 6, title)
332 − p.ln(8)
584 + self._chart_title(title)
585 + p.ln(1)
333 586 vmax = max(it["value"] for it in items) or 1
334 587 for it in items:
335 588 y = p.get_y()
@@ -337,19 +590,23 @@ class GroupeKAReport:
337 590 p.set_text_color(*INK)
338 591 p.set_x(p.l_margin)
339 592 p.cell(46, 5, str(it["label"])[:34])
340 − bw = 96 * (it["value"] / vmax)
593 + bw = 86 * (it["value"] / vmax)
341 594 p.set_fill_color(*self.accent)
342 595 p.set_draw_color(*INK)
343 596 p.set_line_width(0.25)
344 597 p.rect(p.l_margin + 48, y + 0.7, max(bw, 0.8), 3.6, style="DF")
345 − p.set_xy(p.l_margin + 148, y)
598 + p.set_xy(p.l_margin + 136, y)
346 599 p.set_font("helvetica", "B", 7.6)
347 − p.cell(26, 5, _fr(it["value"]) + (" " + unit if unit else ""), align="R")
600 + p.cell(24, 5, _fr(it["value"]) + (" " + unit if unit else ""), align="R")
601 + if it.get("delta_pct") is not None:
602 + up = it["delta_pct"] >= 0
603 + p.set_font("helvetica", "B", 6.6)
604 + p.set_text_color(*(GREEN if up else DANGER))
605 + p.cell(14, 5, f"{'+' if up else ''}{str(round(it['delta_pct'], 1)).replace('.', ',')} %", align="R")
348 606 p.ln(6.4)
349 607 p.ln(3)
350 608
351 609 def _donut(self, b):
352 − # anneau vectoriel simple (arcs) + légende
353 610 p = self.pdf
354 611 items = [it for it in (b.get("items") or []) if it.get("value")][:8]
355 612 total = sum(it["value"] for it in items)
@@ -357,17 +614,13 @@ class GroupeKAReport:
357 614 return
358 615 if p.get_y() > 210:
359 616 p.add_page()
360 − p.set_font("helvetica", "B", 10)
361 − p.set_text_color(*INK)
362 − p.cell(0, 6, b.get("title", ""))
363 − p.ln(8)
617 + self._chart_title(b.get("title", ""))
618 + p.ln(1)
364 619 cx, cy, r = p.l_margin + 26, p.get_y() + 24, 20
365 − shades = [1.0, 0.78, 0.58, 0.42, 0.30, 0.22, 0.15, 0.10]
366 620 start = -90.0
367 621 for i, it in enumerate(items):
368 622 frac = it["value"] / total
369 − f = shades[i % len(shades)]
370 − col = tuple(int(PAPER[j] + (self.accent[j] - PAPER[j]) * f) for j in range(3))
623 + col = self._shade(i)
371 624 steps = max(2, int(72 * frac))
372 625 p.set_fill_color(*col)
373 626 p.set_draw_color(*col)
@@ -386,11 +639,9 @@ class GroupeKAReport:
386 639 p.set_line_width(0.4)
387 640 p.ellipse(cx - 11, cy - 11, 22, 22, style="DF")
388 641 p.ellipse(cx - r, cy - r, 2 * r, 2 * r, style="D")
389 − # légende
390 642 ly = cy - 22
391 643 for i, it in enumerate(items):
392 − f = shades[i % len(shades)]
393 − col = tuple(int(PAPER[j] + (self.accent[j] - PAPER[j]) * f) for j in range(3))
644 + col = self._shade(i)
394 645 p.set_fill_color(*col)
395 646 p.set_draw_color(*INK)
396 647 p.rect(p.l_margin + 60, ly + 0.8, 4, 4, style="DF")
@@ -402,7 +653,39 @@ class GroupeKAReport:
402 653 ly += 5.6
403 654 p.set_y(max(cy + r, ly) + 6)
404 655
405 − def _table(self, t):
656 + def _hourly(self):
657 + hh = self.d.get("hourly") or {}
658 + cells = hh.get("cells") or []
659 + if not cells:
660 + return
661 + p = self.pdf
662 + if p.get_y() > 190:
663 + p.add_page()
664 + self._chart_title(hh.get("title", "Activité par jour et heure"))
665 + x0, y0 = p.l_margin, p.get_y()
666 + cw, chh, lx, ly = 6.4, 6.4, 12, 5
667 + vmax = max((c.get("value") or 0) for c in cells) or 1
668 + grid = {(c.get("dow"), c.get("hour")): c.get("value") or 0 for c in cells}
669 + dows = ["Lun", "Mar", "Mer", "Jeu", "Ven", "Sam", "Dim"]
670 + p.set_font("helvetica", "", 5.8)
671 + p.set_text_color(*INK3)
672 + for h in (0, 6, 12, 18, 23):
673 + p.set_xy(x0 + lx + h * cw, y0)
674 + p.cell(cw, 3, f"{h}h", align="C")
675 + for d in range(7):
676 + p.set_xy(x0, y0 + ly + d * chh + 1.5)
677 + p.cell(lx - 1, 3, dows[d], align="R")
678 + for h in range(24):
679 + v = grid.get((d, h), 0)
680 + f = 0.1 + 0.9 * (v / vmax) if v else 0.0
681 + col = tuple(int(PAPER[j] + (self.accent[j] - PAPER[j]) * f) for j in range(3)) if v else (235, 233, 228)
682 + p.set_fill_color(*col)
683 + p.set_draw_color(215, 213, 207)
684 + p.set_line_width(0.1)
685 + p.rect(x0 + lx + h * cw, y0 + ly + d * chh, cw - 0.5, chh - 0.5, style="DF")
686 + p.set_y(y0 + ly + 7 * chh + 5)
687 +
688 + def _table(self, t, max_rows=200):
406 689 p = self.pdf
407 690 cols = t.get("columns") or []
408 691 rows = t.get("rows") or []
@@ -419,7 +702,7 @@ class GroupeKAReport:
419 702 p.ln(6)
420 703 head()
421 704 p.set_text_color(*INK)
422 − for i, row in enumerate(rows[:200]):
705 + for i, row in enumerate(rows[:max_rows]):
423 706 if p.get_y() > 262:
424 707 p.add_page()
425 708 head()
@@ -430,10 +713,10 @@ class GroupeKAReport:
430 713 txt = _fr(cell) if isinstance(cell, (int, float)) else str(cell)
431 714 p.cell(w, 5.4, " " + txt[:34], fill=True)
432 715 p.ln(5.4)
433 − if len(rows) > 200:
716 + if len(rows) > max_rows:
434 717 p.set_font("helvetica", "", 7)
435 718 p.set_text_color(*INK3)
436 − p.cell(0, 5, f"… {len(rows) - 200} lignes supplémentaires non imprimées")
719 + p.cell(0, 5, f"… {len(rows) - max_rows} lignes supplémentaires non imprimées")
437 720 p.ln(6)
438 721
439 722 def _records(self):
@@ -442,7 +725,7 @@ class GroupeKAReport:
442 725 return
443 726 self._section_title("Records & faits marquants")
444 727 p = self.pdf
445 − for r in recs[:10]:
728 + for r in recs[:14]:
446 729 if p.get_y() > 258:
447 730 p.add_page()
448 731 y = p.get_y()
@@ -500,43 +783,76 @@ class GroupeKAReport:
500 783 "groupe-ka.com/conditions · /confidentialite · /loi-25.",
501 784 )
502 785
503 − def _toc_page(self):
504 − # insérée après coup ? fpdf ne réordonne pas : on écrit le sommaire en
505 − # page 2 en réservant la page lors du build (voir build()).
506 − pass
786 + # ---------- groupes de sections ----------
787 + def _all_series(self, with_stats=True):
788 + for s in self.d.get("series") or []:
789 + self._line_chart(s, with_stats=with_stats)
790 + for ms in self.d.get("multiseries") or []:
791 + self._multiline(ms)
792 + for st in self.d.get("stacked") or []:
793 + self._stacked(st)
794 +
795 + def _all_breakdowns(self):
796 + for b in self.d.get("breakdowns") or []:
797 + if b.get("kind") == "donut":
798 + self._donut(b)
799 + else:
800 + self._bars(b.get("title", ""), b.get("items"))
801 + for dist in self.d.get("distributions") or []:
802 + self._vbars(dist)
803 + geo = self.d.get("geo")
804 + if geo:
805 + self._bars(geo.get("title", "Répartition géographique"), geo.get("items"))
806 + self._hourly()
507 807
508 808 def build(self) -> bytes:
509 809 p = self.pdf
510 810 p.alias_nb_pages()
511 811 self._cover()
812 + with_toc = self.mode in ("complet", "donnees")
813 + toc_page_no = None
512 814 if self.mode == "synthese":
513 815 p.add_page()
514 816 self._kpis()
817 + self._gauges()
818 + self._records()
819 + self._final_page()
820 + elif self.mode == "tendances":
821 + p.add_page()
822 + self._kpis()
823 + self._section_title("Évolution & tendances")
824 + self._all_series(with_stats=True)
515 825 self._records()
516 826 self._final_page()
517 − else:
827 + elif self.mode == "repartitions":
828 + p.add_page()
829 + self._section_title("Répartitions, distributions & géographie")
830 + self._all_breakdowns()
831 + self._final_page()
832 + elif self.mode == "donnees":
833 + p.add_page()
834 + toc_page_no = p.page_no()
835 + for t in self.d.get("tables") or []:
836 + self._table(t, max_rows=400)
837 + self._final_page()
838 + else: # complet
518 839 p.add_page()
519 840 toc_page_no = p.page_no()
520 841 p.add_page()
521 842 self._kpis()
522 − for s in self.d.get("series") or []:
523 − if s.get("kind") == "bar":
524 − self._bars(s.get("title", ""), [{"label": pt.get("t"), "value": pt.get("v")} for pt in (s.get("points") or [])], s.get("unit", ""))
525 − else:
526 − self._line_chart(s)
527 − for b in self.d.get("breakdowns") or []:
528 − if b.get("kind") == "donut":
529 − self._donut(b)
530 − else:
531 − self._bars(b.get("title", ""), b.get("items"))
532 − geo = self.d.get("geo")
533 − if geo:
534 − self._bars(geo.get("title", "Répartition géographique"), geo.get("items"))
843 + self._gauges()
844 + if (self.d.get("series") or self.d.get("multiseries") or self.d.get("stacked")):
845 + self._section_title("Évolution & tendances")
846 + self._all_series(with_stats=True)
847 + if (self.d.get("breakdowns") or self.d.get("distributions") or self.d.get("geo") or self.d.get("hourly")):
848 + self._section_title("Répartitions, distributions & géographie")
849 + self._all_breakdowns()
535 850 for t in self.d.get("tables") or []:
536 851 self._table(t)
537 852 self._records()
538 853 self._final_page()
539 − # sommaire écrit sur la page réservée (page 2)
854 + # sommaire écrit sur la page réservée
855 + if toc_page_no is not None:
540 856 last_page = p.page
541 857 p.page = toc_page_no
542 858 p.set_y(22)
@@ -555,6 +871,7 @@ class GroupeKAReport:
555 871 return bytes(p.output())
556 872
557 873
558 −def filename(platform_id: str, period: str) -> str:
874 +def filename(platform_id: str, period: str, mode: str = "complet") -> str:
559 875 today = datetime.now(ZoneInfo("America/Toronto")).strftime("%Y-%m-%d")
560 − return f"groupe-ka_{platform_id}_stats_{period}_{today}.pdf"
876 + suffix = "" if mode in ("", "complet") else f"_{mode}"
877 + return f"groupe-ka_{platform_id}_stats_{period}{suffix}_{today}.pdf"
modified louka/statsdash.py +408 −50
@@ -1,11 +1,15 @@
1 1 # -----------------------------------------------------------------------------
2 2 # Lou-Ka — Agrégateur de logements à louer (province de Québec)
3 3 # Auteur : Simon-Pierre Boucher — contact@spboucher.ai
4 −# statsdash.py : tableau de bord statistique — contrat commun Groupe KA
4 +# statsdash.py : tableau de bord statistique — contrat commun Groupe KA v2
5 5 # (voir frontend/src/ka/stats/SPEC.md). Construit le JSON du dashboard à
6 6 # partir de requêtes SQL agrégées (listings, sync_log, price_log) avec un
7 7 # cache mémoire de 5 minutes par clé de période. AUCUNE stat inventée :
8 8 # une section sans donnée réelle est simplement absente du JSON.
9 +# v2 (2026-08-19) : sparklines KPI, jauges de couverture, série des loyers
10 +# (area), multi-courbes loyer médian par taille, barres empilées par source,
11 +# distribution des loyers, heatmap horaire 7×24, tableaux « loyers par
12 +# taille » et « baisses de loyer », records enrichis.
9 13 # -----------------------------------------------------------------------------
10 14 from __future__ import annotations
11 15
@@ -26,6 +30,10 @@ CACHE_TTL = 300 # secondes
26 30 _cache: dict[str, tuple[float, dict]] = {}
27 31 _cache_lock = threading.Lock()
28 32
33 +# bornes de plausibilité des loyers résidentiels : au-delà, presque toujours
34 +# des erreurs de lecture à la source — exclues des agrégats de prix.
35 +PRIX_MIN, PRIX_MAX = 300, 15000
36 +
29 37 PERIODS = {
30 38 "auj": ("Aujourd'hui", 0),
31 39 "7j": ("7 jours", 6),
@@ -35,6 +43,8 @@ PERIODS = {
35 43 "12m": ("12 mois", 364),
36 44 }
37 45
46 +DOW_FR = ["lundi", "mardi", "mercredi", "jeudi", "vendredi", "samedi", "dimanche"]
47 +
38 48
39 49 # ---------------------------------------------------------------- utilitaires
40 50 def _day_start_ts(d: date) -> float:
@@ -83,8 +93,25 @@ def _days(a: date, b: date) -> list[date]:
83 93 return [a + timedelta(days=i) for i in range((b - a).days + 1)]
84 94
85 95
96 +def _fr_int(n: float) -> str:
97 + return f"{int(round(n)):,}".replace(",", " ")
98 +
99 +
86 100 def _fr_money(n: float) -> str:
87 − return f"{int(round(n)):,}".replace(",", " ") + " $"
101 + return _fr_int(n) + " $"
102 +
103 +
104 +def _spark(pts: list[dict], cap: int = 30) -> list[dict] | None:
105 + """Sous-échantillonne une série pour la sparkline d'un KPI (≤ cap points)."""
106 + if len(pts) < 2:
107 + return None
108 + if len(pts) <= cap:
109 + return pts
110 + step = max(1, len(pts) // cap)
111 + out = pts[::step]
112 + if out[-1] is not pts[-1]:
113 + out.append(pts[-1])
114 + return out
88 115
89 116
90 117 def _source_names() -> dict[str, str]:
@@ -95,6 +122,13 @@ def _source_names() -> dict[str, str]:
95 122 return {}
96 123
97 124
125 +def _pctile(sorted_vals: list[float], frac: float) -> float | None:
126 + if not sorted_vals:
127 + return None
128 + i = min(len(sorted_vals) - 1, int(len(sorted_vals) * frac))
129 + return sorted_vals[i]
130 +
131 +
98 132 # ------------------------------------------------------------------- dashboard
99 133 def compute(period: str = "30j", from_: str | None = None,
100 134 to_: str | None = None) -> dict:
@@ -118,6 +152,20 @@ def _compute(period: str, from_: str | None, to_: str | None) -> dict:
118 152 con.close()
119 153
120 154
155 +# requête réutilisée : premier loyer observé de chaque annonce (journal de
156 +# prix) — c'est le loyer demandé à l'entrée sur le marché, borné plausible.
157 +_FIRST_PRICE_CTE = """
158 + WITH fp AS (
159 + SELECT p.uid uid, p.ts ts, p.price price
160 + FROM price_log p
161 + JOIN (SELECT uid, MIN(ts) t0 FROM price_log
162 + WHERE price IS NOT NULL GROUP BY uid) f
163 + ON f.uid = p.uid AND p.ts = f.t0
164 + WHERE p.price BETWEEN ? AND ?
165 + )
166 +"""
167 +
168 +
121 169 def _build(con, period: str, from_: str | None, to_: str | None) -> dict:
122 170 today = datetime.now(TZ).date()
123 171 cov_min, _cov_max = _coverage(con)
@@ -160,6 +208,8 @@ def _build(con, period: str, from_: str | None, to_: str | None) -> dict:
160 208 span = (d_to - d_from).days + 1
161 209 p_from, p_to = d_from - timedelta(days=span), d_from - timedelta(days=1)
162 210 prev_ok = p_from >= cov_min
211 + pts_prev_from = _day_start_ts(p_from)
212 + pts_prev_to = _day_start_ts(p_to + timedelta(days=1))
163 213 new_prev = removed_prev = None
164 214 if prev_ok:
165 215 new_prev = sum(n for d, n in starts.items()
@@ -171,15 +221,15 @@ def _build(con, period: str, from_: str | None, to_: str | None) -> dict:
171 221
172 222 row = con.execute(
173 223 "SELECT AVG(price) avg_p, COUNT(price) n_p FROM listings"
174 − " WHERE active=1 AND dup_of IS NULL AND price IS NOT NULL AND price>0"
175 − ).fetchone()
224 + " WHERE active=1 AND dup_of IS NULL AND price BETWEEN ? AND ?",
225 + (PRIX_MIN, PRIX_MAX)).fetchone()
176 226 avg_price, n_priced = row["avg_p"], row["n_p"]
177 227 median_price = None
178 228 if n_priced:
179 229 median_price = con.execute(
180 230 "SELECT price FROM listings WHERE active=1 AND dup_of IS NULL"
181 − " AND price IS NOT NULL AND price>0 ORDER BY price"
182 − " LIMIT 1 OFFSET ?", (n_priced // 2,)).fetchone()["price"]
231 + " AND price BETWEEN ? AND ? ORDER BY price LIMIT 1 OFFSET ?",
232 + (PRIX_MIN, PRIX_MAX, n_priced // 2)).fetchone()["price"]
183 233
184 234 connectors = con.execute(
185 235 "SELECT COUNT(DISTINCT source) n FROM sync_log"
@@ -188,33 +238,52 @@ def _build(con, period: str, from_: str | None, to_: str | None) -> dict:
188 238 "SELECT COUNT(DISTINCT city) n FROM listings"
189 239 " WHERE active=1 AND dup_of IS NULL AND city<>''").fetchone()["n"]
190 240
241 + # séries journalières (réutilisées : séries, sparklines)
242 + days = _days(d_from, d_to)
243 + pts_act = [{"t": d.isoformat(), "v": actives_at(d)} for d in days]
244 + pts_new = [{"t": d.isoformat(), "v": starts.get(d.isoformat(), 0)}
245 + for d in days]
246 + pts_rem = [{"t": d.isoformat(), "v": ends.get(d.isoformat(), 0)}
247 + for d in days]
248 +
249 + # loyer moyen des nouvelles annonces par jour (premier prix observé)
250 + fp_daily = con.execute(
251 + _FIRST_PRICE_CTE +
252 + "SELECT date(ts,'unixepoch','localtime') d, AVG(price) a, COUNT(*) n"
253 + " FROM fp WHERE ts>=? AND ts<? GROUP BY d ORDER BY d",
254 + (PRIX_MIN, PRIX_MAX, ts_from, ts_to)).fetchall()
255 + pts_rent = [{"t": r["d"], "v": round(r["a"])} for r in fp_daily
256 + if r["n"] >= 5]
257 +
191 258 kpis = [
192 259 {"id": "actives", "label": "Annonces actives", "value": actives_now,
193 260 "delta_pct": _pct(actives_now, actives_prev) if actives_prev else None,
194 261 "direction": "up" if (actives_prev and actives_now >= actives_prev) else
195 − ("down" if actives_prev else None)},
262 + ("down" if actives_prev else None),
263 + "spark": _spark(pts_act)},
196 264 {"id": "nouvelles", "label": "Nouvelles annonces (période)",
197 265 "value": new_in,
198 266 "delta_pct": _pct(new_in, new_prev) if prev_ok else None,
199 − "direction": ("up" if new_in >= (new_prev or 0) else "down") if prev_ok else None},
267 + "direction": ("up" if new_in >= (new_prev or 0) else "down") if prev_ok else None,
268 + "spark": _spark(pts_new)},
200 269 {"id": "retirees", "label": "Annonces retirées (période)",
201 270 "value": removed_in,
202 271 "delta_pct": _pct(removed_in, removed_prev) if prev_ok else None,
203 − "direction": ("down" if removed_in >= (removed_prev or 0) else "up") if prev_ok else None},
272 + "direction": ("down" if removed_in >= (removed_prev or 0) else "up") if prev_ok else None,
273 + "spark": _spark(pts_rem)},
204 274 ]
205 275 if avg_price:
206 276 kpis.append({"id": "loyer_moyen", "label": "Loyer moyen (actives)",
207 − "value": round(avg_price), "unit": "$"})
277 + "value": round(avg_price), "unit": "$",
278 + "spark": _spark(pts_rent)})
208 279 if median_price:
209 280 kpis.append({"id": "loyer_median", "label": "Loyer médian (actives)",
210 281 "value": round(median_price), "unit": "$"})
211 − # qualité des données (quality.py) : complétude moyenne + quarantaine
282 + # qualité des données (quality.py) : quarantaine
212 283 qual = con.execute(
213 284 "SELECT ROUND(AVG(completeness),1) c, SUM(published=0) q"
214 285 " FROM listings WHERE active=1 AND dup_of IS NULL").fetchone()
215 286 if qual["c"] is not None:
216 − kpis.append({"id": "completude", "label": "Complétude moyenne des annonces",
217 − "value": qual["c"], "unit": "%"})
218 287 kpis.append({"id": "quarantaine",
219 288 "label": "Annonces en quarantaine (qualité)",
220 289 "value": qual["q"] or 0})
@@ -239,25 +308,131 @@ def _build(con, period: str, from_: str | None, to_: str | None) -> dict:
239 308 kpis.append({"id": "villes", "label": "Villes couvertes", "value": cities_n})
240 309 kpis = [{k: v for k, v in kpi.items() if v is not None} for kpi in kpis]
241 310
311 + # ---- jauges de couverture / complétude ---------------------------------
312 + cov = con.execute(
313 + """SELECT COUNT(*) n,
314 + SUM(lat IS NOT NULL AND lng IS NOT NULL) geo,
315 + SUM(price BETWEEN ? AND ?) prix,
316 + SUM(images IS NOT NULL AND images NOT IN ('', '[]')) img,
317 + SUM(published=1) pub
318 + FROM listings WHERE active=1 AND dup_of IS NULL""",
319 + (PRIX_MIN, PRIX_MAX)).fetchone()
320 + gauges = []
321 + if cov["n"]:
322 + n_act = cov["n"]
323 +
324 + def _gauge(gid, lab, num, help_=None):
325 + g = {"id": gid, "label": lab,
326 + "value": round(100.0 * (num or 0) / n_act, 1),
327 + "max": 100, "unit": "%"}
328 + if help_:
329 + g["help"] = help_
330 + return g
331 +
332 + gauges = [
333 + _gauge("geo", "Annonces géolocalisées", cov["geo"]),
334 + _gauge("prix", "Annonces avec loyer affiché", cov["prix"]),
335 + _gauge("photos", "Annonces avec photos", cov["img"]),
336 + _gauge("publiees", "Annonces publiées (qualité OK)", cov["pub"],
337 + "Le reste est en quarantaine qualité"),
338 + ]
339 + if qual["c"] is not None:
340 + gauges.append({"id": "completude",
341 + "label": "Complétude moyenne des fiches",
342 + "value": qual["c"], "max": 100, "unit": "%"})
343 +
242 344 # ---- séries temporelles ----------------------------------------------
243 − days = _days(d_from, d_to)
244 345 series = []
245 346 if len(days) >= 2:
246 − pts_act = [{"t": d.isoformat(), "v": actives_at(d)} for d in days]
247 347 s_act = {"id": "actives_jour", "title": "Annonces actives par jour",
248 348 "unit": "annonces", "kind": "line", "points": pts_act}
249 − pts_new = [{"t": d.isoformat(), "v": starts.get(d.isoformat(), 0)}
250 − for d in days]
251 349 s_new = {"id": "nouvelles_jour", "title": "Nouvelles annonces par jour",
252 − "unit": "annonces", "kind": "line", "points": pts_new}
350 + "unit": "annonces", "kind": "bar", "points": pts_new}
351 + s_rem = {"id": "retraits_jour", "title": "Annonces retirées par jour",
352 + "unit": "annonces", "kind": "line", "points": pts_rem}
253 353 if prev_ok:
254 354 pdays = _days(p_from, p_to)
255 355 s_act["compare"] = [{"t": d.isoformat(), "v": actives_at(d)}
256 356 for d in pdays]
257 − s_new["compare"] = [{"t": d.isoformat(),
258 − "v": starts.get(d.isoformat(), 0)}
357 + s_rem["compare"] = [{"t": d.isoformat(),
358 + "v": ends.get(d.isoformat(), 0)}
259 359 for d in pdays]
260 − series = [s_act, s_new]
360 + series = [s_act, s_new, s_rem]
361 + if len(pts_rent) >= 2:
362 + series.append({"id": "loyer_entree_jour",
363 + "title": "Loyer moyen des nouvelles annonces par jour",
364 + "unit": "$", "kind": "area", "points": pts_rent})
365 +
366 + # ---- multi-courbes : loyer médian d'entrée par taille -------------------
367 + multiseries = []
368 + if len(days) >= 2:
369 + top_types = [r["t"] for r in con.execute(
370 + _FIRST_PRICE_CTE +
371 + """SELECT l.unit_type t, COUNT(*) n FROM fp
372 + JOIN listings l ON l.uid=fp.uid AND l.dup_of IS NULL
373 + WHERE fp.ts>=? AND fp.ts<? AND l.unit_type<>''
374 + GROUP BY t ORDER BY n DESC LIMIT 4""",
375 + (PRIX_MIN, PRIX_MAX, ts_from, ts_to)).fetchall()]
376 + if top_types:
377 + ph = ",".join("?" * len(top_types))
378 + rows = con.execute(
379 + _FIRST_PRICE_CTE +
380 + f"""SELECT date(fp.ts,'unixepoch','localtime') d,
381 + l.unit_type t, fp.price p FROM fp
382 + JOIN listings l ON l.uid=fp.uid AND l.dup_of IS NULL
383 + WHERE fp.ts>=? AND fp.ts<? AND l.unit_type IN ({ph})""",
384 + (PRIX_MIN, PRIX_MAX, ts_from, ts_to, *top_types)).fetchall()
385 + per: dict[str, dict[str, list[float]]] = {t: {} for t in top_types}
386 + for r in rows:
387 + per[r["t"]].setdefault(r["d"], []).append(r["p"])
388 + # axe commun : jours où chaque taille a au moins 3 observations
389 + common = [d.isoformat() for d in days
390 + if all(len(per[t].get(d.isoformat(), [])) >= 3
391 + for t in top_types)]
392 + if len(common) >= 2:
393 + ms_series = []
394 + for t in top_types:
395 + pts = []
396 + for d in common:
397 + vals = sorted(per[t][d])
398 + pts.append({"t": d, "v": round(vals[len(vals) // 2])})
399 + ms_series.append({"label": t, "points": pts})
400 + multiseries.append({
401 + "id": "loyer_taille",
402 + "title": "Loyer médian des nouvelles annonces par taille",
403 + "unit": "$", "series": ms_series})
404 +
405 + # ---- barres empilées : ajouts par jour et par source --------------------
406 + names = _source_names()
407 + stacked = []
408 + if len(days) >= 2:
409 + src_tot = con.execute(
410 + """SELECT source s, COUNT(*) n FROM listings
411 + WHERE dup_of IS NULL AND first_seen>=? AND first_seen<?
412 + GROUP BY s ORDER BY n DESC""", (ts_from, ts_to)).fetchall()
413 + if src_tot:
414 + top_src = [r["s"] for r in src_tot[:3]]
415 + others = [r["s"] for r in src_tot[3:]]
416 + daily_src: dict[str, dict[str, int]] = {}
417 + for r in con.execute(
418 + """SELECT date(first_seen,'unixepoch','localtime') d,
419 + source s, COUNT(*) n FROM listings
420 + WHERE dup_of IS NULL AND first_seen>=? AND first_seen<?
421 + GROUP BY d, s""", (ts_from, ts_to)):
422 + daily_src.setdefault(r["d"], {})[r["s"]] = r["n"]
423 + keys = [names.get(s, s) for s in top_src] + (
424 + ["Autres"] if others else [])
425 + pts = []
426 + for d in days:
427 + by = daily_src.get(d.isoformat(), {})
428 + vals = [by.get(s, 0) for s in top_src]
429 + if others:
430 + vals.append(sum(by.get(s, 0) for s in others))
431 + pts.append({"t": d.isoformat(), "values": vals})
432 + if any(sum(p["values"]) for p in pts):
433 + stacked.append({"id": "ajouts_source",
434 + "title": "Nouvelles annonces par jour et par source",
435 + "unit": "ajouts", "keys": keys, "points": pts})
261 436
262 437 # ---- répartitions ------------------------------------------------------
263 438 types = [{"label": r["t"] or "Non précisé", "value": r["n"]}
@@ -265,7 +440,6 @@ def _build(con, period: str, from_: str | None, to_: str | None) -> dict:
265 440 "SELECT unit_type t, COUNT(*) n FROM listings"
266 441 " WHERE active=1 AND dup_of IS NULL GROUP BY unit_type"
267 442 " ORDER BY n DESC LIMIT 8")]
268 − names = _source_names()
269 443 by_source = [{"label": names.get(r["s"], r["s"]), "value": r["n"]}
270 444 for r in con.execute(
271 445 "SELECT source s, COUNT(*) n FROM listings"
@@ -282,9 +456,56 @@ def _build(con, period: str, from_: str | None, to_: str | None) -> dict:
282 456 if types:
283 457 breakdowns.append({"id": "types", "title": "Annonces actives par taille",
284 458 "kind": "donut", "items": types})
459 + # nouvelles annonces par taille (période) — deltas vs période précédente
460 + new_types = con.execute(
461 + """SELECT COALESCE(NULLIF(unit_type,''),'Non précisé') t, COUNT(*) n
462 + FROM listings WHERE dup_of IS NULL AND first_seen>=? AND first_seen<?
463 + GROUP BY t ORDER BY n DESC LIMIT 8""", (ts_from, ts_to)).fetchall()
464 + if new_types:
465 + prev_types = {}
466 + if prev_ok:
467 + prev_types = {r["t"]: r["n"] for r in con.execute(
468 + """SELECT COALESCE(NULLIF(unit_type,''),'Non précisé') t,
469 + COUNT(*) n FROM listings
470 + WHERE dup_of IS NULL AND first_seen>=? AND first_seen<?
471 + GROUP BY t""", (pts_prev_from, pts_prev_to))}
472 + items = []
473 + for r in new_types:
474 + it = {"label": r["t"], "value": r["n"]}
475 + if prev_ok:
476 + it["delta_pct"] = _pct(r["n"], prev_types.get(r["t"], 0))
477 + items.append(it)
478 + breakdowns.append({"id": "nouvelles_taille",
479 + "title": "Nouvelles annonces par taille (période)",
480 + "kind": "bars", "items": items})
285 481 if by_source:
286 482 breakdowns.append({"id": "sources", "title": "Top sources (annonces actives)",
287 − "kind": "bar", "items": by_source})
483 + "kind": "bars", "items": by_source})
484 +
485 + # ---- distribution des loyers (annonces actives, tranches de 200 $) ------
486 + distributions = []
487 + bins_rows = con.execute(
488 + """SELECT CAST(price/200 AS INT) b, COUNT(*) n FROM listings
489 + WHERE active=1 AND dup_of IS NULL AND price BETWEEN ? AND ?
490 + GROUP BY b ORDER BY b""", (PRIX_MIN, PRIX_MAX)).fetchall()
491 + if bins_rows:
492 + LO, HI = 2, 16 # < 400 $ … 3 200 $ et +
493 + agg: dict[int, int] = {}
494 + for r in bins_rows:
495 + b = min(max(r["b"], LO - 1), HI)
496 + agg[b] = agg.get(b, 0) + r["n"]
497 + bins = []
498 + for b in sorted(agg):
499 + if b == LO - 1:
500 + lab = f"< {LO * 200} $"
501 + elif b == HI:
502 + lab = f"{_fr_int(HI * 200)} $ +"
503 + else:
504 + lab = f"{_fr_int(b * 200)}–{_fr_int((b + 1) * 200 - 1)} $"
505 + bins.append({"label": lab, "value": agg[b]})
506 + distributions.append({"id": "loyers",
507 + "title": "Distribution des loyers (annonces actives)",
508 + "unit": "annonces", "bins": bins})
288 509
289 510 # ---- géographie --------------------------------------------------------
290 511 geo_items = [{"label": r["c"], "value": r["n"]} for r in con.execute(
@@ -294,43 +515,110 @@ def _build(con, period: str, from_: str | None, to_: str | None) -> dict:
294 515 geo = ({"title": "Top villes (annonces actives)", "items": geo_items}
295 516 if geo_items else None)
296 517
297 − # ---- heatmap (nouvelles annonces par jour, période choisie) ------------
298 − heat_cells = [{"date": d.isoformat(), "value": starts.get(d.isoformat(), 0)}
299 − for d in days if starts.get(d.isoformat())]
300 − heatmap = ({"title": "Nouvelles annonces par jour", "cells": heat_cells}
301 − if heat_cells else None)
518 + # ---- calendrier de chaleur : 26 dernières semaines d'ajouts --------------
519 + heat_from = max(cov_min, today - timedelta(days=181))
520 + heat_cells = [{"date": d, "value": n} for d, n in sorted(starts.items())
521 + if d >= heat_from.isoformat()]
522 + heatmap = ({"title": "Nouvelles annonces par jour (26 dernières semaines)",
523 + "cells": heat_cells} if heat_cells else None)
524 +
525 + # ---- heatmap horaire 7×24 : heure d'observation des ajouts ---------------
526 + hourly = None
527 + hour_rows = con.execute(
528 + """SELECT CAST(strftime('%w', first_seen,'unixepoch','localtime') AS INT) w,
529 + CAST(strftime('%H', first_seen,'unixepoch','localtime') AS INT) h,
530 + COUNT(*) n
531 + FROM listings WHERE dup_of IS NULL AND first_seen>=? AND first_seen<?
532 + GROUP BY w, h""", (ts_from, ts_to)).fetchall()
533 + if hour_rows:
534 + cells = [{"dow": (r["w"] + 6) % 7, "hour": r["h"], "value": r["n"]}
535 + for r in hour_rows] # %w : 0=dim → contrat : 0=lun
536 + hourly = {"title": "Ajouts d'annonces par heure (période)",
537 + "cells": cells}
302 538
303 539 # ---- tableaux ----------------------------------------------------------
304 540 tables = []
305 541 top_villes = con.execute(
306 − """SELECT city, COUNT(*) n, AVG(CASE WHEN price>0 THEN price END) avg_p,
542 + """SELECT city, COUNT(*) n, AVG(CASE WHEN price BETWEEN ? AND ? THEN price END) avg_p,
307 543 SUM(CASE WHEN first_seen>=? AND first_seen<? THEN 1 ELSE 0 END) new_n
308 544 FROM listings WHERE active=1 AND dup_of IS NULL AND city<>''
309 − GROUP BY city ORDER BY n DESC LIMIT 50""", (ts_from, ts_to)).fetchall()
545 + GROUP BY city ORDER BY n DESC LIMIT 50""",
546 + (PRIX_MIN, PRIX_MAX, ts_from, ts_to)).fetchall()
310 547 removed_by_city = {r["city"]: r["n"] for r in con.execute(
311 548 """SELECT city, COUNT(*) n FROM listings
312 549 WHERE active=0 AND dup_of IS NULL AND city<>''
313 550 AND last_seen>=? AND last_seen<? GROUP BY city""",
314 551 (ts_from, ts_to)).fetchall()}
552 +
553 + def _city_median(city: str) -> float | None:
554 + r = con.execute(
555 + "SELECT COUNT(*) n FROM listings WHERE active=1 AND dup_of IS NULL"
556 + " AND city=? AND price BETWEEN ? AND ?",
557 + (city, PRIX_MIN, PRIX_MAX)).fetchone()
558 + if not r["n"]:
559 + return None
560 + return con.execute(
561 + "SELECT price FROM listings WHERE active=1 AND dup_of IS NULL"
562 + " AND city=? AND price BETWEEN ? AND ? ORDER BY price"
563 + " LIMIT 1 OFFSET ?",
564 + (city, PRIX_MIN, PRIX_MAX, r["n"] // 2)).fetchone()["price"]
565 +
566 + city_medians: dict[str, float] = {}
315 567 if top_villes:
316 568 rows = []
317 569 for r in top_villes:
570 + med = _city_median(r["city"])
571 + if med is not None:
572 + city_medians[r["city"]] = med
318 573 net = r["new_n"] - removed_by_city.get(r["city"], 0)
319 574 rows.append([
320 575 r["city"], r["n"],
321 576 _fr_money(r["avg_p"]) if r["avg_p"] else "—",
577 + _fr_money(med) if med is not None else "—",
322 578 r["new_n"], f"{'+' if net >= 0 else ''}{net}"])
323 579 tables.append({"id": "top_villes", "title": "Top villes",
324 580 "columns": ["Ville", "Annonces actives", "Loyer moyen",
325 − "Nouvelles (période)", "Δ net (période)"],
581 + "Loyer médian", "Nouvelles (période)",
582 + "Δ net (période)"],
583 + "rows": rows})
584 +
585 + # loyers par taille de logement (moyenne, médiane, P10–P90)
586 + type_rows = con.execute(
587 + """SELECT COALESCE(NULLIF(unit_type,''),'Non précisé') t, COUNT(*) n,
588 + AVG(price) avg_p FROM listings
589 + WHERE active=1 AND dup_of IS NULL AND price BETWEEN ? AND ?
590 + GROUP BY t ORDER BY n DESC LIMIT 12""",
591 + (PRIX_MIN, PRIX_MAX)).fetchall()
592 + if type_rows:
593 + rows = []
594 + for r in type_rows:
595 + prices = sorted(x["price"] for x in con.execute(
596 + """SELECT price FROM listings WHERE active=1 AND dup_of IS NULL
597 + AND COALESCE(NULLIF(unit_type,''),'Non précisé')=?
598 + AND price BETWEEN ? AND ?""",
599 + (r["t"], PRIX_MIN, PRIX_MAX)))
600 + med = _pctile(prices, 0.5)
601 + p10 = _pctile(prices, 0.10)
602 + p90 = _pctile(prices, 0.90)
603 + rows.append([
604 + r["t"], r["n"], _fr_money(r["avg_p"]),
605 + _fr_money(med) if med is not None else "—",
606 + f"{_fr_money(p10)} – {_fr_money(p90)}"
607 + if p10 is not None and p90 is not None else "—"])
608 + tables.append({"id": "loyers_taille",
609 + "title": "Loyers par taille de logement (actives)",
610 + "columns": ["Taille", "Annonces avec loyer",
611 + "Loyer moyen", "Loyer médian",
612 + "Fourchette P10–P90"],
326 613 "rows": rows})
327 614
328 615 top_srcs = con.execute(
329 − """SELECT source s, COUNT(*) n, AVG(CASE WHEN price>0 THEN price END) avg_p,
616 + """SELECT source s, COUNT(*) n, AVG(CASE WHEN price BETWEEN ? AND ? THEN price END) avg_p,
330 617 SUM(CASE WHEN first_seen>=? AND first_seen<? THEN 1 ELSE 0 END) new_n,
331 618 ROUND(AVG(completeness),0) comp, SUM(published=0) quar
332 619 FROM listings WHERE active=1 AND dup_of IS NULL
333 − GROUP BY source ORDER BY n DESC LIMIT 50""", (ts_from, ts_to)).fetchall()
620 + GROUP BY source ORDER BY n DESC LIMIT 50""",
621 + (PRIX_MIN, PRIX_MAX, ts_from, ts_to)).fetchall()
334 622 last_sync = {r["source"]: r["ts"] for r in con.execute(
335 623 "SELECT source, MAX(ts) ts FROM sync_log WHERE ok=1 GROUP BY source")}
336 624 if top_srcs:
@@ -370,6 +658,36 @@ def _build(con, period: str, from_: str | None, to_: str | None) -> dict:
370 658 f"{'+' if r['dev'] >= 0 else ''}{r['dev']} %",
371 659 r["sous"] or 0] for r in fv_villes]})
372 660
661 + # baisses de loyer observées dans la période (journal de prix, plausibles)
662 + drops = con.execute(
663 + """SELECT a.uid uid, MAX(a.price-b.price) dp, a.price p0, b.price p1,
664 + b.ts ts1
665 + FROM price_log a JOIN price_log b
666 + ON a.uid=b.uid AND b.ts>a.ts
667 + AND a.price BETWEEN ? AND ? AND b.price BETWEEN ? AND ?
668 + AND b.price<a.price AND b.price>=a.price*0.5
669 + WHERE a.ts>=? AND b.ts<?
670 + GROUP BY a.uid ORDER BY dp DESC LIMIT 15""",
671 + (PRIX_MIN, PRIX_MAX, PRIX_MIN, PRIX_MAX, ts_from, ts_to)).fetchall()
672 + if drops:
673 + rows = []
674 + for r in drops:
675 + li = con.execute(
676 + "SELECT city, unit_type FROM listings WHERE uid=?",
677 + (r["uid"],)).fetchone()
678 + what = " · ".join(x for x in [li["unit_type"], li["city"]]
679 + if x) if li else r["uid"]
680 + rows.append([
681 + what or r["uid"], _fr_money(r["p0"]), _fr_money(r["p1"]),
682 + f"−{_fr_money(r['dp'])}",
683 + f"{round(100.0 * r['dp'] / r['p0'], 1)} %",
684 + datetime.fromtimestamp(r["ts1"], TZ).date().isoformat()])
685 + tables.append({"id": "baisses_loyer",
686 + "title": "Plus fortes baisses de loyer (période)",
687 + "columns": ["Logement", "Ancien loyer", "Nouveau loyer",
688 + "Baisse", "Baisse %", "Observée le"],
689 + "rows": rows})
690 +
373 691 # ---- records & faits marquants -----------------------------------------
374 692 records = []
375 693 in_period = {d: n for d, n in starts.items()
@@ -377,42 +695,72 @@ def _build(con, period: str, from_: str | None, to_: str | None) -> dict:
377 695 if in_period:
378 696 best = max(in_period, key=in_period.get)
379 697 records.append({"label": "Jour record d'ajouts",
380 − "value": f"{in_period[best]:,}".replace(",", " ") + " annonces",
698 + "value": _fr_int(in_period[best]) + " annonces",
381 699 "date": best})
382 700 rem_period = {d: n for d, n in ends.items()
383 701 if d_from.isoformat() <= d <= d_to.isoformat()}
384 702 if rem_period:
385 703 worst = max(rem_period, key=rem_period.get)
386 704 records.append({"label": "Jour record de retraits",
387 − "value": f"{rem_period[worst]:,}".replace(",", " ") + " annonces",
705 + "value": _fr_int(rem_period[worst]) + " annonces",
388 706 "date": worst})
389 707 if top_villes:
390 708 ville = max(top_villes, key=lambda r: r["new_n"])
391 709 if ville["new_n"]:
392 710 records.append({"label": "Ville la plus dynamique (nouvelles annonces)",
393 711 "value": f"{ville['city']} — {ville['new_n']}"})
712 + # villes la plus chère / la plus abordable (loyer médian, volume suffisant)
713 + big_meds = {c: m for c, m in city_medians.items()
714 + if next((r["n"] for r in top_villes if r["city"] == c), 0) >= 100}
715 + if big_meds:
716 + chere = max(big_meds, key=big_meds.get)
717 + abordable = min(big_meds, key=big_meds.get)
718 + records.append({"label": "Ville la plus chère (loyer médian, ≥ 100 annonces)",
719 + "value": f"{chere} — {_fr_money(big_meds[chere])}"})
720 + if abordable != chere:
721 + records.append({"label": "Ville la plus abordable (loyer médian, ≥ 100 annonces)",
722 + "value": f"{abordable} — {_fr_money(big_meds[abordable])}"})
723 + if types and types[0]["label"] != "Non précisé":
724 + records.append({"label": "Taille la plus offerte",
725 + "value": f"{types[0]['label']} — "
726 + f"{_fr_int(types[0]['value'])} annonces"})
394 727 # plus forte baisse de loyer observée dans la période (journal de prix)
395 − # bornes de plausibilité (loyers résidentiels) : les écarts extrêmes sont
396 − # presque toujours des erreurs de lecture à la source, pas des baisses.
397 − drop = con.execute(
398 − """SELECT a.uid uid, a.price p0, b.price p1, b.ts ts1
728 + if drops:
729 + d0 = drops[0]
730 + li = con.execute("SELECT city, unit_type FROM listings WHERE uid=?",
731 + (d0["uid"],)).fetchone()
732 + where = " · ".join(x for x in [li["unit_type"], li["city"]] if x) if li else ""
733 + records.append({
734 + "label": "Plus forte baisse de loyer observée"
735 + + (f" ({where})" if where else ""),
736 + "value": f"−{_fr_money(d0['dp'])}"
737 + f" ({_fr_money(d0['p0'])} → {_fr_money(d0['p1'])})",
738 + "date": datetime.fromtimestamp(d0["ts1"], TZ).date().isoformat()})
739 + # plus forte hausse de loyer observée (plausible : ≤ ×2)
740 + hike = con.execute(
741 + """SELECT a.uid uid, MAX(b.price-a.price) dp, a.price p0, b.price p1,
742 + b.ts ts1
399 743 FROM price_log a JOIN price_log b
400 744 ON a.uid=b.uid AND b.ts>a.ts
401 − AND a.price BETWEEN 300 AND 15000
402 − AND b.price BETWEEN 300 AND 15000
403 − AND b.price<a.price AND b.price>=a.price*0.5
404 − WHERE a.ts>=? AND b.ts<? ORDER BY (a.price-b.price) DESC LIMIT 1""",
405 − (ts_from, ts_to)).fetchone()
406 − if drop:
745 + AND a.price BETWEEN ? AND ? AND b.price BETWEEN ? AND ?
746 + AND b.price>a.price AND b.price<=a.price*2
747 + WHERE a.ts>=? AND b.ts<? LIMIT 1""",
748 + (PRIX_MIN, PRIX_MAX, PRIX_MIN, PRIX_MAX, ts_from, ts_to)).fetchone()
749 + if hike and hike["dp"]:
407 750 li = con.execute("SELECT city, unit_type FROM listings WHERE uid=?",
408 − (drop["uid"],)).fetchone()
751 + (hike["uid"],)).fetchone()
409 752 where = " · ".join(x for x in [li["unit_type"], li["city"]] if x) if li else ""
410 753 records.append({
411 − "label": "Plus forte baisse de loyer observée"
754 + "label": "Plus forte hausse de loyer observée"
412 755 + (f" ({where})" if where else ""),
413 − "value": f"−{_fr_money(drop['p0'] - drop['p1'])}"
414 − f" ({_fr_money(drop['p0'])} → {_fr_money(drop['p1'])})",
415 − "date": datetime.fromtimestamp(drop["ts1"], TZ).date().isoformat()})
756 + "value": f"+{_fr_money(hike['dp'])}"
757 + f" ({_fr_money(hike['p0'])} → {_fr_money(hike['p1'])})",
758 + "date": datetime.fromtimestamp(hike["ts1"], TZ).date().isoformat()})
759 + if hourly:
760 + peak = max(hourly["cells"], key=lambda c: c["value"])
761 + records.append({"label": "Heure de pointe des ajouts (période)",
762 + "value": f"{DOW_FR[peak['dow']]} {peak['hour']} h — "
763 + f"{_fr_int(peak['value'])} annonces"})
416 764 if top_srcs:
417 765 src = max(top_srcs, key=lambda r: r["new_n"])
418 766 if src["new_n"]:
@@ -429,8 +777,18 @@ def _build(con, period: str, from_: str | None, to_: str | None) -> dict:
429 777 "tables": tables,
430 778 "records": records,
431 779 }
780 + if gauges:
781 + out["gauges"] = gauges
782 + if multiseries:
783 + out["multiseries"] = multiseries
784 + if stacked:
785 + out["stacked"] = stacked
786 + if distributions:
787 + out["distributions"] = distributions
432 788 if geo:
433 789 out["geo"] = geo
434 790 if heatmap:
435 791 out["heatmap"] = heatmap
792 + if hourly:
793 + out["hourly"] = hourly
436 794 return out
modified louka/web.py +6 −5
@@ -710,20 +710,21 @@ def stats_report(period: str = "30j",
710 710 from_: str | None = Query(None, alias="from"),
711 711 to: str | None = None,
712 712 mode: str = "complet"):
713 − """Rapport statistique PDF estampillé Groupe-KA (complet ou synthèse)."""
713 + """Rapport statistique PDF estampillé Groupe-KA — 5 modes :
714 + complet | synthese | tendances | repartitions | donnees (inconnu → complet)."""
714 715 from fastapi.responses import Response
715 716 from . import kapdf, statsdash
716 717 if period not in _PERIODES_VALIDES:
717 718 period = "perso" if (from_ and to) else "30j"
719 + if mode not in kapdf.REPORT_MODES:
720 + mode = "complet"
718 721 dash = statsdash.compute(period if period != "perso" else "30j",
719 722 from_, to)
720 723 eco = json.loads((ROOT / "frontend" / "src" / "ka" /
721 724 "ecosystem.json").read_text(encoding="utf-8"))
722 725 site = next(s for s in eco["sites"] if s["id"] == "lou-ka")
723 − data = kapdf.GroupeKAReport(
724 − site=site, dashboard=dash,
725 − mode=mode if mode in ("complet", "synthese") else "complet").build()
726 − fname = kapdf.filename("lou-ka", period)
726 + data = kapdf.GroupeKAReport(site=site, dashboard=dash, mode=mode).build()
727 + fname = kapdf.filename("lou-ka", period, mode)
727 728 return Response(content=data, media_type="application/pdf",
728 729 headers={"Content-Disposition":
729 730 f'attachment; filename="{fname}"'})
730 731