feat: track sent mails and a/b test subject lines
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01SfihHazrSHXgndJtSNLubJ
This commit is contained in:
parent
18dc52f676
commit
ea0481da20
8 changed files with 87 additions and 18 deletions
|
|
@ -100,6 +100,7 @@
|
||||||
if (s.template && st.tplStamp !== s.template.updated_at) {
|
if (s.template && st.tplStamp !== s.template.updated_at) {
|
||||||
st.tplStamp = s.template.updated_at;
|
st.tplStamp = s.template.updated_at;
|
||||||
tplForm.subject.value = s.template.subject;
|
tplForm.subject.value = s.template.subject;
|
||||||
|
tplForm.subjectB.value = s.template.subjectB || '';
|
||||||
tplForm.body.value = s.template.body;
|
tplForm.body.value = s.template.body;
|
||||||
}
|
}
|
||||||
$('[data-tpl-state]', el).innerHTML = s.template
|
$('[data-tpl-state]', el).innerHTML = s.template
|
||||||
|
|
|
||||||
10
src/db.js
10
src/db.js
|
|
@ -78,6 +78,16 @@ export const MIGRATIONS = [
|
||||||
SELECT project_id, 'initial', subject, body, status, updated_at FROM mail_templates;
|
SELECT project_id, 'initial', subject, body, status, updated_at FROM mail_templates;
|
||||||
DROP TABLE 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) {
|
export function openDb(dataDir) {
|
||||||
|
|
|
||||||
|
|
@ -4,9 +4,9 @@ import { runClaude, extractJson } from './services/claude.js';
|
||||||
import { addUsage } from './services/jobs.js';
|
import { addUsage } from './services/jobs.js';
|
||||||
import { syncRepo } from './services/git.js';
|
import { syncRepo } from './services/git.js';
|
||||||
import { analyzePrompt, prospectPrompt, templatePrompt, evolutionPrompt, LEVELS } from './services/prompts.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 { 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 sleep = (ms, signal) => new Promise((resolve, reject) => {
|
||||||
const t = setTimeout(resolve, ms);
|
const t = setTimeout(resolve, ms);
|
||||||
|
|
@ -128,8 +128,9 @@ export function makeHandlers(app) {
|
||||||
await transport.verify();
|
await transport.verify();
|
||||||
const minDelay = Number(getSetting(db, 'send_delay_min', '20')) * 1000;
|
const minDelay = Number(getSetting(db, 'send_delay_min', '20')) * 1000;
|
||||||
const maxDelay = Number(getSetting(db, 'send_delay_max', '60')) * 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 log = db.prepare(`INSERT INTO mail_log(project_id, prospect_id, email, sent_at, error, kind, variant, subject, message_id)
|
||||||
const mark = db.prepare("UPDATE prospects SET status = ?, sent_at = ? WHERE id = ?");
|
VALUES(?, ?, ?, ?, ?, 'initial', ?, ?, ?)`);
|
||||||
|
const mark = db.prepare('UPDATE prospects SET status = ?, sent_at = ?, variant = ? WHERE id = ?');
|
||||||
let sent = 0, failed = 0;
|
let sent = 0, failed = 0;
|
||||||
|
|
||||||
for (const p of candidates.slice(0, n)) {
|
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)
|
// 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;
|
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 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 {
|
try {
|
||||||
await transport.sendMail(buildProspectMail({ template, prospect: p, smtp: project.smtp, unsubUrl }));
|
await transport.sendMail(mail);
|
||||||
log.run(project.id, p.id, p.email, now(), null);
|
log.run(project.id, p.id, p.email, now(), null, variant, mail.subject, mail.messageId);
|
||||||
mark.run('sent', now(), p.id);
|
mark.run('sent', now(), variant, p.id);
|
||||||
sent++;
|
sent++;
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
log.run(project.id, p.id, p.email, now(), String(e.message).slice(0, 500));
|
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(), p.id);
|
if (/^5\d\d/.test(String(e.responseCode))) mark.run('bounced', now(), variant, p.id);
|
||||||
failed++;
|
failed++;
|
||||||
}
|
}
|
||||||
ctx.progress({ sent, failed, total: n, message: `${sent + failed}/${n} envoyés` });
|
ctx.progress({ sent, failed, total: n, message: `${sent + failed}/${n} envoyés` });
|
||||||
|
|
|
||||||
|
|
@ -80,10 +80,20 @@ export function getTemplate(db, projectId, kind, { validatedOnly = false } = {})
|
||||||
return row;
|
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');
|
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(?, ?, ?, ?, ?, ?)
|
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,
|
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`)
|
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';
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -123,7 +123,7 @@ export function registerRoutes(router, app) {
|
||||||
const p = getProject(app, pid(params));
|
const p = getProject(app, pid(params));
|
||||||
const jobs = latestJobs(db, p.id);
|
const jobs = latestJobs(db, p.id);
|
||||||
const row = getTemplate(db, p.id, 'initial');
|
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 stats = prospectStats(db, p.id);
|
||||||
const day = now() - 86400;
|
const day = now() - 86400;
|
||||||
const sendMax = allowedToSend({
|
const sendMax = allowedToSend({
|
||||||
|
|
@ -183,9 +183,10 @@ export function registerRoutes(router, app) {
|
||||||
const b = await readBody(req);
|
const b = await readBody(req);
|
||||||
const subject = String(b.subject || '').trim().slice(0, 200);
|
const subject = String(b.subject || '').trim().slice(0, 200);
|
||||||
const body = String(b.body || '').trim().slice(0, 5000);
|
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');
|
if (!subject || !body) throw new HttpError(400, 'Objet et corps requis');
|
||||||
const status = b.mode === 'validate' ? 'validated' : 'draft';
|
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 });
|
json(res, { ok: true, status });
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,5 @@
|
||||||
import nodemailer from 'nodemailer';
|
import nodemailer from 'nodemailer';
|
||||||
|
import { randomBytes } from 'node:crypto';
|
||||||
|
|
||||||
export const EMAIL_RE = /^[^\s@<>()"',;:]+@[a-z0-9-]+(\.[a-z0-9-]+)*\.[a-z]{2,}$/i;
|
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] ?? '');
|
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 = {
|
const vars = {
|
||||||
entreprise: prospect.company,
|
entreprise: prospect.company,
|
||||||
ville: prospect.city || '',
|
ville: prospect.city || '',
|
||||||
|
|
@ -37,8 +44,10 @@ export function buildProspectMail({ template, prospect, smtp, unsubUrl }) {
|
||||||
return {
|
return {
|
||||||
from: smtp.fromName ? `"${smtp.fromName.replace(/"/g, '')}" <${smtp.fromEmail}>` : smtp.fromEmail,
|
from: smtp.fromName ? `"${smtp.fromName.replace(/"/g, '')}" <${smtp.fromEmail}>` : smtp.fromEmail,
|
||||||
to: prospect.email,
|
to: prospect.email,
|
||||||
subject: fillTemplate(template.subject, vars).trim(),
|
subject: fillTemplate(subject, vars).trim(),
|
||||||
text: body + '\n' + footer,
|
text: body + '\n' + footer,
|
||||||
|
...(messageId ? { messageId } : {}),
|
||||||
|
...(inReplyTo ? { inReplyTo, references: [inReplyTo] } : {}),
|
||||||
headers: {
|
headers: {
|
||||||
'List-Unsubscribe': `<${unsubUrl}>`,
|
'List-Unsubscribe': `<${unsubUrl}>`,
|
||||||
'List-Unsubscribe-Post': 'List-Unsubscribe=One-Click',
|
'List-Unsubscribe-Post': 'List-Unsubscribe=One-Click',
|
||||||
|
|
|
||||||
|
|
@ -131,6 +131,7 @@ function projectItem(p, smtp, dbCfg) {
|
||||||
<button type="button" class="btn small" data-run="template" data-id="${p.id}">Générer avec l'IA</button></div>
|
<button type="button" class="btn small" data-run="template" data-id="${p.id}">Générer avec l'IA</button></div>
|
||||||
<p class="muted small">Variables : {{entreprise}} {{ville}} {{accroche}} {{expediteur}}. Le lien de désinscription est ajouté automatiquement.</p>
|
<p class="muted small">Variables : {{entreprise}} {{ville}} {{accroche}} {{expediteur}}. Le lien de désinscription est ajouté automatiquement.</p>
|
||||||
<label>Objet<input name="subject"></label>
|
<label>Objet<input name="subject"></label>
|
||||||
|
<label>Objet B <span class="muted small">(optionnel : test A/B, les envois alternent entre les deux objets)</span><input name="subjectB"></label>
|
||||||
<label>Corps<textarea name="body" rows="9"></textarea></label>
|
<label>Corps<textarea name="body" rows="9"></textarea></label>
|
||||||
<div class="row">
|
<div class="row">
|
||||||
<button class="btn" name="mode" value="save">Enregistrer</button>
|
<button class="btn" name="mode" value="save">Enregistrer</button>
|
||||||
|
|
|
||||||
|
|
@ -8,7 +8,7 @@ import { randomBytes } from 'node:crypto';
|
||||||
import { openDb, setSetting, now } from '../src/db.js';
|
import { openDb, setSetting, now } from '../src/db.js';
|
||||||
import { Worker, enqueue, latestJobs } from '../src/services/jobs.js';
|
import { Worker, enqueue, latestJobs } from '../src/services/jobs.js';
|
||||||
import { makeHandlers, parseProspectLine } from '../src/handlers.js';
|
import { makeHandlers, parseProspectLine } from '../src/handlers.js';
|
||||||
import { createProject, saveSecretConfig, getProject, prospectStats } from '../src/projects.js';
|
import { createProject, saveSecretConfig, getProject, prospectStats, pickVariant } from '../src/projects.js';
|
||||||
import { allowedToSend, buildProspectMail, fillTemplate } from '../src/services/mailer.js';
|
import { allowedToSend, buildProspectMail, fillTemplate } from '../src/services/mailer.js';
|
||||||
import { validateSelect, firstValue } from '../src/services/recap.js';
|
import { validateSelect, firstValue } from '../src/services/recap.js';
|
||||||
import { validateGitUrl } from '../src/services/git.js';
|
import { validateGitUrl } from '../src/services/git.js';
|
||||||
|
|
@ -146,3 +146,33 @@ test('URL Git Forgejo', () => {
|
||||||
assert.throws(() => validateGitUrl('https://github.com/Tony/A.git', 'git.tony-averty.dev'), /doit être/);
|
assert.throws(() => validateGitUrl('https://github.com/Tony/A.git', 'git.tony-averty.dev'), /doit être/);
|
||||||
assert.throws(() => validateGitUrl('https://git.tony-averty.dev/a/b/c/d'), /Format/);
|
assert.throws(() => validateGitUrl('https://git.tony-averty.dev/a/b/c/d'), /Format/);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('envoi : Message-ID journalisé et objets A/B alternés équitablement', async () => {
|
||||||
|
const s = setup();
|
||||||
|
try {
|
||||||
|
saveSecretConfig(s.app, s.id, 'smtp_enc', { host: 'smtp.x', port: 587, user: 'u', pass: 'p', fromEmail: 'tony@codebzh.fr' }, 'pass');
|
||||||
|
s.db.prepare(`INSERT INTO templates(project_id, kind, subject, subject_b, body, status, updated_at)
|
||||||
|
VALUES(?, 'initial', 'Objet A {{entreprise}}', 'Objet B {{entreprise}}', 'Bonjour', 'validated', ?)`).run(s.id, now());
|
||||||
|
for (const n of [1, 2, 3, 4]) {
|
||||||
|
s.db.prepare("INSERT INTO prospects(project_id, company, email, score, created_at) VALUES(?, ?, ?, ?, ?)").run(s.id, `Ent${n}`, `c${n}@ent${n}.fr`, 10 - n, now());
|
||||||
|
}
|
||||||
|
const job = await run(s, 'send', { count: 4 });
|
||||||
|
assert.equal(job.status, 'done', job.error);
|
||||||
|
assert.deepEqual(s.sentMails.map((m) => m.subject), ['Objet A Ent1', 'Objet B Ent2', 'Objet A Ent3', 'Objet B Ent4']);
|
||||||
|
const logs = s.db.prepare("SELECT * FROM mail_log WHERE kind = 'initial' ORDER BY id").all();
|
||||||
|
assert.equal(logs.length, 4);
|
||||||
|
for (const [i, l] of logs.entries()) {
|
||||||
|
assert.equal(l.message_id, s.sentMails[i].messageId);
|
||||||
|
assert.match(l.message_id, /^<[^@\s]+@codebzh\.fr>$/);
|
||||||
|
assert.equal(l.subject, s.sentMails[i].subject);
|
||||||
|
}
|
||||||
|
assert.equal(new Set(logs.map((l) => l.message_id)).size, 4, 'Message-ID uniques');
|
||||||
|
assert.deepEqual(s.db.prepare('SELECT variant FROM prospects ORDER BY id').all().map((r) => r.variant), ['A', 'B', 'A', 'B']);
|
||||||
|
} finally { rmSync(s.tmp, { recursive: true, force: true }); }
|
||||||
|
});
|
||||||
|
|
||||||
|
test('sans objet B : tout part en A', () => {
|
||||||
|
const db = openDb(':memory:');
|
||||||
|
assert.equal(pickVariant(db, 1, { subject_b: null }), 'A');
|
||||||
|
assert.equal(pickVariant(db, 1, { subject_b: '' }), 'A');
|
||||||
|
});
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue