diff --git a/public/app.css b/public/app.css index e59788a..f62cc2b 100644 --- a/public/app.css +++ b/public/app.css @@ -99,3 +99,4 @@ form.send { margin-top: 18px; padding-top: 14px; border-top: 1px solid var(--lin @media (max-width: 640px) { .sys { order: 3; flex-basis: 100%; } } .inbox { margin: 10px 0 4px; line-height: 1.9; } .inbox:empty { display: none; } +.followup { margin-top: 18px; padding-top: 12px; border-top: 1px solid var(--line); } diff --git a/public/app.js b/public/app.js index 212824a..a276677 100644 --- a/public/app.js +++ b/public/app.js @@ -30,7 +30,10 @@ }; const pct = (x) => `${Math.round(x * 100)} %`; const ACTIVE = ['queued', 'running']; - const LABELS = { analyze: 'Analyse', prospect: 'Recherche', template: 'Modèle', send: 'Envoi', evolution: 'Évolutions' }; + const LABELS = { + analyze: 'Analyse', prospect: 'Recherche', template: 'Modèle', send: 'Envoi', evolution: 'Évolutions', + followup_template: 'Modèle de relance', followup: 'Relances', + }; // ---------- Barre système ---------- async function refreshSys() { @@ -67,6 +70,7 @@ let txt = `${LABELS[type]} terminé(e).`; if (type === 'prospect') txt = `Recherche terminée : ${r.found} nouveau(x) prospect(s) sur ${r.requested} demandés.`; if (type === 'send') txt = `Envoi terminé : ${r.sent} envoyé(s), ${r.failed} échec(s).`; + if (type === 'followup') txt = r.postponed ? 'Relances reportées au prochain créneau (lun-ven 9h-18h).' : `Relances terminées : ${r.sent} envoyée(s), ${r.failed} échec(s).`; if (type === 'evolution') { box.innerHTML = `
Envoyé à ${esc(r.sentTo)}.
${esc(r.markdown)}`;
return;
@@ -84,7 +88,7 @@
try { s = await api(`/api/projects/${id}/status`); } catch (e) { return schedule(el, 30_000); }
const st = state.get(id) || {};
const jobs = s.jobs;
- for (const type of ['prospect', 'template', 'send', 'evolution']) renderJob($(`[data-job="${type}"]`, el), jobs[type], type);
+ for (const type of ['prospect', 'template', 'send', 'evolution', 'followup_template', 'followup']) renderJob($(`[data-job="${type}"]`, el), jobs[type], type);
const running = Object.entries(jobs).filter(([, j]) => ACTIVE.includes(j.status)).map(([t]) => LABELS[t]);
$('[data-state]', el).innerHTML = running.length
@@ -102,15 +106,29 @@
if (an?.status === 'error' && !s.hasProfile) $('.profile p', el).outerHTML = `${esc(an.error)}
`; // Modèle de mail : on ne remplace le formulaire que s'il a changé côté serveur - const tplForm = $('form[data-action="template"]', el); - if (s.template && st.tplStamp !== s.template.updated_at) { - st.tplStamp = s.template.updated_at; - tplForm.subject.value = s.template.subject; - tplForm.subjectB.value = s.template.subjectB || ''; - tplForm.body.value = s.template.body; + st.tplStamp ||= {}; + for (const kind of ['initial', 'followup']) { + const t = s.templates[kind]; + const form = $(`form[data-action="template"][data-kind="${kind}"]`, el); + if (t && st.tplStamp[kind] !== t.updated_at) { + st.tplStamp[kind] = t.updated_at; + form.subject.value = t.subject; + if (form.subjectB) form.subjectB.value = t.subjectB || ''; + form.body.value = t.body; + } + $('[data-tpl-state]', form).innerHTML = t + ? (t.status === 'validated' ? 'validé' : 'brouillon') : ''; } - $('[data-tpl-state]', el).innerHTML = s.template - ? (s.template.status === 'validated' ? 'validé' : 'brouillon') : ''; + + // Relance automatique : ce qui est prévu, ou ce qui bloque + const f = s.followup; + $('[data-followup-info]', el).innerHTML = !f.enabled + ? 'Désactivée.' + : f.blockers.length + ? `En attente : ${esc(f.blockers.join(', '))}. ${f.due} relance(s) due(s).` + : f.due + ? `${f.due} relance(s) due(s) : ${f.inHours ? 'envoi au prochain passage (≤ 15 min)' : 'envoi aux heures ouvrées (lun-ven 9h-18h)'}.` + : `Active : les prospects sans réponse après ${f.days} jours seront relancés une fois.`; // Bouton Envoyer : recherche finie + modèle validé + SMTP + quota dispo const prospecting = jobs.prospect && ACTIVE.includes(jobs.prospect.status); @@ -119,7 +137,7 @@ const blockers = []; if (prospecting) blockers.push('recherche en cours'); if (sending) blockers.push('envoi en cours'); - if (s.template?.status !== 'validated') blockers.push('modèle à valider'); + if (s.templates.initial?.status !== 'validated') blockers.push('modèle à valider'); if (!s.hasSmtp) blockers.push('SMTP à configurer'); if (!s.sendMax) blockers.push(s.stats.new ? 'plafond du jour atteint' : 'aucun prospect à contacter'); $('button', sendForm).disabled = blockers.length > 0; @@ -235,6 +253,7 @@ await api(`/api/projects/${id}/evolution`, data); toast('Recherche d\'évolutions lancée'); break; } case 'template': { + data.kind = form.dataset.kind; const r = await api(`/api/projects/${id}/template/save`, data); toast(r.status === 'validated' ? 'Modèle validé' : 'Brouillon enregistré'); break; @@ -255,6 +274,12 @@ else toast(r.error, 'error'); break; } + case 'followup': { + data.enabled = form.enabled.checked; + await api(`/api/projects/${id}/followup`, data); + toast(data.enabled ? 'Relance automatique activée' : 'Relance automatique désactivée'); + break; + } case 'db': data.ssl = form.ssl.checked; await api(`/api/projects/${id}/db`, data); toast('Accès BDD enregistré'); form.password.value = ''; break; case 'delete': await api(`/api/projects/${id}/delete`, {}); location.reload(); break; } diff --git a/src/db.js b/src/db.js index 65bd7ae..1230762 100644 --- a/src/db.js +++ b/src/db.js @@ -95,6 +95,12 @@ export const MIGRATIONS = [ ALTER TABLE projects ADD COLUMN imap_enc TEXT; ALTER TABLE projects ADD COLUMN inbox_json TEXT; -- état de la dernière lecture IMAP `, + // 5 — relance automatique + ` + ALTER TABLE prospects ADD COLUMN followup_at INTEGER; + ALTER TABLE projects ADD COLUMN followup_enabled INTEGER NOT NULL DEFAULT 0; + ALTER TABLE projects ADD COLUMN followup_days INTEGER NOT NULL DEFAULT 7; + `, ]; export function openDb(dataDir) { diff --git a/src/handlers.js b/src/handlers.js index 7bf0197..8938008 100644 --- a/src/handlers.js +++ b/src/handlers.js @@ -3,7 +3,8 @@ import { now, getSetting } from './db.js'; import { runClaude, extractJson } from './services/claude.js'; import { addUsage } from './services/jobs.js'; import { syncRepo } from './services/git.js'; -import { analyzePrompt, prospectPrompt, templatePrompt, evolutionPrompt, LEVELS } from './services/prompts.js'; +import { analyzePrompt, prospectPrompt, templatePrompt, followupTemplatePrompt, evolutionPrompt, LEVELS } from './services/prompts.js'; +import { followupCandidates, followupSubject, isBusinessHours } from './services/followup.js'; import { EMAIL_RE, createTransport, buildProspectMail, allowedToSend, makeMessageId } from './services/mailer.js'; import { unsubToken } from './crypto.js'; import { getProject, repoDir, forgejoToken, globalSmtp, sentSince, getTemplate, saveTemplate, pickVariant } from './projects.js'; @@ -32,6 +33,87 @@ export function makeHandlers(app) { const { db, cfg } = app; const claude = (o) => runClaude({ bin: cfg.claudeBin, ...o }); + const inHours = () => (app.isBusinessHours || isBusinessHours)(); + + // Premier mail ou relance : mêmes plafonds, mêmes délais, même journal + async function sendMails(ctx, kind) { + // Une relance mise en file à 17h55 ne doit pas partir à 19h si le worker était occupé + if (kind === 'followup' && !inHours()) return { sent: 0, failed: 0, total: 0, postponed: true }; + const project = getProject(app, ctx.job.project_id, { secrets: true }); + const template = getTemplate(db, project.id, kind, { validatedOnly: true }); + if (!template) throw new Error(kind === 'followup' ? 'Modèle de relance non validé' : 'Modèle de mail non validé'); + if (!project.smtp) throw new Error('SMTP non configuré pour ce projet'); + + const day = now() - 86400; + const candidates = kind === 'followup' + ? followupCandidates(db, project) + : db.prepare(`SELECT * FROM prospects WHERE project_id = ? AND status = 'new' + AND email NOT IN (SELECT email FROM blacklist) ORDER BY score DESC, id LIMIT 100`).all(project.id); + const n = allowedToSend({ + requested: ctx.params.count, + available: candidates.length, + projectCap: project.dailyMailCap, + sentTodayProject: sentSince(db, day, project.id), + globalCap: Number(getSetting(db, 'global_daily_cap', '100')), + sentTodayGlobal: sentSince(db, day), + }); + if (n === 0) throw new Error(kind === 'followup' ? 'Plafond quotidien atteint ou aucune relance due' : 'Plafond quotidien atteint ou aucun prospect à contacter'); + + const transport = (app.createTransport || createTransport)(project.smtp); + await transport.verify(); + const minDelay = Number(getSetting(db, 'send_delay_min', '20')) * 1000; + const maxDelay = Number(getSetting(db, 'send_delay_max', '60')) * 1000; + const log = db.prepare(`INSERT INTO mail_log(project_id, prospect_id, email, sent_at, error, kind, variant, subject, message_id) + VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?)`); + const markInitial = db.prepare('UPDATE prospects SET status = ?, sent_at = ?, variant = ? WHERE id = ?'); + const markFollowup = db.prepare('UPDATE prospects SET followup_at = ? WHERE id = ?'); + const markBounced = db.prepare("UPDATE prospects SET status = 'bounced' WHERE id = ?"); + const original = db.prepare("SELECT subject, message_id FROM mail_log WHERE prospect_id = ? AND kind = 'initial' AND error IS NULL ORDER BY id LIMIT 1"); + const current = db.prepare('SELECT status, followup_at FROM prospects WHERE id = ?'); + let sent = 0, failed = 0; + + for (const p of candidates.slice(0, n)) { + if (ctx.cancelled()) break; + if (kind === 'followup' && !inHours()) break; // le reste repartira au prochain créneau + // Re-vérifie juste avant l'envoi : désinscription, réponse arrivée pendant le batch… + if (db.prepare('SELECT 1 FROM blacklist WHERE email = ?').get(p.email)) continue; + if (kind === 'followup') { + const c = current.get(p.id); + if (c.status !== 'sent' || c.followup_at) continue; + } + const unsubUrl = `${cfg.appUrl}/u/${encodeURIComponent(p.email)}/${unsubToken(cfg.secretKey, p.email)}`; + let variant = null, subject, inReplyTo; + if (kind === 'initial') { + variant = pickVariant(db, project.id, template); + subject = variant === 'B' ? template.subject_b : template.subject; + } else { + const orig = original.get(p.id); + subject = followupSubject(template, orig); + inReplyTo = orig?.message_id; + } + const mail = buildProspectMail({ + template, prospect: p, smtp: project.smtp, unsubUrl, subject, inReplyTo, + messageId: makeMessageId(project.smtp.fromEmail), + }); + try { + await transport.sendMail(mail); + log.run(project.id, p.id, p.email, now(), null, kind, variant, mail.subject, mail.messageId); + if (kind === 'initial') markInitial.run('sent', now(), variant, p.id); + else markFollowup.run(now(), p.id); + sent++; + } catch (e) { + log.run(project.id, p.id, p.email, now(), String(e.message).slice(0, 500), kind, variant, mail.subject, mail.messageId); + if (/^5\d\d/.test(String(e.responseCode))) markBounced.run(p.id); + failed++; + } + const label = kind === 'followup' ? 'relances envoyées' : 'envoyés'; + ctx.progress({ sent, failed, total: n, message: `${sent + failed}/${n} ${label}` }); + if (sent + failed < n) await sleep(minDelay + Math.random() * (maxDelay - minDelay), ctx.signal).catch(() => {}); + } + transport.close(); + return { sent, failed, total: n }; + } + return { async analyze(ctx) { const project = getProject(app, ctx.job.project_id); @@ -105,62 +187,21 @@ export function makeHandlers(app) { return { ok: true }; }, - async send(ctx) { + async followup_template(ctx) { const project = getProject(app, ctx.job.project_id, { secrets: true }); - const template = getTemplate(db, project.id, 'initial', { validatedOnly: true }); - if (!template) throw new Error('Modèle de mail non validé'); - if (!project.smtp) throw new Error('SMTP non configuré pour ce projet'); - - const day = now() - 86400; - const candidates = db.prepare(`SELECT * FROM prospects WHERE project_id = ? AND status = 'new' - AND email NOT IN (SELECT email FROM blacklist) ORDER BY score DESC, id LIMIT 100`).all(project.id); - const n = allowedToSend({ - requested: ctx.params.count, - available: candidates.length, - projectCap: project.dailyMailCap, - sentTodayProject: sentSince(db, day, project.id), - globalCap: Number(getSetting(db, 'global_daily_cap', '100')), - sentTodayGlobal: sentSince(db, day), - }); - if (n === 0) throw new Error('Plafond quotidien atteint ou aucun prospect à contacter'); - - const transport = (app.createTransport || createTransport)(project.smtp); - await transport.verify(); - const minDelay = Number(getSetting(db, 'send_delay_min', '20')) * 1000; - const maxDelay = Number(getSetting(db, 'send_delay_max', '60')) * 1000; - const log = db.prepare(`INSERT INTO mail_log(project_id, prospect_id, email, sent_at, error, kind, variant, subject, message_id) - VALUES(?, ?, ?, ?, ?, 'initial', ?, ?, ?)`); - const mark = db.prepare('UPDATE prospects SET status = ?, sent_at = ?, variant = ? WHERE id = ?'); - let sent = 0, failed = 0; - - for (const p of candidates.slice(0, n)) { - if (ctx.cancelled()) break; - // Re-vérifie la blacklist juste avant l'envoi (désinscription pendant le batch) - if (db.prepare('SELECT 1 FROM blacklist WHERE email = ?').get(p.email)) continue; - const unsubUrl = `${cfg.appUrl}/u/${encodeURIComponent(p.email)}/${unsubToken(cfg.secretKey, p.email)}`; - const variant = pickVariant(db, project.id, template); - const mail = buildProspectMail({ - template, prospect: p, smtp: project.smtp, unsubUrl, - subject: variant === 'B' ? template.subject_b : template.subject, - messageId: makeMessageId(project.smtp.fromEmail), - }); - try { - await transport.sendMail(mail); - log.run(project.id, p.id, p.email, now(), null, variant, mail.subject, mail.messageId); - mark.run('sent', now(), variant, p.id); - sent++; - } catch (e) { - log.run(project.id, p.id, p.email, now(), String(e.message).slice(0, 500), variant, mail.subject, mail.messageId); - if (/^5\d\d/.test(String(e.responseCode))) mark.run('bounced', now(), variant, p.id); - failed++; - } - ctx.progress({ sent, failed, total: n, message: `${sent + failed}/${n} envoyés` }); - if (sent + failed < n) await sleep(minDelay + Math.random() * (maxDelay - minDelay), ctx.signal).catch(() => {}); - } - transport.close(); - return { sent, failed, total: n }; + if (!project.profile) throw new Error('Analyse le projet d\'abord'); + const { prompt, system } = followupTemplatePrompt({ profile: project.profile, senderName: project.smtp?.fromName }); + const r = await claude({ prompt, system, model: 'haiku', maxTurns: 1, tools: [], signal: ctx.signal }); + addUsage(ctx, r); + const t = extractJson(r.text); + if (!t.body) throw new Error('Modèle de relance invalide'); + saveTemplate(db, project.id, 'followup', { subject: '', body: t.body }); + return { ok: true }; }, + send: (ctx) => sendMails(ctx, 'initial'), + followup: (ctx) => sendMails(ctx, 'followup'), + async evolution(ctx) { const project = getProject(app, ctx.job.project_id, { secrets: true }); const count = Math.max(1, Math.min(20, Math.floor(Number(ctx.params.count) || 5))); diff --git a/src/projects.js b/src/projects.js index 2d78a96..b69e555 100644 --- a/src/projects.js +++ b/src/projects.js @@ -17,6 +17,7 @@ export function getProject(app, id, { secrets = false } = {}) { dailyMailCap: p.daily_mail_cap, createdAt: p.created_at, hasSmtp: !!p.smtp_enc, hasDb: !!p.db_enc, hasImap: !!p.imap_enc, inbox: parse(p.inbox_json), + followupEnabled: !!p.followup_enabled, followupDays: p.followup_days, }; if (secrets) { out.smtp = decryptJson(app.cfg.secretKey, p.smtp_enc); diff --git a/src/routes.js b/src/routes.js index f25b1f8..b6d2762 100644 --- a/src/routes.js +++ b/src/routes.js @@ -9,6 +9,7 @@ import { fetchRecap, clearRecapCache, validateSelect } from './services/recap.js import { allowedToSend, EMAIL_RE } from './services/mailer.js'; import { cpuTemp } from './services/thermal.js'; import { checkInbox } from './services/inbox.js'; +import { followupPlan } from './services/followup.js'; import { getProject, listProjects, createProject, saveSecretConfig, publicConfig, globalSmtp, prospectStats, sentSince, repoDir, getTemplate, saveTemplate, abStats, @@ -123,8 +124,8 @@ export function registerRoutes(router, app) { router.get('/api/projects/:id/status', ({ res, params }) => { const p = getProject(app, pid(params)); const jobs = latestJobs(db, p.id); - const row = getTemplate(db, p.id, 'initial'); - const tpl = row ? { subject: row.subject, subjectB: row.subject_b, body: row.body, status: row.status, updated_at: row.updated_at } : null; + const tplOut = (row) => (row ? { subject: row.subject, subjectB: row.subject_b, body: row.body, status: row.status, updated_at: row.updated_at } : null); + const templates = { initial: tplOut(getTemplate(db, p.id, 'initial')), followup: tplOut(getTemplate(db, p.id, 'followup')) }; const stats = prospectStats(db, p.id); const day = now() - 86400; const sendMax = allowedToSend({ @@ -133,7 +134,8 @@ export function registerRoutes(router, app) { globalCap: Number(getSetting(db, 'global_daily_cap', '100')), sentTodayGlobal: sentSince(db, day), }); json(res, { - jobs, template: tpl, stats, sendMax, + jobs, templates, stats, sendMax, + followup: { enabled: p.followupEnabled, days: p.followupDays, ...followupPlan(db, p) }, targetValidated: p.targetValidated, hasProfile: !!p.profile, hasSmtp: p.hasSmtp, hasImap: p.hasImap, inbox: p.inbox, ab: abStats(db, p.id), }); @@ -167,6 +169,16 @@ export function registerRoutes(router, app) { router.post('/api/projects/:id/template', jobRoute('template', () => ({}), (p) => { if (!p.profile) throw new HttpError(400, "Analyse le projet d'abord"); })); + router.post('/api/projects/:id/followup_template', jobRoute('followup_template', () => ({}), (p) => { + if (!p.profile) throw new HttpError(400, "Analyse le projet d'abord"); + })); + router.post('/api/projects/:id/followup', async ({ req, res, params }) => { + const p = getProject(app, pid(params)); + const b = await readBody(req); + const enabled = b.enabled === true || b.enabled === 'on'; + db.prepare('UPDATE projects SET followup_enabled = ?, followup_days = ? WHERE id = ?').run(enabled ? 1 : 0, int(b.days, 2, 30, 7), p.id); + json(res, { ok: true }); + }); router.post('/api/projects/:id/prospect', jobRoute('prospect', (b) => ({ count: int(b.count, 1, 50, 10) }), (p) => { if (!p.targetValidated) throw new HttpError(400, 'Valide la cible avant de prospecter'); })); @@ -186,9 +198,11 @@ export function registerRoutes(router, app) { const subject = String(b.subject || '').trim().slice(0, 200); const body = String(b.body || '').trim().slice(0, 5000); const subjectB = String(b.subjectB || '').trim().slice(0, 200) || null; - if (!subject || !body) throw new HttpError(400, 'Objet et corps requis'); + const kind = b.kind === 'followup' ? 'followup' : 'initial'; + // Relance : objet facultatif (vide = "Re: