From e8c3221cb32a84f0e7f10cd26d48c2e4742cf08e Mon Sep 17 00:00:00 2001 From: Tony Averty Date: Wed, 21 Oct 2026 23:54:02 +0200 Subject: [PATCH] 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 --- public/app.css | 182 ++++++++++++++++++++++++++- public/app.js | 263 ++++++++++++++++++++++++++++++++++++--- src/handlers.js | 46 +++++-- src/routes.js | 14 ++- src/services/claude.js | 3 + src/services/mailer.js | 10 +- src/services/mailhtml.js | 157 +++++++++++++++++++++++ src/services/markdown.js | 115 +++++++++++++++++ src/services/notify.js | 77 ++++++++++-- src/services/report.js | 22 +++- src/views.js | 88 ++++++++----- test/handlers.test.js | 5 + test/http.test.js | 5 + test/markdown.test.js | 61 +++++++++ test/report.test.js | 5 +- 15 files changed, 964 insertions(+), 89 deletions(-) create mode 100644 src/services/mailhtml.js create mode 100644 src/services/markdown.js create mode 100644 test/markdown.test.js diff --git a/public/app.css b/public/app.css index 1f04bbd..f6821a1 100644 --- a/public/app.css +++ b/public/app.css @@ -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; + } +} diff --git a/public/app.js b/public/app.js index 9820b67..f76de6f 100644 --- a/public/app.js +++ b/public/app.js @@ -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 `
`; + }; + 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 `
+
${scheduled ? '' : running ? '' : ''} + ${esc(LABELS[j.type] || j.type)}${j.project ? esc(j.project) : ''}${v !== null ? `${v} %` : ''}
+ ${msg ? `
${esc(msg)}
` : ''} + ${running ? progressBar(j) : ''} +
${esc(state)} + ${j.projectId ? ` · ` : ''}
+
`; + } + + 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 ? `${s.temp} °C` : ''} ${claudeQuota(s.claudeRateLimit)} ${gauge('24 h', s.budget.day)} ${gauge('30 j', s.budget.month)} - ${s.budget.blocked ? 'Budget IA atteint : jobs IA en attente' : ''} - ${s.queue ? `${s.queue} job(s)` : ''} - ${s.scheduled ? `${s.scheduled} programmé(s) cette nuit` : ''}`; + ${s.budget.blocked ? 'Budget IA atteint : jobs IA en attente' : ''}`; + 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 = `
-
${LABELS[type]} programmé(e) : ${esc(at)}
Le Pi est au frais et ton quota Claude est libre.
+
${LABELS[type]} programmé(e) : ${esc(at)}
Démarrage la nuit, quand ton quota Claude est libre.
`; return; } if (ACTIVE.includes(job.status)) { const extra = type === 'prospect' && p.found !== undefined ? `${p.found} prospect(s) trouvé(s) sur ${p.target}` : ''; + const running = job.status === 'running'; + const v = running ? pctOf(p) : null; box.innerHTML = `
-
${esc(p.message || (job.status === 'queued' ? 'En file d\'attente…' : 'En cours…'))}
${extra ? `
${extra}
` : ''}
+
${esc(p.message || (running ? 'En cours…' : 'En file d\'attente…'))}${v !== null ? `${v} %` : ''}
+ ${extra ? `
${extra}
` : ''}${running ? progressBar(job) : ''}
`; + paintBars(box); } else if (job.status === 'error') { box.innerHTML = `

${LABELS[type]} en échec : ${esc(job.error)}

`; } 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 = `

Envoyé à ${esc(r.sentTo)}.

${esc(r.markdown)}
`; + 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 = `

Envoyé à ${esc(r.sentTo)}${when ? ` · ${esc(when)}` : ''}

+
+ ${r.html || `
${esc(r.markdown)}
`}`; + box._markdown = r.markdown; return; } box.innerHTML = `

${esc(txt)}

`; @@ -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 ---------- + //
: la hauteur du bloc qui suit le 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(); + })(); })(); diff --git a/src/handlers.js b/src/handlers.js index da25d1e..e77d09d 100644 --- a/src/handlers.js +++ b/src/handlers.js @@ -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 }; diff --git a/src/routes.js b/src/routes.js index 3ee1b5b..179a383 100644 --- a/src/routes.js +++ b/src/routes.js @@ -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); diff --git a/src/services/claude.js b/src/services/claude.js index 1da6eed..5b46e56 100644 --- a/src/services/claude.js +++ b/src/services/claude.js @@ -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); } } diff --git a/src/services/mailer.js b/src/services/mailer.js index 6266784..4533af8 100644 --- a/src/services/mailer.js +++ b/src/services/mailer.js @@ -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: { diff --git a/src/services/mailhtml.js b/src/services/mailhtml.js new file mode 100644 index 0000000..6e4a2a1 --- /dev/null +++ b/src/services/mailhtml.js @@ -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 ` + +${esc(title)} + +
${esc(preheader)}
+ +
+ + + + + +
+ AiTools +
+
${esc(title)}
+ ${subtitle ? `
${esc(subtitle)}
` : ''} +
+ ${content} + ${cta && appUrl ? `
+ ${esc(cta)} +
` : ''} +
Envoyé automatiquement par ton panel AiTools.
+
+`; +} + +/** 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 ` + + +
+ + + + ${e.effort ? `` : ''} +
${e.n}
${inlineMd(e.title, st)}${e.effort} · ${EFFORTS[e.effort]}
+
${md(e.body)}
`; + }).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]) => ` +
+
${esc(label)}
+
${esc(value)}
+ ${sub ? `
${esc(sub)}
` : ''} +
`; + const rows = []; + for (let i = 0; i < cells.length; i += 2) rows.push(`${cells.slice(i, i + 2).map(tile).join('')}`); + return `${rows.join('')}
`; +} + +/** 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) => ` + ${esc(label)} + ${esc(value)}`; + const projects = active.map((p) => `
+
${esc(p.name)}
+ + ${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))} +
`).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 || `

Aucune activité cette semaine.

`} + ${quiet.length ? `

Sans activité : ${quiet.map((p) => esc(p.name)).join(', ')}.

` : ''}`; + 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) => `${u}`); + +/** + * 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) => `

${linkify(esc(p)).replace(/\n/g, '
')}

`).join('\n'); + return ` + + +
+${paras} + +
+`; +} diff --git a/src/services/markdown.js b/src/services/markdown.js new file mode 100644 index 0000000..19867c3 --- /dev/null +++ b/src/services/markdown.js @@ -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) => `${t}`) + .replace(/(^|[^*\w])\*([^*\s][^*]*)\*(?!\w)/g, (_, p, t) => `${p}${t}`) + .replace(/\[([^\]]+)\]\((https?:\/\/[^)\s]+)\)/g, (_, t, u) => `${t}`); + return out.replace(/\u0000(\d+)\u0000/g, (_, i) => `${codes[i]}`); +} + +/** + * Titres, paragraphes, listes (un niveau d'imbrication), citations, blocs de code, séparateurs. + * @param {string} md + * @param {{styles?: Record}} [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(`${inlineMd(para.join(' '), st)}

`); + para = []; + }; + const flushList = () => { + if (!list) return; + const items = list.items.map((i) => `${inlineMd(i.text, st)}${i.sub.length + ? `${i.sub.map((s) => `${inlineMd(s, st)}`).join('')}` : ''}`).join(''); + out.push(`<${list.type}${st(list.type)}>${items}`); + 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(`${esc(code.join('\n'))}`); + } else if (!line.trim()) { + flush(); + } else if ((m = /^(#{1,6})\s+(.*?)\s*#*\s*$/.exec(line))) { + flush(); + const n = m[1].length; + out.push(`${inlineMd(m[2], st)}`); + } else if (/^\s*([-*_])(\s*\1){2,}\s*$/.test(line)) { + flush(); + out.push(``); + } 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(`${inlineMd(m[1], st)}`); + } 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 `
${renderMarkdown(md)}
`; + return `
    ${items.map((e) => `
  1. +
    + ${e.n} +
    ${inlineMd(e.title)}
    + ${e.effort ? `${e.effort} · ${EFFORTS[e.effort]}` : ''} +
    +
    ${renderMarkdown(e.body)}
    +
  2. `).join('')}
`; +} diff --git a/src/services/notify.js b/src/services/notify.js index a2ea303..ffae706 100644 --- a/src/services/notify.js +++ b/src/services/notify.js @@ -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)] }); } diff --git a/src/services/report.js b/src/services/report.js index e1f9843..1ed7b43 100644 --- a/src/services/report.js +++ b/src/services/report.js @@ -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'); diff --git a/src/views.js b/src/views.js index 0ca6499..9425044 100644 --- a/src/views.js +++ b/src/views.js @@ -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) => ``; +const ICONS = { + target: svg(''), + search: svg(''), + spark: svg(''), + chart: svg(''), + mail: svg(''), + send: svg(''), + repeat: svg(''), + users: svg(''), + gear: svg(''), +}; + +/** 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 `
+ ${ICONS[icon]}${title}${sub ? `${sub}` : ''} +
${body}
+
`; +} + export function layout({ title, body, email }) { return ` @@ -15,9 +37,17 @@ export function layout({ title, body, email }) { + ${email ? `
- AiTools + AiTools
+
` : ''} @@ -42,7 +72,6 @@ function targetForm(p) { const t = p.target || {}; const list = (a) => esc((a || []).join('\n')); return `
-

Cible ${p.targetValidated ? 'validée' : 'à valider'}

@@ -58,8 +87,7 @@ function targetForm(p) { } function configForms(p, smtp, dbCfg, imap) { - return `
Configuration du projet - + return `

SMTP d'envoi

@@ -102,8 +130,7 @@ function configForms(p, smtp, dbCfg, imap) {
-
-
`; +`; } function templateForm(p, kind) { @@ -126,7 +153,7 @@ function templateForm(p, kind) { function projectItem(p, smtp, dbCfg, imap) { const profile = p.profile; - return `
+ return `
${esc(p.name)}
@@ -141,34 +168,33 @@ function projectItem(p, smtp, dbCfg, imap) { : '

Pas encore analysé.

'} - ${profile ? targetForm(p) : ''} + ${profile ? acc('target', 'target', + `Cible ${p.targetValidated ? 'validée' : 'à valider'}`, + esc((p.target?.description || '').slice(0, 120)), targetForm(p), { open: !p.targetValidated, cls: 'target-acc' }) : ''} -
- - - -
- - `, { cls: 'sub' })} -
Prospects + ${acc('prospects', 'users', 'Prospects ', 'Recherche, filtres, fiches, import et export CSV', ` @@ -194,11 +220,10 @@ function projectItem(p, smtp, dbCfg, imap) {
-
-
- +
`, { cls: 'sub prospects' })} + `, { cls: 'main' })} - +
`, { cls: 'main' })} - + ${acc('recap', 'chart', 'Récapitulatif', 'Chiffres business, prospection et courbes', ` +

Chargement…

`, { cls: 'main' })} +
- ${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' })}
`; } @@ -227,7 +251,7 @@ export function dashboardPage({ email, projects, forgejoHost }) { body: `

Projets

-
+
+ Nouveau projet
diff --git a/test/handlers.test.js b/test/handlers.test.js index 1a9b402..092b88d 100644 --- a/test/handlers.test.js +++ b/test/handlers.test.js @@ -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); diff --git a/test/http.test.js b/test/http.test.js index e5ce548..2932957 100644 --- a/test/http.test.js +++ b/test/http.test.js @@ -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 () => { diff --git a/test/markdown.test.js b/test/markdown.test.js new file mode 100644 index 0000000..bbb980a --- /dev/null +++ b/test/markdown.test.js @@ -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, /

Titre<\/h2>/); + assert.match(h, /

Un gras<\/strong> et code<\/code>\.<\/p>/); + assert.match(h, /

  • a
    • a1<\/li><\/ul><\/li>
    • b<\/li><\/ul>/); + assert.match(h, /
      1. un<\/li>
      2. deux<\/li><\/ol>/); +}); + +test('markdown : le HTML et les liens dangereux ne passent jamais', () => { + const h = renderMarkdown(' [clic](javascript:alert(1)) [ok](https://a.fr/?a=1&b=2) **