Ajoute page statistiques avec graphiques et onglets de période

- Nouvelle page /stats avec histogrammes de distribution par créneau
  horaire (entrée/sortie matin et après-midi)
- Camemberts animés de conformité aux directives (≤09:00, ≥12:00,
  ≤14:00, ≥17:00) globale, par slot et par période (mois, sem. N-1)
- Onglets Tout / 1 an / 3 mois / 1 mois : filtrage côté client avec
  recalcul μ, σ, n et conformité en temps réel
- Graphique des soldes hebdomadaires (barres animées, toutes semaines
  sur l'axe X en rotation -45°, semaines partielles distinctes)
- Clic sur un graphique → modal plein écran avec axe X détaillé (15 min)
- Légende σ / n / directive / moyenne sur chaque histogramme
- Journées incomplètes exclues des stats ; heures dues retirées du solde
- Lien "Statistiques" dans la nav

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
toto
2026-06-24 17:09:37 +02:00
parent 33a28dc4d6
commit 1a34bff1c6
4 changed files with 1119 additions and 0 deletions

View File

@ -484,6 +484,350 @@
}
.cal-grid .cal-current:hover td { background: rgba(47,95,160,.06); }
.cal-grid .cal-current:hover td.cal-wn { background: var(--accent); }
/* ── Stats page ── */
.stats-head {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 1.5rem;
border-bottom: 2px solid var(--text);
padding-bottom: .75rem;
}
.stats-title {
font-family: var(--mono);
font-size: 1.75rem;
font-weight: 500;
letter-spacing: -.02em;
line-height: 1;
margin-bottom: .4rem;
}
.stats-meta {
font-size: 12px;
color: var(--muted);
font-family: var(--mono);
}
.stats-sep { margin: 0 .35em; color: var(--rule); }
.stat-pos { color: var(--pos); font-weight: 500; }
.stat-neg { color: var(--neg); font-weight: 500; }
.stats-overall {
text-align: center;
padding: .75rem 1.1rem;
border: 1.5px solid var(--rule);
background: var(--surface);
flex-shrink: 0;
}
.stats-overall-num {
font-family: var(--mono);
font-size: 2rem;
font-weight: 500;
letter-spacing: -.04em;
line-height: 1;
}
.stats-overall-pct { font-size: 1.1rem; font-weight: 300; }
.stats-overall-label {
font-size: 9px;
letter-spacing: .1em;
text-transform: uppercase;
color: var(--muted);
margin-top: .35rem;
line-height: 1.4;
}
.comp-ok { color: var(--pos); border-color: var(--pos) !important; background: var(--pos-bg) !important; }
.comp-warn { color: #7A5300; border-color: var(--conge-bd) !important; background: var(--conge-bg) !important; }
.comp-bad { color: var(--neg); border-color: var(--neg) !important; background: var(--neg-bg) !important; }
/* ── 3 period-compliance cards ── */
.comp-periods {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 1px;
background: var(--rule);
border: 1.5px solid var(--rule);
}
@media (max-width: 520px) { .comp-periods { grid-template-columns: 1fr; } }
.comp-period-card {
background: var(--surface);
padding: 1rem 1.25rem 1rem;
display: flex;
flex-direction: column;
align-items: center;
gap: .2rem;
text-align: center;
}
.cp-eyebrow {
font-family: var(--mono);
font-size: 9px;
letter-spacing: .12em;
text-transform: uppercase;
color: var(--muted);
}
.cp-sub {
font-family: var(--mono);
font-size: 10px;
color: var(--text);
font-weight: 500;
margin-bottom: .35rem;
}
.cp-donut-wrap { margin: .25rem 0; }
.cp-donut { display: block; }
.cp-n {
font-family: var(--mono);
font-size: 10px;
color: var(--muted);
margin-top: .2rem;
}
.cp-n.comp-ok { color: var(--pos); }
.cp-n.comp-warn { color: #7A5300; }
.cp-n.comp-bad { color: var(--neg); }
.cp-nodata { color: var(--rule); }
/* ── Period tabs ── */
.period-tabs-wrap {
display: flex;
align-items: center;
gap: 1rem;
flex-wrap: wrap;
}
.period-tabs-label {
font-family: var(--mono);
font-size: 9px;
letter-spacing: .12em;
text-transform: uppercase;
color: var(--muted);
flex-shrink: 0;
}
.period-tabs {
display: flex;
gap: 1px;
background: var(--rule);
border: 1.5px solid var(--rule);
}
.ptab {
padding: .38rem .9rem;
font-family: var(--mono);
font-size: 11px;
background: var(--surface);
border: none;
cursor: pointer;
color: var(--muted);
letter-spacing: .04em;
transition: background .12s, color .12s;
white-space: nowrap;
}
.ptab:hover { background: var(--ground); color: var(--text); }
.ptab.active { background: var(--text); color: var(--ground); }
.ptab:focus { outline: 2px solid var(--accent); outline-offset: -2px; }
/* 2×2 grid, 4-in-a-row on wide screens */
.ts-grid {
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: 1px;
background: var(--rule);
border: 1.5px solid var(--rule);
}
@media (min-width: 800px) { .ts-grid { grid-template-columns: repeat(4, 1fr); } }
.ts-card {
background: var(--surface);
padding: 1rem 1.2rem .9rem;
display: flex;
flex-direction: column;
gap: .3rem;
min-width: 0;
}
.ts-card.ts-matin { border-top: 3px solid var(--accent); }
.ts-card.ts-aprem { border-top: 3px solid var(--accent-2); }
.ts-eyebrow {
font-family: var(--mono);
font-size: 9px;
letter-spacing: .12em;
text-transform: uppercase;
color: var(--muted);
}
.ts-mean {
font-family: var(--mono);
font-size: 2rem;
font-weight: 500;
letter-spacing: -.04em;
line-height: 1;
color: var(--text);
margin-top: .15rem;
}
.ts-mean.ts-empty { color: var(--rule); }
.ts-sigma {
font-family: var(--mono);
font-size: 10px;
color: var(--muted);
margin-bottom: .25rem;
}
.ts-mean-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: .5rem;
}
.donut-wrap {
display: flex;
flex-direction: column;
align-items: center;
gap: .15rem;
flex-shrink: 0;
}
.donut-canvas { display: block; }
.donut-label {
font-family: var(--mono);
font-size: 8px;
letter-spacing: .04em;
color: var(--muted);
text-align: center;
}
.dist-canvas {
width: 100%;
display: block;
margin: .25rem 0 .2rem;
background: transparent;
}
.dist-legend {
display: flex;
flex-wrap: wrap;
gap: .5rem .75rem;
font-family: var(--mono);
font-size: 9px;
color: var(--muted);
margin-bottom: .35rem;
}
.dl-item { display: flex; align-items: center; gap: .28rem; white-space: nowrap; }
.dl-mean-line {
display: inline-block;
width: 14px; height: 1.5px;
background: var(--text);
flex-shrink: 0;
}
.dl-target-line {
display: inline-block;
width: 14px; height: 0;
border-top: 1.5px dashed;
flex-shrink: 0;
}
.dl-target-line.dl-neg { border-color: var(--neg); }
.dl-target-line.dl-pos { border-color: var(--pos); }
.dl-band {
display: inline-block;
width: 10px; height: 10px;
flex-shrink: 0;
}
.dl-band.ts-matin { background: rgba(47,95,160,.12); border: 1px solid rgba(47,95,160,.25); }
.dl-band.ts-aprem { background: rgba(184,106,8,.12); border: 1px solid rgba(184,106,8,.25); }
.dl-n { color: var(--muted); }
/* Weekly balance chart */
.wkly-section {
background: var(--surface);
border: 1.5px solid var(--rule);
padding: 1rem 1.25rem;
}
.wkly-eyebrow {
font-family: var(--mono);
font-size: 9px;
letter-spacing: .12em;
text-transform: uppercase;
color: var(--muted);
margin-bottom: .75rem;
}
.wkly-wrap {
overflow-x: auto;
-webkit-overflow-scrolling: touch;
}
#c-weekly { display: block; width: 100%; }
.wkly-note { font-weight: 300; color: var(--muted); letter-spacing: 0; text-transform: none; font-size: 9px; }
.wkly-legend {
margin-top: .5rem;
font-size: 10px;
color: var(--muted);
font-family: var(--mono);
display: flex;
align-items: center;
gap: .4rem;
}
.legend-dot {
width: 10px; height: 10px;
display: inline-block;
flex-shrink: 0;
}
.partial-dot { background: repeating-linear-gradient(45deg, var(--muted) 0, var(--muted) 2px, transparent 2px, transparent 4px); }
/* Zoomable canvas hint */
canvas.zoomable { cursor: zoom-in; }
/* ── Chart zoom modal ── */
.chart-modal {
position: fixed;
inset: 0;
z-index: 1000;
display: flex;
align-items: center;
justify-content: center;
padding: 1rem;
}
.chart-modal[hidden] { display: none; }
.chart-modal-bd {
position: absolute;
inset: 0;
background: rgba(28,23,18,.55);
backdrop-filter: blur(3px);
}
.chart-modal-inner {
position: relative;
background: var(--surface);
border: 1.5px solid var(--rule);
max-width: 92vw;
max-height: 90vh;
overflow: auto;
display: flex;
flex-direction: column;
}
.chart-modal-header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 1rem;
padding: .65rem 1rem;
border-bottom: 1px solid var(--rule);
background: var(--ground);
}
.chart-modal-title {
font-family: var(--mono);
font-size: 10px;
letter-spacing: .1em;
text-transform: uppercase;
color: var(--muted);
}
.chart-modal-close {
background: none;
border: 1.5px solid var(--rule);
width: 26px; height: 26px;
display: flex; align-items: center; justify-content: center;
cursor: pointer;
font-size: 12px;
color: var(--muted);
flex-shrink: 0;
transition: border-color .15s, color .15s;
}
.chart-modal-close:hover { border-color: var(--text); color: var(--text); }
.chart-modal-close:focus { outline: 2px solid var(--accent); outline-offset: 2px; }
.chart-modal-body {
padding: 1.25rem;
overflow-x: auto;
}
#chart-modal-canvas { display: block; }
</style>
</head>
<body>
@ -491,6 +835,7 @@
<a href="/" class="nav-brand"><span class="nav-dot"></span>Décompte Horaire</a>
<span class="spacer"></span>
<a href="/" class="nav-link">Semaine courante</a>
<a href="/stats" class="nav-link">Statistiques</a>
</nav>
<div class="container">
{% block content %}{% endblock %}

558
app/templates/stats.html Normal file
View File

@ -0,0 +1,558 @@
{% extends "base.html" %}
{% block content %}
<div class="stats-head">
<div>
<div class="stats-title">Statistiques</div>
<div class="stats-meta">
{{ stats.n_jours }} jours complets analysés
<span class="stats-sep">·</span>
{{ stats.total_weeks }} semaines
{% if stats.avg_delta_min != 0 %}
<span class="stats-sep">·</span>
solde moyen
<span class="{{ 'stat-pos' if stats.avg_delta_min > 0 else 'stat-neg' }}">{{ stats.avg_delta }}/sem</span>
{% endif %}
</div>
</div>
</div>
{# ── 3 période-conformité cards ── #}
<div class="comp-periods">
{% set periods = [
(stats.comp_globale, "Conformité globale", "Toutes périodes"),
(stats.comp_mois, "Ce mois", stats.mois_label),
(stats.comp_sem_n1, "Semaine précédente", stats.prev_week_label),
] %}
{% for comp, title, sub in periods %}
{% set pct = comp.pct %}
{% set cls = 'comp-ok' if pct is not none and pct >= 95 else ('comp-warn' if pct is not none and pct >= 80 else 'comp-bad') %}
<div class="comp-period-card">
<div class="cp-eyebrow">{{ title }}</div>
<div class="cp-sub">{{ sub }}</div>
<div class="cp-donut-wrap">
<canvas class="cp-donut" id="cpd-{{ loop.index }}" width="90" height="90"
data-pct="{{ pct if pct is not none else 0 }}"
data-has-data="{{ 'true' if pct is not none else 'false' }}"
aria-label="{{ pct }}%"></canvas>
</div>
<div class="cp-n {{ cls if pct is not none }}">
{% if pct is not none %}{{ comp.n_ok }}/{{ comp.n }} jours conformes
{% else %}<span class="cp-nodata">pas de données</span>{% endif %}
</div>
</div>
{% endfor %}
</div>
{# ── Onglets de période ── #}
<div class="period-tabs-wrap">
<span class="period-tabs-label">Période d'analyse</span>
<div class="period-tabs" role="tablist">
<button class="ptab active" data-period="all" role="tab" aria-selected="true">Tout</button>
<button class="ptab" data-period="1y" role="tab">1&thinsp;an</button>
<button class="ptab" data-period="3m" role="tab">3&thinsp;mois</button>
<button class="ptab" data-period="1m" role="tab">1&thinsp;mois</button>
</div>
</div>
{# ── 4 time-slot cards ── #}
<div class="ts-grid">
{% set slot_meta = [
("matin_entree", "Entrée matin", "≤ 09:00", "le", "matin"),
("matin_sortie", "Sortie matin", "≥ 12:00", "ge", "matin"),
("aprem_entree", "Entrée après-midi","≤ 14:00", "le", "aprem"),
("aprem_sortie", "Sortie après-midi","≥ 17:00", "ge", "aprem"),
] %}
{% for slot, label, constraint, op, half in slot_meta %}
{% set ts = stats.time_stats[slot] %}
{% set comp = stats.compliance[slot] %}
<div class="ts-card ts-{{ half }}">
<div class="ts-eyebrow">{{ label }}</div>
{% if ts %}
<div class="ts-mean-row">
<div class="ts-mean" id="ts-mean-{{ slot }}">{{ ts.mean_hhmm }}</div>
{% if comp is not none %}
<div class="donut-wrap">
<canvas id="donut-{{ slot }}" class="donut-canvas" width="60" height="60"
data-pct="{{ comp }}" data-op="{{ op }}"
aria-label="{{ comp }}% {{ constraint }}"></canvas>
<div class="donut-label" id="donut-label-{{ slot }}">{{ constraint }}</div>
</div>
{% endif %}
</div>
<div class="ts-sigma" id="ts-sigma-{{ slot }}">σ&thinsp;=&thinsp;{{ ts.sigma_min }}&nbsp;min&ensp;·&ensp;n&thinsp;=&thinsp;{{ ts.n }}</div>
<canvas class="dist-canvas zoomable" id="dist-{{ slot }}" width="1" height="76"
data-chart-type="dist" data-chart-slot="{{ slot }}"
data-chart-title="{{ label }}"
aria-label="Distribution {{ label }}"></canvas>
<div class="dist-legend">
<span class="dl-item"><span class="dl-mean-line"></span>μ&thinsp;=&thinsp;<span id="dl-mean-{{ slot }}">{{ ts.mean_hhmm }}</span></span>
<span class="dl-item"><span class="dl-target-line {{ 'dl-neg' if op == 'le' else 'dl-pos' }}"></span>{{ constraint }}</span>
<span class="dl-item"><span class="dl-band ts-{{ half }}"></span>±1σ&thinsp;(<span id="dl-sigma-{{ slot }}">{{ ts.sigma_min }}</span>&thinsp;min)</span>
<span class="dl-item dl-n">n&thinsp;=&thinsp;<span id="dl-n-{{ slot }}">{{ ts.n }}</span>&thinsp;jours</span>
</div>
{% else %}
<div class="ts-mean ts-empty"></div>
<div class="ts-sigma">pas de données</div>
{% endif %}
</div>
{% endfor %}
</div>
{# ── Weekly balance chart ── #}
{% if stats.weekly_balances %}
<div class="wkly-section">
<div class="wkly-eyebrow">Soldes hebdomadaires <span class="wkly-note">(jours incomplets exclus)</span></div>
<div class="wkly-wrap">
<canvas id="c-weekly" class="zoomable" height="180"
data-chart-type="weekly" data-chart-title="Soldes hebdomadaires"
aria-label="Soldes hebdomadaires"></canvas>
</div>
{% set has_partial = stats.weekly_balances | selectattr("partial") | list %}
{% if has_partial %}
<div class="wkly-legend">
<span class="legend-dot partial-dot"></span> semaine avec jours non renseignés
</div>
{% endif %}
</div>
{% endif %}
{# ── Zoom modal ── #}
<div id="chart-modal" class="chart-modal" hidden aria-modal="true" role="dialog" aria-labelledby="chart-modal-title">
<div class="chart-modal-bd" id="chart-modal-bd"></div>
<div class="chart-modal-inner">
<div class="chart-modal-header">
<span id="chart-modal-title" class="chart-modal-title"></span>
<button class="chart-modal-close" id="chart-modal-close" aria-label="Fermer"></button>
</div>
<div class="chart-modal-body">
<canvas id="chart-modal-canvas"></canvas>
</div>
</div>
</div>
<script>
(function () {
const DATA = {{ data_json | safe }};
const C = {
pos: '#2A5E42', neg: '#9B3528',
accent: '#2F5FA0', accent2: '#B86A08', warn: '#B86A08',
rule: '#D8D0C0', ruleL: '#EAE5DA',
text: '#1C1712', muted: '#6B6152',
ground: '#F4F0E8', surface: '#FDFAF4',
};
const MONO = "'DM Mono', 'Cascadia Code', ui-monospace, monospace";
const SLOTS = ['matin_entree', 'matin_sortie', 'aprem_entree', 'aprem_sortie'];
const SLOT_COLOR = { matin_entree: C.accent, matin_sortie: C.accent, aprem_entree: C.accent2, aprem_sortie: C.accent2 };
const SLOT_TARGET = { matin_entree: [9*60,'le'], matin_sortie: [12*60,'ge'], aprem_entree: [14*60,'le'], aprem_sortie: [17*60,'ge'] };
let currentPeriod = 'all';
/* ─── Period filtering ─── */
function getCutoff(period) {
if (period === 'all') return null;
const d = new Date(DATA.today);
if (period === '1m') d.setMonth(d.getMonth() - 1);
else if (period === '3m') d.setMonth(d.getMonth() - 3);
else if (period === '1y') d.setFullYear(d.getFullYear() - 1);
return d;
}
function filterVals(slot, period) {
const dv = DATA.time_stats[slot]?.dated_values;
if (!dv) return [];
const cutoff = getCutoff(period);
return cutoff
? dv.filter(x => new Date(x.d) >= cutoff).map(x => x.v)
: dv.map(x => x.v);
}
function filterWeekly(period) {
const cutoff = getCutoff(period);
if (!cutoff) return DATA.weekly_balances;
return DATA.weekly_balances.filter(b => new Date(b.date) >= cutoff);
}
/* ─── Stats helpers ─── */
function _mean(arr) { return arr.length ? arr.reduce((a,b) => a+b,0) / arr.length : 0; }
function _sigma(arr) {
if (arr.length < 2) return 0;
const m = _mean(arr);
return Math.sqrt(arr.reduce((a,b) => a+(b-m)**2, 0) / (arr.length-1));
}
function _fmtMin(m) {
const h = Math.floor(m/60), mm = m%60;
return `${h.toString().padStart(2,'0')}:${mm.toString().padStart(2,'0')}`;
}
function _compPct(vals, target, op) {
if (!vals.length) return null;
const ok = vals.filter(v => op === 'le' ? v <= target : v >= target).length;
return Math.round(100 * ok / vals.length);
}
/* ─── Donut ─── */
function drawDonut(canvas, pct, op, progress) {
const W = canvas.width, H = canvas.height;
const ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, W, H);
const cx = W/2, cy = H/2;
const outerR = Math.min(W,H)/2 - 2;
const lw = outerR * 0.38;
const r = outerR - lw/2;
ctx.beginPath(); ctx.arc(cx, cy, r, 0, 2*Math.PI);
ctx.strokeStyle = C.ruleL; ctx.lineWidth = lw; ctx.stroke();
if (pct === null) {
ctx.fillStyle = C.muted; ctx.font = `400 ${Math.round(W*0.19)}px ${MONO}`;
ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; ctx.fillText('—', cx, cy);
return;
}
const color = pct >= 95 ? C.pos : (pct >= 80 ? C.warn : C.neg);
ctx.beginPath(); ctx.arc(cx, cy, r, -Math.PI/2, -Math.PI/2 + 2*Math.PI*(pct/100)*progress);
ctx.strokeStyle = color; ctx.lineWidth = lw; ctx.lineCap = 'butt'; ctx.stroke();
if (progress >= 1) {
ctx.fillStyle = color;
ctx.font = `500 ${Math.round(W*0.19)}px ${MONO}`;
ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
ctx.fillText(pct + '%', cx, cy);
}
}
function animateDonut(canvas, pct, op) {
if (pct === null) { drawDonut(canvas, null, op, 1); return; }
if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) { drawDonut(canvas, pct, op, 1); return; }
const DUR = 600; let t0 = null;
function step(ts) {
if (!t0) t0 = ts;
const p = Math.min((ts-t0)/DUR, 1);
drawDonut(canvas, pct, op, 1-Math.pow(1-p,3));
if (p < 1) requestAnimationFrame(step);
}
requestAnimationFrame(step);
}
/* ─── Distribution core ─── */
function _drawDistVals(canvas, vals, mean, sigma, target, op, color, enlarged) {
if (!vals || !vals.length) return;
const W = canvas.width, H = canvas.height;
const ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, W, H);
const lo = Math.min(...vals, target) - 15;
const hi = Math.max(...vals, target) + 15;
const range = hi - lo || 1;
const toX = v => ((v - lo) / range) * W;
const PAD_T = 4, PAD_B = H > 60 ? 20 : 4, chartH = H - PAD_T - PAD_B;
const targetColor = op === 'le' ? C.neg : C.pos;
const binSize = 5;
const nBins = Math.ceil((hi-lo)/binSize) + 1;
const bins = new Array(nBins).fill(0);
vals.forEach(v => { const b = Math.min(Math.floor((v-lo)/binSize), nBins-1); bins[b]++; });
const maxBin = Math.max(...bins, 1);
// σ band
ctx.fillStyle = color === C.accent ? 'rgba(47,95,160,.09)' : 'rgba(184,106,8,.09)';
const sLo = Math.max(0, toX(mean-sigma)), sHi = Math.min(W, toX(mean+sigma));
ctx.fillRect(sLo, 0, sHi-sLo, PAD_T+chartH);
// Bars
const bw = Math.max(1, (W/nBins) - 0.5);
bins.forEach((count, i) => {
if (!count) return;
const x = (i/nBins)*W, bh = (count/maxBin)*chartH;
ctx.fillStyle = color + 'BB';
ctx.fillRect(x, PAD_T+chartH-bh, bw, bh);
});
// Baseline
ctx.strokeStyle = C.rule; ctx.lineWidth = 0.5;
ctx.beginPath(); ctx.moveTo(0, PAD_T+chartH); ctx.lineTo(W, PAD_T+chartH); ctx.stroke();
// Target line
const tx = toX(target);
if (tx >= 0 && tx <= W) {
ctx.save(); ctx.strokeStyle = targetColor; ctx.lineWidth = 1.5; ctx.setLineDash([3,3]);
ctx.beginPath(); ctx.moveTo(tx, PAD_T); ctx.lineTo(tx, PAD_T+chartH); ctx.stroke(); ctx.restore();
}
// Mean line
ctx.strokeStyle = C.text; ctx.lineWidth = 1.5;
ctx.beginPath(); ctx.moveTo(toX(mean), PAD_T); ctx.lineTo(toX(mean), PAD_T+chartH); ctx.stroke();
// X axis labels
if (PAD_B > 10) {
const tickStep = enlarged ? 15 : 30;
const firstTick = Math.ceil(lo/tickStep)*tickStep;
const labelY = PAD_T+chartH+5;
const fs = Math.max(7, Math.min(9, Math.floor(W/28)));
ctx.textBaseline = 'top';
let ticks;
if (enlarged) {
ticks = new Set();
for (let t = firstTick; t <= hi; t += tickStep) {
if (toX(t) >= 2 && toX(t) <= W-2) ticks.add(t);
}
} else {
ticks = new Set([Math.round(target/tickStep)*tickStep]);
let lastX = -999;
for (let t = firstTick; t <= hi; t += tickStep) {
const x = toX(t);
if (x >= 4 && x <= W-4 && x-lastX >= 30) { ticks.add(t); lastX = x; }
}
}
ticks.forEach(t => {
const x = toX(t);
if (x < 0 || x > W) return;
const isTarget = (t === target);
const isMean = !isTarget && Math.abs(t - Math.round(mean/tickStep)*tickStep) < 2;
ctx.textAlign = x < 16 ? 'left' : (x > W-16 ? 'right' : 'center');
ctx.fillStyle = isTarget ? targetColor : (isMean ? C.text : C.muted);
ctx.font = `${isTarget||isMean?'500':'400'} ${fs}px ${MONO}`;
ctx.strokeStyle = isTarget ? targetColor : C.rule;
ctx.lineWidth = isTarget ? 1 : 0.5;
ctx.beginPath(); ctx.moveTo(x, PAD_T+chartH); ctx.lineTo(x, PAD_T+chartH+3); ctx.stroke();
ctx.fillText(_fmtMin(t), x, labelY);
});
}
}
function _drawDist(canvas, slot, enlarged) {
const stat = DATA.time_stats[slot];
if (!stat) return;
const vals = filterVals(slot, currentPeriod);
if (!vals.length) return;
const mean = _mean(vals), sigma = _sigma(vals);
const [target, op] = SLOT_TARGET[slot];
_drawDistVals(canvas, vals, mean, sigma, target, op, SLOT_COLOR[slot], enlarged);
}
function drawDist(slot) {
const c = document.getElementById('dist-'+slot);
if (!c) return;
c.width = c.parentElement.clientWidth || 240;
_drawDist(c, slot, false);
}
/* ─── Weekly bars ─── */
function _drawWeekly(canvas, balances) {
if (!balances || !balances.length) return;
const W = canvas.width, H = canvas.height;
const ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, W, H);
const PAD_L = 42, PAD_R = 12, PAD_T = 12, PAD_B = 42;
const chartW = W-PAD_L-PAD_R, chartH = H-PAD_T-PAD_B;
const midY = PAD_T+chartH/2;
const maxAbs = Math.max(...balances.map(b => Math.abs(b.delta_min)), 1);
const axisMax = Math.ceil(maxAbs/30)*30;
const toY = v => midY - (v/axisMax)*(chartH/2);
const barSlot = chartW/balances.length;
const barW = Math.max(4, Math.min(32, barSlot-3));
ctx.fillStyle = C.surface; ctx.fillRect(PAD_L, PAD_T, chartW, chartH);
ctx.strokeStyle = C.ruleL; ctx.lineWidth = 0.5;
for (let v = 30; v <= axisMax; v += 30) {
[toY(v), toY(-v)].forEach(y => {
ctx.beginPath(); ctx.moveTo(PAD_L,y); ctx.lineTo(PAD_L+chartW,y); ctx.stroke();
});
}
ctx.strokeStyle = C.rule; ctx.lineWidth = 1;
ctx.beginPath(); ctx.moveTo(PAD_L,midY); ctx.lineTo(PAD_L+chartW,midY); ctx.stroke();
ctx.fillStyle = C.muted; ctx.font = `9px ${MONO}`; ctx.textAlign = 'right';
for (let v = 60; v <= axisMax; v += 60) {
const h = Math.floor(v/60);
ctx.fillText(`+${h}h`, PAD_L-5, toY(v)+3);
ctx.fillText(`-${h}h`, PAD_L-5, toY(-v)+3);
}
ctx.fillText('0', PAD_L-5, midY+3);
balances.forEach((b, i) => {
const x = PAD_L+i*barSlot+(barSlot-barW)/2;
const hPx = (Math.abs(b.delta_min)/axisMax)*(chartH/2);
const baseColor = b.delta_min >= 0 ? C.pos : C.neg;
const alpha = b.partial ? '55' : 'CC';
if (b.delta_min >= 0) {
const g = ctx.createLinearGradient(x, midY-hPx, x, midY);
g.addColorStop(0, baseColor+alpha); g.addColorStop(1, baseColor+(b.partial?'33':'88'));
ctx.fillStyle = g; ctx.fillRect(x, midY-hPx, barW, hPx);
} else {
const g = ctx.createLinearGradient(x, midY, x, midY+hPx);
g.addColorStop(0, baseColor+(b.partial?'33':'88')); g.addColorStop(1, baseColor+alpha);
ctx.fillStyle = g; ctx.fillRect(x, midY, barW, hPx);
}
if (b.partial && hPx > 2) {
const yEdge = b.delta_min >= 0 ? midY-hPx : midY+hPx;
ctx.save(); ctx.strokeStyle = baseColor+'88'; ctx.lineWidth=1; ctx.setLineDash([2,2]);
ctx.beginPath(); ctx.moveTo(x,yEdge); ctx.lineTo(x+barW,yEdge); ctx.stroke(); ctx.restore();
}
});
ctx.font = `9px ${MONO}`; ctx.fillStyle = C.muted;
ctx.textAlign = 'right'; ctx.textBaseline = 'middle';
balances.forEach((b, i) => {
const x = PAD_L+i*barSlot+barSlot/2, y = PAD_T+chartH+8;
ctx.save(); ctx.translate(x,y); ctx.rotate(-Math.PI/4); ctx.fillText(b.label,0,0); ctx.restore();
});
ctx.strokeStyle = C.rule; ctx.lineWidth = 1;
ctx.strokeRect(PAD_L, PAD_T, chartW, chartH);
}
function drawWeekly() {
const c = document.getElementById('c-weekly');
if (!c) return;
c.width = c.parentElement.clientWidth || 800;
const balances = filterWeekly(currentPeriod);
if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) {
_drawWeekly(c, balances); return;
}
const DUR = 500; let t0 = null;
function step(ts) {
if (!t0) t0 = ts;
const p = Math.min((ts-t0)/DUR, 1);
const ease = 1-Math.pow(1-p,3);
// Animate bar heights by scaling delta_min
const scaled = balances.map(b => ({...b, delta_min: b.delta_min * ease}));
_drawWeekly(c, scaled);
if (p < 1) requestAnimationFrame(step);
}
requestAnimationFrame(step);
}
/* ─── Update everything for a period ─── */
function updateForPeriod(period) {
currentPeriod = period;
SLOTS.forEach(slot => {
if (!DATA.time_stats[slot]) return;
const vals = filterVals(slot, period);
const [target, op] = SLOT_TARGET[slot];
if (!vals.length) {
const meanEl = document.getElementById('ts-mean-'+slot);
if (meanEl) meanEl.textContent = '—';
const sigmaEl = document.getElementById('ts-sigma-'+slot);
if (sigmaEl) sigmaEl.textContent = 'pas de données pour cette période';
const donutEl = document.getElementById('donut-'+slot);
if (donutEl) drawDonut(donutEl, null, op, 1);
return;
}
const m = _mean(vals), s = _sigma(vals);
const pct = _compPct(vals, target, op);
// Update text
const meanEl = document.getElementById('ts-mean-'+slot);
if (meanEl) meanEl.textContent = _fmtMin(Math.round(m));
const sigmaEl = document.getElementById('ts-sigma-'+slot);
if (sigmaEl) sigmaEl.textContent = `σ=${Math.round(s)} min·n=${vals.length}`;
// Update legend
const dlMean = document.getElementById('dl-mean-'+slot);
if (dlMean) dlMean.textContent = _fmtMin(Math.round(m));
const dlSigma = document.getElementById('dl-sigma-'+slot);
if (dlSigma) dlSigma.textContent = Math.round(s);
const dlN = document.getElementById('dl-n-'+slot);
if (dlN) dlN.textContent = vals.length;
// Redraw distribution
const c = document.getElementById('dist-'+slot);
if (c) {
c.width = c.parentElement.clientWidth || 240;
_drawDistVals(c, vals, m, s, target, op, SLOT_COLOR[slot], false);
}
// Redraw donut
const donutEl = document.getElementById('donut-'+slot);
if (donutEl) drawDonut(donutEl, pct, op, 1);
});
drawWeekly();
}
/* ─── Zoom modal ─── */
function openModal(sourceCanvas) {
const type = sourceCanvas.dataset.chartType;
const slot = sourceCanvas.dataset.chartSlot;
const title = sourceCanvas.dataset.chartTitle || '';
const mc = document.getElementById('chart-modal-canvas');
const maxW = Math.floor(Math.min(window.innerWidth*0.88, 1050));
document.getElementById('chart-modal-title').textContent = title;
if (type === 'dist') {
mc.width = maxW; mc.height = 180;
_drawDist(mc, slot, true);
} else if (type === 'weekly') {
mc.width = maxW; mc.height = 300;
_drawWeekly(mc, filterWeekly(currentPeriod));
}
document.getElementById('chart-modal').removeAttribute('hidden');
document.body.style.overflow = 'hidden';
document.getElementById('chart-modal-close').focus();
}
function closeModal() {
document.getElementById('chart-modal').setAttribute('hidden', '');
document.body.style.overflow = '';
}
/* ─── Init ─── */
function init() {
[1,2,3].forEach(i => {
const el = document.getElementById('cpd-'+i);
if (!el) return;
el.dataset.hasData === 'true'
? animateDonut(el, parseInt(el.dataset.pct), 'day')
: (function(){
const ctx = el.getContext('2d');
const W=el.width,H=el.height,cx=W/2,cy=H/2;
const r=(Math.min(W,H)/2-2)*0.69;
ctx.beginPath(); ctx.arc(cx,cy,r,0,2*Math.PI);
ctx.strokeStyle=C.ruleL; ctx.lineWidth=(Math.min(W,H)/2-2)*0.38; ctx.stroke();
ctx.fillStyle=C.muted; ctx.font=`400 13px ${MONO}`;
ctx.textAlign='center'; ctx.textBaseline='middle'; ctx.fillText('—',cx,cy);
})();
});
SLOTS.forEach(slot => {
drawDist(slot);
const el = document.getElementById('donut-'+slot);
if (el) animateDonut(el, parseInt(el.dataset.pct), el.dataset.op);
});
drawWeekly();
}
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', init);
} else { init(); }
// Tabs
document.querySelectorAll('.ptab').forEach(btn => {
btn.addEventListener('click', () => {
document.querySelectorAll('.ptab').forEach(b => {
b.classList.remove('active'); b.setAttribute('aria-selected','false');
});
btn.classList.add('active'); btn.setAttribute('aria-selected','true');
updateForPeriod(btn.dataset.period);
});
});
// Zoom
document.addEventListener('click', e => { const c = e.target.closest('canvas.zoomable'); if (c) openModal(c); });
document.getElementById('chart-modal-close').addEventListener('click', closeModal);
document.getElementById('chart-modal-bd').addEventListener('click', closeModal);
document.addEventListener('keydown', e => { if (e.key === 'Escape') closeModal(); });
let resizeTimer;
window.addEventListener('resize', () => { clearTimeout(resizeTimer); resizeTimer = setTimeout(init, 120); });
})();
</script>
{% endblock %}