feat: chart daily metrics and weekly prospecting over time
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01SfihHazrSHXgndJtSNLubJ
This commit is contained in:
parent
8d76fc139b
commit
287061cb1c
7 changed files with 331 additions and 3 deletions
|
|
@ -2,12 +2,14 @@
|
||||||
--bg: #f4f5f7; --card: #fff; --text: #17191c; --muted: #6b7078; --line: #e2e4e8;
|
--bg: #f4f5f7; --card: #fff; --text: #17191c; --muted: #6b7078; --line: #e2e4e8;
|
||||||
--accent: #2f5bea; --accent-text: #fff; --ok: #15803d; --warn: #b45309; --err: #b91c1c;
|
--accent: #2f5bea; --accent-text: #fff; --ok: #15803d; --warn: #b45309; --err: #b91c1c;
|
||||||
--locked: #eceef1; --radius: 10px;
|
--locked: #eceef1; --radius: 10px;
|
||||||
|
--series-1: #2a78d6; --series-2: #eb6834; /* paire validée (daltonisme, contraste) sur fond clair */
|
||||||
color-scheme: light;
|
color-scheme: light;
|
||||||
}
|
}
|
||||||
@media (prefers-color-scheme: dark) {
|
@media (prefers-color-scheme: dark) {
|
||||||
:root {
|
:root {
|
||||||
--bg: #111317; --card: #1a1d22; --text: #e8eaed; --muted: #9097a1; --line: #2b2f36;
|
--bg: #111317; --card: #1a1d22; --text: #e8eaed; --muted: #9097a1; --line: #2b2f36;
|
||||||
--accent: #5b82ff; --ok: #4ade80; --warn: #fbbf24; --err: #f87171; --locked: #23272e;
|
--accent: #5b82ff; --ok: #4ade80; --warn: #fbbf24; --err: #f87171; --locked: #23272e;
|
||||||
|
--series-1: #3987e5; --series-2: #d95926; /* mêmes teintes, pas d'inversion automatique */
|
||||||
color-scheme: dark;
|
color-scheme: dark;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -127,3 +129,30 @@ select.st-new { color: var(--accent); }
|
||||||
@media (max-width: 640px) { .pfilters .todo { grid-column: 1 / -1; } }
|
@media (max-width: 640px) { .pfilters .todo { grid-column: 1 / -1; } }
|
||||||
.csv { justify-content: flex-start; margin: 4px 0 8px; }
|
.csv { justify-content: flex-start; margin: 4px 0 8px; }
|
||||||
label.btn.file { display: inline-block; margin: 0; color: var(--text); font-size: .85rem; }
|
label.btn.file { display: inline-block; margin: 0; color: var(--text); font-size: .85rem; }
|
||||||
|
.chart-head { margin-top: 14px; }
|
||||||
|
.chart-head h4 { margin: 0; }
|
||||||
|
.seg { display: flex; gap: 6px; }
|
||||||
|
.seg [aria-pressed="true"] { border-color: var(--accent); color: var(--accent); }
|
||||||
|
.charts { display: grid; grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); gap: 12px; margin: 10px 0; }
|
||||||
|
figure.chart { position: relative; margin: 0; border: 1px solid var(--line); border-radius: 8px; padding: 10px; min-width: 0; }
|
||||||
|
figure.chart figcaption { font-size: .85rem; font-weight: 600; margin-bottom: 4px; }
|
||||||
|
.chart .plot { width: 100%; }
|
||||||
|
.chart svg { display: block; overflow: visible; touch-action: pan-y; }
|
||||||
|
.chart .grid { stroke: var(--line); stroke-width: 1; }
|
||||||
|
.chart .base { stroke: var(--muted); stroke-width: 1; }
|
||||||
|
.chart .axis { fill: var(--muted); font-size: 11px; font-variant-numeric: tabular-nums; }
|
||||||
|
.chart .end { fill: var(--text); font-size: 12px; font-weight: 600; font-variant-numeric: tabular-nums; }
|
||||||
|
.chart .line { fill: none; stroke: var(--series-1); stroke-width: 2; stroke-linejoin: round; stroke-linecap: round; }
|
||||||
|
.chart .dot { fill: var(--series-1); stroke: var(--card); stroke-width: 2; }
|
||||||
|
.chart .cross { stroke: var(--muted); stroke-width: 1; stroke-dasharray: 3 3; }
|
||||||
|
.chart .cross, .chart .dot.hover { visibility: hidden; }
|
||||||
|
.chart.hovering .cross, .chart.hovering .dot.hover { visibility: visible; }
|
||||||
|
.chart .b1 { fill: var(--series-1); }
|
||||||
|
.chart .b2 { fill: var(--series-2); }
|
||||||
|
.chart .hit { fill: transparent; cursor: crosshair; }
|
||||||
|
.chart .tip { position: absolute; transform: translate(-50%, -100%); pointer-events: none; background: var(--card); color: var(--text);
|
||||||
|
border: 1px solid var(--line); border-radius: 6px; padding: 4px 8px; font-size: 12px; white-space: nowrap; box-shadow: 0 2px 10px rgba(0,0,0,.15); z-index: 2; }
|
||||||
|
.legend { margin: 0 0 4px; display: flex; align-items: center; gap: 6px; flex-wrap: wrap; color: var(--muted); }
|
||||||
|
.sw { display: inline-block; width: 10px; height: 10px; border-radius: 2px; margin-left: 8px; }
|
||||||
|
.sw.s1 { background: var(--series-1); margin-left: 0; }
|
||||||
|
.sw.s2 { background: var(--series-2); }
|
||||||
|
|
|
||||||
148
public/app.js
148
public/app.js
|
|
@ -327,6 +327,150 @@
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// ---------- Courbes (SVG maison : pas de lib externe, CSP stricte) ----------
|
||||||
|
// Dessinées à la largeur réelle du conteneur (1 unité = 1 px) pour que les textes restent lisibles sur mobile.
|
||||||
|
const M = { l: 46, r: 56, t: 12, b: 24, h: 150 };
|
||||||
|
const niceMax = (v) => { if (!(v > 0)) return 1; const p = 10 ** Math.floor(Math.log10(v)); const m = v / p; return (m <= 1 ? 1 : m <= 2 ? 2 : m <= 5 ? 5 : 10) * p; };
|
||||||
|
const fmtVal = (v, unit) => (unit === '€'
|
||||||
|
? v.toLocaleString('fr-FR', { style: 'currency', currency: 'EUR', maximumFractionDigits: 0 })
|
||||||
|
: v.toLocaleString('fr-FR', { maximumFractionDigits: 1 }));
|
||||||
|
const shortDay = (d) => { const [, m, dd] = d.split('-'); return `${dd}/${m}`; };
|
||||||
|
const yGrid = (w, max, unit, Y) => [0, 0.5, 1].map((f) => `<line class="grid" x1="${M.l}" x2="${w - M.r}" y1="${Y(max * f)}" y2="${Y(max * f)}"/>
|
||||||
|
<text class="axis" x="${M.l - 6}" y="${Y(max * f) + 4}" text-anchor="end">${esc(fmtVal(max * f, unit))}</text>`).join('');
|
||||||
|
|
||||||
|
function drawLine(fig, w) {
|
||||||
|
const { unit, xs, ys } = JSON.parse(fig.dataset.series);
|
||||||
|
const max = niceMax(Math.max(...ys));
|
||||||
|
const step = (w - M.l - M.r) / (xs.length - 1);
|
||||||
|
const X = (i) => M.l + i * step;
|
||||||
|
const Y = (v) => M.t + (M.h - M.t - M.b) * (1 - v / max);
|
||||||
|
const d = ys.map((v, i) => `${i ? 'L' : 'M'}${X(i).toFixed(1)},${Y(v).toFixed(1)}`).join('');
|
||||||
|
const n = xs.length - 1;
|
||||||
|
fig.querySelector('.plot').innerHTML = `<svg width="${w}" height="${M.h}" role="img" aria-label="${esc(fig.dataset.title)}">
|
||||||
|
${yGrid(w, max, unit, Y)}
|
||||||
|
<text class="axis" x="${M.l}" y="${M.h - 6}">${shortDay(xs[0])}</text>
|
||||||
|
<text class="axis" x="${w - M.r}" y="${M.h - 6}" text-anchor="end">${shortDay(xs[n])}</text>
|
||||||
|
<path class="line" d="${d}"/>
|
||||||
|
<circle class="dot" cx="${X(n)}" cy="${Y(ys[n])}" r="4"/>
|
||||||
|
<text class="end" x="${X(n) + 8}" y="${Y(ys[n]) + 4}">${esc(fmtVal(ys[n], unit))}</text>
|
||||||
|
<line class="cross" x1="0" x2="0" y1="${M.t}" y2="${M.h - M.b}"/>
|
||||||
|
<circle class="dot hover" r="5"/>
|
||||||
|
<rect class="hit" x="${M.l - step / 2}" y="0" width="${w - M.l - M.r + step}" height="${M.h}"/>
|
||||||
|
</svg>`;
|
||||||
|
fig._hover = (vx) => {
|
||||||
|
const i = Math.max(0, Math.min(n, Math.round((vx - M.l) / step)));
|
||||||
|
return { x: X(i), y: Y(ys[i]), html: `<strong>${esc(fmtVal(ys[i], unit))}</strong> · ${shortDay(xs[i])}` };
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Barres arrondies en haut (4 px), à plat sur la ligne de base
|
||||||
|
const bar = (x, y, bw, base) => {
|
||||||
|
const r = Math.min(4, bw / 2, base - y);
|
||||||
|
return base - y < 1 ? '' : `M${x},${base}V${y + r}Q${x},${y} ${x + r},${y}H${x + bw - r}Q${x + bw},${y} ${x + bw},${y + r}V${base}Z`;
|
||||||
|
};
|
||||||
|
|
||||||
|
function drawBars(fig, w) {
|
||||||
|
const { weeks } = JSON.parse(fig.dataset.series);
|
||||||
|
const max = niceMax(Math.max(1, ...weeks.flatMap((x) => [x.sent, x.replies])));
|
||||||
|
const base = M.h - M.b;
|
||||||
|
const Y = (v) => M.t + (base - M.t) * (1 - v / max);
|
||||||
|
const gw = (w - M.l - M.r) / weeks.length;
|
||||||
|
const bw = Math.max(3, Math.min(18, (gw - 8) / 2));
|
||||||
|
// Une étiquette de date tous les ~56 px au minimum, quelle que soit la largeur
|
||||||
|
const every = Math.max(1, Math.ceil(weeks.length / Math.max(1, Math.floor((w - M.l - M.r) / 56))));
|
||||||
|
const marks = weeks.map((x, i) => {
|
||||||
|
const x0 = M.l + i * gw + (gw - (2 * bw + 2)) / 2;
|
||||||
|
const last = i === weeks.length - 1;
|
||||||
|
return `<path class="b1" d="${bar(x0, Y(x.sent), bw, base)}"/><path class="b2" d="${bar(x0 + bw + 2, Y(x.replies), bw, base)}"/>
|
||||||
|
${(weeks.length - 1 - i) % every === 0 ? `<text class="axis" x="${x0 + bw + 1}" y="${M.h - 6}" text-anchor="middle">${shortDay(x.start)}</text>` : ''}
|
||||||
|
${last ? `<text class="end" x="${x0 + bw / 2}" y="${Y(x.sent) - 5}" text-anchor="middle">${x.sent}</text>
|
||||||
|
<text class="end" x="${x0 + bw * 1.5 + 2}" y="${Y(x.replies) - 5}" text-anchor="middle">${x.replies}</text>` : ''}`;
|
||||||
|
}).join('');
|
||||||
|
fig.querySelector('.plot').innerHTML = `<svg width="${w}" height="${M.h}" role="img" aria-label="${esc(fig.dataset.title)}">
|
||||||
|
${yGrid(w, max, '', Y)}<line class="base" x1="${M.l}" x2="${w - M.r}" y1="${base}" y2="${base}"/>${marks}
|
||||||
|
<rect class="hit" x="${M.l}" y="0" width="${w - M.l - M.r}" height="${M.h}"/></svg>`;
|
||||||
|
fig._hover = (vx) => {
|
||||||
|
const i = Math.max(0, Math.min(weeks.length - 1, Math.floor((vx - M.l) / gw)));
|
||||||
|
const x = weeks[i];
|
||||||
|
const rate = x.sent ? ` (${Math.round((x.replies / x.sent) * 100)} %)` : '';
|
||||||
|
return { x: M.l + (i + 0.5) * gw, y: Y(Math.max(x.sent, x.replies)), band: true,
|
||||||
|
html: `Semaine du ${shortDay(x.start)}<br><strong>${x.sent}</strong> envoyé(s) · <strong>${x.replies}</strong> réponse(s)${rate}` };
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function drawChart(fig) {
|
||||||
|
const w = Math.max(240, Math.floor(fig.querySelector('.plot').clientWidth));
|
||||||
|
(fig.dataset.kind === 'bars' ? drawBars : drawLine)(fig, w);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Survol : réticule + infobulle (souris et tactile)
|
||||||
|
document.addEventListener('pointermove', (e) => {
|
||||||
|
const svg = e.target.closest?.('.chart svg');
|
||||||
|
const fig = svg?.closest('.chart');
|
||||||
|
// L'attribut hidden n'agit pas sur les éléments SVG : on passe par une classe
|
||||||
|
$$('.chart.hovering').forEach((c) => { if (c !== fig) { c.classList.remove('hovering'); c.querySelector('.tip').hidden = true; } });
|
||||||
|
if (!svg) return;
|
||||||
|
fig.classList.add('hovering');
|
||||||
|
if (!fig._hover) return;
|
||||||
|
const box = svg.getBoundingClientRect();
|
||||||
|
const h = fig._hover(e.clientX - box.left);
|
||||||
|
const cross = svg.querySelector('.cross');
|
||||||
|
const dot = svg.querySelector('.dot.hover');
|
||||||
|
if (cross) { cross.setAttribute('x1', h.x); cross.setAttribute('x2', h.x); }
|
||||||
|
if (dot) { dot.setAttribute('cx', h.x); dot.setAttribute('cy', h.y); }
|
||||||
|
const tip = fig.querySelector('.tip');
|
||||||
|
tip.innerHTML = h.html;
|
||||||
|
tip.hidden = false;
|
||||||
|
tip.style.left = `${Math.min(box.width - 70, Math.max(70, h.x))}px`;
|
||||||
|
tip.style.top = `${h.y + fig.querySelector('.plot').offsetTop - 8}px`;
|
||||||
|
});
|
||||||
|
|
||||||
|
function figure(kind, title, series, empty) {
|
||||||
|
return `<figure class="chart" data-kind="${kind}" data-title="${esc(title)}" data-series="${esc(JSON.stringify(series))}">
|
||||||
|
<figcaption>${esc(title)}</figcaption>
|
||||||
|
${kind === 'bars' ? '<p class="legend small"><span class="sw s1"></span>Mails envoyés <span class="sw s2"></span>Réponses</p>' : ''}${empty ? `<p class="muted small">${empty}</p>` : '<div class="plot"></div><div class="tip" hidden></div>'}</figure>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadHistory(proj, days = 30) {
|
||||||
|
const box = $('[data-charts]', proj);
|
||||||
|
if (!box) return;
|
||||||
|
let h;
|
||||||
|
try { h = await api(`/api/projects/${proj.dataset.id}/history?days=${days}`); }
|
||||||
|
catch (err) { box.innerHTML = `<p class="error small">${esc(err.message)}</p>`; return; }
|
||||||
|
const kpi = (key, title, unit) => {
|
||||||
|
const pts = h.daily.filter((d) => d[key] != null);
|
||||||
|
return figure('line', title, { unit, xs: pts.map((d) => d.day), ys: pts.map((d) => d[key]) },
|
||||||
|
pts.length < 2 ? 'Pas encore assez de données : une photo est prise chaque jour (et à chaque ouverture du récap).' : '');
|
||||||
|
};
|
||||||
|
box.innerHTML = `
|
||||||
|
<div class="row chart-head"><h4>Évolution</h4>
|
||||||
|
<div class="seg" role="group" aria-label="Période">${[30, 90].map((d) => `<button type="button" class="btn small" data-days="${d}" aria-pressed="${d === days}">${d} jours</button>`).join('')}</div>
|
||||||
|
</div>
|
||||||
|
<div class="charts">
|
||||||
|
${kpi('users', 'Utilisateurs', '')}${kpi('clients', 'Clients payants', '')}${kpi('revenue', 'Revenu total', '€')}
|
||||||
|
${figure('bars', 'Prospection par semaine', { weeks: h.weeks })}
|
||||||
|
</div>
|
||||||
|
<details class="small"><summary>Voir les données</summary>
|
||||||
|
<div class="table-wrap"><table><thead><tr><th>Jour</th><th>Utilisateurs</th><th>Clients</th><th>Revenu</th></tr></thead><tbody>
|
||||||
|
${h.daily.map((d) => `<tr><td>${shortDay(d.day)}</td><td>${d.users ?? '–'}</td><td>${d.clients ?? '–'}</td><td>${d.revenue != null ? esc(fmtVal(d.revenue, '€')) : '–'}</td></tr>`).join('') || '<tr><td colspan="4">Aucune photo pour l\'instant.</td></tr>'}
|
||||||
|
</tbody></table>
|
||||||
|
<table><thead><tr><th>Semaine du</th><th>Envoyés</th><th>Réponses</th></tr></thead><tbody>
|
||||||
|
${h.weeks.map((x) => `<tr><td>${shortDay(x.start)}</td><td>${x.sent}</td><td>${x.replies}</td></tr>`).join('')}
|
||||||
|
</tbody></table></div>
|
||||||
|
</details>`;
|
||||||
|
$$('.chart', box).forEach((fig) => { if (fig.querySelector('.plot')) drawChart(fig); });
|
||||||
|
}
|
||||||
|
|
||||||
|
document.addEventListener('click', (e) => {
|
||||||
|
const b = e.target.closest('[data-days]');
|
||||||
|
if (b) loadHistory(b.closest('.project'), Number(b.dataset.days));
|
||||||
|
});
|
||||||
|
let resizeT;
|
||||||
|
window.addEventListener('resize', () => {
|
||||||
|
clearTimeout(resizeT);
|
||||||
|
resizeT = setTimeout(() => $$('.chart .plot').forEach((p) => drawChart(p.closest('.chart'))), 150);
|
||||||
|
});
|
||||||
|
|
||||||
// ---------- Récap ----------
|
// ---------- Récap ----------
|
||||||
async function loadRecap(proj, force = false) {
|
async function loadRecap(proj, force = false) {
|
||||||
const box = $('[data-recap]', proj);
|
const box = $('[data-recap]', proj);
|
||||||
|
|
@ -351,7 +495,9 @@
|
||||||
<div class="kpi"><span>Convertis</span><strong>${s.client || 0}</strong></div>
|
<div class="kpi"><span>Convertis</span><strong>${s.client || 0}</strong></div>
|
||||||
</div>
|
</div>
|
||||||
<p class="muted small">Coût IA du projet (équivalent API) : $${r.aiCostUsd.toFixed(2)}${b?.cached ? ' · chiffres en cache (10 min)' : ''}
|
<p class="muted small">Coût IA du projet (équivalent API) : $${r.aiCostUsd.toFixed(2)}${b?.cached ? ' · chiffres en cache (10 min)' : ''}
|
||||||
<button class="btn small" data-recap-refresh>Rafraîchir</button></p>`;
|
<button class="btn small" data-recap-refresh>Rafraîchir</button></p>
|
||||||
|
<div data-charts></div>`;
|
||||||
|
loadHistory(proj);
|
||||||
} catch (err) { box.innerHTML = `<p class="error small">${esc(err.message)}</p>`; }
|
} catch (err) { box.innerHTML = `<p class="error small">${esc(err.message)}</p>`; }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -117,6 +117,15 @@ export const MIGRATIONS = [
|
||||||
ALTER TABLE prospects ADD COLUMN next_action TEXT;
|
ALTER TABLE prospects ADD COLUMN next_action TEXT;
|
||||||
ALTER TABLE prospects ADD COLUMN next_action_at INTEGER;
|
ALTER TABLE prospects ADD COLUMN next_action_at INTEGER;
|
||||||
`,
|
`,
|
||||||
|
// 8 — historique quotidien des KPI business (pour les courbes)
|
||||||
|
`
|
||||||
|
CREATE TABLE metrics_daily (
|
||||||
|
project_id INTEGER NOT NULL REFERENCES projects(id) ON DELETE CASCADE,
|
||||||
|
day TEXT NOT NULL, -- AAAA-MM-JJ, heure de Paris
|
||||||
|
users REAL, clients REAL, revenue REAL,
|
||||||
|
PRIMARY KEY (project_id, day)
|
||||||
|
);
|
||||||
|
`,
|
||||||
];
|
];
|
||||||
|
|
||||||
export function openDb(dataDir) {
|
export function openDb(dataDir) {
|
||||||
|
|
|
||||||
|
|
@ -15,6 +15,7 @@ import { notify, notifyConfig, EVENTS, WEBHOOK_RE } from './services/notify.js';
|
||||||
import { budgetState, AI_JOBS } from './services/budget.js';
|
import { budgetState, AI_JOBS } from './services/budget.js';
|
||||||
import { sendWeeklyReport } from './services/report.js';
|
import { sendWeeklyReport } from './services/report.js';
|
||||||
import { exportProspects, importProspects } from './services/csv.js';
|
import { exportProspects, importProspects } from './services/csv.js';
|
||||||
|
import { history, saveSnapshot } from './services/metrics.js';
|
||||||
import {
|
import {
|
||||||
listProspects, parseFilters, STATUSES as PROSPECT_STATUSES, prospectDetail, addNote, deleteNote, setNextAction,
|
listProspects, parseFilters, STATUSES as PROSPECT_STATUSES, prospectDetail, addNote, deleteNote, setNextAction,
|
||||||
} from './services/crm.js';
|
} from './services/crm.js';
|
||||||
|
|
@ -301,8 +302,10 @@ export function registerRoutes(router, app) {
|
||||||
const stats = prospectStats(db, p.id);
|
const stats = prospectStats(db, p.id);
|
||||||
const cost = db.prepare('SELECT COALESCE(SUM(cost_usd),0) c FROM jobs WHERE project_id = ?').get(p.id).c;
|
const cost = db.prepare('SELECT COALESCE(SUM(cost_usd),0) c FROM jobs WHERE project_id = ?').get(p.id).c;
|
||||||
let business = null, error = null;
|
let business = null, error = null;
|
||||||
try { business = await fetchRecap(p.id, p.dbCfg, { force: url.searchParams.has('force') }); }
|
try {
|
||||||
catch (e) { error = e.message; }
|
business = await fetchRecap(p.id, p.dbCfg, { force: url.searchParams.has('force') });
|
||||||
|
saveSnapshot(db, p.id, business); // la consultation alimente aussi la courbe du jour
|
||||||
|
} catch (e) { error = e.message; }
|
||||||
json(res, { business, error, stats, aiCostUsd: cost });
|
json(res, { business, error, stats, aiCostUsd: cost });
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
@ -325,6 +328,11 @@ export function registerRoutes(router, app) {
|
||||||
catch (e) { throw new HttpError(400, e.message); }
|
catch (e) { throw new HttpError(400, e.message); }
|
||||||
});
|
});
|
||||||
|
|
||||||
|
router.get('/api/projects/:id/history', ({ res, params, url }) => {
|
||||||
|
const p = getProject(app, pid(params));
|
||||||
|
json(res, history(db, p.id, { days: url.searchParams.get('days') === '90' ? 90 : 30 }));
|
||||||
|
});
|
||||||
|
|
||||||
router.get('/api/projects/:id/prospects', ({ res, params, url }) => {
|
router.get('/api/projects/:id/prospects', ({ res, params, url }) => {
|
||||||
const p = getProject(app, pid(params));
|
const p = getProject(app, pid(params));
|
||||||
json(res, listProspects(db, p.id, parseFilters(url.searchParams)));
|
json(res, listProspects(db, p.id, parseFilters(url.searchParams)));
|
||||||
|
|
|
||||||
65
src/services/metrics.js
Normal file
65
src/services/metrics.js
Normal file
|
|
@ -0,0 +1,65 @@
|
||||||
|
// Historique : photo quotidienne des KPI business (la BDD des projets ne les historise pas)
|
||||||
|
// + prospection recalculée depuis nos propres journaux (rien à stocker en plus).
|
||||||
|
import { now } from '../db.js';
|
||||||
|
import { getProject } from '../projects.js';
|
||||||
|
import { fetchRecap } from './recap.js';
|
||||||
|
import { parisParts, parisTime, addParisDays } from './paris-time.js';
|
||||||
|
|
||||||
|
const pad = (n) => String(n).padStart(2, '0');
|
||||||
|
export const parisDay = (date = new Date()) => { const p = parisParts(date); return `${p.year}-${pad(p.month)}-${pad(p.day)}`; };
|
||||||
|
const num = (v) => (typeof v === 'number' && Number.isFinite(v) ? v : null);
|
||||||
|
|
||||||
|
export function saveSnapshot(db, projectId, business, { date = new Date() } = {}) {
|
||||||
|
db.prepare(`INSERT INTO metrics_daily(project_id, day, users, clients, revenue) VALUES(?, ?, ?, ?, ?)
|
||||||
|
ON CONFLICT(project_id, day) DO UPDATE SET users = excluded.users, clients = excluded.clients, revenue = excluded.revenue`)
|
||||||
|
.run(projectId, parisDay(date), num(business.users), num(business.clients), num(business.revenue));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Une photo par projet et par jour, appelée par le planificateur (toutes les 15 min, ne fait rien si déjà prise). */
|
||||||
|
export async function snapshotAll(app, { date = new Date(), log = console } = {}) {
|
||||||
|
const day = parisDay(date);
|
||||||
|
const todo = app.db.prepare(`SELECT id FROM projects WHERE db_enc IS NOT NULL
|
||||||
|
AND id NOT IN (SELECT project_id FROM metrics_daily WHERE day = ?)`).all(day);
|
||||||
|
let n = 0;
|
||||||
|
for (const { id } of todo) {
|
||||||
|
try {
|
||||||
|
const p = getProject(app, id, { secrets: true });
|
||||||
|
saveSnapshot(app.db, id, await (app.fetchRecap || fetchRecap)(id, p.dbCfg, { force: true }), { date });
|
||||||
|
n++;
|
||||||
|
} catch (e) { log.error(`[métriques ${id}]`, e.message); }
|
||||||
|
}
|
||||||
|
return n;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Lundi (heure de Paris) de la semaine qui contient cet instant
|
||||||
|
function weekStart(date) {
|
||||||
|
const p = parisParts(date);
|
||||||
|
const back = ({ Mon: 0, Tue: 1, Wed: 2, Thu: 3, Fri: 4, Sat: 5, Sun: 6 })[p.weekday];
|
||||||
|
const d = addParisDays(date, -back);
|
||||||
|
return `${d.year}-${pad(d.month)}-${pad(d.day)}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Séries pour les graphiques : jours (KPI business) et semaines (envois / réponses). */
|
||||||
|
export function history(db, projectId, { days = 30, at = now() } = {}) {
|
||||||
|
const fromDay = parisDay(new Date((at - (days - 1) * 86400) * 1000));
|
||||||
|
const daily = db.prepare('SELECT day, users, clients, revenue FROM metrics_daily WHERE project_id = ? AND day >= ? ORDER BY day')
|
||||||
|
.all(projectId, fromDay);
|
||||||
|
|
||||||
|
const nWeeks = Math.ceil(days / 7);
|
||||||
|
const weeks = [];
|
||||||
|
let cursor = new Date(at * 1000);
|
||||||
|
for (let i = 0; i < nWeeks; i++) {
|
||||||
|
weeks.unshift({ start: weekStart(cursor), sent: 0, replies: 0 });
|
||||||
|
cursor = new Date(cursor.getTime() - 7 * 86_400_000);
|
||||||
|
}
|
||||||
|
const first = weeks[0].start.split('-').map(Number);
|
||||||
|
const since = Math.floor(parisTime(first[0], first[1], first[2], 0).getTime() / 1000);
|
||||||
|
const bucket = (ts) => weeks.find((w) => w.start === weekStart(new Date(ts * 1000)));
|
||||||
|
for (const r of db.prepare("SELECT sent_at FROM mail_log WHERE project_id = ? AND kind = 'initial' AND error IS NULL AND sent_at >= ?").all(projectId, since)) {
|
||||||
|
const w = bucket(r.sent_at); if (w) w.sent++;
|
||||||
|
}
|
||||||
|
for (const r of db.prepare('SELECT replied_at FROM prospects WHERE project_id = ? AND replied_at >= ?').all(projectId, since)) {
|
||||||
|
const w = bucket(r.replied_at); if (w) w.replies++;
|
||||||
|
}
|
||||||
|
return { daily, weeks };
|
||||||
|
}
|
||||||
|
|
@ -2,11 +2,13 @@
|
||||||
// 1. lecture des boîtes IMAP (réponses, bounces)
|
// 1. lecture des boîtes IMAP (réponses, bounces)
|
||||||
// 2. puis seulement ensuite, mise en file des relances dues
|
// 2. puis seulement ensuite, mise en file des relances dues
|
||||||
// 3. rapport hebdo le lundi à 8h
|
// 3. rapport hebdo le lundi à 8h
|
||||||
|
// 4. photo quotidienne des KPI business (pour les courbes)
|
||||||
import { checkInbox } from './inbox.js';
|
import { checkInbox } from './inbox.js';
|
||||||
import { followupPlan } from './followup.js';
|
import { followupPlan } from './followup.js';
|
||||||
import { enqueue } from './jobs.js';
|
import { enqueue } from './jobs.js';
|
||||||
import { getProject } from '../projects.js';
|
import { getProject } from '../projects.js';
|
||||||
import { maybeSendWeekly } from './report.js';
|
import { maybeSendWeekly } from './report.js';
|
||||||
|
import { snapshotAll } from './metrics.js';
|
||||||
|
|
||||||
export class Scheduler {
|
export class Scheduler {
|
||||||
constructor(app, { everyMs = 15 * 60_000, log = console } = {}) {
|
constructor(app, { everyMs = 15 * 60_000, log = console } = {}) {
|
||||||
|
|
@ -38,6 +40,7 @@ export class Scheduler {
|
||||||
this.queueFollowups();
|
this.queueFollowups();
|
||||||
try { await maybeSendWeekly(this.app); }
|
try { await maybeSendWeekly(this.app); }
|
||||||
catch (e) { this.log.error('[rapport hebdo]', e.message); }
|
catch (e) { this.log.error('[rapport hebdo]', e.message); }
|
||||||
|
await snapshotAll(this.app, { log: this.log });
|
||||||
} finally { this.running = false; }
|
} finally { this.running = false; }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
68
test/metrics.test.js
Normal file
68
test/metrics.test.js
Normal file
|
|
@ -0,0 +1,68 @@
|
||||||
|
import { test } from 'node:test';
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import { randomBytes } from 'node:crypto';
|
||||||
|
import { openDb } from '../src/db.js';
|
||||||
|
import { saveSnapshot, snapshotAll, history, parisDay } from '../src/services/metrics.js';
|
||||||
|
import { createProject, saveSecretConfig } from '../src/projects.js';
|
||||||
|
|
||||||
|
const ts = (iso) => Math.floor(Date.parse(iso) / 1000);
|
||||||
|
|
||||||
|
function setup() {
|
||||||
|
const db = openDb(':memory:');
|
||||||
|
const app = { db, cfg: { secretKey: randomBytes(32) } };
|
||||||
|
const id = createProject(app, { name: 'MEP', gitUrl: 'https://g/T/M.git' });
|
||||||
|
return { db, app, id };
|
||||||
|
}
|
||||||
|
|
||||||
|
test('jour de Paris, même à 23h30 UTC', () => {
|
||||||
|
assert.equal(parisDay(new Date('2026-10-21T22:30:00Z')), '2026-10-22');
|
||||||
|
assert.equal(parisDay(new Date('2026-12-31T22:59:00Z')), '2026-12-31');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('photo du jour : une ligne par jour, valeurs non numériques ignorées', () => {
|
||||||
|
const s = setup();
|
||||||
|
const d = new Date('2026-10-21T10:00:00Z');
|
||||||
|
saveSnapshot(s.db, s.id, { users: 10, clients: 2, revenue: 'n/a' }, { date: d });
|
||||||
|
saveSnapshot(s.db, s.id, { users: 12, clients: 3, revenue: 150.5 }, { date: d });
|
||||||
|
const rows = s.db.prepare('SELECT * FROM metrics_daily').all();
|
||||||
|
assert.equal(rows.length, 1, 'mise à jour, pas de doublon');
|
||||||
|
assert.deepEqual({ ...rows[0] }, { project_id: s.id, day: '2026-10-21', users: 12, clients: 3, revenue: 150.5 });
|
||||||
|
});
|
||||||
|
|
||||||
|
test('photo automatique : une seule par jour et par projet, les erreurs n\'arrêtent pas les autres', async () => {
|
||||||
|
const s = setup();
|
||||||
|
const other = createProject(s.app, { name: 'GoSortir', gitUrl: 'https://g/T/G.git' });
|
||||||
|
createProject(s.app, { name: 'Sans BDD', gitUrl: 'https://g/T/X.git' });
|
||||||
|
for (const id of [s.id, other]) saveSecretConfig(s.app, id, 'db_enc', { type: 'mysql', host: 'h', sql_users: 'SELECT 1' }, 'password');
|
||||||
|
let calls = 0;
|
||||||
|
s.app.fetchRecap = async (id) => { calls++; if (id === other) throw new Error('BDD injoignable'); return { users: 5, clients: 1, revenue: 30 }; };
|
||||||
|
const log = { errors: [], error(...a) { this.errors.push(a.join(' ')); } };
|
||||||
|
const date = new Date('2026-10-21T10:00:00Z');
|
||||||
|
assert.equal(await snapshotAll(s.app, { date, log }), 1);
|
||||||
|
assert.match(log.errors[0], /BDD injoignable/);
|
||||||
|
assert.equal(calls, 2, 'le projet sans BDD n\'est pas interrogé');
|
||||||
|
await snapshotAll(s.app, { date: new Date('2026-10-21T15:00:00Z'), log });
|
||||||
|
assert.equal(calls, 3, 'déjà pris : seul le projet en erreur est retenté');
|
||||||
|
await snapshotAll(s.app, { date: new Date('2026-10-22T08:00:00Z'), log });
|
||||||
|
assert.equal(s.db.prepare('SELECT COUNT(*) n FROM metrics_daily WHERE project_id = ?').get(s.id).n, 2);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('historique : fenêtre 30/90 jours et semaines du lundi au dimanche (heure de Paris)', () => {
|
||||||
|
const s = setup();
|
||||||
|
const at = ts('2026-10-21T12:00:00Z'); // mercredi
|
||||||
|
for (const day of ['2026-08-01', '2026-09-25', '2026-10-20']) s.db.prepare('INSERT INTO metrics_daily VALUES(?, ?, 1, 1, 1)').run(s.id, day);
|
||||||
|
assert.deepEqual(history(s.db, s.id, { days: 30, at }).daily.map((d) => d.day), ['2026-09-25', '2026-10-20']);
|
||||||
|
assert.equal(history(s.db, s.id, { days: 90, at }).daily.length, 3);
|
||||||
|
|
||||||
|
const log = (iso, kind = 'initial', error = null) => s.db.prepare('INSERT INTO mail_log(project_id, email, sent_at, kind, error) VALUES(?, ?, ?, ?, ?)').run(s.id, 'x@y.fr', ts(iso), kind, error);
|
||||||
|
log('2026-10-19T00:30:00+02:00'); // lundi 0h30 Paris = dimanche UTC : semaine du 19
|
||||||
|
log('2026-10-18T23:30:00+02:00'); // dimanche soir : semaine du 12
|
||||||
|
log('2026-10-20T10:00:00+02:00');
|
||||||
|
log('2026-10-20T10:00:00+02:00', 'followup'); // les relances ne comptent pas comme premiers mails
|
||||||
|
log('2026-10-20T10:00:00+02:00', 'initial', '550'); // ni les échecs
|
||||||
|
s.db.prepare('INSERT INTO prospects(project_id, company, email, replied_at, created_at) VALUES(?, ?, ?, ?, ?)').run(s.id, 'A', 'a@a.fr', ts('2026-10-21T09:00:00+02:00'), at);
|
||||||
|
const w = history(s.db, s.id, { days: 30, at }).weeks;
|
||||||
|
assert.equal(w.length, 5);
|
||||||
|
assert.equal(w.at(-1).start, '2026-10-19');
|
||||||
|
assert.deepEqual(w.slice(-2).map((x) => [x.start, x.sent, x.replies]), [['2026-10-12', 1, 0], ['2026-10-19', 2, 1]]);
|
||||||
|
});
|
||||||
Loading…
Reference in a new issue