SPB Git forge

spb/immo-ka

Public

Immo-Ka — agrégateur des propriétés à vendre au Québec (73 connecteurs, ~40 000 annonces, React+FastAPI)

112commits 1branches 0releases
125.4 MBsize
maindefault branch
13 days agolast push
Python 47.5% HTML 27.9% TypeScript 15.5% CSS 7.2% JavaScript 2%

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

- immoka/stats.py : /api/stats/dashboard (contrat ka-stats, cache 5 min) —
  KPI (actives, nouvelles, retirées, prix moyen/médian, prix/m², villes,
  connecteurs, tension retraits/nouvelles), séries quotidiennes reconstruites
  (actives/nouvelles/retraits), répartitions (types, fourchettes de prix,
  chambres), géo par région (fusion accents/casse), heatmap, top villes,
  délai de présence par ville, records. Deltas seulement si la période
  précédente a été observée en entier — rien d'inventé.
- immoka/kapdf.py (copie du kit ka-ui) + /api/stats/report : PDF estampillé
  Groupe-KA (complet / synthèse), wordmark Immo·Ka, accent #e23744.
- frontend/src/pages/Stats.tsx : page réécrite sur le kit ka/stats/kacharts —
  PdfButton + fraîcheur, KPI auto-fit, sélecteur de période (refetch),
  courbes, anneau, barres, géo, heatmap, tableaux triables, records ;
  bloc Vrai-Prix conservé. Zéro débordement à 360/768/1440.
- fpdf2 ajouté aux dépendances.

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

8 changed files +2,285 −132

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 +170 −131
@@ -1,17 +1,40 @@
1 1 // -----------------------------------------------------------------------------
2 2 // Immo-Ka — Agrégateur de propriétés à vendre (province de Québec)
3 3 // Auteur : Simon-Pierre Boucher — contact@spboucher.ai
4 −// pages/Stats.tsx : statistiques du marché agrégé (totaux + répartitions)
5 −// Les répartitions sont calculées à partir de /api/facets et /api/listings
6 −// (échantillon trié par prix) — le backend n'expose pas d'agrégats détaillés.
4 +// pages/Stats.tsx : tableau de bord analytique du module Stats commun Groupe KA
5 +// (voir ka/stats/SPEC.md). Consomme /api/stats/dashboard (période → refetch)
6 +// et propose l'export PDF /api/stats/report via le kit ka/stats/kacharts.
7 +// Section spécifique Immo-Ka conservée : écart prix demandé vs Vrai-Prix.
7 8 // -----------------------------------------------------------------------------
8 −import { useEffect, useMemo, useState } from "react";
9 −import { Link } from "react-router-dom";
9 +import { useCallback, useEffect, useState } from "react";
10 +import type { CSSProperties } from "react";
10 11 import {
11 − Facets, Listing, Stats, VpBanniere,
12 − fetchFacets, fetchListings, fetchSources, fetchStats,
13 − registerSourceNames, sourceName,
14 −} from "../api";
12 + BarChart, CalendarHeatmap, DataTable, Donut, EmptyBlock, Fraicheur,
13 + KpiCard, LineChart, PdfButton, PeriodSelector, RecordCard,
14 +} from "../ka/stats/kacharts";
15 +import type { BreakItem, Kpi, RecordFact, Serie, TableSpec } from "../ka/stats/kacharts";
16 +import { fetchStats } from "../api";
17 +import type { Stats as LegacyStats, VpBanniere } from "../api";
18 +
19 +interface Breakdown { id: string; title: string; kind: string; items: BreakItem[] }
20 +interface Dashboard {
21 + updated: string;
22 + period: { from: string; to: string; label: string; observed_from?: string };
23 + kpis: Kpi[];
24 + series: Serie[];
25 + breakdowns: Breakdown[];
26 + geo?: { title: string; items: BreakItem[] };
27 + heatmap?: { title: string; cells: { date: string; value: number }[] };
28 + tables: TableSpec[];
29 + records: RecordFact[];
30 +}
31 +
32 +const gridAutoFit = (min: number): CSSProperties => ({
33 + display: "grid",
34 + gridTemplateColumns: `repeat(auto-fit, minmax(min(100%, ${min}px), 1fr))`,
35 + gap: 14,
36 + minWidth: 0,
37 +});
15 38
16 39 // --- Survalorisation vs Vrai-Prix : jauge divergente par bannière ------------
17 40 const VP_SCALE = 30; // la jauge couvre −30 % … +30 %
@@ -45,144 +68,160 @@ function VpGauge({ b }: { b: VpBanniere }) {
45 68 );
46 69 }
47 70
48 −function Bars({ rows, unit }: { rows: { key: string; n: number; href?: string }[]; unit?: string }) {
49 − const max = Math.max(1, ...rows.map((r) => r.n));
71 +function VraiPrixBlock({ legacy }: { legacy: LegacyStats | null }) {
72 + const vp = legacy?.vraiprix;
73 + if (!vp?.bannieres?.length) return null;
50 74 return (
51 − <div className="hbars">
52 − {rows.map((r) => (
53 − <div className="hbar-row" key={r.key}>
54 − <div className="hbar-label">{r.href ? <Link to={r.href}>{r.key}</Link> : r.key}</div>
55 − <div className="hbar-track"><span className="hbar-fill" style={{ width: `${(r.n / max) * 100}%` }} /></div>
56 − <div className="hbar-value">{r.n.toLocaleString("fr-CA")}{unit ? <em> {unit}</em> : ""}</div>
57 − </div>
58 − ))}
75 + <div className="viz-card">
76 + <h2>Prix demandé vs valeur Vrai-Prix</h2>
77 + <div className="viz-sub">
78 + Écart médian entre le prix demandé et l'estimation indépendante Vrai-Prix, par bannière.
79 + La bande grise couvre la moitié centrale des annonces (P25–P75) ; le trait est la médiane.
80 + </div>
81 + <div className="vpg-axis">
82 + <div><span>−{VP_SCALE} %</span><span>estimation Vrai-Prix</span><span>+{VP_SCALE} %</span></div>
83 + </div>
84 + {vp.ensemble && <VpGauge b={vp.ensemble} />}
85 + <div className="vpg-sep" />
86 + {vp.bannieres.map((b) => <VpGauge b={b} key={b.banniere} />)}
87 + <div className="vpg-legend">
88 + <span><i className="vps-sous" /> sous l'estimation (≤ −5 %)</span>
89 + <span><i className="vps-juste" /> dans l'estimation</span>
90 + <span><i className="vps-sur" /> survalorisé (≥ +10 %)</span>
91 + </div>
59 92 </div>
60 93 );
61 94 }
62 95
96 +// --- Page ---------------------------------------------------------------------
63 97 export default function StatsPage() {
64 − const [stats, setStats] = useState<Stats | null>(null);
65 − const [facets, setFacets] = useState<Facets | null>(null);
66 − const [sample, setSample] = useState<Listing[] | null>(null);
67 −
68 − useEffect(() => {
69 − fetchSources().then((r) => registerSourceNames(r.sources)).catch(() => {});
70 − fetchStats().then(setStats).catch(() => {});
71 − fetchFacets().then(setFacets).catch(() => {});
72 − fetchListings({ sort: "price_asc" }, 2000, 0).then((r) => setSample(r.listings)).catch(() => {});
73 − }, []);
74 −
75 − const byType = useMemo(() => {
76 − if (!sample) return [];
77 − const m = new Map<string, number>();
78 − for (const l of sample) if (l.property_type) m.set(l.property_type, (m.get(l.property_type) ?? 0) + 1);
79 − return [...m.entries()].map(([key, n]) => ({ key, n, href: `/?property_type=${encodeURIComponent(key)}` }))
80 − .sort((a, b) => b.n - a.n).slice(0, 12);
81 − }, [sample]);
82 −
83 − const byCity = useMemo(() => {
84 − if (!sample) return [];
85 − const m = new Map<string, number>();
86 − for (const l of sample) if (l.city) m.set(l.city, (m.get(l.city) ?? 0) + 1);
87 − return [...m.entries()].map(([key, n]) => ({ key, n, href: `/?city=${encodeURIComponent(key)}` }))
88 − .sort((a, b) => b.n - a.n).slice(0, 15);
89 − }, [sample]);
90 −
91 − const bySource = useMemo(() => {
92 − if (!facets) return [];
93 − return facets.sources.map((s) => ({ key: sourceName(s.source), n: s.n, href: `/?source=${encodeURIComponent(s.source)}` }))
94 − .sort((a, b) => b.n - a.n).slice(0, 15);
95 − }, [facets]);
96 −
97 − const tiles = [
98 − { v: stats ? stats.total.toLocaleString("fr-CA") : "…", k: "Propriétés à vendre", hero: true },
99 − { v: stats ? String(stats.sources) : "…", k: "Agences agrégées" },
100 − { v: stats ? stats.cities.toLocaleString("fr-CA") : "…", k: "Villes couvertes" },
101 − { v: stats?.avg_price != null ? `${Math.round(stats.avg_price).toLocaleString("fr-CA")} $` : "…", k: "Prix moyen demandé" },
102 − { v: stats?.min_price != null ? `${Math.round(stats.min_price).toLocaleString("fr-CA")} $` : "…", k: "Prix minimum" },
103 − { v: stats?.max_price != null ? `${Math.round(stats.max_price).toLocaleString("fr-CA")} $` : "…", k: "Prix maximum" },
104 − ];
98 + const [period, setPeriod] = useState("30j");
99 + const [custom, setCustom] = useState<{ from: string; to: string }>({ from: "", to: "" });
100 + const [dash, setDash] = useState<Dashboard | null>(null);
101 + const [legacy, setLegacy] = useState<LegacyStats | null>(null);
102 + const [loading, setLoading] = useState(true);
103 + const [error, setError] = useState(false);
104 +
105 + const useCustom = Boolean(custom.from && custom.to);
106 +
107 + const load = useCallback(() => {
108 + setLoading(true);
109 + setError(false);
110 + const p = new URLSearchParams();
111 + if (useCustom) {
112 + p.set("from", custom.from);
113 + p.set("to", custom.to);
114 + } else {
115 + p.set("period", period);
116 + }
117 + fetch(`/api/stats/dashboard?${p}`)
118 + .then((r) => { if (!r.ok) throw new Error(String(r.status)); return r.json(); })
119 + .then((d: Dashboard) => setDash(d))
120 + .catch(() => setError(true))
121 + .finally(() => setLoading(false));
122 + }, [period, custom.from, custom.to, useCustom]);
123 +
124 + useEffect(() => { load(); }, [load]);
125 + useEffect(() => { fetchStats().then(setLegacy).catch(() => {}); }, []);
126 +
127 + const lines = dash?.series?.filter((s) => (s.kind ?? "line") === "line") ?? [];
128 + const donuts = dash?.breakdowns?.filter((b) => b.kind === "donut") ?? [];
129 + const barBds = dash?.breakdowns?.filter((b) => b.kind !== "donut") ?? [];
105 130
106 131 return (
107 − <div className="container stats-page">
108 − <span className="kicker">Le marché agrégé</span>
109 − <h1 className="stats-title">Statistiques</h1>
110 − <p className="sub">
111 − Portrait en direct des propriétés à vendre agrégées par Immo-Ka à travers toutes les
112 − agences connectées. Répartitions calculées sur un échantillon des annonces actives.
113 − </p>
114 −
115 − <div className="tiles">
116 − {tiles.map((t) => (
117 − <div className={`tile ${t.hero ? "hero-tile" : ""}`} key={t.k}>
118 − <div className="tile-v">{t.v}</div>
119 − <div className="tile-k">{t.k}</div>
120 − </div>
121 − ))}
122 − </div>
123 −
124 − <div className="viz-grid">
125 − <div className="viz-card">
126 − <h2>Par type de propriété</h2>
127 − <div className="viz-sub">Échantillon des annonces actives</div>
128 − {byType.length ? <Bars rows={byType} /> : <p className="fine">Chargement…</p>}
129 − </div>
130 − <div className="viz-card">
131 − <h2>Par agence</h2>
132 − <div className="viz-sub">Annonces actives (après déduplication)</div>
133 − {bySource.length ? <Bars rows={bySource} /> : <p className="fine">Chargement…</p>}
132 + <div className="container stats-page" style={{ display: "grid", gap: 22, minWidth: 0 }}>
133 + {/* --- en-tête : titre + fraîcheur + export PDF --------------------------- */}
134 + <header style={{ minWidth: 0 }}>
135 + <span className="kicker">Le marché agrégé</span>
136 + <h1 className="stats-title">Statistiques</h1>
137 + <p className="sub" style={{ marginBottom: 14 }}>
138 + Tableau de bord en direct des propriétés à vendre agrégées par Immo-Ka —
139 + volumes, prix, retraits et tension du marché, calculés sur les données réelles
140 + de la plateforme{dash?.period?.observed_from ? ` (collecte depuis le ${dash.period.observed_from})` : ""}.
141 + </p>
142 + <div style={{ display: "flex", flexWrap: "wrap", gap: 12, alignItems: "center", justifyContent: "space-between" }}>
143 + <PdfButton period={useCustom ? "personnalise" : period}
144 + from={useCustom ? custom.from : undefined}
145 + to={useCustom ? custom.to : undefined} />
146 + {dash && <Fraicheur updated={dash.updated} onRefresh={load} />}
134 147 </div>
135 − </div>
148 + </header>
136 149
137 − {stats?.vraiprix?.bannieres && stats.vraiprix.bannieres.length > 0 && (
138 − <div className="viz-card">
139 − <h2>Prix demandé vs valeur Vrai-Prix</h2>
140 − <div className="viz-sub">
141 − Écart médian entre le prix demandé et l'estimation indépendante Vrai-Prix, par bannière.
142 − La bande grise couvre la moitié centrale des annonces (P25–P75) ; le trait est la médiane.
143 − </div>
144 − <div className="vpg-axis">
145 − <div><span>−{VP_SCALE} %</span><span>estimation Vrai-Prix</span><span>+{VP_SCALE} %</span></div>
146 − </div>
147 − {stats.vraiprix.ensemble && <VpGauge b={stats.vraiprix.ensemble} />}
148 − <div className="vpg-sep" />
149 − {stats.vraiprix.bannieres.map((b) => <VpGauge b={b} key={b.banniere} />)}
150 − <div className="vpg-legend">
151 − <span><i className="vps-sous" /> sous l'estimation (≤ −5 %)</span>
152 − <span><i className="vps-juste" /> dans l'estimation</span>
153 − <span><i className="vps-sur" /> survalorisé (≥ +10 %)</span>
154 − </div>
150 + {error && (
151 + <div className="notice">
152 + <h2>Statistiques indisponibles</h2>
153 + <p>Le tableau de bord n'a pas pu être chargé. <button className="btn btn-ghost" onClick={load}>Réessayer</button></p>
155 154 </div>
156 155 )}
157 156
158 − <div className="viz-card">
159 − <h2>Par ville</h2>
160 − <div className="viz-sub">Top 15 · échantillon des annonces actives</div>
161 − {byCity.length ? <Bars rows={byCity} /> : <p className="fine">Chargement…</p>}
162 − </div>
157 + {/* --- 1. bandeau KPI ------------------------------------------------------ */}
158 + {dash?.kpis?.length ? (
159 + <section aria-label="Indicateurs clés" style={{ ...gridAutoFit(190), opacity: loading ? 0.55 : 1, transition: "opacity 0.2s" }}>
160 + {dash.kpis.map((k) => <KpiCard k={k} key={k.id} />)}
161 + </section>
162 + ) : !error && (
163 + <section style={gridAutoFit(190)}>
164 + {[0, 1, 2, 3].map((i) => <EmptyBlock key={i} title="Chargement…" />)}
165 + </section>
166 + )}
163 167
164 − {stats?.recent_syncs && stats.recent_syncs.length > 0 && (
165 − <div className="viz-card">
166 − <h2>Synchronisations récentes</h2>
167 − <div className="viz-sub">Journal du moteur d'agrégation</div>
168 − <div className="viz-table">
169 − <table>
170 − <thead><tr><th>Agence</th><th>Trouvées</th><th>Ajoutées</th><th>MàJ</th><th>Retirées</th><th>Quand</th></tr></thead>
171 − <tbody>
172 − {stats.recent_syncs.slice(0, 15).map((s, i) => (
173 − <tr key={i}>
174 − <td>{sourceName(s.source)}</td>
175 − <td>{s.found}</td><td>{s.added}</td><td>{s.updated}</td><td>{s.removed}</td>
176 − <td style={{ color: "var(--ink-3)" }}>{new Date(s.ts * 1000).toLocaleString("fr-CA")}</td>
177 − </tr>
178 − ))}
179 − </tbody>
180 − </table>
181 − </div>
182 − </div>
168 + {/* --- 2. sélecteur de période --------------------------------------------- */}
169 + <section aria-label="Période analysée">
170 + <p className="klabel" style={{ margin: "0 0 8px" }}>
171 + Période analysée{dash ? ` — ${dash.period.label} (${dash.period.from} → ${dash.period.to})` : ""}
172 + </p>
173 + <PeriodSelector
174 + value={useCustom ? "" : period}
175 + onChange={(p) => { setCustom({ from: "", to: "" }); setPeriod(p); }}
176 + custom={custom}
177 + onCustom={(from, to) => setCustom({ from, to })}
178 + />
179 + </section>
180 +
181 + {/* --- 3. courbes d'évolution ----------------------------------------------- */}
182 + {dash && (
183 + <section aria-label="Évolution" style={gridAutoFit(360)}>
184 + {lines.length
185 + ? lines.map((s) => <LineChart serie={s} key={s.id} />)
186 + : <EmptyBlock title="Évolution quotidienne" />}
187 + </section>
188 + )}
189 +
190 + {/* --- répartitions : anneau + barres ---------------------------------------- */}
191 + {dash && (
192 + <section aria-label="Répartitions" style={gridAutoFit(340)}>
193 + {donuts.map((b) => <Donut title={b.title} items={b.items} key={b.id} />)}
194 + {barBds.map((b) => <BarChart title={b.title} items={b.items} key={b.id} />)}
195 + </section>
183 196 )}
184 197
185 − <p className="stats-foot">Mise à jour automatique — chaque fiche renvoie à l'annonce originale de l'agence.</p>
198 + {/* --- 4. répartition géographique ------------------------------------------- */}
199 + {dash?.geo && <BarChart title={dash.geo.title} items={dash.geo.items} unit="annonces" />}
200 +
201 + {/* --- calendrier de chaleur --------------------------------------------------- */}
202 + {dash?.heatmap && <CalendarHeatmap title={dash.heatmap.title} cells={dash.heatmap.cells} />}
203 +
204 + {/* --- spécifique Immo-Ka : croisement Vrai-Prix ------------------------------- */}
205 + <VraiPrixBlock legacy={legacy} />
206 +
207 + {/* --- 5. tableaux détaillés ----------------------------------------------------- */}
208 + {dash?.tables?.map((t) => <DataTable spec={t} key={t.id} />)}
209 +
210 + {/* --- 6. records & faits marquants ----------------------------------------------- */}
211 + {dash?.records?.length ? (
212 + <section aria-label="Records et faits marquants">
213 + <p className="klabel" style={{ margin: "0 0 8px" }}>Records & faits marquants</p>
214 + <div style={gridAutoFit(300)}>
215 + {dash.records.map((r, i) => <RecordCard r={r} key={i} />)}
216 + </div>
217 + </section>
218 + ) : null}
219 +
220 + <p className="stats-foot">
221 + Mise à jour automatique — statistiques calculées sur les annonces agrégées
222 + (doublons d'agences exclus, « prix sur demande » exclus). Chaque fiche renvoie
223 + à l'annonce originale de l'agence.
224 + </p>
186 225 </div>
187 226 );
188 227 }
added immoka/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"
added immoka/stats.py +448 −0
@@ -0,0 +1,448 @@
1 +# -----------------------------------------------------------------------------
2 +# Immo-Ka — Agrégateur de propriétés à vendre (province de Québec)
3 +# Auteur : Simon-Pierre Boucher — contact@spboucher.ai
4 +# stats.py : tableau de bord analytique /api/stats/dashboard + rapport PDF
5 +# /api/stats/report (module Stats commun Groupe KA — voir
6 +# frontend/src/ka/stats/SPEC.md). Toutes les valeurs viennent de la base
7 +# (listings, price_log, sync_log) — AUCUNE statistique inventée : une
8 +# mesure indisponible est simplement omise (le front affiche un état vide).
9 +# -----------------------------------------------------------------------------
10 +from __future__ import annotations
11 +
12 +import statistics
13 +import threading
14 +import time
15 +import unicodedata
16 +from datetime import date, datetime, timedelta
17 +from zoneinfo import ZoneInfo
18 +
19 +from . import db
20 +
21 +TZ = ZoneInfo("America/Toronto")
22 +SQFT_PER_M2 = 10.7639104
23 +
24 +# Même règle de visibilité que le reste de l'API (web.DEDUP_CLAUSE) :
25 +# doublons de sous-agences masqués + « Prix sur demande » exclus.
26 +VISIBLE = " AND dup_hidden=0 AND price IS NOT NULL"
27 +
28 +PERIOD_LABELS = {
29 + "auj": "Aujourd'hui", "7j": "7 jours", "30j": "30 jours",
30 + "3m": "3 mois", "6m": "6 mois", "12m": "12 mois",
31 + "annee": "Année en cours", "tout": "Toute la période",
32 +}
33 +
34 +# --- cache serveur (>= 5 min par période, contrat SPEC) -----------------------
35 +_CACHE: dict[str, tuple[float, dict]] = {}
36 +_CACHE_TTL = 300
37 +_CACHE_LOCK = threading.Lock()
38 +
39 +
40 +# --- utilitaires --------------------------------------------------------------
41 +def _today() -> date:
42 + return datetime.now(TZ).date()
43 +
44 +
45 +def _iso(d: date) -> str:
46 + return d.isoformat()
47 +
48 +
49 +def _parse(d: str) -> date | None:
50 + try:
51 + return date.fromisoformat(d[:10])
52 + except (ValueError, TypeError):
53 + return None
54 +
55 +
56 +def _epoch(d: date) -> float:
57 + """Minuit local (heure de l'Est) du jour donné, en epoch."""
58 + return datetime(d.year, d.month, d.day, tzinfo=TZ).timestamp()
59 +
60 +
61 +def resolve_period(period: str | None, frm: str | None, to: str | None,
62 + data_start: date) -> tuple[date, date, str]:
63 + today = _today()
64 + f, t = _parse(frm or ""), _parse(to or "")
65 + if f and t:
66 + if t < f:
67 + f, t = t, f
68 + return f, t, f"{_iso(f)} → {_iso(t)}"
69 + p = (period or "30j").lower()
70 + spans = {"7j": 6, "30j": 29, "3m": 89, "6m": 181, "12m": 364}
71 + if p == "auj":
72 + return today, today, PERIOD_LABELS["auj"]
73 + if p == "annee":
74 + return date(today.year, 1, 1), today, PERIOD_LABELS["annee"]
75 + if p == "tout":
76 + return data_start, today, PERIOD_LABELS["tout"]
77 + days = spans.get(p, 29)
78 + label = PERIOD_LABELS.get(p, PERIOD_LABELS["30j"])
79 + return today - timedelta(days=days), today, label
80 +
81 +
82 +def _fold(s: str) -> str:
83 + return "".join(c for c in unicodedata.normalize("NFKD", s.lower().strip())
84 + if not unicodedata.combining(c))
85 +
86 +
87 +def _median(vals: list[float]) -> float | None:
88 + return statistics.median(vals) if vals else None
89 +
90 +
91 +def _fmt_money(v: float) -> str:
92 + return f"{round(v):,}".replace(",", " ") + " $"
93 +
94 +
95 +def _fmt_pct(cur: float, prev: float) -> float | None:
96 + if prev <= 0:
97 + return None
98 + return round((cur - prev) / prev * 100.0, 1)
99 +
100 +
101 +def _daterange(a: date, b: date):
102 + d = a
103 + while d <= b:
104 + yield d
105 + d += timedelta(days=1)
106 +
107 +
108 +# --- calcul du tableau de bord ------------------------------------------------
109 +def _compute(frm_q: str | None, to_q: str | None, period: str | None) -> dict:
110 + con = db.connect()
111 + try:
112 + return _compute_con(con, frm_q, to_q, period)
113 + finally:
114 + con.close()
115 +
116 +
117 +def _compute_con(con, frm_q, to_q, period) -> dict:
118 + today = _today()
119 + row = con.execute("SELECT MIN(first_seen) m FROM listings").fetchone()
120 + data_start = (datetime.fromtimestamp(row["m"], TZ).date()
121 + if row and row["m"] else today)
122 +
123 + frm, to, label = resolve_period(period, frm_q, to_q, data_start)
124 + to = min(to, today)
125 + # fenêtre observée : la collecte a commencé le data_start — les séries
126 + # sont bornées à ce qui a réellement été mesuré (rien d'extrapolé).
127 + s_frm = max(frm, data_start)
128 + s_to = max(to, s_frm)
129 + ep_frm, ep_to = _epoch(s_frm), _epoch(s_to + timedelta(days=1))
130 + ndays = (s_to - s_frm).days + 1
131 + # période précédente de même longueur (pour les deltas)
132 + p_frm, p_to = s_frm - timedelta(days=ndays), s_frm - timedelta(days=1)
133 + # deltas seulement si la période précédente a été observée EN ENTIER —
134 + # comparer à une fenêtre tronquée fausserait les variations.
135 + prev_ok = p_frm >= data_start
136 + ep_pfrm, ep_pto = _epoch(p_frm), _epoch(p_to + timedelta(days=1))
137 +
138 + # ---- reconstruction « annonces actives par jour » (événements) ----------
139 + actives_by_day: dict[str, int] = {}
140 + deltas: dict[date, int] = {}
141 + for r in con.execute(
142 + "SELECT date(first_seen,'unixepoch','localtime') fs,"
143 + " date(last_seen,'unixepoch','localtime') ls, active"
144 + " FROM listings WHERE 1=1" + VISIBLE):
145 + d0 = _parse(r["fs"])
146 + if d0 is None:
147 + continue
148 + deltas[d0] = deltas.get(d0, 0) + 1
149 + if not r["active"]:
150 + d1 = (_parse(r["ls"]) or d0) + timedelta(days=1)
151 + deltas[d1] = deltas.get(d1, 0) - 1
152 + run = 0
153 + for d in _daterange(data_start, today):
154 + run += deltas.get(d, 0)
155 + actives_by_day[_iso(d)] = run
156 +
157 + # ---- KPI -----------------------------------------------------------------
158 + snap = con.execute(
159 + "SELECT COUNT(*) n, AVG(price) avg_p,"
160 + " COUNT(DISTINCT NULLIF(city,'')) cities"
161 + " FROM listings WHERE active=1" + VISIBLE).fetchone()
162 + prices = [r["price"] for r in con.execute(
163 + "SELECT price FROM listings WHERE active=1" + VISIBLE)]
164 + med_price = _median(prices)
165 + ppm2 = [r["v"] for r in con.execute(
166 + "SELECT price/(area_sqft/" + str(SQFT_PER_M2) + ") v FROM listings"
167 + " WHERE active=1 AND area_sqft>=200" + VISIBLE)]
168 + med_ppm2 = _median(ppm2)
169 + n_ppm2 = len(ppm2)
170 +
171 + new_cur = con.execute(
172 + "SELECT COUNT(*) n FROM listings WHERE first_seen>=? AND first_seen<?"
173 + + VISIBLE, (ep_frm, ep_to)).fetchone()["n"]
174 + new_prev = con.execute(
175 + "SELECT COUNT(*) n FROM listings WHERE first_seen>=? AND first_seen<?"
176 + + VISIBLE, (ep_pfrm, ep_pto)).fetchone()["n"] if prev_ok else 0
177 + gone_cur = con.execute(
178 + "SELECT COUNT(*) n FROM listings WHERE active=0 AND last_seen>=?"
179 + " AND last_seen<?" + VISIBLE, (ep_frm, ep_to)).fetchone()["n"]
180 + gone_prev = con.execute(
181 + "SELECT COUNT(*) n FROM listings WHERE active=0 AND last_seen>=?"
182 + " AND last_seen<?" + VISIBLE, (ep_pfrm, ep_pto)).fetchone()["n"] if prev_ok else 0
183 + conn_cur = con.execute(
184 + "SELECT COUNT(DISTINCT source) n FROM sync_log WHERE ok=1 AND ts>=?"
185 + " AND ts<?", (ep_frm, ep_to)).fetchone()["n"]
186 +
187 + act_now = snap["n"]
188 + act_prev = actives_by_day.get(_iso(p_to)) if prev_ok else None
189 +
190 + def kpi(id_, lbl, val, unit="", dpct=None):
191 + k = {"id": id_, "label": lbl, "value": val, "unit": unit}
192 + if dpct is not None:
193 + k["delta_pct"] = dpct
194 + k["direction"] = "up" if dpct >= 0 else "down"
195 + return k
196 +
197 + kpis = [
198 + kpi("actives", "Annonces actives", act_now, "",
199 + _fmt_pct(act_now, act_prev) if act_prev else None),
200 + kpi("nouvelles", "Nouvelles annonces (période)", new_cur, "",
201 + _fmt_pct(new_cur, new_prev) if prev_ok and new_prev else None),
202 + kpi("retirees", "Vendues / retirées (période)", gone_cur, "",
203 + _fmt_pct(gone_cur, gone_prev) if prev_ok and gone_prev else None),
204 + ]
205 + if snap["avg_p"]:
206 + kpis.append(kpi("prix_moyen", "Prix moyen demandé",
207 + round(snap["avg_p"]), "$"))
208 + if med_price:
209 + kpis.append(kpi("prix_median", "Prix médian demandé",
210 + round(med_price), "$"))
211 + if med_ppm2 and n_ppm2 >= 100:
212 + kpis.append(kpi("prix_m2",
213 + f"Prix médian au m² ({n_ppm2:,} annonces avec superficie)".replace(",", " "),
214 + round(med_ppm2), "$/m²"))
215 + kpis.append(kpi("villes", "Villes couvertes", snap["cities"]))
216 + kpis.append(kpi("connecteurs", "Connecteurs actifs (période)", conn_cur))
217 + # indice de tension : retraits / nouvelles entrées (mesuré, pas modélisé)
218 + if new_cur >= 50:
219 + kpis.append(kpi("tension", "Tension — retraits / nouvelles",
220 + round(100.0 * gone_cur / new_cur, 1), "%"))
221 +
222 + # ---- séries quotidiennes ---------------------------------------------------
223 + days = [_iso(d) for d in _daterange(s_frm, s_to)]
224 + new_by_day = {r["d"]: r["n"] for r in con.execute(
225 + "SELECT date(first_seen,'unixepoch','localtime') d, COUNT(*) n"
226 + " FROM listings WHERE first_seen>=? AND first_seen<?" + VISIBLE +
227 + " GROUP BY d", (ep_frm, ep_to))}
228 + gone_by_day = {r["d"]: r["n"] for r in con.execute(
229 + "SELECT date(last_seen,'unixepoch','localtime') d, COUNT(*) n"
230 + " FROM listings WHERE active=0 AND last_seen>=? AND last_seen<?"
231 + + VISIBLE + " GROUP BY d", (ep_frm, ep_to))}
232 + series = []
233 + if len(days) >= 2:
234 + series = [
235 + {"id": "actives", "title": "Annonces actives par jour",
236 + "unit": "annonces", "kind": "line",
237 + "points": [{"t": d, "v": actives_by_day.get(d, 0)} for d in days]},
238 + {"id": "nouvelles", "title": "Nouvelles annonces par jour",
239 + "unit": "annonces", "kind": "line",
240 + "points": [{"t": d, "v": new_by_day.get(d, 0)} for d in days]},
241 + {"id": "retraits", "title": "Retraits (vendues / retirées) par jour",
242 + "unit": "annonces", "kind": "line",
243 + "points": [{"t": d, "v": gone_by_day.get(d, 0)} for d in days]},
244 + ]
245 + # comparaison N-1 : seulement si l'an dernier a réellement été observé
246 + y_frm, y_to = s_frm - timedelta(days=365), s_to - timedelta(days=365)
247 + if y_frm >= data_start:
248 + cmp_new = {r["d"]: r["n"] for r in con.execute(
249 + "SELECT date(first_seen,'unixepoch','localtime') d, COUNT(*) n"
250 + " FROM listings WHERE first_seen>=? AND first_seen<?" + VISIBLE +
251 + " GROUP BY d", (_epoch(y_frm), _epoch(y_to + timedelta(days=1))))}
252 + ydays = [_iso(d) for d in _daterange(y_frm, y_to)]
253 + series[1]["compare"] = [{"t": d, "v": cmp_new.get(d, 0)} for d in ydays]
254 +
255 + # ---- répartitions (photo des annonces actives) -----------------------------
256 + types = [{"label": r["t"] or "Autre / non précisé", "value": r["n"]}
257 + for r in con.execute(
258 + "SELECT property_type t, COUNT(*) n FROM listings"
259 + " WHERE active=1" + VISIBLE +
260 + " GROUP BY property_type ORDER BY n DESC LIMIT 9")]
261 + ranges = [("Moins de 200 k$", 0, 200e3), ("200 – 300 k$", 200e3, 300e3),
262 + ("300 – 400 k$", 300e3, 400e3), ("400 – 500 k$", 400e3, 500e3),
263 + ("500 – 750 k$", 500e3, 750e3), ("750 k$ – 1 M$", 750e3, 1e6),
264 + ("1 – 2 M$", 1e6, 2e6), ("2 M$ et plus", 2e6, None)]
265 + price_items = []
266 + for lbl, lo, hi in ranges:
267 + q = "SELECT COUNT(*) n FROM listings WHERE active=1 AND price>=?" + VISIBLE
268 + args: list = [lo]
269 + if hi is not None:
270 + q += " AND price<?"
271 + args.append(hi)
272 + price_items.append({"label": lbl,
273 + "value": con.execute(q, args).fetchone()["n"]})
274 + beds = [{"label": ("8 chambres et +" if r["b"] >= 8
275 + else f"{int(r['b'])} chambre" + ("s" if r["b"] > 1 else "")),
276 + "value": r["n"]}
277 + for r in con.execute(
278 + "SELECT MIN(bedrooms,8) b, COUNT(*) n FROM listings"
279 + " WHERE active=1 AND bedrooms IS NOT NULL" + VISIBLE +
280 + " GROUP BY MIN(bedrooms,8) ORDER BY b")]
281 + breakdowns = [
282 + {"id": "types", "title": "Répartition par type de propriété",
283 + "kind": "donut", "items": types},
284 + {"id": "prix", "title": "Répartition par fourchette de prix demandé",
285 + "kind": "bar", "items": price_items},
286 + ]
287 + if beds:
288 + breakdowns.append({"id": "chambres",
289 + "title": "Répartition par nombre de chambres (renseignées)",
290 + "kind": "bar", "items": beds})
291 +
292 + # ---- géographie : par région (fusion accents/casse, libellé le + fréquent)
293 + reg_counts: dict[str, dict[str, int]] = {}
294 + for r in con.execute(
295 + "SELECT region, COUNT(*) n FROM listings WHERE active=1"
296 + " AND region<>''" + VISIBLE + " GROUP BY region"):
297 + raw = (r["region"] or "").strip()
298 + key = _fold(raw)
299 + if not key or key.isdigit():
300 + continue
301 + reg_counts.setdefault(key, {})[raw] = reg_counts.get(key, {}).get(raw, 0) + r["n"]
302 + geo_items = []
303 + for key, variants in reg_counts.items():
304 + best_variant = max(variants, key=variants.get)
305 + geo_items.append({"label": best_variant, "value": sum(variants.values())})
306 + geo_items.sort(key=lambda x: -x["value"])
307 + geo = ({"title": "Annonces actives par région", "items": geo_items[:14]}
308 + if geo_items else None)
309 +
310 + # ---- heatmap : nouvelles annonces par jour (26 dernières semaines max) ----
311 + h_frm = max(data_start, s_to - timedelta(days=181))
312 + hm = [{"date": r["d"], "value": r["n"]} for r in con.execute(
313 + "SELECT date(first_seen,'unixepoch','localtime') d, COUNT(*) n"
314 + " FROM listings WHERE first_seen>=? AND first_seen<?" + VISIBLE +
315 + " GROUP BY d", (_epoch(h_frm), _epoch(s_to + timedelta(days=1))))]
316 + heatmap = ({"title": "Nouvelles annonces par jour", "cells": hm}
317 + if len(hm) >= 2 else None)
318 +
319 + # ---- tableaux ---------------------------------------------------------------
320 + # Top villes : actives, prix moyen/médian, nouvelles sur la période + delta
321 + city_prices: dict[str, list[float]] = {}
322 + for r in con.execute(
323 + "SELECT city, price FROM listings WHERE active=1 AND city<>''"
324 + + VISIBLE):
325 + city_prices.setdefault(r["city"], []).append(r["price"])
326 + new_city = {r["city"]: r["n"] for r in con.execute(
327 + "SELECT city, COUNT(*) n FROM listings WHERE city<>''"
328 + " AND first_seen>=? AND first_seen<?" + VISIBLE + " GROUP BY city",
329 + (ep_frm, ep_to))}
330 + new_city_prev = {r["city"]: r["n"] for r in con.execute(
331 + "SELECT city, COUNT(*) n FROM listings WHERE city<>''"
332 + " AND first_seen>=? AND first_seen<?" + VISIBLE + " GROUP BY city",
333 + (ep_pfrm, ep_pto))} if prev_ok else {}
334 + top = sorted(city_prices.items(), key=lambda kv: -len(kv[1]))[:50]
335 + top_rows = []
336 + for city, ps in top:
337 + n_new = new_city.get(city, 0)
338 + n_prev = new_city_prev.get(city, 0)
339 + d = _fmt_pct(n_new, n_prev) if prev_ok and n_prev else None
340 + top_rows.append([
341 + city, len(ps), _fmt_money(sum(ps) / len(ps)),
342 + _fmt_money(statistics.median(ps)), n_new,
343 + (f"{'+' if d >= 0 else ''}{str(d).replace('.', ',')} %"
344 + if d is not None else "—"),
345 + ])
346 + tables = [{
347 + "id": "top_villes", "title": "Top villes",
348 + "columns": ["Ville", "Actives", "Prix moyen", "Prix médian",
349 + "Nouvelles (période)", "Var. nouvelles"],
350 + "rows": top_rows,
351 + }]
352 + # Délai de présence (retirées de la période) par ville
353 + dur_city: dict[str, list[float]] = {}
354 + for r in con.execute(
355 + "SELECT city, (last_seen-first_seen)/86400.0 d FROM listings"
356 + " WHERE active=0 AND city<>'' AND last_seen>=? AND last_seen<?"
357 + + VISIBLE, (ep_frm, ep_to)):
358 + dur_city.setdefault(r["city"], []).append(max(r["d"], 0.0))
359 + dur_rows = []
360 + for city, ds in sorted(dur_city.items(), key=lambda kv: -len(kv[1]))[:50]:
361 + if len(ds) < 3:
362 + continue
363 + dur_rows.append([
364 + city, len(ds),
365 + str(round(sum(ds) / len(ds), 1)).replace(".", ","),
366 + str(round(statistics.median(ds), 1)).replace(".", ","),
367 + ])
368 + if dur_rows:
369 + tables.append({
370 + "id": "delai_villes",
371 + "title": "Délai de présence avant retrait, par ville (période)",
372 + "columns": ["Ville", "Retirées", "Délai moyen (j)", "Délai médian (j)"],
373 + "rows": dur_rows,
374 + })
375 +
376 + # ---- records & faits marquants ---------------------------------------------
377 + records = []
378 + if new_by_day:
379 + best = max(new_by_day.items(), key=lambda kv: kv[1])
380 + records.append({"label": "Jour record de nouvelles annonces",
381 + "value": f"{best[1]:,} annonces".replace(",", " "),
382 + "date": best[0]})
383 + fast = con.execute(
384 + "SELECT city, address, (last_seen-first_seen)/86400.0 d,"
385 + " date(last_seen,'unixepoch','localtime') dt FROM listings"
386 + " WHERE active=0 AND last_seen>=? AND last_seen<?"
387 + " AND last_seen-first_seen>=3600" # >= 1 h : écarte les artefacts de sync
388 + + VISIBLE + " ORDER BY (last_seen-first_seen) ASC LIMIT 1",
389 + (ep_frm, ep_to)).fetchone()
390 + if fast:
391 + d = fast["d"]
392 + val = (f"{round(d * 24, 1)} h" if d < 1 else f"{round(d, 1)} j").replace(".", ",")
393 + records.append({"label": "Retrait le plus rapide (mise en ligne → retrait)",
394 + "value": val + (f" · {fast['city']}" if fast["city"] else ""),
395 + "date": fast["dt"]})
396 + drop = con.execute(
397 + """SELECT l.city, MAX(p1.price - p2.price) drop_amt,
398 + date(MAX(p2.ts),'unixepoch','localtime') dt, l.uid
399 + FROM price_log p1
400 + JOIN price_log p2 ON p2.uid = p1.uid AND p2.ts > p1.ts
401 + JOIN listings l ON l.uid = p1.uid
402 + WHERE p2.ts>=? AND p2.ts<? AND p1.price > p2.price
403 + AND l.dup_hidden=0
404 + GROUP BY l.uid ORDER BY drop_amt DESC LIMIT 1""",
405 + (ep_frm, ep_to)).fetchone()
406 + if drop and drop["drop_amt"]:
407 + records.append({"label": "Plus forte baisse de prix demandé",
408 + "value": "−" + _fmt_money(drop["drop_amt"]) +
409 + (f" · {drop['city']}" if drop["city"] else ""),
410 + "date": drop["dt"]})
411 + if new_city:
412 + c, n = max(new_city.items(), key=lambda kv: kv[1])
413 + records.append({"label": "Ville la plus active (nouvelles annonces)",
414 + "value": f"{c} — {n:,} annonces".replace(",", " ")})
415 +
416 + out = {
417 + "updated": datetime.now(TZ).isoformat(timespec="seconds"),
418 + "period": {"from": _iso(frm), "to": _iso(to), "label": label,
419 + "observed_from": _iso(data_start)},
420 + "kpis": kpis,
421 + "series": series,
422 + "breakdowns": breakdowns,
423 + "tables": tables,
424 + "records": records,
425 + }
426 + if geo:
427 + out["geo"] = geo
428 + if heatmap:
429 + out["heatmap"] = heatmap
430 + return out
431 +
432 +
433 +def dashboard(period: str | None = None, frm: str | None = None,
434 + to: str | None = None) -> dict:
435 + key = f"{period or ''}|{frm or ''}|{to or ''}"
436 + now = time.time()
437 + with _CACHE_LOCK:
438 + hit = _CACHE.get(key)
439 + if hit and now - hit[0] < _CACHE_TTL:
440 + return hit[1]
441 + data = _compute(frm, to, period)
442 + with _CACHE_LOCK:
443 + _CACHE[key] = (time.time(), data)
444 + # garder le cache borné
445 + if len(_CACHE) > 64:
446 + for k in sorted(_CACHE, key=lambda k: _CACHE[k][0])[:32]:
447 + _CACHE.pop(k, None)
448 + return data
modified immoka/web.py +38 −1
@@ -12,10 +12,11 @@ from pathlib import Path
12 12 from fastapi import BackgroundTasks, FastAPI, HTTPException, Query, Request
13 13 from fastapi.middleware.cors import CORSMiddleware
14 14 from fastapi.middleware.gzip import GZipMiddleware
15 −from fastapi.responses import FileResponse
15 +from fastapi.responses import FileResponse, Response
16 16 from fastapi.staticfiles import StaticFiles
17 17
18 18 from . import auth, db, favorites, ingest, seo
19 +from . import stats as kastats
19 20
20 21 ROOT = Path(__file__).resolve().parent.parent
21 22 SOURCES_PATH = ROOT / "data" / "sources.json"
@@ -403,6 +404,42 @@ def stats():
403 404 return {**dict(row), "vraiprix": vraiprix, "recent_syncs": log}
404 405
405 406
407 +# --- Module Stats commun Groupe KA (voir frontend/src/ka/stats/SPEC.md) ------
408 +@app.get("/api/stats/dashboard")
409 +def stats_dashboard(
410 + period: str | None = Query(None),
411 + from_: str | None = Query(None, alias="from"),
412 + to: str | None = Query(None),
413 +):
414 + """Tableau de bord analytique (contrat SPEC ka-stats, cache 5 min)."""
415 + return kastats.dashboard(period, from_, to)
416 +
417 +
418 +@app.get("/api/stats/report")
419 +def stats_report(
420 + period: str = Query("30j"),
421 + from_: str | None = Query(None, alias="from"),
422 + to: str | None = Query(None),
423 + mode: str = Query("complet"),
424 +):
425 + """Rapport PDF estampillé Groupe-KA (gabarit commun immoka/kapdf.py)."""
426 + from . import kapdf
427 + dash = kastats.dashboard(period, from_, to)
428 + site = {
429 + "wordmark": "Immo·Ka",
430 + "accent": "#e23744",
431 + "domain": "www.immo-ka.com",
432 + "tagline": "Agrégateur de propriétés à vendre — province de Québec",
433 + }
434 + pdf = kapdf.GroupeKAReport(
435 + site=site, dashboard=dash,
436 + mode="synthese" if mode == "synthese" else "complet").build()
437 + return Response(
438 + content=pdf, media_type="application/pdf",
439 + headers={"Content-Disposition":
440 + f'attachment; filename="{kapdf.filename("immo-ka", period)}"'})
441 +
442 +
406 443 @app.post("/api/sync")
407 444 def trigger_sync(background: BackgroundTasks, source: str | None = None):
408 445 """Déclenche une synchronisation (équivalent d'un webhook entrant)."""
modified requirements.txt +1 −0
@@ -2,3 +2,4 @@ requests>=2.31
2 2 beautifulsoup4>=4.12
3 3 fastapi>=0.110
4 4 uvicorn>=0.29
5 +fpdf2>=2.8
5 6