diff --git a/public/app.js b/public/app.js index 378a226..427a554 100644 --- a/public/app.js +++ b/public/app.js @@ -232,6 +232,12 @@ 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]')) { try { await api('/api/notify/test', {}); toast('Notification envoyée sur Discord'); } catch (err) { toast(err.message, 'error'); } diff --git a/src/routes.js b/src/routes.js index 8c07c3b..19f9b3f 100644 --- a/src/routes.js +++ b/src/routes.js @@ -13,6 +13,7 @@ import { followupPlan } from './services/followup.js'; import { nextNightSlot } from './services/paris-time.js'; 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 { getProject, listProjects, createProject, saveSecretConfig, publicConfig, globalSmtp, prospectStats, sentSince, repoDir, getTemplate, saveTemplate, abStats, @@ -71,6 +72,7 @@ export function registerRoutes(router, app) { send_delay_max: getSetting(db, 'send_delay_max', '60'), prospect_model: getSetting(db, 'prospect_model', 'haiku'), 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_month_usd: getSetting(db, 'budget_month_usd', ''), 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, '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) : ''; }; + setSetting(db, 'weekly_report', b.weekly_report === 'on' ? '1' : '0'); setSetting(db, 'budget_day_usd', money(b.budget_day_usd)); setSetting(db, 'budget_month_usd', money(b.budget_month_usd)); @@ -108,6 +111,12 @@ export function registerRoutes(router, app) { }); // ---------- 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 }) => { 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 }); diff --git a/src/services/report.js b/src/services/report.js new file mode 100644 index 0000000..e1f9843 --- /dev/null +++ b/src/services/report.js @@ -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; +} diff --git a/src/services/scheduler.js b/src/services/scheduler.js index e6e4e4f..930bed7 100644 --- a/src/services/scheduler.js +++ b/src/services/scheduler.js @@ -1,10 +1,12 @@ // Tâches de fond légères (sans Claude), toutes les 15 min : // 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 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'; export class Scheduler { constructor(app, { everyMs = 15 * 60_000, log = console } = {}) { @@ -34,6 +36,8 @@ export class Scheduler { catch (e) { this.log.error(`[inbox ${id}]`, e.message); } } this.queueFollowups(); + try { await maybeSendWeekly(this.app); } + catch (e) { this.log.error('[rapport hebdo]', e.message); } } finally { this.running = false; } } diff --git a/src/views.js b/src/views.js index 7641e2b..053719c 100644 --- a/src/views.js +++ b/src/views.js @@ -234,7 +234,9 @@ export function settingsPage({ email, s, saved }) { ${saved ? '

Enregistré.

' : ''}

Notifications

- + + +

Forgejo

diff --git a/test/report.test.js b/test/report.test.js new file mode 100644 index 0000000..09231e2 --- /dev/null +++ b/test/report.test.js @@ -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); +});