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: ", même fil de discussion) + if (!body || (kind === 'initial' && !subject)) throw new HttpError(400, kind === 'initial' ? 'Objet et corps requis' : 'Corps requis'); const status = b.mode === 'validate' ? 'validated' : 'draft'; - saveTemplate(db, p.id, 'initial', { subject, subjectB, body, status }); + saveTemplate(db, p.id, kind, { subject, subjectB, body, status }); json(res, { ok: true, status }); }); diff --git a/src/services/followup.js b/src/services/followup.js new file mode 100644 index 0000000..fabd304 --- /dev/null +++ b/src/services/followup.js @@ -0,0 +1,47 @@ +// Relance automatique : qui relancer, quand, et ce qui bloque. +import { now } from '../db.js'; +import { getTemplate } from '../projects.js'; + +const INBOX_MAX_AGE = 2 * 3600; // la boîte doit avoir été lue il y a moins de 2 h + +// Lundi-vendredi, 9h-18h heure de Paris : une relance à 3h du matin sent le robot +export function isBusinessHours(date = new Date(), timeZone = 'Europe/Paris') { + const parts = Object.fromEntries( + new Intl.DateTimeFormat('en-GB', { timeZone, weekday: 'short', hour: 'numeric', hour12: false }) + .formatToParts(date).map((p) => [p.type, p.value]), + ); + const hour = Number(parts.hour) % 24; + return !['Sat', 'Sun'].includes(parts.weekday) && hour >= 9 && hour < 18; +} + +const CANDIDATES_SQL = `FROM prospects WHERE project_id = ? AND status = 'sent' AND followup_at IS NULL + AND sent_at <= ? AND email NOT IN (SELECT email FROM blacklist)`; + +export function followupCandidates(db, project, { at = now(), limit = 100 } = {}) { + const cutoff = at - project.followupDays * 86400; + return db.prepare(`SELECT * ${CANDIDATES_SQL} ORDER BY sent_at, id LIMIT ?`).all(project.id, cutoff, limit); +} + +/** @returns {{due: number, blockers: string[], inHours: boolean, ready: boolean}} */ +export function followupPlan(db, project, { at = now(), date = new Date(at * 1000) } = {}) { + const blockers = []; + if (!project.followupEnabled) blockers.push('relance désactivée'); + if (!getTemplate(db, project.id, 'followup', { validatedOnly: true })) blockers.push('modèle de relance à valider'); + if (!project.hasSmtp) blockers.push('SMTP à configurer'); + // Sans lecture de la boîte, on relancerait des gens qui ont déjà répondu + const inbox = project.inbox || {}; + if (!project.hasImap) blockers.push('boîte IMAP à connecter'); + else if (inbox.lastError || !inbox.lastOk || at - inbox.lastOk > INBOX_MAX_AGE) blockers.push('boîte non vérifiée récemment'); + + const cutoff = at - project.followupDays * 86400; + const due = db.prepare(`SELECT COUNT(*) n ${CANDIDATES_SQL}`).get(project.id, cutoff).n; + const inHours = isBusinessHours(date); + return { due, blockers, inHours, ready: !blockers.length && inHours && due > 0 }; +} + +// Objet de la relance : vide = "Re: " pour rester dans le même fil +export function followupSubject(template, original) { + if (template.subject) return template.subject; + const s = original?.subject || 'notre échange'; + return /^re\s*:/i.test(s) ? s : `Re: ${s}`; +} diff --git a/src/services/prompts.js b/src/services/prompts.js index 19e9c8a..b81e103 100644 --- a/src/services/prompts.js +++ b/src/services/prompts.js @@ -69,6 +69,23 @@ Réponds UNIQUEMENT avec : {"subject":"...","body":"..."}`, }; } +export function followupTemplatePrompt({ profile, senderName }) { + return { + system: SYSTEM_FR, + prompt: `Rédige un mail de RELANCE B2B très court (60 mots max), envoyé dans le même fil que le premier mail resté sans réponse. +Produit : ${profile.resume} +Valeur : ${profile.proposition_valeur} +Ton : ${profile.ton || 'direct et chaleureux'} +Expéditeur : ${senderName || '{{expediteur}}'} + +Règles : rappelle en une phrase l'intérêt pour {{entreprise}}, pose une question simple qui appelle une réponse courte (oui/non), +aucune culpabilisation ("je me permets de revenir vers vous" interdit), pas de proposition d'appel ni de visio. +Variables disponibles : {{entreprise}}, {{ville}}, {{expediteur}}. +Ne mets PAS de lien de désinscription (ajouté automatiquement). +Réponds UNIQUEMENT avec : {"body":"..."}`, + }; +} + export const LEVELS = { rapide: { model: 'haiku', maxTurns: 12, files: 8 }, normal: { model: 'sonnet', maxTurns: 20, files: 15 }, diff --git a/src/services/scheduler.js b/src/services/scheduler.js index 4e22bd0..e6e4e4f 100644 --- a/src/services/scheduler.js +++ b/src/services/scheduler.js @@ -1,5 +1,10 @@ -// Tâches de fond légères (sans Claude) : lecture des boîtes IMAP 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) +// 2. puis seulement ensuite, mise en file des relances dues import { checkInbox } from './inbox.js'; +import { followupPlan } from './followup.js'; +import { enqueue } from './jobs.js'; +import { getProject } from '../projects.js'; export class Scheduler { constructor(app, { everyMs = 15 * 60_000, log = console } = {}) { @@ -28,6 +33,17 @@ export class Scheduler { try { await checkInbox(this.app, id); } catch (e) { this.log.error(`[inbox ${id}]`, e.message); } } + this.queueFollowups(); } finally { this.running = false; } } + + queueFollowups(opts) { + const { db } = this.app; + const queued = []; + for (const { id } of db.prepare('SELECT id FROM projects WHERE followup_enabled = 1').all()) { + const plan = followupPlan(db, getProject(this.app, id), opts); + if (plan.ready) queued.push({ id, ...enqueue(db, { projectId: id, type: 'followup', params: { count: plan.due } }) }); + } + return queued; + } } diff --git a/src/views.js b/src/views.js index fe77236..2b5665e 100644 --- a/src/views.js +++ b/src/views.js @@ -105,6 +105,24 @@ function configForms(p, smtp, dbCfg, imap) { `; } +function templateForm(p, kind) { + const initial = kind === 'initial'; + const job = initial ? 'template' : 'followup_template'; + return `
+

${initial ? 'Modèle de mail' : 'Modèle de relance'}

+
+

Variables : {{entreprise}} {{ville}}${initial ? ' {{accroche}}' : ''} {{expediteur}}. Le lien de désinscription est ajouté automatiquement.

+ + ${initial ? '' : ''} + +
+ + +
+
+
`; +} + function projectItem(p, smtp, dbCfg, imap) { const profile = p.profile; return `
@@ -137,19 +155,7 @@ function projectItem(p, smtp, dbCfg, imap) {
-
-

Modèle de mail

-
-

Variables : {{entreprise}} {{ville}} {{accroche}} {{expediteur}}. Le lien de désinscription est ajouté automatiquement.

- - - -
- - -
-
-
+ ${templateForm(p, 'initial')}
@@ -159,6 +165,18 @@ function projectItem(p, smtp, dbCfg, imap) {

+
+

Relance automatique

+ + + + + +

+ ${templateForm(p, 'followup')} +
+
+
Prospects
diff --git a/test/fixtures/fake-claude.js b/test/fixtures/fake-claude.js index 0dfc29e..7792c70 100755 --- a/test/fixtures/fake-claude.js +++ b/test/fixtures/fake-claude.js @@ -6,6 +6,7 @@ out({ type: 'system', subtype: 'init', args: process.argv.slice(2) }); if (prompt.includes('CRASH')) process.exit(3); const profile = { resume: 'Cartes de fidélité digitales.', proposition_valeur: 'Fidélisez sans carton.', fonctionnalites: ['tampons'], stack: 'node', modele_eco: 'abonnement', cible: { description: 'commerces de proximité', secteurs: ['boulangerie'], zone: 'Bretagne', taille: 'TPE', decideur: 'gérant', requetes: ['boulangerie rennes'] }, arguments: ['simple'], ton: 'direct' }; const lines = prompt.includes('fiche commerciale') ? ['```json\n' + JSON.stringify(profile) + '\n```'] + : prompt.includes('mail de RELANCE') ? ['{"body":"Petite relance : toujours partant, {{entreprise}} ?"}'] : prompt.includes('email de prospection') ? ['{"subject":"Idée pour {{entreprise}}","body":"{{accroche}}\\n\\nBonjour {{entreprise}} à {{ville}}.\\n\\n{{expediteur}}"}'] : prompt.includes('évolutions') ? ['### 1. Export CSV\n- **Pourquoi** : pratique'] : prompt.includes('prospects') diff --git a/test/followup.test.js b/test/followup.test.js new file mode 100644 index 0000000..00a0402 --- /dev/null +++ b/test/followup.test.js @@ -0,0 +1,169 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { mkdtempSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join, resolve } from 'node:path'; +import { randomBytes } from 'node:crypto'; +import { openDb, now, setSetting } from '../src/db.js'; +import { isBusinessHours, followupPlan, followupSubject } from '../src/services/followup.js'; +import { Worker, latestJobs } from '../src/services/jobs.js'; +import { Scheduler } from '../src/services/scheduler.js'; +import { makeHandlers } from '../src/handlers.js'; +import { createProject, saveSecretConfig, getProject } from '../src/projects.js'; + +const paris = (iso) => new Date(iso); // ISO avec décalage explicite + +test('heures ouvrées à Paris, y compris autour du passage à l\'heure d\'hiver', () => { + assert.equal(isBusinessHours(paris('2026-10-21T10:00:00+02:00')), true, 'mercredi 10h'); + assert.equal(isBusinessHours(paris('2026-10-21T08:59:00+02:00')), false, 'mercredi 8h59'); + assert.equal(isBusinessHours(paris('2026-10-21T18:00:00+02:00')), false, 'mercredi 18h'); + assert.equal(isBusinessHours(paris('2026-10-24T11:00:00+02:00')), false, 'samedi'); + assert.equal(isBusinessHours(paris('2026-10-25T11:00:00+01:00')), false, 'dimanche'); + // Lundi 26/10 : Paris est passé en UTC+1 la veille + assert.equal(isBusinessHours(new Date('2026-10-26T08:30:00Z')), true, '8h30 UTC = 9h30 Paris'); + assert.equal(isBusinessHours(new Date('2026-10-26T07:30:00Z')), false, '7h30 UTC = 8h30 Paris'); +}); + +test('objet de la relance : même fil par défaut', () => { + assert.equal(followupSubject({ subject: '' }, { subject: 'Une idée pour Fournil' }), 'Re: Une idée pour Fournil'); + assert.equal(followupSubject({ subject: '' }, { subject: 'RE: déjà' }), 'RE: déjà'); + assert.equal(followupSubject({ subject: 'Petite question' }, { subject: 'x' }), 'Petite question'); + assert.equal(followupSubject({ subject: '' }, null), 'Re: notre échange'); +}); + +const WED_10H = Math.floor(new Date('2026-10-21T10:00:00+02:00').getTime() / 1000); + +function setup() { + const tmp = mkdtempSync(join(tmpdir(), 'aitools-fu-')); + const db = openDb(':memory:'); + const sentMails = []; + const app = { + db, cfg: { dataDir: tmp, claudeBin: resolve('test/fixtures/fake-claude.js'), secretKey: randomBytes(32), appUrl: 'https://ai.test' }, + createTransport: () => ({ verify: async () => true, sendMail: async (m) => { sentMails.push(m); }, close() {} }), + isBusinessHours: () => true, // horloge figée : le test ne dépend pas de l'heure à laquelle on le lance + }; + setSetting(db, 'send_delay_min', '0'); + setSetting(db, 'send_delay_max', '0'); + const id = createProject(app, { name: 'P', gitUrl: 'https://git.x/T/P.git' }); + saveSecretConfig(app, id, 'smtp_enc', { host: 'smtp.x', user: 'u', pass: 'p', fromEmail: 'tony@codebzh.fr' }, 'pass'); + saveSecretConfig(app, id, 'imap_enc', { host: 'imap.x', port: 993 }, 'pass'); + const inboxOk = (at = now(), extra = {}) => db.prepare('UPDATE projects SET inbox_json = ? WHERE id = ?') + .run(JSON.stringify({ lastOk: at, lastCheck: at, lastError: null, ...extra }), id); + inboxOk(); + db.prepare("INSERT INTO templates(project_id, kind, subject, body, status, updated_at) VALUES(?, 'followup', '', 'Toujours partant, {{entreprise}} ?', 'validated', ?)").run(id, now()); + db.prepare('UPDATE projects SET followup_enabled = 1, followup_days = 7 WHERE id = ?').run(id); + const add = (email, daysAgo, status = 'sent') => { + const t = now() - daysAgo * 86400; + const pid = Number(db.prepare('INSERT INTO prospects(project_id, company, email, status, sent_at, created_at) VALUES(?, ?, ?, ?, ?, ?)') + .run(id, email.split('@')[1], email, status, t, t).lastInsertRowid); + db.prepare("INSERT INTO mail_log(project_id, prospect_id, email, sent_at, kind, subject, message_id) VALUES(?, ?, ?, ?, 'initial', ?, ?)") + .run(id, pid, email, t, `Une idée pour ${email}`, ``); + return pid; + }; + const worker = new Worker(db, makeHandlers(app), { thermalMax: 999, log: { error() {} } }); + const scheduler = new Scheduler(app, { log: { error() {} } }); + return { tmp, db, app, id, add, inboxOk, worker, scheduler, sentMails }; +} + +test('relance : seulement les prospects dus, sans réponse, dans le même fil, une seule fois', async () => { + const s = setup(); + try { + const due = s.add('contact@fournil.fr', 8); + const tooEarly = s.add('hello@zen.fr', 3); + const replied = s.add('jean@atelier.fr', 10, 'replied'); + const blacklisted = s.add('stop@ferme.fr', 9); + s.db.prepare("INSERT INTO blacklist(email, reason, created_at) VALUES('stop@ferme.fr', 'unsubscribe', ?)").run(now()); + + const plan = followupPlan(s.db, getProject(s.app, s.id), { date: new Date(WED_10H * 1000) }); + assert.deepEqual({ due: plan.due, blockers: plan.blockers }, { due: 1, blockers: [] }); + + const queued = s.scheduler.queueFollowups({ date: new Date(WED_10H * 1000) }); + assert.equal(queued.length, 1); + await s.worker.tick(); + const job = latestJobs(s.db, s.id).followup; + assert.equal(job.status, 'done', job.error); + assert.deepEqual(job.result, { sent: 1, failed: 0, total: 1 }); + + const m = s.sentMails[0]; + assert.equal(m.to, 'contact@fournil.fr'); + assert.equal(m.subject, 'Re: Une idée pour contact@fournil.fr'); + assert.equal(m.inReplyTo, ``); + assert.match(m.text, /Toujours partant, fournil\.fr \?/); + assert.match(m.text, /Pour ne plus être contacté/); + const log = s.db.prepare("SELECT * FROM mail_log WHERE kind = 'followup'").all(); + assert.equal(log.length, 1); + assert.equal(log[0].message_id, m.messageId); + + const st = (pid) => s.db.prepare('SELECT status, followup_at FROM prospects WHERE id = ?').get(pid); + assert.ok(st(due).followup_at > 0); + assert.equal(st(due).status, 'sent', 'reste "contacté" : une réponse à la relance sera détectée normalement'); + for (const pid of [tooEarly, replied, blacklisted]) assert.equal(st(pid).followup_at, null); + + assert.equal(s.scheduler.queueFollowups({ date: new Date(WED_10H * 1000) }).length, 0, 'jamais 2 relances'); + } finally { rmSync(s.tmp, { recursive: true, force: true }); } +}); + +test('relance bloquée : boîte en erreur, boîte pas lue récemment, week-end, désactivée, modèle non validé', () => { + const s = setup(); + try { + s.add('contact@fournil.fr', 8); + const plan = (o = {}) => followupPlan(s.db, getProject(s.app, s.id), o); + const sat = new Date('2026-10-24T11:00:00+02:00'); + assert.equal(plan({ date: sat }).ready, false); + assert.equal(plan({ date: sat }).inHours, false); + assert.equal(s.scheduler.queueFollowups({ date: sat }).length, 0, 'pas le week-end'); + + s.inboxOk(now(), { lastError: 'AUTHENTICATIONFAILED' }); + assert.deepEqual(plan().blockers, ['boîte non vérifiée récemment']); + s.inboxOk(now() - 3 * 3600); + assert.deepEqual(plan().blockers, ['boîte non vérifiée récemment']); + s.db.prepare('UPDATE projects SET imap_enc = NULL WHERE id = ?').run(s.id); + assert.deepEqual(plan().blockers, ['boîte IMAP à connecter']); + s.db.prepare("UPDATE templates SET status = 'draft' WHERE kind = 'followup'").run(); + s.db.prepare('UPDATE projects SET followup_enabled = 0 WHERE id = ?').run(s.id); + assert.deepEqual(plan().blockers, ['relance désactivée', 'modèle de relance à valider', 'boîte IMAP à connecter']); + } finally { rmSync(s.tmp, { recursive: true, force: true }); } +}); + +test('réponse arrivée entre la mise en file et l\'envoi : pas de relance', async () => { + const s = setup(); + try { + const pid = s.add('contact@fournil.fr', 8); + assert.equal(s.scheduler.queueFollowups({ date: new Date(WED_10H * 1000) }).length, 1); + s.db.prepare("UPDATE prospects SET status = 'replied' WHERE id = ?").run(pid); + await s.worker.tick(); + assert.equal(s.sentMails.length, 0); + } finally { rmSync(s.tmp, { recursive: true, force: true }); } +}); + +test('relance en file mais heures ouvrées dépassées : reportée, rien n\'est envoyé', async () => { + const s = setup(); + try { + const pid = s.add('contact@fournil.fr', 8); + s.scheduler.queueFollowups({ date: new Date(WED_10H * 1000) }); + s.app.isBusinessHours = () => false; + await s.worker.tick(); + assert.equal(s.sentMails.length, 0); + assert.equal(latestJobs(s.db, s.id).followup.result.postponed, true); + assert.equal(s.db.prepare('SELECT followup_at FROM prospects WHERE id = ?').get(pid).followup_at, null, 'toujours due'); + s.app.isBusinessHours = () => true; + assert.equal(s.scheduler.queueFollowups({ date: new Date(WED_10H * 1000) }).length, 1, 'reprogrammée au créneau suivant'); + } finally { rmSync(s.tmp, { recursive: true, force: true }); } +}); + +test('génération du modèle de relance par l\'IA', async () => { + const s = setup(); + try { + s.db.prepare('UPDATE projects SET profile_json = ? WHERE id = ?').run(JSON.stringify({ resume: 'x', proposition_valeur: 'y' }), s.id); + s.db.prepare("DELETE FROM templates WHERE kind = 'followup'").run(); + const { enqueue } = await import('../src/services/jobs.js'); + enqueue(s.db, { projectId: s.id, type: 'followup_template' }); + await s.worker.tick(); + const job = latestJobs(s.db, s.id).followup_template; + assert.equal(job.status, 'done', job.error); + const t = s.db.prepare("SELECT * FROM templates WHERE kind = 'followup'").get(); + assert.equal(t.status, 'draft'); + assert.equal(t.subject, ''); + assert.match(t.body, /relance/i); + } finally { rmSync(s.tmp, { recursive: true, force: true }); } +});