diff --git a/public/app.js b/public/app.js index e8ead6f..936872f 100644 --- a/public/app.js +++ b/public/app.js @@ -100,6 +100,7 @@ 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; } $('[data-tpl-state]', el).innerHTML = s.template diff --git a/src/db.js b/src/db.js index 0fd01fc..b13d713 100644 --- a/src/db.js +++ b/src/db.js @@ -78,6 +78,16 @@ export const MIGRATIONS = [ SELECT project_id, 'initial', subject, body, status, updated_at FROM mail_templates; DROP TABLE mail_templates; `, + // 3 — suivi des mails envoyés + test A/B de l'objet + ` + ALTER TABLE templates ADD COLUMN subject_b TEXT; -- objet B (premier mail uniquement) + ALTER TABLE prospects ADD COLUMN variant TEXT; -- A | B + ALTER TABLE mail_log ADD COLUMN kind TEXT NOT NULL DEFAULT 'initial'; + ALTER TABLE mail_log ADD COLUMN variant TEXT; + ALTER TABLE mail_log ADD COLUMN subject TEXT; + ALTER TABLE mail_log ADD COLUMN message_id TEXT; + CREATE INDEX mail_log_msgid ON mail_log(message_id); + `, ]; export function openDb(dataDir) { diff --git a/src/handlers.js b/src/handlers.js index 44fbab8..7bf0197 100644 --- a/src/handlers.js +++ b/src/handlers.js @@ -4,9 +4,9 @@ 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 { EMAIL_RE, createTransport, buildProspectMail, allowedToSend } from './services/mailer.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 } from './projects.js'; +import { getProject, repoDir, forgejoToken, globalSmtp, sentSince, getTemplate, saveTemplate, pickVariant } from './projects.js'; const sleep = (ms, signal) => new Promise((resolve, reject) => { const t = setTimeout(resolve, ms); @@ -128,8 +128,9 @@ export function makeHandlers(app) { 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) VALUES(?, ?, ?, ?, ?)'); - const mark = db.prepare("UPDATE prospects SET status = ?, sent_at = ? WHERE id = ?"); + 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)) { @@ -137,14 +138,20 @@ export function makeHandlers(app) { // 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(buildProspectMail({ template, prospect: p, smtp: project.smtp, unsubUrl })); - log.run(project.id, p.id, p.email, now(), null); - mark.run('sent', now(), p.id); + 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)); - if (/^5\d\d/.test(String(e.responseCode))) mark.run('bounced', now(), p.id); + 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` }); diff --git a/src/projects.js b/src/projects.js index 1476215..2458991 100644 --- a/src/projects.js +++ b/src/projects.js @@ -80,10 +80,20 @@ export function getTemplate(db, projectId, kind, { validatedOnly = false } = {}) return row; } -export function saveTemplate(db, projectId, kind, { subject = '', body, status = 'draft' }) { +export function saveTemplate(db, projectId, kind, { subject = '', subjectB = null, body, status = 'draft' }) { if (!TEMPLATE_KINDS.includes(kind)) throw new HttpError(400, 'Type de modèle inconnu'); - db.prepare(`INSERT INTO templates(project_id, kind, subject, body, status, updated_at) VALUES(?, ?, ?, ?, ?, ?) - ON CONFLICT(project_id, kind) DO UPDATE SET subject = excluded.subject, + db.prepare(`INSERT INTO templates(project_id, kind, subject, subject_b, body, status, updated_at) VALUES(?, ?, ?, ?, ?, ?, ?) + ON CONFLICT(project_id, kind) DO UPDATE SET subject = excluded.subject, subject_b = excluded.subject_b, body = excluded.body, status = excluded.status, updated_at = excluded.updated_at`) - .run(projectId, kind, subject, body, status, now()); + .run(projectId, kind, subject, kind === 'initial' ? (subjectB || null) : null, body, status, now()); +} + +// Objet A ou B : on équilibre les envois (B seulement si un objet B est défini) +export function pickVariant(db, projectId, template) { + if (!template.subject_b) return 'A'; + const rows = db.prepare(`SELECT variant, COUNT(*) n FROM mail_log + WHERE project_id = ? AND kind = 'initial' AND error IS NULL AND variant IN ('A', 'B') GROUP BY variant`).all(projectId); + const count = { A: 0, B: 0 }; + for (const r of rows) count[r.variant] = r.n; + return count.B < count.A ? 'B' : 'A'; } diff --git a/src/routes.js b/src/routes.js index c7cc1c4..f312ec6 100644 --- a/src/routes.js +++ b/src/routes.js @@ -123,7 +123,7 @@ export function registerRoutes(router, app) { 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, body: row.body, status: row.status, updated_at: row.updated_at } : null; + const tpl = row ? { subject: row.subject, subjectB: row.subject_b, body: row.body, status: row.status, updated_at: row.updated_at } : null; const stats = prospectStats(db, p.id); const day = now() - 86400; const sendMax = allowedToSend({ @@ -183,9 +183,10 @@ export function registerRoutes(router, app) { const b = await readBody(req); 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 status = b.mode === 'validate' ? 'validated' : 'draft'; - saveTemplate(db, p.id, 'initial', { subject, body, status }); + saveTemplate(db, p.id, 'initial', { subject, subjectB, body, status }); json(res, { ok: true, status }); }); diff --git a/src/services/mailer.js b/src/services/mailer.js index 6713e4e..6266784 100644 --- a/src/services/mailer.js +++ b/src/services/mailer.js @@ -1,4 +1,5 @@ import nodemailer from 'nodemailer'; +import { randomBytes } from 'node:crypto'; export const EMAIL_RE = /^[^\s@<>()"',;:]+@[a-z0-9-]+(\.[a-z0-9-]+)*\.[a-z]{2,}$/i; @@ -20,7 +21,13 @@ export function fillTemplate(text, vars) { return String(text).replace(/\{\{\s*(\w+)\s*\}\}/g, (_, k) => vars[k] ?? ''); } -export function buildProspectMail({ template, prospect, smtp, unsubUrl }) { +// Message-ID maîtrisé : c'est lui qui permet de rattacher une réponse au bon prospect +export function makeMessageId(fromEmail) { + const domain = String(fromEmail || '').split('@')[1] || 'aitools.local'; + return `<${Date.now().toString(36)}.${randomBytes(9).toString('base64url')}@${domain}>`; +} + +export function buildProspectMail({ template, prospect, smtp, unsubUrl, subject = template.subject, messageId, inReplyTo }) { const vars = { entreprise: prospect.company, ville: prospect.city || '', @@ -37,8 +44,10 @@ export function buildProspectMail({ template, prospect, smtp, unsubUrl }) { return { from: smtp.fromName ? `"${smtp.fromName.replace(/"/g, '')}" <${smtp.fromEmail}>` : smtp.fromEmail, to: prospect.email, - subject: fillTemplate(template.subject, vars).trim(), + subject: fillTemplate(subject, vars).trim(), text: body + '\n' + footer, + ...(messageId ? { messageId } : {}), + ...(inReplyTo ? { inReplyTo, references: [inReplyTo] } : {}), headers: { 'List-Unsubscribe': `<${unsubUrl}>`, 'List-Unsubscribe-Post': 'List-Unsubscribe=One-Click', diff --git a/src/views.js b/src/views.js index e2cb29c..ec4f9fa 100644 --- a/src/views.js +++ b/src/views.js @@ -131,6 +131,7 @@ function projectItem(p, smtp, dbCfg) {
Variables : {{entreprise}} {{ville}} {{accroche}} {{expediteur}}. Le lien de désinscription est ajouté automatiquement.
+