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)
7 changed files +1,699 −292
modified
frontend/index.html
+285 −11
@@ -328,6 +328,32 @@ button{font-family:inherit} | ||
| 328 | 328 | .st-record .rv{text-align:right} |
| 329 | 329 | .st-record .rv b{font-family:var(--font-display);font-size:15px} |
| 330 | 330 | .st-record .rv .klabel{display:block} |
| 331 | +/* v2 : menu PDF, sparklines KPI, jauges, résumé statistique, heatmap horaire */ | |
| 332 | +.st-pdf-menu{position:relative;display:inline-block} | |
| 333 | +.st-pdf-drop{position:absolute;right:0;top:calc(100% + 6px);z-index:40;min-width:240px; | |
| 334 | + display:flex;flex-direction:column;background:var(--paper);border:1.5px solid var(--ink); | |
| 335 | + border-radius:10px;box-shadow:0 10px 28px rgba(20,24,20,.18);overflow:hidden} | |
| 336 | +.st-pdf-drop button{border:0;background:none;cursor:pointer;text-align:left;padding:12px 14px; | |
| 337 | + font:inherit;font-size:13.5px;font-weight:600;color:var(--ink);min-height:44px; | |
| 338 | + display:flex;justify-content:space-between;gap:10px;align-items:baseline} | |
| 339 | +.st-pdf-drop button+button{border-top:1px solid var(--line)} | |
| 340 | +.st-pdf-drop button:hover{background:var(--accent-soft)} | |
| 341 | +.st-pdf-drop small{font-family:var(--font-mono);font-size:10px;color:var(--ink-3)} | |
| 342 | +.st-kpi .spark{margin-top:8px} | |
| 343 | +.st-kpi .spark svg{display:block;width:100%;height:26px} | |
| 344 | +.st-gauges{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(200px,100%),1fr));gap:14px;margin-top:18px} | |
| 345 | +.st-gauge{padding:14px 16px;display:flex;gap:14px;align-items:center;min-width:0} | |
| 346 | +.st-gauge svg{width:86px;flex:none} | |
| 347 | +.st-gauge .gv{font-family:var(--font-display);font-weight:700;font-size:21px;letter-spacing:-.02em} | |
| 348 | +.st-gauge .gv small{font-size:.62em;color:var(--ink-2)} | |
| 349 | +.st-sum{display:flex;flex-wrap:wrap;gap:8px 18px;margin-top:10px;padding-top:10px;border-top:1px dashed var(--line)} | |
| 350 | +.st-sum span{font-family:var(--font-mono);font-size:10.5px;color:var(--ink-3);text-transform:uppercase;letter-spacing:.05em} | |
| 351 | +.st-sum b{color:var(--ink);font-size:11.5px;margin-left:4px} | |
| 352 | +.st-legend .sw.p1{border-top-style:dashed} | |
| 353 | +.st-legend .sw.p2{border-top-style:dotted} | |
| 354 | +.st-legend .sw.p3{border-top-style:double;border-bottom:1px solid var(--accent);height:3px} | |
| 355 | +.st-legend .sw.fill{width:12px;height:12px;border:1px solid var(--ink);border-radius:3px;background:var(--accent)} | |
| 356 | +.st-bar-lbl .bd{font-family:var(--font-mono);font-size:10px;font-weight:700;flex:none;margin-left:6px} | |
| 331 | 357 | .st-empty{padding:20px;background:var(--surface-2);border-style:dashed} |
| 332 | 358 | .st-empty b{font-family:var(--font-display);font-size:14px} |
| 333 | 359 | .st-loading{padding:40px 0;font-family:var(--font-mono);font-size:12px;color:var(--ink-3);text-transform:uppercase;letter-spacing:.08em} |
@@ -451,16 +477,28 @@ button{font-family:inherit} | ||
| 451 | 477 | <p class="st-fresh" id="st-fresh"></p> |
| 452 | 478 | </div> |
| 453 | 479 | <div class="st-pdf"> |
| 454 | − <button type="button" class="btn btn-primary" id="st-pdf-full">⬇ Télécharger le rapport PDF</button> | |
| 455 | − <button type="button" class="btn btn-ghost" id="st-pdf-syn">Synthèse (2 p.)</button> | |
| 480 | + <button type="button" class="btn btn-primary" id="st-pdf-full">⬇ Rapport PDF complet</button> | |
| 481 | + <span class="st-pdf-menu"> | |
| 482 | + <button type="button" class="btn btn-ghost" id="st-pdf-more" | |
| 483 | + aria-haspopup="true" aria-expanded="false">Autres rapports ▾</button> | |
| 484 | + <span class="st-pdf-drop hidden" id="st-pdf-drop" role="menu"> | |
| 485 | + <button type="button" data-mode="synthese">Synthèse exécutive <small>2-3 pages</small></button> | |
| 486 | + <button type="button" data-mode="tendances">Tendances & évolution</button> | |
| 487 | + <button type="button" data-mode="repartitions">Répartitions & géographie</button> | |
| 488 | + <button type="button" data-mode="donnees">Données détaillées <small>tableaux longs</small></button> | |
| 489 | + </span> | |
| 490 | + </span> | |
| 456 | 491 | </div> |
| 457 | 492 | </div> |
| 458 | − <div class="st-periods" id="st-periods"></div> | |
| 459 | 493 | <div class="st-kpis" id="st-kpis"></div> |
| 494 | + <div class="st-periods" id="st-periods"></div> | |
| 495 | + <div class="st-gauges" id="st-gauges"></div> | |
| 460 | 496 | <div class="st-sec" id="st-series"></div> |
| 497 | + <div class="st-sec" id="st-multi"></div> | |
| 461 | 498 | <div class="st-2col" id="st-breaks"></div> |
| 462 | 499 | <div class="st-2col" id="st-geosrc"></div> |
| 463 | 500 | <div class="st-sec" id="st-heat"></div> |
| 501 | + <div class="st-sec" id="st-hourly"></div> | |
| 464 | 502 | <div class="st-sec" id="st-tables"></div> |
| 465 | 503 | <section id="st-records-wrap" class="hidden" style="margin-top:34px"> |
| 466 | 504 | <span class="kicker">Records & faits marquants</span> |
@@ -797,7 +835,37 @@ function stRenderPeriods(){ | ||
| 797 | 835 | $("st-from").onchange = onDate; $("st-to").onchange = onDate; |
| 798 | 836 | } |
| 799 | 837 | |
| 800 | −/* ---- KPI ---- */ | |
| 838 | +/* ---- sparkline (tendance dans les cartes KPI) ---- */ | |
| 839 | +function stSpark(points){ | |
| 840 | + const pts = (points||[]).filter(p=>typeof p.v==="number"); | |
| 841 | + if(pts.length < 2) return ""; | |
| 842 | + const W=120, H=26, n=pts.length; | |
| 843 | + const vmax = Math.max(...pts.map(p=>p.v), 1), vmin = Math.min(0, ...pts.map(p=>p.v)); | |
| 844 | + const X = i => 2 + (W-4)*i/(n-1); | |
| 845 | + const Y = v => 2 + (H-4)*(1-(v-vmin)/((vmax-vmin)||1)); | |
| 846 | + const line = pts.map((p,i)=>`${i?"L":"M"}${X(i).toFixed(1)},${Y(p.v).toFixed(1)}`).join(""); | |
| 847 | + return `<div class="spark" aria-hidden="true"><svg viewBox="0 0 ${W} ${H}" preserveAspectRatio="none"> | |
| 848 | + <path d="${line} L${W-2},${H-1} L2,${H-1} Z" fill="var(--accent)" fill-opacity=".12" stroke="none"/> | |
| 849 | + <path d="${line}" fill="none" stroke="var(--accent)" stroke-width="1.6"/></svg></div>`; | |
| 850 | +} | |
| 851 | + | |
| 852 | +/* ---- statistiques de série : min / max / moyenne / médiane / écart-type ---- */ | |
| 853 | +function stSummary(points, unit){ | |
| 854 | + const vs = (points||[]).map(p=>p.v).filter(v=>typeof v==="number"); | |
| 855 | + if(vs.length < 5) return ""; | |
| 856 | + const n = vs.length, mean = vs.reduce((s,v)=>s+v,0)/n; | |
| 857 | + const sorted = [...vs].sort((a,b)=>a-b); | |
| 858 | + const med = n%2 ? sorted[(n-1)/2] : (sorted[n/2-1]+sorted[n/2])/2; | |
| 859 | + const sd = Math.sqrt(vs.reduce((s,v)=>s+(v-mean)**2,0)/n); | |
| 860 | + const u = unit ? ` ${esc(unit)}` : ""; | |
| 861 | + const f = v => fmtN(Math.round(v*10)/10); | |
| 862 | + return `<div class="st-sum"> | |
| 863 | + <span>min<b>${f(sorted[0])}${u}</b></span><span>max<b>${f(sorted[n-1])}${u}</b></span> | |
| 864 | + <span>moyenne<b>${f(mean)}${u}</b></span><span>médiane<b>${f(med)}${u}</b></span> | |
| 865 | + <span>écart-type<b>${f(sd)}</b></span></div>`; | |
| 866 | +} | |
| 867 | + | |
| 868 | +/* ---- KPI (delta ▲/▼ + sparkline) ---- */ | |
| 801 | 869 | function stKpi(k){ |
| 802 | 870 | let delta = ""; |
| 803 | 871 | if(k.delta_pct !== null && k.delta_pct !== undefined){ |
@@ -807,7 +875,23 @@ function stKpi(k){ | ||
| 807 | 875 | } |
| 808 | 876 | return `<article class="gk-card st-kpi"> |
| 809 | 877 | <div class="v">${typeof k.value === "number" ? fmtN(k.value) : esc(k.value)}${k.unit?` <small>${esc(k.unit)}</small>`:""}</div> |
| 810 | − <div class="klabel" style="margin-top:6px">${esc(k.label)}</div>${delta}</article>`; | |
| 878 | + <div class="klabel" style="margin-top:6px">${esc(k.label)}</div>${delta}${stSpark(k.spark)}</article>`; | |
| 879 | +} | |
| 880 | + | |
| 881 | +/* ---- jauge demi-arc (taux, couvertures, complétude) ---- */ | |
| 882 | +function stGauge(g){ | |
| 883 | + const max = g.max || 100, frac = Math.max(0, Math.min(1, g.value/max)); | |
| 884 | + const R = 34, C = Math.PI*R; | |
| 885 | + return `<article class="gk-card st-gauge" role="img" | |
| 886 | + aria-label="${esc(g.label)} : ${fmtN(g.value)}${g.unit?` ${esc(g.unit)}`:""} sur ${fmtN(max)}"> | |
| 887 | + <svg viewBox="0 0 86 50"> | |
| 888 | + <path d="M 9 44 A ${R} ${R} 0 0 1 77 44" fill="none" stroke="rgba(20,24,20,.09)" stroke-width="9" stroke-linecap="round"/> | |
| 889 | + <path d="M 9 44 A ${R} ${R} 0 0 1 77 44" fill="none" stroke="var(--accent)" stroke-width="9" stroke-linecap="round" | |
| 890 | + stroke-dasharray="${(frac*C).toFixed(1)} ${C.toFixed(1)}"/> | |
| 891 | + <path d="M 9 44 A ${R} ${R} 0 0 1 77 44" fill="none" stroke="var(--ink)" stroke-opacity=".25" stroke-width="1"/> | |
| 892 | + </svg> | |
| 893 | + <div><div class="gv">${fmtN(g.value)}${g.unit?`<small> ${esc(g.unit)}</small>`:""}</div> | |
| 894 | + <div class="klabel" style="margin-top:4px">${esc(g.label)}</div></div></article>`; | |
| 811 | 895 | } |
| 812 | 896 | |
| 813 | 897 | /* ---- courbe (infobulle au survol + légende cliquable + N-1) ---- */ |
@@ -848,7 +932,7 @@ function stLine(host, serie){ | ||
| 848 | 932 | </g> |
| 849 | 933 | <rect x="${PL}" y="0" width="${W-PL-PR}" height="${H}" fill="transparent"/> |
| 850 | 934 | </svg> |
| 851 | − <p class="chip st-tip"></p></figure>`; | |
| 935 | + <p class="chip st-tip"></p>${stSummary(pts, serie.unit)}</figure>`; | |
| 852 | 936 | const svg = host.querySelector("svg"), mk = svg.querySelector("[data-marker]"), |
| 853 | 937 | mline = mk.querySelector("line"), mdot = mk.querySelector("circle"), |
| 854 | 938 | tip = host.querySelector(".st-tip"); |
@@ -877,20 +961,186 @@ function stLine(host, serie){ | ||
| 877 | 961 | render(); |
| 878 | 962 | } |
| 879 | 963 | |
| 880 | −/* ---- barres horizontales ---- */ | |
| 964 | +/* ---- barres horizontales (delta_pct optionnel par barre) ---- */ | |
| 881 | 965 | function stBars(host, title, items, unit){ |
| 882 | 966 | const rows = (items||[]).filter(r=>typeof r.value==="number").slice(0,14); |
| 883 | 967 | if(!rows.length){ host.innerHTML = stEmpty(title); return; } |
| 884 | 968 | const max = Math.max(...rows.map(r=>r.value), 1); |
| 969 | + const delta = r => (r.delta_pct === null || r.delta_pct === undefined) ? "" : | |
| 970 | + `<span class="bd" style="color:${r.delta_pct>=0?"var(--green)":"var(--danger)"}">${r.delta_pct>=0?"▲ +":"▼ "}${fmtN(r.delta_pct)} %</span>`; | |
| 885 | 971 | host.innerHTML = `<figure class="gk-card st-fig"> |
| 886 | 972 | <figcaption><b>${esc(title)}</b></figcaption> |
| 887 | 973 | <div class="st-bars">${rows.map(r=>` |
| 888 | 974 | <div title="${esc(r.label)} — ${fmtN(r.value)}${unit?` ${unit}`:""}"> |
| 889 | − <div class="st-bar-lbl"><span>${esc(r.label)}</span><b>${fmtN(r.value)}${unit?` ${esc(unit)}`:""}</b></div> | |
| 975 | + <div class="st-bar-lbl"><span>${esc(r.label)}</span><b>${fmtN(r.value)}${unit?` ${esc(unit)}`:""}</b>${delta(r)}</div> | |
| 890 | 976 | <div class="st-bar-track"><div class="st-bar-fill" style="width:${Math.max(r.value/max*100,1)}%"></div></div> |
| 891 | 977 | </div>`).join("")}</div></figure>`; |
| 892 | 978 | } |
| 893 | 979 | |
| 980 | +/* ---- barres verticales (volumes quotidiens & histogrammes) ---- */ | |
| 981 | +function stVBar(host, title, bins, unit, sub){ | |
| 982 | + const rows = (bins||[]).filter(b=>typeof b.value==="number"); | |
| 983 | + if(!rows.length || !rows.some(b=>b.value>0)){ host.innerHTML = stEmpty(title); return; } | |
| 984 | + const W=720, H=240, PL=54, PR=10, PT=14, PB=40; | |
| 985 | + const max = Math.max(...rows.map(b=>b.value), 1); | |
| 986 | + const n = rows.length, bw = (W-PL-PR)/n; | |
| 987 | + let grid = ""; | |
| 988 | + for(let g=0; g<5; g++){ | |
| 989 | + const y = PT + (H-PT-PB)*g/4, v = max*(4-g)/4; | |
| 990 | + grid += `<line x1="${PL}" x2="${W-PR}" y1="${y}" y2="${y}" stroke="var(--line)" stroke-width="1"/> | |
| 991 | + <text x="${PL-6}" y="${y+3}" text-anchor="end" font-size="10" fill="var(--ink-3)" font-family="var(--font-mono)">${fmtI(v)}</text>`; | |
| 992 | + } | |
| 993 | + const few = n <= 12; | |
| 994 | + const bars = rows.map((b,i)=>{ | |
| 995 | + const h = (H-PT-PB)*b.value/max, x = PL + i*bw; | |
| 996 | + const lab = few ? `<text x="${x+bw/2}" y="${H-PB+14}" text-anchor="middle" font-size="9.5" | |
| 997 | + fill="var(--ink-3)" font-family="var(--font-mono)">${esc(String(b.label).slice(0,12))}</text>` : | |
| 998 | + (i===0 || i===n-1 || i===Math.floor(n/2) ? | |
| 999 | + `<text x="${x+bw/2}" y="${H-PB+14}" text-anchor="middle" font-size="9.5" | |
| 1000 | + fill="var(--ink-3)" font-family="var(--font-mono)">${esc(String(b.label))}</text>` : ""); | |
| 1001 | + return `<rect x="${(x+bw*0.12).toFixed(1)}" y="${(H-PB-h).toFixed(1)}" width="${(bw*0.76).toFixed(1)}" | |
| 1002 | + height="${Math.max(h, b.value>0?1.5:0).toFixed(1)}" fill="var(--accent)" stroke="var(--ink)" stroke-width=".8"> | |
| 1003 | + <title>${esc(b.label)} — ${fmtN(b.value)}${unit?` ${unit}`:""}</title></rect>${lab}`; | |
| 1004 | + }).join(""); | |
| 1005 | + host.innerHTML = `<figure class="gk-card st-fig"> | |
| 1006 | + <figcaption><b>${esc(title)}</b>${sub?` <span class="klabel">${esc(sub)}</span>`:""}</figcaption> | |
| 1007 | + <svg viewBox="0 0 ${W} ${H}" role="img" aria-label="${esc(title)}">${grid}${bars}</svg></figure>`; | |
| 1008 | +} | |
| 1009 | + | |
| 1010 | +/* ---- multi-courbes ≤ 4 séries : motifs de trait distincts + légende ---- */ | |
| 1011 | +const ST_DASH = ["", "7 4", "2 4", "10 4 2 4"]; | |
| 1012 | +function stMulti(host, ms){ | |
| 1013 | + const sers = (ms.series||[]).slice(0,4).filter(s=>(s.points||[]).length>1); | |
| 1014 | + if(!sers.length){ host.innerHTML = stEmpty(ms.title); return; } | |
| 1015 | + const on = sers.map(()=>true); | |
| 1016 | + const W=720, H=260, PL=54, PR=10, PT=14, PB=26; | |
| 1017 | + const n = Math.max(...sers.map(s=>s.points.length)); | |
| 1018 | + const X = i => PL + (W-PL-PR)*i/(n-1); | |
| 1019 | + const render = () => { | |
| 1020 | + const vis = sers.filter((_,i)=>on[i]); | |
| 1021 | + const all = vis.flatMap(s=>s.points.map(p=>p.v)); | |
| 1022 | + const vmax = Math.max(...(all.length?all:[1]), 1), vmin = Math.min(0, ...(all.length?all:[0])); | |
| 1023 | + const Y = v => PT + (H-PT-PB)*(1-(v-vmin)/((vmax-vmin)||1)); | |
| 1024 | + let grid = ""; | |
| 1025 | + for(let g=0; g<5; g++){ | |
| 1026 | + const y = PT + (H-PT-PB)*g/4, v = vmax-(vmax-vmin)*g/4; | |
| 1027 | + grid += `<line x1="${PL}" x2="${W-PR}" y1="${y}" y2="${y}" stroke="var(--line)" stroke-width="1"/> | |
| 1028 | + <text x="${PL-6}" y="${y+3}" text-anchor="end" font-size="10" fill="var(--ink-3)" font-family="var(--font-mono)">${fmtI(v)}</text>`; | |
| 1029 | + } | |
| 1030 | + const ts = sers[0].points; | |
| 1031 | + const xlab = [0, Math.floor(ts.length/2), ts.length-1].map(i => | |
| 1032 | + `<text x="${X(i)}" y="${H-8}" text-anchor="middle" font-size="10" fill="var(--ink-3)" font-family="var(--font-mono)">${esc(ts[i].t)}</text>`).join(""); | |
| 1033 | + const paths = sers.map((s,si)=> !on[si] ? "" : | |
| 1034 | + `<path d="${s.points.map((p,i)=>`${i?"L":"M"}${X(i).toFixed(1)},${Y(p.v).toFixed(1)}`).join("")}" | |
| 1035 | + fill="none" stroke="var(--accent)" stroke-opacity="${(1-si*0.16).toFixed(2)}" stroke-width="2.2" | |
| 1036 | + ${ST_DASH[si]?`stroke-dasharray="${ST_DASH[si]}"`:""}/>`).join(""); | |
| 1037 | + host.innerHTML = `<figure class="gk-card st-fig"> | |
| 1038 | + <figcaption><b>${esc(ms.title)}</b> | |
| 1039 | + <span class="st-legend">${sers.map((s,i)=> | |
| 1040 | + `<button type="button" data-i="${i}" class="${on[i]?"":"off"}" aria-pressed="${on[i]}"> | |
| 1041 | + <span class="sw ${i?`p${i}`:""}"></span>${esc(s.label)}</button>`).join("")}</span></figcaption> | |
| 1042 | + <svg viewBox="0 0 ${W} ${H}" role="img" aria-label="${esc(ms.title)}"> | |
| 1043 | + ${grid}${xlab}${paths} | |
| 1044 | + <g data-marker style="visibility:hidden"> | |
| 1045 | + <line y1="${PT}" y2="${H-PB}" stroke="var(--ink)" stroke-width="1" stroke-dasharray="2 3"/></g> | |
| 1046 | + <rect x="${PL}" y="0" width="${W-PL-PR}" height="${H}" fill="transparent"/> | |
| 1047 | + </svg><p class="chip st-tip"></p></figure>`; | |
| 1048 | + const svg = host.querySelector("svg"), mk = svg.querySelector("[data-marker]"), | |
| 1049 | + mline = mk.querySelector("line"), tip = host.querySelector(".st-tip"); | |
| 1050 | + const move = clientX => { | |
| 1051 | + const r = svg.getBoundingClientRect(); | |
| 1052 | + const fx = (clientX - r.left)/r.width*W; | |
| 1053 | + const i = Math.min(n-1, Math.max(0, Math.round((fx-PL)/(W-PL-PR)*(n-1)))); | |
| 1054 | + mk.style.visibility = "visible"; | |
| 1055 | + mline.setAttribute("x1",X(i)); mline.setAttribute("x2",X(i)); | |
| 1056 | + tip.classList.add("show"); | |
| 1057 | + tip.innerHTML = `${esc(ts[i]?ts[i].t:"")} — ` + sers.map((s,si)=> !on[si] ? "" : | |
| 1058 | + `<span style="margin-left:8px">${esc(s.label)} : <b>${s.points[i]?fmtN(s.points[i].v):"—"}</b></span>`).join(""); | |
| 1059 | + }; | |
| 1060 | + svg.addEventListener("mousemove", e => move(e.clientX)); | |
| 1061 | + svg.addEventListener("touchstart", e => move(e.touches[0].clientX), {passive:true}); | |
| 1062 | + svg.addEventListener("touchmove", e => move(e.touches[0].clientX), {passive:true}); | |
| 1063 | + svg.addEventListener("mouseleave", () => { mk.style.visibility="hidden"; tip.classList.remove("show"); }); | |
| 1064 | + host.querySelectorAll(".st-legend button").forEach(b => b.onclick = () => { | |
| 1065 | + const i = Number(b.dataset.i); | |
| 1066 | + on[i] = !on[i]; | |
| 1067 | + if(!on.some(Boolean)) on[i] = true; | |
| 1068 | + render(); | |
| 1069 | + }); | |
| 1070 | + }; | |
| 1071 | + render(); | |
| 1072 | +} | |
| 1073 | + | |
| 1074 | +/* ---- barres empilées (composition dans le temps, nuances d'accent) ---- */ | |
| 1075 | +function stStacked(host, sp){ | |
| 1076 | + const keys = sp.keys || [], pts = sp.points || []; | |
| 1077 | + if(!keys.length || !pts.length || !pts.some(p=>(p.values||[]).some(v=>v>0))){ | |
| 1078 | + host.innerHTML = stEmpty(sp.title); return; | |
| 1079 | + } | |
| 1080 | + const W=720, H=260, PL=54, PR=10, PT=14, PB=26; | |
| 1081 | + const totals = pts.map(p=>(p.values||[]).reduce((s,v)=>s+(v||0),0)); | |
| 1082 | + const max = Math.max(...totals, 1); | |
| 1083 | + const n = pts.length, bw = (W-PL-PR)/n; | |
| 1084 | + let grid = ""; | |
| 1085 | + for(let g=0; g<5; g++){ | |
| 1086 | + const y = PT + (H-PT-PB)*g/4, v = max*(4-g)/4; | |
| 1087 | + grid += `<line x1="${PL}" x2="${W-PR}" y1="${y}" y2="${y}" stroke="var(--line)" stroke-width="1"/> | |
| 1088 | + <text x="${PL-6}" y="${y+3}" text-anchor="end" font-size="10" fill="var(--ink-3)" font-family="var(--font-mono)">${fmtI(v)}</text>`; | |
| 1089 | + } | |
| 1090 | + const xlab = [0, Math.floor(n/2), n-1].map(i => | |
| 1091 | + `<text x="${PL+i*bw+bw/2}" y="${H-8}" text-anchor="middle" font-size="10" fill="var(--ink-3)" font-family="var(--font-mono)">${esc(pts[i].t)}</text>`).join(""); | |
| 1092 | + let bars = ""; | |
| 1093 | + pts.forEach((p,i)=>{ | |
| 1094 | + let yTop = H-PB; | |
| 1095 | + const tt = `${p.t} — total ${fmtN(totals[i])}${sp.unit?` ${sp.unit}`:""} · ` + | |
| 1096 | + keys.map((k,ki)=>`${k} : ${fmtN((p.values||[])[ki]||0)}`).join(" · "); | |
| 1097 | + (p.values||[]).forEach((v,ki)=>{ | |
| 1098 | + const h = (H-PT-PB)*(v||0)/max; | |
| 1099 | + if(h>0){ | |
| 1100 | + yTop -= h; | |
| 1101 | + bars += `<rect x="${(PL+i*bw+bw*0.1).toFixed(1)}" y="${yTop.toFixed(1)}" width="${(bw*0.8).toFixed(1)}" | |
| 1102 | + height="${h.toFixed(1)}" fill="var(--accent)" fill-opacity="${ST_SHADES[ki%8]}" | |
| 1103 | + stroke="var(--ink)" stroke-width=".6"><title>${esc(tt)}</title></rect>`; | |
| 1104 | + } | |
| 1105 | + }); | |
| 1106 | + }); | |
| 1107 | + host.innerHTML = `<figure class="gk-card st-fig"> | |
| 1108 | + <figcaption><b>${esc(sp.title)}</b> | |
| 1109 | + <span class="st-legend">${keys.map((k,i)=> | |
| 1110 | + `<button type="button" disabled style="cursor:default"><span class="sw fill" style="opacity:${ST_SHADES[i%8]}"></span>${esc(k)}</button>`).join("")}</span></figcaption> | |
| 1111 | + <svg viewBox="0 0 ${W} ${H}" role="img" aria-label="${esc(sp.title)}">${grid}${xlab}${bars}</svg></figure>`; | |
| 1112 | +} | |
| 1113 | + | |
| 1114 | +/* ---- heatmap horaire 7 jours × 24 h (dow 0 = lundi) ---- */ | |
| 1115 | +function stHourly(host, h){ | |
| 1116 | + const cells = h.cells || []; | |
| 1117 | + if(!cells.length){ host.innerHTML = stEmpty(h.title); return; } | |
| 1118 | + const grid = Array.from({length:7}, ()=>Array(24).fill(0)); | |
| 1119 | + cells.forEach(c => { if(c.dow>=0 && c.dow<7 && c.hour>=0 && c.hour<24) grid[c.dow][c.hour] = c.value; }); | |
| 1120 | + const max = Math.max(...cells.map(c=>c.value), 1); | |
| 1121 | + const DAYS = ["Lun","Mar","Mer","Jeu","Ven","Sam","Dim"]; | |
| 1122 | + const CW=17, CH=17, OX=38, OY=16; | |
| 1123 | + let rects = ""; | |
| 1124 | + for(let d=0; d<7; d++){ | |
| 1125 | + rects += `<text x="${OX-6}" y="${OY+d*CH+12}" text-anchor="end" font-size="9.5" fill="var(--ink-3)" font-family="var(--font-mono)">${DAYS[d]}</text>`; | |
| 1126 | + for(let hr=0; hr<24; hr++){ | |
| 1127 | + const v = grid[d][hr]; | |
| 1128 | + rects += `<rect x="${OX+hr*CW}" y="${OY+d*CH}" width="${CW-2}" height="${CH-2}" rx="2.5" | |
| 1129 | + fill="${v?"var(--accent)":"rgba(20,24,20,0.07)"}" fill-opacity="${v?(.22+.78*v/max).toFixed(3):1}" | |
| 1130 | + stroke="rgba(20,24,20,0.15)" stroke-width=".5"> | |
| 1131 | + <title>${DAYS[d]} ${hr} h — ${fmtN(v)} événement${v>1?"s":""}</title></rect>`; | |
| 1132 | + } | |
| 1133 | + } | |
| 1134 | + for(let hr=0; hr<24; hr+=3){ | |
| 1135 | + rects += `<text x="${OX+hr*CW+(CW-2)/2}" y="${OY-5}" text-anchor="middle" font-size="9" fill="var(--ink-3)" font-family="var(--font-mono)">${hr} h</text>`; | |
| 1136 | + } | |
| 1137 | + host.innerHTML = `<figure class="gk-card st-fig"> | |
| 1138 | + <figcaption><b>${esc(h.title)}</b></figcaption> | |
| 1139 | + <div class="tbl-wrap" style="margin-top:12px"> | |
| 1140 | + <svg viewBox="0 0 ${OX+24*CW} ${OY+7*CH}" style="min-width:480px" role="img" aria-label="${esc(h.title)}">${rects}</svg> | |
| 1141 | + </div></figure>`; | |
| 1142 | +} | |
| 1143 | + | |
| 894 | 1144 | /* ---- anneau ---- */ |
| 895 | 1145 | function stDonut(host, title, items){ |
| 896 | 1146 | const rows = (items||[]).filter(r=>r.value>0).slice(0,8); |
@@ -1002,21 +1252,28 @@ function stRender(){ | ||
| 1002 | 1252 | $("st-refresh").onclick = stFetch; |
| 1003 | 1253 | |
| 1004 | 1254 | $("st-kpis").innerHTML = (d.kpis||[]).map(stKpi).join("") || stEmpty("Indicateurs"); |
| 1255 | + $("st-gauges").innerHTML = (d.gauges||[]).map(stGauge).join(""); | |
| 1005 | 1256 | |
| 1006 | 1257 | const mount = (parent) => { const el = document.createElement("div"); parent.appendChild(el); return el; }; |
| 1007 | 1258 | $("st-series").innerHTML = ""; |
| 1008 | 1259 | (d.series||[]).forEach(s => { |
| 1009 | 1260 | const el = mount($("st-series")); |
| 1010 | − if(s.kind === "bar") stBars(el, s.title, (s.points||[]).map(p=>({label:p.t,value:p.v})), s.unit); | |
| 1261 | + if(s.kind === "bar") stVBar(el, s.title, (s.points||[]).map(p=>({label:p.t,value:p.v})), s.unit); | |
| 1011 | 1262 | else stLine(el, s); |
| 1012 | 1263 | }); |
| 1013 | 1264 | |
| 1265 | + $("st-multi").innerHTML = ""; | |
| 1266 | + (d.multiseries||[]).forEach(ms => stMulti(mount($("st-multi")), ms)); | |
| 1267 | + (d.stacked||[]).forEach(sp => stStacked(mount($("st-multi")), sp)); | |
| 1268 | + | |
| 1014 | 1269 | $("st-breaks").innerHTML = ""; |
| 1015 | 1270 | (d.breakdowns||[]).filter(b=>b.id!=="sources").forEach(b => { |
| 1016 | 1271 | const el = mount($("st-breaks")); |
| 1017 | 1272 | if(b.kind === "donut") stDonut(el, b.title, b.items); |
| 1018 | 1273 | else stBars(el, b.title, b.items); |
| 1019 | 1274 | }); |
| 1275 | + (d.distributions||[]).forEach(di => | |
| 1276 | + stVBar(mount($("st-breaks")), di.title, di.bins, di.unit)); | |
| 1020 | 1277 | |
| 1021 | 1278 | $("st-geosrc").innerHTML = ""; |
| 1022 | 1279 | if(d.geo) stBars(mount($("st-geosrc")), d.geo.title || "Par région", d.geo.items); |
@@ -1026,6 +1283,9 @@ function stRender(){ | ||
| 1026 | 1283 | $("st-heat").innerHTML = ""; |
| 1027 | 1284 | if(d.heatmap) stHeat(mount($("st-heat")), d.heatmap); |
| 1028 | 1285 | |
| 1286 | + $("st-hourly").innerHTML = ""; | |
| 1287 | + if(d.hourly) stHourly(mount($("st-hourly")), d.hourly); | |
| 1288 | + | |
| 1029 | 1289 | $("st-tables").innerHTML = ""; |
| 1030 | 1290 | (d.tables||[]).forEach(t => stTable(mount($("st-tables")), t)); |
| 1031 | 1291 | |
@@ -1036,7 +1296,7 @@ function stRender(){ | ||
| 1036 | 1296 | <span class="rv"><b>${esc(r.value)}</b>${r.date?`<span class="klabel">${esc(r.date)}</span>`:""}</span></article>`).join(""); |
| 1037 | 1297 | } |
| 1038 | 1298 | |
| 1039 | −/* ---- bouton PDF (complet / synthèse, indicateur si > 2 s) ---- */ | |
| 1299 | +/* ---- boutons PDF : rapport complet + menu des 4 autres rapports ---- */ | |
| 1040 | 1300 | function stPdf(mode, btn){ |
| 1041 | 1301 | const original = btn.textContent; |
| 1042 | 1302 | btn.disabled = true; btn.textContent = "Génération…"; |
@@ -1047,6 +1307,21 @@ function stPdf(mode, btn){ | ||
| 1047 | 1307 | setTimeout(()=>{ btn.disabled = false; btn.textContent = original; }, 2500); |
| 1048 | 1308 | } |
| 1049 | 1309 | |
| 1310 | +function stPdfMenu(open){ | |
| 1311 | + const drop = $("st-pdf-drop"), more = $("st-pdf-more"); | |
| 1312 | + const on = open === undefined ? drop.classList.contains("hidden") : open; | |
| 1313 | + drop.classList.toggle("hidden", !on); | |
| 1314 | + more.setAttribute("aria-expanded", String(on)); | |
| 1315 | +} | |
| 1316 | +$("st-pdf-more").onclick = e => { e.stopPropagation(); stPdfMenu(); }; | |
| 1317 | +$("st-pdf-drop").querySelectorAll("[data-mode]").forEach(b => b.onclick = e => { | |
| 1318 | + stPdfMenu(false); | |
| 1319 | + stPdf(b.dataset.mode, $("st-pdf-more")); | |
| 1320 | +}); | |
| 1321 | +document.addEventListener("click", e => { | |
| 1322 | + if(!e.target.closest(".st-pdf-menu")) stPdfMenu(false); | |
| 1323 | +}); | |
| 1324 | + | |
| 1050 | 1325 | function showStats(){ |
| 1051 | 1326 | document.title = "Statistiques — Sorti-Ka | Un service Groupe KA"; |
| 1052 | 1327 | show("view-stats"); |
@@ -1055,7 +1330,6 @@ function showStats(){ | ||
| 1055 | 1330 | } |
| 1056 | 1331 | |
| 1057 | 1332 | $("st-pdf-full").onclick = e => stPdf("complet", e.currentTarget); |
| 1058 | −$("st-pdf-syn").onclick = e => stPdf("synthese", e.currentTarget); | |
| 1059 | 1333 | stRenderPeriods(); |
| 1060 | 1334 | |
| 1061 | 1335 | /* ---------- vues ---------- */ |
modified
frontend/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, "&").replace(/</g, "<").replace(/>/g, ">"); |
| 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*>|^\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
frontend/src/ka/stats/SPEC.md
+128 −66
@@ -1,53 +1,88 @@ | ||
| 1 | −# ka-stats — module Stats commun Groupe KA (spec v1) | |
| 1 | +# ka-stats — module Stats commun Groupe KA (spec v2) | |
| 2 | 2 | |
| 3 | −Contrat partagé par les 12 plateformes pour leurs pages **/stats** (tableau de | |
| 4 | −bord analytique) et l'**export PDF** estampillé Groupe-KA. Le visuel suit le | |
| 5 | −design system ka-ui (tokens.css) avec l'accent de la marque. | |
| 3 | +Contrat partagé par les plateformes pour leurs pages **/stats** (tableau de | |
| 4 | +bord analytique) et les **exports PDF** estampillés Groupe-KA. Le visuel suit | |
| 5 | +le design system ka-ui (tokens.css) avec l'accent de la marque. | |
| 6 | + | |
| 7 | +**v2 (2026-08-19)** : sparklines dans les KPI, jauges, multi-courbes, | |
| 8 | +barres empilées, distributions (histogrammes), heatmap horaire 7×24, deltas | |
| 9 | +sur les répartitions, statistiques de séries (min/max/moy/méd/σ), et **5 | |
| 10 | +rapports PDF** au lieu de 2. Tous les nouveaux champs sont **optionnels** : | |
| 11 | +un dashboard v1 reste valide et se rend tel quel. | |
| 6 | 12 | |
| 7 | 13 | ## 1. Page /stats — structure obligatoire (dans cet ordre) |
| 8 | 14 | |
| 9 | −1. **Bandeau KPI** : 4–6 grandes cartes (`KpiCard`) — valeur, libellé, | |
| 10 | − variation vs période précédente (▲/▼ + %, vert `--green` / rouge `--danger`). | |
| 15 | +1. **Bandeau KPI** : 6–10 grandes cartes (`KpiCard`) — valeur, libellé, | |
| 16 | + variation vs période précédente (▲/▼ + %, vert `--green` / rouge | |
| 17 | + `--danger`), **sparkline** de tendance quand une série existe. | |
| 11 | 18 | 2. **Sélecteur de période global** (`PeriodSelector`) : `aujourd'hui · 7 j · |
| 12 | 19 | 30 j · 3 m · 6 m · 12 m · année en cours · tout` + plage personnalisée |
| 13 | 20 | (2 champs date). Toute la page se recalcule (state → refetch dashboard). |
| 14 | −3. **Graphiques** : courbes d'évolution (`LineChart`, survol = infobulle, | |
| 15 | − légende cliquable pour masquer une série, comparaison N vs N-1 en | |
| 16 | − pointillé), barres (`BarChart`), anneaux (`Donut`), calendrier de chaleur | |
| 17 | − (`CalendarHeatmap`) quand pertinent. | |
| 18 | −4. **Répartition géographique** (par ville/région) quand pertinent — barres | |
| 19 | − horizontales triées (pas besoin de vraie carte). | |
| 20 | −5. **Tableaux détaillés** (`DataTable`) : tri par colonne, recherche interne, | |
| 21 | +3. **Jauges** (`GaugeCard`) quand pertinent : taux, couvertures, complétude. | |
| 22 | +4. **Graphiques d'évolution** : courbes/aires (`LineChart`, survol = | |
| 23 | + infobulle, légende cliquable, comparaison N vs N-1 en pointillé), barres | |
| 24 | + verticales (`VBarChart` — volumes quotidiens), **multi-courbes ≤ 4 séries** | |
| 25 | + (`MultiLineChart` — motifs de trait distincts, jamais la couleur seule), | |
| 26 | + **barres empilées** (`StackedBarChart` — composition dans le temps). | |
| 27 | + Sous les courbes clés : `StatSummary` (min/max/moyenne/médiane/écart-type). | |
| 28 | +5. **Répartitions** : barres horizontales (`BarChart`, deltas optionnels), | |
| 29 | + anneaux (`Donut`), **distributions/histogrammes** (`Histogram`). | |
| 30 | +6. **Répartition géographique** (par ville/région) — barres horizontales | |
| 31 | + triées (pas besoin de vraie carte). | |
| 32 | +7. **Calendriers** : `CalendarHeatmap` (26 semaines) et, quand l'activité | |
| 33 | + horaire est journalisée, `HourHeatmap` (7 jours × 24 h). | |
| 34 | +8. **Tableaux détaillés** (`DataTable`) : tri par colonne, recherche interne, | |
| 21 | 35 | pagination (25/pg), débordement horizontal propre sur mobile (.tbl-wrap). |
| 22 | −6. **Records & faits marquants** : générés depuis les données (jour record, | |
| 23 | − plus forte croissance, meilleure entrée…) — cartes compactes. | |
| 24 | −7. **Fraîcheur** : « Mis à jour le {date heure} » + bouton Rafraîchir. | |
| 25 | −8. **Bouton PDF** bien visible en haut : « Télécharger le rapport PDF » avec | |
| 26 | − deux choix (Rapport complet / Synthèse 2 pages). Indicateur de progression | |
| 27 | − si > 2 s. | |
| 36 | + Viser 3 à 5 tableaux par plateforme. | |
| 37 | +9. **Records & faits marquants** : générés depuis les données (jour record, | |
| 38 | + plus forte croissance, meilleure entrée…) — cartes compactes, 6–12. | |
| 39 | +10. **Fraîcheur** : « Mis à jour le {date heure} » + bouton Rafraîchir. | |
| 40 | +11. **Bouton PDF** bien visible en haut (`PdfButton`) : bouton principal | |
| 41 | + « Rapport PDF complet » + menu « Autres rapports ▾ » listant les | |
| 42 | + **5 rapports** (voir §3). Indicateur de progression si > 2 s. | |
| 28 | 43 | |
| 29 | 44 | Responsive : KPI empilés < 768 px, graphiques pleine largeur redimensionnés |
| 30 | 45 | (SVG viewBox), tableaux en défilement horizontal contenu, tactile ≥ 44 px. |
| 31 | 46 | AUCUNE donnée inventée : une stat indisponible = bloc « Pas encore mesuré » |
| 32 | 47 | (carte grise propre), jamais un faux chiffre. |
| 33 | 48 | |
| 49 | +Accessibilité (règles fermes) : un seul axe Y par graphique (jamais de | |
| 50 | +double échelle) ; ≥ 2 séries ⇒ légende obligatoire ; l'identité d'une série | |
| 51 | +multi-courbes passe par le **motif de trait** en plus de la couleur ; le | |
| 52 | +texte reste en encre (jamais coloré à la couleur de série) ; chaque | |
| 53 | +graphique a son infobulle de survol et un équivalent tableau existe. | |
| 54 | + | |
| 34 | 55 | ## 2. API — contrat commun |
| 35 | 56 | |
| 36 | 57 | `GET /api/stats/dashboard?period=7j|30j|3m|6m|12m|annee|tout|auj&from=YYYY-MM-DD&to=YYYY-MM-DD` |
| 37 | 58 | |
| 38 | 59 | ```jsonc |
| 39 | 60 | { |
| 40 | − "updated": "2026-08-17T21:04:00-04:00", | |
| 41 | − "period": { "from": "2026-07-18", "to": "2026-08-17", "label": "30 jours" }, | |
| 61 | + "updated": "2026-08-19T01:00:00-04:00", | |
| 62 | + "period": { "from": "2026-07-20", "to": "2026-08-19", "label": "30 jours" }, | |
| 42 | 63 | "kpis": [ { "id": "total", "label": "Annonces actives", "value": 33744, |
| 43 | − "unit": "", "delta_pct": 4.2, "direction": "up" } ], | |
| 64 | + "unit": "", "delta_pct": 4.2, "direction": "up", | |
| 65 | + "spark": [{ "t": "2026-08-01", "v": 31200 }] } ], // spark optionnel | |
| 66 | + "gauges": [ { "id": "geo", "label": "Fiches géolocalisées", "value": 92, | |
| 67 | + "max": 100, "unit": "%" } ], // optionnel | |
| 44 | 68 | "series": [ { "id": "vol", "title": "Annonces actives par jour", "unit": "annonces", |
| 45 | − "kind": "line", "points": [{ "t": "2026-07-18", "v": 31200 }], | |
| 46 | − "compare": [{ "t": "2025-07-18", "v": 24100 }] } ], | |
| 47 | − "breakdowns": [ { "id": "types", "title": "Par type", "kind": "donut", | |
| 48 | − "items": [{ "label": "4½", "value": 9120 }] } ], | |
| 69 | + "kind": "line", // line | bar | area | |
| 70 | + "points": [{ "t": "2026-07-20", "v": 31200 }], | |
| 71 | + "compare": [{ "t": "2025-07-20", "v": 24100 }] } ], | |
| 72 | + "multiseries": [ { "id": "seg", "title": "Prix médian par taille", "unit": "$", | |
| 73 | + "series": [ { "label": "3½", "points": [/* … */] }, | |
| 74 | + { "label": "4½", "points": [/* … */] } ] } ], // ≤ 4 | |
| 75 | + "stacked": [ { "id": "src", "title": "Ajouts par source", "unit": "ajouts", | |
| 76 | + "keys": ["Kijiji", "Centris", "Autres"], | |
| 77 | + "points": [{ "t": "2026-08-01", "values": [120, 80, 30] }] } ], | |
| 78 | + "breakdowns": [ { "id": "types", "title": "Par type", "kind": "donut", // donut | bars | |
| 79 | + "items": [{ "label": "4½", "value": 9120, "delta_pct": 2.1 }] } ], | |
| 80 | + "distributions": [ { "id": "prix", "title": "Distribution des loyers", "unit": "annonces", | |
| 81 | + "bins": [{ "label": "800-1000$", "value": 3120 }] } ], | |
| 49 | 82 | "geo": { "title": "Par région", "items": [{ "label": "Montréal", "value": 15680 }] }, |
| 50 | 83 | "heatmap": { "title": "Activité", "cells": [{ "date": "2026-08-01", "value": 210 }] }, |
| 84 | + "hourly": { "title": "Activité par heure", | |
| 85 | + "cells": [{ "dow": 0, "hour": 9, "value": 40 }] }, // dow 0=lun … 6=dim | |
| 51 | 86 | "tables": [ { "id": "top", "title": "Top villes", "columns": ["Ville", "Annonces", "Δ 30 j"], |
| 52 | 87 | "rows": [["Montréal", 15680, "+3,1 %"]] } ], |
| 53 | 88 | "records": [ { "label": "Jour record d'ajouts", "value": "412 annonces", "date": "2026-08-09" } ] |
@@ -56,23 +91,40 @@ AUCUNE donnée inventée : une stat indisponible = bloc « Pas encore mesuré » | ||
| 56 | 91 | |
| 57 | 92 | Champs absents = section masquée. Cache serveur recommandé (≥ 5 min par |
| 58 | 93 | période). Les valeurs proviennent des données réelles (DB de la plateforme, |
| 59 | −journaux de sync des connecteurs, /api/v1/runs d'API-KA…). | |
| 94 | +journaux de sync des connecteurs, /api/v1/runs d'API-KA…). Arrondir les | |
| 95 | +`delta_pct` à 1 décimale côté serveur. | |
| 60 | 96 | |
| 61 | −`GET /api/stats/report?period=…&from=&to=&mode=complet|synthese` | |
| 97 | +## 3. Rapports PDF — 5 modes | |
| 98 | + | |
| 99 | +`GET /api/stats/report?period=…&from=&to=&mode=complet|synthese|tendances|repartitions|donnees` | |
| 62 | 100 | → `application/pdf`, en-tête `Content-Disposition: attachment; filename= |
| 63 | −groupe-ka_<plateforme>_stats_<periode>_<YYYY-MM-DD>.pdf`. | |
| 101 | +groupe-ka_<plateforme>_stats_<periode>[_<mode>]_<YYYY-MM-DD>.pdf` | |
| 102 | +(pas de suffixe pour `complet` — rétrocompatible v1 ; `kapdf.filename()` | |
| 103 | +accepte maintenant `mode` en 3e argument). | |
| 104 | + | |
| 105 | +| Mode | Contenu | | |
| 106 | +|---|---| | |
| 107 | +| `complet` | tout : sommaire, KPI, jauges, séries + stats de séries, multi-séries, empilées, répartitions, distributions, géo, heatmap horaire, tableaux (200 lignes), records | | |
| 108 | +| `synthese` | couverture + KPI + jauges + records (2–3 pages) | | |
| 109 | +| `tendances` | KPI + toutes les séries temporelles + min/max/moy/méd/σ + records | | |
| 110 | +| `repartitions` | breakdowns, distributions, géo, activité horaire | | |
| 111 | +| `donnees` | tous les tableaux en version longue (400 lignes) | | |
| 64 | 112 | |
| 65 | −## 3. PDF — gabarit Groupe-KA (implémentations : `kapdf.py` fpdf2 pour les | |
| 66 | −apps Python ; les apps Next portent le même gabarit en pdfkit) | |
| 113 | +Un `mode` inconnu retombe sur `complet`. Le gabarit (implémentations : | |
| 114 | +`kapdf.py` fpdf2 pour les apps Python ; les apps Next portent le même | |
| 115 | +gabarit en pdfkit) : | |
| 67 | 116 | |
| 68 | 117 | - **Couverture** : cadre encre, kicker « GROUPE KA · RAPPORT STATISTIQUE », |
| 69 | − wordmark de la plateforme (boîte encre + accent), sous-titre, période | |
| 70 | − couverte, date/heure de génération, bande encre au pied avec | |
| 118 | + wordmark de la plateforme (boîte encre + accent), **type de rapport**, | |
| 119 | + période couverte, date/heure de génération, bande encre au pied avec | |
| 71 | 120 | « par Groupe KA — groupe-ka.com ». |
| 72 | −- **Sommaire** avec numéros de pages (mode complet). | |
| 73 | −- **KPI** : grille de cartes (bordure encre, valeur en gros, delta coloré). | |
| 121 | +- **Sommaire** avec numéros de pages (modes complet et donnees). | |
| 122 | +- **KPI** : grille de cartes (bordure encre, valeur en gros, delta coloré | |
| 123 | + arrondi à 1 décimale). **Jauges** : demi-arcs accent. | |
| 74 | 124 | - **Graphiques VECTORIELS** (dessinés en primitives, jamais de capture) : |
| 75 | − courbes, barres, anneaux — accent de la plateforme, axes/graduations encre. | |
| 125 | + courbes/aires, barres verticales, multi-courbes (motifs distincts), | |
| 126 | + empilées (nuances d'accent), anneaux, heatmap horaire — accent de la | |
| 127 | + plateforme, axes/graduations encre. | |
| 76 | 128 | - **Tableaux** paginés proprement (lignes zébrées `--surface-2`, jamais |
| 77 | 129 | coupés en deux à cheval sur une ligne). |
| 78 | 130 | - **Records** puis **page de fin** : coordonnées Groupe KA (3 courriels + |
@@ -81,43 +133,53 @@ apps Python ; les apps Next portent le même gabarit en pdfkit) | ||
| 81 | 133 | - **Chaque page** : en-tête discret (« Groupe KA · {Plateforme} », filet |
| 82 | 134 | encre) + pied (« © Groupe-KA — {année} — groupe-ka.com · {période} · p. X/Y »). |
| 83 | 135 | - A4 portrait, marges 18 mm, typo : Helvetica (fallback sûr) ou fonts TTF du |
| 84 | − DS si présentes. Mode « synthese » = couverture + 1 page KPI/records. | |
| 136 | + DS si présentes. | |
| 85 | 137 | |
| 86 | 138 | ## 4. Spécifique par plateforme (sections métier attendues) |
| 87 | 139 | |
| 88 | −- **groupe-ka** : tableau de bord maître — consolidation des 12 (volume total, | |
| 89 | − croissance), classement des plateformes, bloc résumé par plateforme + lien | |
| 140 | +- **groupe-ka** : tableau de bord maître — consolidation des plateformes | |
| 141 | + (volume total, croissance), classement, bloc résumé par plateforme + lien | |
| 90 | 142 | vers sa page /stats ; « Rapport écosystème complet » = PDF consolidé. |
| 91 | 143 | - **lou-ka** : annonces actives/nouvelles/retirées, loyers moyens/médians par |
| 92 | − ville & taille, évolution, répartition par type, top villes. | |
| 93 | −- **immo-ka** : annonces actives/nouvelles/vendues-retirées, prix moyen/médian | |
| 94 | − par ville/région/type, délai de présence, top villes, tension du marché. | |
| 144 | + ville & taille (multiseries), distribution des loyers, évolution, | |
| 145 | + répartition par type, top villes, sources (stacked). | |
| 146 | +- **immo-ka** : annonces actives/nouvelles/vendues-retirées, prix | |
| 147 | + moyen/médian par ville/région/type (multiseries), distribution des prix, | |
| 148 | + délai de présence, top villes, tension du marché. | |
| 95 | 149 | - **vrai-prix** : couverture du rôle (unités, valeur totale), estimations |
| 96 | − servies si journalisées, répartitions par municipalité/type, indices marché. | |
| 97 | −- **auto-ka** : volume par marque/modèle/année/carburant/boîte, prix moyens et | |
| 98 | − km moyens par segment, top marques/modèles. | |
| 99 | −- **fabri-ka** : produits par catégorie/région/boutique, fourchettes de prix, | |
| 100 | − nouveautés par période, top catégories. | |
| 101 | −- **food-ka** : produits suivis, relevés de prix, soldes détectés (baisses/ | |
| 102 | − hausses, amplitude), top produits en solde, prix moyens par catégorie. | |
| 103 | −- **resto-ka** : restos par cuisine/ville/gamme, menus & plats, nouveautés/ | |
| 104 | − fermetures détectées, top établissements. | |
| 150 | + servies si journalisées, répartitions par municipalité/type, distribution | |
| 151 | + des valeurs, indices marché. | |
| 152 | +- **auto-ka** : volume par marque/modèle/année/carburant/boîte, prix moyens | |
| 153 | + et km moyens par segment (multiseries), distributions prix/km/année, | |
| 154 | + top marques/modèles. | |
| 155 | +- **fabri-ka** : produits par catégorie/région/boutique, fourchettes de prix | |
| 156 | + (distribution), nouveautés par période, top catégories. | |
| 157 | +- **food-ka** : produits suivis, relevés de prix, soldes détectés | |
| 158 | + (baisses/hausses, amplitude — stacked), top produits en solde, prix moyens | |
| 159 | + par catégorie, distribution des rabais. | |
| 160 | +- **resto-ka** : restos par cuisine/ville/gamme, menus & plats, distribution | |
| 161 | + des prix de plats, nouveautés/fermetures détectées, top établissements. | |
| 105 | 162 | - **sorti-ka** : événements à venir/passés par catégorie/ville, gratuits vs |
| 106 | − payants, heatmap calendrier, top lieux. | |
| 107 | −- **crea-ka** : créateurs par plateforme/niche/tier, comptes reliés, top | |
| 108 | − créateurs, croissance du répertoire. | |
| 109 | −- **trouve-ka** : pages indexées, domaines, rythme de crawl (indexées/h), | |
| 110 | − erreurs, file frontier, tendances si les requêtes sont journalisées. | |
| 111 | −- **api-ka** : appels par endpoint/jour/heure, latences moyennes + p95, taux | |
| 112 | − d'erreur, top endpoints, uptime (données des middlewares de logging + runs). | |
| 113 | −- **Transverse (tous)** : volume total agrégé + croissance, connecteurs actifs | |
| 114 | − et éléments ajoutés/mis à jour par période (journaux de sync), complétude/ | |
| 115 | − fraîcheur moyenne des fiches quand mesurable. Trafic web : seulement si des | |
| 116 | − journaux d'accès existent — sinon état vide propre. | |
| 163 | + payants (stacked), heatmap calendrier + horaire, top lieux. | |
| 164 | +- **crea-ka** : créateurs par plateforme/niche/tier, comptes reliés | |
| 165 | + (stacked par plateforme), distribution des audiences, top créateurs, | |
| 166 | + croissance du répertoire. | |
| 167 | +- **trouve-ka** : pages indexées, domaines, rythme de crawl (indexées/h — | |
| 168 | + hourly), erreurs, file frontier, tendances des requêtes journalisées. | |
| 169 | +- **api-ka** : appels par endpoint/jour/heure (hourly), latences moyennes + | |
| 170 | + p95 (multiseries), taux d'erreur, top endpoints/clés, uptime. | |
| 171 | +- **job-ka** : offres actives/nouvelles/expirées par catégorie/ville/ | |
| 172 | + entreprise, distribution des salaires affichés, top employeurs. | |
| 173 | +- **Transverse (tous)** : volume total agrégé + croissance, connecteurs | |
| 174 | + actifs et éléments ajoutés/mis à jour par période (journaux de sync — | |
| 175 | + stacked par source quand possible), complétude/fraîcheur moyenne des | |
| 176 | + fiches quand mesurable (jauges). Trafic web : seulement si des journaux | |
| 177 | + d'accès existent — sinon état vide propre. | |
| 117 | 178 | |
| 118 | 179 | ## 5. Ajouter une métrique / un graphique / une plateforme |
| 119 | 180 | |
| 120 | −1 métrique = 1 entrée `kpis[]` ou `series[]` côté API (requête SQL agrégée + | |
| 121 | −cache) — le front la rend automatiquement. 1 plateforme = implémenter les 2 | |
| 122 | −endpoints du contrat + une page /stats montée sur les composants du kit + | |
| 123 | −`kapdf.py` (ou gabarit pdfkit) branché sur le même JSON de dashboard. | |
| 181 | +1 métrique = 1 entrée `kpis[]`, `series[]`, `multiseries[]`, `stacked[]`, | |
| 182 | +`distributions[]` ou `gauges[]` côté API (requête SQL agrégée + cache) — le | |
| 183 | +front la rend automatiquement. 1 plateforme = implémenter les 2 endpoints du | |
| 184 | +contrat + une page /stats montée sur les composants du kit + `kapdf.py` (ou | |
| 185 | +gabarit pdfkit) branché sur le même JSON de dashboard. | |
modified
frontend/src/ka/stats/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
sortika/kapdf.py
+388 −69
@@ -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 | |
@@ -95,6 +111,8 @@ class _PDF(FPDF): | ||
| 95 | 111 | self.set_y(20) |
| 96 | 112 | |
| 97 | 113 | def footer(self): |
| 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) | |
| 98 | 116 | if self.cover_mode or self.page_no() == 1: |
| 99 | 117 | return |
| 100 | 118 | self.set_y(-15) |
@@ -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
sortika/stats.py
+326 −23
@@ -2,8 +2,12 @@ | ||
| 2 | 2 | # Sorti-Ka — Agrégateur de sorties & événements (province de Québec) |
| 3 | 3 | # Auteur : Simon-Pierre Boucher — contact@spboucher.ai |
| 4 | 4 | # stats.py : tableau de bord analytique /api/stats/dashboard (contrat ka-stats |
| 5 | −# SPEC.md) — agrégations SQL réelles sur events/sync_log, AUCUNE | |
| 5 | +# SPEC.md v2) — agrégations SQL réelles sur events/sync_log, AUCUNE | |
| 6 | 6 | # statistique inventée, cache mémoire 5 min par période. |
| 7 | +# v2 : sparklines KPI, jauges, multi-courbes (top catégories), | |
| 8 | +# barres empilées (sources, gratuits vs payants), distributions | |
| 9 | +# (prix, durée), heatmap horaire 7×24, deltas de répartitions, | |
| 10 | +# 5 tableaux, ~10 records. | |
| 7 | 11 | # ----------------------------------------------------------------------------- |
| 8 | 12 | from __future__ import annotations |
| 9 | 13 | |
@@ -21,6 +25,7 @@ _cache: dict[tuple, tuple[float, dict]] = {} | ||
| 21 | 25 | HEATMAP_DAYS = 182 # 26 semaines de calendrier des dates d'événements |
| 22 | 26 | ONGOING_DAYS = 30 # série « se déroulant par jour » (30 prochains jours) |
| 23 | 27 | BIGDAYS_HORIZON = 90 # tableau « prochains gros jours » |
| 28 | +WEEKLY_OVER = 62 # au-delà de N jours, empilées/multi-courbes par semaine | |
| 24 | 29 | |
| 25 | 30 | # Libellés humains (mêmes que le frontend — taxonomie sortika/normalize.py) |
| 26 | 31 | CAT_LABELS = { |
@@ -34,7 +39,10 @@ SRC_LABELS = { | ||
| 34 | 39 | "sitq": "SIT Québec (MTO)", "montreal": "Ville de Montréal", |
| 35 | 40 | "laval": "Ville de Laval", "lepointdevente": "Le point de vente", |
| 36 | 41 | "evenko": "evenko", "atuvu": "Atuvu.ca", "lavitrine": "La Vitrine", |
| 37 | − "sherbrooke": "Ville de Sherbrooke", | |
| 42 | + "sherbrooke": "Ville de Sherbrooke", "eventbrite": "Eventbrite", | |
| 43 | + "ticketmaster": "Ticketmaster", "bandsintown": "Bandsintown", | |
| 44 | + "brossard": "Ville de Brossard", "longueuil": "Ville de Longueuil", | |
| 45 | + "cantonsdelest": "Cantons-de-l'Est (ATR)", | |
| 38 | 46 | } |
| 39 | 47 | |
| 40 | 48 | PERIOD_DAYS = {"7j": 7, "30j": 30, "3m": 91, "6m": 182, "12m": 365} |
@@ -44,6 +52,12 @@ PERIOD_LABELS = { | ||
| 44 | 52 | "tout": "Toute la période", |
| 45 | 53 | } |
| 46 | 54 | |
| 55 | +PRICE_BINS = [(0, 10), (10, 20), (20, 30), (30, 50), (50, 75), (75, 100), | |
| 56 | + (100, 150), (150, None)] | |
| 57 | +DURATION_BINS = [("1 jour", 1, 1), ("2-3 jours", 2, 3), ("4-7 jours", 4, 7), | |
| 58 | + ("1-2 semaines", 8, 14), ("2-4 semaines", 15, 28), | |
| 59 | + ("1-3 mois", 29, 92), ("3 mois +", 93, None)] | |
| 60 | + | |
| 47 | 61 | |
| 48 | 62 | def _parse_iso(s: str) -> date | None: |
| 49 | 63 | try: |
@@ -80,11 +94,13 @@ def _pct(cur: float, prev: float) -> float | None: | ||
| 80 | 94 | return round(100.0 * (cur - prev) / prev, 1) |
| 81 | 95 | |
| 82 | 96 | |
| 83 | −def _kpi(id, label, value, unit="", delta_pct=None) -> dict: | |
| 97 | +def _kpi(id, label, value, unit="", delta_pct=None, spark=None) -> dict: | |
| 84 | 98 | d = {"id": id, "label": label, "value": value, "unit": unit, |
| 85 | 99 | "delta_pct": delta_pct} |
| 86 | 100 | if delta_pct is not None: |
| 87 | 101 | d["direction"] = "up" if delta_pct >= 0 else "down" |
| 102 | + if spark: | |
| 103 | + d["spark"] = spark | |
| 88 | 104 | return d |
| 89 | 105 | |
| 90 | 106 | |
@@ -124,6 +140,25 @@ def _upcoming_where() -> str: | ||
| 124 | 140 | "(end_date IS NULL AND start_date >= :today))") |
| 125 | 141 | |
| 126 | 142 | |
| 143 | +def _buckets(p_from: date, p_to: date) -> tuple[list[date], bool]: | |
| 144 | + """Bornes des seaux temporels (jour, ou lundi de semaine si la période | |
| 145 | + dépasse WEEKLY_OVER jours) couvrant [p_from, p_to].""" | |
| 146 | + length = (p_to - p_from).days + 1 | |
| 147 | + weekly = length > WEEKLY_OVER | |
| 148 | + if not weekly: | |
| 149 | + return [p_from + timedelta(days=i) for i in range(length)], False | |
| 150 | + start = p_from - timedelta(days=p_from.weekday()) # lundi | |
| 151 | + out, d = [], start | |
| 152 | + while d <= p_to: | |
| 153 | + out.append(d) | |
| 154 | + d += timedelta(days=7) | |
| 155 | + return out, True | |
| 156 | + | |
| 157 | + | |
| 158 | +def _bucket_of(d: date, weekly: bool) -> date: | |
| 159 | + return d - timedelta(days=d.weekday()) if weekly else d | |
| 160 | + | |
| 161 | + | |
| 127 | 162 | def dashboard(period: str = "30j", dfrom: str = "", dto: str = "") -> dict: |
| 128 | 163 | key = (period, dfrom, dto) |
| 129 | 164 | hit = _cache.get(key) |
@@ -146,9 +181,21 @@ def dashboard(period: str = "30j", dfrom: str = "", dto: str = "") -> dict: | ||
| 146 | 181 | free_up = con.execute( |
| 147 | 182 | f"SELECT COUNT(*) FROM events WHERE {_upcoming_where()} AND is_free=1", |
| 148 | 183 | tp).fetchone()[0] |
| 184 | + paid_up = con.execute( | |
| 185 | + f"SELECT COUNT(*) FROM events WHERE {_upcoming_where()} AND is_free=0", | |
| 186 | + tp).fetchone()[0] | |
| 187 | + unknown_price_up = upcoming - free_up - paid_up | |
| 188 | + past = con.execute( | |
| 189 | + "SELECT COUNT(*) FROM events WHERE start_date IS NOT NULL " | |
| 190 | + "AND COALESCE(end_date, start_date) < :today", tp).fetchone()[0] | |
| 149 | 191 | cities = con.execute( |
| 150 | 192 | "SELECT COUNT(DISTINCT city) FROM events WHERE active=1 AND city != ''" |
| 151 | 193 | ).fetchone()[0] |
| 194 | + venues_up = con.execute( | |
| 195 | + f"SELECT COUNT(DISTINCT venue) FROM events WHERE {_upcoming_where()} " | |
| 196 | + "AND venue != ''", tp).fetchone()[0] | |
| 197 | + n_sources = con.execute( | |
| 198 | + "SELECT COUNT(DISTINCT source) FROM events WHERE active=1").fetchone()[0] | |
| 152 | 199 | |
| 153 | 200 | added_map = _added_by_day(con, prev_from, p_to) |
| 154 | 201 | added_cur = sum(v for d, v in added_map.items() |
@@ -171,14 +218,32 @@ def dashboard(period: str = "30j", dfrom: str = "", dto: str = "") -> dict: | ||
| 171 | 218 | (p_from.isoformat(), p_from.isoformat())).fetchone()[0] |
| 172 | 219 | prev_active = active - added_active + deactivated |
| 173 | 220 | |
| 221 | + # sparklines : ajouts/jour (période) et « se déroulant » (30 prochains j.) | |
| 222 | + horizon_counts = _ongoing_counts(con, today, HEATMAP_DAYS) | |
| 223 | + spark_added = [{"t": (p_from + timedelta(days=i)).isoformat(), | |
| 224 | + "v": added_map.get((p_from + timedelta(days=i)).isoformat(), 0)} | |
| 225 | + for i in range(length)] | |
| 226 | + spark_up = [{"t": (today + timedelta(days=i)).isoformat(), | |
| 227 | + "v": horizon_counts[i]} for i in range(ONGOING_DAYS)] | |
| 228 | + | |
| 174 | 229 | kpis = [ |
| 175 | 230 | _kpi("actifs", "Événements actifs", active, "", |
| 176 | 231 | _pct(active, prev_active)), |
| 177 | − _kpi("avenir", "Événements à venir", upcoming), | |
| 232 | + _kpi("avenir", "Événements à venir", upcoming, "", None, spark_up), | |
| 233 | + _kpi("ajouts", f"Ajoutés sur la période ({p_label})", added_cur, "", | |
| 234 | + _pct(added_cur, added_prev), spark_added), | |
| 235 | + _kpi("passes", "Événements passés (archives)", past), | |
| 178 | 236 | _kpi("gratuits", "Gratuits à venir", free_up), |
| 237 | + ] | |
| 238 | + if free_up + paid_up > 0: | |
| 239 | + kpis.append(_kpi( | |
| 240 | + "part_gratuits", | |
| 241 | + f"Part de gratuits (sur {free_up + paid_up} avec prix connu)", | |
| 242 | + round(100.0 * free_up / (free_up + paid_up), 1), "%")) | |
| 243 | + kpis += [ | |
| 179 | 244 | _kpi("villes", "Villes couvertes", cities), |
| 180 | − _kpi("ajouts", f"Ajoutés sur la période ({p_label})", added_cur, "", | |
| 181 | − _pct(added_cur, added_prev)), | |
| 245 | + _kpi("lieux", "Lieux référencés (à venir)", venues_up), | |
| 246 | + _kpi("sources_n", "Sources branchées", n_sources), | |
| 182 | 247 | ] |
| 183 | 248 | prices = con.execute( |
| 184 | 249 | f"SELECT COUNT(*), AVG(price_min) FROM events WHERE {_upcoming_where()} " |
@@ -188,13 +253,26 @@ def dashboard(period: str = "30j", dfrom: str = "", dto: str = "") -> dict: | ||
| 188 | 253 | kpis.append(_kpi("prix", f"Prix moyen des billets ({prices[0]} relevés)", |
| 189 | 254 | round(prices[1], 2), "$")) |
| 190 | 255 | |
| 256 | + # ---------- jauges (complétude des fiches à venir) ---------- | |
| 257 | + gauges = [] | |
| 258 | + if upcoming: | |
| 259 | + def _cov(id_, label, where_extra): | |
| 260 | + n = con.execute( | |
| 261 | + f"SELECT COUNT(*) FROM events WHERE {_upcoming_where()} " | |
| 262 | + f"AND {where_extra}", tp).fetchone()[0] | |
| 263 | + gauges.append({"id": id_, "label": label, | |
| 264 | + "value": round(100.0 * n / upcoming, 1), | |
| 265 | + "max": 100, "unit": "%"}) | |
| 266 | + _cov("geo", "Événements géolocalisés", "lat IS NOT NULL AND lng IS NOT NULL") | |
| 267 | + _cov("prixinfo", "Info de prix connue", "is_free IS NOT NULL") | |
| 268 | + _cov("image", "Fiches avec image", "image != ''") | |
| 269 | + _cov("heure", "Heure de début connue", | |
| 270 | + "start_time IS NOT NULL AND start_time != ''") | |
| 271 | + | |
| 191 | 272 | # ---------- séries ---------- |
| 192 | 273 | series = [] |
| 193 | − pts = [{"t": (p_from + timedelta(days=i)).isoformat(), | |
| 194 | − "v": added_map.get((p_from + timedelta(days=i)).isoformat(), 0)} | |
| 195 | − for i in range(length)] | |
| 196 | 274 | s_added = {"id": "ajouts", "title": "Événements ajoutés par jour", |
| 197 | − "unit": "événements", "kind": "line", "points": pts} | |
| 275 | + "unit": "événements", "kind": "line", "points": spark_added} | |
| 198 | 276 | if period not in ("tout", "annee") and not (dfrom and dto): |
| 199 | 277 | s_added["compare"] = [ |
| 200 | 278 | {"t": (prev_from + timedelta(days=i)).isoformat(), |
@@ -202,13 +280,102 @@ def dashboard(period: str = "30j", dfrom: str = "", dto: str = "") -> dict: | ||
| 202 | 280 | for i in range(length)] |
| 203 | 281 | series.append(s_added) |
| 204 | 282 | |
| 205 | − horizon_counts = _ongoing_counts(con, today, HEATMAP_DAYS) | |
| 206 | 283 | series.append({ |
| 207 | 284 | "id": "en_cours", "title": |
| 208 | 285 | f"Événements se déroulant par jour ({ONGOING_DAYS} prochains jours)", |
| 209 | − "unit": "événements", "kind": "line", | |
| 286 | + "unit": "événements", "kind": "line", "points": spark_up}) | |
| 287 | + | |
| 288 | + starts_by_day = {r[0]: r[1] for r in con.execute( | |
| 289 | + "SELECT start_date, COUNT(*) FROM events WHERE active=1 " | |
| 290 | + "AND start_date >= ? GROUP BY start_date", (today.isoformat(),))} | |
| 291 | + series.append({ | |
| 292 | + "id": "debuts", "title": | |
| 293 | + f"Événements débutant par jour ({ONGOING_DAYS} prochains jours)", | |
| 294 | + "unit": "événements", "kind": "bar", | |
| 210 | 295 | "points": [{"t": (today + timedelta(days=i)).isoformat(), |
| 211 | − "v": horizon_counts[i]} for i in range(ONGOING_DAYS)]}) | |
| 296 | + "v": starts_by_day.get((today + timedelta(days=i)).isoformat(), 0)} | |
| 297 | + for i in range(ONGOING_DAYS)]}) | |
| 298 | + | |
| 299 | + # ---------- multi-courbes : ajouts par top catégories (≤ 4) ---------- | |
| 300 | + buckets, weekly = _buckets(p_from, p_to) | |
| 301 | + b_index = {b.isoformat(): i for i, b in enumerate(buckets)} | |
| 302 | + cat_added: dict[str, list[int]] = {} | |
| 303 | + cat_tot: dict[str, int] = {} | |
| 304 | + src_added: dict[str, list[int]] = {} | |
| 305 | + for r in con.execute( | |
| 306 | + "SELECT date(first_seen,'unixepoch','localtime') AS d, categories, " | |
| 307 | + "source FROM events WHERE d >= ? AND d <= ?", | |
| 308 | + (p_from.isoformat(), p_to.isoformat())): | |
| 309 | + d = _parse_iso(r["d"]) | |
| 310 | + if not d: | |
| 311 | + continue | |
| 312 | + bi = b_index.get(_bucket_of(d, weekly).isoformat()) | |
| 313 | + if bi is None: | |
| 314 | + continue | |
| 315 | + for c in json.loads(r["categories"] or "[]"): | |
| 316 | + cat_added.setdefault(c, [0] * len(buckets))[bi] += 1 | |
| 317 | + cat_tot[c] = cat_tot.get(c, 0) + 1 | |
| 318 | + src_added.setdefault(r["source"], [0] * len(buckets))[bi] += 1 | |
| 319 | + | |
| 320 | + gran = "semaine" if weekly else "jour" | |
| 321 | + multiseries = [] | |
| 322 | + top4 = [c for c, _ in sorted(cat_tot.items(), key=lambda kv: -kv[1])[:4]] | |
| 323 | + if top4 and added_cur: | |
| 324 | + multiseries.append({ | |
| 325 | + "id": "cat_ajouts", | |
| 326 | + "title": f"Ajouts par {gran} — top {len(top4)} catégories", | |
| 327 | + "unit": "événements", | |
| 328 | + "series": [{"label": CAT_LABELS.get(c, c), | |
| 329 | + "points": [{"t": buckets[i].isoformat(), | |
| 330 | + "v": cat_added[c][i]} | |
| 331 | + for i in range(len(buckets))]} | |
| 332 | + for c in top4]}) | |
| 333 | + | |
| 334 | + # ---------- barres empilées ---------- | |
| 335 | + stacked = [] | |
| 336 | + if src_added and added_cur: | |
| 337 | + top_src = [s for s, _ in sorted( | |
| 338 | + ((s, sum(v)) for s, v in src_added.items()), | |
| 339 | + key=lambda kv: -kv[1])[:5]] | |
| 340 | + others = [s for s in src_added if s not in top_src] | |
| 341 | + keys = [SRC_LABELS.get(s, s) for s in top_src] + ( | |
| 342 | + ["Autres"] if others else []) | |
| 343 | + pts = [] | |
| 344 | + for i in range(len(buckets)): | |
| 345 | + vals = [src_added[s][i] for s in top_src] | |
| 346 | + if others: | |
| 347 | + vals.append(sum(src_added[s][i] for s in others)) | |
| 348 | + pts.append({"t": buckets[i].isoformat(), "values": vals}) | |
| 349 | + stacked.append({"id": "src_ajouts", | |
| 350 | + "title": f"Ajouts par {gran} et par source", | |
| 351 | + "unit": "ajouts", "keys": keys, "points": pts}) | |
| 352 | + | |
| 353 | + # gratuits vs payants par semaine de tenue (12 prochaines semaines) | |
| 354 | + monday = today - timedelta(days=today.weekday()) | |
| 355 | + wk_free, wk_paid, wk_unk = [0] * 12, [0] * 12, [0] * 12 | |
| 356 | + for r in con.execute( | |
| 357 | + f"SELECT start_date, is_free FROM events WHERE {_upcoming_where()} " | |
| 358 | + "AND start_date >= :today", tp): | |
| 359 | + d = _parse_iso(r["start_date"]) | |
| 360 | + if not d: | |
| 361 | + continue | |
| 362 | + wi = ((d - timedelta(days=d.weekday())) - monday).days // 7 | |
| 363 | + if 0 <= wi < 12: | |
| 364 | + if r["is_free"] == 1: | |
| 365 | + wk_free[wi] += 1 | |
| 366 | + elif r["is_free"] == 0: | |
| 367 | + wk_paid[wi] += 1 | |
| 368 | + else: | |
| 369 | + wk_unk[wi] += 1 | |
| 370 | + if sum(wk_free) + sum(wk_paid) + sum(wk_unk) > 0: | |
| 371 | + stacked.append({ | |
| 372 | + "id": "gratuite_temps", | |
| 373 | + "title": "Gratuits vs payants — débuts par semaine (12 prochaines)", | |
| 374 | + "unit": "événements", | |
| 375 | + "keys": ["Gratuits", "Payants", "Prix non précisé"], | |
| 376 | + "points": [{"t": (monday + timedelta(days=7 * i)).isoformat(), | |
| 377 | + "values": [wk_free[i], wk_paid[i], wk_unk[i]]} | |
| 378 | + for i in range(12)]}) | |
| 212 | 379 | |
| 213 | 380 | # ---------- répartitions ---------- |
| 214 | 381 | cat_counts: dict[str, int] = {} |
@@ -217,6 +384,21 @@ def dashboard(period: str = "30j", dfrom: str = "", dto: str = "") -> dict: | ||
| 217 | 384 | for c in json.loads(r["categories"] or "[]"): |
| 218 | 385 | cat_counts[c] = cat_counts.get(c, 0) + 1 |
| 219 | 386 | top_cats = sorted(cat_counts.items(), key=lambda kv: -kv[1])[:8] |
| 387 | + | |
| 388 | + # ajouts par région (période vs précédente) — deltas honnêtes | |
| 389 | + reg_cur: dict[str, int] = {} | |
| 390 | + reg_prev: dict[str, int] = {} | |
| 391 | + for r in con.execute( | |
| 392 | + "SELECT region, date(first_seen,'unixepoch','localtime') AS d, " | |
| 393 | + "COUNT(*) AS n FROM events WHERE d >= ? AND d <= ? " | |
| 394 | + "GROUP BY region, d", | |
| 395 | + (prev_from.isoformat(), p_to.isoformat())): | |
| 396 | + lbl = r["region"] or "Non rattachée" | |
| 397 | + if r["d"] >= p_from.isoformat(): | |
| 398 | + reg_cur[lbl] = reg_cur.get(lbl, 0) + r["n"] | |
| 399 | + else: | |
| 400 | + reg_prev[lbl] = reg_prev.get(lbl, 0) + r["n"] | |
| 401 | + | |
| 220 | 402 | breakdowns = [ |
| 221 | 403 | {"id": "categories", "title": "Événements à venir par catégorie (top 8)", |
| 222 | 404 | "kind": "donut", |
@@ -225,12 +407,8 @@ def dashboard(period: str = "30j", dfrom: str = "", dto: str = "") -> dict: | ||
| 225 | 407 | {"id": "gratuite", "title": "Gratuits vs payants (à venir)", "kind": "bar", |
| 226 | 408 | "items": [ |
| 227 | 409 | {"label": "Gratuits", "value": free_up}, |
| 228 | − {"label": "Payants", "value": con.execute( | |
| 229 | − f"SELECT COUNT(*) FROM events WHERE {_upcoming_where()} " | |
| 230 | − "AND is_free=0", tp).fetchone()[0]}, | |
| 231 | − {"label": "Prix non précisé", "value": con.execute( | |
| 232 | − f"SELECT COUNT(*) FROM events WHERE {_upcoming_where()} " | |
| 233 | − "AND is_free IS NULL", tp).fetchone()[0]}, | |
| 410 | + {"label": "Payants", "value": paid_up}, | |
| 411 | + {"label": "Prix non précisé", "value": unknown_price_up}, | |
| 234 | 412 | ]}, |
| 235 | 413 | {"id": "sources", "title": "Événements actifs par source", "kind": "bar", |
| 236 | 414 | "items": [{"label": SRC_LABELS.get(r["source"], r["source"]), |
@@ -239,6 +417,50 @@ def dashboard(period: str = "30j", dfrom: str = "", dto: str = "") -> dict: | ||
| 239 | 417 | "SELECT source, COUNT(*) AS n FROM events WHERE active=1 " |
| 240 | 418 | "GROUP BY source ORDER BY n DESC")]}, |
| 241 | 419 | ] |
| 420 | + if reg_cur: | |
| 421 | + breakdowns.append({ | |
| 422 | + "id": "reg_ajouts", | |
| 423 | + "title": f"Ajouts par région ({p_label}) — Δ vs période précédente", | |
| 424 | + "kind": "bar", | |
| 425 | + "items": [{"label": lbl, "value": n, | |
| 426 | + "delta_pct": _pct(n, reg_prev.get(lbl, 0))} | |
| 427 | + for lbl, n in sorted(reg_cur.items(), | |
| 428 | + key=lambda kv: -kv[1])[:12]]}) | |
| 429 | + | |
| 430 | + # ---------- distributions ---------- | |
| 431 | + distributions = [] | |
| 432 | + price_vals = [r[0] for r in con.execute( | |
| 433 | + f"SELECT price_min FROM events WHERE {_upcoming_where()} " | |
| 434 | + "AND is_free=0 AND price_min IS NOT NULL AND price_min > 0", tp)] | |
| 435 | + if len(price_vals) >= 10: | |
| 436 | + bins = [] | |
| 437 | + for lo, hi in PRICE_BINS: | |
| 438 | + n = sum(1 for v in price_vals | |
| 439 | + if v >= lo and (hi is None or v < hi)) | |
| 440 | + bins.append({"label": f"{lo}-{hi} $" if hi else f"{lo} $ +", | |
| 441 | + "value": n}) | |
| 442 | + distributions.append({ | |
| 443 | + "id": "prix", | |
| 444 | + "title": f"Distribution des prix d'entrée ({len(price_vals)} relevés, à venir)", | |
| 445 | + "unit": "événements", "bins": bins}) | |
| 446 | + dur_bins = [0] * len(DURATION_BINS) | |
| 447 | + n_dur = 0 | |
| 448 | + for r in con.execute( | |
| 449 | + f"SELECT julianday(COALESCE(end_date,start_date)) - " | |
| 450 | + f"julianday(start_date) + 1 AS j FROM events " | |
| 451 | + f"WHERE {_upcoming_where()} AND start_date IS NOT NULL", tp): | |
| 452 | + j = int(r["j"] or 1) | |
| 453 | + n_dur += 1 | |
| 454 | + for i, (_, lo, hi) in enumerate(DURATION_BINS): | |
| 455 | + if j >= lo and (hi is None or j <= hi): | |
| 456 | + dur_bins[i] += 1 | |
| 457 | + break | |
| 458 | + if n_dur: | |
| 459 | + distributions.append({ | |
| 460 | + "id": "duree", "title": "Durée des événements à venir", | |
| 461 | + "unit": "événements", | |
| 462 | + "bins": [{"label": DURATION_BINS[i][0], "value": dur_bins[i]} | |
| 463 | + for i in range(len(DURATION_BINS))]}) | |
| 242 | 464 | |
| 243 | 465 | # ---------- géographie ---------- |
| 244 | 466 | geo = {"title": "Événements à venir par région", "items": [ |
@@ -253,6 +475,29 @@ def dashboard(period: str = "30j", dfrom: str = "", dto: str = "") -> dict: | ||
| 253 | 475 | "value": horizon_counts[i]} |
| 254 | 476 | for i in range(HEATMAP_DAYS)]} |
| 255 | 477 | |
| 478 | + # ---------- heatmap horaire 7×24 : heure de début des événements à venir -- | |
| 479 | + hourly = None | |
| 480 | + hh: dict[tuple[int, int], int] = {} | |
| 481 | + n_hourly = 0 | |
| 482 | + for r in con.execute( | |
| 483 | + f"SELECT start_date, start_time FROM events WHERE {_upcoming_where()} " | |
| 484 | + "AND start_time IS NOT NULL AND start_time != '' " | |
| 485 | + "AND start_date IS NOT NULL", tp): | |
| 486 | + d = _parse_iso(r["start_date"]) | |
| 487 | + try: | |
| 488 | + h = int(str(r["start_time"])[:2]) | |
| 489 | + except ValueError: | |
| 490 | + continue | |
| 491 | + if d is None or not 0 <= h <= 23: | |
| 492 | + continue | |
| 493 | + hh[(d.weekday(), h)] = hh.get((d.weekday(), h), 0) + 1 | |
| 494 | + n_hourly += 1 | |
| 495 | + if n_hourly >= 20: | |
| 496 | + hourly = {"title": f"Débuts d'événements par jour et heure " | |
| 497 | + f"({n_hourly} événements à venir avec heure)", | |
| 498 | + "cells": [{"dow": k[0], "hour": k[1], "value": v} | |
| 499 | + for k, v in sorted(hh.items())]} | |
| 500 | + | |
| 256 | 501 | # ---------- tableaux ---------- |
| 257 | 502 | city_rows = [[r["city"], r["n"], r["g"], |
| 258 | 503 | f"{100.0 * r['n'] / upcoming:.1f} %".replace(".", ",")] |
@@ -266,15 +511,33 @@ def dashboard(period: str = "30j", dfrom: str = "", dto: str = "") -> dict: | ||
| 266 | 511 | f"SELECT venue, city, COUNT(*) AS n FROM events " |
| 267 | 512 | f"WHERE {_upcoming_where()} AND venue != '' " |
| 268 | 513 | "GROUP BY venue, city ORDER BY n DESC LIMIT 40", tp)] |
| 269 | − starts_by_day = {r[0]: r[1] for r in con.execute( | |
| 270 | − "SELECT start_date, COUNT(*) FROM events WHERE active=1 " | |
| 271 | − "AND start_date >= ? GROUP BY start_date", (today.isoformat(),))} | |
| 272 | 514 | big_days = sorted( |
| 273 | 515 | ((today + timedelta(days=i), horizon_counts[i]) |
| 274 | 516 | for i in range(min(BIGDAYS_HORIZON, HEATMAP_DAYS))), |
| 275 | 517 | key=lambda dv: -dv[1])[:15] |
| 276 | 518 | bigday_rows = [[d.isoformat(), n, starts_by_day.get(d.isoformat(), 0)] |
| 277 | 519 | for d, n in big_days] |
| 520 | + org_rows = [[r["organizer"], r["n"], r["g"], r["c"]] | |
| 521 | + for r in con.execute( | |
| 522 | + f"SELECT organizer, COUNT(*) AS n, " | |
| 523 | + f"SUM(CASE WHEN is_free=1 THEN 1 ELSE 0 END) AS g, " | |
| 524 | + f"COUNT(DISTINCT city) AS c FROM events " | |
| 525 | + f"WHERE {_upcoming_where()} AND organizer != '' " | |
| 526 | + "GROUP BY organizer ORDER BY n DESC LIMIT 40", tp)] | |
| 527 | + # sources & connecteurs : actifs, ajoutés (période), dernière synchro OK | |
| 528 | + last_sync = {r["source"]: r["ts"] for r in con.execute( | |
| 529 | + "SELECT source, MAX(ts) AS ts FROM sync_log WHERE error IS NULL " | |
| 530 | + "GROUP BY source")} | |
| 531 | + src_rows = [] | |
| 532 | + for r in con.execute( | |
| 533 | + "SELECT source, COUNT(*) AS n FROM events WHERE active=1 " | |
| 534 | + "GROUP BY source ORDER BY n DESC"): | |
| 535 | + s = r["source"] | |
| 536 | + ts = last_sync.get(s) | |
| 537 | + sync_txt = (datetime.fromtimestamp(ts, TZ).strftime("%Y-%m-%d %H:%M") | |
| 538 | + if ts else "—") | |
| 539 | + src_rows.append([SRC_LABELS.get(s, s), r["n"], | |
| 540 | + sum(src_added.get(s, [])), sync_txt]) | |
| 278 | 541 | tables = [ |
| 279 | 542 | {"id": "villes", "title": "Top villes (événements à venir)", |
| 280 | 543 | "columns": ["Ville", "À venir", "Gratuits", "Part"], "rows": city_rows}, |
@@ -284,6 +547,13 @@ def dashboard(period: str = "30j", dfrom: str = "", dto: str = "") -> dict: | ||
| 284 | 547 | "title": f"Prochains gros jours ({BIGDAYS_HORIZON} jours)", |
| 285 | 548 | "columns": ["Date", "Événements ce jour-là", "Débutent ce jour-là"], |
| 286 | 549 | "rows": bigday_rows}, |
| 550 | + {"id": "organisateurs", "title": "Top organisateurs (à venir)", | |
| 551 | + "columns": ["Organisateur", "À venir", "Gratuits", "Villes"], | |
| 552 | + "rows": org_rows}, | |
| 553 | + {"id": "sources_sync", "title": "Sources & connecteurs", | |
| 554 | + "columns": ["Source", "Événements actifs", f"Ajoutés ({p_label})", | |
| 555 | + "Dernière synchro"], | |
| 556 | + "rows": src_rows}, | |
| 287 | 557 | ] |
| 288 | 558 | |
| 289 | 559 | # ---------- records ---------- |
@@ -293,6 +563,14 @@ def dashboard(period: str = "30j", dfrom: str = "", dto: str = "") -> dict: | ||
| 293 | 563 | records.append({"label": "Jour le plus chargé (26 prochaines semaines)", |
| 294 | 564 | "value": f"{horizon_counts[i_max]:,} événements".replace(",", " "), |
| 295 | 565 | "date": (today + timedelta(days=i_max)).isoformat()}) |
| 566 | + best_w, best_wi = -1, 0 | |
| 567 | + for i in range(HEATMAP_DAYS - 6): | |
| 568 | + s = sum(horizon_counts[i:i + 7]) | |
| 569 | + if s > best_w: | |
| 570 | + best_w, best_wi = s, i | |
| 571 | + records.append({"label": "Semaine la plus chargée (à venir)", | |
| 572 | + "value": f"≈ {round(best_w / 7):,} événements/jour".replace(",", " "), | |
| 573 | + "date": (today + timedelta(days=best_wi)).isoformat()}) | |
| 296 | 574 | add_rec = con.execute( |
| 297 | 575 | "SELECT date(first_seen,'unixepoch','localtime') AS d, COUNT(*) AS n " |
| 298 | 576 | "FROM events GROUP BY d ORDER BY n DESC LIMIT 1").fetchone() |
@@ -304,10 +582,31 @@ def dashboard(period: str = "30j", dfrom: str = "", dto: str = "") -> dict: | ||
| 304 | 582 | records.append({"label": "Ville la plus active (à venir)", |
| 305 | 583 | "value": f"{city_rows[0][0]} — " |
| 306 | 584 | f"{city_rows[0][1]:,} événements".replace(",", " ")}) |
| 585 | + if venue_rows: | |
| 586 | + records.append({"label": "Lieu le plus actif (à venir)", | |
| 587 | + "value": f"{venue_rows[0][0]} — " | |
| 588 | + f"{venue_rows[0][2]:,} événements".replace(",", " ")}) | |
| 589 | + if geo["items"]: | |
| 590 | + g0 = geo["items"][0] | |
| 591 | + records.append({"label": "Région la plus animée (à venir)", | |
| 592 | + "value": f"{g0['label']} — " | |
| 593 | + f"{g0['value']:,} événements".replace(",", " ")}) | |
| 307 | 594 | if top_cats: |
| 308 | 595 | records.append({"label": "Catégorie dominante (à venir)", |
| 309 | 596 | "value": f"{CAT_LABELS.get(top_cats[0][0], top_cats[0][0])}" |
| 310 | 597 | f" — {top_cats[0][1]:,} événements".replace(",", " ")}) |
| 598 | + if hh: | |
| 599 | + (dow, hr), n_pk = max(hh.items(), key=lambda kv: kv[1]) | |
| 600 | + days_fr = ["lundi", "mardi", "mercredi", "jeudi", | |
| 601 | + "vendredi", "samedi", "dimanche"] | |
| 602 | + records.append({"label": "Créneau de début le plus fréquent (à venir)", | |
| 603 | + "value": f"{days_fr[dow]} {hr} h — " | |
| 604 | + f"{n_pk:,} événements".replace(",", " ")}) | |
| 605 | + if src_added and added_cur: | |
| 606 | + s_top = max(src_added.items(), key=lambda kv: sum(kv[1])) | |
| 607 | + records.append({"label": f"Source la plus productive ({p_label})", | |
| 608 | + "value": f"{SRC_LABELS.get(s_top[0], s_top[0])} — " | |
| 609 | + f"{sum(s_top[1]):,} ajouts".replace(",", " ")}) | |
| 311 | 610 | longest = con.execute( |
| 312 | 611 | f"SELECT title, start_date, end_date, " |
| 313 | 612 | f"julianday(end_date) - julianday(start_date) + 1 AS j " |
@@ -324,8 +623,12 @@ def dashboard(period: str = "30j", dfrom: str = "", dto: str = "") -> dict: | ||
| 324 | 623 | "updated": now.isoformat(timespec="seconds"), |
| 325 | 624 | "period": {"from": p_from.isoformat(), "to": p_to.isoformat(), |
| 326 | 625 | "label": p_label}, |
| 327 | − "kpis": kpis, "series": series, "breakdowns": breakdowns, | |
| 626 | + "kpis": kpis, "gauges": gauges, "series": series, | |
| 627 | + "multiseries": multiseries, "stacked": stacked, | |
| 628 | + "breakdowns": breakdowns, "distributions": distributions, | |
| 328 | 629 | "geo": geo, "heatmap": heatmap, "tables": tables, "records": records, |
| 329 | 630 | } |
| 631 | + if hourly: | |
| 632 | + payload["hourly"] = hourly | |
| 330 | 633 | _cache[key] = (time.time(), payload) |
| 331 | 634 | return payload |
modified
sortika/web.py
+5 −4
@@ -199,13 +199,14 @@ def stats_report( | ||
| 199 | 199 | period: str = Query("30j"), |
| 200 | 200 | date_from: str = Query("", alias="from"), |
| 201 | 201 | date_to: str = Query("", alias="to"), |
| 202 | − mode: str = Query("complet", description="complet | synthese"), | |
| 202 | + mode: str = Query("complet", description="complet | synthese | tendances " | |
| 203 | + "| repartitions | donnees"), | |
| 203 | 204 | ) -> Response: |
| 204 | − if mode not in ("complet", "synthese"): | |
| 205 | − raise HTTPException(422, "mode invalide (complet | synthese)") | |
| 205 | + if mode not in kapdf.REPORT_MODES: # mode inconnu → rapport complet (SPEC v2) | |
| 206 | + mode = "complet" | |
| 206 | 207 | dash = kstats.dashboard(period, date_from, date_to) |
| 207 | 208 | pdf = kapdf.GroupeKAReport(site=SITE, dashboard=dash, mode=mode).build() |
| 208 | − fname = kapdf.filename("sorti-ka", period) | |
| 209 | + fname = kapdf.filename("sorti-ka", period, mode) | |
| 209 | 210 | return Response(pdf, media_type="application/pdf", |
| 210 | 211 | headers={"Content-Disposition": |
| 211 | 212 | f'attachment; filename="{fname}"'}) |
| 212 | 213 | |