feat(tenant): filtre toute requête métier par utilisateur
Routes, handlers de jobs, worker, planificateur, rapport hebdo, notifications, métriques, boîtes IMAP, plafonds et budget, export/import CSV : tout est borné à l'utilisateur courant, et la ressource d'un autre compte répond 404. getProject exige l'utilisateur. Réglages (SMTP, Discord, budget, plafonds, Forgejo) et dossier des clones git (repos/<utilisateur>/<projet>) par utilisateur. La liste d'opposition reste commune mais ne révèle ni motif ni origine d'un autre compte (compteur et fiche prospect, prompt de prospection). Le planificateur ne travaille que pour les comptes actifs.
This commit is contained in:
parent
e9164b323c
commit
97e856189a
27 changed files with 523 additions and 395 deletions
|
|
@ -54,15 +54,15 @@ export function parseProspectLine(line) {
|
|||
|
||||
export function makeHandlers(app) {
|
||||
const { db, cfg } = app;
|
||||
const claude = async (o) => {
|
||||
const claude = async (userId, o) => {
|
||||
const r = await runClaude({ bin: cfg.claudeBin, ...o });
|
||||
// État du quota Pro (session 5h + semaine), affiché dans la barre système
|
||||
const w = rateLimitWindows(r.rateLimit);
|
||||
if (w) {
|
||||
await setSetting(db, 'claude_rate_limit_json', JSON.stringify({ at: now(), ...w }));
|
||||
for (const a of await quotaAlerts(db, w)) {
|
||||
await setSetting(db, userId, 'claude_rate_limit_json', JSON.stringify({ at: now(), ...w }));
|
||||
for (const a of await quotaAlerts(db, userId, w)) {
|
||||
// notify ne lève jamais : un Discord indisponible ne fait pas échouer le job
|
||||
await notify(app, 'quota', {
|
||||
await notify(app, userId, 'quota', {
|
||||
title: `Quota Claude : ${a.level}+ % (${a.label})`,
|
||||
level: a.level >= 95 ? 'error' : 'warn',
|
||||
description: `${Math.round(a.utilization * 100)} % utilisé sur la ${a.label}.`,
|
||||
|
|
@ -78,7 +78,8 @@ export function makeHandlers(app) {
|
|||
async function sendMails(ctx, kind) {
|
||||
// Une relance mise en file à 17h55 ne doit pas partir à 19h si le worker était occupé
|
||||
if (kind === 'followup' && !inHours()) return { sent: 0, failed: 0, total: 0, postponed: true };
|
||||
const project = await getProject(app, ctx.job.project_id, { secrets: true });
|
||||
const userId = ctx.job.user_id;
|
||||
const project = await getProject(app, ctx.job.project_id, { userId, secrets: true });
|
||||
const template = await getTemplate(db, project.id, kind, { validatedOnly: true });
|
||||
if (!template) throw new Error(kind === 'followup' ? 'Modèle de relance non validé' : 'Modèle de mail non validé');
|
||||
if (!project.smtp) throw new Error('SMTP non configuré pour ce projet');
|
||||
|
|
@ -92,16 +93,16 @@ export function makeHandlers(app) {
|
|||
requested: ctx.params.count,
|
||||
available: candidates.length,
|
||||
projectCap: project.dailyMailCap,
|
||||
sentTodayProject: await sentSince(db, day, project.id),
|
||||
globalCap: Number(await getSetting(db, 'global_daily_cap', '100')),
|
||||
sentTodayGlobal: await sentSince(db, day),
|
||||
sentTodayProject: await sentSince(db, day, userId, project.id),
|
||||
globalCap: Number(await getSetting(db, userId, 'global_daily_cap', '100')),
|
||||
sentTodayGlobal: await sentSince(db, day, userId),
|
||||
});
|
||||
if (n === 0) throw new Error(kind === 'followup' ? 'Plafond quotidien atteint ou aucune relance due' : 'Plafond quotidien atteint ou aucun prospect à contacter');
|
||||
|
||||
const transport = (app.createTransport || createTransport)(project.smtp);
|
||||
await transport.verify();
|
||||
const minDelay = Number(await getSetting(db, 'send_delay_min', '20')) * 1000;
|
||||
const maxDelay = Number(await getSetting(db, 'send_delay_max', '60')) * 1000;
|
||||
const minDelay = Number(await getSetting(db, userId, 'send_delay_min', '20')) * 1000;
|
||||
const maxDelay = Number(await getSetting(db, userId, 'send_delay_max', '60')) * 1000;
|
||||
const log = db.prepare(`INSERT INTO mail_log(project_id, prospect_id, email, sent_at, error, kind, variant, subject, message_id)
|
||||
VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?)`);
|
||||
const markInitial = db.prepare('UPDATE prospects SET status = ?, sent_at = ?, variant = ? WHERE id = ?');
|
||||
|
|
@ -156,16 +157,17 @@ export function makeHandlers(app) {
|
|||
|
||||
return {
|
||||
async analyze(ctx) {
|
||||
const project = await getProject(app, ctx.job.project_id);
|
||||
const userId = ctx.job.user_id;
|
||||
const project = await getProject(app, ctx.job.project_id, { userId });
|
||||
await ctx.progress({ message: 'Récupération du repo…', pct: 3 });
|
||||
const dir = repoDir(cfg, project.id);
|
||||
const commit = await syncRepo(project.gitUrl, dir, await forgejoToken(app));
|
||||
const dir = repoDir(cfg, userId, project.id);
|
||||
const commit = await syncRepo(project.gitUrl, dir, await forgejoToken(app, userId));
|
||||
|
||||
await ctx.progress({ message: 'Analyse du code par Claude…', pct: 10 });
|
||||
const { prompt, system } = analyzePrompt(project.name);
|
||||
const model = await getSetting(db, 'analyze_model', 'haiku');
|
||||
const model = await getSetting(db, userId, 'analyze_model', 'haiku');
|
||||
const sink = makeSink();
|
||||
const r = await claude({
|
||||
const r = await claude(userId, {
|
||||
prompt, system, cwd: dir, model, maxTurns: 20, tools: ['Read', 'Glob', 'Grep'], signal: ctx.signal,
|
||||
onTurn: (n) => sink.push(() => ctx.progress({ message: `Lecture du code par Claude (étape ${n})…`, pct: turnPct(10, 95, n, 20) })),
|
||||
});
|
||||
|
|
@ -181,14 +183,15 @@ export function makeHandlers(app) {
|
|||
},
|
||||
|
||||
async prospect(ctx) {
|
||||
const project = await getProject(app, ctx.job.project_id);
|
||||
const userId = ctx.job.user_id;
|
||||
const project = await getProject(app, ctx.job.project_id, { userId });
|
||||
if (!project.profile || !project.targetValidated) throw new Error('Valide la cible du projet avant de prospecter');
|
||||
const count = Math.max(1, Math.min(50, Math.floor(Number(ctx.params.count) || 10)));
|
||||
|
||||
// Domaines déjà connus (tous projets) : Claude ne les recherche pas une 2e fois
|
||||
// Domaines déjà connus de ce projet : Claude ne les recherche pas une 2e fois. La liste d'opposition,
|
||||
// commune à tous les comptes, n'entre pas dans le prompt (elle est appliquée à l'insertion, ci-dessous).
|
||||
const exclude = (await db.prepare(`
|
||||
SELECT DISTINCT substr(email, instr(email, '@') + 1) d FROM prospects WHERE project_id = ?
|
||||
UNION SELECT substr(email, instr(email, '@') + 1) FROM blacklist
|
||||
LIMIT 300`).all(project.id)).map((r) => r.d);
|
||||
|
||||
// Deux requêtes plutôt qu'un INSERT ... SELECT sans FROM (non portable) ; l'unicité (projet, email) reste garantie par la base
|
||||
|
|
@ -226,8 +229,8 @@ export function makeHandlers(app) {
|
|||
};
|
||||
await report();
|
||||
const { prompt, system } = prospectPrompt({ profile: project.profile, target: project.target, count, exclude });
|
||||
const model = await getSetting(db, 'prospect_model', 'haiku');
|
||||
const r = await claude({
|
||||
const model = await getSetting(db, userId, 'prospect_model', 'haiku');
|
||||
const r = await claude(userId, {
|
||||
prompt, system, model, tools: ['WebSearch', 'WebFetch'],
|
||||
maxTurns, onText, signal: ctx.signal,
|
||||
onTurn: (n) => { turns = n; sink.push(report); },
|
||||
|
|
@ -239,11 +242,12 @@ export function makeHandlers(app) {
|
|||
},
|
||||
|
||||
async template(ctx) {
|
||||
const project = await getProject(app, ctx.job.project_id, { secrets: true });
|
||||
const userId = ctx.job.user_id;
|
||||
const project = await getProject(app, ctx.job.project_id, { userId, secrets: true });
|
||||
if (!project.profile) throw new Error('Analyse le projet d\'abord');
|
||||
await ctx.progress({ message: 'Rédaction du modèle par Claude…', pct: 40 });
|
||||
const { prompt, system } = templatePrompt({ profile: project.profile, target: project.target || {}, senderName: project.smtp?.fromName });
|
||||
const r = await claude({ prompt, system, model: 'haiku', maxTurns: 1, tools: [], signal: ctx.signal });
|
||||
const r = await claude(userId, { prompt, system, model: 'haiku', maxTurns: 1, tools: [], signal: ctx.signal });
|
||||
addUsage(ctx, r);
|
||||
const t = extractJson(r.text);
|
||||
if (!t.subject || !t.body) throw new Error('Modèle de mail invalide');
|
||||
|
|
@ -252,11 +256,12 @@ export function makeHandlers(app) {
|
|||
},
|
||||
|
||||
async followup_template(ctx) {
|
||||
const project = await getProject(app, ctx.job.project_id, { secrets: true });
|
||||
const userId = ctx.job.user_id;
|
||||
const project = await getProject(app, ctx.job.project_id, { userId, secrets: true });
|
||||
if (!project.profile) throw new Error('Analyse le projet d\'abord');
|
||||
await ctx.progress({ message: 'Rédaction de la relance par Claude…', pct: 40 });
|
||||
const { prompt, system } = followupTemplatePrompt({ profile: project.profile, senderName: project.smtp?.fromName });
|
||||
const r = await claude({ prompt, system, model: 'haiku', maxTurns: 1, tools: [], signal: ctx.signal });
|
||||
const r = await claude(userId, { prompt, system, model: 'haiku', maxTurns: 1, tools: [], signal: ctx.signal });
|
||||
addUsage(ctx, r);
|
||||
const t = extractJson(r.text);
|
||||
if (!t.body) throw new Error('Modèle de relance invalide');
|
||||
|
|
@ -268,23 +273,24 @@ export function makeHandlers(app) {
|
|||
followup: (ctx) => sendMails(ctx, 'followup'),
|
||||
|
||||
async evolution(ctx) {
|
||||
const project = await getProject(app, ctx.job.project_id, { secrets: true });
|
||||
const userId = ctx.job.user_id;
|
||||
const project = await getProject(app, ctx.job.project_id, { userId, secrets: true });
|
||||
const count = Math.max(1, Math.min(20, Math.floor(Number(ctx.params.count) || 5)));
|
||||
const level = LEVELS[ctx.params.level] ? ctx.params.level : 'normal';
|
||||
const to = await getSetting(db, 'notify_email');
|
||||
const smtp = (await globalSmtp(app)) || project.smtp;
|
||||
const to = await getSetting(db, userId, 'notify_email');
|
||||
const smtp = (await globalSmtp(app, userId)) || project.smtp;
|
||||
if (!to) throw new Error('Adresse de réception non configurée (Réglages)');
|
||||
if (!smtp) throw new Error('Aucun SMTP configuré (Réglages ou projet)');
|
||||
|
||||
await ctx.progress({ message: 'Mise à jour du repo…', pct: 3 });
|
||||
const dir = repoDir(cfg, project.id);
|
||||
await syncRepo(project.gitUrl, dir, await forgejoToken(app));
|
||||
const dir = repoDir(cfg, userId, project.id);
|
||||
await syncRepo(project.gitUrl, dir, await forgejoToken(app, userId));
|
||||
|
||||
await ctx.progress({ message: `Recherche de ${count} évolutions (${level})…`, pct: 10 });
|
||||
const { prompt, system } = evolutionPrompt({ projectName: project.name, profile: project.profile, count, level });
|
||||
const { model, maxTurns } = LEVELS[level];
|
||||
const sink = makeSink();
|
||||
const r = await claude({
|
||||
const r = await claude(userId, {
|
||||
prompt, system, cwd: dir, model, maxTurns, tools: ['Read', 'Glob', 'Grep'], signal: ctx.signal,
|
||||
onTurn: (n) => sink.push(() => ctx.progress({ message: `Recherche de ${count} évolutions (${level}) · étape ${n}…`, pct: turnPct(10, 90, n, maxTurns) })),
|
||||
});
|
||||
|
|
|
|||
|
|
@ -3,7 +3,8 @@ import { now, getSetting } from './db.js';
|
|||
import { encryptJson, decryptJson, decrypt } from './crypto.js';
|
||||
import { HttpError } from './http.js';
|
||||
|
||||
export const repoDir = (cfg, id) => join(cfg.dataDir, 'repos', String(id));
|
||||
// Un dossier de clones par utilisateur : data/repos/<utilisateur>/<projet>
|
||||
export const repoDir = (cfg, userId, id) => join(cfg.dataDir, 'repos', String(Number(userId)), String(Number(id)));
|
||||
|
||||
const parse = (s) => (s ? JSON.parse(s) : null);
|
||||
|
||||
|
|
@ -14,11 +15,16 @@ function readSecret(key, payload, what) {
|
|||
catch { console.warn(`[secrets] ${what} illisible (SECRET_KEY changée ?), à ressaisir`); return null; }
|
||||
}
|
||||
|
||||
export async function getProject(app, id, { secrets = false } = {}) {
|
||||
const p = await app.db.prepare('SELECT * FROM projects WHERE id = ?').get(Number(id));
|
||||
/**
|
||||
* Projet d'un utilisateur. `userId` est obligatoire : un projet d'un autre compte est introuvable (404),
|
||||
* exactement comme un projet qui n'existe pas. Les tâches de fond passent le propriétaire lu en base.
|
||||
*/
|
||||
export async function getProject(app, id, { userId, secrets = false } = {}) {
|
||||
if (!Number.isInteger(Number(userId)) || Number(userId) <= 0) throw new Error('getProject : userId requis');
|
||||
const p = await app.db.prepare('SELECT * FROM projects WHERE id = ? AND user_id = ?').get(Number(id), Number(userId));
|
||||
if (!p) throw new HttpError(404, 'Projet introuvable');
|
||||
const out = {
|
||||
id: p.id, name: p.name, gitUrl: p.git_url,
|
||||
id: p.id, userId: Number(p.user_id), name: p.name, gitUrl: p.git_url,
|
||||
profile: parse(p.profile_json), profileCommit: p.profile_commit, profileAt: p.profile_at,
|
||||
target: parse(p.target_json), targetValidated: !!p.target_validated,
|
||||
dailyMailCap: p.daily_mail_cap, createdAt: p.created_at,
|
||||
|
|
@ -35,13 +41,13 @@ export async function getProject(app, id, { secrets = false } = {}) {
|
|||
return out;
|
||||
}
|
||||
|
||||
export async function listProjects(app) {
|
||||
const rows = await app.db.prepare('SELECT id FROM projects ORDER BY LOWER(name)').all();
|
||||
return Promise.all(rows.map((r) => getProject(app, r.id)));
|
||||
export async function listProjects(app, userId) {
|
||||
const rows = await app.db.prepare('SELECT id FROM projects WHERE user_id = ? ORDER BY LOWER(name)').all(Number(userId));
|
||||
return Promise.all(rows.map((r) => getProject(app, r.id, { userId })));
|
||||
}
|
||||
|
||||
export async function createProject(app, { name, gitUrl }) {
|
||||
const r = await app.db.prepare('INSERT INTO projects(name, git_url, created_at) VALUES(?, ?, ?)').run(name, gitUrl, now());
|
||||
export async function createProject(app, { userId, name, gitUrl }) {
|
||||
const r = await app.db.prepare('INSERT INTO projects(user_id, name, git_url, created_at) VALUES(?, ?, ?, ?)').run(Number(userId), name, gitUrl, now());
|
||||
return Number(r.lastInsertRowid);
|
||||
}
|
||||
|
||||
|
|
@ -62,13 +68,13 @@ export function publicConfig(cfg, secretField) {
|
|||
return { ...rest, [`${secretField}Set`]: !!_omit };
|
||||
}
|
||||
|
||||
export async function forgejoToken(app) {
|
||||
try { return decrypt(app.cfg.secretKey, await getSetting(app.db, 'forgejo_token_enc')); }
|
||||
export async function forgejoToken(app, userId) {
|
||||
try { return decrypt(app.cfg.secretKey, await getSetting(app.db, userId, 'forgejo_token_enc')); }
|
||||
catch { console.warn('[secrets] token Forgejo illisible, à ressaisir'); return null; }
|
||||
}
|
||||
|
||||
export async function globalSmtp(app) {
|
||||
return readSecret(app.cfg.secretKey, await getSetting(app.db, 'smtp_enc'), 'SMTP global');
|
||||
export async function globalSmtp(app, userId) {
|
||||
return readSecret(app.cfg.secretKey, await getSetting(app.db, userId, 'smtp_enc'), 'SMTP global');
|
||||
}
|
||||
|
||||
export async function prospectStats(db, projectId) {
|
||||
|
|
@ -78,11 +84,14 @@ export async function prospectStats(db, projectId) {
|
|||
return out;
|
||||
}
|
||||
|
||||
export async function sentSince(db, since, projectId = null) {
|
||||
const sql = projectId == null
|
||||
? 'SELECT COUNT(*) n FROM mail_log WHERE sent_at > ? AND error IS NULL'
|
||||
: 'SELECT COUNT(*) n FROM mail_log WHERE sent_at > ? AND error IS NULL AND project_id = ?';
|
||||
return (projectId == null ? await db.prepare(sql).get(since) : await db.prepare(sql).get(since, projectId)).n;
|
||||
/** Envois réussis depuis `since` : tous les projets de l'utilisateur, ou un seul projet (déjà vérifié comme étant le sien). */
|
||||
export async function sentSince(db, since, userId, projectId = null) {
|
||||
if (projectId == null) {
|
||||
return (await db.prepare(`SELECT COUNT(*) n FROM mail_log m JOIN projects p ON p.id = m.project_id
|
||||
WHERE m.sent_at > ? AND m.error IS NULL AND p.user_id = ?`).get(since, Number(userId))).n;
|
||||
}
|
||||
return (await db.prepare(`SELECT COUNT(*) n FROM mail_log m JOIN projects p ON p.id = m.project_id
|
||||
WHERE m.sent_at > ? AND m.error IS NULL AND p.user_id = ? AND m.project_id = ?`).get(since, Number(userId), projectId)).n;
|
||||
}
|
||||
|
||||
// IMAP : utilisateur vide = mêmes identifiants que le SMTP du projet (cas le plus courant)
|
||||
|
|
|
|||
294
src/routes.js
294
src/routes.js
|
|
@ -1,7 +1,7 @@
|
|||
import { now, getSetting, setSetting } from './db.js';
|
||||
import { encrypt, encryptJson, decryptJson, verifyUnsubToken } from './crypto.js';
|
||||
import { html, json, redirect, readBody, HttpError } from './http.js';
|
||||
import { startGoogleLogin, finishGoogleLogin, destroySession } from './auth.js';
|
||||
import { startLogin, finishLogin, destroySession } from './auth.js';
|
||||
import { loginPage, dashboardPage, settingsPage, unsubPage } from './views.js';
|
||||
import { enqueue, latestJobs, cancelJob, usageSummary } from './services/jobs.js';
|
||||
import { validateGitUrl, removeRepo } from './services/git.js';
|
||||
|
|
@ -32,12 +32,27 @@ const pid = (params) => Number(params.id);
|
|||
export function registerRoutes(router, app) {
|
||||
const { db, cfg } = app;
|
||||
|
||||
// Toute ressource métier est lue AVEC l'utilisateur courant : celle d'un autre compte est « introuvable » (404)
|
||||
const project = (ctx, opts) => getProject(app, pid(ctx.params), { userId: ctx.session.userId, ...opts });
|
||||
|
||||
// ---------- Public ----------
|
||||
router.get('/login', async ({ res, url }) => html(res, loginPage(url.searchParams.get('e'))), { public: true });
|
||||
router.get('/auth/google', async ({ res }) => startGoogleLogin(db, cfg, res), { public: true });
|
||||
router.get('/auth/google/callback', async ({ res, url }) => {
|
||||
try { await finishGoogleLogin(db, cfg, url, res); }
|
||||
catch (e) { redirect(res, `/login?e=${encodeURIComponent(e.message)}`); }
|
||||
router.get('/login', async ({ res, url }) => html(res, loginPage(url.searchParams.get('e'), { apple: !!cfg.apple, bye: url.searchParams.has('bye') })), { public: true });
|
||||
// Erreur de connexion : message du serveur s'il est destiné à l'utilisateur, sinon générique (rien de technique à l'écran)
|
||||
const loginFailed = (res, e) => {
|
||||
if (!e.status || e.status >= 500) console.error('[connexion]', e);
|
||||
redirect(res, `/login?e=${encodeURIComponent(e.status && e.status < 500 ? e.message : 'Connexion impossible, réessaie dans un instant')}`);
|
||||
};
|
||||
router.get('/auth/google', async ({ res }) => startLogin(app, 'google', res), { public: true });
|
||||
router.get('/auth/google/callback', async ({ req, res, url }) => {
|
||||
try { await finishLogin(app, 'google', url.searchParams, req, res); }
|
||||
catch (e) { loginFailed(res, e); }
|
||||
}, { public: true });
|
||||
// Apple : le retour est un POST cross-site (response_mode=form_post), donc public et sans contrôle d'origine ;
|
||||
// la protection repose sur state + nonce + cookie de liaison (voir auth.js)
|
||||
router.get('/auth/apple', async ({ res }) => startLogin(app, 'apple', res), { public: true });
|
||||
router.post('/auth/apple/callback', async ({ req, res }) => {
|
||||
try { await finishLogin(app, 'apple', await readBody(req), req, res); }
|
||||
catch (e) { loginFailed(res, e); }
|
||||
}, { public: true });
|
||||
|
||||
// Désinscription (RGPD). GET = page de confirmation (évite les désinscriptions par les scanners de liens),
|
||||
|
|
@ -60,125 +75,142 @@ export function registerRoutes(router, app) {
|
|||
router.post('/logout', async ({ req, res }) => { await destroySession(db, req, res); redirect(res, '/login'); });
|
||||
|
||||
router.get('/', async ({ res, session }) => {
|
||||
const userId = session.userId;
|
||||
const projects = [];
|
||||
for (const p of await listProjects(app)) {
|
||||
const full = await getProject(app, p.id, { secrets: true });
|
||||
for (const p of await listProjects(app, userId)) {
|
||||
const full = await getProject(app, p.id, { userId, secrets: true });
|
||||
projects.push({ project: p, smtp: publicConfig(full.smtp, 'pass'), dbCfg: publicConfig(full.dbCfg, 'password'), imap: publicConfig(full.imapCfg, 'pass') });
|
||||
}
|
||||
html(res, dashboardPage({ email: session.email, projects, forgejoHost: await getSetting(db, 'forgejo_host') }));
|
||||
html(res, dashboardPage({
|
||||
email: session.email, projects, forgejoHost: await getSetting(db, userId, 'forgejo_host'),
|
||||
}));
|
||||
});
|
||||
|
||||
router.get('/settings', async ({ res, session, url }) => {
|
||||
const discord = await notifyConfig(app);
|
||||
const userId = session.userId;
|
||||
const discord = await notifyConfig(app, userId);
|
||||
const s = {
|
||||
notify_email: await getSetting(db, 'notify_email', ''),
|
||||
forgejo_host: await getSetting(db, 'forgejo_host', ''),
|
||||
forgejo_token_set: !!await getSetting(db, 'forgejo_token_enc'),
|
||||
smtp: publicConfig(await globalSmtp(app), 'pass'),
|
||||
global_daily_cap: await getSetting(db, 'global_daily_cap', '100'),
|
||||
send_delay_min: await getSetting(db, 'send_delay_min', '20'),
|
||||
send_delay_max: await getSetting(db, 'send_delay_max', '60'),
|
||||
prospect_model: await getSetting(db, 'prospect_model', 'haiku'),
|
||||
analyze_model: await getSetting(db, 'analyze_model', 'haiku'),
|
||||
blacklist_count: (await db.prepare('SELECT COUNT(*) n FROM blacklist').get()).n,
|
||||
weekly_report: await getSetting(db, 'weekly_report', '0') === '1',
|
||||
budget_day_usd: await getSetting(db, 'budget_day_usd', ''),
|
||||
budget_month_usd: await getSetting(db, 'budget_month_usd', ''),
|
||||
notify_email: await getSetting(db, userId, 'notify_email', ''),
|
||||
forgejo_host: await getSetting(db, userId, 'forgejo_host', ''),
|
||||
forgejo_token_set: !!await getSetting(db, userId, 'forgejo_token_enc'),
|
||||
smtp: publicConfig(await globalSmtp(app, userId), 'pass'),
|
||||
global_daily_cap: await getSetting(db, userId, 'global_daily_cap', '100'),
|
||||
send_delay_min: await getSetting(db, userId, 'send_delay_min', '20'),
|
||||
send_delay_max: await getSetting(db, userId, 'send_delay_max', '60'),
|
||||
prospect_model: await getSetting(db, userId, 'prospect_model', 'haiku'),
|
||||
analyze_model: await getSetting(db, userId, 'analyze_model', 'haiku'),
|
||||
// La liste d'opposition est commune à tous les comptes : on n'en montre que ce qui touche SES prospects
|
||||
blacklist_count: (await db.prepare(`SELECT COUNT(DISTINCT x.email) n FROM prospects x JOIN projects p ON p.id = x.project_id
|
||||
WHERE p.user_id = ? AND x.email IN (SELECT email FROM blacklist)`).get(userId)).n,
|
||||
weekly_report: await getSetting(db, userId, 'weekly_report', '0') === '1',
|
||||
budget_day_usd: await getSetting(db, userId, 'budget_day_usd', ''),
|
||||
budget_month_usd: await getSetting(db, userId, 'budget_month_usd', ''),
|
||||
discord: { set: !!discord.url, events: discord.events, all: EVENTS },
|
||||
};
|
||||
html(res, settingsPage({ email: session.email, s, saved: url.searchParams.has('ok') }));
|
||||
});
|
||||
|
||||
router.post('/settings', async ({ req, res }) => {
|
||||
router.post('/settings', async ({ req, res, session }) => {
|
||||
const userId = session.userId;
|
||||
const set = (k, v) => setSetting(db, userId, k, v);
|
||||
const b = await readBody(req);
|
||||
if (b.notify_email && !EMAIL_RE.test(b.notify_email)) throw new HttpError(400, 'Email de réception invalide');
|
||||
await setSetting(db, 'notify_email', (b.notify_email || '').trim());
|
||||
await setSetting(db, 'forgejo_host', (b.forgejo_host || '').trim().replace(/^https?:\/\//, '').replace(/\/.*$/, ''));
|
||||
if (b.forgejo_token) await setSetting(db, 'forgejo_token_enc', encrypt(cfg.secretKey, b.forgejo_token.trim()));
|
||||
await set('notify_email', (b.notify_email || '').trim());
|
||||
await set('forgejo_host', (b.forgejo_host || '').trim().replace(/^https?:\/\//, '').replace(/\/.*$/, ''));
|
||||
if (b.forgejo_token) await set('forgejo_token_enc', encrypt(cfg.secretKey, b.forgejo_token.trim()));
|
||||
const cap = int(b.global_daily_cap, 1, 300, 100);
|
||||
const dmin = int(b.send_delay_min, 5, 3600, 20);
|
||||
const dmax = Math.max(dmin, int(b.send_delay_max, 5, 3600, 60));
|
||||
await setSetting(db, 'global_daily_cap', String(cap));
|
||||
await setSetting(db, 'send_delay_min', String(dmin));
|
||||
await setSetting(db, 'send_delay_max', String(dmax));
|
||||
await setSetting(db, 'prospect_model', b.prospect_model === 'sonnet' ? 'sonnet' : 'haiku');
|
||||
await setSetting(db, 'analyze_model', b.analyze_model === 'sonnet' ? 'sonnet' : 'haiku');
|
||||
await set('global_daily_cap', String(cap));
|
||||
await set('send_delay_min', String(dmin));
|
||||
await set('send_delay_max', String(dmax));
|
||||
await set('prospect_model', b.prospect_model === 'sonnet' ? 'sonnet' : 'haiku');
|
||||
await set('analyze_model', b.analyze_model === 'sonnet' ? 'sonnet' : 'haiku');
|
||||
const money = (v) => { const n = Number(String(v || '').replace(',', '.')); return Number.isFinite(n) && n > 0 ? String(Math.round(n * 100) / 100) : ''; };
|
||||
await setSetting(db, 'weekly_report', b.weekly_report === 'on' ? '1' : '0');
|
||||
await setSetting(db, 'budget_day_usd', money(b.budget_day_usd));
|
||||
await setSetting(db, 'budget_month_usd', money(b.budget_month_usd));
|
||||
await set('weekly_report', b.weekly_report === 'on' ? '1' : '0');
|
||||
await set('budget_day_usd', money(b.budget_day_usd));
|
||||
await set('budget_month_usd', money(b.budget_month_usd));
|
||||
|
||||
const hook = String(b.discord_webhook || '').trim();
|
||||
if (hook && !WEBHOOK_RE.test(hook)) throw new HttpError(400, 'URL de webhook Discord invalide (https://discord.com/api/webhooks/…)');
|
||||
if (hook) await setSetting(db, 'discord_webhook_enc', encrypt(cfg.secretKey, hook));
|
||||
if (b.discord_remove === 'on') await setSetting(db, 'discord_webhook_enc', null);
|
||||
await setSetting(db, 'discord_events', JSON.stringify(Object.keys(EVENTS).filter((k) => b[`ev_${k}`] === 'on')));
|
||||
if (hook) await set('discord_webhook_enc', encrypt(cfg.secretKey, hook));
|
||||
if (b.discord_remove === 'on') await set('discord_webhook_enc', null);
|
||||
await set('discord_events', JSON.stringify(Object.keys(EVENTS).filter((k) => b[`ev_${k}`] === 'on')));
|
||||
|
||||
const prev = await globalSmtp(app) || {};
|
||||
const prev = await globalSmtp(app, userId) || {};
|
||||
const smtp = { host: b.smtp_host, port: b.smtp_port, user: b.smtp_user, pass: b.smtp_pass || prev.pass, fromEmail: b.smtp_fromEmail };
|
||||
await setSetting(db, 'smtp_enc', smtp.host ? encryptJson(cfg.secretKey, smtp) : null);
|
||||
await set('smtp_enc', smtp.host ? encryptJson(cfg.secretKey, smtp) : null);
|
||||
redirect(res, '/settings?ok');
|
||||
});
|
||||
|
||||
// ---------- API JSON ----------
|
||||
router.post('/api/report/send', async ({ res }) => {
|
||||
const r = await sendWeeklyReport(app);
|
||||
router.post('/api/report/send', async ({ res, session }) => {
|
||||
const r = await sendWeeklyReport(app, session.userId);
|
||||
if (!r.channels.length) throw new HttpError(400, 'Configure le SMTP global + l\'email de réception, ou un webhook Discord');
|
||||
json(res, { ok: true, channels: r.channels });
|
||||
});
|
||||
|
||||
router.post('/api/notify/test', async ({ res }) => {
|
||||
if (!(await notifyConfig(app)).url) throw new HttpError(400, 'Aucun webhook Discord configuré');
|
||||
const ok = await notify(app, 'test', { title: 'Notification de test', description: 'Les notifications AiTools arrivent bien ici.', level: 'ok' }, { force: true });
|
||||
router.post('/api/notify/test', async ({ res, session }) => {
|
||||
if (!(await notifyConfig(app, session.userId)).url) throw new HttpError(400, 'Aucun webhook Discord configuré');
|
||||
const ok = await notify(app, session.userId, 'test', { title: 'Notification de test', description: 'Les notifications AiTools arrivent bien ici.', level: 'ok' }, { force: true });
|
||||
if (!ok) throw new HttpError(502, 'Discord a refusé la notification (webhook supprimé ?)');
|
||||
json(res, { ok: true });
|
||||
});
|
||||
|
||||
router.get('/api/system', async ({ res }) => {
|
||||
const queue = (await db.prepare(`SELECT COUNT(*) n FROM jobs WHERE status = 'running'
|
||||
OR (status = 'queued' AND (run_after IS NULL OR run_after <= ?))`).get(now())).n;
|
||||
const scheduled = (await db.prepare("SELECT COUNT(*) n FROM jobs WHERE status = 'queued' AND run_after > ?").get(now())).n;
|
||||
const rlRaw = await getSetting(db, 'claude_rate_limit_json');
|
||||
// Barre du haut : uniquement les jobs, l'usage et les quotas de l'utilisateur courant (la température du serveur, réservée aux admins)
|
||||
router.get('/api/system', async ({ res, session }) => {
|
||||
const userId = session.userId;
|
||||
const queue = (await db.prepare(`SELECT COUNT(*) n FROM jobs WHERE user_id = ? AND (status = 'running'
|
||||
OR (status = 'queued' AND (run_after IS NULL OR run_after <= ?)))`).get(userId, now())).n;
|
||||
const scheduled = (await db.prepare("SELECT COUNT(*) n FROM jobs WHERE user_id = ? AND status = 'queued' AND run_after > ?").get(userId, now())).n;
|
||||
const rlRaw = await getSetting(db, userId, 'claude_rate_limit_json');
|
||||
// Détail pour le menu « jobs » de la barre du haut : en cours d'abord, puis la file, puis les programmés
|
||||
const jobs = (await db.prepare(`SELECT j.id, j.type, j.status, j.progress_json, j.run_after, j.started_at, j.created_at, p.id pid, p.name project
|
||||
FROM jobs j LEFT JOIN projects p ON p.id = j.project_id
|
||||
WHERE j.status IN ('queued','running')
|
||||
ORDER BY j.status = 'running' DESC, COALESCE(j.run_after, 0), j.id LIMIT 20`).all()).map((r) => ({
|
||||
WHERE j.user_id = ? AND j.status IN ('queued','running')
|
||||
ORDER BY j.status = 'running' DESC, COALESCE(j.run_after, 0), j.id LIMIT 20`).all(userId)).map((r) => ({
|
||||
id: r.id, type: r.type, status: r.status, projectId: r.pid, project: r.project,
|
||||
progress: r.progress_json ? JSON.parse(r.progress_json) : null,
|
||||
runAfter: r.run_after, startedAt: r.started_at, createdAt: r.created_at,
|
||||
}));
|
||||
json(res, {
|
||||
temp: cpuTemp(), queue, scheduled, jobs, usage: await usageSummary(db), budget: await budgetState(db), thermalMax: cfg.thermalMax,
|
||||
temp: session.user.isAdmin ? cpuTemp() : null, queue, scheduled, jobs, usage: await usageSummary(db, userId), budget: await budgetState(db, userId), thermalMax: cfg.thermalMax,
|
||||
claudeRateLimit: rlRaw ? JSON.parse(rlRaw) : null,
|
||||
});
|
||||
});
|
||||
|
||||
router.post('/api/projects', async ({ req, res }) => {
|
||||
router.post('/api/projects', async ({ req, res, session }) => {
|
||||
const userId = session.userId;
|
||||
const b = await readBody(req);
|
||||
const name = String(b.name || '').trim().slice(0, 80);
|
||||
if (!name) throw new HttpError(400, 'Nom requis');
|
||||
const host = await getSetting(db, 'forgejo_host');
|
||||
const host = await getSetting(db, userId, 'forgejo_host');
|
||||
if (!host) throw new HttpError(400, "Configure l'hôte Forgejo dans Réglages");
|
||||
let gitUrl;
|
||||
try { gitUrl = validateGitUrl(String(b.gitUrl || '').trim(), host); }
|
||||
catch (e) { throw new HttpError(400, e.message); }
|
||||
if (await db.prepare('SELECT 1 FROM projects WHERE git_url = ?').get(gitUrl)) throw new HttpError(409, 'Ce dépôt est déjà un projet');
|
||||
const id = await createProject(app, { name, gitUrl });
|
||||
await enqueue(db, { projectId: id, type: 'analyze' });
|
||||
// Un même dépôt peut être un projet pour deux comptes différents : l'unicité est par utilisateur
|
||||
const exists = () => db.prepare('SELECT 1 FROM projects WHERE user_id = ? AND git_url = ?').get(userId, gitUrl);
|
||||
if (await exists()) throw new HttpError(409, 'Ce dépôt est déjà un projet');
|
||||
let id;
|
||||
try { id = await createProject(app, { userId, name, gitUrl }); }
|
||||
catch (e) { if (await exists()) throw new HttpError(409, 'Ce dépôt est déjà un projet'); throw e; }
|
||||
await enqueue(db, { userId, projectId: id, type: 'analyze' });
|
||||
json(res, { id });
|
||||
});
|
||||
|
||||
router.post('/api/projects/:id/delete', async ({ res, params }) => {
|
||||
const p = await getProject(app, pid(params));
|
||||
await db.prepare('DELETE FROM projects WHERE id = ?').run(p.id);
|
||||
removeRepo(repoDir(cfg, p.id));
|
||||
router.post('/api/projects/:id/delete', async (ctx) => {
|
||||
const p = await project(ctx);
|
||||
await db.prepare('DELETE FROM projects WHERE id = ? AND user_id = ?').run(p.id, ctx.session.userId);
|
||||
removeRepo(repoDir(cfg, ctx.session.userId, p.id));
|
||||
clearRecapCache(p.id);
|
||||
json(res, { ok: true });
|
||||
json(ctx.res, { ok: true });
|
||||
});
|
||||
|
||||
router.get('/api/projects/:id/status', async ({ res, params }) => {
|
||||
const p = await getProject(app, pid(params));
|
||||
router.get('/api/projects/:id/status', async (ctx) => {
|
||||
const { res, session } = ctx;
|
||||
const userId = session.userId;
|
||||
const p = await project(ctx);
|
||||
const jobs = await latestJobs(db, p.id);
|
||||
// Rendu côté serveur (échappé) : le front n'injecte jamais le Markdown brut de Claude
|
||||
if (jobs.evolution?.result?.markdown) jobs.evolution.result.html = evolutionHtml(jobs.evolution.result.markdown);
|
||||
|
|
@ -188,8 +220,8 @@ export function registerRoutes(router, app) {
|
|||
const day = now() - 86400;
|
||||
const sendMax = allowedToSend({
|
||||
requested: 100, available: stats.new || 0,
|
||||
projectCap: p.dailyMailCap, sentTodayProject: await sentSince(db, day, p.id),
|
||||
globalCap: Number(await getSetting(db, 'global_daily_cap', '100')), sentTodayGlobal: await sentSince(db, day),
|
||||
projectCap: p.dailyMailCap, sentTodayProject: await sentSince(db, day, userId, p.id),
|
||||
globalCap: Number(await getSetting(db, userId, 'global_daily_cap', '100')), sentTodayGlobal: await sentSince(db, day, userId),
|
||||
});
|
||||
json(res, {
|
||||
jobs, templates, stats, sendMax,
|
||||
|
|
@ -199,8 +231,9 @@ export function registerRoutes(router, app) {
|
|||
});
|
||||
});
|
||||
|
||||
router.post('/api/projects/:id/target', async ({ req, res, params }) => {
|
||||
const p = await getProject(app, pid(params));
|
||||
router.post('/api/projects/:id/target', async (ctx) => {
|
||||
const { req, res } = ctx;
|
||||
const p = await project(ctx);
|
||||
const b = await readBody(req);
|
||||
const target = {
|
||||
description: String(b.description || '').slice(0, 300),
|
||||
|
|
@ -215,14 +248,15 @@ export function registerRoutes(router, app) {
|
|||
json(res, { ok: true });
|
||||
});
|
||||
|
||||
const jobRoute = (type, paramsOf = () => ({}), guard = () => {}) => async ({ req, res, params }) => {
|
||||
const p = await getProject(app, pid(params));
|
||||
const jobRoute = (type, paramsOf = () => ({}), guard = () => {}) => async (ctx) => {
|
||||
const { req, res, session } = ctx;
|
||||
const p = await project(ctx);
|
||||
const b = req.headers['content-type']?.includes('json') ? await readBody(req) : {};
|
||||
await guard(p, b);
|
||||
// "Cette nuit" : démarrage au prochain créneau 1h-6h (Pi au frais, quota Claude libre)
|
||||
const runAfter = b.when === 'night' ? Math.floor(nextNightSlot().getTime() / 1000) : null;
|
||||
const r = await enqueue(db, { projectId: p.id, type, params: paramsOf(b), runAfter });
|
||||
const budget = AI_JOBS.has(type) ? await budgetState(db) : null;
|
||||
const r = await enqueue(db, { userId: session.userId, projectId: p.id, type, params: paramsOf(b), runAfter });
|
||||
const budget = AI_JOBS.has(type) ? await budgetState(db, session.userId) : null;
|
||||
json(res, { ...r, budgetBlocked: budget?.blocked ? budget.reason : null });
|
||||
};
|
||||
|
||||
|
|
@ -233,8 +267,9 @@ export function registerRoutes(router, app) {
|
|||
router.post('/api/projects/:id/followup_template', jobRoute('followup_template', () => ({}), (p) => {
|
||||
if (!p.profile) throw new HttpError(400, "Analyse le projet d'abord");
|
||||
}));
|
||||
router.post('/api/projects/:id/followup', async ({ req, res, params }) => {
|
||||
const p = await getProject(app, pid(params));
|
||||
router.post('/api/projects/:id/followup', async (ctx) => {
|
||||
const { req, res } = ctx;
|
||||
const p = await project(ctx);
|
||||
const b = await readBody(req);
|
||||
const enabled = b.enabled === true || b.enabled === 'on';
|
||||
await db.prepare('UPDATE projects SET followup_enabled = ?, followup_days = ? WHERE id = ?').run(enabled ? 1 : 0, int(b.days, 2, 30, 7), p.id);
|
||||
|
|
@ -253,8 +288,9 @@ export function registerRoutes(router, app) {
|
|||
if (running) throw new HttpError(409, 'La recherche de prospects est encore en cours');
|
||||
}));
|
||||
|
||||
router.post('/api/projects/:id/template/save', async ({ req, res, params }) => {
|
||||
const p = await getProject(app, pid(params));
|
||||
router.post('/api/projects/:id/template/save', async (ctx) => {
|
||||
const { req, res } = ctx;
|
||||
const p = await project(ctx);
|
||||
const b = await readBody(req);
|
||||
const subject = String(b.subject || '').trim().slice(0, 200);
|
||||
const body = String(b.body || '').trim().slice(0, 5000);
|
||||
|
|
@ -267,8 +303,9 @@ export function registerRoutes(router, app) {
|
|||
json(res, { ok: true, status });
|
||||
});
|
||||
|
||||
router.post('/api/projects/:id/smtp', async ({ req, res, params }) => {
|
||||
const p = await getProject(app, pid(params));
|
||||
router.post('/api/projects/:id/smtp', async (ctx) => {
|
||||
const { req, res } = ctx;
|
||||
const p = await project(ctx);
|
||||
const b = await readBody(req);
|
||||
if (b.fromEmail && !EMAIL_RE.test(b.fromEmail)) throw new HttpError(400, 'Email expéditeur invalide');
|
||||
await saveSecretConfig(app, p.id, 'smtp_enc', {
|
||||
|
|
@ -280,8 +317,9 @@ export function registerRoutes(router, app) {
|
|||
});
|
||||
|
||||
// Boîte de réception : on enregistre puis on teste tout de suite la connexion
|
||||
router.post('/api/projects/:id/imap', async ({ req, res, params }) => {
|
||||
const p = await getProject(app, pid(params));
|
||||
router.post('/api/projects/:id/imap', async (ctx) => {
|
||||
const { req, res, session } = ctx;
|
||||
const p = await project(ctx);
|
||||
const b = await readBody(req);
|
||||
const host = String(b.host || '').trim();
|
||||
if (!host) {
|
||||
|
|
@ -291,18 +329,20 @@ export function registerRoutes(router, app) {
|
|||
await saveSecretConfig(app, p.id, 'imap_enc', {
|
||||
host, port: int(b.port, 1, 65535, 993), user: String(b.user || '').trim(), pass: b.pass || '',
|
||||
}, 'pass');
|
||||
try { json(res, { ok: true, check: await checkInbox(app, p.id) }); }
|
||||
try { json(res, { ok: true, check: await checkInbox(app, session.userId, p.id) }); }
|
||||
catch (e) { json(res, { ok: false, error: e.message }); }
|
||||
});
|
||||
|
||||
router.post('/api/projects/:id/inbox/check', async ({ res, params }) => {
|
||||
const p = await getProject(app, pid(params));
|
||||
try { json(res, { ok: true, check: await checkInbox(app, p.id) }); }
|
||||
router.post('/api/projects/:id/inbox/check', async (ctx) => {
|
||||
const { res, session } = ctx;
|
||||
const p = await project(ctx);
|
||||
try { json(res, { ok: true, check: await checkInbox(app, session.userId, p.id) }); }
|
||||
catch (e) { throw new HttpError(502, e.message); }
|
||||
});
|
||||
|
||||
router.post('/api/projects/:id/db', async ({ req, res, params }) => {
|
||||
const p = await getProject(app, pid(params));
|
||||
router.post('/api/projects/:id/db', async (ctx) => {
|
||||
const { req, res } = ctx;
|
||||
const p = await project(ctx);
|
||||
const b = await readBody(req);
|
||||
for (const k of ['sql_users', 'sql_clients', 'sql_revenue']) {
|
||||
try { validateSelect(b[k]); } catch (e) { throw new HttpError(400, `${k} : ${e.message}`); }
|
||||
|
|
@ -317,10 +357,11 @@ export function registerRoutes(router, app) {
|
|||
json(res, { ok: true });
|
||||
});
|
||||
|
||||
router.get('/api/projects/:id/recap', async ({ res, params, url }) => {
|
||||
const p = await getProject(app, pid(params), { secrets: true });
|
||||
router.get('/api/projects/:id/recap', async (ctx) => {
|
||||
const { res, url } = ctx;
|
||||
const p = await project(ctx, { secrets: true });
|
||||
const stats = await prospectStats(db, p.id);
|
||||
const cost = (await db.prepare('SELECT COALESCE(SUM(cost_usd),0) c FROM jobs WHERE project_id = ?').get(p.id)).c;
|
||||
const cost = (await db.prepare('SELECT COALESCE(SUM(cost_usd),0) c FROM jobs WHERE project_id = ? AND user_id = ?').get(p.id, ctx.session.userId)).c;
|
||||
let business = null, error = null;
|
||||
try {
|
||||
business = await fetchRecap(p.id, p.dbCfg, { force: url.searchParams.has('force') });
|
||||
|
|
@ -329,8 +370,9 @@ export function registerRoutes(router, app) {
|
|||
json(res, { business, error, stats, aiCostUsd: cost });
|
||||
});
|
||||
|
||||
router.get('/api/projects/:id/prospects\\.csv', async ({ res, params, url }) => {
|
||||
const p = await getProject(app, pid(params));
|
||||
router.get('/api/projects/:id/prospects\\.csv', async (ctx) => {
|
||||
const { res, url } = ctx;
|
||||
const p = await project(ctx);
|
||||
const slug = p.name.normalize('NFD').replace(/[^\w-]+/g, '-').replace(/^-|-$/g, '').toLowerCase() || 'projet';
|
||||
const date = new Date().toLocaleDateString('sv-SE', { timeZone: 'Europe/Paris' });
|
||||
res.writeHead(200, {
|
||||
|
|
@ -341,59 +383,67 @@ export function registerRoutes(router, app) {
|
|||
res.end(await exportProspects(db, p.id, parseFilters(url.searchParams)));
|
||||
});
|
||||
|
||||
router.post('/api/projects/:id/prospects/import', async ({ req, res, params }) => {
|
||||
const p = await getProject(app, pid(params));
|
||||
router.post('/api/projects/:id/prospects/import', async (ctx) => {
|
||||
const { req, res } = ctx;
|
||||
const p = await project(ctx);
|
||||
const b = await readBody(req, { max: 1024 * 1024 });
|
||||
try { json(res, await importProspects(db, p.id, String(b.csv || ''))); }
|
||||
catch (e) { throw new HttpError(400, e.message); }
|
||||
});
|
||||
|
||||
router.get('/api/projects/:id/history', async ({ res, params, url }) => {
|
||||
const p = await getProject(app, pid(params));
|
||||
router.get('/api/projects/:id/history', async (ctx) => {
|
||||
const { res, url } = ctx;
|
||||
const p = await project(ctx);
|
||||
json(res, await history(db, p.id, { days: url.searchParams.get('days') === '90' ? 90 : 30 }));
|
||||
});
|
||||
|
||||
router.get('/api/projects/:id/prospects', async ({ res, params, url }) => {
|
||||
const p = await getProject(app, pid(params));
|
||||
router.get('/api/projects/:id/prospects', async (ctx) => {
|
||||
const { res, url } = ctx;
|
||||
const p = await project(ctx);
|
||||
json(res, await listProspects(db, p.id, parseFilters(url.searchParams)));
|
||||
});
|
||||
|
||||
const STATUSES = Object.keys(PROSPECT_STATUSES);
|
||||
router.post('/api/prospects/:id/status', async ({ req, res, params }) => {
|
||||
// ---------- Fiche prospect ----------
|
||||
// Un prospect n'est accessible que par le propriétaire de son projet ; sinon 404, comme s'il n'existait pas
|
||||
const ownedProspect = async ({ params, session }) => {
|
||||
const row = await db.prepare(`SELECT x.id, x.email FROM prospects x JOIN projects p ON p.id = x.project_id
|
||||
WHERE x.id = ? AND p.user_id = ?`).get(Number(params.id), session.userId);
|
||||
if (!row) throw new HttpError(404, 'Prospect introuvable');
|
||||
return row;
|
||||
};
|
||||
router.post('/api/prospects/:id/status', async (ctx) => {
|
||||
const { req, res } = ctx;
|
||||
const b = await readBody(req);
|
||||
if (!STATUSES.includes(b.status)) throw new HttpError(400, 'Statut invalide');
|
||||
const r = await db.prepare('UPDATE prospects SET status = ? WHERE id = ?').run(b.status, Number(params.id));
|
||||
if (!r.changes) throw new HttpError(404, 'Prospect introuvable');
|
||||
const row = await ownedProspect(ctx);
|
||||
await db.prepare('UPDATE prospects SET status = ? WHERE id = ?').run(b.status, row.id);
|
||||
if (b.status === 'refused') {
|
||||
const { email } = await db.prepare('SELECT email FROM prospects WHERE id = ?').get(Number(params.id));
|
||||
await db.prepare("INSERT OR IGNORE INTO blacklist(email, reason, created_at) VALUES(?, 'refused', ?)").run(email, now());
|
||||
await db.prepare("INSERT OR IGNORE INTO blacklist(email, reason, created_at) VALUES(?, 'refused', ?)").run(row.email, now());
|
||||
}
|
||||
json(res, { ok: true });
|
||||
});
|
||||
|
||||
// ---------- Fiche prospect ----------
|
||||
const prospectId = async (params) => {
|
||||
const id = Number(params.id);
|
||||
if (!(await db.prepare('SELECT 1 FROM prospects WHERE id = ?').get(id))) throw new HttpError(404, 'Prospect introuvable');
|
||||
return id;
|
||||
};
|
||||
router.get('/api/prospects/:id', async ({ res, params }) => json(res, await prospectDetail(db, await prospectId(params))));
|
||||
router.post('/api/prospects/:id/notes', async ({ req, res, params }) => {
|
||||
const id = await prospectId(params);
|
||||
const noteId = await addNote(db, id, (await readBody(req)).body);
|
||||
router.get('/api/prospects/:id', async (ctx) => json(ctx.res, await prospectDetail(db, (await ownedProspect(ctx)).id)));
|
||||
router.post('/api/prospects/:id/notes', async (ctx) => {
|
||||
const id = (await ownedProspect(ctx)).id;
|
||||
const noteId = await addNote(db, id, (await readBody(ctx.req)).body);
|
||||
if (!noteId) throw new HttpError(400, 'Note vide');
|
||||
json(res, { ok: true, id: noteId });
|
||||
json(ctx.res, { ok: true, id: noteId });
|
||||
});
|
||||
router.post('/api/prospects/:id/notes/:nid/delete', async ({ res, params }) => {
|
||||
if (!await deleteNote(db, await prospectId(params), Number(params.nid))) throw new HttpError(404, 'Note introuvable');
|
||||
json(res, { ok: true });
|
||||
router.post('/api/prospects/:id/notes/:nid/delete', async (ctx) => {
|
||||
if (!await deleteNote(db, (await ownedProspect(ctx)).id, Number(ctx.params.nid))) throw new HttpError(404, 'Note introuvable');
|
||||
json(ctx.res, { ok: true });
|
||||
});
|
||||
router.post('/api/prospects/:id/next', async ({ req, res, params }) => {
|
||||
const id = await prospectId(params);
|
||||
const b = await readBody(req);
|
||||
try { json(res, { ok: true, at: await setNextAction(db, id, b.action, b.day) }); }
|
||||
router.post('/api/prospects/:id/next', async (ctx) => {
|
||||
const id = (await ownedProspect(ctx)).id;
|
||||
const b = await readBody(ctx.req);
|
||||
try { json(ctx.res, { ok: true, at: await setNextAction(db, id, b.action, b.day) }); }
|
||||
catch (e) { throw new HttpError(400, e.message); }
|
||||
});
|
||||
|
||||
router.post('/api/jobs/:id/cancel', async ({ res, params }) => { await cancelJob(db, Number(params.id)); json(res, { ok: true }); });
|
||||
router.post('/api/jobs/:id/cancel', async ({ res, params, session }) => {
|
||||
await cancelJob(db, session.userId, Number(params.id));
|
||||
json(res, { ok: true });
|
||||
});
|
||||
}
|
||||
|
|
|
|||
|
|
@ -6,6 +6,7 @@ import { loadConfig } from './config.js';
|
|||
import { openDb } from './db.js';
|
||||
import { Router, json, redirect, html, HttpError } from './http.js';
|
||||
import { getSession, checkOrigin, purgeExpired } from './auth.js';
|
||||
import { syncAdmins } from './users.js';
|
||||
import { registerRoutes } from './routes.js';
|
||||
import { Worker } from './services/jobs.js';
|
||||
import { makeHandlers } from './handlers.js';
|
||||
|
|
@ -31,7 +32,8 @@ const SECURITY_HEADERS = {
|
|||
};
|
||||
|
||||
export async function createApp(cfg, { db, worker = true, createTransport } = {}) {
|
||||
db ??= await openDb(cfg.db);
|
||||
db ??= await openDb(cfg.db, { adminEmails: cfg.adminEmails });
|
||||
await syncAdmins(db, cfg.adminEmails || []); // ADMIN_EMAILS fait foi pour le rôle admin
|
||||
const app = { db, cfg, createTransport };
|
||||
const router = new Router();
|
||||
registerRoutes(router, app);
|
||||
|
|
@ -76,19 +78,19 @@ export async function createApp(cfg, { db, worker = true, createTransport } = {}
|
|||
w = new Worker(db, makeHandlers(app), {
|
||||
thermalMax: cfg.thermalMax,
|
||||
onFinish: (job, r) => notifyJob(app, job, r),
|
||||
budget: () => budgetState(db),
|
||||
budget: (userId) => budgetState(db, userId),
|
||||
isAiJob: (type) => AI_JOBS.has(type),
|
||||
onBudget: (reason) => notify(app, 'budget', {
|
||||
onBudget: (reason, userId) => notify(app, userId, 'budget', {
|
||||
title: 'Budget IA atteint', level: 'warn',
|
||||
description: `${reason[0].toUpperCase()}${reason.slice(1)}. Les jobs IA attendent ; les envois et relances continuent.`,
|
||||
}),
|
||||
quota: () => quotaState(db),
|
||||
quota: (userId) => quotaState(db, userId),
|
||||
isQuotaSensitive,
|
||||
onQuotaHold: (reason) => notify(app, 'quota', {
|
||||
onQuotaHold: (reason, userId) => notify(app, userId, 'quota', {
|
||||
title: 'Job IA reporté (quota serré)', level: 'warn',
|
||||
description: `${reason[0].toUpperCase()}${reason.slice(1)}. Analyse et évolutions attendent ; prospection et envois continuent.`,
|
||||
}),
|
||||
onThermal: (t) => notify(app, 'thermal', {
|
||||
onThermal: (t, userId) => notify(app, userId, 'thermal', {
|
||||
title: 'Pause thermique', level: 'warn',
|
||||
description: `CPU à ${t} °C : les jobs IA attendent que le Pi redescende sous ${cfg.thermalMax - 5} °C.`,
|
||||
}),
|
||||
|
|
@ -118,6 +120,7 @@ export async function createApp(cfg, { db, worker = true, createTransport } = {}
|
|||
|
||||
if (process.argv[1] === fileURLToPath(import.meta.url)) {
|
||||
const cfg = loadConfig();
|
||||
if (!cfg.adminEmails.length) console.warn('ADMIN_EMAILS est vide : aucun administrateur (personne ne pourra lancer de job IA).');
|
||||
const app = await createApp(cfg);
|
||||
app.server.listen(cfg.port, cfg.host, () => console.log(`AiTools sur http://${cfg.host}:${cfg.port} (${cfg.appUrl})`));
|
||||
const shutdown = () => app.close().then(() => process.exit(0), (e) => { console.error(e); process.exit(1); });
|
||||
|
|
|
|||
|
|
@ -7,20 +7,20 @@ export const AI_JOBS = new Set(['analyze', 'prospect', 'template', 'followup_tem
|
|||
|
||||
const usd = (n) => `${n.toFixed(2)} $`;
|
||||
|
||||
// La dépense compte au moment où le job s'est terminé (un job de nuit compte la nuit)
|
||||
async function spentSince(db, since) {
|
||||
return (await db.prepare('SELECT COALESCE(SUM(cost_usd), 0) c FROM jobs WHERE COALESCE(finished_at, created_at) > ?').get(since)).c;
|
||||
// La dépense compte au moment où le job s'est terminé (un job de nuit compte la nuit). Budget propre à chaque utilisateur.
|
||||
async function spentSince(db, userId, since) {
|
||||
return (await db.prepare('SELECT COALESCE(SUM(cost_usd), 0) c FROM jobs WHERE user_id = ? AND COALESCE(finished_at, created_at) > ?').get(userId, since)).c;
|
||||
}
|
||||
|
||||
async function limit(db, key) {
|
||||
const v = Number(await getSetting(db, key, ''));
|
||||
async function limit(db, userId, key) {
|
||||
const v = Number(await getSetting(db, userId, key, ''));
|
||||
return Number.isFinite(v) && v > 0 ? v : null;
|
||||
}
|
||||
|
||||
/** @returns {{day: {used:number, limit:number|null}, month: {used:number, limit:number|null}, blocked: boolean, reason: string|null}} */
|
||||
export async function budgetState(db, { at = now() } = {}) {
|
||||
const day = { used: await spentSince(db, at - 86400), limit: await limit(db, 'budget_day_usd') };
|
||||
const month = { used: await spentSince(db, at - 30 * 86400), limit: await limit(db, 'budget_month_usd') };
|
||||
export async function budgetState(db, userId, { at = now() } = {}) {
|
||||
const day = { used: await spentSince(db, userId, at - 86400), limit: await limit(db, userId, 'budget_day_usd') };
|
||||
const month = { used: await spentSince(db, userId, at - 30 * 86400), limit: await limit(db, userId, 'budget_month_usd') };
|
||||
const over = (x) => x.limit != null && x.used >= x.limit;
|
||||
const reason = over(day) ? `budget IA des dernières 24 h atteint (${usd(day.used)} / ${usd(day.limit)})`
|
||||
: over(month) ? `budget IA des 30 derniers jours atteint (${usd(month.used)} / ${usd(month.limit)})`
|
||||
|
|
@ -40,8 +40,8 @@ export const QUOTA_PAUSE_THRESHOLD = 0.85;
|
|||
const WINDOW_LABELS = { fiveHour: 'session Claude (5 h)', sevenDay: 'semaine Claude' };
|
||||
|
||||
/** @returns {{blocked: boolean, reason: string|null}} */
|
||||
export async function quotaState(db) {
|
||||
const raw = await getSetting(db, 'claude_rate_limit_json');
|
||||
export async function quotaState(db, userId) {
|
||||
const raw = await getSetting(db, userId, 'claude_rate_limit_json');
|
||||
if (!raw) return { blocked: false, reason: null };
|
||||
let rl;
|
||||
try { rl = JSON.parse(raw); } catch { return { blocked: false, reason: null }; }
|
||||
|
|
@ -58,10 +58,10 @@ export async function quotaState(db) {
|
|||
const ALERT_LEVELS = [0.95, 0.80];
|
||||
|
||||
/** Renvoie les paliers nouvellement franchis et enregistre l'état pour ne pas re-notifier. */
|
||||
export async function quotaAlerts(db, windows) {
|
||||
export async function quotaAlerts(db, userId, windows) {
|
||||
if (!windows) return [];
|
||||
let prev = {};
|
||||
try { prev = JSON.parse((await getSetting(db, 'claude_quota_notified_json', '{}')) || '{}'); } catch { prev = {}; }
|
||||
try { prev = JSON.parse((await getSetting(db, userId, 'claude_quota_notified_json', '{}')) || '{}'); } catch { prev = {}; }
|
||||
const next = { ...prev };
|
||||
const alerts = [];
|
||||
for (const [key, label] of Object.entries(WINDOW_LABELS)) {
|
||||
|
|
@ -73,6 +73,6 @@ export async function quotaAlerts(db, windows) {
|
|||
if (crossed) alerts.push({ label, level: Math.round(crossed * 100), utilization: w.utilization });
|
||||
next[key] = { resetsAt: w.resetsAt, level: crossed ? Math.round(crossed * 100) : state.level };
|
||||
}
|
||||
await setSetting(db, 'claude_quota_notified_json', JSON.stringify(next));
|
||||
await setSetting(db, userId, 'claude_quota_notified_json', JSON.stringify(next));
|
||||
return alerts;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -65,7 +65,10 @@ export async function prospectDetail(db, id) {
|
|||
const mails = await db.prepare(`SELECT kind, subject, variant, sent_at, error FROM mail_log
|
||||
WHERE prospect_id = ? ORDER BY sent_at, id`).all(id);
|
||||
const notes = await db.prepare('SELECT id, body, created_at FROM prospect_notes WHERE prospect_id = ? ORDER BY created_at DESC, id DESC').all(id);
|
||||
const optOut = (await db.prepare('SELECT reason, created_at FROM blacklist WHERE email = ?').get(p.email)) || null;
|
||||
// La liste d'opposition est commune à tous les comptes : on n'en révèle que le strict nécessaire. Le motif d'un
|
||||
// autre compte (refus, adresse invalide) n'est pas montré ; seule la désinscription, acte de la personne elle-même, l'est.
|
||||
const row = await db.prepare('SELECT reason FROM blacklist WHERE email = ?').get(p.email);
|
||||
const optOut = row ? { reason: row.reason === 'unsubscribe' ? 'unsubscribe' : p.status === 'bounced' ? 'bounce' : 'refused' } : null;
|
||||
return { prospect: p, mails, notes, optOut };
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -143,9 +143,9 @@ export async function fetchInbox(creds, state, { since, max = 500 }) {
|
|||
}
|
||||
|
||||
/** Vérifie la boîte d'un projet et mémorise l'état (dernier UID, erreurs, compteurs). */
|
||||
export async function checkInbox(app, projectId) {
|
||||
export async function checkInbox(app, userId, projectId) {
|
||||
const { db } = app;
|
||||
const project = await getProject(app, projectId, { secrets: true });
|
||||
const project = await getProject(app, projectId, { userId, secrets: true });
|
||||
if (!project.imap) throw new Error('Boîte IMAP non configurée');
|
||||
const state = project.inbox || {};
|
||||
const firstSent = (await db.prepare('SELECT MIN(sent_at) t FROM mail_log WHERE project_id = ?').get(project.id)).t;
|
||||
|
|
@ -161,7 +161,7 @@ export async function checkInbox(app, projectId) {
|
|||
});
|
||||
if (res.replies) {
|
||||
const who = await db.prepare('SELECT company, email, reply_subject FROM prospects WHERE project_id = ? AND replied_at = ? LIMIT 10').all(project.id, at);
|
||||
await notify(app, 'reply', {
|
||||
await notify(app, userId, 'reply', {
|
||||
title: `${project.name} · ${res.replies} réponse(s) de prospect`, level: 'ok',
|
||||
description: who.map((p) => `**${p.company}** (${p.email}) : ${p.reply_subject || 'sans objet'}`).join('\n'),
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,27 +1,42 @@
|
|||
// File de jobs en base, UN seul worker : un seul `claude` à la fois.
|
||||
import { now } from '../db.js';
|
||||
import { HttpError } from '../http.js';
|
||||
import { getUser } from '../users.js';
|
||||
import { waitCool } from './thermal.js';
|
||||
|
||||
export async function enqueue(db, { projectId, type, params = {}, runAfter = null }) {
|
||||
/**
|
||||
* Met un job en file pour un utilisateur. Point de passage obligé de toutes les routes et tâches de fond :
|
||||
* - le projet doit appartenir à l'utilisateur (sinon 404) ;
|
||||
* - un compte suspendu ne met rien en file ;
|
||||
* Sans projet, `userId` est obligatoire.
|
||||
*/
|
||||
export async function enqueue(db, { userId, projectId, type, params = {}, runAfter = null }) {
|
||||
if (projectId != null) {
|
||||
const owner = await db.prepare('SELECT user_id FROM projects WHERE id = ?').get(projectId);
|
||||
if (!owner || (userId != null && Number(owner.user_id) !== Number(userId))) throw new HttpError(404, 'Projet introuvable');
|
||||
userId = Number(owner.user_id);
|
||||
}
|
||||
const user = userId == null ? null : await getUser(db, userId);
|
||||
if (!user) throw new Error('enqueue : utilisateur requis');
|
||||
if (user.status !== 'active') throw new HttpError(403, 'Compte suspendu');
|
||||
// Deux écritures de la même condition : "= ?" ne marche pas avec NULL, et "IS ?" n'existe pas en MySQL
|
||||
const running = projectId == null
|
||||
? await db.prepare("SELECT id FROM jobs WHERE project_id IS NULL AND type = ? AND status IN ('queued','running')").get(type)
|
||||
? await db.prepare("SELECT id FROM jobs WHERE user_id = ? AND project_id IS NULL AND type = ? AND status IN ('queued','running')").get(user.id, type)
|
||||
: await db.prepare("SELECT id FROM jobs WHERE project_id = ? AND type = ? AND status IN ('queued','running')").get(projectId, type);
|
||||
if (running) return { id: running.id, existing: true };
|
||||
const r = await db.prepare('INSERT INTO jobs(project_id, type, params_json, created_at, run_after) VALUES(?, ?, ?, ?, ?)')
|
||||
.run(projectId ?? null, type, JSON.stringify(params), now(), runAfter);
|
||||
const r = await db.prepare('INSERT INTO jobs(user_id, project_id, type, params_json, created_at, run_after) VALUES(?, ?, ?, ?, ?, ?)')
|
||||
.run(user.id, projectId ?? null, type, JSON.stringify(params), now(), runAfter);
|
||||
return { id: Number(r.lastInsertRowid), existing: false };
|
||||
}
|
||||
|
||||
export async function setProgress(db, jobId, progress) {
|
||||
await db.prepare('UPDATE jobs SET progress_json = ? WHERE id = ?').run(JSON.stringify(progress), jobId);
|
||||
}
|
||||
|
||||
export async function cancelJob(db, jobId) {
|
||||
await db.prepare("UPDATE jobs SET status = 'cancelled', finished_at = ? WHERE id = ? AND status IN ('queued','running')")
|
||||
.run(now(), jobId);
|
||||
/** Annule un job de l'utilisateur ; un job d'un autre compte est introuvable. */
|
||||
export async function cancelJob(db, userId, jobId) {
|
||||
const r = await db.prepare("UPDATE jobs SET status = 'cancelled', finished_at = ? WHERE id = ? AND user_id = ? AND status IN ('queued','running')")
|
||||
.run(now(), jobId, userId);
|
||||
if (!r.changes && !(await db.prepare('SELECT 1 FROM jobs WHERE id = ? AND user_id = ?').get(jobId, userId))) throw new HttpError(404, 'Job introuvable');
|
||||
}
|
||||
|
||||
/** Derniers jobs d'un projet (le projet doit déjà avoir été vérifié comme appartenant à l'utilisateur). */
|
||||
export async function latestJobs(db, projectId) {
|
||||
const rows = await db.prepare(`
|
||||
SELECT j.* FROM jobs j
|
||||
|
|
@ -45,16 +60,16 @@ export class Worker {
|
|||
budget, isAiJob, onBudget, quota, isQuotaSensitive, onQuotaHold,
|
||||
} = {}) {
|
||||
this.clock = clock;
|
||||
this.budget = budget; // async () => {blocked, reason}
|
||||
this.budget = budget; // async (userId) => {blocked, reason} : budget de CET utilisateur
|
||||
this.isAiJob = isAiJob; // (type) => bool : jobs à mettre en attente si budget ($ équivalent) atteint
|
||||
this.onBudget = onBudget; // (reason) → une notif quand le blocage commence
|
||||
this.budgetBlocked = false;
|
||||
this.quota = quota; // async () => {blocked, reason} : quota du compte Claude lui-même (session/semaine)
|
||||
this.onBudget = onBudget; // (reason, userId) → une notif quand le blocage commence
|
||||
this.budgetBlocked = new Set(); // utilisateurs dont les jobs IA attendent (budget)
|
||||
this.quota = quota; // async (userId) => {blocked, reason} : quota du compte Claude lui-même (session/semaine)
|
||||
this.isQuotaSensitive = isQuotaSensitive; // (type) => bool : jobs à reporter si le quota est serré (pas la prospection/l'envoi)
|
||||
this.onQuotaHold = onQuotaHold; // (reason) → une notif quand le report commence
|
||||
this.quotaBlocked = false;
|
||||
this.onQuotaHold = onQuotaHold; // (reason, userId) → une notif quand le report commence
|
||||
this.quotaBlocked = new Set();
|
||||
this.onFinish = onFinish; // (job, {status, result, error}) → notifications
|
||||
this.onThermal = onThermal; // (°C) → une fois par pause
|
||||
this.onThermal = onThermal; // (°C, userId) → une fois par pause
|
||||
this.db = db;
|
||||
this.handlers = handlers;
|
||||
this.thermalMax = thermalMax;
|
||||
|
|
@ -121,25 +136,30 @@ export class Worker {
|
|||
// Budget $ atteint ou quota du compte Claude serré : les jobs concernés restent en file
|
||||
// (pas perdus), les autres passent devant. Deux garde-fous indépendants, deux périmètres :
|
||||
// le budget met en pause TOUS les jobs IA, le quota ne retarde que les jobs non urgents
|
||||
// (analyse, évolutions) — la prospection et les envois continuent.
|
||||
const budget = (await this.budget?.()) || { blocked: false };
|
||||
const quota = (await this.quota?.()) || { blocked: false };
|
||||
// (analyse, évolutions) — la prospection et les envois continuent. Chaque utilisateur a les siens.
|
||||
const budgets = new Map(), quotas = new Map();
|
||||
const perUser = async (cache, fn, userId) => {
|
||||
if (!cache.has(userId)) cache.set(userId, (await fn?.(userId)) || { blocked: false });
|
||||
return cache.get(userId);
|
||||
};
|
||||
const hold = async (j, reason) => {
|
||||
const msg = JSON.stringify({ message: `En attente : ${reason}` });
|
||||
if (j.progress_json !== msg) await this.db.prepare('UPDATE jobs SET progress_json = ? WHERE id = ?').run(msg, j.id);
|
||||
};
|
||||
let job = null;
|
||||
let waiting = false, quotaWaiting = false;
|
||||
const waiting = new Map(), quotaWaiting = new Map();
|
||||
for (const j of due) {
|
||||
if (budget.blocked && this.isAiJob?.(j.type)) { waiting = true; await hold(j, budget.reason); continue; }
|
||||
if (quota.blocked && this.isQuotaSensitive?.(j.type)) { quotaWaiting = true; await hold(j, quota.reason); continue; }
|
||||
const budget = await perUser(budgets, this.budget, j.user_id);
|
||||
if (budget.blocked && this.isAiJob?.(j.type)) { waiting.set(j.user_id, budget.reason); await hold(j, budget.reason); continue; }
|
||||
const quota = await perUser(quotas, this.quota, j.user_id);
|
||||
if (quota.blocked && this.isQuotaSensitive?.(j.type)) { quotaWaiting.set(j.user_id, quota.reason); await hold(j, quota.reason); continue; }
|
||||
job = j;
|
||||
break;
|
||||
}
|
||||
if (waiting && !this.budgetBlocked) this.emit('onBudget', budget.reason);
|
||||
this.budgetBlocked = waiting;
|
||||
if (quotaWaiting && !this.quotaBlocked) this.emit('onQuotaHold', quota.reason);
|
||||
this.quotaBlocked = quotaWaiting;
|
||||
for (const [userId, reason] of waiting) if (!this.budgetBlocked.has(userId)) this.emit('onBudget', reason, userId);
|
||||
this.budgetBlocked = new Set(waiting.keys());
|
||||
for (const [userId, reason] of quotaWaiting) if (!this.quotaBlocked.has(userId)) this.emit('onQuotaHold', reason, userId);
|
||||
this.quotaBlocked = new Set(quotaWaiting.keys());
|
||||
if (!job) return false;
|
||||
const handler = this.handlers[job.type];
|
||||
if (!handler) {
|
||||
|
|
@ -151,7 +171,7 @@ export class Worker {
|
|||
await waitCool(this.thermalMax, {
|
||||
onWait: async (t) => {
|
||||
await setProgress(this.db, job.id, { message: `Pause thermique (${t} °C)` });
|
||||
if (!warned) { warned = true; this.emit('onThermal', t); }
|
||||
if (!warned) { warned = true; this.emit('onThermal', t, job.user_id); }
|
||||
},
|
||||
});
|
||||
|
||||
|
|
@ -201,10 +221,10 @@ export function addUsage(ctx, r) {
|
|||
}
|
||||
|
||||
// Conso des 30 derniers jours, pour la jauge (comptée à la fin du job, comme le budget)
|
||||
export async function usageSummary(db) {
|
||||
export async function usageSummary(db, userId) {
|
||||
const since = now() - 30 * 86400;
|
||||
const day = now() - 86400;
|
||||
const q = (s) => db.prepare(`SELECT COALESCE(SUM(cost_usd),0) cost, COALESCE(SUM(tokens_in),0) tin, COALESCE(SUM(tokens_out),0) tout, COUNT(*) n
|
||||
FROM jobs WHERE COALESCE(finished_at, created_at) > ?`).get(s);
|
||||
FROM jobs WHERE user_id = ? AND COALESCE(finished_at, created_at) > ?`).get(userId, s);
|
||||
return { month: await q(since), day: await q(day) };
|
||||
}
|
||||
|
|
|
|||
|
|
@ -18,12 +18,13 @@ export async function saveSnapshot(db, projectId, business, { date = new Date()
|
|||
/** Une photo par projet et par jour, appelée par le planificateur (toutes les 15 min, ne fait rien si déjà prise). */
|
||||
export async function snapshotAll(app, { date = new Date(), log = console } = {}) {
|
||||
const day = parisDay(date);
|
||||
const todo = await app.db.prepare(`SELECT id FROM projects WHERE db_enc IS NOT NULL
|
||||
AND id NOT IN (SELECT project_id FROM metrics_daily WHERE day = ?)`).all(day);
|
||||
const todo = await app.db.prepare(`SELECT p.id, p.user_id FROM projects p JOIN users u ON u.id = p.user_id
|
||||
WHERE p.db_enc IS NOT NULL AND u.status = 'active'
|
||||
AND p.id NOT IN (SELECT project_id FROM metrics_daily WHERE day = ?)`).all(day);
|
||||
let n = 0;
|
||||
for (const { id } of todo) {
|
||||
for (const { id, user_id: userId } of todo) {
|
||||
try {
|
||||
const p = await getProject(app, id, { secrets: true });
|
||||
const p = await getProject(app, id, { userId, secrets: true });
|
||||
await saveSnapshot(app.db, id, await (app.fetchRecap || fetchRecap)(id, p.dbCfg, { force: true }), { date });
|
||||
n++;
|
||||
} catch (e) { log.error(`[métriques ${id}]`, e.message); }
|
||||
|
|
|
|||
|
|
@ -31,18 +31,18 @@ export function bar(done, total, width = 12) {
|
|||
return `${'▰'.repeat(full)}${'▱'.repeat(width - full)} ${Math.round(r * 100)} %`;
|
||||
}
|
||||
|
||||
export async function notifyConfig(app) {
|
||||
export async function notifyConfig(app, userId) {
|
||||
let url = null;
|
||||
try { url = decrypt(app.cfg.secretKey, await getSetting(app.db, 'discord_webhook_enc')); }
|
||||
try { url = decrypt(app.cfg.secretKey, await getSetting(app.db, userId, 'discord_webhook_enc')); }
|
||||
catch { url = null; }
|
||||
const raw = await getSetting(app.db, 'discord_events');
|
||||
const raw = await getSetting(app.db, userId, 'discord_events');
|
||||
const events = raw ? JSON.parse(raw) : Object.keys(EVENTS);
|
||||
return { url, events };
|
||||
}
|
||||
|
||||
/** Envoie une notif si le webhook est configuré et l'événement activé. Ne lève jamais d'erreur. */
|
||||
export async function notify(app, event, { title, description = '', level = 'info', fields = [], footer }, { force = false } = {}) {
|
||||
const { url, events } = await notifyConfig(app);
|
||||
export async function notify(app, userId, event, { title, description = '', level = 'info', fields = [], footer }, { force = false } = {}) {
|
||||
const { url, events } = await notifyConfig(app, userId);
|
||||
if (!url || (!force && !events.includes(event))) return false;
|
||||
const body = {
|
||||
username: 'AiTools',
|
||||
|
|
@ -111,7 +111,7 @@ const LABEL = { analyze: 'Analyse', prospect: 'Recherche', template: 'Modèle de
|
|||
// Durée et coût réels, relus en base une fois le job clos (absents dans les tests unitaires)
|
||||
async function jobMeta(app, job) {
|
||||
if (!job.id) return [];
|
||||
const row = await app.db.prepare('SELECT started_at, finished_at, cost_usd FROM jobs WHERE id = ?').get(job.id);
|
||||
const row = await app.db.prepare('SELECT started_at, finished_at, cost_usd FROM jobs WHERE id = ? AND user_id = ?').get(job.id, job.user_id);
|
||||
const out = [];
|
||||
if (row?.started_at && row?.finished_at) out.push({ name: '⏱️ Durée', value: duration(row.finished_at - row.started_at) });
|
||||
if (row?.cost_usd) out.push({ name: '💳 Coût IA', value: `${row.cost_usd.toFixed(2)} $` });
|
||||
|
|
@ -119,11 +119,11 @@ async function jobMeta(app, job) {
|
|||
}
|
||||
|
||||
export async function notifyJob(app, job, { status, result, error }) {
|
||||
const project = job.project_id ? (await app.db.prepare('SELECT name FROM projects WHERE id = ?').get(job.project_id))?.name : null;
|
||||
const project = job.project_id ? (await app.db.prepare('SELECT name FROM projects WHERE id = ? AND user_id = ?').get(job.project_id, job.user_id))?.name : null;
|
||||
const prefix = project ? `${project} · ` : '';
|
||||
const footer = project ? `${project} · ${LABEL[job.type] || job.type}` : undefined;
|
||||
if (status === 'error') {
|
||||
return notify(app, 'job_error', {
|
||||
return notify(app, job.user_id, 'job_error', {
|
||||
title: `${prefix}${LABEL[job.type] || job.type} en échec`, level: 'error', footer,
|
||||
description: `\`\`\`\n${String(error || 'Erreur inconnue').slice(0, 900).replace(/```/g, "'''")}\n\`\`\``,
|
||||
fields: await jobMeta(app, job),
|
||||
|
|
@ -132,7 +132,7 @@ export async function notifyJob(app, job, { status, result, error }) {
|
|||
if (status !== 'done') return false;
|
||||
if (job.type === 'followup') {
|
||||
if (!result?.sent) return false;
|
||||
return notify(app, 'followup', {
|
||||
return notify(app, job.user_id, 'followup', {
|
||||
title: `${prefix}Relances envoyées`, level: 'info', footer,
|
||||
description: `${result.sent} relance(s), ${result.failed} échec(s).\n${bar(result.sent, result.total || result.sent)}`,
|
||||
});
|
||||
|
|
@ -140,5 +140,5 @@ export async function notifyJob(app, job, { status, result, error }) {
|
|||
const make = DONE[job.type];
|
||||
if (!make) return false;
|
||||
const n = make(result);
|
||||
return notify(app, 'job_done', { ...n, title: `${prefix}${n.title}`, footer, fields: [...(n.fields || []), ...(await jobMeta(app, job))] });
|
||||
return notify(app, job.user_id, 'job_done', { ...n, title: `${prefix}${n.title}`, footer, fields: [...(n.fields || []), ...(await jobMeta(app, job))] });
|
||||
}
|
||||
|
|
|
|||
|
|
@ -10,11 +10,11 @@ const pct = (a, b) => (b ? `${Math.round((a / b) * 100)} %` : '-');
|
|||
const usd = (n) => `${n.toFixed(2)} $`;
|
||||
const day = (ts) => new Date(ts * 1000).toLocaleDateString('fr-FR', { day: '2-digit', month: '2-digit', timeZone: 'Europe/Paris' });
|
||||
|
||||
export async function weeklyStats(db, { at = now() } = {}) {
|
||||
export async function weeklyStats(db, userId, { at = now() } = {}) {
|
||||
const from = at - 7 * 86400;
|
||||
const one = async (sql, ...a) => (await db.prepare(sql).get(...a)).n;
|
||||
const projects = [];
|
||||
for (const p of await db.prepare('SELECT id, name FROM projects ORDER BY LOWER(name)').all()) {
|
||||
for (const p of await db.prepare('SELECT id, name FROM projects WHERE user_id = ? ORDER BY LOWER(name)').all(userId)) {
|
||||
const sent = await one("SELECT COUNT(*) n FROM mail_log WHERE project_id = ? AND kind = 'initial' AND error IS NULL AND sent_at > ?", p.id, from);
|
||||
const ab = await abStats(db, p.id);
|
||||
projects.push({
|
||||
|
|
@ -30,7 +30,7 @@ export async function weeklyStats(db, { at = now() } = {}) {
|
|||
bestSubject: ab.length > 1 && ab.every((v) => v.sent >= 10) ? [...ab].sort((a, b) => b.rate - a.rate)[0] : null,
|
||||
});
|
||||
}
|
||||
const cost = (await db.prepare('SELECT COALESCE(SUM(cost_usd), 0) c FROM jobs WHERE COALESCE(finished_at, created_at) > ?').get(from)).c;
|
||||
const cost = (await db.prepare('SELECT COALESCE(SUM(cost_usd), 0) c FROM jobs WHERE user_id = ? AND COALESCE(finished_at, created_at) > ?').get(userId, from)).c;
|
||||
const sum = (k) => projects.reduce((t, p) => t + p[k], 0);
|
||||
return { from, to: at, projects, totals: { found: sum('found'), sent: sum('sent'), followups: sum('followups'), replies: sum('replies'), cost } };
|
||||
}
|
||||
|
|
@ -55,12 +55,12 @@ export function weeklyText(st) {
|
|||
}
|
||||
|
||||
/** Envoie le rapport (mail si SMTP global + adresse, Discord si webhook). Retourne les canaux utilisés. */
|
||||
export async function sendWeeklyReport(app, { at = now() } = {}) {
|
||||
const st = await weeklyStats(app.db, { at });
|
||||
export async function sendWeeklyReport(app, userId, { at = now() } = {}) {
|
||||
const st = await weeklyStats(app.db, userId, { at });
|
||||
const text = weeklyText(st);
|
||||
const channels = [];
|
||||
const to = await getSetting(app.db, 'notify_email');
|
||||
const smtp = await globalSmtp(app);
|
||||
const to = await getSetting(app.db, userId, 'notify_email');
|
||||
const smtp = await globalSmtp(app, userId);
|
||||
if (to && smtp) {
|
||||
const transport = (app.createTransport || createTransport)(smtp);
|
||||
try {
|
||||
|
|
@ -73,7 +73,7 @@ export async function sendWeeklyReport(app, { at = now() } = {}) {
|
|||
}
|
||||
const t = st.totals;
|
||||
const active = st.projects.filter((p) => p.sent || p.found || p.replies);
|
||||
const ok = await notify(app, 'weekly', {
|
||||
const ok = await notify(app, userId, 'weekly', {
|
||||
title: `Rapport hebdo · ${day(st.from)} → ${day(st.to)}`, level: 'info',
|
||||
description: active.length
|
||||
? `**${t.sent}** mails · **${t.replies}** réponses (${pct(t.replies, t.sent)}) · **${t.found}** prospects trouvés`
|
||||
|
|
@ -93,15 +93,15 @@ export async function sendWeeklyReport(app, { at = now() } = {}) {
|
|||
}
|
||||
|
||||
/** Appelé toutes les 15 min : envoie une fois par semaine, le lundi à partir de 8h (Paris). */
|
||||
export async function maybeSendWeekly(app, { date = new Date() } = {}) {
|
||||
if ((await getSetting(app.db, 'weekly_report', '0')) !== '1') return null;
|
||||
export async function maybeSendWeekly(app, userId, { date = new Date() } = {}) {
|
||||
if ((await getSetting(app.db, userId, 'weekly_report', '0')) !== '1') return null;
|
||||
const p = parisParts(date);
|
||||
if (p.weekday !== 'Mon' || p.hour < 8) return null;
|
||||
const mondayAt8 = Math.floor(parisTime(p.year, p.month, p.day, 8).getTime() / 1000);
|
||||
if (Number(await getSetting(app.db, 'weekly_report_last', '0')) >= mondayAt8) return null;
|
||||
if (Number(await getSetting(app.db, userId, 'weekly_report_last', '0')) >= mondayAt8) return null;
|
||||
const at = Math.floor(date.getTime() / 1000);
|
||||
const r = await sendWeeklyReport(app, { at });
|
||||
const r = await sendWeeklyReport(app, userId, { at });
|
||||
// Rien de configuré : on ne marque pas, il partira dès qu'un canal existera
|
||||
if (r.channels.length) await setSetting(app.db, 'weekly_report_last', String(at));
|
||||
if (r.channels.length) await setSetting(app.db, userId, 'weekly_report_last', String(at));
|
||||
return r;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -42,14 +42,20 @@ export class Scheduler {
|
|||
if (this.running) return;
|
||||
this.running = true;
|
||||
try {
|
||||
const projects = await this.app.db.prepare('SELECT id FROM projects WHERE imap_enc IS NOT NULL').all();
|
||||
for (const { id } of projects) {
|
||||
try { await checkInbox(this.app, id); }
|
||||
// Les tâches de fond ne travaillent que pour les comptes actifs, projet par projet avec son propriétaire
|
||||
const projects = await this.app.db.prepare(`SELECT p.id, p.user_id FROM projects p JOIN users u ON u.id = p.user_id
|
||||
WHERE p.imap_enc IS NOT NULL AND u.status = 'active'`).all();
|
||||
for (const { id, user_id: userId } of projects) {
|
||||
try { await checkInbox(this.app, userId, id); }
|
||||
catch (e) { this.log.error(`[inbox ${id}]`, e.message); }
|
||||
}
|
||||
await this.queueFollowups();
|
||||
try { await maybeSendWeekly(this.app); }
|
||||
catch (e) { this.log.error('[rapport hebdo]', e.message); }
|
||||
const users = await this.app.db.prepare(`SELECT s.user_id FROM user_settings s JOIN users u ON u.id = s.user_id
|
||||
WHERE s.\`key\` = 'weekly_report' AND s.value = '1' AND u.status = 'active'`).all();
|
||||
for (const { user_id: userId } of users) {
|
||||
try { await maybeSendWeekly(this.app, userId); }
|
||||
catch (e) { this.log.error('[rapport hebdo]', e.message); }
|
||||
}
|
||||
await snapshotAll(this.app, { log: this.log });
|
||||
} finally { this.running = false; }
|
||||
}
|
||||
|
|
@ -57,9 +63,10 @@ export class Scheduler {
|
|||
async queueFollowups(opts) {
|
||||
const { db } = this.app;
|
||||
const queued = [];
|
||||
for (const { id } of await db.prepare('SELECT id FROM projects WHERE followup_enabled = 1').all()) {
|
||||
const plan = await followupPlan(db, await getProject(this.app, id), opts);
|
||||
if (plan.ready) queued.push({ id, ...await enqueue(db, { projectId: id, type: 'followup', params: { count: plan.due } }) });
|
||||
for (const { id, user_id: userId } of await db.prepare(`SELECT p.id, p.user_id FROM projects p JOIN users u ON u.id = p.user_id
|
||||
WHERE p.followup_enabled = 1 AND u.status = 'active'`).all()) {
|
||||
const plan = await followupPlan(db, await getProject(this.app, id, { userId }), opts);
|
||||
if (plan.ready) queued.push({ id, ...await enqueue(db, { userId, projectId: id, type: 'followup', params: { count: plan.due } }) });
|
||||
}
|
||||
return queued;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -329,7 +329,7 @@ ${saved ? '<p class="ok">Enregistré.</p>' : ''}
|
|||
|
||||
<section class="card">
|
||||
<h4>Liste d'opposition</h4>
|
||||
<p class="muted small">${s.blacklist_count} adresse(s) désinscrite(s). Elles ne seront plus jamais contactées, tous projets confondus.</p>
|
||||
<p class="muted small">${s.blacklist_count} de tes prospects ont demandé à ne plus être contactés. La liste d'opposition est commune à tous les comptes : une adresse désinscrite n'est plus jamais contactée, quel que soit le projet.</p>
|
||||
</section>`,
|
||||
});
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,15 +2,17 @@ import { test } from 'node:test';
|
|||
import assert from 'node:assert/strict';
|
||||
import { now, setSetting } from '../src/db.js';
|
||||
import { testDb } from './helpers/db.js';
|
||||
import { addUser } from './helpers/users.js';
|
||||
import { budgetState, AI_JOBS, quotaState, isQuotaSensitive, quotaAlerts } from '../src/services/budget.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());
|
||||
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);
|
||||
return { db, spend };
|
||||
const u = await addUser(db);
|
||||
await db.prepare("INSERT INTO projects(user_id, name, git_url, created_at) VALUES(?, 'p', 'u', ?)").run(u, now());
|
||||
const spend = (usd, finishedAgo, user = u) => db.prepare("INSERT INTO jobs(user_id, project_id, type, status, cost_usd, created_at, finished_at) VALUES(?, 1, 'prospect', 'done', ?, ?, ?)")
|
||||
.run(user, usd, now() - finishedAgo - 60, now() - finishedAgo);
|
||||
return { db, spend, u };
|
||||
}
|
||||
|
||||
test('budget : pas de limite par défaut, puis plafonds 24 h et 30 j glissants', async () => {
|
||||
|
|
@ -18,22 +20,22 @@ test('budget : pas de limite par défaut, puis plafonds 24 h et 30 j glissants',
|
|||
await s.spend(1.5, 3600); // il y a 1 h
|
||||
await s.spend(10, 5 * 86400); // il y a 5 jours
|
||||
await s.spend(99, 40 * 86400); // hors fenêtre
|
||||
let b = await budgetState(s.db);
|
||||
let b = await budgetState(s.db, s.u);
|
||||
assert.equal(b.blocked, false);
|
||||
assert.equal(b.day.used, 1.5);
|
||||
assert.equal(b.month.used, 11.5);
|
||||
|
||||
await setSetting(s.db, 'budget_day_usd', '2');
|
||||
assert.equal((await budgetState(s.db)).blocked, false);
|
||||
await setSetting(s.db, 'budget_day_usd', '1.5');
|
||||
b = await budgetState(s.db);
|
||||
await setSetting(s.db, s.u, 'budget_day_usd', '2');
|
||||
assert.equal((await budgetState(s.db, s.u)).blocked, false);
|
||||
await setSetting(s.db, s.u, 'budget_day_usd', '1.5');
|
||||
b = await budgetState(s.db, s.u);
|
||||
assert.equal(b.blocked, true);
|
||||
assert.equal(b.reason, 'budget IA des dernières 24 h atteint (1.50 $ / 1.50 $)');
|
||||
|
||||
await setSetting(s.db, 'budget_day_usd', '');
|
||||
await setSetting(s.db, 'budget_month_usd', '10');
|
||||
assert.match((await budgetState(s.db)).reason, /30 derniers jours atteint \(11\.50 \$ \/ 10\.00 \$\)/);
|
||||
assert.equal((await budgetState(s.db, { at: now() + 30 * 86400 })).blocked, false, 'la fenêtre glisse');
|
||||
await setSetting(s.db, s.u, 'budget_day_usd', '');
|
||||
await setSetting(s.db, s.u, 'budget_month_usd', '10');
|
||||
assert.match((await budgetState(s.db, s.u)).reason, /30 derniers jours atteint \(11\.50 \$ \/ 10\.00 \$\)/);
|
||||
assert.equal((await budgetState(s.db, s.u, { at: now() + 30 * 86400 })).blocked, false, 'la fenêtre glisse');
|
||||
});
|
||||
|
||||
test('les envois et relances ne consomment pas d\'IA', () => {
|
||||
|
|
@ -44,17 +46,17 @@ 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 () => {
|
||||
const s = await setup();
|
||||
await s.spend(5, 600);
|
||||
await setSetting(s.db, 'budget_day_usd', '3');
|
||||
await setSetting(s.db, s.u, 'budget_day_usd', '3');
|
||||
const ran = [];
|
||||
const alerts = [];
|
||||
const h = (name) => async () => { ran.push(name); };
|
||||
const w = new Worker(s.db, { prospect: h('prospect'), evolution: h('evolution'), send: h('send') }, {
|
||||
thermalMax: 999, log: { error() {} },
|
||||
budget: () => budgetState(s.db), isAiJob: (t) => AI_JOBS.has(t), onBudget: (r) => alerts.push(r),
|
||||
budget: (u) => budgetState(s.db, u), isAiJob: (t) => AI_JOBS.has(t), onBudget: (r) => alerts.push(r),
|
||||
});
|
||||
await enqueue(s.db, { projectId: 1, type: 'prospect' });
|
||||
await enqueue(s.db, { projectId: 1, type: 'send' });
|
||||
await enqueue(s.db, { projectId: 1, type: 'evolution' });
|
||||
await enqueue(s.db, { userId: s.u, projectId: 1, type: 'prospect' });
|
||||
await enqueue(s.db, { userId: s.u, projectId: 1, type: 'send' });
|
||||
await enqueue(s.db, { userId: s.u, projectId: 1, type: 'evolution' });
|
||||
|
||||
assert.equal(await w.tick(), true);
|
||||
assert.deepEqual(ran, ['send'], 'l\'envoi passe devant les jobs IA bloqués');
|
||||
|
|
@ -65,12 +67,12 @@ test('budget atteint : les jobs IA attendent (pas perdus), les envois passent, u
|
|||
assert.equal(jobs.prospect.status, 'queued');
|
||||
assert.match(jobs.prospect.progress.message, /^En attente : budget IA des dernières 24 h atteint/);
|
||||
|
||||
await setSetting(s.db, 'budget_day_usd', '20'); // ou la fenêtre de 24 h qui glisse
|
||||
await setSetting(s.db, s.u, 'budget_day_usd', '20'); // ou la fenêtre de 24 h qui glisse
|
||||
await w.tick(); await w.tick();
|
||||
assert.deepEqual(ran, ['send', 'prospect', 'evolution'], 'les jobs repartent tout seuls, dans l\'ordre');
|
||||
|
||||
await setSetting(s.db, 'budget_day_usd', '1');
|
||||
await enqueue(s.db, { projectId: 1, type: 'prospect' });
|
||||
await setSetting(s.db, s.u, 'budget_day_usd', '1');
|
||||
await enqueue(s.db, { userId: s.u, projectId: 1, type: 'prospect' });
|
||||
await w.tick();
|
||||
assert.equal(alerts.length, 2, 'nouvelle notif pour un nouveau blocage');
|
||||
});
|
||||
|
|
@ -82,33 +84,33 @@ test('analyse et évolutions sont "non urgents", pas la prospection ni l\'envoi'
|
|||
|
||||
test('quotaState : pas mesuré, en dessous du seuil, puis bloqué à 85 %', async () => {
|
||||
const s = await setup();
|
||||
assert.deepEqual(await quotaState(s.db), { blocked: false, reason: null });
|
||||
await setSetting(s.db, 'claude_rate_limit_json', JSON.stringify({ fiveHour: { utilization: 0.5 }, sevenDay: { utilization: 0.6 } }));
|
||||
assert.equal((await quotaState(s.db)).blocked, false);
|
||||
await setSetting(s.db, 'claude_rate_limit_json', JSON.stringify({ fiveHour: { utilization: 0.9 }, sevenDay: { utilization: 0.6 } }));
|
||||
let q = await quotaState(s.db);
|
||||
assert.deepEqual(await quotaState(s.db, s.u), { blocked: false, reason: null });
|
||||
await setSetting(s.db, s.u, 'claude_rate_limit_json', JSON.stringify({ fiveHour: { utilization: 0.5 }, sevenDay: { utilization: 0.6 } }));
|
||||
assert.equal((await quotaState(s.db, s.u)).blocked, false);
|
||||
await setSetting(s.db, s.u, 'claude_rate_limit_json', JSON.stringify({ fiveHour: { utilization: 0.9 }, sevenDay: { utilization: 0.6 } }));
|
||||
let q = await quotaState(s.db, s.u);
|
||||
assert.equal(q.blocked, true);
|
||||
assert.equal(q.reason, 'quota de la session Claude (5 h) à 90 %');
|
||||
await setSetting(s.db, 'claude_rate_limit_json', JSON.stringify({ fiveHour: { utilization: 0.1 }, sevenDay: { utilization: 0.99 } }));
|
||||
q = await quotaState(s.db);
|
||||
await setSetting(s.db, s.u, 'claude_rate_limit_json', JSON.stringify({ fiveHour: { utilization: 0.1 }, sevenDay: { utilization: 0.99 } }));
|
||||
q = await quotaState(s.db, s.u);
|
||||
assert.equal(q.reason, 'quota de la semaine Claude à 99 %');
|
||||
await setSetting(s.db, 'claude_rate_limit_json', 'pas du json');
|
||||
assert.deepEqual(await quotaState(s.db), { blocked: false, reason: null }, 'jamais planter sur une valeur corrompue');
|
||||
await setSetting(s.db, s.u, 'claude_rate_limit_json', 'pas du json');
|
||||
assert.deepEqual(await quotaState(s.db, s.u), { blocked: false, reason: null }, 'jamais planter sur une valeur corrompue');
|
||||
});
|
||||
|
||||
test('quota serré : analyse/évolution attendent, la prospection et l\'envoi continuent', async () => {
|
||||
const s = await setup();
|
||||
await setSetting(s.db, 'claude_rate_limit_json', JSON.stringify({ fiveHour: { utilization: 0.9 } }));
|
||||
await setSetting(s.db, s.u, 'claude_rate_limit_json', JSON.stringify({ fiveHour: { utilization: 0.9 } }));
|
||||
const ran = [];
|
||||
const alerts = [];
|
||||
const h = (name) => async () => { ran.push(name); };
|
||||
const w = new Worker(s.db, { prospect: h('prospect'), evolution: h('evolution'), analyze: h('analyze') }, {
|
||||
thermalMax: 999, log: { error() {} },
|
||||
quota: () => quotaState(s.db), isQuotaSensitive, onQuotaHold: (r) => alerts.push(r),
|
||||
quota: (u) => quotaState(s.db, u), isQuotaSensitive, onQuotaHold: (r) => alerts.push(r),
|
||||
});
|
||||
await enqueue(s.db, { projectId: 1, type: 'evolution' });
|
||||
await enqueue(s.db, { projectId: 1, type: 'analyze' });
|
||||
await enqueue(s.db, { projectId: 1, type: 'prospect' });
|
||||
await enqueue(s.db, { userId: s.u, projectId: 1, type: 'evolution' });
|
||||
await enqueue(s.db, { userId: s.u, projectId: 1, type: 'analyze' });
|
||||
await enqueue(s.db, { userId: s.u, projectId: 1, type: 'prospect' });
|
||||
|
||||
assert.equal(await w.tick(), true);
|
||||
assert.deepEqual(ran, ['prospect'], 'la prospection passe devant les jobs reportés');
|
||||
|
|
@ -117,27 +119,27 @@ test('quota serré : analyse/évolution attendent, la prospection et l\'envoi co
|
|||
const jobs = await latestJobs(s.db, 1);
|
||||
assert.match(jobs.evolution.progress.message, /^En attente : quota de la session/);
|
||||
|
||||
await setSetting(s.db, 'claude_rate_limit_json', JSON.stringify({ fiveHour: { utilization: 0.1 } }));
|
||||
await setSetting(s.db, s.u, 'claude_rate_limit_json', JSON.stringify({ fiveHour: { utilization: 0.1 } }));
|
||||
await w.tick(); await w.tick();
|
||||
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é', async () => {
|
||||
const s = await setup();
|
||||
let a = await quotaAlerts(s.db, { fiveHour: { utilization: 0.5, resetsAt: 100 } });
|
||||
let a = await quotaAlerts(s.db, s.u, { fiveHour: { utilization: 0.5, resetsAt: 100 } });
|
||||
assert.deepEqual(a, []);
|
||||
a = await quotaAlerts(s.db, { fiveHour: { utilization: 0.82, resetsAt: 100 } });
|
||||
a = await quotaAlerts(s.db, s.u, { fiveHour: { utilization: 0.82, resetsAt: 100 } });
|
||||
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
|
||||
a = await quotaAlerts(s.db, { fiveHour: { utilization: 0.88, resetsAt: 100 } });
|
||||
a = await quotaAlerts(s.db, s.u, { fiveHour: { utilization: 0.88, resetsAt: 100 } });
|
||||
assert.deepEqual(a, []);
|
||||
// passe 95 % : nouveau palier
|
||||
a = await quotaAlerts(s.db, { fiveHour: { utilization: 0.97, resetsAt: 100 } });
|
||||
a = await quotaAlerts(s.db, s.u, { fiveHour: { utilization: 0.97, resetsAt: 100 } });
|
||||
assert.deepEqual(a, [{ label: 'session Claude (5 h)', level: 95, utilization: 0.97 }]);
|
||||
// la fenêtre a tourné (nouveau resetsAt) : 80 % re-sonne
|
||||
a = await quotaAlerts(s.db, { fiveHour: { utilization: 0.81, resetsAt: 200 } });
|
||||
a = await quotaAlerts(s.db, s.u, { fiveHour: { utilization: 0.81, resetsAt: 200 } });
|
||||
assert.deepEqual(a, [{ label: 'session Claude (5 h)', level: 80, utilization: 0.81 }]);
|
||||
// saut direct à 95 % : un seul palier notifié, pas 80 puis 95
|
||||
a = await quotaAlerts(s.db, { sevenDay: { utilization: 0.97, resetsAt: 300 } });
|
||||
a = await quotaAlerts(s.db, s.u, { sevenDay: { utilization: 0.97, resetsAt: 300 } });
|
||||
assert.deepEqual(a, [{ label: 'semaine Claude', level: 95, utilization: 0.97 }]);
|
||||
});
|
||||
|
|
|
|||
|
|
@ -2,11 +2,13 @@ import { test } from 'node:test';
|
|||
import assert from 'node:assert/strict';
|
||||
import { now } from '../src/db.js';
|
||||
import { testDb } from './helpers/db.js';
|
||||
import { addUser } from './helpers/users.js';
|
||||
import { parseFilters, listProspects } from '../src/services/crm.js';
|
||||
|
||||
async function setup() {
|
||||
const db = await testDb();
|
||||
await db.prepare("INSERT INTO projects(name, git_url, created_at) VALUES('A', 'a', ?), ('B', 'b', ?)").run(now(), now());
|
||||
const u = await addUser(db);
|
||||
await db.prepare("INSERT INTO projects(user_id, name, git_url, created_at) VALUES(?, 'A', 'a', ?), (?, 'B', 'b', ?)").run(u, now(), u, now());
|
||||
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());
|
||||
await add(1, 'Le Fournil', 'contact@fournil.fr', { score: 9, status: 'replied', sent: now() - 100 });
|
||||
|
|
|
|||
|
|
@ -2,13 +2,15 @@ import { test } from 'node:test';
|
|||
import assert from 'node:assert/strict';
|
||||
import { now } from '../src/db.js';
|
||||
import { testDb } from './helpers/db.js';
|
||||
import { addUser } from './helpers/users.js';
|
||||
import { csvCell, toCsv, parseCsv, exportProspects, importProspects } from '../src/services/csv.js';
|
||||
import { parseFilters } from '../src/services/crm.js';
|
||||
|
||||
const f = (o = {}) => parseFilters(new URLSearchParams(o));
|
||||
async function setup() {
|
||||
const db = await testDb();
|
||||
await db.prepare("INSERT INTO projects(name, git_url, created_at) VALUES('A', 'a', ?), ('B', 'b', ?)").run(now(), now());
|
||||
const u = await addUser(db);
|
||||
await db.prepare("INSERT INTO projects(user_id, name, git_url, created_at) VALUES(?, 'A', 'a', ?), (?, 'B', 'b', ?)").run(u, now(), u, now());
|
||||
return db;
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -12,6 +12,7 @@ import { Worker, latestJobs } from '../src/services/jobs.js';
|
|||
import { Scheduler } from '../src/services/scheduler.js';
|
||||
import { makeHandlers } from '../src/handlers.js';
|
||||
import { createProject, saveSecretConfig, getProject } from '../src/projects.js';
|
||||
import { addUser } from './helpers/users.js';
|
||||
|
||||
const paris = (iso) => new Date(iso); // ISO avec décalage explicite
|
||||
|
||||
|
|
@ -44,9 +45,10 @@ async function setup() {
|
|||
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
|
||||
};
|
||||
await setSetting(db, 'send_delay_min', '0');
|
||||
await setSetting(db, 'send_delay_max', '0');
|
||||
const id = await createProject(app, { name: 'P', gitUrl: 'https://git.x/T/P.git' });
|
||||
const userId = await addUser(db);
|
||||
await setSetting(db, userId, 'send_delay_min', '0');
|
||||
await setSetting(db, userId, 'send_delay_max', '0');
|
||||
const id = await createProject(app, { userId, name: 'P', gitUrl: 'https://git.x/T/P.git' });
|
||||
await saveSecretConfig(app, id, 'smtp_enc', { host: 'smtp.x', user: 'u', pass: 'p', fromEmail: 'tony@codebzh.fr' }, '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 = ?')
|
||||
|
|
@ -64,7 +66,7 @@ async function setup() {
|
|||
};
|
||||
const worker = new Worker(db, makeHandlers(app), { thermalMax: 999, log: { error() {} } });
|
||||
const scheduler = new Scheduler(app, { log: { error() {} } });
|
||||
return { tmp, db, app, id, add, inboxOk, worker, scheduler, sentMails };
|
||||
return { tmp, db, app, id, userId, add, inboxOk, worker, scheduler, sentMails };
|
||||
}
|
||||
|
||||
test('relance : seulement les prospects dus, sans réponse, dans le même fil, une seule fois', async () => {
|
||||
|
|
@ -76,7 +78,7 @@ test('relance : seulement les prospects dus, sans réponse, dans le même fil, u
|
|||
const blacklisted = await s.add('stop@ferme.fr', 9);
|
||||
await s.db.prepare("INSERT INTO blacklist(email, reason, created_at) VALUES('stop@ferme.fr', 'unsubscribe', ?)").run(now());
|
||||
|
||||
const plan = await followupPlan(s.db, await getProject(s.app, s.id), { date: new Date(WED_10H * 1000) });
|
||||
const plan = await followupPlan(s.db, await getProject(s.app, s.id, { userId: s.userId }), { date: new Date(WED_10H * 1000) });
|
||||
assert.deepEqual({ due: plan.due, blockers: plan.blockers }, { due: 1, blockers: [] });
|
||||
|
||||
const queued = await s.scheduler.queueFollowups({ date: new Date(WED_10H * 1000) });
|
||||
|
|
@ -109,7 +111,7 @@ test('relance bloquée : boîte en erreur, boîte pas lue récemment, week-end,
|
|||
const s = await setup();
|
||||
try {
|
||||
await s.add('contact@fournil.fr', 8);
|
||||
const plan = async (o = {}) => followupPlan(s.db, await getProject(s.app, s.id), o);
|
||||
const plan = async (o = {}) => followupPlan(s.db, await getProject(s.app, s.id, { userId: s.userId }), o);
|
||||
const sat = new Date('2026-10-24T11:00:00+02:00');
|
||||
assert.equal((await plan({ date: sat })).ready, false);
|
||||
assert.equal((await plan({ date: sat })).inHours, false);
|
||||
|
|
@ -159,7 +161,7 @@ test('génération du modèle de relance par l\'IA', async () => {
|
|||
await s.db.prepare('UPDATE projects SET profile_json = ? WHERE id = ?').run(JSON.stringify({ resume: 'x', proposition_valeur: 'y' }), s.id);
|
||||
await s.db.prepare("DELETE FROM templates WHERE kind = 'followup'").run();
|
||||
const { enqueue } = await import('../src/services/jobs.js');
|
||||
await enqueue(s.db, { projectId: s.id, type: 'followup_template' });
|
||||
await enqueue(s.db, { userId: s.userId, projectId: s.id, type: 'followup_template' });
|
||||
await s.worker.tick();
|
||||
const job = (await latestJobs(s.db, s.id)).followup_template;
|
||||
assert.equal(job.status, 'done', job.error);
|
||||
|
|
|
|||
|
|
@ -14,6 +14,7 @@ import { allowedToSend, buildProspectMail, fillTemplate } from '../src/services/
|
|||
import { validateSelect, firstValue } from '../src/services/recap.js';
|
||||
import { validateGitUrl } from '../src/services/git.js';
|
||||
import { verifyUnsubToken, encrypt } from '../src/crypto.js';
|
||||
import { addUser } from './helpers/users.js';
|
||||
|
||||
async function setup() {
|
||||
const tmp = mkdtempSync(join(tmpdir(), 'aitools-'));
|
||||
|
|
@ -30,26 +31,27 @@ async function setup() {
|
|||
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() {} }),
|
||||
};
|
||||
await setSetting(db, 'send_delay_min', '0');
|
||||
await setSetting(db, 'send_delay_max', '0');
|
||||
const id = await createProject(app, { name: 'MonEspacePro', gitUrl: `file://${src}` });
|
||||
const userId = await addUser(db);
|
||||
await setSetting(db, userId, 'send_delay_min', '0');
|
||||
await setSetting(db, userId, 'send_delay_max', '0');
|
||||
const id = await createProject(app, { userId, name: 'MonEspacePro', gitUrl: `file://${src}` });
|
||||
const worker = new Worker(db, makeHandlers(app), { thermalMax: 999, log: { error: (...a) => console.error(...a) } });
|
||||
return { tmp, db, app, id, worker, sentMails };
|
||||
return { tmp, db, app, id, userId, worker, sentMails };
|
||||
}
|
||||
|
||||
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]; };
|
||||
const run = async (s, type, params) => { await enqueue(s.db, { userId: s.userId, 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 () => {
|
||||
const s = await setup();
|
||||
try {
|
||||
const a = await run(s, 'analyze');
|
||||
assert.equal(a.status, 'done', a.error);
|
||||
let p = await getProject(s.app, s.id);
|
||||
let p = await getProject(s.app, s.id, { userId: s.userId });
|
||||
assert.equal(p.profile.resume, 'Cartes de fidélité digitales.');
|
||||
assert.equal(p.target.zone, 'Bretagne');
|
||||
assert.equal(p.targetValidated, false);
|
||||
assert.match(p.profileCommit, /^[0-9a-f]{40}$/);
|
||||
const rl = JSON.parse(await getSetting(s.db, 'claude_rate_limit_json'));
|
||||
const rl = JSON.parse(await getSetting(s.db, s.userId, 'claude_rate_limit_json'));
|
||||
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');
|
||||
|
||||
|
|
@ -92,7 +94,7 @@ test('flux complet : analyse → cible → prospection → modèle → envoi →
|
|||
|
||||
const ev1 = await run(s, 'evolution', { count: 3, level: 'rapide' });
|
||||
assert.match(ev1.error, /Adresse de réception/);
|
||||
await setSetting(s.db, 'notify_email', 'moi@x.fr');
|
||||
await setSetting(s.db, s.userId, 'notify_email', 'moi@x.fr');
|
||||
const ev = await run(s, 'evolution', { count: 3, level: 'rapide' });
|
||||
assert.equal(ev.status, 'done', ev.error);
|
||||
assert.equal(s.sentMails.at(-1).to, 'moi@x.fr');
|
||||
|
|
@ -202,7 +204,7 @@ test('analyse : modèle économique (Haiku) par défaut, Sonnet uniquement sur d
|
|||
try {
|
||||
const a = await run(s, 'analyze');
|
||||
assert.equal(a.status, 'done', a.error);
|
||||
await setSetting(s.db, 'analyze_model', 'sonnet');
|
||||
await setSetting(s.db, s.userId, 'analyze_model', 'sonnet');
|
||||
const a2 = await run(s, 'analyze');
|
||||
assert.equal(a2.status, 'done', a2.error);
|
||||
assert.deepEqual(readFileSync(spyFile, 'utf8').trim().split('\n'), ['haiku', 'sonnet']);
|
||||
|
|
@ -214,7 +216,7 @@ test('quota Claude serré : alerte Discord à 80 %, pas en dessous', async () =>
|
|||
const sent = [];
|
||||
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';
|
||||
await setSetting(s.db, 'discord_webhook_enc', encrypt(s.app.cfg.secretKey, hook));
|
||||
await setSetting(s.db, s.userId, 'discord_webhook_enc', encrypt(s.app.cfg.secretKey, hook));
|
||||
try {
|
||||
const a = await run(s, 'analyze'); // fake-claude : 33 % / 50 % par défaut
|
||||
assert.equal(a.status, 'done', a.error);
|
||||
|
|
|
|||
|
|
@ -8,20 +8,22 @@ import { now, setSetting } from '../src/db.js';
|
|||
import { testDb } from './helpers/db.js';
|
||||
import { createApp } from '../src/server.js';
|
||||
import { unsubToken } from '../src/crypto.js';
|
||||
import { addUser } from './helpers/users.js';
|
||||
|
||||
const APP_URL = 'https://ai.tony-averty.dev';
|
||||
let app, base, cookie, tmp;
|
||||
let app, base, cookie, tmp, uid;
|
||||
|
||||
before(async () => {
|
||||
tmp = mkdtempSync(join(tmpdir(), 'aitools-http-'));
|
||||
const cfg = {
|
||||
appUrl: APP_URL, google: { clientId: 'cid', clientSecret: 'cs' }, allowedEmails: ['me@gmail.com'],
|
||||
appUrl: APP_URL, google: { clientId: 'cid', clientSecret: 'cs' }, apple: null, adminEmails: ['me@gmail.com'],
|
||||
secretKey: randomBytes(32), dataDir: tmp, claudeBin: 'claude', thermalMax: 75,
|
||||
};
|
||||
app = await createApp(cfg, { db: await testDb(), worker: false });
|
||||
await new Promise((r) => app.server.listen(0, '127.0.0.1', r));
|
||||
base = `http://127.0.0.1:${app.server.address().port}`;
|
||||
await app.db.prepare('INSERT INTO sessions(id, email, created_at, expires_at) VALUES(?, ?, ?, ?)').run('sess1', 'me@gmail.com', now(), now() + 3600);
|
||||
uid = await addUser(app.db, { email: 'me@gmail.com' });
|
||||
await app.db.prepare('INSERT INTO sessions(id, user_id, created_at, expires_at) VALUES(?, ?, ?, ?)').run('sess1', uid, now(), now() + 3600);
|
||||
cookie = 'sid=sess1';
|
||||
});
|
||||
after(async () => { await app.close(); rmSync(tmp, { recursive: true, force: true }); });
|
||||
|
|
@ -80,7 +82,7 @@ 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 });
|
||||
assert.equal(r.status, 303);
|
||||
const s = async (k) => (await app.db.prepare('SELECT value FROM settings WHERE `key` = ?').get(k))?.value;
|
||||
const s = async (k) => (await app.db.prepare('SELECT value FROM user_settings WHERE user_id = ? AND `key` = ?').get(uid, k))?.value;
|
||||
assert.equal(await s('forgejo_host'), 'git.tony-averty.dev');
|
||||
assert.equal(await s('global_daily_cap'), '300', 'plafond borné');
|
||||
assert.equal(await s('send_delay_min'), '5');
|
||||
|
|
@ -189,29 +191,29 @@ 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';
|
||||
r = await post('/settings', { ...base, discord_webhook: hook, ev_reply: 'on', ev_job_error: 'on' }, { form: true });
|
||||
assert.equal(r.status, 303);
|
||||
const enc = (await app.db.prepare("SELECT value FROM settings WHERE `key` = 'discord_webhook_enc'").get()).value;
|
||||
const enc = (await app.db.prepare("SELECT value FROM user_settings WHERE user_id = ? AND `key` = 'discord_webhook_enc'").get(uid)).value;
|
||||
assert.ok(!enc.includes('abcdefghijklmnop'), 'URL chiffrée');
|
||||
assert.deepEqual(JSON.parse((await 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 user_settings WHERE user_id = ? AND `key` = 'discord_events'").get(uid)).value), ['job_error', 'reply']);
|
||||
r = await get('/settings');
|
||||
const page = await r.text();
|
||||
assert.ok(!page.includes('abcdefghijklmnop'), 'URL jamais réaffichée');
|
||||
assert.match(page, /data-notify-test/);
|
||||
r = await post('/settings', { ...base, discord_remove: 'on' }, { form: true });
|
||||
assert.equal((await app.db.prepare("SELECT value FROM settings WHERE `key` = 'discord_webhook_enc'").get()).value, null);
|
||||
assert.equal((await app.db.prepare("SELECT value FROM user_settings WHERE user_id = ? AND `key` = 'discord_webhook_enc'").get(uid)).value, null);
|
||||
});
|
||||
|
||||
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' };
|
||||
let r = await post('/settings', { ...base, budget_day_usd: '0,5', budget_month_usd: 'abc' }, { form: true });
|
||||
assert.equal(r.status, 303);
|
||||
const s = async (k) => (await app.db.prepare('SELECT value FROM settings WHERE `key` = ?').get(k))?.value;
|
||||
const s = async (k) => (await app.db.prepare('SELECT value FROM user_settings WHERE user_id = ? AND `key` = ?').get(uid, k))?.value;
|
||||
assert.equal(await s('budget_day_usd'), '0.5', 'virgule française acceptée');
|
||||
assert.equal(await s('budget_month_usd'), '', 'valeur invalide = pas de limite');
|
||||
await 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(user_id, type, status, cost_usd, created_at, finished_at) VALUES(?, 'evolution', 'done', 0.8, ?, ?)").run(uid, now(), now());
|
||||
let sys = await (await get('/api/system')).json();
|
||||
assert.equal(sys.budget.blocked, true);
|
||||
assert.equal(sys.claudeRateLimit, null, 'pas encore mesuré sans appel Claude');
|
||||
await 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, uid, '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();
|
||||
assert.equal(sys.claudeRateLimit.fiveHour.utilization, 0.42);
|
||||
assert.equal(sys.claudeRateLimit.sevenDay.utilization, 0.1);
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ import assert from 'node:assert/strict';
|
|||
import { randomBytes } from 'node:crypto';
|
||||
import { now } from '../src/db.js';
|
||||
import { testDb } from './helpers/db.js';
|
||||
import { addUser } from './helpers/users.js';
|
||||
|
||||
import { checkInbox } from '../src/services/inbox.js';
|
||||
import { createProject, saveSecretConfig, getProject } from '../src/projects.js';
|
||||
|
|
@ -15,7 +16,8 @@ test('checkInbox sur un vrai serveur IMAP', { skip: !live && 'IMAP_TEST non déf
|
|||
const [host, port, user, pass] = live.split(':');
|
||||
const db = await testDb();
|
||||
const app = { db, cfg: { secretKey: randomBytes(32) } };
|
||||
const id = await createProject(app, { name: 'P', gitUrl: 'https://git.x/T/P.git' });
|
||||
const userId = await addUser(db);
|
||||
const id = await createProject(app, { userId, name: 'P', gitUrl: 'https://git.x/T/P.git' });
|
||||
await saveSecretConfig(app, id, 'smtp_enc', { host: 'smtp.x', user, pass, fromEmail: user }, 'pass');
|
||||
await saveSecretConfig(app, id, 'imap_enc', { host, port: Number(port), user: '', pass: '' }, 'pass');
|
||||
const add = async (email, msgId) => {
|
||||
|
|
@ -29,11 +31,11 @@ test('checkInbox sur un vrai serveur IMAP', { skip: !live && 'IMAP_TEST non déf
|
|||
const zen = await add('hello@zen.fr', '<m2@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, userId, id), { replies: 1, bounces: 1, ignored: 2 });
|
||||
const st = async (pid) => (await db.prepare('SELECT status FROM prospects WHERE id = ?').get(pid)).status;
|
||||
assert.equal(await st(fournil), 'replied');
|
||||
assert.equal(await st(zen), 'sent', 'une absence n\'est pas une réponse');
|
||||
assert.equal(await st(ferme), 'bounced');
|
||||
assert.deepEqual(await checkInbox(app, id), { replies: 0, bounces: 0, ignored: 0 }, 'rien de relu');
|
||||
assert.equal((await getProject(app, id)).inbox.lastUid, 4);
|
||||
assert.deepEqual(await checkInbox(app, userId, id), { replies: 0, bounces: 0, ignored: 0 }, 'rien de relu');
|
||||
assert.equal((await getProject(app, id, { userId })).inbox.lastUid, 4);
|
||||
});
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ import assert from 'node:assert/strict';
|
|||
import { randomBytes } from 'node:crypto';
|
||||
import { now } from '../src/db.js';
|
||||
import { testDb } from './helpers/db.js';
|
||||
import { addUser } from './helpers/users.js';
|
||||
|
||||
import { parseHeaders, classify, applyMessages, checkInbox } from '../src/services/inbox.js';
|
||||
import { createProject, saveSecretConfig, getProject, imapCredentials } from '../src/projects.js';
|
||||
|
|
@ -10,7 +11,8 @@ import { createProject, saveSecretConfig, getProject, imapCredentials } from '..
|
|||
async function setup() {
|
||||
const db = await testDb();
|
||||
const app = { db, cfg: { secretKey: randomBytes(32) } };
|
||||
const id = await createProject(app, { name: 'P', gitUrl: 'https://git.x/T/P.git' });
|
||||
const userId = await addUser(db);
|
||||
const id = await createProject(app, { userId, name: 'P', gitUrl: 'https://git.x/T/P.git' });
|
||||
const add = async (company, email, msgId, status = 'sent') => {
|
||||
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());
|
||||
|
|
@ -22,7 +24,7 @@ async function setup() {
|
|||
return pid;
|
||||
};
|
||||
const status = (pid) => db.prepare('SELECT status, replied_at, reply_subject FROM prospects WHERE id = ?').get(pid);
|
||||
return { db, app, id, add, status };
|
||||
return { db, app, id, userId, add, status };
|
||||
}
|
||||
|
||||
test('parseHeaders déplie les en-têtes multi-lignes', () => {
|
||||
|
|
@ -116,12 +118,12 @@ test('checkInbox : reprend au dernier UID, mémorise l\'état et les erreurs', a
|
|||
? { uidValidity: '7', lastUid: 12, messages: [{ uid: 12, from: 'contact@fournil.fr', subject: 'Re: idée' }] }
|
||||
: { uidValidity: '7', lastUid: 12, messages: [] };
|
||||
};
|
||||
assert.deepEqual(await checkInbox(s.app, s.id), { replies: 1, bounces: 0, ignored: 0 });
|
||||
assert.deepEqual(await checkInbox(s.app, s.userId, s.id), { replies: 1, bounces: 0, ignored: 0 });
|
||||
assert.equal(calls[0].creds.user, 'u', 'identifiants SMTP réutilisés');
|
||||
await checkInbox(s.app, s.id);
|
||||
await checkInbox(s.app, s.userId, s.id);
|
||||
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/);
|
||||
const inbox = (await getProject(s.app, s.id)).inbox;
|
||||
await assert.rejects(checkInbox(s.app, s.userId, s.id), /AUTHENTICATIONFAILED/);
|
||||
const inbox = (await getProject(s.app, s.id, { userId: s.userId })).inbox;
|
||||
assert.equal(inbox.lastError, 'AUTHENTICATIONFAILED');
|
||||
assert.equal(inbox.replies, 1);
|
||||
assert.equal(inbox.lastUid, 12, 'le dernier UID est conservé après une erreur');
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@ import { test } from 'node:test';
|
|||
import assert from 'node:assert/strict';
|
||||
import { randomBytes } from 'node:crypto';
|
||||
import { testDb } from './helpers/db.js';
|
||||
import { addUser } from './helpers/users.js';
|
||||
import { saveSnapshot, snapshotAll, history, parisDay } from '../src/services/metrics.js';
|
||||
import { createProject, saveSecretConfig } from '../src/projects.js';
|
||||
|
||||
|
|
@ -10,8 +11,9 @@ const ts = (iso) => Math.floor(Date.parse(iso) / 1000);
|
|||
async function setup() {
|
||||
const db = await testDb();
|
||||
const app = { db, cfg: { secretKey: randomBytes(32) } };
|
||||
const id = await createProject(app, { name: 'MEP', gitUrl: 'https://g/T/M.git' });
|
||||
return { db, app, id };
|
||||
const userId = await addUser(db);
|
||||
const id = await createProject(app, { userId, name: 'MEP', gitUrl: 'https://g/T/M.git' });
|
||||
return { db, app, id, userId };
|
||||
}
|
||||
|
||||
test('jour de Paris, même à 23h30 UTC', () => {
|
||||
|
|
@ -31,8 +33,8 @@ test('photo du jour : une ligne par jour, valeurs non numériques ignorées', as
|
|||
|
||||
test('photo automatique : une seule par jour et par projet, les erreurs n\'arrêtent pas les autres', async () => {
|
||||
const s = await setup();
|
||||
const other = await createProject(s.app, { name: 'GoSortir', gitUrl: 'https://g/T/G.git' });
|
||||
await createProject(s.app, { name: 'Sans BDD', gitUrl: 'https://g/T/X.git' });
|
||||
const other = await createProject(s.app, { userId: s.userId, name: 'GoSortir', gitUrl: 'https://g/T/G.git' });
|
||||
await createProject(s.app, { userId: s.userId, name: 'Sans BDD', gitUrl: 'https://g/T/X.git' });
|
||||
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;
|
||||
s.app.fetchRecap = async (id) => { calls++; if (id === other) throw new Error('BDD injoignable'); return { users: 5, clients: 1, revenue: 30 }; };
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ import assert from 'node:assert/strict';
|
|||
import { parisParts, parisTime, nextNightSlot, addParisDays } from '../src/services/paris-time.js';
|
||||
import { now } from '../src/db.js';
|
||||
import { testDb } from './helpers/db.js';
|
||||
import { addUser } from './helpers/users.js';
|
||||
import { enqueue, Worker, latestJobs } from '../src/services/jobs.js';
|
||||
|
||||
const iso = (d) => d.toISOString();
|
||||
|
|
@ -31,9 +32,10 @@ test('le worker ne démarre pas un job programmé avant son heure', async () =>
|
|||
const ran = [];
|
||||
const w = new Worker(db, { prospect: async () => { ran.push('prospect'); }, evolution: async () => { ran.push('evolution'); } },
|
||||
{ thermalMax: 999, log: { error() {} }, clock: () => clock });
|
||||
await db.prepare("INSERT INTO projects(name, git_url, created_at) VALUES('p', 'u', ?)").run(now());
|
||||
await enqueue(db, { projectId: 1, type: 'prospect', runAfter: clock + 3600 });
|
||||
await enqueue(db, { projectId: 1, type: 'evolution' });
|
||||
const u = await addUser(db);
|
||||
await db.prepare("INSERT INTO projects(user_id, name, git_url, created_at) VALUES(?, 'p', 'u', ?)").run(u, now());
|
||||
await enqueue(db, { userId: u, projectId: 1, type: 'prospect', runAfter: clock + 3600 });
|
||||
await enqueue(db, { userId: u, projectId: 1, type: 'evolution' });
|
||||
assert.equal(await w.tick(), true);
|
||||
assert.deepEqual(ran, ['evolution'], 'le job immédiat passe devant le job programmé');
|
||||
assert.equal(await w.tick(), false, 'rien à faire avant l\'heure');
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ import assert from 'node:assert/strict';
|
|||
import { randomBytes } from 'node:crypto';
|
||||
import { now, setSetting } from '../src/db.js';
|
||||
import { testDb } from './helpers/db.js';
|
||||
import { addUser } from './helpers/users.js';
|
||||
import { encrypt } from '../src/crypto.js';
|
||||
import { notify, notifyJob, WEBHOOK_RE } from '../src/services/notify.js';
|
||||
import { Worker, enqueue } from '../src/services/jobs.js';
|
||||
|
|
@ -18,10 +19,11 @@ async function setup({ events } = {}) {
|
|||
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 }; },
|
||||
};
|
||||
await setSetting(db, 'discord_webhook_enc', encrypt(app.cfg.secretKey, HOOK));
|
||||
if (events) await setSetting(db, 'discord_events', JSON.stringify(events));
|
||||
const id = await createProject(app, { name: 'MonEspacePro', gitUrl: 'https://g/T/M.git' });
|
||||
return { db, app, sent, id };
|
||||
const userId = await addUser(db);
|
||||
await setSetting(db, userId, 'discord_webhook_enc', encrypt(app.cfg.secretKey, HOOK));
|
||||
if (events) await setSetting(db, userId, 'discord_events', JSON.stringify(events));
|
||||
const id = await createProject(app, { userId, name: 'MonEspacePro', gitUrl: 'https://g/T/M.git' });
|
||||
return { db, app, sent, id, userId };
|
||||
}
|
||||
|
||||
test('validation stricte de l\'URL de webhook', () => {
|
||||
|
|
@ -35,7 +37,7 @@ test('validation stricte de l\'URL de webhook', () => {
|
|||
|
||||
test('notif : forme du message, aucune mention possible', async () => {
|
||||
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, s.userId, 'reply', { title: '@everyone Boulangerie', description: 'x', level: 'ok', fields: [{ name: 'a', value: '' }] }), true);
|
||||
const b = s.sent[0].body;
|
||||
assert.equal(s.sent[0].url, HOOK);
|
||||
assert.deepEqual(b.allowed_mentions, { parse: [] });
|
||||
|
|
@ -46,23 +48,23 @@ test('notif : forme du message, aucune mention possible', async () => {
|
|||
|
||||
test('événement désactivé, webhook absent ou Discord en panne : rien ne casse', async () => {
|
||||
const s = await setup({ events: ['job_error'] });
|
||||
assert.equal(await notify(s.app, 'reply', { title: 'x' }), false);
|
||||
assert.equal(await notify(s.app, s.userId, 'reply', { title: 'x' }), false);
|
||||
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, s.userId, 'reply', { title: 'x' }, { force: true }), true, 'le bouton de test force l\'envoi');
|
||||
const warn = console.warn; console.warn = () => {};
|
||||
try {
|
||||
s.app.fetch = async () => ({ ok: false, status: 404 });
|
||||
assert.equal(await notify(s.app, 'job_error', { title: 'x' }), false);
|
||||
assert.equal(await notify(s.app, s.userId, 'job_error', { title: 'x' }), false);
|
||||
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, s.userId, 'job_error', { title: 'x' }), false);
|
||||
} finally { console.warn = warn; }
|
||||
await setSetting(s.db, 'discord_webhook_enc', null);
|
||||
assert.equal(await notify(s.app, 'job_error', { title: 'x' }), false);
|
||||
await setSetting(s.db, s.userId, 'discord_webhook_enc', null);
|
||||
assert.equal(await notify(s.app, s.userId, 'job_error', { title: 'x' }), false);
|
||||
});
|
||||
|
||||
test('fin de job : succès, erreur, relances, et silence pour les jobs courts', async () => {
|
||||
const s = await setup();
|
||||
const job = (type) => ({ type, project_id: s.id });
|
||||
const job = (type) => ({ type, project_id: s.id, user_id: s.userId });
|
||||
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('followup'), { status: 'done', result: { sent: 3, failed: 0 } });
|
||||
|
|
@ -83,8 +85,8 @@ test('le worker notifie en fin de job, et un callback qui plante ne le bloque pa
|
|||
thermalMax: 999, log: { error() {} },
|
||||
onFinish: (job, r) => { seen.push(`${job.type}:${r.status}`); if (job.type === 'evolution') throw new Error('callback cassé'); },
|
||||
});
|
||||
await enqueue(s.db, { projectId: s.id, type: 'prospect' });
|
||||
await enqueue(s.db, { projectId: s.id, type: 'evolution' });
|
||||
await enqueue(s.db, { userId: s.userId, projectId: s.id, type: 'prospect' });
|
||||
await enqueue(s.db, { userId: s.userId, projectId: s.id, type: 'evolution' });
|
||||
await w.tick(); await w.tick();
|
||||
assert.deepEqual(seen, ['prospect:done', 'evolution:error']);
|
||||
assert.equal((await s.db.prepare("SELECT COUNT(*) n FROM jobs WHERE status IN ('done','error')").get()).n, 2);
|
||||
|
|
@ -96,10 +98,10 @@ test('nouvelles réponses détectées → une notif avec les entreprises', async
|
|||
await saveSecretConfig(s.app, s.id, 'imap_enc', { host: 'imap.x' }, 'pass');
|
||||
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' }] });
|
||||
await checkInbox(s.app, s.id);
|
||||
await checkInbox(s.app, s.userId, s.id);
|
||||
assert.equal(s.sent.length, 1);
|
||||
assert.equal(s.sent[0].body.embeds[0].title, 'MonEspacePro · 1 réponse(s) de prospect');
|
||||
assert.match(s.sent[0].body.embeds[0].description, /\*\*Le Fournil\*\* \(contact@fournil\.fr\) : Re: idée/);
|
||||
await checkInbox(s.app, s.id);
|
||||
await checkInbox(s.app, s.userId, s.id);
|
||||
assert.equal(s.sent.length, 1, 'pas de notif quand rien de neuf');
|
||||
});
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ import assert from 'node:assert/strict';
|
|||
import { randomBytes } from 'node:crypto';
|
||||
import { now, setSetting, getSetting } from '../src/db.js';
|
||||
import { testDb } from './helpers/db.js';
|
||||
import { addUser } from './helpers/users.js';
|
||||
import { encrypt, encryptJson } from '../src/crypto.js';
|
||||
import { weeklyStats, weeklyText, maybeSendWeekly } from '../src/services/report.js';
|
||||
import { createProject } from '../src/projects.js';
|
||||
|
|
@ -15,8 +16,9 @@ async function setup() {
|
|||
createTransport: () => ({ sendMail: async (m) => { mails.push(m); }, close() {} }),
|
||||
fetch: async (url, o) => { hooks.push(JSON.parse(o.body)); return { ok: true }; },
|
||||
};
|
||||
const mep = await createProject(app, { name: 'MonEspacePro', gitUrl: 'https://g/T/M.git' });
|
||||
await createProject(app, { name: 'GoSortir', gitUrl: 'https://g/T/G.git' });
|
||||
const userId = await addUser(db);
|
||||
const mep = await createProject(app, { userId, name: 'MonEspacePro', gitUrl: 'https://g/T/M.git' });
|
||||
await createProject(app, { userId, name: 'GoSortir', gitUrl: 'https://g/T/G.git' });
|
||||
const t = now() - 2 * 86400;
|
||||
for (let i = 0; i < 20; i++) {
|
||||
const v = i % 2 ? 'B' : 'A';
|
||||
|
|
@ -28,14 +30,14 @@ async function setup() {
|
|||
await 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, error) VALUES(?, 'e6@x6.fr', ?, 'followup', 'refusé')").run(mep, t);
|
||||
await db.prepare("INSERT INTO blacklist(email, reason, created_at) VALUES('e7@x7.fr', 'bounce', ?)").run(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);
|
||||
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 };
|
||||
await db.prepare("INSERT INTO jobs(user_id, project_id, type, status, cost_usd, created_at, finished_at) VALUES(?, ?, 'prospect', 'done', 0.42, ?, ?)").run(userId, mep, t, t);
|
||||
await db.prepare("INSERT INTO jobs(user_id, project_id, type, status, cost_usd, created_at, finished_at) VALUES(?, ?, 'prospect', 'done', 9, ?, ?)").run(userId, mep, t - 30 * 86400, t - 30 * 86400);
|
||||
return { db, app, mails, hooks, userId };
|
||||
}
|
||||
|
||||
test('statistiques de la semaine', async () => {
|
||||
const s = await setup();
|
||||
const st = await weeklyStats(s.db);
|
||||
const st = await weeklyStats(s.db, s.userId);
|
||||
const mep = st.projects.find((p) => p.name === 'MonEspacePro');
|
||||
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',
|
||||
|
|
@ -52,16 +54,16 @@ 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 () => {
|
||||
const s = await setup();
|
||||
await setSetting(s.db, 'notify_email', 'moi@x.fr');
|
||||
await setSetting(s.db, 'smtp_enc', encryptJson(s.app.cfg.secretKey, { host: 'h', user: 'u', pass: 'p', fromEmail: 'aitools@x.fr' }));
|
||||
await setSetting(s.db, 'discord_webhook_enc', encrypt(s.app.cfg.secretKey, 'https://discord.com/api/webhooks/123456789012345678/abcdefghijklmnopqrstuvwxyz'));
|
||||
await setSetting(s.db, s.userId, 'notify_email', 'moi@x.fr');
|
||||
await setSetting(s.db, s.userId, 'smtp_enc', encryptJson(s.app.cfg.secretKey, { host: 'h', user: 'u', pass: 'p', fromEmail: 'aitools@x.fr' }));
|
||||
await setSetting(s.db, s.userId, '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');
|
||||
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-27T09:00:00+01:00') }), null, 'mardi : non');
|
||||
assert.equal(await maybeSendWeekly(s.app, s.userId, { date: MON_0830 }), null, 'désactivé par défaut');
|
||||
await setSetting(s.db, s.userId, 'weekly_report', '1');
|
||||
assert.equal(await maybeSendWeekly(s.app, s.userId, { date: new Date('2026-10-26T07:45:00+01:00') }), null, 'lundi 7h45 : trop tôt');
|
||||
assert.equal(await maybeSendWeekly(s.app, s.userId, { date: new Date('2026-10-27T09:00:00+01:00') }), null, 'mardi : non');
|
||||
|
||||
const r = await maybeSendWeekly(s.app, { date: MON_0830 });
|
||||
const r = await maybeSendWeekly(s.app, s.userId, { date: MON_0830 });
|
||||
assert.deepEqual(r.channels, ['mail', 'discord']);
|
||||
assert.equal(s.mails[0].to, 'moi@x.fr');
|
||||
assert.match(s.mails[0].subject, /^\[AiTools\] Rapport du/);
|
||||
|
|
@ -70,15 +72,15 @@ test('envoi automatique : lundi 8h, une seule fois par semaine, désactivé par
|
|||
assert.match(s.mails[0].html, /Rapport hebdo/);
|
||||
assert.match(s.mails[0].html, /MonEspacePro/);
|
||||
|
||||
assert.equal(await maybeSendWeekly(s.app, { date: new Date('2026-10-26T08:45:00+01:00') }), null, 'pas deux fois le même lundi');
|
||||
assert.notEqual(await maybeSendWeekly(s.app, { date: new Date('2026-11-02T08:15:00+01:00') }), null, 'lundi suivant');
|
||||
assert.equal(await maybeSendWeekly(s.app, s.userId, { date: new Date('2026-10-26T08:45:00+01:00') }), null, 'pas deux fois le même lundi');
|
||||
assert.notEqual(await maybeSendWeekly(s.app, s.userId, { date: new Date('2026-11-02T08:15:00+01:00') }), null, 'lundi suivant');
|
||||
assert.equal(s.mails.length, 2);
|
||||
});
|
||||
|
||||
test('aucun canal configuré : rien n\'est marqué comme envoyé', async () => {
|
||||
const s = await setup();
|
||||
await setSetting(s.db, 'weekly_report', '1');
|
||||
const r = await maybeSendWeekly(s.app, { date: MON_0830 });
|
||||
await setSetting(s.db, s.userId, 'weekly_report', '1');
|
||||
const r = await maybeSendWeekly(s.app, s.userId, { date: MON_0830 });
|
||||
assert.deepEqual(r.channels, []);
|
||||
assert.equal(await getSetting(s.db, 'weekly_report_last'), null);
|
||||
assert.equal(await getSetting(s.db, s.userId, 'weekly_report_last'), null);
|
||||
});
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ import { runClaude, extractJson, rateLimitWindows } from '../src/services/claude
|
|||
import { waitCool } from '../src/services/thermal.js';
|
||||
import { now } from '../src/db.js';
|
||||
import { testDb } from './helpers/db.js';
|
||||
import { addUser } from './helpers/users.js';
|
||||
import { enqueue, Worker, latestJobs, cancelJob, addUsage, usageSummary } from '../src/services/jobs.js';
|
||||
|
||||
const bin = resolve('test/fixtures/fake-claude.js');
|
||||
|
|
@ -57,19 +58,20 @@ test('waitCool attend la redescente avec hystérésis', async () => {
|
|||
|
||||
test('worker : exécution, dédoublonnage, erreurs, annulation, conso', async () => {
|
||||
const db = await testDb();
|
||||
await db.prepare("INSERT INTO projects(name, git_url, created_at) VALUES('p','u',?)").run(now());
|
||||
const a = await enqueue(db, { projectId: 1, type: 'ok', params: { x: 2 } });
|
||||
assert.equal((await enqueue(db, { projectId: 1, type: 'ok' })).existing, true);
|
||||
const u = await addUser(db);
|
||||
await db.prepare("INSERT INTO projects(user_id, name, git_url, created_at) VALUES(?, 'p','u',?)").run(u, now());
|
||||
const a = await enqueue(db, { userId: u, projectId: 1, type: 'ok', params: { x: 2 } });
|
||||
assert.equal((await enqueue(db, { userId: u, projectId: 1, type: 'ok' })).existing, true);
|
||||
const handlers = {
|
||||
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é'); },
|
||||
};
|
||||
const w = new Worker(db, handlers, { thermalMax: 999, log: { error() {} } });
|
||||
assert.equal(await w.tick(), true);
|
||||
await enqueue(db, { projectId: 1, type: 'boom' });
|
||||
await enqueue(db, { userId: u, projectId: 1, type: 'boom' });
|
||||
await w.tick();
|
||||
const c = await enqueue(db, { projectId: 1, type: 'ok' });
|
||||
await cancelJob(db, c.id);
|
||||
const c = await enqueue(db, { userId: u, projectId: 1, type: 'ok' });
|
||||
await cancelJob(db, u, c.id);
|
||||
assert.equal(await w.tick(), false);
|
||||
const jobs = await latestJobs(db, 1);
|
||||
assert.equal(a.id, 1);
|
||||
|
|
@ -79,5 +81,5 @@ test('worker : exécution, dédoublonnage, erreurs, annulation, conso', async ()
|
|||
const first = await db.prepare('SELECT * FROM jobs WHERE id = 1').get();
|
||||
assert.equal(first.status, 'done');
|
||||
assert.deepEqual(JSON.parse(first.result_json), { double: 4 });
|
||||
assert.equal((await usageSummary(db)).month.cost, 0.5);
|
||||
assert.equal((await usageSummary(db, u)).month.cost, 0.5);
|
||||
});
|
||||
|
|
|
|||
|
|
@ -2,11 +2,14 @@ import { test } from 'node:test';
|
|||
import assert from 'node:assert/strict';
|
||||
import { now } from '../src/db.js';
|
||||
import { testDb } from './helpers/db.js';
|
||||
import { addUser } from './helpers/users.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());
|
||||
const u = await addUser(db);
|
||||
await db.prepare("INSERT INTO projects(user_id, name, git_url, created_at) VALUES(?, 'p', 'u', ?)").run(u, now());
|
||||
db.userId = u;
|
||||
return db;
|
||||
}
|
||||
|
||||
|
|
@ -20,7 +23,7 @@ test('start puis stop : la boucle s\'arrête, le job en cours est annulé et att
|
|||
ctx.signal.addEventListener('abort', () => reject(new Error('Annulé')), { once: true });
|
||||
}),
|
||||
}, { thermalMax: 999, pollMs: 10, log: { error() {} } });
|
||||
await enqueue(db, { projectId: 1, type: 'prospect' });
|
||||
await enqueue(db, { userId: db.userId, projectId: 1, type: 'prospect' });
|
||||
await w.start();
|
||||
await running;
|
||||
await w.stop();
|
||||
|
|
@ -42,8 +45,8 @@ test('stop attend les notifications en vol, et un callback qui échoue est journ
|
|||
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 enqueue(db, { userId: db.userId, projectId: 1, type: 'prospect' });
|
||||
await enqueue(db, { userId: db.userId, projectId: 1, type: 'evolution' });
|
||||
await w.tick(); await w.tick();
|
||||
assert.deepEqual(seen, [], 'les notifications ne bloquent pas la file');
|
||||
await w.stop();
|
||||
|
|
@ -53,7 +56,7 @@ test('stop attend les notifications en vol, et un callback qui échoue est journ
|
|||
|
||||
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());
|
||||
await db.prepare("INSERT INTO jobs(user_id, project_id, type, status, created_at) VALUES(?, 1, 'analyze', 'running', ?)").run(db.userId, now());
|
||||
const w = new Worker(db, {}, { thermalMax: 999, pollMs: 10, log: { error() {} } });
|
||||
await w.start();
|
||||
await w.stop();
|
||||
|
|
|
|||
Loading…
Reference in a new issue