feat: add project model and background job handlers

This commit is contained in:
Tony Averty 2026-10-21 13:49:22 +02:00
parent 3ace08f297
commit 6fb1332778
No known key found for this signature in database
5 changed files with 509 additions and 1 deletions

190
src/handlers.js Normal file
View file

@ -0,0 +1,190 @@
// Handlers des jobs en arrière-plan.
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 { EMAIL_RE, createTransport, buildProspectMail, allowedToSend } from './services/mailer.js';
import { unsubToken } from './crypto.js';
import { getProject, repoDir, forgejoToken, globalSmtp, sentSince } from './projects.js';
const sleep = (ms, signal) => new Promise((resolve, reject) => {
const t = setTimeout(resolve, ms);
signal?.addEventListener('abort', () => { clearTimeout(t); reject(new Error('Annulé')); }, { once: true });
});
export function parseProspectLine(line) {
const m = /^\s*PROSPECT\s+(\{.*\})\s*$/.exec(line);
if (!m) return null;
let p;
try { p = JSON.parse(m[1]); } catch { return null; }
const email = String(p.email || '').trim().toLowerCase();
if (!EMAIL_RE.test(email) || !p.company) return null;
const str = (v, max = 300) => (v == null ? null : String(v).slice(0, max));
const score = Math.max(1, Math.min(10, Math.round(Number(p.score) || 5)));
return {
company: str(p.company, 200), email, website: str(p.website), city: str(p.city, 100),
sector: str(p.sector, 100), hook: str(p.hook, 400), source: str(p.source), score,
};
}
export function makeHandlers(app) {
const { db, cfg } = app;
const claude = (o) => runClaude({ bin: cfg.claudeBin, ...o });
return {
async analyze(ctx) {
const project = getProject(app, ctx.job.project_id);
ctx.progress({ message: 'Récupération du repo…' });
const dir = repoDir(cfg, project.id);
const commit = await syncRepo(project.gitUrl, dir, forgejoToken(app));
ctx.progress({ message: 'Analyse du code par Claude…' });
const { prompt, system } = analyzePrompt(project.name);
const r = await claude({ prompt, system, cwd: dir, model: 'sonnet', maxTurns: 20, tools: ['Read', 'Glob', 'Grep'], signal: ctx.signal });
addUsage(ctx, r);
if (!r.ok) throw new Error(`Analyse incomplète (${r.subtype})`);
const profile = extractJson(r.text);
if (!profile.resume || !profile.cible) throw new Error('Fiche projet incomplète');
const { cible, ...rest } = profile;
db.prepare('UPDATE projects SET profile_json = ?, profile_commit = ?, profile_at = ?, target_json = ?, target_validated = 0 WHERE id = ?')
.run(JSON.stringify(rest), commit, now(), JSON.stringify(cible), project.id);
return { commit };
},
async prospect(ctx) {
const project = getProject(app, ctx.job.project_id);
if (!project.profile || !project.targetValidated) throw new Error('Valide la cible du projet avant de prospecter');
const count = Math.max(1, Math.min(50, Math.floor(Number(ctx.params.count) || 10)));
// Domaines déjà connus (tous projets) : Claude ne les recherche pas une 2e fois
const exclude = db.prepare(`
SELECT DISTINCT substr(email, instr(email, '@') + 1) d FROM prospects WHERE project_id = ?
UNION SELECT substr(email, instr(email, '@') + 1) FROM blacklist
LIMIT 300`).all(project.id).map((r) => r.d);
const insert = db.prepare(`INSERT OR IGNORE INTO prospects(project_id, company, email, website, city, sector, hook, source, score, created_at)
SELECT ?, ?, ?, ?, ?, ?, ?, ?, ?, ? WHERE NOT EXISTS (SELECT 1 FROM blacklist WHERE email = ?)`);
let found = 0;
let pending = '';
const onText = (text) => {
pending += text + '\n';
const lines = pending.split('\n');
pending = lines.pop();
for (const line of lines) {
const p = parseProspectLine(line);
if (!p) continue;
const res = insert.run(project.id, p.company, p.email, p.website, p.city, p.sector, p.hook, p.source, p.score, now(), p.email);
if (res.changes) {
found++;
ctx.progress({ found, target: count, message: `${found}/${count} — ${p.company}` });
}
}
};
ctx.progress({ found: 0, target: count, message: 'Recherche en cours…' });
const { prompt, system } = prospectPrompt({ profile: project.profile, target: project.target, count, exclude });
const model = getSetting(db, 'prospect_model', 'haiku');
const r = await claude({
prompt, system, model, tools: ['WebSearch', 'WebFetch'],
maxTurns: Math.min(80, count * 3 + 10), onText, signal: ctx.signal,
});
onText('\n');
addUsage(ctx, r);
return { found, requested: count, stoppedBy: r.subtype };
},
async template(ctx) {
const project = getProject(app, ctx.job.project_id, { secrets: true });
if (!project.profile) throw new Error('Analyse le projet d\'abord');
const { prompt, system } = templatePrompt({ profile: project.profile, target: project.target || {}, 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.subject || !t.body) throw new Error('Modèle de mail invalide');
db.prepare(`INSERT INTO mail_templates(project_id, subject, body, status, updated_at) VALUES(?, ?, ?, 'draft', ?)
ON CONFLICT(project_id) DO UPDATE SET subject = excluded.subject, body = excluded.body, status = 'draft', updated_at = excluded.updated_at`)
.run(project.id, t.subject, t.body, now());
return { ok: true };
},
async send(ctx) {
const project = getProject(app, ctx.job.project_id, { secrets: true });
const template = db.prepare("SELECT * FROM mail_templates WHERE project_id = ? AND status = 'validated'").get(project.id);
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) VALUES(?, ?, ?, ?, ?)');
const mark = db.prepare("UPDATE prospects SET status = ?, sent_at = ? 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)}`;
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);
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);
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 };
},
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)));
const level = LEVELS[ctx.params.level] ? ctx.params.level : 'normal';
const to = getSetting(db, 'notify_email');
const smtp = globalSmtp(app) || project.smtp;
if (!to) throw new Error('Adresse de réception non configurée (Réglages)');
if (!smtp) throw new Error('Aucun SMTP configuré (Réglages ou projet)');
ctx.progress({ message: 'Mise à jour du repo…' });
const dir = repoDir(cfg, project.id);
await syncRepo(project.gitUrl, dir, forgejoToken(app));
ctx.progress({ message: `Recherche de ${count} évolutions (${level})…` });
const { prompt, system } = evolutionPrompt({ projectName: project.name, profile: project.profile, count, level });
const { model, maxTurns } = LEVELS[level];
const r = await claude({ prompt, system, cwd: dir, model, maxTurns, tools: ['Read', 'Glob', 'Grep'], signal: ctx.signal });
addUsage(ctx, r);
if (!r.text?.trim()) throw new Error(`Pas de résultat (${r.subtype})`);
ctx.progress({ message: 'Envoi par mail…' });
const transport = (app.createTransport || createTransport)(smtp);
await transport.sendMail({
from: smtp.fromEmail, to,
subject: `[AiTools] ${count} évolutions pour ${project.name}`,
text: r.text,
});
transport.close();
return { markdown: r.text, sentTo: to };
},
};
}

72
src/projects.js Normal file
View file

@ -0,0 +1,72 @@
import { join } from 'node:path';
import { now, getSetting } from './db.js';
import { encryptJson, decryptJson, decrypt } from './crypto.js';
import { HttpError } from './http.js';
export const repoDir = (cfg, id) => join(cfg.dataDir, 'repos', String(id));
const parse = (s) => (s ? JSON.parse(s) : null);
export function getProject(app, id, { secrets = false } = {}) {
const p = app.db.prepare('SELECT * FROM projects WHERE id = ?').get(Number(id));
if (!p) throw new HttpError(404, 'Projet introuvable');
const out = {
id: p.id, name: p.name, gitUrl: p.git_url,
profile: parse(p.profile_json), profileCommit: p.profile_commit, profileAt: p.profile_at,
target: parse(p.target_json), targetValidated: !!p.target_validated,
dailyMailCap: p.daily_mail_cap, createdAt: p.created_at,
hasSmtp: !!p.smtp_enc, hasDb: !!p.db_enc,
};
if (secrets) {
out.smtp = decryptJson(app.cfg.secretKey, p.smtp_enc);
out.dbCfg = decryptJson(app.cfg.secretKey, p.db_enc);
}
return out;
}
export function listProjects(app) {
return app.db.prepare('SELECT id FROM projects ORDER BY name COLLATE NOCASE').all().map((r) => getProject(app, r.id));
}
export function createProject(app, { name, gitUrl }) {
const r = app.db.prepare('INSERT INTO projects(name, git_url, created_at) VALUES(?, ?, ?)').run(name, gitUrl, now());
return Number(r.lastInsertRowid);
}
// Les secrets vides dans le formulaire = on garde l'ancien (le formulaire ne les réaffiche jamais)
export function saveSecretConfig(app, id, column, incoming, secretField) {
if (!['smtp_enc', 'db_enc'].includes(column)) throw new Error('Colonne invalide');
const current = decryptJson(app.cfg.secretKey, app.db.prepare(`SELECT ${column} c FROM projects WHERE id = ?`).get(id)?.c) || {};
const next = { ...current, ...incoming };
if (!incoming[secretField]) next[secretField] = current[secretField];
app.db.prepare(`UPDATE projects SET ${column} = ? WHERE id = ?`).run(encryptJson(app.cfg.secretKey, next), id);
}
// Version "affichable" d'une config secrète (sans mot de passe)
export function publicConfig(cfg, secretField) {
if (!cfg) return {};
const { [secretField]: _omit, ...rest } = cfg;
return { ...rest, [`${secretField}Set`]: !!_omit };
}
export function forgejoToken(app) {
return decrypt(app.cfg.secretKey, getSetting(app.db, 'forgejo_token_enc'));
}
export function globalSmtp(app) {
return decryptJson(app.cfg.secretKey, getSetting(app.db, 'smtp_enc'));
}
export function prospectStats(db, projectId) {
const rows = db.prepare('SELECT status, COUNT(*) n FROM prospects WHERE project_id = ? GROUP BY status').all(projectId);
const out = { total: 0 };
for (const r of rows) { out[r.status] = r.n; out.total += r.n; }
return out;
}
export function sentSince(db, since, projectId = null) {
const sql = projectId == null
? 'SELECT COUNT(*) n FROM mail_log WHERE sent_at > ? AND error IS NULL'
: 'SELECT COUNT(*) n FROM mail_log WHERE sent_at > ? AND error IS NULL AND project_id = ?';
return (projectId == null ? db.prepare(sql).get(since) : db.prepare(sql).get(since, projectId)).n;
}

94
src/services/prompts.js Normal file
View file

@ -0,0 +1,94 @@
// Prompts courts et cadrés : chaque token compte avec un abonnement Pro.
const SYSTEM_FR = 'Tu travailles pour un outil interne. Réponds en français. Sois bref. Pas de politesse, pas de récapitulatif.';
export function analyzePrompt(projectName) {
return {
system: SYSTEM_FR,
prompt: `Analyse le projet "${projectName}" dans le dossier courant pour en faire une fiche commerciale.
Lis en priorité : README, manifestes (package.json, composer.json…), routes/pages principales, modèles de données.
Lis 15 fichiers au maximum, n'explore pas node_modules/vendor/dist.
Réponds UNIQUEMENT avec ce JSON :
{
"resume": "2 phrases : ce que fait le produit",
"proposition_valeur": "1 phrase orientée client",
"fonctionnalites": ["5 à 8 fonctionnalités clés"],
"stack": "techno principale",
"modele_eco": "abonnement / commission / ... si détectable, sinon null",
"cible": {
"description": "qui achète, en 1 phrase",
"secteurs": ["types d'entreprises à démarcher"],
"zone": "zone géographique pertinente",
"taille": "TPE / PME / indépendants...",
"decideur": "qui contacter",
"requetes": ["4 à 6 requêtes web pour trouver ces entreprises"]
},
"arguments": ["3 à 5 arguments de vente"],
"ton": "ton recommandé pour les mails"
}`,
};
}
export function prospectPrompt({ profile, target, count, exclude }) {
return {
system: `${SYSTEM_FR}
Règles strictes :
- Uniquement des emails PROFESSIONNELS publiés publiquement par l'entreprise (site, page contact, annuaire pro). Jamais inventés ni devinés.
- Pas de particuliers, pas d'emails personnels nominatifs devinés.
- Donne l'URL exacte où l'email apparaît (champ source).
- Une ligne par prospect, dès que tu le trouves, au format exact :
PROSPECT {"company":"","email":"","website":"","city":"","sector":"","hook":"","source":"","score":0}
- hook : 1 phrase d'accroche personnalisée basée sur ce que tu as vu sur leur site.
- score : pertinence de 1 à 10 pour ce produit.
- Arrête-toi dès que tu as ${count} prospects. Termine par DONE.`,
prompt: `Produit : ${profile.resume}
Valeur : ${profile.proposition_valeur}
Cible : ${target.description} — secteurs : ${(target.secteurs || []).join(', ')} — zone : ${target.zone} — taille : ${target.taille}
Pistes de recherche : ${(target.requetes || []).join(' | ')}
Trouve ${count} prospects.${exclude.length ? `\nDéjà connus, à ignorer : ${exclude.join(', ')}` : ''}`,
};
}
export function templatePrompt({ profile, target, senderName }) {
return {
system: SYSTEM_FR,
prompt: `Rédige un email de prospection B2B court (120 mots max) pour :
Produit : ${profile.resume}
Valeur : ${profile.proposition_valeur}
Arguments : ${(profile.arguments || []).join(' ; ')}
Cible : ${target.description} (${target.decideur})
Ton : ${profile.ton || 'direct et chaleureux'}
Expéditeur : ${senderName || '{{expediteur}}'}
Variables disponibles : {{entreprise}}, {{ville}}, {{accroche}} (phrase perso déjà rédigée, à placer en ouverture).
Pas de proposition d'appel téléphonique ni de visio : propose de répondre au mail ou d'essayer le produit.
Ne mets PAS de lien de désinscription (ajouté automatiquement).
Réponds UNIQUEMENT avec : {"subject":"...","body":"..."}`,
};
}
export const LEVELS = {
rapide: { model: 'haiku', maxTurns: 12, files: 8 },
normal: { model: 'sonnet', maxTurns: 20, files: 15 },
approfondi: { model: 'opus', maxTurns: 30, files: 25 },
};
export function evolutionPrompt({ projectName, profile, count, level }) {
const l = LEVELS[level];
return {
system: SYSTEM_FR,
prompt: `Projet "${projectName}" (dossier courant). ${profile ? `Résumé : ${profile.resume}` : ''}
Propose ${count} évolutions qui plairaient aux utilisateurs de ce produit.
Lis ${l.files} fichiers au maximum pour comprendre l'existant. Ne propose rien qui existe déjà.
Format Markdown, pour chaque évolution :
### N. Titre
- **Pourquoi** : bénéfice utilisateur (1-2 phrases)
- **Effort** : S / M / L
- **Pistes techniques** : 1-3 puces liées au code existant
Classe de la plus rentable à la moins rentable. Aucune intro ni conclusion.`,
};
}

View file

@ -4,7 +4,11 @@ const prompt = process.argv[process.argv.indexOf('-p') + 1] || '';
const out = (o) => process.stdout.write(JSON.stringify(o) + '\n'); const out = (o) => process.stdout.write(JSON.stringify(o) + '\n');
out({ type: 'system', subtype: 'init', args: process.argv.slice(2) }); out({ type: 'system', subtype: 'init', args: process.argv.slice(2) });
if (prompt.includes('CRASH')) process.exit(3); if (prompt.includes('CRASH')) process.exit(3);
const lines = prompt.includes('PROSPECTS') 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('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')
? ['Je cherche...', 'PROSPECT {"company":"Boulangerie Le Fournil","email":"contact@fournil.fr","website":"https://fournil.fr","city":"Rennes","sector":"boulangerie","hook":"Votre fidélité client mérite mieux que le carton.","source":"https://fournil.fr/contact","score":8}', ? ['Je cherche...', 'PROSPECT {"company":"Boulangerie Le Fournil","email":"contact@fournil.fr","website":"https://fournil.fr","city":"Rennes","sector":"boulangerie","hook":"Votre fidélité client mérite mieux que le carton.","source":"https://fournil.fr/contact","score":8}',
'PROSPECT {"company":"Bad","email":"pas-un-email","score":5}', 'PROSPECT {"company":"Bad","email":"pas-un-email","score":5}',
'PROSPECT {"company":"Coiffure Zen","email":"Hello@Zen.fr","website":"https://zen.fr","city":"Vern","score":6,"source":"https://zen.fr"}'] 'PROSPECT {"company":"Coiffure Zen","email":"Hello@Zen.fr","website":"https://zen.fr","city":"Vern","score":6,"source":"https://zen.fr"}']

148
test/handlers.test.js Normal file
View file

@ -0,0 +1,148 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { execFileSync } from 'node:child_process';
import { mkdtempSync, writeFileSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join, resolve } from 'node:path';
import { randomBytes } from 'node:crypto';
import { openDb, setSetting, now } from '../src/db.js';
import { Worker, enqueue, latestJobs } from '../src/services/jobs.js';
import { makeHandlers, parseProspectLine } from '../src/handlers.js';
import { createProject, saveSecretConfig, getProject, prospectStats } from '../src/projects.js';
import { allowedToSend, buildProspectMail, fillTemplate } from '../src/services/mailer.js';
import { validateSelect, firstValue } from '../src/services/recap.js';
import { validateGitUrl } from '../src/services/git.js';
import { verifyUnsubToken } from '../src/crypto.js';
function setup() {
const tmp = mkdtempSync(join(tmpdir(), 'aitools-'));
const src = join(tmp, 'src-repo');
execFileSync('git', ['init', '-q', '-b', 'main', src]);
writeFileSync(join(src, 'README.md'), '# MonEspacePro\n');
execFileSync('git', ['-C', src, '-c', 'user.name=t', '-c', 'user.email=t@t', 'commit', '-qam', 'init', '--allow-empty']);
execFileSync('git', ['-C', src, 'add', '.']);
execFileSync('git', ['-C', src, '-c', 'user.name=t', '-c', 'user.email=t@t', 'commit', '-qm', 'readme']);
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() {} }),
};
setSetting(db, 'send_delay_min', '0');
setSetting(db, 'send_delay_max', '0');
const id = createProject(app, { name: 'MonEspacePro', gitUrl: `file://${src}` });
const worker = new Worker(db, makeHandlers(app), { thermalMax: 999, log: { error: (...a) => console.error(...a) } });
return { tmp, db, app, id, worker, sentMails };
}
const run = async (s, type, params) => { enqueue(s.db, { projectId: s.id, type, params }); await s.worker.tick(); return latestJobs(s.db, s.id)[type]; };
test('flux complet : analyse → cible → prospection → modèle → envoi → évolution', async () => {
const s = setup();
try {
const a = await run(s, 'analyze');
assert.equal(a.status, 'done', a.error);
let p = getProject(s.app, s.id);
assert.equal(p.profile.resume, 'Cartes de fidélité digitales.');
assert.equal(p.target.zone, 'Bretagne');
assert.equal(p.targetValidated, false);
assert.match(p.profileCommit, /^[0-9a-f]{40}$/);
const refused = await run(s, 'prospect', { count: 3 });
assert.match(refused.error, /Valide la cible/);
s.db.prepare('UPDATE projects SET target_validated = 1 WHERE id = ?').run(s.id);
s.db.prepare("INSERT INTO blacklist(email, created_at) VALUES('hello@zen.fr', ?)").run(now());
const pr = await run(s, 'prospect', { count: 3 });
assert.equal(pr.status, 'done', pr.error);
assert.equal(pr.result.found, 1, 'email invalide rejeté + blacklisté ignoré');
assert.equal(prospectStats(s.db, s.id).new, 1);
const t = await run(s, 'template');
assert.equal(t.status, 'done', t.error);
const noValid = await run(s, 'send', { count: 5 });
assert.match(noValid.error, /non validé/);
s.db.prepare("UPDATE mail_templates SET status = 'validated' WHERE project_id = ?").run(s.id);
const noSmtp = await run(s, 'send', { count: 5 });
assert.match(noSmtp.error, /SMTP/);
saveSecretConfig(s.app, s.id, 'smtp_enc', { host: 'smtp.x', port: 587, user: 'u', pass: 'secret', fromEmail: 'tony@x.fr', fromName: 'Tony' }, 'pass');
const sent = await run(s, 'send', { count: 5 });
assert.equal(sent.status, 'done', sent.error);
assert.deepEqual(sent.result, { sent: 1, failed: 0, total: 1 });
const mail = s.sentMails[0];
assert.equal(mail.to, 'contact@fournil.fr');
assert.equal(mail.subject, 'Idée pour Boulangerie Le Fournil');
assert.match(mail.text, /Bonjour Boulangerie Le Fournil à Rennes/);
assert.match(mail.text, /fournil\.fr\/contact/);
const unsub = /\/u\/([^/]+)\/(\S+)/.exec(mail.headers['List-Unsubscribe']);
assert.ok(verifyUnsubToken(s.app.cfg.secretKey, decodeURIComponent(unsub[1]), unsub[2].replace('>', '')));
assert.equal(prospectStats(s.db, s.id).sent, 1);
const again = await run(s, 'send', { count: 5 });
assert.match(again.error, /aucun prospect/, 'jamais 2 fois le même prospect');
const ev1 = await run(s, 'evolution', { count: 3, level: 'rapide' });
assert.match(ev1.error, /Adresse de réception/);
setSetting(s.db, 'notify_email', 'moi@x.fr');
const ev = await run(s, 'evolution', { count: 3, level: 'rapide' });
assert.equal(ev.status, 'done', ev.error);
assert.equal(s.sentMails.at(-1).to, 'moi@x.fr');
assert.match(s.sentMails.at(-1).text, /Export CSV/);
const usage = s.db.prepare('SELECT SUM(cost_usd) c FROM jobs').get().c;
assert.ok(usage > 0);
} finally { rmSync(s.tmp, { recursive: true, force: true }); }
});
test('parseProspectLine filtre les lignes invalides', () => {
assert.equal(parseProspectLine('blabla'), null);
assert.equal(parseProspectLine('PROSPECT {cassé'), null);
assert.equal(parseProspectLine('PROSPECT {"company":"A","email":"x"}'), null);
assert.equal(parseProspectLine('PROSPECT {"email":"a@b.fr"}'), null);
const p = parseProspectLine('PROSPECT {"company":"A","email":" A@B.FR ","score":42}');
assert.equal(p.email, 'a@b.fr');
assert.equal(p.score, 10);
});
test('plafonds d\'envoi anti-abus', () => {
const base = { requested: 50, available: 80, projectCap: 30, sentTodayProject: 0, globalCap: 100, sentTodayGlobal: 0 };
assert.equal(allowedToSend(base), 30);
assert.equal(allowedToSend({ ...base, sentTodayProject: 25 }), 5);
assert.equal(allowedToSend({ ...base, projectCap: 9999, requested: 9999, available: 9999 }), 100);
assert.equal(allowedToSend({ ...base, sentTodayGlobal: 100 }), 0);
assert.equal(allowedToSend({ ...base, available: 3 }), 3);
assert.throws(() => allowedToSend({ ...base, requested: 0 }));
assert.throws(() => allowedToSend({ ...base, requested: 'abc' }));
});
test('modèle de mail', () => {
assert.equal(fillTemplate('Salut {{ entreprise }} {{inconnu}}!', { entreprise: 'X' }), 'Salut X !');
const m = buildProspectMail({
template: { subject: 'Pour {{entreprise}}', body: 'Hey' },
prospect: { company: 'Y', email: 'y@y.fr' }, smtp: { fromEmail: 'a@a.fr', fromName: 'To"ny' }, unsubUrl: 'https://u',
});
assert.equal(m.from, '"Tony" <a@a.fr>');
assert.match(m.text, /Pour ne plus être contacté : https:\/\/u/);
});
test('récap : seules les requêtes SELECT passent', () => {
assert.equal(validateSelect('SELECT COUNT(*) FROM users;'), 'SELECT COUNT(*) FROM users');
assert.equal(validateSelect(' '), null);
assert.ok(validateSelect('WITH a AS (SELECT 1) SELECT * FROM a'));
assert.throws(() => validateSelect('DELETE FROM users'));
assert.throws(() => validateSelect('SELECT 1; DROP TABLE users'));
assert.throws(() => validateSelect('SELECT * FROM a INTO OUTFILE "/tmp/x"'));
assert.equal(firstValue([{ n: '12.5' }]), 12.5);
assert.equal(firstValue([]), 0);
});
test('URL Git Forgejo', () => {
assert.equal(validateGitUrl('https://git.tony-averty.dev/Tony/AiTools.git', 'git.tony-averty.dev'), 'https://git.tony-averty.dev/Tony/AiTools.git');
assert.throws(() => validateGitUrl('http://git.tony-averty.dev/Tony/A.git'), /https/);
assert.throws(() => validateGitUrl('https://user:pw@git.tony-averty.dev/Tony/A.git'), /identifiants/);
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/);
});