feat: jobs menu with progress, animated sections, styled evolutions, HTML mails

- Top bar jobs button opens a detailed list (project, step, % bar, cancel, open project)
- Jobs report real progress: found/target, sent/total, Claude turns for analyze/evolution
- Project actions become animated collapsible sections with Prospecter sub-sections
- Evolution result rendered server-side (escaped) as cards with effort badges
- HTML versions for evolution, weekly report and prospect mails (text kept)
- Richer Discord embeds: icons, progress bars, duration and AI cost, per-project weekly fields
- Mouse-reactive particle background and UI transitions (respects reduced motion)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Tony Averty 2026-10-21 23:54:02 +02:00
parent 896148cb25
commit e8c3221cb3
15 changed files with 964 additions and 89 deletions

View file

@ -59,14 +59,13 @@ details > summary { cursor: pointer; list-style: none; }
details > summary::-webkit-details-marker { display: none; }
details.new > summary { display: inline-block; }
.project > summary { display: flex; justify-content: space-between; align-items: center; gap: 12px; }
.project > summary::before { content: "▸"; color: var(--muted); transition: transform .15s; }
.project[open] > summary::before { transform: rotate(90deg); }
.pname { font-weight: 600; flex: 1; }
.project > summary::before { content: ""; width: 8px; height: 8px; border-right: 2px solid var(--muted); border-bottom: 2px solid var(--muted); transform: rotate(-45deg); transition: transform .25s cubic-bezier(.2,.8,.2,1); flex: none; }
.project[open] > summary::before { transform: rotate(45deg); }
.pname { font-weight: 600; flex: 1; font-size: 1.05rem; }
.pbody { border-top: 1px solid var(--line); margin-top: 12px; padding-top: 8px; }
.actions { display: flex; gap: 10px; flex-wrap: wrap; margin: 16px 0 8px; }
.panel { border: 1px dashed var(--line); border-radius: var(--radius); padding: 12px; margin: 8px 0; }
.config { margin-top: 18px; }
.config > summary { color: var(--muted); font-size: .9rem; }
.prospects { margin-top: 12px; }
.prospects > summary { font-weight: 600; }
@ -156,3 +155,178 @@ figure.chart figcaption { font-size: .85rem; font-weight: 600; margin-bottom: 4p
.sw { display: inline-block; width: 10px; height: 10px; border-radius: 2px; margin-left: 8px; }
.sw.s1 { background: var(--series-1); margin-left: 0; }
.sw.s2 { background: var(--series-2); }
/* ======================================================================
Habillage : fond animé, verre dépoli, sections dépliables, menu des jobs
====================================================================== */
:root {
--accent-2: #7c4dff;
--accent-soft: color-mix(in srgb, var(--accent) 11%, transparent);
--glass: color-mix(in srgb, var(--card) 84%, transparent);
--shadow: 0 1px 2px rgba(16, 24, 40, .04), 0 8px 28px rgba(16, 24, 40, .07);
--ease: cubic-bezier(.2, .8, .2, 1);
}
@media (prefers-color-scheme: dark) {
:root { --accent-2: #a78bfa; --shadow: 0 1px 2px rgba(0, 0, 0, .3), 0 10px 32px rgba(0, 0, 0, .4); }
}
body {
min-height: 100vh;
background:
radial-gradient(1100px 600px at 8% -12%, var(--accent-soft), transparent 60%),
radial-gradient(900px 520px at 108% 8%, color-mix(in srgb, var(--accent-2) 9%, transparent), transparent 60%),
var(--bg);
background-attachment: fixed;
}
#bg { position: fixed; inset: 0; width: 100%; height: 100%; z-index: -1; pointer-events: none; }
.top { position: sticky; top: 0; z-index: 20; background: var(--glass); backdrop-filter: blur(12px) saturate(1.4); }
.logo { display: inline-block; width: 14px; height: 14px; border-radius: 4px; margin-right: 8px; vertical-align: -2px;
background: linear-gradient(135deg, var(--accent), var(--accent-2)); animation: glow 3s ease-in-out infinite; }
main > h1, .head h1 { background: linear-gradient(90deg, var(--text), color-mix(in srgb, var(--accent) 75%, var(--text))); -webkit-background-clip: text; background-clip: text; color: transparent; }
.card { background: var(--glass); backdrop-filter: blur(8px); box-shadow: var(--shadow); animation: rise .5s var(--ease) both; transition: border-color .25s, box-shadow .25s; }
.projects > .card:nth-child(2) { animation-delay: .06s; }
.projects > .card:nth-child(3) { animation-delay: .12s; }
.projects > .card:nth-child(4) { animation-delay: .18s; }
.projects > .card:nth-child(n+5) { animation-delay: .24s; }
.project:hover, .project[open] { border-color: color-mix(in srgb, var(--accent) 35%, var(--line)); }
.project > summary { padding: 2px 0; }
.btn { transition: transform .18s var(--ease), box-shadow .18s, border-color .18s, background .18s; }
.btn:hover:not(:disabled) { transform: translateY(-1px); box-shadow: 0 4px 14px color-mix(in srgb, var(--accent) 18%, transparent); }
.btn:active:not(:disabled) { transform: translateY(0) scale(.98); }
.btn.primary { background: linear-gradient(135deg, var(--accent), var(--accent-2)); border-color: transparent; }
.btn.primary:hover:not(:disabled) { box-shadow: 0 6px 20px color-mix(in srgb, var(--accent) 35%, transparent); }
input, select, textarea { transition: border-color .18s, box-shadow .18s; }
input:focus, select:focus, textarea:focus { outline: none; border-color: var(--accent); box-shadow: 0 0 0 3px var(--accent-soft); }
/* ---------- Sections dépliables ---------- */
.accs { margin-top: 14px; }
.acc { border: 1px solid var(--line); border-radius: var(--radius); margin: 10px 0; background: var(--card); transition: border-color .25s, box-shadow .25s; }
.acc > summary { display: flex; align-items: center; gap: 12px; padding: 12px 14px; border-radius: var(--radius); transition: background .2s; }
.acc > summary:hover { background: var(--accent-soft); }
.acc > summary:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
.acc[open] { border-color: color-mix(in srgb, var(--accent) 40%, var(--line)); box-shadow: var(--shadow); }
.acc[open] > summary { border-bottom-left-radius: 0; border-bottom-right-radius: 0; }
.acc-ico { width: 34px; height: 34px; border-radius: 9px; display: grid; place-items: center; flex: none;
background: var(--accent-soft); color: var(--accent); transition: transform .35s var(--ease), background .25s, color .25s; }
.acc[open]:not(.closing) > summary .acc-ico { transform: rotate(-8deg) scale(1.06); background: linear-gradient(135deg, var(--accent), var(--accent-2)); color: #fff; }
.acc-txt { flex: 1; min-width: 0; display: flex; flex-direction: column; }
.acc-title { font-weight: 600; }
.acc-sub { font-size: .82rem; color: var(--muted); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.chev { width: 9px; height: 9px; border-right: 2px solid var(--muted); border-bottom: 2px solid var(--muted); transform: rotate(45deg);
transition: transform .3s var(--ease); margin: 0 6px 4px; flex: none; }
details[open]:not(.closing) > summary .chev { transform: rotate(225deg); margin-bottom: -2px; }
.acc-body { padding: 4px 16px 14px; }
.acc-body > :first-child { margin-top: 6px; }
.acc.main > summary .acc-title { font-size: 1.02rem; }
.acc.sub { background: transparent; box-shadow: none; margin: 8px 0; }
.acc.sub[open] { background: color-mix(in srgb, var(--accent) 3%, transparent); box-shadow: none; }
.acc.sub > summary { padding: 9px 12px; }
.acc.sub .acc-ico { width: 28px; height: 28px; border-radius: 7px; }
.acc.sub .acc-body { padding: 2px 12px 12px; }
.acc.config { margin-top: 18px; }
.acc.config .acc-ico { background: var(--locked); color: var(--muted); }
.acc.target-acc .acc-title .badge { margin-left: 6px; }
.acc[open]:not(.closing) > .acc-body > * { animation: rise .35s var(--ease) both; }
.acc[open]:not(.closing) > .acc-body > :nth-child(2) { animation-delay: .04s; }
.acc[open]:not(.closing) > .acc-body > :nth-child(3) { animation-delay: .08s; }
.acc[open]:not(.closing) > .acc-body > :nth-child(n+4) { animation-delay: .12s; }
.followup { margin-top: 0; padding-top: 0; border-top: 0; }
form.send { margin-top: 6px; padding-top: 0; border-top: 0; }
@media (max-width: 640px) { .acc-sub { white-space: normal; } .acc-body { padding: 4px 10px 12px; } }
/* ---------- Progression ---------- */
.bar { position: relative; height: 6px; border-radius: 99px; background: color-mix(in srgb, var(--muted) 18%, transparent); overflow: hidden; margin-top: 8px; }
.bar > span { position: absolute; top: 0; bottom: 0; left: 0; width: 0; border-radius: inherit; overflow: hidden;
background: linear-gradient(90deg, var(--accent), var(--accent-2)); transition: width .7s var(--ease); }
.bar > span::after { content: ""; position: absolute; inset: 0; background: linear-gradient(90deg, transparent, rgba(255, 255, 255, .5), transparent);
transform: translateX(-100%); animation: shimmer 1.6s infinite; }
.bar.indet > span { width: 35%; animation: indet 1.4s ease-in-out infinite; }
.run-head { display: flex; justify-content: space-between; gap: 10px; }
.jpct { font-variant-numeric: tabular-nums; font-weight: 700; color: var(--accent); white-space: nowrap; }
.running { background: color-mix(in srgb, var(--accent) 6%, var(--card)); border: 1px solid color-mix(in srgb, var(--accent) 18%, var(--line)); }
/* ---------- Menu des jobs (barre du haut) ---------- */
.jobs { position: relative; }
.jobs-btn { display: inline-flex; align-items: center; gap: 6px; border: 1px solid var(--line); background: var(--card); color: var(--text);
border-radius: 99px; padding: 4px 12px; font: inherit; font-size: .82rem; cursor: pointer; transition: border-color .2s, box-shadow .2s; animation: pop .3s var(--ease) both; }
.jobs-btn:hover, .jobs-btn[aria-expanded="true"] { border-color: var(--accent); box-shadow: 0 0 0 3px var(--accent-soft); }
.jobs-btn .spin-inline { margin-right: 0; }
.jobs-btn .chev { width: 7px; height: 7px; margin: 0 0 3px 2px; }
.jobs-btn[aria-expanded="true"] .chev { transform: rotate(225deg); margin-bottom: -2px; }
.jobs-pop { position: absolute; right: 0; top: calc(100% + 10px); width: 390px; max-width: calc(100vw - 24px); max-height: 70vh; overflow: auto;
background: var(--card); border: 1px solid var(--line); border-radius: 12px; box-shadow: 0 16px 48px rgba(0, 0, 0, .2); padding: 10px; z-index: 30;
transform-origin: top right; animation: pop .22s var(--ease) both; }
.jobs-head { display: flex; justify-content: space-between; align-items: baseline; padding: 2px 4px 10px; }
.jitem { padding: 10px 12px; border-radius: 10px; border: 1px solid var(--line); margin-bottom: 8px; }
.jobs-pop.fresh .jitem { animation: rise .3s var(--ease) both; }
.jitem:last-child { margin-bottom: 0; }
.jitem.j-running { border-color: color-mix(in srgb, var(--accent) 30%, var(--line)); background: color-mix(in srgb, var(--accent) 4%, var(--card)); }
.jrow { display: flex; gap: 8px; align-items: center; }
.jproj { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--muted); font-size: .85rem; }
.jmsg { margin: 3px 0 0; overflow-wrap: anywhere; }
.jmeta { display: flex; justify-content: space-between; gap: 8px; margin-top: 8px; }
.jitem .moon { width: 12px; height: 12px; box-shadow: inset -3px -2px 0 0 var(--accent); }
.pulse { width: 8px; height: 8px; border-radius: 50%; background: var(--accent); flex: none; animation: glow 1.6s ease-in-out infinite; }
.dot-wait { width: 8px; height: 8px; border-radius: 50%; border: 2px solid var(--muted); flex: none; }
@media (max-width: 640px) { .jobs-pop { position: fixed; left: 12px; right: 12px; top: calc(100% + 6px); width: auto; } }
/* ---------- Résultat « Évolution » ---------- */
.evo-done { display: flex; justify-content: space-between; align-items: center; gap: 10px; flex-wrap: wrap; margin: 6px 0 12px; }
.evo-done p { margin: 0; }
.evos { list-style: none; padding: 0; margin: 0; display: grid; gap: 12px; }
.evo { border: 1px solid var(--line); border-radius: 12px; padding: 14px 16px; background: var(--card); animation: rise .45s var(--ease) both;
transition: transform .25s var(--ease), box-shadow .25s, border-color .25s; }
.evo:hover { transform: translateY(-2px); box-shadow: var(--shadow); border-color: color-mix(in srgb, var(--accent) 40%, var(--line)); }
.evo:nth-child(2) { animation-delay: .05s; }
.evo:nth-child(3) { animation-delay: .1s; }
.evo:nth-child(4) { animation-delay: .15s; }
.evo:nth-child(5) { animation-delay: .2s; }
.evo:nth-child(n+6) { animation-delay: .25s; }
.evo-head { display: flex; align-items: center; gap: 10px; }
.evo-head h5 { margin: 0; font-size: 1rem; flex: 1; line-height: 1.35; }
.evo-n { width: 28px; height: 28px; border-radius: 8px; display: grid; place-items: center; flex: none; font-weight: 700; font-size: .9rem; color: #fff;
background: linear-gradient(135deg, var(--accent), var(--accent-2)); }
.effort { font-size: .75rem; font-weight: 600; padding: 2px 10px; border-radius: 99px; white-space: nowrap; }
.e-S { color: var(--ok); background: color-mix(in srgb, var(--ok) 14%, transparent); }
.e-M { color: var(--warn); background: color-mix(in srgb, var(--warn) 14%, transparent); }
.e-L { color: var(--err); background: color-mix(in srgb, var(--err) 14%, transparent); }
.md { font-size: .92rem; line-height: 1.6; }
.evo .md { margin-top: 8px; padding-left: 38px; }
.md > :last-child { margin-bottom: 0; }
.md p { margin: 0 0 8px; }
.md ul, .md ol { margin: 0 0 8px; padding-left: 18px; }
.md li { margin: 4px 0; }
.md li::marker { color: var(--accent); }
.md strong { font-weight: 600; }
.md code { font-size: .85em; background: var(--locked); padding: 1px 5px; border-radius: 4px; }
.md pre { background: var(--locked); padding: 10px; border-radius: 8px; overflow: auto; }
.md h1, .md h2, .md h3, .md h4 { font-size: 1rem; margin: 12px 0 6px; }
.md blockquote { border-left: 3px solid var(--accent); margin: 0 0 8px; padding-left: 10px; color: var(--muted); }
@media (max-width: 640px) { .evo .md { padding-left: 0; } .evo-head { flex-wrap: wrap; } }
/* ---------- Toasts, fenêtres ---------- */
.toast { animation: toast-in .3s var(--ease) both; transition: opacity .3s, transform .3s; }
.toast.out { opacity: 0; transform: translateY(8px) scale(.98); }
.prospect-dialog[open] { animation: pop .25s var(--ease) both; box-shadow: 0 24px 64px rgba(0, 0, 0, .3); }
.prospect-dialog::backdrop { backdrop-filter: blur(3px); }
.badge { animation: pop .3s var(--ease) both; }
@keyframes rise { from { opacity: 0; transform: translateY(10px); } }
@keyframes fadein { from { opacity: 0; } }
@keyframes pop { from { opacity: 0; transform: translateY(-6px) scale(.97); } }
@keyframes toast-in { from { opacity: 0; transform: translateY(14px) scale(.96); } }
@keyframes shimmer { to { transform: translateX(100%); } }
@keyframes indet { from { left: -35%; } to { left: 100%; } }
@keyframes glow {
0%, 100% { box-shadow: 0 0 0 0 color-mix(in srgb, var(--accent) 45%, transparent); }
50% { box-shadow: 0 0 0 6px transparent; }
}
@media (prefers-reduced-motion: reduce) {
*:not(.spinner):not(.spin-inline), *::before, *::after {
animation-duration: .01ms !important; animation-iteration-count: 1 !important; transition-duration: .01ms !important;
}
}

View file

@ -19,9 +19,29 @@
t.className = `toast ${kind}`;
t.textContent = msg;
document.body.append(t);
setTimeout(() => t.remove(), 4500);
setTimeout(() => { t.classList.add('out'); setTimeout(() => t.remove(), 300); }, 4200);
}
// Barres de progression : la largeur passe par le CSSOM (la CSP interdit les attributs style="").
// On repart de la dernière valeur connue du job pour que la barre glisse au lieu de repartir de 0 à chaque rafraîchissement.
const barMem = new Map();
function paintBars(root) {
$$('.bar > span[data-pct]', root).forEach((s) => {
if (s.dataset.pct === '') return;
const pct = Number(s.dataset.pct);
const key = s.dataset.key;
s.style.width = `${barMem.get(key) ?? 0}%`;
void s.offsetWidth; // force le calcul pour déclencher la transition
s.style.width = `${pct}%`;
if (key) barMem.set(key, pct);
});
}
const pctOf = (p) => (typeof p?.pct === 'number' ? Math.max(0, Math.min(100, Math.round(p.pct))) : null);
const progressBar = (job) => {
const v = pctOf(job.progress);
return `<div class="bar${v === null ? ' indet' : ''}"><span data-key="${job.id}" data-pct="${v ?? ''}"></span></div>`;
};
const formData = (form) => Object.fromEntries(new FormData(form));
const ago = (ts) => {
if (!ts) return 'jamais';
@ -61,41 +81,124 @@
return `${claudeBit('session 5h', rl.fiveHour)} ${claudeBit('semaine', rl.sevenDay)}`.trim();
}
// ---------- Menu « jobs » : détail de ce qui tourne, avec l'avancement ----------
const jobsBox = $('#jobs');
const jobsBtn = jobsBox && $('.jobs-btn', jobsBox);
const jobsPop = jobsBox && $('.jobs-pop', jobsBox);
const jobsOpen = () => jobsBtn?.getAttribute('aria-expanded') === 'true';
const fmtWhen = (ts) => new Date(ts * 1000).toLocaleString('fr-FR', { weekday: 'long', hour: '2-digit', minute: '2-digit', timeZone: 'Europe/Paris' });
const plural = (n, w) => `${n} ${w}${n > 1 ? 's' : ''}`;
function jobItem(j) {
const p = j.progress || {};
const scheduled = j.status === 'queued' && j.runAfter && j.runAfter * 1000 > Date.now();
const running = j.status === 'running';
const v = running ? pctOf(p) : null;
const state = scheduled ? `Programmé ${fmtWhen(j.runAfter)}` : running ? `Démarré ${ago(j.startedAt)}` : 'En file d\'attente';
const msg = p.message || (running ? 'En cours…' : '');
return `<div class="jitem j-${scheduled ? 'scheduled' : j.status}">
<div class="jrow">${scheduled ? '<span class="moon" aria-hidden="true"></span>' : running ? '<span class="pulse" aria-hidden="true"></span>' : '<span class="dot-wait" aria-hidden="true"></span>'}
<strong>${esc(LABELS[j.type] || j.type)}</strong><span class="jproj">${j.project ? esc(j.project) : ''}</span>${v !== null ? `<span class="jpct">${v} %</span>` : ''}</div>
${msg ? `<div class="jmsg small muted">${esc(msg)}</div>` : ''}
${running ? progressBar(j) : ''}
<div class="jmeta small muted"><span>${esc(state)}</span>
<span>${j.projectId ? `<button type="button" class="link small" data-goto="${j.projectId}">Voir</button> · ` : ''}<button type="button" class="link small" data-cancel="${j.id}">Annuler</button></span></div>
</div>`;
}
function renderJobsMenu(s) {
if (!jobsBox) return;
const list = s.jobs || [];
jobsBox.hidden = !list.length;
if (!list.length) { if (jobsOpen()) toggleJobs(false); return; }
$('.spin-inline', jobsBtn).hidden = !s.queue;
$('[data-jobs-count]', jobsBtn).textContent = s.queue
? `${plural(s.queue, 'job')}${s.scheduled ? ` · ${s.scheduled} cette nuit` : ''}`
: `${plural(s.scheduled, 'programmé')} cette nuit`;
const running = list.filter((j) => j.status === 'running').length;
$('[data-jobs-sub]', jobsPop).textContent = `${running} en cours · ${list.length - running} en attente`;
// Redessine seulement si le contenu change : sinon l'animation d'apparition rejouerait à chaque poll
const html = list.map(jobItem).join('');
const box = $('[data-jobs-list]', jobsPop);
if (box._html === html) return;
box._html = html;
box.innerHTML = html;
paintBars(jobsPop);
}
function toggleJobs(open = !jobsOpen()) {
if (!jobsBtn) return;
jobsBtn.setAttribute('aria-expanded', String(open));
jobsPop.hidden = !open;
if (open) {
// Les lignes n'apparaissent en fondu qu'à l'ouverture, pas à chaque mise à jour
jobsPop.classList.add('fresh');
setTimeout(() => jobsPop.classList.remove('fresh'), 600);
refreshSys();
}
}
jobsBtn?.addEventListener('click', () => toggleJobs());
document.addEventListener('click', (e) => {
if (jobsOpen() && !e.target.closest('#jobs')) toggleJobs(false);
const go = e.target.closest('[data-goto]');
if (!go) return;
sessionStorageSet('openProject', go.dataset.goto);
const d = $(`details.project[data-id="${go.dataset.goto}"]`);
if (!d) { location.href = '/'; return; }
toggleJobs(false);
d.open = true;
d.scrollIntoView({ behavior: 'smooth', block: 'start' });
});
document.addEventListener('keydown', (e) => { if (e.key === 'Escape' && jobsOpen()) { toggleJobs(false); jobsBtn.focus(); } });
let sysTimer;
async function refreshSys() {
clearTimeout(sysTimer);
const el = $('#sys');
if (!el) return;
let busy = false;
try {
const s = await api('/api/system');
const hot = s.temp !== null && s.temp >= s.thermalMax - 5;
el.innerHTML = `${s.temp !== null ? `<span class="${hot ? 'warn' : ''}">${s.temp} °C</span>` : ''}
${claudeQuota(s.claudeRateLimit)}
${gauge('24 h', s.budget.day)} ${gauge('30 j', s.budget.month)}
${s.budget.blocked ? '<span class="error">Budget IA atteint : jobs IA en attente</span>' : ''}
${s.queue ? `<span class="spin-inline"></span>${s.queue} job(s)` : ''}
${s.scheduled ? `<span>${s.scheduled} programmé(s) cette nuit</span>` : ''}`;
${s.budget.blocked ? '<span class="error">Budget IA atteint : jobs IA en attente</span>' : ''}`;
renderJobsMenu(s);
busy = s.queue > 0;
} catch { /* silencieux */ }
// Plus réactif quand quelque chose tourne ou que le menu est ouvert
sysTimer = setTimeout(refreshSys, jobsOpen() ? 3000 : busy ? 6000 : 30_000);
}
refreshSys();
setInterval(refreshSys, 30_000);
// ---------- Rendu d'un job ----------
function renderJob(box, job, type) {
if (!box) return;
if (!job) { box.innerHTML = ''; return; }
if (!job) { box.innerHTML = ''; box._sig = ''; return; }
const p = job.progress || {};
if (job.status === 'queued' && job.runAfter && job.runAfter * 1000 > Date.now()) {
const later = job.status === 'queued' && job.runAfter && job.runAfter * 1000 > Date.now();
// Rien n'a changé : on ne touche pas au DOM (sinon les animations d'apparition rejoueraient à chaque poll)
const sig = `${job.id}|${job.status}|${later}|${JSON.stringify(p)}`;
if (box._sig === sig) return;
box._sig = sig;
if (later) {
const at = new Date(job.runAfter * 1000).toLocaleString('fr-FR', { weekday: 'long', hour: '2-digit', minute: '2-digit', timeZone: 'Europe/Paris' });
box.innerHTML = `<div class="running scheduled"><span class="moon" aria-hidden="true"></span>
<div><div>${LABELS[type]} programmé(e) : ${esc(at)}</div><div class="small muted">Le Pi est au frais et ton quota Claude est libre.</div></div>
<div><div>${LABELS[type]} programmé(e) : ${esc(at)}</div><div class="small muted">Démarrage la nuit, quand ton quota Claude est libre.</div></div>
<button class="btn small" data-cancel="${job.id}">Annuler</button></div>`;
return;
}
if (ACTIVE.includes(job.status)) {
const extra = type === 'prospect' && p.found !== undefined
? `<strong>${p.found}</strong> prospect(s) trouvé(s) sur ${p.target}` : '';
const running = job.status === 'running';
const v = running ? pctOf(p) : null;
box.innerHTML = `<div class="running"><span class="spinner"></span>
<div><div>${esc(p.message || (job.status === 'queued' ? 'En file d\'attente…' : 'En cours…'))}</div>${extra ? `<div class="small">${extra}</div>` : ''}</div>
<div><div class="run-head"><span>${esc(p.message || (running ? 'En cours…' : 'En file d\'attente…'))}</span>${v !== null ? `<strong class="jpct">${v} %</strong>` : ''}</div>
${extra ? `<div class="small">${extra}</div>` : ''}${running ? progressBar(job) : ''}</div>
<button class="btn small" data-cancel="${job.id}">Annuler</button></div>`;
paintBars(box);
} else if (job.status === 'error') {
box.innerHTML = `<p class="error small">${LABELS[type]} en échec : ${esc(job.error)}</p>`;
} else if (job.status === 'cancelled') {
@ -107,7 +210,12 @@
if (type === 'send') txt = `Envoi terminé : ${r.sent} envoyé(s), ${r.failed} échec(s).`;
if (type === 'followup') txt = r.postponed ? 'Relances reportées au prochain créneau (lun-ven 9h-18h).' : `Relances terminées : ${r.sent} envoyée(s), ${r.failed} échec(s).`;
if (type === 'evolution') {
box.innerHTML = `<p class="ok small">Envoyé à ${esc(r.sentTo)}.</p><pre class="md">${esc(r.markdown)}</pre>`;
const when = job.finishedAt ? new Date(job.finishedAt * 1000).toLocaleString('fr-FR', { dateStyle: 'short', timeStyle: 'short', timeZone: 'Europe/Paris' }) : '';
// r.html est rendu et échappé par le serveur (src/services/markdown.js)
box.innerHTML = `<div class="evo-done"><p class="ok small">Envoyé à ${esc(r.sentTo)}${when ? ` · ${esc(when)}` : ''}</p>
<button type="button" class="btn small" data-copy-md>Copier le Markdown</button></div>
${r.html || `<pre class="md">${esc(r.markdown)}</pre>`}`;
box._markdown = r.markdown;
return;
}
box.innerHTML = `<p class="ok small">${esc(txt)}</p>`;
@ -217,15 +325,44 @@
function sessionStorageSet(k, v) { try { sessionStorage.setItem(k, v); } catch { /* ignore */ } }
$$('details.project').forEach((el) => el.addEventListener('toggle', () => { if (el.open) sessionStorageSet('openProject', el.dataset.id); }));
// ---------- Panneaux ----------
// ---------- Sections dépliables animées ----------
// <details class="anim"> : la hauteur du bloc qui suit le <summary> glisse à l'ouverture et à la fermeture.
const reduceMotion = matchMedia('(prefers-reduced-motion: reduce)');
document.addEventListener('click', (e) => {
const sum = e.target.closest('summary');
const d = sum?.parentElement;
const body = sum?.nextElementSibling;
if (!d?.matches('details.anim') || !body || reduceMotion.matches) return;
e.preventDefault();
d._anim?.cancel();
const opening = !d.open || d.classList.contains('closing');
const from = d.open ? body.getBoundingClientRect().height : 0;
d.classList.remove('closing');
if (opening) d.open = true;
else d.classList.add('closing');
const to = opening ? body.scrollHeight : 0;
body.style.overflow = 'hidden';
const anim = body.animate(
[{ height: `${from}px`, opacity: opening ? 0 : 1 }, { height: `${to}px`, opacity: opening ? 1 : 0 }],
{ duration: Math.min(450, 200 + Math.abs(to - from) * 0.2), easing: 'cubic-bezier(.2,.8,.2,1)' },
);
d._anim = anim;
anim.oncancel = () => { body.style.overflow = ''; };
anim.onfinish = () => {
d._anim = null;
body.style.overflow = '';
if (!opening) { d.open = false; d.classList.remove('closing'); }
};
});
// Le récap se charge à l'ouverture de sa section
$$('details[data-acc="recap"]').forEach((d) => d.addEventListener('toggle', () => { if (d.open) loadRecap(d.closest('.project')); }));
document.addEventListener('click', async (e) => {
const panelBtn = e.target.closest('[data-panel]');
if (panelBtn) {
const proj = panelBtn.closest('.project');
const name = panelBtn.dataset.panel;
$$('[data-panel]', proj).forEach((b) => b.classList.toggle('active', b === panelBtn && !b.classList.contains('active')));
$$('[data-panel-body]', proj).forEach((p) => { p.hidden = p.dataset.panelBody !== name || !panelBtn.classList.contains('active'); });
if (name === 'recap' && panelBtn.classList.contains('active')) loadRecap(proj);
const copy = e.target.closest('[data-copy-md]');
if (copy) {
const md = copy.closest('.job')?._markdown || '';
try { await navigator.clipboard.writeText(md); toast('Markdown copié'); } catch { toast('Copie impossible dans ce navigateur', 'error'); }
return;
}
@ -244,7 +381,11 @@
const cancel = e.target.closest('[data-cancel]');
if (cancel) {
await api(`/api/jobs/${cancel.dataset.cancel}/cancel`, {}).catch((err) => toast(err.message, 'error'));
refreshProject(cancel.closest('.project'));
// Depuis le menu du haut, le bouton n'est dans aucun projet : on rafraîchit tout ce qui est ouvert
const proj = cancel.closest('.project');
if (proj) refreshProject(proj);
else $$('details.project[open]').forEach((el) => refreshProject(el));
refreshSys();
return;
}
@ -679,4 +820,88 @@
try { await api(`/api/prospects/${sel.dataset.prospect}/status`, { status: sel.value }); sel.className = `st-${sel.value}`; toast('Statut mis à jour'); }
catch (err) { toast(err.message, 'error'); }
});
// ---------- Fond : constellation de particules qui fuient la souris ----------
// Canvas 2D, ~90 points max : léger. Coupé quand l'onglet est caché, figé si l'OS demande moins d'animations.
(function particles() {
const cv = $('#bg');
const ctx = cv?.getContext?.('2d');
if (!ctx) return;
const LINK = 120; // distance max d'un trait entre deux points
const R = 170; // rayon d'influence de la souris
const mouse = { x: -1e4, y: -1e4 };
let W = 0, H = 0, pts = [], raf = 0, rgb = '47,91,234';
const readColor = () => {
const m = /^#?([\da-f]{2})([\da-f]{2})([\da-f]{2})$/i.exec(getComputedStyle(document.documentElement).getPropertyValue('--accent').trim());
if (m) rgb = m.slice(1).map((h) => parseInt(h, 16)).join(',');
};
const spawn = () => {
const a = Math.random() * Math.PI * 2, s = 0.12 + Math.random() * 0.25;
const bvx = Math.cos(a) * s, bvy = Math.sin(a) * s;
return { x: Math.random() * W, y: Math.random() * H, vx: bvx, vy: bvy, bvx, bvy, r: 1 + Math.random() * 1.6 };
};
function resize() {
const dpr = Math.min(2, window.devicePixelRatio || 1);
W = window.innerWidth; H = window.innerHeight;
cv.width = Math.round(W * dpr); cv.height = Math.round(H * dpr);
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
const n = Math.round(Math.min(90, Math.max(24, (W * H) / 16000)));
while (pts.length < n) pts.push(spawn());
pts.length = n;
}
function step() {
for (const p of pts) {
const dx = p.x - mouse.x, dy = p.y - mouse.y, d = Math.hypot(dx, dy);
if (d < R && d > 0.5) { const f = (1 - d / R) * 0.45; p.vx += (dx / d) * f; p.vy += (dy / d) * f; }
// Revient doucement à sa dérive de base après une poussée
p.vx += (p.bvx - p.vx) * 0.03; p.vy += (p.bvy - p.vy) * 0.03;
p.x += p.vx; p.y += p.vy;
if (p.x < -12) p.x = W + 12; else if (p.x > W + 12) p.x = -12;
if (p.y < -12) p.y = H + 12; else if (p.y > H + 12) p.y = -12;
}
}
function draw() {
ctx.clearRect(0, 0, W, H);
ctx.lineWidth = 1;
for (let i = 0; i < pts.length; i++) {
const a = pts[i];
for (let j = i + 1; j < pts.length; j++) {
const b = pts[j], dx = a.x - b.x, dy = a.y - b.y, d2 = dx * dx + dy * dy;
if (d2 > LINK * LINK) continue;
ctx.strokeStyle = `rgba(${rgb},${((1 - Math.sqrt(d2) / LINK) * 0.2).toFixed(3)})`;
ctx.beginPath(); ctx.moveTo(a.x, a.y); ctx.lineTo(b.x, b.y); ctx.stroke();
}
const md = Math.hypot(a.x - mouse.x, a.y - mouse.y);
if (md < R) {
ctx.strokeStyle = `rgba(${rgb},${((1 - md / R) * 0.45).toFixed(3)})`;
ctx.beginPath(); ctx.moveTo(a.x, a.y); ctx.lineTo(mouse.x, mouse.y); ctx.stroke();
}
}
for (const p of pts) {
const glow = Math.max(0, 1 - Math.hypot(p.x - mouse.x, p.y - mouse.y) / R);
ctx.fillStyle = `rgba(${rgb},${(0.45 + glow * 0.5).toFixed(3)})`;
ctx.beginPath(); ctx.arc(p.x, p.y, p.r + glow * 1.5, 0, Math.PI * 2); ctx.fill();
}
}
const loop = () => { step(); draw(); raf = requestAnimationFrame(loop); };
const start = () => { cancelAnimationFrame(raf); if (reduceMotion.matches) draw(); else raf = requestAnimationFrame(loop); };
window.addEventListener('pointermove', (e) => { mouse.x = e.clientX; mouse.y = e.clientY; }, { passive: true });
document.addEventListener('pointerleave', () => { mouse.x = mouse.y = -1e4; });
window.addEventListener('blur', () => { mouse.x = mouse.y = -1e4; });
// Un clic souffle les particules alentour
window.addEventListener('pointerdown', (e) => {
for (const p of pts) {
const dx = p.x - e.clientX, dy = p.y - e.clientY, d = Math.hypot(dx, dy);
if (d < 240 && d > 0.5) { const f = (1 - d / 240) * 5; p.vx += (dx / d) * f; p.vy += (dy / d) * f; }
}
}, { passive: true });
let rt;
window.addEventListener('resize', () => { clearTimeout(rt); rt = setTimeout(() => { resize(); start(); }, 120); });
document.addEventListener('visibilitychange', () => { if (document.hidden) cancelAnimationFrame(raf); else start(); });
matchMedia('(prefers-color-scheme: dark)').addEventListener('change', readColor);
reduceMotion.addEventListener('change', start);
readColor(); resize(); start();
})();
})();

View file

@ -9,6 +9,7 @@ import { EMAIL_RE, createTransport, buildProspectMail, allowedToSend, makeMessag
import { unsubToken } from './crypto.js';
import { quotaAlerts } from './services/budget.js';
import { notify } from './services/notify.js';
import { evolutionMail } from './services/mailhtml.js';
import { getProject, repoDir, forgejoToken, globalSmtp, sentSince, getTemplate, saveTemplate, pickVariant } from './projects.js';
const sleep = (ms, signal) => new Promise((resolve, reject) => {
@ -16,6 +17,9 @@ const sleep = (ms, signal) => new Promise((resolve, reject) => {
signal?.addEventListener('abort', () => { clearTimeout(t); reject(new Error('Annulé')); }, { once: true });
});
// 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)));
// Une page web peut tenter de faire enregistrer "javascript:…" : seules les URLs http(s) sont gardées
export function httpUrl(v) {
const s = String(v ?? '').trim();
@ -95,6 +99,7 @@ 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 });
for (const p of candidates.slice(0, n)) {
if (ctx.cancelled()) break;
@ -131,7 +136,7 @@ export function makeHandlers(app) {
failed++;
}
const label = kind === 'followup' ? 'relances envoyées' : 'envoyés';
ctx.progress({ sent, failed, total: n, message: `${sent + failed}/${n} ${label}` });
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();
@ -141,14 +146,17 @@ export function makeHandlers(app) {
return {
async analyze(ctx) {
const project = getProject(app, ctx.job.project_id);
ctx.progress({ message: 'Récupération du repo…' });
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));
ctx.progress({ message: 'Analyse du code par Claude…' });
ctx.progress({ message: 'Analyse du code par Claude…', pct: 10 });
const { prompt, system } = analyzePrompt(project.name);
const model = getSetting(db, 'analyze_model', 'haiku');
const r = await claude({ prompt, system, cwd: dir, model, maxTurns: 20, tools: ['Read', 'Glob', 'Grep'], signal: ctx.signal });
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) }),
});
addUsage(ctx, r);
if (!r.ok) throw new Error(`Analyse incomplète (${r.subtype})`);
const profile = extractJson(r.text);
@ -174,6 +182,14 @@ export function makeHandlers(app) {
SELECT ?, ?, ?, ?, ?, ?, ?, ?, ?, ? WHERE NOT EXISTS (SELECT 1 FROM blacklist WHERE email = ?)`);
let found = 0;
let pending = '';
let turns = 0;
let message = 'Recherche en cours…';
const maxTurns = Math.min(80, count * 3 + 10);
// Le plus avancé des deux : prospects trouvés, ou messages de Claude consommés
const report = () => ctx.progress({
found, target: count, message,
pct: Math.min(99, Math.max(Math.round((found / count) * 100), turnPct(0, 90, turns, maxTurns))),
});
const onText = (text) => {
pending += text + '\n';
const lines = pending.split('\n');
@ -184,16 +200,18 @@ export function makeHandlers(app) {
const res = insert.run(project.id, p.company, p.email, p.website, p.city, p.sector, p.hook, p.source, p.score, now(), p.email);
if (res.changes) {
found++;
ctx.progress({ found, target: count, message: `${found}/${count} — ${p.company}` });
message = `${found}/${count} — ${p.company}`;
report();
}
}
};
ctx.progress({ found: 0, target: count, message: 'Recherche en cours…' });
report();
const { prompt, system } = prospectPrompt({ profile: project.profile, target: project.target, count, exclude });
const model = getSetting(db, 'prospect_model', 'haiku');
const r = await claude({
prompt, system, model, tools: ['WebSearch', 'WebFetch'],
maxTurns: Math.min(80, count * 3 + 10), onText, signal: ctx.signal,
maxTurns, onText, signal: ctx.signal,
onTurn: (n) => { turns = n; report(); },
});
onText('\n');
addUsage(ctx, r);
@ -203,6 +221,7 @@ export function makeHandlers(app) {
async template(ctx) {
const project = 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 });
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);
@ -215,6 +234,7 @@ export function makeHandlers(app) {
async followup_template(ctx) {
const project = 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 });
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);
@ -236,23 +256,27 @@ export function makeHandlers(app) {
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…' });
ctx.progress({ message: 'Mise à jour du repo…', pct: 3 });
const dir = repoDir(cfg, project.id);
await syncRepo(project.gitUrl, dir, forgejoToken(app));
ctx.progress({ message: `Recherche de ${count} évolutions (${level})…` });
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 r = await claude({ prompt, system, cwd: dir, model, maxTurns, tools: ['Read', 'Glob', 'Grep'], signal: ctx.signal });
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) }),
});
addUsage(ctx, r);
if (!r.text?.trim()) throw new Error(`Pas de résultat (${r.subtype})`);
ctx.progress({ message: 'Envoi par mail…' });
ctx.progress({ message: 'Envoi par mail…', pct: 95 });
const transport = (app.createTransport || createTransport)(smtp);
await transport.sendMail({
from: smtp.fromEmail, to,
subject: `[AiTools] ${count} évolutions pour ${project.name}`,
text: r.text,
html: evolutionMail({ markdown: r.text, projectName: project.name, count, appUrl: cfg.appUrl }),
});
transport.close();
return { markdown: r.text, sentTo: to };

View file

@ -16,6 +16,7 @@ import { budgetState, AI_JOBS } from './services/budget.js';
import { sendWeeklyReport } from './services/report.js';
import { exportProspects, importProspects } from './services/csv.js';
import { history, saveSnapshot } from './services/metrics.js';
import { evolutionHtml } from './services/markdown.js';
import {
listProspects, parseFilters, STATUSES as PROSPECT_STATUSES, prospectDetail, addNote, deleteNote, setNextAction,
} from './services/crm.js';
@ -136,8 +137,17 @@ export function registerRoutes(router, app) {
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');
// 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
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) => ({
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, usage: usageSummary(db), budget: budgetState(db), thermalMax: cfg.thermalMax,
temp: cpuTemp(), queue, scheduled, jobs, usage: usageSummary(db), budget: budgetState(db), thermalMax: cfg.thermalMax,
claudeRateLimit: rlRaw ? JSON.parse(rlRaw) : null,
});
});
@ -168,6 +178,8 @@ export function registerRoutes(router, app) {
router.get('/api/projects/:id/status', ({ res, params }) => {
const p = getProject(app, pid(params));
const jobs = 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);

View file

@ -13,6 +13,7 @@ export const MODELS = { rapide: 'haiku', normal: 'sonnet', approfondi: 'opus' };
* @param {string[]} [o.tools] outils autorisés, tout le reste est refusé
* @param {string} [o.system] consignes ajoutées au prompt système
* @param {(text:string)=>void} [o.onText] appelé à chaque bloc texte de Claude
* @param {(n:number)=>void} [o.onTurn] appelé à chaque message de Claude (sert à estimer l'avancement)
* @param {AbortSignal} [o.signal]
* @param {number} [o.timeoutMs]
* @param {string} [o.bin]
@ -38,6 +39,7 @@ export function runClaude(o) {
let stderr = '';
let result = null;
let rateLimit = null;
let turns = 0;
const texts = [];
const timer = setTimeout(() => child.kill('SIGTERM'), o.timeoutMs || 30 * 60_000);
@ -58,6 +60,7 @@ export function runClaude(o) {
let ev;
try { ev = JSON.parse(line); } catch { return; }
if (ev.type === 'assistant') {
o.onTurn?.(++turns);
for (const block of ev.message?.content || []) {
if (block.type === 'text' && block.text) { texts.push(block.text); o.onText?.(block.text); }
}

View file

@ -1,5 +1,6 @@
import nodemailer from 'nodemailer';
import { randomBytes } from 'node:crypto';
import { prospectHtml } from './mailhtml.js';
export const EMAIL_RE = /^[^\s@<>()"',;:]+@[a-z0-9-]+(\.[a-z0-9-]+)*\.[a-z]{2,}$/i;
@ -35,17 +36,14 @@ export function buildProspectMail({ template, prospect, smtp, unsubUrl, subject
expediteur: smtp.fromName || '',
};
const body = fillTemplate(template.body, vars).replace(/\n{3,}/g, '\n\n').trim();
const footer = [
'',
'—',
`Vous recevez ce message car l'adresse ${prospect.email} est publiée publiquement${prospect.source ? ` (${prospect.source})` : ''}.`,
`Pour ne plus être contacté : ${unsubUrl}`,
].join('\n');
const notice = `Vous recevez ce message car l'adresse ${prospect.email} est publiée publiquement${prospect.source ? ` (${prospect.source})` : ''}.`;
const footer = ['', '—', notice, `Pour ne plus être contacté : ${unsubUrl}`].join('\n');
return {
from: smtp.fromName ? `"${smtp.fromName.replace(/"/g, '')}" <${smtp.fromEmail}>` : smtp.fromEmail,
to: prospect.email,
subject: fillTemplate(subject, vars).trim(),
text: body + '\n' + footer,
html: prospectHtml({ body, notice, unsubUrl }),
...(messageId ? { messageId } : {}),
...(inReplyTo ? { inReplyTo, references: [inReplyTo] } : {}),
headers: {

157
src/services/mailhtml.js Normal file
View file

@ -0,0 +1,157 @@
// Gabarits HTML des mails. Styles inline + tableaux : c'est ce que Gmail, Outlook et Apple Mail rendent pareil.
// Chaque mail garde aussi sa version texte (lisible partout, et meilleure délivrabilité).
import { esc } from '../http.js';
import { renderMarkdown, inlineMd, parseEvolutions, EFFORTS } from './markdown.js';
const C = {
bg: '#f4f5f7', card: '#ffffff', text: '#17191c', muted: '#6b7078', line: '#e2e4e8',
accent: '#2f5bea', accentSoft: '#eef2fe', ok: '#15803d',
};
const FONT = "-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,Helvetica,Arial,sans-serif";
const MD_STYLES = {
p: `margin:0 0 12px;font-size:15px;line-height:1.6;color:${C.text}`,
ul: 'margin:0 0 12px;padding-left:20px',
ol: 'margin:0 0 12px;padding-left:20px',
li: `margin:0 0 6px;font-size:15px;line-height:1.55;color:${C.text}`,
strong: `color:${C.text};font-weight:600`,
code: `font-family:SFMono-Regular,Consolas,monospace;font-size:13px;background:${C.bg};border:1px solid ${C.line};border-radius:4px;padding:1px 5px`,
pre: `margin:0 0 12px;padding:12px;background:${C.bg};border-radius:8px;font-size:13px;white-space:pre-wrap`,
a: `color:${C.accent}`,
h1: `margin:18px 0 8px;font-size:20px;color:${C.text}`,
h2: `margin:18px 0 8px;font-size:18px;color:${C.text}`,
h3: `margin:16px 0 8px;font-size:16px;color:${C.text}`,
h4: `margin:14px 0 6px;font-size:15px;color:${C.text}`,
blockquote: `margin:0 0 12px;padding:4px 12px;border-left:3px solid ${C.accent};color:${C.muted}`,
hr: `border:0;border-top:1px solid ${C.line};margin:16px 0`,
};
const md = (s) => renderMarkdown(s, { styles: MD_STYLES });
const st = (tag) => (MD_STYLES[tag] ? ` style="${MD_STYLES[tag]}"` : '');
const EFFORT_COLORS = {
S: ['#15803d', '#dcfce7'], M: ['#b45309', '#fef3c7'], L: ['#b91c1c', '#fee2e2'],
};
/** Mise en page commune des mails envoyés à toi (évolutions, rapport hebdo). */
export function mailLayout({ title, subtitle = '', preheader = '', content, appUrl = '', cta = '' }) {
return `<!doctype html>
<html lang="fr"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="color-scheme" content="light"><title>${esc(title)}</title></head>
<body style="margin:0;padding:0;background:${C.bg};">
<div style="display:none;max-height:0;overflow:hidden;opacity:0;">${esc(preheader)}</div>
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="background:${C.bg};">
<tr><td align="center" style="padding:28px 12px;">
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="max-width:640px;font-family:${FONT};">
<tr><td style="padding:0 4px 14px;font-size:14px;font-weight:700;color:${C.text};letter-spacing:.2px;">
<span style="display:inline-block;width:10px;height:10px;border-radius:3px;background:${C.accent};margin-right:8px;"></span>AiTools
</td></tr>
<tr><td style="background:${C.accent};background-image:linear-gradient(135deg,#2f5bea,#7c4dff);border-radius:14px 14px 0 0;padding:24px 20px;">
<div style="font-size:22px;line-height:1.3;font-weight:700;color:#ffffff;">${esc(title)}</div>
${subtitle ? `<div style="margin-top:6px;font-size:14px;color:#dfe6ff;">${esc(subtitle)}</div>` : ''}
</td></tr>
<tr><td style="background:${C.card};border:1px solid ${C.line};border-top:0;border-radius:0 0 14px 14px;padding:22px 20px;">
${content}
${cta && appUrl ? `<table role="presentation" cellpadding="0" cellspacing="0" style="margin-top:8px;"><tr><td style="background:${C.accent};border-radius:8px;">
<a href="${esc(appUrl)}" style="display:inline-block;padding:11px 20px;font-size:14px;font-weight:600;color:#ffffff;text-decoration:none;">${esc(cta)}</a>
</td></tr></table>` : ''}
</td></tr>
<tr><td style="padding:16px 4px;font-size:12px;color:${C.muted};text-align:center;">Envoyé automatiquement par ton panel AiTools.</td></tr>
</table>
</td></tr></table>
</body></html>`;
}
/** Mail « Évolutions » : une carte par idée, avec le niveau d'effort en pastille. */
export function evolutionMail({ markdown, projectName, count, appUrl }) {
const items = parseEvolutions(markdown);
const content = items.length ? items.map((e) => {
const [fg, bg] = EFFORT_COLORS[e.effort] || [C.muted, C.bg];
return `<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="margin:0 0 16px;border:1px solid ${C.line};border-radius:12px;">
<tr><td style="padding:16px 18px 6px;">
<table role="presentation" width="100%" cellpadding="0" cellspacing="0"><tr>
<td width="36" valign="top"><div style="width:28px;height:28px;line-height:28px;border-radius:8px;background:${C.accentSoft};color:${C.accent};font-weight:700;font-size:14px;text-align:center;">${e.n}</div></td>
<td valign="middle" style="font-size:16px;font-weight:700;color:${C.text};line-height:1.35;">${inlineMd(e.title, st)}</td>
${e.effort ? `<td align="right" valign="middle" style="white-space:nowrap;padding-left:8px;"><span style="display:inline-block;padding:3px 10px;border-radius:99px;background:${bg};color:${fg};font-size:12px;font-weight:600;">${e.effort} · ${EFFORTS[e.effort]}</span></td>` : ''}
</tr></table>
</td></tr>
<tr><td style="padding:4px 18px 8px 54px;">${md(e.body)}</td></tr>
</table>`;
}).join('') : md(markdown);
return mailLayout({
title: `${count} évolution${count > 1 ? 's' : ''} pour ${projectName}`,
subtitle: 'Classées de la plus rentable à la moins rentable',
preheader: items.slice(0, 3).map((e) => e.title).join(' · '),
content, appUrl, cta: 'Ouvrir le panel',
});
}
const pct = (a, b) => (b ? `${Math.round((a / b) * 100)} %` : '–');
// Tuiles par 2 : tient sur un écran de téléphone sans défilement horizontal
function kpiCells(cells) {
const tile = ([label, value, sub]) => `<td width="50%" valign="top" style="padding:4px;">
<div style="border:1px solid ${C.line};border-radius:10px;padding:12px 12px 10px;">
<div style="font-size:12px;color:${C.muted};">${esc(label)}</div>
<div style="font-size:22px;font-weight:700;color:${C.text};line-height:1.3;white-space:nowrap;">${esc(value)}</div>
${sub ? `<div style="font-size:12px;color:${C.muted};">${esc(sub)}</div>` : ''}
</div></td>`;
const rows = [];
for (let i = 0; i < cells.length; i += 2) rows.push(`<tr>${cells.slice(i, i + 2).map(tile).join('')}</tr>`);
return `<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="margin:0 0 20px;">${rows.join('')}</table>`;
}
/** Rapport hebdo : totaux en tuiles, puis un tableau par projet actif. */
export function weeklyMail(st, { period, appUrl }) {
const t = st.totals;
const usd = (n) => `${n.toFixed(2)} $`;
const active = st.projects.filter((p) => p.found || p.sent || p.followups || p.replies || p.cost);
const quiet = st.projects.filter((p) => !active.includes(p));
const row = (label, value, strong = false) => `<tr>
<td style="padding:7px 0;border-top:1px solid ${C.line};font-size:14px;color:${C.muted};">${esc(label)}</td>
<td align="right" style="padding:7px 0;border-top:1px solid ${C.line};font-size:14px;color:${C.text};${strong ? 'font-weight:700;' : ''}">${esc(value)}</td></tr>`;
const projects = active.map((p) => `<div style="margin:0 0 18px;">
<div style="font-size:16px;font-weight:700;color:${C.text};margin:0 0 4px;">${esc(p.name)}</div>
<table role="presentation" width="100%" cellpadding="0" cellspacing="0">
${row('Prospects trouvés', String(p.found))}
${row('Mails envoyés', `${p.sent}${p.followups ? ` + ${p.followups} relance(s)` : ''}`)}
${row('Réponses', `${p.replies} (${pct(p.replies, p.sent)})`, true)}
${row('Clients (total)', String(p.clients))}
${p.bounces ? row('Adresses invalides', String(p.bounces)) : ''}
${p.bestSubject ? row('Test A/B', `objet ${p.bestSubject.variant} gagnant (${pct(p.bestSubject.replied, p.bestSubject.sent)})`) : ''}
${row('Coût IA', usd(p.cost))}
</table></div>`).join('');
const content = `${kpiCells([
['Prospects', String(t.found), 'trouvés'],
['Mails', String(t.sent), t.followups ? `+ ${t.followups} relance(s)` : 'envoyés'],
['Réponses', String(t.replies), pct(t.replies, t.sent)],
['Coût IA', usd(t.cost), 'équivalent API'],
])}
${projects || `<p style="${MD_STYLES.p}">Aucune activité cette semaine.</p>`}
${quiet.length ? `<p style="margin:0 0 16px;font-size:13px;color:${C.muted};">Sans activité : ${quiet.map((p) => esc(p.name)).join(', ')}.</p>` : ''}`;
return mailLayout({
title: 'Rapport hebdo', subtitle: period,
preheader: `${t.sent} mails, ${t.replies} réponses (${pct(t.replies, t.sent)}), ${t.found} prospects trouvés`,
content, appUrl, cta: 'Ouvrir le panel',
});
}
const linkify = (escaped) => escaped.replace(/https?:\/\/[^\s<]+[^\s<.,;:!?)]/g, (u) => `<a href="${u}" style="color:${C.accent};">${u}</a>`);
/**
* Mail de prospection : volontairement sobre, comme un mail écrit à la main
* (pas de bannière ni d'images : c'est ce qui passe le mieux les filtres anti-spam).
*/
export function prospectHtml({ body, notice, unsubUrl }) {
const paras = String(body).split(/\n{2,}/).map((p) => p.trim()).filter(Boolean)
.map((p) => `<p style="margin:0 0 14px;">${linkify(esc(p)).replace(/\n/g, '<br>')}</p>`).join('\n');
return `<!doctype html>
<html lang="fr"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"></head>
<body style="margin:0;padding:0;background:#ffffff;">
<div style="max-width:600px;margin:0 auto;padding:20px 18px;font-family:${FONT};font-size:15px;line-height:1.6;color:#1f2328;">
${paras}
<div style="margin-top:28px;padding-top:12px;border-top:1px solid #eceef1;font-size:12px;line-height:1.5;color:#8a9099;">
${esc(notice)}<br><a href="${esc(unsubUrl)}" style="color:#8a9099;">Ne plus recevoir de messages</a>
</div>
</div>
</body></html>`;
}

115
src/services/markdown.js Normal file
View file

@ -0,0 +1,115 @@
// Mini rendu Markdown (le sous-ensemble que Claude produit) sans dépendance.
// Tout le texte est échappé AVANT la mise en forme : le contenu vient d'un repo et du web, jamais de HTML brut.
import { esc } from '../http.js';
const noStyle = () => '';
/** Gras, italique, code et liens http(s) sur une ligne. `st(tag)` ajoute un style inline (mails). */
export function inlineMd(text, st = noStyle) {
const codes = [];
let out = esc(text).replace(/`([^`]+)`/g, (_, c) => { codes.push(c); return `\u0000${codes.length - 1}\u0000`; });
out = out
.replace(/\*\*([^*]+)\*\*/g, (_, t) => `<strong${st('strong')}>${t}</strong>`)
.replace(/(^|[^*\w])\*([^*\s][^*]*)\*(?!\w)/g, (_, p, t) => `${p}<em>${t}</em>`)
.replace(/\[([^\]]+)\]\((https?:\/\/[^)\s]+)\)/g, (_, t, u) => `<a href="${u}"${st('a')} target="_blank" rel="noopener noreferrer">${t}</a>`);
return out.replace(/\u0000(\d+)\u0000/g, (_, i) => `<code${st('code')}>${codes[i]}</code>`);
}
/**
* Titres, paragraphes, listes (un niveau d'imbrication), citations, blocs de code, séparateurs.
* @param {string} md
* @param {{styles?: Record<string,string>}} [o] styles inline par balise (pour les clients mail)
*/
export function renderMarkdown(md, { styles = {} } = {}) {
const st = (tag) => (styles[tag] ? ` style="${styles[tag]}"` : '');
const lines = String(md ?? '').replace(/\r\n?/g, '\n').split('\n');
const out = [];
let para = [];
let list = null; // { type: 'ul'|'ol', items: [{ text, sub: [] }] }
const flushPara = () => {
if (para.length) out.push(`<p${st('p')}>${inlineMd(para.join(' '), st)}</p>`);
para = [];
};
const flushList = () => {
if (!list) return;
const items = list.items.map((i) => `<li${st('li')}>${inlineMd(i.text, st)}${i.sub.length
? `<ul${st('ul')}>${i.sub.map((s) => `<li${st('li')}>${inlineMd(s, st)}</li>`).join('')}</ul>` : ''}</li>`).join('');
out.push(`<${list.type}${st(list.type)}>${items}</${list.type}>`);
list = null;
};
const flush = () => { flushPara(); flushList(); };
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
let m;
if (/^\s*```/.test(line)) {
flush();
const code = [];
while (++i < lines.length && !/^\s*```/.test(lines[i])) code.push(lines[i]);
out.push(`<pre${st('pre')}><code>${esc(code.join('\n'))}</code></pre>`);
} else if (!line.trim()) {
flush();
} else if ((m = /^(#{1,6})\s+(.*?)\s*#*\s*$/.exec(line))) {
flush();
const n = m[1].length;
out.push(`<h${n}${st(`h${n}`)}>${inlineMd(m[2], st)}</h${n}>`);
} else if (/^\s*([-*_])(\s*\1){2,}\s*$/.test(line)) {
flush();
out.push(`<hr${st('hr')}>`);
} else if (list && (m = /^\s{2,}[-*+]\s+(.*)$/.exec(line))) {
list.items.at(-1).sub.push(m[1]);
} else if ((m = /^\s*([-*+]|\d+[.)])\s+(.*)$/.exec(line))) {
flushPara();
const type = /\d/.test(m[1]) ? 'ol' : 'ul';
if (list?.type !== type) { flushList(); list = { type, items: [] }; }
list.items.push({ text: m[2], sub: [] });
} else if ((m = /^>\s?(.*)$/.exec(line))) {
flush();
out.push(`<blockquote${st('blockquote')}>${inlineMd(m[1], st)}</blockquote>`);
} else if (list && /^\s{2,}\S/.test(line)) {
const last = list.items.at(-1);
if (last.sub.length) last.sub[last.sub.length - 1] += ` ${line.trim()}`;
else last.text += ` ${line.trim()}`;
} else {
flushList();
para.push(line.trim());
}
}
flush();
return out.join('\n');
}
/** Découpe la réponse « Évolution » (### N. Titre + puces) en fiches. [] si le format n'est pas reconnu. */
export function parseEvolutions(md) {
const parts = String(md ?? '').replace(/\r\n?/g, '\n').split(/^###\s+/m);
parts.shift(); // texte avant le premier titre (normalement vide)
return parts.map((p, idx) => {
const [head, ...rest] = p.split('\n');
const m = /^(\d+)[.)]\s*(.*)$/.exec(head.trim());
let effort = null, effortNote = '';
// [ \t] et pas \s : sinon la ligne suivante serait avalée comme « note » de l'effort
const body = rest.join('\n').replace(/^[ \t]*[-*][ \t]*\*\*Effort\*\*[ \t]*:?[ \t]*\**[ \t]*([SML])\b\**[ \t]*(.*)(?:\n|$)/mi, (_, e, note) => {
effort = e.toUpperCase();
effortNote = note.replace(/^[\s()–—-]+|[\s()]+$/g, '');
return '';
}).trim();
return { n: m ? Number(m[1]) : idx + 1, title: (m ? m[2] : head).trim(), effort, effortNote, body };
}).filter((e) => e.title);
}
export const EFFORTS = { S: 'Rapide', M: 'Moyen', L: 'Gros chantier' };
/** Fiches d'évolution pour le panel (classes CSS, pas de style inline : CSP stricte). */
export function evolutionHtml(md) {
const items = parseEvolutions(md);
if (!items.length) return `<div class="md">${renderMarkdown(md)}</div>`;
return `<ol class="evos">${items.map((e) => `<li class="evo">
<div class="evo-head">
<span class="evo-n">${e.n}</span>
<h5>${inlineMd(e.title)}</h5>
${e.effort ? `<span class="effort e-${e.effort}"${e.effortNote ? ` title="${esc(e.effortNote)}"` : ''}>${e.effort} · ${EFFORTS[e.effort]}</span>` : ''}
</div>
<div class="md">${renderMarkdown(e.body)}</div>
</li>`).join('')}</ol>`;
}

View file

@ -1,6 +1,7 @@
// Notifications Discord via webhook (pas de bot, pas de process permanent : une requête HTTP).
import { getSetting } from '../db.js';
import { decrypt } from '../crypto.js';
import { parseEvolutions, EFFORTS } from './markdown.js';
// Uniquement de vraies URLs de webhook Discord : jamais d'envoi vers une adresse arbitraire
export const WEBHOOK_RE = /^https:\/\/(?:canary\.|ptb\.)?discord(?:app)?\.com\/api\/webhooks\/\d{5,25}\/[\w-]{20,120}$/;
@ -17,6 +18,18 @@ export const EVENTS = {
};
const COLORS = { ok: 0x15803d, info: 0x2f5bea, warn: 0xb45309, error: 0xb91c1c };
const ICONS = { ok: '✅', info: '🔷', warn: '⚠️', error: '⛔' };
const FOOTERS = {
job_done: 'Job terminé', job_error: 'Job en échec', reply: 'Réponse prospect', followup: 'Relances',
thermal: 'Température', budget: 'Budget IA', quota: 'Quota Claude', weekly: 'Rapport hebdo', test: 'Test',
};
/** Barre de progression en caractères (Discord n'affiche pas d'images inline dans un embed sans hébergement). */
export function bar(done, total, width = 12) {
const r = total ? Math.max(0, Math.min(1, done / total)) : 0;
const full = Math.round(r * width);
return `${'▰'.repeat(full)}${'▱'.repeat(width - full)} ${Math.round(r * 100)} %`;
}
export function notifyConfig(app) {
let url = null;
@ -28,20 +41,22 @@ export function notifyConfig(app) {
}
/** 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 = [] }, { force = false } = {}) {
export async function notify(app, event, { title, description = '', level = 'info', fields = [], footer }, { force = false } = {}) {
const { url, events } = notifyConfig(app);
if (!url || (!force && !events.includes(event))) return false;
const body = {
username: 'AiTools',
allowed_mentions: { parse: [] }, // un "@everyone" dans un nom d'entreprise ne pingera personne
embeds: [{
author: { name: `${ICONS[level] ?? ICONS.info} AiTools`, ...(app.cfg.appUrl ? { url: app.cfg.appUrl } : {}) },
title: String(title).slice(0, 256),
description: String(description).slice(0, 4000),
color: COLORS[level] ?? COLORS.info,
fields: fields.slice(0, 10).map((f) => ({
fields: fields.slice(0, 25).map((f) => ({
name: String(f.name).slice(0, 256), value: String(f.value ?? '-').slice(0, 1024) || '-', inline: f.inline ?? true,
})),
url: app.cfg.appUrl || undefined,
footer: { text: String(footer || FOOTERS[event] || 'AiTools').slice(0, 200) },
timestamp: new Date().toISOString(),
}],
};
@ -58,28 +73,72 @@ export async function notify(app, event, { title, description = '', level = 'inf
}
}
const duration = (s) => (s < 60 ? `${s} s` : s < 3600 ? `${Math.round(s / 60)} min` : `${Math.floor(s / 3600)} h ${Math.round((s % 3600) / 60)} min`);
// Fin de job → notif (seulement pour les jobs longs, ceux qu'on lance et qu'on oublie)
const DONE = {
analyze: () => ({ title: 'Fiche projet à jour', level: 'ok' }),
prospect: (r) => ({ title: 'Recherche de prospects terminée', description: `${r?.found ?? 0} nouveau(x) prospect(s) sur ${r?.requested ?? '?'} demandés.`, level: 'ok' }),
send: (r) => ({ title: 'Envoi terminé', description: `${r?.sent ?? 0} mail(s) envoyé(s), ${r?.failed ?? 0} échec(s).`, level: r?.failed ? 'warn' : 'ok' }),
evolution: (r) => ({ title: 'Évolutions prêtes', description: `Envoyées à ${r?.sentTo ?? 'ta boîte'}.`, level: 'ok' }),
analyze: (r) => ({
title: 'Fiche projet à jour', level: 'ok',
description: 'Le code a été relu : la fiche et la cible proposée sont prêtes à valider dans le panel.',
fields: r?.commit ? [{ name: 'Commit', value: `\`${String(r.commit).slice(0, 8)}\`` }] : [],
}),
prospect: (r) => ({
title: 'Recherche de prospects terminée', level: 'ok',
description: `${r?.found ?? 0} nouveau(x) prospect(s) sur ${r?.requested ?? '?'} demandés.\n${bar(r?.found ?? 0, r?.requested ?? 0)}`,
fields: [
{ name: '🔎 Trouvés', value: `**${r?.found ?? 0}**` },
{ name: '🎯 Demandés', value: String(r?.requested ?? '?') },
],
}),
send: (r) => ({
title: 'Envoi terminé', level: r?.failed ? 'warn' : 'ok',
description: `${r?.sent ?? 0} mail(s) envoyé(s), ${r?.failed ?? 0} échec(s).\n${bar(r?.sent ?? 0, r?.total ?? 0)}`,
fields: [
{ name: '✉️ Envoyés', value: `**${r?.sent ?? 0}**` },
{ name: '❌ Échecs', value: String(r?.failed ?? 0) },
],
}),
evolution: (r) => {
const items = parseEvolutions(r?.markdown);
return {
title: 'Évolutions prêtes', level: 'ok',
description: `Envoyées à ${r?.sentTo ?? 'ta boîte'}.${items.length ? `\n\n${items.slice(0, 10).map((e) => `**${e.n}.** ${e.title}${e.effort ? ` · \`${e.effort} ${EFFORTS[e.effort].toLowerCase()}\`` : ''}`).join('\n')}` : ''}`,
};
},
};
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) {
if (!job.id) return [];
const row = 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;
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`, description: String(error || '').slice(0, 500), level: '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),
});
}
if (status !== 'done') return Promise.resolve(false);
if (job.type === 'followup') {
if (!result?.sent) return Promise.resolve(false);
return notify(app, 'followup', { title: `${prefix}Relances envoyées`, description: `${result.sent} relance(s), ${result.failed} échec(s).`, level: 'info' });
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);
const n = make(result);
return notify(app, 'job_done', { ...n, title: `${prefix}${n.title}` });
return notify(app, 'job_done', { ...n, title: `${prefix}${n.title}`, footer, fields: [...(n.fields || []), ...jobMeta(app, job)] });
}

View file

@ -3,6 +3,7 @@ import { now, getSetting, setSetting } from '../db.js';
import { abStats, globalSmtp } from '../projects.js';
import { createTransport } from './mailer.js';
import { notify } from './notify.js';
import { weeklyMail } from './mailhtml.js';
import { parisParts, parisTime } from './paris-time.js';
const pct = (a, b) => (b ? `${Math.round((a / b) * 100)} %` : '-');
@ -62,19 +63,28 @@ export async function sendWeeklyReport(app, { at = now() } = {}) {
if (to && smtp) {
const transport = (app.createTransport || createTransport)(smtp);
try {
await transport.sendMail({ from: smtp.fromEmail, to, subject: `[AiTools] Rapport du ${day(st.from)} au ${day(st.to)}`, text });
await transport.sendMail({
from: smtp.fromEmail, to, subject: `[AiTools] Rapport du ${day(st.from)} au ${day(st.to)}`, text,
html: weeklyMail(st, { period: `Semaine du ${day(st.from)} au ${day(st.to)}`, appUrl: app.cfg.appUrl }),
});
channels.push('mail');
} finally { transport.close(); }
}
const t = st.totals;
const active = st.projects.filter((p) => p.sent || p.found || p.replies);
const ok = await notify(app, 'weekly', {
title: `Rapport hebdo · ${day(st.from)} → ${day(st.to)}`, level: 'info',
description: st.projects.filter((p) => p.sent || p.found || p.replies)
.map((p) => `**${p.name}** : ${p.found} trouvés · ${p.sent} envoyés · ${p.replies} réponses`).join('\n') || 'Rien cette semaine.',
description: active.length
? `**${t.sent}** mails · **${t.replies}** réponses (${pct(t.replies, t.sent)}) · **${t.found}** prospects trouvés`
: 'Rien cette semaine.',
fields: [
{ name: 'Réponses', value: `${t.replies} (${pct(t.replies, t.sent)})` },
{ name: 'Relances', value: String(t.followups) },
{ name: 'Coût IA', value: usd(t.cost) },
{ name: '💬 Réponses', value: `**${t.replies}** (${pct(t.replies, t.sent)})` },
{ name: '🔁 Relances', value: String(t.followups) },
{ name: '💳 Coût IA', value: usd(t.cost) },
...active.slice(0, 21).map((p) => ({
name: `📁 ${p.name}`, inline: false,
value: `🔎 ${p.found} trouvés · ✉️ ${p.sent} envoyés · 💬 ${p.replies} réponses (${pct(p.replies, p.sent)})${p.bestSubject ? ` · 🏆 objet ${p.bestSubject.variant}` : ''}`,
})),
],
});
if (ok) channels.push('discord');

View file

@ -3,6 +3,28 @@ import { STATUSES } from './services/crm.js';
const fmtDate = (ts) => (ts ? new Date(ts * 1000).toLocaleString('fr-FR', { dateStyle: 'short', timeStyle: 'short', timeZone: 'Europe/Paris' }) : '—');
// Icônes en SVG inline (attributs de présentation uniquement : compatible avec la CSP sans style inline)
const svg = (d) => `<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">${d}</svg>`;
const ICONS = {
target: svg('<circle cx="12" cy="12" r="9"/><circle cx="12" cy="12" r="5"/><circle cx="12" cy="12" r="1"/>'),
search: svg('<circle cx="11" cy="11" r="7"/><path d="m20 20-3.5-3.5"/>'),
spark: svg('<path d="M12 3v3M12 18v3M3 12h3M18 12h3M5.6 5.6l2.1 2.1M16.3 16.3l2.1 2.1M5.6 18.4l2.1-2.1M16.3 7.7l2.1-2.1"/><circle cx="12" cy="12" r="3"/>'),
chart: svg('<path d="M4 20V10M10 20V4M16 20v-7M22 20H2"/>'),
mail: svg('<rect x="3" y="5" width="18" height="14" rx="2"/><path d="m3 7 9 6 9-6"/>'),
send: svg('<path d="M22 2 11 13"/><path d="M22 2 15 22l-4-9-9-4z"/>'),
repeat: svg('<path d="M17 2l4 4-4 4"/><path d="M3 11V9a3 3 0 0 1 3-3h15"/><path d="M7 22l-4-4 4-4"/><path d="M21 13v2a3 3 0 0 1-3 3H3"/>'),
users: svg('<circle cx="9" cy="8" r="4"/><path d="M2 21a7 7 0 0 1 14 0"/><path d="M16 4a4 4 0 0 1 0 8M22 21a7 7 0 0 0-4-6.3"/>'),
gear: svg('<circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.7 1.7 0 0 0 .3 1.8l.1.1a2 2 0 1 1-2.8 2.8l-.1-.1a1.7 1.7 0 0 0-1.8-.3 1.7 1.7 0 0 0-1 1.5V21a2 2 0 1 1-4 0v-.1a1.7 1.7 0 0 0-1.1-1.5 1.7 1.7 0 0 0-1.8.3l-.1.1a2 2 0 1 1-2.8-2.8l.1-.1a1.7 1.7 0 0 0 .3-1.8 1.7 1.7 0 0 0-1.5-1H3a2 2 0 1 1 0-4h.1a1.7 1.7 0 0 0 1.5-1.1 1.7 1.7 0 0 0-.3-1.8l-.1-.1a2 2 0 1 1 2.8-2.8l.1.1a1.7 1.7 0 0 0 1.8.3H9a1.7 1.7 0 0 0 1-1.5V3a2 2 0 1 1 4 0v.1a1.7 1.7 0 0 0 1 1.5 1.7 1.7 0 0 0 1.8-.3l.1-.1a2 2 0 1 1 2.8 2.8l-.1.1a1.7 1.7 0 0 0-.3 1.8V9a1.7 1.7 0 0 0 1.5 1H21a2 2 0 1 1 0 4h-.1a1.7 1.7 0 0 0-1.5 1z"/>'),
};
/** Section dépliable animée. `title` peut contenir du HTML de confiance (badges), jamais de donnée utilisateur brute. */
function acc(key, icon, title, sub, body, { open = false, cls = '' } = {}) {
return `<details class="acc anim ${cls}" data-acc="${key}"${open ? ' open' : ''}>
<summary><span class="acc-ico">${ICONS[icon]}</span><span class="acc-txt"><span class="acc-title">${title}</span>${sub ? `<span class="acc-sub">${sub}</span>` : ''}</span><span class="chev" aria-hidden="true"></span></summary>
<div class="acc-body">${body}</div>
</details>`;
}
export function layout({ title, body, email }) {
return `<!doctype html>
<html lang="fr">
@ -15,9 +37,17 @@ export function layout({ title, body, email }) {
<script src="/static/app.js" defer></script>
</head>
<body>
<canvas id="bg" aria-hidden="true"></canvas>
${email ? `<header class="top">
<a class="brand" href="/">AiTools</a>
<a class="brand" href="/"><span class="logo" aria-hidden="true"></span>AiTools</a>
<div class="sys" id="sys" aria-live="polite"></div>
<div class="jobs" id="jobs" hidden>
<button type="button" class="jobs-btn" aria-expanded="false" aria-controls="jobs-pop"><span class="spin-inline"></span><span data-jobs-count></span><span class="chev" aria-hidden="true"></span></button>
<div class="jobs-pop" id="jobs-pop" role="region" aria-label="Jobs en cours" hidden>
<div class="jobs-head"><strong>Activité</strong><span class="muted small" data-jobs-sub></span></div>
<div data-jobs-list></div>
</div>
</div>
<nav><a href="/settings">Réglages</a>
<form method="post" action="/logout"><button class="link">Déconnexion</button></form></nav>
</header>` : ''}
@ -42,7 +72,6 @@ function targetForm(p) {
const t = p.target || {};
const list = (a) => esc((a || []).join('\n'));
return `<form class="target" data-action="target" data-id="${p.id}">
<h4>Cible ${p.targetValidated ? '<span class="badge ok">validée</span>' : '<span class="badge warn">à valider</span>'}</h4>
<label>Description<input name="description" value="${esc(t.description)}"></label>
<div class="grid3">
<label>Zone<input name="zone" value="${esc(t.zone)}"></label>
@ -58,8 +87,7 @@ function targetForm(p) {
}
function configForms(p, smtp, dbCfg, imap) {
return `<details class="config"><summary>Configuration du projet</summary>
<form data-action="smtp" data-id="${p.id}" class="cfg">
return `<form data-action="smtp" data-id="${p.id}" class="cfg">
<h4>SMTP d'envoi</h4>
<div class="grid3">
<label>Hôte<input name="host" value="${esc(smtp.host)}" required></label>
@ -102,8 +130,7 @@ function configForms(p, smtp, dbCfg, imap) {
</form>
<form data-action="delete" data-id="${p.id}" data-confirm="Supprimer ${esc(p.name)} et tous ses prospects ?" class="cfg">
<button class="btn danger">Supprimer le projet</button>
</form>
</details>`;
</form>`;
}
function templateForm(p, kind) {
@ -126,7 +153,7 @@ function templateForm(p, kind) {
function projectItem(p, smtp, dbCfg, imap) {
const profile = p.profile;
return `<details class="project card" data-id="${p.id}">
return `<details class="project card anim" data-id="${p.id}">
<summary><span class="pname">${esc(p.name)}</span><span class="pstate" data-state></span></summary>
<div class="pbody">
<label>Dépôt Git<input class="locked" value="${esc(p.gitUrl)}" readonly disabled></label>
@ -141,34 +168,33 @@ function projectItem(p, smtp, dbCfg, imap) {
: '<p class="muted">Pas encore analysé.</p>'}
</section>
${profile ? targetForm(p) : ''}
${profile ? acc('target', 'target',
`Cible ${p.targetValidated ? '<span class="badge ok">validée</span>' : '<span class="badge warn">à valider</span>'}`,
esc((p.target?.description || '').slice(0, 120)), targetForm(p), { open: !p.targetValidated, cls: 'target-acc' }) : ''}
<div class="actions">
<button class="btn primary" data-panel="prospect">Prospecter</button>
<button class="btn" data-panel="evolution">Évolution</button>
<button class="btn" data-panel="recap">Récapitulatif</button>
</div>
<section class="panel" data-panel-body="prospect" hidden>
<div class="accs">
${acc('prospect', 'search', 'Prospecter', 'Recherche, modèle de mail, envoi, relances et CRM', `
${acc('search', 'search', 'Recherche de prospects', 'Claude cherche des entreprises qui collent à la cible', `
<form data-action="prospect" data-id="${p.id}" class="inline">
<label>Prospects à chercher<input name="count" type="number" min="1" max="50" value="10"></label>
<label>Quand<select name="when"><option value="now">Maintenant</option><option value="night">Cette nuit (1h-6h)</option></select></label>
<button class="btn primary">Lancer la recherche</button>
</form>
<div class="job" data-job="prospect"></div>
<div class="job" data-job="prospect"></div>`, { open: true, cls: 'sub' })}
${templateForm(p, 'initial')}
${acc('template', 'mail', 'Modèle de mail', 'Objet, test A/B et corps du premier mail', templateForm(p, 'initial'), { cls: 'sub' })}
${acc('send', 'send', 'Envoi', 'Envoi par lots, boîte de réception et test A/B', `
<form data-action="send" data-id="${p.id}" class="inline send">
<label>Mails à envoyer<input name="count" type="number" min="1" value="10"></label>
<button class="btn primary" disabled>Envoyer</button>
<span class="muted small" data-send-info></span>
</form>
<div class="job" data-job="send"></div>
<p class="inbox small" data-inbox></p>
<p class="inbox small" data-inbox></p>`, { cls: 'sub' })}
${acc('followup', 'repeat', 'Relance automatique', 'Une relance dans le même fil après quelques jours', `
<section class="followup">
<h4>Relance automatique</h4>
<form data-action="followup" data-id="${p.id}" class="inline">
<label class="check"><input type="checkbox" name="enabled" ${p.followupEnabled ? 'checked' : ''}> Relancer une fois les prospects sans réponse</label>
<label>Après (jours)<input name="days" type="number" min="2" max="30" value="${p.followupDays}"></label>
@ -177,9 +203,9 @@ function projectItem(p, smtp, dbCfg, imap) {
<p class="muted small" data-followup-info></p>
${templateForm(p, 'followup')}
<div class="job" data-job="followup"></div>
</section>
</section>`, { cls: 'sub' })}
<details class="prospects"><summary>Prospects <span data-count></span></summary>
${acc('prospects', 'users', 'Prospects <span data-count></span>', 'Recherche, filtres, fiches, import et export CSV', `
<form class="pfilters" data-filters>
<input type="search" name="q" placeholder="Rechercher : entreprise, email, ville, secteur" aria-label="Rechercher">
<select name="status" aria-label="Statut"><option value="">Tous les statuts</option>${Object.entries(STATUSES).map(([k, l]) => `<option value="${k}">${l}</option>`).join('')}</select>
@ -194,11 +220,10 @@ function projectItem(p, smtp, dbCfg, imap) {
</div>
<div data-import-report></div>
<div data-prospects></div>
<div class="pager" data-pager></div>
</details>
</section>
<div class="pager" data-pager></div>`, { cls: 'sub prospects' })}
`, { cls: 'main' })}
<section class="panel" data-panel-body="evolution" hidden>
${acc('evolution', 'spark', 'Évolution', 'Idées de fonctionnalités tirées du code, envoyées par mail', `
<form data-action="evolution" data-id="${p.id}" class="inline">
<label>Nombre d'évolutions<input name="count" type="number" min="1" max="20" value="5"></label>
<label>Raisonnement<select name="level">
@ -209,14 +234,13 @@ function projectItem(p, smtp, dbCfg, imap) {
<label>Quand<select name="when"><option value="now">Maintenant</option><option value="night">Cette nuit (1h-6h)</option></select></label>
<button class="btn primary">Chercher et envoyer par mail</button>
</form>
<div class="job" data-job="evolution"></div>
</section>
<div class="job" data-job="evolution"></div>`, { cls: 'main' })}
<section class="panel" data-panel-body="recap" hidden>
<div class="recap" data-recap><p class="muted">Chargement…</p></div>
</section>
${acc('recap', 'chart', 'Récapitulatif', 'Chiffres business, prospection et courbes', `
<div class="recap" data-recap><p class="muted">Chargement…</p></div>`, { cls: 'main' })}
</div>
${configForms(p, smtp, dbCfg, imap)}
${acc('config', 'gear', 'Configuration du projet', 'SMTP, boîte IMAP, base de données', configForms(p, smtp, dbCfg, imap), { cls: 'config' })}
</div>
</details>`;
}
@ -227,7 +251,7 @@ export function dashboardPage({ email, projects, forgejoHost }) {
body: `<div class="row head">
<h1>Projets</h1>
</div>
<details class="card new">
<details class="card new anim">
<summary class="btn primary">+ Nouveau projet</summary>
<form data-action="create" class="cfg">
<label>Nom<input name="name" required maxlength="80"></label>

View file

@ -80,6 +80,8 @@ test('flux complet : analyse → cible → prospection → modèle → envoi →
assert.equal(mail.subject, 'Idée pour Boulangerie Le Fournil');
assert.match(mail.text, /Bonjour Boulangerie Le Fournil à Rennes/);
assert.match(mail.text, /fournil\.fr\/contact/);
assert.match(mail.html, /Bonjour Boulangerie Le Fournil à Rennes/);
assert.match(mail.html, /Ne plus recevoir de messages/);
const unsub = /\/u\/([^/]+)\/(\S+)/.exec(mail.headers['List-Unsubscribe']);
assert.ok(verifyUnsubToken(s.app.cfg.secretKey, decodeURIComponent(unsub[1]), unsub[2].replace('>', '')));
assert.equal(prospectStats(s.db, s.id).sent, 1);
@ -94,6 +96,9 @@ test('flux complet : analyse → cible → prospection → modèle → envoi →
assert.equal(ev.status, 'done', ev.error);
assert.equal(s.sentMails.at(-1).to, 'moi@x.fr');
assert.match(s.sentMails.at(-1).text, /Export CSV/);
assert.match(s.sentMails.at(-1).html, /class|style/, 'version HTML mise en forme');
assert.match(s.sentMails.at(-1).html, /Export CSV/);
assert.equal(ev.progress.pct, 95, 'avancement remonté jusqu\'au mail');
const usage = s.db.prepare('SELECT SUM(cost_usd) c FROM jobs').get().c;
assert.ok(usage > 0);

View file

@ -174,6 +174,11 @@ test('« Cette nuit » programme le job au prochain créneau 1h-6h', async () =>
assert.ok(p.hour >= 1 && p.hour < 6, `démarrage à ${p.hour}h`);
const sys = await (await get('/api/system')).json();
assert.ok(job.run_after > now() ? sys.scheduled >= 1 : true);
// Le menu « jobs » de la barre du haut reçoit le détail, avec le nom du projet
const listed = sys.jobs.find((j) => j.type === 'evolution');
assert.equal(listed.status, 'queued');
assert.equal(listed.projectId, id);
assert.ok(listed.project);
});
test('réglages Discord : URL validée, chiffrée, événements enregistrés', async () => {

61
test/markdown.test.js Normal file
View file

@ -0,0 +1,61 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { renderMarkdown, parseEvolutions, evolutionHtml } from '../src/services/markdown.js';
import { evolutionMail, prospectHtml } from '../src/services/mailhtml.js';
import { bar } from '../src/services/notify.js';
const EVOS = `### 1. Export CSV des clients
- **Pourquoi** : les commerçants veulent leurs données dans Excel.
- **Effort** : S
- **Pistes techniques** :
- route \`GET /export\` dans \`src/routes.js\`
- réutiliser le module csv
### 2. Rappels par SMS
- **Pourquoi** : *beaucoup* plus lu qu'un mail.
- **Effort** : L (fournisseur à intégrer)`;
test('markdown : titres, listes imbriquées, gras, code', () => {
const h = renderMarkdown('## Titre\n\nUn **gras** et `code`.\n\n- a\n - a1\n- b\n\n1. un\n2. deux');
assert.match(h, /<h2>Titre<\/h2>/);
assert.match(h, /<p>Un <strong>gras<\/strong> et <code>code<\/code>\.<\/p>/);
assert.match(h, /<ul><li>a<ul><li>a1<\/li><\/ul><\/li><li>b<\/li><\/ul>/);
assert.match(h, /<ol><li>un<\/li><li>deux<\/li><\/ol>/);
});
test('markdown : le HTML et les liens dangereux ne passent jamais', () => {
const h = renderMarkdown('<img src=x onerror=alert(1)> [clic](javascript:alert(1)) [ok](https://a.fr/?a=1&b=2) **<script>**');
assert.doesNotMatch(h, /<img|<script|href="javascript/i);
assert.match(h, /&lt;img/);
assert.match(h, /<a href="https:\/\/a\.fr\/\?a=1&amp;b=2" target="_blank" rel="noopener noreferrer">ok<\/a>/);
assert.doesNotMatch(renderMarkdown('```\n<b>x</b>\n```'), /<b>/);
});
test('évolutions : découpage en fiches avec effort', () => {
const e = parseEvolutions(EVOS);
assert.equal(e.length, 2);
assert.deepEqual([e[0].n, e[0].title, e[0].effort], [1, 'Export CSV des clients', 'S']);
assert.equal(e[1].effort, 'L');
assert.equal(e[1].effortNote, 'fournisseur à intégrer');
assert.doesNotMatch(e[0].body, /Effort/, 'l\'effort passe en pastille, pas dans le corps');
const h = evolutionHtml(EVOS);
assert.match(h, /<span class="effort e-S">S · Rapide<\/span>/);
assert.match(h, /<li><strong>Pistes techniques<\/strong> :<ul><li>route <code>GET \/export<\/code>/);
assert.match(evolutionHtml('Pas de titres ici'), /<div class="md"><p>Pas de titres ici<\/p><\/div>/, 'format inconnu : rendu simple');
});
test('mails HTML : évolutions en cartes, prospection sobre avec désinscription', () => {
const m = evolutionMail({ markdown: EVOS, projectName: 'MonEspacePro', count: 2, appUrl: 'https://ai.test' });
assert.match(m, /2 évolutions pour MonEspacePro/);
assert.match(m, /S · Rapide/);
assert.match(m, /href="https:\/\/ai\.test"/);
const p = prospectHtml({ body: 'Bonjour <b>Fournil</b>,\n\nVoir https://monespacepro.fr.\nÀ bientôt', notice: 'Adresse publique.', unsubUrl: 'https://ai.test/u/x/y' });
assert.match(p, /Bonjour &lt;b&gt;Fournil&lt;\/b&gt;,/);
assert.match(p, /<a href="https:\/\/monespacepro\.fr" [^>]*>https:\/\/monespacepro\.fr<\/a>\.<br>À bientôt/);
assert.match(p, /href="https:\/\/ai\.test\/u\/x\/y"/);
});
test('barre de progression Discord', () => {
assert.equal(bar(7, 10, 10), '▰▰▰▰▰▰▰▱▱▱ 70 %');
assert.equal(bar(0, 0, 4), '▱▱▱▱ 0 %');
});

View file

@ -64,7 +64,10 @@ test('envoi automatique : lundi 8h, une seule fois par semaine, désactivé par
assert.deepEqual(r.channels, ['mail', 'discord']);
assert.equal(s.mails[0].to, 'moi@x.fr');
assert.match(s.mails[0].subject, /^\[AiTools\] Rapport du/);
assert.match(s.hooks[0].embeds[0].description, /\*\*MonEspacePro\*\* : 20 trouvés · 20 envoyés · 6 réponses/);
const field = s.hooks[0].embeds[0].fields.find((f) => f.name === '📁 MonEspacePro');
assert.match(field.value, /20 trouvés · ✉️ 20 envoyés · 💬 6 réponses \(30 %\)/);
assert.match(s.mails[0].html, /Rapport hebdo/);
assert.match(s.mails[0].html, /MonEspacePro/);
assert.equal(await maybeSendWeekly(s.app, { date: new Date('2026-10-26T08:45:00+01:00') }), null, 'pas deux fois le même lundi');
assert.notEqual(await maybeSendWeekly(s.app, { date: new Date('2026-11-02T08:15:00+01:00') }), null, 'lundi suivant');