SPB Git forge

spb/groupe-ka

Public

Groupe KA — site du holding + KA ID (compte unique & SSO des 7 plateformes). Next.js 16, SQLite, Google & Apple login.

81commits 1branches 0releases
89.2 MBsize
maindefault branch
22 days agolast push
TypeScript 70.4% HTML 18.4% JavaScript 4% Python 3.8% CSS 3.4%

KA Agent v2 (widget) : plein écran à l'ouverture (desktop+mobile), fond gelé + calage visualViewport (clavier mobile stable), rendu Markdown complet en streaming (titres, listes, tableaux, code, liens nommés)

Simon-Pierre Boucher committed 1 mo ago (Aug 19, 2026) parent ea1292c

9 changed files +2,250 −682

modified public/ka-agent.js +177 −48
@@ -3,7 +3,11 @@
3 3 * Groupe KA. Vanilla JS, zéro dépendance, injecté sur les 13 sites.
4 4 * <script>window.KA_AGENT={site:"lou-ka"}</script>
5 5 * <script src="/ka-agent.js" defer></script>
6 − * Bulle flottante en bas à droite → panneau de chat (bulle) → plein écran (⛶).
6 + * v2 (2026-08-19) : ouverture directement PLEIN ÉCRAN (desktop et mobile,
7 + * bouton ▭ pour réduire en fenêtre sur desktop) ; sur téléphone le panneau se
8 + * cale sur window.visualViewport (le clavier ne fait plus grossir/défiler la
9 + * page — fond verrouillé par body position:fixed) ; rendu MARKDOWN complet en
10 + * streaming (titres, listes, tableaux, code, liens nommés, citations).
7 11 * Flux SSE en direct depuis le backend central (texte token par token +
8 12 * indicateur d'outil). Historique conservé en localStorage (par site).
9 13 */
@@ -21,60 +25,147 @@
21 25 border-radius:50%;border:2px solid var(--ink,#141814);background:var(--accent,#d9f26b);
22 26 color:var(--on-accent,#141814);font:700 17px/1 "Space Grotesk",system-ui,sans-serif;
23 27 cursor:pointer;box-shadow:4px 4px 0 rgba(20,24,20,.85);display:flex;align-items:center;
24 − justify-content:center;transition:transform .15s}
28 + justify-content:center;transition:transform .15s;touch-action:manipulation}
25 29 .kaa-btn:hover{transform:translate(-2px,-2px)}
26 − .kaa-panel{position:fixed;right:16px;bottom:calc(86px + env(safe-area-inset-bottom,0px));z-index:2147483001;width:min(392px,calc(100vw - 24px));
27 − height:min(580px,calc(100vh - 110px));height:min(580px,calc(100dvh - 110px));display:none;flex-direction:column;background:var(--paper,#f5f3ee);
28 − border:2px solid var(--ink,#141814);border-radius:14px;box-shadow:8px 8px 0 rgba(20,24,20,.85);
29 − overflow:hidden;font-family:Inter,system-ui,sans-serif}
30 + .kaa-panel{position:fixed;z-index:2147483001;display:none;flex-direction:column;background:var(--paper,#f5f3ee);
31 + overflow:hidden;font-family:Inter,system-ui,sans-serif;touch-action:manipulation}
30 32 .kaa-panel.kaa-open{display:flex}
31 − .kaa-panel.kaa-full{right:0;bottom:0;width:100vw;height:100vh;height:100dvh;border-radius:0;border:0;box-shadow:none}
32 − html.kaa-lock,html.kaa-lock body{overflow:hidden!important;overscroll-behavior:none}
33 + .kaa-panel.kaa-full{left:0;top:0;right:0;bottom:0;width:100vw;height:100vh;height:100dvh;border:0;border-radius:0;box-shadow:none}
34 + .kaa-panel:not(.kaa-full){right:16px;bottom:calc(86px + env(safe-area-inset-bottom,0px));width:min(392px,calc(100vw - 24px));
35 + height:min(580px,calc(100vh - 110px));height:min(580px,calc(100dvh - 110px));
36 + border:2px solid var(--ink,#141814);border-radius:14px;box-shadow:8px 8px 0 rgba(20,24,20,.85)}
37 + html.kaa-lock,html.kaa-lock body{overflow:hidden!important;overscroll-behavior:none;touch-action:none}
33 38 .kaa-head{display:flex;align-items:center;gap:9px;padding:11px 14px;background:var(--ink,#141814);
34 − color:var(--paper,#f5f3ee);flex:none}
39 + color:var(--paper,#f5f3ee);flex:none;padding-top:max(11px,env(safe-area-inset-top,0px))}
35 40 .kaa-head b{font:700 15px "Space Grotesk",system-ui,sans-serif;letter-spacing:-.02em}
36 41 .kaa-head .kaa-ka{display:inline-block;background:var(--accent,#d9f26b);color:var(--on-accent,#141814);
37 42 border-radius:6px;padding:1px 7px 2px;transform:rotate(-2deg);font-weight:700}
38 43 .kaa-head small{font:700 9.5px "JetBrains Mono",monospace;letter-spacing:.09em;text-transform:uppercase;opacity:.65}
39 44 .kaa-head .kaa-sp{flex:1}
40 45 .kaa-hbtn{width:34px;height:34px;border:1.5px solid rgba(245,243,238,.4);border-radius:8px;background:none;
41 − color:var(--paper,#f5f3ee);font-size:15px;cursor:pointer;line-height:1}
46 + color:var(--paper,#f5f3ee);font-size:15px;cursor:pointer;line-height:1;flex:none}
42 47 .kaa-hbtn:hover{border-color:var(--accent,#d9f26b);color:var(--accent,#d9f26b)}
43 48 .kaa-log{flex:1;overflow-y:auto;padding:14px;display:flex;flex-direction:column;gap:10px;
44 49 overscroll-behavior:contain;-webkit-overflow-scrolling:touch}
45 50 .kaa-msg{max-width:86%;padding:9px 13px;border:1.5px solid var(--ink,#141814);border-radius:12px;
46 − font-size:13.5px;line-height:1.5;white-space:pre-wrap;word-break:break-word}
51 + font-size:13.5px;line-height:1.55;word-break:break-word}
52 + .kaa-full .kaa-msg{max-width:min(86%,760px)}
53 + .kaa-full .kaa-log{align-items:stretch}
47 54 .kaa-msg.kaa-u{align-self:flex-end;background:var(--accent,#d9f26b);color:var(--on-accent,#141814);
48 − border-bottom-right-radius:4px}
55 + border-bottom-right-radius:4px;white-space:pre-wrap}
49 56 .kaa-msg.kaa-a{align-self:flex-start;background:#fff;border-bottom-left-radius:4px;box-shadow:3px 3px 0 rgba(20,24,20,.12)}
50 − .kaa-msg.kaa-a a{color:inherit;text-decoration:underline;text-underline-offset:3px}
51 − .kaa-msg.kaa-a b{font-weight:700}
57 + .kaa-msg.kaa-a a{color:inherit;text-decoration:underline;text-underline-offset:3px;font-weight:600}
58 + .kaa-msg.kaa-a p{margin:.35em 0}
59 + .kaa-msg.kaa-a p:first-child{margin-top:0}
60 + .kaa-msg.kaa-a p:last-child{margin-bottom:0}
61 + .kaa-msg.kaa-a h1,.kaa-msg.kaa-a h2,.kaa-msg.kaa-a h3,.kaa-msg.kaa-a h4{
62 + font:700 14px "Space Grotesk",system-ui,sans-serif;letter-spacing:-.01em;margin:.7em 0 .3em}
63 + .kaa-msg.kaa-a h1:first-child,.kaa-msg.kaa-a h2:first-child,.kaa-msg.kaa-a h3:first-child,.kaa-msg.kaa-a h4:first-child{margin-top:.1em}
64 + .kaa-msg.kaa-a h1{font-size:15.5px}.kaa-msg.kaa-a h2{font-size:14.5px}
65 + .kaa-msg.kaa-a ul,.kaa-msg.kaa-a ol{margin:.35em 0;padding-left:1.35em}
66 + .kaa-msg.kaa-a li{margin:.18em 0}
67 + .kaa-msg.kaa-a code{font:600 12px "JetBrains Mono",monospace;background:var(--surface-2,#f0eee7);
68 + border:1px solid rgba(20,24,20,.15);border-radius:5px;padding:.5px 4px}
69 + .kaa-msg.kaa-a pre{margin:.45em 0;padding:9px 11px;background:var(--ink,#141814);color:var(--paper,#f5f3ee);
70 + border-radius:9px;overflow-x:auto}
71 + .kaa-msg.kaa-a pre code{background:none;border:0;color:inherit;padding:0;font-weight:400;font-size:11.5px;line-height:1.5}
72 + .kaa-msg.kaa-a blockquote{margin:.45em 0;padding:.15em .8em;border-left:3px solid var(--accent,#d9f26b);
73 + background:var(--surface-2,#faf9f5);color:var(--ink-2,#4d5551)}
74 + .kaa-msg.kaa-a hr{border:0;border-top:1.5px dashed rgba(20,24,20,.3);margin:.6em 0}
75 + .kaa-msg.kaa-a table{border-collapse:collapse;margin:.45em 0;font-size:12.5px;display:block;overflow-x:auto;max-width:100%}
76 + .kaa-msg.kaa-a th,.kaa-msg.kaa-a td{border:1.5px solid var(--ink,#141814);padding:4px 9px;text-align:left;white-space:nowrap}
77 + .kaa-msg.kaa-a th{background:var(--accent,#d9f26b);color:var(--on-accent,#141814);
78 + font:700 11px "Space Grotesk",system-ui,sans-serif;letter-spacing:.02em}
79 + .kaa-msg.kaa-a td{background:#fff}
52 80 .kaa-tool{align-self:flex-start;font:700 10px "JetBrains Mono",monospace;letter-spacing:.07em;
53 81 text-transform:uppercase;color:var(--ink-2,#4d5551);padding:3px 10px;border:1.5px dashed var(--ink-2,#4d5551);
54 82 border-radius:999px;background:var(--surface-2,#faf9f5)}
55 83 .kaa-in{display:flex;gap:8px;padding:11px;border-top:2px solid var(--ink,#141814);background:#fff;flex:none;
56 84 padding-bottom:calc(11px + env(safe-area-inset-bottom,0))}
85 + .kaa-full .kaa-in{justify-content:center}
86 + .kaa-full .kaa-in textarea{max-width:700px}
57 87 .kaa-in textarea{flex:1;resize:none;min-height:44px;max-height:110px;padding:10px 12px;font:16px/1.4 Inter,system-ui,sans-serif;
58 88 border:1.5px solid var(--ink,#141814);border-radius:9px;background:var(--paper,#f5f3ee);outline:none}
59 89 .kaa-in button{min-width:52px;min-height:44px;border:1.5px solid var(--ink,#141814);border-radius:9px;
60 − background:var(--ink,#141814);color:var(--accent,#d9f26b);font:700 16px "Space Grotesk",system-ui;cursor:pointer}
90 + background:var(--ink,#141814);color:var(--accent,#d9f26b);font:700 16px "Space Grotesk",system-ui;cursor:pointer;touch-action:manipulation}
61 91 .kaa-in button:disabled{opacity:.45}
62 − .kaa-hello{font-size:12.5px;color:var(--ink-2,#4d5551);padding:4px 2px}
92 + .kaa-hello{font-size:12.5px;color:var(--ink-2,#4d5551);padding:4px 2px;max-width:760px}
63 93 .kaa-dots::after{content:"…";animation:kaa-b 1.2s infinite}
64 94 @keyframes kaa-b{0%{opacity:.2}50%{opacity:1}100%{opacity:.2}}
65 − @media (max-width:560px){.kaa-panel{right:8px;left:8px;width:auto}}
95 + @media (max-width:640px){.kaa-x1{display:none}}
66 96 `;
67 97
68 − /* ---------- markdown minimal (gras, liens, puces) — texte échappé d'abord ---------- */
98 + /* ---------- markdown complet (rendu en streaming, texte échappé d'abord) ---------- */
69 99 function esc(s) {
70 100 return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
71 101 }
72 − function md(s) {
73 − return esc(s)
74 − .replace(/\*\*([^*]+)\*\*/g, "<b>$1</b>")
75 − .replace(/(https?:\/\/[^\s<)"']+)/g, function (u) {
76 − return '<a href="' + u + '" target="_blank" rel="noopener noreferrer">' + u.replace(/^https?:\/\/(www\.)?/, "").slice(0, 40) + "</a>";
77 − });
102 + function inline(s) {
103 + s = esc(s);
104 + s = s.replace(/`([^`\n]+)`/g, "<code>$1</code>");
105 + s = s.replace(/\[([^\]\n]+)\]\((https?:\/\/[^\s)]+)\)/g,
106 + '<a href="$2" target="_blank" rel="noopener noreferrer">$1</a>');
107 + s = s.replace(/\*\*([^*\n]+)\*\*/g, "<b>$1</b>");
108 + s = s.replace(/(^|[^*\w])\*([^*\n]+)\*(?!\*)/g, "$1<i>$2</i>");
109 + s = s.replace(/(^|[^"'>=\w])(https?:\/\/[^\s<)"']+)/g, function (m, pre, u) {
110 + return pre + '<a href="' + u + '" target="_blank" rel="noopener noreferrer">' +
111 + u.replace(/^https?:\/\/(www\.)?/, "").slice(0, 42) + "</a>";
112 + });
113 + return s;
114 + }
115 + function md(src) {
116 + var lines = String(src).split("\n"), out = [], i = 0, m;
117 + function para(buf) { if (buf.length) out.push("<p>" + buf.map(inline).join("<br>") + "</p>"); }
118 + while (i < lines.length) {
119 + var l = lines[i];
120 + if (/^\s*```/.test(l)) { /* bloc de code */
121 + var code = []; i++;
122 + while (i < lines.length && !/^\s*```/.test(lines[i])) code.push(lines[i++]);
123 + i++;
124 + out.push("<pre><code>" + esc(code.join("\n")) + "</code></pre>");
125 + } else if ((m = l.match(/^\s*(#{1,4})\s+(.*)$/))) { /* titres */
126 + out.push("<h" + m[1].length + ">" + inline(m[2]) + "</h" + m[1].length + ">"); i++;
127 + } else if (/^\s*(---+|\*\*\*+)\s*$/.test(l)) { /* filet */
128 + out.push("<hr>"); i++;
129 + } else if (/^\s*&gt;|^\s*>/.test(l)) { /* citation */
130 + var q = [];
131 + while (i < lines.length && /^\s*>/.test(lines[i])) q.push(lines[i++].replace(/^\s*>\s?/, ""));
132 + out.push("<blockquote>" + q.map(inline).join("<br>") + "</blockquote>");
133 + } else if (/^\s*\|.*\|\s*$/.test(l)) { /* tableau */
134 + var rows = [];
135 + while (i < lines.length && /^\s*\|.*\|\s*$/.test(lines[i])) {
136 + var cells = lines[i].trim().replace(/^\||\|$/g, "").split("|").map(function (c) { return c.trim(); });
137 + if (!/^[:\-\s|]+$/.test(lines[i].replace(/\|/g, ""))) rows.push(cells);
138 + i++;
139 + }
140 + if (rows.length) {
141 + var t = "<table>";
142 + rows.forEach(function (r, ri) {
143 + var tag = ri === 0 ? "th" : "td";
144 + t += "<tr>" + r.map(function (c) { return "<" + tag + ">" + inline(c) + "</" + tag + ">"; }).join("") + "</tr>";
145 + });
146 + out.push(t + "</table>");
147 + }
148 + } else if (/^\s*[-*+]\s+/.test(l)) { /* liste à puces */
149 + var ul = [];
150 + while (i < lines.length && /^\s*[-*+]\s+/.test(lines[i]))
151 + ul.push("<li>" + inline(lines[i++].replace(/^\s*[-*+]\s+/, "")) + "</li>");
152 + out.push("<ul>" + ul.join("") + "</ul>");
153 + } else if (/^\s*\d+[.)]\s+/.test(l)) { /* liste numérotée */
154 + var ol = [];
155 + while (i < lines.length && /^\s*\d+[.)]\s+/.test(lines[i]))
156 + ol.push("<li>" + inline(lines[i++].replace(/^\s*\d+[.)]\s+/, "")) + "</li>");
157 + out.push("<ol>" + ol.join("") + "</ol>");
158 + } else if (!l.trim()) { i++; } /* ligne vide */
159 + else { /* paragraphe */
160 + var buf = [];
161 + while (i < lines.length && lines[i].trim() &&
162 + !/^\s*(```|#{1,4}\s|[-*+]\s|\d+[.)]\s|>|\||---+\s*$)/.test(lines[i]))
163 + buf.push(lines[i++]);
164 + if (!buf.length) buf.push(lines[i++] || "");
165 + para(buf);
166 + }
167 + }
168 + return out.join("");
78 169 }
79 170
80 171 /* ---------- état ---------- */
@@ -98,10 +189,10 @@
98 189 panel.setAttribute("aria-label", "KA Agent");
99 190 panel.innerHTML =
100 191 '<div class="kaa-head"><b>KA<span class="kaa-ka">Agent</span></b><small>Groupe KA · IA</small><span class="kaa-sp"></span>' +
101 − '<button class="kaa-hbtn kaa-x1" title="Plein écran" aria-label="Plein écran">⛶</button>' +
192 + '<button class="kaa-hbtn kaa-x1" title="Réduire / agrandir" aria-label="Réduire ou agrandir">▭</button>' +
102 193 '<button class="kaa-hbtn kaa-x2" title="Fermer" aria-label="Fermer">✕</button></div>' +
103 194 '<div class="kaa-log"></div>' +
104 − '<div class="kaa-in"><textarea rows="1" placeholder="Posez votre question…" aria-label="Votre question"></textarea>' +
195 + '<div class="kaa-in"><textarea rows="1" enterkeyhint="send" autocapitalize="sentences" autocomplete="off" placeholder="Posez votre question…" aria-label="Votre question"></textarea>' +
105 196 "<button aria-label=\"Envoyer\">➤</button></div>";
106 197 document.body.appendChild(btn);
107 198 document.body.appendChild(panel);
@@ -132,45 +223,83 @@
132 223 if (log.length) return;
133 224 var d = document.createElement("div");
134 225 d.className = "kaa-hello";
135 − d.textContent = "👋 Je suis KA Agent, l'assistant de l'écosystème Groupe KA. Posez-moi une question sur ce site, ses données (prix, annonces, stats…) ou sur le groupe.";
226 + d.textContent = "👋 Je suis KA Agent, l'assistant de l'écosystème Groupe KA. Posez-moi une question sur ce site, ses données (prix, annonces, fiches, stats…) ou sur le groupe.";
136 227 logEl.appendChild(d);
137 228 }
138 229 function render() {
139 230 logEl.innerHTML = "";
140 231 hello();
141 − log.forEach(function (m) { bubble(m.role === "user" ? "kaa-u" : "kaa-a", md(m.content)); });
232 + log.forEach(function (m) {
233 + m.role === "user" ? bubble("kaa-u", esc(m.content)) : bubble("kaa-a", md(m.content));
234 + });
142 235 scroll();
143 236 }
144 237
145 − /* ---------- ouverture / plein écran ---------- */
146 − /* Sur téléphone : panneau plein écran d'office + scroll d'arrière-plan
147 − verrouillé tant qu'il est ouvert (html.kaa-lock). Pas de focus clavier
148 − forcé au tap (le clavier ne s'ouvre que si l'utilisateur touche le champ). */
149 − var mobileMq = window.matchMedia("(max-width: 640px)");
238 + /* ---------- plein écran + clavier mobile ----------
239 + Ouverture = PLEIN ÉCRAN direct (desktop et mobile). ▭ réduit en fenêtre
240 + (desktop seulement — caché sur mobile). Tant que le plein écran est ouvert,
241 + l'arrière-plan est GELÉ (body position:fixed, scroll restauré à la
242 + fermeture) et le panneau se cale sur window.visualViewport : quand le
243 + clavier s'ouvre, le panneau rétrécit à la place de laisser iOS
244 + zoomer/pousser la page. Pas de focus clavier forcé au tap sur mobile. */
150 245 var fineInput = window.matchMedia("(hover: hover) and (pointer: fine)");
151 − function syncLock() {
152 − var open = panel.classList.contains("kaa-open");
153 − if (open && mobileMq.matches) panel.classList.add("kaa-full");
154 − document.documentElement.classList.toggle(
155 − "kaa-lock", open && panel.classList.contains("kaa-full"));
246 + var vv = window.visualViewport;
247 + var savedY = 0;
248 +
249 + function isOpen() { return panel.classList.contains("kaa-open"); }
250 + function isFull() { return panel.classList.contains("kaa-full"); }
251 +
252 + function fitVV() {
253 + if (!vv || !isOpen() || !isFull()) { panel.style.height = ""; panel.style.top = ""; return; }
254 + panel.style.top = Math.round(vv.offsetTop) + "px";
255 + panel.style.height = Math.round(vv.height) + "px";
256 + scroll();
156 257 }
157 − btn.addEventListener("click", function () {
158 − panel.classList.toggle("kaa-open");
159 − if (panel.classList.contains("kaa-open")) {
160 − render();
161 − if (fineInput.matches) ta.focus();
258 + if (vv) {
259 + vv.addEventListener("resize", fitVV);
260 + vv.addEventListener("scroll", fitVV);
261 + }
262 +
263 + function lockBg(on) {
264 + var b = document.body, h = document.documentElement;
265 + if (on && !h.classList.contains("kaa-lock")) {
266 + savedY = window.scrollY || 0;
267 + h.classList.add("kaa-lock");
268 + b.style.position = "fixed";
269 + b.style.top = -savedY + "px";
270 + b.style.left = "0"; b.style.right = "0"; b.style.width = "100%";
271 + } else if (!on && h.classList.contains("kaa-lock")) {
272 + h.classList.remove("kaa-lock");
273 + b.style.position = ""; b.style.top = ""; b.style.left = ""; b.style.right = ""; b.style.width = "";
274 + window.scrollTo(0, savedY);
162 275 }
163 − syncLock();
276 + }
277 + function sync() {
278 + lockBg(isOpen() && isFull());
279 + fitVV();
280 + }
281 +
282 + btn.addEventListener("click", function () {
283 + panel.classList.add("kaa-open", "kaa-full"); // plein écran d'office
284 + render();
285 + if (fineInput.matches) ta.focus();
286 + sync();
164 287 });
165 288 panel.querySelector(".kaa-x2").addEventListener("click", function () {
166 289 panel.classList.remove("kaa-open", "kaa-full");
167 − syncLock();
290 + sync();
168 291 });
169 292 panel.querySelector(".kaa-x1").addEventListener("click", function () {
170 293 panel.classList.toggle("kaa-full");
171 − syncLock();
294 + sync();
172 295 scroll();
173 296 });
297 + document.addEventListener("keydown", function (e) {
298 + if (e.key === "Escape" && isOpen()) {
299 + panel.classList.remove("kaa-open", "kaa-full");
300 + sync();
301 + }
302 + });
174 303
175 304 /* ---------- envoi + flux SSE ---------- */
176 305 var busy = false;
@@ -182,7 +311,7 @@
182 311 ta.value = "";
183 312 log.push({ role: "user", content: q });
184 313 save();
185 − bubble("kaa-u", md(q));
314 + bubble("kaa-u", esc(q));
186 315 var out = bubble("kaa-a", '<span class="kaa-dots"></span>');
187 316 var acc = "";
188 317 var chips = [];
@@ -211,7 +340,7 @@
211 340 try { data = JSON.parse(dm); } catch (e) {}
212 341 if (ev === "delta" && data.text) {
213 342 acc += data.text;
214 − out.innerHTML = md(acc);
343 + out.innerHTML = md(acc); // markdown re-rendu à chaque delta
215 344 scroll();
216 345 } else if (ev === "tool") {
217 346 chips.push(toolChip(data.name || "recherche"));
modified src/app/api/stats/ecosystem-report/route.ts +38 −24
@@ -1,49 +1,63 @@
1 1 // Auteur : Simon-Pierre Boucher — contact@spboucher.ai
2 2 // /api/stats/ecosystem-report — proxy en streaming du rapport écosystème PDF
3 3 // généré par API-KA (GET https://www.api-ka.com/api/stats/ecosystem-report).
4 −// Conserve Content-Type et Content-Disposition (filename
5 −// groupe-ka_ecosysteme_stats_<periode>_<date>.pdf) ; API-KA garde son propre
6 −// cache de 10 minutes par (period, mode).
7 −import { NextRequest, NextResponse } from "next/server";
4 +// v2 : 5 modes de rapport (complet | synthese | tendances | repartitions |
5 +// donnees) + plage personnalisée from/to relayés à API-KA ; un mode ou une
6 +// période inconnus retombent sur les valeurs par défaut (tolérant — si
7 +// API-KA ignore encore `mode`, il renvoie le rapport complet). Conserve
8 +// Content-Type et Content-Disposition (filename groupe-ka_ecosysteme_stats_
9 +// <periode>[_<mode>]_<date>.pdf) ; API-KA garde son propre cache de
10 +// 10 minutes par (period, mode). Aussi exposé sous /api/stats/report
11 +// (endpoint standard du contrat src/ka/stats/SPEC.md).
12 +import { NextRequest } from "next/server";
8 13
9 14 export const dynamic = "force-dynamic";
10 15
11 16 const UPSTREAM = "https://www.api-ka.com/api/stats/ecosystem-report";
12 17 const PERIODS = new Set(["auj", "7j", "30j", "3m", "6m", "12m", "annee", "tout"]);
13 −const MODES = new Set(["complet", "synthese"]);
18 +const MODES = new Set([
19 + "complet",
20 + "synthese",
21 + "tendances",
22 + "repartitions",
23 + "donnees",
24 +]);
25 +const DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
14 26
15 27 export async function GET(req: NextRequest) {
16 28 const sp = req.nextUrl.searchParams;
17 − const period = sp.get("period") ?? "30j";
18 − const mode = sp.get("mode") ?? "complet";
19 − if (!PERIODS.has(period) || !MODES.has(mode)) {
20 − return NextResponse.json(
21 − { error: "Paramètres invalides (period, mode)" },
22 − { status: 422 },
23 − );
24 − }
29 + const rawPeriod = sp.get("period") ?? "30j";
30 + const rawMode = sp.get("mode") ?? "complet";
31 + const period = PERIODS.has(rawPeriod) ? rawPeriod : "30j";
32 + const mode = MODES.has(rawMode) ? rawMode : "complet";
33 + const qs = new URLSearchParams({ period, mode });
34 + const from = sp.get("from");
35 + const to = sp.get("to");
36 + if (from && DATE_RE.test(from)) qs.set("from", from);
37 + if (to && DATE_RE.test(to)) qs.set("to", to);
38 +
25 39 let upstream: Response;
26 40 try {
27 − upstream = await fetch(
28 − `${UPSTREAM}?period=${encodeURIComponent(period)}&mode=${encodeURIComponent(mode)}`,
29 − {
30 − cache: "no-store",
31 − signal: AbortSignal.timeout(60_000),
32 − headers: { accept: "application/pdf" },
33 − },
34 − );
41 + upstream = await fetch(`${UPSTREAM}?${qs}`, {
42 + cache: "no-store",
43 + signal: AbortSignal.timeout(60_000),
44 + headers: { accept: "application/pdf" },
45 + });
35 46 } catch {
36 − return NextResponse.json(
47 + return Response.json(
37 48 { error: "API-KA injoignable — réessayez dans quelques instants" },
38 49 { status: 502 },
39 50 );
40 51 }
41 52 if (!upstream.ok || !upstream.body) {
42 − return NextResponse.json(
53 + return Response.json(
43 54 { error: `API-KA a répondu ${upstream.status}` },
44 55 { status: 502 },
45 56 );
46 57 }
58 + const fallbackName = `groupe-ka_ecosysteme_stats_${period}${
59 + mode !== "complet" ? `_${mode}` : ""
60 + }_${new Date().toISOString().slice(0, 10)}.pdf`;
47 61 return new Response(upstream.body, {
48 62 status: 200,
49 63 headers: {
@@ -51,7 +65,7 @@ export async function GET(req: NextRequest) {
51 65 upstream.headers.get("content-type") ?? "application/pdf",
52 66 "content-disposition":
53 67 upstream.headers.get("content-disposition") ??
54 − `attachment; filename="groupe-ka_ecosysteme_stats_${period}.pdf"`,
68 + `attachment; filename="${fallbackName}"`,
55 69 "cache-control": "no-store",
56 70 },
57 71 });
added src/app/api/stats/report/route.ts +8 −0
@@ -0,0 +1,8 @@
1 +// Auteur : Simon-Pierre Boucher — contact@spboucher.ai
2 +// /api/stats/report — endpoint standard du contrat Stats commun
3 +// (src/ka/stats/SPEC.md §3) pour le hub : le rapport du hub EST le rapport
4 +// écosystème consolidé. Alias du proxy /api/stats/ecosystem-report
5 +// (streaming API-KA, 5 modes, tolérant).
6 +export { GET } from "../ecosystem-report/route";
7 +
8 +export const dynamic = "force-dynamic";
added src/app/stats/eco-client.tsx +468 −0
@@ -0,0 +1,468 @@
1 +// Auteur : Simon-Pierre Boucher — contact@spboucher.ai
2 +// /stats — partie interactive du tableau de bord maître : rend le payload
3 +// consolidé (src/lib/ecostats.ts) avec le kit de graphiques commun
4 +// src/ka/stats/kacharts.tsx (v2) : KPI + sparklines, jauges, courbe du
5 +// volume agrégé, classement (barres à deltas + anneau), croissance comparée
6 +// (multi-courbes indice 100), volume empilé par plateforme, calendriers
7 +// agrégés, blocs répartitions des plateformes phares (accent de la marque),
8 +// résumé par plateforme, table détaillée, records et menu de rapports PDF
9 +// (5 modes, proxy /api/stats/report → API-KA). Tolérant : toute section sans
10 +// données est simplement masquée — jamais un chiffre inventé.
11 +"use client";
12 +
13 +import type { CSSProperties } from "react";
14 +import {
15 + BarChart,
16 + CalendarHeatmap,
17 + DataTable,
18 + Donut,
19 + GaugeCard,
20 + HourHeatmap,
21 + KpiCard,
22 + LineChart,
23 + MultiLineChart,
24 + PdfButton,
25 + RecordCard,
26 + StackedBarChart,
27 + StatSummary,
28 + fmtNum,
29 +} from "@/ka/stats/kacharts";
30 +import type { EcoPayload, PlatformSummary } from "@/lib/ecostats";
31 +import { PERIODS } from "@/lib/ecostats";
32 +
33 +/* Pose l'accent d'une plateforme sur un sous-arbre (les composants du kit
34 + dessinent avec var(--accent)). */
35 +const accentStyle = (accent: string): CSSProperties =>
36 + ({ "--accent": accent } as CSSProperties);
37 +
38 +function SectionHead({
39 + kicker,
40 + title,
41 + lead,
42 +}: {
43 + kicker: string;
44 + title: string;
45 + lead?: string;
46 +}) {
47 + return (
48 + <>
49 + <p className="kicker">{kicker}</p>
50 + <h2 className="gk-display mt-3 text-[clamp(22px,3vw,30px)] font-bold tracking-[-0.03em]">
51 + {title}
52 + </h2>
53 + {lead ? (
54 + <p className="mt-3 max-w-2xl text-[13px] text-ink-2">{lead}</p>
55 + ) : null}
56 + </>
57 + );
58 +}
59 +
60 +function Pastille({ accent }: { accent: string }) {
61 + return (
62 + <span
63 + aria-hidden="true"
64 + className="inline-block h-[10px] w-[10px] flex-none rounded-[3px] border border-ink"
65 + style={{ background: accent }}
66 + />
67 + );
68 +}
69 +
70 +/** Mini-sparkline (tendance du volume principal d'une plateforme). */
71 +function Spark({ pts, accent }: { pts: { t: string; v: number }[]; accent: string }) {
72 + if (pts.length < 2) return null;
73 + const w = 130;
74 + const h = 34;
75 + const vmax = Math.max(...pts.map((p) => p.v));
76 + const vmin = Math.min(...pts.map((p) => p.v));
77 + const rng = vmax - vmin || 1;
78 + const X = (i: number) => (w * i) / (pts.length - 1);
79 + const Y = (v: number) => 2 + (h - 4) * (1 - (v - vmin) / rng);
80 + const d = pts
81 + .map((p, i) => `${i ? "L" : "M"}${X(i).toFixed(1)},${Y(p.v).toFixed(1)}`)
82 + .join("");
83 + return (
84 + <svg
85 + viewBox={`0 0 ${w} ${h}`}
86 + className="h-[26px] w-[104px] flex-none"
87 + aria-hidden="true"
88 + >
89 + <path d={`${d}L${w},${h}L0,${h}Z`} fill={accent} opacity={0.16} />
90 + <path d={d} fill="none" stroke={accent} strokeWidth={1.8} />
91 + </svg>
92 + );
93 +}
94 +
95 +/** Format compact honnête (aligné sur fmtCompact côté serveur). */
96 +function fmtVal(value: number | string, unit?: string): string {
97 + if (typeof value !== "number" || !Number.isFinite(value))
98 + return `${value}${unit ? ` ${unit}` : ""}`;
99 + let txt: string;
100 + if (Math.abs(value) >= 1_000_000_000) {
101 + txt = `${(value / 1_000_000_000).toLocaleString("fr-CA", { maximumFractionDigits: 2 })} G`;
102 + } else if (Math.abs(value) >= 100_000_000) {
103 + txt = `${(value / 1_000_000).toLocaleString("fr-CA", { maximumFractionDigits: 1 })} M`;
104 + } else {
105 + txt = fmtNum(value);
106 + }
107 + return unit ? `${txt} ${unit}` : txt;
108 +}
109 +
110 +function PlatformCard({ p }: { p: PlatformSummary }) {
111 + const { site } = p;
112 + if (!p.ok) {
113 + return (
114 + <article className="gk-card flex flex-col bg-surface-2 p-5">
115 + <div className="flex items-center gap-2">
116 + <Pastille accent={site.accent} />
117 + <span className="gk-display truncate text-[17px] font-bold tracking-[-0.02em] text-ink-3">
118 + {site.wordmark}
119 + </span>
120 + </div>
121 + <p className="klabel mt-4">Données indisponibles</p>
122 + <p className="mt-2 text-[13px] text-ink-3">
123 + La plateforme n&apos;a pas répondu au moment du chargement. Ses
124 + statistiques restent consultables directement sur son site.
125 + </p>
126 + <a
127 + href={`https://${site.domain}/stats`}
128 + target="_blank"
129 + rel="noopener noreferrer"
130 + className="gk-mono mt-auto pt-4 text-[11.5px] font-bold text-ink-3 underline-offset-4 hover:text-ink hover:underline"
131 + >
132 + Stats détaillées →
133 + </a>
134 + </article>
135 + );
136 + }
137 + const spark = p.kpis[0]?.spark ?? [];
138 + return (
139 + <article className="gk-card flex flex-col p-5">
140 + <div className="flex flex-wrap items-center justify-between gap-x-3 gap-y-1">
141 + <span className="flex min-w-0 items-center gap-2">
142 + <Pastille accent={site.accent} />
143 + <span className="gk-display truncate text-[17px] font-bold tracking-[-0.02em]">
144 + {site.wordmark}
145 + </span>
146 + </span>
147 + <span className="flex items-center gap-2">
148 + {p.v2 ? (
149 + <span className="gk-mono rounded-[4px] bg-lime-soft px-[6px] py-[2px] text-[9px] font-bold tracking-[0.08em] text-green uppercase">
150 + v2
151 + </span>
152 + ) : null}
153 + <a
154 + href={`https://${site.domain}`}
155 + target="_blank"
156 + rel="noopener noreferrer"
157 + className="gk-mono text-[10.5px] font-bold text-ink-3 underline-offset-4 hover:text-ink hover:underline"
158 + >
159 + {site.domain}
160 + </a>
161 + </span>
162 + </div>
163 + {spark.length >= 2 ? (
164 + <div className="mt-3 flex items-center justify-between gap-3">
165 + <span className="klabel">Tendance · volume principal</span>
166 + <Spark pts={spark} accent={site.accent} />
167 + </div>
168 + ) : null}
169 + <dl className="mt-3 space-y-3">
170 + {p.kpis.map((k) => (
171 + <div
172 + key={k.id}
173 + className="flex items-baseline justify-between gap-3 border-b border-dashed border-[rgba(20,24,20,0.18)] pb-2"
174 + >
175 + <dt className="min-w-0 text-[12px] leading-snug text-ink-2">
176 + {k.label}
177 + </dt>
178 + <dd className="flex flex-none items-baseline gap-2">
179 + <span className="gk-mono text-[15px] font-bold tracking-[-0.01em] whitespace-nowrap">
180 + {fmtVal(k.value, k.unit)}
181 + </span>
182 + {typeof k.delta_pct === "number" ? (
183 + <span
184 + className={`gk-mono text-[10.5px] font-bold ${
185 + (k.direction ?? (k.delta_pct >= 0 ? "up" : "down")) === "up"
186 + ? "text-green"
187 + : "text-danger"
188 + }`}
189 + >
190 + {k.delta_pct >= 0 ? "▲ +" : "▼ "}
191 + {k.delta_pct.toLocaleString("fr-CA")} %
192 + </span>
193 + ) : null}
194 + </dd>
195 + </div>
196 + ))}
197 + </dl>
198 + {p.growth ? (
199 + <p className="gk-mono mt-3 text-[10.5px] text-ink-3">
200 + Croissance{" "}
201 + <b className={p.growth.pct >= 0 ? "text-green" : "text-danger"}>
202 + {p.growth.pct >= 0 ? "+" : ""}
203 + {p.growth.pct.toLocaleString("fr-CA")} %
204 + </b>
205 + {p.growth.derived ? " (dérivée de la série publiée)" : " vs période précédente"}
206 + </p>
207 + ) : null}
208 + {p.record ? (
209 + <p className="mt-3 rounded-md bg-lime-soft px-3 py-2 text-[12px] leading-snug">
210 + <span className="gk-mono text-[10px] font-bold tracking-[0.08em] text-green uppercase">
211 + Record ·{" "}
212 + </span>
213 + {p.record.label} : <strong>{p.record.value}</strong>
214 + {p.record.date ? (
215 + <span className="text-ink-3"> ({p.record.date})</span>
216 + ) : null}
217 + </p>
218 + ) : null}
219 + <a
220 + href={`https://${site.domain}/stats`}
221 + target="_blank"
222 + rel="noopener noreferrer"
223 + className="gk-mono mt-auto pt-4 text-[11.5px] font-bold text-green underline-offset-4 hover:text-ink hover:underline"
224 + >
225 + Stats détaillées → {site.domain}/stats
226 + </a>
227 + </article>
228 + );
229 +}
230 +
231 +/** Bloc « sous le capot » d'une plateforme phare : répartitions + géo,
232 + * dessinées avec l'accent de la marque. */
233 +function SpotlightCard({ p }: { p: PlatformSummary }) {
234 + if (!p.breakdown && !p.geo) return null;
235 + return (
236 + <article className="gk-card p-5 sm:p-6" style={accentStyle(p.site.accent)}>
237 + <div className="flex flex-wrap items-center justify-between gap-x-3 gap-y-1">
238 + <span className="flex min-w-0 items-center gap-2">
239 + <Pastille accent={p.site.accent} />
240 + <span className="gk-display truncate text-[17px] font-bold tracking-[-0.02em]">
241 + {p.site.wordmark}
242 + </span>
243 + </span>
244 + <span className="gk-mono text-[10.5px] font-bold text-ink-3">
245 + {p.site.domain}
246 + </span>
247 + </div>
248 + <div className="mt-5 grid gap-5 xl:grid-cols-2">
249 + {p.breakdown ? (
250 + p.breakdown.kind === "donut" ? (
251 + <Donut title={p.breakdown.title} items={p.breakdown.items} />
252 + ) : (
253 + <BarChart title={p.breakdown.title} items={p.breakdown.items} />
254 + )
255 + ) : null}
256 + {p.geo ? <BarChart title={p.geo.title} items={p.geo.items} /> : null}
257 + </div>
258 + </article>
259 + );
260 +}
261 +
262 +export default function EcoStatsClient({ data }: { data: EcoPayload }) {
263 + const spotlights = data.platforms
264 + .filter((p) => p.ok && (p.breakdown || p.geo))
265 + .slice(0, 2);
266 + const hasDerived =
267 + data.growthDerived ||
268 + data.platforms.some((p) => p.growth?.derived);
269 +
270 + return (
271 + <>
272 + {/* rapports PDF (menu 5 modes) + fraîcheur */}
273 + <div className="mt-6 flex flex-wrap items-center gap-3">
274 + <PdfButton period={data.period} endpoint="/api/stats/report" />
275 + </div>
276 + <p className="gk-mono mt-3 text-[11px] text-ink-3">
277 + {data.freshness
278 + ? `Données mises à jour le ${data.freshness} (heure de l'Est) · cache 10 min · rapport PDF généré par API-KA`
279 + : "Fraîcheur inconnue — aucune plateforme jointe pour le moment"}
280 + </p>
281 +
282 + {/* sélecteur de période : simples liens ?period=… */}
283 + <nav aria-label="Période" className="mt-6 flex flex-wrap gap-2">
284 + {PERIODS.map(([key, label]) => (
285 + <a
286 + key={key}
287 + href={`/stats?period=${key}`}
288 + aria-current={key === data.period ? "page" : undefined}
289 + className={`stat-chip !py-[6px] transition-colors ${
290 + key === data.period ? "!bg-ink !text-lime" : "hover:!bg-lime-soft"
291 + }`}
292 + >
293 + {label}
294 + </a>
295 + ))}
296 + </nav>
297 +
298 + {/* 1 — bandeau KPI écosystème */}
299 + <section className="mt-8 grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
300 + {data.banner.map((k) => (
301 + <KpiCard key={k.id} k={k} />
302 + ))}
303 + </section>
304 +
305 + {/* 2 — jauges de couverture */}
306 + <section className="mt-4 grid gap-4 sm:grid-cols-3">
307 + {data.gauges.map((g) => (
308 + <GaugeCard key={g.id} g={g} />
309 + ))}
310 + </section>
311 +
312 + {/* 3 — volume agrégé dans le temps */}
313 + {data.volume ? (
314 + <section className="mt-14">
315 + <SectionHead
316 + kicker="Tendance · volume agrégé"
317 + title="L'écosystème, jour par jour"
318 + lead={data.volume.note}
319 + />
320 + <div className="mt-5">
321 + <LineChart serie={data.volume.serie} />
322 + <StatSummary serie={data.volume.serie} />
323 + </div>
324 + </section>
325 + ) : null}
326 +
327 + {/* 4 — classement : barres à deltas + anneau de répartition */}
328 + {data.ranking.length > 0 ? (
329 + <section className="mt-14">
330 + <SectionHead
331 + kicker="Classement · volume principal"
332 + title="Les plateformes, par volume"
333 + lead="Le « volume principal » est le premier indicateur du tableau de bord de chaque plateforme (annonces actives, véhicules, produits, pages indexées…). Les volumes ne sont pas de même nature : le classement donne un ordre de grandeur, pas une comparaison homogène."
334 + />
335 + <div className="mt-5 grid gap-5 lg:grid-cols-2">
336 + <BarChart
337 + title="Classement par volume principal"
338 + items={data.ranking}
339 + />
340 + <Donut
341 + title="Répartition du volume agrégé"
342 + items={data.ranking.map(({ label, value }) => ({ label, value }))}
343 + />
344 + </div>
345 + </section>
346 + ) : null}
347 +
348 + {/* 5 — croissance comparée (indice 100) */}
349 + {data.growthIndex ? (
350 + <section className="mt-14">
351 + <SectionHead
352 + kicker="Croissance comparée"
353 + title="Qui grandit le plus vite ?"
354 + lead={data.growthIndex.note}
355 + />
356 + <div className="mt-5">
357 + <MultiLineChart ms={data.growthIndex.ms} />
358 + </div>
359 + </section>
360 + ) : null}
361 +
362 + {/* 6 — volume empilé par plateforme */}
363 + {data.stacked ? (
364 + <section className="mt-14">
365 + <SectionHead
366 + kicker="Composition · dans le temps"
367 + title="Le volume, plateforme par plateforme"
368 + lead={data.stacked.note}
369 + />
370 + <div className="mt-5">
371 + <StackedBarChart st={data.stacked.st} />
372 + </div>
373 + </section>
374 + ) : null}
375 +
376 + {/* 7 — calendriers agrégés */}
377 + {data.heat || data.hourly ? (
378 + <section className="mt-14">
379 + <SectionHead
380 + kicker="Activité · calendriers"
381 + title="Le pouls de l'écosystème"
382 + />
383 + <div className="mt-5 grid gap-5">
384 + {data.heat ? (
385 + <div>
386 + <CalendarHeatmap title={data.heat.title} cells={data.heat.cells} />
387 + <p className="mt-2 text-[12px] leading-relaxed text-ink-3">
388 + {data.heat.note}
389 + </p>
390 + </div>
391 + ) : null}
392 + {data.hourly ? (
393 + <div>
394 + <HourHeatmap title={data.hourly.title} cells={data.hourly.cells} />
395 + <p className="mt-2 text-[12px] leading-relaxed text-ink-3">
396 + {data.hourly.note}
397 + </p>
398 + </div>
399 + ) : null}
400 + </div>
401 + </section>
402 + ) : null}
403 +
404 + {/* 8 — répartitions des plateformes phares */}
405 + {spotlights.length > 0 ? (
406 + <section className="mt-14">
407 + <SectionHead
408 + kicker="Sous le capot · répartitions"
409 + title="Les plus grosses, décomposées"
410 + lead="Les tableaux de bord des plateformes publient aussi leurs répartitions — par type, par ville, par région. Voici celles des plus gros inventaires joints, lues telles quelles et dessinées aux couleurs de chaque marque."
411 + />
412 + <div className="mt-5 grid gap-5 lg:grid-cols-2">
413 + {spotlights.map((p) => (
414 + <SpotlightCard key={p.site.id} p={p} />
415 + ))}
416 + </div>
417 + </section>
418 + ) : null}
419 +
420 + {/* 9 — un bloc résumé par plateforme */}
421 + <section className="mt-14">
422 + <SectionHead
423 + kicker="Plateforme par plateforme"
424 + title="Le résumé de chacune"
425 + />
426 + <div className="mt-5 grid gap-5 sm:grid-cols-2 lg:grid-cols-3">
427 + {data.platforms.map((p) => (
428 + <PlatformCard key={p.site.id} p={p} />
429 + ))}
430 + </div>
431 + </section>
432 +
433 + {/* 10 — table détaillée */}
434 + <section className="mt-14">
435 + <SectionHead
436 + kicker="Données · classement détaillé"
437 + title="Toutes les plateformes en une table"
438 + />
439 + <div className="mt-5">
440 + <DataTable spec={data.table} />
441 + </div>
442 + {hasDerived ? (
443 + <p className="gk-mono mt-3 text-[11px] text-ink-3">
444 + * croissance dérivée de la série de tendance publiée par la
445 + plateforme (dernier point vs premier point de sa fenêtre), en
446 + attendant qu&apos;elle publie sa variation vs période précédente.
447 + </p>
448 + ) : null}
449 + </section>
450 +
451 + {/* 11 — records écosystème */}
452 + {data.records.length > 0 ? (
453 + <section className="mt-14">
454 + <SectionHead
455 + kicker="Records · faits marquants"
456 + title="Les records de l'écosystème"
457 + lead="Générés depuis les données consolidées et les records publiés par les plateformes elles-mêmes."
458 + />
459 + <div className="mt-5 grid gap-3 sm:grid-cols-2">
460 + {data.records.map((r) => (
461 + <RecordCard key={`${r.label}-${r.value}`} r={r} />
462 + ))}
463 + </div>
464 + </section>
465 + ) : null}
466 + </>
467 + );
468 +}
modified src/app/stats/page.tsx +29 −420
@@ -1,223 +1,30 @@
1 1 // Auteur : Simon-Pierre Boucher — contact@spboucher.ai
2 2 // /stats — tableau de bord maître de l'écosystème Groupe KA : consolidation
3 −// LIVE des tableaux de bord /api/stats/dashboard des 11 plateformes de
4 −// données (src/lib/ecostats.ts, cache 10 min), classement, bloc résumé par
5 −// plateforme, rapport écosystème PDF (proxy API-KA). Aucune donnée inventée :
6 −// une plateforme injoignable = carte « indisponible » grise.
3 +// LIVE des tableaux de bord /api/stats/dashboard des plateformes de données
4 +// (src/lib/ecostats.ts, cache 10 min) rendue avec le kit commun
5 +// src/ka/stats/kacharts.tsx v2 : KPI + sparklines, jauges, volume agrégé,
6 +// classement (barres + anneau), croissance comparée (indice 100), volume
7 +// empilé, calendriers agrégés, résumé par plateforme, table détaillée,
8 +// records et menu de rapports PDF (5 modes, proxy API-KA). Aucune donnée
9 +// inventée : plateforme injoignable = carte « indisponible », dashboard v1 =
10 +// bloc dégradé propre (sans sparkline ni graphiques temporels).
7 11 import type { Metadata } from "next";
8 −import { fmtInt, getLiveMetrics } from "@/lib/live";
12 +import { getLiveMetrics } from "@/lib/live";
9 13 import {
10 14 PERIODS,
11 − type Breakdown,
12 − type Kpi,
13 15 type PeriodKey,
14 − type PlatformStats,
15 − breakdownItems,
16 − consolidate,
17 − firstBreakdown,
18 − geoBreakdown,
16 + buildEcoPayload,
19 17 getEcosystemStats,
20 18 isPeriod,
21 − mainKpi,
22 − newKpi,
23 − topKpis,
24 19 } from "@/lib/ecostats";
20 +import EcoStatsClient from "./eco-client";
25 21
26 22 export const metadata: Metadata = {
27 23 title: "Statistiques de l'écosystème — Groupe KA",
28 24 description:
29 − "Tableau de bord maître du Groupe KA : indicateurs consolidés en direct des plateformes de l'écosystème ·Ka, classement par volume, résumé par plateforme et rapport écosystème PDF.",
25 + "Tableau de bord maître du Groupe KA : indicateurs consolidés en direct des plateformes de l'écosystème ·Ka, classement par volume, croissance comparée, résumé par plateforme et rapports écosystème PDF.",
30 26 };
31 27
32 −/** Format compact honnête pour les très grands nombres (G / M). */
33 −function fmtVal(k: Kpi): string {
34 − const v = k.value;
35 − if (typeof v !== "number" || !Number.isFinite(v)) return String(v);
36 − let txt: string;
37 − if (Math.abs(v) >= 1_000_000_000) {
38 − txt = `${(v / 1_000_000_000).toLocaleString("fr-CA", { maximumFractionDigits: 2 })} G`;
39 − } else if (Math.abs(v) >= 100_000_000) {
40 − txt = `${(v / 1_000_000).toLocaleString("fr-CA", { maximumFractionDigits: 1 })} M`;
41 − } else if (Number.isInteger(v)) {
42 − txt = fmtInt(v);
43 − } else {
44 − txt = v.toLocaleString("fr-CA", { maximumFractionDigits: 2 });
45 − }
46 − return k.unit ? `${txt} ${k.unit}` : txt;
47 −}
48 −
49 −function Delta({ k }: { k: Kpi }) {
50 − if (typeof k.delta_pct !== "number") return null;
51 − const up = (k.direction ?? (k.delta_pct >= 0 ? "up" : "down")) === "up";
52 − return (
53 − <span
54 − className={`gk-mono text-[10.5px] font-bold ${up ? "text-green" : "text-danger"}`}
55 − >
56 − {k.delta_pct >= 0 ? "▲ +" : "▼ "}
57 − {k.delta_pct.toLocaleString("fr-CA")} %
58 − </span>
59 − );
60 −}
61 −
62 −function Pastille({ accent }: { accent: string }) {
63 − return (
64 − <span
65 − aria-hidden="true"
66 − className="inline-block h-[10px] w-[10px] flex-none rounded-[3px] border border-ink"
67 − style={{ background: accent }}
68 − />
69 − );
70 −}
71 −
72 −function PlatformCard({ p }: { p: PlatformStats }) {
73 − const { site, dash } = p;
74 − if (!dash) {
75 − return (
76 − <article className="gk-card flex flex-col bg-surface-2 p-5">
77 − <div className="flex items-center gap-2">
78 − <Pastille accent={site.accent} />
79 − <span className="gk-display truncate text-[17px] font-bold tracking-[-0.02em] text-ink-3">
80 − {site.wordmark}
81 − </span>
82 − </div>
83 − <p className="klabel mt-4">Données indisponibles</p>
84 − <p className="mt-2 text-[13px] text-ink-3">
85 − La plateforme n&apos;a pas répondu au moment du chargement. Ses
86 − statistiques restent consultables directement sur son site.
87 − </p>
88 − <a
89 − href={`https://${site.domain}/stats`}
90 − target="_blank"
91 − rel="noopener noreferrer"
92 − className="gk-mono mt-auto pt-4 text-[11.5px] font-bold text-ink-3 underline-offset-4 hover:text-ink hover:underline"
93 − >
94 − Stats détaillées →
95 − </a>
96 − </article>
97 − );
98 − }
99 − const kpis = topKpis(dash, 3);
100 − const record = dash.records?.[0] ?? null;
101 − return (
102 − <article className="gk-card flex flex-col p-5">
103 − <div className="flex flex-wrap items-center justify-between gap-x-3 gap-y-1">
104 − <span className="flex min-w-0 items-center gap-2">
105 − <Pastille accent={site.accent} />
106 − <span className="gk-display truncate text-[17px] font-bold tracking-[-0.02em]">
107 − {site.wordmark}
108 − </span>
109 − </span>
110 − <a
111 − href={`https://${site.domain}`}
112 − target="_blank"
113 − rel="noopener noreferrer"
114 − className="gk-mono text-[10.5px] font-bold text-ink-3 underline-offset-4 hover:text-ink hover:underline"
115 − >
116 − {site.domain}
117 − </a>
118 − </div>
119 − <dl className="mt-4 space-y-3">
120 − {kpis.map((k) => (
121 − <div
122 − key={k.id ?? k.label}
123 − className="flex items-baseline justify-between gap-3 border-b border-dashed border-[rgba(20,24,20,0.18)] pb-2"
124 − >
125 − <dt className="min-w-0 text-[12px] leading-snug text-ink-2">
126 − {k.label}
127 − </dt>
128 − <dd className="flex flex-none items-baseline gap-2">
129 − <span className="gk-mono text-[15px] font-bold tracking-[-0.01em] whitespace-nowrap">
130 − {fmtVal(k)}
131 − </span>
132 − <Delta k={k} />
133 − </dd>
134 − </div>
135 − ))}
136 − </dl>
137 − {record ? (
138 − <p className="mt-3 rounded-md bg-lime-soft px-3 py-2 text-[12px] leading-snug">
139 − <span className="gk-mono text-[10px] font-bold tracking-[0.08em] text-green uppercase">
140 − Record ·{" "}
141 − </span>
142 − {record.label} : <strong>{record.value}</strong>
143 − {record.date ? (
144 − <span className="text-ink-3"> ({record.date})</span>
145 − ) : null}
146 − </p>
147 − ) : null}
148 − <a
149 − href={`https://${site.domain}/stats`}
150 − target="_blank"
151 − rel="noopener noreferrer"
152 − className="gk-mono mt-auto pt-4 text-[11.5px] font-bold text-green underline-offset-4 hover:text-ink hover:underline"
153 − >
154 − Stats détaillées → {site.domain}/stats
155 − </a>
156 − </article>
157 − );
158 −}
159 −
160 −/** Format compact d'un nombre de répartition (réutilise la logique KPI). */
161 −const fmtNum = (v: number): string => fmtVal({ label: "", value: v });
162 −
163 −/** Liste à barres d'une répartition SPEC (breakdown ou geo). */
164 −function BreakdownBars({ b, n = 6 }: { b: Breakdown; n?: number }) {
165 − const items = breakdownItems(b, n);
166 − if (items.length === 0) return null;
167 − const max = Math.max(...items.map((it) => it.value));
168 − return (
169 − <div>
170 − <p className="klabel">{b.title ?? b.label ?? b.id ?? "Répartition"}</p>
171 − <div className="mt-3 space-y-3">
172 − {items.map((it) => (
173 − <div key={it.label}>
174 − <div className="flex items-baseline justify-between gap-3">
175 − <span className="min-w-0 truncate text-[12px] text-ink-2">
176 − {it.label}
177 − </span>
178 − <span className="gk-mono flex-none text-[11.5px] font-bold">
179 − {fmtNum(it.value)}
180 − </span>
181 − </div>
182 − <div className="mt-[4px] h-[9px] w-full rounded-r-[3px] bg-[rgba(20,24,20,0.06)]">
183 − <div
184 − className="h-full rounded-r-[3px] bg-green"
185 − style={{ width: `${Math.max((it.value / max) * 100, 1.5)}%` }}
186 − />
187 − </div>
188 − </div>
189 − ))}
190 − </div>
191 − </div>
192 − );
193 −}
194 −
195 −/** Carte « répartitions » d'une plateforme phare : 1er breakdown + geo. */
196 −function BreakdownCard({ p }: { p: PlatformStats }) {
197 − const bd = firstBreakdown(p.dash);
198 − const geo = geoBreakdown(p.dash);
199 − if (!bd && !geo) return null;
200 − return (
201 − <article className="gk-card p-5 sm:p-6">
202 − <div className="flex flex-wrap items-center justify-between gap-x-3 gap-y-1">
203 − <span className="flex min-w-0 items-center gap-2">
204 − <Pastille accent={p.site.accent} />
205 − <span className="gk-display truncate text-[17px] font-bold tracking-[-0.02em]">
206 − {p.site.wordmark}
207 − </span>
208 − </span>
209 − <span className="gk-mono text-[10.5px] font-bold text-ink-3">
210 − {p.site.domain}
211 − </span>
212 − </div>
213 − <div className="mt-5 grid gap-6 sm:grid-cols-2">
214 − {bd ? <BreakdownBars b={bd} /> : null}
215 − {geo ? <BreakdownBars b={geo} n={5} /> : null}
216 − </div>
217 − </article>
218 − );
219 −}
220 −
221 28 export default async function StatsPage({
222 29 searchParams,
223 30 }: {
@@ -229,56 +36,18 @@ export default async function StatsPage({
229 36 getEcosystemStats(period),
230 37 getLiveMetrics(),
231 38 ]);
232 − const c = consolidate(platforms);
233 39 const periodLabel =
234 40 platforms.find((p) => p.dash?.period?.label)?.dash?.period?.label ??
235 41 (PERIODS.find(([k]) => k === period)?.[1] ?? period);
236 − const freshness = c.latestUpdate
237 − ? new Date(c.latestUpdate).toLocaleString("fr-CA", {
238 − timeZone: "America/Toronto",
239 − dateStyle: "long",
240 − timeStyle: "short",
241 − })
242 − : null;
243 − const reportHref = (mode: "complet" | "synthese") =>
244 − `/api/stats/ecosystem-report?period=${period}&mode=${mode}`;
245 −
246 − // Plateformes phares dont le tableau de bord publie des répartitions
247 − // (breakdowns / geo du contrat SPEC) — les 2 plus grosses jointes.
248 − const richPlatforms = c.ranked
249 − .filter((p) => firstBreakdown(p.dash) || geoBreakdown(p.dash))
250 − .slice(0, 2);
251 −
252 − const banner: { label: string; value: string; note?: string }[] = [
253 − {
254 − label: "Volume principal agrégé",
255 − value: fmtInt(c.totalVolume),
256 − note: `somme des indicateurs principaux des ${c.reachable} plateformes jointes`,
257 − },
258 − {
259 − label: "Plateformes en ligne",
260 − value: `${c.reachable + 1}/12`,
261 − note: "11 plateformes de données + le hub groupe-ka.com",
262 − },
263 − {
264 − label: "Connecteurs totaux",
265 − value: `${fmtInt(live.totals.connectors)}+`,
266 − note: "connecteurs sources actifs sur l'écosystème",
267 − },
268 − ...(c.newCount > 0
269 − ? [
270 − {
271 − label: "Nouveautés de la période",
272 − value: fmtInt(c.totalNew),
273 − note: `${c.newCount} plateformes qui les mesurent`,
274 − },
275 − ]
276 − : []),
277 − ];
42 + const payload = buildEcoPayload(platforms, {
43 + period,
44 + periodLabel,
45 + connectors: live.totals.connectors,
46 + });
278 47
279 48 return (
280 49 <main className="mx-auto max-w-6xl px-4 py-12 sm:px-6">
281 − {/* 1 — en-tête : titre, rapports PDF, fraîcheur, période */}
50 + {/* en-tête : titre + intro */}
282 51 <p className="kicker">Tableau de bord maître · tout l’écosystème</p>
283 52 <h1 className="gk-display mt-3 text-[clamp(28px,4.5vw,44px)] leading-[1.02] font-bold tracking-[-0.035em] uppercase">
284 53 Statistiques de <span className="hl">l&apos;écosystème</span>
@@ -286,184 +55,24 @@ export default async function StatsPage({
286 55 <p className="mt-4 max-w-2xl text-[14.5px] text-ink-2">
287 56 Chaque plateforme ·Ka expose son tableau de bord statistique ; cette
288 57 page les consolide en direct — période affichée :{" "}
289 − <strong>{periodLabel}</strong>. Rien d&apos;inventé : chaque chiffre
290 − vient de la plateforme qui le mesure.
58 + <strong>{payload.periodLabel}</strong>. Rien d&apos;inventé : chaque
59 + chiffre vient de la plateforme qui le mesure.
291 60 </p>
292 − <div className="mt-6 flex flex-wrap items-center gap-3">
293 − <a href={reportHref("complet")} className="btn btn-primary">
294 − Rapport écosystème complet (PDF)
295 − </a>
296 − <a href={reportHref("synthese")} className="btn btn-ghost">
297 − Synthèse (PDF)
298 − </a>
299 − </div>
300 − <p className="gk-mono mt-3 text-[11px] text-ink-3">
301 − {freshness
302 − ? `Données mises à jour le ${freshness} (heure de l'Est) · cache 10 min`
303 − : "Fraîcheur inconnue — aucune plateforme jointe pour le moment"}
304 − </p>
305 −
306 − {/* sélecteur de période : simples liens ?period=… */}
307 − <nav aria-label="Période" className="mt-6 flex flex-wrap gap-2">
308 − {PERIODS.map(([key, label]) => (
309 − <a
310 − key={key}
311 − href={`/stats?period=${key}`}
312 − aria-current={key === period ? "page" : undefined}
313 − className={`stat-chip !py-[6px] transition-colors ${
314 − key === period
315 − ? "!bg-ink !text-lime"
316 − : "hover:!bg-lime-soft"
317 − }`}
318 − >
319 − {label}
320 − </a>
321 − ))}
322 − </nav>
323 −
324 − {/* 2 — bandeau KPI consolidés */}
325 − <section className="mt-8 grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
326 − {banner.map((b) => (
327 − <div key={b.label} className="gk-card p-5">
328 − <p className="gk-display text-[26px] leading-none font-bold tracking-[-0.02em]">
329 − {b.value}
330 − </p>
331 − <p className="klabel mt-2">{b.label}</p>
332 − {b.note ? (
333 − <p className="mt-1 text-[11.5px] leading-snug text-ink-3">
334 − {b.note}
335 − </p>
336 − ) : null}
337 − </div>
338 − ))}
339 − </section>
340 −
341 − {/* 3 — classement des plateformes */}
342 − <section className="mt-14">
343 − <p className="kicker">Classement · volume principal</p>
344 − <h2 className="gk-display mt-3 text-[clamp(22px,3vw,30px)] font-bold tracking-[-0.03em]">
345 − Les plateformes, par volume
346 − </h2>
347 − <div className="gk-card mt-5 overflow-x-auto">
348 − <table className="w-full min-w-[640px] border-collapse text-[13px]">
349 − <thead>
350 − <tr className="bg-ink text-left text-paper">
351 − {[
352 − "#",
353 − "Plateforme",
354 − "Indicateur principal",
355 − "Volume",
356 − "Nouveautés (période)",
357 − "",
358 − ].map((h, i) => (
359 − <th
360 − key={i}
361 − className="gk-mono px-4 py-3 text-[10.5px] font-bold tracking-[0.08em] whitespace-nowrap uppercase"
362 − >
363 − {h}
364 − </th>
365 − ))}
366 − </tr>
367 − </thead>
368 − <tbody>
369 − {c.ranked.map((p, i) => {
370 − const mk = mainKpi(p.dash);
371 − const nk = newKpi(p.dash);
372 − return (
373 − <tr
374 − key={p.site.id}
375 − className={`border-t border-[rgba(20,24,20,0.12)] ${
376 − i % 2 ? "bg-surface-2" : ""
377 − } ${p.dash ? "" : "text-ink-3"}`}
378 − >
379 − <td className="gk-mono px-4 py-3 text-[11.5px] font-bold">
380 − {i + 1}
381 − </td>
382 − <td className="px-4 py-3">
383 − <span className="flex items-center gap-2">
384 − <Pastille accent={p.site.accent} />
385 − <span className="gk-display font-bold whitespace-nowrap">
386 − {p.site.wordmark}
387 − </span>
388 − </span>
389 − </td>
390 − <td className="px-4 py-3 text-ink-2">
391 − {p.dash
392 − ? (mk?.label ?? "—")
393 − : "données indisponibles"}
394 − </td>
395 − <td className="gk-mono px-4 py-3 font-bold whitespace-nowrap">
396 − {mk ? fmtVal(mk) : "—"}
397 − </td>
398 − <td className="gk-mono px-4 py-3 whitespace-nowrap">
399 − {nk && typeof nk.value === "number"
400 − ? fmtInt(nk.value)
401 − : "—"}
402 − </td>
403 − <td className="px-4 py-3">
404 − <a
405 − href={`https://${p.site.domain}/stats`}
406 − target="_blank"
407 − rel="noopener noreferrer"
408 − className="gk-mono text-[11px] font-bold text-green underline-offset-4 hover:underline"
409 − >
410 − Stats →
411 − </a>
412 − </td>
413 − </tr>
414 − );
415 − })}
416 − </tbody>
417 − </table>
418 − </div>
419 − <p className="mt-3 max-w-3xl text-[12px] leading-relaxed text-ink-3">
420 − Le « volume principal » est le premier indicateur du tableau de bord
421 − de chaque plateforme (annonces actives, véhicules, produits, pages
422 − indexées…). Les volumes ne sont pas de même nature : le classement
423 − donne un ordre de grandeur, pas une comparaison homogène.
424 − </p>
425 − </section>
426 −
427 − {/* 3b — répartitions des plateformes phares (breakdowns/geo du SPEC) */}
428 − {richPlatforms.length > 0 ? (
429 − <section className="mt-14">
430 − <p className="kicker">Sous le capot · répartitions</p>
431 − <h2 className="gk-display mt-3 text-[clamp(22px,3vw,30px)] font-bold tracking-[-0.03em]">
432 − Les plus grosses, décomposées
433 − </h2>
434 − <p className="mt-3 max-w-2xl text-[13px] text-ink-2">
435 − Les tableaux de bord des plateformes publient aussi leurs
436 − répartitions — par type, par ville, par région. Voici celles des
437 − plus gros inventaires joints, lues telles quelles.
438 − </p>
439 − <div className="mt-5 grid gap-5 lg:grid-cols-2">
440 − {richPlatforms.map((p) => (
441 − <BreakdownCard key={p.site.id} p={p} />
442 − ))}
443 − </div>
444 − </section>
445 − ) : null}
446 61
447 − {/* 4 — un bloc résumé par plateforme */}
448 − <section className="mt-14">
449 − <p className="kicker">Plateforme par plateforme</p>
450 − <h2 className="gk-display mt-3 text-[clamp(22px,3vw,30px)] font-bold tracking-[-0.03em]">
451 − Le résumé de chacune
452 − </h2>
453 − <div className="mt-5 grid gap-5 sm:grid-cols-2 lg:grid-cols-3">
454 − {c.ranked.map((p) => (
455 − <PlatformCard key={p.site.id} p={p} />
456 − ))}
457 − </div>
458 − </section>
62 + {/* tout le tableau de bord (client : graphiques SVG + menu PDF) */}
63 + <EcoStatsClient data={payload} />
459 64
460 − {/* 5 — note de méthode */}
65 + {/* note de méthode */}
461 66 <p className="gk-mono mt-12 text-[11px] leading-relaxed text-ink-3">
462 67 Méthode : les chiffres sont lus en direct sur le tableau de bord
463 68 statistique de chaque plateforme (endpoint commun
464 69 /api/stats/dashboard, délai 8 s), avec un cache serveur de 10 minutes
465 − par période. Le rapport écosystème PDF est généré par API-KA à partir
466 − des mêmes données. Une plateforme qui ne répond pas est affichée «
70 + par période. Les agrégats temporels (volume agrégé, croissance
71 + comparée, volume empilé, calendriers) sont des sommes et des indices
72 + calculés sur les seules dates communes aux séries publiées — jamais
73 + d&apos;extrapolation. Les rapports écosystème PDF (complet, synthèse,
74 + tendances, répartitions, données) sont générés par API-KA à partir des
75 + mêmes données. Une plateforme qui ne répond pas est affichée «
467 76 indisponible » — jamais remplacée par un chiffre inventé. Aucune
468 77 statistique de visites : nous ne mesurons pas votre navigation.
469 78 </p>
modified src/ka/stats/SPEC.md +128 −66
@@ -1,53 +1,88 @@
1 −# ka-stats — module Stats commun Groupe KA (spec v1)
1 +# ka-stats — module Stats commun Groupe KA (spec v2)
2 2
3 −Contrat partagé par les 12 plateformes pour leurs pages **/stats** (tableau de
4 −bord analytique) et l'**export PDF** estampillé Groupe-KA. Le visuel suit le
5 −design system ka-ui (tokens.css) avec l'accent de la marque.
3 +Contrat partagé par les plateformes pour leurs pages **/stats** (tableau de
4 +bord analytique) et les **exports PDF** estampillés Groupe-KA. Le visuel suit
5 +le design system ka-ui (tokens.css) avec l'accent de la marque.
6 +
7 +**v2 (2026-08-19)** : sparklines dans les KPI, jauges, multi-courbes,
8 +barres empilées, distributions (histogrammes), heatmap horaire 7×24, deltas
9 +sur les répartitions, statistiques de séries (min/max/moy/méd/σ), et **5
10 +rapports PDF** au lieu de 2. Tous les nouveaux champs sont **optionnels** :
11 +un dashboard v1 reste valide et se rend tel quel.
6 12
7 13 ## 1. Page /stats — structure obligatoire (dans cet ordre)
8 14
9 −1. **Bandeau KPI** : 4–6 grandes cartes (`KpiCard`) — valeur, libellé,
10 − variation vs période précédente (▲/▼ + %, vert `--green` / rouge `--danger`).
15 +1. **Bandeau KPI** : 6–10 grandes cartes (`KpiCard`) — valeur, libellé,
16 + variation vs période précédente (▲/▼ + %, vert `--green` / rouge
17 + `--danger`), **sparkline** de tendance quand une série existe.
11 18 2. **Sélecteur de période global** (`PeriodSelector`) : `aujourd'hui · 7 j ·
12 19 30 j · 3 m · 6 m · 12 m · année en cours · tout` + plage personnalisée
13 20 (2 champs date). Toute la page se recalcule (state → refetch dashboard).
14 −3. **Graphiques** : courbes d'évolution (`LineChart`, survol = infobulle,
15 − légende cliquable pour masquer une série, comparaison N vs N-1 en
16 − pointillé), barres (`BarChart`), anneaux (`Donut`), calendrier de chaleur
17 − (`CalendarHeatmap`) quand pertinent.
18 −4. **Répartition géographique** (par ville/région) quand pertinent — barres
19 − horizontales triées (pas besoin de vraie carte).
20 −5. **Tableaux détaillés** (`DataTable`) : tri par colonne, recherche interne,
21 +3. **Jauges** (`GaugeCard`) quand pertinent : taux, couvertures, complétude.
22 +4. **Graphiques d'évolution** : courbes/aires (`LineChart`, survol =
23 + infobulle, légende cliquable, comparaison N vs N-1 en pointillé), barres
24 + verticales (`VBarChart` — volumes quotidiens), **multi-courbes ≤ 4 séries**
25 + (`MultiLineChart` — motifs de trait distincts, jamais la couleur seule),
26 + **barres empilées** (`StackedBarChart` — composition dans le temps).
27 + Sous les courbes clés : `StatSummary` (min/max/moyenne/médiane/écart-type).
28 +5. **Répartitions** : barres horizontales (`BarChart`, deltas optionnels),
29 + anneaux (`Donut`), **distributions/histogrammes** (`Histogram`).
30 +6. **Répartition géographique** (par ville/région) — barres horizontales
31 + triées (pas besoin de vraie carte).
32 +7. **Calendriers** : `CalendarHeatmap` (26 semaines) et, quand l'activité
33 + horaire est journalisée, `HourHeatmap` (7 jours × 24 h).
34 +8. **Tableaux détaillés** (`DataTable`) : tri par colonne, recherche interne,
21 35 pagination (25/pg), débordement horizontal propre sur mobile (.tbl-wrap).
22 −6. **Records & faits marquants** : générés depuis les données (jour record,
23 − plus forte croissance, meilleure entrée…) — cartes compactes.
24 −7. **Fraîcheur** : « Mis à jour le {date heure} » + bouton Rafraîchir.
25 −8. **Bouton PDF** bien visible en haut : « Télécharger le rapport PDF » avec
26 − deux choix (Rapport complet / Synthèse 2 pages). Indicateur de progression
27 − si > 2 s.
36 + Viser 3 à 5 tableaux par plateforme.
37 +9. **Records & faits marquants** : générés depuis les données (jour record,
38 + plus forte croissance, meilleure entrée…) — cartes compactes, 6–12.
39 +10. **Fraîcheur** : « Mis à jour le {date heure} » + bouton Rafraîchir.
40 +11. **Bouton PDF** bien visible en haut (`PdfButton`) : bouton principal
41 + « Rapport PDF complet » + menu « Autres rapports ▾ » listant les
42 + **5 rapports** (voir §3). Indicateur de progression si > 2 s.
28 43
29 44 Responsive : KPI empilés < 768 px, graphiques pleine largeur redimensionnés
30 45 (SVG viewBox), tableaux en défilement horizontal contenu, tactile ≥ 44 px.
31 46 AUCUNE donnée inventée : une stat indisponible = bloc « Pas encore mesuré »
32 47 (carte grise propre), jamais un faux chiffre.
33 48
49 +Accessibilité (règles fermes) : un seul axe Y par graphique (jamais de
50 +double échelle) ; ≥ 2 séries ⇒ légende obligatoire ; l'identité d'une série
51 +multi-courbes passe par le **motif de trait** en plus de la couleur ; le
52 +texte reste en encre (jamais coloré à la couleur de série) ; chaque
53 +graphique a son infobulle de survol et un équivalent tableau existe.
54 +
34 55 ## 2. API — contrat commun
35 56
36 57 `GET /api/stats/dashboard?period=7j|30j|3m|6m|12m|annee|tout|auj&from=YYYY-MM-DD&to=YYYY-MM-DD`
37 58
38 59 ```jsonc
39 60 {
40 − "updated": "2026-08-17T21:04:00-04:00",
41 − "period": { "from": "2026-07-18", "to": "2026-08-17", "label": "30 jours" },
61 + "updated": "2026-08-19T01:00:00-04:00",
62 + "period": { "from": "2026-07-20", "to": "2026-08-19", "label": "30 jours" },
42 63 "kpis": [ { "id": "total", "label": "Annonces actives", "value": 33744,
43 − "unit": "", "delta_pct": 4.2, "direction": "up" } ],
64 + "unit": "", "delta_pct": 4.2, "direction": "up",
65 + "spark": [{ "t": "2026-08-01", "v": 31200 }] } ], // spark optionnel
66 + "gauges": [ { "id": "geo", "label": "Fiches géolocalisées", "value": 92,
67 + "max": 100, "unit": "%" } ], // optionnel
44 68 "series": [ { "id": "vol", "title": "Annonces actives par jour", "unit": "annonces",
45 − "kind": "line", "points": [{ "t": "2026-07-18", "v": 31200 }],
46 − "compare": [{ "t": "2025-07-18", "v": 24100 }] } ],
47 − "breakdowns": [ { "id": "types", "title": "Par type", "kind": "donut",
48 − "items": [{ "label": "4½", "value": 9120 }] } ],
69 + "kind": "line", // line | bar | area
70 + "points": [{ "t": "2026-07-20", "v": 31200 }],
71 + "compare": [{ "t": "2025-07-20", "v": 24100 }] } ],
72 + "multiseries": [ { "id": "seg", "title": "Prix médian par taille", "unit": "$",
73 + "series": [ { "label": "3½", "points": [/* … */] },
74 + { "label": "4½", "points": [/* … */] } ] } ], // ≤ 4
75 + "stacked": [ { "id": "src", "title": "Ajouts par source", "unit": "ajouts",
76 + "keys": ["Kijiji", "Centris", "Autres"],
77 + "points": [{ "t": "2026-08-01", "values": [120, 80, 30] }] } ],
78 + "breakdowns": [ { "id": "types", "title": "Par type", "kind": "donut", // donut | bars
79 + "items": [{ "label": "4½", "value": 9120, "delta_pct": 2.1 }] } ],
80 + "distributions": [ { "id": "prix", "title": "Distribution des loyers", "unit": "annonces",
81 + "bins": [{ "label": "800-1000$", "value": 3120 }] } ],
49 82 "geo": { "title": "Par région", "items": [{ "label": "Montréal", "value": 15680 }] },
50 83 "heatmap": { "title": "Activité", "cells": [{ "date": "2026-08-01", "value": 210 }] },
84 + "hourly": { "title": "Activité par heure",
85 + "cells": [{ "dow": 0, "hour": 9, "value": 40 }] }, // dow 0=lun … 6=dim
51 86 "tables": [ { "id": "top", "title": "Top villes", "columns": ["Ville", "Annonces", "Δ 30 j"],
52 87 "rows": [["Montréal", 15680, "+3,1 %"]] } ],
53 88 "records": [ { "label": "Jour record d'ajouts", "value": "412 annonces", "date": "2026-08-09" } ]
@@ -56,23 +91,40 @@ AUCUNE donnée inventée : une stat indisponible = bloc « Pas encore mesuré »
56 91
57 92 Champs absents = section masquée. Cache serveur recommandé (≥ 5 min par
58 93 période). Les valeurs proviennent des données réelles (DB de la plateforme,
59 −journaux de sync des connecteurs, /api/v1/runs d'API-KA…).
94 +journaux de sync des connecteurs, /api/v1/runs d'API-KA…). Arrondir les
95 +`delta_pct` à 1 décimale côté serveur.
60 96
61 −`GET /api/stats/report?period=…&from=&to=&mode=complet|synthese`
97 +## 3. Rapports PDF — 5 modes
98 +
99 +`GET /api/stats/report?period=…&from=&to=&mode=complet|synthese|tendances|repartitions|donnees`
62 100 → `application/pdf`, en-tête `Content-Disposition: attachment; filename=
63 −groupe-ka_<plateforme>_stats_<periode>_<YYYY-MM-DD>.pdf`.
101 +groupe-ka_<plateforme>_stats_<periode>[_<mode>]_<YYYY-MM-DD>.pdf`
102 +(pas de suffixe pour `complet` — rétrocompatible v1 ; `kapdf.filename()`
103 +accepte maintenant `mode` en 3e argument).
104 +
105 +| Mode | Contenu |
106 +|---|---|
107 +| `complet` | tout : sommaire, KPI, jauges, séries + stats de séries, multi-séries, empilées, répartitions, distributions, géo, heatmap horaire, tableaux (200 lignes), records |
108 +| `synthese` | couverture + KPI + jauges + records (2–3 pages) |
109 +| `tendances` | KPI + toutes les séries temporelles + min/max/moy/méd/σ + records |
110 +| `repartitions` | breakdowns, distributions, géo, activité horaire |
111 +| `donnees` | tous les tableaux en version longue (400 lignes) |
64 112
65 −## 3. PDF — gabarit Groupe-KA (implémentations : `kapdf.py` fpdf2 pour les
66 −apps Python ; les apps Next portent le même gabarit en pdfkit)
113 +Un `mode` inconnu retombe sur `complet`. Le gabarit (implémentations :
114 +`kapdf.py` fpdf2 pour les apps Python ; les apps Next portent le même
115 +gabarit en pdfkit) :
67 116
68 117 - **Couverture** : cadre encre, kicker « GROUPE KA · RAPPORT STATISTIQUE »,
69 − wordmark de la plateforme (boîte encre + accent), sous-titre, période
70 − couverte, date/heure de génération, bande encre au pied avec
118 + wordmark de la plateforme (boîte encre + accent), **type de rapport**,
119 + période couverte, date/heure de génération, bande encre au pied avec
71 120 « par Groupe KA — groupe-ka.com ».
72 −- **Sommaire** avec numéros de pages (mode complet).
73 −- **KPI** : grille de cartes (bordure encre, valeur en gros, delta coloré).
121 +- **Sommaire** avec numéros de pages (modes complet et donnees).
122 +- **KPI** : grille de cartes (bordure encre, valeur en gros, delta coloré
123 + arrondi à 1 décimale). **Jauges** : demi-arcs accent.
74 124 - **Graphiques VECTORIELS** (dessinés en primitives, jamais de capture) :
75 − courbes, barres, anneaux — accent de la plateforme, axes/graduations encre.
125 + courbes/aires, barres verticales, multi-courbes (motifs distincts),
126 + empilées (nuances d'accent), anneaux, heatmap horaire — accent de la
127 + plateforme, axes/graduations encre.
76 128 - **Tableaux** paginés proprement (lignes zébrées `--surface-2`, jamais
77 129 coupés en deux à cheval sur une ligne).
78 130 - **Records** puis **page de fin** : coordonnées Groupe KA (3 courriels +
@@ -81,43 +133,53 @@ apps Python ; les apps Next portent le même gabarit en pdfkit)
81 133 - **Chaque page** : en-tête discret (« Groupe KA · {Plateforme} », filet
82 134 encre) + pied (« © Groupe-KA — {année} — groupe-ka.com · {période} · p. X/Y »).
83 135 - A4 portrait, marges 18 mm, typo : Helvetica (fallback sûr) ou fonts TTF du
84 − DS si présentes. Mode « synthese » = couverture + 1 page KPI/records.
136 + DS si présentes.
85 137
86 138 ## 4. Spécifique par plateforme (sections métier attendues)
87 139
88 −- **groupe-ka** : tableau de bord maître — consolidation des 12 (volume total,
89 − croissance), classement des plateformes, bloc résumé par plateforme + lien
140 +- **groupe-ka** : tableau de bord maître — consolidation des plateformes
141 + (volume total, croissance), classement, bloc résumé par plateforme + lien
90 142 vers sa page /stats ; « Rapport écosystème complet » = PDF consolidé.
91 143 - **lou-ka** : annonces actives/nouvelles/retirées, loyers moyens/médians par
92 − ville & taille, évolution, répartition par type, top villes.
93 −- **immo-ka** : annonces actives/nouvelles/vendues-retirées, prix moyen/médian
94 − par ville/région/type, délai de présence, top villes, tension du marché.
144 + ville & taille (multiseries), distribution des loyers, évolution,
145 + répartition par type, top villes, sources (stacked).
146 +- **immo-ka** : annonces actives/nouvelles/vendues-retirées, prix
147 + moyen/médian par ville/région/type (multiseries), distribution des prix,
148 + délai de présence, top villes, tension du marché.
95 149 - **vrai-prix** : couverture du rôle (unités, valeur totale), estimations
96 − servies si journalisées, répartitions par municipalité/type, indices marché.
97 −- **auto-ka** : volume par marque/modèle/année/carburant/boîte, prix moyens et
98 − km moyens par segment, top marques/modèles.
99 −- **fabri-ka** : produits par catégorie/région/boutique, fourchettes de prix,
100 − nouveautés par période, top catégories.
101 −- **food-ka** : produits suivis, relevés de prix, soldes détectés (baisses/
102 − hausses, amplitude), top produits en solde, prix moyens par catégorie.
103 −- **resto-ka** : restos par cuisine/ville/gamme, menus & plats, nouveautés/
104 − fermetures détectées, top établissements.
150 + servies si journalisées, répartitions par municipalité/type, distribution
151 + des valeurs, indices marché.
152 +- **auto-ka** : volume par marque/modèle/année/carburant/boîte, prix moyens
153 + et km moyens par segment (multiseries), distributions prix/km/année,
154 + top marques/modèles.
155 +- **fabri-ka** : produits par catégorie/région/boutique, fourchettes de prix
156 + (distribution), nouveautés par période, top catégories.
157 +- **food-ka** : produits suivis, relevés de prix, soldes détectés
158 + (baisses/hausses, amplitude — stacked), top produits en solde, prix moyens
159 + par catégorie, distribution des rabais.
160 +- **resto-ka** : restos par cuisine/ville/gamme, menus & plats, distribution
161 + des prix de plats, nouveautés/fermetures détectées, top établissements.
105 162 - **sorti-ka** : événements à venir/passés par catégorie/ville, gratuits vs
106 − payants, heatmap calendrier, top lieux.
107 −- **crea-ka** : créateurs par plateforme/niche/tier, comptes reliés, top
108 − créateurs, croissance du répertoire.
109 −- **trouve-ka** : pages indexées, domaines, rythme de crawl (indexées/h),
110 − erreurs, file frontier, tendances si les requêtes sont journalisées.
111 −- **api-ka** : appels par endpoint/jour/heure, latences moyennes + p95, taux
112 − d'erreur, top endpoints, uptime (données des middlewares de logging + runs).
113 −- **Transverse (tous)** : volume total agrégé + croissance, connecteurs actifs
114 − et éléments ajoutés/mis à jour par période (journaux de sync), complétude/
115 − fraîcheur moyenne des fiches quand mesurable. Trafic web : seulement si des
116 − journaux d'accès existent — sinon état vide propre.
163 + payants (stacked), heatmap calendrier + horaire, top lieux.
164 +- **crea-ka** : créateurs par plateforme/niche/tier, comptes reliés
165 + (stacked par plateforme), distribution des audiences, top créateurs,
166 + croissance du répertoire.
167 +- **trouve-ka** : pages indexées, domaines, rythme de crawl (indexées/h —
168 + hourly), erreurs, file frontier, tendances des requêtes journalisées.
169 +- **api-ka** : appels par endpoint/jour/heure (hourly), latences moyennes +
170 + p95 (multiseries), taux d'erreur, top endpoints/clés, uptime.
171 +- **job-ka** : offres actives/nouvelles/expirées par catégorie/ville/
172 + entreprise, distribution des salaires affichés, top employeurs.
173 +- **Transverse (tous)** : volume total agrégé + croissance, connecteurs
174 + actifs et éléments ajoutés/mis à jour par période (journaux de sync —
175 + stacked par source quand possible), complétude/fraîcheur moyenne des
176 + fiches quand mesurable (jauges). Trafic web : seulement si des journaux
177 + d'accès existent — sinon état vide propre.
117 178
118 179 ## 5. Ajouter une métrique / un graphique / une plateforme
119 180
120 −1 métrique = 1 entrée `kpis[]` ou `series[]` côté API (requête SQL agrégée +
121 −cache) — le front la rend automatiquement. 1 plateforme = implémenter les 2
122 −endpoints du contrat + une page /stats montée sur les composants du kit +
123 −`kapdf.py` (ou gabarit pdfkit) branché sur le même JSON de dashboard.
181 +1 métrique = 1 entrée `kpis[]`, `series[]`, `multiseries[]`, `stacked[]`,
182 +`distributions[]` ou `gauges[]` côté API (requête SQL agrégée + cache) — le
183 +front la rend automatiquement. 1 plateforme = implémenter les 2 endpoints du
184 +contrat + une page /stats montée sur les composants du kit + `kapdf.py` (ou
185 +gabarit pdfkit) branché sur le même JSON de dashboard.
modified src/ka/stats/kacharts.tsx +393 −30
@@ -2,22 +2,39 @@
2 2 // ka-ui/stats/kacharts.tsx — kit de graphiques SVG du module Stats commun
3 3 // Groupe KA (zéro dépendance, React 18+). Style : design system ka-ui
4 4 // (bordures encre, accent de la plateforme via var(--accent)).
5 −// Composants : KpiCard, PeriodSelector, LineChart (infobulle + légende
6 −// cliquable + comparaison N-1), BarChart, Donut, CalendarHeatmap, DataTable
7 −// (tri/recherche/pagination), RecordCard, PdfButton, EmptyBlock, Fraicheur.
8 −import { useMemo, useState } from "react";
5 +// v2 — composants : KpiCard (+sparkline), PeriodSelector, LineChart (ligne/
6 +// aire, infobulle + légende cliquable + comparaison N-1), MultiLineChart
7 +// (≤4 séries, pointillés distincts = jamais la couleur seule), VBarChart
8 +// (barres verticales / histogrammes), StackedBarChart, BarChart (horizontal,
9 +// deltas), Donut, GaugeCard, CalendarHeatmap, HourHeatmap (7×24),
10 +// StatSummary (min/max/moy/méd/σ), DataTable (tri/recherche/pagination),
11 +// RecordCard, PdfButton (menu de rapports), EmptyBlock, Fraicheur.
12 +import { useEffect, useMemo, useRef, useState } from "react";
9 13
10 −/* ---------- types (contrat SPEC.md) ---------- */
14 +/* ---------- types (contrat SPEC.md v2) ---------- */
11 15 export type Kpi = {
12 16 id: string; label: string; value: number | string; unit?: string;
13 17 delta_pct?: number | null; direction?: "up" | "down";
18 + spark?: Point[]; help?: string;
14 19 };
15 20 export type Point = { t: string; v: number };
16 21 export type Serie = {
17 − id: string; title: string; unit?: string; kind?: "line" | "bar";
22 + id: string; title: string; unit?: string;
23 + kind?: "line" | "bar" | "area";
18 24 points: Point[]; compare?: Point[];
19 25 };
20 −export type BreakItem = { label: string; value: number };
26 +export type MultiSerie = {
27 + id: string; title: string; unit?: string;
28 + series: { label: string; points: Point[] }[]; // ≤ 4 séries
29 +};
30 +export type StackedSerie = {
31 + id: string; title: string; unit?: string;
32 + keys: string[]; points: { t: string; values: number[] }[];
33 +};
34 +export type BreakItem = { label: string; value: number; delta_pct?: number | null };
35 +export type Distribution = { id: string; title: string; unit?: string; bins: { label: string; value: number }[] };
36 +export type Gauge = { id: string; label: string; value: number; max: number; unit?: string; help?: string };
37 +export type HourCell = { dow: number; hour: number; value: number }; // dow 0=lun … 6=dim
21 38 export type TableSpec = { id: string; title: string; columns: string[]; rows: (string | number)[][] };
22 39 export type RecordFact = { label: string; value: string; date?: string };
23 40
@@ -32,25 +49,63 @@ export const PERIODS: { id: string; label: string }[] = [
32 49 { id: "tout", label: "Tout" },
33 50 ];
34 51
52 +export const REPORT_MODES: { id: string; label: string; desc: string }[] = [
53 + { id: "complet", label: "Rapport complet", desc: "Toutes les sections — KPI, tendances, répartitions, tableaux, records" },
54 + { id: "synthese", label: "Synthèse exécutive", desc: "2 pages — indicateurs clés et faits marquants" },
55 + { id: "tendances", label: "Tendances & évolution", desc: "Courbes, comparaisons N-1 et statistiques de séries" },
56 + { id: "repartitions", label: "Répartitions & géographie", desc: "Catégories, distributions, régions et activité" },
57 + { id: "donnees", label: "Données détaillées", desc: "Tous les tableaux, en version longue" },
58 +];
59 +
35 60 export const fmtInt = (n: number) => n.toLocaleString("fr-CA");
36 61 export const fmtNum = (n: number) =>
37 62 Number.isInteger(n) ? fmtInt(n) : n.toLocaleString("fr-CA", { maximumFractionDigits: 2 });
63 +const fmtPct = (n: number) => `${n >= 0 ? "+" : ""}${fmtNum(n)} %`;
38 64
39 −/* ---------- KPI ---------- */
65 +/* Styles des séries multiples : couleur + motif de trait (l'identité n'est
66 + jamais portée par la couleur seule — règle d'accessibilité). */
67 +const MULTI_STYLES = [
68 + { stroke: "var(--accent)", dash: undefined, width: 2.4 },
69 + { stroke: "var(--ink)", dash: undefined, width: 1.6 },
70 + { stroke: "var(--accent-deep, var(--accent))", dash: "6 3", width: 2 },
71 + { stroke: "var(--ink-3)", dash: "2 3", width: 2 },
72 +];
73 +
74 +/* ---------- KPI (+ sparkline) ---------- */
40 75 export function KpiCard({ k }: { k: Kpi }) {
41 76 const up = (k.direction ?? ((k.delta_pct ?? 0) >= 0 ? "up" : "down")) === "up";
77 + const sp = (k.spark ?? []).filter((p) => typeof p.v === "number");
78 + const spark = useMemo(() => {
79 + if (sp.length < 2) return null;
80 + const w = 120, h = 30;
81 + const vmax = Math.max(...sp.map((p) => p.v));
82 + const vmin = Math.min(...sp.map((p) => p.v));
83 + const rng = vmax - vmin || 1;
84 + const X = (i: number) => (w * i) / (sp.length - 1);
85 + const Y = (v: number) => 2 + (h - 4) * (1 - (v - vmin) / rng);
86 + const d = sp.map((p, i) => `${i ? "L" : "M"}${X(i).toFixed(1)},${Y(p.v).toFixed(1)}`).join("");
87 + return { w, h, d, area: `${d}L${w},${h}L0,${h}Z` };
88 + }, [k.spark]);
42 89 return (
43 − <article className="card" style={{ padding: "14px 16px", minWidth: 0 }}>
90 + <article className="card" style={{ padding: "14px 16px", minWidth: 0 }} title={k.help}>
44 91 <p style={{ margin: 0, fontFamily: "var(--font-display)", fontWeight: 700, fontSize: "clamp(22px,2.4vw,30px)", letterSpacing: "-0.02em" }}>
45 92 {typeof k.value === "number" ? fmtNum(k.value) : k.value}
46 93 {k.unit ? <span style={{ fontSize: "0.6em", color: "var(--ink-2)" }}> {k.unit}</span> : null}
47 94 </p>
48 95 <p className="klabel" style={{ margin: "6px 0 0" }}>{k.label}</p>
49 − {k.delta_pct !== undefined && k.delta_pct !== null && (
50 − <p style={{ margin: "8px 0 0", fontFamily: "var(--font-mono)", fontSize: 11, fontWeight: 700, color: up ? "var(--green)" : "var(--danger)" }}>
51 − {up ? "▲" : "▼"} {k.delta_pct >= 0 ? "+" : ""}{fmtNum(k.delta_pct)} % <span style={{ color: "var(--ink-3)", fontWeight: 500 }}>vs période préc.</span>
52 − </p>
53 − )}
96 + <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-end", gap: 8 }}>
97 + {k.delta_pct !== undefined && k.delta_pct !== null ? (
98 + <p style={{ margin: "8px 0 0", fontFamily: "var(--font-mono)", fontSize: 11, fontWeight: 700, color: up ? "var(--green)" : "var(--danger)" }}>
99 + {up ? "▲" : "▼"} {fmtPct(k.delta_pct)} <span style={{ color: "var(--ink-3)", fontWeight: 500 }}>vs période préc.</span>
100 + </p>
101 + ) : <span />}
102 + {spark && (
103 + <svg viewBox={`0 0 ${spark.w} ${spark.h}`} style={{ width: 96, height: 24, flex: "none" }} aria-hidden="true">
104 + <path d={spark.area} fill="var(--accent)" opacity={0.14} />
105 + <path d={spark.d} fill="none" stroke="var(--accent)" strokeWidth={1.8} />
106 + </svg>
107 + )}
108 + </div>
54 109 </article>
55 110 );
56 111 }
@@ -84,12 +139,13 @@ export function PeriodSelector({
84 139 );
85 140 }
86 141
87 −/* ---------- Courbe ---------- */
142 +/* ---------- Courbe / aire ---------- */
88 143 export function LineChart({ serie, height = 240 }: { serie: Serie; height?: number }) {
89 144 const [hide, setHide] = useState<{ cur: boolean; cmp: boolean }>({ cur: false, cmp: false });
90 145 const [hover, setHover] = useState<number | null>(null);
91 146 const W = 720, H = height, PL = 54, PR = 10, PT = 14, PB = 26;
92 147 const pts = serie.points ?? [];
148 + if (serie.kind === "bar") return <VBarChart serie={serie} height={height} />;
93 149 if (pts.length < 2) return <EmptyBlock title={serie.title} />;
94 150 const all = [...(hide.cur ? [] : pts), ...(!hide.cmp && serie.compare ? serie.compare : [])];
95 151 const vmax = Math.max(...all.map((p) => p.v), 1);
@@ -127,6 +183,9 @@ export function LineChart({ serie, height = 240 }: { serie: Serie; height?: numb
127 183 {[0, Math.floor(pts.length / 2), pts.length - 1].map((i) => (
128 184 <text key={i} x={X(i, pts.length)} y={H - 8} textAnchor="middle" fontSize={10} fill="var(--ink-3)" fontFamily="var(--font-mono)">{pts[i].t}</text>
129 185 ))}
186 + {serie.kind === "area" && !hide.cur && (
187 + <path d={`${path(pts)}L${X(pts.length - 1, pts.length)},${Y(0)}L${X(0, pts.length)},${Y(0)}Z`} fill="var(--accent)" opacity={0.13} />
188 + )}
130 189 {!hide.cmp && serie.compare && serie.compare.length > 1 && (
131 190 <path d={path(serie.compare)} fill="none" stroke="var(--ink-3)" strokeWidth={1.4} strokeDasharray="4 4" />
132 191 )}
@@ -148,17 +207,211 @@ export function LineChart({ serie, height = 240 }: { serie: Serie; height?: numb
148 207 );
149 208 }
150 209
151 −function LegendChip({ label, color, off, dashed, onClick }: { label: string; color: string; off: boolean; dashed?: boolean; onClick: () => void }) {
210 +function LegendChip({ label, color, off, dashed, onClick }: { label: string; color: string; off?: boolean; dashed?: boolean; onClick?: () => void }) {
152 211 return (
153 − <button type="button" onClick={onClick} aria-pressed={!off}
154 − style={{ display: "inline-flex", alignItems: "center", gap: 6, border: 0, background: "none", cursor: "pointer", opacity: off ? 0.4 : 1, fontFamily: "var(--font-mono)", fontSize: 10.5, fontWeight: 700, textTransform: "uppercase", letterSpacing: "0.06em", minHeight: 44 }}>
212 + <button type="button" onClick={onClick} aria-pressed={!off} disabled={!onClick}
213 + style={{ display: "inline-flex", alignItems: "center", gap: 6, border: 0, background: "none", cursor: onClick ? "pointer" : "default", opacity: off ? 0.4 : 1, fontFamily: "var(--font-mono)", fontSize: 10.5, fontWeight: 700, textTransform: "uppercase", letterSpacing: "0.06em", minHeight: 44 }}>
155 214 <span style={{ width: 18, height: 0, borderTop: `3px ${dashed ? "dashed" : "solid"} ${color}` }} />
156 215 {label}
157 216 </button>
158 217 );
159 218 }
160 219
161 −/* ---------- Barres horizontales (répartitions, géo) ---------- */
220 +/* ---------- Multi-courbes (≤ 4 séries, motifs distincts) ---------- */
221 +export function MultiLineChart({ ms, height = 260 }: { ms: MultiSerie; height?: number }) {
222 + const series = (ms.series ?? []).filter((s) => (s.points ?? []).length > 1).slice(0, 4);
223 + const [off, setOff] = useState<Record<string, boolean>>({});
224 + const [hover, setHover] = useState<number | null>(null);
225 + if (!series.length) return <EmptyBlock title={ms.title} />;
226 + const W = 720, H = height, PL = 54, PR = 10, PT = 14, PB = 26;
227 + const n = Math.max(...series.map((s) => s.points.length));
228 + const shown = series.filter((s) => !off[s.label]);
229 + const all = shown.flatMap((s) => s.points.map((p) => p.v));
230 + const vmax = Math.max(...(all.length ? all : [1]), 1);
231 + const vmin = Math.min(0, ...(all.length ? all : [0]));
232 + const X = (i: number, len: number) => PL + ((W - PL - PR) * i) / (len - 1);
233 + const Y = (v: number) => PT + (H - PT - PB) * (1 - (v - vmin) / (vmax - vmin || 1));
234 + const ref = series[0].points;
235 + const hi = hover !== null ? Math.min(n - 1, Math.max(0, hover)) : null;
236 + return (
237 + <figure className="card" style={{ margin: 0, padding: 16 }}>
238 + <figcaption style={{ display: "flex", justifyContent: "space-between", flexWrap: "wrap", gap: 8 }}>
239 + <b style={{ fontFamily: "var(--font-display)", fontSize: 15 }}>{ms.title}</b>
240 + <span style={{ display: "flex", gap: 10, flexWrap: "wrap" }}>
241 + {series.map((s, i) => (
242 + <LegendChip key={s.label} label={s.label} color={MULTI_STYLES[i].stroke}
243 + dashed={!!MULTI_STYLES[i].dash} off={!!off[s.label]}
244 + onClick={() => setOff((o) => ({ ...o, [s.label]: !o[s.label] }))} />
245 + ))}
246 + </span>
247 + </figcaption>
248 + <svg viewBox={`0 0 ${W} ${H}`} style={{ width: "100%", height: "auto", marginTop: 10, touchAction: "pan-y" }} role="img" aria-label={ms.title}
249 + onMouseMove={(e) => {
250 + const r = (e.currentTarget as SVGSVGElement).getBoundingClientRect();
251 + const fx = ((e.clientX - r.left) / r.width) * W;
252 + setHover(Math.round(((fx - PL) / (W - PL - PR)) * (n - 1)));
253 + }}
254 + onMouseLeave={() => setHover(null)}>
255 + {[0, 1, 2, 3, 4].map((g) => {
256 + const y = PT + ((H - PT - PB) * g) / 4;
257 + const v = vmax - ((vmax - vmin) * g) / 4;
258 + return (
259 + <g key={g}>
260 + <line x1={PL} x2={W - PR} y1={y} y2={y} stroke="var(--line)" strokeWidth={1} />
261 + <text x={PL - 6} y={y + 3} textAnchor="end" fontSize={10} fill="var(--ink-3)" fontFamily="var(--font-mono)">{fmtInt(Math.round(v))}</text>
262 + </g>
263 + );
264 + })}
265 + {[0, Math.floor(ref.length / 2), ref.length - 1].map((i) => (
266 + <text key={i} x={X(i, ref.length)} y={H - 8} textAnchor="middle" fontSize={10} fill="var(--ink-3)" fontFamily="var(--font-mono)">{ref[i]?.t}</text>
267 + ))}
268 + {series.map((s, i) => off[s.label] ? null : (
269 + <path key={s.label}
270 + d={s.points.map((p, j) => `${j ? "L" : "M"}${X(j, s.points.length)},${Y(p.v)}`).join("")}
271 + fill="none" stroke={MULTI_STYLES[i].stroke} strokeWidth={MULTI_STYLES[i].width}
272 + strokeDasharray={MULTI_STYLES[i].dash} />
273 + ))}
274 + {hi !== null && (
275 + <line x1={X(hi, n)} x2={X(hi, n)} y1={PT} y2={H - PB} stroke="var(--ink)" strokeWidth={1} strokeDasharray="2 3" />
276 + )}
277 + </svg>
278 + {hi !== null && (
279 + <p className="chip" style={{ marginTop: 8, display: "inline-flex", gap: 12, flexWrap: "wrap" }}>
280 + <b>{ref[hi]?.t}</b>
281 + {shown.map((s) => (
282 + <span key={s.label}>{s.label} : <b>{s.points[hi] ? fmtNum(s.points[hi].v) : "—"}{ms.unit ? ` ${ms.unit}` : ""}</b></span>
283 + ))}
284 + </p>
285 + )}
286 + </figure>
287 + );
288 +}
289 +
290 +/* ---------- Barres verticales (volumes quotidiens, histogrammes) ---------- */
291 +export function VBarChart({ serie, height = 240 }: { serie: Serie; height?: number }) {
292 + const [hover, setHover] = useState<number | null>(null);
293 + const pts = serie.points ?? [];
294 + if (!pts.length) return <EmptyBlock title={serie.title} />;
295 + const W = 720, H = height, PL = 54, PR = 10, PT = 14, PB = 26;
296 + const vmax = Math.max(...pts.map((p) => p.v), 1);
297 + const bw = Math.max(2, (W - PL - PR) / pts.length - 2);
298 + return (
299 + <figure className="card" style={{ margin: 0, padding: 16 }}>
300 + <figcaption><b style={{ fontFamily: "var(--font-display)", fontSize: 15 }}>{serie.title}</b></figcaption>
301 + <svg viewBox={`0 0 ${W} ${H}`} style={{ width: "100%", height: "auto", marginTop: 10 }} role="img" aria-label={serie.title}
302 + onMouseLeave={() => setHover(null)}>
303 + {[0, 1, 2, 3, 4].map((g) => {
304 + const y = PT + ((H - PT - PB) * g) / 4;
305 + const v = vmax - (vmax * g) / 4;
306 + return (
307 + <g key={g}>
308 + <line x1={PL} x2={W - PR} y1={y} y2={y} stroke="var(--line)" strokeWidth={1} />
309 + <text x={PL - 6} y={y + 3} textAnchor="end" fontSize={10} fill="var(--ink-3)" fontFamily="var(--font-mono)">{fmtInt(Math.round(v))}</text>
310 + </g>
311 + );
312 + })}
313 + {pts.map((p, i) => {
314 + const x = PL + ((W - PL - PR) * i) / pts.length;
315 + const h = (H - PT - PB) * (p.v / vmax);
316 + return (
317 + <rect key={i} x={x + 1} y={H - PB - h} width={bw} height={Math.max(h, p.v > 0 ? 1.5 : 0)} rx={2}
318 + fill="var(--accent)" opacity={hover === null || hover === i ? 1 : 0.45}
319 + stroke="var(--ink)" strokeWidth={0.5}
320 + onMouseEnter={() => setHover(i)}>
321 + <title>{`${p.t} — ${fmtNum(p.v)}${serie.unit ? ` ${serie.unit}` : ""}`}</title>
322 + </rect>
323 + );
324 + })}
325 + {[0, Math.floor(pts.length / 2), pts.length - 1].filter((v, i, a) => a.indexOf(v) === i).map((i) => (
326 + <text key={i} x={PL + ((W - PL - PR) * (i + 0.5)) / pts.length} y={H - 8} textAnchor="middle" fontSize={10} fill="var(--ink-3)" fontFamily="var(--font-mono)">{pts[i].t}</text>
327 + ))}
328 + </svg>
329 + {hover !== null && (
330 + <p className="chip" style={{ marginTop: 8 }}>{pts[hover].t} — <b>{fmtNum(pts[hover].v)}{serie.unit ? ` ${serie.unit}` : ""}</b></p>
331 + )}
332 + </figure>
333 + );
334 +}
335 +
336 +/* ---------- Histogramme (distribution) ---------- */
337 +export function Histogram({ dist }: { dist: Distribution }) {
338 + const serie: Serie = {
339 + id: dist.id, title: dist.title, unit: dist.unit, kind: "bar",
340 + points: (dist.bins ?? []).map((b) => ({ t: b.label, v: b.value })),
341 + };
342 + return <VBarChart serie={serie} height={220} />;
343 +}
344 +
345 +/* ---------- Barres empilées (composition dans le temps) ---------- */
346 +export function StackedBarChart({ st, height = 260 }: { st: StackedSerie; height?: number }) {
347 + const [hover, setHover] = useState<number | null>(null);
348 + const keys = (st.keys ?? []).slice(0, 6);
349 + const pts = st.points ?? [];
350 + if (!keys.length || !pts.length) return <EmptyBlock title={st.title} />;
351 + const W = 720, H = height, PL = 54, PR = 10, PT = 14, PB = 26;
352 + const totals = pts.map((p) => p.values.slice(0, keys.length).reduce((s, v) => s + (v || 0), 0));
353 + const vmax = Math.max(...totals, 1);
354 + const bw = Math.max(2, (W - PL - PR) / pts.length - 2);
355 + const shades = [1, 0.72, 0.5, 0.34, 0.22, 0.13];
356 + return (
357 + <figure className="card" style={{ margin: 0, padding: 16 }}>
358 + <figcaption style={{ display: "flex", justifyContent: "space-between", flexWrap: "wrap", gap: 8 }}>
359 + <b style={{ fontFamily: "var(--font-display)", fontSize: 15 }}>{st.title}</b>
360 + <span style={{ display: "flex", gap: 10, flexWrap: "wrap" }}>
361 + {keys.map((k, i) => (
362 + <span key={k} style={{ display: "inline-flex", alignItems: "center", gap: 5, fontFamily: "var(--font-mono)", fontSize: 10.5, fontWeight: 700, textTransform: "uppercase", letterSpacing: "0.06em" }}>
363 + <span style={{ width: 11, height: 11, borderRadius: 3, border: "1px solid var(--ink)", background: "var(--accent)", opacity: shades[i] }} />
364 + {k}
365 + </span>
366 + ))}
367 + </span>
368 + </figcaption>
369 + <svg viewBox={`0 0 ${W} ${H}`} style={{ width: "100%", height: "auto", marginTop: 10 }} role="img" aria-label={st.title}
370 + onMouseLeave={() => setHover(null)}>
371 + {[0, 1, 2, 3, 4].map((g) => {
372 + const y = PT + ((H - PT - PB) * g) / 4;
373 + return (
374 + <g key={g}>
375 + <line x1={PL} x2={W - PR} y1={y} y2={y} stroke="var(--line)" strokeWidth={1} />
376 + <text x={PL - 6} y={y + 3} textAnchor="end" fontSize={10} fill="var(--ink-3)" fontFamily="var(--font-mono)">{fmtInt(Math.round(vmax - (vmax * g) / 4))}</text>
377 + </g>
378 + );
379 + })}
380 + {pts.map((p, i) => {
381 + const x = PL + ((W - PL - PR) * i) / pts.length;
382 + let yAcc = H - PB;
383 + return (
384 + <g key={i} onMouseEnter={() => setHover(i)} opacity={hover === null || hover === i ? 1 : 0.5}>
385 + {keys.map((k, j) => {
386 + const v = p.values[j] || 0;
387 + const h = (H - PT - PB) * (v / vmax);
388 + yAcc -= h;
389 + return v > 0 ? (
390 + <rect key={k} x={x + 1} y={yAcc} width={bw} height={Math.max(h - 1, 0.8)} rx={1.5}
391 + fill="var(--accent)" opacity={shades[j]} stroke="var(--ink)" strokeWidth={0.4}>
392 + <title>{`${p.t} · ${k} — ${fmtNum(v)}${st.unit ? ` ${st.unit}` : ""}`}</title>
393 + </rect>
394 + ) : null;
395 + })}
396 + </g>
397 + );
398 + })}
399 + {[0, Math.floor(pts.length / 2), pts.length - 1].filter((v, i, a) => a.indexOf(v) === i).map((i) => (
400 + <text key={i} x={PL + ((W - PL - PR) * (i + 0.5)) / pts.length} y={H - 8} textAnchor="middle" fontSize={10} fill="var(--ink-3)" fontFamily="var(--font-mono)">{pts[i].t}</text>
401 + ))}
402 + </svg>
403 + {hover !== null && (
404 + <p className="chip" style={{ marginTop: 8, display: "inline-flex", gap: 12, flexWrap: "wrap" }}>
405 + <b>{pts[hover].t}</b>
406 + {keys.map((k, j) => <span key={k}>{k} : <b>{fmtNum(pts[hover].values[j] || 0)}</b></span>)}
407 + <span style={{ color: "var(--ink-3)" }}>total {fmtNum(totals[hover])}</span>
408 + </p>
409 + )}
410 + </figure>
411 + );
412 +}
413 +
414 +/* ---------- Barres horizontales (répartitions, géo) — deltas optionnels ---------- */
162 415 export function BarChart({ title, items, unit }: { title: string; items: BreakItem[]; unit?: string }) {
163 416 const rows = (items ?? []).slice(0, 14);
164 417 if (!rows.length) return <EmptyBlock title={title} />;
@@ -169,9 +422,16 @@ export function BarChart({ title, items, unit }: { title: string; items: BreakIt
169 422 <div style={{ marginTop: 12, display: "grid", gap: 9 }}>
170 423 {rows.map((r) => (
171 424 <div key={r.label} title={`${r.label} — ${fmtNum(r.value)}${unit ? ` ${unit}` : ""}`}>
172 − <div style={{ display: "flex", justifyContent: "space-between", fontSize: 12.5 }}>
425 + <div style={{ display: "flex", justifyContent: "space-between", gap: 8, fontSize: 12.5 }}>
173 426 <span style={{ overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{r.label}</span>
174 − <b style={{ fontFamily: "var(--font-mono)", fontSize: 11.5 }}>{fmtNum(r.value)}{unit ? ` ${unit}` : ""}</b>
427 + <span style={{ display: "inline-flex", gap: 8, alignItems: "baseline", flex: "none" }}>
428 + {r.delta_pct !== undefined && r.delta_pct !== null && (
429 + <span style={{ fontFamily: "var(--font-mono)", fontSize: 10, fontWeight: 700, color: r.delta_pct >= 0 ? "var(--green)" : "var(--danger)" }}>
430 + {r.delta_pct >= 0 ? "▲" : "▼"} {fmtPct(r.delta_pct)}
431 + </span>
432 + )}
433 + <b style={{ fontFamily: "var(--font-mono)", fontSize: 11.5 }}>{fmtNum(r.value)}{unit ? ` ${unit}` : ""}</b>
434 + </span>
175 435 </div>
176 436 <div style={{ marginTop: 3, height: 12, background: "rgba(20,24,20,0.06)", borderRadius: "0 3px 3px 0" }}>
177 437 <div style={{ height: "100%", width: `${Math.max((r.value / max) * 100, 1)}%`, background: "var(--accent)", border: "1px solid var(--ink)", borderRadius: "0 3px 3px 0", boxSizing: "border-box" }} />
@@ -224,6 +484,26 @@ export function Donut({ title, items }: { title: string; items: BreakItem[] }) {
224 484 );
225 485 }
226 486
487 +/* ---------- Jauge (taux, complétude, couverture) ---------- */
488 +export function GaugeCard({ g }: { g: Gauge }) {
489 + const frac = Math.max(0, Math.min(1, g.max ? g.value / g.max : 0));
490 + const R = 60, C = Math.PI * R;
491 + return (
492 + <article className="card" style={{ padding: "14px 16px", minWidth: 0 }} title={g.help}>
493 + <svg viewBox="0 0 150 84" style={{ width: "100%", maxWidth: 190, display: "block", margin: "0 auto" }} role="img" aria-label={`${g.label} : ${fmtNum(g.value)}${g.unit ?? ""} sur ${fmtNum(g.max)}`}>
494 + <path d={`M15,75 A${R},${R} 0 0 1 135,75`} fill="none" stroke="rgba(20,24,20,0.08)" strokeWidth={13} strokeLinecap="round" />
495 + <path d={`M15,75 A${R},${R} 0 0 1 135,75`} fill="none" stroke="var(--accent)" strokeWidth={13} strokeLinecap="round"
496 + strokeDasharray={`${frac * C} ${C}`} />
497 + <text x={75} y={66} textAnchor="middle" fontFamily="var(--font-display)" fontWeight={700} fontSize={22} fill="var(--ink)">
498 + {fmtNum(g.value)}{g.unit ? <tspan fontSize={12} fill="var(--ink-2)"> {g.unit}</tspan> : null}
499 + </text>
500 + <text x={75} y={80} textAnchor="middle" fontSize={9} fill="var(--ink-3)" fontFamily="var(--font-mono)">{(frac * 100).toFixed(0)} % de {fmtNum(g.max)}{g.unit ? ` ${g.unit}` : ""}</text>
501 + </svg>
502 + <p className="klabel" style={{ margin: "8px 0 0", textAlign: "center" }}>{g.label}</p>
503 + </article>
504 + );
505 +}
506 +
227 507 /* ---------- Calendrier de chaleur ---------- */
228 508 export function CalendarHeatmap({ title, cells }: { title: string; cells: { date: string; value: number }[] }) {
229 509 if (!cells?.length) return <EmptyBlock title={title} />;
@@ -261,6 +541,64 @@ export function CalendarHeatmap({ title, cells }: { title: string; cells: { date
261 541 );
262 542 }
263 543
544 +/* ---------- Heatmap horaire 7 × 24 (activité par heure) ---------- */
545 +const DOW = ["Lun", "Mar", "Mer", "Jeu", "Ven", "Sam", "Dim"];
546 +export function HourHeatmap({ title, cells }: { title: string; cells: HourCell[] }) {
547 + if (!cells?.length) return <EmptyBlock title={title} />;
548 + const grid = new Map(cells.map((c) => [`${c.dow}-${c.hour}`, c.value]));
549 + const max = Math.max(...cells.map((c) => c.value), 1);
550 + const CW = 24, CH = 20, LX = 34, LY = 16;
551 + return (
552 + <figure className="card" style={{ margin: 0, padding: 16 }}>
553 + <figcaption><b style={{ fontFamily: "var(--font-display)", fontSize: 15 }}>{title}</b> <span className="klabel">jour × heure</span></figcaption>
554 + <div className="tbl-wrap" style={{ marginTop: 12 }}>
555 + <svg viewBox={`0 0 ${LX + 24 * CW} ${LY + 7 * CH}`} style={{ minWidth: 520, width: "100%", height: "auto" }} role="img" aria-label={title}>
556 + {[0, 6, 12, 18, 23].map((h) => (
557 + <text key={h} x={LX + h * CW + CW / 2} y={11} textAnchor="middle" fontSize={9} fill="var(--ink-3)" fontFamily="var(--font-mono)">{h} h</text>
558 + ))}
559 + {DOW.map((d, i) => (
560 + <text key={d} x={LX - 6} y={LY + i * CH + CH / 2 + 3} textAnchor="end" fontSize={9} fill="var(--ink-3)" fontFamily="var(--font-mono)">{d}</text>
561 + ))}
562 + {Array.from({ length: 7 }, (_, d) => Array.from({ length: 24 }, (_, h) => {
563 + const v = grid.get(`${d}-${h}`) ?? 0;
564 + return (
565 + <rect key={`${d}-${h}`} x={LX + h * CW} y={LY + d * CH} width={CW - 2} height={CH - 2} rx={2.5}
566 + fill={v ? "var(--accent)" : "rgba(20,24,20,0.07)"} fillOpacity={v ? 0.22 + 0.78 * (v / max) : 1}
567 + stroke="rgba(20,24,20,0.15)" strokeWidth={0.5}>
568 + <title>{`${DOW[d]} ${h} h — ${fmtNum(v)}`}</title>
569 + </rect>
570 + );
571 + }))}
572 + </svg>
573 + </div>
574 + </figure>
575 + );
576 +}
577 +
578 +/* ---------- Statistiques de série (min/max/moy/méd/σ) ---------- */
579 +export function StatSummary({ serie }: { serie: Serie }) {
580 + const vs = (serie.points ?? []).map((p) => p.v).filter((v) => typeof v === "number");
581 + if (vs.length < 2) return null;
582 + const sorted = [...vs].sort((a, b) => a - b);
583 + const mean = vs.reduce((s, v) => s + v, 0) / vs.length;
584 + const med = sorted[Math.floor(sorted.length / 2)];
585 + const sd = Math.sqrt(vs.reduce((s, v) => s + (v - mean) ** 2, 0) / vs.length);
586 + const items: [string, number][] = [
587 + ["Min", sorted[0]], ["Max", sorted[sorted.length - 1]],
588 + ["Moyenne", Math.round(mean * 100) / 100], ["Médiane", med],
589 + ["Écart-type", Math.round(sd * 100) / 100],
590 + ];
591 + return (
592 + <div style={{ display: "flex", flexWrap: "wrap", gap: 8, marginTop: 8 }}>
593 + {items.map(([l, v]) => (
594 + <span key={l} className="chip" style={{ fontSize: 11 }}>
595 + <span style={{ color: "var(--ink-3)" }}>{l}</span> <b style={{ fontFamily: "var(--font-mono)" }}>{fmtNum(v)}</b>
596 + </span>
597 + ))}
598 + </div>
599 + );
600 +}
601 +
264 602 /* ---------- Tableau : tri, recherche, pagination ---------- */
265 603 export function DataTable({ spec, pageSize = 25 }: { spec: TableSpec; pageSize?: number }) {
266 604 const [q, setQ] = useState("");
@@ -338,9 +676,19 @@ export function RecordCard({ r }: { r: RecordFact }) {
338 676 );
339 677 }
340 678
341 −/* ---------- Bouton PDF ---------- */
679 +/* ---------- Menu de rapports PDF (5 rapports) ---------- */
342 680 export function PdfButton({ period, from, to, endpoint = "/api/stats/report" }: { period: string; from?: string; to?: string; endpoint?: string }) {
343 − const [busy, setBusy] = useState(false);
681 + const [open, setOpen] = useState(false);
682 + const [busy, setBusy] = useState<string | null>(null);
683 + const box = useRef<HTMLSpanElement>(null);
684 + useEffect(() => {
685 + if (!open) return;
686 + const close = (e: MouseEvent) => {
687 + if (box.current && !box.current.contains(e.target as Node)) setOpen(false);
688 + };
689 + document.addEventListener("mousedown", close);
690 + return () => document.removeEventListener("mousedown", close);
691 + }, [open]);
344 692 const url = (mode: string) => {
345 693 const p = new URLSearchParams({ period, mode });
346 694 if (from) p.set("from", from);
@@ -348,23 +696,38 @@ export function PdfButton({ period, from, to, endpoint = "/api/stats/report" }:
348 696 return `${endpoint}?${p}`;
349 697 };
350 698 const dl = (mode: string) => {
351 − setBusy(true);
699 + setBusy(mode);
700 + setOpen(false);
352 701 const a = document.createElement("a");
353 702 a.href = url(mode);
354 703 a.download = "";
355 704 document.body.appendChild(a);
356 705 a.click();
357 706 a.remove();
358 − setTimeout(() => setBusy(false), 2500);
707 + setTimeout(() => setBusy(null), 3000);
359 708 };
360 709 return (
361 − <span style={{ display: "inline-flex", gap: 8, flexWrap: "wrap" }}>
362 − <button type="button" className="btn btn-primary" onClick={() => dl("complet")} disabled={busy}>
363 − {busy ? "Génération…" : "⬇ Télécharger le rapport PDF"}
710 + <span ref={box} style={{ position: "relative", display: "inline-flex", gap: 8, flexWrap: "wrap" }}>
711 + <button type="button" className="btn btn-primary" onClick={() => dl("complet")} disabled={!!busy}>
712 + {busy ? "Génération…" : "⬇ Rapport PDF complet"}
364 713 </button>
365 − <button type="button" className="btn btn-ghost" onClick={() => dl("synthese")} disabled={busy}>
366 − Synthèse (2 p.)
714 + <button type="button" className="btn btn-ghost" onClick={() => setOpen((o) => !o)} disabled={!!busy}
715 + aria-haspopup="menu" aria-expanded={open}>
716 + Autres rapports ▾
367 717 </button>
718 + {open && (
719 + <div role="menu" className="card" style={{ position: "absolute", top: "calc(100% + 6px)", right: 0, zIndex: 50, minWidth: 300, padding: 6, background: "var(--surface)", boxShadow: "0 10px 28px rgba(20,24,20,0.18)" }}>
720 + {REPORT_MODES.map((m) => (
721 + <button key={m.id} type="button" role="menuitem" onClick={() => dl(m.id)}
722 + style={{ display: "block", width: "100%", textAlign: "left", border: 0, background: "none", cursor: "pointer", padding: "9px 10px", borderRadius: 6 }}
723 + onMouseEnter={(e) => (e.currentTarget.style.background = "var(--surface-2)")}
724 + onMouseLeave={(e) => (e.currentTarget.style.background = "none")}>
725 + <b style={{ display: "block", fontSize: 13, fontFamily: "var(--font-display)" }}>{m.label}</b>
726 + <span className="klabel" style={{ fontSize: 11 }}>{m.desc}</span>
727 + </button>
728 + ))}
729 + </div>
730 + )}
368 731 </span>
369 732 );
370 733 }
modified src/ka/stats/kapdf.py +390 −71
@@ -1,10 +1,17 @@
1 1 # Auteur : Simon-Pierre Boucher — contact@spboucher.ai
2 −# ka-ui/stats/kapdf.py — moteur PDF commun Groupe KA (fpdf2).
2 +# ka-ui/stats/kapdf.py — moteur PDF commun Groupe KA (fpdf2). v2
3 3 # Consomme le JSON du contrat /api/stats/dashboard (voir SPEC.md) et produit
4 −# le rapport estampillé Groupe-KA : couverture, sommaire, KPI, graphiques
5 −# VECTORIELS (courbes/barres/anneaux), tableaux paginés, records, page de fin.
4 +# les rapports estampillés Groupe-KA. 5 modes :
5 +# complet — toutes les sections (KPI, jauges, séries + stats, multi-
6 +# séries, empilées, distributions, répartitions, géo,
7 +# heatmap horaire, tableaux, records)
8 +# synthese — couverture + KPI + records (2-3 pages)
9 +# tendances — KPI + toutes les séries temporelles + stats de séries
10 +# repartitions — breakdowns, distributions, géo, activité horaire
11 +# donnees — tous les tableaux en version longue (400 lignes max)
12 +# Graphiques VECTORIELS uniquement (primitives fpdf), accent de la marque.
6 13 # Usage :
7 −# from kapdf import GroupeKAReport
14 +# from kapdf import GroupeKAReport, REPORT_MODES, filename
8 15 # pdf_bytes = GroupeKAReport(site={"wordmark":"Lou·Ka","accent":"#ff6a00",
9 16 # "domain":"www.lou-ka.com","tagline":"…"}, dashboard=dash_json,
10 17 # mode="complet").build()
@@ -26,6 +33,14 @@ GREEN = (28, 92, 65)
26 33 DANGER = (179, 66, 58)
27 34 WHITE = (255, 255, 255)
28 35
36 +REPORT_MODES = {
37 + "complet": "Rapport complet",
38 + "synthese": "Synthèse exécutive",
39 + "tendances": "Tendances & évolution",
40 + "repartitions": "Répartitions & géographie",
41 + "donnees": "Données détaillées",
42 +}
43 +
29 44 EMAILS = [
30 45 ("contact@groupe-ka.com", "Projets, partenariats & données"),
31 46 ("info@groupe-ka.com", "Médias & questions générales"),
@@ -52,7 +67,8 @@ def _fr(n) -> str:
52 67 _SUBST = {
53 68 "—": "-", "–": "-", "→": "->", "▲": "+", "▼": "-",
54 69 "…": "...", "’": "'", "‘": "'", "“": '"', "”": '"',
55 − "œ": "oe", "Œ": "OE", "−": "-", " ": " ", " ": " ",
70 + "œ": "oe", "Œ": "OE", "−": "-", " ": " ", " ": " ",
71 + "×": "x", "·": ".", "σ": "sigma", "Δ": "delta",
56 72 }
57 73
58 74
@@ -79,7 +95,7 @@ class _PDF(FPDF):
79 95 self.set_auto_page_break(True, margin=22)
80 96
81 97 def header(self):
82 − if self.cover_mode:
98 + if self.cover_mode or self.page_no() == 1:
83 99 return
84 100 self.set_font("helvetica", "B", 8.5)
85 101 self.set_text_color(*INK)
@@ -95,7 +111,9 @@ class _PDF(FPDF):
95 111 self.set_y(20)
96 112
97 113 def footer(self):
98 − if self.cover_mode:
114 + # page 1 = couverture (le flag cover_mode est déjà retombé quand
115 + # add_page() clôt la page 1 → tester aussi le numéro de page)
116 + if self.cover_mode or self.page_no() == 1:
99 117 return
100 118 self.set_y(-15)
101 119 self.set_draw_color(*INK3)
@@ -112,7 +130,7 @@ class GroupeKAReport:
112 130 def __init__(self, site: dict, dashboard: dict, mode: str = "complet"):
113 131 self.site = site
114 132 self.d = dashboard
115 − self.mode = mode
133 + self.mode = mode if mode in REPORT_MODES else "complet"
116 134 self.accent = _hex(site.get("accent", "#d9f26b"))
117 135 period = dashboard.get("period", {}) or {}
118 136 self.period_label = period.get("label") or "toute la période"
@@ -127,6 +145,11 @@ class GroupeKAReport:
127 145 p.set_fill_color(*fill)
128 146 p.rect(x, y, w, h, style="DF", round_corners=True, corner_radius=2.2)
129 147
148 + def _shade(self, i, n=8):
149 + shades = [1.0, 0.78, 0.58, 0.42, 0.30, 0.22, 0.15, 0.10]
150 + f = shades[i % len(shades)]
151 + return tuple(int(PAPER[j] + (self.accent[j] - PAPER[j]) * f) for j in range(3))
152 +
130 153 def _kicker(self, text):
131 154 p = self.pdf
132 155 p.set_font("helvetica", "B", 8)
@@ -150,6 +173,14 @@ class GroupeKAReport:
150 173 self.toc.append((title, self.pdf.page_no()))
151 174 self.pdf.ln(11)
152 175
176 + def _chart_title(self, title):
177 + p = self.pdf
178 + p.set_font("helvetica", "B", 10)
179 + p.set_text_color(*INK)
180 + p.set_x(p.l_margin)
181 + p.cell(0, 6, title)
182 + p.ln(7)
183 +
153 184 # ---------- pages ----------
154 185 def _cover(self):
155 186 p = self.pdf
@@ -161,12 +192,10 @@ class GroupeKAReport:
161 192 p.set_draw_color(*INK)
162 193 p.set_line_width(1.0)
163 194 p.rect(10, 10, 190, 277)
164 − # kicker
165 195 p.set_font("helvetica", "B", 10)
166 196 p.set_text_color(*GREEN)
167 197 p.set_xy(24, 34)
168 198 p.cell(0, 6, "GROUPE KA · RAPPORT STATISTIQUE")
169 − # wordmark : partie gauche + boîte encre/accent
170 199 wm = self.site.get("wordmark", "")
171 200 left, boxed = (wm.split("·") + [None])[:2] if "·" in wm else (wm, None)
172 201 p.set_xy(24, 70)
@@ -184,7 +213,7 @@ class GroupeKAReport:
184 213 p.set_xy(24, 100)
185 214 p.set_font("helvetica", "", 13)
186 215 p.set_text_color(*INK2)
187 − p.multi_cell(150, 7, f"Rapport statistique — {wm}")
216 + p.multi_cell(150, 7, f"{REPORT_MODES[self.mode]} — {wm}")
188 217 now = datetime.now(ZoneInfo("America/Toronto"))
189 218 per = self.d.get("period", {}) or {}
190 219 p.set_xy(24, 125)
@@ -193,7 +222,7 @@ class GroupeKAReport:
193 222 ("Période couverte", self.period_label + (f" ({per.get('from')} → {per.get('to')})" if per.get("from") else "")),
194 223 ("Généré le", now.strftime("%Y-%m-%d à %H:%M") + " (heure de l'Est)"),
195 224 ("Plateforme", "https://" + self.site.get("domain", "")),
196 − ("Mode", "Rapport complet" if self.mode == "complet" else "Synthèse"),
225 + ("Type de rapport", REPORT_MODES[self.mode]),
197 226 ]
198 227 y = 128
199 228 for k, v in rows:
@@ -205,7 +234,6 @@ class GroupeKAReport:
205 234 p.cell(0, 6, str(v))
206 235 p.set_font("helvetica", "", 10.5)
207 236 y += 8
208 − # bande encre au pied
209 237 p.set_fill_color(*INK)
210 238 p.rect(10, 262, 190, 25, style="F")
211 239 p.set_xy(24, 270)
@@ -230,7 +258,7 @@ class GroupeKAReport:
230 258 p = self.pdf
231 259 cols, gw, gh, gap = 3, 56, 26, 3
232 260 x0, y = p.l_margin, p.get_y()
233 − for i, k in enumerate(kpis[:9]):
261 + for i, k in enumerate(kpis[:12]):
234 262 x = x0 + (i % cols) * (gw + gap)
235 263 if i and i % cols == 0:
236 264 y += gh + gap
@@ -252,20 +280,81 @@ class GroupeKAReport:
252 280 p.set_font("helvetica", "B", 8)
253 281 p.set_text_color(*(GREEN if up else DANGER))
254 282 arrow = "+" if k["delta_pct"] >= 0 else ""
255 − p.cell(gw - 8, 4, f"{'▲' if up else '▼'} {arrow}{str(k['delta_pct']).replace('.', ',')} % vs période préc.")
283 + dv = round(float(k["delta_pct"]), 1)
284 + dv = int(dv) if float(dv).is_integer() else dv
285 + p.cell(gw - 8, 4, f"{'▲' if up else '▼'} {arrow}{str(dv).replace('.', ',')} % vs période préc.")
256 286 p.set_y(y + gh + 8)
257 287
258 − def _line_chart(self, s):
288 + def _gauges(self):
289 + gs = self.d.get("gauges") or []
290 + gs = [g for g in gs if isinstance(g.get("value"), (int, float)) and g.get("max")]
291 + if not gs:
292 + return
293 + self._section_title("Taux & couvertures")
294 + p = self.pdf
295 + cols, gw, gh, gap = 3, 56, 34, 3
296 + x0, y = p.l_margin, p.get_y()
297 + for i, g in enumerate(gs[:9]):
298 + x = x0 + (i % cols) * (gw + gap)
299 + if i and i % cols == 0:
300 + y += gh + gap
301 + if y > 240:
302 + p.add_page(); y = p.get_y()
303 + self._card(x, y, gw, gh)
304 + frac = max(0.0, min(1.0, g["value"] / g["max"]))
305 + cx, cy, r = x + gw / 2, y + 20, 14
306 + # arc de fond + arc de valeur (demi-cercle en petits segments)
307 + for pass_col, pass_frac, lw in (((225, 223, 217), 1.0, 2.6), (self.accent, frac, 2.6)):
308 + p.set_draw_color(*pass_col)
309 + p.set_line_width(lw)
310 + steps = max(2, int(60 * pass_frac))
311 + last = None
312 + for st in range(steps + 1):
313 + a = math.pi + math.pi * pass_frac * st / steps
314 + pt = (cx + r * math.cos(a), cy + r * math.sin(a))
315 + if last:
316 + p.line(last[0], last[1], pt[0], pt[1])
317 + last = pt
318 + p.set_font("helvetica", "B", 11)
319 + p.set_text_color(*INK)
320 + p.set_xy(x + 4, cy - 5)
321 + p.cell(gw - 8, 6, f"{_fr(g['value'])}{' ' + g['unit'] if g.get('unit') else ''}", align="C")
322 + p.set_font("helvetica", "", 6.6)
323 + p.set_text_color(*INK3)
324 + p.set_xy(x + 4, cy + 1.5)
325 + p.cell(gw - 8, 4, f"{frac * 100:.0f} % de {_fr(g['max'])}", align="C")
326 + p.set_xy(x + 3, y + gh - 7)
327 + p.set_font("helvetica", "", 7)
328 + p.set_text_color(*INK2)
329 + p.multi_cell(gw - 6, 3.3, str(g.get("label", ""))[:60], align="C")
330 + p.set_y(y + gh + 8)
331 +
332 + def _serie_stats_row(self, s):
333 + """Ligne min/max/moyenne/médiane sous un graphique de série."""
334 + p = self.pdf
335 + vs = [pt["v"] for pt in (s.get("points") or []) if isinstance(pt.get("v"), (int, float))]
336 + if len(vs) < 2:
337 + return
338 + sv = sorted(vs)
339 + mean = sum(vs) / len(vs)
340 + med = sv[len(sv) // 2]
341 + sd = math.sqrt(sum((v - mean) ** 2 for v in vs) / len(vs))
342 + p.set_font("helvetica", "", 6.8)
343 + p.set_text_color(*INK3)
344 + p.cell(0, 4, f"min {_fr(sv[0])} · max {_fr(sv[-1])} · moyenne {_fr(round(mean, 2))} · médiane {_fr(med)} · écart-type {_fr(round(sd, 2))}")
345 + p.ln(5.5)
346 +
347 + def _line_chart(self, s, with_stats=False):
259 348 p = self.pdf
260 349 pts = s.get("points") or []
261 350 if len(pts) < 2:
262 351 return
352 + if s.get("kind") == "bar":
353 + self._vbars(s)
354 + return
263 355 if p.get_y() > 200:
264 356 p.add_page()
265 − p.set_font("helvetica", "B", 10)
266 − p.set_text_color(*INK)
267 − p.cell(0, 6, s.get("title", ""))
268 − p.ln(7)
357 + self._chart_title(s.get("title", ""))
269 358 x0, y0, w, h = p.l_margin, p.get_y(), 174, 52
270 359 self._card(x0, y0, w, h, fill=WHITE)
271 360 cx, cy, cw, ch = x0 + 12, y0 + 6, w - 20, h - 16
@@ -273,7 +362,6 @@ class GroupeKAReport:
273 362 vmax = max(vals) or 1
274 363 vmin = min(0, min(vals))
275 364 rng = (vmax - vmin) or 1
276 − # grille + graduations
277 365 p.set_font("helvetica", "", 6.3)
278 366 p.set_text_color(*INK3)
279 367 p.set_draw_color(200, 200, 195)
@@ -284,6 +372,20 @@ class GroupeKAReport:
284 372 p.set_xy(x0 + 1, gy - 1.6)
285 373 p.cell(10, 3, _fr(vmin + rng * g / 4), align="R")
286 374
375 + def xy(i, n, v):
376 + return (cx + cw * (i / (n - 1)), cy + ch - ch * ((v - vmin) / rng))
377 +
378 + # aire sous la courbe (kind=area) : petits trapèzes accent pâle
379 + if s.get("kind") == "area":
380 + fill = tuple(int(PAPER[j] + (self.accent[j] - PAPER[j]) * 0.18) for j in range(3))
381 + p.set_fill_color(*fill)
382 + p.set_draw_color(*fill)
383 + n = len(pts)
384 + for i in range(n - 1):
385 + x1, y1 = xy(i, n, pts[i]["v"])
386 + x2, y2 = xy(i + 1, n, pts[i + 1]["v"])
387 + p.polygon([(x1, y1), (x2, y2), (x2, cy + ch), (x1, cy + ch)], style="DF")
388 +
287 389 def draw(series, color, width, dash=None):
288 390 n = len(series)
289 391 p.set_draw_color(*color)
@@ -292,8 +394,7 @@ class GroupeKAReport:
292 394 p.set_dash_pattern(dash=1.2, gap=1.2)
293 395 last = None
294 396 for i, pt in enumerate(series):
295 − px = cx + cw * (i / (n - 1))
296 − py = cy + ch - ch * ((pt["v"] - vmin) / rng)
397 + px, py = xy(i, n, pt["v"])
297 398 if last:
298 399 p.line(last[0], last[1], px, py)
299 400 last = (px, py)
@@ -302,7 +403,6 @@ class GroupeKAReport:
302 403 if s.get("compare"):
303 404 draw(s["compare"], INK3, 0.35, dash=True)
304 405 draw(pts, self.accent, 0.7)
305 − # libellés d'axe X (premier / milieu / dernier)
306 406 p.set_text_color(*INK3)
307 407 for frac, idx in ((0, 0), (0.5, len(pts) // 2), (1, -1)):
308 408 p.set_xy(cx + cw * frac - 9, cy + ch + 1.5)
@@ -312,9 +412,166 @@ class GroupeKAReport:
312 412 p.set_font("helvetica", "", 6.8)
313 413 p.set_text_color(*INK3)
314 414 p.cell(0, 4, "— période courante (accent) · ---- période comparée")
315 − p.ln(6)
316 − else:
317 − p.ln(2)
415 + p.ln(5.5)
416 + if with_stats:
417 + self._serie_stats_row(s)
418 + p.ln(1.5)
419 +
420 + def _vbars(self, s):
421 + """Barres verticales : série kind=bar ou distribution (bins)."""
422 + p = self.pdf
423 + pts = s.get("points") or [{"t": b.get("label"), "v": b.get("value")} for b in (s.get("bins") or [])]
424 + pts = [pt for pt in pts if isinstance(pt.get("v"), (int, float))]
425 + if not pts:
426 + return
427 + if p.get_y() > 205:
428 + p.add_page()
429 + self._chart_title(s.get("title", ""))
430 + x0, y0, w, h = p.l_margin, p.get_y(), 174, 48
431 + self._card(x0, y0, w, h, fill=WHITE)
432 + cx, cy, cw, ch = x0 + 12, y0 + 5, w - 20, h - 14
433 + vmax = max(pt["v"] for pt in pts) or 1
434 + p.set_font("helvetica", "", 6.3)
435 + p.set_text_color(*INK3)
436 + p.set_draw_color(200, 200, 195)
437 + p.set_line_width(0.15)
438 + for g in range(5):
439 + gy = cy + ch - ch * g / 4
440 + p.line(cx, gy, cx + cw, gy)
441 + p.set_xy(x0 + 1, gy - 1.6)
442 + p.cell(10, 3, _fr(vmax * g / 4), align="R")
443 + n = len(pts)
444 + bw = max(0.8, cw / n - 0.6)
445 + p.set_fill_color(*self.accent)
446 + p.set_draw_color(*INK)
447 + p.set_line_width(0.15)
448 + for i, pt in enumerate(pts):
449 + bh = ch * (pt["v"] / vmax)
450 + p.rect(cx + cw * i / n + 0.3, cy + ch - bh, bw, max(bh, 0.4 if pt["v"] > 0 else 0), style="DF")
451 + p.set_text_color(*INK3)
452 + for frac, idx in ((0, 0), (0.5, n // 2), (1, -1)):
453 + p.set_xy(cx + cw * frac - 10, cy + ch + 1.5)
454 + p.cell(20, 3, str(pts[idx].get("t", ""))[:12], align="C")
455 + p.set_y(y0 + h + 5)
456 +
457 + def _multiline(self, ms):
458 + """Multi-séries (≤4) : accent plein / encre fin / accent pointillé /
459 + gris pointillé — l'identité passe par le motif, pas la couleur seule."""
460 + p = self.pdf
461 + series = [s for s in (ms.get("series") or []) if len(s.get("points") or []) > 1][:4]
462 + if not series:
463 + return
464 + if p.get_y() > 195:
465 + p.add_page()
466 + self._chart_title(ms.get("title", ""))
467 + x0, y0, w, h = p.l_margin, p.get_y(), 174, 52
468 + self._card(x0, y0, w, h, fill=WHITE)
469 + cx, cy, cw, ch = x0 + 12, y0 + 6, w - 20, h - 16
470 + vals = [pt["v"] for s in series for pt in s["points"]]
471 + vmax = max(vals) or 1
472 + vmin = min(0, min(vals))
473 + rng = (vmax - vmin) or 1
474 + p.set_font("helvetica", "", 6.3)
475 + p.set_text_color(*INK3)
476 + p.set_draw_color(200, 200, 195)
477 + p.set_line_width(0.15)
478 + for g in range(5):
479 + gy = cy + ch - ch * g / 4
480 + p.line(cx, gy, cx + cw, gy)
481 + p.set_xy(x0 + 1, gy - 1.6)
482 + p.cell(10, 3, _fr(vmin + rng * g / 4), align="R")
483 + styles = [
484 + (self.accent, 0.7, None),
485 + (INK, 0.45, None),
486 + (self.accent, 0.55, True),
487 + (INK3, 0.5, True),
488 + ]
489 + for si, s in enumerate(series):
490 + col, lw, dash = styles[si]
491 + p.set_draw_color(*col)
492 + p.set_line_width(lw)
493 + if dash:
494 + p.set_dash_pattern(dash=1.4, gap=1.2)
495 + n = len(s["points"])
496 + last = None
497 + for i, pt in enumerate(s["points"]):
498 + px = cx + cw * (i / (n - 1))
499 + py = cy + ch - ch * ((pt["v"] - vmin) / rng)
500 + if last:
501 + p.line(last[0], last[1], px, py)
502 + last = (px, py)
503 + p.set_dash_pattern()
504 + ref = series[0]["points"]
505 + p.set_text_color(*INK3)
506 + for frac, idx in ((0, 0), (0.5, len(ref) // 2), (1, -1)):
507 + p.set_xy(cx + cw * frac - 9, cy + ch + 1.5)
508 + p.cell(18, 3, str(ref[idx].get("t", ""))[:10], align="C")
509 + p.set_y(y0 + h + 4)
510 + p.set_font("helvetica", "", 6.8)
511 + p.set_text_color(*INK3)
512 + marks = ["—", "—", "----", "----"]
513 + leg = " · ".join(f"{marks[i]} {s.get('label', '')}" for i, s in enumerate(series))
514 + p.cell(0, 4, leg[:120])
515 + p.ln(6)
516 +
517 + def _stacked(self, st):
518 + p = self.pdf
519 + keys = (st.get("keys") or [])[:6]
520 + pts = st.get("points") or []
521 + if not keys or not pts:
522 + return
523 + if p.get_y() > 195:
524 + p.add_page()
525 + self._chart_title(st.get("title", ""))
526 + x0, y0, w, h = p.l_margin, p.get_y(), 174, 52
527 + self._card(x0, y0, w, h, fill=WHITE)
528 + cx, cy, cw, ch = x0 + 12, y0 + 6, w - 20, h - 16
529 + totals = [sum(v or 0 for v in pt.get("values", [])[: len(keys)]) for pt in pts]
530 + vmax = max(totals) or 1
531 + p.set_font("helvetica", "", 6.3)
532 + p.set_text_color(*INK3)
533 + p.set_draw_color(200, 200, 195)
534 + p.set_line_width(0.15)
535 + for g in range(5):
536 + gy = cy + ch - ch * g / 4
537 + p.line(cx, gy, cx + cw, gy)
538 + p.set_xy(x0 + 1, gy - 1.6)
539 + p.cell(10, 3, _fr(vmax * g / 4), align="R")
540 + n = len(pts)
541 + bw = max(0.8, cw / n - 0.6)
542 + p.set_draw_color(*WHITE)
543 + p.set_line_width(0.12)
544 + for i, pt in enumerate(pts):
545 + yacc = cy + ch
546 + for j, k in enumerate(keys):
547 + v = (pt.get("values") or [0] * len(keys))[j] if j < len(pt.get("values", [])) else 0
548 + if not v:
549 + continue
550 + bh = ch * (v / vmax)
551 + yacc -= bh
552 + p.set_fill_color(*self._shade(j))
553 + p.rect(cx + cw * i / n + 0.3, yacc, bw, max(bh - 0.15, 0.3), style="DF")
554 + p.set_text_color(*INK3)
555 + for frac, idx in ((0, 0), (0.5, n // 2), (1, -1)):
556 + p.set_xy(cx + cw * frac - 10, cy + ch + 1.5)
557 + p.cell(20, 3, str(pts[idx].get("t", ""))[:12], align="C")
558 + p.set_y(y0 + h + 4)
559 + # légende
560 + p.set_font("helvetica", "", 6.8)
561 + lx = p.l_margin
562 + for j, k in enumerate(keys):
563 + p.set_fill_color(*self._shade(j))
564 + p.set_draw_color(*INK)
565 + p.set_line_width(0.2)
566 + p.rect(lx, p.get_y() + 0.6, 3, 3, style="DF")
567 + p.set_xy(lx + 4, p.get_y())
568 + p.set_text_color(*INK2)
569 + txt = str(k)[:22]
570 + p.cell(p.get_string_width(txt) + 3, 4, txt)
571 + lx = p.get_x() + 3
572 + if lx > 165:
573 + break
574 + p.ln(7)
318 575
319 576 def _bars(self, title, items, unit=""):
320 577 p = self.pdf
@@ -324,10 +581,8 @@ class GroupeKAReport:
324 581 need = 10 + len(items) * 7
325 582 if p.get_y() + need > 265:
326 583 p.add_page()
327 − p.set_font("helvetica", "B", 10)
328 − p.set_text_color(*INK)
329 − p.cell(0, 6, title)
330 − p.ln(8)
584 + self._chart_title(title)
585 + p.ln(1)
331 586 vmax = max(it["value"] for it in items) or 1
332 587 for it in items:
333 588 y = p.get_y()
@@ -335,19 +590,23 @@ class GroupeKAReport:
335 590 p.set_text_color(*INK)
336 591 p.set_x(p.l_margin)
337 592 p.cell(46, 5, str(it["label"])[:34])
338 − bw = 96 * (it["value"] / vmax)
593 + bw = 86 * (it["value"] / vmax)
339 594 p.set_fill_color(*self.accent)
340 595 p.set_draw_color(*INK)
341 596 p.set_line_width(0.25)
342 597 p.rect(p.l_margin + 48, y + 0.7, max(bw, 0.8), 3.6, style="DF")
343 − p.set_xy(p.l_margin + 148, y)
598 + p.set_xy(p.l_margin + 136, y)
344 599 p.set_font("helvetica", "B", 7.6)
345 − p.cell(26, 5, _fr(it["value"]) + (" " + unit if unit else ""), align="R")
600 + p.cell(24, 5, _fr(it["value"]) + (" " + unit if unit else ""), align="R")
601 + if it.get("delta_pct") is not None:
602 + up = it["delta_pct"] >= 0
603 + p.set_font("helvetica", "B", 6.6)
604 + p.set_text_color(*(GREEN if up else DANGER))
605 + p.cell(14, 5, f"{'+' if up else ''}{str(round(it['delta_pct'], 1)).replace('.', ',')} %", align="R")
346 606 p.ln(6.4)
347 607 p.ln(3)
348 608
349 609 def _donut(self, b):
350 − # anneau vectoriel simple (arcs) + légende
351 610 p = self.pdf
352 611 items = [it for it in (b.get("items") or []) if it.get("value")][:8]
353 612 total = sum(it["value"] for it in items)
@@ -355,17 +614,13 @@ class GroupeKAReport:
355 614 return
356 615 if p.get_y() > 210:
357 616 p.add_page()
358 − p.set_font("helvetica", "B", 10)
359 − p.set_text_color(*INK)
360 − p.cell(0, 6, b.get("title", ""))
361 − p.ln(8)
617 + self._chart_title(b.get("title", ""))
618 + p.ln(1)
362 619 cx, cy, r = p.l_margin + 26, p.get_y() + 24, 20
363 − shades = [1.0, 0.78, 0.58, 0.42, 0.30, 0.22, 0.15, 0.10]
364 620 start = -90.0
365 621 for i, it in enumerate(items):
366 622 frac = it["value"] / total
367 − f = shades[i % len(shades)]
368 − col = tuple(int(PAPER[j] + (self.accent[j] - PAPER[j]) * f) for j in range(3))
623 + col = self._shade(i)
369 624 steps = max(2, int(72 * frac))
370 625 p.set_fill_color(*col)
371 626 p.set_draw_color(*col)
@@ -384,11 +639,9 @@ class GroupeKAReport:
384 639 p.set_line_width(0.4)
385 640 p.ellipse(cx - 11, cy - 11, 22, 22, style="DF")
386 641 p.ellipse(cx - r, cy - r, 2 * r, 2 * r, style="D")
387 − # légende
388 642 ly = cy - 22
389 643 for i, it in enumerate(items):
390 − f = shades[i % len(shades)]
391 − col = tuple(int(PAPER[j] + (self.accent[j] - PAPER[j]) * f) for j in range(3))
644 + col = self._shade(i)
392 645 p.set_fill_color(*col)
393 646 p.set_draw_color(*INK)
394 647 p.rect(p.l_margin + 60, ly + 0.8, 4, 4, style="DF")
@@ -400,7 +653,39 @@ class GroupeKAReport:
400 653 ly += 5.6
401 654 p.set_y(max(cy + r, ly) + 6)
402 655
403 − def _table(self, t):
656 + def _hourly(self):
657 + hh = self.d.get("hourly") or {}
658 + cells = hh.get("cells") or []
659 + if not cells:
660 + return
661 + p = self.pdf
662 + if p.get_y() > 190:
663 + p.add_page()
664 + self._chart_title(hh.get("title", "Activité par jour et heure"))
665 + x0, y0 = p.l_margin, p.get_y()
666 + cw, chh, lx, ly = 6.4, 6.4, 12, 5
667 + vmax = max((c.get("value") or 0) for c in cells) or 1
668 + grid = {(c.get("dow"), c.get("hour")): c.get("value") or 0 for c in cells}
669 + dows = ["Lun", "Mar", "Mer", "Jeu", "Ven", "Sam", "Dim"]
670 + p.set_font("helvetica", "", 5.8)
671 + p.set_text_color(*INK3)
672 + for h in (0, 6, 12, 18, 23):
673 + p.set_xy(x0 + lx + h * cw, y0)
674 + p.cell(cw, 3, f"{h}h", align="C")
675 + for d in range(7):
676 + p.set_xy(x0, y0 + ly + d * chh + 1.5)
677 + p.cell(lx - 1, 3, dows[d], align="R")
678 + for h in range(24):
679 + v = grid.get((d, h), 0)
680 + f = 0.1 + 0.9 * (v / vmax) if v else 0.0
681 + col = tuple(int(PAPER[j] + (self.accent[j] - PAPER[j]) * f) for j in range(3)) if v else (235, 233, 228)
682 + p.set_fill_color(*col)
683 + p.set_draw_color(215, 213, 207)
684 + p.set_line_width(0.1)
685 + p.rect(x0 + lx + h * cw, y0 + ly + d * chh, cw - 0.5, chh - 0.5, style="DF")
686 + p.set_y(y0 + ly + 7 * chh + 5)
687 +
688 + def _table(self, t, max_rows=200):
404 689 p = self.pdf
405 690 cols = t.get("columns") or []
406 691 rows = t.get("rows") or []
@@ -417,7 +702,7 @@ class GroupeKAReport:
417 702 p.ln(6)
418 703 head()
419 704 p.set_text_color(*INK)
420 − for i, row in enumerate(rows[:200]):
705 + for i, row in enumerate(rows[:max_rows]):
421 706 if p.get_y() > 262:
422 707 p.add_page()
423 708 head()
@@ -428,10 +713,10 @@ class GroupeKAReport:
428 713 txt = _fr(cell) if isinstance(cell, (int, float)) else str(cell)
429 714 p.cell(w, 5.4, " " + txt[:34], fill=True)
430 715 p.ln(5.4)
431 − if len(rows) > 200:
716 + if len(rows) > max_rows:
432 717 p.set_font("helvetica", "", 7)
433 718 p.set_text_color(*INK3)
434 − p.cell(0, 5, f"… {len(rows) - 200} lignes supplémentaires non imprimées")
719 + p.cell(0, 5, f"… {len(rows) - max_rows} lignes supplémentaires non imprimées")
435 720 p.ln(6)
436 721
437 722 def _records(self):
@@ -440,7 +725,7 @@ class GroupeKAReport:
440 725 return
441 726 self._section_title("Records & faits marquants")
442 727 p = self.pdf
443 − for r in recs[:10]:
728 + for r in recs[:14]:
444 729 if p.get_y() > 258:
445 730 p.add_page()
446 731 y = p.get_y()
@@ -498,43 +783,76 @@ class GroupeKAReport:
498 783 "groupe-ka.com/conditions · /confidentialite · /loi-25.",
499 784 )
500 785
501 − def _toc_page(self):
502 − # insérée après coup ? fpdf ne réordonne pas : on écrit le sommaire en
503 − # page 2 en réservant la page lors du build (voir build()).
504 − pass
786 + # ---------- groupes de sections ----------
787 + def _all_series(self, with_stats=True):
788 + for s in self.d.get("series") or []:
789 + self._line_chart(s, with_stats=with_stats)
790 + for ms in self.d.get("multiseries") or []:
791 + self._multiline(ms)
792 + for st in self.d.get("stacked") or []:
793 + self._stacked(st)
794 +
795 + def _all_breakdowns(self):
796 + for b in self.d.get("breakdowns") or []:
797 + if b.get("kind") == "donut":
798 + self._donut(b)
799 + else:
800 + self._bars(b.get("title", ""), b.get("items"))
801 + for dist in self.d.get("distributions") or []:
802 + self._vbars(dist)
803 + geo = self.d.get("geo")
804 + if geo:
805 + self._bars(geo.get("title", "Répartition géographique"), geo.get("items"))
806 + self._hourly()
505 807
506 808 def build(self) -> bytes:
507 809 p = self.pdf
508 810 p.alias_nb_pages()
509 811 self._cover()
812 + with_toc = self.mode in ("complet", "donnees")
813 + toc_page_no = None
510 814 if self.mode == "synthese":
511 815 p.add_page()
512 816 self._kpis()
817 + self._gauges()
818 + self._records()
819 + self._final_page()
820 + elif self.mode == "tendances":
821 + p.add_page()
822 + self._kpis()
823 + self._section_title("Évolution & tendances")
824 + self._all_series(with_stats=True)
513 825 self._records()
514 826 self._final_page()
515 − else:
827 + elif self.mode == "repartitions":
828 + p.add_page()
829 + self._section_title("Répartitions, distributions & géographie")
830 + self._all_breakdowns()
831 + self._final_page()
832 + elif self.mode == "donnees":
833 + p.add_page()
834 + toc_page_no = p.page_no()
835 + for t in self.d.get("tables") or []:
836 + self._table(t, max_rows=400)
837 + self._final_page()
838 + else: # complet
516 839 p.add_page()
517 840 toc_page_no = p.page_no()
518 841 p.add_page()
519 842 self._kpis()
520 − for s in self.d.get("series") or []:
521 − if s.get("kind") == "bar":
522 − self._bars(s.get("title", ""), [{"label": pt.get("t"), "value": pt.get("v")} for pt in (s.get("points") or [])], s.get("unit", ""))
523 − else:
524 − self._line_chart(s)
525 − for b in self.d.get("breakdowns") or []:
526 − if b.get("kind") == "donut":
527 − self._donut(b)
528 − else:
529 − self._bars(b.get("title", ""), b.get("items"))
530 − geo = self.d.get("geo")
531 − if geo:
532 − self._bars(geo.get("title", "Répartition géographique"), geo.get("items"))
843 + self._gauges()
844 + if (self.d.get("series") or self.d.get("multiseries") or self.d.get("stacked")):
845 + self._section_title("Évolution & tendances")
846 + self._all_series(with_stats=True)
847 + if (self.d.get("breakdowns") or self.d.get("distributions") or self.d.get("geo") or self.d.get("hourly")):
848 + self._section_title("Répartitions, distributions & géographie")
849 + self._all_breakdowns()
533 850 for t in self.d.get("tables") or []:
534 851 self._table(t)
535 852 self._records()
536 853 self._final_page()
537 − # sommaire écrit sur la page réservée (page 2)
854 + # sommaire écrit sur la page réservée
855 + if toc_page_no is not None:
538 856 last_page = p.page
539 857 p.page = toc_page_no
540 858 p.set_y(22)
@@ -553,6 +871,7 @@ class GroupeKAReport:
553 871 return bytes(p.output())
554 872
555 873
556 −def filename(platform_id: str, period: str) -> str:
874 +def filename(platform_id: str, period: str, mode: str = "complet") -> str:
557 875 today = datetime.now(ZoneInfo("America/Toronto")).strftime("%Y-%m-%d")
558 − return f"groupe-ka_{platform_id}_stats_{period}_{today}.pdf"
876 + suffix = "" if mode in ("", "complet") else f"_{mode}"
877 + return f"groupe-ka_{platform_id}_stats_{period}{suffix}_{today}.pdf"
modified src/lib/ecostats.ts +619 −23
@@ -1,24 +1,49 @@
1 1 // Auteur : Simon-Pierre Boucher — contact@spboucher.ai
2 2 // Statistiques de l'écosystème — fetch serveur parallèle des tableaux de
3 −// bord /api/stats/dashboard des 11 plateformes de données (contrat commun
4 −// src/ka/stats/SPEC.md), cache ISR 10 min, délai 8 s, null si échec.
5 −// AUCUNE donnée inventée : une plateforme injoignable reste null et la page
6 −// l'affiche comme « indisponible ».
3 +// bord /api/stats/dashboard des plateformes de données (contrat commun
4 +// src/ka/stats/SPEC.md v2), cache ISR 10 min, délai 8 s, null si échec.
5 +// buildEcoPayload() consolide le tout en un objet sérialisable pour la page
6 +// /stats maître : KPI écosystème (+ sparkline sommée sur les dates communes),
7 +// classement, croissance comparée (indice 100), volume empilé par plateforme,
8 +// calendrier/heatmap horaire agrégés, résumé par plateforme, table détaillée
9 +// et records. AUCUNE donnée inventée : une plateforme injoignable reste null
10 +// (bloc « indisponible »), un dashboard v1 est rendu tel quel (dégradé
11 +// propre) ; les seuls calculs sont des sommes/alignements/indices sur les
12 +// chiffres publiés par les plateformes elles-mêmes.
7 13
8 14 import eco from "@/ka/ecosystem.json";
15 +import type {
16 + Kpi as ChartKpi,
17 + Point as SeriePoint,
18 + Serie as ChartSerie,
19 + MultiSerie as ChartMultiSerie,
20 + StackedSerie as ChartStacked,
21 + BreakItem,
22 + Gauge as ChartGauge,
23 + TableSpec as ChartTable,
24 + RecordFact,
25 + HourCell,
26 +} from "@/ka/stats/kacharts";
27 +
28 +/* ---------- types du contrat SPEC v2 (tous champs optionnels) ---------- */
9 29
10 30 export type Kpi = {
11 31 id?: string;
12 32 label: string;
13 33 value: number | string;
14 34 unit?: string;
15 − delta_pct?: number;
35 + delta_pct?: number | null;
16 36 direction?: "up" | "down";
37 + spark?: SeriePoint[];
17 38 };
18 39
19 −export type KaRecord = { label: string; value: string; date?: string };
40 +export type KaRecord = RecordFact;
20 41
21 −export type BreakdownItem = { label: string; value: number };
42 +export type BreakdownItem = {
43 + label: string;
44 + value: number;
45 + delta_pct?: number | null;
46 +};
22 47
23 48 export type Breakdown = {
24 49 id?: string;
@@ -28,13 +53,30 @@ export type Breakdown = {
28 53 items?: BreakdownItem[];
29 54 };
30 55
56 +export type DashSerie = {
57 + id?: string;
58 + title?: string;
59 + unit?: string;
60 + kind?: string;
61 + points?: SeriePoint[];
62 + compare?: SeriePoint[];
63 +};
64 +
31 65 export type Dashboard = {
32 66 updated?: string;
33 67 period?: { from?: string; to?: string; label?: string };
34 68 kpis?: Kpi[];
35 − records?: KaRecord[];
69 + gauges?: { id?: string; label?: string; value?: number; max?: number; unit?: string }[];
70 + series?: DashSerie[];
71 + multiseries?: unknown[];
72 + stacked?: unknown[];
36 73 breakdowns?: Breakdown[];
74 + distributions?: unknown[];
37 75 geo?: Breakdown | null;
76 + heatmap?: { title?: string; cells?: { date?: string; value?: number }[] } | null;
77 + hourly?: { title?: string; cells?: { dow?: number; hour?: number; value?: number }[] } | null;
78 + tables?: unknown[];
79 + records?: KaRecord[];
38 80 };
39 81
40 82 export type Site = {
@@ -64,6 +106,8 @@ export type PeriodKey = (typeof PERIODS)[number][0];
64 106 export const isPeriod = (p: string | undefined): p is PeriodKey =>
65 107 PERIODS.some(([k]) => k === p);
66 108
109 +/* ---------- lecture des dashboards ---------- */
110 +
67 111 // Identifiants de KPI « nouveautés de la période » connus des plateformes.
68 112 const NEW_KPI_IDS = [
69 113 "nouvelles",
@@ -102,7 +146,10 @@ export function topKpis(dash: Dashboard | null, n = 3): Kpi[] {
102 146 }
103 147
104 148 /** Items valides d'un bloc de répartition (breakdowns[] / geo du SPEC). */
105 −export function breakdownItems(b: Breakdown | null | undefined, n = 6): BreakdownItem[] {
149 +export function breakdownItems(
150 + b: Breakdown | null | undefined,
151 + n = 6,
152 +): BreakdownItem[] {
106 153 if (!b || !Array.isArray(b.items)) return [];
107 154 return b.items
108 155 .filter(
@@ -128,6 +175,59 @@ export function geoBreakdown(dash: Dashboard | null): Breakdown | null {
128 175 return g && breakdownItems(g, 1).length > 0 ? g : null;
129 176 }
130 177
178 +const numPts = (pts?: SeriePoint[]): SeriePoint[] =>
179 + (pts ?? []).filter(
180 + (p): p is SeriePoint => !!p && typeof p.t === "string" && isNum(p.v),
181 + );
182 +
183 +const trimPts = (pts: SeriePoint[], n: number): SeriePoint[] =>
184 + pts.length > n ? pts.slice(pts.length - n) : pts;
185 +
186 +/** Première série temporelle exploitable (convention : la 1re = volume). */
187 +export function mainSeries(dash: Dashboard | null): DashSerie | null {
188 + for (const s of dash?.series ?? [])
189 + if (numPts(s.points).length >= 2) return s;
190 + return null;
191 +}
192 +
193 +/** Tendance du volume principal : spark v2 du KPI, sinon 1re série publiée. */
194 +export function sparkOf(dash: Dashboard | null): SeriePoint[] {
195 + const ks = numPts(mainKpi(dash)?.spark);
196 + if (ks.length >= 2) return ks;
197 + return numPts(mainSeries(dash)?.points);
198 +}
199 +
200 +/** Croissance du volume principal : delta_pct publié (v2), sinon dérivée de
201 + * la série publiée (dernier vs premier point — marquée `derived`). */
202 +export function growthOf(
203 + dash: Dashboard | null,
204 +): { pct: number; derived: boolean } | null {
205 + const mk = mainKpi(dash);
206 + if (mk && isNum(mk.delta_pct)) return { pct: mk.delta_pct, derived: false };
207 + const sp = sparkOf(dash);
208 + if (sp.length >= 2 && sp[0].v > 0) {
209 + const pct =
210 + Math.round(((sp[sp.length - 1].v - sp[0].v) / sp[0].v) * 1000) / 10;
211 + return { pct, derived: true };
212 + }
213 + return null;
214 +}
215 +
216 +/** Dashboard v2 : publie au moins un des enrichissements du SPEC v2. */
217 +export function isV2(dash: Dashboard | null): boolean {
218 + if (!dash) return false;
219 + return Boolean(
220 + dash.gauges?.length ||
221 + dash.multiseries?.length ||
222 + dash.stacked?.length ||
223 + dash.distributions?.length ||
224 + dash.hourly?.cells?.length ||
225 + (dash.kpis ?? []).some(
226 + (k) => (k.spark?.length ?? 0) > 1 || isNum(k.delta_pct),
227 + ),
228 + );
229 +}
230 +
131 231 export const dataSites: Site[] = (eco.sites as Site[]).filter(
132 232 (s) => s.id !== "groupe-ka",
133 233 );
@@ -165,7 +265,7 @@ async function fetchDashboard(
165 265 }
166 266 }
167 267
168 −/** Dashboards des 11 plateformes de données, en parallèle (ordre d'ecosystem.json). */
268 +/** Dashboards des plateformes de données, en parallèle (ordre d'ecosystem.json). */
169 269 export async function getEcosystemStats(
170 270 period: PeriodKey,
171 271 ): Promise<PlatformStats[]> {
@@ -177,13 +277,119 @@ export async function getEcosystemStats(
177 277 );
178 278 }
179 279
180 −/** Agrégats consolidés — uniquement à partir des plateformes jointes. */
181 −export function consolidate(platforms: PlatformStats[]) {
280 +/* ---------- consolidation v2 → payload sérialisable pour la page ---------- */
281 +
282 +const fmtInt = (n: number): string => n.toLocaleString("fr-CA");
283 +
284 +/** Format compact honnête pour les très grands nombres (G / M). */
285 +export function fmtCompact(v: number, unit?: string): string {
286 + let txt: string;
287 + if (Math.abs(v) >= 1_000_000_000) {
288 + txt = `${(v / 1_000_000_000).toLocaleString("fr-CA", { maximumFractionDigits: 2 })} G`;
289 + } else if (Math.abs(v) >= 100_000_000) {
290 + txt = `${(v / 1_000_000).toLocaleString("fr-CA", { maximumFractionDigits: 1 })} M`;
291 + } else if (Number.isInteger(v)) {
292 + txt = fmtInt(v);
293 + } else {
294 + txt = v.toLocaleString("fr-CA", { maximumFractionDigits: 2 });
295 + }
296 + return unit ? `${txt} ${unit}` : txt;
297 +}
298 +
299 +const fmtPctSigned = (pct: number): string =>
300 + `${pct >= 0 ? "+" : ""}${pct.toLocaleString("fr-CA", { maximumFractionDigits: 1 })} %`;
301 +
302 +function fmtAgo(ms: number): string {
303 + const min = Math.round(ms / 60_000);
304 + if (min < 1) return "< 1 min";
305 + if (min < 90) return `${min} min`;
306 + const h = ms / 3_600_000;
307 + if (h < 48)
308 + return `${h.toLocaleString("fr-CA", { maximumFractionDigits: 1 })} h`;
309 + return `${Math.round(h / 24)} j`;
310 +}
311 +
312 +const fmtDateTime = (iso: string): string =>
313 + new Date(iso).toLocaleString("fr-CA", {
314 + timeZone: "America/Toronto",
315 + dateStyle: "medium",
316 + timeStyle: "short",
317 + });
318 +
319 +/** Dates communes (intersection triée) à plusieurs séries alignables. */
320 +function commonDates(seriesList: SeriePoint[][]): string[] {
321 + if (!seriesList.length) return [];
322 + let set = new Set(seriesList[0].map((p) => p.t));
323 + for (const s of seriesList.slice(1)) {
324 + const other = new Set(s.map((p) => p.t));
325 + set = new Set([...set].filter((d) => other.has(d)));
326 + }
327 + return [...set].sort();
328 +}
329 +
330 +const byDateMap = (pts: SeriePoint[]): Map<string, number> =>
331 + new Map(pts.map((p) => [p.t, p.v]));
332 +
333 +export type SiteLite = Pick<Site, "id" | "wordmark" | "domain" | "accent">;
334 +
335 +export type PlatformSummary = {
336 + site: SiteLite;
337 + ok: boolean;
338 + v2: boolean;
339 + kpis: ChartKpi[]; // ≤ 3, le 1er porte la sparkline du volume principal
340 + record: RecordFact | null;
341 + breakdown: { title: string; kind: string; items: BreakItem[] } | null;
342 + geo: { title: string; items: BreakItem[] } | null;
343 + volume: number | null;
344 + growth: { pct: number; derived: boolean } | null;
345 + updatedFmt: string | null;
346 +};
347 +
348 +export type EcoPayload = {
349 + period: PeriodKey;
350 + periodLabel: string;
351 + banner: ChartKpi[];
352 + gauges: ChartGauge[];
353 + volume: { serie: ChartSerie; note: string } | null;
354 + growthIndex: { ms: ChartMultiSerie; note: string } | null;
355 + stacked: { st: ChartStacked; note: string } | null;
356 + ranking: BreakItem[];
357 + heat: { title: string; cells: { date: string; value: number }[]; note: string } | null;
358 + hourly: { title: string; cells: HourCell[]; note: string } | null;
359 + platforms: PlatformSummary[];
360 + table: ChartTable;
361 + records: RecordFact[];
362 + freshness: string | null;
363 + reachable: number;
364 + total: number;
365 + v2count: number;
366 + growthDerived: boolean;
367 +};
368 +
369 +export function buildEcoPayload(
370 + platforms: PlatformStats[],
371 + opts: { period: PeriodKey; periodLabel: string; connectors: number },
372 +): EcoPayload {
373 + const now = Date.now();
182 374 const ok = platforms.filter((p) => p.dash);
375 +
376 + // classement par volume principal (injoignables à la fin)
377 + const ranked = [...platforms].sort((a, b) => {
378 + const va = mainKpi(a.dash)?.value;
379 + const vb = mainKpi(b.dash)?.value;
380 + return (isNum(vb) ? vb : -1) - (isNum(va) ? va : -1);
381 + });
382 + const rankedOk = ranked.filter((p) => p.dash);
383 +
384 + // agrégats de base
183 385 let totalVolume = 0;
184 386 let totalNew = 0;
185 387 let newCount = 0;
186 − let latestUpdate: string | null = null;
388 + let latestUpdate: { iso: string; site: Site } | null = null;
389 + const ages: number[] = [];
390 + let gNum = 0;
391 + let gDen = 0;
392 + let growthDerived = false;
187 393 for (const p of ok) {
188 394 const mk = mainKpi(p.dash);
189 395 if (mk && isNum(mk.value)) totalVolume += mk.value;
@@ -193,20 +399,410 @@ export function consolidate(platforms: PlatformStats[]) {
193 399 newCount += 1;
194 400 }
195 401 const upd = p.dash?.updated;
196 − if (upd && (!latestUpdate || upd > latestUpdate)) latestUpdate = upd;
402 + if (upd) {
403 + const t = Date.parse(upd);
404 + if (Number.isFinite(t)) ages.push(Math.max(0, now - t));
405 + if (!latestUpdate || upd > latestUpdate.iso)
406 + latestUpdate = { iso: upd, site: p.site };
407 + }
408 + const g = growthOf(p.dash);
409 + if (g && mk && isNum(mk.value) && mk.value > 0) {
410 + gNum += mk.value * g.pct;
411 + gDen += mk.value;
412 + if (g.derived) growthDerived = true;
413 + }
197 414 }
198 − const ranked = [...platforms].sort((a, b) => {
199 − const va = mainKpi(a.dash)?.value;
200 − const vb = mainKpi(b.dash)?.value;
201 − return (isNum(vb) ? vb : -1) - (isNum(va) ? va : -1);
415 + const wGrowth = gDen > 0 ? Math.round((gNum / gDen) * 10) / 10 : null;
416 + const avgAge =
417 + ages.length > 0 ? ages.reduce((s, v) => s + v, 0) / ages.length : null;
418 + const v2count = ok.filter((p) => isV2(p.dash)).length;
419 +
420 + // contributeurs aux graphiques temporels : plateformes avec tendance ≥ 2 pts
421 + const withSpark = rankedOk
422 + .map((p) => ({ p, spark: sparkOf(p.dash) }))
423 + .filter((x) => x.spark.length >= 2);
424 +
425 + // 1) série écosystème = somme des volumes sur les dates communes
426 + let volume: EcoPayload["volume"] = null;
427 + if (withSpark.length > 0) {
428 + const dates = commonDates(withSpark.map((x) => x.spark));
429 + if (dates.length >= 2) {
430 + const maps = withSpark.map((x) => byDateMap(x.spark));
431 + const points = trimPts(
432 + dates.map((t) => ({
433 + t,
434 + v: maps.reduce((s, m) => s + (m.get(t) ?? 0), 0),
435 + })),
436 + 90,
437 + );
438 + volume = {
439 + serie: {
440 + id: "eco-vol",
441 + title: `Volume principal agrégé — ${withSpark.length} plateformes`,
442 + kind: "area",
443 + points,
444 + },
445 + note: `Somme, jour par jour, des indicateurs principaux publiés par ${withSpark.length} plateformes (${withSpark
446 + .map((x) => x.p.site.wordmark)
447 + .join(", ")}), sur les ${dates.length} dates communes à leurs séries.`,
448 + };
449 + }
450 + }
451 +
452 + // 2) croissance comparée des 4 plus grosses plateformes (indice base 100)
453 + let growthIndex: EcoPayload["growthIndex"] = null;
454 + {
455 + const top4 = withSpark.slice(0, 4);
456 + if (top4.length >= 2) {
457 + const dates = commonDates(top4.map((x) => x.spark));
458 + if (dates.length >= 2) {
459 + const series = top4
460 + .map((x) => {
461 + const m = byDateMap(x.spark);
462 + const base = m.get(dates[0]) ?? 0;
463 + if (base <= 0) return null;
464 + return {
465 + label: x.p.site.wordmark,
466 + points: dates.map((t) => ({
467 + t,
468 + v: Math.round(((m.get(t) ?? 0) / base) * 1000) / 10,
469 + })),
470 + };
471 + })
472 + .filter((s): s is NonNullable<typeof s> => s !== null);
473 + if (series.length >= 2) {
474 + growthIndex = {
475 + ms: {
476 + id: "eco-growth",
477 + title: "Croissance comparée des plus grosses plateformes",
478 + unit: "indice",
479 + series,
480 + },
481 + note: `Indice 100 = volume principal de chaque plateforme au ${dates[0]} (début de la fenêtre commune aux séries publiées) — permet de comparer les rythmes de croissance malgré des volumes de natures différentes.`,
482 + };
483 + }
484 + }
485 + }
486 + }
487 +
488 + // 3) volume empilé par plateforme dans le temps (top 5)
489 + let stacked: EcoPayload["stacked"] = null;
490 + {
491 + const top5 = withSpark.slice(0, 5);
492 + if (top5.length >= 2) {
493 + const dates = commonDates(top5.map((x) => x.spark));
494 + if (dates.length >= 2) {
495 + const maps = top5.map((x) => byDateMap(x.spark));
496 + stacked = {
497 + st: {
498 + id: "eco-stack",
499 + title: "Volume par plateforme dans le temps",
500 + keys: top5.map((x) => x.p.site.wordmark),
501 + points: dates.map((t) => ({
502 + t,
503 + values: maps.map((m) => m.get(t) ?? 0),
504 + })),
505 + },
506 + note: `Composition du volume agrégé sur les dates communes aux séries des ${top5.length} plus grosses plateformes. Les volumes ne sont pas de même nature (annonces, produits, pages…) : lire comme un ordre de grandeur.`,
507 + };
508 + }
509 + }
510 + }
511 +
512 + // 4) classement (barres + anneau)
513 + const ranking: BreakItem[] = rankedOk
514 + .map((p) => {
515 + const mk = mainKpi(p.dash);
516 + const g = growthOf(p.dash);
517 + return {
518 + label: p.site.wordmark,
519 + value: mk && isNum(mk.value) ? mk.value : 0,
520 + delta_pct: g ? g.pct : undefined,
521 + };
522 + })
523 + .filter((r) => r.value > 0);
524 +
525 + // 5) calendriers agrégés (somme des plateformes qui les publient)
526 + let heat: EcoPayload["heat"] = null;
527 + {
528 + const contrib: Site[] = [];
529 + const sum = new Map<string, number>();
530 + for (const p of ok) {
531 + const cells = p.dash?.heatmap?.cells ?? [];
532 + const valid = cells.filter(
533 + (c) => typeof c?.date === "string" && isNum(c?.value),
534 + );
535 + if (!valid.length) continue;
536 + contrib.push(p.site);
537 + for (const c of valid)
538 + sum.set(c.date as string, (sum.get(c.date as string) ?? 0) + (c.value as number));
539 + }
540 + if (sum.size > 0) {
541 + heat = {
542 + title: "Activité quotidienne de l'écosystème",
543 + cells: [...sum.entries()].map(([date, value]) => ({ date, value })),
544 + note: `Somme des calendriers d'activité publiés par ${contrib.length} plateformes (${contrib.map((s) => s.wordmark).join(", ")}).`,
545 + };
546 + }
547 + }
548 + let hourly: EcoPayload["hourly"] = null;
549 + {
550 + const contrib: Site[] = [];
551 + const sum = new Map<string, number>();
552 + for (const p of ok) {
553 + const cells = p.dash?.hourly?.cells ?? [];
554 + const valid = cells.filter(
555 + (c) => isNum(c?.dow) && isNum(c?.hour) && isNum(c?.value),
556 + );
557 + if (!valid.length) continue;
558 + contrib.push(p.site);
559 + for (const c of valid) {
560 + const key = `${c.dow}-${c.hour}`;
561 + sum.set(key, (sum.get(key) ?? 0) + (c.value as number));
562 + }
563 + }
564 + if (sum.size > 0) {
565 + hourly = {
566 + title: "Activité horaire de l'écosystème",
567 + cells: [...sum.entries()].map(([k, value]) => {
568 + const [dow, hour] = k.split("-").map(Number);
569 + return { dow, hour, value };
570 + }),
571 + note: `Somme de l'activité horaire journalisée par ${contrib.length} plateformes (${contrib.map((s) => s.wordmark).join(", ")}).`,
572 + };
573 + }
574 + }
575 +
576 + // 6) résumé par plateforme
577 + const summaries: PlatformSummary[] = ranked.map((p) => {
578 + const { site, dash } = p;
579 + const lite: SiteLite = {
580 + id: site.id,
581 + wordmark: site.wordmark,
582 + domain: site.domain,
583 + accent: site.accent,
584 + };
585 + if (!dash)
586 + return {
587 + site: lite,
588 + ok: false,
589 + v2: false,
590 + kpis: [],
591 + record: null,
592 + breakdown: null,
593 + geo: null,
594 + volume: null,
595 + growth: null,
596 + updatedFmt: null,
597 + };
598 + const spark = trimPts(sparkOf(dash), 40);
599 + const kpis: ChartKpi[] = topKpis(dash, 3).map((k, i) => ({
600 + id: k.id ?? k.label,
601 + label: k.label,
602 + value: k.value,
603 + unit: k.unit,
604 + delta_pct: isNum(k.delta_pct) ? k.delta_pct : undefined,
605 + direction: k.direction,
606 + spark: i === 0 && spark.length >= 2 ? spark : undefined,
607 + }));
608 + const bd = firstBreakdown(dash);
609 + const g = geoBreakdown(dash);
610 + const mk = mainKpi(dash);
611 + return {
612 + site: lite,
613 + ok: true,
614 + v2: isV2(dash),
615 + kpis,
616 + record: dash.records?.[0] ?? null,
617 + breakdown: bd
618 + ? {
619 + title: bd.title ?? bd.label ?? bd.id ?? "Répartition",
620 + kind: bd.kind === "donut" ? "donut" : "bars",
621 + items: breakdownItems(bd, 8),
622 + }
623 + : null,
624 + geo: g
625 + ? {
626 + title: g.title ?? g.label ?? "Par région",
627 + items: breakdownItems(g, 6),
628 + }
629 + : null,
630 + volume: mk && isNum(mk.value) ? mk.value : null,
631 + growth: growthOf(dash),
632 + updatedFmt: dash.updated ? fmtDateTime(dash.updated) : null,
633 + };
202 634 });
635 +
636 + // 7) bandeau KPI écosystème
637 + const banner: ChartKpi[] = [
638 + ...(ok.length > 0
639 + ? [
640 + {
641 + id: "vol",
642 + label: "Volume principal agrégé",
643 + value: totalVolume,
644 + delta_pct: wGrowth,
645 + spark: volume ? trimPts(volume.serie.points, 40) : undefined,
646 + help: `Somme des indicateurs principaux des ${ok.length} plateformes jointes${
647 + wGrowth !== null
648 + ? ` · croissance pondérée par le volume${growthDerived ? ", en partie dérivée des séries publiées" : ""}`
649 + : ""
650 + }`,
651 + } satisfies ChartKpi,
652 + ]
653 + : []),
654 + ...(newCount > 0
655 + ? [
656 + {
657 + id: "new",
658 + label: `Nouveautés de la période (${newCount} plateformes)`,
659 + value: totalNew,
660 + } satisfies ChartKpi,
661 + ]
662 + : []),
663 + {
664 + id: "online",
665 + label: "Plateformes de données en ligne",
666 + value: `${ok.length}/${platforms.length}`,
667 + },
668 + {
669 + id: "err",
670 + label: "Plateformes injoignables",
671 + value: platforms.length - ok.length,
672 + },
673 + ...(avgAge !== null
674 + ? [
675 + {
676 + id: "fresh",
677 + label: "Fraîcheur moyenne des données",
678 + value: fmtAgo(avgAge),
679 + help: "Âge moyen de la dernière mise à jour des tableaux de bord joints",
680 + } satisfies ChartKpi,
681 + ]
682 + : []),
683 + {
684 + id: "conn",
685 + label: "Connecteurs sources actifs",
686 + value: `${fmtInt(opts.connectors)}+`,
687 + },
688 + ];
689 +
690 + // 8) jauges de couverture du hub
691 + const gauges: ChartGauge[] = [
692 + {
693 + id: "jointes",
694 + label: "Plateformes jointes",
695 + value: ok.length,
696 + max: platforms.length,
697 + },
698 + {
699 + id: "series",
700 + label: "Publient des séries de tendance",
701 + value: withSpark.length,
702 + max: platforms.length,
703 + },
704 + {
705 + id: "v2",
706 + label: "Tableaux de bord enrichis (v2)",
707 + value: v2count,
708 + max: platforms.length,
709 + },
710 + ];
711 +
712 + // 9) table détaillée du classement
713 + const table: ChartTable = {
714 + id: "classement",
715 + title: "Classement détaillé des plateformes",
716 + columns: [
717 + "#",
718 + "Plateforme",
719 + "Indicateur principal",
720 + "Volume",
721 + "Croissance",
722 + "Nouveautés",
723 + "Mis à jour",
724 + "Statut",
725 + ],
726 + rows: ranked.map((p, i) => {
727 + const mk = mainKpi(p.dash);
728 + const nk = newKpi(p.dash);
729 + const g = growthOf(p.dash);
730 + const s = summaries.find((x) => x.site.id === p.site.id);
731 + return [
732 + i + 1,
733 + p.site.wordmark,
734 + p.dash ? (mk?.label ?? "—") : "—",
735 + mk && isNum(mk.value) ? mk.value : "—",
736 + g ? `${fmtPctSigned(g.pct)}${g.derived ? " *" : ""}` : "—",
737 + nk && isNum(nk.value) ? nk.value : "—",
738 + s?.updatedFmt ?? "—",
739 + p.dash ? (isV2(p.dash) ? "en ligne · v2" : "en ligne") : "injoignable",
740 + ];
741 + }),
742 + };
743 +
744 + // 10) records écosystème (calculés depuis les données publiées)
745 + const records: RecordFact[] = [];
746 + const top = summaries.find((s) => s.ok && s.volume !== null);
747 + if (top && top.volume !== null)
748 + records.push({
749 + label: "Plus gros inventaire",
750 + value: `${top.site.wordmark} · ${fmtCompact(top.volume)}`,
751 + });
752 + const gBest = summaries
753 + .filter((s) => s.ok && s.growth)
754 + .sort((a, b) => (b.growth?.pct ?? 0) - (a.growth?.pct ?? 0))[0];
755 + if (gBest?.growth)
756 + records.push({
757 + label: "Plus forte croissance de la période",
758 + value: `${gBest.site.wordmark} · ${fmtPctSigned(gBest.growth.pct)}`,
759 + });
760 + let nBest: { site: Site; v: number } | null = null;
761 + for (const p of ok) {
762 + const nk = newKpi(p.dash);
763 + if (nk && isNum(nk.value) && (!nBest || nk.value > nBest.v))
764 + nBest = { site: p.site, v: nk.value };
765 + }
766 + if (nBest)
767 + records.push({
768 + label: "Le plus de nouveautés (période)",
769 + value: `${nBest.site.wordmark} · ${fmtCompact(nBest.v)}`,
770 + });
771 + if (latestUpdate)
772 + records.push({
773 + label: "Mise à jour la plus récente",
774 + value: latestUpdate.site.wordmark,
775 + date: fmtDateTime(latestUpdate.iso),
776 + });
777 + for (const p of rankedOk) {
778 + if (records.length >= 10) break;
779 + const r = p.dash?.records?.[0];
780 + if (r && typeof r.label === "string" && typeof r.value === "string")
781 + records.push({
782 + label: `${p.site.wordmark} — ${r.label}`,
783 + value: r.value,
784 + date: r.date,
785 + });
786 + }
787 +
203 788 return {
789 + period: opts.period,
790 + periodLabel: opts.periodLabel,
791 + banner,
792 + gauges,
793 + volume,
794 + growthIndex,
795 + stacked,
796 + ranking,
797 + heat,
798 + hourly,
799 + platforms: summaries,
800 + table,
801 + records,
802 + freshness: latestUpdate ? fmtDateTime(latestUpdate.iso) : null,
204 803 reachable: ok.length,
205 804 total: platforms.length,
206 − totalVolume,
207 − totalNew,
208 − newCount,
209 − latestUpdate,
210 − ranked,
805 + v2count,
806 + growthDerived,
211 807 };
212 808 }
213 809