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%

Page /stats refaite en tableau de bord analytique + rapport PDF Groupe-KA

- louka/statsdash.py : GET /api/stats/dashboard (contrat ka-stats SPEC.md) —
  KPI avec deltas vs période précédente, séries actives/nouvelles par jour
  (reconstruites de first_seen/last_seen), répartitions taille/source, top
  villes, heatmap, tableaux villes & gestionnaires, records auto-générés ;
  requêtes SQL agrégées + cache mémoire 5 min par période.
- louka/kapdf.py (moteur PDF commun fpdf2) + GET /api/stats/report :
  rapport estampillé Groupe-KA (couverture Lou·Ka, sommaire, graphiques
  vectoriels, tableaux zébrés, records, page contact), modes complet/synthèse,
  nom de fichier normalisé groupe-ka_lou-ka_stats_<periode>_<date>.pdf.
- frontend : pages/Stats.tsx réécrite sur le kit ka/stats/kacharts.tsx
  (KpiCard, PeriodSelector, LineChart N-1, Donut, BarChart, CalendarHeatmap,
  DataTable, RecordCard, PdfButton, Fraicheur) — responsive 360/768/1440,
  états vides propres quand la donnée n existe pas.

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

8 changed files +2,177 −390

added frontend/src/ka/stats/SPEC.md +123 −0
@@ -0,0 +1,123 @@
1 +# ka-stats — module Stats commun Groupe KA (spec v1)
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.
6 +
7 +## 1. Page /stats — structure obligatoire (dans cet ordre)
8 +
9 +1. **Bandeau KPI** : 4–6 grandes cartes (`KpiCard`) — valeur, libellé,
10 + variation vs période précédente (▲/▼ + %, vert `--green` / rouge `--danger`).
11 +2. **Sélecteur de période global** (`PeriodSelector`) : `aujourd'hui · 7 j ·
12 + 30 j · 3 m · 6 m · 12 m · année en cours · tout` + plage personnalisée
13 + (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 + 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.
28 +
29 +Responsive : KPI empilés < 768 px, graphiques pleine largeur redimensionnés
30 +(SVG viewBox), tableaux en défilement horizontal contenu, tactile ≥ 44 px.
31 +AUCUNE donnée inventée : une stat indisponible = bloc « Pas encore mesuré »
32 +(carte grise propre), jamais un faux chiffre.
33 +
34 +## 2. API — contrat commun
35 +
36 +`GET /api/stats/dashboard?period=7j|30j|3m|6m|12m|annee|tout|auj&from=YYYY-MM-DD&to=YYYY-MM-DD`
37 +
38 +```jsonc
39 +{
40 + "updated": "2026-08-17T21:04:00-04:00",
41 + "period": { "from": "2026-07-18", "to": "2026-08-17", "label": "30 jours" },
42 + "kpis": [ { "id": "total", "label": "Annonces actives", "value": 33744,
43 + "unit": "", "delta_pct": 4.2, "direction": "up" } ],
44 + "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 }] } ],
49 + "geo": { "title": "Par région", "items": [{ "label": "Montréal", "value": 15680 }] },
50 + "heatmap": { "title": "Activité", "cells": [{ "date": "2026-08-01", "value": 210 }] },
51 + "tables": [ { "id": "top", "title": "Top villes", "columns": ["Ville", "Annonces", "Δ 30 j"],
52 + "rows": [["Montréal", 15680, "+3,1 %"]] } ],
53 + "records": [ { "label": "Jour record d'ajouts", "value": "412 annonces", "date": "2026-08-09" } ]
54 +}
55 +```
56 +
57 +Champs absents = section masquée. Cache serveur recommandé (≥ 5 min par
58 +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…).
60 +
61 +`GET /api/stats/report?period=…&from=&to=&mode=complet|synthese`
62 +→ `application/pdf`, en-tête `Content-Disposition: attachment; filename=
63 +groupe-ka_<plateforme>_stats_<periode>_<YYYY-MM-DD>.pdf`.
64 +
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)
67 +
68 +- **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
71 + « 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é).
74 +- **Graphiques VECTORIELS** (dessinés en primitives, jamais de capture) :
75 + courbes, barres, anneaux — accent de la plateforme, axes/graduations encre.
76 +- **Tableaux** paginés proprement (lignes zébrées `--surface-2`, jamais
77 + coupés en deux à cheval sur une ligne).
78 +- **Records** puis **page de fin** : coordonnées Groupe KA (3 courriels +
79 + rôles d'ecosystem.json, groupe-ka.com), avertissement d'agrégateur,
80 + mentions légales courtes.
81 +- **Chaque page** : en-tête discret (« Groupe KA · {Plateforme} », filet
82 + encre) + pied (« © Groupe-KA — {année} — groupe-ka.com · {période} · p. X/Y »).
83 +- 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.
85 +
86 +## 4. Spécifique par plateforme (sections métier attendues)
87 +
88 +- **groupe-ka** : tableau de bord maître — consolidation des 12 (volume total,
89 + croissance), classement des plateformes, bloc résumé par plateforme + lien
90 + vers sa page /stats ; « Rapport écosystème complet » = PDF consolidé.
91 +- **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é.
95 +- **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.
105 +- **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.
117 +
118 +## 5. Ajouter une métrique / un graphique / une plateforme
119 +
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.
added frontend/src/ka/stats/kacharts.tsx +389 −0
@@ -0,0 +1,389 @@
1 +// Auteur : Simon-Pierre Boucher — contact@spboucher.ai
2 +// ka-ui/stats/kacharts.tsx — kit de graphiques SVG du module Stats commun
3 +// Groupe KA (zéro dépendance, React 18+). Style : design system ka-ui
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";
9 +
10 +/* ---------- types (contrat SPEC.md) ---------- */
11 +export type Kpi = {
12 + id: string; label: string; value: number | string; unit?: string;
13 + delta_pct?: number | null; direction?: "up" | "down";
14 +};
15 +export type Point = { t: string; v: number };
16 +export type Serie = {
17 + id: string; title: string; unit?: string; kind?: "line" | "bar";
18 + points: Point[]; compare?: Point[];
19 +};
20 +export type BreakItem = { label: string; value: number };
21 +export type TableSpec = { id: string; title: string; columns: string[]; rows: (string | number)[][] };
22 +export type RecordFact = { label: string; value: string; date?: string };
23 +
24 +export const PERIODS: { id: string; label: string }[] = [
25 + { id: "auj", label: "Aujourd'hui" },
26 + { id: "7j", label: "7 jours" },
27 + { id: "30j", label: "30 jours" },
28 + { id: "3m", label: "3 mois" },
29 + { id: "6m", label: "6 mois" },
30 + { id: "12m", label: "12 mois" },
31 + { id: "annee", label: "Année en cours" },
32 + { id: "tout", label: "Tout" },
33 +];
34 +
35 +export const fmtInt = (n: number) => n.toLocaleString("fr-CA");
36 +export const fmtNum = (n: number) =>
37 + Number.isInteger(n) ? fmtInt(n) : n.toLocaleString("fr-CA", { maximumFractionDigits: 2 });
38 +
39 +/* ---------- KPI ---------- */
40 +export function KpiCard({ k }: { k: Kpi }) {
41 + const up = (k.direction ?? ((k.delta_pct ?? 0) >= 0 ? "up" : "down")) === "up";
42 + return (
43 + <article className="card" style={{ padding: "14px 16px", minWidth: 0 }}>
44 + <p style={{ margin: 0, fontFamily: "var(--font-display)", fontWeight: 700, fontSize: "clamp(22px,2.4vw,30px)", letterSpacing: "-0.02em" }}>
45 + {typeof k.value === "number" ? fmtNum(k.value) : k.value}
46 + {k.unit ? <span style={{ fontSize: "0.6em", color: "var(--ink-2)" }}> {k.unit}</span> : null}
47 + </p>
48 + <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 + )}
54 + </article>
55 + );
56 +}
57 +
58 +/* ---------- Sélecteur de période ---------- */
59 +export function PeriodSelector({
60 + value, onChange, custom, onCustom,
61 +}: {
62 + value: string; onChange: (p: string) => void;
63 + custom?: { from: string; to: string }; onCustom?: (from: string, to: string) => void;
64 +}) {
65 + return (
66 + <div style={{ display: "flex", flexWrap: "wrap", gap: 8, alignItems: "center" }}>
67 + {PERIODS.map((p) => (
68 + <button key={p.id} type="button" onClick={() => onChange(p.id)}
69 + className="chip" aria-pressed={value === p.id}
70 + style={{ cursor: "pointer", minHeight: 44, background: value === p.id ? "var(--accent)" : "var(--surface)", color: value === p.id ? "var(--on-accent)" : "var(--ink)" }}>
71 + {p.label}
72 + </button>
73 + ))}
74 + {onCustom && (
75 + <span style={{ display: "inline-flex", gap: 6, alignItems: "center" }}>
76 + <input className="input" type="date" style={{ width: 150 }} value={custom?.from ?? ""} aria-label="Du"
77 + onChange={(e) => onCustom(e.target.value, custom?.to ?? "")} />
78 + <span className="klabel">au</span>
79 + <input className="input" type="date" style={{ width: 150 }} value={custom?.to ?? ""} aria-label="Au"
80 + onChange={(e) => onCustom(custom?.from ?? "", e.target.value)} />
81 + </span>
82 + )}
83 + </div>
84 + );
85 +}
86 +
87 +/* ---------- Courbe ---------- */
88 +export function LineChart({ serie, height = 240 }: { serie: Serie; height?: number }) {
89 + const [hide, setHide] = useState<{ cur: boolean; cmp: boolean }>({ cur: false, cmp: false });
90 + const [hover, setHover] = useState<number | null>(null);
91 + const W = 720, H = height, PL = 54, PR = 10, PT = 14, PB = 26;
92 + const pts = serie.points ?? [];
93 + if (pts.length < 2) return <EmptyBlock title={serie.title} />;
94 + const all = [...(hide.cur ? [] : pts), ...(!hide.cmp && serie.compare ? serie.compare : [])];
95 + const vmax = Math.max(...all.map((p) => p.v), 1);
96 + const vmin = Math.min(0, ...all.map((p) => p.v));
97 + const X = (i: number, n: number) => PL + ((W - PL - PR) * i) / (n - 1);
98 + const Y = (v: number) => PT + (H - PT - PB) * (1 - (v - vmin) / (vmax - vmin || 1));
99 + const path = (s: Point[]) => s.map((p, i) => `${i ? "L" : "M"}${X(i, s.length)},${Y(p.v)}`).join("");
100 + const hi = hover !== null ? Math.min(pts.length - 1, Math.max(0, hover)) : null;
101 + return (
102 + <figure className="card" style={{ margin: 0, padding: 16 }}>
103 + <figcaption style={{ display: "flex", justifyContent: "space-between", flexWrap: "wrap", gap: 8 }}>
104 + <b style={{ fontFamily: "var(--font-display)", fontSize: 15 }}>{serie.title}</b>
105 + <span style={{ display: "flex", gap: 10 }}>
106 + <LegendChip label="Période courante" color="var(--accent)" off={hide.cur} onClick={() => setHide((h) => ({ ...h, cur: !h.cur }))} />
107 + {serie.compare && <LegendChip label="Période comparée" color="var(--ink-3)" dashed off={hide.cmp} onClick={() => setHide((h) => ({ ...h, cmp: !h.cmp }))} />}
108 + </span>
109 + </figcaption>
110 + <svg viewBox={`0 0 ${W} ${H}`} style={{ width: "100%", height: "auto", marginTop: 10, touchAction: "pan-y" }} role="img" aria-label={serie.title}
111 + onMouseMove={(e) => {
112 + const r = (e.currentTarget as SVGSVGElement).getBoundingClientRect();
113 + const fx = ((e.clientX - r.left) / r.width) * W;
114 + setHover(Math.round(((fx - PL) / (W - PL - PR)) * (pts.length - 1)));
115 + }}
116 + onMouseLeave={() => setHover(null)}>
117 + {[0, 1, 2, 3, 4].map((g) => {
118 + const y = PT + ((H - PT - PB) * g) / 4;
119 + const v = vmax - ((vmax - vmin) * g) / 4;
120 + return (
121 + <g key={g}>
122 + <line x1={PL} x2={W - PR} y1={y} y2={y} stroke="var(--line)" strokeWidth={1} />
123 + <text x={PL - 6} y={y + 3} textAnchor="end" fontSize={10} fill="var(--ink-3)" fontFamily="var(--font-mono)">{fmtInt(Math.round(v))}</text>
124 + </g>
125 + );
126 + })}
127 + {[0, Math.floor(pts.length / 2), pts.length - 1].map((i) => (
128 + <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 + ))}
130 + {!hide.cmp && serie.compare && serie.compare.length > 1 && (
131 + <path d={path(serie.compare)} fill="none" stroke="var(--ink-3)" strokeWidth={1.4} strokeDasharray="4 4" />
132 + )}
133 + {!hide.cur && <path d={path(pts)} fill="none" stroke="var(--accent)" strokeWidth={2.4} />}
134 + {hi !== null && (
135 + <g>
136 + <line x1={X(hi, pts.length)} x2={X(hi, pts.length)} y1={PT} y2={H - PB} stroke="var(--ink)" strokeWidth={1} strokeDasharray="2 3" />
137 + <circle cx={X(hi, pts.length)} cy={Y(pts[hi].v)} r={4} fill="var(--accent)" stroke="var(--ink)" strokeWidth={1.5} />
138 + </g>
139 + )}
140 + </svg>
141 + {hi !== null && (
142 + <p className="chip" style={{ marginTop: 8 }}>
143 + {pts[hi].t} — <b>{fmtNum(pts[hi].v)}{serie.unit ? ` ${serie.unit}` : ""}</b>
144 + {serie.compare?.[hi] && !hide.cmp ? <span style={{ color: "var(--ink-3)" }}> · N-1 : {fmtNum(serie.compare[hi].v)}</span> : null}
145 + </p>
146 + )}
147 + </figure>
148 + );
149 +}
150 +
151 +function LegendChip({ label, color, off, dashed, onClick }: { label: string; color: string; off: boolean; dashed?: boolean; onClick: () => void }) {
152 + 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 }}>
155 + <span style={{ width: 18, height: 0, borderTop: `3px ${dashed ? "dashed" : "solid"} ${color}` }} />
156 + {label}
157 + </button>
158 + );
159 +}
160 +
161 +/* ---------- Barres horizontales (répartitions, géo) ---------- */
162 +export function BarChart({ title, items, unit }: { title: string; items: BreakItem[]; unit?: string }) {
163 + const rows = (items ?? []).slice(0, 14);
164 + if (!rows.length) return <EmptyBlock title={title} />;
165 + const max = Math.max(...rows.map((r) => r.value), 1);
166 + return (
167 + <figure className="card" style={{ margin: 0, padding: 16 }}>
168 + <figcaption><b style={{ fontFamily: "var(--font-display)", fontSize: 15 }}>{title}</b></figcaption>
169 + <div style={{ marginTop: 12, display: "grid", gap: 9 }}>
170 + {rows.map((r) => (
171 + <div key={r.label} title={`${r.label} — ${fmtNum(r.value)}${unit ? ` ${unit}` : ""}`}>
172 + <div style={{ display: "flex", justifyContent: "space-between", fontSize: 12.5 }}>
173 + <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>
175 + </div>
176 + <div style={{ marginTop: 3, height: 12, background: "rgba(20,24,20,0.06)", borderRadius: "0 3px 3px 0" }}>
177 + <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" }} />
178 + </div>
179 + </div>
180 + ))}
181 + </div>
182 + </figure>
183 + );
184 +}
185 +
186 +/* ---------- Anneau ---------- */
187 +export function Donut({ title, items }: { title: string; items: BreakItem[] }) {
188 + const rows = (items ?? []).filter((i) => i.value > 0).slice(0, 8);
189 + const total = rows.reduce((s, r) => s + r.value, 0);
190 + if (!total) return <EmptyBlock title={title} />;
191 + const R = 74, C = 2 * Math.PI * R;
192 + let acc = 0;
193 + const shades = [1, 0.78, 0.58, 0.42, 0.3, 0.22, 0.15, 0.1];
194 + return (
195 + <figure className="card" style={{ margin: 0, padding: 16 }}>
196 + <figcaption><b style={{ fontFamily: "var(--font-display)", fontSize: 15 }}>{title}</b></figcaption>
197 + <div style={{ display: "flex", flexWrap: "wrap", gap: 18, alignItems: "center", marginTop: 12 }}>
198 + <svg viewBox="0 0 200 200" style={{ width: 180, maxWidth: "100%" }} role="img" aria-label={title}>
199 + {rows.map((r, i) => {
200 + const frac = r.value / total;
201 + const off = acc; acc += frac;
202 + return (
203 + <circle key={r.label} cx={100} cy={100} r={R} fill="none"
204 + stroke="var(--accent)" strokeOpacity={shades[i % shades.length]}
205 + strokeWidth={30} strokeDasharray={`${frac * C} ${C}`} strokeDashoffset={-off * C}
206 + transform="rotate(-90 100 100)">
207 + <title>{`${r.label} — ${fmtNum(r.value)} (${((100 * r.value) / total).toFixed(1)} %)`}</title>
208 + </circle>
209 + );
210 + })}
211 + <circle cx={100} cy={100} r={R} fill="none" stroke="var(--ink)" strokeWidth={1} opacity={0.5} />
212 + </svg>
213 + <ul style={{ listStyle: "none", margin: 0, padding: 0, display: "grid", gap: 6, minWidth: 200, flex: 1 }}>
214 + {rows.map((r, i) => (
215 + <li key={r.label} style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 12.5 }}>
216 + <span style={{ width: 11, height: 11, borderRadius: 3, border: "1px solid var(--ink)", background: "var(--accent)", opacity: shades[i % shades.length] }} />
217 + <span style={{ flex: 1, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{r.label}</span>
218 + <b style={{ fontFamily: "var(--font-mono)", fontSize: 11 }}>{((100 * r.value) / total).toFixed(1)} %</b>
219 + </li>
220 + ))}
221 + </ul>
222 + </div>
223 + </figure>
224 + );
225 +}
226 +
227 +/* ---------- Calendrier de chaleur ---------- */
228 +export function CalendarHeatmap({ title, cells }: { title: string; cells: { date: string; value: number }[] }) {
229 + if (!cells?.length) return <EmptyBlock title={title} />;
230 + const byDate = new Map(cells.map((c) => [c.date, c.value]));
231 + const dates = cells.map((c) => c.date).sort();
232 + const end = new Date(dates[dates.length - 1] + "T12:00:00");
233 + const max = Math.max(...cells.map((c) => c.value), 1);
234 + const weeks = 26, cols: { date: string; v: number }[][] = [];
235 + const cur = new Date(end);
236 + cur.setDate(cur.getDate() - (weeks * 7 - 1));
237 + for (let w = 0; w < weeks; w++) {
238 + const col: { date: string; v: number }[] = [];
239 + for (let d = 0; d < 7; d++) {
240 + const iso = cur.toISOString().slice(0, 10);
241 + col.push({ date: iso, v: byDate.get(iso) ?? 0 });
242 + cur.setDate(cur.getDate() + 1);
243 + }
244 + cols.push(col);
245 + }
246 + return (
247 + <figure className="card" style={{ margin: 0, padding: 16 }}>
248 + <figcaption><b style={{ fontFamily: "var(--font-display)", fontSize: 15 }}>{title}</b> <span className="klabel">26 dernières semaines</span></figcaption>
249 + <div className="tbl-wrap" style={{ marginTop: 12 }}>
250 + <svg viewBox={`0 0 ${weeks * 14} ${7 * 14}`} style={{ minWidth: 480, width: "100%", height: "auto" }} role="img" aria-label={title}>
251 + {cols.map((col, w) => col.map((c, d) => (
252 + <rect key={c.date} x={w * 14} y={d * 14} width={12} height={12} rx={2.5}
253 + fill={c.v ? "var(--accent)" : "rgba(20,24,20,0.07)"} fillOpacity={c.v ? 0.25 + 0.75 * (c.v / max) : 1}
254 + stroke="rgba(20,24,20,0.15)" strokeWidth={0.5}>
255 + <title>{`${c.date} — ${fmtNum(c.v)}`}</title>
256 + </rect>
257 + )))}
258 + </svg>
259 + </div>
260 + </figure>
261 + );
262 +}
263 +
264 +/* ---------- Tableau : tri, recherche, pagination ---------- */
265 +export function DataTable({ spec, pageSize = 25 }: { spec: TableSpec; pageSize?: number }) {
266 + const [q, setQ] = useState("");
267 + const [sort, setSort] = useState<{ col: number; dir: 1 | -1 } | null>(null);
268 + const [page, setPage] = useState(0);
269 + const rows = useMemo(() => {
270 + let r = spec.rows ?? [];
271 + if (q) r = r.filter((row) => row.some((c) => String(c).toLowerCase().includes(q.toLowerCase())));
272 + if (sort) r = [...r].sort((a, b) => {
273 + const x = a[sort.col], y = b[sort.col];
274 + const nx = typeof x === "number" ? x : parseFloat(String(x).replace(/[^\d.,-]/g, "").replace(",", "."));
275 + const ny = typeof y === "number" ? y : parseFloat(String(y).replace(/[^\d.,-]/g, "").replace(",", "."));
276 + if (!Number.isNaN(nx) && !Number.isNaN(ny)) return (nx - ny) * sort.dir;
277 + return String(x).localeCompare(String(y), "fr") * sort.dir;
278 + });
279 + return r;
280 + }, [spec.rows, q, sort]);
281 + const pages = Math.max(1, Math.ceil(rows.length / pageSize));
282 + const cur = Math.min(page, pages - 1);
283 + return (
284 + <section className="card" style={{ padding: 16 }}>
285 + <div style={{ display: "flex", flexWrap: "wrap", gap: 10, justifyContent: "space-between", alignItems: "center" }}>
286 + <b style={{ fontFamily: "var(--font-display)", fontSize: 15 }}>{spec.title}</b>
287 + <input className="input" style={{ maxWidth: 240 }} placeholder="Rechercher…" value={q}
288 + onChange={(e) => { setQ(e.target.value); setPage(0); }} aria-label={`Rechercher dans ${spec.title}`} />
289 + </div>
290 + <div className="tbl-wrap" style={{ marginTop: 10 }}>
291 + <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 13 }}>
292 + <thead>
293 + <tr>
294 + {spec.columns.map((c, i) => (
295 + <th key={c} onClick={() => setSort((s) => ({ col: i, dir: s?.col === i && s.dir === 1 ? -1 : 1 }))}
296 + style={{ cursor: "pointer", textAlign: "left", padding: "8px 10px", background: "var(--ink)", color: "var(--paper)", fontFamily: "var(--font-mono)", fontSize: 10.5, textTransform: "uppercase", letterSpacing: "0.06em", whiteSpace: "nowrap", userSelect: "none" }}
297 + aria-sort={sort?.col === i ? (sort.dir === 1 ? "ascending" : "descending") : "none"}>
298 + {c} {sort?.col === i ? (sort.dir === 1 ? "▲" : "▼") : "↕"}
299 + </th>
300 + ))}
301 + </tr>
302 + </thead>
303 + <tbody>
304 + {rows.slice(cur * pageSize, (cur + 1) * pageSize).map((row, ri) => (
305 + <tr key={ri} style={{ background: ri % 2 ? "var(--surface-2)" : "var(--surface)" }}>
306 + {row.map((c, ci) => (
307 + <td key={ci} style={{ padding: "7px 10px", borderBottom: "1px solid var(--line)", whiteSpace: "nowrap" }}>
308 + {typeof c === "number" ? fmtNum(c) : c}
309 + </td>
310 + ))}
311 + </tr>
312 + ))}
313 + </tbody>
314 + </table>
315 + </div>
316 + <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginTop: 10, flexWrap: "wrap", gap: 8 }}>
317 + <span className="klabel">{fmtInt(rows.length)} lignes</span>
318 + <span style={{ display: "flex", gap: 6 }}>
319 + <button type="button" className="btn btn-ghost" disabled={cur === 0} onClick={() => setPage(cur - 1)}>←</button>
320 + <span className="chip">{cur + 1} / {pages}</span>
321 + <button type="button" className="btn btn-ghost" disabled={cur >= pages - 1} onClick={() => setPage(cur + 1)}>→</button>
322 + </span>
323 + </div>
324 + </section>
325 + );
326 +}
327 +
328 +/* ---------- Records / faits marquants ---------- */
329 +export function RecordCard({ r }: { r: RecordFact }) {
330 + return (
331 + <article className="card" style={{ padding: "12px 16px", display: "flex", justifyContent: "space-between", gap: 12, alignItems: "baseline", background: "var(--surface-2)" }}>
332 + <span style={{ fontSize: 13, color: "var(--ink-2)" }}>{r.label}</span>
333 + <span style={{ textAlign: "right" }}>
334 + <b style={{ fontFamily: "var(--font-display)", fontSize: 15 }}>{r.value}</b>
335 + {r.date && <span className="klabel" style={{ display: "block" }}>{r.date}</span>}
336 + </span>
337 + </article>
338 + );
339 +}
340 +
341 +/* ---------- Bouton PDF ---------- */
342 +export function PdfButton({ period, from, to, endpoint = "/api/stats/report" }: { period: string; from?: string; to?: string; endpoint?: string }) {
343 + const [busy, setBusy] = useState(false);
344 + const url = (mode: string) => {
345 + const p = new URLSearchParams({ period, mode });
346 + if (from) p.set("from", from);
347 + if (to) p.set("to", to);
348 + return `${endpoint}?${p}`;
349 + };
350 + const dl = (mode: string) => {
351 + setBusy(true);
352 + const a = document.createElement("a");
353 + a.href = url(mode);
354 + a.download = "";
355 + document.body.appendChild(a);
356 + a.click();
357 + a.remove();
358 + setTimeout(() => setBusy(false), 2500);
359 + };
360 + 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"}
364 + </button>
365 + <button type="button" className="btn btn-ghost" onClick={() => dl("synthese")} disabled={busy}>
366 + Synthèse (2 p.)
367 + </button>
368 + </span>
369 + );
370 +}
371 +
372 +/* ---------- États ---------- */
373 +export function EmptyBlock({ title }: { title: string }) {
374 + return (
375 + <div className="card" style={{ padding: 20, background: "var(--surface-2)", borderStyle: "dashed" }}>
376 + <b style={{ fontFamily: "var(--font-display)", fontSize: 14 }}>{title}</b>
377 + <p className="klabel" style={{ margin: "6px 0 0" }}>Pas encore mesuré — aucune donnée disponible pour cette période.</p>
378 + </div>
379 + );
380 +}
381 +
382 +export function Fraicheur({ updated, onRefresh }: { updated: string; onRefresh: () => void }) {
383 + return (
384 + <p style={{ display: "flex", gap: 10, alignItems: "center", flexWrap: "wrap", margin: 0 }}>
385 + <span className="klabel">Mis à jour le {new Date(updated).toLocaleString("fr-CA", { dateStyle: "medium", timeStyle: "short" })}</span>
386 + <button type="button" className="btn btn-ghost" onClick={onRefresh}>↻ Rafraîchir</button>
387 + </p>
388 + );
389 +}
added frontend/src/ka/stats/kapdf.py +558 −0
@@ -0,0 +1,558 @@
1 +# Auteur : Simon-Pierre Boucher — contact@spboucher.ai
2 +# ka-ui/stats/kapdf.py — moteur PDF commun Groupe KA (fpdf2).
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.
6 +# Usage :
7 +# from kapdf import GroupeKAReport
8 +# pdf_bytes = GroupeKAReport(site={"wordmark":"Lou·Ka","accent":"#ff6a00",
9 +# "domain":"www.lou-ka.com","tagline":"…"}, dashboard=dash_json,
10 +# mode="complet").build()
11 +# Dépendance : pip install fpdf2 (aucune autre)
12 +from __future__ import annotations
13 +
14 +import math
15 +from datetime import datetime
16 +from zoneinfo import ZoneInfo
17 +
18 +from fpdf import FPDF
19 +
20 +INK = (20, 24, 20)
21 +INK2 = (77, 85, 81)
22 +INK3 = (139, 146, 140)
23 +PAPER = (245, 243, 238)
24 +SURFACE2 = (250, 249, 245)
25 +GREEN = (28, 92, 65)
26 +DANGER = (179, 66, 58)
27 +WHITE = (255, 255, 255)
28 +
29 +EMAILS = [
30 + ("contact@groupe-ka.com", "Projets, partenariats & données"),
31 + ("info@groupe-ka.com", "Médias & questions générales"),
32 + ("admin@groupe-ka.com", "Légal, vie privée & Loi 25"),
33 +]
34 +DISCLAIMER = (
35 + "Groupe KA est un agrégateur de contenu : nous ne vendons rien, ne louons "
36 + "rien et ne sommes partie à aucune transaction. Données lues à la source, "
37 + "rien d'inventé, tout est traçable."
38 +)
39 +
40 +
41 +def _hex(c: str) -> tuple[int, int, int]:
42 + c = c.lstrip("#")
43 + return tuple(int(c[i : i + 2], 16) for i in (0, 2, 4)) # type: ignore
44 +
45 +
46 +def _fr(n) -> str:
47 + if isinstance(n, float) and not n.is_integer():
48 + return f"{n:,.2f}".replace(",", " ").replace(".", ",")
49 + return f"{int(n):,}".replace(",", " ")
50 +
51 +
52 +_SUBST = {
53 + "—": "-", "–": "-", "→": "->", "▲": "+", "▼": "-",
54 + "…": "...", "’": "'", "‘": "'", "“": '"', "”": '"',
55 + "œ": "oe", "Œ": "OE", "−": "-", " ": " ", " ": " ",
56 +}
57 +
58 +
59 +def _latin1(s: str) -> str:
60 + for k, v in _SUBST.items():
61 + s = s.replace(k, v)
62 + return s.encode("latin-1", "replace").decode("latin-1")
63 +
64 +
65 +class _PDF(FPDF):
66 + """FPDF avec en-tête/pied Groupe-KA sur chaque page (sauf couverture).
67 + Les polices core sont latin-1 : normalize_text sanitise en amont."""
68 +
69 + def normalize_text(self, text):
70 + return super().normalize_text(_latin1(text))
71 +
72 + def __init__(self, brand: str, accent: tuple, period_label: str):
73 + super().__init__(orientation="P", unit="mm", format="A4")
74 + self.brand = brand
75 + self.accent = accent
76 + self.period_label = period_label
77 + self.cover_mode = False
78 + self.set_margins(18, 20, 18)
79 + self.set_auto_page_break(True, margin=22)
80 +
81 + def header(self):
82 + if self.cover_mode:
83 + return
84 + self.set_font("helvetica", "B", 8.5)
85 + self.set_text_color(*INK)
86 + self.set_xy(18, 9)
87 + self.cell(0, 5, f"Groupe KA · {self.brand}")
88 + self.set_font("helvetica", "", 8)
89 + self.set_text_color(*INK3)
90 + self.set_xy(18, 9)
91 + self.cell(0, 5, "Rapport statistique", align="R")
92 + self.set_draw_color(*INK)
93 + self.set_line_width(0.5)
94 + self.line(18, 15.5, 192, 15.5)
95 + self.set_y(20)
96 +
97 + def footer(self):
98 + if self.cover_mode:
99 + return
100 + self.set_y(-15)
101 + self.set_draw_color(*INK3)
102 + self.set_line_width(0.2)
103 + self.line(18, self.get_y() - 1.5, 192, self.get_y() - 1.5)
104 + self.set_font("helvetica", "", 7.5)
105 + self.set_text_color(*INK3)
106 + year = datetime.now(ZoneInfo("America/Toronto")).year
107 + self.cell(130, 5, f"© Groupe-KA — {year} — groupe-ka.com · {self.period_label}")
108 + self.cell(0, 5, f"p. {self.page_no()}/{{nb}}", align="R")
109 +
110 +
111 +class GroupeKAReport:
112 + def __init__(self, site: dict, dashboard: dict, mode: str = "complet"):
113 + self.site = site
114 + self.d = dashboard
115 + self.mode = mode
116 + self.accent = _hex(site.get("accent", "#d9f26b"))
117 + period = dashboard.get("period", {}) or {}
118 + self.period_label = period.get("label") or "toute la période"
119 + self.pdf = _PDF(site.get("wordmark", ""), self.accent, self.period_label)
120 + self.toc: list[tuple[str, int]] = []
121 +
122 + # ---------- primitives ----------
123 + def _card(self, x, y, w, h, fill=WHITE):
124 + p = self.pdf
125 + p.set_draw_color(*INK)
126 + p.set_line_width(0.45)
127 + p.set_fill_color(*fill)
128 + p.rect(x, y, w, h, style="DF", round_corners=True, corner_radius=2.2)
129 +
130 + def _kicker(self, text):
131 + p = self.pdf
132 + p.set_font("helvetica", "B", 8)
133 + p.set_text_color(*GREEN)
134 + p.set_draw_color(*GREEN)
135 + p.set_line_width(0.6)
136 + y = p.get_y() + 2
137 + p.line(p.l_margin, y, p.l_margin + 7, y)
138 + p.set_xy(p.l_margin + 9, y - 2.5)
139 + p.cell(0, 5, text.upper())
140 + p.ln(8)
141 +
142 + def _section_title(self, title):
143 + if self.pdf.get_y() > 240:
144 + self.pdf.add_page()
145 + self._kicker("Groupe KA · " + self.site.get("wordmark", ""))
146 + self.pdf.set_font("helvetica", "B", 15)
147 + self.pdf.set_text_color(*INK)
148 + self.pdf.set_x(self.pdf.l_margin)
149 + self.pdf.cell(0, 8, title)
150 + self.toc.append((title, self.pdf.page_no()))
151 + self.pdf.ln(11)
152 +
153 + # ---------- pages ----------
154 + def _cover(self):
155 + p = self.pdf
156 + p.cover_mode = True
157 + p.set_auto_page_break(False)
158 + p.add_page()
159 + p.set_fill_color(*PAPER)
160 + p.rect(0, 0, 210, 297, style="F")
161 + p.set_draw_color(*INK)
162 + p.set_line_width(1.0)
163 + p.rect(10, 10, 190, 277)
164 + # kicker
165 + p.set_font("helvetica", "B", 10)
166 + p.set_text_color(*GREEN)
167 + p.set_xy(24, 34)
168 + p.cell(0, 6, "GROUPE KA · RAPPORT STATISTIQUE")
169 + # wordmark : partie gauche + boîte encre/accent
170 + wm = self.site.get("wordmark", "")
171 + left, boxed = (wm.split("·") + [None])[:2] if "·" in wm else (wm, None)
172 + p.set_xy(24, 70)
173 + p.set_font("helvetica", "B", 40)
174 + p.set_text_color(*INK)
175 + p.cell(p.get_string_width(left) + 2, 20, left)
176 + if boxed:
177 + bw = p.get_string_width(boxed) + 12
178 + x = p.get_x() + 2
179 + p.set_fill_color(*INK)
180 + p.rect(x, 68, bw, 22, style="F", round_corners=True, corner_radius=3)
181 + p.set_text_color(*self.accent)
182 + p.set_xy(x + 6, 70)
183 + p.cell(bw - 12, 18, boxed)
184 + p.set_xy(24, 100)
185 + p.set_font("helvetica", "", 13)
186 + p.set_text_color(*INK2)
187 + p.multi_cell(150, 7, f"Rapport statistique — {wm}")
188 + now = datetime.now(ZoneInfo("America/Toronto"))
189 + per = self.d.get("period", {}) or {}
190 + p.set_xy(24, 125)
191 + p.set_font("helvetica", "", 10.5)
192 + rows = [
193 + ("Période couverte", self.period_label + (f" ({per.get('from')} → {per.get('to')})" if per.get("from") else "")),
194 + ("Généré le", now.strftime("%Y-%m-%d à %H:%M") + " (heure de l'Est)"),
195 + ("Plateforme", "https://" + self.site.get("domain", "")),
196 + ("Mode", "Rapport complet" if self.mode == "complet" else "Synthèse"),
197 + ]
198 + y = 128
199 + for k, v in rows:
200 + p.set_xy(24, y)
201 + p.set_text_color(*INK3)
202 + p.cell(40, 6, k)
203 + p.set_text_color(*INK)
204 + p.set_font("helvetica", "B", 10.5)
205 + p.cell(0, 6, str(v))
206 + p.set_font("helvetica", "", 10.5)
207 + y += 8
208 + # bande encre au pied
209 + p.set_fill_color(*INK)
210 + p.rect(10, 262, 190, 25, style="F")
211 + p.set_xy(24, 270)
212 + p.set_font("helvetica", "B", 12)
213 + p.set_text_color(*WHITE)
214 + p.cell(60, 8, "par Groupe ")
215 + p.set_text_color(*self.accent)
216 + p.set_xy(24 + p.get_string_width("par Groupe ") + 1, 270)
217 + p.cell(20, 8, "KA")
218 + p.set_font("helvetica", "B", 10)
219 + p.set_xy(24, 270)
220 + p.set_text_color(*self.accent)
221 + p.cell(162, 8, "groupe-ka.com", align="R")
222 + p.set_auto_page_break(True, margin=22)
223 + p.cover_mode = False
224 +
225 + def _kpis(self):
226 + kpis = self.d.get("kpis") or []
227 + if not kpis:
228 + return
229 + self._section_title("Synthèse des indicateurs")
230 + p = self.pdf
231 + cols, gw, gh, gap = 3, 56, 26, 3
232 + x0, y = p.l_margin, p.get_y()
233 + for i, k in enumerate(kpis[:9]):
234 + x = x0 + (i % cols) * (gw + gap)
235 + if i and i % cols == 0:
236 + y += gh + gap
237 + if y > 250:
238 + p.add_page(); y = p.get_y()
239 + self._card(x, y, gw, gh)
240 + p.set_xy(x + 4, y + 4)
241 + p.set_font("helvetica", "B", 14)
242 + p.set_text_color(*INK)
243 + val = k.get("value")
244 + p.cell(gw - 8, 7, (_fr(val) if isinstance(val, (int, float)) else str(val)) + (" " + k["unit"] if k.get("unit") else ""))
245 + p.set_xy(x + 4, y + 12)
246 + p.set_font("helvetica", "", 7.6)
247 + p.set_text_color(*INK2)
248 + p.multi_cell(gw - 8, 3.6, str(k.get("label", ""))[:70])
249 + if k.get("delta_pct") is not None:
250 + up = (k.get("direction") or ("up" if k["delta_pct"] >= 0 else "down")) == "up"
251 + p.set_xy(x + 4, y + gh - 6.5)
252 + p.set_font("helvetica", "B", 8)
253 + p.set_text_color(*(GREEN if up else DANGER))
254 + 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.")
256 + p.set_y(y + gh + 8)
257 +
258 + def _line_chart(self, s):
259 + p = self.pdf
260 + pts = s.get("points") or []
261 + if len(pts) < 2:
262 + return
263 + if p.get_y() > 200:
264 + 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)
269 + x0, y0, w, h = p.l_margin, p.get_y(), 174, 52
270 + self._card(x0, y0, w, h, fill=WHITE)
271 + cx, cy, cw, ch = x0 + 12, y0 + 6, w - 20, h - 16
272 + vals = [pt["v"] for pt in pts] + [c["v"] for c in (s.get("compare") or [])]
273 + vmax = max(vals) or 1
274 + vmin = min(0, min(vals))
275 + rng = (vmax - vmin) or 1
276 + # grille + graduations
277 + p.set_font("helvetica", "", 6.3)
278 + p.set_text_color(*INK3)
279 + p.set_draw_color(200, 200, 195)
280 + p.set_line_width(0.15)
281 + for g in range(5):
282 + gy = cy + ch - ch * g / 4
283 + p.line(cx, gy, cx + cw, gy)
284 + p.set_xy(x0 + 1, gy - 1.6)
285 + p.cell(10, 3, _fr(vmin + rng * g / 4), align="R")
286 +
287 + def draw(series, color, width, dash=None):
288 + n = len(series)
289 + p.set_draw_color(*color)
290 + p.set_line_width(width)
291 + if dash:
292 + p.set_dash_pattern(dash=1.2, gap=1.2)
293 + last = None
294 + for i, pt in enumerate(series):
295 + px = cx + cw * (i / (n - 1))
296 + py = cy + ch - ch * ((pt["v"] - vmin) / rng)
297 + if last:
298 + p.line(last[0], last[1], px, py)
299 + last = (px, py)
300 + p.set_dash_pattern()
301 +
302 + if s.get("compare"):
303 + draw(s["compare"], INK3, 0.35, dash=True)
304 + draw(pts, self.accent, 0.7)
305 + # libellés d'axe X (premier / milieu / dernier)
306 + p.set_text_color(*INK3)
307 + for frac, idx in ((0, 0), (0.5, len(pts) // 2), (1, -1)):
308 + p.set_xy(cx + cw * frac - 9, cy + ch + 1.5)
309 + p.cell(18, 3, str(pts[idx].get("t", ""))[:10], align="C")
310 + p.set_y(y0 + h + 4)
311 + if s.get("compare"):
312 + p.set_font("helvetica", "", 6.8)
313 + p.set_text_color(*INK3)
314 + p.cell(0, 4, "— période courante (accent) · ---- période comparée")
315 + p.ln(6)
316 + else:
317 + p.ln(2)
318 +
319 + def _bars(self, title, items, unit=""):
320 + p = self.pdf
321 + items = [it for it in (items or []) if isinstance(it.get("value"), (int, float))][:12]
322 + if not items:
323 + return
324 + need = 10 + len(items) * 7
325 + if p.get_y() + need > 265:
326 + 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)
331 + vmax = max(it["value"] for it in items) or 1
332 + for it in items:
333 + y = p.get_y()
334 + p.set_font("helvetica", "", 7.6)
335 + p.set_text_color(*INK)
336 + p.set_x(p.l_margin)
337 + p.cell(46, 5, str(it["label"])[:34])
338 + bw = 96 * (it["value"] / vmax)
339 + p.set_fill_color(*self.accent)
340 + p.set_draw_color(*INK)
341 + p.set_line_width(0.25)
342 + 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)
344 + p.set_font("helvetica", "B", 7.6)
345 + p.cell(26, 5, _fr(it["value"]) + (" " + unit if unit else ""), align="R")
346 + p.ln(6.4)
347 + p.ln(3)
348 +
349 + def _donut(self, b):
350 + # anneau vectoriel simple (arcs) + légende
351 + p = self.pdf
352 + items = [it for it in (b.get("items") or []) if it.get("value")][:8]
353 + total = sum(it["value"] for it in items)
354 + if not items or not total:
355 + return
356 + if p.get_y() > 210:
357 + 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)
362 + 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 + start = -90.0
365 + for i, it in enumerate(items):
366 + 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))
369 + steps = max(2, int(72 * frac))
370 + p.set_fill_color(*col)
371 + p.set_draw_color(*col)
372 + for st in range(steps):
373 + a0 = math.radians(start + 360 * frac * st / steps)
374 + a1 = math.radians(start + 360 * frac * (st + 1) / steps)
375 + p.polygon(
376 + [(cx, cy),
377 + (cx + r * math.cos(a0), cy + r * math.sin(a0)),
378 + (cx + r * math.cos(a1), cy + r * math.sin(a1))],
379 + style="DF",
380 + )
381 + start += 360 * frac
382 + p.set_fill_color(*WHITE)
383 + p.set_draw_color(*INK)
384 + p.set_line_width(0.4)
385 + p.ellipse(cx - 11, cy - 11, 22, 22, style="DF")
386 + p.ellipse(cx - r, cy - r, 2 * r, 2 * r, style="D")
387 + # légende
388 + ly = cy - 22
389 + 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))
392 + p.set_fill_color(*col)
393 + p.set_draw_color(*INK)
394 + p.rect(p.l_margin + 60, ly + 0.8, 4, 4, style="DF")
395 + p.set_xy(p.l_margin + 66, ly)
396 + p.set_font("helvetica", "", 7.6)
397 + p.set_text_color(*INK)
398 + pct = 100 * it["value"] / total
399 + p.cell(0, 5.6, f"{str(it['label'])[:40]} — {_fr(it['value'])} ({pct:.1f} %)".replace(".", ","))
400 + ly += 5.6
401 + p.set_y(max(cy + r, ly) + 6)
402 +
403 + def _table(self, t):
404 + p = self.pdf
405 + cols = t.get("columns") or []
406 + rows = t.get("rows") or []
407 + if not cols or not rows:
408 + return
409 + self._section_title(t.get("title", "Tableau"))
410 + w = 174 / len(cols)
411 + def head():
412 + p.set_font("helvetica", "B", 7.6)
413 + p.set_fill_color(*INK)
414 + p.set_text_color(*WHITE)
415 + for c in cols:
416 + p.cell(w, 6, " " + str(c)[:30], fill=True)
417 + p.ln(6)
418 + head()
419 + p.set_text_color(*INK)
420 + for i, row in enumerate(rows[:200]):
421 + if p.get_y() > 262:
422 + p.add_page()
423 + head()
424 + p.set_text_color(*INK)
425 + p.set_font("helvetica", "", 7.4)
426 + p.set_fill_color(*(SURFACE2 if i % 2 else WHITE))
427 + for cell in row:
428 + txt = _fr(cell) if isinstance(cell, (int, float)) else str(cell)
429 + p.cell(w, 5.4, " " + txt[:34], fill=True)
430 + p.ln(5.4)
431 + if len(rows) > 200:
432 + p.set_font("helvetica", "", 7)
433 + p.set_text_color(*INK3)
434 + p.cell(0, 5, f"… {len(rows) - 200} lignes supplémentaires non imprimées")
435 + p.ln(6)
436 +
437 + def _records(self):
438 + recs = self.d.get("records") or []
439 + if not recs:
440 + return
441 + self._section_title("Records & faits marquants")
442 + p = self.pdf
443 + for r in recs[:10]:
444 + if p.get_y() > 258:
445 + p.add_page()
446 + y = p.get_y()
447 + self._card(p.l_margin, y, 174, 11, fill=SURFACE2)
448 + p.set_xy(p.l_margin + 4, y + 2)
449 + p.set_font("helvetica", "", 8.6)
450 + p.set_text_color(*INK2)
451 + p.cell(96, 7, str(r.get("label", ""))[:70])
452 + p.set_font("helvetica", "B", 9)
453 + p.set_text_color(*INK)
454 + p.cell(52, 7, str(r.get("value", ""))[:36], align="R")
455 + p.set_font("helvetica", "", 7.6)
456 + p.set_text_color(*INK3)
457 + p.cell(20, 7, str(r.get("date", "") or ""), align="R")
458 + p.set_y(y + 13.5)
459 + p.ln(4)
460 +
461 + def _final_page(self):
462 + p = self.pdf
463 + p.add_page()
464 + self._kicker("Groupe KA · contact")
465 + p.set_font("helvetica", "B", 15)
466 + p.set_text_color(*INK)
467 + p.cell(0, 8, "Coordonnées du Groupe KA")
468 + p.ln(12)
469 + for email, role in EMAILS:
470 + p.set_font("helvetica", "B", 10.5)
471 + p.set_text_color(*INK)
472 + p.cell(0, 6, email)
473 + p.ln(5.5)
474 + p.set_font("helvetica", "", 8.6)
475 + p.set_text_color(*INK3)
476 + p.cell(0, 5, role)
477 + p.ln(8)
478 + p.ln(2)
479 + p.set_font("helvetica", "B", 10)
480 + p.set_text_color(*GREEN)
481 + p.cell(0, 6, "groupe-ka.com — le portail de l'écosystème ·Ka")
482 + p.ln(10)
483 + p.set_draw_color(*self.accent)
484 + p.set_line_width(0.8)
485 + p.line(p.l_margin, p.get_y(), p.l_margin + 30, p.get_y())
486 + p.ln(4)
487 + p.set_font("helvetica", "", 8.6)
488 + p.set_text_color(*INK2)
489 + p.multi_cell(160, 4.6, DISCLAIMER)
490 + p.ln(4)
491 + p.set_font("helvetica", "", 7.6)
492 + p.set_text_color(*INK3)
493 + p.multi_cell(
494 + 160, 4.2,
495 + "Mentions : rapport généré automatiquement à partir des données réelles de la "
496 + "plateforme au moment indiqué en couverture. Conditions d'utilisation, politique "
497 + "de confidentialité et protection des renseignements personnels (Loi 25) : "
498 + "groupe-ka.com/conditions · /confidentialite · /loi-25.",
499 + )
500 +
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
505 +
506 + def build(self) -> bytes:
507 + p = self.pdf
508 + p.alias_nb_pages()
509 + self._cover()
510 + if self.mode == "synthese":
511 + p.add_page()
512 + self._kpis()
513 + self._records()
514 + self._final_page()
515 + else:
516 + p.add_page()
517 + toc_page_no = p.page_no()
518 + p.add_page()
519 + 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"))
533 + for t in self.d.get("tables") or []:
534 + self._table(t)
535 + self._records()
536 + self._final_page()
537 + # sommaire écrit sur la page réservée (page 2)
538 + last_page = p.page
539 + p.page = toc_page_no
540 + p.set_y(22)
541 + p.set_font("helvetica", "B", 15)
542 + p.set_text_color(*INK)
543 + p.cell(0, 8, "Sommaire")
544 + p.ln(12)
545 + p.set_font("helvetica", "", 9.5)
546 + for title, page_no in self.toc:
547 + p.set_text_color(*INK)
548 + p.cell(140, 6.5, title[:80])
549 + p.set_text_color(*INK3)
550 + p.cell(0, 6.5, str(page_no), align="R")
551 + p.ln(6.5)
552 + p.page = last_page
553 + return bytes(p.output())
554 +
555 +
556 +def filename(platform_id: str, period: str) -> str:
557 + today = datetime.now(ZoneInfo("America/Toronto")).strftime("%Y-%m-%d")
558 + return f"groupe-ka_{platform_id}_stats_{period}_{today}.pdf"
modified frontend/src/pages/Stats.tsx +126 −389
@@ -1,417 +1,154 @@
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 −// pages/Stats.tsx : observatoire du marché — 5 onglets (Vue d'ensemble, Loyers,
5 −// Régions & villes, Offre, Gestionnaires), tuiles héro, histogramme,
6 −// barres mono-série, baisses de prix, santé des sources. Rapport PDF global.
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.
7 8 // -----------------------------------------------------------------------------
8 −import { useEffect, useMemo, useState } from "react";
9 −import { Link, useSearchParams } from "react-router-dom";
10 −import { IcoChart, IcoFolder, IcoHouse, IcoMap } from "../components/Icons";
9 +import { useCallback, useEffect, useState } from "react";
11 10 import {
12 − DetailedStats, GroupStat,
13 − fetchDetailedStats, fetchSources, registerSourceNames, sourceName,
14 −} from "../api";
15 −
16 −const fmt = (n: number | null | undefined) =>
17 − n == null ? "—" : n.toLocaleString("fr-CA");
18 −const fmt$ = (n: number | null | undefined) => (n == null ? "—" : `${fmt(n)} $`);
11 + BarChart, BreakItem, CalendarHeatmap, DataTable, Donut, EmptyBlock,
12 + Fraicheur, Kpi, KpiCard, LineChart, PdfButton, PeriodSelector, RecordCard,
13 + RecordFact, Serie, TableSpec,
14 +} from "../ka/stats/kacharts";
15 +
16 +interface Dashboard {
17 + updated: string;
18 + period: { from: string | null; to: string | null; label: string };
19 + kpis: Kpi[];
20 + series: Serie[];
21 + breakdowns: { id: string; title: string; kind?: string; items: BreakItem[] }[];
22 + geo?: { title: string; items: BreakItem[] };
23 + heatmap?: { title: string; cells: { date: string; value: number }[] };
24 + tables: TableSpec[];
25 + records: RecordFact[];
26 +}
19 27
20 −const ONGLETS = [
21 − { id: "ensemble", label: "Vue d'ensemble", icon: <IcoChart size={14} /> },
22 − { id: "loyers", label: "Loyers", icon: <span className="mono">$</span> },
23 − { id: "regions", label: "Régions & villes", icon: <IcoMap size={14} /> },
24 − { id: "offre", label: "L'offre", icon: <IcoHouse size={14} /> },
25 − { id: "gestionnaires", label: "Gestionnaires", icon: <IcoFolder size={14} /> },
26 −] as const;
27 −type OngletId = (typeof ONGLETS)[number]["id"];
28 +export default function StatsPage() {
29 + const [period, setPeriod] = useState("30j");
30 + const [custom, setCustom] = useState<{ from: string; to: string }>({ from: "", to: "" });
31 + const [dash, setDash] = useState<Dashboard | null>(null);
32 + const [loading, setLoading] = useState(true);
33 + const [err, setErr] = useState<string | null>(null);
34 +
35 + const customOk = Boolean(custom.from && custom.to);
36 +
37 + const load = useCallback(() => {
38 + setLoading(true);
39 + setErr(null);
40 + const p = new URLSearchParams({ period });
41 + if (customOk) {
42 + p.set("from", custom.from);
43 + p.set("to", custom.to);
44 + }
45 + fetch(`/api/stats/dashboard?${p}`)
46 + .then((r) => {
47 + if (!r.ok) throw new Error(`API ${r.status}`);
48 + return r.json();
49 + })
50 + .then((d: Dashboard) => setDash(d))
51 + .catch((e) => setErr(String(e?.message ?? e)))
52 + .finally(() => setLoading(false));
53 + }, [period, custom.from, custom.to, customOk]);
28 54
29 −// ---- infobulle partagée ------------------------------------------------------
30 −interface Tip { x: number; y: number; title: string; lines: string[]; }
55 + useEffect(() => {
56 + document.title = "Statistiques du marché locatif — Lou·Ka";
57 + load();
58 + }, [load]);
31 59
32 −function useTooltip() {
33 − const [tip, setTip] = useState<Tip | null>(null);
34 − const show = (e: React.MouseEvent, title: string, lines: string[]) =>
35 − setTip({ x: e.clientX, y: e.clientY, title, lines });
36 − const hide = () => setTip(null);
37 − const node = tip && (
38 − <div className="viz-tip" role="status"
39 − style={{ left: Math.min(tip.x + 14, window.innerWidth - 190), top: tip.y + 14 }}>
40 − <div className="viz-tip-title">{tip.title}</div>
41 − {tip.lines.map((l) => <div key={l}>{l}</div>)}
42 − </div>
43 − );
44 − return { show, hide, node };
45 −}
60 + const donuts = dash?.breakdowns?.filter((b) => b.kind === "donut") ?? [];
61 + const barBreaks = dash?.breakdowns?.filter((b) => b.kind !== "donut") ?? [];
46 62
47 −// ---- barres horizontales (une série) ----------------------------------------
48 −function HBars({ data, unit, tip }: {
49 − data: { label: string; count: number; avg: number | null; href?: string }[];
50 − unit: string;
51 − tip: ReturnType<typeof useTooltip>;
52 −}) {
53 − const max = Math.max(...data.map((d) => d.count), 1);
54 63 return (
55 − <div className="hbars">
56 − {data.map((d) => (
57 − <div className="hbar-row" key={d.label}
58 − onMouseMove={(e) => tip.show(e, d.label, [
59 − `${fmt(d.count)} ${unit}`,
60 − d.avg != null ? `loyer moyen ${fmt$(d.avg)}` : "loyer non affiché"])}
61 − onMouseLeave={tip.hide}>
62 − <span className="hbar-label" title={d.label}>
63 − {d.href ? <Link to={d.href}>{d.label}</Link> : d.label}
64 − </span>
65 − <span className="hbar-track">
66 − <span className="hbar-fill" style={{ width: `${(d.count / max) * 100}%` }} />
67 − </span>
68 − <span className="hbar-value">
69 − {fmt(d.count)}{d.avg != null && <em> · {fmt$(d.avg)}</em>}
70 − </span>
64 + <div className="container" style={{ display: "grid", gap: 18, paddingBottom: 40 }}>
65 + {/* --- en-tête : titre + PDF + fraîcheur ------------------------------ */}
66 + <header style={{ display: "flex", flexWrap: "wrap", gap: 14, alignItems: "flex-end", justifyContent: "space-between", marginTop: 8 }}>
67 + <div style={{ minWidth: 0 }}>
68 + <p className="klabel" style={{ margin: 0 }}>Groupe KA · Lou·Ka</p>
69 + <h1 style={{ margin: "4px 0 0", fontFamily: "var(--font-display)", fontSize: "clamp(24px,3.4vw,34px)", letterSpacing: "-0.02em" }}>
70 + Statistiques du marché locatif
71 + </h1>
72 + {dash && (
73 + <p className="klabel" style={{ margin: "6px 0 0" }}>
74 + Période : {dash.period.label}
75 + {dash.period.from ? ` (${dash.period.from} → ${dash.period.to})` : ""}
76 + </p>
77 + )}
71 78 </div>
72 − ))}
73 − </div>
74 − );
75 −}
76 −
77 −// ---- barres de pourcentage (inclusions) ---------------------------------------
78 −function PctBars({ data }: { data: { label: string; pct: number | null }[] }) {
79 − return (
80 − <div className="hbars">
81 − {data.filter((d) => d.pct != null).map((d) => (
82 − <div className="hbar-row" key={d.label}>
83 − <span className="hbar-label">{d.label}</span>
84 − <span className="hbar-track">
85 − <span className="hbar-fill" style={{ width: `${Math.min(100, d.pct!)}%` }} />
86 − </span>
87 − <span className="hbar-value">{d.pct!.toLocaleString("fr-CA")} %</span>
79 + <div style={{ display: "grid", gap: 8, justifyItems: "end" }}>
80 + <PdfButton period={period} from={customOk ? custom.from : undefined} to={customOk ? custom.to : undefined} />
81 + {dash && <Fraicheur updated={dash.updated} onRefresh={load} />}
88 82 </div>
89 − ))}
90 − </div>
91 − );
92 −}
93 −
94 −function DataTable({ rows, unit }: { rows: GroupStat[]; unit: string }) {
95 − return (
96 − <details className="viz-table">
97 − <summary>Voir les données</summary>
98 − <table>
99 − <thead>
100 − <tr><th>Catégorie</th><th>{unit}</th><th>Loyer moyen</th><th>À partir de</th></tr>
101 − </thead>
102 − <tbody>
103 − {rows.map((r) => (
104 − <tr key={r.key}>
105 − <td>{r.key}</td><td>{fmt(r.count)}</td>
106 − <td>{fmt$(r.avg_price)}</td><td>{fmt$(r.min_price)}</td>
107 − </tr>
108 − ))}
109 − </tbody>
110 − </table>
111 − </details>
112 − );
113 −}
114 −
115 −function Tile({ v, k, hero }: { v: string; k: string; hero?: boolean }) {
116 − return (
117 − <div className={`tile ${hero ? "hero-tile" : ""}`}>
118 − <div className="tile-v">{v}</div>
119 − <div className="tile-k">{k}</div>
120 − </div>
121 − );
122 −}
123 −
124 −// ---- page --------------------------------------------------------------------
125 −export default function StatsPage() {
126 − const [d, setD] = useState<DetailedStats | null>(null);
127 − const [error, setError] = useState<string | null>(null);
128 − const [params, setParams] = useSearchParams();
129 − const onglet = (params.get("onglet") as OngletId) || "ensemble";
130 − const tip = useTooltip();
83 + </header>
131 84
132 − useEffect(() => {
133 − fetchSources().then((r) => registerSourceNames(r.sources)).catch(() => {});
134 − fetchDetailedStats().then(setD).catch((e) => setError(String(e)));
135 − }, []);
136 −
137 − const histMax = useMemo(
138 − () => Math.max(...(d?.histogram.map((h) => h.count) ?? [1]), 1), [d]);
139 −
140 − if (error)
141 − return (
142 − <div className="notice container">
143 − <div className="big">⚠️</div>
144 − <h2>Statistiques indisponibles</h2>
145 − <p>{error}</p>
146 − </div>
147 − );
85 + {err && (
86 + <div className="card" style={{ padding: 18, borderColor: "var(--danger)" }}>
87 + <b>Impossible de charger les statistiques.</b>
88 + <p className="klabel" style={{ margin: "6px 0 10px" }}>{err}</p>
89 + <button type="button" className="btn btn-primary" onClick={load}>Réessayer</button>
90 + </div>
91 + )}
148 92
149 − if (!d)
150 − return (
151 − <div className="container stats-page" aria-busy="true">
152 − <div className="skel" style={{ height: 120, marginTop: 40 }} />
153 − <div className="skel" style={{ height: 300, marginTop: 20 }} />
154 − </div>
155 − );
93 + {/* --- bandeau KPI ----------------------------------------------------- */}
94 + {dash && dash.kpis.length > 0 && (
95 + <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 + {dash.kpis.map((k) => <KpiCard key={k.id} k={k} />)}
97 + </section>
98 + )}
99 + {!dash && loading && (
100 + <div className="card" style={{ padding: 24, textAlign: "center" }}>
101 + <span className="klabel">Chargement des statistiques…</span>
102 + </div>
103 + )}
156 104
157 − const t = d.totals;
158 − const o = d.offre;
159 − const fold = (rest: GroupStat[]): GroupStat | null =>
160 − rest.length === 0 ? null : {
161 − key: `Autres (${rest.length})`,
162 − count: rest.reduce((s, r) => s + r.count, 0),
163 − avg_price: null, min_price: null,
164 − };
105 + {/* --- sélecteur de période -------------------------------------------- */}
106 + <section className="card" style={{ padding: "14px 16px" }} aria-label="Période">
107 + <PeriodSelector
108 + value={period}
109 + onChange={(p) => { setPeriod(p); setCustom({ from: "", to: "" }); }}
110 + custom={custom}
111 + onCustom={(from, to) => setCustom({ from, to })}
112 + />
113 + </section>
114 +
115 + {dash && (
116 + <div style={{ display: "grid", gap: 18, opacity: loading ? 0.55 : 1, transition: "opacity .2s" }}>
117 + {/* --- courbes ----------------------------------------------------- */}
118 + {dash.series?.length ? (
119 + dash.series.map((s) => <LineChart key={s.id} serie={s} />)
120 + ) : (
121 + <EmptyBlock title="Évolution quotidienne" />
122 + )}
165 123
166 − const histogramme = (
167 − <section className="viz-card">
168 − <h2>Distribution des loyers</h2>
169 − <p className="viz-sub">{fmt(t.with_price)} annonces avec prix affiché — classes de 200 $</p>
170 − <div className="histo" role="img" aria-label="Histogramme des loyers mensuels">
171 − {d.histogram.map((h) => (
172 − <div className="histo-col" key={`${h.lo}`}
173 − onMouseMove={(e) => tip.show(e,
174 − h.hi ? `${fmt(h.lo)} – ${fmt(h.hi)} $` : `${fmt(h.lo)} $ et plus`,
175 − [`${fmt(h.count)} logements`,
176 − `${((h.count / Math.max(t.with_price, 1)) * 100).toFixed(1)} % du parc`])}
177 − onMouseLeave={tip.hide}>
178 − <div className="histo-bar-zone">
179 − <div className="histo-bar" style={{ height: `${(h.count / histMax) * 100}%` }} />
180 − </div>
181 − <div className="histo-x">
182 − {h.lo % 400 === 0 ? (h.lo >= 1000 ? `${h.lo / 1000}k` : h.lo) : ""}
124 + {/* --- répartitions (anneau + barres) ------------------------------ */}
125 + {(donuts.length > 0 || barBreaks.length > 0) && (
126 + <div style={{ display: "grid", gap: 18, gridTemplateColumns: "repeat(auto-fit, minmax(min(340px, 100%), 1fr))" }}>
127 + {donuts.map((b) => <Donut key={b.id} title={b.title} items={b.items} />)}
128 + {barBreaks.map((b) => <BarChart key={b.id} title={b.title} items={b.items} unit="annonces" />)}
183 129 </div>
184 − </div>
185 − ))}
186 − </div>
187 − </section>
188 − );
130 + )}
189 131
190 − return (
191 − <div className="container stats-page">
192 − {tip.node}
193 − <span className="kicker">Observatoire — marché locatif québécois</span>
194 − <h1 className="stats-title">Le marché, en chiffres</h1>
195 − <p className="sub">
196 − Calculé en direct sur les {fmt(t.total)} annonces actives de {fmt(t.sources)} gestionnaires,
197 − dans {fmt(t.cities)} villes et {fmt(t.regions)} régions.
198 − </p>
199 − <p>
200 − <a className="btn btn-primary" href="/api/stats/rapport.pdf" download>
201 − 📊 Télécharger le rapport global (PDF)
202 − </a>
203 − </p>
132 + {/* --- géographie --------------------------------------------------- */}
133 + {dash.geo && <BarChart title={dash.geo.title} items={dash.geo.items} unit="annonces" />}
204 134
205 − {/* barre d'onglets */}
206 − <nav className="onglets" role="tablist" aria-label="Sections des statistiques">
207 − {ONGLETS.map((g) => (
208 − <button key={g.id} role="tab" aria-selected={onglet === g.id}
209 − className={`onglet ${onglet === g.id ? "on" : ""}`}
210 − onClick={() => setParams(g.id === "ensemble" ? {} : { onglet: g.id })}>
211 − <span aria-hidden="true">{g.icon}</span> {g.label}
212 − </button>
213 − ))}
214 − </nav>
135 + {/* --- calendrier de chaleur ---------------------------------------- */}
136 + {dash.heatmap && <CalendarHeatmap title={dash.heatmap.title} cells={dash.heatmap.cells} />}
215 137
216 − {/* ============ Vue d'ensemble ============ */}
217 − {onglet === "ensemble" && (
218 − <>
219 − <div className="tiles">
220 − <Tile hero v={fmt(t.total)} k="logements actifs" />
221 − <Tile v={fmt$(t.median)} k="loyer médian" />
222 − <Tile v={fmt$(t.avg)} k="loyer moyen" />
223 − <Tile v={fmt(t.dispo_now)} k="libres maintenant" />
224 − <Tile v={t.superficie_moyenne ? `${fmt(t.superficie_moyenne)} pi²` : "—"} k="superficie moyenne" />
225 − <Tile v={t.gps_pct != null ? `${t.gps_pct} %` : "—"} k="géolocalisées" />
226 − </div>
227 − <section className="viz-card">
228 − <h2>Couverture par région</h2>
229 − <p className="viz-sub">annonces actives · loyer moyen régional</p>
230 − <HBars tip={tip} unit="logements"
231 − data={d.by_region.map((r) => ({ label: r.key, count: r.count, avg: r.avg_price }))} />
232 − <DataTable rows={d.by_region} unit="Logements" />
233 − </section>
234 − {histogramme}
235 − </>
236 − )}
138 + {/* --- tableaux détaillés ------------------------------------------- */}
139 + {dash.tables?.map((t) => <DataTable key={t.id} spec={t} />)}
237 140
238 − {/* ============ Loyers ============ */}
239 − {onglet === "loyers" && (
240 − <>
241 − <div className="tiles">
242 − <Tile hero v={fmt$(t.median)} k="loyer médian" />
243 − <Tile v={fmt$(t.avg)} k="loyer moyen" />
244 − <Tile v={fmt$(t.min)} k="loyer le plus bas" />
245 − <Tile v={fmt$(t.max)} k="loyer le plus élevé" />
246 − </div>
247 − {histogramme}
248 − <div className="viz-grid">
249 − <section className="viz-card">
250 − <h2>Par taille de logement</h2>
251 − <p className="viz-sub">nombre d'annonces · loyer moyen</p>
252 − <HBars tip={tip} unit="logements"
253 − data={d.by_type.slice(0, 9).map((r) => ({
254 − label: r.key, count: r.count, avg: r.avg_price,
255 − href: `/?unit_type=${encodeURIComponent(r.key)}` }))} />
256 − <DataTable rows={d.by_type} unit="Logements" />
257 − </section>
258 − <section className="viz-card">
259 − <h2>Prix au pied carré</h2>
260 − <p className="viz-sub">loyer ÷ superficie, par taille (annonces publiant les deux)</p>
261 − <div className="hbars">
262 − {o.prix_pi2.map((r) => {
263 − const max = Math.max(...o.prix_pi2.map((x) => x.val), 0.01);
264 − return (
265 − <div className="hbar-row" key={r.key}>
266 − <span className="hbar-label">{r.key}</span>
267 − <span className="hbar-track">
268 − <span className="hbar-fill" style={{ width: `${(r.val / max) * 100}%` }} />
269 − </span>
270 − <span className="hbar-value">
271 − {r.val.toLocaleString("fr-CA")} $/pi²<em> · {r.count}</em>
272 − </span>
273 − </div>
274 − );
275 − })}
141 + {/* --- records & faits marquants ------------------------------------ */}
142 + {dash.records?.length > 0 && (
143 + <section aria-label="Records et faits marquants" style={{ display: "grid", gap: 10 }}>
144 + <h2 style={{ margin: 0, fontFamily: "var(--font-display)", fontSize: 19 }}>Records & faits marquants</h2>
145 + <div style={{ display: "grid", gap: 10, gridTemplateColumns: "repeat(auto-fit, minmax(min(280px, 100%), 1fr))" }}>
146 + {dash.records.map((r) => <RecordCard key={r.label} r={r} />)}
276 147 </div>
277 148 </section>
278 − </div>
279 − {d.baisses.length > 0 && (
280 − <section className="viz-card">
281 − <h2>Baisses de prix récentes 📉</h2>
282 − <p className="viz-sub">30 derniers jours — leviers de négociation</p>
283 − <ul className="baisses">
284 − {d.baisses.map((b) => (
285 − <li key={b.uid}>
286 − <Link to={`/logement/${encodeURIComponent(b.uid)}`}>
287 − {b.title || b.uid}
288 − </Link>
289 − <span className="baisse-ville">{b.city}</span>
290 − <span className="baisse-prix">
291 − <s>{fmt$(b.avant)}</s> → <b>{fmt$(b.apres)}</b>
292 − <em className="baisse-pct">{b.pct.toLocaleString("fr-CA")} %</em>
293 − </span>
294 − </li>
295 − ))}
296 − </ul>
297 − </section>
298 149 )}
299 − </>
300 − )}
301 −
302 − {/* ============ Régions & villes ============ */}
303 − {onglet === "regions" && (
304 − <>
305 − <section className="viz-card">
306 − <h2>Par région</h2>
307 − <p className="viz-sub">annonces · gestionnaires · loyer moyen</p>
308 − <HBars tip={tip} unit="logements"
309 − data={d.by_region.map((r) => ({ label: r.key, count: r.count, avg: r.avg_price }))} />
310 − <details className="viz-table" open>
311 − <summary>Voir les données</summary>
312 − <table>
313 − <thead><tr><th>Région</th><th>Annonces</th><th>Sources</th><th>Loyer moyen</th></tr></thead>
314 − <tbody>
315 − {d.by_region.map((r) => (
316 − <tr key={r.key}>
317 − <td>{r.key}</td><td>{fmt(r.count)}</td>
318 − <td>{r.sources ?? "—"}</td><td>{fmt$(r.avg_price)}</td>
319 − </tr>
320 − ))}
321 − </tbody>
322 − </table>
323 − </details>
324 − </section>
325 − <section className="viz-card">
326 − <h2>Par ville</h2>
327 − <p className="viz-sub">top 20 — nombre d'annonces · loyer moyen</p>
328 − <HBars tip={tip} unit="logements"
329 − data={[...d.by_city.slice(0, 20).map((r) => ({
330 − label: r.key, count: r.count, avg: r.avg_price,
331 − href: `/?city=${encodeURIComponent(r.key)}` })),
332 − ...(fold(d.by_city.slice(20))
333 − ? [{ label: fold(d.by_city.slice(20))!.key,
334 − count: fold(d.by_city.slice(20))!.count, avg: null }] : [])]} />
335 − <DataTable rows={d.by_city} unit="Logements" />
336 − </section>
337 − </>
338 − )}
339 −
340 − {/* ============ L'offre ============ */}
341 − {onglet === "offre" && (
342 − <>
343 − <div className="tiles">
344 − <Tile hero v={fmt(o.dispo_now)} k="libres maintenant" />
345 − <Tile v={fmt(o.dispo_date)} k="libres à date future" />
346 − <Tile v={o.superficie_moyenne ? `${fmt(o.superficie_moyenne)} pi²` : "—"} k="superficie moyenne" />
347 − <Tile v={o.pets_oui_pct != null ? `${o.pets_oui_pct} %` : "—"}
348 − k={`acceptent les animaux (sur ${fmt(o.pets_connu)} précisées)`} />
349 − </div>
350 − <section className="viz-card">
351 − <h2>Inclusions et caractéristiques</h2>
352 − <p className="viz-sub">part du parc dont la source confirme l'inclusion — le reste est inconnu, pas absent</p>
353 − <PctBars data={[
354 − { label: "Balcon", pct: o.balcon_pct },
355 − { label: "Stationnement", pct: o.stationnement_pct },
356 − { label: "Climatisation", pct: o.clim_pct },
357 − { label: "Internet inclus", pct: o.internet_pct },
358 − { label: "Eau chaude incluse", pct: o.eau_chaude_pct },
359 − { label: "Chauffage inclus", pct: o.chauffage_pct },
360 − { label: "Électricité incluse", pct: o.electricite_pct },
361 − { label: "Meublé", pct: o.furnished_pct },
362 − ].sort((a, b) => (b.pct ?? 0) - (a.pct ?? 0))} />
363 − </section>
364 − <section className="viz-card">
365 − <h2>Par taille de logement</h2>
366 − <HBars tip={tip} unit="logements"
367 − data={d.by_type.slice(0, 9).map((r) => ({
368 − label: r.key, count: r.count, avg: r.avg_price,
369 − href: `/?unit_type=${encodeURIComponent(r.key)}` }))} />
370 − </section>
371 − </>
372 − )}
373 −
374 − {/* ============ Gestionnaires ============ */}
375 − {onglet === "gestionnaires" && (
376 − <>
377 − <div className="tiles">
378 − <Tile hero v={fmt(t.sources)} k="gestionnaires connectés" />
379 − <Tile v={fmt(d.sante.sources_sync_24h)} k="synchronisés (24 h)" />
380 − <Tile v={fmt(d.sante.alertes_24h.length)} k="alertes (24 h)" />
381 − </div>
382 − <section className="viz-card">
383 − <h2>Par gestionnaire immobilier</h2>
384 − <p className="viz-sub">top 20 — nombre d'annonces · loyer moyen</p>
385 − <HBars tip={tip} unit="logements"
386 − data={[...d.by_source.slice(0, 20).map((r) => ({
387 − label: sourceName(r.key), count: r.count, avg: r.avg_price,
388 − href: `/?source=${encodeURIComponent(r.key)}` })),
389 − ...(fold(d.by_source.slice(20))
390 − ? [{ label: fold(d.by_source.slice(20))!.key,
391 − count: fold(d.by_source.slice(20))!.count, avg: null }] : [])]} />
392 − <DataTable rows={d.by_source.map((r) => ({ ...r, key: sourceName(r.key) }))}
393 − unit="Logements" />
394 − </section>
395 − {d.sante.alertes_24h.length > 0 && (
396 − <section className="viz-card">
397 − <h2>Alertes de synchronisation (24 h)</h2>
398 − <ul className="alertes">
399 − {d.sante.alertes_24h.map((a, i) => (
400 − <li key={i}><b>{sourceName(a.source)}</b> — {a.message}</li>
401 − ))}
402 − </ul>
403 − </section>
404 − )}
405 − <p className="stats-foot">
406 − <Link to="/sources">Voir le registre complet des sources →</Link>
407 − </p>
408 − </>
150 + </div>
409 151 )}
410 −
411 − <p className="stats-foot">
412 − Données recalculées à chaque synchronisation (horaire). Les catégories
413 − renvoient vers les logements filtrés correspondants.
414 − </p>
415 152 </div>
416 153 );
417 154 }
modified frontend/tsconfig.tsbuildinfo +1 −1
@@ -1 +1 @@
1 −{"root":["./src/app.tsx","./src/logo.tsx","./src/account.tsx","./src/api.ts","./src/main.tsx","./src/vite-env.d.ts","./src/components/cookieconsent.tsx","./src/components/icons.tsx","./src/components/listingcard.tsx","./src/components/listingmap3d.tsx","./src/components/logo.tsx","./src/components/mapview.tsx","./src/components/pager.tsx","./src/components/quartierblock.tsx","./src/ka/groupekabadge.tsx","./src/ka/kafooter.tsx","./src/kamaps/adapter.ts","./src/kamaps/config.ts","./src/kamaps/theme.ts","./src/pages/bienvenue.tsx","./src/pages/bot.tsx","./src/pages/contact.tsx","./src/pages/favoris.tsx","./src/pages/gestion.tsx","./src/pages/gestionpublic.tsx","./src/pages/home.tsx","./src/pages/listing.tsx","./src/pages/passerelle.tsx","./src/pages/privacy.tsx","./src/pages/profile.tsx","./src/pages/publicprofile.tsx","./src/pages/sources.tsx","./src/pages/stats.tsx","./src/pages/terms.tsx","./src/pages/ville.tsx"],"version":"5.9.3"}
\ No newline at end of file
1 +{"root":["./src/app.tsx","./src/logo.tsx","./src/account.tsx","./src/api.ts","./src/main.tsx","./src/vite-env.d.ts","./src/components/cookieconsent.tsx","./src/components/icons.tsx","./src/components/listingcard.tsx","./src/components/listingmap3d.tsx","./src/components/logo.tsx","./src/components/mapview.tsx","./src/components/pager.tsx","./src/components/quartierblock.tsx","./src/ka/groupekabadge.tsx","./src/ka/kafooter.tsx","./src/ka/stats/kacharts.tsx","./src/kamaps/adapter.ts","./src/kamaps/config.ts","./src/kamaps/theme.ts","./src/pages/bienvenue.tsx","./src/pages/bot.tsx","./src/pages/contact.tsx","./src/pages/favoris.tsx","./src/pages/gestion.tsx","./src/pages/gestionpublic.tsx","./src/pages/home.tsx","./src/pages/listing.tsx","./src/pages/passerelle.tsx","./src/pages/privacy.tsx","./src/pages/profile.tsx","./src/pages/publicprofile.tsx","./src/pages/sources.tsx","./src/pages/stats.tsx","./src/pages/terms.tsx","./src/pages/ville.tsx"],"version":"5.9.3"}
\ No newline at end of file
added louka/kapdf.py +560 −0
@@ -0,0 +1,560 @@
1 +# Auteur : Simon-Pierre Boucher — contact@spboucher.ai
2 +# ka-ui/stats/kapdf.py — moteur PDF commun Groupe KA (fpdf2).
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.
6 +# Usage :
7 +# from kapdf import GroupeKAReport
8 +# pdf_bytes = GroupeKAReport(site={"wordmark":"Lou·Ka","accent":"#ff6a00",
9 +# "domain":"www.lou-ka.com","tagline":"…"}, dashboard=dash_json,
10 +# mode="complet").build()
11 +# Dépendance : pip install fpdf2 (aucune autre)
12 +from __future__ import annotations
13 +
14 +import math
15 +from datetime import datetime
16 +from zoneinfo import ZoneInfo
17 +
18 +from fpdf import FPDF
19 +
20 +INK = (20, 24, 20)
21 +INK2 = (77, 85, 81)
22 +INK3 = (139, 146, 140)
23 +PAPER = (245, 243, 238)
24 +SURFACE2 = (250, 249, 245)
25 +GREEN = (28, 92, 65)
26 +DANGER = (179, 66, 58)
27 +WHITE = (255, 255, 255)
28 +
29 +EMAILS = [
30 + ("contact@groupe-ka.com", "Projets, partenariats & données"),
31 + ("info@groupe-ka.com", "Médias & questions générales"),
32 + ("admin@groupe-ka.com", "Légal, vie privée & Loi 25"),
33 +]
34 +DISCLAIMER = (
35 + "Groupe KA est un agrégateur de contenu : nous ne vendons rien, ne louons "
36 + "rien et ne sommes partie à aucune transaction. Données lues à la source, "
37 + "rien d'inventé, tout est traçable."
38 +)
39 +
40 +
41 +def _hex(c: str) -> tuple[int, int, int]:
42 + c = c.lstrip("#")
43 + return tuple(int(c[i : i + 2], 16) for i in (0, 2, 4)) # type: ignore
44 +
45 +
46 +def _fr(n) -> str:
47 + if isinstance(n, float) and not n.is_integer():
48 + return f"{n:,.2f}".replace(",", " ").replace(".", ",")
49 + return f"{int(n):,}".replace(",", " ")
50 +
51 +
52 +_SUBST = {
53 + "—": "-", "–": "-", "→": "->", "▲": "+", "▼": "-",
54 + "…": "...", "’": "'", "‘": "'", "“": '"', "”": '"',
55 + "œ": "oe", "Œ": "OE", "−": "-", " ": " ", " ": " ",
56 +}
57 +
58 +
59 +def _latin1(s: str) -> str:
60 + for k, v in _SUBST.items():
61 + s = s.replace(k, v)
62 + return s.encode("latin-1", "replace").decode("latin-1")
63 +
64 +
65 +class _PDF(FPDF):
66 + """FPDF avec en-tête/pied Groupe-KA sur chaque page (sauf couverture).
67 + Les polices core sont latin-1 : normalize_text sanitise en amont."""
68 +
69 + def normalize_text(self, text):
70 + return super().normalize_text(_latin1(text))
71 +
72 + def __init__(self, brand: str, accent: tuple, period_label: str):
73 + super().__init__(orientation="P", unit="mm", format="A4")
74 + self.brand = brand
75 + self.accent = accent
76 + self.period_label = period_label
77 + self.cover_mode = False
78 + self.set_margins(18, 20, 18)
79 + self.set_auto_page_break(True, margin=22)
80 +
81 + def header(self):
82 + if self.cover_mode:
83 + return
84 + self.set_font("helvetica", "B", 8.5)
85 + self.set_text_color(*INK)
86 + self.set_xy(18, 9)
87 + self.cell(0, 5, f"Groupe KA · {self.brand}")
88 + self.set_font("helvetica", "", 8)
89 + self.set_text_color(*INK3)
90 + self.set_xy(18, 9)
91 + self.cell(0, 5, "Rapport statistique", align="R")
92 + self.set_draw_color(*INK)
93 + self.set_line_width(0.5)
94 + self.line(18, 15.5, 192, 15.5)
95 + self.set_y(20)
96 +
97 + 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.
100 + if self.cover_mode or self.page_no() == 1:
101 + return
102 + self.set_y(-15)
103 + self.set_draw_color(*INK3)
104 + self.set_line_width(0.2)
105 + self.line(18, self.get_y() - 1.5, 192, self.get_y() - 1.5)
106 + self.set_font("helvetica", "", 7.5)
107 + self.set_text_color(*INK3)
108 + year = datetime.now(ZoneInfo("America/Toronto")).year
109 + self.cell(130, 5, f"© Groupe-KA — {year} — groupe-ka.com · {self.period_label}")
110 + self.cell(0, 5, f"p. {self.page_no()}/{{nb}}", align="R")
111 +
112 +
113 +class GroupeKAReport:
114 + def __init__(self, site: dict, dashboard: dict, mode: str = "complet"):
115 + self.site = site
116 + self.d = dashboard
117 + self.mode = mode
118 + self.accent = _hex(site.get("accent", "#d9f26b"))
119 + period = dashboard.get("period", {}) or {}
120 + self.period_label = period.get("label") or "toute la période"
121 + self.pdf = _PDF(site.get("wordmark", ""), self.accent, self.period_label)
122 + self.toc: list[tuple[str, int]] = []
123 +
124 + # ---------- primitives ----------
125 + def _card(self, x, y, w, h, fill=WHITE):
126 + p = self.pdf
127 + p.set_draw_color(*INK)
128 + p.set_line_width(0.45)
129 + p.set_fill_color(*fill)
130 + p.rect(x, y, w, h, style="DF", round_corners=True, corner_radius=2.2)
131 +
132 + def _kicker(self, text):
133 + p = self.pdf
134 + p.set_font("helvetica", "B", 8)
135 + p.set_text_color(*GREEN)
136 + p.set_draw_color(*GREEN)
137 + p.set_line_width(0.6)
138 + y = p.get_y() + 2
139 + p.line(p.l_margin, y, p.l_margin + 7, y)
140 + p.set_xy(p.l_margin + 9, y - 2.5)
141 + p.cell(0, 5, text.upper())
142 + p.ln(8)
143 +
144 + def _section_title(self, title):
145 + if self.pdf.get_y() > 240:
146 + self.pdf.add_page()
147 + self._kicker("Groupe KA · " + self.site.get("wordmark", ""))
148 + self.pdf.set_font("helvetica", "B", 15)
149 + self.pdf.set_text_color(*INK)
150 + self.pdf.set_x(self.pdf.l_margin)
151 + self.pdf.cell(0, 8, title)
152 + self.toc.append((title, self.pdf.page_no()))
153 + self.pdf.ln(11)
154 +
155 + # ---------- pages ----------
156 + def _cover(self):
157 + p = self.pdf
158 + p.cover_mode = True
159 + p.set_auto_page_break(False)
160 + p.add_page()
161 + p.set_fill_color(*PAPER)
162 + p.rect(0, 0, 210, 297, style="F")
163 + p.set_draw_color(*INK)
164 + p.set_line_width(1.0)
165 + p.rect(10, 10, 190, 277)
166 + # kicker
167 + p.set_font("helvetica", "B", 10)
168 + p.set_text_color(*GREEN)
169 + p.set_xy(24, 34)
170 + p.cell(0, 6, "GROUPE KA · RAPPORT STATISTIQUE")
171 + # wordmark : partie gauche + boîte encre/accent
172 + wm = self.site.get("wordmark", "")
173 + left, boxed = (wm.split("·") + [None])[:2] if "·" in wm else (wm, None)
174 + p.set_xy(24, 70)
175 + p.set_font("helvetica", "B", 40)
176 + p.set_text_color(*INK)
177 + p.cell(p.get_string_width(left) + 2, 20, left)
178 + if boxed:
179 + bw = p.get_string_width(boxed) + 12
180 + x = p.get_x() + 2
181 + p.set_fill_color(*INK)
182 + p.rect(x, 68, bw, 22, style="F", round_corners=True, corner_radius=3)
183 + p.set_text_color(*self.accent)
184 + p.set_xy(x + 6, 70)
185 + p.cell(bw - 12, 18, boxed)
186 + p.set_xy(24, 100)
187 + p.set_font("helvetica", "", 13)
188 + p.set_text_color(*INK2)
189 + p.multi_cell(150, 7, f"Rapport statistique — {wm}")
190 + now = datetime.now(ZoneInfo("America/Toronto"))
191 + per = self.d.get("period", {}) or {}
192 + p.set_xy(24, 125)
193 + p.set_font("helvetica", "", 10.5)
194 + rows = [
195 + ("Période couverte", self.period_label + (f" ({per.get('from')} → {per.get('to')})" if per.get("from") else "")),
196 + ("Généré le", now.strftime("%Y-%m-%d à %H:%M") + " (heure de l'Est)"),
197 + ("Plateforme", "https://" + self.site.get("domain", "")),
198 + ("Mode", "Rapport complet" if self.mode == "complet" else "Synthèse"),
199 + ]
200 + y = 128
201 + for k, v in rows:
202 + p.set_xy(24, y)
203 + p.set_text_color(*INK3)
204 + p.cell(40, 6, k)
205 + p.set_text_color(*INK)
206 + p.set_font("helvetica", "B", 10.5)
207 + p.cell(0, 6, str(v))
208 + p.set_font("helvetica", "", 10.5)
209 + y += 8
210 + # bande encre au pied
211 + p.set_fill_color(*INK)
212 + p.rect(10, 262, 190, 25, style="F")
213 + p.set_xy(24, 270)
214 + p.set_font("helvetica", "B", 12)
215 + p.set_text_color(*WHITE)
216 + p.cell(60, 8, "par Groupe ")
217 + p.set_text_color(*self.accent)
218 + p.set_xy(24 + p.get_string_width("par Groupe ") + 1, 270)
219 + p.cell(20, 8, "KA")
220 + p.set_font("helvetica", "B", 10)
221 + p.set_xy(24, 270)
222 + p.set_text_color(*self.accent)
223 + p.cell(162, 8, "groupe-ka.com", align="R")
224 + p.set_auto_page_break(True, margin=22)
225 + p.cover_mode = False
226 +
227 + def _kpis(self):
228 + kpis = self.d.get("kpis") or []
229 + if not kpis:
230 + return
231 + self._section_title("Synthèse des indicateurs")
232 + p = self.pdf
233 + cols, gw, gh, gap = 3, 56, 26, 3
234 + x0, y = p.l_margin, p.get_y()
235 + for i, k in enumerate(kpis[:9]):
236 + x = x0 + (i % cols) * (gw + gap)
237 + if i and i % cols == 0:
238 + y += gh + gap
239 + if y > 250:
240 + p.add_page(); y = p.get_y()
241 + self._card(x, y, gw, gh)
242 + p.set_xy(x + 4, y + 4)
243 + p.set_font("helvetica", "B", 14)
244 + p.set_text_color(*INK)
245 + val = k.get("value")
246 + p.cell(gw - 8, 7, (_fr(val) if isinstance(val, (int, float)) else str(val)) + (" " + k["unit"] if k.get("unit") else ""))
247 + p.set_xy(x + 4, y + 12)
248 + p.set_font("helvetica", "", 7.6)
249 + p.set_text_color(*INK2)
250 + p.multi_cell(gw - 8, 3.6, str(k.get("label", ""))[:70])
251 + if k.get("delta_pct") is not None:
252 + up = (k.get("direction") or ("up" if k["delta_pct"] >= 0 else "down")) == "up"
253 + p.set_xy(x + 4, y + gh - 6.5)
254 + p.set_font("helvetica", "B", 8)
255 + p.set_text_color(*(GREEN if up else DANGER))
256 + 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.")
258 + p.set_y(y + gh + 8)
259 +
260 + def _line_chart(self, s):
261 + p = self.pdf
262 + pts = s.get("points") or []
263 + if len(pts) < 2:
264 + return
265 + if p.get_y() > 200:
266 + 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)
271 + x0, y0, w, h = p.l_margin, p.get_y(), 174, 52
272 + self._card(x0, y0, w, h, fill=WHITE)
273 + cx, cy, cw, ch = x0 + 12, y0 + 6, w - 20, h - 16
274 + vals = [pt["v"] for pt in pts] + [c["v"] for c in (s.get("compare") or [])]
275 + vmax = max(vals) or 1
276 + vmin = min(0, min(vals))
277 + rng = (vmax - vmin) or 1
278 + # grille + graduations
279 + p.set_font("helvetica", "", 6.3)
280 + p.set_text_color(*INK3)
281 + p.set_draw_color(200, 200, 195)
282 + p.set_line_width(0.15)
283 + for g in range(5):
284 + gy = cy + ch - ch * g / 4
285 + p.line(cx, gy, cx + cw, gy)
286 + p.set_xy(x0 + 1, gy - 1.6)
287 + p.cell(10, 3, _fr(vmin + rng * g / 4), align="R")
288 +
289 + def draw(series, color, width, dash=None):
290 + n = len(series)
291 + p.set_draw_color(*color)
292 + p.set_line_width(width)
293 + if dash:
294 + p.set_dash_pattern(dash=1.2, gap=1.2)
295 + last = None
296 + for i, pt in enumerate(series):
297 + px = cx + cw * (i / (n - 1))
298 + py = cy + ch - ch * ((pt["v"] - vmin) / rng)
299 + if last:
300 + p.line(last[0], last[1], px, py)
301 + last = (px, py)
302 + p.set_dash_pattern()
303 +
304 + if s.get("compare"):
305 + draw(s["compare"], INK3, 0.35, dash=True)
306 + draw(pts, self.accent, 0.7)
307 + # libellés d'axe X (premier / milieu / dernier)
308 + p.set_text_color(*INK3)
309 + for frac, idx in ((0, 0), (0.5, len(pts) // 2), (1, -1)):
310 + p.set_xy(cx + cw * frac - 9, cy + ch + 1.5)
311 + p.cell(18, 3, str(pts[idx].get("t", ""))[:10], align="C")
312 + p.set_y(y0 + h + 4)
313 + if s.get("compare"):
314 + p.set_font("helvetica", "", 6.8)
315 + p.set_text_color(*INK3)
316 + p.cell(0, 4, "— période courante (accent) · ---- période comparée")
317 + p.ln(6)
318 + else:
319 + p.ln(2)
320 +
321 + def _bars(self, title, items, unit=""):
322 + p = self.pdf
323 + items = [it for it in (items or []) if isinstance(it.get("value"), (int, float))][:12]
324 + if not items:
325 + return
326 + need = 10 + len(items) * 7
327 + if p.get_y() + need > 265:
328 + 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)
333 + vmax = max(it["value"] for it in items) or 1
334 + for it in items:
335 + y = p.get_y()
336 + p.set_font("helvetica", "", 7.6)
337 + p.set_text_color(*INK)
338 + p.set_x(p.l_margin)
339 + p.cell(46, 5, str(it["label"])[:34])
340 + bw = 96 * (it["value"] / vmax)
341 + p.set_fill_color(*self.accent)
342 + p.set_draw_color(*INK)
343 + p.set_line_width(0.25)
344 + 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)
346 + p.set_font("helvetica", "B", 7.6)
347 + p.cell(26, 5, _fr(it["value"]) + (" " + unit if unit else ""), align="R")
348 + p.ln(6.4)
349 + p.ln(3)
350 +
351 + def _donut(self, b):
352 + # anneau vectoriel simple (arcs) + légende
353 + p = self.pdf
354 + items = [it for it in (b.get("items") or []) if it.get("value")][:8]
355 + total = sum(it["value"] for it in items)
356 + if not items or not total:
357 + return
358 + if p.get_y() > 210:
359 + 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)
364 + 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 + start = -90.0
367 + for i, it in enumerate(items):
368 + 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))
371 + steps = max(2, int(72 * frac))
372 + p.set_fill_color(*col)
373 + p.set_draw_color(*col)
374 + for st in range(steps):
375 + a0 = math.radians(start + 360 * frac * st / steps)
376 + a1 = math.radians(start + 360 * frac * (st + 1) / steps)
377 + p.polygon(
378 + [(cx, cy),
379 + (cx + r * math.cos(a0), cy + r * math.sin(a0)),
380 + (cx + r * math.cos(a1), cy + r * math.sin(a1))],
381 + style="DF",
382 + )
383 + start += 360 * frac
384 + p.set_fill_color(*WHITE)
385 + p.set_draw_color(*INK)
386 + p.set_line_width(0.4)
387 + p.ellipse(cx - 11, cy - 11, 22, 22, style="DF")
388 + p.ellipse(cx - r, cy - r, 2 * r, 2 * r, style="D")
389 + # légende
390 + ly = cy - 22
391 + 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))
394 + p.set_fill_color(*col)
395 + p.set_draw_color(*INK)
396 + p.rect(p.l_margin + 60, ly + 0.8, 4, 4, style="DF")
397 + p.set_xy(p.l_margin + 66, ly)
398 + p.set_font("helvetica", "", 7.6)
399 + p.set_text_color(*INK)
400 + pct = 100 * it["value"] / total
401 + p.cell(0, 5.6, f"{str(it['label'])[:40]} — {_fr(it['value'])} ({pct:.1f} %)".replace(".", ","))
402 + ly += 5.6
403 + p.set_y(max(cy + r, ly) + 6)
404 +
405 + def _table(self, t):
406 + p = self.pdf
407 + cols = t.get("columns") or []
408 + rows = t.get("rows") or []
409 + if not cols or not rows:
410 + return
411 + self._section_title(t.get("title", "Tableau"))
412 + w = 174 / len(cols)
413 + def head():
414 + p.set_font("helvetica", "B", 7.6)
415 + p.set_fill_color(*INK)
416 + p.set_text_color(*WHITE)
417 + for c in cols:
418 + p.cell(w, 6, " " + str(c)[:30], fill=True)
419 + p.ln(6)
420 + head()
421 + p.set_text_color(*INK)
422 + for i, row in enumerate(rows[:200]):
423 + if p.get_y() > 262:
424 + p.add_page()
425 + head()
426 + p.set_text_color(*INK)
427 + p.set_font("helvetica", "", 7.4)
428 + p.set_fill_color(*(SURFACE2 if i % 2 else WHITE))
429 + for cell in row:
430 + txt = _fr(cell) if isinstance(cell, (int, float)) else str(cell)
431 + p.cell(w, 5.4, " " + txt[:34], fill=True)
432 + p.ln(5.4)
433 + if len(rows) > 200:
434 + p.set_font("helvetica", "", 7)
435 + p.set_text_color(*INK3)
436 + p.cell(0, 5, f"… {len(rows) - 200} lignes supplémentaires non imprimées")
437 + p.ln(6)
438 +
439 + def _records(self):
440 + recs = self.d.get("records") or []
441 + if not recs:
442 + return
443 + self._section_title("Records & faits marquants")
444 + p = self.pdf
445 + for r in recs[:10]:
446 + if p.get_y() > 258:
447 + p.add_page()
448 + y = p.get_y()
449 + self._card(p.l_margin, y, 174, 11, fill=SURFACE2)
450 + p.set_xy(p.l_margin + 4, y + 2)
451 + p.set_font("helvetica", "", 8.6)
452 + p.set_text_color(*INK2)
453 + p.cell(96, 7, str(r.get("label", ""))[:70])
454 + p.set_font("helvetica", "B", 9)
455 + p.set_text_color(*INK)
456 + p.cell(52, 7, str(r.get("value", ""))[:36], align="R")
457 + p.set_font("helvetica", "", 7.6)
458 + p.set_text_color(*INK3)
459 + p.cell(20, 7, str(r.get("date", "") or ""), align="R")
460 + p.set_y(y + 13.5)
461 + p.ln(4)
462 +
463 + def _final_page(self):
464 + p = self.pdf
465 + p.add_page()
466 + self._kicker("Groupe KA · contact")
467 + p.set_font("helvetica", "B", 15)
468 + p.set_text_color(*INK)
469 + p.cell(0, 8, "Coordonnées du Groupe KA")
470 + p.ln(12)
471 + for email, role in EMAILS:
472 + p.set_font("helvetica", "B", 10.5)
473 + p.set_text_color(*INK)
474 + p.cell(0, 6, email)
475 + p.ln(5.5)
476 + p.set_font("helvetica", "", 8.6)
477 + p.set_text_color(*INK3)
478 + p.cell(0, 5, role)
479 + p.ln(8)
480 + p.ln(2)
481 + p.set_font("helvetica", "B", 10)
482 + p.set_text_color(*GREEN)
483 + p.cell(0, 6, "groupe-ka.com — le portail de l'écosystème ·Ka")
484 + p.ln(10)
485 + p.set_draw_color(*self.accent)
486 + p.set_line_width(0.8)
487 + p.line(p.l_margin, p.get_y(), p.l_margin + 30, p.get_y())
488 + p.ln(4)
489 + p.set_font("helvetica", "", 8.6)
490 + p.set_text_color(*INK2)
491 + p.multi_cell(160, 4.6, DISCLAIMER)
492 + p.ln(4)
493 + p.set_font("helvetica", "", 7.6)
494 + p.set_text_color(*INK3)
495 + p.multi_cell(
496 + 160, 4.2,
497 + "Mentions : rapport généré automatiquement à partir des données réelles de la "
498 + "plateforme au moment indiqué en couverture. Conditions d'utilisation, politique "
499 + "de confidentialité et protection des renseignements personnels (Loi 25) : "
500 + "groupe-ka.com/conditions · /confidentialite · /loi-25.",
501 + )
502 +
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
507 +
508 + def build(self) -> bytes:
509 + p = self.pdf
510 + p.alias_nb_pages()
511 + self._cover()
512 + if self.mode == "synthese":
513 + p.add_page()
514 + self._kpis()
515 + self._records()
516 + self._final_page()
517 + else:
518 + p.add_page()
519 + toc_page_no = p.page_no()
520 + p.add_page()
521 + 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"))
535 + for t in self.d.get("tables") or []:
536 + self._table(t)
537 + self._records()
538 + self._final_page()
539 + # sommaire écrit sur la page réservée (page 2)
540 + last_page = p.page
541 + p.page = toc_page_no
542 + p.set_y(22)
543 + p.set_font("helvetica", "B", 15)
544 + p.set_text_color(*INK)
545 + p.cell(0, 8, "Sommaire")
546 + p.ln(12)
547 + p.set_font("helvetica", "", 9.5)
548 + for title, page_no in self.toc:
549 + p.set_text_color(*INK)
550 + p.cell(140, 6.5, title[:80])
551 + p.set_text_color(*INK3)
552 + p.cell(0, 6.5, str(page_no), align="R")
553 + p.ln(6.5)
554 + p.page = last_page
555 + return bytes(p.output())
556 +
557 +
558 +def filename(platform_id: str, period: str) -> str:
559 + today = datetime.now(ZoneInfo("America/Toronto")).strftime("%Y-%m-%d")
560 + return f"groupe-ka_{platform_id}_stats_{period}_{today}.pdf"
added louka/statsdash.py +381 −0
@@ -0,0 +1,381 @@
1 +# -----------------------------------------------------------------------------
2 +# Lou-Ka — Agrégateur de logements à louer (province de Québec)
3 +# Auteur : Simon-Pierre Boucher — contact@spboucher.ai
4 +# statsdash.py : tableau de bord statistique — contrat commun Groupe KA
5 +# (voir frontend/src/ka/stats/SPEC.md). Construit le JSON du dashboard à
6 +# partir de requêtes SQL agrégées (listings, sync_log, price_log) avec un
7 +# cache mémoire de 5 minutes par clé de période. AUCUNE stat inventée :
8 +# une section sans donnée réelle est simplement absente du JSON.
9 +# -----------------------------------------------------------------------------
10 +from __future__ import annotations
11 +
12 +import json
13 +import threading
14 +import time
15 +from datetime import date, datetime, timedelta
16 +from pathlib import Path
17 +from zoneinfo import ZoneInfo
18 +
19 +from . import db
20 +
21 +TZ = ZoneInfo("America/Toronto")
22 +ROOT = Path(__file__).resolve().parent.parent
23 +SOURCES_PATH = ROOT / "data" / "sources.json"
24 +
25 +CACHE_TTL = 300 # secondes
26 +_cache: dict[str, tuple[float, dict]] = {}
27 +_cache_lock = threading.Lock()
28 +
29 +PERIODS = {
30 + "auj": ("Aujourd'hui", 0),
31 + "7j": ("7 jours", 6),
32 + "30j": ("30 jours", 29),
33 + "3m": ("3 mois", 89),
34 + "6m": ("6 mois", 179),
35 + "12m": ("12 mois", 364),
36 +}
37 +
38 +
39 +# ---------------------------------------------------------------- utilitaires
40 +def _day_start_ts(d: date) -> float:
41 + return datetime(d.year, d.month, d.day, tzinfo=TZ).timestamp()
42 +
43 +
44 +def _coverage(con) -> tuple[date | None, date | None]:
45 + """Première et dernière date observées dans la base (first/last_seen)."""
46 + row = con.execute(
47 + "SELECT MIN(first_seen) a, MAX(last_seen) b FROM listings"
48 + " WHERE dup_of IS NULL"
49 + ).fetchone()
50 + if row["a"] is None:
51 + return None, None
52 + return (datetime.fromtimestamp(row["a"], TZ).date(),
53 + datetime.fromtimestamp(row["b"], TZ).date())
54 +
55 +
56 +def resolve_period(period: str, from_: str | None, to_: str | None,
57 + cov_min: date, today: date) -> tuple[date, date, str]:
58 + """Bornes [from, to] (dates locales incluses) + libellé humain."""
59 + if from_ and to_:
60 + try:
61 + a = date.fromisoformat(from_)
62 + b = date.fromisoformat(to_)
63 + if a > b:
64 + a, b = b, a
65 + return max(a, cov_min), min(b, today), f"{a} → {b}"
66 + except ValueError:
67 + pass
68 + if period == "tout":
69 + return cov_min, today, "Toute la période"
70 + if period == "annee":
71 + return max(date(today.year, 1, 1), cov_min), today, "Année en cours"
72 + label, back = PERIODS.get(period, PERIODS["30j"])
73 + return max(today - timedelta(days=back), cov_min), today, label
74 +
75 +
76 +def _pct(cur: float, prev: float) -> float | None:
77 + if not prev:
78 + return None
79 + return round(100.0 * (cur - prev) / prev, 1)
80 +
81 +
82 +def _days(a: date, b: date) -> list[date]:
83 + return [a + timedelta(days=i) for i in range((b - a).days + 1)]
84 +
85 +
86 +def _fr_money(n: float) -> str:
87 + return f"{int(round(n)):,}".replace(",", " ") + " $"
88 +
89 +
90 +def _source_names() -> dict[str, str]:
91 + try:
92 + reg = json.loads(SOURCES_PATH.read_text(encoding="utf-8"))["sources"]
93 + return {s["id"]: s.get("name") or s["id"] for s in reg}
94 + except (OSError, ValueError, KeyError):
95 + return {}
96 +
97 +
98 +# ------------------------------------------------------------------- dashboard
99 +def compute(period: str = "30j", from_: str | None = None,
100 + to_: str | None = None) -> dict:
101 + key = f"{period}|{from_ or ''}|{to_ or ''}"
102 + now = time.time()
103 + with _cache_lock:
104 + hit = _cache.get(key)
105 + if hit and hit[0] > now:
106 + return hit[1]
107 + data = _compute(period, from_, to_)
108 + with _cache_lock:
109 + _cache[key] = (now + CACHE_TTL, data)
110 + return data
111 +
112 +
113 +def _compute(period: str, from_: str | None, to_: str | None) -> dict:
114 + con = db.connect()
115 + try:
116 + return _build(con, period, from_, to_)
117 + finally:
118 + con.close()
119 +
120 +
121 +def _build(con, period: str, from_: str | None, to_: str | None) -> dict:
122 + today = datetime.now(TZ).date()
123 + cov_min, _cov_max = _coverage(con)
124 + if cov_min is None: # base vide
125 + return {"updated": datetime.now(TZ).isoformat(),
126 + "period": {"from": None, "to": None, "label": "—"},
127 + "kpis": [], "series": [], "breakdowns": [], "tables": [],
128 + "records": []}
129 +
130 + d_from, d_to, label = resolve_period(period, from_, to_, cov_min, today)
131 + ts_from = _day_start_ts(d_from)
132 + ts_to = _day_start_ts(d_to + timedelta(days=1)) # borne exclusive
133 +
134 + # ---- histogrammes journaliers (2 balayages agrégés, réutilisés partout)
135 + starts = {r["d"]: r["n"] for r in con.execute(
136 + "SELECT date(first_seen,'unixepoch','localtime') d, COUNT(*) n"
137 + " FROM listings WHERE dup_of IS NULL GROUP BY d")}
138 + ends = {r["d"]: r["n"] for r in con.execute(
139 + "SELECT date(last_seen,'unixepoch','localtime') d, COUNT(*) n"
140 + " FROM listings WHERE dup_of IS NULL AND active=0 GROUP BY d")}
141 +
142 + def actives_at(d: date) -> int:
143 + """Reconstruction : cum(first_seen<=d) − cum(retraits<=d−1)."""
144 + iso = d.isoformat()
145 + prev = (d - timedelta(days=1)).isoformat()
146 + s = sum(n for dd, n in starts.items() if dd <= iso)
147 + e = sum(n for dd, n in ends.items() if dd <= prev)
148 + return s - e
149 +
150 + # ---- KPI ------------------------------------------------------------
151 + actives_now = con.execute(
152 + "SELECT COUNT(*) n FROM listings WHERE active=1 AND dup_of IS NULL"
153 + ).fetchone()["n"]
154 + new_in = sum(n for d, n in starts.items()
155 + if d_from.isoformat() <= d <= d_to.isoformat())
156 + removed_in = sum(n for d, n in ends.items()
157 + if d_from.isoformat() <= d <= d_to.isoformat())
158 +
159 + # période précédente de même longueur (uniquement si couverte par la base)
160 + span = (d_to - d_from).days + 1
161 + p_from, p_to = d_from - timedelta(days=span), d_from - timedelta(days=1)
162 + prev_ok = p_from >= cov_min
163 + new_prev = removed_prev = None
164 + if prev_ok:
165 + new_prev = sum(n for d, n in starts.items()
166 + if p_from.isoformat() <= d <= p_to.isoformat())
167 + removed_prev = sum(n for d, n in ends.items()
168 + if p_from.isoformat() <= d <= p_to.isoformat())
169 +
170 + actives_prev = actives_at(p_to) if d_from - timedelta(days=1) >= cov_min else None
171 +
172 + row = con.execute(
173 + "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()
176 + avg_price, n_priced = row["avg_p"], row["n_p"]
177 + median_price = None
178 + if n_priced:
179 + median_price = con.execute(
180 + "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"]
183 +
184 + connectors = con.execute(
185 + "SELECT COUNT(DISTINCT source) n FROM sync_log"
186 + " WHERE ok=1 AND ts>=? AND ts<?", (ts_from, ts_to)).fetchone()["n"]
187 + cities_n = con.execute(
188 + "SELECT COUNT(DISTINCT city) n FROM listings"
189 + " WHERE active=1 AND dup_of IS NULL AND city<>''").fetchone()["n"]
190 +
191 + kpis = [
192 + {"id": "actives", "label": "Annonces actives", "value": actives_now,
193 + "delta_pct": _pct(actives_now, actives_prev) if actives_prev else None,
194 + "direction": "up" if (actives_prev and actives_now >= actives_prev) else
195 + ("down" if actives_prev else None)},
196 + {"id": "nouvelles", "label": "Nouvelles annonces (période)",
197 + "value": new_in,
198 + "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},
200 + {"id": "retirees", "label": "Annonces retirées (période)",
201 + "value": removed_in,
202 + "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},
204 + ]
205 + if avg_price:
206 + kpis.append({"id": "loyer_moyen", "label": "Loyer moyen (actives)",
207 + "value": round(avg_price), "unit": "$"})
208 + if median_price:
209 + kpis.append({"id": "loyer_median", "label": "Loyer médian (actives)",
210 + "value": round(median_price), "unit": "$"})
211 + kpis.append({"id": "connecteurs", "label": "Connecteurs actifs (période)",
212 + "value": connectors})
213 + kpis.append({"id": "villes", "label": "Villes couvertes", "value": cities_n})
214 + kpis = [{k: v for k, v in kpi.items() if v is not None} for kpi in kpis]
215 +
216 + # ---- séries temporelles ----------------------------------------------
217 + days = _days(d_from, d_to)
218 + series = []
219 + if len(days) >= 2:
220 + pts_act = [{"t": d.isoformat(), "v": actives_at(d)} for d in days]
221 + s_act = {"id": "actives_jour", "title": "Annonces actives par jour",
222 + "unit": "annonces", "kind": "line", "points": pts_act}
223 + pts_new = [{"t": d.isoformat(), "v": starts.get(d.isoformat(), 0)}
224 + for d in days]
225 + s_new = {"id": "nouvelles_jour", "title": "Nouvelles annonces par jour",
226 + "unit": "annonces", "kind": "line", "points": pts_new}
227 + if prev_ok:
228 + pdays = _days(p_from, p_to)
229 + s_act["compare"] = [{"t": d.isoformat(), "v": actives_at(d)}
230 + for d in pdays]
231 + s_new["compare"] = [{"t": d.isoformat(),
232 + "v": starts.get(d.isoformat(), 0)}
233 + for d in pdays]
234 + series = [s_act, s_new]
235 +
236 + # ---- répartitions ------------------------------------------------------
237 + types = [{"label": r["t"] or "Non précisé", "value": r["n"]}
238 + for r in con.execute(
239 + "SELECT unit_type t, COUNT(*) n FROM listings"
240 + " WHERE active=1 AND dup_of IS NULL GROUP BY unit_type"
241 + " ORDER BY n DESC LIMIT 8")]
242 + names = _source_names()
243 + by_source = [{"label": names.get(r["s"], r["s"]), "value": r["n"]}
244 + for r in con.execute(
245 + "SELECT source s, COUNT(*) n FROM listings"
246 + " WHERE active=1 AND dup_of IS NULL GROUP BY source"
247 + " ORDER BY n DESC LIMIT 12")]
248 + breakdowns = []
249 + if types:
250 + breakdowns.append({"id": "types", "title": "Annonces actives par taille",
251 + "kind": "donut", "items": types})
252 + if by_source:
253 + breakdowns.append({"id": "sources", "title": "Top sources (annonces actives)",
254 + "kind": "bar", "items": by_source})
255 +
256 + # ---- géographie --------------------------------------------------------
257 + geo_items = [{"label": r["c"], "value": r["n"]} for r in con.execute(
258 + "SELECT city c, COUNT(*) n FROM listings"
259 + " WHERE active=1 AND dup_of IS NULL AND city<>''"
260 + " GROUP BY city ORDER BY n DESC LIMIT 14")]
261 + geo = ({"title": "Top villes (annonces actives)", "items": geo_items}
262 + if geo_items else None)
263 +
264 + # ---- heatmap (nouvelles annonces par jour, période choisie) ------------
265 + heat_cells = [{"date": d.isoformat(), "value": starts.get(d.isoformat(), 0)}
266 + for d in days if starts.get(d.isoformat())]
267 + heatmap = ({"title": "Nouvelles annonces par jour", "cells": heat_cells}
268 + if heat_cells else None)
269 +
270 + # ---- tableaux ----------------------------------------------------------
271 + tables = []
272 + top_villes = con.execute(
273 + """SELECT city, COUNT(*) n, AVG(CASE WHEN price>0 THEN price END) avg_p,
274 + SUM(CASE WHEN first_seen>=? AND first_seen<? THEN 1 ELSE 0 END) new_n
275 + FROM listings WHERE active=1 AND dup_of IS NULL AND city<>''
276 + GROUP BY city ORDER BY n DESC LIMIT 50""", (ts_from, ts_to)).fetchall()
277 + removed_by_city = {r["city"]: r["n"] for r in con.execute(
278 + """SELECT city, COUNT(*) n FROM listings
279 + WHERE active=0 AND dup_of IS NULL AND city<>''
280 + AND last_seen>=? AND last_seen<? GROUP BY city""",
281 + (ts_from, ts_to)).fetchall()}
282 + if top_villes:
283 + rows = []
284 + for r in top_villes:
285 + net = r["new_n"] - removed_by_city.get(r["city"], 0)
286 + rows.append([
287 + r["city"], r["n"],
288 + _fr_money(r["avg_p"]) if r["avg_p"] else "—",
289 + r["new_n"], f"{'+' if net >= 0 else ''}{net}"])
290 + tables.append({"id": "top_villes", "title": "Top villes",
291 + "columns": ["Ville", "Annonces actives", "Loyer moyen",
292 + "Nouvelles (période)", "Δ net (période)"],
293 + "rows": rows})
294 +
295 + top_srcs = con.execute(
296 + """SELECT source s, COUNT(*) n, AVG(CASE WHEN price>0 THEN price END) avg_p,
297 + SUM(CASE WHEN first_seen>=? AND first_seen<? THEN 1 ELSE 0 END) new_n
298 + FROM listings WHERE active=1 AND dup_of IS NULL
299 + GROUP BY source ORDER BY n DESC LIMIT 50""", (ts_from, ts_to)).fetchall()
300 + last_sync = {r["source"]: r["ts"] for r in con.execute(
301 + "SELECT source, MAX(ts) ts FROM sync_log WHERE ok=1 GROUP BY source")}
302 + if top_srcs:
303 + rows = []
304 + for r in top_srcs:
305 + ls = last_sync.get(r["s"])
306 + rows.append([
307 + names.get(r["s"], r["s"]), r["n"],
308 + _fr_money(r["avg_p"]) if r["avg_p"] else "—",
309 + r["new_n"],
310 + datetime.fromtimestamp(ls, TZ).strftime("%Y-%m-%d %H:%M") if ls else "—"])
311 + tables.append({"id": "top_gestionnaires",
312 + "title": "Top gestionnaires & sources",
313 + "columns": ["Gestionnaire / source", "Annonces actives",
314 + "Loyer moyen", "Nouvelles (période)",
315 + "Dernière synchro"],
316 + "rows": rows})
317 +
318 + # ---- records & faits marquants -----------------------------------------
319 + records = []
320 + in_period = {d: n for d, n in starts.items()
321 + if d_from.isoformat() <= d <= d_to.isoformat()}
322 + if in_period:
323 + best = max(in_period, key=in_period.get)
324 + records.append({"label": "Jour record d'ajouts",
325 + "value": f"{in_period[best]:,}".replace(",", " ") + " annonces",
326 + "date": best})
327 + rem_period = {d: n for d, n in ends.items()
328 + if d_from.isoformat() <= d <= d_to.isoformat()}
329 + if rem_period:
330 + worst = max(rem_period, key=rem_period.get)
331 + records.append({"label": "Jour record de retraits",
332 + "value": f"{rem_period[worst]:,}".replace(",", " ") + " annonces",
333 + "date": worst})
334 + if top_villes:
335 + ville = max(top_villes, key=lambda r: r["new_n"])
336 + if ville["new_n"]:
337 + records.append({"label": "Ville la plus dynamique (nouvelles annonces)",
338 + "value": f"{ville['city']} — {ville['new_n']}"})
339 + # plus forte baisse de loyer observée dans la période (journal de prix)
340 + # bornes de plausibilité (loyers résidentiels) : les écarts extrêmes sont
341 + # presque toujours des erreurs de lecture à la source, pas des baisses.
342 + drop = con.execute(
343 + """SELECT a.uid uid, a.price p0, b.price p1, b.ts ts1
344 + FROM price_log a JOIN price_log b
345 + ON a.uid=b.uid AND b.ts>a.ts
346 + AND a.price BETWEEN 300 AND 15000
347 + AND b.price BETWEEN 300 AND 15000
348 + AND b.price<a.price AND b.price>=a.price*0.5
349 + WHERE a.ts>=? AND b.ts<? ORDER BY (a.price-b.price) DESC LIMIT 1""",
350 + (ts_from, ts_to)).fetchone()
351 + if drop:
352 + li = con.execute("SELECT city, unit_type FROM listings WHERE uid=?",
353 + (drop["uid"],)).fetchone()
354 + where = " · ".join(x for x in [li["unit_type"], li["city"]] if x) if li else ""
355 + records.append({
356 + "label": "Plus forte baisse de loyer observée"
357 + + (f" ({where})" if where else ""),
358 + "value": f"−{_fr_money(drop['p0'] - drop['p1'])}"
359 + f" ({_fr_money(drop['p0'])} → {_fr_money(drop['p1'])})",
360 + "date": datetime.fromtimestamp(drop["ts1"], TZ).date().isoformat()})
361 + if top_srcs:
362 + src = max(top_srcs, key=lambda r: r["new_n"])
363 + if src["new_n"]:
364 + records.append({"label": "Source la plus active (nouvelles annonces)",
365 + "value": f"{names.get(src['s'], src['s'])} — {src['new_n']}"})
366 +
367 + out = {
368 + "updated": datetime.now(TZ).isoformat(),
369 + "period": {"from": d_from.isoformat(), "to": d_to.isoformat(),
370 + "label": label},
371 + "kpis": kpis,
372 + "series": series,
373 + "breakdowns": breakdowns,
374 + "tables": tables,
375 + "records": records,
376 + }
377 + if geo:
378 + out["geo"] = geo
379 + if heatmap:
380 + out["heatmap"] = heatmap
381 + return out
modified louka/web.py +39 −0
@@ -366,6 +366,45 @@ def stats_detailed():
366 366 return marketstats.compute()
367 367
368 368
369 +# --- Module Stats commun Groupe KA (contrat frontend/src/ka/stats/SPEC.md) ---
370 +_PERIODES_VALIDES = {"auj", "7j", "30j", "3m", "6m", "12m", "annee", "tout"}
371 +
372 +
373 +@app.get("/api/stats/dashboard")
374 +def stats_dashboard(period: str = "30j",
375 + from_: str | None = Query(None, alias="from"),
376 + to: str | None = None):
377 + """Tableau de bord analytique (KPI, séries, répartitions, tableaux…)."""
378 + from . import statsdash
379 + if period not in _PERIODES_VALIDES and not (from_ and to):
380 + period = "30j"
381 + return statsdash.compute(period, from_, to)
382 +
383 +
384 +@app.get("/api/stats/report")
385 +def stats_report(period: str = "30j",
386 + from_: str | None = Query(None, alias="from"),
387 + to: str | None = None,
388 + mode: str = "complet"):
389 + """Rapport statistique PDF estampillé Groupe-KA (complet ou synthèse)."""
390 + from fastapi.responses import Response
391 + from . import kapdf, statsdash
392 + if period not in _PERIODES_VALIDES:
393 + period = "perso" if (from_ and to) else "30j"
394 + dash = statsdash.compute(period if period != "perso" else "30j",
395 + from_, to)
396 + eco = json.loads((ROOT / "frontend" / "src" / "ka" /
397 + "ecosystem.json").read_text(encoding="utf-8"))
398 + site = next(s for s in eco["sites"] if s["id"] == "lou-ka")
399 + data = kapdf.GroupeKAReport(
400 + site=site, dashboard=dash,
401 + mode=mode if mode in ("complet", "synthese") else "complet").build()
402 + fname = kapdf.filename("lou-ka", period)
403 + return Response(content=data, media_type="application/pdf",
404 + headers={"Content-Disposition":
405 + f'attachment; filename="{fname}"'})
406 +
407 +
369 408
370 409 @app.post("/api/sync")
371 410 def trigger_sync(background: BackgroundTasks, source: str | None = None):
372 411