feat: send weekly report by email and discord

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SfihHazrSHXgndJtSNLubJ
This commit is contained in:
Tony Averty 2026-10-21 15:41:27 +02:00
parent 4cba23b264
commit 6fe24f0e86
No known key found for this signature in database
6 changed files with 198 additions and 1 deletions

View file

@ -232,6 +232,12 @@
if (e.target.matches('[data-recap-refresh]')) loadRecap(e.target.closest('.project'), true); if (e.target.matches('[data-recap-refresh]')) loadRecap(e.target.closest('.project'), true);
if (e.target.closest('[data-report-send]')) {
try { const r = await api('/api/report/send', {}); toast(`Rapport envoyé (${r.channels.join(' + ')})`); }
catch (err) { toast(err.message, 'error'); }
return;
}
if (e.target.closest('[data-notify-test]')) { if (e.target.closest('[data-notify-test]')) {
try { await api('/api/notify/test', {}); toast('Notification envoyée sur Discord'); } try { await api('/api/notify/test', {}); toast('Notification envoyée sur Discord'); }
catch (err) { toast(err.message, 'error'); } catch (err) { toast(err.message, 'error'); }

View file

@ -13,6 +13,7 @@ import { followupPlan } from './services/followup.js';
import { nextNightSlot } from './services/paris-time.js'; import { nextNightSlot } from './services/paris-time.js';
import { notify, notifyConfig, EVENTS, WEBHOOK_RE } from './services/notify.js'; 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 { import {
getProject, listProjects, createProject, saveSecretConfig, publicConfig, globalSmtp, getProject, listProjects, createProject, saveSecretConfig, publicConfig, globalSmtp,
prospectStats, sentSince, repoDir, getTemplate, saveTemplate, abStats, prospectStats, sentSince, repoDir, getTemplate, saveTemplate, abStats,
@ -71,6 +72,7 @@ export function registerRoutes(router, app) {
send_delay_max: getSetting(db, 'send_delay_max', '60'), send_delay_max: getSetting(db, 'send_delay_max', '60'),
prospect_model: getSetting(db, 'prospect_model', 'haiku'), prospect_model: getSetting(db, 'prospect_model', 'haiku'),
blacklist_count: db.prepare('SELECT COUNT(*) n FROM blacklist').get().n, blacklist_count: db.prepare('SELECT COUNT(*) n FROM blacklist').get().n,
weekly_report: getSetting(db, 'weekly_report', '0') === '1',
budget_day_usd: getSetting(db, 'budget_day_usd', ''), budget_day_usd: getSetting(db, 'budget_day_usd', ''),
budget_month_usd: getSetting(db, 'budget_month_usd', ''), budget_month_usd: getSetting(db, 'budget_month_usd', ''),
discord: { set: !!notifyConfig(app).url, events: notifyConfig(app).events, all: EVENTS }, discord: { set: !!notifyConfig(app).url, events: notifyConfig(app).events, all: EVENTS },
@ -92,6 +94,7 @@ export function registerRoutes(router, app) {
setSetting(db, 'send_delay_max', String(dmax)); setSetting(db, 'send_delay_max', String(dmax));
setSetting(db, 'prospect_model', b.prospect_model === 'sonnet' ? 'sonnet' : 'haiku'); setSetting(db, 'prospect_model', b.prospect_model === 'sonnet' ? 'sonnet' : 'haiku');
const money = (v) => { const n = Number(String(v || '').replace(',', '.')); return Number.isFinite(n) && n > 0 ? String(Math.round(n * 100) / 100) : ''; }; const money = (v) => { const n = Number(String(v || '').replace(',', '.')); return Number.isFinite(n) && n > 0 ? String(Math.round(n * 100) / 100) : ''; };
setSetting(db, 'weekly_report', b.weekly_report === 'on' ? '1' : '0');
setSetting(db, 'budget_day_usd', money(b.budget_day_usd)); setSetting(db, 'budget_day_usd', money(b.budget_day_usd));
setSetting(db, 'budget_month_usd', money(b.budget_month_usd)); setSetting(db, 'budget_month_usd', money(b.budget_month_usd));
@ -108,6 +111,12 @@ export function registerRoutes(router, app) {
}); });
// ---------- API JSON ---------- // ---------- API JSON ----------
router.post('/api/report/send', async ({ res }) => {
const r = await sendWeeklyReport(app);
if (!r.channels.length) throw new HttpError(400, 'Configure le SMTP global + l\'email de réception, ou un webhook Discord');
json(res, { ok: true, channels: r.channels });
});
router.post('/api/notify/test', async ({ res }) => { router.post('/api/notify/test', async ({ res }) => {
if (!notifyConfig(app).url) throw new HttpError(400, 'Aucun webhook Discord configuré'); if (!notifyConfig(app).url) throw new HttpError(400, 'Aucun webhook Discord configuré');
const ok = await notify(app, 'test', { title: 'Notification de test', description: 'Les notifications AiTools arrivent bien ici.', level: 'ok' }, { force: true }); const ok = await notify(app, 'test', { title: 'Notification de test', description: 'Les notifications AiTools arrivent bien ici.', level: 'ok' }, { force: true });

96
src/services/report.js Normal file
View file

@ -0,0 +1,96 @@
// Rapport hebdo : lundi 8h (Paris), par mail + résumé Discord. Aucun token Claude.
import { now, getSetting, setSetting } from '../db.js';
import { abStats, globalSmtp } from '../projects.js';
import { createTransport } from './mailer.js';
import { notify } from './notify.js';
import { parisParts, parisTime } from './paris-time.js';
const pct = (a, b) => (b ? `${Math.round((a / b) * 100)} %` : '-');
const usd = (n) => `${n.toFixed(2)} $`;
const day = (ts) => new Date(ts * 1000).toLocaleDateString('fr-FR', { day: '2-digit', month: '2-digit', timeZone: 'Europe/Paris' });
export function weeklyStats(db, { at = now() } = {}) {
const from = at - 7 * 86400;
const one = (sql, ...a) => db.prepare(sql).get(...a).n;
const projects = db.prepare('SELECT id, name FROM projects ORDER BY name COLLATE NOCASE').all().map((p) => {
const sent = one("SELECT COUNT(*) n FROM mail_log WHERE project_id = ? AND kind = 'initial' AND error IS NULL AND sent_at > ?", p.id, from);
const ab = abStats(db, p.id);
return {
name: p.name,
found: one('SELECT COUNT(*) n FROM prospects WHERE project_id = ? AND created_at > ?', p.id, from),
sent,
followups: one("SELECT COUNT(*) n FROM mail_log WHERE project_id = ? AND kind = 'followup' AND error IS NULL AND sent_at > ?", p.id, from),
replies: one('SELECT COUNT(*) n FROM prospects WHERE project_id = ? AND replied_at > ?', p.id, from),
clients: one("SELECT COUNT(*) n FROM prospects WHERE project_id = ? AND status = 'client'", p.id),
bounces: one(`SELECT COUNT(*) n FROM blacklist b JOIN prospects x ON x.email = b.email
WHERE x.project_id = ? AND b.reason = 'bounce' AND b.created_at > ?`, p.id, from),
cost: db.prepare('SELECT COALESCE(SUM(cost_usd), 0) c FROM jobs WHERE project_id = ? AND COALESCE(finished_at, created_at) > ?').get(p.id, from).c,
bestSubject: ab.length > 1 && ab.every((v) => v.sent >= 10) ? [...ab].sort((a, b) => b.rate - a.rate)[0] : null,
};
});
const cost = db.prepare('SELECT COALESCE(SUM(cost_usd), 0) c FROM jobs WHERE COALESCE(finished_at, created_at) > ?').get(from).c;
const sum = (k) => projects.reduce((t, p) => t + p[k], 0);
return { from, to: at, projects, totals: { found: sum('found'), sent: sum('sent'), followups: sum('followups'), replies: sum('replies'), cost } };
}
export function weeklyText(st) {
const lines = [`AiTools · semaine du ${day(st.from)} au ${day(st.to)}`, ''];
const t = st.totals;
lines.push(`Total : ${t.found} prospect(s) trouvé(s), ${t.sent} mail(s) + ${t.followups} relance(s), ${t.replies} réponse(s) (${pct(t.replies, t.sent)}), IA ${usd(t.cost)}`, '');
for (const p of st.projects) {
const quiet = !p.found && !p.sent && !p.followups && !p.replies && !p.cost;
if (quiet) { lines.push(`${p.name} : rien cette semaine`, ''); continue; }
lines.push(p.name);
lines.push(` Prospects trouvés : ${p.found}`);
lines.push(` Mails envoyés : ${p.sent} (+ ${p.followups} relance(s))`);
lines.push(` Réponses : ${p.replies} (taux ${pct(p.replies, p.sent)})`);
lines.push(` Clients (total) : ${p.clients}`);
if (p.bounces) lines.push(` Adresses invalides: ${p.bounces}`);
if (p.bestSubject) lines.push(` Test A/B : l'objet ${p.bestSubject.variant} gagne (${pct(p.bestSubject.replied, p.bestSubject.sent)} de réponses)`);
lines.push(` Coût IA : ${usd(p.cost)}`, '');
}
return lines.join('\n').trimEnd() + '\n';
}
/** Envoie le rapport (mail si SMTP global + adresse, Discord si webhook). Retourne les canaux utilisés. */
export async function sendWeeklyReport(app, { at = now() } = {}) {
const st = weeklyStats(app.db, { at });
const text = weeklyText(st);
const channels = [];
const to = getSetting(app.db, 'notify_email');
const smtp = globalSmtp(app);
if (to && smtp) {
const transport = (app.createTransport || createTransport)(smtp);
try {
await transport.sendMail({ from: smtp.fromEmail, to, subject: `[AiTools] Rapport du ${day(st.from)} au ${day(st.to)}`, text });
channels.push('mail');
} finally { transport.close(); }
}
const t = st.totals;
const ok = await notify(app, 'weekly', {
title: `Rapport hebdo · ${day(st.from)} → ${day(st.to)}`, level: 'info',
description: st.projects.filter((p) => p.sent || p.found || p.replies)
.map((p) => `**${p.name}** : ${p.found} trouvés · ${p.sent} envoyés · ${p.replies} réponses`).join('\n') || 'Rien cette semaine.',
fields: [
{ name: 'Réponses', value: `${t.replies} (${pct(t.replies, t.sent)})` },
{ name: 'Relances', value: String(t.followups) },
{ name: 'Coût IA', value: usd(t.cost) },
],
});
if (ok) channels.push('discord');
return { channels, text };
}
/** Appelé toutes les 15 min : envoie une fois par semaine, le lundi à partir de 8h (Paris). */
export async function maybeSendWeekly(app, { date = new Date() } = {}) {
if (getSetting(app.db, 'weekly_report', '0') !== '1') return null;
const p = parisParts(date);
if (p.weekday !== 'Mon' || p.hour < 8) return null;
const mondayAt8 = Math.floor(parisTime(p.year, p.month, p.day, 8).getTime() / 1000);
if (Number(getSetting(app.db, 'weekly_report_last', '0')) >= mondayAt8) return null;
const at = Math.floor(date.getTime() / 1000);
const r = await sendWeeklyReport(app, { at });
// Rien de configuré : on ne marque pas, il partira dès qu'un canal existera
if (r.channels.length) setSetting(app.db, 'weekly_report_last', String(at));
return r;
}

View file

@ -1,10 +1,12 @@
// Tâches de fond légères (sans Claude), toutes les 15 min : // Tâches de fond légères (sans Claude), toutes les 15 min :
// 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
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';
export class Scheduler { export class Scheduler {
constructor(app, { everyMs = 15 * 60_000, log = console } = {}) { constructor(app, { everyMs = 15 * 60_000, log = console } = {}) {
@ -34,6 +36,8 @@ export class Scheduler {
catch (e) { this.log.error(`[inbox ${id}]`, e.message); } catch (e) { this.log.error(`[inbox ${id}]`, e.message); }
} }
this.queueFollowups(); this.queueFollowups();
try { await maybeSendWeekly(this.app); }
catch (e) { this.log.error('[rapport hebdo]', e.message); }
} finally { this.running = false; } } finally { this.running = false; }
} }

View file

@ -234,7 +234,9 @@ export function settingsPage({ email, s, saved }) {
${saved ? '<p class="ok">Enregistré.</p>' : ''} ${saved ? '<p class="ok">Enregistré.</p>' : ''}
<form method="post" action="/settings" class="card cfg"> <form method="post" action="/settings" class="card cfg">
<h4>Notifications</h4> <h4>Notifications</h4>
<label>Email de réception (évolutions)<input name="notify_email" type="email" value="${esc(s.notify_email)}"></label> <label>Email de réception (évolutions, rapport hebdo)<input name="notify_email" type="email" value="${esc(s.notify_email)}"></label>
<label class="check"><input type="checkbox" name="weekly_report" ${s.weekly_report ? 'checked' : ''}> Rapport hebdo le lundi à 8h (mail + Discord)</label>
<button type="button" class="btn small" data-report-send>Envoyer le rapport maintenant</button>
<h4>Forgejo</h4> <h4>Forgejo</h4>
<div class="grid2"> <div class="grid2">

80
test/report.test.js Normal file
View file

@ -0,0 +1,80 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { randomBytes } from 'node:crypto';
import { openDb, now, setSetting, getSetting } from '../src/db.js';
import { encrypt, encryptJson } from '../src/crypto.js';
import { weeklyStats, weeklyText, maybeSendWeekly } from '../src/services/report.js';
import { createProject } from '../src/projects.js';
function setup() {
const db = openDb(':memory:');
const mails = [], hooks = [];
const app = {
db, cfg: { secretKey: randomBytes(32), appUrl: 'https://ai.test' },
createTransport: () => ({ sendMail: async (m) => { mails.push(m); }, close() {} }),
fetch: async (url, o) => { hooks.push(JSON.parse(o.body)); return { ok: true }; },
};
const mep = createProject(app, { name: 'MonEspacePro', gitUrl: 'https://g/T/M.git' });
createProject(app, { name: 'GoSortir', gitUrl: 'https://g/T/G.git' });
const t = now() - 2 * 86400;
for (let i = 0; i < 20; i++) {
const v = i % 2 ? 'B' : 'A';
const replied = (v === 'B' && i < 10) || i === 0;
const pid = Number(db.prepare('INSERT INTO prospects(project_id, company, email, status, sent_at, variant, replied_at, created_at) VALUES(?, ?, ?, ?, ?, ?, ?, ?)')
.run(mep, `E${i}`, `e${i}@x${i}.fr`, i === 3 ? 'client' : replied ? 'replied' : 'sent', t, v, replied ? t + 60 : null, t).lastInsertRowid);
db.prepare("INSERT INTO mail_log(project_id, prospect_id, email, sent_at, kind, variant) VALUES(?, ?, ?, ?, 'initial', ?)").run(mep, pid, `e${i}@x${i}.fr`, t, v);
}
db.prepare("INSERT INTO mail_log(project_id, email, sent_at, kind) VALUES(?, 'e5@x5.fr', ?, 'followup')").run(mep, t);
db.prepare("INSERT INTO mail_log(project_id, email, sent_at, kind, error) VALUES(?, 'e6@x6.fr', ?, 'followup', 'refusé')").run(mep, t);
db.prepare("INSERT INTO blacklist(email, reason, created_at) VALUES('e7@x7.fr', 'bounce', ?)").run(t);
db.prepare("INSERT INTO jobs(project_id, type, status, cost_usd, created_at, finished_at) VALUES(?, 'prospect', 'done', 0.42, ?, ?)").run(mep, t, t);
db.prepare("INSERT INTO jobs(project_id, type, status, cost_usd, created_at, finished_at) VALUES(?, 'prospect', 'done', 9, ?, ?)").run(mep, t - 30 * 86400, t - 30 * 86400);
return { db, app, mails, hooks };
}
test('statistiques de la semaine', () => {
const s = setup();
const st = weeklyStats(s.db);
const mep = st.projects.find((p) => p.name === 'MonEspacePro');
assert.deepEqual({ ...mep, bestSubject: mep.bestSubject?.variant }, {
name: 'MonEspacePro', found: 20, sent: 20, followups: 1, replies: 6, clients: 1, bounces: 1, cost: 0.42, bestSubject: 'B',
});
assert.equal(st.totals.cost, 0.42, 'le job d\'il y a 30 jours ne compte pas');
const txt = weeklyText(st);
assert.match(txt, /^AiTools · semaine du \d\d\/\d\d au \d\d\/\d\d/);
assert.match(txt, /Réponses {10}: 6 \(taux 30 %\)/);
assert.match(txt, /l'objet B gagne \(50 % de réponses\)/);
assert.match(txt, /GoSortir : rien cette semaine/);
});
const MON_0830 = new Date('2026-10-26T08:30:00+01:00');
test('envoi automatique : lundi 8h, une seule fois par semaine, désactivé par défaut', async () => {
const s = setup();
setSetting(s.db, 'notify_email', 'moi@x.fr');
setSetting(s.db, 'smtp_enc', encryptJson(s.app.cfg.secretKey, { host: 'h', user: 'u', pass: 'p', fromEmail: 'aitools@x.fr' }));
setSetting(s.db, 'discord_webhook_enc', encrypt(s.app.cfg.secretKey, 'https://discord.com/api/webhooks/123456789012345678/abcdefghijklmnopqrstuvwxyz'));
assert.equal(await maybeSendWeekly(s.app, { date: MON_0830 }), null, 'désactivé par défaut');
setSetting(s.db, 'weekly_report', '1');
assert.equal(await maybeSendWeekly(s.app, { date: new Date('2026-10-26T07:45:00+01:00') }), null, 'lundi 7h45 : trop tôt');
assert.equal(await maybeSendWeekly(s.app, { date: new Date('2026-10-27T09:00:00+01:00') }), null, 'mardi : non');
const r = await maybeSendWeekly(s.app, { date: MON_0830 });
assert.deepEqual(r.channels, ['mail', 'discord']);
assert.equal(s.mails[0].to, 'moi@x.fr');
assert.match(s.mails[0].subject, /^\[AiTools\] Rapport du/);
assert.match(s.hooks[0].embeds[0].description, /\*\*MonEspacePro\*\* : 20 trouvés · 20 envoyés · 6 réponses/);
assert.equal(await maybeSendWeekly(s.app, { date: new Date('2026-10-26T08:45:00+01:00') }), null, 'pas deux fois le même lundi');
assert.notEqual(await maybeSendWeekly(s.app, { date: new Date('2026-11-02T08:15:00+01:00') }), null, 'lundi suivant');
assert.equal(s.mails.length, 2);
});
test('aucun canal configuré : rien n\'est marqué comme envoyé', async () => {
const s = setup();
setSetting(s.db, 'weekly_report', '1');
const r = await maybeSendWeekly(s.app, { date: MON_0830 });
assert.deepEqual(r.channels, []);
assert.equal(getSetting(s.db, 'weekly_report_last'), null);
});