// Front vanilla, sans build. Polling léger uniquement sur les projets dépliés. (() => { const $ = (sel, el = document) => el.querySelector(sel); const $$ = (sel, el = document) => [...el.querySelectorAll(sel)]; const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c])); async function api(path, body) { const r = await fetch(path, body === undefined ? { headers: { Accept: 'application/json' } } : { method: 'POST', headers: { 'Content-Type': 'application/json', Accept: 'application/json' }, body: JSON.stringify(body), }); if (r.status === 401) { location.href = '/login'; throw new Error('Session expirée'); } const data = await r.json().catch(() => ({})); if (!r.ok) throw new Error(data.error || `Erreur ${r.status}`); return data; } function toast(msg, kind = 'ok') { const t = document.createElement('div'); t.className = `toast ${kind}`; t.textContent = msg; document.body.append(t); setTimeout(() => t.remove(), 4500); } const formData = (form) => Object.fromEntries(new FormData(form)); const ago = (ts) => { if (!ts) return 'jamais'; const m = Math.round((Date.now() / 1000 - ts) / 60); return m < 1 ? "à l'instant" : m < 60 ? `il y a ${m} min` : m < 1440 ? `il y a ${Math.round(m / 60)} h` : `il y a ${Math.round(m / 1440)} j`; }; const pct = (x) => `${Math.round(x * 100)} %`; const ACTIVE = ['queued', 'running']; const LABELS = { analyze: 'Analyse', prospect: 'Recherche', template: 'Modèle', send: 'Envoi', evolution: 'Évolutions', followup_template: 'Modèle de relance', followup: 'Relances', }; // ---------- Barre système ---------- // "IA 24 h : 0,42 $ / 2 $" : orange à 80 %, rouge une fois atteint function gauge(label, x) { const used = `${x.used.toFixed(2)} $`; if (!x.limit) return `IA ${label} : ${used}`; const r = x.used / x.limit; return `IA ${label} : ${used} / ${x.limit} $`; } async function refreshSys() { const el = $('#sys'); if (!el) return; 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` : ''} ${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` : ''}`; } catch { /* silencieux */ } } refreshSys(); setInterval(refreshSys, 30_000); // ---------- Rendu d'un job ---------- function renderJob(box, job, type) { if (!box) return; if (!job) { box.innerHTML = ''; return; } const p = job.progress || {}; if (job.status === 'queued' && job.runAfter && job.runAfter * 1000 > Date.now()) { 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]} en échec : ${esc(job.error)}
`; } else if (job.status === 'cancelled') { box.innerHTML = `${LABELS[type]} annulé(e).
`; } else if (job.status === 'done') { const r = job.result || {}; let txt = `${LABELS[type]} terminé(e).`; if (type === 'prospect') txt = `Recherche terminée : ${r.found} nouveau(x) prospect(s) sur ${r.requested} demandés.`; 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)}`;
return;
}
box.innerHTML = `${esc(txt)}
`; } } // ---------- État d'un projet ---------- const state = new Map(); // id -> { timer, tplStamp, analyzing } async function refreshProject(el) { const id = el.dataset.id; let s; try { s = await api(`/api/projects/${id}/status`); } catch (e) { return schedule(el, 30_000); } const st = state.get(id) || {}; const jobs = s.jobs; for (const type of ['prospect', 'template', 'send', 'evolution', 'followup_template', 'followup']) renderJob($(`[data-job="${type}"]`, el), jobs[type], type); const running = Object.entries(jobs).filter(([, j]) => ACTIVE.includes(j.status)).map(([t]) => LABELS[t]); $('[data-state]', el).innerHTML = running.length ? `${esc(running.join(', '))}` : `${s.stats.total || 0} prospect(s)`; // Fin d'analyse → recharge la page pour afficher fiche + cible const an = jobs.analyze; if (an && ACTIVE.includes(an.status)) st.analyzing = true; else if (st.analyzing && an) { st.analyzing = false; if (an.status === 'done') { toast('Analyse terminée'); location.reload(); return; } if (an.status === 'error') toast(`Analyse en échec : ${an.error}`, 'error'); } if (an?.status === 'error' && !s.hasProfile) $('.profile p', el).outerHTML = `${esc(an.error)}
`; // Modèle de mail : on ne remplace le formulaire que s'il a changé côté serveur st.tplStamp ||= {}; for (const kind of ['initial', 'followup']) { const t = s.templates[kind]; const form = $(`form[data-action="template"][data-kind="${kind}"]`, el); if (t && st.tplStamp[kind] !== t.updated_at) { st.tplStamp[kind] = t.updated_at; form.subject.value = t.subject; if (form.subjectB) form.subjectB.value = t.subjectB || ''; form.body.value = t.body; } $('[data-tpl-state]', form).innerHTML = t ? (t.status === 'validated' ? 'validé' : 'brouillon') : ''; } // Relance automatique : ce qui est prévu, ou ce qui bloque const f = s.followup; $('[data-followup-info]', el).innerHTML = !f.enabled ? 'Désactivée.' : f.blockers.length ? `En attente : ${esc(f.blockers.join(', '))}. ${f.due} relance(s) due(s).` : f.due ? `${f.due} relance(s) due(s) : ${f.inHours ? 'envoi au prochain passage (≤ 15 min)' : 'envoi aux heures ouvrées (lun-ven 9h-18h)'}.` : `Active : les prospects sans réponse après ${f.days} jours seront relancés une fois.`; // Bouton Envoyer : recherche finie + modèle validé + SMTP + quota dispo const prospecting = jobs.prospect && ACTIVE.includes(jobs.prospect.status); const sending = jobs.send && ACTIVE.includes(jobs.send.status); const sendForm = $('form[data-action="send"]', el); const blockers = []; if (prospecting) blockers.push('recherche en cours'); if (sending) blockers.push('envoi en cours'); if (s.templates.initial?.status !== 'validated') blockers.push('modèle à valider'); if (!s.hasSmtp) blockers.push('SMTP à configurer'); if (!s.sendMax) blockers.push(s.stats.new ? 'plafond du jour atteint' : 'aucun prospect à contacter'); $('button', sendForm).disabled = blockers.length > 0; sendForm.count.max = s.sendMax || 1; if (Number(sendForm.count.value) > s.sendMax && s.sendMax) sendForm.count.value = s.sendMax; $('[data-send-info]', sendForm).textContent = blockers.length ? `Bloqué : ${blockers.join(', ')}` : `${s.stats.new} prospect(s) en attente · max ${s.sendMax} maintenant`; $('[data-count]', el).textContent = `(${s.stats.total || 0})`; // Boîte de réception + test A/B const ib = $('[data-inbox]', el); const ab = s.ab.length > 1 ? `Chargement…
'; try { const r = await api(`/api/projects/${proj.dataset.id}/recap${force ? '?force' : ''}`); const b = r.business; const s = r.stats; const eur = (v) => (typeof v === 'number' ? v.toLocaleString('fr-FR', { style: 'currency', currency: 'EUR' }) : esc(v ?? '—')); box.innerHTML = `BDD : ${esc(r.error)}
` : ''}Coût IA du projet (équivalent API) : $${r.aiCostUsd.toFixed(2)}${b?.cached ? ' · chiffres en cache (10 min)' : ''}
`; } catch (err) { box.innerHTML = `${esc(err.message)}
`; } } // ---------- Liste des prospects (mini CRM) ---------- const STATUS = { new: 'À contacter', sent: 'Contacté', replied: 'A répondu', client: 'Client', refused: 'Refus', bounced: 'Rejeté' }; // Seuls les liens http(s) sont cliquables : un "javascript:" venu d'une page web scrapée ne doit jamais s'exécuter ici const safeUrl = (u) => (/^https?:\/\//i.test(String(u || '')) ? String(u) : ''); const fmtDay = (ts) => (ts ? new Date(ts * 1000).toLocaleDateString('fr-FR', { day: '2-digit', month: '2-digit', timeZone: 'Europe/Paris' }) : ''); async function loadProspects(d, page = 1) { const proj = d.closest('.project'); const box = $('[data-prospects]', d); const qs = new URLSearchParams({ ...formData($('[data-filters]', d)), page }); try { const r = await api(`/api/projects/${proj.dataset.id}/prospects?${qs}`); d.dataset.page = r.page; box.innerHTML = r.rows.length ? `| Entreprise | Ville | Score | Contacté | Statut | |
|---|---|---|---|---|---|
| ${safeUrl(x.website) ? `${esc(x.company)}` : esc(x.company)} | ${esc(x.email)} | ${esc(x.city)} | ${x.score ?? ''} | ${fmtDay(x.sent_at)}${x.followup_at ? ' + relance' : ''} |
Aucun prospect ne correspond.
'; $('[data-pager]', d).innerHTML = r.pages > 1 ? ` Page ${r.page} / ${r.pages} · ${r.total} prospect(s) ` : `${r.total} prospect(s)`; } catch (err) { box.innerHTML = `${esc(err.message)}
`; } } $$('details.prospects').forEach((d) => { d.addEventListener('toggle', () => { if (d.open) loadProspects(d); }); const form = $('[data-filters]', d); let t; form.addEventListener('input', (e) => { if (e.target.name === 'q') { clearTimeout(t); t = setTimeout(() => loadProspects(d), 300); } }); form.addEventListener('change', (e) => { if (e.target.name !== 'q') loadProspects(d); }); form.addEventListener('submit', (e) => { e.preventDefault(); loadProspects(d); }); d.addEventListener('click', (e) => { const b = e.target.closest('[data-page]'); if (b) loadProspects(d, Number(b.dataset.page)); }); }); document.addEventListener('change', async (e) => { const sel = e.target.closest('[data-prospect]'); if (!sel) return; if (sel.value === 'refused' && !confirm('Marquer en refus ajoute l\'adresse à la liste d\'opposition. Continuer ?')) return; 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'); } }); })();