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é.
' : ''}