From 287061cb1c5c1731196372d08d591616ca08b45c Mon Sep 17 00:00:00 2001
From: Tony Averty Mails envoyés Réponses ${empty} ${esc(err.message)} Coût IA du projet (équivalent API) : $${r.aiCostUsd.toFixed(2)}${b?.cached ? ' · chiffres en cache (10 min)' : ''}
-
${x.sent} envoyé(s) · ${x.replies} 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 `Évolution
+ Voir les données
+
+
+ ${h.daily.map((d) => `Jour Utilisateurs Clients Revenu `).join('') || '${shortDay(d.day)} ${d.users ?? '–'} ${d.clients ?? '–'} ${d.revenue != null ? esc(fmtVal(d.revenue, '€')) : '–'} '}
+ Aucune photo pour l\'instant.
+ ${h.weeks.map((x) => `Semaine du Envoyés Réponses `).join('')}
+ ${shortDay(x.start)} ${x.sent} ${x.replies}
${esc(err.message)}
`; } } diff --git a/src/db.js b/src/db.js index a505329..e42528b 100644 --- a/src/db.js +++ b/src/db.js @@ -117,6 +117,15 @@ export const MIGRATIONS = [ ALTER TABLE prospects ADD COLUMN next_action TEXT; 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) { diff --git a/src/routes.js b/src/routes.js index 70f4bd8..9302977 100644 --- a/src/routes.js +++ b/src/routes.js @@ -15,6 +15,7 @@ import { notify, notifyConfig, EVENTS, WEBHOOK_RE } from './services/notify.js'; import { budgetState, AI_JOBS } from './services/budget.js'; import { sendWeeklyReport } from './services/report.js'; import { exportProspects, importProspects } from './services/csv.js'; +import { history, saveSnapshot } from './services/metrics.js'; import { listProspects, parseFilters, STATUSES as PROSPECT_STATUSES, prospectDetail, addNote, deleteNote, setNextAction, } from './services/crm.js'; @@ -301,8 +302,10 @@ export function registerRoutes(router, app) { 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; let business = null, error = null; - try { business = await fetchRecap(p.id, p.dbCfg, { force: url.searchParams.has('force') }); } - catch (e) { error = e.message; } + try { + 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 }); }); @@ -325,6 +328,11 @@ export function registerRoutes(router, app) { 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 }) => { const p = getProject(app, pid(params)); json(res, listProspects(db, p.id, parseFilters(url.searchParams))); diff --git a/src/services/metrics.js b/src/services/metrics.js new file mode 100644 index 0000000..75d9bbd --- /dev/null +++ b/src/services/metrics.js @@ -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 }; +} diff --git a/src/services/scheduler.js b/src/services/scheduler.js index 930bed7..104e3a6 100644 --- a/src/services/scheduler.js +++ b/src/services/scheduler.js @@ -2,11 +2,13 @@ // 1. lecture des boîtes IMAP (réponses, bounces) // 2. puis seulement ensuite, mise en file des relances dues // 3. rapport hebdo le lundi à 8h +// 4. photo quotidienne des KPI business (pour les courbes) import { checkInbox } from './inbox.js'; import { followupPlan } from './followup.js'; import { enqueue } from './jobs.js'; import { getProject } from '../projects.js'; import { maybeSendWeekly } from './report.js'; +import { snapshotAll } from './metrics.js'; export class Scheduler { constructor(app, { everyMs = 15 * 60_000, log = console } = {}) { @@ -38,6 +40,7 @@ export class Scheduler { this.queueFollowups(); try { await maybeSendWeekly(this.app); } catch (e) { this.log.error('[rapport hebdo]', e.message); } + await snapshotAll(this.app, { log: this.log }); } finally { this.running = false; } } diff --git a/test/metrics.test.js b/test/metrics.test.js new file mode 100644 index 0000000..41b70a1 --- /dev/null +++ b/test/metrics.test.js @@ -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]]); +});