diff --git a/public/app.css b/public/app.css
index 817b301..593268f 100644
--- a/public/app.css
+++ b/public/app.css
@@ -104,10 +104,24 @@ form.send { margin-top: 18px; padding-top: 14px; border-top: 1px solid var(--lin
.moon { width: 18px; height: 18px; border-radius: 50%; box-shadow: inset -5px -3px 0 0 var(--accent); flex: none; transform: rotate(-20deg); }
.checks { display: grid; grid-template-columns: repeat(auto-fit, minmax(240px, 1fr)); gap: 0 12px; margin: 4px 0 10px; }
.checks label.check { margin: 4px 0; }
-.pfilters { display: grid; grid-template-columns: 2fr repeat(3, 1fr); gap: 8px; margin: 10px 0; }
+.pfilters { display: grid; grid-template-columns: 2fr repeat(4, auto); gap: 8px; margin: 10px 0; }
.pfilters input, .pfilters select { margin: 0; }
@media (max-width: 640px) { .pfilters { grid-template-columns: 1fr 1fr; } .pfilters input { grid-column: 1 / -1; } }
.pager { display: flex; gap: 10px; align-items: center; justify-content: center; margin: 8px 0; }
select.st-replied, select.st-client { color: var(--ok); font-weight: 600; }
select.st-refused, select.st-bounced { color: var(--err); }
select.st-new { color: var(--accent); }
+.prospect-dialog { width: min(720px, calc(100vw - 32px)); max-height: calc(100vh - 48px); border: 1px solid var(--line); border-radius: var(--radius); background: var(--card); color: var(--text); padding: 18px; }
+.prospect-dialog::backdrop { background: rgba(0, 0, 0, .45); }
+.dlg-head { align-items: flex-start; }
+.dlg-head h3 { margin: 0 0 4px; }
+.hook { font-style: italic; border-left: 3px solid var(--accent); padding-left: 10px; margin: 10px 0; }
+.timeline { list-style: none; padding: 0; margin: 0; border-left: 2px solid var(--line); }
+.timeline li { position: relative; padding: 0 0 10px 14px; }
+.timeline li::before { content: ""; position: absolute; left: -6px; top: 6px; width: 10px; height: 10px; border-radius: 50%; background: var(--accent); }
+.timeline time { display: block; font-size: .8rem; color: var(--muted); }
+.notes { list-style: none; padding: 0; }
+.notes li { border-top: 1px solid var(--line); padding: 8px 0; }
+.note-body { white-space: pre-wrap; }
+.pfilters .todo { margin: 0; align-self: center; }
+@media (max-width: 640px) { .pfilters .todo { grid-column: 1 / -1; } }
diff --git a/public/app.js b/public/app.js
index 4a53c7d..67c27c8 100644
--- a/public/app.js
+++ b/public/app.js
@@ -359,6 +359,92 @@
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 fmtDate = (ts) => new Date(ts * 1000).toLocaleString('fr-FR', { dateStyle: 'short', timeStyle: 'short', timeZone: 'Europe/Paris' });
+ const isoDay = (ts) => (ts ? new Date(ts * 1000).toLocaleDateString('sv-SE', { timeZone: 'Europe/Paris' }) : '');
+
+ // ---------- Fiche prospect ----------
+ const dlg = $('#prospect-dialog');
+
+ async function openProspect(id) {
+ let d;
+ try { d = await api(`/api/prospects/${id}`); } catch (err) { toast(err.message, 'error'); return; }
+ const p = d.prospect;
+ const site = safeUrl(p.website);
+ const source = safeUrl(p.source);
+ const events = [
+ ...d.mails.map((m) => ({
+ at: m.sent_at,
+ html: `${m.kind === 'followup' ? 'Relance' : 'Premier mail'} ${m.variant ? ` (objet ${esc(m.variant)}) ` : ''} : ${esc(m.subject || '')}
+ ${m.error ? ` · échec : ${esc(m.error)} ` : ''}`,
+ })),
+ ...(p.replied_at ? [{ at: p.replied_at, html: `Réponse reçue : ${esc(p.reply_subject || 'sans objet')}` }] : []),
+ ].sort((a, b) => a.at - b.at);
+
+ $('[data-dialog-body]', dlg).innerHTML = `
+
+
+
+
${esc(p.email)} ${p.city ? ` · ${esc(p.city)}` : ''}${p.sector ? ` · ${esc(p.sector)}` : ''}${p.score ? ` · score ${p.score}/10` : ''} · ${esc(STATUS[p.status] || p.status)}
+
+
Fermer
+
+ ${d.optOut ? `Sur la liste d'opposition (${d.optOut.reason === 'bounce' ? 'adresse invalide' : d.optOut.reason === 'refused' ? 'refus' : 'désinscription'}) : ne plus contacter.
` : ''}
+ ${p.hook ? `« ${esc(p.hook)} »
` : ''}
+ ${source ? `Email trouvé sur : ${esc(source)}
` : ''}
+
+ Historique
+ ${events.length ? `${events.map((e) => `${fmtDate(e.at)} ${e.html}
`).join('')} ` : 'Pas encore contacté.
'}
+
+ Prochaine action
+
+
+ Notes
+
+ `;
+ dlg.dataset.id = id;
+ if (!dlg.open) dlg.showModal();
+ }
+
+ function refreshOpenLists() { $$('details.prospects[open]').forEach((d) => loadProspects(d, Number(d.dataset.page) || 1)); }
+
+ if (dlg) {
+ dlg.addEventListener('click', async (e) => {
+ if (e.target === dlg || e.target.closest('[data-close]')) { dlg.close(); return; }
+ const id = dlg.dataset.id;
+ const del = e.target.closest('[data-del-note]');
+ if (del && confirm('Supprimer cette note ?')) {
+ await api(`/api/prospects/${id}/notes/${del.dataset.delNote}/delete`, {}).catch((err) => toast(err.message, 'error'));
+ openProspect(id);
+ }
+ if (e.target.closest('[data-clear-next]')) {
+ await api(`/api/prospects/${id}/next`, { action: '' }).catch((err) => toast(err.message, 'error'));
+ openProspect(id); refreshOpenLists();
+ }
+ });
+ dlg.addEventListener('submit', async (e) => {
+ const form = e.target.closest('form[data-dlg]');
+ if (!form) return;
+ e.preventDefault();
+ const id = dlg.dataset.id;
+ try {
+ if (form.dataset.dlg === 'note') { await api(`/api/prospects/${id}/notes`, formData(form)); toast('Note ajoutée'); }
+ else { await api(`/api/prospects/${id}/next`, formData(form)); toast('Prochaine action enregistrée'); refreshOpenLists(); }
+ openProspect(id);
+ } catch (err) { toast(err.message, 'error'); }
+ });
+ }
+ document.addEventListener('click', (e) => {
+ const b = e.target.closest('[data-open-prospect]');
+ if (b) openProspect(b.dataset.openProspect);
+ });
const fmtDay = (ts) => (ts ? new Date(ts * 1000).toLocaleDateString('fr-FR', { day: '2-digit', month: '2-digit', timeZone: 'Europe/Paris' }) : '');
@@ -370,7 +456,8 @@
const r = await api(`/api/projects/${proj.dataset.id}/prospects?${qs}`);
d.dataset.page = r.page;
box.innerHTML = r.rows.length ? `Entreprise Email Ville Score Contacté Statut
- ${r.rows.map((x) => `${safeUrl(x.website) ? `${esc(x.company)} ` : esc(x.company)}
+ ${r.rows.map((x) => `${esc(x.company)}
+ ${x.next_action ? `→ ${esc(x.next_action)} (${fmtDay(x.next_action_at)})
` : ''}
${esc(x.email)} ${esc(x.city)} ${x.score ?? ''}
${fmtDay(x.sent_at)}${x.followup_at ? ' + relance ' : ''}
${Object.entries(STATUS).map(([k, v]) => `${v} `).join('')} `).join('')}
diff --git a/src/db.js b/src/db.js
index c8a0c71..a505329 100644
--- a/src/db.js
+++ b/src/db.js
@@ -105,6 +105,18 @@ export const MIGRATIONS = [
`
ALTER TABLE jobs ADD COLUMN run_after INTEGER; -- ne pas démarrer avant (epoch s)
`,
+ // 7 — fiche prospect : notes et prochaine action
+ `
+ CREATE TABLE prospect_notes (
+ id INTEGER PRIMARY KEY,
+ prospect_id INTEGER NOT NULL REFERENCES prospects(id) ON DELETE CASCADE,
+ body TEXT NOT NULL,
+ created_at INTEGER NOT NULL
+ );
+ CREATE INDEX prospect_notes_p ON prospect_notes(prospect_id, created_at);
+ ALTER TABLE prospects ADD COLUMN next_action TEXT;
+ ALTER TABLE prospects ADD COLUMN next_action_at INTEGER;
+ `,
];
export function openDb(dataDir) {
diff --git a/src/routes.js b/src/routes.js
index cd5cf26..4eb3f97 100644
--- a/src/routes.js
+++ b/src/routes.js
@@ -14,7 +14,9 @@ import { nextNightSlot } from './services/paris-time.js';
import { notify, notifyConfig, EVENTS, WEBHOOK_RE } from './services/notify.js';
import { budgetState, AI_JOBS } from './services/budget.js';
import { sendWeeklyReport } from './services/report.js';
-import { listProspects, parseFilters, STATUSES as PROSPECT_STATUSES } from './services/crm.js';
+import {
+ listProspects, parseFilters, STATUSES as PROSPECT_STATUSES, prospectDetail, addNote, deleteNote, setNextAction,
+} from './services/crm.js';
import {
getProject, listProjects, createProject, saveSecretConfig, publicConfig, globalSmtp,
prospectStats, sentSince, repoDir, getTemplate, saveTemplate, abStats,
@@ -321,5 +323,29 @@ export function registerRoutes(router, app) {
json(res, { ok: true });
});
+ // ---------- Fiche prospect ----------
+ const prospectId = (params) => {
+ const id = Number(params.id);
+ if (!db.prepare('SELECT 1 FROM prospects WHERE id = ?').get(id)) throw new HttpError(404, 'Prospect introuvable');
+ return id;
+ };
+ router.get('/api/prospects/:id', ({ res, params }) => json(res, prospectDetail(db, prospectId(params))));
+ router.post('/api/prospects/:id/notes', async ({ req, res, params }) => {
+ const id = prospectId(params);
+ const noteId = addNote(db, id, (await readBody(req)).body);
+ if (!noteId) throw new HttpError(400, 'Note vide');
+ json(res, { ok: true, id: noteId });
+ });
+ router.post('/api/prospects/:id/notes/:nid/delete', ({ res, params }) => {
+ if (!deleteNote(db, prospectId(params), Number(params.nid))) throw new HttpError(404, 'Note introuvable');
+ json(res, { ok: true });
+ });
+ router.post('/api/prospects/:id/next', async ({ req, res, params }) => {
+ const id = prospectId(params);
+ const b = await readBody(req);
+ try { json(res, { ok: true, at: setNextAction(db, id, b.action, b.day) }); }
+ catch (e) { throw new HttpError(400, e.message); }
+ });
+
router.post('/api/jobs/:id/cancel', ({ res, params }) => { cancelJob(db, Number(params.id)); json(res, { ok: true }); });
}
diff --git a/src/services/crm.js b/src/services/crm.js
index 4026d28..97dc7b8 100644
--- a/src/services/crm.js
+++ b/src/services/crm.js
@@ -1,4 +1,6 @@
-// Prospects : filtres, tri, pagination. Partagé par la liste et l'export CSV.
+// Prospects : filtres, tri, pagination, fiche détaillée. Partagé par la liste et l'export CSV.
+import { now } from '../db.js';
+import { parisTime, parisParts } from './paris-time.js';
export const STATUSES = {
new: 'À contacter', sent: 'Contacté', replied: 'A répondu', client: 'Client', refused: 'Refus', bounced: 'Rejeté',
@@ -23,6 +25,7 @@ export function parseFilters(sp) {
status: Object.hasOwn(STATUSES, sp.get('status')) ? sp.get('status') : '',
minScore: int(sp.get('minScore'), 0, 10, 0),
sort: Object.hasOwn(SORTS, sp.get('sort')) ? sp.get('sort') : 'score',
+ todo: sp.get('todo') === '1',
page: int(sp.get('page'), 1, 100_000, 1),
};
}
@@ -37,6 +40,7 @@ export function filterWhere(projectId, f) {
}
if (f.status) { where.push('status = ?'); args.push(f.status); }
if (f.minScore) { where.push('score >= ?'); args.push(f.minScore); }
+ if (f.todo) { where.push('next_action_at IS NOT NULL AND next_action_at <= ?'); args.push(f.at ?? now()); }
return { sql: where.join(' AND '), args, order: SORTS[f.sort] || SORTS.score };
}
@@ -45,7 +49,48 @@ export function listProspects(db, projectId, f, { limit = 100 } = {}) {
const total = db.prepare(`SELECT COUNT(*) n FROM prospects WHERE ${sql}`).get(...args).n;
const pages = Math.max(1, Math.ceil(total / limit));
const page = Math.min(f.page, pages);
- const rows = db.prepare(`SELECT id, company, email, website, city, sector, score, status, sent_at, followup_at, replied_at
+ const rows = db.prepare(`SELECT id, company, email, website, city, sector, score, status, sent_at, followup_at, replied_at,
+ next_action, next_action_at
FROM prospects WHERE ${sql} ORDER BY ${order} LIMIT ? OFFSET ?`).all(...args, limit, (page - 1) * limit);
return { total, page, pages, rows };
}
+
+// ---------- Fiche prospect ----------
+
+/** Tout ce qu'on sait d'un prospect : infos, mails envoyés, réponse, notes. */
+export function prospectDetail(db, id) {
+ const p = db.prepare('SELECT * FROM prospects WHERE id = ?').get(id);
+ if (!p) return null;
+ const mails = db.prepare(`SELECT kind, subject, variant, sent_at, error FROM mail_log
+ WHERE prospect_id = ? ORDER BY sent_at, id`).all(id);
+ const notes = db.prepare('SELECT id, body, created_at FROM prospect_notes WHERE prospect_id = ? ORDER BY created_at DESC, id DESC').all(id);
+ const optOut = db.prepare('SELECT reason, created_at FROM blacklist WHERE email = ?').get(p.email) || null;
+ return { prospect: p, mails, notes, optOut };
+}
+
+export function addNote(db, prospectId, body) {
+ const text = String(body || '').trim().slice(0, 2000);
+ if (!text) return null;
+ return Number(db.prepare('INSERT INTO prospect_notes(prospect_id, body, created_at) VALUES(?, ?, ?)').run(prospectId, text, now()).lastInsertRowid);
+}
+
+export function deleteNote(db, prospectId, noteId) {
+ return db.prepare('DELETE FROM prospect_notes WHERE id = ? AND prospect_id = ?').run(noteId, prospectId).changes > 0;
+}
+
+/** Prochaine action : texte + jour (AAAA-MM-JJ, rappel à 9h heure de Paris). Vide = effacer. */
+export function setNextAction(db, prospectId, action, day) {
+ const text = String(action || '').trim().slice(0, 200);
+ const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(String(day || ''));
+ if (!text) {
+ db.prepare('UPDATE prospects SET next_action = NULL, next_action_at = NULL WHERE id = ?').run(prospectId);
+ return null;
+ }
+ if (!m) throw new Error('Date attendue au format AAAA-MM-JJ');
+ const date = parisTime(+m[1], +m[2], +m[3], 9);
+ // 2026-02-31 deviendrait le 3 mars sans prévenir : on refuse
+ if (parisParts(date).day !== +m[3]) throw new Error('Date invalide');
+ const at = Math.floor(date.getTime() / 1000);
+ db.prepare('UPDATE prospects SET next_action = ?, next_action_at = ? WHERE id = ?').run(text, at, prospectId);
+ return at;
+}
diff --git a/src/views.js b/src/views.js
index 20dce14..3af1935 100644
--- a/src/views.js
+++ b/src/views.js
@@ -184,6 +184,7 @@ function projectItem(p, smtp, dbCfg, imap) {
Tous les statuts ${Object.entries(STATUSES).map(([k, l]) => `${l} `).join('')}
Tous les scores Score ≥ 5 Score ≥ 7 Score ≥ 9
+ Actions à faire
Tri : score Plus récents Dernier contact Entreprise A → Z
@@ -229,6 +230,7 @@ export function dashboardPage({ email, projects, forgejoHost }) {
Créer et analyser
+
${projects.length ? projects.map((x) => projectItem(x.project, x.smtp, x.dbCfg, x.imap)).join('\n') : '
Aucun projet pour l\'instant.
'}
`,
diff --git a/test/crm.test.js b/test/crm.test.js
index f729214..129198a 100644
--- a/test/crm.test.js
+++ b/test/crm.test.js
@@ -20,7 +20,7 @@ const names = (r) => r.rows.map((x) => x.company);
test('parseFilters ignore tout ce qui n\'est pas prévu', () => {
assert.deepEqual(f({ status: 'drop table', sort: 'id; --', minScore: '99', page: '-3', q: ' zen ' }),
- { q: 'zen', status: '', minScore: 10, sort: 'score', page: 1 });
+ { q: 'zen', status: '', minScore: 10, sort: 'score', todo: false, page: 1 });
});
test('recherche, filtres, tri, et isolation entre projets', () => {
@@ -49,3 +49,44 @@ test('pagination', () => {
const ids = new Set([...p1.rows, ...listProspects(db, 1, f({ page: '2' })).rows, ...p3.rows].map((x) => x.id));
assert.equal(ids.size, 254, 'aucun doublon ni trou entre les pages');
});
+
+test('fiche : historique des mails, réponse, opposition', async () => {
+ const { prospectDetail } = await import('../src/services/crm.js');
+ const db = setup();
+ db.prepare("INSERT INTO mail_log(project_id, prospect_id, email, sent_at, kind, variant, subject) VALUES(1, 1, 'contact@fournil.fr', 100, 'initial', 'B', 'Objet B')").run();
+ db.prepare("INSERT INTO mail_log(project_id, prospect_id, email, sent_at, kind, subject, error) VALUES(1, 1, 'contact@fournil.fr', 200, 'followup', 'Re: Objet B', '421 retry')").run();
+ db.prepare("INSERT INTO blacklist(email, reason, created_at) VALUES('contact@fournil.fr', 'unsubscribe', 300)").run();
+ const d = prospectDetail(db, 1);
+ assert.equal(d.prospect.company, 'Le Fournil');
+ assert.deepEqual(d.mails.map((m) => [m.kind, m.variant, m.error]), [['initial', 'B', null], ['followup', null, '421 retry']]);
+ assert.equal(d.optOut.reason, 'unsubscribe');
+ assert.equal(prospectDetail(db, 999), null);
+});
+
+test('notes : ajout, ordre, suppression limitée au bon prospect', async () => {
+ const { addNote, deleteNote, prospectDetail } = await import('../src/services/crm.js');
+ const db = setup();
+ assert.equal(addNote(db, 1, ' '), null, 'note vide refusée');
+ const n1 = addNote(db, 1, 'A rappelé, intéressé');
+ const n2 = addNote(db, 1, 'x'.repeat(5000));
+ assert.equal(prospectDetail(db, 1).notes[0].id, n2, 'plus récente en premier');
+ assert.equal(prospectDetail(db, 1).notes[0].body.length, 2000, 'tronquée à 2000');
+ assert.equal(deleteNote(db, 2, n1), false, 'pas la note d\'un autre prospect');
+ assert.equal(deleteNote(db, 1, n1), true);
+ db.prepare('DELETE FROM prospects WHERE id = 1').run();
+ assert.equal(db.prepare('SELECT COUNT(*) n FROM prospect_notes').get().n, 0, 'supprimées avec le prospect');
+});
+
+test('prochaine action : 9h heure de Paris, dates impossibles refusées, filtre "à faire"', async () => {
+ const { setNextAction } = await import('../src/services/crm.js');
+ const db = setup();
+ assert.equal(setNextAction(db, 1, 'Rappeler', '2026-07-14'), Date.parse('2026-07-14T07:00:00Z') / 1000, 'été');
+ assert.equal(setNextAction(db, 2, 'Devis', '2026-12-01'), Date.parse('2026-12-01T08:00:00Z') / 1000, 'hiver');
+ assert.throws(() => setNextAction(db, 1, 'x', '2026-02-31'), /Date invalide/);
+ assert.throws(() => setNextAction(db, 1, 'x', '14/07/2026'), /AAAA-MM-JJ/);
+ const todo = (at) => names(listProspects(db, 1, { ...f({ todo: '1' }), at }));
+ assert.deepEqual(todo(Date.parse('2026-08-01T00:00:00Z') / 1000), ['Le Fournil'], 'seule l\'action échue');
+ assert.deepEqual(todo(Date.parse('2027-01-01T00:00:00Z') / 1000), ['Le Fournil', 'Coiffure Zen']);
+ assert.equal(setNextAction(db, 1, '', ''), null);
+ assert.deepEqual(todo(Date.parse('2027-01-01T00:00:00Z') / 1000), ['Coiffure Zen'], 'action effacée');
+});
diff --git a/test/http.test.js b/test/http.test.js
index 715e8c4..490aad4 100644
--- a/test/http.test.js
+++ b/test/http.test.js
@@ -209,3 +209,25 @@ test('budget : réglages, jauge et avertissement au lancement', async () => {
assert.match((await r.json()).budgetBlocked, /budget IA des dernières 24 h atteint/);
await post('/settings', { ...base, budget_day_usd: '' }, { form: true });
});
+
+test('fiche prospect : routes notes et prochaine action', async () => {
+ const pid = app.db.prepare('SELECT id FROM projects LIMIT 1').get().id;
+ const id = Number(app.db.prepare("INSERT INTO prospects(project_id, company, email, website, created_at) VALUES(?, 'Atelier', 'a@atelier.fr', 'javascript:alert(1)', ?)").run(pid, now()).lastInsertRowid);
+ let r = await post(`/api/prospects/${id}/notes`, { body: '' });
+ assert.equal(r.status, 200);
+ r = await post(`/api/prospects/${id}/notes`, { body: '' });
+ assert.equal(r.status, 400);
+ r = await post(`/api/prospects/${id}/next`, { action: 'Rappeler', day: '2026-02-31' });
+ assert.equal(r.status, 400);
+ r = await post(`/api/prospects/${id}/next`, { action: 'Rappeler', day: '2026-11-03' });
+ assert.equal(r.status, 200);
+ const d = await (await get(`/api/prospects/${id}`)).json();
+ assert.equal(d.notes[0].body, '', 'stocké brut, échappé à l\'affichage');
+ assert.equal(d.prospect.next_action, 'Rappeler');
+ r = await get('/api/prospects/999999');
+ assert.equal(r.status, 404);
+ r = await post(`/api/prospects/${id}/notes/${d.notes[0].id}/delete`, {}, { origin: 'https://evil.com' });
+ assert.equal(r.status, 403, 'CSRF bloqué');
+ const list = await (await get(`/api/projects/${pid}/prospects?q=atelier`)).json();
+ assert.equal(list.rows[0].next_action, 'Rappeler');
+});