test: adapte la suite à l'API asynchrone et ajoute les tests du worker
Tous les tests passent par testDb() : SQLite en mémoire par défaut, vrai MySQL/MariaDB si TEST_DB_HOST est défini (npm run test:mysql). Le glob de npm test est rendu portable (guillemets doubles), il ne trouvait aucun fichier sous Windows. Retire le test de l'ancienne migration SQLite 2, remplacée par le script de migration des données.
This commit is contained in:
parent
b2608a8635
commit
de3ee9936b
16 changed files with 491 additions and 437 deletions
|
|
@ -11,8 +11,8 @@
|
||||||
"start": "node --env-file=.env --no-warnings=ExperimentalWarning src/server.js",
|
"start": "node --env-file=.env --no-warnings=ExperimentalWarning src/server.js",
|
||||||
"dev": "node --env-file=.env --watch --no-warnings=ExperimentalWarning src/server.js",
|
"dev": "node --env-file=.env --watch --no-warnings=ExperimentalWarning src/server.js",
|
||||||
"lint": "node scripts/check-syntax.js",
|
"lint": "node scripts/check-syntax.js",
|
||||||
"test": "node --no-warnings=ExperimentalWarning --test 'test/**/*.test.js'",
|
"test": "node --no-warnings=ExperimentalWarning --test \"test/**/*.test.js\"",
|
||||||
"test:mysql": "node --no-warnings=ExperimentalWarning --test --test-concurrency=1 'test/**/*.test.js'",
|
"test:mysql": "node --no-warnings=ExperimentalWarning --test --test-concurrency=1 \"test/**/*.test.js\"",
|
||||||
"migrate:sqlite": "node --env-file=.env --no-warnings=ExperimentalWarning scripts/migrate-sqlite-to-mysql.js",
|
"migrate:sqlite": "node --env-file=.env --no-warnings=ExperimentalWarning scripts/migrate-sqlite-to-mysql.js",
|
||||||
"check": "npm run lint && npm run test",
|
"check": "npm run lint && npm run test",
|
||||||
"hooks": "git config core.hooksPath .githooks"
|
"hooks": "git config core.hooksPath .githooks"
|
||||||
|
|
|
||||||
|
|
@ -1,38 +1,39 @@
|
||||||
import { test } from 'node:test';
|
import { test } from 'node:test';
|
||||||
import assert from 'node:assert/strict';
|
import assert from 'node:assert/strict';
|
||||||
import { openDb, now, setSetting } from '../src/db.js';
|
import { now, setSetting } from '../src/db.js';
|
||||||
|
import { testDb } from './helpers/db.js';
|
||||||
import { budgetState, AI_JOBS, quotaState, isQuotaSensitive, quotaAlerts } from '../src/services/budget.js';
|
import { budgetState, AI_JOBS, quotaState, isQuotaSensitive, quotaAlerts } from '../src/services/budget.js';
|
||||||
import { Worker, enqueue, latestJobs } from '../src/services/jobs.js';
|
import { Worker, enqueue, latestJobs } from '../src/services/jobs.js';
|
||||||
|
|
||||||
function setup() {
|
async function setup() {
|
||||||
const db = openDb(':memory:');
|
const db = await testDb();
|
||||||
db.prepare("INSERT INTO projects(name, git_url, created_at) VALUES('p', 'u', ?)").run(now());
|
await db.prepare("INSERT INTO projects(name, git_url, created_at) VALUES('p', 'u', ?)").run(now());
|
||||||
const spend = (usd, finishedAgo) => db.prepare("INSERT INTO jobs(project_id, type, status, cost_usd, created_at, finished_at) VALUES(1, 'prospect', 'done', ?, ?, ?)")
|
const spend = (usd, finishedAgo) => db.prepare("INSERT INTO jobs(project_id, type, status, cost_usd, created_at, finished_at) VALUES(1, 'prospect', 'done', ?, ?, ?)")
|
||||||
.run(usd, now() - finishedAgo - 60, now() - finishedAgo);
|
.run(usd, now() - finishedAgo - 60, now() - finishedAgo);
|
||||||
return { db, spend };
|
return { db, spend };
|
||||||
}
|
}
|
||||||
|
|
||||||
test('budget : pas de limite par défaut, puis plafonds 24 h et 30 j glissants', () => {
|
test('budget : pas de limite par défaut, puis plafonds 24 h et 30 j glissants', async () => {
|
||||||
const s = setup();
|
const s = await setup();
|
||||||
s.spend(1.5, 3600); // il y a 1 h
|
await s.spend(1.5, 3600); // il y a 1 h
|
||||||
s.spend(10, 5 * 86400); // il y a 5 jours
|
await s.spend(10, 5 * 86400); // il y a 5 jours
|
||||||
s.spend(99, 40 * 86400); // hors fenêtre
|
await s.spend(99, 40 * 86400); // hors fenêtre
|
||||||
let b = budgetState(s.db);
|
let b = await budgetState(s.db);
|
||||||
assert.equal(b.blocked, false);
|
assert.equal(b.blocked, false);
|
||||||
assert.equal(b.day.used, 1.5);
|
assert.equal(b.day.used, 1.5);
|
||||||
assert.equal(b.month.used, 11.5);
|
assert.equal(b.month.used, 11.5);
|
||||||
|
|
||||||
setSetting(s.db, 'budget_day_usd', '2');
|
await setSetting(s.db, 'budget_day_usd', '2');
|
||||||
assert.equal(budgetState(s.db).blocked, false);
|
assert.equal((await budgetState(s.db)).blocked, false);
|
||||||
setSetting(s.db, 'budget_day_usd', '1.5');
|
await setSetting(s.db, 'budget_day_usd', '1.5');
|
||||||
b = budgetState(s.db);
|
b = await budgetState(s.db);
|
||||||
assert.equal(b.blocked, true);
|
assert.equal(b.blocked, true);
|
||||||
assert.equal(b.reason, 'budget IA des dernières 24 h atteint (1.50 $ / 1.50 $)');
|
assert.equal(b.reason, 'budget IA des dernières 24 h atteint (1.50 $ / 1.50 $)');
|
||||||
|
|
||||||
setSetting(s.db, 'budget_day_usd', '');
|
await setSetting(s.db, 'budget_day_usd', '');
|
||||||
setSetting(s.db, 'budget_month_usd', '10');
|
await setSetting(s.db, 'budget_month_usd', '10');
|
||||||
assert.match(budgetState(s.db).reason, /30 derniers jours atteint \(11\.50 \$ \/ 10\.00 \$\)/);
|
assert.match((await budgetState(s.db)).reason, /30 derniers jours atteint \(11\.50 \$ \/ 10\.00 \$\)/);
|
||||||
assert.equal(budgetState(s.db, { at: now() + 30 * 86400 }).blocked, false, 'la fenêtre glisse');
|
assert.equal((await budgetState(s.db, { at: now() + 30 * 86400 })).blocked, false, 'la fenêtre glisse');
|
||||||
});
|
});
|
||||||
|
|
||||||
test('les envois et relances ne consomment pas d\'IA', () => {
|
test('les envois et relances ne consomment pas d\'IA', () => {
|
||||||
|
|
@ -41,9 +42,9 @@ test('les envois et relances ne consomment pas d\'IA', () => {
|
||||||
});
|
});
|
||||||
|
|
||||||
test('budget atteint : les jobs IA attendent (pas perdus), les envois passent, une seule notif', async () => {
|
test('budget atteint : les jobs IA attendent (pas perdus), les envois passent, une seule notif', async () => {
|
||||||
const s = setup();
|
const s = await setup();
|
||||||
s.spend(5, 600);
|
await s.spend(5, 600);
|
||||||
setSetting(s.db, 'budget_day_usd', '3');
|
await setSetting(s.db, 'budget_day_usd', '3');
|
||||||
const ran = [];
|
const ran = [];
|
||||||
const alerts = [];
|
const alerts = [];
|
||||||
const h = (name) => async () => { ran.push(name); };
|
const h = (name) => async () => { ran.push(name); };
|
||||||
|
|
@ -51,25 +52,25 @@ test('budget atteint : les jobs IA attendent (pas perdus), les envois passent, u
|
||||||
thermalMax: 999, log: { error() {} },
|
thermalMax: 999, log: { error() {} },
|
||||||
budget: () => budgetState(s.db), isAiJob: (t) => AI_JOBS.has(t), onBudget: (r) => alerts.push(r),
|
budget: () => budgetState(s.db), isAiJob: (t) => AI_JOBS.has(t), onBudget: (r) => alerts.push(r),
|
||||||
});
|
});
|
||||||
enqueue(s.db, { projectId: 1, type: 'prospect' });
|
await enqueue(s.db, { projectId: 1, type: 'prospect' });
|
||||||
enqueue(s.db, { projectId: 1, type: 'send' });
|
await enqueue(s.db, { projectId: 1, type: 'send' });
|
||||||
enqueue(s.db, { projectId: 1, type: 'evolution' });
|
await enqueue(s.db, { projectId: 1, type: 'evolution' });
|
||||||
|
|
||||||
assert.equal(await w.tick(), true);
|
assert.equal(await w.tick(), true);
|
||||||
assert.deepEqual(ran, ['send'], 'l\'envoi passe devant les jobs IA bloqués');
|
assert.deepEqual(ran, ['send'], 'l\'envoi passe devant les jobs IA bloqués');
|
||||||
assert.equal(await w.tick(), false);
|
assert.equal(await w.tick(), false);
|
||||||
assert.equal(await w.tick(), false);
|
assert.equal(await w.tick(), false);
|
||||||
assert.equal(alerts.length, 1, 'une seule notif, pas une toutes les 3 s');
|
assert.equal(alerts.length, 1, 'une seule notif, pas une toutes les 3 s');
|
||||||
const jobs = latestJobs(s.db, 1);
|
const jobs = await latestJobs(s.db, 1);
|
||||||
assert.equal(jobs.prospect.status, 'queued');
|
assert.equal(jobs.prospect.status, 'queued');
|
||||||
assert.match(jobs.prospect.progress.message, /^En attente : budget IA des dernières 24 h atteint/);
|
assert.match(jobs.prospect.progress.message, /^En attente : budget IA des dernières 24 h atteint/);
|
||||||
|
|
||||||
setSetting(s.db, 'budget_day_usd', '20'); // ou la fenêtre de 24 h qui glisse
|
await setSetting(s.db, 'budget_day_usd', '20'); // ou la fenêtre de 24 h qui glisse
|
||||||
await w.tick(); await w.tick();
|
await w.tick(); await w.tick();
|
||||||
assert.deepEqual(ran, ['send', 'prospect', 'evolution'], 'les jobs repartent tout seuls, dans l\'ordre');
|
assert.deepEqual(ran, ['send', 'prospect', 'evolution'], 'les jobs repartent tout seuls, dans l\'ordre');
|
||||||
|
|
||||||
setSetting(s.db, 'budget_day_usd', '1');
|
await setSetting(s.db, 'budget_day_usd', '1');
|
||||||
enqueue(s.db, { projectId: 1, type: 'prospect' });
|
await enqueue(s.db, { projectId: 1, type: 'prospect' });
|
||||||
await w.tick();
|
await w.tick();
|
||||||
assert.equal(alerts.length, 2, 'nouvelle notif pour un nouveau blocage');
|
assert.equal(alerts.length, 2, 'nouvelle notif pour un nouveau blocage');
|
||||||
});
|
});
|
||||||
|
|
@ -79,25 +80,25 @@ test('analyse et évolutions sont "non urgents", pas la prospection ni l\'envoi'
|
||||||
for (const t of ['prospect', 'template', 'followup_template', 'send', 'followup']) assert.equal(isQuotaSensitive(t), false);
|
for (const t of ['prospect', 'template', 'followup_template', 'send', 'followup']) assert.equal(isQuotaSensitive(t), false);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('quotaState : pas mesuré, en dessous du seuil, puis bloqué à 85 %', () => {
|
test('quotaState : pas mesuré, en dessous du seuil, puis bloqué à 85 %', async () => {
|
||||||
const s = setup();
|
const s = await setup();
|
||||||
assert.deepEqual(quotaState(s.db), { blocked: false, reason: null });
|
assert.deepEqual(await quotaState(s.db), { blocked: false, reason: null });
|
||||||
setSetting(s.db, 'claude_rate_limit_json', JSON.stringify({ fiveHour: { utilization: 0.5 }, sevenDay: { utilization: 0.6 } }));
|
await setSetting(s.db, 'claude_rate_limit_json', JSON.stringify({ fiveHour: { utilization: 0.5 }, sevenDay: { utilization: 0.6 } }));
|
||||||
assert.equal(quotaState(s.db).blocked, false);
|
assert.equal((await quotaState(s.db)).blocked, false);
|
||||||
setSetting(s.db, 'claude_rate_limit_json', JSON.stringify({ fiveHour: { utilization: 0.9 }, sevenDay: { utilization: 0.6 } }));
|
await setSetting(s.db, 'claude_rate_limit_json', JSON.stringify({ fiveHour: { utilization: 0.9 }, sevenDay: { utilization: 0.6 } }));
|
||||||
let q = quotaState(s.db);
|
let q = await quotaState(s.db);
|
||||||
assert.equal(q.blocked, true);
|
assert.equal(q.blocked, true);
|
||||||
assert.equal(q.reason, 'quota de la session Claude (5 h) à 90 %');
|
assert.equal(q.reason, 'quota de la session Claude (5 h) à 90 %');
|
||||||
setSetting(s.db, 'claude_rate_limit_json', JSON.stringify({ fiveHour: { utilization: 0.1 }, sevenDay: { utilization: 0.99 } }));
|
await setSetting(s.db, 'claude_rate_limit_json', JSON.stringify({ fiveHour: { utilization: 0.1 }, sevenDay: { utilization: 0.99 } }));
|
||||||
q = quotaState(s.db);
|
q = await quotaState(s.db);
|
||||||
assert.equal(q.reason, 'quota de la semaine Claude à 99 %');
|
assert.equal(q.reason, 'quota de la semaine Claude à 99 %');
|
||||||
setSetting(s.db, 'claude_rate_limit_json', 'pas du json');
|
await setSetting(s.db, 'claude_rate_limit_json', 'pas du json');
|
||||||
assert.deepEqual(quotaState(s.db), { blocked: false, reason: null }, 'jamais planter sur une valeur corrompue');
|
assert.deepEqual(await quotaState(s.db), { blocked: false, reason: null }, 'jamais planter sur une valeur corrompue');
|
||||||
});
|
});
|
||||||
|
|
||||||
test('quota serré : analyse/évolution attendent, la prospection et l\'envoi continuent', async () => {
|
test('quota serré : analyse/évolution attendent, la prospection et l\'envoi continuent', async () => {
|
||||||
const s = setup();
|
const s = await setup();
|
||||||
setSetting(s.db, 'claude_rate_limit_json', JSON.stringify({ fiveHour: { utilization: 0.9 } }));
|
await setSetting(s.db, 'claude_rate_limit_json', JSON.stringify({ fiveHour: { utilization: 0.9 } }));
|
||||||
const ran = [];
|
const ran = [];
|
||||||
const alerts = [];
|
const alerts = [];
|
||||||
const h = (name) => async () => { ran.push(name); };
|
const h = (name) => async () => { ran.push(name); };
|
||||||
|
|
@ -105,38 +106,38 @@ test('quota serré : analyse/évolution attendent, la prospection et l\'envoi co
|
||||||
thermalMax: 999, log: { error() {} },
|
thermalMax: 999, log: { error() {} },
|
||||||
quota: () => quotaState(s.db), isQuotaSensitive, onQuotaHold: (r) => alerts.push(r),
|
quota: () => quotaState(s.db), isQuotaSensitive, onQuotaHold: (r) => alerts.push(r),
|
||||||
});
|
});
|
||||||
enqueue(s.db, { projectId: 1, type: 'evolution' });
|
await enqueue(s.db, { projectId: 1, type: 'evolution' });
|
||||||
enqueue(s.db, { projectId: 1, type: 'analyze' });
|
await enqueue(s.db, { projectId: 1, type: 'analyze' });
|
||||||
enqueue(s.db, { projectId: 1, type: 'prospect' });
|
await enqueue(s.db, { projectId: 1, type: 'prospect' });
|
||||||
|
|
||||||
assert.equal(await w.tick(), true);
|
assert.equal(await w.tick(), true);
|
||||||
assert.deepEqual(ran, ['prospect'], 'la prospection passe devant les jobs reportés');
|
assert.deepEqual(ran, ['prospect'], 'la prospection passe devant les jobs reportés');
|
||||||
assert.equal(alerts.length, 1);
|
assert.equal(alerts.length, 1);
|
||||||
assert.match(alerts[0], /quota de la session Claude \(5 h\) à 90 %/);
|
assert.match(alerts[0], /quota de la session Claude \(5 h\) à 90 %/);
|
||||||
const jobs = latestJobs(s.db, 1);
|
const jobs = await latestJobs(s.db, 1);
|
||||||
assert.match(jobs.evolution.progress.message, /^En attente : quota de la session/);
|
assert.match(jobs.evolution.progress.message, /^En attente : quota de la session/);
|
||||||
|
|
||||||
setSetting(s.db, 'claude_rate_limit_json', JSON.stringify({ fiveHour: { utilization: 0.1 } }));
|
await setSetting(s.db, 'claude_rate_limit_json', JSON.stringify({ fiveHour: { utilization: 0.1 } }));
|
||||||
await w.tick(); await w.tick();
|
await w.tick(); await w.tick();
|
||||||
assert.deepEqual(ran, ['prospect', 'evolution', 'analyze'], 'repartent tout seuls une fois le quota libéré');
|
assert.deepEqual(ran, ['prospect', 'evolution', 'analyze'], 'repartent tout seuls une fois le quota libéré');
|
||||||
});
|
});
|
||||||
|
|
||||||
test('quotaAlerts : un palier (80 %, 95 %) une seule fois, re-sonne si la fenêtre a tourné', () => {
|
test('quotaAlerts : un palier (80 %, 95 %) une seule fois, re-sonne si la fenêtre a tourné', async () => {
|
||||||
const s = setup();
|
const s = await setup();
|
||||||
let a = quotaAlerts(s.db, { fiveHour: { utilization: 0.5, resetsAt: 100 } });
|
let a = await quotaAlerts(s.db, { fiveHour: { utilization: 0.5, resetsAt: 100 } });
|
||||||
assert.deepEqual(a, []);
|
assert.deepEqual(a, []);
|
||||||
a = quotaAlerts(s.db, { fiveHour: { utilization: 0.82, resetsAt: 100 } });
|
a = await quotaAlerts(s.db, { fiveHour: { utilization: 0.82, resetsAt: 100 } });
|
||||||
assert.deepEqual(a, [{ label: 'session Claude (5 h)', level: 80, utilization: 0.82 }]);
|
assert.deepEqual(a, [{ label: 'session Claude (5 h)', level: 80, utilization: 0.82 }]);
|
||||||
// toujours au-dessus de 80 %, même fenêtre : pas de redite
|
// toujours au-dessus de 80 %, même fenêtre : pas de redite
|
||||||
a = quotaAlerts(s.db, { fiveHour: { utilization: 0.88, resetsAt: 100 } });
|
a = await quotaAlerts(s.db, { fiveHour: { utilization: 0.88, resetsAt: 100 } });
|
||||||
assert.deepEqual(a, []);
|
assert.deepEqual(a, []);
|
||||||
// passe 95 % : nouveau palier
|
// passe 95 % : nouveau palier
|
||||||
a = quotaAlerts(s.db, { fiveHour: { utilization: 0.97, resetsAt: 100 } });
|
a = await quotaAlerts(s.db, { fiveHour: { utilization: 0.97, resetsAt: 100 } });
|
||||||
assert.deepEqual(a, [{ label: 'session Claude (5 h)', level: 95, utilization: 0.97 }]);
|
assert.deepEqual(a, [{ label: 'session Claude (5 h)', level: 95, utilization: 0.97 }]);
|
||||||
// la fenêtre a tourné (nouveau resetsAt) : 80 % re-sonne
|
// la fenêtre a tourné (nouveau resetsAt) : 80 % re-sonne
|
||||||
a = quotaAlerts(s.db, { fiveHour: { utilization: 0.81, resetsAt: 200 } });
|
a = await quotaAlerts(s.db, { fiveHour: { utilization: 0.81, resetsAt: 200 } });
|
||||||
assert.deepEqual(a, [{ label: 'session Claude (5 h)', level: 80, utilization: 0.81 }]);
|
assert.deepEqual(a, [{ label: 'session Claude (5 h)', level: 80, utilization: 0.81 }]);
|
||||||
// saut direct à 95 % : un seul palier notifié, pas 80 puis 95
|
// saut direct à 95 % : un seul palier notifié, pas 80 puis 95
|
||||||
a = quotaAlerts(s.db, { sevenDay: { utilization: 0.97, resetsAt: 300 } });
|
a = await quotaAlerts(s.db, { sevenDay: { utilization: 0.97, resetsAt: 300 } });
|
||||||
assert.deepEqual(a, [{ label: 'semaine Claude', level: 95, utilization: 0.97 }]);
|
assert.deepEqual(a, [{ label: 'semaine Claude', level: 95, utilization: 0.97 }]);
|
||||||
});
|
});
|
||||||
|
|
|
||||||
|
|
@ -2,7 +2,8 @@ import { test } from 'node:test';
|
||||||
import assert from 'node:assert/strict';
|
import assert from 'node:assert/strict';
|
||||||
import { randomBytes } from 'node:crypto';
|
import { randomBytes } from 'node:crypto';
|
||||||
import { encrypt, decrypt, encryptJson, decryptJson, unsubToken, verifyUnsubToken } from '../src/crypto.js';
|
import { encrypt, decrypt, encryptJson, decryptJson, unsubToken, verifyUnsubToken } from '../src/crypto.js';
|
||||||
import { openDb, getSetting, setSetting, MIGRATIONS } from '../src/db.js';
|
import { getSetting, setSetting, MIGRATIONS } from '../src/db.js';
|
||||||
|
import { testDb } from './helpers/db.js';
|
||||||
import { Router, esc } from '../src/http.js';
|
import { Router, esc } from '../src/http.js';
|
||||||
import { checkIdTokenClaims, checkOrigin } from '../src/auth.js';
|
import { checkIdTokenClaims, checkOrigin } from '../src/auth.js';
|
||||||
|
|
||||||
|
|
@ -25,38 +26,13 @@ test('token de désinscription', () => {
|
||||||
assert.ok(!verifyUnsubToken(key, 'foo@bar.fr', 'x'));
|
assert.ok(!verifyUnsubToken(key, 'foo@bar.fr', 'x'));
|
||||||
});
|
});
|
||||||
|
|
||||||
test('migrations et settings', () => {
|
test('migrations et settings', async () => {
|
||||||
const db = openDb(':memory:');
|
const db = await testDb();
|
||||||
assert.equal(db.prepare('PRAGMA user_version').get().user_version, MIGRATIONS.length);
|
const v = await db.prepare('SELECT COUNT(*) n, MAX(version) v FROM schema_migrations').get();
|
||||||
setSetting(db, 'a', '1'); setSetting(db, 'a', '2');
|
assert.deepEqual({ n: v.n, v: v.v }, { n: MIGRATIONS.length, v: MIGRATIONS.length });
|
||||||
assert.equal(getSetting(db, 'a'), '2');
|
await setSetting(db, 'a', '1'); await setSetting(db, 'a', '2');
|
||||||
assert.equal(getSetting(db, 'nope', 'x'), 'x');
|
assert.equal(await getSetting(db, 'a'), '2');
|
||||||
});
|
assert.equal(await getSetting(db, 'nope', 'x'), 'x');
|
||||||
|
|
||||||
test('migration 2 : les modèles existants deviennent des modèles "initial"', async () => {
|
|
||||||
const { DatabaseSync } = await import('node:sqlite');
|
|
||||||
const { mkdtempSync, rmSync } = await import('node:fs');
|
|
||||||
const { join } = await import('node:path');
|
|
||||||
const { tmpdir } = await import('node:os');
|
|
||||||
const dir = mkdtempSync(join(tmpdir(), 'mig-'));
|
|
||||||
// Base en version 1 avec un modèle déjà validé
|
|
||||||
let raw = new DatabaseSync(join(dir, 'aitools.sqlite'));
|
|
||||||
raw.exec(`CREATE TABLE projects (id INTEGER PRIMARY KEY);
|
|
||||||
CREATE TABLE mail_templates (project_id INTEGER PRIMARY KEY, subject TEXT NOT NULL, body TEXT NOT NULL, status TEXT NOT NULL DEFAULT 'draft', updated_at INTEGER NOT NULL);
|
|
||||||
INSERT INTO projects VALUES (1); INSERT INTO mail_templates VALUES (1, 'Objet', 'Corps', 'validated', 123);
|
|
||||||
PRAGMA user_version = 1;`);
|
|
||||||
raw.close();
|
|
||||||
// On rejoue seulement la migration 2 (les autres tables v1 sont absentes de ce mini-schéma)
|
|
||||||
raw = new DatabaseSync(join(dir, 'aitools.sqlite'));
|
|
||||||
const { MIGRATIONS } = await import('../src/db.js');
|
|
||||||
raw.exec(MIGRATIONS[1]);
|
|
||||||
const t = raw.prepare('SELECT * FROM templates').get();
|
|
||||||
assert.equal(t.kind, 'initial');
|
|
||||||
assert.equal(t.subject, 'Objet');
|
|
||||||
assert.equal(t.status, 'validated');
|
|
||||||
assert.equal(raw.prepare("SELECT COUNT(*) n FROM sqlite_master WHERE name = 'mail_templates'").get().n, 0);
|
|
||||||
raw.close();
|
|
||||||
rmSync(dir, { recursive: true, force: true });
|
|
||||||
});
|
});
|
||||||
|
|
||||||
test('router avec paramètres', () => {
|
test('router avec paramètres', () => {
|
||||||
|
|
|
||||||
111
test/crm.test.js
111
test/crm.test.js
|
|
@ -1,18 +1,19 @@
|
||||||
import { test } from 'node:test';
|
import { test } from 'node:test';
|
||||||
import assert from 'node:assert/strict';
|
import assert from 'node:assert/strict';
|
||||||
import { openDb, now } from '../src/db.js';
|
import { now } from '../src/db.js';
|
||||||
|
import { testDb } from './helpers/db.js';
|
||||||
import { parseFilters, listProspects } from '../src/services/crm.js';
|
import { parseFilters, listProspects } from '../src/services/crm.js';
|
||||||
|
|
||||||
function setup() {
|
async function setup() {
|
||||||
const db = openDb(':memory:');
|
const db = await testDb();
|
||||||
db.prepare("INSERT INTO projects(name, git_url, created_at) VALUES('A', 'a', ?), ('B', 'b', ?)").run(now(), now());
|
await db.prepare("INSERT INTO projects(name, git_url, created_at) VALUES('A', 'a', ?), ('B', 'b', ?)").run(now(), now());
|
||||||
const add = (project, company, email, o = {}) => db.prepare(`INSERT INTO prospects(project_id, company, email, city, sector, score, status, sent_at, created_at)
|
const add = (project, company, email, o = {}) => db.prepare(`INSERT INTO prospects(project_id, company, email, city, sector, score, status, sent_at, created_at)
|
||||||
VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(project, company, email, o.city ?? 'Rennes', o.sector ?? 'boulangerie', o.score ?? 5, o.status ?? 'new', o.sent ?? null, o.created ?? now());
|
VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(project, company, email, o.city ?? 'Rennes', o.sector ?? 'boulangerie', o.score ?? 5, o.status ?? 'new', o.sent ?? null, o.created ?? now());
|
||||||
add(1, 'Le Fournil', 'contact@fournil.fr', { score: 9, status: 'replied', sent: now() - 100 });
|
await add(1, 'Le Fournil', 'contact@fournil.fr', { score: 9, status: 'replied', sent: now() - 100 });
|
||||||
add(1, 'Coiffure Zen', 'hello@zen.fr', { city: 'Vern-sur-Seiche', sector: 'coiffeur', score: 6, status: 'sent', sent: now() - 50 });
|
await add(1, 'Coiffure Zen', 'hello@zen.fr', { city: 'Vern-sur-Seiche', sector: 'coiffeur', score: 6, status: 'sent', sent: now() - 50 });
|
||||||
add(1, 'Fleurs & Co', 'bonjour@fleurs.fr', { sector: 'fleuriste', score: 3, created: now() - 1000 });
|
await add(1, 'Fleurs & Co', 'bonjour@fleurs.fr', { sector: 'fleuriste', score: 3, created: now() - 1000 });
|
||||||
add(1, '100% Bio', 'bio@100pourcent.fr', { score: 7 });
|
await add(1, '100% Bio', 'bio@100pourcent.fr', { score: 7 });
|
||||||
add(2, 'Le Fournil', 'contact@fournil.fr', { score: 10 });
|
await add(2, 'Le Fournil', 'contact@fournil.fr', { score: 10 });
|
||||||
return db;
|
return db;
|
||||||
}
|
}
|
||||||
const f = (o = {}) => parseFilters(new URLSearchParams(o));
|
const f = (o = {}) => parseFilters(new URLSearchParams(o));
|
||||||
|
|
@ -23,70 +24,70 @@ test('parseFilters ignore tout ce qui n\'est pas prévu', () => {
|
||||||
{ q: 'zen', status: '', minScore: 10, sort: 'score', todo: false, page: 1 });
|
{ q: 'zen', status: '', minScore: 10, sort: 'score', todo: false, page: 1 });
|
||||||
});
|
});
|
||||||
|
|
||||||
test('recherche, filtres, tri, et isolation entre projets', () => {
|
test('recherche, filtres, tri, et isolation entre projets', async () => {
|
||||||
const db = setup();
|
const db = await setup();
|
||||||
assert.deepEqual(names(listProspects(db, 1, f())), ['Le Fournil', '100% Bio', 'Coiffure Zen', 'Fleurs & Co'], 'tri par score');
|
assert.deepEqual(names(await listProspects(db, 1, f())), ['Le Fournil', '100% Bio', 'Coiffure Zen', 'Fleurs & Co'], 'tri par score');
|
||||||
assert.deepEqual(names(listProspects(db, 1, f({ q: 'ZEN' }))), ['Coiffure Zen'], 'insensible à la casse');
|
assert.deepEqual(names(await listProspects(db, 1, f({ q: 'ZEN' }))), ['Coiffure Zen'], 'insensible à la casse');
|
||||||
assert.deepEqual(names(listProspects(db, 1, f({ q: 'vern' }))), ['Coiffure Zen'], 'par ville');
|
assert.deepEqual(names(await listProspects(db, 1, f({ q: 'vern' }))), ['Coiffure Zen'], 'par ville');
|
||||||
assert.deepEqual(names(listProspects(db, 1, f({ q: 'fleuriste' }))), ['Fleurs & Co'], 'par secteur');
|
assert.deepEqual(names(await listProspects(db, 1, f({ q: 'fleuriste' }))), ['Fleurs & Co'], 'par secteur');
|
||||||
assert.deepEqual(names(listProspects(db, 1, f({ q: '100%' }))), ['100% Bio'], '% littéral, pas un joker');
|
assert.deepEqual(names(await listProspects(db, 1, f({ q: '100%' }))), ['100% Bio'], '% littéral, pas un joker');
|
||||||
assert.deepEqual(names(listProspects(db, 1, f({ q: '_' }))), [], '_ littéral, pas un joker');
|
assert.deepEqual(names(await listProspects(db, 1, f({ q: '_' }))), [], '_ littéral, pas un joker');
|
||||||
assert.deepEqual(names(listProspects(db, 1, f({ status: 'sent' }))), ['Coiffure Zen']);
|
assert.deepEqual(names(await listProspects(db, 1, f({ status: 'sent' }))), ['Coiffure Zen']);
|
||||||
assert.deepEqual(names(listProspects(db, 1, f({ minScore: '7' }))), ['Le Fournil', '100% Bio']);
|
assert.deepEqual(names(await listProspects(db, 1, f({ minScore: '7' }))), ['Le Fournil', '100% Bio']);
|
||||||
assert.deepEqual(names(listProspects(db, 1, f({ sort: 'company' }))), ['100% Bio', 'Coiffure Zen', 'Fleurs & Co', 'Le Fournil']);
|
assert.deepEqual(names(await listProspects(db, 1, f({ sort: 'company' }))), ['100% Bio', 'Coiffure Zen', 'Fleurs & Co', 'Le Fournil']);
|
||||||
assert.deepEqual(names(listProspects(db, 1, f({ sort: 'contacted' }))).slice(0, 2), ['Coiffure Zen', 'Le Fournil']);
|
assert.deepEqual(names(await listProspects(db, 1, f({ sort: 'contacted' }))).slice(0, 2), ['Coiffure Zen', 'Le Fournil']);
|
||||||
assert.equal(listProspects(db, 2, f()).total, 1, 'jamais les prospects d\'un autre projet');
|
assert.equal((await listProspects(db, 2, f())).total, 1, 'jamais les prospects d\'un autre projet');
|
||||||
});
|
});
|
||||||
|
|
||||||
test('pagination', () => {
|
test('pagination', async () => {
|
||||||
const db = setup();
|
const db = await setup();
|
||||||
for (let i = 0; i < 250; i++) db.prepare("INSERT INTO prospects(project_id, company, email, score, created_at) VALUES(1, ?, ?, 1, ?)").run(`E${i}`, `e${i}@x.fr`, now());
|
for (let i = 0; i < 250; i++) await db.prepare("INSERT INTO prospects(project_id, company, email, score, created_at) VALUES(1, ?, ?, 1, ?)").run(`E${i}`, `e${i}@x.fr`, now());
|
||||||
const p1 = listProspects(db, 1, f());
|
const p1 = await listProspects(db, 1, f());
|
||||||
assert.deepEqual({ total: p1.total, pages: p1.pages, n: p1.rows.length }, { total: 254, pages: 3, n: 100 });
|
assert.deepEqual({ total: p1.total, pages: p1.pages, n: p1.rows.length }, { total: 254, pages: 3, n: 100 });
|
||||||
const p3 = listProspects(db, 1, f({ page: '3' }));
|
const p3 = await listProspects(db, 1, f({ page: '3' }));
|
||||||
assert.equal(p3.rows.length, 54);
|
assert.equal(p3.rows.length, 54);
|
||||||
assert.equal(listProspects(db, 1, f({ page: '99' })).page, 3, 'page trop grande ramenée à la dernière');
|
assert.equal((await listProspects(db, 1, f({ page: '99' }))).page, 3, 'page trop grande ramenée à la dernière');
|
||||||
const ids = new Set([...p1.rows, ...listProspects(db, 1, f({ page: '2' })).rows, ...p3.rows].map((x) => x.id));
|
const ids = new Set([...p1.rows, ...(await listProspects(db, 1, f({ page: '2' }))).rows, ...p3.rows].map((x) => x.id));
|
||||||
assert.equal(ids.size, 254, 'aucun doublon ni trou entre les pages');
|
assert.equal(ids.size, 254, 'aucun doublon ni trou entre les pages');
|
||||||
});
|
});
|
||||||
|
|
||||||
test('fiche : historique des mails, réponse, opposition', async () => {
|
test('fiche : historique des mails, réponse, opposition', async () => {
|
||||||
const { prospectDetail } = await import('../src/services/crm.js');
|
const { prospectDetail } = await import('../src/services/crm.js');
|
||||||
const db = setup();
|
const db = await setup();
|
||||||
db.prepare("INSERT INTO mail_log(project_id, prospect_id, email, sent_at, kind, variant, subject) VALUES(1, 1, 'contact@fournil.fr', 100, 'initial', 'B', 'Objet B')").run();
|
await db.prepare("INSERT INTO mail_log(project_id, prospect_id, email, sent_at, kind, variant, subject) VALUES(1, 1, 'contact@fournil.fr', 100, 'initial', 'B', 'Objet B')").run();
|
||||||
db.prepare("INSERT INTO mail_log(project_id, prospect_id, email, sent_at, kind, subject, error) VALUES(1, 1, 'contact@fournil.fr', 200, 'followup', 'Re: Objet B', '421 retry')").run();
|
await db.prepare("INSERT INTO mail_log(project_id, prospect_id, email, sent_at, kind, subject, error) VALUES(1, 1, 'contact@fournil.fr', 200, 'followup', 'Re: Objet B', '421 retry')").run();
|
||||||
db.prepare("INSERT INTO blacklist(email, reason, created_at) VALUES('contact@fournil.fr', 'unsubscribe', 300)").run();
|
await db.prepare("INSERT INTO blacklist(email, reason, created_at) VALUES('contact@fournil.fr', 'unsubscribe', 300)").run();
|
||||||
const d = prospectDetail(db, 1);
|
const d = await prospectDetail(db, 1);
|
||||||
assert.equal(d.prospect.company, 'Le Fournil');
|
assert.equal(d.prospect.company, 'Le Fournil');
|
||||||
assert.deepEqual(d.mails.map((m) => [m.kind, m.variant, m.error]), [['initial', 'B', null], ['followup', null, '421 retry']]);
|
assert.deepEqual(d.mails.map((m) => [m.kind, m.variant, m.error]), [['initial', 'B', null], ['followup', null, '421 retry']]);
|
||||||
assert.equal(d.optOut.reason, 'unsubscribe');
|
assert.equal(d.optOut.reason, 'unsubscribe');
|
||||||
assert.equal(prospectDetail(db, 999), null);
|
assert.equal(await prospectDetail(db, 999), null);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('notes : ajout, ordre, suppression limitée au bon prospect', async () => {
|
test('notes : ajout, ordre, suppression limitée au bon prospect', async () => {
|
||||||
const { addNote, deleteNote, prospectDetail } = await import('../src/services/crm.js');
|
const { addNote, deleteNote, prospectDetail } = await import('../src/services/crm.js');
|
||||||
const db = setup();
|
const db = await setup();
|
||||||
assert.equal(addNote(db, 1, ' '), null, 'note vide refusée');
|
assert.equal(await addNote(db, 1, ' '), null, 'note vide refusée');
|
||||||
const n1 = addNote(db, 1, 'A rappelé, intéressé');
|
const n1 = await addNote(db, 1, 'A rappelé, intéressé');
|
||||||
const n2 = addNote(db, 1, 'x'.repeat(5000));
|
const n2 = await addNote(db, 1, 'x'.repeat(5000));
|
||||||
assert.equal(prospectDetail(db, 1).notes[0].id, n2, 'plus récente en premier');
|
assert.equal((await prospectDetail(db, 1)).notes[0].id, n2, 'plus récente en premier');
|
||||||
assert.equal(prospectDetail(db, 1).notes[0].body.length, 2000, 'tronquée à 2000');
|
assert.equal((await prospectDetail(db, 1)).notes[0].body.length, 2000, 'tronquée à 2000');
|
||||||
assert.equal(deleteNote(db, 2, n1), false, 'pas la note d\'un autre prospect');
|
assert.equal(await deleteNote(db, 2, n1), false, 'pas la note d\'un autre prospect');
|
||||||
assert.equal(deleteNote(db, 1, n1), true);
|
assert.equal(await deleteNote(db, 1, n1), true);
|
||||||
db.prepare('DELETE FROM prospects WHERE id = 1').run();
|
await db.prepare('DELETE FROM prospects WHERE id = 1').run();
|
||||||
assert.equal(db.prepare('SELECT COUNT(*) n FROM prospect_notes').get().n, 0, 'supprimées avec le prospect');
|
assert.equal((await db.prepare('SELECT COUNT(*) n FROM prospect_notes').get()).n, 0, 'supprimées avec le prospect');
|
||||||
});
|
});
|
||||||
|
|
||||||
test('prochaine action : 9h heure de Paris, dates impossibles refusées, filtre "à faire"', async () => {
|
test('prochaine action : 9h heure de Paris, dates impossibles refusées, filtre "à faire"', async () => {
|
||||||
const { setNextAction } = await import('../src/services/crm.js');
|
const { setNextAction } = await import('../src/services/crm.js');
|
||||||
const db = setup();
|
const db = await setup();
|
||||||
assert.equal(setNextAction(db, 1, 'Rappeler', '2026-07-14'), Date.parse('2026-07-14T07:00:00Z') / 1000, 'été');
|
assert.equal(await setNextAction(db, 1, 'Rappeler', '2026-07-14'), Date.parse('2026-07-14T07:00:00Z') / 1000, 'été');
|
||||||
assert.equal(setNextAction(db, 2, 'Devis', '2026-12-01'), Date.parse('2026-12-01T08:00:00Z') / 1000, 'hiver');
|
assert.equal(await setNextAction(db, 2, 'Devis', '2026-12-01'), Date.parse('2026-12-01T08:00:00Z') / 1000, 'hiver');
|
||||||
assert.throws(() => setNextAction(db, 1, 'x', '2026-02-31'), /Date invalide/);
|
await assert.rejects(setNextAction(db, 1, 'x', '2026-02-31'), /Date invalide/);
|
||||||
assert.throws(() => setNextAction(db, 1, 'x', '14/07/2026'), /AAAA-MM-JJ/);
|
await assert.rejects(setNextAction(db, 1, 'x', '14/07/2026'), /AAAA-MM-JJ/);
|
||||||
const todo = (at) => names(listProspects(db, 1, { ...f({ todo: '1' }), at }));
|
const todo = async (at) => names(await listProspects(db, 1, { ...f({ todo: '1' }), at }));
|
||||||
assert.deepEqual(todo(Date.parse('2026-08-01T00:00:00Z') / 1000), ['Le Fournil'], 'seule l\'action échue');
|
assert.deepEqual(await todo(Date.parse('2026-08-01T00:00:00Z') / 1000), ['Le Fournil'], 'seule l\'action échue');
|
||||||
assert.deepEqual(todo(Date.parse('2027-01-01T00:00:00Z') / 1000), ['Le Fournil', 'Coiffure Zen']);
|
assert.deepEqual(await todo(Date.parse('2027-01-01T00:00:00Z') / 1000), ['Le Fournil', 'Coiffure Zen']);
|
||||||
assert.equal(setNextAction(db, 1, '', ''), null);
|
assert.equal(await setNextAction(db, 1, '', ''), null);
|
||||||
assert.deepEqual(todo(Date.parse('2027-01-01T00:00:00Z') / 1000), ['Coiffure Zen'], 'action effacée');
|
assert.deepEqual(await todo(Date.parse('2027-01-01T00:00:00Z') / 1000), ['Coiffure Zen'], 'action effacée');
|
||||||
});
|
});
|
||||||
|
|
|
||||||
|
|
@ -1,13 +1,14 @@
|
||||||
import { test } from 'node:test';
|
import { test } from 'node:test';
|
||||||
import assert from 'node:assert/strict';
|
import assert from 'node:assert/strict';
|
||||||
import { openDb, now } from '../src/db.js';
|
import { now } from '../src/db.js';
|
||||||
|
import { testDb } from './helpers/db.js';
|
||||||
import { csvCell, toCsv, parseCsv, exportProspects, importProspects } from '../src/services/csv.js';
|
import { csvCell, toCsv, parseCsv, exportProspects, importProspects } from '../src/services/csv.js';
|
||||||
import { parseFilters } from '../src/services/crm.js';
|
import { parseFilters } from '../src/services/crm.js';
|
||||||
|
|
||||||
const f = (o = {}) => parseFilters(new URLSearchParams(o));
|
const f = (o = {}) => parseFilters(new URLSearchParams(o));
|
||||||
function setup() {
|
async function setup() {
|
||||||
const db = openDb(':memory:');
|
const db = await testDb();
|
||||||
db.prepare("INSERT INTO projects(name, git_url, created_at) VALUES('A', 'a', ?), ('B', 'b', ?)").run(now(), now());
|
await db.prepare("INSERT INTO projects(name, git_url, created_at) VALUES('A', 'a', ?), ('B', 'b', ?)").run(now(), now());
|
||||||
return db;
|
return db;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -27,10 +28,10 @@ test('parseCsv : séparateur détecté, guillemets, retours à la ligne, BOM, li
|
||||||
assert.deepEqual(parseCsv('email\tville\nx@y.fr\tBrest'), [['email', 'ville'], ['x@y.fr', 'Brest']]);
|
assert.deepEqual(parseCsv('email\tville\nx@y.fr\tBrest'), [['email', 'ville'], ['x@y.fr', 'Brest']]);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('import : en-têtes souples, doublons, opposition, invalides, origine RGPD', () => {
|
test('import : en-têtes souples, doublons, opposition, invalides, origine RGPD', async () => {
|
||||||
const db = setup();
|
const db = await setup();
|
||||||
db.prepare("INSERT INTO prospects(project_id, company, email, created_at) VALUES(1, 'Déjà', 'deja@la.fr', ?)").run(now());
|
await db.prepare("INSERT INTO prospects(project_id, company, email, created_at) VALUES(1, 'Déjà', 'deja@la.fr', ?)").run(now());
|
||||||
db.prepare("INSERT INTO blacklist(email, reason, created_at) VALUES('stop@moi.fr', 'unsubscribe', ?)").run(now());
|
await db.prepare("INSERT INTO blacklist(email, reason, created_at) VALUES('stop@moi.fr', 'unsubscribe', ?)").run(now());
|
||||||
const csv = [
|
const csv = [
|
||||||
'Raison sociale;E-mail;Site web;Commune;Activité;Note;Origine',
|
'Raison sociale;E-mail;Site web;Commune;Activité;Note;Origine',
|
||||||
'Crêperie Ty Breizh;Contact@TyBreizh.bzh;https://tybreizh.bzh;Quimper;crêperie;8;annuaire CCI',
|
'Crêperie Ty Breizh;Contact@TyBreizh.bzh;https://tybreizh.bzh;Quimper;crêperie;8;annuaire CCI',
|
||||||
|
|
@ -41,40 +42,40 @@ test('import : en-têtes souples, doublons, opposition, invalides, origine RGPD'
|
||||||
'Cassé;pas-un-email;;;;;',
|
'Cassé;pas-un-email;;;;;',
|
||||||
"Formule;f@x.fr;;'=1+1;;99;",
|
"Formule;f@x.fr;;'=1+1;;99;",
|
||||||
].join('\r\n');
|
].join('\r\n');
|
||||||
const r = importProspects(db, 1, csv, { at: Date.parse('2026-10-21T10:00:00Z') / 1000 });
|
const r = await importProspects(db, 1, csv, { at: Date.parse('2026-10-21T10:00:00Z') / 1000 });
|
||||||
assert.deepEqual({ ...r, invalid: r.invalid.map((x) => x.line) }, { total: 7, imported: 3, duplicates: 2, blacklisted: 1, invalid: [7] });
|
assert.deepEqual({ ...r, invalid: r.invalid.map((x) => x.line) }, { total: 7, imported: 3, duplicates: 2, blacklisted: 1, invalid: [7] });
|
||||||
const get = (email) => db.prepare('SELECT * FROM prospects WHERE project_id = 1 AND email = ?').get(email);
|
const get = async (email) => db.prepare('SELECT * FROM prospects WHERE project_id = 1 AND email = ?').get(email);
|
||||||
const ty = get('contact@tybreizh.bzh');
|
const ty = await get('contact@tybreizh.bzh');
|
||||||
assert.deepEqual([ty.company, ty.website, ty.city, ty.sector, ty.score, ty.source, ty.status], ['Crêperie Ty Breizh', 'https://tybreizh.bzh', 'Quimper', 'crêperie', 8, 'annuaire CCI', 'new']);
|
assert.deepEqual([ty.company, ty.website, ty.city, ty.sector, ty.score, ty.source, ty.status], ['Crêperie Ty Breizh', 'https://tybreizh.bzh', 'Quimper', 'crêperie', 8, 'annuaire CCI', 'new']);
|
||||||
const sn = get('sans-nom@atelier.fr');
|
const sn = await get('sans-nom@atelier.fr');
|
||||||
assert.equal(sn.company, 'atelier.fr', 'nom déduit du domaine');
|
assert.equal(sn.company, 'atelier.fr', 'nom déduit du domaine');
|
||||||
assert.equal(sn.website, null, 'javascript: rejeté');
|
assert.equal(sn.website, null, 'javascript: rejeté');
|
||||||
assert.equal(sn.source, 'Import CSV du 21/10/2026', 'origine toujours renseignée');
|
assert.equal(sn.source, 'Import CSV du 21/10/2026', 'origine toujours renseignée');
|
||||||
assert.equal(get('f@x.fr').city, '=1+1', 'apostrophe de notre export retirée');
|
assert.equal((await get('f@x.fr')).city, '=1+1', 'apostrophe de notre export retirée');
|
||||||
assert.equal(get('f@x.fr').score, 10, 'score borné');
|
assert.equal((await get('f@x.fr')).score, 10, 'score borné');
|
||||||
assert.equal(db.prepare('SELECT COUNT(*) n FROM prospects WHERE project_id = 2').get().n, 0, 'rien dans l\'autre projet');
|
assert.equal((await db.prepare('SELECT COUNT(*) n FROM prospects WHERE project_id = 2').get()).n, 0, 'rien dans l\'autre projet');
|
||||||
});
|
});
|
||||||
|
|
||||||
test('import : erreurs claires', () => {
|
test('import : erreurs claires', async () => {
|
||||||
const db = setup();
|
const db = await setup();
|
||||||
assert.throws(() => importProspects(db, 1, 'email\n'), /vide ou sans en-tête/);
|
await assert.rejects(importProspects(db, 1, 'email\n'), /vide ou sans en-tête/);
|
||||||
assert.throws(() => importProspects(db, 1, 'nom;ville\nA;B'), /Colonne email introuvable/);
|
await assert.rejects(importProspects(db, 1, 'nom;ville\nA;B'), /Colonne email introuvable/);
|
||||||
assert.throws(() => importProspects(db, 1, 'email\n' + 'a@b.fr\n'.repeat(2001)), /Maximum 2000 lignes/);
|
await assert.rejects(importProspects(db, 1, 'email\n' + 'a@b.fr\n'.repeat(2001)), /Maximum 2000 lignes/);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('export puis réimport dans un autre projet : aller-retour sans perte', () => {
|
test('export puis réimport dans un autre projet : aller-retour sans perte', async () => {
|
||||||
const db = setup();
|
const db = await setup();
|
||||||
db.prepare(`INSERT INTO prospects(project_id, company, email, website, city, sector, score, status, source, hook, created_at)
|
await db.prepare(`INSERT INTO prospects(project_id, company, email, website, city, sector, score, status, source, hook, created_at)
|
||||||
VALUES(1, 'Le "Fournil"; SARL', 'c@fournil.fr', 'https://fournil.fr', 'Rennes', 'boulangerie', 9, 'replied', 'https://fournil.fr/contact', '=Votre pain mérite mieux', ?)`).run(now());
|
VALUES(1, 'Le "Fournil"; SARL', 'c@fournil.fr', 'https://fournil.fr', 'Rennes', 'boulangerie', 9, 'replied', 'https://fournil.fr/contact', '=Votre pain mérite mieux', ?)`).run(now());
|
||||||
db.prepare("INSERT INTO prospects(project_id, company, email, score, status, created_at) VALUES(1, 'Zen', 'z@zen.fr', 4, 'new', ?)").run(now());
|
await db.prepare("INSERT INTO prospects(project_id, company, email, score, status, created_at) VALUES(1, 'Zen', 'z@zen.fr', 4, 'new', ?)").run(now());
|
||||||
const all = exportProspects(db, 1, f());
|
const all = await exportProspects(db, 1, f());
|
||||||
assert.match(all, /^Entreprise;Email;Site/);
|
assert.match(all, /^Entreprise;Email;Site/);
|
||||||
assert.match(all, /"Le ""Fournil""; SARL";c@fournil\.fr/);
|
assert.match(all, /"Le ""Fournil""; SARL";c@fournil\.fr/);
|
||||||
assert.match(all, /'=Votre pain/, 'formule neutralisée');
|
assert.match(all, /'=Votre pain/, 'formule neutralisée');
|
||||||
assert.match(all, /;A répondu;/, 'statut lisible');
|
assert.match(all, /;A répondu;/, 'statut lisible');
|
||||||
assert.equal(exportProspects(db, 1, f({ minScore: '5' })).trim().split('\r\n').length, 2, 'l\'export suit les filtres');
|
assert.equal((await exportProspects(db, 1, f({ minScore: '5' }))).trim().split('\r\n').length, 2, 'l\'export suit les filtres');
|
||||||
const r = importProspects(db, 2, all);
|
const r = await importProspects(db, 2, all);
|
||||||
assert.equal(r.imported, 2);
|
assert.equal(r.imported, 2);
|
||||||
const back = db.prepare("SELECT company, website, source, hook, score FROM prospects WHERE project_id = 2 AND email = 'c@fournil.fr'").get();
|
const back = await db.prepare("SELECT company, website, source, hook, score FROM prospects WHERE project_id = 2 AND email = 'c@fournil.fr'").get();
|
||||||
assert.deepEqual({ ...back }, { company: 'Le "Fournil"; SARL', website: 'https://fournil.fr', source: 'https://fournil.fr/contact', hook: '=Votre pain mérite mieux', score: 9 });
|
assert.deepEqual({ ...back }, { company: 'Le "Fournil"; SARL', website: 'https://fournil.fr', source: 'https://fournil.fr/contact', hook: '=Votre pain mérite mieux', score: 9 });
|
||||||
});
|
});
|
||||||
|
|
|
||||||
|
|
@ -4,7 +4,9 @@ import { mkdtempSync, rmSync } from 'node:fs';
|
||||||
import { tmpdir } from 'node:os';
|
import { tmpdir } from 'node:os';
|
||||||
import { join, resolve } from 'node:path';
|
import { join, resolve } from 'node:path';
|
||||||
import { randomBytes } from 'node:crypto';
|
import { randomBytes } from 'node:crypto';
|
||||||
import { openDb, now, setSetting } from '../src/db.js';
|
import { now, setSetting } from '../src/db.js';
|
||||||
|
import { testDb } from './helpers/db.js';
|
||||||
|
|
||||||
import { isBusinessHours, followupPlan, followupSubject } from '../src/services/followup.js';
|
import { isBusinessHours, followupPlan, followupSubject } from '../src/services/followup.js';
|
||||||
import { Worker, latestJobs } from '../src/services/jobs.js';
|
import { Worker, latestJobs } from '../src/services/jobs.js';
|
||||||
import { Scheduler } from '../src/services/scheduler.js';
|
import { Scheduler } from '../src/services/scheduler.js';
|
||||||
|
|
@ -33,30 +35,30 @@ test('objet de la relance : même fil par défaut', () => {
|
||||||
|
|
||||||
const WED_10H = Math.floor(new Date('2026-10-21T10:00:00+02:00').getTime() / 1000);
|
const WED_10H = Math.floor(new Date('2026-10-21T10:00:00+02:00').getTime() / 1000);
|
||||||
|
|
||||||
function setup() {
|
async function setup() {
|
||||||
const tmp = mkdtempSync(join(tmpdir(), 'aitools-fu-'));
|
const tmp = mkdtempSync(join(tmpdir(), 'aitools-fu-'));
|
||||||
const db = openDb(':memory:');
|
const db = await testDb();
|
||||||
const sentMails = [];
|
const sentMails = [];
|
||||||
const app = {
|
const app = {
|
||||||
db, cfg: { dataDir: tmp, claudeBin: resolve('test/fixtures/fake-claude.js'), secretKey: randomBytes(32), appUrl: 'https://ai.test' },
|
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() {} }),
|
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
|
isBusinessHours: () => true, // horloge figée : le test ne dépend pas de l'heure à laquelle on le lance
|
||||||
};
|
};
|
||||||
setSetting(db, 'send_delay_min', '0');
|
await setSetting(db, 'send_delay_min', '0');
|
||||||
setSetting(db, 'send_delay_max', '0');
|
await setSetting(db, 'send_delay_max', '0');
|
||||||
const id = createProject(app, { name: 'P', gitUrl: 'https://git.x/T/P.git' });
|
const id = await 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');
|
await 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');
|
await 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 = ?')
|
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);
|
.run(JSON.stringify({ lastOk: at, lastCheck: at, lastError: null, ...extra }), id);
|
||||||
inboxOk();
|
await inboxOk();
|
||||||
db.prepare("INSERT INTO templates(project_id, kind, subject, body, status, updated_at) VALUES(?, 'followup', '', 'Toujours partant, {{entreprise}} ?', 'validated', ?)").run(id, now());
|
await 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);
|
await db.prepare('UPDATE projects SET followup_enabled = 1, followup_days = 7 WHERE id = ?').run(id);
|
||||||
const add = (email, daysAgo, status = 'sent') => {
|
const add = async (email, daysAgo, status = 'sent') => {
|
||||||
const t = now() - daysAgo * 86400;
|
const t = now() - daysAgo * 86400;
|
||||||
const pid = Number(db.prepare('INSERT INTO prospects(project_id, company, email, status, sent_at, created_at) VALUES(?, ?, ?, ?, ?, ?)')
|
const pid = Number((await 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);
|
.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', ?, ?)")
|
await 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}`, `<orig-${pid}@codebzh.fr>`);
|
.run(id, pid, email, t, `Une idée pour ${email}`, `<orig-${pid}@codebzh.fr>`);
|
||||||
return pid;
|
return pid;
|
||||||
};
|
};
|
||||||
|
|
@ -66,21 +68,21 @@ function setup() {
|
||||||
}
|
}
|
||||||
|
|
||||||
test('relance : seulement les prospects dus, sans réponse, dans le même fil, une seule fois', async () => {
|
test('relance : seulement les prospects dus, sans réponse, dans le même fil, une seule fois', async () => {
|
||||||
const s = setup();
|
const s = await setup();
|
||||||
try {
|
try {
|
||||||
const due = s.add('contact@fournil.fr', 8);
|
const due = await s.add('contact@fournil.fr', 8);
|
||||||
const tooEarly = s.add('hello@zen.fr', 3);
|
const tooEarly = await s.add('hello@zen.fr', 3);
|
||||||
const replied = s.add('jean@atelier.fr', 10, 'replied');
|
const replied = await s.add('jean@atelier.fr', 10, 'replied');
|
||||||
const blacklisted = s.add('stop@ferme.fr', 9);
|
const blacklisted = await s.add('stop@ferme.fr', 9);
|
||||||
s.db.prepare("INSERT INTO blacklist(email, reason, created_at) VALUES('stop@ferme.fr', 'unsubscribe', ?)").run(now());
|
await 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) });
|
const plan = await followupPlan(s.db, await getProject(s.app, s.id), { date: new Date(WED_10H * 1000) });
|
||||||
assert.deepEqual({ due: plan.due, blockers: plan.blockers }, { due: 1, blockers: [] });
|
assert.deepEqual({ due: plan.due, blockers: plan.blockers }, { due: 1, blockers: [] });
|
||||||
|
|
||||||
const queued = s.scheduler.queueFollowups({ date: new Date(WED_10H * 1000) });
|
const queued = await s.scheduler.queueFollowups({ date: new Date(WED_10H * 1000) });
|
||||||
assert.equal(queued.length, 1);
|
assert.equal(queued.length, 1);
|
||||||
await s.worker.tick();
|
await s.worker.tick();
|
||||||
const job = latestJobs(s.db, s.id).followup;
|
const job = (await latestJobs(s.db, s.id)).followup;
|
||||||
assert.equal(job.status, 'done', job.error);
|
assert.equal(job.status, 'done', job.error);
|
||||||
assert.deepEqual(job.result, { sent: 1, failed: 0, total: 1 });
|
assert.deepEqual(job.result, { sent: 1, failed: 0, total: 1 });
|
||||||
|
|
||||||
|
|
@ -90,78 +92,78 @@ test('relance : seulement les prospects dus, sans réponse, dans le même fil, u
|
||||||
assert.equal(m.inReplyTo, `<orig-${due}@codebzh.fr>`);
|
assert.equal(m.inReplyTo, `<orig-${due}@codebzh.fr>`);
|
||||||
assert.match(m.text, /Toujours partant, fournil\.fr \?/);
|
assert.match(m.text, /Toujours partant, fournil\.fr \?/);
|
||||||
assert.match(m.text, /Pour ne plus être contacté/);
|
assert.match(m.text, /Pour ne plus être contacté/);
|
||||||
const log = s.db.prepare("SELECT * FROM mail_log WHERE kind = 'followup'").all();
|
const log = await s.db.prepare("SELECT * FROM mail_log WHERE kind = 'followup'").all();
|
||||||
assert.equal(log.length, 1);
|
assert.equal(log.length, 1);
|
||||||
assert.equal(log[0].message_id, m.messageId);
|
assert.equal(log[0].message_id, m.messageId);
|
||||||
|
|
||||||
const st = (pid) => s.db.prepare('SELECT status, followup_at FROM prospects WHERE id = ?').get(pid);
|
const st = (pid) => s.db.prepare('SELECT status, followup_at FROM prospects WHERE id = ?').get(pid);
|
||||||
assert.ok(st(due).followup_at > 0);
|
assert.ok((await st(due)).followup_at > 0);
|
||||||
assert.equal(st(due).status, 'sent', 'reste "contacté" : une réponse à la relance sera détectée normalement');
|
assert.equal((await 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);
|
for (const pid of [tooEarly, replied, blacklisted]) assert.equal((await st(pid)).followup_at, null);
|
||||||
|
|
||||||
assert.equal(s.scheduler.queueFollowups({ date: new Date(WED_10H * 1000) }).length, 0, 'jamais 2 relances');
|
assert.equal((await s.scheduler.queueFollowups({ date: new Date(WED_10H * 1000) })).length, 0, 'jamais 2 relances');
|
||||||
} finally { rmSync(s.tmp, { recursive: true, force: true }); }
|
} 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é', () => {
|
test('relance bloquée : boîte en erreur, boîte pas lue récemment, week-end, désactivée, modèle non validé', async () => {
|
||||||
const s = setup();
|
const s = await setup();
|
||||||
try {
|
try {
|
||||||
s.add('contact@fournil.fr', 8);
|
await s.add('contact@fournil.fr', 8);
|
||||||
const plan = (o = {}) => followupPlan(s.db, getProject(s.app, s.id), o);
|
const plan = async (o = {}) => followupPlan(s.db, await getProject(s.app, s.id), o);
|
||||||
const sat = new Date('2026-10-24T11:00:00+02:00');
|
const sat = new Date('2026-10-24T11:00:00+02:00');
|
||||||
assert.equal(plan({ date: sat }).ready, false);
|
assert.equal((await plan({ date: sat })).ready, false);
|
||||||
assert.equal(plan({ date: sat }).inHours, false);
|
assert.equal((await plan({ date: sat })).inHours, false);
|
||||||
assert.equal(s.scheduler.queueFollowups({ date: sat }).length, 0, 'pas le week-end');
|
assert.equal((await s.scheduler.queueFollowups({ date: sat })).length, 0, 'pas le week-end');
|
||||||
|
|
||||||
s.inboxOk(now(), { lastError: 'AUTHENTICATIONFAILED' });
|
await s.inboxOk(now(), { lastError: 'AUTHENTICATIONFAILED' });
|
||||||
assert.deepEqual(plan().blockers, ['boîte non vérifiée récemment']);
|
assert.deepEqual((await plan()).blockers, ['boîte non vérifiée récemment']);
|
||||||
s.inboxOk(now() - 3 * 3600);
|
await s.inboxOk(now() - 3 * 3600);
|
||||||
assert.deepEqual(plan().blockers, ['boîte non vérifiée récemment']);
|
assert.deepEqual((await plan()).blockers, ['boîte non vérifiée récemment']);
|
||||||
s.db.prepare('UPDATE projects SET imap_enc = NULL WHERE id = ?').run(s.id);
|
await s.db.prepare('UPDATE projects SET imap_enc = NULL WHERE id = ?').run(s.id);
|
||||||
assert.deepEqual(plan().blockers, ['boîte IMAP à connecter']);
|
assert.deepEqual((await plan()).blockers, ['boîte IMAP à connecter']);
|
||||||
s.db.prepare("UPDATE templates SET status = 'draft' WHERE kind = 'followup'").run();
|
await 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);
|
await 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']);
|
assert.deepEqual((await plan()).blockers, ['relance désactivée', 'modèle de relance à valider', 'boîte IMAP à connecter']);
|
||||||
} finally { rmSync(s.tmp, { recursive: true, force: true }); }
|
} 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 () => {
|
test('réponse arrivée entre la mise en file et l\'envoi : pas de relance', async () => {
|
||||||
const s = setup();
|
const s = await setup();
|
||||||
try {
|
try {
|
||||||
const pid = s.add('contact@fournil.fr', 8);
|
const pid = await s.add('contact@fournil.fr', 8);
|
||||||
assert.equal(s.scheduler.queueFollowups({ date: new Date(WED_10H * 1000) }).length, 1);
|
assert.equal((await 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.db.prepare("UPDATE prospects SET status = 'replied' WHERE id = ?").run(pid);
|
||||||
await s.worker.tick();
|
await s.worker.tick();
|
||||||
assert.equal(s.sentMails.length, 0);
|
assert.equal(s.sentMails.length, 0);
|
||||||
} finally { rmSync(s.tmp, { recursive: true, force: true }); }
|
} 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 () => {
|
test('relance en file mais heures ouvrées dépassées : reportée, rien n\'est envoyé', async () => {
|
||||||
const s = setup();
|
const s = await setup();
|
||||||
try {
|
try {
|
||||||
const pid = s.add('contact@fournil.fr', 8);
|
const pid = await s.add('contact@fournil.fr', 8);
|
||||||
s.scheduler.queueFollowups({ date: new Date(WED_10H * 1000) });
|
await s.scheduler.queueFollowups({ date: new Date(WED_10H * 1000) });
|
||||||
s.app.isBusinessHours = () => false;
|
s.app.isBusinessHours = () => false;
|
||||||
await s.worker.tick();
|
await s.worker.tick();
|
||||||
assert.equal(s.sentMails.length, 0);
|
assert.equal(s.sentMails.length, 0);
|
||||||
assert.equal(latestJobs(s.db, s.id).followup.result.postponed, true);
|
assert.equal((await 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');
|
assert.equal((await s.db.prepare('SELECT followup_at FROM prospects WHERE id = ?').get(pid)).followup_at, null, 'toujours due');
|
||||||
s.app.isBusinessHours = () => true;
|
s.app.isBusinessHours = () => true;
|
||||||
assert.equal(s.scheduler.queueFollowups({ date: new Date(WED_10H * 1000) }).length, 1, 'reprogrammée au créneau suivant');
|
assert.equal((await 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 }); }
|
} finally { rmSync(s.tmp, { recursive: true, force: true }); }
|
||||||
});
|
});
|
||||||
|
|
||||||
test('génération du modèle de relance par l\'IA', async () => {
|
test('génération du modèle de relance par l\'IA', async () => {
|
||||||
const s = setup();
|
const s = await setup();
|
||||||
try {
|
try {
|
||||||
s.db.prepare('UPDATE projects SET profile_json = ? WHERE id = ?').run(JSON.stringify({ resume: 'x', proposition_valeur: 'y' }), s.id);
|
await 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();
|
await s.db.prepare("DELETE FROM templates WHERE kind = 'followup'").run();
|
||||||
const { enqueue } = await import('../src/services/jobs.js');
|
const { enqueue } = await import('../src/services/jobs.js');
|
||||||
enqueue(s.db, { projectId: s.id, type: 'followup_template' });
|
await enqueue(s.db, { projectId: s.id, type: 'followup_template' });
|
||||||
await s.worker.tick();
|
await s.worker.tick();
|
||||||
const job = latestJobs(s.db, s.id).followup_template;
|
const job = (await latestJobs(s.db, s.id)).followup_template;
|
||||||
assert.equal(job.status, 'done', job.error);
|
assert.equal(job.status, 'done', job.error);
|
||||||
const t = s.db.prepare("SELECT * FROM templates WHERE kind = 'followup'").get();
|
const t = await s.db.prepare("SELECT * FROM templates WHERE kind = 'followup'").get();
|
||||||
assert.equal(t.status, 'draft');
|
assert.equal(t.status, 'draft');
|
||||||
assert.equal(t.subject, '');
|
assert.equal(t.subject, '');
|
||||||
assert.match(t.body, /relance/i);
|
assert.match(t.body, /relance/i);
|
||||||
|
|
|
||||||
|
|
@ -5,7 +5,8 @@ import { mkdtempSync, writeFileSync, readFileSync, rmSync } from 'node:fs';
|
||||||
import { tmpdir } from 'node:os';
|
import { tmpdir } from 'node:os';
|
||||||
import { join, resolve } from 'node:path';
|
import { join, resolve } from 'node:path';
|
||||||
import { randomBytes } from 'node:crypto';
|
import { randomBytes } from 'node:crypto';
|
||||||
import { openDb, setSetting, getSetting, now } from '../src/db.js';
|
import { setSetting, getSetting, now } from '../src/db.js';
|
||||||
|
import { testDb } from './helpers/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, pickVariant } from '../src/projects.js';
|
import { createProject, saveSecretConfig, getProject, prospectStats, pickVariant } from '../src/projects.js';
|
||||||
|
|
@ -14,7 +15,7 @@ import { validateSelect, firstValue } from '../src/services/recap.js';
|
||||||
import { validateGitUrl } from '../src/services/git.js';
|
import { validateGitUrl } from '../src/services/git.js';
|
||||||
import { verifyUnsubToken, encrypt } from '../src/crypto.js';
|
import { verifyUnsubToken, encrypt } from '../src/crypto.js';
|
||||||
|
|
||||||
function setup() {
|
async function setup() {
|
||||||
const tmp = mkdtempSync(join(tmpdir(), 'aitools-'));
|
const tmp = mkdtempSync(join(tmpdir(), 'aitools-'));
|
||||||
const src = join(tmp, 'src-repo');
|
const src = join(tmp, 'src-repo');
|
||||||
execFileSync('git', ['init', '-q', '-b', 'main', src]);
|
execFileSync('git', ['init', '-q', '-b', 'main', src]);
|
||||||
|
|
@ -22,56 +23,56 @@ function setup() {
|
||||||
execFileSync('git', ['-C', src, '-c', 'user.name=t', '-c', 'user.email=t@t', 'commit', '-qam', 'init', '--allow-empty']);
|
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, 'add', '.']);
|
||||||
execFileSync('git', ['-C', src, '-c', 'user.name=t', '-c', 'user.email=t@t', 'commit', '-qm', 'readme']);
|
execFileSync('git', ['-C', src, '-c', 'user.name=t', '-c', 'user.email=t@t', 'commit', '-qm', 'readme']);
|
||||||
const db = openDb(':memory:');
|
const db = await testDb();
|
||||||
const sentMails = [];
|
const sentMails = [];
|
||||||
const app = {
|
const app = {
|
||||||
db,
|
db,
|
||||||
cfg: { dataDir: tmp, claudeBin: resolve('test/fixtures/fake-claude.js'), secretKey: randomBytes(32), appUrl: 'https://ai.test' },
|
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() {} }),
|
createTransport: () => ({ verify: async () => true, sendMail: async (m) => { sentMails.push(m); }, close() {} }),
|
||||||
};
|
};
|
||||||
setSetting(db, 'send_delay_min', '0');
|
await setSetting(db, 'send_delay_min', '0');
|
||||||
setSetting(db, 'send_delay_max', '0');
|
await setSetting(db, 'send_delay_max', '0');
|
||||||
const id = createProject(app, { name: 'MonEspacePro', gitUrl: `file://${src}` });
|
const id = await createProject(app, { name: 'MonEspacePro', gitUrl: `file://${src}` });
|
||||||
const worker = new Worker(db, makeHandlers(app), { thermalMax: 999, log: { error: (...a) => console.error(...a) } });
|
const worker = new Worker(db, makeHandlers(app), { thermalMax: 999, log: { error: (...a) => console.error(...a) } });
|
||||||
return { tmp, db, app, id, worker, sentMails };
|
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]; };
|
const run = async (s, type, params) => { await enqueue(s.db, { projectId: s.id, type, params }); await s.worker.tick(); return (await latestJobs(s.db, s.id))[type]; };
|
||||||
|
|
||||||
test('flux complet : analyse → cible → prospection → modèle → envoi → évolution', async () => {
|
test('flux complet : analyse → cible → prospection → modèle → envoi → évolution', async () => {
|
||||||
const s = setup();
|
const s = await setup();
|
||||||
try {
|
try {
|
||||||
const a = await run(s, 'analyze');
|
const a = await run(s, 'analyze');
|
||||||
assert.equal(a.status, 'done', a.error);
|
assert.equal(a.status, 'done', a.error);
|
||||||
let p = getProject(s.app, s.id);
|
let p = await getProject(s.app, s.id);
|
||||||
assert.equal(p.profile.resume, 'Cartes de fidélité digitales.');
|
assert.equal(p.profile.resume, 'Cartes de fidélité digitales.');
|
||||||
assert.equal(p.target.zone, 'Bretagne');
|
assert.equal(p.target.zone, 'Bretagne');
|
||||||
assert.equal(p.targetValidated, false);
|
assert.equal(p.targetValidated, false);
|
||||||
assert.match(p.profileCommit, /^[0-9a-f]{40}$/);
|
assert.match(p.profileCommit, /^[0-9a-f]{40}$/);
|
||||||
const rl = JSON.parse(getSetting(s.db, 'claude_rate_limit_json'));
|
const rl = JSON.parse(await getSetting(s.db, 'claude_rate_limit_json'));
|
||||||
assert.equal(rl.fiveHour.utilization, 0.33, 'quota Claude (session) enregistré après l\'appel');
|
assert.equal(rl.fiveHour.utilization, 0.33, 'quota Claude (session) enregistré après l\'appel');
|
||||||
assert.equal(rl.sevenDay.utilization, 0.5, 'quota Claude (semaine) enregistré après l\'appel');
|
assert.equal(rl.sevenDay.utilization, 0.5, 'quota Claude (semaine) enregistré après l\'appel');
|
||||||
|
|
||||||
const refused = await run(s, 'prospect', { count: 3 });
|
const refused = await run(s, 'prospect', { count: 3 });
|
||||||
assert.match(refused.error, /Valide la cible/);
|
assert.match(refused.error, /Valide la cible/);
|
||||||
|
|
||||||
s.db.prepare('UPDATE projects SET target_validated = 1 WHERE id = ?').run(s.id);
|
await 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());
|
await s.db.prepare("INSERT INTO blacklist(email, created_at) VALUES('hello@zen.fr', ?)").run(now());
|
||||||
const pr = await run(s, 'prospect', { count: 3 });
|
const pr = await run(s, 'prospect', { count: 3 });
|
||||||
assert.equal(pr.status, 'done', pr.error);
|
assert.equal(pr.status, 'done', pr.error);
|
||||||
assert.equal(pr.result.found, 1, 'email invalide rejeté + blacklisté ignoré');
|
assert.equal(pr.result.found, 1, 'email invalide rejeté + blacklisté ignoré');
|
||||||
assert.equal(prospectStats(s.db, s.id).new, 1);
|
assert.equal((await prospectStats(s.db, s.id)).new, 1);
|
||||||
|
|
||||||
const t = await run(s, 'template');
|
const t = await run(s, 'template');
|
||||||
assert.equal(t.status, 'done', t.error);
|
assert.equal(t.status, 'done', t.error);
|
||||||
const noValid = await run(s, 'send', { count: 5 });
|
const noValid = await run(s, 'send', { count: 5 });
|
||||||
assert.match(noValid.error, /non validé/);
|
assert.match(noValid.error, /non validé/);
|
||||||
|
|
||||||
s.db.prepare("UPDATE templates SET status = 'validated' WHERE project_id = ? AND kind = 'initial'").run(s.id);
|
await s.db.prepare("UPDATE templates SET status = 'validated' WHERE project_id = ? AND kind = 'initial'").run(s.id);
|
||||||
const noSmtp = await run(s, 'send', { count: 5 });
|
const noSmtp = await run(s, 'send', { count: 5 });
|
||||||
assert.match(noSmtp.error, /SMTP/);
|
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');
|
await 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 });
|
const sent = await run(s, 'send', { count: 5 });
|
||||||
assert.equal(sent.status, 'done', sent.error);
|
assert.equal(sent.status, 'done', sent.error);
|
||||||
assert.deepEqual(sent.result, { sent: 1, failed: 0, total: 1 });
|
assert.deepEqual(sent.result, { sent: 1, failed: 0, total: 1 });
|
||||||
|
|
@ -84,14 +85,14 @@ test('flux complet : analyse → cible → prospection → modèle → envoi →
|
||||||
assert.match(mail.html, /Ne plus recevoir de messages/);
|
assert.match(mail.html, /Ne plus recevoir de messages/);
|
||||||
const unsub = /\/u\/([^/]+)\/(\S+)/.exec(mail.headers['List-Unsubscribe']);
|
const unsub = /\/u\/([^/]+)\/(\S+)/.exec(mail.headers['List-Unsubscribe']);
|
||||||
assert.ok(verifyUnsubToken(s.app.cfg.secretKey, decodeURIComponent(unsub[1]), unsub[2].replace('>', '')));
|
assert.ok(verifyUnsubToken(s.app.cfg.secretKey, decodeURIComponent(unsub[1]), unsub[2].replace('>', '')));
|
||||||
assert.equal(prospectStats(s.db, s.id).sent, 1);
|
assert.equal((await prospectStats(s.db, s.id)).sent, 1);
|
||||||
|
|
||||||
const again = await run(s, 'send', { count: 5 });
|
const again = await run(s, 'send', { count: 5 });
|
||||||
assert.match(again.error, /aucun prospect/, 'jamais 2 fois le même prospect');
|
assert.match(again.error, /aucun prospect/, 'jamais 2 fois le même prospect');
|
||||||
|
|
||||||
const ev1 = await run(s, 'evolution', { count: 3, level: 'rapide' });
|
const ev1 = await run(s, 'evolution', { count: 3, level: 'rapide' });
|
||||||
assert.match(ev1.error, /Adresse de réception/);
|
assert.match(ev1.error, /Adresse de réception/);
|
||||||
setSetting(s.db, 'notify_email', 'moi@x.fr');
|
await setSetting(s.db, 'notify_email', 'moi@x.fr');
|
||||||
const ev = await run(s, 'evolution', { count: 3, level: 'rapide' });
|
const ev = await run(s, 'evolution', { count: 3, level: 'rapide' });
|
||||||
assert.equal(ev.status, 'done', ev.error);
|
assert.equal(ev.status, 'done', ev.error);
|
||||||
assert.equal(s.sentMails.at(-1).to, 'moi@x.fr');
|
assert.equal(s.sentMails.at(-1).to, 'moi@x.fr');
|
||||||
|
|
@ -100,7 +101,7 @@ test('flux complet : analyse → cible → prospection → modèle → envoi →
|
||||||
assert.match(s.sentMails.at(-1).html, /Export CSV/);
|
assert.match(s.sentMails.at(-1).html, /Export CSV/);
|
||||||
assert.equal(ev.progress.pct, 95, 'avancement remonté jusqu\'au mail');
|
assert.equal(ev.progress.pct, 95, 'avancement remonté jusqu\'au mail');
|
||||||
|
|
||||||
const usage = s.db.prepare('SELECT SUM(cost_usd) c FROM jobs').get().c;
|
const usage = (await s.db.prepare('SELECT SUM(cost_usd) c FROM jobs').get()).c;
|
||||||
assert.ok(usage > 0);
|
assert.ok(usage > 0);
|
||||||
} finally { rmSync(s.tmp, { recursive: true, force: true }); }
|
} finally { rmSync(s.tmp, { recursive: true, force: true }); }
|
||||||
});
|
});
|
||||||
|
|
@ -164,18 +165,18 @@ test('URL Git Forgejo', () => {
|
||||||
});
|
});
|
||||||
|
|
||||||
test('envoi : Message-ID journalisé et objets A/B alternés équitablement', async () => {
|
test('envoi : Message-ID journalisé et objets A/B alternés équitablement', async () => {
|
||||||
const s = setup();
|
const s = await setup();
|
||||||
try {
|
try {
|
||||||
saveSecretConfig(s.app, s.id, 'smtp_enc', { host: 'smtp.x', port: 587, user: 'u', pass: 'p', fromEmail: 'tony@codebzh.fr' }, 'pass');
|
await 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)
|
await 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());
|
VALUES(?, 'initial', 'Objet A {{entreprise}}', 'Objet B {{entreprise}}', 'Bonjour', 'validated', ?)`).run(s.id, now());
|
||||||
for (const n of [1, 2, 3, 4]) {
|
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());
|
await 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 });
|
const job = await run(s, 'send', { count: 4 });
|
||||||
assert.equal(job.status, 'done', job.error);
|
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']);
|
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();
|
const logs = await s.db.prepare("SELECT * FROM mail_log WHERE kind = 'initial' ORDER BY id").all();
|
||||||
assert.equal(logs.length, 4);
|
assert.equal(logs.length, 4);
|
||||||
for (const [i, l] of logs.entries()) {
|
for (const [i, l] of logs.entries()) {
|
||||||
assert.equal(l.message_id, s.sentMails[i].messageId);
|
assert.equal(l.message_id, s.sentMails[i].messageId);
|
||||||
|
|
@ -183,25 +184,25 @@ test('envoi : Message-ID journalisé et objets A/B alternés équitablement', as
|
||||||
assert.equal(l.subject, s.sentMails[i].subject);
|
assert.equal(l.subject, s.sentMails[i].subject);
|
||||||
}
|
}
|
||||||
assert.equal(new Set(logs.map((l) => l.message_id)).size, 4, 'Message-ID uniques');
|
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']);
|
assert.deepEqual((await 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 }); }
|
} finally { rmSync(s.tmp, { recursive: true, force: true }); }
|
||||||
});
|
});
|
||||||
|
|
||||||
test('sans objet B : tout part en A', () => {
|
test('sans objet B : tout part en A', async () => {
|
||||||
const db = openDb(':memory:');
|
const db = await testDb();
|
||||||
assert.equal(pickVariant(db, 1, { subject_b: null }), 'A');
|
assert.equal(await pickVariant(db, 1, { subject_b: null }), 'A');
|
||||||
assert.equal(pickVariant(db, 1, { subject_b: '' }), 'A');
|
assert.equal(await pickVariant(db, 1, { subject_b: '' }), 'A');
|
||||||
});
|
});
|
||||||
|
|
||||||
test('analyse : modèle économique (Haiku) par défaut, Sonnet uniquement sur demande', async () => {
|
test('analyse : modèle économique (Haiku) par défaut, Sonnet uniquement sur demande', async () => {
|
||||||
const s = setup();
|
const s = await setup();
|
||||||
const spyFile = join(s.tmp, 'models.log');
|
const spyFile = join(s.tmp, 'models.log');
|
||||||
s.app.cfg.claudeBin = resolve('test/fixtures/spy-claude.js');
|
s.app.cfg.claudeBin = resolve('test/fixtures/spy-claude.js');
|
||||||
process.env.MODEL_SPY_FILE = spyFile;
|
process.env.MODEL_SPY_FILE = spyFile;
|
||||||
try {
|
try {
|
||||||
const a = await run(s, 'analyze');
|
const a = await run(s, 'analyze');
|
||||||
assert.equal(a.status, 'done', a.error);
|
assert.equal(a.status, 'done', a.error);
|
||||||
setSetting(s.db, 'analyze_model', 'sonnet');
|
await setSetting(s.db, 'analyze_model', 'sonnet');
|
||||||
const a2 = await run(s, 'analyze');
|
const a2 = await run(s, 'analyze');
|
||||||
assert.equal(a2.status, 'done', a2.error);
|
assert.equal(a2.status, 'done', a2.error);
|
||||||
assert.deepEqual(readFileSync(spyFile, 'utf8').trim().split('\n'), ['haiku', 'sonnet']);
|
assert.deepEqual(readFileSync(spyFile, 'utf8').trim().split('\n'), ['haiku', 'sonnet']);
|
||||||
|
|
@ -209,11 +210,11 @@ test('analyse : modèle économique (Haiku) par défaut, Sonnet uniquement sur d
|
||||||
});
|
});
|
||||||
|
|
||||||
test('quota Claude serré : alerte Discord à 80 %, pas en dessous', async () => {
|
test('quota Claude serré : alerte Discord à 80 %, pas en dessous', async () => {
|
||||||
const s = setup();
|
const s = await setup();
|
||||||
const sent = [];
|
const sent = [];
|
||||||
s.app.fetch = async (url, opts) => { sent.push({ url, body: JSON.parse(opts.body) }); return { ok: true, status: 204 }; };
|
s.app.fetch = async (url, opts) => { sent.push({ url, body: JSON.parse(opts.body) }); return { ok: true, status: 204 }; };
|
||||||
const hook = 'https://discord.com/api/webhooks/123456789012345678/abcdefghijklmnopqrstuvwxyz-ABC_123';
|
const hook = 'https://discord.com/api/webhooks/123456789012345678/abcdefghijklmnopqrstuvwxyz-ABC_123';
|
||||||
setSetting(s.db, 'discord_webhook_enc', encrypt(s.app.cfg.secretKey, hook));
|
await setSetting(s.db, 'discord_webhook_enc', encrypt(s.app.cfg.secretKey, hook));
|
||||||
try {
|
try {
|
||||||
const a = await run(s, 'analyze'); // fake-claude : 33 % / 50 % par défaut
|
const a = await run(s, 'analyze'); // fake-claude : 33 % / 50 % par défaut
|
||||||
assert.equal(a.status, 'done', a.error);
|
assert.equal(a.status, 'done', a.error);
|
||||||
|
|
|
||||||
|
|
@ -4,7 +4,8 @@ import { randomBytes } from 'node:crypto';
|
||||||
import { mkdtempSync, rmSync } from 'node:fs';
|
import { mkdtempSync, rmSync } from 'node:fs';
|
||||||
import { tmpdir } from 'node:os';
|
import { tmpdir } from 'node:os';
|
||||||
import { join } from 'node:path';
|
import { join } from 'node:path';
|
||||||
import { openDb, now, setSetting } from '../src/db.js';
|
import { now, setSetting } from '../src/db.js';
|
||||||
|
import { testDb } from './helpers/db.js';
|
||||||
import { createApp } from '../src/server.js';
|
import { createApp } from '../src/server.js';
|
||||||
import { unsubToken } from '../src/crypto.js';
|
import { unsubToken } from '../src/crypto.js';
|
||||||
|
|
||||||
|
|
@ -17,10 +18,10 @@ before(async () => {
|
||||||
appUrl: APP_URL, google: { clientId: 'cid', clientSecret: 'cs' }, allowedEmails: ['me@gmail.com'],
|
appUrl: APP_URL, google: { clientId: 'cid', clientSecret: 'cs' }, allowedEmails: ['me@gmail.com'],
|
||||||
secretKey: randomBytes(32), dataDir: tmp, claudeBin: 'claude', thermalMax: 75,
|
secretKey: randomBytes(32), dataDir: tmp, claudeBin: 'claude', thermalMax: 75,
|
||||||
};
|
};
|
||||||
app = createApp(cfg, { db: openDb(':memory:'), worker: false });
|
app = await createApp(cfg, { db: await testDb(), worker: false });
|
||||||
await new Promise((r) => app.server.listen(0, '127.0.0.1', r));
|
await new Promise((r) => app.server.listen(0, '127.0.0.1', r));
|
||||||
base = `http://127.0.0.1:${app.server.address().port}`;
|
base = `http://127.0.0.1:${app.server.address().port}`;
|
||||||
app.db.prepare('INSERT INTO sessions(id, email, created_at, expires_at) VALUES(?, ?, ?, ?)').run('sess1', 'me@gmail.com', now(), now() + 3600);
|
await app.db.prepare('INSERT INTO sessions(id, email, created_at, expires_at) VALUES(?, ?, ?, ?)').run('sess1', 'me@gmail.com', now(), now() + 3600);
|
||||||
cookie = 'sid=sess1';
|
cookie = 'sid=sess1';
|
||||||
});
|
});
|
||||||
after(async () => { await app.close(); rmSync(tmp, { recursive: true, force: true }); });
|
after(async () => { await app.close(); rmSync(tmp, { recursive: true, force: true }); });
|
||||||
|
|
@ -79,13 +80,13 @@ test('dashboard, réglages, création de projet et statut', async () => {
|
||||||
|
|
||||||
r = await post('/settings', { notify_email: 'moi@x.fr', forgejo_host: 'https://git.tony-averty.dev/', forgejo_token: 'tok123', global_daily_cap: '9999', send_delay_min: '1', send_delay_max: '2', prospect_model: 'opus', analyze_model: 'opus' }, { form: true });
|
r = await post('/settings', { notify_email: 'moi@x.fr', forgejo_host: 'https://git.tony-averty.dev/', forgejo_token: 'tok123', global_daily_cap: '9999', send_delay_min: '1', send_delay_max: '2', prospect_model: 'opus', analyze_model: 'opus' }, { form: true });
|
||||||
assert.equal(r.status, 303);
|
assert.equal(r.status, 303);
|
||||||
const s = (k) => app.db.prepare('SELECT value FROM settings WHERE key = ?').get(k)?.value;
|
const s = async (k) => (await app.db.prepare('SELECT value FROM settings WHERE `key` = ?').get(k))?.value;
|
||||||
assert.equal(s('forgejo_host'), 'git.tony-averty.dev');
|
assert.equal(await s('forgejo_host'), 'git.tony-averty.dev');
|
||||||
assert.equal(s('global_daily_cap'), '300', 'plafond borné');
|
assert.equal(await s('global_daily_cap'), '300', 'plafond borné');
|
||||||
assert.equal(s('send_delay_min'), '5');
|
assert.equal(await s('send_delay_min'), '5');
|
||||||
assert.equal(s('prospect_model'), 'haiku', 'opus refusé pour la prospection');
|
assert.equal(await s('prospect_model'), 'haiku', 'opus refusé pour la prospection');
|
||||||
assert.equal(s('analyze_model'), 'haiku', 'opus refusé pour l\'analyse');
|
assert.equal(await s('analyze_model'), 'haiku', 'opus refusé pour l\'analyse');
|
||||||
assert.ok(!s('forgejo_token_enc').includes('tok123'), 'token chiffré');
|
assert.ok(!(await s('forgejo_token_enc')).includes('tok123'), 'token chiffré');
|
||||||
|
|
||||||
r = await post('/api/projects', { name: 'MEP', gitUrl: 'https://github.com/Tony/MEP.git' });
|
r = await post('/api/projects', { name: 'MEP', gitUrl: 'https://github.com/Tony/MEP.git' });
|
||||||
assert.equal(r.status, 400);
|
assert.equal(r.status, 400);
|
||||||
|
|
@ -107,7 +108,7 @@ test('dashboard, réglages, création de projet et statut', async () => {
|
||||||
assert.equal(r.status, 200);
|
assert.equal(r.status, 200);
|
||||||
r = await post(`/api/projects/${id}/prospect`, { count: 999 });
|
r = await post(`/api/projects/${id}/prospect`, { count: 999 });
|
||||||
assert.equal(r.status, 200);
|
assert.equal(r.status, 200);
|
||||||
const job = app.db.prepare("SELECT params_json FROM jobs WHERE type = 'prospect'").get();
|
const job = await app.db.prepare("SELECT params_json FROM jobs WHERE type = 'prospect'").get();
|
||||||
assert.equal(JSON.parse(job.params_json).count, 50, 'borné à 50');
|
assert.equal(JSON.parse(job.params_json).count, 50, 'borné à 50');
|
||||||
|
|
||||||
r = await post(`/api/projects/${id}/send`, { count: 5 });
|
r = await post(`/api/projects/${id}/send`, { count: 5 });
|
||||||
|
|
@ -119,7 +120,7 @@ test('dashboard, réglages, création de projet et statut', async () => {
|
||||||
assert.equal(r.status, 400);
|
assert.equal(r.status, 400);
|
||||||
r = await post(`/api/projects/${id}/smtp`, { host: 'smtp.x', user: 'u', pass: 'secretpass', fromEmail: 'a@x.fr', dailyCap: 5000 });
|
r = await post(`/api/projects/${id}/smtp`, { host: 'smtp.x', user: 'u', pass: 'secretpass', fromEmail: 'a@x.fr', dailyCap: 5000 });
|
||||||
assert.equal(r.status, 200);
|
assert.equal(r.status, 200);
|
||||||
const row = app.db.prepare('SELECT smtp_enc, daily_mail_cap FROM projects WHERE id = ?').get(id);
|
const row = await app.db.prepare('SELECT smtp_enc, daily_mail_cap FROM projects WHERE id = ?').get(id);
|
||||||
assert.ok(!row.smtp_enc.includes('secretpass'));
|
assert.ok(!row.smtp_enc.includes('secretpass'));
|
||||||
assert.equal(row.daily_mail_cap, 200);
|
assert.equal(row.daily_mail_cap, 200);
|
||||||
|
|
||||||
|
|
@ -138,17 +139,17 @@ test('désinscription : GET confirme, POST blackliste, token forgé refusé', as
|
||||||
let r = await get(`/u/${encodeURIComponent(email)}/${tok}`, false);
|
let r = await get(`/u/${encodeURIComponent(email)}/${tok}`, false);
|
||||||
assert.equal(r.status, 200);
|
assert.equal(r.status, 200);
|
||||||
assert.match(await r.text(), /Confirmer/);
|
assert.match(await r.text(), /Confirmer/);
|
||||||
assert.equal(app.db.prepare('SELECT COUNT(*) n FROM blacklist').get().n, 0);
|
assert.equal((await app.db.prepare('SELECT COUNT(*) n FROM blacklist').get()).n, 0);
|
||||||
r = await post(`/u/${encodeURIComponent(email)}/${tok}`, 'List-Unsubscribe=One-Click', { auth: false, origin: null, form: true });
|
r = await post(`/u/${encodeURIComponent(email)}/${tok}`, 'List-Unsubscribe=One-Click', { auth: false, origin: null, form: true });
|
||||||
assert.equal(r.status, 200);
|
assert.equal(r.status, 200);
|
||||||
assert.equal(app.db.prepare('SELECT COUNT(*) n FROM blacklist WHERE email = ?').get(email).n, 1);
|
assert.equal((await app.db.prepare('SELECT COUNT(*) n FROM blacklist WHERE email = ?').get(email)).n, 1);
|
||||||
r = await post(`/u/${encodeURIComponent(email)}/faux`, {}, { auth: false, origin: null });
|
r = await post(`/u/${encodeURIComponent(email)}/faux`, {}, { auth: false, origin: null });
|
||||||
assert.equal(r.status, 400);
|
assert.equal(r.status, 400);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('SECRET_KEY changée : le panel reste utilisable, les secrets sont à ressaisir', async () => {
|
test('SECRET_KEY changée : le panel reste utilisable, les secrets sont à ressaisir', async () => {
|
||||||
const id = app.db.prepare('SELECT id FROM projects LIMIT 1').get().id;
|
const id = (await app.db.prepare('SELECT id FROM projects LIMIT 1').get()).id;
|
||||||
app.db.prepare('UPDATE projects SET smtp_enc = ? WHERE id = ?').run('v1:AAAA:BBBB:CCCC', id);
|
await app.db.prepare('UPDATE projects SET smtp_enc = ? WHERE id = ?').run('v1:AAAA:BBBB:CCCC', id);
|
||||||
const warn = console.warn; console.warn = () => {};
|
const warn = console.warn; console.warn = () => {};
|
||||||
try {
|
try {
|
||||||
let r = await get('/');
|
let r = await get('/');
|
||||||
|
|
@ -164,11 +165,11 @@ test('SECRET_KEY changée : le panel reste utilisable, les secrets sont à ressa
|
||||||
});
|
});
|
||||||
|
|
||||||
test('« Cette nuit » programme le job au prochain créneau 1h-6h', async () => {
|
test('« Cette nuit » programme le job au prochain créneau 1h-6h', async () => {
|
||||||
const id = app.db.prepare('SELECT id FROM projects LIMIT 1').get().id;
|
const id = (await app.db.prepare('SELECT id FROM projects LIMIT 1').get()).id;
|
||||||
app.db.prepare("UPDATE jobs SET status = 'cancelled' WHERE status IN ('queued', 'running')").run();
|
await app.db.prepare("UPDATE jobs SET status = 'cancelled' WHERE status IN ('queued', 'running')").run();
|
||||||
const r = await post(`/api/projects/${id}/evolution`, { count: 3, level: 'rapide', when: 'night' });
|
const r = await post(`/api/projects/${id}/evolution`, { count: 3, level: 'rapide', when: 'night' });
|
||||||
assert.equal(r.status, 200);
|
assert.equal(r.status, 200);
|
||||||
const job = app.db.prepare("SELECT run_after FROM jobs WHERE type = 'evolution' ORDER BY id DESC LIMIT 1").get();
|
const job = await app.db.prepare("SELECT run_after FROM jobs WHERE type = 'evolution' ORDER BY id DESC LIMIT 1").get();
|
||||||
const { parisParts } = await import('../src/services/paris-time.js');
|
const { parisParts } = await import('../src/services/paris-time.js');
|
||||||
const p = parisParts(new Date(job.run_after * 1000));
|
const p = parisParts(new Date(job.run_after * 1000));
|
||||||
assert.ok(p.hour >= 1 && p.hour < 6, `démarrage à ${p.hour}h`);
|
assert.ok(p.hour >= 1 && p.hour < 6, `démarrage à ${p.hour}h`);
|
||||||
|
|
@ -188,42 +189,42 @@ test('réglages Discord : URL validée, chiffrée, événements enregistrés', a
|
||||||
const hook = 'https://discord.com/api/webhooks/123456789012345678/abcdefghijklmnopqrstuvwxyz-ABC_123';
|
const hook = 'https://discord.com/api/webhooks/123456789012345678/abcdefghijklmnopqrstuvwxyz-ABC_123';
|
||||||
r = await post('/settings', { ...base, discord_webhook: hook, ev_reply: 'on', ev_job_error: 'on' }, { form: true });
|
r = await post('/settings', { ...base, discord_webhook: hook, ev_reply: 'on', ev_job_error: 'on' }, { form: true });
|
||||||
assert.equal(r.status, 303);
|
assert.equal(r.status, 303);
|
||||||
const enc = app.db.prepare("SELECT value FROM settings WHERE key = 'discord_webhook_enc'").get().value;
|
const enc = (await app.db.prepare("SELECT value FROM settings WHERE `key` = 'discord_webhook_enc'").get()).value;
|
||||||
assert.ok(!enc.includes('abcdefghijklmnop'), 'URL chiffrée');
|
assert.ok(!enc.includes('abcdefghijklmnop'), 'URL chiffrée');
|
||||||
assert.deepEqual(JSON.parse(app.db.prepare("SELECT value FROM settings WHERE key = 'discord_events'").get().value), ['job_error', 'reply']);
|
assert.deepEqual(JSON.parse((await app.db.prepare("SELECT value FROM settings WHERE `key` = 'discord_events'").get()).value), ['job_error', 'reply']);
|
||||||
r = await get('/settings');
|
r = await get('/settings');
|
||||||
const page = await r.text();
|
const page = await r.text();
|
||||||
assert.ok(!page.includes('abcdefghijklmnop'), 'URL jamais réaffichée');
|
assert.ok(!page.includes('abcdefghijklmnop'), 'URL jamais réaffichée');
|
||||||
assert.match(page, /data-notify-test/);
|
assert.match(page, /data-notify-test/);
|
||||||
r = await post('/settings', { ...base, discord_remove: 'on' }, { form: true });
|
r = await post('/settings', { ...base, discord_remove: 'on' }, { form: true });
|
||||||
assert.equal(app.db.prepare("SELECT value FROM settings WHERE key = 'discord_webhook_enc'").get().value, null);
|
assert.equal((await app.db.prepare("SELECT value FROM settings WHERE `key` = 'discord_webhook_enc'").get()).value, null);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('budget : réglages, jauge et avertissement au lancement', async () => {
|
test('budget : réglages, jauge et avertissement au lancement', async () => {
|
||||||
const base = { notify_email: 'moi@x.fr', forgejo_host: 'git.tony-averty.dev', global_daily_cap: '100', send_delay_min: '20', send_delay_max: '60' };
|
const base = { notify_email: 'moi@x.fr', forgejo_host: 'git.tony-averty.dev', global_daily_cap: '100', send_delay_min: '20', send_delay_max: '60' };
|
||||||
let r = await post('/settings', { ...base, budget_day_usd: '0,5', budget_month_usd: 'abc' }, { form: true });
|
let r = await post('/settings', { ...base, budget_day_usd: '0,5', budget_month_usd: 'abc' }, { form: true });
|
||||||
assert.equal(r.status, 303);
|
assert.equal(r.status, 303);
|
||||||
const s = (k) => app.db.prepare('SELECT value FROM settings WHERE key = ?').get(k)?.value;
|
const s = async (k) => (await app.db.prepare('SELECT value FROM settings WHERE `key` = ?').get(k))?.value;
|
||||||
assert.equal(s('budget_day_usd'), '0.5', 'virgule française acceptée');
|
assert.equal(await s('budget_day_usd'), '0.5', 'virgule française acceptée');
|
||||||
assert.equal(s('budget_month_usd'), '', 'valeur invalide = pas de limite');
|
assert.equal(await s('budget_month_usd'), '', 'valeur invalide = pas de limite');
|
||||||
app.db.prepare("INSERT INTO jobs(type, status, cost_usd, created_at, finished_at) VALUES('evolution', 'done', 0.8, ?, ?)").run(now(), now());
|
await app.db.prepare("INSERT INTO jobs(type, status, cost_usd, created_at, finished_at) VALUES('evolution', 'done', 0.8, ?, ?)").run(now(), now());
|
||||||
let sys = await (await get('/api/system')).json();
|
let sys = await (await get('/api/system')).json();
|
||||||
assert.equal(sys.budget.blocked, true);
|
assert.equal(sys.budget.blocked, true);
|
||||||
assert.equal(sys.claudeRateLimit, null, 'pas encore mesuré sans appel Claude');
|
assert.equal(sys.claudeRateLimit, null, 'pas encore mesuré sans appel Claude');
|
||||||
setSetting(app.db, 'claude_rate_limit_json', JSON.stringify({ at: now(), fiveHour: { utilization: 0.42, resetsAt: 123 }, sevenDay: { utilization: 0.1, resetsAt: 456 } }));
|
await setSetting(app.db, 'claude_rate_limit_json', JSON.stringify({ at: now(), fiveHour: { utilization: 0.42, resetsAt: 123 }, sevenDay: { utilization: 0.1, resetsAt: 456 } }));
|
||||||
sys = await (await get('/api/system')).json();
|
sys = await (await get('/api/system')).json();
|
||||||
assert.equal(sys.claudeRateLimit.fiveHour.utilization, 0.42);
|
assert.equal(sys.claudeRateLimit.fiveHour.utilization, 0.42);
|
||||||
assert.equal(sys.claudeRateLimit.sevenDay.utilization, 0.1);
|
assert.equal(sys.claudeRateLimit.sevenDay.utilization, 0.1);
|
||||||
const id = app.db.prepare('SELECT id FROM projects LIMIT 1').get().id;
|
const id = (await app.db.prepare('SELECT id FROM projects LIMIT 1').get()).id;
|
||||||
app.db.prepare("UPDATE jobs SET status = 'cancelled' WHERE status IN ('queued', 'running')").run();
|
await app.db.prepare("UPDATE jobs SET status = 'cancelled' WHERE status IN ('queued', 'running')").run();
|
||||||
r = await post(`/api/projects/${id}/evolution`, { count: 2, level: 'rapide' });
|
r = await post(`/api/projects/${id}/evolution`, { count: 2, level: 'rapide' });
|
||||||
assert.match((await r.json()).budgetBlocked, /budget IA des dernières 24 h atteint/);
|
assert.match((await r.json()).budgetBlocked, /budget IA des dernières 24 h atteint/);
|
||||||
await post('/settings', { ...base, budget_day_usd: '' }, { form: true });
|
await post('/settings', { ...base, budget_day_usd: '' }, { form: true });
|
||||||
});
|
});
|
||||||
|
|
||||||
test('fiche prospect : routes notes et prochaine action', async () => {
|
test('fiche prospect : routes notes et prochaine action', async () => {
|
||||||
const pid = app.db.prepare('SELECT id FROM projects LIMIT 1').get().id;
|
const pid = (await app.db.prepare('SELECT id FROM projects LIMIT 1').get()).id;
|
||||||
const id = Number(app.db.prepare("INSERT INTO prospects(project_id, company, email, website, created_at) VALUES(?, 'Atelier', 'a@atelier.fr', 'javascript:alert(1)', ?)").run(pid, now()).lastInsertRowid);
|
const id = Number((await app.db.prepare("INSERT INTO prospects(project_id, company, email, website, created_at) VALUES(?, 'Atelier', 'a@atelier.fr', 'javascript:alert(1)', ?)").run(pid, now())).lastInsertRowid);
|
||||||
let r = await post(`/api/prospects/${id}/notes`, { body: '<script>x</script>' });
|
let r = await post(`/api/prospects/${id}/notes`, { body: '<script>x</script>' });
|
||||||
assert.equal(r.status, 200);
|
assert.equal(r.status, 200);
|
||||||
r = await post(`/api/prospects/${id}/notes`, { body: '' });
|
r = await post(`/api/prospects/${id}/notes`, { body: '' });
|
||||||
|
|
@ -244,7 +245,7 @@ test('fiche prospect : routes notes et prochaine action', async () => {
|
||||||
});
|
});
|
||||||
|
|
||||||
test('CSV : export en pièce jointe, import via l\'API', async () => {
|
test('CSV : export en pièce jointe, import via l\'API', async () => {
|
||||||
const pid = app.db.prepare('SELECT id FROM projects LIMIT 1').get().id;
|
const pid = (await app.db.prepare('SELECT id FROM projects LIMIT 1').get()).id;
|
||||||
let r = await get(`/api/projects/${pid}/prospects.csv?q=atelier`);
|
let r = await get(`/api/projects/${pid}/prospects.csv?q=atelier`);
|
||||||
assert.equal(r.status, 200);
|
assert.equal(r.status, 200);
|
||||||
assert.match(r.headers.get('content-type'), /text\/csv/);
|
assert.match(r.headers.get('content-type'), /text\/csv/);
|
||||||
|
|
|
||||||
|
|
@ -3,7 +3,9 @@
|
||||||
import { test } from 'node:test';
|
import { test } from 'node:test';
|
||||||
import assert from 'node:assert/strict';
|
import assert from 'node:assert/strict';
|
||||||
import { randomBytes } from 'node:crypto';
|
import { randomBytes } from 'node:crypto';
|
||||||
import { openDb, now } from '../src/db.js';
|
import { now } from '../src/db.js';
|
||||||
|
import { testDb } from './helpers/db.js';
|
||||||
|
|
||||||
import { checkInbox } from '../src/services/inbox.js';
|
import { checkInbox } from '../src/services/inbox.js';
|
||||||
import { createProject, saveSecretConfig, getProject } from '../src/projects.js';
|
import { createProject, saveSecretConfig, getProject } from '../src/projects.js';
|
||||||
|
|
||||||
|
|
@ -11,27 +13,27 @@ const live = process.env.IMAP_TEST;
|
||||||
|
|
||||||
test('checkInbox sur un vrai serveur IMAP', { skip: !live && 'IMAP_TEST non défini' }, async () => {
|
test('checkInbox sur un vrai serveur IMAP', { skip: !live && 'IMAP_TEST non défini' }, async () => {
|
||||||
const [host, port, user, pass] = live.split(':');
|
const [host, port, user, pass] = live.split(':');
|
||||||
const db = openDb(':memory:');
|
const db = await testDb();
|
||||||
const app = { db, cfg: { secretKey: randomBytes(32) } };
|
const app = { db, cfg: { secretKey: randomBytes(32) } };
|
||||||
const id = createProject(app, { name: 'P', gitUrl: 'https://git.x/T/P.git' });
|
const id = await createProject(app, { name: 'P', gitUrl: 'https://git.x/T/P.git' });
|
||||||
saveSecretConfig(app, id, 'smtp_enc', { host: 'smtp.x', user, pass, fromEmail: user }, 'pass');
|
await saveSecretConfig(app, id, 'smtp_enc', { host: 'smtp.x', user, pass, fromEmail: user }, 'pass');
|
||||||
saveSecretConfig(app, id, 'imap_enc', { host, port: Number(port), user: '', pass: '' }, 'pass');
|
await saveSecretConfig(app, id, 'imap_enc', { host, port: Number(port), user: '', pass: '' }, 'pass');
|
||||||
const add = (email, msgId) => {
|
const add = async (email, msgId) => {
|
||||||
const pid = Number(db.prepare("INSERT INTO prospects(project_id, company, email, status, sent_at, created_at) VALUES(?, 'X', ?, 'sent', ?, ?)")
|
const pid = Number((await db.prepare("INSERT INTO prospects(project_id, company, email, status, sent_at, created_at) VALUES(?, 'X', ?, 'sent', ?, ?)")
|
||||||
.run(id, email, now() - 86400 * 30, now()).lastInsertRowid);
|
.run(id, email, now() - 86400 * 30, now())).lastInsertRowid);
|
||||||
db.prepare("INSERT INTO mail_log(project_id, prospect_id, email, sent_at, kind, message_id) VALUES(?, ?, ?, ?, 'initial', ?)")
|
await db.prepare("INSERT INTO mail_log(project_id, prospect_id, email, sent_at, kind, message_id) VALUES(?, ?, ?, ?, 'initial', ?)")
|
||||||
.run(id, pid, email, now() - 86400 * 30, msgId);
|
.run(id, pid, email, now() - 86400 * 30, msgId);
|
||||||
return pid;
|
return pid;
|
||||||
};
|
};
|
||||||
const fournil = add('contact@fournil.fr', '<m1@codebzh.fr>');
|
const fournil = await add('contact@fournil.fr', '<m1@codebzh.fr>');
|
||||||
const zen = add('hello@zen.fr', '<m2@codebzh.fr>');
|
const zen = await add('hello@zen.fr', '<m2@codebzh.fr>');
|
||||||
const ferme = add('contact@ferme.fr', '<m3@codebzh.fr>');
|
const ferme = await add('contact@ferme.fr', '<m3@codebzh.fr>');
|
||||||
|
|
||||||
assert.deepEqual(await checkInbox(app, id), { replies: 1, bounces: 1, ignored: 2 });
|
assert.deepEqual(await checkInbox(app, id), { replies: 1, bounces: 1, ignored: 2 });
|
||||||
const st = (pid) => db.prepare('SELECT status FROM prospects WHERE id = ?').get(pid).status;
|
const st = async (pid) => (await db.prepare('SELECT status FROM prospects WHERE id = ?').get(pid)).status;
|
||||||
assert.equal(st(fournil), 'replied');
|
assert.equal(await st(fournil), 'replied');
|
||||||
assert.equal(st(zen), 'sent', 'une absence n\'est pas une réponse');
|
assert.equal(await st(zen), 'sent', 'une absence n\'est pas une réponse');
|
||||||
assert.equal(st(ferme), 'bounced');
|
assert.equal(await st(ferme), 'bounced');
|
||||||
assert.deepEqual(await checkInbox(app, id), { replies: 0, bounces: 0, ignored: 0 }, 'rien de relu');
|
assert.deepEqual(await checkInbox(app, id), { replies: 0, bounces: 0, ignored: 0 }, 'rien de relu');
|
||||||
assert.equal(getProject(app, id).inbox.lastUid, 4);
|
assert.equal((await getProject(app, id)).inbox.lastUid, 4);
|
||||||
});
|
});
|
||||||
|
|
|
||||||
|
|
@ -1,20 +1,22 @@
|
||||||
import { test } from 'node:test';
|
import { test } from 'node:test';
|
||||||
import assert from 'node:assert/strict';
|
import assert from 'node:assert/strict';
|
||||||
import { randomBytes } from 'node:crypto';
|
import { randomBytes } from 'node:crypto';
|
||||||
import { openDb, now } from '../src/db.js';
|
import { now } from '../src/db.js';
|
||||||
|
import { testDb } from './helpers/db.js';
|
||||||
|
|
||||||
import { parseHeaders, classify, applyMessages, checkInbox } from '../src/services/inbox.js';
|
import { parseHeaders, classify, applyMessages, checkInbox } from '../src/services/inbox.js';
|
||||||
import { createProject, saveSecretConfig, getProject, imapCredentials } from '../src/projects.js';
|
import { createProject, saveSecretConfig, getProject, imapCredentials } from '../src/projects.js';
|
||||||
|
|
||||||
function setup() {
|
async function setup() {
|
||||||
const db = openDb(':memory:');
|
const db = await testDb();
|
||||||
const app = { db, cfg: { secretKey: randomBytes(32) } };
|
const app = { db, cfg: { secretKey: randomBytes(32) } };
|
||||||
const id = createProject(app, { name: 'P', gitUrl: 'https://git.x/T/P.git' });
|
const id = await createProject(app, { name: 'P', gitUrl: 'https://git.x/T/P.git' });
|
||||||
const add = (company, email, msgId, status = 'sent') => {
|
const add = async (company, email, msgId, status = 'sent') => {
|
||||||
const r = db.prepare('INSERT INTO prospects(project_id, company, email, status, sent_at, created_at) VALUES(?, ?, ?, ?, ?, ?)')
|
const r = await db.prepare('INSERT INTO prospects(project_id, company, email, status, sent_at, created_at) VALUES(?, ?, ?, ?, ?, ?)')
|
||||||
.run(id, company, email, status, now(), now());
|
.run(id, company, email, status, now(), now());
|
||||||
const pid = Number(r.lastInsertRowid);
|
const pid = Number(r.lastInsertRowid);
|
||||||
if (msgId) {
|
if (msgId) {
|
||||||
db.prepare("INSERT INTO mail_log(project_id, prospect_id, email, sent_at, kind, message_id) VALUES(?, ?, ?, ?, 'initial', ?)")
|
await db.prepare("INSERT INTO mail_log(project_id, prospect_id, email, sent_at, kind, message_id) VALUES(?, ?, ?, ?, 'initial', ?)")
|
||||||
.run(id, pid, email, now(), msgId);
|
.run(id, pid, email, now(), msgId);
|
||||||
}
|
}
|
||||||
return pid;
|
return pid;
|
||||||
|
|
@ -42,36 +44,36 @@ test('classify : réponse, réponse automatique, bounce', () => {
|
||||||
assert.equal(classify({ from: 'x@y.fr', subject: 'Rapport', headers: { 'content-type': 'multipart/report; report-type=delivery-status' } }).type, 'bounce');
|
assert.equal(classify({ from: 'x@y.fr', subject: 'Rapport', headers: { 'content-type': 'multipart/report; report-type=delivery-status' } }).type, 'bounce');
|
||||||
});
|
});
|
||||||
|
|
||||||
test('réponse rattachée par le fil (In-Reply-To), même depuis une autre adresse', () => {
|
test('réponse rattachée par le fil (In-Reply-To), même depuis une autre adresse', async () => {
|
||||||
const s = setup();
|
const s = await setup();
|
||||||
const p = s.add('Fournil', 'contact@fournil.fr', '<m1@codebzh.fr>');
|
const p = await s.add('Fournil', 'contact@fournil.fr', '<m1@codebzh.fr>');
|
||||||
const r = applyMessages(s.db, s.id, [{ from: 'jean.dupont@gmail.com', subject: 'Re: Une idée', inReplyTo: '<m1@codebzh.fr>' }]);
|
const r = await applyMessages(s.db, s.id, [{ from: 'jean.dupont@gmail.com', subject: 'Re: Une idée', inReplyTo: '<m1@codebzh.fr>' }]);
|
||||||
assert.deepEqual(r, { replies: 1, bounces: 0, ignored: 0 });
|
assert.deepEqual(r, { replies: 1, bounces: 0, ignored: 0 });
|
||||||
assert.equal(s.status(p).status, 'replied');
|
assert.equal((await s.status(p)).status, 'replied');
|
||||||
assert.equal(s.status(p).reply_subject, 'Re: Une idée');
|
assert.equal((await s.status(p)).reply_subject, 'Re: Une idée');
|
||||||
assert.ok(s.status(p).replied_at > 0);
|
assert.ok((await s.status(p)).replied_at > 0);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('réponse rattachée par adresse puis par domaine pro', () => {
|
test('réponse rattachée par adresse puis par domaine pro', async () => {
|
||||||
const s = setup();
|
const s = await setup();
|
||||||
const byMail = s.add('Zen', 'hello@zen.fr', null);
|
const byMail = await s.add('Zen', 'hello@zen.fr', null);
|
||||||
const byDomain = s.add('Atelier', 'contact@atelier-bois.fr', null);
|
const byDomain = await s.add('Atelier', 'contact@atelier-bois.fr', null);
|
||||||
const r = applyMessages(s.db, s.id, [
|
const r = await applyMessages(s.db, s.id, [
|
||||||
{ from: 'Hello@Zen.fr', subject: 'Intéressé' },
|
{ from: 'Hello@Zen.fr', subject: 'Intéressé' },
|
||||||
{ from: 'marc@atelier-bois.fr', subject: 'Re: votre message' },
|
{ from: 'marc@atelier-bois.fr', subject: 'Re: votre message' },
|
||||||
]);
|
]);
|
||||||
assert.equal(r.replies, 2);
|
assert.equal(r.replies, 2);
|
||||||
assert.equal(s.status(byMail).status, 'replied');
|
assert.equal((await s.status(byMail)).status, 'replied');
|
||||||
assert.equal(s.status(byDomain).status, 'replied');
|
assert.equal((await s.status(byDomain)).status, 'replied');
|
||||||
});
|
});
|
||||||
|
|
||||||
test('pas de faux positif : webmail générique, domaine ambigu, réponse auto, statut déjà traité', () => {
|
test('pas de faux positif : webmail générique, domaine ambigu, réponse auto, statut déjà traité', async () => {
|
||||||
const s = setup();
|
const s = await setup();
|
||||||
const g = s.add('Perso', 'boulanger.rennes@gmail.com', null);
|
const g = await s.add('Perso', 'boulanger.rennes@gmail.com', null);
|
||||||
const a1 = s.add('Groupe A', 'rennes@groupe.fr', null);
|
const a1 = await s.add('Groupe A', 'rennes@groupe.fr', null);
|
||||||
const a2 = s.add('Groupe B', 'nantes@groupe.fr', null);
|
const a2 = await s.add('Groupe B', 'nantes@groupe.fr', null);
|
||||||
const client = s.add('Déjà client', 'boss@client.fr', null, 'client');
|
const client = await s.add('Déjà client', 'boss@client.fr', null, 'client');
|
||||||
const r = applyMessages(s.db, s.id, [
|
const r = await applyMessages(s.db, s.id, [
|
||||||
{ from: 'autre@gmail.com', subject: 'Re: ?' }, // gmail : on ne devine pas
|
{ from: 'autre@gmail.com', subject: 'Re: ?' }, // gmail : on ne devine pas
|
||||||
{ from: 'direction@groupe.fr', subject: 'Re: ?' }, // 2 prospects sur ce domaine
|
{ from: 'direction@groupe.fr', subject: 'Re: ?' }, // 2 prospects sur ce domaine
|
||||||
{ from: 'boulanger.rennes@gmail.com', subject: 'Absence', headers: {} },
|
{ from: 'boulanger.rennes@gmail.com', subject: 'Absence', headers: {} },
|
||||||
|
|
@ -79,18 +81,18 @@ test('pas de faux positif : webmail générique, domaine ambigu, réponse auto,
|
||||||
{ from: 'inconnu@ailleurs.fr', subject: 'Spam' },
|
{ from: 'inconnu@ailleurs.fr', subject: 'Spam' },
|
||||||
]);
|
]);
|
||||||
assert.deepEqual(r, { replies: 0, bounces: 0, ignored: 5 });
|
assert.deepEqual(r, { replies: 0, bounces: 0, ignored: 5 });
|
||||||
for (const pid of [g, a1, a2]) assert.equal(s.status(pid).status, 'sent');
|
for (const pid of [g, a1, a2]) assert.equal((await s.status(pid)).status, 'sent');
|
||||||
assert.equal(s.status(client).status, 'client');
|
assert.equal((await s.status(client)).status, 'client');
|
||||||
});
|
});
|
||||||
|
|
||||||
test('bounce : prospect rejeté + liste d\'opposition, et traitement idempotent', () => {
|
test('bounce : prospect rejeté + liste d\'opposition, et traitement idempotent', async () => {
|
||||||
const s = setup();
|
const s = await setup();
|
||||||
const p = s.add('Fermé', 'contact@ferme-definitivement.fr', '<m9@codebzh.fr>');
|
const p = await s.add('Fermé', 'contact@ferme-definitivement.fr', '<m9@codebzh.fr>');
|
||||||
const bounce = { from: 'mailer-daemon@mx.ovh.net', subject: 'Mail delivery failed', body: 'Message-ID: <m9@codebzh.fr>\n550 user unknown' };
|
const bounce = { from: 'mailer-daemon@mx.ovh.net', subject: 'Mail delivery failed', body: 'Message-ID: <m9@codebzh.fr>\n550 user unknown' };
|
||||||
assert.equal(applyMessages(s.db, s.id, [bounce]).bounces, 1);
|
assert.equal((await applyMessages(s.db, s.id, [bounce])).bounces, 1);
|
||||||
assert.equal(s.status(p).status, 'bounced');
|
assert.equal((await s.status(p)).status, 'bounced');
|
||||||
assert.equal(s.db.prepare("SELECT reason FROM blacklist WHERE email = 'contact@ferme-definitivement.fr'").get().reason, 'bounce');
|
assert.equal((await s.db.prepare("SELECT reason FROM blacklist WHERE email = 'contact@ferme-definitivement.fr'").get()).reason, 'bounce');
|
||||||
assert.deepEqual(applyMessages(s.db, s.id, [bounce]), { replies: 0, bounces: 0, ignored: 1 });
|
assert.deepEqual(await applyMessages(s.db, s.id, [bounce]), { replies: 0, bounces: 0, ignored: 1 });
|
||||||
});
|
});
|
||||||
|
|
||||||
test('imapCredentials : utilisateur vide = identifiants SMTP', () => {
|
test('imapCredentials : utilisateur vide = identifiants SMTP', () => {
|
||||||
|
|
@ -102,10 +104,10 @@ test('imapCredentials : utilisateur vide = identifiants SMTP', () => {
|
||||||
});
|
});
|
||||||
|
|
||||||
test('checkInbox : reprend au dernier UID, mémorise l\'état et les erreurs', async () => {
|
test('checkInbox : reprend au dernier UID, mémorise l\'état et les erreurs', async () => {
|
||||||
const s = setup();
|
const s = await setup();
|
||||||
saveSecretConfig(s.app, s.id, 'smtp_enc', { host: 'smtp.x', user: 'u', pass: 'p', fromEmail: 'a@x.fr' }, 'pass');
|
await saveSecretConfig(s.app, s.id, 'smtp_enc', { host: 'smtp.x', user: 'u', pass: 'p', fromEmail: 'a@x.fr' }, 'pass');
|
||||||
saveSecretConfig(s.app, s.id, 'imap_enc', { host: 'imap.x', port: 993, user: '', pass: '' }, 'pass');
|
await saveSecretConfig(s.app, s.id, 'imap_enc', { host: 'imap.x', port: 993, user: '', pass: '' }, 'pass');
|
||||||
const p = s.add('Fournil', 'contact@fournil.fr', '<m1@x.fr>');
|
const p = await s.add('Fournil', 'contact@fournil.fr', '<m1@x.fr>');
|
||||||
const calls = [];
|
const calls = [];
|
||||||
s.app.fetchInbox = async (creds, state) => {
|
s.app.fetchInbox = async (creds, state) => {
|
||||||
calls.push({ creds, state });
|
calls.push({ creds, state });
|
||||||
|
|
@ -119,9 +121,9 @@ test('checkInbox : reprend au dernier UID, mémorise l\'état et les erreurs', a
|
||||||
await checkInbox(s.app, s.id);
|
await checkInbox(s.app, s.id);
|
||||||
assert.deepEqual(calls[1].state && { v: calls[1].state.uidValidity, u: calls[1].state.lastUid }, { v: '7', u: 12 });
|
assert.deepEqual(calls[1].state && { v: calls[1].state.uidValidity, u: calls[1].state.lastUid }, { v: '7', u: 12 });
|
||||||
await assert.rejects(checkInbox(s.app, s.id), /AUTHENTICATIONFAILED/);
|
await assert.rejects(checkInbox(s.app, s.id), /AUTHENTICATIONFAILED/);
|
||||||
const inbox = getProject(s.app, s.id).inbox;
|
const inbox = (await getProject(s.app, s.id)).inbox;
|
||||||
assert.equal(inbox.lastError, 'AUTHENTICATIONFAILED');
|
assert.equal(inbox.lastError, 'AUTHENTICATIONFAILED');
|
||||||
assert.equal(inbox.replies, 1);
|
assert.equal(inbox.replies, 1);
|
||||||
assert.equal(inbox.lastUid, 12, 'le dernier UID est conservé après une erreur');
|
assert.equal(inbox.lastUid, 12, 'le dernier UID est conservé après une erreur');
|
||||||
assert.equal(s.status(p).status, 'replied');
|
assert.equal((await s.status(p)).status, 'replied');
|
||||||
});
|
});
|
||||||
|
|
|
||||||
|
|
@ -1,16 +1,16 @@
|
||||||
import { test } from 'node:test';
|
import { test } from 'node:test';
|
||||||
import assert from 'node:assert/strict';
|
import assert from 'node:assert/strict';
|
||||||
import { randomBytes } from 'node:crypto';
|
import { randomBytes } from 'node:crypto';
|
||||||
import { openDb } from '../src/db.js';
|
import { testDb } from './helpers/db.js';
|
||||||
import { saveSnapshot, snapshotAll, history, parisDay } from '../src/services/metrics.js';
|
import { saveSnapshot, snapshotAll, history, parisDay } from '../src/services/metrics.js';
|
||||||
import { createProject, saveSecretConfig } from '../src/projects.js';
|
import { createProject, saveSecretConfig } from '../src/projects.js';
|
||||||
|
|
||||||
const ts = (iso) => Math.floor(Date.parse(iso) / 1000);
|
const ts = (iso) => Math.floor(Date.parse(iso) / 1000);
|
||||||
|
|
||||||
function setup() {
|
async function setup() {
|
||||||
const db = openDb(':memory:');
|
const db = await testDb();
|
||||||
const app = { db, cfg: { secretKey: randomBytes(32) } };
|
const app = { db, cfg: { secretKey: randomBytes(32) } };
|
||||||
const id = createProject(app, { name: 'MEP', gitUrl: 'https://g/T/M.git' });
|
const id = await createProject(app, { name: 'MEP', gitUrl: 'https://g/T/M.git' });
|
||||||
return { db, app, id };
|
return { db, app, id };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -19,21 +19,21 @@ test('jour de Paris, même à 23h30 UTC', () => {
|
||||||
assert.equal(parisDay(new Date('2026-12-31T22:59:00Z')), '2026-12-31');
|
assert.equal(parisDay(new Date('2026-12-31T22:59:00Z')), '2026-12-31');
|
||||||
});
|
});
|
||||||
|
|
||||||
test('photo du jour : une ligne par jour, valeurs non numériques ignorées', () => {
|
test('photo du jour : une ligne par jour, valeurs non numériques ignorées', async () => {
|
||||||
const s = setup();
|
const s = await setup();
|
||||||
const d = new Date('2026-10-21T10:00:00Z');
|
const d = new Date('2026-10-21T10:00:00Z');
|
||||||
saveSnapshot(s.db, s.id, { users: 10, clients: 2, revenue: 'n/a' }, { date: d });
|
await saveSnapshot(s.db, s.id, { users: 10, clients: 2, revenue: 'n/a' }, { date: d });
|
||||||
saveSnapshot(s.db, s.id, { users: 12, clients: 3, revenue: 150.5 }, { date: d });
|
await saveSnapshot(s.db, s.id, { users: 12, clients: 3, revenue: 150.5 }, { date: d });
|
||||||
const rows = s.db.prepare('SELECT * FROM metrics_daily').all();
|
const rows = await s.db.prepare('SELECT * FROM metrics_daily').all();
|
||||||
assert.equal(rows.length, 1, 'mise à jour, pas de doublon');
|
assert.equal(rows.length, 1, 'mise à jour, pas de doublon');
|
||||||
assert.deepEqual({ ...rows[0] }, { project_id: s.id, day: '2026-10-21', users: 12, clients: 3, revenue: 150.5 });
|
assert.deepEqual({ ...rows[0] }, { project_id: s.id, day: '2026-10-21', users: 12, clients: 3, revenue: 150.5 });
|
||||||
});
|
});
|
||||||
|
|
||||||
test('photo automatique : une seule par jour et par projet, les erreurs n\'arrêtent pas les autres', async () => {
|
test('photo automatique : une seule par jour et par projet, les erreurs n\'arrêtent pas les autres', async () => {
|
||||||
const s = setup();
|
const s = await setup();
|
||||||
const other = createProject(s.app, { name: 'GoSortir', gitUrl: 'https://g/T/G.git' });
|
const other = await createProject(s.app, { name: 'GoSortir', gitUrl: 'https://g/T/G.git' });
|
||||||
createProject(s.app, { name: 'Sans BDD', gitUrl: 'https://g/T/X.git' });
|
await createProject(s.app, { name: 'Sans BDD', gitUrl: 'https://g/T/X.git' });
|
||||||
for (const id of [s.id, other]) saveSecretConfig(s.app, id, 'db_enc', { type: 'mysql', host: 'h', sql_users: 'SELECT 1' }, 'password');
|
for (const id of [s.id, other]) await saveSecretConfig(s.app, id, 'db_enc', { type: 'mysql', host: 'h', sql_users: 'SELECT 1' }, 'password');
|
||||||
let calls = 0;
|
let calls = 0;
|
||||||
s.app.fetchRecap = async (id) => { calls++; if (id === other) throw new Error('BDD injoignable'); return { users: 5, clients: 1, revenue: 30 }; };
|
s.app.fetchRecap = async (id) => { calls++; if (id === other) throw new Error('BDD injoignable'); return { users: 5, clients: 1, revenue: 30 }; };
|
||||||
const log = { errors: [], error(...a) { this.errors.push(a.join(' ')); } };
|
const log = { errors: [], error(...a) { this.errors.push(a.join(' ')); } };
|
||||||
|
|
@ -44,15 +44,15 @@ test('photo automatique : une seule par jour et par projet, les erreurs n\'arrê
|
||||||
await snapshotAll(s.app, { date: new Date('2026-10-21T15:00:00Z'), log });
|
await snapshotAll(s.app, { date: new Date('2026-10-21T15:00:00Z'), log });
|
||||||
assert.equal(calls, 3, 'déjà pris : seul le projet en erreur est retenté');
|
assert.equal(calls, 3, 'déjà pris : seul le projet en erreur est retenté');
|
||||||
await snapshotAll(s.app, { date: new Date('2026-10-22T08:00:00Z'), log });
|
await snapshotAll(s.app, { date: new Date('2026-10-22T08:00:00Z'), log });
|
||||||
assert.equal(s.db.prepare('SELECT COUNT(*) n FROM metrics_daily WHERE project_id = ?').get(s.id).n, 2);
|
assert.equal((await s.db.prepare('SELECT COUNT(*) n FROM metrics_daily WHERE project_id = ?').get(s.id)).n, 2);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('historique : fenêtre 30/90 jours et semaines du lundi au dimanche (heure de Paris)', () => {
|
test('historique : fenêtre 30/90 jours et semaines du lundi au dimanche (heure de Paris)', async () => {
|
||||||
const s = setup();
|
const s = await setup();
|
||||||
const at = ts('2026-10-21T12:00:00Z'); // mercredi
|
const at = ts('2026-10-21T12:00:00Z'); // mercredi
|
||||||
for (const day of ['2026-08-01', '2026-09-25', '2026-10-20']) s.db.prepare('INSERT INTO metrics_daily VALUES(?, ?, 1, 1, 1)').run(s.id, day);
|
for (const day of ['2026-08-01', '2026-09-25', '2026-10-20']) await s.db.prepare('INSERT INTO metrics_daily VALUES(?, ?, 1, 1, 1)').run(s.id, day);
|
||||||
assert.deepEqual(history(s.db, s.id, { days: 30, at }).daily.map((d) => d.day), ['2026-09-25', '2026-10-20']);
|
assert.deepEqual((await history(s.db, s.id, { days: 30, at })).daily.map((d) => d.day), ['2026-09-25', '2026-10-20']);
|
||||||
assert.equal(history(s.db, s.id, { days: 90, at }).daily.length, 3);
|
assert.equal((await history(s.db, s.id, { days: 90, at })).daily.length, 3);
|
||||||
|
|
||||||
const log = (iso, kind = 'initial', error = null) => s.db.prepare('INSERT INTO mail_log(project_id, email, sent_at, kind, error) VALUES(?, ?, ?, ?, ?)').run(s.id, 'x@y.fr', ts(iso), kind, error);
|
const log = (iso, kind = 'initial', error = null) => s.db.prepare('INSERT INTO mail_log(project_id, email, sent_at, kind, error) VALUES(?, ?, ?, ?, ?)').run(s.id, 'x@y.fr', ts(iso), kind, error);
|
||||||
log('2026-10-19T00:30:00+02:00'); // lundi 0h30 Paris = dimanche UTC : semaine du 19
|
log('2026-10-19T00:30:00+02:00'); // lundi 0h30 Paris = dimanche UTC : semaine du 19
|
||||||
|
|
@ -60,8 +60,8 @@ test('historique : fenêtre 30/90 jours et semaines du lundi au dimanche (heure
|
||||||
log('2026-10-20T10:00:00+02:00');
|
log('2026-10-20T10:00:00+02:00');
|
||||||
log('2026-10-20T10:00:00+02:00', 'followup'); // les relances ne comptent pas comme premiers mails
|
log('2026-10-20T10:00:00+02:00', 'followup'); // les relances ne comptent pas comme premiers mails
|
||||||
log('2026-10-20T10:00:00+02:00', 'initial', '550'); // ni les échecs
|
log('2026-10-20T10:00:00+02:00', 'initial', '550'); // ni les échecs
|
||||||
s.db.prepare('INSERT INTO prospects(project_id, company, email, replied_at, created_at) VALUES(?, ?, ?, ?, ?)').run(s.id, 'A', 'a@a.fr', ts('2026-10-21T09:00:00+02:00'), at);
|
await s.db.prepare('INSERT INTO prospects(project_id, company, email, replied_at, created_at) VALUES(?, ?, ?, ?, ?)').run(s.id, 'A', 'a@a.fr', ts('2026-10-21T09:00:00+02:00'), at);
|
||||||
const w = history(s.db, s.id, { days: 30, at }).weeks;
|
const w = (await history(s.db, s.id, { days: 30, at })).weeks;
|
||||||
assert.equal(w.length, 5);
|
assert.equal(w.length, 5);
|
||||||
assert.equal(w.at(-1).start, '2026-10-19');
|
assert.equal(w.at(-1).start, '2026-10-19');
|
||||||
assert.deepEqual(w.slice(-2).map((x) => [x.start, x.sent, x.replies]), [['2026-10-12', 1, 0], ['2026-10-19', 2, 1]]);
|
assert.deepEqual(w.slice(-2).map((x) => [x.start, x.sent, x.replies]), [['2026-10-12', 1, 0], ['2026-10-19', 2, 1]]);
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,8 @@
|
||||||
import { test } from 'node:test';
|
import { test } from 'node:test';
|
||||||
import assert from 'node:assert/strict';
|
import assert from 'node:assert/strict';
|
||||||
import { parisParts, parisTime, nextNightSlot, addParisDays } from '../src/services/paris-time.js';
|
import { parisParts, parisTime, nextNightSlot, addParisDays } from '../src/services/paris-time.js';
|
||||||
import { openDb, now } from '../src/db.js';
|
import { now } from '../src/db.js';
|
||||||
|
import { testDb } from './helpers/db.js';
|
||||||
import { enqueue, Worker, latestJobs } from '../src/services/jobs.js';
|
import { enqueue, Worker, latestJobs } from '../src/services/jobs.js';
|
||||||
|
|
||||||
const iso = (d) => d.toISOString();
|
const iso = (d) => d.toISOString();
|
||||||
|
|
@ -25,18 +26,18 @@ test('prochain créneau de nuit (1h-6h Paris)', () => {
|
||||||
});
|
});
|
||||||
|
|
||||||
test('le worker ne démarre pas un job programmé avant son heure', async () => {
|
test('le worker ne démarre pas un job programmé avant son heure', async () => {
|
||||||
const db = openDb(':memory:');
|
const db = await testDb();
|
||||||
let clock = now();
|
let clock = now();
|
||||||
const ran = [];
|
const ran = [];
|
||||||
const w = new Worker(db, { prospect: async () => { ran.push('prospect'); }, evolution: async () => { ran.push('evolution'); } },
|
const w = new Worker(db, { prospect: async () => { ran.push('prospect'); }, evolution: async () => { ran.push('evolution'); } },
|
||||||
{ thermalMax: 999, log: { error() {} }, clock: () => clock });
|
{ thermalMax: 999, log: { error() {} }, clock: () => clock });
|
||||||
db.prepare("INSERT INTO projects(name, git_url, created_at) VALUES('p', 'u', ?)").run(now());
|
await db.prepare("INSERT INTO projects(name, git_url, created_at) VALUES('p', 'u', ?)").run(now());
|
||||||
enqueue(db, { projectId: 1, type: 'prospect', runAfter: clock + 3600 });
|
await enqueue(db, { projectId: 1, type: 'prospect', runAfter: clock + 3600 });
|
||||||
enqueue(db, { projectId: 1, type: 'evolution' });
|
await enqueue(db, { projectId: 1, type: 'evolution' });
|
||||||
assert.equal(await w.tick(), true);
|
assert.equal(await w.tick(), true);
|
||||||
assert.deepEqual(ran, ['evolution'], 'le job immédiat passe devant le job programmé');
|
assert.deepEqual(ran, ['evolution'], 'le job immédiat passe devant le job programmé');
|
||||||
assert.equal(await w.tick(), false, 'rien à faire avant l\'heure');
|
assert.equal(await w.tick(), false, 'rien à faire avant l\'heure');
|
||||||
assert.equal(latestJobs(db, 1).prospect.runAfter, clock + 3600);
|
assert.equal((await latestJobs(db, 1)).prospect.runAfter, clock + 3600);
|
||||||
clock += 3601;
|
clock += 3601;
|
||||||
assert.equal(await w.tick(), true);
|
assert.equal(await w.tick(), true);
|
||||||
assert.deepEqual(ran, ['evolution', 'prospect']);
|
assert.deepEqual(ran, ['evolution', 'prospect']);
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,8 @@
|
||||||
import { test } from 'node:test';
|
import { test } from 'node:test';
|
||||||
import assert from 'node:assert/strict';
|
import assert from 'node:assert/strict';
|
||||||
import { randomBytes } from 'node:crypto';
|
import { randomBytes } from 'node:crypto';
|
||||||
import { openDb, now, setSetting } from '../src/db.js';
|
import { now, setSetting } from '../src/db.js';
|
||||||
|
import { testDb } from './helpers/db.js';
|
||||||
import { encrypt } from '../src/crypto.js';
|
import { encrypt } from '../src/crypto.js';
|
||||||
import { notify, notifyJob, WEBHOOK_RE } from '../src/services/notify.js';
|
import { notify, notifyJob, WEBHOOK_RE } from '../src/services/notify.js';
|
||||||
import { Worker, enqueue } from '../src/services/jobs.js';
|
import { Worker, enqueue } from '../src/services/jobs.js';
|
||||||
|
|
@ -10,16 +11,16 @@ import { createProject, saveSecretConfig } from '../src/projects.js';
|
||||||
|
|
||||||
const HOOK = 'https://discord.com/api/webhooks/123456789012345678/abcdefghijklmnopqrstuvwxyz-ABC_123';
|
const HOOK = 'https://discord.com/api/webhooks/123456789012345678/abcdefghijklmnopqrstuvwxyz-ABC_123';
|
||||||
|
|
||||||
function setup({ events } = {}) {
|
async function setup({ events } = {}) {
|
||||||
const db = openDb(':memory:');
|
const db = await testDb();
|
||||||
const sent = [];
|
const sent = [];
|
||||||
const app = {
|
const app = {
|
||||||
db, cfg: { secretKey: randomBytes(32), appUrl: 'https://ai.test' },
|
db, cfg: { secretKey: randomBytes(32), appUrl: 'https://ai.test' },
|
||||||
fetch: async (url, opts) => { sent.push({ url, body: JSON.parse(opts.body) }); return { ok: true, status: 204 }; },
|
fetch: async (url, opts) => { sent.push({ url, body: JSON.parse(opts.body) }); return { ok: true, status: 204 }; },
|
||||||
};
|
};
|
||||||
setSetting(db, 'discord_webhook_enc', encrypt(app.cfg.secretKey, HOOK));
|
await setSetting(db, 'discord_webhook_enc', encrypt(app.cfg.secretKey, HOOK));
|
||||||
if (events) setSetting(db, 'discord_events', JSON.stringify(events));
|
if (events) await setSetting(db, 'discord_events', JSON.stringify(events));
|
||||||
const id = createProject(app, { name: 'MonEspacePro', gitUrl: 'https://g/T/M.git' });
|
const id = await createProject(app, { name: 'MonEspacePro', gitUrl: 'https://g/T/M.git' });
|
||||||
return { db, app, sent, id };
|
return { db, app, sent, id };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -33,7 +34,7 @@ test('validation stricte de l\'URL de webhook', () => {
|
||||||
});
|
});
|
||||||
|
|
||||||
test('notif : forme du message, aucune mention possible', async () => {
|
test('notif : forme du message, aucune mention possible', async () => {
|
||||||
const s = setup();
|
const s = await setup();
|
||||||
assert.equal(await notify(s.app, 'reply', { title: '@everyone Boulangerie', description: 'x', level: 'ok', fields: [{ name: 'a', value: '' }] }), true);
|
assert.equal(await notify(s.app, 'reply', { title: '@everyone Boulangerie', description: 'x', level: 'ok', fields: [{ name: 'a', value: '' }] }), true);
|
||||||
const b = s.sent[0].body;
|
const b = s.sent[0].body;
|
||||||
assert.equal(s.sent[0].url, HOOK);
|
assert.equal(s.sent[0].url, HOOK);
|
||||||
|
|
@ -44,7 +45,7 @@ test('notif : forme du message, aucune mention possible', async () => {
|
||||||
});
|
});
|
||||||
|
|
||||||
test('événement désactivé, webhook absent ou Discord en panne : rien ne casse', async () => {
|
test('événement désactivé, webhook absent ou Discord en panne : rien ne casse', async () => {
|
||||||
const s = setup({ events: ['job_error'] });
|
const s = await setup({ events: ['job_error'] });
|
||||||
assert.equal(await notify(s.app, 'reply', { title: 'x' }), false);
|
assert.equal(await notify(s.app, 'reply', { title: 'x' }), false);
|
||||||
assert.equal(s.sent.length, 0);
|
assert.equal(s.sent.length, 0);
|
||||||
assert.equal(await notify(s.app, 'reply', { title: 'x' }, { force: true }), true, 'le bouton de test force l\'envoi');
|
assert.equal(await notify(s.app, 'reply', { title: 'x' }, { force: true }), true, 'le bouton de test force l\'envoi');
|
||||||
|
|
@ -55,12 +56,12 @@ test('événement désactivé, webhook absent ou Discord en panne : rien ne cass
|
||||||
s.app.fetch = async () => { throw new Error('réseau'); };
|
s.app.fetch = async () => { throw new Error('réseau'); };
|
||||||
assert.equal(await notify(s.app, 'job_error', { title: 'x' }), false);
|
assert.equal(await notify(s.app, 'job_error', { title: 'x' }), false);
|
||||||
} finally { console.warn = warn; }
|
} finally { console.warn = warn; }
|
||||||
setSetting(s.db, 'discord_webhook_enc', null);
|
await setSetting(s.db, 'discord_webhook_enc', null);
|
||||||
assert.equal(await notify(s.app, 'job_error', { title: 'x' }), false);
|
assert.equal(await notify(s.app, 'job_error', { title: 'x' }), false);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('fin de job : succès, erreur, relances, et silence pour les jobs courts', async () => {
|
test('fin de job : succès, erreur, relances, et silence pour les jobs courts', async () => {
|
||||||
const s = setup();
|
const s = await setup();
|
||||||
const job = (type) => ({ type, project_id: s.id });
|
const job = (type) => ({ type, project_id: s.id });
|
||||||
await notifyJob(s.app, job('prospect'), { status: 'done', result: { found: 7, requested: 10 } });
|
await notifyJob(s.app, job('prospect'), { status: 'done', result: { found: 7, requested: 10 } });
|
||||||
await notifyJob(s.app, job('send'), { status: 'error', error: 'SMTP refusé' });
|
await notifyJob(s.app, job('send'), { status: 'error', error: 'SMTP refusé' });
|
||||||
|
|
@ -76,24 +77,24 @@ test('fin de job : succès, erreur, relances, et silence pour les jobs courts',
|
||||||
});
|
});
|
||||||
|
|
||||||
test('le worker notifie en fin de job, et un callback qui plante ne le bloque pas', async () => {
|
test('le worker notifie en fin de job, et un callback qui plante ne le bloque pas', async () => {
|
||||||
const s = setup();
|
const s = await setup();
|
||||||
const seen = [];
|
const seen = [];
|
||||||
const w = new Worker(s.db, { prospect: async () => ({ found: 2, requested: 5 }), evolution: async () => { throw new Error('boom'); } }, {
|
const w = new Worker(s.db, { prospect: async () => ({ found: 2, requested: 5 }), evolution: async () => { throw new Error('boom'); } }, {
|
||||||
thermalMax: 999, log: { error() {} },
|
thermalMax: 999, log: { error() {} },
|
||||||
onFinish: (job, r) => { seen.push(`${job.type}:${r.status}`); if (job.type === 'evolution') throw new Error('callback cassé'); },
|
onFinish: (job, r) => { seen.push(`${job.type}:${r.status}`); if (job.type === 'evolution') throw new Error('callback cassé'); },
|
||||||
});
|
});
|
||||||
enqueue(s.db, { projectId: s.id, type: 'prospect' });
|
await enqueue(s.db, { projectId: s.id, type: 'prospect' });
|
||||||
enqueue(s.db, { projectId: s.id, type: 'evolution' });
|
await enqueue(s.db, { projectId: s.id, type: 'evolution' });
|
||||||
await w.tick(); await w.tick();
|
await w.tick(); await w.tick();
|
||||||
assert.deepEqual(seen, ['prospect:done', 'evolution:error']);
|
assert.deepEqual(seen, ['prospect:done', 'evolution:error']);
|
||||||
assert.equal(s.db.prepare("SELECT COUNT(*) n FROM jobs WHERE status IN ('done','error')").get().n, 2);
|
assert.equal((await s.db.prepare("SELECT COUNT(*) n FROM jobs WHERE status IN ('done','error')").get()).n, 2);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('nouvelles réponses détectées → une notif avec les entreprises', async () => {
|
test('nouvelles réponses détectées → une notif avec les entreprises', async () => {
|
||||||
const s = setup();
|
const s = await setup();
|
||||||
saveSecretConfig(s.app, s.id, 'smtp_enc', { host: 'h', user: 'u', pass: 'p', fromEmail: 'a@x.fr' }, 'pass');
|
await saveSecretConfig(s.app, s.id, 'smtp_enc', { host: 'h', user: 'u', pass: 'p', fromEmail: 'a@x.fr' }, 'pass');
|
||||||
saveSecretConfig(s.app, s.id, 'imap_enc', { host: 'imap.x' }, 'pass');
|
await saveSecretConfig(s.app, s.id, 'imap_enc', { host: 'imap.x' }, 'pass');
|
||||||
s.db.prepare("INSERT INTO prospects(project_id, company, email, status, sent_at, created_at) VALUES(?, 'Le Fournil', 'contact@fournil.fr', 'sent', ?, ?)").run(s.id, now(), now());
|
await s.db.prepare("INSERT INTO prospects(project_id, company, email, status, sent_at, created_at) VALUES(?, 'Le Fournil', 'contact@fournil.fr', 'sent', ?, ?)").run(s.id, now(), now());
|
||||||
s.app.fetchInbox = async () => ({ uidValidity: '1', lastUid: 1, messages: [{ uid: 1, from: 'contact@fournil.fr', subject: 'Re: idée' }] });
|
s.app.fetchInbox = async () => ({ uidValidity: '1', lastUid: 1, messages: [{ uid: 1, from: 'contact@fournil.fr', subject: 'Re: idée' }] });
|
||||||
await checkInbox(s.app, s.id);
|
await checkInbox(s.app, s.id);
|
||||||
assert.equal(s.sent.length, 1);
|
assert.equal(s.sent.length, 1);
|
||||||
|
|
|
||||||
|
|
@ -1,40 +1,41 @@
|
||||||
import { test } from 'node:test';
|
import { test } from 'node:test';
|
||||||
import assert from 'node:assert/strict';
|
import assert from 'node:assert/strict';
|
||||||
import { randomBytes } from 'node:crypto';
|
import { randomBytes } from 'node:crypto';
|
||||||
import { openDb, now, setSetting, getSetting } from '../src/db.js';
|
import { now, setSetting, getSetting } from '../src/db.js';
|
||||||
|
import { testDb } from './helpers/db.js';
|
||||||
import { encrypt, encryptJson } from '../src/crypto.js';
|
import { encrypt, encryptJson } from '../src/crypto.js';
|
||||||
import { weeklyStats, weeklyText, maybeSendWeekly } from '../src/services/report.js';
|
import { weeklyStats, weeklyText, maybeSendWeekly } from '../src/services/report.js';
|
||||||
import { createProject } from '../src/projects.js';
|
import { createProject } from '../src/projects.js';
|
||||||
|
|
||||||
function setup() {
|
async function setup() {
|
||||||
const db = openDb(':memory:');
|
const db = await testDb();
|
||||||
const mails = [], hooks = [];
|
const mails = [], hooks = [];
|
||||||
const app = {
|
const app = {
|
||||||
db, cfg: { secretKey: randomBytes(32), appUrl: 'https://ai.test' },
|
db, cfg: { secretKey: randomBytes(32), appUrl: 'https://ai.test' },
|
||||||
createTransport: () => ({ sendMail: async (m) => { mails.push(m); }, close() {} }),
|
createTransport: () => ({ sendMail: async (m) => { mails.push(m); }, close() {} }),
|
||||||
fetch: async (url, o) => { hooks.push(JSON.parse(o.body)); return { ok: true }; },
|
fetch: async (url, o) => { hooks.push(JSON.parse(o.body)); return { ok: true }; },
|
||||||
};
|
};
|
||||||
const mep = createProject(app, { name: 'MonEspacePro', gitUrl: 'https://g/T/M.git' });
|
const mep = await createProject(app, { name: 'MonEspacePro', gitUrl: 'https://g/T/M.git' });
|
||||||
createProject(app, { name: 'GoSortir', gitUrl: 'https://g/T/G.git' });
|
await createProject(app, { name: 'GoSortir', gitUrl: 'https://g/T/G.git' });
|
||||||
const t = now() - 2 * 86400;
|
const t = now() - 2 * 86400;
|
||||||
for (let i = 0; i < 20; i++) {
|
for (let i = 0; i < 20; i++) {
|
||||||
const v = i % 2 ? 'B' : 'A';
|
const v = i % 2 ? 'B' : 'A';
|
||||||
const replied = (v === 'B' && i < 10) || i === 0;
|
const replied = (v === 'B' && i < 10) || i === 0;
|
||||||
const pid = Number(db.prepare('INSERT INTO prospects(project_id, company, email, status, sent_at, variant, replied_at, created_at) VALUES(?, ?, ?, ?, ?, ?, ?, ?)')
|
const pid = Number((await db.prepare('INSERT INTO prospects(project_id, company, email, status, sent_at, variant, replied_at, created_at) VALUES(?, ?, ?, ?, ?, ?, ?, ?)')
|
||||||
.run(mep, `E${i}`, `e${i}@x${i}.fr`, i === 3 ? 'client' : replied ? 'replied' : 'sent', t, v, replied ? t + 60 : null, t).lastInsertRowid);
|
.run(mep, `E${i}`, `e${i}@x${i}.fr`, i === 3 ? 'client' : replied ? 'replied' : 'sent', t, v, replied ? t + 60 : null, t)).lastInsertRowid);
|
||||||
db.prepare("INSERT INTO mail_log(project_id, prospect_id, email, sent_at, kind, variant) VALUES(?, ?, ?, ?, 'initial', ?)").run(mep, pid, `e${i}@x${i}.fr`, t, v);
|
await db.prepare("INSERT INTO mail_log(project_id, prospect_id, email, sent_at, kind, variant) VALUES(?, ?, ?, ?, 'initial', ?)").run(mep, pid, `e${i}@x${i}.fr`, t, v);
|
||||||
}
|
}
|
||||||
db.prepare("INSERT INTO mail_log(project_id, email, sent_at, kind) VALUES(?, 'e5@x5.fr', ?, 'followup')").run(mep, t);
|
await db.prepare("INSERT INTO mail_log(project_id, email, sent_at, kind) VALUES(?, 'e5@x5.fr', ?, 'followup')").run(mep, t);
|
||||||
db.prepare("INSERT INTO mail_log(project_id, email, sent_at, kind, error) VALUES(?, 'e6@x6.fr', ?, 'followup', 'refusé')").run(mep, t);
|
await db.prepare("INSERT INTO mail_log(project_id, email, sent_at, kind, error) VALUES(?, 'e6@x6.fr', ?, 'followup', 'refusé')").run(mep, t);
|
||||||
db.prepare("INSERT INTO blacklist(email, reason, created_at) VALUES('e7@x7.fr', 'bounce', ?)").run(t);
|
await db.prepare("INSERT INTO blacklist(email, reason, created_at) VALUES('e7@x7.fr', 'bounce', ?)").run(t);
|
||||||
db.prepare("INSERT INTO jobs(project_id, type, status, cost_usd, created_at, finished_at) VALUES(?, 'prospect', 'done', 0.42, ?, ?)").run(mep, t, t);
|
await db.prepare("INSERT INTO jobs(project_id, type, status, cost_usd, created_at, finished_at) VALUES(?, 'prospect', 'done', 0.42, ?, ?)").run(mep, t, t);
|
||||||
db.prepare("INSERT INTO jobs(project_id, type, status, cost_usd, created_at, finished_at) VALUES(?, 'prospect', 'done', 9, ?, ?)").run(mep, t - 30 * 86400, t - 30 * 86400);
|
await db.prepare("INSERT INTO jobs(project_id, type, status, cost_usd, created_at, finished_at) VALUES(?, 'prospect', 'done', 9, ?, ?)").run(mep, t - 30 * 86400, t - 30 * 86400);
|
||||||
return { db, app, mails, hooks };
|
return { db, app, mails, hooks };
|
||||||
}
|
}
|
||||||
|
|
||||||
test('statistiques de la semaine', () => {
|
test('statistiques de la semaine', async () => {
|
||||||
const s = setup();
|
const s = await setup();
|
||||||
const st = weeklyStats(s.db);
|
const st = await weeklyStats(s.db);
|
||||||
const mep = st.projects.find((p) => p.name === 'MonEspacePro');
|
const mep = st.projects.find((p) => p.name === 'MonEspacePro');
|
||||||
assert.deepEqual({ ...mep, bestSubject: mep.bestSubject?.variant }, {
|
assert.deepEqual({ ...mep, bestSubject: mep.bestSubject?.variant }, {
|
||||||
name: 'MonEspacePro', found: 20, sent: 20, followups: 1, replies: 6, clients: 1, bounces: 1, cost: 0.42, bestSubject: 'B',
|
name: 'MonEspacePro', found: 20, sent: 20, followups: 1, replies: 6, clients: 1, bounces: 1, cost: 0.42, bestSubject: 'B',
|
||||||
|
|
@ -50,13 +51,13 @@ test('statistiques de la semaine', () => {
|
||||||
const MON_0830 = new Date('2026-10-26T08:30:00+01:00');
|
const MON_0830 = new Date('2026-10-26T08:30:00+01:00');
|
||||||
|
|
||||||
test('envoi automatique : lundi 8h, une seule fois par semaine, désactivé par défaut', async () => {
|
test('envoi automatique : lundi 8h, une seule fois par semaine, désactivé par défaut', async () => {
|
||||||
const s = setup();
|
const s = await setup();
|
||||||
setSetting(s.db, 'notify_email', 'moi@x.fr');
|
await setSetting(s.db, 'notify_email', 'moi@x.fr');
|
||||||
setSetting(s.db, 'smtp_enc', encryptJson(s.app.cfg.secretKey, { host: 'h', user: 'u', pass: 'p', fromEmail: 'aitools@x.fr' }));
|
await setSetting(s.db, 'smtp_enc', encryptJson(s.app.cfg.secretKey, { host: 'h', user: 'u', pass: 'p', fromEmail: 'aitools@x.fr' }));
|
||||||
setSetting(s.db, 'discord_webhook_enc', encrypt(s.app.cfg.secretKey, 'https://discord.com/api/webhooks/123456789012345678/abcdefghijklmnopqrstuvwxyz'));
|
await setSetting(s.db, 'discord_webhook_enc', encrypt(s.app.cfg.secretKey, 'https://discord.com/api/webhooks/123456789012345678/abcdefghijklmnopqrstuvwxyz'));
|
||||||
|
|
||||||
assert.equal(await maybeSendWeekly(s.app, { date: MON_0830 }), null, 'désactivé par défaut');
|
assert.equal(await maybeSendWeekly(s.app, { date: MON_0830 }), null, 'désactivé par défaut');
|
||||||
setSetting(s.db, 'weekly_report', '1');
|
await setSetting(s.db, 'weekly_report', '1');
|
||||||
assert.equal(await maybeSendWeekly(s.app, { date: new Date('2026-10-26T07:45:00+01:00') }), null, 'lundi 7h45 : trop tôt');
|
assert.equal(await maybeSendWeekly(s.app, { date: new Date('2026-10-26T07:45:00+01:00') }), null, 'lundi 7h45 : trop tôt');
|
||||||
assert.equal(await maybeSendWeekly(s.app, { date: new Date('2026-10-27T09:00:00+01:00') }), null, 'mardi : non');
|
assert.equal(await maybeSendWeekly(s.app, { date: new Date('2026-10-27T09:00:00+01:00') }), null, 'mardi : non');
|
||||||
|
|
||||||
|
|
@ -75,9 +76,9 @@ test('envoi automatique : lundi 8h, une seule fois par semaine, désactivé par
|
||||||
});
|
});
|
||||||
|
|
||||||
test('aucun canal configuré : rien n\'est marqué comme envoyé', async () => {
|
test('aucun canal configuré : rien n\'est marqué comme envoyé', async () => {
|
||||||
const s = setup();
|
const s = await setup();
|
||||||
setSetting(s.db, 'weekly_report', '1');
|
await setSetting(s.db, 'weekly_report', '1');
|
||||||
const r = await maybeSendWeekly(s.app, { date: MON_0830 });
|
const r = await maybeSendWeekly(s.app, { date: MON_0830 });
|
||||||
assert.deepEqual(r.channels, []);
|
assert.deepEqual(r.channels, []);
|
||||||
assert.equal(getSetting(s.db, 'weekly_report_last'), null);
|
assert.equal(await getSetting(s.db, 'weekly_report_last'), null);
|
||||||
});
|
});
|
||||||
|
|
|
||||||
|
|
@ -3,7 +3,8 @@ import assert from 'node:assert/strict';
|
||||||
import { resolve } from 'node:path';
|
import { resolve } from 'node:path';
|
||||||
import { runClaude, extractJson, rateLimitWindows } from '../src/services/claude.js';
|
import { runClaude, extractJson, rateLimitWindows } from '../src/services/claude.js';
|
||||||
import { waitCool } from '../src/services/thermal.js';
|
import { waitCool } from '../src/services/thermal.js';
|
||||||
import { openDb, now } from '../src/db.js';
|
import { now } from '../src/db.js';
|
||||||
|
import { testDb } from './helpers/db.js';
|
||||||
import { enqueue, Worker, latestJobs, cancelJob, addUsage, usageSummary } from '../src/services/jobs.js';
|
import { enqueue, Worker, latestJobs, cancelJob, addUsage, usageSummary } from '../src/services/jobs.js';
|
||||||
|
|
||||||
const bin = resolve('test/fixtures/fake-claude.js');
|
const bin = resolve('test/fixtures/fake-claude.js');
|
||||||
|
|
@ -55,28 +56,28 @@ test('waitCool attend la redescente avec hystérésis', async () => {
|
||||||
});
|
});
|
||||||
|
|
||||||
test('worker : exécution, dédoublonnage, erreurs, annulation, conso', async () => {
|
test('worker : exécution, dédoublonnage, erreurs, annulation, conso', async () => {
|
||||||
const db = openDb(':memory:');
|
const db = await testDb();
|
||||||
db.prepare("INSERT INTO projects(name, git_url, created_at) VALUES('p','u',?)").run(now());
|
await db.prepare("INSERT INTO projects(name, git_url, created_at) VALUES('p','u',?)").run(now());
|
||||||
const a = enqueue(db, { projectId: 1, type: 'ok', params: { x: 2 } });
|
const a = await enqueue(db, { projectId: 1, type: 'ok', params: { x: 2 } });
|
||||||
assert.equal(enqueue(db, { projectId: 1, type: 'ok' }).existing, true);
|
assert.equal((await enqueue(db, { projectId: 1, type: 'ok' })).existing, true);
|
||||||
const handlers = {
|
const handlers = {
|
||||||
ok: async (ctx) => { ctx.progress({ found: 1 }); addUsage(ctx, { costUsd: 0.5, tokensIn: 10, tokensOut: 5 }); return { double: ctx.params.x * 2 }; },
|
ok: async (ctx) => { ctx.progress({ found: 1 }); addUsage(ctx, { costUsd: 0.5, tokensIn: 10, tokensOut: 5 }); return { double: ctx.params.x * 2 }; },
|
||||||
boom: async () => { throw new Error('raté'); },
|
boom: async () => { throw new Error('raté'); },
|
||||||
};
|
};
|
||||||
const w = new Worker(db, handlers, { thermalMax: 999, log: { error() {} } });
|
const w = new Worker(db, handlers, { thermalMax: 999, log: { error() {} } });
|
||||||
assert.equal(await w.tick(), true);
|
assert.equal(await w.tick(), true);
|
||||||
enqueue(db, { projectId: 1, type: 'boom' });
|
await enqueue(db, { projectId: 1, type: 'boom' });
|
||||||
await w.tick();
|
await w.tick();
|
||||||
const c = enqueue(db, { projectId: 1, type: 'ok' });
|
const c = await enqueue(db, { projectId: 1, type: 'ok' });
|
||||||
cancelJob(db, c.id);
|
await cancelJob(db, c.id);
|
||||||
assert.equal(await w.tick(), false);
|
assert.equal(await w.tick(), false);
|
||||||
const jobs = latestJobs(db, 1);
|
const jobs = await latestJobs(db, 1);
|
||||||
assert.equal(a.id, 1);
|
assert.equal(a.id, 1);
|
||||||
assert.equal(jobs.boom.status, 'error');
|
assert.equal(jobs.boom.status, 'error');
|
||||||
assert.equal(jobs.boom.error, 'raté');
|
assert.equal(jobs.boom.error, 'raté');
|
||||||
assert.equal(jobs.ok.status, 'cancelled');
|
assert.equal(jobs.ok.status, 'cancelled');
|
||||||
const first = db.prepare('SELECT * FROM jobs WHERE id = 1').get();
|
const first = await db.prepare('SELECT * FROM jobs WHERE id = 1').get();
|
||||||
assert.equal(first.status, 'done');
|
assert.equal(first.status, 'done');
|
||||||
assert.deepEqual(JSON.parse(first.result_json), { double: 4 });
|
assert.deepEqual(JSON.parse(first.result_json), { double: 4 });
|
||||||
assert.equal(usageSummary(db).month.cost, 0.5);
|
assert.equal((await usageSummary(db)).month.cost, 0.5);
|
||||||
});
|
});
|
||||||
|
|
|
||||||
63
test/worker.test.js
Normal file
63
test/worker.test.js
Normal file
|
|
@ -0,0 +1,63 @@
|
||||||
|
import { test } from 'node:test';
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import { now } from '../src/db.js';
|
||||||
|
import { testDb } from './helpers/db.js';
|
||||||
|
import { Worker, enqueue, latestJobs } from '../src/services/jobs.js';
|
||||||
|
|
||||||
|
async function setup() {
|
||||||
|
const db = await testDb();
|
||||||
|
await db.prepare("INSERT INTO projects(name, git_url, created_at) VALUES('p', 'u', ?)").run(now());
|
||||||
|
return db;
|
||||||
|
}
|
||||||
|
|
||||||
|
test('start puis stop : la boucle s\'arrête, le job en cours est annulé et attendu', async () => {
|
||||||
|
const db = await setup();
|
||||||
|
let started;
|
||||||
|
const running = new Promise((r) => { started = r; });
|
||||||
|
const w = new Worker(db, {
|
||||||
|
prospect: (ctx) => new Promise((_, reject) => {
|
||||||
|
started();
|
||||||
|
ctx.signal.addEventListener('abort', () => reject(new Error('Annulé')), { once: true });
|
||||||
|
}),
|
||||||
|
}, { thermalMax: 999, pollMs: 10, log: { error() {} } });
|
||||||
|
await enqueue(db, { projectId: 1, type: 'prospect' });
|
||||||
|
await w.start();
|
||||||
|
await running;
|
||||||
|
await w.stop();
|
||||||
|
assert.equal(w.current, null);
|
||||||
|
const job = (await latestJobs(db, 1)).prospect;
|
||||||
|
assert.equal(job.status, 'error');
|
||||||
|
assert.match(job.error, /Annulé/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('stop attend les notifications en vol, et un callback qui échoue est journalisé', async () => {
|
||||||
|
const db = await setup();
|
||||||
|
const seen = [];
|
||||||
|
const errors = [];
|
||||||
|
const w = new Worker(db, { prospect: async () => ({ ok: true }), evolution: async () => { throw new Error('boum'); } }, {
|
||||||
|
thermalMax: 999, pollMs: 10, log: { error: (...a) => errors.push(a.join(' ')) },
|
||||||
|
onFinish: async (job, r) => {
|
||||||
|
await new Promise((res) => setTimeout(res, 30));
|
||||||
|
seen.push(`${job.type}:${r.status}`);
|
||||||
|
if (job.type === 'evolution') throw new Error('notification cassée');
|
||||||
|
},
|
||||||
|
});
|
||||||
|
await enqueue(db, { projectId: 1, type: 'prospect' });
|
||||||
|
await enqueue(db, { projectId: 1, type: 'evolution' });
|
||||||
|
await w.tick(); await w.tick();
|
||||||
|
assert.deepEqual(seen, [], 'les notifications ne bloquent pas la file');
|
||||||
|
await w.stop();
|
||||||
|
assert.deepEqual(seen.sort(), ['evolution:error', 'prospect:done']);
|
||||||
|
assert.ok(errors.some((e) => /notification cassée/.test(e)));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('un job "running" laissé par un crash est marqué en erreur au démarrage', async () => {
|
||||||
|
const db = await setup();
|
||||||
|
await db.prepare("INSERT INTO jobs(project_id, type, status, created_at) VALUES(1, 'analyze', 'running', ?)").run(now());
|
||||||
|
const w = new Worker(db, {}, { thermalMax: 999, pollMs: 10, log: { error() {} } });
|
||||||
|
await w.start();
|
||||||
|
await w.stop();
|
||||||
|
const job = (await latestJobs(db, 1)).analyze;
|
||||||
|
assert.equal(job.status, 'error');
|
||||||
|
assert.equal(job.error, 'Interrompu (redémarrage)');
|
||||||
|
});
|
||||||
Loading…
Reference in a new issue