refactor: passe tout src/ en async/await sur la nouvelle couche de données
Routes, handlers de jobs, worker, planificateur et services attendent désormais chaque accès base. Requêtes réécrites pour être portables (IS ? sur NULL, COLLATE NOCASE, ESCAPE, INSERT ... SELECT sans FROM, transaction de l'import CSV via db.transaction). Les callbacks synchrones du flux de sortie passent par une file ordonnée attendue en fin de phase ; createApp devient asynchrone et l'arrêt attend job, tâches et base.
This commit is contained in:
parent
53edd27066
commit
637ac8ccb6
17 changed files with 469 additions and 394 deletions
30
src/auth.js
30
src/auth.js
|
|
@ -1,4 +1,4 @@
|
|||
// Auth Google (OIDC, code flow + PKCE) avec whitelist d'emails. Sessions en SQLite.
|
||||
// Auth Google (OIDC, code flow + PKCE) avec whitelist d'emails. Sessions en base.
|
||||
import { createHash } from 'node:crypto';
|
||||
import { now } from './db.js';
|
||||
import { randomId } from './crypto.js';
|
||||
|
|
@ -10,37 +10,37 @@ const STATE_TTL = 600;
|
|||
const GOOGLE_AUTH = 'https://accounts.google.com/o/oauth2/v2/auth';
|
||||
const GOOGLE_TOKEN = 'https://oauth2.googleapis.com/token';
|
||||
|
||||
export function getSession(db, req) {
|
||||
export async function getSession(db, req) {
|
||||
const sid = parseCookies(req)[SESSION_COOKIE];
|
||||
if (!sid) return null;
|
||||
const s = db.prepare('SELECT * FROM sessions WHERE id = ? AND expires_at > ?').get(sid, now());
|
||||
const s = await db.prepare('SELECT * FROM sessions WHERE id = ? AND expires_at > ?').get(sid, now());
|
||||
return s || null;
|
||||
}
|
||||
|
||||
export function createSession(db, res, email) {
|
||||
export async function createSession(db, res, email) {
|
||||
const id = randomId();
|
||||
db.prepare('INSERT INTO sessions(id, email, created_at, expires_at) VALUES(?, ?, ?, ?)')
|
||||
await db.prepare('INSERT INTO sessions(id, email, created_at, expires_at) VALUES(?, ?, ?, ?)')
|
||||
.run(id, email, now(), now() + SESSION_TTL);
|
||||
setCookie(res, SESSION_COOKIE, id, { maxAge: SESSION_TTL });
|
||||
}
|
||||
|
||||
export function destroySession(db, req, res) {
|
||||
export async function destroySession(db, req, res) {
|
||||
const sid = parseCookies(req)[SESSION_COOKIE];
|
||||
if (sid) db.prepare('DELETE FROM sessions WHERE id = ?').run(sid);
|
||||
if (sid) await db.prepare('DELETE FROM sessions WHERE id = ?').run(sid);
|
||||
setCookie(res, SESSION_COOKIE, '', { maxAge: 0 });
|
||||
}
|
||||
|
||||
export function purgeExpired(db) {
|
||||
db.prepare('DELETE FROM sessions WHERE expires_at < ?').run(now());
|
||||
db.prepare('DELETE FROM oauth_states WHERE created_at < ?').run(now() - STATE_TTL);
|
||||
export async function purgeExpired(db) {
|
||||
await db.prepare('DELETE FROM sessions WHERE expires_at < ?').run(now());
|
||||
await db.prepare('DELETE FROM oauth_states WHERE created_at < ?').run(now() - STATE_TTL);
|
||||
}
|
||||
|
||||
export function startGoogleLogin(db, cfg, res) {
|
||||
export async function startGoogleLogin(db, cfg, res) {
|
||||
const state = randomId(24);
|
||||
const nonce = randomId(24);
|
||||
const verifier = randomId(48);
|
||||
const challenge = createHash('sha256').update(verifier).digest('base64url');
|
||||
db.prepare('INSERT INTO oauth_states(state, verifier, nonce, created_at) VALUES(?, ?, ?, ?)')
|
||||
await db.prepare('INSERT INTO oauth_states(state, verifier, nonce, created_at) VALUES(?, ?, ?, ?)')
|
||||
.run(state, verifier, nonce, now());
|
||||
const q = new URLSearchParams({
|
||||
client_id: cfg.google.clientId,
|
||||
|
|
@ -79,8 +79,8 @@ export async function finishGoogleLogin(db, cfg, url, res) {
|
|||
const state = url.searchParams.get('state');
|
||||
if (!code || !state) throw new HttpError(400, 'Paramètres OAuth manquants');
|
||||
|
||||
const row = db.prepare('SELECT * FROM oauth_states WHERE state = ? AND created_at > ?').get(state, now() - STATE_TTL);
|
||||
db.prepare('DELETE FROM oauth_states WHERE state = ?').run(state);
|
||||
const row = await db.prepare('SELECT * FROM oauth_states WHERE state = ? AND created_at > ?').get(state, now() - STATE_TTL);
|
||||
await db.prepare('DELETE FROM oauth_states WHERE state = ?').run(state);
|
||||
if (!row) throw new HttpError(400, 'State OAuth invalide ou expiré');
|
||||
|
||||
const r = await fetch(GOOGLE_TOKEN, {
|
||||
|
|
@ -100,7 +100,7 @@ export async function finishGoogleLogin(db, cfg, url, res) {
|
|||
const email = checkIdTokenClaims(decodeJwtPayload(tokens.id_token), {
|
||||
clientId: cfg.google.clientId, nonce: row.nonce, allowedEmails: cfg.allowedEmails,
|
||||
});
|
||||
createSession(db, res, email);
|
||||
await createSession(db, res, email);
|
||||
redirect(res, '/');
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
import { resolve } from 'node:path';
|
||||
import { dbConfigFromEnv } from './db.js';
|
||||
|
||||
const env = process.env;
|
||||
|
||||
|
|
@ -23,6 +24,7 @@ export function loadConfig() {
|
|||
},
|
||||
allowedEmails: required('ALLOWED_EMAILS').split(',').map((e) => e.trim().toLowerCase()).filter(Boolean),
|
||||
secretKey: Buffer.from(secretKey, 'hex'),
|
||||
db: dbConfigFromEnv(env),
|
||||
dataDir: resolve(env.DATA_DIR || './data'),
|
||||
claudeBin: env.CLAUDE_BIN || 'claude',
|
||||
thermalMax: Number(env.THERMAL_MAX || 75),
|
||||
|
|
|
|||
136
src/handlers.js
136
src/handlers.js
|
|
@ -17,6 +17,16 @@ const sleep = (ms, signal) => new Promise((resolve, reject) => {
|
|||
signal?.addEventListener('abort', () => { clearTimeout(t); reject(new Error('Annulé')); }, { once: true });
|
||||
});
|
||||
|
||||
// Les callbacks du flux Claude (onText, onTurn) sont synchrones : leurs écritures en base passent par une file
|
||||
// ordonnée, attendue à la fin de la phase (flush). Une erreur d'écriture fait échouer le job au lieu de se perdre.
|
||||
function makeSink() {
|
||||
let chain = Promise.resolve();
|
||||
return {
|
||||
push(fn) { chain = chain.then(fn); chain.catch(() => {}); },
|
||||
flush: () => chain,
|
||||
};
|
||||
}
|
||||
|
||||
// Avancement d'une phase Claude : de `from` à `to` % au fil des messages, sur `maxTurns` au plus (estimation)
|
||||
const turnPct = (from, to, n, maxTurns) => Math.round(from + (to - from) * Math.min(1, n / Math.max(1, maxTurns)));
|
||||
|
||||
|
|
@ -49,9 +59,10 @@ export function makeHandlers(app) {
|
|||
// État du quota Pro (session 5h + semaine), affiché dans la barre système
|
||||
const w = rateLimitWindows(r.rateLimit);
|
||||
if (w) {
|
||||
setSetting(db, 'claude_rate_limit_json', JSON.stringify({ at: now(), ...w }));
|
||||
for (const a of quotaAlerts(db, w)) {
|
||||
notify(app, 'quota', {
|
||||
await setSetting(db, 'claude_rate_limit_json', JSON.stringify({ at: now(), ...w }));
|
||||
for (const a of await quotaAlerts(db, w)) {
|
||||
// notify ne lève jamais : un Discord indisponible ne fait pas échouer le job
|
||||
await notify(app, '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}.`,
|
||||
|
|
@ -67,30 +78,30 @@ 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 = getProject(app, ctx.job.project_id, { secrets: true });
|
||||
const template = getTemplate(db, project.id, kind, { validatedOnly: true });
|
||||
const project = await getProject(app, ctx.job.project_id, { 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');
|
||||
|
||||
const day = now() - 86400;
|
||||
const candidates = kind === 'followup'
|
||||
? followupCandidates(db, project)
|
||||
: db.prepare(`SELECT * FROM prospects WHERE project_id = ? AND status = 'new'
|
||||
? await followupCandidates(db, project)
|
||||
: await db.prepare(`SELECT * FROM prospects WHERE project_id = ? AND status = 'new'
|
||||
AND email NOT IN (SELECT email FROM blacklist) ORDER BY score DESC, id LIMIT 100`).all(project.id);
|
||||
const n = allowedToSend({
|
||||
requested: ctx.params.count,
|
||||
available: candidates.length,
|
||||
projectCap: project.dailyMailCap,
|
||||
sentTodayProject: sentSince(db, day, project.id),
|
||||
globalCap: Number(getSetting(db, 'global_daily_cap', '100')),
|
||||
sentTodayGlobal: sentSince(db, day),
|
||||
sentTodayProject: await sentSince(db, day, project.id),
|
||||
globalCap: Number(await getSetting(db, 'global_daily_cap', '100')),
|
||||
sentTodayGlobal: await sentSince(db, day),
|
||||
});
|
||||
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(getSetting(db, 'send_delay_min', '20')) * 1000;
|
||||
const maxDelay = Number(getSetting(db, 'send_delay_max', '60')) * 1000;
|
||||
const minDelay = Number(await getSetting(db, 'send_delay_min', '20')) * 1000;
|
||||
const maxDelay = Number(await getSetting(db, '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 = ?');
|
||||
|
|
@ -99,24 +110,24 @@ export function makeHandlers(app) {
|
|||
const original = db.prepare("SELECT subject, message_id FROM mail_log WHERE prospect_id = ? AND kind = 'initial' AND error IS NULL ORDER BY id LIMIT 1");
|
||||
const current = db.prepare('SELECT status, followup_at FROM prospects WHERE id = ?');
|
||||
let sent = 0, failed = 0;
|
||||
ctx.progress({ sent, failed, total: n, message: `0/${n} ${kind === 'followup' ? 'relances envoyées' : 'envoyés'}`, pct: 0 });
|
||||
await ctx.progress({ sent, failed, total: n, message: `0/${n} ${kind === 'followup' ? 'relances envoyées' : 'envoyés'}`, pct: 0 });
|
||||
|
||||
for (const p of candidates.slice(0, n)) {
|
||||
if (ctx.cancelled()) break;
|
||||
if (await ctx.cancelled()) break;
|
||||
if (kind === 'followup' && !inHours()) break; // le reste repartira au prochain créneau
|
||||
// Re-vérifie juste avant l'envoi : désinscription, réponse arrivée pendant le batch…
|
||||
if (db.prepare('SELECT 1 FROM blacklist WHERE email = ?').get(p.email)) continue;
|
||||
if (await db.prepare('SELECT 1 FROM blacklist WHERE email = ?').get(p.email)) continue;
|
||||
if (kind === 'followup') {
|
||||
const c = current.get(p.id);
|
||||
const c = await current.get(p.id);
|
||||
if (c.status !== 'sent' || c.followup_at) continue;
|
||||
}
|
||||
const unsubUrl = `${cfg.appUrl}/u/${encodeURIComponent(p.email)}/${unsubToken(cfg.secretKey, p.email)}`;
|
||||
let variant = null, subject, inReplyTo;
|
||||
if (kind === 'initial') {
|
||||
variant = pickVariant(db, project.id, template);
|
||||
variant = await pickVariant(db, project.id, template);
|
||||
subject = variant === 'B' ? template.subject_b : template.subject;
|
||||
} else {
|
||||
const orig = original.get(p.id);
|
||||
const orig = await original.get(p.id);
|
||||
subject = followupSubject(template, orig);
|
||||
inReplyTo = orig?.message_id;
|
||||
}
|
||||
|
|
@ -126,17 +137,17 @@ export function makeHandlers(app) {
|
|||
});
|
||||
try {
|
||||
await transport.sendMail(mail);
|
||||
log.run(project.id, p.id, p.email, now(), null, kind, variant, mail.subject, mail.messageId);
|
||||
if (kind === 'initial') markInitial.run('sent', now(), variant, p.id);
|
||||
else markFollowup.run(now(), p.id);
|
||||
await log.run(project.id, p.id, p.email, now(), null, kind, variant, mail.subject, mail.messageId);
|
||||
if (kind === 'initial') await markInitial.run('sent', now(), variant, p.id);
|
||||
else await markFollowup.run(now(), p.id);
|
||||
sent++;
|
||||
} catch (e) {
|
||||
log.run(project.id, p.id, p.email, now(), String(e.message).slice(0, 500), kind, variant, mail.subject, mail.messageId);
|
||||
if (/^5\d\d/.test(String(e.responseCode))) markBounced.run(p.id);
|
||||
await log.run(project.id, p.id, p.email, now(), String(e.message).slice(0, 500), kind, variant, mail.subject, mail.messageId);
|
||||
if (/^5\d\d/.test(String(e.responseCode))) await markBounced.run(p.id);
|
||||
failed++;
|
||||
}
|
||||
const label = kind === 'followup' ? 'relances envoyées' : 'envoyés';
|
||||
ctx.progress({ sent, failed, total: n, message: `${sent + failed}/${n} ${label}`, pct: Math.round(((sent + failed) / n) * 100) });
|
||||
await ctx.progress({ sent, failed, total: n, message: `${sent + failed}/${n} ${label}`, pct: Math.round(((sent + failed) / n) * 100) });
|
||||
if (sent + failed < n) await sleep(minDelay + Math.random() * (maxDelay - minDelay), ctx.signal).catch(() => {});
|
||||
}
|
||||
transport.close();
|
||||
|
|
@ -145,41 +156,46 @@ export function makeHandlers(app) {
|
|||
|
||||
return {
|
||||
async analyze(ctx) {
|
||||
const project = getProject(app, ctx.job.project_id);
|
||||
ctx.progress({ message: 'Récupération du repo…', pct: 3 });
|
||||
const project = await getProject(app, ctx.job.project_id);
|
||||
await ctx.progress({ message: 'Récupération du repo…', pct: 3 });
|
||||
const dir = repoDir(cfg, project.id);
|
||||
const commit = await syncRepo(project.gitUrl, dir, forgejoToken(app));
|
||||
const commit = await syncRepo(project.gitUrl, dir, await forgejoToken(app));
|
||||
|
||||
ctx.progress({ message: 'Analyse du code par Claude…', pct: 10 });
|
||||
await ctx.progress({ message: 'Analyse du code par Claude…', pct: 10 });
|
||||
const { prompt, system } = analyzePrompt(project.name);
|
||||
const model = getSetting(db, 'analyze_model', 'haiku');
|
||||
const model = await getSetting(db, 'analyze_model', 'haiku');
|
||||
const sink = makeSink();
|
||||
const r = await claude({
|
||||
prompt, system, cwd: dir, model, maxTurns: 20, tools: ['Read', 'Glob', 'Grep'], signal: ctx.signal,
|
||||
onTurn: (n) => ctx.progress({ message: `Lecture du code par Claude (étape ${n})…`, pct: turnPct(10, 95, n, 20) }),
|
||||
onTurn: (n) => sink.push(() => ctx.progress({ message: `Lecture du code par Claude (étape ${n})…`, pct: turnPct(10, 95, n, 20) })),
|
||||
});
|
||||
await sink.flush();
|
||||
addUsage(ctx, r);
|
||||
if (!r.ok) throw new Error(`Analyse incomplète (${r.subtype})`);
|
||||
const profile = extractJson(r.text);
|
||||
if (!profile.resume || !profile.cible) throw new Error('Fiche projet incomplète');
|
||||
const { cible, ...rest } = profile;
|
||||
db.prepare('UPDATE projects SET profile_json = ?, profile_commit = ?, profile_at = ?, target_json = ?, target_validated = 0 WHERE id = ?')
|
||||
await db.prepare('UPDATE projects SET profile_json = ?, profile_commit = ?, profile_at = ?, target_json = ?, target_validated = 0 WHERE id = ?')
|
||||
.run(JSON.stringify(rest), commit, now(), JSON.stringify(cible), project.id);
|
||||
return { commit };
|
||||
},
|
||||
|
||||
async prospect(ctx) {
|
||||
const project = getProject(app, ctx.job.project_id);
|
||||
const project = await getProject(app, ctx.job.project_id);
|
||||
if (!project.profile || !project.targetValidated) throw new Error('Valide la cible du projet avant de prospecter');
|
||||
const count = Math.max(1, Math.min(50, Math.floor(Number(ctx.params.count) || 10)));
|
||||
|
||||
// Domaines déjà connus (tous projets) : Claude ne les recherche pas une 2e fois
|
||||
const exclude = db.prepare(`
|
||||
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);
|
||||
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
|
||||
const optedOut = db.prepare('SELECT 1 FROM blacklist WHERE email = ?');
|
||||
const insert = db.prepare(`INSERT OR IGNORE INTO prospects(project_id, company, email, website, city, sector, hook, source, score, created_at)
|
||||
SELECT ?, ?, ?, ?, ?, ?, ?, ?, ?, ? WHERE NOT EXISTS (SELECT 1 FROM blacklist WHERE email = ?)`);
|
||||
VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);
|
||||
const sink = makeSink();
|
||||
let found = 0;
|
||||
let pending = '';
|
||||
let turns = 0;
|
||||
|
|
@ -194,53 +210,57 @@ export function makeHandlers(app) {
|
|||
pending += text + '\n';
|
||||
const lines = pending.split('\n');
|
||||
pending = lines.pop();
|
||||
for (const line of lines) {
|
||||
const p = parseProspectLine(line);
|
||||
if (!p) continue;
|
||||
const res = insert.run(project.id, p.company, p.email, p.website, p.city, p.sector, p.hook, p.source, p.score, now(), p.email);
|
||||
const parsed = lines.map(parseProspectLine).filter(Boolean);
|
||||
if (!parsed.length) return;
|
||||
sink.push(async () => {
|
||||
for (const p of parsed) {
|
||||
if (await optedOut.get(p.email)) continue;
|
||||
const res = await insert.run(project.id, p.company, p.email, p.website, p.city, p.sector, p.hook, p.source, p.score, now());
|
||||
if (res.changes) {
|
||||
found++;
|
||||
message = `${found}/${count} — ${p.company}`;
|
||||
report();
|
||||
await report();
|
||||
}
|
||||
}
|
||||
});
|
||||
};
|
||||
report();
|
||||
await report();
|
||||
const { prompt, system } = prospectPrompt({ profile: project.profile, target: project.target, count, exclude });
|
||||
const model = getSetting(db, 'prospect_model', 'haiku');
|
||||
const model = await getSetting(db, 'prospect_model', 'haiku');
|
||||
const r = await claude({
|
||||
prompt, system, model, tools: ['WebSearch', 'WebFetch'],
|
||||
maxTurns, onText, signal: ctx.signal,
|
||||
onTurn: (n) => { turns = n; report(); },
|
||||
onTurn: (n) => { turns = n; sink.push(report); },
|
||||
});
|
||||
onText('\n');
|
||||
await sink.flush();
|
||||
addUsage(ctx, r);
|
||||
return { found, requested: count, stoppedBy: r.subtype };
|
||||
},
|
||||
|
||||
async template(ctx) {
|
||||
const project = getProject(app, ctx.job.project_id, { secrets: true });
|
||||
const project = await getProject(app, ctx.job.project_id, { secrets: true });
|
||||
if (!project.profile) throw new Error('Analyse le projet d\'abord');
|
||||
ctx.progress({ message: 'Rédaction du modèle par Claude…', pct: 40 });
|
||||
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 });
|
||||
addUsage(ctx, r);
|
||||
const t = extractJson(r.text);
|
||||
if (!t.subject || !t.body) throw new Error('Modèle de mail invalide');
|
||||
saveTemplate(db, project.id, 'initial', { subject: t.subject, body: t.body });
|
||||
await saveTemplate(db, project.id, 'initial', { subject: t.subject, body: t.body });
|
||||
return { ok: true };
|
||||
},
|
||||
|
||||
async followup_template(ctx) {
|
||||
const project = getProject(app, ctx.job.project_id, { secrets: true });
|
||||
const project = await getProject(app, ctx.job.project_id, { secrets: true });
|
||||
if (!project.profile) throw new Error('Analyse le projet d\'abord');
|
||||
ctx.progress({ message: 'Rédaction de la relance par Claude…', pct: 40 });
|
||||
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 });
|
||||
addUsage(ctx, r);
|
||||
const t = extractJson(r.text);
|
||||
if (!t.body) throw new Error('Modèle de relance invalide');
|
||||
saveTemplate(db, project.id, 'followup', { subject: '', body: t.body });
|
||||
await saveTemplate(db, project.id, 'followup', { subject: '', body: t.body });
|
||||
return { ok: true };
|
||||
},
|
||||
|
||||
|
|
@ -248,29 +268,31 @@ export function makeHandlers(app) {
|
|||
followup: (ctx) => sendMails(ctx, 'followup'),
|
||||
|
||||
async evolution(ctx) {
|
||||
const project = getProject(app, ctx.job.project_id, { secrets: true });
|
||||
const project = await getProject(app, ctx.job.project_id, { secrets: true });
|
||||
const count = Math.max(1, Math.min(20, Math.floor(Number(ctx.params.count) || 5)));
|
||||
const level = LEVELS[ctx.params.level] ? ctx.params.level : 'normal';
|
||||
const to = getSetting(db, 'notify_email');
|
||||
const smtp = globalSmtp(app) || project.smtp;
|
||||
const to = await getSetting(db, 'notify_email');
|
||||
const smtp = (await globalSmtp(app)) || project.smtp;
|
||||
if (!to) throw new Error('Adresse de réception non configurée (Réglages)');
|
||||
if (!smtp) throw new Error('Aucun SMTP configuré (Réglages ou projet)');
|
||||
|
||||
ctx.progress({ message: 'Mise à jour du repo…', pct: 3 });
|
||||
await ctx.progress({ message: 'Mise à jour du repo…', pct: 3 });
|
||||
const dir = repoDir(cfg, project.id);
|
||||
await syncRepo(project.gitUrl, dir, forgejoToken(app));
|
||||
await syncRepo(project.gitUrl, dir, await forgejoToken(app));
|
||||
|
||||
ctx.progress({ message: `Recherche de ${count} évolutions (${level})…`, pct: 10 });
|
||||
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({
|
||||
prompt, system, cwd: dir, model, maxTurns, tools: ['Read', 'Glob', 'Grep'], signal: ctx.signal,
|
||||
onTurn: (n) => ctx.progress({ message: `Recherche de ${count} évolutions (${level}) · étape ${n}…`, pct: turnPct(10, 90, n, maxTurns) }),
|
||||
onTurn: (n) => sink.push(() => ctx.progress({ message: `Recherche de ${count} évolutions (${level}) · étape ${n}…`, pct: turnPct(10, 90, n, maxTurns) })),
|
||||
});
|
||||
await sink.flush();
|
||||
addUsage(ctx, r);
|
||||
if (!r.text?.trim()) throw new Error(`Pas de résultat (${r.subtype})`);
|
||||
|
||||
ctx.progress({ message: 'Envoi par mail…', pct: 95 });
|
||||
await ctx.progress({ message: 'Envoi par mail…', pct: 95 });
|
||||
const transport = (app.createTransport || createTransport)(smtp);
|
||||
await transport.sendMail({
|
||||
from: smtp.fromEmail, to,
|
||||
|
|
|
|||
|
|
@ -14,8 +14,8 @@ function readSecret(key, payload, what) {
|
|||
catch { console.warn(`[secrets] ${what} illisible (SECRET_KEY changée ?), à ressaisir`); return null; }
|
||||
}
|
||||
|
||||
export function getProject(app, id, { secrets = false } = {}) {
|
||||
const p = app.db.prepare('SELECT * FROM projects WHERE id = ?').get(Number(id));
|
||||
export async function getProject(app, id, { secrets = false } = {}) {
|
||||
const p = await app.db.prepare('SELECT * FROM projects WHERE id = ?').get(Number(id));
|
||||
if (!p) throw new HttpError(404, 'Projet introuvable');
|
||||
const out = {
|
||||
id: p.id, name: p.name, gitUrl: p.git_url,
|
||||
|
|
@ -35,22 +35,24 @@ export function getProject(app, id, { secrets = false } = {}) {
|
|||
return out;
|
||||
}
|
||||
|
||||
export function listProjects(app) {
|
||||
return app.db.prepare('SELECT id FROM projects ORDER BY name COLLATE NOCASE').all().map((r) => getProject(app, r.id));
|
||||
export 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 function createProject(app, { name, gitUrl }) {
|
||||
const r = app.db.prepare('INSERT INTO projects(name, git_url, created_at) VALUES(?, ?, ?)').run(name, gitUrl, now());
|
||||
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());
|
||||
return Number(r.lastInsertRowid);
|
||||
}
|
||||
|
||||
// Les secrets vides dans le formulaire = on garde l'ancien (le formulaire ne les réaffiche jamais)
|
||||
export function saveSecretConfig(app, id, column, incoming, secretField) {
|
||||
export async function saveSecretConfig(app, id, column, incoming, secretField) {
|
||||
if (!['smtp_enc', 'db_enc', 'imap_enc'].includes(column)) throw new Error('Colonne invalide');
|
||||
const current = readSecret(app.cfg.secretKey, app.db.prepare(`SELECT ${column} c FROM projects WHERE id = ?`).get(id)?.c, column) || {};
|
||||
const row = await app.db.prepare(`SELECT ${column} c FROM projects WHERE id = ?`).get(id);
|
||||
const current = readSecret(app.cfg.secretKey, row?.c, column) || {};
|
||||
const next = { ...current, ...incoming };
|
||||
if (!incoming[secretField]) next[secretField] = current[secretField];
|
||||
app.db.prepare(`UPDATE projects SET ${column} = ? WHERE id = ?`).run(encryptJson(app.cfg.secretKey, next), id);
|
||||
await app.db.prepare(`UPDATE projects SET ${column} = ? WHERE id = ?`).run(encryptJson(app.cfg.secretKey, next), id);
|
||||
}
|
||||
|
||||
// Version "affichable" d'une config secrète (sans mot de passe)
|
||||
|
|
@ -60,27 +62,27 @@ export function publicConfig(cfg, secretField) {
|
|||
return { ...rest, [`${secretField}Set`]: !!_omit };
|
||||
}
|
||||
|
||||
export function forgejoToken(app) {
|
||||
try { return decrypt(app.cfg.secretKey, getSetting(app.db, 'forgejo_token_enc')); }
|
||||
export async function forgejoToken(app) {
|
||||
try { return decrypt(app.cfg.secretKey, await getSetting(app.db, 'forgejo_token_enc')); }
|
||||
catch { console.warn('[secrets] token Forgejo illisible, à ressaisir'); return null; }
|
||||
}
|
||||
|
||||
export function globalSmtp(app) {
|
||||
return readSecret(app.cfg.secretKey, getSetting(app.db, 'smtp_enc'), 'SMTP global');
|
||||
export async function globalSmtp(app) {
|
||||
return readSecret(app.cfg.secretKey, await getSetting(app.db, 'smtp_enc'), 'SMTP global');
|
||||
}
|
||||
|
||||
export function prospectStats(db, projectId) {
|
||||
const rows = db.prepare('SELECT status, COUNT(*) n FROM prospects WHERE project_id = ? GROUP BY status').all(projectId);
|
||||
export async function prospectStats(db, projectId) {
|
||||
const rows = await db.prepare('SELECT status, COUNT(*) n FROM prospects WHERE project_id = ? GROUP BY status').all(projectId);
|
||||
const out = { total: 0 };
|
||||
for (const r of rows) { out[r.status] = r.n; out.total += r.n; }
|
||||
return out;
|
||||
}
|
||||
|
||||
export function sentSince(db, since, projectId = null) {
|
||||
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 ? db.prepare(sql).get(since) : db.prepare(sql).get(since, projectId)).n;
|
||||
return (projectId == null ? await db.prepare(sql).get(since) : await db.prepare(sql).get(since, projectId)).n;
|
||||
}
|
||||
|
||||
// IMAP : utilisateur vide = mêmes identifiants que le SMTP du projet (cas le plus courant)
|
||||
|
|
@ -96,24 +98,24 @@ export function imapCredentials(imap, smtp) {
|
|||
// ---------- Modèles de mail ----------
|
||||
export const TEMPLATE_KINDS = ['initial', 'followup'];
|
||||
|
||||
export function getTemplate(db, projectId, kind, { validatedOnly = false } = {}) {
|
||||
const row = db.prepare('SELECT * FROM templates WHERE project_id = ? AND kind = ?').get(projectId, kind);
|
||||
export async function getTemplate(db, projectId, kind, { validatedOnly = false } = {}) {
|
||||
const row = await db.prepare('SELECT * FROM templates WHERE project_id = ? AND kind = ?').get(projectId, kind);
|
||||
if (!row || (validatedOnly && row.status !== 'validated')) return null;
|
||||
return row;
|
||||
}
|
||||
|
||||
export function saveTemplate(db, projectId, kind, { subject = '', subjectB = null, body, status = 'draft' }) {
|
||||
export async function saveTemplate(db, projectId, kind, { subject = '', subjectB = null, body, status = 'draft' }) {
|
||||
if (!TEMPLATE_KINDS.includes(kind)) throw new HttpError(400, 'Type de modèle inconnu');
|
||||
db.prepare(`INSERT INTO templates(project_id, kind, subject, subject_b, body, status, updated_at) VALUES(?, ?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(project_id, kind) DO UPDATE SET subject = excluded.subject, subject_b = excluded.subject_b,
|
||||
body = excluded.body, status = excluded.status, updated_at = excluded.updated_at`)
|
||||
await db.prepare(`INSERT INTO templates(project_id, kind, subject, subject_b, body, status, updated_at) VALUES(?, ?, ?, ?, ?, ?, ?)
|
||||
ON DUPLICATE KEY UPDATE subject = VALUES(subject), subject_b = VALUES(subject_b),
|
||||
body = VALUES(body), status = VALUES(status), updated_at = VALUES(updated_at)`)
|
||||
.run(projectId, kind, subject, kind === 'initial' ? (subjectB || null) : null, body, status, now());
|
||||
}
|
||||
|
||||
// Objet A ou B : on équilibre les envois (B seulement si un objet B est défini)
|
||||
export function pickVariant(db, projectId, template) {
|
||||
export async function pickVariant(db, projectId, template) {
|
||||
if (!template.subject_b) return 'A';
|
||||
const rows = db.prepare(`SELECT variant, COUNT(*) n FROM mail_log
|
||||
const rows = await db.prepare(`SELECT variant, COUNT(*) n FROM mail_log
|
||||
WHERE project_id = ? AND kind = 'initial' AND error IS NULL AND variant IN ('A', 'B') GROUP BY variant`).all(projectId);
|
||||
const count = { A: 0, B: 0 };
|
||||
for (const r of rows) count[r.variant] = r.n;
|
||||
|
|
@ -121,8 +123,8 @@ export function pickVariant(db, projectId, template) {
|
|||
}
|
||||
|
||||
// Taux de réponse par objet (A/B) sur les premiers mails
|
||||
export function abStats(db, projectId) {
|
||||
const rows = db.prepare(`SELECT m.variant v, COUNT(*) sent, SUM(p.replied_at IS NOT NULL) replied
|
||||
export async function abStats(db, projectId) {
|
||||
const rows = await db.prepare(`SELECT m.variant v, COUNT(*) sent, SUM(p.replied_at IS NOT NULL) replied
|
||||
FROM mail_log m JOIN prospects p ON p.id = m.prospect_id
|
||||
WHERE m.project_id = ? AND m.kind = 'initial' AND m.error IS NULL AND m.variant IS NOT NULL
|
||||
GROUP BY m.variant ORDER BY m.variant`).all(projectId);
|
||||
|
|
|
|||
238
src/routes.js
238
src/routes.js
|
|
@ -33,8 +33,8 @@ export function registerRoutes(router, app) {
|
|||
const { db, cfg } = app;
|
||||
|
||||
// ---------- Public ----------
|
||||
router.get('/login', ({ res, url }) => html(res, loginPage(url.searchParams.get('e'))), { public: true });
|
||||
router.get('/auth/google', ({ res }) => startGoogleLogin(db, cfg, res), { public: true });
|
||||
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)}`); }
|
||||
|
|
@ -42,47 +42,49 @@ export function registerRoutes(router, app) {
|
|||
|
||||
// Désinscription (RGPD). GET = page de confirmation (évite les désinscriptions par les scanners de liens),
|
||||
// POST = désinscription effective, compatible "one-click" (RFC 8058).
|
||||
router.get('/u/:email/:token', ({ res, params }) => {
|
||||
router.get('/u/:email/:token', async ({ res, params }) => {
|
||||
const valid = verifyUnsubToken(cfg.secretKey, params.email, params.token);
|
||||
html(res, unsubPage({ email: params.email, valid, done: false }), valid ? 200 : 400);
|
||||
}, { public: true });
|
||||
router.post('/u/:email/:token', ({ res, params }) => {
|
||||
router.post('/u/:email/:token', async ({ res, params }) => {
|
||||
const email = params.email.toLowerCase();
|
||||
const valid = verifyUnsubToken(cfg.secretKey, email, params.token);
|
||||
if (valid) {
|
||||
db.prepare("INSERT OR IGNORE INTO blacklist(email, reason, created_at) VALUES(?, 'unsubscribe', ?)").run(email, now());
|
||||
db.prepare("UPDATE prospects SET status = 'refused' WHERE email = ? AND status IN ('new','sent')").run(email);
|
||||
await db.prepare("INSERT OR IGNORE INTO blacklist(email, reason, created_at) VALUES(?, 'unsubscribe', ?)").run(email, now());
|
||||
await db.prepare("UPDATE prospects SET status = 'refused' WHERE email = ? AND status IN ('new','sent')").run(email);
|
||||
}
|
||||
html(res, unsubPage({ email, valid, done: valid }), valid ? 200 : 400);
|
||||
}, { public: true });
|
||||
|
||||
// ---------- Privé ----------
|
||||
router.post('/logout', ({ req, res }) => { destroySession(db, req, res); redirect(res, '/login'); });
|
||||
router.post('/logout', async ({ req, res }) => { await destroySession(db, req, res); redirect(res, '/login'); });
|
||||
|
||||
router.get('/', ({ res, session }) => {
|
||||
const projects = listProjects(app).map((p) => {
|
||||
const full = getProject(app, p.id, { secrets: true });
|
||||
return { 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: getSetting(db, 'forgejo_host') }));
|
||||
router.get('/', async ({ res, session }) => {
|
||||
const projects = [];
|
||||
for (const p of await listProjects(app)) {
|
||||
const full = await getProject(app, p.id, { 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') }));
|
||||
});
|
||||
|
||||
router.get('/settings', ({ res, session, url }) => {
|
||||
router.get('/settings', async ({ res, session, url }) => {
|
||||
const discord = await notifyConfig(app);
|
||||
const s = {
|
||||
notify_email: getSetting(db, 'notify_email', ''),
|
||||
forgejo_host: getSetting(db, 'forgejo_host', ''),
|
||||
forgejo_token_set: !!getSetting(db, 'forgejo_token_enc'),
|
||||
smtp: publicConfig(globalSmtp(app), 'pass'),
|
||||
global_daily_cap: getSetting(db, 'global_daily_cap', '100'),
|
||||
send_delay_min: getSetting(db, 'send_delay_min', '20'),
|
||||
send_delay_max: getSetting(db, 'send_delay_max', '60'),
|
||||
prospect_model: getSetting(db, 'prospect_model', 'haiku'),
|
||||
analyze_model: getSetting(db, 'analyze_model', 'haiku'),
|
||||
blacklist_count: db.prepare('SELECT COUNT(*) n FROM blacklist').get().n,
|
||||
weekly_report: getSetting(db, 'weekly_report', '0') === '1',
|
||||
budget_day_usd: getSetting(db, 'budget_day_usd', ''),
|
||||
budget_month_usd: getSetting(db, 'budget_month_usd', ''),
|
||||
discord: { set: !!notifyConfig(app).url, events: notifyConfig(app).events, all: EVENTS },
|
||||
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', ''),
|
||||
discord: { set: !!discord.url, events: discord.events, all: EVENTS },
|
||||
};
|
||||
html(res, settingsPage({ email: session.email, s, saved: url.searchParams.has('ok') }));
|
||||
});
|
||||
|
|
@ -90,31 +92,31 @@ export function registerRoutes(router, app) {
|
|||
router.post('/settings', async ({ req, res }) => {
|
||||
const b = await readBody(req);
|
||||
if (b.notify_email && !EMAIL_RE.test(b.notify_email)) throw new HttpError(400, 'Email de réception invalide');
|
||||
setSetting(db, 'notify_email', (b.notify_email || '').trim());
|
||||
setSetting(db, 'forgejo_host', (b.forgejo_host || '').trim().replace(/^https?:\/\//, '').replace(/\/.*$/, ''));
|
||||
if (b.forgejo_token) setSetting(db, 'forgejo_token_enc', encrypt(cfg.secretKey, b.forgejo_token.trim()));
|
||||
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()));
|
||||
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));
|
||||
setSetting(db, 'global_daily_cap', String(cap));
|
||||
setSetting(db, 'send_delay_min', String(dmin));
|
||||
setSetting(db, 'send_delay_max', String(dmax));
|
||||
setSetting(db, 'prospect_model', b.prospect_model === 'sonnet' ? 'sonnet' : 'haiku');
|
||||
setSetting(db, 'analyze_model', b.analyze_model === 'sonnet' ? 'sonnet' : 'haiku');
|
||||
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');
|
||||
const money = (v) => { const n = Number(String(v || '').replace(',', '.')); return Number.isFinite(n) && n > 0 ? String(Math.round(n * 100) / 100) : ''; };
|
||||
setSetting(db, 'weekly_report', b.weekly_report === 'on' ? '1' : '0');
|
||||
setSetting(db, 'budget_day_usd', money(b.budget_day_usd));
|
||||
setSetting(db, 'budget_month_usd', money(b.budget_month_usd));
|
||||
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));
|
||||
|
||||
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) setSetting(db, 'discord_webhook_enc', encrypt(cfg.secretKey, hook));
|
||||
if (b.discord_remove === 'on') setSetting(db, 'discord_webhook_enc', null);
|
||||
setSetting(db, 'discord_events', JSON.stringify(Object.keys(EVENTS).filter((k) => b[`ev_${k}`] === 'on')));
|
||||
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')));
|
||||
|
||||
const prev = globalSmtp(app) || {};
|
||||
const prev = await globalSmtp(app) || {};
|
||||
const smtp = { host: b.smtp_host, port: b.smtp_port, user: b.smtp_user, pass: b.smtp_pass || prev.pass, fromEmail: b.smtp_fromEmail };
|
||||
setSetting(db, 'smtp_enc', smtp.host ? encryptJson(cfg.secretKey, smtp) : null);
|
||||
await setSetting(db, 'smtp_enc', smtp.host ? encryptJson(cfg.secretKey, smtp) : null);
|
||||
redirect(res, '/settings?ok');
|
||||
});
|
||||
|
||||
|
|
@ -126,28 +128,28 @@ export function registerRoutes(router, app) {
|
|||
});
|
||||
|
||||
router.post('/api/notify/test', async ({ res }) => {
|
||||
if (!notifyConfig(app).url) throw new HttpError(400, 'Aucun webhook Discord configuré');
|
||||
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 });
|
||||
if (!ok) throw new HttpError(502, 'Discord a refusé la notification (webhook supprimé ?)');
|
||||
json(res, { ok: true });
|
||||
});
|
||||
|
||||
router.get('/api/system', ({ res }) => {
|
||||
const queue = 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 = db.prepare("SELECT COUNT(*) n FROM jobs WHERE status = 'queued' AND run_after > ?").get(now()).n;
|
||||
const rlRaw = getSetting(db, 'claude_rate_limit_json');
|
||||
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');
|
||||
// Détail pour le menu « jobs » de la barre du haut : en cours d'abord, puis la file, puis les programmés
|
||||
const jobs = 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
|
||||
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) => ({
|
||||
ORDER BY j.status = 'running' DESC, COALESCE(j.run_after, 0), j.id LIMIT 20`).all()).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: usageSummary(db), budget: budgetState(db), thermalMax: cfg.thermalMax,
|
||||
temp: cpuTemp(), queue, scheduled, jobs, usage: await usageSummary(db), budget: await budgetState(db), thermalMax: cfg.thermalMax,
|
||||
claudeRateLimit: rlRaw ? JSON.parse(rlRaw) : null,
|
||||
});
|
||||
});
|
||||
|
|
@ -156,49 +158,49 @@ export function registerRoutes(router, app) {
|
|||
const b = await readBody(req);
|
||||
const name = String(b.name || '').trim().slice(0, 80);
|
||||
if (!name) throw new HttpError(400, 'Nom requis');
|
||||
const host = getSetting(db, 'forgejo_host');
|
||||
const host = await getSetting(db, '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 (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 = createProject(app, { name, gitUrl });
|
||||
enqueue(db, { projectId: id, type: 'analyze' });
|
||||
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' });
|
||||
json(res, { id });
|
||||
});
|
||||
|
||||
router.post('/api/projects/:id/delete', ({ res, params }) => {
|
||||
const p = getProject(app, pid(params));
|
||||
db.prepare('DELETE FROM projects WHERE id = ?').run(p.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));
|
||||
clearRecapCache(p.id);
|
||||
json(res, { ok: true });
|
||||
});
|
||||
|
||||
router.get('/api/projects/:id/status', ({ res, params }) => {
|
||||
const p = getProject(app, pid(params));
|
||||
const jobs = latestJobs(db, p.id);
|
||||
router.get('/api/projects/:id/status', async ({ res, params }) => {
|
||||
const p = await getProject(app, pid(params));
|
||||
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);
|
||||
const tplOut = (row) => (row ? { subject: row.subject, subjectB: row.subject_b, body: row.body, status: row.status, updated_at: row.updated_at } : null);
|
||||
const templates = { initial: tplOut(getTemplate(db, p.id, 'initial')), followup: tplOut(getTemplate(db, p.id, 'followup')) };
|
||||
const stats = prospectStats(db, p.id);
|
||||
const templates = { initial: tplOut(await getTemplate(db, p.id, 'initial')), followup: tplOut(await getTemplate(db, p.id, 'followup')) };
|
||||
const stats = await prospectStats(db, p.id);
|
||||
const day = now() - 86400;
|
||||
const sendMax = allowedToSend({
|
||||
requested: 100, available: stats.new || 0,
|
||||
projectCap: p.dailyMailCap, sentTodayProject: sentSince(db, day, p.id),
|
||||
globalCap: Number(getSetting(db, 'global_daily_cap', '100')), sentTodayGlobal: sentSince(db, day),
|
||||
projectCap: p.dailyMailCap, sentTodayProject: await sentSince(db, day, p.id),
|
||||
globalCap: Number(await getSetting(db, 'global_daily_cap', '100')), sentTodayGlobal: await sentSince(db, day),
|
||||
});
|
||||
json(res, {
|
||||
jobs, templates, stats, sendMax,
|
||||
followup: { enabled: p.followupEnabled, days: p.followupDays, ...followupPlan(db, p) },
|
||||
followup: { enabled: p.followupEnabled, days: p.followupDays, ...(await followupPlan(db, p)) },
|
||||
targetValidated: p.targetValidated, hasProfile: !!p.profile, hasSmtp: p.hasSmtp,
|
||||
hasImap: p.hasImap, inbox: p.inbox, ab: abStats(db, p.id),
|
||||
hasImap: p.hasImap, inbox: p.inbox, ab: await abStats(db, p.id),
|
||||
});
|
||||
});
|
||||
|
||||
router.post('/api/projects/:id/target', async ({ req, res, params }) => {
|
||||
const p = getProject(app, pid(params));
|
||||
const p = await getProject(app, pid(params));
|
||||
const b = await readBody(req);
|
||||
const target = {
|
||||
description: String(b.description || '').slice(0, 300),
|
||||
|
|
@ -209,18 +211,18 @@ export function registerRoutes(router, app) {
|
|||
requetes: lines(b.requetes),
|
||||
};
|
||||
if (!target.description || !target.secteurs.length) throw new HttpError(400, 'Description et au moins un secteur requis');
|
||||
db.prepare('UPDATE projects SET target_json = ?, target_validated = 1 WHERE id = ?').run(JSON.stringify(target), p.id);
|
||||
await db.prepare('UPDATE projects SET target_json = ?, target_validated = 1 WHERE id = ?').run(JSON.stringify(target), p.id);
|
||||
json(res, { ok: true });
|
||||
});
|
||||
|
||||
const jobRoute = (type, paramsOf = () => ({}), guard = () => {}) => async ({ req, res, params }) => {
|
||||
const p = getProject(app, pid(params));
|
||||
const p = await getProject(app, pid(params));
|
||||
const b = req.headers['content-type']?.includes('json') ? await readBody(req) : {};
|
||||
guard(p, b);
|
||||
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 = enqueue(db, { projectId: p.id, type, params: paramsOf(b), runAfter });
|
||||
const budget = AI_JOBS.has(type) ? budgetState(db) : null;
|
||||
const r = await enqueue(db, { projectId: p.id, type, params: paramsOf(b), runAfter });
|
||||
const budget = AI_JOBS.has(type) ? await budgetState(db) : null;
|
||||
json(res, { ...r, budgetBlocked: budget?.blocked ? budget.reason : null });
|
||||
};
|
||||
|
||||
|
|
@ -232,10 +234,10 @@ export function registerRoutes(router, app) {
|
|||
if (!p.profile) throw new HttpError(400, "Analyse le projet d'abord");
|
||||
}));
|
||||
router.post('/api/projects/:id/followup', async ({ req, res, params }) => {
|
||||
const p = getProject(app, pid(params));
|
||||
const p = await getProject(app, pid(params));
|
||||
const b = await readBody(req);
|
||||
const enabled = b.enabled === true || b.enabled === 'on';
|
||||
db.prepare('UPDATE projects SET followup_enabled = ?, followup_days = ? WHERE id = ?').run(enabled ? 1 : 0, int(b.days, 2, 30, 7), p.id);
|
||||
await db.prepare('UPDATE projects SET followup_enabled = ?, followup_days = ? WHERE id = ?').run(enabled ? 1 : 0, int(b.days, 2, 30, 7), p.id);
|
||||
json(res, { ok: true });
|
||||
});
|
||||
router.post('/api/projects/:id/prospect', jobRoute('prospect', (b) => ({ count: int(b.count, 1, 50, 10) }), (p) => {
|
||||
|
|
@ -245,14 +247,14 @@ export function registerRoutes(router, app) {
|
|||
count: int(b.count, 1, 20, 5),
|
||||
level: ['rapide', 'normal', 'approfondi'].includes(b.level) ? b.level : 'rapide',
|
||||
})));
|
||||
router.post('/api/projects/:id/send', jobRoute('send', (b) => ({ count: int(b.count, 1, 100, 10) }), (p, b) => {
|
||||
router.post('/api/projects/:id/send', jobRoute('send', (b) => ({ count: int(b.count, 1, 100, 10) }), async (p, b) => {
|
||||
if (!b.confirm) throw new HttpError(400, 'Confirmation requise');
|
||||
const running = db.prepare("SELECT 1 FROM jobs WHERE project_id = ? AND type = 'prospect' AND status IN ('queued','running')").get(p.id);
|
||||
const running = await db.prepare("SELECT 1 FROM jobs WHERE project_id = ? AND type = 'prospect' AND status IN ('queued','running')").get(p.id);
|
||||
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 = getProject(app, pid(params));
|
||||
const p = await getProject(app, pid(params));
|
||||
const b = await readBody(req);
|
||||
const subject = String(b.subject || '').trim().slice(0, 200);
|
||||
const body = String(b.body || '').trim().slice(0, 5000);
|
||||
|
|
@ -261,32 +263,32 @@ export function registerRoutes(router, app) {
|
|||
// Relance : objet facultatif (vide = "Re: <objet du 1er mail>", même fil de discussion)
|
||||
if (!body || (kind === 'initial' && !subject)) throw new HttpError(400, kind === 'initial' ? 'Objet et corps requis' : 'Corps requis');
|
||||
const status = b.mode === 'validate' ? 'validated' : 'draft';
|
||||
saveTemplate(db, p.id, kind, { subject, subjectB, body, status });
|
||||
await saveTemplate(db, p.id, kind, { subject, subjectB, body, status });
|
||||
json(res, { ok: true, status });
|
||||
});
|
||||
|
||||
router.post('/api/projects/:id/smtp', async ({ req, res, params }) => {
|
||||
const p = getProject(app, pid(params));
|
||||
const p = await getProject(app, pid(params));
|
||||
const b = await readBody(req);
|
||||
if (b.fromEmail && !EMAIL_RE.test(b.fromEmail)) throw new HttpError(400, 'Email expéditeur invalide');
|
||||
saveSecretConfig(app, p.id, 'smtp_enc', {
|
||||
await saveSecretConfig(app, p.id, 'smtp_enc', {
|
||||
host: String(b.host || '').trim(), port: int(b.port, 1, 65535, 587), user: String(b.user || '').trim(),
|
||||
pass: b.pass || '', fromEmail: String(b.fromEmail || '').trim(), fromName: String(b.fromName || '').trim().slice(0, 80),
|
||||
}, 'pass');
|
||||
db.prepare('UPDATE projects SET daily_mail_cap = ? WHERE id = ?').run(int(b.dailyCap, 1, 200, 30), p.id);
|
||||
await db.prepare('UPDATE projects SET daily_mail_cap = ? WHERE id = ?').run(int(b.dailyCap, 1, 200, 30), p.id);
|
||||
json(res, { ok: true });
|
||||
});
|
||||
|
||||
// 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 = getProject(app, pid(params));
|
||||
const p = await getProject(app, pid(params));
|
||||
const b = await readBody(req);
|
||||
const host = String(b.host || '').trim();
|
||||
if (!host) {
|
||||
db.prepare('UPDATE projects SET imap_enc = NULL, inbox_json = NULL WHERE id = ?').run(p.id);
|
||||
await db.prepare('UPDATE projects SET imap_enc = NULL, inbox_json = NULL WHERE id = ?').run(p.id);
|
||||
return json(res, { ok: true, disabled: true });
|
||||
}
|
||||
saveSecretConfig(app, p.id, 'imap_enc', {
|
||||
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) }); }
|
||||
|
|
@ -294,18 +296,18 @@ export function registerRoutes(router, app) {
|
|||
});
|
||||
|
||||
router.post('/api/projects/:id/inbox/check', async ({ res, params }) => {
|
||||
const p = getProject(app, pid(params));
|
||||
const p = await getProject(app, pid(params));
|
||||
try { json(res, { ok: true, check: await checkInbox(app, p.id) }); }
|
||||
catch (e) { throw new HttpError(502, e.message); }
|
||||
});
|
||||
|
||||
router.post('/api/projects/:id/db', async ({ req, res, params }) => {
|
||||
const p = getProject(app, pid(params));
|
||||
const p = await getProject(app, pid(params));
|
||||
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}`); }
|
||||
}
|
||||
saveSecretConfig(app, p.id, 'db_enc', {
|
||||
await saveSecretConfig(app, p.id, 'db_enc', {
|
||||
type: b.type === 'pg' ? 'pg' : 'mysql', host: String(b.host || '').trim(), port: b.port ? int(b.port, 1, 65535, null) : null,
|
||||
database: String(b.database || '').trim(), user: String(b.user || '').trim(), password: b.password || '',
|
||||
ssl: b.ssl === 'on' || b.ssl === true,
|
||||
|
|
@ -316,19 +318,19 @@ export function registerRoutes(router, app) {
|
|||
});
|
||||
|
||||
router.get('/api/projects/:id/recap', async ({ res, params, url }) => {
|
||||
const p = getProject(app, pid(params), { secrets: true });
|
||||
const stats = prospectStats(db, p.id);
|
||||
const cost = db.prepare('SELECT COALESCE(SUM(cost_usd),0) c FROM jobs WHERE project_id = ?').get(p.id).c;
|
||||
const p = await getProject(app, pid(params), { 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;
|
||||
let business = null, error = null;
|
||||
try {
|
||||
business = await fetchRecap(p.id, p.dbCfg, { force: url.searchParams.has('force') });
|
||||
saveSnapshot(db, p.id, business); // la consultation alimente aussi la courbe du jour
|
||||
await saveSnapshot(db, p.id, business); // la consultation alimente aussi la courbe du jour
|
||||
} catch (e) { error = e.message; }
|
||||
json(res, { business, error, stats, aiCostUsd: cost });
|
||||
});
|
||||
|
||||
router.get('/api/projects/:id/prospects\\.csv', ({ res, params, url }) => {
|
||||
const p = getProject(app, pid(params));
|
||||
router.get('/api/projects/:id/prospects\\.csv', async ({ res, params, url }) => {
|
||||
const p = await getProject(app, pid(params));
|
||||
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, {
|
||||
|
|
@ -336,62 +338,62 @@ export function registerRoutes(router, app) {
|
|||
'Content-Disposition': `attachment; filename="prospects-${slug}-${date}.csv"`,
|
||||
'Cache-Control': 'no-store',
|
||||
});
|
||||
res.end(exportProspects(db, p.id, parseFilters(url.searchParams)));
|
||||
res.end(await exportProspects(db, p.id, parseFilters(url.searchParams)));
|
||||
});
|
||||
|
||||
router.post('/api/projects/:id/prospects/import', async ({ req, res, params }) => {
|
||||
const p = getProject(app, pid(params));
|
||||
const p = await getProject(app, pid(params));
|
||||
const b = await readBody(req, { max: 1024 * 1024 });
|
||||
try { json(res, importProspects(db, p.id, String(b.csv || ''))); }
|
||||
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', ({ res, params, url }) => {
|
||||
const p = getProject(app, pid(params));
|
||||
json(res, history(db, p.id, { days: url.searchParams.get('days') === '90' ? 90 : 30 }));
|
||||
router.get('/api/projects/:id/history', async ({ res, params, url }) => {
|
||||
const p = await getProject(app, pid(params));
|
||||
json(res, await history(db, p.id, { days: url.searchParams.get('days') === '90' ? 90 : 30 }));
|
||||
});
|
||||
|
||||
router.get('/api/projects/:id/prospects', ({ res, params, url }) => {
|
||||
const p = getProject(app, pid(params));
|
||||
json(res, listProspects(db, p.id, parseFilters(url.searchParams)));
|
||||
router.get('/api/projects/:id/prospects', async ({ res, params, url }) => {
|
||||
const p = await getProject(app, pid(params));
|
||||
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 }) => {
|
||||
const b = await readBody(req);
|
||||
if (!STATUSES.includes(b.status)) throw new HttpError(400, 'Statut invalide');
|
||||
const r = db.prepare('UPDATE prospects SET status = ? WHERE id = ?').run(b.status, Number(params.id));
|
||||
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');
|
||||
if (b.status === 'refused') {
|
||||
const { email } = db.prepare('SELECT email FROM prospects WHERE id = ?').get(Number(params.id));
|
||||
db.prepare("INSERT OR IGNORE INTO blacklist(email, reason, created_at) VALUES(?, 'refused', ?)").run(email, now());
|
||||
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());
|
||||
}
|
||||
json(res, { ok: true });
|
||||
});
|
||||
|
||||
// ---------- Fiche prospect ----------
|
||||
const prospectId = (params) => {
|
||||
const prospectId = async (params) => {
|
||||
const id = Number(params.id);
|
||||
if (!db.prepare('SELECT 1 FROM prospects WHERE id = ?').get(id)) throw new HttpError(404, 'Prospect introuvable');
|
||||
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', ({ res, params }) => json(res, prospectDetail(db, prospectId(params))));
|
||||
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 = prospectId(params);
|
||||
const noteId = addNote(db, id, (await readBody(req)).body);
|
||||
const id = await prospectId(params);
|
||||
const noteId = await addNote(db, id, (await readBody(req)).body);
|
||||
if (!noteId) throw new HttpError(400, 'Note vide');
|
||||
json(res, { ok: true, id: noteId });
|
||||
});
|
||||
router.post('/api/prospects/:id/notes/:nid/delete', ({ res, params }) => {
|
||||
if (!deleteNote(db, prospectId(params), Number(params.nid))) throw new HttpError(404, 'Note introuvable');
|
||||
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/next', async ({ req, res, params }) => {
|
||||
const id = prospectId(params);
|
||||
const id = await prospectId(params);
|
||||
const b = await readBody(req);
|
||||
try { json(res, { ok: true, at: setNextAction(db, id, b.action, b.day) }); }
|
||||
try { json(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', ({ res, params }) => { cancelJob(db, Number(params.id)); json(res, { ok: true }); });
|
||||
router.post('/api/jobs/:id/cancel', async ({ res, params }) => { await cancelJob(db, Number(params.id)); json(res, { ok: true }); });
|
||||
}
|
||||
|
|
|
|||
|
|
@ -30,7 +30,8 @@ const SECURITY_HEADERS = {
|
|||
'Strict-Transport-Security': 'max-age=31536000',
|
||||
};
|
||||
|
||||
export function createApp(cfg, { db = openDb(cfg.dataDir), worker = true, createTransport } = {}) {
|
||||
export async function createApp(cfg, { db, worker = true, createTransport } = {}) {
|
||||
db ??= await openDb(cfg.db);
|
||||
const app = { db, cfg, createTransport };
|
||||
const router = new Router();
|
||||
registerRoutes(router, app);
|
||||
|
|
@ -46,7 +47,7 @@ export function createApp(cfg, { db = openDb(cfg.dataDir), worker = true, create
|
|||
}
|
||||
const route = router.match(req.method, url.pathname);
|
||||
if (!route) throw new HttpError(404, 'Page introuvable');
|
||||
const session = route.public ? null : getSession(db, req);
|
||||
const session = route.public ? null : await getSession(db, req);
|
||||
if (!route.public) {
|
||||
if (!session) {
|
||||
if (url.pathname.startsWith('/api/')) throw new HttpError(401, 'Non connecté');
|
||||
|
|
@ -92,23 +93,34 @@ export function createApp(cfg, { db = openDb(cfg.dataDir), worker = true, create
|
|||
description: `CPU à ${t} °C : les jobs IA attendent que le Pi redescende sous ${cfg.thermalMax - 5} °C.`,
|
||||
}),
|
||||
});
|
||||
w.start();
|
||||
await w.start();
|
||||
scheduler = new Scheduler(app);
|
||||
scheduler.start();
|
||||
}
|
||||
const purge = setInterval(() => purgeExpired(db), 3600_000);
|
||||
let purging = null;
|
||||
const purge = setInterval(() => {
|
||||
purging = purgeExpired(db).catch((e) => console.error('[purge]', e.message));
|
||||
}, 3600_000);
|
||||
purge.unref();
|
||||
|
||||
app.close = () => new Promise((r) => { w?.stop(); scheduler?.stop(); clearInterval(purge); server.close(() => { db.close(); r(); }); });
|
||||
// Arrêt propre : plus de requêtes, puis fin du job en cours et des tâches de fond, enfin fermeture de la base
|
||||
app.close = async () => {
|
||||
clearInterval(purge);
|
||||
await new Promise((r) => { server.close(r); server.closeIdleConnections?.(); });
|
||||
await w?.stop();
|
||||
await scheduler?.stop();
|
||||
await purging;
|
||||
await db.close();
|
||||
};
|
||||
app.server = server;
|
||||
return app;
|
||||
}
|
||||
|
||||
if (process.argv[1] === fileURLToPath(import.meta.url)) {
|
||||
const cfg = loadConfig();
|
||||
const app = createApp(cfg);
|
||||
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));
|
||||
const shutdown = () => app.close().then(() => process.exit(0), (e) => { console.error(e); process.exit(1); });
|
||||
process.on('SIGTERM', shutdown);
|
||||
process.on('SIGINT', shutdown);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -8,19 +8,19 @@ 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)
|
||||
function spentSince(db, since) {
|
||||
return db.prepare('SELECT COALESCE(SUM(cost_usd), 0) c FROM jobs WHERE COALESCE(finished_at, created_at) > ?').get(since).c;
|
||||
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;
|
||||
}
|
||||
|
||||
function limit(db, key) {
|
||||
const v = Number(getSetting(db, key, ''));
|
||||
async function limit(db, key) {
|
||||
const v = Number(await getSetting(db, 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 function budgetState(db, { at = now() } = {}) {
|
||||
const day = { used: spentSince(db, at - 86400), limit: limit(db, 'budget_day_usd') };
|
||||
const month = { used: spentSince(db, at - 30 * 86400), limit: limit(db, 'budget_month_usd') };
|
||||
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') };
|
||||
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 function quotaState(db) {
|
||||
const raw = getSetting(db, 'claude_rate_limit_json');
|
||||
export async function quotaState(db) {
|
||||
const raw = await getSetting(db, '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 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 function quotaAlerts(db, windows) {
|
||||
export async function quotaAlerts(db, windows) {
|
||||
if (!windows) return [];
|
||||
let prev = {};
|
||||
try { prev = JSON.parse(getSetting(db, 'claude_quota_notified_json', '{}') || '{}'); } catch { prev = {}; }
|
||||
try { prev = JSON.parse((await getSetting(db, '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 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 };
|
||||
}
|
||||
setSetting(db, 'claude_quota_notified_json', JSON.stringify(next));
|
||||
await setSetting(db, 'claude_quota_notified_json', JSON.stringify(next));
|
||||
return alerts;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -10,7 +10,7 @@ const SORTS = {
|
|||
score: 'score DESC, id DESC',
|
||||
recent: 'created_at DESC, id DESC',
|
||||
contacted: 'COALESCE(sent_at, 0) DESC, id DESC',
|
||||
company: 'company COLLATE NOCASE, id',
|
||||
company: 'LOWER(company), id',
|
||||
};
|
||||
|
||||
const int = (v, min, max, def) => {
|
||||
|
|
@ -34,8 +34,9 @@ export function filterWhere(projectId, f) {
|
|||
const where = ['project_id = ?'];
|
||||
const args = [projectId];
|
||||
if (f.q) {
|
||||
const like = `%${f.q.replace(/[\\%_]/g, (c) => `\\${c}`)}%`;
|
||||
where.push("(company LIKE ? ESCAPE '\\' OR email LIKE ? ESCAPE '\\' OR city LIKE ? ESCAPE '\\' OR sector LIKE ? ESCAPE '\\')");
|
||||
// '!' comme échappement : le backslash n'a pas le même sens dans un littéral SQLite et MySQL
|
||||
const like = `%${f.q.replace(/[!%_]/g, (c) => `!${c}`)}%`;
|
||||
where.push("(company LIKE ? ESCAPE '!' OR email LIKE ? ESCAPE '!' OR city LIKE ? ESCAPE '!' OR sector LIKE ? ESCAPE '!')");
|
||||
args.push(like, like, like, like);
|
||||
}
|
||||
if (f.status) { where.push('status = ?'); args.push(f.status); }
|
||||
|
|
@ -44,12 +45,12 @@ export function filterWhere(projectId, f) {
|
|||
return { sql: where.join(' AND '), args, order: SORTS[f.sort] || SORTS.score };
|
||||
}
|
||||
|
||||
export function listProspects(db, projectId, f, { limit = 100 } = {}) {
|
||||
export async function listProspects(db, projectId, f, { limit = 100 } = {}) {
|
||||
const { sql, args, order } = filterWhere(projectId, f);
|
||||
const total = db.prepare(`SELECT COUNT(*) n FROM prospects WHERE ${sql}`).get(...args).n;
|
||||
const total = (await db.prepare(`SELECT COUNT(*) n FROM prospects WHERE ${sql}`).get(...args)).n;
|
||||
const pages = Math.max(1, Math.ceil(total / limit));
|
||||
const page = Math.min(f.page, pages);
|
||||
const rows = db.prepare(`SELECT id, company, email, website, city, sector, score, status, sent_at, followup_at, replied_at,
|
||||
const rows = await db.prepare(`SELECT id, company, email, website, city, sector, score, status, sent_at, followup_at, replied_at,
|
||||
next_action, next_action_at
|
||||
FROM prospects WHERE ${sql} ORDER BY ${order} LIMIT ? OFFSET ?`).all(...args, limit, (page - 1) * limit);
|
||||
return { total, page, pages, rows };
|
||||
|
|
@ -58,32 +59,32 @@ export function listProspects(db, projectId, f, { limit = 100 } = {}) {
|
|||
// ---------- Fiche prospect ----------
|
||||
|
||||
/** Tout ce qu'on sait d'un prospect : infos, mails envoyés, réponse, notes. */
|
||||
export function prospectDetail(db, id) {
|
||||
const p = db.prepare('SELECT * FROM prospects WHERE id = ?').get(id);
|
||||
export async function prospectDetail(db, id) {
|
||||
const p = await db.prepare('SELECT * FROM prospects WHERE id = ?').get(id);
|
||||
if (!p) return null;
|
||||
const mails = db.prepare(`SELECT kind, subject, variant, sent_at, error FROM mail_log
|
||||
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 = db.prepare('SELECT id, body, created_at FROM prospect_notes WHERE prospect_id = ? ORDER BY created_at DESC, id DESC').all(id);
|
||||
const optOut = db.prepare('SELECT reason, created_at FROM blacklist WHERE email = ?').get(p.email) || null;
|
||||
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;
|
||||
return { prospect: p, mails, notes, optOut };
|
||||
}
|
||||
|
||||
export function addNote(db, prospectId, body) {
|
||||
export async function addNote(db, prospectId, body) {
|
||||
const text = String(body || '').trim().slice(0, 2000);
|
||||
if (!text) return null;
|
||||
return Number(db.prepare('INSERT INTO prospect_notes(prospect_id, body, created_at) VALUES(?, ?, ?)').run(prospectId, text, now()).lastInsertRowid);
|
||||
return Number((await db.prepare('INSERT INTO prospect_notes(prospect_id, body, created_at) VALUES(?, ?, ?)').run(prospectId, text, now())).lastInsertRowid);
|
||||
}
|
||||
|
||||
export function deleteNote(db, prospectId, noteId) {
|
||||
return db.prepare('DELETE FROM prospect_notes WHERE id = ? AND prospect_id = ?').run(noteId, prospectId).changes > 0;
|
||||
export async function deleteNote(db, prospectId, noteId) {
|
||||
return (await db.prepare('DELETE FROM prospect_notes WHERE id = ? AND prospect_id = ?').run(noteId, prospectId)).changes > 0;
|
||||
}
|
||||
|
||||
/** Prochaine action : texte + jour (AAAA-MM-JJ, rappel à 9h heure de Paris). Vide = effacer. */
|
||||
export function setNextAction(db, prospectId, action, day) {
|
||||
export async function setNextAction(db, prospectId, action, day) {
|
||||
const text = String(action || '').trim().slice(0, 200);
|
||||
const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(String(day || ''));
|
||||
if (!text) {
|
||||
db.prepare('UPDATE prospects SET next_action = NULL, next_action_at = NULL WHERE id = ?').run(prospectId);
|
||||
await db.prepare('UPDATE prospects SET next_action = NULL, next_action_at = NULL WHERE id = ?').run(prospectId);
|
||||
return null;
|
||||
}
|
||||
if (!m) throw new Error('Date attendue au format AAAA-MM-JJ');
|
||||
|
|
@ -91,6 +92,6 @@ export function setNextAction(db, prospectId, action, day) {
|
|||
// 2026-02-31 deviendrait le 3 mars sans prévenir : on refuse
|
||||
if (parisParts(date).day !== +m[3]) throw new Error('Date invalide');
|
||||
const at = Math.floor(date.getTime() / 1000);
|
||||
db.prepare('UPDATE prospects SET next_action = ?, next_action_at = ? WHERE id = ?').run(text, at, prospectId);
|
||||
await db.prepare('UPDATE prospects SET next_action = ?, next_action_at = ? WHERE id = ?').run(text, at, prospectId);
|
||||
return at;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -21,9 +21,9 @@ export function toCsv(header, rows) {
|
|||
|
||||
const day = (ts) => (ts ? new Date(ts * 1000).toLocaleString('sv-SE', { timeZone: 'Europe/Paris' }).slice(0, 16) : '');
|
||||
|
||||
export function exportProspects(db, projectId, filters) {
|
||||
export async function exportProspects(db, projectId, filters) {
|
||||
const { sql, args, order } = filterWhere(projectId, filters);
|
||||
const rows = db.prepare(`SELECT * FROM prospects WHERE ${sql} ORDER BY ${order} LIMIT 10000`).all(...args);
|
||||
const rows = await db.prepare(`SELECT * FROM prospects WHERE ${sql} ORDER BY ${order} LIMIT 10000`).all(...args);
|
||||
const header = ['Entreprise', 'Email', 'Site', 'Ville', 'Secteur', 'Score', 'Statut', 'Ajouté le', 'Contacté le', 'Objet',
|
||||
'Relancé le', 'Répondu le', 'Prochaine action', 'Échéance', 'Source', 'Accroche'];
|
||||
return toCsv(header, rows.map((p) => [
|
||||
|
|
@ -75,7 +75,7 @@ const MAX_ROWS = 2000;
|
|||
// Notre propre export préfixe les formules par ' : on l'enlève à la relecture
|
||||
const unformula = (s) => (/^'[=+\-@]/.test(s) ? s.slice(1) : s);
|
||||
|
||||
export function importProspects(db, projectId, text, { at = now() } = {}) {
|
||||
export async function importProspects(db, projectId, text, { at = now() } = {}) {
|
||||
const rows = parseCsv(text);
|
||||
if (rows.length < 2) throw new Error('Fichier vide ou sans en-tête');
|
||||
const header = rows[0].map(norm);
|
||||
|
|
@ -89,36 +89,32 @@ export function importProspects(db, projectId, text, { at = now() } = {}) {
|
|||
if (data.length > MAX_ROWS) throw new Error(`Maximum ${MAX_ROWS} lignes par import (${data.length} dans le fichier)`);
|
||||
|
||||
const dateLabel = new Date(at * 1000).toLocaleDateString('fr-FR', { timeZone: 'Europe/Paris' });
|
||||
const exists = db.prepare('SELECT 1 FROM prospects WHERE project_id = ? AND email = ?');
|
||||
const optOut = db.prepare('SELECT 1 FROM blacklist WHERE email = ?');
|
||||
const insert = db.prepare(`INSERT INTO prospects(project_id, company, email, website, city, sector, score, source, hook, created_at)
|
||||
VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);
|
||||
const res = { total: data.length, imported: 0, duplicates: 0, blacklisted: 0, invalid: [] };
|
||||
const seen = new Set();
|
||||
const get = (r, k, max = 200) => (col[k] === undefined ? '' : unformula(String(r[col[k]] ?? '').trim()).slice(0, max));
|
||||
|
||||
db.exec('BEGIN');
|
||||
try {
|
||||
data.forEach((r, i) => {
|
||||
// Tout ou rien : une ligne qui plante annule l'import entier
|
||||
await db.transaction(async (tx) => {
|
||||
const exists = tx.prepare('SELECT 1 FROM prospects WHERE project_id = ? AND email = ?');
|
||||
const optOut = tx.prepare('SELECT 1 FROM blacklist WHERE email = ?');
|
||||
const insert = tx.prepare(`INSERT INTO prospects(project_id, company, email, website, city, sector, score, source, hook, created_at)
|
||||
VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);
|
||||
for (const [i, r] of data.entries()) {
|
||||
const line = i + 2;
|
||||
const email = get(r, 'email').toLowerCase();
|
||||
if (!EMAIL_RE.test(email)) { if (res.invalid.length < 50) res.invalid.push({ line, reason: `email invalide : "${email || 'vide'}"` }); return; }
|
||||
if (seen.has(email) || exists.get(projectId, email)) { res.duplicates++; return; }
|
||||
if (!EMAIL_RE.test(email)) { if (res.invalid.length < 50) res.invalid.push({ line, reason: `email invalide : "${email || 'vide'}"` }); continue; }
|
||||
if (seen.has(email) || await exists.get(projectId, email)) { res.duplicates++; continue; }
|
||||
seen.add(email);
|
||||
if (optOut.get(email)) { res.blacklisted++; return; }
|
||||
if (await optOut.get(email)) { res.blacklisted++; continue; }
|
||||
const s = Number(get(r, 'score'));
|
||||
insert.run(
|
||||
await insert.run(
|
||||
projectId, get(r, 'company') || email.split('@')[1], email, httpUrl(get(r, 'website', 300)), get(r, 'city', 100) || null,
|
||||
get(r, 'sector', 100) || null, Number.isFinite(s) && s > 0 ? Math.max(1, Math.min(10, Math.round(s))) : null,
|
||||
// RGPD : on garde toujours l'origine de la donnée
|
||||
httpUrl(get(r, 'source', 300)) || get(r, 'source', 300) || `Import CSV du ${dateLabel}`, get(r, 'hook', 400) || null, at,
|
||||
);
|
||||
res.imported++;
|
||||
});
|
||||
db.exec('COMMIT');
|
||||
} catch (e) {
|
||||
db.exec('ROLLBACK');
|
||||
throw e;
|
||||
}
|
||||
});
|
||||
return res;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -17,16 +17,16 @@ export function isBusinessHours(date = new Date(), timeZone = 'Europe/Paris') {
|
|||
const CANDIDATES_SQL = `FROM prospects WHERE project_id = ? AND status = 'sent' AND followup_at IS NULL
|
||||
AND sent_at <= ? AND email NOT IN (SELECT email FROM blacklist)`;
|
||||
|
||||
export function followupCandidates(db, project, { at = now(), limit = 100 } = {}) {
|
||||
export async function followupCandidates(db, project, { at = now(), limit = 100 } = {}) {
|
||||
const cutoff = at - project.followupDays * 86400;
|
||||
return db.prepare(`SELECT * ${CANDIDATES_SQL} ORDER BY sent_at, id LIMIT ?`).all(project.id, cutoff, limit);
|
||||
}
|
||||
|
||||
/** @returns {{due: number, blockers: string[], inHours: boolean, ready: boolean}} */
|
||||
export function followupPlan(db, project, { at = now(), date = new Date(at * 1000) } = {}) {
|
||||
export async function followupPlan(db, project, { at = now(), date = new Date(at * 1000) } = {}) {
|
||||
const blockers = [];
|
||||
if (!project.followupEnabled) blockers.push('relance désactivée');
|
||||
if (!getTemplate(db, project.id, 'followup', { validatedOnly: true })) blockers.push('modèle de relance à valider');
|
||||
if (!(await getTemplate(db, project.id, 'followup', { validatedOnly: true }))) blockers.push('modèle de relance à valider');
|
||||
if (!project.hasSmtp) blockers.push('SMTP à configurer');
|
||||
// Sans lecture de la boîte, on relancerait des gens qui ont déjà répondu
|
||||
const inbox = project.inbox || {};
|
||||
|
|
@ -34,7 +34,7 @@ export function followupPlan(db, project, { at = now(), date = new Date(at * 100
|
|||
else if (inbox.lastError || !inbox.lastOk || at - inbox.lastOk > INBOX_MAX_AGE) blockers.push('boîte non vérifiée récemment');
|
||||
|
||||
const cutoff = at - project.followupDays * 86400;
|
||||
const due = db.prepare(`SELECT COUNT(*) n ${CANDIDATES_SQL}`).get(project.id, cutoff).n;
|
||||
const due = (await db.prepare(`SELECT COUNT(*) n ${CANDIDATES_SQL}`).get(project.id, cutoff)).n;
|
||||
const inHours = isBusinessHours(date);
|
||||
return { due, blockers, inHours, ready: !blockers.length && inHours && due > 0 };
|
||||
}
|
||||
|
|
|
|||
|
|
@ -48,7 +48,7 @@ export function classify(msg) {
|
|||
}
|
||||
|
||||
/** Applique une liste de messages aux prospects du projet. Idempotent. */
|
||||
export function applyMessages(db, projectId, messages, { at = now() } = {}) {
|
||||
export async function applyMessages(db, projectId, messages, { at = now() } = {}) {
|
||||
const res = { replies: 0, bounces: 0, ignored: 0 };
|
||||
const byMsgId = db.prepare('SELECT prospect_id FROM mail_log WHERE project_id = ? AND message_id = ? AND prospect_id IS NOT NULL LIMIT 1');
|
||||
const byEmail = db.prepare('SELECT id FROM prospects WHERE project_id = ? AND email = ? LIMIT 1');
|
||||
|
|
@ -57,30 +57,30 @@ export function applyMessages(db, projectId, messages, { at = now() } = {}) {
|
|||
const markBounce = db.prepare("UPDATE prospects SET status = 'bounced' WHERE id = ? AND status = 'sent'");
|
||||
const blacklist = db.prepare("INSERT OR IGNORE INTO blacklist(email, reason, created_at) SELECT email, 'bounce', ? FROM prospects WHERE id = ?");
|
||||
|
||||
const fromIds = (list) => {
|
||||
for (const id of list) { const r = byMsgId.get(projectId, id); if (r) return r.prospect_id; }
|
||||
const fromIds = async (list) => {
|
||||
for (const id of list) { const r = await byMsgId.get(projectId, id); if (r) return r.prospect_id; }
|
||||
return null;
|
||||
};
|
||||
|
||||
for (const msg of messages) {
|
||||
const c = classify(msg);
|
||||
if (c.type === 'bounce') {
|
||||
const pid = fromIds(c.ids);
|
||||
if (pid && markBounce.run(pid).changes) { blacklist.run(at, pid); res.bounces++; } else res.ignored++;
|
||||
const pid = await fromIds(c.ids);
|
||||
if (pid && (await markBounce.run(pid)).changes) { await blacklist.run(at, pid); res.bounces++; } else res.ignored++;
|
||||
continue;
|
||||
}
|
||||
if (c.type === 'auto') { res.ignored++; continue; }
|
||||
|
||||
// Réponse : 1) fil de discussion, 2) même adresse, 3) même domaine pro (un seul prospect en attente dessus)
|
||||
let pid = fromIds(c.ids) ?? byEmail.get(projectId, c.from)?.id ?? null;
|
||||
let pid = (await fromIds(c.ids)) ?? (await byEmail.get(projectId, c.from))?.id ?? null;
|
||||
if (!pid) {
|
||||
const domain = c.from.split('@')[1];
|
||||
if (domain && !GENERIC_DOMAINS.has(domain)) {
|
||||
const rows = byDomain.all(projectId, domain);
|
||||
const rows = await byDomain.all(projectId, domain);
|
||||
if (rows.length === 1) pid = rows[0].id;
|
||||
}
|
||||
}
|
||||
if (pid && markReply.run(at, String(msg.subject || '').slice(0, 300), pid).changes) res.replies++;
|
||||
if (pid && (await markReply.run(at, String(msg.subject || '').slice(0, 300), pid)).changes) res.replies++;
|
||||
else res.ignored++;
|
||||
}
|
||||
return res;
|
||||
|
|
@ -145,22 +145,22 @@ 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) {
|
||||
const { db } = app;
|
||||
const project = getProject(app, projectId, { secrets: true });
|
||||
const project = await getProject(app, projectId, { secrets: true });
|
||||
if (!project.imap) throw new Error('Boîte IMAP non configurée');
|
||||
const state = project.inbox || {};
|
||||
const firstSent = db.prepare('SELECT MIN(sent_at) t FROM mail_log WHERE project_id = ?').get(project.id).t;
|
||||
const firstSent = (await db.prepare('SELECT MIN(sent_at) t FROM mail_log WHERE project_id = ?').get(project.id)).t;
|
||||
const since = new Date(((firstSent || now()) - 86400) * 1000);
|
||||
const at = now();
|
||||
const save = (s) => db.prepare('UPDATE projects SET inbox_json = ? WHERE id = ?').run(JSON.stringify(s), project.id);
|
||||
try {
|
||||
const r = await (app.fetchInbox || fetchInbox)(project.imap, state, { since });
|
||||
const res = applyMessages(db, project.id, r.messages, { at });
|
||||
save({
|
||||
const res = await applyMessages(db, project.id, r.messages, { at });
|
||||
await save({
|
||||
uidValidity: r.uidValidity, lastUid: r.lastUid, lastCheck: at, lastOk: at, lastError: null,
|
||||
replies: (state.replies || 0) + res.replies, bounces: (state.bounces || 0) + res.bounces,
|
||||
});
|
||||
if (res.replies) {
|
||||
const who = db.prepare('SELECT company, email, reply_subject FROM prospects WHERE project_id = ? AND replied_at = ? LIMIT 10').all(project.id, at);
|
||||
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', {
|
||||
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'),
|
||||
|
|
@ -169,7 +169,7 @@ export async function checkInbox(app, projectId) {
|
|||
return res;
|
||||
} catch (e) {
|
||||
const msg = String(e.responseText || e.message || e).slice(0, 300);
|
||||
save({ ...state, lastCheck: at, lastError: msg });
|
||||
await save({ ...state, lastCheck: at, lastError: msg });
|
||||
throw new Error(`IMAP : ${msg}`);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,30 +1,31 @@
|
|||
// File de jobs dans SQLite, UN seul worker : un seul `claude` à la fois sur le Pi.
|
||||
// File de jobs en base, UN seul worker : un seul `claude` à la fois.
|
||||
import { now } from '../db.js';
|
||||
import { waitCool } from './thermal.js';
|
||||
|
||||
export function enqueue(db, { projectId, type, params = {}, runAfter = null }) {
|
||||
const running = db.prepare(
|
||||
"SELECT id FROM jobs WHERE project_id IS ? AND type = ? AND status IN ('queued','running')"
|
||||
).get(projectId ?? null, type);
|
||||
export async function enqueue(db, { projectId, type, params = {}, runAfter = null }) {
|
||||
// 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 project_id = ? AND type = ? AND status IN ('queued','running')").get(projectId, type);
|
||||
if (running) return { id: running.id, existing: true };
|
||||
const r = db.prepare('INSERT INTO jobs(project_id, type, params_json, created_at, run_after) VALUES(?, ?, ?, ?, ?)')
|
||||
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);
|
||||
return { id: Number(r.lastInsertRowid), existing: false };
|
||||
}
|
||||
|
||||
export function setProgress(db, jobId, progress) {
|
||||
db.prepare('UPDATE jobs SET progress_json = ? WHERE id = ?').run(JSON.stringify(progress), jobId);
|
||||
export async function setProgress(db, jobId, progress) {
|
||||
await db.prepare('UPDATE jobs SET progress_json = ? WHERE id = ?').run(JSON.stringify(progress), jobId);
|
||||
}
|
||||
|
||||
export function cancelJob(db, jobId) {
|
||||
db.prepare("UPDATE jobs SET status = 'cancelled', finished_at = ? WHERE id = ? AND status IN ('queued','running')")
|
||||
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);
|
||||
}
|
||||
|
||||
export function latestJobs(db, projectId) {
|
||||
const rows = db.prepare(`
|
||||
export async function latestJobs(db, projectId) {
|
||||
const rows = await db.prepare(`
|
||||
SELECT j.* FROM jobs j
|
||||
JOIN (SELECT type, MAX(id) id FROM jobs WHERE project_id = ? GROUP BY type) last ON last.id = j.id
|
||||
JOIN (SELECT type, MAX(id) id FROM jobs WHERE project_id = ? GROUP BY type) lj ON lj.id = j.id
|
||||
`).all(projectId);
|
||||
const out = {};
|
||||
for (const r of rows) {
|
||||
|
|
@ -44,11 +45,11 @@ export class Worker {
|
|||
budget, isAiJob, onBudget, quota, isQuotaSensitive, onQuotaHold,
|
||||
} = {}) {
|
||||
this.clock = clock;
|
||||
this.budget = budget; // () => {blocked, reason}
|
||||
this.budget = budget; // async () => {blocked, reason}
|
||||
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; // () => {blocked, reason} : quota du compte Claude lui-même (session/semaine)
|
||||
this.quota = quota; // async () => {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;
|
||||
|
|
@ -61,35 +62,59 @@ export class Worker {
|
|||
this.log = log;
|
||||
this.current = null;
|
||||
this.stopped = false;
|
||||
this.pending = new Set(); // callbacks de notification en vol (attendus à l'arrêt)
|
||||
this.loopDone = null;
|
||||
this.wake = null;
|
||||
}
|
||||
|
||||
start() {
|
||||
async start() {
|
||||
// Un job "running" au démarrage = crash/reboot pendant l'exécution
|
||||
this.db.prepare("UPDATE jobs SET status = 'error', error = 'Interrompu (redémarrage)', finished_at = ? WHERE status = 'running'").run(now());
|
||||
this.loop();
|
||||
await this.db.prepare("UPDATE jobs SET status = 'error', error = 'Interrompu (redémarrage)', finished_at = ? WHERE status = 'running'").run(now());
|
||||
this.loopDone = this.loop();
|
||||
}
|
||||
|
||||
stop() { this.stopped = true; this.current?.abort(); }
|
||||
/** Arrête la boucle et attend le job en cours ainsi que les notifications en vol. */
|
||||
async stop() {
|
||||
this.stopped = true;
|
||||
this.current?.abort();
|
||||
this.wake?.();
|
||||
await this.loopDone;
|
||||
await this.idle();
|
||||
}
|
||||
|
||||
// Les callbacks ne doivent jamais bloquer ni faire tomber le worker
|
||||
/** Attend les callbacks (notifications) lancés par emit(). */
|
||||
async idle() {
|
||||
while (this.pending.size) await Promise.allSettled([...this.pending]);
|
||||
}
|
||||
|
||||
// Les callbacks ne doivent jamais bloquer ni faire tomber le worker : lancés sans attendre,
|
||||
// mais suivis (idle/stop les attendent) et leurs erreurs journalisées.
|
||||
emit(name, ...args) {
|
||||
try { Promise.resolve(this[name]?.(...args)).catch((e) => this.log.error(`[${name}]`, e.message)); }
|
||||
catch (e) { this.log.error(`[${name}]`, e.message); }
|
||||
let p;
|
||||
try { p = Promise.resolve(this[name]?.(...args)); }
|
||||
catch (e) { this.log.error(`[${name}]`, e.message); return; }
|
||||
const tracked = p.catch((e) => this.log.error(`[${name}]`, e.message)).finally(() => this.pending.delete(tracked));
|
||||
this.pending.add(tracked);
|
||||
}
|
||||
|
||||
isCancelled(jobId) {
|
||||
return this.db.prepare('SELECT status FROM jobs WHERE id = ?').get(jobId)?.status === 'cancelled';
|
||||
async isCancelled(jobId) {
|
||||
return (await this.db.prepare('SELECT status FROM jobs WHERE id = ?').get(jobId))?.status === 'cancelled';
|
||||
}
|
||||
|
||||
async loop() {
|
||||
while (!this.stopped) {
|
||||
const ran = await this.tick();
|
||||
if (!ran) await new Promise((r) => setTimeout(r, this.pollMs));
|
||||
let ran = false;
|
||||
try { ran = await this.tick(); }
|
||||
catch (e) { this.log.error('[worker]', e.message); } // base indisponible : on réessaie au prochain passage
|
||||
if (!ran && !this.stopped) {
|
||||
await new Promise((r) => { this.wake = r; setTimeout(r, this.pollMs).unref(); });
|
||||
this.wake = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async tick() {
|
||||
const due = this.db.prepare(`SELECT * FROM jobs WHERE status = 'queued'
|
||||
const due = await this.db.prepare(`SELECT * FROM jobs WHERE status = 'queued'
|
||||
AND (run_after IS NULL OR run_after <= ?) ORDER BY id`).all(this.clock());
|
||||
if (!due.length) return false;
|
||||
|
||||
|
|
@ -97,17 +122,17 @@ export class Worker {
|
|||
// (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 = this.budget?.() || { blocked: false };
|
||||
const quota = this.quota?.() || { blocked: false };
|
||||
const hold = (j, reason) => {
|
||||
const budget = (await this.budget?.()) || { blocked: false };
|
||||
const quota = (await this.quota?.()) || { blocked: false };
|
||||
const hold = async (j, reason) => {
|
||||
const msg = JSON.stringify({ message: `En attente : ${reason}` });
|
||||
if (j.progress_json !== msg) this.db.prepare('UPDATE jobs SET progress_json = ? WHERE id = ?').run(msg, j.id);
|
||||
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;
|
||||
for (const j of due) {
|
||||
if (budget.blocked && this.isAiJob?.(j.type)) { waiting = true; hold(j, budget.reason); continue; }
|
||||
if (quota.blocked && this.isQuotaSensitive?.(j.type)) { quotaWaiting = true; hold(j, quota.reason); continue; }
|
||||
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; }
|
||||
job = j;
|
||||
break;
|
||||
}
|
||||
|
|
@ -118,19 +143,19 @@ export class Worker {
|
|||
if (!job) return false;
|
||||
const handler = this.handlers[job.type];
|
||||
if (!handler) {
|
||||
this.db.prepare("UPDATE jobs SET status='error', error=?, finished_at=? WHERE id=?").run(`Type inconnu : ${job.type}`, now(), job.id);
|
||||
await this.db.prepare("UPDATE jobs SET status='error', error=?, finished_at=? WHERE id=?").run(`Type inconnu : ${job.type}`, now(), job.id);
|
||||
return true;
|
||||
}
|
||||
|
||||
let warned = false;
|
||||
await waitCool(this.thermalMax, {
|
||||
onWait: (t) => {
|
||||
setProgress(this.db, job.id, { message: `Pause thermique (${t} °C)` });
|
||||
onWait: async (t) => {
|
||||
await setProgress(this.db, job.id, { message: `Pause thermique (${t} °C)` });
|
||||
if (!warned) { warned = true; this.emit('onThermal', t); }
|
||||
},
|
||||
});
|
||||
|
||||
this.db.prepare("UPDATE jobs SET status='running', started_at=? WHERE id=? AND status='queued'").run(now(), job.id);
|
||||
await this.db.prepare("UPDATE jobs SET status='running', started_at=? WHERE id=? AND status='queued'").run(now(), job.id);
|
||||
const ctrl = new AbortController();
|
||||
this.current = ctrl;
|
||||
const ctx = {
|
||||
|
|
@ -141,20 +166,22 @@ export class Worker {
|
|||
cancelled: () => this.isCancelled(job.id),
|
||||
usage: { costUsd: 0, tokensIn: 0, tokensOut: 0 },
|
||||
};
|
||||
// Annulation depuis l'UI : on surveille la BDD
|
||||
const watch = setInterval(() => { if (this.isCancelled(job.id)) ctrl.abort(); }, 2000);
|
||||
// Annulation depuis l'UI : on surveille la BDD (une erreur ici ne doit jamais faire tomber le process)
|
||||
const watch = setInterval(() => {
|
||||
this.isCancelled(job.id).then((c) => { if (c) ctrl.abort(); }, () => {});
|
||||
}, 2000);
|
||||
|
||||
try {
|
||||
const result = await handler(ctx);
|
||||
if (!this.isCancelled(job.id)) {
|
||||
this.db.prepare("UPDATE jobs SET status='done', result_json=?, finished_at=?, cost_usd=?, tokens_in=?, tokens_out=? WHERE id=?")
|
||||
if (!(await this.isCancelled(job.id))) {
|
||||
await this.db.prepare("UPDATE jobs SET status='done', result_json=?, finished_at=?, cost_usd=?, tokens_in=?, tokens_out=? WHERE id=?")
|
||||
.run(JSON.stringify(result ?? null), now(), ctx.usage.costUsd, ctx.usage.tokensIn, ctx.usage.tokensOut, job.id);
|
||||
this.emit('onFinish', job, { status: 'done', result });
|
||||
}
|
||||
} catch (e) {
|
||||
this.log.error(`[job ${job.id} ${job.type}]`, e.message);
|
||||
if (!this.isCancelled(job.id)) {
|
||||
this.db.prepare("UPDATE jobs SET status='error', error=?, finished_at=?, cost_usd=?, tokens_in=?, tokens_out=? WHERE id=?")
|
||||
if (!(await this.isCancelled(job.id))) {
|
||||
await this.db.prepare("UPDATE jobs SET status='error', error=?, finished_at=?, cost_usd=?, tokens_in=?, tokens_out=? WHERE id=?")
|
||||
.run(String(e.message).slice(0, 2000), now(), ctx.usage.costUsd, ctx.usage.tokensIn, ctx.usage.tokensOut, job.id);
|
||||
this.emit('onFinish', job, { status: 'error', error: e.message });
|
||||
}
|
||||
|
|
@ -174,10 +201,10 @@ export function addUsage(ctx, r) {
|
|||
}
|
||||
|
||||
// Conso des 30 derniers jours, pour la jauge (comptée à la fin du job, comme le budget)
|
||||
export function usageSummary(db) {
|
||||
export async function usageSummary(db) {
|
||||
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);
|
||||
return { month: q(since), day: q(day) };
|
||||
return { month: await q(since), day: await q(day) };
|
||||
}
|
||||
|
|
|
|||
|
|
@ -9,8 +9,8 @@ const pad = (n) => String(n).padStart(2, '0');
|
|||
export const parisDay = (date = new Date()) => { const p = parisParts(date); return `${p.year}-${pad(p.month)}-${pad(p.day)}`; };
|
||||
const num = (v) => (typeof v === 'number' && Number.isFinite(v) ? v : null);
|
||||
|
||||
export function saveSnapshot(db, projectId, business, { date = new Date() } = {}) {
|
||||
db.prepare(`INSERT INTO metrics_daily(project_id, day, users, clients, revenue) VALUES(?, ?, ?, ?, ?)
|
||||
export async function saveSnapshot(db, projectId, business, { date = new Date() } = {}) {
|
||||
await db.prepare(`INSERT INTO metrics_daily(project_id, day, users, clients, revenue) VALUES(?, ?, ?, ?, ?)
|
||||
ON CONFLICT(project_id, day) DO UPDATE SET users = excluded.users, clients = excluded.clients, revenue = excluded.revenue`)
|
||||
.run(projectId, parisDay(date), num(business.users), num(business.clients), num(business.revenue));
|
||||
}
|
||||
|
|
@ -18,13 +18,13 @@ export 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 = app.db.prepare(`SELECT id FROM projects WHERE db_enc IS NOT NULL
|
||||
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);
|
||||
let n = 0;
|
||||
for (const { id } of todo) {
|
||||
try {
|
||||
const p = getProject(app, id, { secrets: true });
|
||||
saveSnapshot(app.db, id, await (app.fetchRecap || fetchRecap)(id, p.dbCfg, { force: true }), { date });
|
||||
const p = await getProject(app, id, { 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); }
|
||||
}
|
||||
|
|
@ -40,9 +40,9 @@ function weekStart(date) {
|
|||
}
|
||||
|
||||
/** Séries pour les graphiques : jours (KPI business) et semaines (envois / réponses). */
|
||||
export function history(db, projectId, { days = 30, at = now() } = {}) {
|
||||
export async function history(db, projectId, { days = 30, at = now() } = {}) {
|
||||
const fromDay = parisDay(new Date((at - (days - 1) * 86400) * 1000));
|
||||
const daily = db.prepare('SELECT day, users, clients, revenue FROM metrics_daily WHERE project_id = ? AND day >= ? ORDER BY day')
|
||||
const daily = await db.prepare('SELECT day, users, clients, revenue FROM metrics_daily WHERE project_id = ? AND day >= ? ORDER BY day')
|
||||
.all(projectId, fromDay);
|
||||
|
||||
const nWeeks = Math.ceil(days / 7);
|
||||
|
|
@ -55,10 +55,10 @@ export function history(db, projectId, { days = 30, at = now() } = {}) {
|
|||
const first = weeks[0].start.split('-').map(Number);
|
||||
const since = Math.floor(parisTime(first[0], first[1], first[2], 0).getTime() / 1000);
|
||||
const bucket = (ts) => weeks.find((w) => w.start === weekStart(new Date(ts * 1000)));
|
||||
for (const r of db.prepare("SELECT sent_at FROM mail_log WHERE project_id = ? AND kind = 'initial' AND error IS NULL AND sent_at >= ?").all(projectId, since)) {
|
||||
for (const r of await db.prepare("SELECT sent_at FROM mail_log WHERE project_id = ? AND kind = 'initial' AND error IS NULL AND sent_at >= ?").all(projectId, since)) {
|
||||
const w = bucket(r.sent_at); if (w) w.sent++;
|
||||
}
|
||||
for (const r of db.prepare('SELECT replied_at FROM prospects WHERE project_id = ? AND replied_at >= ?').all(projectId, since)) {
|
||||
for (const r of await db.prepare('SELECT replied_at FROM prospects WHERE project_id = ? AND replied_at >= ?').all(projectId, since)) {
|
||||
const w = bucket(r.replied_at); if (w) w.replies++;
|
||||
}
|
||||
return { daily, weeks };
|
||||
|
|
|
|||
|
|
@ -31,18 +31,18 @@ export function bar(done, total, width = 12) {
|
|||
return `${'▰'.repeat(full)}${'▱'.repeat(width - full)} ${Math.round(r * 100)} %`;
|
||||
}
|
||||
|
||||
export function notifyConfig(app) {
|
||||
export async function notifyConfig(app) {
|
||||
let url = null;
|
||||
try { url = decrypt(app.cfg.secretKey, getSetting(app.db, 'discord_webhook_enc')); }
|
||||
try { url = decrypt(app.cfg.secretKey, await getSetting(app.db, 'discord_webhook_enc')); }
|
||||
catch { url = null; }
|
||||
const raw = getSetting(app.db, 'discord_events');
|
||||
const raw = await getSetting(app.db, '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 } = notifyConfig(app);
|
||||
const { url, events } = await notifyConfig(app);
|
||||
if (!url || (!force && !events.includes(event))) return false;
|
||||
const body = {
|
||||
username: 'AiTools',
|
||||
|
|
@ -109,36 +109,36 @@ const DONE = {
|
|||
const LABEL = { analyze: 'Analyse', prospect: 'Recherche', template: 'Modèle de mail', followup_template: 'Modèle de relance', send: 'Envoi', followup: 'Relances', evolution: 'Évolutions' };
|
||||
|
||||
// Durée et coût réels, relus en base une fois le job clos (absents dans les tests unitaires)
|
||||
function jobMeta(app, job) {
|
||||
async function jobMeta(app, job) {
|
||||
if (!job.id) return [];
|
||||
const row = 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 = ?').get(job.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)} $` });
|
||||
return out;
|
||||
}
|
||||
|
||||
export function notifyJob(app, job, { status, result, error }) {
|
||||
const project = job.project_id ? app.db.prepare('SELECT name FROM projects WHERE id = ?').get(job.project_id)?.name : null;
|
||||
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 prefix = project ? `${project} · ` : '';
|
||||
const footer = project ? `${project} · ${LABEL[job.type] || job.type}` : undefined;
|
||||
if (status === 'error') {
|
||||
return notify(app, '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: jobMeta(app, job),
|
||||
fields: await jobMeta(app, job),
|
||||
});
|
||||
}
|
||||
if (status !== 'done') return Promise.resolve(false);
|
||||
if (status !== 'done') return false;
|
||||
if (job.type === 'followup') {
|
||||
if (!result?.sent) return Promise.resolve(false);
|
||||
if (!result?.sent) return false;
|
||||
return notify(app, '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)}`,
|
||||
});
|
||||
}
|
||||
const make = DONE[job.type];
|
||||
if (!make) return Promise.resolve(false);
|
||||
if (!make) return false;
|
||||
const n = make(result);
|
||||
return notify(app, 'job_done', { ...n, title: `${prefix}${n.title}`, footer, fields: [...(n.fields || []), ...jobMeta(app, job)] });
|
||||
return notify(app, 'job_done', { ...n, title: `${prefix}${n.title}`, footer, fields: [...(n.fields || []), ...(await jobMeta(app, job))] });
|
||||
}
|
||||
|
|
|
|||
|
|
@ -10,26 +10,27 @@ 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 function weeklyStats(db, { at = now() } = {}) {
|
||||
export async function weeklyStats(db, { at = now() } = {}) {
|
||||
const from = at - 7 * 86400;
|
||||
const one = (sql, ...a) => db.prepare(sql).get(...a).n;
|
||||
const projects = db.prepare('SELECT id, name FROM projects ORDER BY name COLLATE NOCASE').all().map((p) => {
|
||||
const sent = 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 = abStats(db, p.id);
|
||||
return {
|
||||
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()) {
|
||||
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({
|
||||
name: p.name,
|
||||
found: one('SELECT COUNT(*) n FROM prospects WHERE project_id = ? AND created_at > ?', p.id, from),
|
||||
found: await one('SELECT COUNT(*) n FROM prospects WHERE project_id = ? AND created_at > ?', p.id, from),
|
||||
sent,
|
||||
followups: one("SELECT COUNT(*) n FROM mail_log WHERE project_id = ? AND kind = 'followup' AND error IS NULL AND sent_at > ?", p.id, from),
|
||||
replies: one('SELECT COUNT(*) n FROM prospects WHERE project_id = ? AND replied_at > ?', p.id, from),
|
||||
clients: one("SELECT COUNT(*) n FROM prospects WHERE project_id = ? AND status = 'client'", p.id),
|
||||
bounces: one(`SELECT COUNT(*) n FROM blacklist b JOIN prospects x ON x.email = b.email
|
||||
followups: await one("SELECT COUNT(*) n FROM mail_log WHERE project_id = ? AND kind = 'followup' AND error IS NULL AND sent_at > ?", p.id, from),
|
||||
replies: await one('SELECT COUNT(*) n FROM prospects WHERE project_id = ? AND replied_at > ?', p.id, from),
|
||||
clients: await one("SELECT COUNT(*) n FROM prospects WHERE project_id = ? AND status = 'client'", p.id),
|
||||
bounces: await one(`SELECT COUNT(*) n FROM blacklist b JOIN prospects x ON x.email = b.email
|
||||
WHERE x.project_id = ? AND b.reason = 'bounce' AND b.created_at > ?`, p.id, from),
|
||||
cost: db.prepare('SELECT COALESCE(SUM(cost_usd), 0) c FROM jobs WHERE project_id = ? AND COALESCE(finished_at, created_at) > ?').get(p.id, from).c,
|
||||
cost: (await db.prepare('SELECT COALESCE(SUM(cost_usd), 0) c FROM jobs WHERE project_id = ? AND COALESCE(finished_at, created_at) > ?').get(p.id, from)).c,
|
||||
bestSubject: ab.length > 1 && ab.every((v) => v.sent >= 10) ? [...ab].sort((a, b) => b.rate - a.rate)[0] : null,
|
||||
};
|
||||
});
|
||||
const cost = 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 COALESCE(finished_at, created_at) > ?').get(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,11 +56,11 @@ 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 = weeklyStats(app.db, { at });
|
||||
const st = await weeklyStats(app.db, { at });
|
||||
const text = weeklyText(st);
|
||||
const channels = [];
|
||||
const to = getSetting(app.db, 'notify_email');
|
||||
const smtp = globalSmtp(app);
|
||||
const to = await getSetting(app.db, 'notify_email');
|
||||
const smtp = await globalSmtp(app);
|
||||
if (to && smtp) {
|
||||
const transport = (app.createTransport || createTransport)(smtp);
|
||||
try {
|
||||
|
|
@ -93,14 +94,14 @@ 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 (getSetting(app.db, 'weekly_report', '0') !== '1') return null;
|
||||
if ((await getSetting(app.db, '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(getSetting(app.db, 'weekly_report_last', '0')) >= mondayAt8) return null;
|
||||
if (Number(await getSetting(app.db, 'weekly_report_last', '0')) >= mondayAt8) return null;
|
||||
const at = Math.floor(date.getTime() / 1000);
|
||||
const r = await sendWeeklyReport(app, { at });
|
||||
// Rien de configuré : on ne marque pas, il partira dès qu'un canal existera
|
||||
if (r.channels.length) setSetting(app.db, 'weekly_report_last', String(at));
|
||||
if (r.channels.length) await setSetting(app.db, 'weekly_report_last', String(at));
|
||||
return r;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -16,40 +16,50 @@ export class Scheduler {
|
|||
this.everyMs = everyMs;
|
||||
this.log = log;
|
||||
this.running = false;
|
||||
this.inflight = null;
|
||||
}
|
||||
|
||||
// Passage lancé par un minuteur : suivi (stop() l'attend) et jamais d'erreur non gérée
|
||||
run() {
|
||||
this.inflight = this.tick().catch((e) => this.log.error('[planificateur]', e.message));
|
||||
}
|
||||
|
||||
start() {
|
||||
this.timer = setInterval(() => this.tick(), this.everyMs);
|
||||
this.timer = setInterval(() => this.run(), this.everyMs);
|
||||
this.timer.unref();
|
||||
// Premier passage peu après le démarrage
|
||||
this.first = setTimeout(() => this.tick(), 60_000);
|
||||
this.first = setTimeout(() => this.run(), 60_000);
|
||||
this.first.unref();
|
||||
}
|
||||
|
||||
stop() { clearInterval(this.timer); clearTimeout(this.first); }
|
||||
async stop() {
|
||||
clearInterval(this.timer);
|
||||
clearTimeout(this.first);
|
||||
await this.inflight;
|
||||
}
|
||||
|
||||
async tick() {
|
||||
if (this.running) return;
|
||||
this.running = true;
|
||||
try {
|
||||
const projects = this.app.db.prepare('SELECT id FROM projects WHERE imap_enc IS NOT NULL').all();
|
||||
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); }
|
||||
catch (e) { this.log.error(`[inbox ${id}]`, e.message); }
|
||||
}
|
||||
this.queueFollowups();
|
||||
await this.queueFollowups();
|
||||
try { await maybeSendWeekly(this.app); }
|
||||
catch (e) { this.log.error('[rapport hebdo]', e.message); }
|
||||
await snapshotAll(this.app, { log: this.log });
|
||||
} finally { this.running = false; }
|
||||
}
|
||||
|
||||
queueFollowups(opts) {
|
||||
async queueFollowups(opts) {
|
||||
const { db } = this.app;
|
||||
const queued = [];
|
||||
for (const { id } of db.prepare('SELECT id FROM projects WHERE followup_enabled = 1').all()) {
|
||||
const plan = followupPlan(db, getProject(this.app, id), opts);
|
||||
if (plan.ready) queued.push({ id, ...enqueue(db, { projectId: id, type: 'followup', params: { count: plan.due } }) });
|
||||
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 } }) });
|
||||
}
|
||||
return queued;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -11,7 +11,7 @@ export async function waitCool(max, { read = cpuTemp, sleep = (ms) => new Promis
|
|||
let t = read();
|
||||
if (t === null || t < max) return;
|
||||
while (t !== null && t >= max - 5) {
|
||||
onWait?.(t);
|
||||
await onWait?.(t);
|
||||
await sleep(30_000);
|
||||
t = read();
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue