SPB Git

spb/job-ka

Public

Intégration complète à l'écosystème Groupe KA

- Design : ka-ui vendoré (tokens.css importé avant le CSS local), accent
  officiel cyan #0c8599 (fin du lime hérité), socle dédupliqué, badge
  « Un service Groupe KA » au header (desktop + mobile, zéro débordement
  à 360/768/1440), prefooter local + KaFooter commun, page /contact
  (ecosystem.json), title « Job-Ka — Un service Groupe KA », assets
  og.png/favicon.svg/apple-touch-icon + meta OG/Twitter absolues.
- SSO KA ID : jobka/auth.py (client job-ka, cookie jobka_session, table
  users), bouton « Se connecter avec KA » au header, testé bout-en-bout
  jusqu'au hub (307 → /connexion, client reconnu).
- Stats : /api/stats/dashboard (contrat SPEC, cache 5 min, salaires
  bornés 25–400 k$, série date_posted réelle) + /api/stats/report (PDF
  fpdf2 via jobka/kapdf.py, complet + synthèse), page /stats refaite sur
  ka/stats/kacharts.tsx ; /api/stats historique conservé pour le hub.
- KA Agent : widget ka-agent.js câblé (site job-ka).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Simon-Pierre Boucher committed (Aug 18, 2026) parent 4657429 Browse files

24 changed files +3,546 −132

modified frontend/index.html +17 −4
@@ -13,15 +13,28 @@ Créé : 2026-08-17 Modifié : 2026-08-17
13 13 <head>
14 14 <meta charset="UTF-8" />
15 15 <meta name="viewport" content="width=device-width, initial-scale=1.0" />
16 − <meta name="description" content="Job·Ka — toutes les offres d'emploi des employeurs québécois, directement à la source. Salaires transparents, zéro boîte noire." />
17 − <title>Job·Ka — L'emploi au Québec, à la source</title>
18 − <link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 64 64'%3E%3Crect width='64' height='64' rx='14' fill='%23141814'/%3E%3Ctext x='32' y='42' font-family='Inter,sans-serif' font-size='28' font-weight='800' fill='%23d9f26b' text-anchor='middle'%3EJ·K%3C/text%3E%3C/svg%3E" />
16 + <meta name="description" content="Job·Ka — toutes les offres d'emploi des employeurs québécois, directement à la source. Salaires transparents, zéro boîte noire. Un service Groupe KA." />
17 + <title>Job-Ka — Un service Groupe KA</title>
18 + <link rel="icon" type="image/svg+xml" href="/favicon.svg" />
19 + <link rel="apple-touch-icon" href="/apple-touch-icon.png" />
20 + <meta property="og:title" content="Job-Ka — Un service Groupe KA" />
21 + <meta property="og:description" content="Toutes les offres d'emploi des employeurs québécois, directement à la source. Salaires transparents, zéro boîte noire." />
22 + <meta property="og:type" content="website" />
23 + <meta property="og:url" content="https://www.job-ka.com/" />
24 + <meta property="og:image" content="https://www.job-ka.com/og.png" />
25 + <meta property="og:image:width" content="1200" />
26 + <meta property="og:image:height" content="630" />
27 + <meta name="twitter:card" content="summary_large_image" />
28 + <meta name="twitter:image" content="https://www.job-ka.com/og.png" />
19 29 <link rel="preconnect" href="https://fonts.googleapis.com" />
20 30 <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
21 − <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet" />
31 + <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&family=Space+Grotesk:wght@500;600;700&family=JetBrains+Mono:wght@500;700&display=swap" rel="stylesheet" />
22 32 </head>
23 33 <body>
24 34 <div id="root"></div>
25 35 <script type="module" src="/src/main.tsx"></script>
36 + <!-- KA Agent : assistant IA commun de l'écosystème Groupe KA -->
37 + <script>window.KA_AGENT={site:"job-ka"}</script>
38 + <script src="/ka-agent.js" defer></script>
26 39 </body>
27 40 </html>
added frontend/public/apple-touch-icon.png +0 −0

Binary file not shown.

added frontend/public/favicon.svg +5 −0
@@ -0,0 +1,5 @@
1 +<svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" viewBox="0 0 64 64">
2 +<rect width="64" height="64" rx="14" fill="#141814"/>
3 +<rect x="4.5" y="4.5" width="55" height="55" rx="11" fill="none" stroke="#0c8599" stroke-opacity="0.35" stroke-width="2"/>
4 +<text x="32" y="43" text-anchor="middle" font-family="'Space Grotesk','Arial Black',sans-serif" font-size="30" font-weight="700" letter-spacing="-1" fill="#0c8599" transform="rotate(-4 32 32)">Ka</text>
5 +</svg>
\ No newline at end of file
added frontend/public/ka-agent.js +233 −0
@@ -0,0 +1,233 @@
1 +/* Auteur : Simon-Pierre Boucher — contact@spboucher.ai
2 + * ka-ui/agent/ka-agent.js — KA AGENT : widget de chat commun de l'écosystème
3 + * Groupe KA. Vanilla JS, zéro dépendance, injecté sur les 13 sites.
4 + * <script>window.KA_AGENT={site:"lou-ka"}</script>
5 + * <script src="/ka-agent.js" defer></script>
6 + * Bulle flottante en bas à droite → panneau de chat (bulle) → plein écran (⛶).
7 + * Flux SSE en direct depuis le backend central (texte token par token +
8 + * indicateur d'outil). Historique conservé en localStorage (par site).
9 + */
10 +(function () {
11 + "use strict";
12 + var CFG = window.KA_AGENT || {};
13 + var SITE = CFG.site || "groupe-ka";
14 + var ENDPOINT = CFG.endpoint || "https://www.api-ka.com/api/agent/chat";
15 + var KEY = "ka-agent-" + SITE;
16 + var MAXLOG = 20;
17 +
18 + /* ---------- styles ---------- */
19 + var css = `
20 + .kaa-btn{position:fixed;right:18px;bottom:18px;z-index:2147483000;width:58px;height:58px;
21 + border-radius:50%;border:2px solid var(--ink,#141814);background:var(--accent,#d9f26b);
22 + color:var(--on-accent,#141814);font:700 17px/1 "Space Grotesk",system-ui,sans-serif;
23 + cursor:pointer;box-shadow:4px 4px 0 rgba(20,24,20,.85);display:flex;align-items:center;
24 + justify-content:center;transition:transform .15s;padding-bottom:env(safe-area-inset-bottom,0)}
25 + .kaa-btn:hover{transform:translate(-2px,-2px)}
26 + .kaa-panel{position:fixed;right:16px;bottom:86px;z-index:2147483001;width:min(392px,calc(100vw - 24px));
27 + 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.kaa-open{display:flex}
31 + .kaa-panel.kaa-full{right:0;bottom:0;width:100vw;height:100dvh;border-radius:0;border:0;box-shadow:none}
32 + .kaa-head{display:flex;align-items:center;gap:9px;padding:11px 14px;background:var(--ink,#141814);
33 + color:var(--paper,#f5f3ee);flex:none}
34 + .kaa-head b{font:700 15px "Space Grotesk",system-ui,sans-serif;letter-spacing:-.02em}
35 + .kaa-head .kaa-ka{display:inline-block;background:var(--accent,#d9f26b);color:var(--on-accent,#141814);
36 + border-radius:6px;padding:1px 7px 2px;transform:rotate(-2deg);font-weight:700}
37 + .kaa-head small{font:700 9.5px "JetBrains Mono",monospace;letter-spacing:.09em;text-transform:uppercase;opacity:.65}
38 + .kaa-head .kaa-sp{flex:1}
39 + .kaa-hbtn{width:34px;height:34px;border:1.5px solid rgba(245,243,238,.4);border-radius:8px;background:none;
40 + color:var(--paper,#f5f3ee);font-size:15px;cursor:pointer;line-height:1}
41 + .kaa-hbtn:hover{border-color:var(--accent,#d9f26b);color:var(--accent,#d9f26b)}
42 + .kaa-log{flex:1;overflow-y:auto;padding:14px;display:flex;flex-direction:column;gap:10px;
43 + overscroll-behavior:contain;-webkit-overflow-scrolling:touch}
44 + .kaa-msg{max-width:86%;padding:9px 13px;border:1.5px solid var(--ink,#141814);border-radius:12px;
45 + font-size:13.5px;line-height:1.5;white-space:pre-wrap;word-break:break-word}
46 + .kaa-msg.kaa-u{align-self:flex-end;background:var(--accent,#d9f26b);color:var(--on-accent,#141814);
47 + border-bottom-right-radius:4px}
48 + .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)}
49 + .kaa-msg.kaa-a a{color:inherit;text-decoration:underline;text-underline-offset:3px}
50 + .kaa-msg.kaa-a b{font-weight:700}
51 + .kaa-tool{align-self:flex-start;font:700 10px "JetBrains Mono",monospace;letter-spacing:.07em;
52 + text-transform:uppercase;color:var(--ink-2,#4d5551);padding:3px 10px;border:1.5px dashed var(--ink-2,#4d5551);
53 + border-radius:999px;background:var(--surface-2,#faf9f5)}
54 + .kaa-in{display:flex;gap:8px;padding:11px;border-top:2px solid var(--ink,#141814);background:#fff;flex:none;
55 + padding-bottom:calc(11px + env(safe-area-inset-bottom,0))}
56 + .kaa-in textarea{flex:1;resize:none;min-height:44px;max-height:110px;padding:11px 12px;font:13.5px/1.4 Inter,system-ui,sans-serif;
57 + border:1.5px solid var(--ink,#141814);border-radius:9px;background:var(--paper,#f5f3ee);outline:none}
58 + .kaa-in button{min-width:52px;min-height:44px;border:1.5px solid var(--ink,#141814);border-radius:9px;
59 + background:var(--ink,#141814);color:var(--accent,#d9f26b);font:700 16px "Space Grotesk",system-ui;cursor:pointer}
60 + .kaa-in button:disabled{opacity:.45}
61 + .kaa-hello{font-size:12.5px;color:var(--ink-2,#4d5551);padding:4px 2px}
62 + .kaa-dots::after{content:"…";animation:kaa-b 1.2s infinite}
63 + @keyframes kaa-b{0%{opacity:.2}50%{opacity:1}100%{opacity:.2}}
64 + @media (max-width:560px){.kaa-panel{right:8px;left:8px;width:auto}}
65 + `;
66 +
67 + /* ---------- markdown minimal (gras, liens, puces) — texte échappé d'abord ---------- */
68 + function esc(s) {
69 + return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
70 + }
71 + function md(s) {
72 + return esc(s)
73 + .replace(/\*\*([^*]+)\*\*/g, "<b>$1</b>")
74 + .replace(/(https?:\/\/[^\s<)"']+)/g, function (u) {
75 + return '<a href="' + u + '" target="_blank" rel="noopener noreferrer">' + u.replace(/^https?:\/\/(www\.)?/, "").slice(0, 40) + "</a>";
76 + });
77 + }
78 +
79 + /* ---------- état ---------- */
80 + var log = [];
81 + try { log = JSON.parse(localStorage.getItem(KEY) || "[]"); } catch (e) {}
82 + function save() { try { localStorage.setItem(KEY, JSON.stringify(log.slice(-MAXLOG))); } catch (e) {} }
83 +
84 + /* ---------- DOM ---------- */
85 + var style = document.createElement("style");
86 + style.textContent = css;
87 + document.head.appendChild(style);
88 +
89 + var btn = document.createElement("button");
90 + btn.className = "kaa-btn";
91 + btn.setAttribute("aria-label", "Ouvrir KA Agent — assistant de l'écosystème Groupe KA");
92 + btn.innerHTML = "Ka";
93 +
94 + var panel = document.createElement("div");
95 + panel.className = "kaa-panel";
96 + panel.setAttribute("role", "dialog");
97 + panel.setAttribute("aria-label", "KA Agent");
98 + panel.innerHTML =
99 + '<div class="kaa-head"><b>KA<span class="kaa-ka">Agent</span></b><small>Groupe KA · IA</small><span class="kaa-sp"></span>' +
100 + '<button class="kaa-hbtn kaa-x1" title="Plein écran" aria-label="Plein écran">⛶</button>' +
101 + '<button class="kaa-hbtn kaa-x2" title="Fermer" aria-label="Fermer">✕</button></div>' +
102 + '<div class="kaa-log"></div>' +
103 + '<div class="kaa-in"><textarea rows="1" placeholder="Posez votre question…" aria-label="Votre question"></textarea>' +
104 + "<button aria-label=\"Envoyer\">➤</button></div>";
105 + document.body.appendChild(btn);
106 + document.body.appendChild(panel);
107 +
108 + var logEl = panel.querySelector(".kaa-log");
109 + var ta = panel.querySelector("textarea");
110 + var send = panel.querySelector(".kaa-in button");
111 +
112 + function scroll() { logEl.scrollTop = logEl.scrollHeight; }
113 + function bubble(cls, html) {
114 + var d = document.createElement("div");
115 + d.className = "kaa-msg " + cls;
116 + d.innerHTML = html;
117 + logEl.appendChild(d);
118 + scroll();
119 + return d;
120 + }
121 + function toolChip(name) {
122 + var d = document.createElement("div");
123 + d.className = "kaa-tool kaa-dots";
124 + d.textContent = "🔎 " + name.replace(/_/g, " ");
125 + logEl.appendChild(d);
126 + scroll();
127 + return d;
128 + }
129 +
130 + function hello() {
131 + if (log.length) return;
132 + var d = document.createElement("div");
133 + d.className = "kaa-hello";
134 + 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.";
135 + logEl.appendChild(d);
136 + }
137 + function render() {
138 + logEl.innerHTML = "";
139 + hello();
140 + log.forEach(function (m) { bubble(m.role === "user" ? "kaa-u" : "kaa-a", md(m.content)); });
141 + scroll();
142 + }
143 +
144 + /* ---------- ouverture / plein écran ---------- */
145 + btn.addEventListener("click", function () {
146 + panel.classList.toggle("kaa-open");
147 + if (panel.classList.contains("kaa-open")) { render(); ta.focus(); }
148 + });
149 + panel.querySelector(".kaa-x2").addEventListener("click", function () {
150 + panel.classList.remove("kaa-open", "kaa-full");
151 + });
152 + panel.querySelector(".kaa-x1").addEventListener("click", function () {
153 + panel.classList.toggle("kaa-full");
154 + scroll();
155 + });
156 +
157 + /* ---------- envoi + flux SSE ---------- */
158 + var busy = false;
159 + function ask() {
160 + var q = ta.value.trim();
161 + if (!q || busy) return;
162 + busy = true;
163 + send.disabled = true;
164 + ta.value = "";
165 + log.push({ role: "user", content: q });
166 + save();
167 + bubble("kaa-u", md(q));
168 + var out = bubble("kaa-a", '<span class="kaa-dots"></span>');
169 + var acc = "";
170 + var chips = [];
171 +
172 + fetch(ENDPOINT, {
173 + method: "POST",
174 + headers: { "Content-Type": "application/json" },
175 + body: JSON.stringify({ site: SITE, messages: log.slice(-MAXLOG) }),
176 + })
177 + .then(function (res) {
178 + if (!res.ok || !res.body) throw new Error("HTTP " + res.status);
179 + var reader = res.body.getReader();
180 + var dec = new TextDecoder();
181 + var buf = "";
182 + function pump() {
183 + return reader.read().then(function (r) {
184 + if (r.done) return finish();
185 + buf += dec.decode(r.value, { stream: true });
186 + var blocks = buf.split("\n\n");
187 + buf = blocks.pop();
188 + blocks.forEach(function (b) {
189 + var ev = (b.match(/^event: (.+)$/m) || [])[1];
190 + var dm = (b.match(/^data: (.+)$/m) || [])[1];
191 + if (!ev || !dm) return;
192 + var data = {};
193 + try { data = JSON.parse(dm); } catch (e) {}
194 + if (ev === "delta" && data.text) {
195 + acc += data.text;
196 + out.innerHTML = md(acc);
197 + scroll();
198 + } else if (ev === "tool") {
199 + chips.push(toolChip(data.name || "recherche"));
200 + logEl.appendChild(out); // la bulle reste après le chip
201 + scroll();
202 + } else if (ev === "error") {
203 + acc = acc || "Désolé, une erreur est survenue (" + (data.message || "inconnue") + "). Réessayez.";
204 + out.innerHTML = md(acc);
205 + }
206 + });
207 + return pump();
208 + });
209 + }
210 + return pump();
211 + })
212 + .catch(function (e) {
213 + acc = acc || "Impossible de joindre KA Agent (" + e.message + "). Réessayez dans un instant.";
214 + out.innerHTML = md(acc);
215 + })
216 + .then(function () { finish(); });
217 +
218 + function finish() {
219 + if (busy === false) return;
220 + busy = false;
221 + send.disabled = false;
222 + chips.forEach(function (c) { c.classList.remove("kaa-dots"); });
223 + if (!acc) { acc = "Je n'ai pas pu formuler de réponse — réessayez."; out.innerHTML = md(acc); }
224 + log.push({ role: "assistant", content: acc });
225 + save();
226 + scroll();
227 + }
228 + }
229 + send.addEventListener("click", ask);
230 + ta.addEventListener("keydown", function (e) {
231 + if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); ask(); }
232 + });
233 +})();
added frontend/public/og.png +0 −0

Binary file not shown.

modified frontend/src/App.tsx +66 −11
@@ -4,32 +4,82 @@
4 4 * Auteur : Simon-Pierre Boucher
5 5 * Contact : contact@spboucher.ai
6 6 * Fichier : frontend/src/App.tsx
7 − * Rôle : Gabarit global (en-tête, navigation, routes, pied de page)
7 + * Rôle : Gabarit global (en-tête + badge Groupe KA + connexion KA ID,
8 + * navigation, routes, pied de page commun Groupe KA)
8 9 * Créé : 2026-08-17 Modifié : 2026-08-17
9 10 * =============================================================================
10 11 */
11 −import { lazy, Suspense } from "react";
12 +import { lazy, Suspense, useEffect, useState } from "react";
12 13 import { NavLink, Route, Routes } from "react-router-dom";
13 14 import Home from "./pages/Home";
14 15 import JobPage from "./pages/Job";
15 16 import Sources from "./pages/Sources";
16 17 import Stats from "./pages/Stats";
18 +import Contact from "./pages/Contact";
19 +import GroupeKaBadge from "./ka/GroupeKaBadge";
20 +import KaFooter from "./ka/KaFooter";
17 21
18 22 // MapLibre pèse ~700 kB : chargé uniquement quand on visite /carte
19 23 const MapPage = lazy(() => import("./pages/MapPage"));
20 24
25 +interface Me { name: string; email: string; picture: string; ka_id: string }
26 +
27 +/** Connexion KA ID (hub groupe-ka.com) — bouton ou profil connecté. */
28 +function KaAuth() {
29 + const [enabled, setEnabled] = useState(false);
30 + const [me, setMe] = useState<Me | null>(null);
31 +
32 + useEffect(() => {
33 + fetch("/api/auth/config")
34 + .then((r) => r.json())
35 + .then((c) => setEnabled(Boolean(c.ka)))
36 + .catch(() => {});
37 + fetch("/api/me")
38 + .then((r) => (r.ok ? r.json() : null))
39 + .then(setMe)
40 + .catch(() => {});
41 + }, []);
42 +
43 + const logout = () => {
44 + fetch("/api/auth/logout", { method: "POST" })
45 + .then(() => setMe(null))
46 + .catch(() => {});
47 + };
48 +
49 + if (!enabled) return null;
50 + if (me) {
51 + return (
52 + <span className="auth-user">
53 + {me.picture ? <img src={me.picture} alt="" referrerPolicy="no-referrer" /> : null}
54 + <span className="name">{me.name || me.email}</span>
55 + <button type="button" onClick={logout}>Déconnexion</button>
56 + </span>
57 + );
58 + }
59 + return (
60 + <a className="btn-ka" href="/api/auth/ka/login">
61 + Se connecter avec <b>KA</b>
62 + </a>
63 + );
64 +}
65 +
21 66 export default function App() {
22 67 return (
23 68 <>
24 69 <header className="site">
25 70 <div className="container">
26 71 <NavLink to="/" className="logo">Job<em>·</em>Ka</NavLink>
72 + <GroupeKaBadge dark />
27 73 <nav className="main">
28 74 <NavLink to="/" end className={({ isActive }) => (isActive ? "active" : "")}>Offres</NavLink>
29 75 <NavLink to="/carte" className={({ isActive }) => (isActive ? "active" : "")}>Carte</NavLink>
30 76 <NavLink to="/sources" className={({ isActive }) => (isActive ? "active" : "")}>Employeurs</NavLink>
31 − <NavLink to="/stats" className={({ isActive }) => (isActive ? "active" : "")}>Statistiques</NavLink>
77 + <NavLink to="/stats" className={({ isActive }) => (isActive ? "active" : "")}>Stats</NavLink>
78 + <NavLink to="/contact" className={({ isActive }) => (isActive ? "active" : "")}>Contact</NavLink>
32 79 </nav>
80 + <div className="auth-box">
81 + <KaAuth />
82 + </div>
33 83 </div>
34 84 </header>
35 85 <Routes>
@@ -42,19 +92,24 @@ export default function App() {
42 92 <Route path="/emploi/:uid" element={<JobPage />} />
43 93 <Route path="/sources" element={<Sources />} />
44 94 <Route path="/stats" element={<Stats />} />
95 + <Route path="/contact" element={<Contact />} />
45 96 <Route path="*" element={<div className="container empty"><h2>Page introuvable</h2></div>} />
46 97 </Routes>
47 − <footer className="site">
98 + <div className="prefooter">
48 99 <div className="container">
49 − <span>
50 − Une plateforme du <a href="https://www.groupe-ka.com">Groupe KA</a> —{" "}
51 − <a href="mailto:contact@spboucher.ai">contact@spboucher.ai</a>
52 − </span>
53 − <span>
54 − Chaque offre est traçable à sa source originale. Zéro boîte noire.
100 + <span className="baseline">
101 + <b>Job-Ka</b> — Tous les emplois des employeurs québécois, directement
102 + à la source. Chaque offre est traçable à sa source originale, zéro
103 + boîte noire.
55 104 </span>
105 + <NavLink to="/">Offres</NavLink>
106 + <NavLink to="/carte">Carte</NavLink>
107 + <NavLink to="/sources">Employeurs</NavLink>
108 + <NavLink to="/stats">Stats</NavLink>
109 + <NavLink to="/contact">Contact</NavLink>
56 110 </div>
57 − </footer>
111 + </div>
112 + <KaFooter siteId="job-ka" />
58 113 </>
59 114 );
60 115 }
added frontend/src/ka/GroupeKaBadge.tsx +21 −0
@@ -0,0 +1,21 @@
1 +// Auteur : Simon-Pierre Boucher — contact@spboucher.ai
2 +// ka-ui/react/GroupeKaBadge.tsx — badge « Un service Groupe KA », cliquable
3 +// vers le hub. À placer dans le header de chaque site (à côté du logo de la
4 +// marque). Variante dark pour les surfaces encre. Zone de protection : le
5 +// padding interne du badge suffit ; ne rien coller à moins de 8 px du badge.
6 +export default function GroupeKaBadge({ dark = false }: { dark?: boolean }) {
7 + return (
8 + <a
9 + className={`gk-badge${dark ? " gk-badge--dark" : ""}`}
10 + href="https://www.groupe-ka.com"
11 + target="_blank"
12 + rel="noopener noreferrer"
13 + aria-label="Un service Groupe KA — visiter le portail de l'écosystème"
14 + >
15 + Un service
16 + <b>
17 + Groupe<span className="ka">KA</span>
18 + </b>
19 + </a>
20 + );
21 +}
added frontend/src/ka/KaFooter.tsx +91 −0
@@ -0,0 +1,91 @@
1 +// Auteur : Simon-Pierre Boucher — contact@spboucher.ai
2 +// ka-ui/react/KaFooter.tsx — footer commun Groupe KA (fond encre), à vendorer
3 +// dans chaque app Vite/React sous frontend/src/ka/. Consomme ecosystem.json :
4 +// toute modification des infos de contact se fait dans ka-ui/ecosystem.json
5 +// puis se resynchronise sur les 12 sites (voir ka-ui/README.md).
6 +import eco from "./ecosystem.json";
7 +
8 +type LocalLink = { label: string; href: string };
9 +
10 +export default function KaFooter({
11 + siteId,
12 + localLegal = [],
13 +}: {
14 + /** id du site courant dans ecosystem.json (ex. "resto-ka") */
15 + siteId: string;
16 + /** pages légales PROPRES au site (ex. /conditions), affichées avant celles du hub */
17 + localLegal?: LocalLink[];
18 +}) {
19 + const year = new Date().getFullYear();
20 + const site = eco.sites.find((s) => s.id === siteId);
21 + const others = eco.sites.filter((s) => s.id !== siteId);
22 + return (
23 + <footer className="ka-footer" id="contact">
24 + <div className="container">
25 + <a
26 + className="wordmark"
27 + href={eco.hub.url}
28 + target={siteId === "groupe-ka" ? undefined : "_blank"}
29 + rel="noopener noreferrer"
30 + aria-label="Groupe KA — le portail de l'écosystème"
31 + >
32 + Groupe <span className="ka">KA</span>
33 + </a>
34 + <p className="desc">
35 + {eco.org.tagline} Des centaines de connecteurs lisent les sites à la
36 + source, normalisent la donnée et se resynchronisent seuls.{" "}
37 + {site ? (
38 + <>
39 + <b style={{ color: "var(--paper)" }}>{site.wordmark}</b> —{" "}
40 + {site.tagline} — est un service Groupe KA.
41 + </>
42 + ) : null}
43 + </p>
44 + <p className="notice">
45 + <b>{eco.org.disclaimer}</b>
46 + </p>
47 + <ul className="sites">
48 + {others.map((s) => (
49 + <li key={s.id}>
50 + <a href={`https://${s.domain}`} target="_blank" rel="noopener noreferrer">
51 + {s.wordmark}
52 + </a>
53 + </li>
54 + ))}
55 + {eco.extraFooterLinks.map((l) => (
56 + <li key={l.href}>
57 + <a href={l.href} target="_blank" rel="noopener noreferrer">
58 + {l.label}
59 + </a>
60 + </li>
61 + ))}
62 + </ul>
63 + <div className="contacts">
64 + {eco.contacts.map((c) => (
65 + <p key={c.email} style={{ margin: 0 }}>
66 + <a href={`mailto:${c.email}`}>{c.email}</a>
67 + <span>{c.role}</span>
68 + </p>
69 + ))}
70 + </div>
71 + <p className="legal">
72 + © {year} {eco.org.copyrightHolder}
73 + {localLegal.map((l) => (
74 + <span key={l.href}>
75 + {" · "}
76 + <a href={l.href}>{l.label}</a>
77 + </span>
78 + ))}
79 + {eco.legal.map((l) => (
80 + <span key={l.href}>
81 + {" · "}
82 + <a href={l.href} target="_blank" rel="noopener noreferrer">
83 + {l.label}
84 + </a>
85 + </span>
86 + ))}
87 + </p>
88 + </div>
89 + </footer>
90 + );
91 +}
added frontend/src/ka/ecosystem.json +196 −0
@@ -0,0 +1,196 @@
1 +{
2 + "org": {
3 + "name": "Groupe KA",
4 + "legalName": "Groupe KA — Simon-Pierre Boucher",
5 + "tagline": "Holding québécois d'agrégateurs de produits et services entièrement automatisés.",
6 + "disclaimer": "Groupe KA est un agrégateur de contenu : nous ne vendons rien, ne louons rien et ne sommes partie à aucune transaction.",
7 + "copyrightHolder": "Groupe KA — Simon-Pierre Boucher"
8 + },
9 + "hub": {
10 + "url": "https://www.groupe-ka.com",
11 + "loginPath": "/connexion",
12 + "signupNote": "La création de compte KA ID se fait sur le hub groupe-ka.com ; chaque site délègue sa connexion via /api/auth/ka/login."
13 + },
14 + "contacts": [
15 + {
16 + "email": "contact@groupe-ka.com",
17 + "role": "Projets, partenariats & données"
18 + },
19 + {
20 + "email": "info@groupe-ka.com",
21 + "role": "Médias & questions générales"
22 + },
23 + {
24 + "email": "admin@groupe-ka.com",
25 + "role": "Légal, vie privée & Loi 25"
26 + }
27 + ],
28 + "legal": [
29 + {
30 + "label": "Conditions d'utilisation",
31 + "href": "https://www.groupe-ka.com/conditions"
32 + },
33 + {
34 + "label": "Politique de confidentialité",
35 + "href": "https://www.groupe-ka.com/confidentialite"
36 + },
37 + {
38 + "label": "Protection des renseignements personnels (Loi 25)",
39 + "href": "https://www.groupe-ka.com/loi-25"
40 + },
41 + {
42 + "label": "Transparence des robots d'indexation",
43 + "href": "https://www.groupe-ka.com/bots"
44 + }
45 + ],
46 + "sites": [
47 + {
48 + "id": "groupe-ka",
49 + "wordmark": "Groupe KA",
50 + "domain": "www.groupe-ka.com",
51 + "accent": "#d9f26b",
52 + "accentSoft": "#f0f9d2",
53 + "accentDeep": "#123f2e",
54 + "onAccent": "#141814",
55 + "tagline": "Le portail de l'écosystème ·Ka"
56 + },
57 + {
58 + "id": "trouve-ka",
59 + "wordmark": "Trouve·Ka",
60 + "domain": "www.trouve-ka.com",
61 + "accent": "#1c7ed6",
62 + "accentSoft": "#e7f2fd",
63 + "accentDeep": "#14508f",
64 + "onAccent": "#ffffff",
65 + "tagline": "Le moteur de recherche du web québécois"
66 + },
67 + {
68 + "id": "lou-ka",
69 + "wordmark": "Lou·Ka",
70 + "domain": "www.lou-ka.com",
71 + "accent": "#ff6a00",
72 + "accentSoft": "#fff1e6",
73 + "accentDeep": "#cc5500",
74 + "onAccent": "#ffffff",
75 + "tagline": "Tous les logements à louer"
76 + },
77 + {
78 + "id": "immo-ka",
79 + "wordmark": "Immo·Ka",
80 + "domain": "www.immo-ka.com",
81 + "accent": "#e23744",
82 + "accentSoft": "#fbe0e2",
83 + "accentDeep": "#a8232e",
84 + "onAccent": "#ffffff",
85 + "tagline": "Toutes les propriétés à vendre"
86 + },
87 + {
88 + "id": "vrai-prix",
89 + "wordmark": "Vrai-Prix",
90 + "domain": "www.vrai-prix.com",
91 + "accent": "#ff5148",
92 + "accentSoft": "#ffe3e0",
93 + "accentDeep": "#9e2a25",
94 + "onAccent": "#ffffff",
95 + "tagline": "La valeur réelle de chaque propriété"
96 + },
97 + {
98 + "id": "auto-ka",
99 + "wordmark": "Auto·Ka",
100 + "domain": "www.auto-ka.com",
101 + "accent": "#ff5a2a",
102 + "accentSoft": "#ffe8de",
103 + "accentDeep": "#cc3f16",
104 + "onAccent": "#ffffff",
105 + "tagline": "Les voitures usagées du Québec"
106 + },
107 + {
108 + "id": "fabri-ka",
109 + "wordmark": "Fabri·Ka",
110 + "domain": "www.fabri-ka.com",
111 + "accent": "#c4532e",
112 + "accentSoft": "#f7e3da",
113 + "accentDeep": "#a94525",
114 + "onAccent": "#ffffff",
115 + "tagline": "Les produits fabriqués au Québec"
116 + },
117 + {
118 + "id": "food-ka",
119 + "wordmark": "Food·Ka",
120 + "domain": "www.food-ka.com",
121 + "accent": "#1f9d55",
122 + "accentSoft": "#e2f5ea",
123 + "accentDeep": "#157a40",
124 + "onAccent": "#ffffff",
125 + "tagline": "Les prix d'épicerie, suivis à la source"
126 + },
127 + {
128 + "id": "resto-ka",
129 + "wordmark": "Resto·Ka",
130 + "domain": "www.resto-ka.com",
131 + "accent": "#f08c00",
132 + "accentSoft": "#fdeed7",
133 + "accentDeep": "#b96a00",
134 + "onAccent": "#141814",
135 + "tagline": "Chaque resto, chaque plat, chaque prix"
136 + },
137 + {
138 + "id": "sorti-ka",
139 + "wordmark": "Sorti·Ka",
140 + "domain": "www.sorti-ka.com",
141 + "accent": "#d6336c",
142 + "accentSoft": "#fbe0eb",
143 + "accentDeep": "#a12551",
144 + "onAccent": "#ffffff",
145 + "tagline": "Toutes les sorties, dans les 17 régions"
146 + },
147 + {
148 + "id": "crea-ka",
149 + "wordmark": "Créa·Ka",
150 + "domain": "www.crea-ka.com",
151 + "accent": "#7048e8",
152 + "accentSoft": "#ece5fc",
153 + "accentDeep": "#5433b8",
154 + "onAccent": "#ffffff",
155 + "tagline": "Les créateurs d'ici, tous leurs liens"
156 + },
157 + {
158 + "id": "api-ka",
159 + "wordmark": "API·Ka",
160 + "domain": "www.api-ka.com",
161 + "accent": "#3b5bdb",
162 + "accentSoft": "#e4eafb",
163 + "accentDeep": "#2b44a8",
164 + "onAccent": "#ffffff",
165 + "tagline": "La donnée de l'écosystème, par API"
166 + },
167 + {
168 + "id": "job-ka",
169 + "wordmark": "Job·Ka",
170 + "domain": "www.job-ka.com",
171 + "accent": "#0c8599",
172 + "accentSoft": "#def0f4",
173 + "accentDeep": "#095c6b",
174 + "onAccent": "#ffffff",
175 + "tagline": "Tous les emplois des employeurs québécois"
176 + }
177 + ],
178 + "extraFooterLinks": [
179 + {
180 + "label": "ValoPlex",
181 + "href": "https://www.valoplex.com"
182 + },
183 + {
184 + "label": "Ka2",
185 + "href": "https://www.ka2.bot"
186 + },
187 + {
188 + "label": "Ka4",
189 + "href": "https://www.ka4.bot"
190 + },
191 + {
192 + "label": "Ka6",
193 + "href": "https://www.ka6.bot"
194 + }
195 + ]
196 +}
\ No newline at end of file
added frontend/src/ka/stats/SPEC.md +123 −0
@@ -0,0 +1,123 @@
1 +# ka-stats — module Stats commun Groupe KA (spec v1)
2 +
3 +Contrat partagé par les 12 plateformes pour leurs pages **/stats** (tableau de
4 +bord analytique) et l'**export PDF** estampillé Groupe-KA. Le visuel suit le
5 +design system ka-ui (tokens.css) avec l'accent de la marque.
6 +
7 +## 1. Page /stats — structure obligatoire (dans cet ordre)
8 +
9 +1. **Bandeau KPI** : 4–6 grandes cartes (`KpiCard`) — valeur, libellé,
10 + variation vs période précédente (▲/▼ + %, vert `--green` / rouge `--danger`).
11 +2. **Sélecteur de période global** (`PeriodSelector`) : `aujourd'hui · 7 j ·
12 + 30 j · 3 m · 6 m · 12 m · année en cours · tout` + plage personnalisée
13 + (2 champs date). Toute la page se recalcule (state → refetch dashboard).
14 +3. **Graphiques** : courbes d'évolution (`LineChart`, survol = infobulle,
15 + légende cliquable pour masquer une série, comparaison N vs N-1 en
16 + pointillé), barres (`BarChart`), anneaux (`Donut`), calendrier de chaleur
17 + (`CalendarHeatmap`) quand pertinent.
18 +4. **Répartition géographique** (par ville/région) quand pertinent — barres
19 + horizontales triées (pas besoin de vraie carte).
20 +5. **Tableaux détaillés** (`DataTable`) : tri par colonne, recherche interne,
21 + pagination (25/pg), débordement horizontal propre sur mobile (.tbl-wrap).
22 +6. **Records & faits marquants** : générés depuis les données (jour record,
23 + plus forte croissance, meilleure entrée…) — cartes compactes.
24 +7. **Fraîcheur** : « Mis à jour le {date heure} » + bouton Rafraîchir.
25 +8. **Bouton PDF** bien visible en haut : « Télécharger le rapport PDF » avec
26 + deux choix (Rapport complet / Synthèse 2 pages). Indicateur de progression
27 + si > 2 s.
28 +
29 +Responsive : KPI empilés < 768 px, graphiques pleine largeur redimensionnés
30 +(SVG viewBox), tableaux en défilement horizontal contenu, tactile ≥ 44 px.
31 +AUCUNE donnée inventée : une stat indisponible = bloc « Pas encore mesuré »
32 +(carte grise propre), jamais un faux chiffre.
33 +
34 +## 2. API — contrat commun
35 +
36 +`GET /api/stats/dashboard?period=7j|30j|3m|6m|12m|annee|tout|auj&from=YYYY-MM-DD&to=YYYY-MM-DD`
37 +
38 +```jsonc
39 +{
40 + "updated": "2026-08-17T21:04:00-04:00",
41 + "period": { "from": "2026-07-18", "to": "2026-08-17", "label": "30 jours" },
42 + "kpis": [ { "id": "total", "label": "Annonces actives", "value": 33744,
43 + "unit": "", "delta_pct": 4.2, "direction": "up" } ],
44 + "series": [ { "id": "vol", "title": "Annonces actives par jour", "unit": "annonces",
45 + "kind": "line", "points": [{ "t": "2026-07-18", "v": 31200 }],
46 + "compare": [{ "t": "2025-07-18", "v": 24100 }] } ],
47 + "breakdowns": [ { "id": "types", "title": "Par type", "kind": "donut",
48 + "items": [{ "label": "4½", "value": 9120 }] } ],
49 + "geo": { "title": "Par région", "items": [{ "label": "Montréal", "value": 15680 }] },
50 + "heatmap": { "title": "Activité", "cells": [{ "date": "2026-08-01", "value": 210 }] },
51 + "tables": [ { "id": "top", "title": "Top villes", "columns": ["Ville", "Annonces", "Δ 30 j"],
52 + "rows": [["Montréal", 15680, "+3,1 %"]] } ],
53 + "records": [ { "label": "Jour record d'ajouts", "value": "412 annonces", "date": "2026-08-09" } ]
54 +}
55 +```
56 +
57 +Champs absents = section masquée. Cache serveur recommandé (≥ 5 min par
58 +période). Les valeurs proviennent des données réelles (DB de la plateforme,
59 +journaux de sync des connecteurs, /api/v1/runs d'API-KA…).
60 +
61 +`GET /api/stats/report?period=…&from=&to=&mode=complet|synthese`
62 +→ `application/pdf`, en-tête `Content-Disposition: attachment; filename=
63 +groupe-ka_<plateforme>_stats_<periode>_<YYYY-MM-DD>.pdf`.
64 +
65 +## 3. PDF — gabarit Groupe-KA (implémentations : `kapdf.py` fpdf2 pour les
66 +apps Python ; les apps Next portent le même gabarit en pdfkit)
67 +
68 +- **Couverture** : cadre encre, kicker « GROUPE KA · RAPPORT STATISTIQUE »,
69 + wordmark de la plateforme (boîte encre + accent), sous-titre, période
70 + couverte, date/heure de génération, bande encre au pied avec
71 + « par Groupe KA — groupe-ka.com ».
72 +- **Sommaire** avec numéros de pages (mode complet).
73 +- **KPI** : grille de cartes (bordure encre, valeur en gros, delta coloré).
74 +- **Graphiques VECTORIELS** (dessinés en primitives, jamais de capture) :
75 + courbes, barres, anneaux — accent de la plateforme, axes/graduations encre.
76 +- **Tableaux** paginés proprement (lignes zébrées `--surface-2`, jamais
77 + coupés en deux à cheval sur une ligne).
78 +- **Records** puis **page de fin** : coordonnées Groupe KA (3 courriels +
79 + rôles d'ecosystem.json, groupe-ka.com), avertissement d'agrégateur,
80 + mentions légales courtes.
81 +- **Chaque page** : en-tête discret (« Groupe KA · {Plateforme} », filet
82 + encre) + pied (« © Groupe-KA — {année} — groupe-ka.com · {période} · p. X/Y »).
83 +- A4 portrait, marges 18 mm, typo : Helvetica (fallback sûr) ou fonts TTF du
84 + DS si présentes. Mode « synthese » = couverture + 1 page KPI/records.
85 +
86 +## 4. Spécifique par plateforme (sections métier attendues)
87 +
88 +- **groupe-ka** : tableau de bord maître — consolidation des 12 (volume total,
89 + croissance), classement des plateformes, bloc résumé par plateforme + lien
90 + vers sa page /stats ; « Rapport écosystème complet » = PDF consolidé.
91 +- **lou-ka** : annonces actives/nouvelles/retirées, loyers moyens/médians par
92 + ville & taille, évolution, répartition par type, top villes.
93 +- **immo-ka** : annonces actives/nouvelles/vendues-retirées, prix moyen/médian
94 + par ville/région/type, délai de présence, top villes, tension du marché.
95 +- **vrai-prix** : couverture du rôle (unités, valeur totale), estimations
96 + servies si journalisées, répartitions par municipalité/type, indices marché.
97 +- **auto-ka** : volume par marque/modèle/année/carburant/boîte, prix moyens et
98 + km moyens par segment, top marques/modèles.
99 +- **fabri-ka** : produits par catégorie/région/boutique, fourchettes de prix,
100 + nouveautés par période, top catégories.
101 +- **food-ka** : produits suivis, relevés de prix, soldes détectés (baisses/
102 + hausses, amplitude), top produits en solde, prix moyens par catégorie.
103 +- **resto-ka** : restos par cuisine/ville/gamme, menus & plats, nouveautés/
104 + fermetures détectées, top établissements.
105 +- **sorti-ka** : événements à venir/passés par catégorie/ville, gratuits vs
106 + payants, heatmap calendrier, top lieux.
107 +- **crea-ka** : créateurs par plateforme/niche/tier, comptes reliés, top
108 + créateurs, croissance du répertoire.
109 +- **trouve-ka** : pages indexées, domaines, rythme de crawl (indexées/h),
110 + erreurs, file frontier, tendances si les requêtes sont journalisées.
111 +- **api-ka** : appels par endpoint/jour/heure, latences moyennes + p95, taux
112 + d'erreur, top endpoints, uptime (données des middlewares de logging + runs).
113 +- **Transverse (tous)** : volume total agrégé + croissance, connecteurs actifs
114 + et éléments ajoutés/mis à jour par période (journaux de sync), complétude/
115 + fraîcheur moyenne des fiches quand mesurable. Trafic web : seulement si des
116 + journaux d'accès existent — sinon état vide propre.
117 +
118 +## 5. Ajouter une métrique / un graphique / une plateforme
119 +
120 +1 métrique = 1 entrée `kpis[]` ou `series[]` côté API (requête SQL agrégée +
121 +cache) — le front la rend automatiquement. 1 plateforme = implémenter les 2
122 +endpoints du contrat + une page /stats montée sur les composants du kit +
123 +`kapdf.py` (ou gabarit pdfkit) branché sur le même JSON de dashboard.
added frontend/src/ka/stats/kacharts.tsx +389 −0
@@ -0,0 +1,389 @@
1 +// Auteur : Simon-Pierre Boucher — contact@spboucher.ai
2 +// ka-ui/stats/kacharts.tsx — kit de graphiques SVG du module Stats commun
3 +// Groupe KA (zéro dépendance, React 18+). Style : design system ka-ui
4 +// (bordures encre, accent de la plateforme via var(--accent)).
5 +// Composants : KpiCard, PeriodSelector, LineChart (infobulle + légende
6 +// cliquable + comparaison N-1), BarChart, Donut, CalendarHeatmap, DataTable
7 +// (tri/recherche/pagination), RecordCard, PdfButton, EmptyBlock, Fraicheur.
8 +import { useMemo, useState } from "react";
9 +
10 +/* ---------- types (contrat SPEC.md) ---------- */
11 +export type Kpi = {
12 + id: string; label: string; value: number | string; unit?: string;
13 + delta_pct?: number | null; direction?: "up" | "down";
14 +};
15 +export type Point = { t: string; v: number };
16 +export type Serie = {
17 + id: string; title: string; unit?: string; kind?: "line" | "bar";
18 + points: Point[]; compare?: Point[];
19 +};
20 +export type BreakItem = { label: string; value: number };
21 +export type TableSpec = { id: string; title: string; columns: string[]; rows: (string | number)[][] };
22 +export type RecordFact = { label: string; value: string; date?: string };
23 +
24 +export const PERIODS: { id: string; label: string }[] = [
25 + { id: "auj", label: "Aujourd'hui" },
26 + { id: "7j", label: "7 jours" },
27 + { id: "30j", label: "30 jours" },
28 + { id: "3m", label: "3 mois" },
29 + { id: "6m", label: "6 mois" },
30 + { id: "12m", label: "12 mois" },
31 + { id: "annee", label: "Année en cours" },
32 + { id: "tout", label: "Tout" },
33 +];
34 +
35 +export const fmtInt = (n: number) => n.toLocaleString("fr-CA");
36 +export const fmtNum = (n: number) =>
37 + Number.isInteger(n) ? fmtInt(n) : n.toLocaleString("fr-CA", { maximumFractionDigits: 2 });
38 +
39 +/* ---------- KPI ---------- */
40 +export function KpiCard({ k }: { k: Kpi }) {
41 + const up = (k.direction ?? ((k.delta_pct ?? 0) >= 0 ? "up" : "down")) === "up";
42 + return (
43 + <article className="card" style={{ padding: "14px 16px", minWidth: 0 }}>
44 + <p style={{ margin: 0, fontFamily: "var(--font-display)", fontWeight: 700, fontSize: "clamp(22px,2.4vw,30px)", letterSpacing: "-0.02em" }}>
45 + {typeof k.value === "number" ? fmtNum(k.value) : k.value}
46 + {k.unit ? <span style={{ fontSize: "0.6em", color: "var(--ink-2)" }}> {k.unit}</span> : null}
47 + </p>
48 + <p className="klabel" style={{ margin: "6px 0 0" }}>{k.label}</p>
49 + {k.delta_pct !== undefined && k.delta_pct !== null && (
50 + <p style={{ margin: "8px 0 0", fontFamily: "var(--font-mono)", fontSize: 11, fontWeight: 700, color: up ? "var(--green)" : "var(--danger)" }}>
51 + {up ? "▲" : "▼"} {k.delta_pct >= 0 ? "+" : ""}{fmtNum(k.delta_pct)} % <span style={{ color: "var(--ink-3)", fontWeight: 500 }}>vs période préc.</span>
52 + </p>
53 + )}
54 + </article>
55 + );
56 +}
57 +
58 +/* ---------- Sélecteur de période ---------- */
59 +export function PeriodSelector({
60 + value, onChange, custom, onCustom,
61 +}: {
62 + value: string; onChange: (p: string) => void;
63 + custom?: { from: string; to: string }; onCustom?: (from: string, to: string) => void;
64 +}) {
65 + return (
66 + <div style={{ display: "flex", flexWrap: "wrap", gap: 8, alignItems: "center" }}>
67 + {PERIODS.map((p) => (
68 + <button key={p.id} type="button" onClick={() => onChange(p.id)}
69 + className="chip" aria-pressed={value === p.id}
70 + style={{ cursor: "pointer", minHeight: 44, background: value === p.id ? "var(--accent)" : "var(--surface)", color: value === p.id ? "var(--on-accent)" : "var(--ink)" }}>
71 + {p.label}
72 + </button>
73 + ))}
74 + {onCustom && (
75 + <span style={{ display: "inline-flex", gap: 6, alignItems: "center" }}>
76 + <input className="input" type="date" style={{ width: 150 }} value={custom?.from ?? ""} aria-label="Du"
77 + onChange={(e) => onCustom(e.target.value, custom?.to ?? "")} />
78 + <span className="klabel">au</span>
79 + <input className="input" type="date" style={{ width: 150 }} value={custom?.to ?? ""} aria-label="Au"
80 + onChange={(e) => onCustom(custom?.from ?? "", e.target.value)} />
81 + </span>
82 + )}
83 + </div>
84 + );
85 +}
86 +
87 +/* ---------- Courbe ---------- */
88 +export function LineChart({ serie, height = 240 }: { serie: Serie; height?: number }) {
89 + const [hide, setHide] = useState<{ cur: boolean; cmp: boolean }>({ cur: false, cmp: false });
90 + const [hover, setHover] = useState<number | null>(null);
91 + const W = 720, H = height, PL = 54, PR = 10, PT = 14, PB = 26;
92 + const pts = serie.points ?? [];
93 + if (pts.length < 2) return <EmptyBlock title={serie.title} />;
94 + const all = [...(hide.cur ? [] : pts), ...(!hide.cmp && serie.compare ? serie.compare : [])];
95 + const vmax = Math.max(...all.map((p) => p.v), 1);
96 + const vmin = Math.min(0, ...all.map((p) => p.v));
97 + const X = (i: number, n: number) => PL + ((W - PL - PR) * i) / (n - 1);
98 + const Y = (v: number) => PT + (H - PT - PB) * (1 - (v - vmin) / (vmax - vmin || 1));
99 + const path = (s: Point[]) => s.map((p, i) => `${i ? "L" : "M"}${X(i, s.length)},${Y(p.v)}`).join("");
100 + const hi = hover !== null ? Math.min(pts.length - 1, Math.max(0, hover)) : null;
101 + return (
102 + <figure className="card" style={{ margin: 0, padding: 16 }}>
103 + <figcaption style={{ display: "flex", justifyContent: "space-between", flexWrap: "wrap", gap: 8 }}>
104 + <b style={{ fontFamily: "var(--font-display)", fontSize: 15 }}>{serie.title}</b>
105 + <span style={{ display: "flex", gap: 10 }}>
106 + <LegendChip label="Période courante" color="var(--accent)" off={hide.cur} onClick={() => setHide((h) => ({ ...h, cur: !h.cur }))} />
107 + {serie.compare && <LegendChip label="Période comparée" color="var(--ink-3)" dashed off={hide.cmp} onClick={() => setHide((h) => ({ ...h, cmp: !h.cmp }))} />}
108 + </span>
109 + </figcaption>
110 + <svg viewBox={`0 0 ${W} ${H}`} style={{ width: "100%", height: "auto", marginTop: 10, touchAction: "pan-y" }} role="img" aria-label={serie.title}
111 + onMouseMove={(e) => {
112 + const r = (e.currentTarget as SVGSVGElement).getBoundingClientRect();
113 + const fx = ((e.clientX - r.left) / r.width) * W;
114 + setHover(Math.round(((fx - PL) / (W - PL - PR)) * (pts.length - 1)));
115 + }}
116 + onMouseLeave={() => setHover(null)}>
117 + {[0, 1, 2, 3, 4].map((g) => {
118 + const y = PT + ((H - PT - PB) * g) / 4;
119 + const v = vmax - ((vmax - vmin) * g) / 4;
120 + return (
121 + <g key={g}>
122 + <line x1={PL} x2={W - PR} y1={y} y2={y} stroke="var(--line)" strokeWidth={1} />
123 + <text x={PL - 6} y={y + 3} textAnchor="end" fontSize={10} fill="var(--ink-3)" fontFamily="var(--font-mono)">{fmtInt(Math.round(v))}</text>
124 + </g>
125 + );
126 + })}
127 + {[0, Math.floor(pts.length / 2), pts.length - 1].map((i) => (
128 + <text key={i} x={X(i, pts.length)} y={H - 8} textAnchor="middle" fontSize={10} fill="var(--ink-3)" fontFamily="var(--font-mono)">{pts[i].t}</text>
129 + ))}
130 + {!hide.cmp && serie.compare && serie.compare.length > 1 && (
131 + <path d={path(serie.compare)} fill="none" stroke="var(--ink-3)" strokeWidth={1.4} strokeDasharray="4 4" />
132 + )}
133 + {!hide.cur && <path d={path(pts)} fill="none" stroke="var(--accent)" strokeWidth={2.4} />}
134 + {hi !== null && (
135 + <g>
136 + <line x1={X(hi, pts.length)} x2={X(hi, pts.length)} y1={PT} y2={H - PB} stroke="var(--ink)" strokeWidth={1} strokeDasharray="2 3" />
137 + <circle cx={X(hi, pts.length)} cy={Y(pts[hi].v)} r={4} fill="var(--accent)" stroke="var(--ink)" strokeWidth={1.5} />
138 + </g>
139 + )}
140 + </svg>
141 + {hi !== null && (
142 + <p className="chip" style={{ marginTop: 8 }}>
143 + {pts[hi].t} — <b>{fmtNum(pts[hi].v)}{serie.unit ? ` ${serie.unit}` : ""}</b>
144 + {serie.compare?.[hi] && !hide.cmp ? <span style={{ color: "var(--ink-3)" }}> · N-1 : {fmtNum(serie.compare[hi].v)}</span> : null}
145 + </p>
146 + )}
147 + </figure>
148 + );
149 +}
150 +
151 +function LegendChip({ label, color, off, dashed, onClick }: { label: string; color: string; off: boolean; dashed?: boolean; onClick: () => void }) {
152 + return (
153 + <button type="button" onClick={onClick} aria-pressed={!off}
154 + style={{ display: "inline-flex", alignItems: "center", gap: 6, border: 0, background: "none", cursor: "pointer", opacity: off ? 0.4 : 1, fontFamily: "var(--font-mono)", fontSize: 10.5, fontWeight: 700, textTransform: "uppercase", letterSpacing: "0.06em", minHeight: 44 }}>
155 + <span style={{ width: 18, height: 0, borderTop: `3px ${dashed ? "dashed" : "solid"} ${color}` }} />
156 + {label}
157 + </button>
158 + );
159 +}
160 +
161 +/* ---------- Barres horizontales (répartitions, géo) ---------- */
162 +export function BarChart({ title, items, unit }: { title: string; items: BreakItem[]; unit?: string }) {
163 + const rows = (items ?? []).slice(0, 14);
164 + if (!rows.length) return <EmptyBlock title={title} />;
165 + const max = Math.max(...rows.map((r) => r.value), 1);
166 + return (
167 + <figure className="card" style={{ margin: 0, padding: 16 }}>
168 + <figcaption><b style={{ fontFamily: "var(--font-display)", fontSize: 15 }}>{title}</b></figcaption>
169 + <div style={{ marginTop: 12, display: "grid", gap: 9 }}>
170 + {rows.map((r) => (
171 + <div key={r.label} title={`${r.label} — ${fmtNum(r.value)}${unit ? ` ${unit}` : ""}`}>
172 + <div style={{ display: "flex", justifyContent: "space-between", fontSize: 12.5 }}>
173 + <span style={{ overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{r.label}</span>
174 + <b style={{ fontFamily: "var(--font-mono)", fontSize: 11.5 }}>{fmtNum(r.value)}{unit ? ` ${unit}` : ""}</b>
175 + </div>
176 + <div style={{ marginTop: 3, height: 12, background: "rgba(20,24,20,0.06)", borderRadius: "0 3px 3px 0" }}>
177 + <div style={{ height: "100%", width: `${Math.max((r.value / max) * 100, 1)}%`, background: "var(--accent)", border: "1px solid var(--ink)", borderRadius: "0 3px 3px 0", boxSizing: "border-box" }} />
178 + </div>
179 + </div>
180 + ))}
181 + </div>
182 + </figure>
183 + );
184 +}
185 +
186 +/* ---------- Anneau ---------- */
187 +export function Donut({ title, items }: { title: string; items: BreakItem[] }) {
188 + const rows = (items ?? []).filter((i) => i.value > 0).slice(0, 8);
189 + const total = rows.reduce((s, r) => s + r.value, 0);
190 + if (!total) return <EmptyBlock title={title} />;
191 + const R = 74, C = 2 * Math.PI * R;
192 + let acc = 0;
193 + const shades = [1, 0.78, 0.58, 0.42, 0.3, 0.22, 0.15, 0.1];
194 + return (
195 + <figure className="card" style={{ margin: 0, padding: 16 }}>
196 + <figcaption><b style={{ fontFamily: "var(--font-display)", fontSize: 15 }}>{title}</b></figcaption>
197 + <div style={{ display: "flex", flexWrap: "wrap", gap: 18, alignItems: "center", marginTop: 12 }}>
198 + <svg viewBox="0 0 200 200" style={{ width: 180, maxWidth: "100%" }} role="img" aria-label={title}>
199 + {rows.map((r, i) => {
200 + const frac = r.value / total;
201 + const off = acc; acc += frac;
202 + return (
203 + <circle key={r.label} cx={100} cy={100} r={R} fill="none"
204 + stroke="var(--accent)" strokeOpacity={shades[i % shades.length]}
205 + strokeWidth={30} strokeDasharray={`${frac * C} ${C}`} strokeDashoffset={-off * C}
206 + transform="rotate(-90 100 100)">
207 + <title>{`${r.label} — ${fmtNum(r.value)} (${((100 * r.value) / total).toFixed(1)} %)`}</title>
208 + </circle>
209 + );
210 + })}
211 + <circle cx={100} cy={100} r={R} fill="none" stroke="var(--ink)" strokeWidth={1} opacity={0.5} />
212 + </svg>
213 + <ul style={{ listStyle: "none", margin: 0, padding: 0, display: "grid", gap: 6, minWidth: 200, flex: 1 }}>
214 + {rows.map((r, i) => (
215 + <li key={r.label} style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 12.5 }}>
216 + <span style={{ width: 11, height: 11, borderRadius: 3, border: "1px solid var(--ink)", background: "var(--accent)", opacity: shades[i % shades.length] }} />
217 + <span style={{ flex: 1, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{r.label}</span>
218 + <b style={{ fontFamily: "var(--font-mono)", fontSize: 11 }}>{((100 * r.value) / total).toFixed(1)} %</b>
219 + </li>
220 + ))}
221 + </ul>
222 + </div>
223 + </figure>
224 + );
225 +}
226 +
227 +/* ---------- Calendrier de chaleur ---------- */
228 +export function CalendarHeatmap({ title, cells }: { title: string; cells: { date: string; value: number }[] }) {
229 + if (!cells?.length) return <EmptyBlock title={title} />;
230 + const byDate = new Map(cells.map((c) => [c.date, c.value]));
231 + const dates = cells.map((c) => c.date).sort();
232 + const end = new Date(dates[dates.length - 1] + "T12:00:00");
233 + const max = Math.max(...cells.map((c) => c.value), 1);
234 + const weeks = 26, cols: { date: string; v: number }[][] = [];
235 + const cur = new Date(end);
236 + cur.setDate(cur.getDate() - (weeks * 7 - 1));
237 + for (let w = 0; w < weeks; w++) {
238 + const col: { date: string; v: number }[] = [];
239 + for (let d = 0; d < 7; d++) {
240 + const iso = cur.toISOString().slice(0, 10);
241 + col.push({ date: iso, v: byDate.get(iso) ?? 0 });
242 + cur.setDate(cur.getDate() + 1);
243 + }
244 + cols.push(col);
245 + }
246 + return (
247 + <figure className="card" style={{ margin: 0, padding: 16 }}>
248 + <figcaption><b style={{ fontFamily: "var(--font-display)", fontSize: 15 }}>{title}</b> <span className="klabel">26 dernières semaines</span></figcaption>
249 + <div className="tbl-wrap" style={{ marginTop: 12 }}>
250 + <svg viewBox={`0 0 ${weeks * 14} ${7 * 14}`} style={{ minWidth: 480, width: "100%", height: "auto" }} role="img" aria-label={title}>
251 + {cols.map((col, w) => col.map((c, d) => (
252 + <rect key={c.date} x={w * 14} y={d * 14} width={12} height={12} rx={2.5}
253 + fill={c.v ? "var(--accent)" : "rgba(20,24,20,0.07)"} fillOpacity={c.v ? 0.25 + 0.75 * (c.v / max) : 1}
254 + stroke="rgba(20,24,20,0.15)" strokeWidth={0.5}>
255 + <title>{`${c.date} — ${fmtNum(c.v)}`}</title>
256 + </rect>
257 + )))}
258 + </svg>
259 + </div>
260 + </figure>
261 + );
262 +}
263 +
264 +/* ---------- Tableau : tri, recherche, pagination ---------- */
265 +export function DataTable({ spec, pageSize = 25 }: { spec: TableSpec; pageSize?: number }) {
266 + const [q, setQ] = useState("");
267 + const [sort, setSort] = useState<{ col: number; dir: 1 | -1 } | null>(null);
268 + const [page, setPage] = useState(0);
269 + const rows = useMemo(() => {
270 + let r = spec.rows ?? [];
271 + if (q) r = r.filter((row) => row.some((c) => String(c).toLowerCase().includes(q.toLowerCase())));
272 + if (sort) r = [...r].sort((a, b) => {
273 + const x = a[sort.col], y = b[sort.col];
274 + const nx = typeof x === "number" ? x : parseFloat(String(x).replace(/[^\d.,-]/g, "").replace(",", "."));
275 + const ny = typeof y === "number" ? y : parseFloat(String(y).replace(/[^\d.,-]/g, "").replace(",", "."));
276 + if (!Number.isNaN(nx) && !Number.isNaN(ny)) return (nx - ny) * sort.dir;
277 + return String(x).localeCompare(String(y), "fr") * sort.dir;
278 + });
279 + return r;
280 + }, [spec.rows, q, sort]);
281 + const pages = Math.max(1, Math.ceil(rows.length / pageSize));
282 + const cur = Math.min(page, pages - 1);
283 + return (
284 + <section className="card" style={{ padding: 16 }}>
285 + <div style={{ display: "flex", flexWrap: "wrap", gap: 10, justifyContent: "space-between", alignItems: "center" }}>
286 + <b style={{ fontFamily: "var(--font-display)", fontSize: 15 }}>{spec.title}</b>
287 + <input className="input" style={{ maxWidth: 240 }} placeholder="Rechercher…" value={q}
288 + onChange={(e) => { setQ(e.target.value); setPage(0); }} aria-label={`Rechercher dans ${spec.title}`} />
289 + </div>
290 + <div className="tbl-wrap" style={{ marginTop: 10 }}>
291 + <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 13 }}>
292 + <thead>
293 + <tr>
294 + {spec.columns.map((c, i) => (
295 + <th key={c} onClick={() => setSort((s) => ({ col: i, dir: s?.col === i && s.dir === 1 ? -1 : 1 }))}
296 + style={{ cursor: "pointer", textAlign: "left", padding: "8px 10px", background: "var(--ink)", color: "var(--paper)", fontFamily: "var(--font-mono)", fontSize: 10.5, textTransform: "uppercase", letterSpacing: "0.06em", whiteSpace: "nowrap", userSelect: "none" }}
297 + aria-sort={sort?.col === i ? (sort.dir === 1 ? "ascending" : "descending") : "none"}>
298 + {c} {sort?.col === i ? (sort.dir === 1 ? "▲" : "▼") : "↕"}
299 + </th>
300 + ))}
301 + </tr>
302 + </thead>
303 + <tbody>
304 + {rows.slice(cur * pageSize, (cur + 1) * pageSize).map((row, ri) => (
305 + <tr key={ri} style={{ background: ri % 2 ? "var(--surface-2)" : "var(--surface)" }}>
306 + {row.map((c, ci) => (
307 + <td key={ci} style={{ padding: "7px 10px", borderBottom: "1px solid var(--line)", whiteSpace: "nowrap" }}>
308 + {typeof c === "number" ? fmtNum(c) : c}
309 + </td>
310 + ))}
311 + </tr>
312 + ))}
313 + </tbody>
314 + </table>
315 + </div>
316 + <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginTop: 10, flexWrap: "wrap", gap: 8 }}>
317 + <span className="klabel">{fmtInt(rows.length)} lignes</span>
318 + <span style={{ display: "flex", gap: 6 }}>
319 + <button type="button" className="btn btn-ghost" disabled={cur === 0} onClick={() => setPage(cur - 1)}>←</button>
320 + <span className="chip">{cur + 1} / {pages}</span>
321 + <button type="button" className="btn btn-ghost" disabled={cur >= pages - 1} onClick={() => setPage(cur + 1)}>→</button>
322 + </span>
323 + </div>
324 + </section>
325 + );
326 +}
327 +
328 +/* ---------- Records / faits marquants ---------- */
329 +export function RecordCard({ r }: { r: RecordFact }) {
330 + return (
331 + <article className="card" style={{ padding: "12px 16px", display: "flex", justifyContent: "space-between", gap: 12, alignItems: "baseline", background: "var(--surface-2)" }}>
332 + <span style={{ fontSize: 13, color: "var(--ink-2)" }}>{r.label}</span>
333 + <span style={{ textAlign: "right" }}>
334 + <b style={{ fontFamily: "var(--font-display)", fontSize: 15 }}>{r.value}</b>
335 + {r.date && <span className="klabel" style={{ display: "block" }}>{r.date}</span>}
336 + </span>
337 + </article>
338 + );
339 +}
340 +
341 +/* ---------- Bouton PDF ---------- */
342 +export function PdfButton({ period, from, to, endpoint = "/api/stats/report" }: { period: string; from?: string; to?: string; endpoint?: string }) {
343 + const [busy, setBusy] = useState(false);
344 + const url = (mode: string) => {
345 + const p = new URLSearchParams({ period, mode });
346 + if (from) p.set("from", from);
347 + if (to) p.set("to", to);
348 + return `${endpoint}?${p}`;
349 + };
350 + const dl = (mode: string) => {
351 + setBusy(true);
352 + const a = document.createElement("a");
353 + a.href = url(mode);
354 + a.download = "";
355 + document.body.appendChild(a);
356 + a.click();
357 + a.remove();
358 + setTimeout(() => setBusy(false), 2500);
359 + };
360 + return (
361 + <span style={{ display: "inline-flex", gap: 8, flexWrap: "wrap" }}>
362 + <button type="button" className="btn btn-primary" onClick={() => dl("complet")} disabled={busy}>
363 + {busy ? "Génération…" : "⬇ Télécharger le rapport PDF"}
364 + </button>
365 + <button type="button" className="btn btn-ghost" onClick={() => dl("synthese")} disabled={busy}>
366 + Synthèse (2 p.)
367 + </button>
368 + </span>
369 + );
370 +}
371 +
372 +/* ---------- États ---------- */
373 +export function EmptyBlock({ title }: { title: string }) {
374 + return (
375 + <div className="card" style={{ padding: 20, background: "var(--surface-2)", borderStyle: "dashed" }}>
376 + <b style={{ fontFamily: "var(--font-display)", fontSize: 14 }}>{title}</b>
377 + <p className="klabel" style={{ margin: "6px 0 0" }}>Pas encore mesuré — aucune donnée disponible pour cette période.</p>
378 + </div>
379 + );
380 +}
381 +
382 +export function Fraicheur({ updated, onRefresh }: { updated: string; onRefresh: () => void }) {
383 + return (
384 + <p style={{ display: "flex", gap: 10, alignItems: "center", flexWrap: "wrap", margin: 0 }}>
385 + <span className="klabel">Mis à jour le {new Date(updated).toLocaleString("fr-CA", { dateStyle: "medium", timeStyle: "short" })}</span>
386 + <button type="button" className="btn btn-ghost" onClick={onRefresh}>↻ Rafraîchir</button>
387 + </p>
388 + );
389 +}
added frontend/src/ka/stats/kapdf.py +560 −0
@@ -0,0 +1,560 @@
1 +# Auteur : Simon-Pierre Boucher — contact@spboucher.ai
2 +# ka-ui/stats/kapdf.py — moteur PDF commun Groupe KA (fpdf2).
3 +# Consomme le JSON du contrat /api/stats/dashboard (voir SPEC.md) et produit
4 +# le rapport estampillé Groupe-KA : couverture, sommaire, KPI, graphiques
5 +# VECTORIELS (courbes/barres/anneaux), tableaux paginés, records, page de fin.
6 +# Usage :
7 +# from kapdf import GroupeKAReport
8 +# pdf_bytes = GroupeKAReport(site={"wordmark":"Lou·Ka","accent":"#ff6a00",
9 +# "domain":"www.lou-ka.com","tagline":"…"}, dashboard=dash_json,
10 +# mode="complet").build()
11 +# Dépendance : pip install fpdf2 (aucune autre)
12 +from __future__ import annotations
13 +
14 +import math
15 +from datetime import datetime
16 +from zoneinfo import ZoneInfo
17 +
18 +from fpdf import FPDF
19 +
20 +INK = (20, 24, 20)
21 +INK2 = (77, 85, 81)
22 +INK3 = (139, 146, 140)
23 +PAPER = (245, 243, 238)
24 +SURFACE2 = (250, 249, 245)
25 +GREEN = (28, 92, 65)
26 +DANGER = (179, 66, 58)
27 +WHITE = (255, 255, 255)
28 +
29 +EMAILS = [
30 + ("contact@groupe-ka.com", "Projets, partenariats & données"),
31 + ("info@groupe-ka.com", "Médias & questions générales"),
32 + ("admin@groupe-ka.com", "Légal, vie privée & Loi 25"),
33 +]
34 +DISCLAIMER = (
35 + "Groupe KA est un agrégateur de contenu : nous ne vendons rien, ne louons "
36 + "rien et ne sommes partie à aucune transaction. Données lues à la source, "
37 + "rien d'inventé, tout est traçable."
38 +)
39 +
40 +
41 +def _hex(c: str) -> tuple[int, int, int]:
42 + c = c.lstrip("#")
43 + return tuple(int(c[i : i + 2], 16) for i in (0, 2, 4)) # type: ignore
44 +
45 +
46 +def _fr(n) -> str:
47 + if isinstance(n, float) and not n.is_integer():
48 + return f"{n:,.2f}".replace(",", " ").replace(".", ",")
49 + return f"{int(n):,}".replace(",", " ")
50 +
51 +
52 +_SUBST = {
53 + "—": "-", "–": "-", "→": "->", "▲": "+", "▼": "-",
54 + "…": "...", "’": "'", "‘": "'", "“": '"', "”": '"',
55 + "œ": "oe", "Œ": "OE", "−": "-", " ": " ", " ": " ",
56 +}
57 +
58 +
59 +def _latin1(s: str) -> str:
60 + for k, v in _SUBST.items():
61 + s = s.replace(k, v)
62 + return s.encode("latin-1", "replace").decode("latin-1")
63 +
64 +
65 +class _PDF(FPDF):
66 + """FPDF avec en-tête/pied Groupe-KA sur chaque page (sauf couverture).
67 + Les polices core sont latin-1 : normalize_text sanitise en amont."""
68 +
69 + def normalize_text(self, text):
70 + return super().normalize_text(_latin1(text))
71 +
72 + def __init__(self, brand: str, accent: tuple, period_label: str):
73 + super().__init__(orientation="P", unit="mm", format="A4")
74 + self.brand = brand
75 + self.accent = accent
76 + self.period_label = period_label
77 + self.cover_mode = False
78 + self.set_margins(18, 20, 18)
79 + self.set_auto_page_break(True, margin=22)
80 +
81 + def header(self):
82 + if self.cover_mode or self.page_no() == 1:
83 + return
84 + self.set_font("helvetica", "B", 8.5)
85 + self.set_text_color(*INK)
86 + self.set_xy(18, 9)
87 + self.cell(0, 5, f"Groupe KA · {self.brand}")
88 + self.set_font("helvetica", "", 8)
89 + self.set_text_color(*INK3)
90 + self.set_xy(18, 9)
91 + self.cell(0, 5, "Rapport statistique", align="R")
92 + self.set_draw_color(*INK)
93 + self.set_line_width(0.5)
94 + self.line(18, 15.5, 192, 15.5)
95 + self.set_y(20)
96 +
97 + def footer(self):
98 + # page 1 = couverture (le flag cover_mode est déjà retombé quand
99 + # add_page() clôt la page 1 → tester aussi le numéro de page)
100 + if self.cover_mode or self.page_no() == 1:
101 + return
102 + self.set_y(-15)
103 + self.set_draw_color(*INK3)
104 + self.set_line_width(0.2)
105 + self.line(18, self.get_y() - 1.5, 192, self.get_y() - 1.5)
106 + self.set_font("helvetica", "", 7.5)
107 + self.set_text_color(*INK3)
108 + year = datetime.now(ZoneInfo("America/Toronto")).year
109 + self.cell(130, 5, f"© Groupe-KA — {year} — groupe-ka.com · {self.period_label}")
110 + self.cell(0, 5, f"p. {self.page_no()}/{{nb}}", align="R")
111 +
112 +
113 +class GroupeKAReport:
114 + def __init__(self, site: dict, dashboard: dict, mode: str = "complet"):
115 + self.site = site
116 + self.d = dashboard
117 + self.mode = mode
118 + self.accent = _hex(site.get("accent", "#d9f26b"))
119 + period = dashboard.get("period", {}) or {}
120 + self.period_label = period.get("label") or "toute la période"
121 + self.pdf = _PDF(site.get("wordmark", ""), self.accent, self.period_label)
122 + self.toc: list[tuple[str, int]] = []
123 +
124 + # ---------- primitives ----------
125 + def _card(self, x, y, w, h, fill=WHITE):
126 + p = self.pdf
127 + p.set_draw_color(*INK)
128 + p.set_line_width(0.45)
129 + p.set_fill_color(*fill)
130 + p.rect(x, y, w, h, style="DF", round_corners=True, corner_radius=2.2)
131 +
132 + def _kicker(self, text):
133 + p = self.pdf
134 + p.set_font("helvetica", "B", 8)
135 + p.set_text_color(*GREEN)
136 + p.set_draw_color(*GREEN)
137 + p.set_line_width(0.6)
138 + y = p.get_y() + 2
139 + p.line(p.l_margin, y, p.l_margin + 7, y)
140 + p.set_xy(p.l_margin + 9, y - 2.5)
141 + p.cell(0, 5, text.upper())
142 + p.ln(8)
143 +
144 + def _section_title(self, title):
145 + if self.pdf.get_y() > 240:
146 + self.pdf.add_page()
147 + self._kicker("Groupe KA · " + self.site.get("wordmark", ""))
148 + self.pdf.set_font("helvetica", "B", 15)
149 + self.pdf.set_text_color(*INK)
150 + self.pdf.set_x(self.pdf.l_margin)
151 + self.pdf.cell(0, 8, title)
152 + self.toc.append((title, self.pdf.page_no()))
153 + self.pdf.ln(11)
154 +
155 + # ---------- pages ----------
156 + def _cover(self):
157 + p = self.pdf
158 + p.cover_mode = True
159 + p.set_auto_page_break(False)
160 + p.add_page()
161 + p.set_fill_color(*PAPER)
162 + p.rect(0, 0, 210, 297, style="F")
163 + p.set_draw_color(*INK)
164 + p.set_line_width(1.0)
165 + p.rect(10, 10, 190, 277)
166 + # kicker
167 + p.set_font("helvetica", "B", 10)
168 + p.set_text_color(*GREEN)
169 + p.set_xy(24, 34)
170 + p.cell(0, 6, "GROUPE KA · RAPPORT STATISTIQUE")
171 + # wordmark : partie gauche + boîte encre/accent
172 + wm = self.site.get("wordmark", "")
173 + left, boxed = (wm.split("·") + [None])[:2] if "·" in wm else (wm, None)
174 + p.set_xy(24, 70)
175 + p.set_font("helvetica", "B", 40)
176 + p.set_text_color(*INK)
177 + p.cell(p.get_string_width(left) + 2, 20, left)
178 + if boxed:
179 + bw = p.get_string_width(boxed) + 12
180 + x = p.get_x() + 2
181 + p.set_fill_color(*INK)
182 + p.rect(x, 68, bw, 22, style="F", round_corners=True, corner_radius=3)
183 + p.set_text_color(*self.accent)
184 + p.set_xy(x + 6, 70)
185 + p.cell(bw - 12, 18, boxed)
186 + p.set_xy(24, 100)
187 + p.set_font("helvetica", "", 13)
188 + p.set_text_color(*INK2)
189 + p.multi_cell(150, 7, f"Rapport statistique — {wm}")
190 + now = datetime.now(ZoneInfo("America/Toronto"))
191 + per = self.d.get("period", {}) or {}
192 + p.set_xy(24, 125)
193 + p.set_font("helvetica", "", 10.5)
194 + rows = [
195 + ("Période couverte", self.period_label + (f" ({per.get('from')} → {per.get('to')})" if per.get("from") else "")),
196 + ("Généré le", now.strftime("%Y-%m-%d à %H:%M") + " (heure de l'Est)"),
197 + ("Plateforme", "https://" + self.site.get("domain", "")),
198 + ("Mode", "Rapport complet" if self.mode == "complet" else "Synthèse"),
199 + ]
200 + y = 128
201 + for k, v in rows:
202 + p.set_xy(24, y)
203 + p.set_text_color(*INK3)
204 + p.cell(40, 6, k)
205 + p.set_text_color(*INK)
206 + p.set_font("helvetica", "B", 10.5)
207 + p.cell(0, 6, str(v))
208 + p.set_font("helvetica", "", 10.5)
209 + y += 8
210 + # bande encre au pied
211 + p.set_fill_color(*INK)
212 + p.rect(10, 262, 190, 25, style="F")
213 + p.set_xy(24, 270)
214 + p.set_font("helvetica", "B", 12)
215 + p.set_text_color(*WHITE)
216 + p.cell(60, 8, "par Groupe ")
217 + p.set_text_color(*self.accent)
218 + p.set_xy(24 + p.get_string_width("par Groupe ") + 1, 270)
219 + p.cell(20, 8, "KA")
220 + p.set_font("helvetica", "B", 10)
221 + p.set_xy(24, 270)
222 + p.set_text_color(*self.accent)
223 + p.cell(162, 8, "groupe-ka.com", align="R")
224 + p.set_auto_page_break(True, margin=22)
225 + p.cover_mode = False
226 +
227 + def _kpis(self):
228 + kpis = self.d.get("kpis") or []
229 + if not kpis:
230 + return
231 + self._section_title("Synthèse des indicateurs")
232 + p = self.pdf
233 + cols, gw, gh, gap = 3, 56, 26, 3
234 + x0, y = p.l_margin, p.get_y()
235 + for i, k in enumerate(kpis[:9]):
236 + x = x0 + (i % cols) * (gw + gap)
237 + if i and i % cols == 0:
238 + y += gh + gap
239 + if y > 250:
240 + p.add_page(); y = p.get_y()
241 + self._card(x, y, gw, gh)
242 + p.set_xy(x + 4, y + 4)
243 + p.set_font("helvetica", "B", 14)
244 + p.set_text_color(*INK)
245 + val = k.get("value")
246 + p.cell(gw - 8, 7, (_fr(val) if isinstance(val, (int, float)) else str(val)) + (" " + k["unit"] if k.get("unit") else ""))
247 + p.set_xy(x + 4, y + 12)
248 + p.set_font("helvetica", "", 7.6)
249 + p.set_text_color(*INK2)
250 + p.multi_cell(gw - 8, 3.6, str(k.get("label", ""))[:70])
251 + if k.get("delta_pct") is not None:
252 + up = (k.get("direction") or ("up" if k["delta_pct"] >= 0 else "down")) == "up"
253 + p.set_xy(x + 4, y + gh - 6.5)
254 + p.set_font("helvetica", "B", 8)
255 + p.set_text_color(*(GREEN if up else DANGER))
256 + arrow = "+" if k["delta_pct"] >= 0 else ""
257 + p.cell(gw - 8, 4, f"{'▲' if up else '▼'} {arrow}{str(k['delta_pct']).replace('.', ',')} % vs période préc.")
258 + p.set_y(y + gh + 8)
259 +
260 + def _line_chart(self, s):
261 + p = self.pdf
262 + pts = s.get("points") or []
263 + if len(pts) < 2:
264 + return
265 + if p.get_y() > 200:
266 + p.add_page()
267 + p.set_font("helvetica", "B", 10)
268 + p.set_text_color(*INK)
269 + p.cell(0, 6, s.get("title", ""))
270 + p.ln(7)
271 + x0, y0, w, h = p.l_margin, p.get_y(), 174, 52
272 + self._card(x0, y0, w, h, fill=WHITE)
273 + cx, cy, cw, ch = x0 + 12, y0 + 6, w - 20, h - 16
274 + vals = [pt["v"] for pt in pts] + [c["v"] for c in (s.get("compare") or [])]
275 + vmax = max(vals) or 1
276 + vmin = min(0, min(vals))
277 + rng = (vmax - vmin) or 1
278 + # grille + graduations
279 + p.set_font("helvetica", "", 6.3)
280 + p.set_text_color(*INK3)
281 + p.set_draw_color(200, 200, 195)
282 + p.set_line_width(0.15)
283 + for g in range(5):
284 + gy = cy + ch - ch * g / 4
285 + p.line(cx, gy, cx + cw, gy)
286 + p.set_xy(x0 + 1, gy - 1.6)
287 + p.cell(10, 3, _fr(vmin + rng * g / 4), align="R")
288 +
289 + def draw(series, color, width, dash=None):
290 + n = len(series)
291 + p.set_draw_color(*color)
292 + p.set_line_width(width)
293 + if dash:
294 + p.set_dash_pattern(dash=1.2, gap=1.2)
295 + last = None
296 + for i, pt in enumerate(series):
297 + px = cx + cw * (i / (n - 1))
298 + py = cy + ch - ch * ((pt["v"] - vmin) / rng)
299 + if last:
300 + p.line(last[0], last[1], px, py)
301 + last = (px, py)
302 + p.set_dash_pattern()
303 +
304 + if s.get("compare"):
305 + draw(s["compare"], INK3, 0.35, dash=True)
306 + draw(pts, self.accent, 0.7)
307 + # libellés d'axe X (premier / milieu / dernier)
308 + p.set_text_color(*INK3)
309 + for frac, idx in ((0, 0), (0.5, len(pts) // 2), (1, -1)):
310 + p.set_xy(cx + cw * frac - 9, cy + ch + 1.5)
311 + p.cell(18, 3, str(pts[idx].get("t", ""))[:10], align="C")
312 + p.set_y(y0 + h + 4)
313 + if s.get("compare"):
314 + p.set_font("helvetica", "", 6.8)
315 + p.set_text_color(*INK3)
316 + p.cell(0, 4, "— période courante (accent) · ---- période comparée")
317 + p.ln(6)
318 + else:
319 + p.ln(2)
320 +
321 + def _bars(self, title, items, unit=""):
322 + p = self.pdf
323 + items = [it for it in (items or []) if isinstance(it.get("value"), (int, float))][:12]
324 + if not items:
325 + return
326 + need = 10 + len(items) * 7
327 + if p.get_y() + need > 265:
328 + p.add_page()
329 + p.set_font("helvetica", "B", 10)
330 + p.set_text_color(*INK)
331 + p.cell(0, 6, title)
332 + p.ln(8)
333 + vmax = max(it["value"] for it in items) or 1
334 + for it in items:
335 + y = p.get_y()
336 + p.set_font("helvetica", "", 7.6)
337 + p.set_text_color(*INK)
338 + p.set_x(p.l_margin)
339 + p.cell(46, 5, str(it["label"])[:34])
340 + bw = 96 * (it["value"] / vmax)
341 + p.set_fill_color(*self.accent)
342 + p.set_draw_color(*INK)
343 + p.set_line_width(0.25)
344 + p.rect(p.l_margin + 48, y + 0.7, max(bw, 0.8), 3.6, style="DF")
345 + p.set_xy(p.l_margin + 148, y)
346 + p.set_font("helvetica", "B", 7.6)
347 + p.cell(26, 5, _fr(it["value"]) + (" " + unit if unit else ""), align="R")
348 + p.ln(6.4)
349 + p.ln(3)
350 +
351 + def _donut(self, b):
352 + # anneau vectoriel simple (arcs) + légende
353 + p = self.pdf
354 + items = [it for it in (b.get("items") or []) if it.get("value")][:8]
355 + total = sum(it["value"] for it in items)
356 + if not items or not total:
357 + return
358 + if p.get_y() > 210:
359 + p.add_page()
360 + p.set_font("helvetica", "B", 10)
361 + p.set_text_color(*INK)
362 + p.cell(0, 6, b.get("title", ""))
363 + p.ln(8)
364 + cx, cy, r = p.l_margin + 26, p.get_y() + 24, 20
365 + shades = [1.0, 0.78, 0.58, 0.42, 0.30, 0.22, 0.15, 0.10]
366 + start = -90.0
367 + for i, it in enumerate(items):
368 + frac = it["value"] / total
369 + f = shades[i % len(shades)]
370 + col = tuple(int(PAPER[j] + (self.accent[j] - PAPER[j]) * f) for j in range(3))
371 + steps = max(2, int(72 * frac))
372 + p.set_fill_color(*col)
373 + p.set_draw_color(*col)
374 + for st in range(steps):
375 + a0 = math.radians(start + 360 * frac * st / steps)
376 + a1 = math.radians(start + 360 * frac * (st + 1) / steps)
377 + p.polygon(
378 + [(cx, cy),
379 + (cx + r * math.cos(a0), cy + r * math.sin(a0)),
380 + (cx + r * math.cos(a1), cy + r * math.sin(a1))],
381 + style="DF",
382 + )
383 + start += 360 * frac
384 + p.set_fill_color(*WHITE)
385 + p.set_draw_color(*INK)
386 + p.set_line_width(0.4)
387 + p.ellipse(cx - 11, cy - 11, 22, 22, style="DF")
388 + p.ellipse(cx - r, cy - r, 2 * r, 2 * r, style="D")
389 + # légende
390 + ly = cy - 22
391 + for i, it in enumerate(items):
392 + f = shades[i % len(shades)]
393 + col = tuple(int(PAPER[j] + (self.accent[j] - PAPER[j]) * f) for j in range(3))
394 + p.set_fill_color(*col)
395 + p.set_draw_color(*INK)
396 + p.rect(p.l_margin + 60, ly + 0.8, 4, 4, style="DF")
397 + p.set_xy(p.l_margin + 66, ly)
398 + p.set_font("helvetica", "", 7.6)
399 + p.set_text_color(*INK)
400 + pct = 100 * it["value"] / total
401 + p.cell(0, 5.6, f"{str(it['label'])[:40]} — {_fr(it['value'])} ({pct:.1f} %)".replace(".", ","))
402 + ly += 5.6
403 + p.set_y(max(cy + r, ly) + 6)
404 +
405 + def _table(self, t):
406 + p = self.pdf
407 + cols = t.get("columns") or []
408 + rows = t.get("rows") or []
409 + if not cols or not rows:
410 + return
411 + self._section_title(t.get("title", "Tableau"))
412 + w = 174 / len(cols)
413 + def head():
414 + p.set_font("helvetica", "B", 7.6)
415 + p.set_fill_color(*INK)
416 + p.set_text_color(*WHITE)
417 + for c in cols:
418 + p.cell(w, 6, " " + str(c)[:30], fill=True)
419 + p.ln(6)
420 + head()
421 + p.set_text_color(*INK)
422 + for i, row in enumerate(rows[:200]):
423 + if p.get_y() > 262:
424 + p.add_page()
425 + head()
426 + p.set_text_color(*INK)
427 + p.set_font("helvetica", "", 7.4)
428 + p.set_fill_color(*(SURFACE2 if i % 2 else WHITE))
429 + for cell in row:
430 + txt = _fr(cell) if isinstance(cell, (int, float)) else str(cell)
431 + p.cell(w, 5.4, " " + txt[:34], fill=True)
432 + p.ln(5.4)
433 + if len(rows) > 200:
434 + p.set_font("helvetica", "", 7)
435 + p.set_text_color(*INK3)
436 + p.cell(0, 5, f"… {len(rows) - 200} lignes supplémentaires non imprimées")
437 + p.ln(6)
438 +
439 + def _records(self):
440 + recs = self.d.get("records") or []
441 + if not recs:
442 + return
443 + self._section_title("Records & faits marquants")
444 + p = self.pdf
445 + for r in recs[:10]:
446 + if p.get_y() > 258:
447 + p.add_page()
448 + y = p.get_y()
449 + self._card(p.l_margin, y, 174, 11, fill=SURFACE2)
450 + p.set_xy(p.l_margin + 4, y + 2)
451 + p.set_font("helvetica", "", 8.6)
452 + p.set_text_color(*INK2)
453 + p.cell(96, 7, str(r.get("label", ""))[:70])
454 + p.set_font("helvetica", "B", 9)
455 + p.set_text_color(*INK)
456 + p.cell(52, 7, str(r.get("value", ""))[:36], align="R")
457 + p.set_font("helvetica", "", 7.6)
458 + p.set_text_color(*INK3)
459 + p.cell(20, 7, str(r.get("date", "") or ""), align="R")
460 + p.set_y(y + 13.5)
461 + p.ln(4)
462 +
463 + def _final_page(self):
464 + p = self.pdf
465 + p.add_page()
466 + self._kicker("Groupe KA · contact")
467 + p.set_font("helvetica", "B", 15)
468 + p.set_text_color(*INK)
469 + p.cell(0, 8, "Coordonnées du Groupe KA")
470 + p.ln(12)
471 + for email, role in EMAILS:
472 + p.set_font("helvetica", "B", 10.5)
473 + p.set_text_color(*INK)
474 + p.cell(0, 6, email)
475 + p.ln(5.5)
476 + p.set_font("helvetica", "", 8.6)
477 + p.set_text_color(*INK3)
478 + p.cell(0, 5, role)
479 + p.ln(8)
480 + p.ln(2)
481 + p.set_font("helvetica", "B", 10)
482 + p.set_text_color(*GREEN)
483 + p.cell(0, 6, "groupe-ka.com — le portail de l'écosystème ·Ka")
484 + p.ln(10)
485 + p.set_draw_color(*self.accent)
486 + p.set_line_width(0.8)
487 + p.line(p.l_margin, p.get_y(), p.l_margin + 30, p.get_y())
488 + p.ln(4)
489 + p.set_font("helvetica", "", 8.6)
490 + p.set_text_color(*INK2)
491 + p.multi_cell(160, 4.6, DISCLAIMER)
492 + p.ln(4)
493 + p.set_font("helvetica", "", 7.6)
494 + p.set_text_color(*INK3)
495 + p.multi_cell(
496 + 160, 4.2,
497 + "Mentions : rapport généré automatiquement à partir des données réelles de la "
498 + "plateforme au moment indiqué en couverture. Conditions d'utilisation, politique "
499 + "de confidentialité et protection des renseignements personnels (Loi 25) : "
500 + "groupe-ka.com/conditions · /confidentialite · /loi-25.",
501 + )
502 +
503 + def _toc_page(self):
504 + # insérée après coup ? fpdf ne réordonne pas : on écrit le sommaire en
505 + # page 2 en réservant la page lors du build (voir build()).
506 + pass
507 +
508 + def build(self) -> bytes:
509 + p = self.pdf
510 + p.alias_nb_pages()
511 + self._cover()
512 + if self.mode == "synthese":
513 + p.add_page()
514 + self._kpis()
515 + self._records()
516 + self._final_page()
517 + else:
518 + p.add_page()
519 + toc_page_no = p.page_no()
520 + p.add_page()
521 + self._kpis()
522 + for s in self.d.get("series") or []:
523 + if s.get("kind") == "bar":
524 + self._bars(s.get("title", ""), [{"label": pt.get("t"), "value": pt.get("v")} for pt in (s.get("points") or [])], s.get("unit", ""))
525 + else:
526 + self._line_chart(s)
527 + for b in self.d.get("breakdowns") or []:
528 + if b.get("kind") == "donut":
529 + self._donut(b)
530 + else:
531 + self._bars(b.get("title", ""), b.get("items"))
532 + geo = self.d.get("geo")
533 + if geo:
534 + self._bars(geo.get("title", "Répartition géographique"), geo.get("items"))
535 + for t in self.d.get("tables") or []:
536 + self._table(t)
537 + self._records()
538 + self._final_page()
539 + # sommaire écrit sur la page réservée (page 2)
540 + last_page = p.page
541 + p.page = toc_page_no
542 + p.set_y(22)
543 + p.set_font("helvetica", "B", 15)
544 + p.set_text_color(*INK)
545 + p.cell(0, 8, "Sommaire")
546 + p.ln(12)
547 + p.set_font("helvetica", "", 9.5)
548 + for title, page_no in self.toc:
549 + p.set_text_color(*INK)
550 + p.cell(140, 6.5, title[:80])
551 + p.set_text_color(*INK3)
552 + p.cell(0, 6.5, str(page_no), align="R")
553 + p.ln(6.5)
554 + p.page = last_page
555 + return bytes(p.output())
556 +
557 +
558 +def filename(platform_id: str, period: str) -> str:
559 + today = datetime.now(ZoneInfo("America/Toronto")).strftime("%Y-%m-%d")
560 + return f"groupe-ka_{platform_id}_stats_{period}_{today}.pdf"
added frontend/src/ka/tokens.css +229 −0
Large diff (229 lines) is not loaded by default to keep the page fast.Load diff
modified frontend/src/main.tsx +1 −0
Large diff (7 lines) is not loaded by default to keep the page fast.Load diff
added frontend/src/pages/Contact.tsx +72 −0
Large diff (72 lines) is not loaded by default to keep the page fast.Load diff
modified frontend/src/pages/MapPage.tsx +2 −2
Large diff (16 lines) is not loaded by default to keep the page fast.Load diff
modified frontend/src/pages/Stats.tsx +139 −59
Large diff (215 lines) is not loaded by default to keep the page fast.Load diff
modified frontend/src/styles.css +121 −53
Large diff (257 lines) is not loaded by default to keep the page fast.Load diff
added jobka/auth.py +238 −0
Large diff (238 lines) is not loaded by default to keep the page fast.Load diff
modified jobka/db.py +12 −0
Large diff (18 lines) is not loaded by default to keep the page fast.Load diff
added jobka/kapdf.py +560 −0
Large diff (560 lines) is not loaded by default to keep the page fast.Load diff
added jobka/statsdash.py +428 −0
Large diff (428 lines) is not loaded by default to keep the page fast.Load diff
modified jobka/web.py +42 −3
Large diff (71 lines) is not loaded by default to keep the page fast.Load diff
modified requirements.txt +1 −0
Large diff (5 lines) is not loaded by default to keep the page fast.Load diff
Menu

Theme