feat: add prospect detail with history, notes and next action
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01SfihHazrSHXgndJtSNLubJ
This commit is contained in:
parent
c32f4350de
commit
2b017731e5
8 changed files with 255 additions and 6 deletions
|
|
@ -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; } }
|
||||
|
|
|
|||
|
|
@ -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: `<strong>${m.kind === 'followup' ? 'Relance' : 'Premier mail'}</strong>${m.variant ? ` <span class="muted">(objet ${esc(m.variant)})</span>` : ''} : ${esc(m.subject || '')}
|
||||
${m.error ? `<span class="error"> · échec : ${esc(m.error)}</span>` : ''}`,
|
||||
})),
|
||||
...(p.replied_at ? [{ at: p.replied_at, html: `<strong class="ok">Réponse reçue</strong> : ${esc(p.reply_subject || 'sans objet')}` }] : []),
|
||||
].sort((a, b) => a.at - b.at);
|
||||
|
||||
$('[data-dialog-body]', dlg).innerHTML = `
|
||||
<div class="row dlg-head">
|
||||
<div>
|
||||
<h3>${site ? `<a href="${esc(site)}" target="_blank" rel="noopener noreferrer">${esc(p.company)}</a>` : esc(p.company)}</h3>
|
||||
<div class="small muted"><a href="mailto:${esc(p.email)}">${esc(p.email)}</a>${p.city ? ` · ${esc(p.city)}` : ''}${p.sector ? ` · ${esc(p.sector)}` : ''}${p.score ? ` · score ${p.score}/10` : ''} · ${esc(STATUS[p.status] || p.status)}</div>
|
||||
</div>
|
||||
<button type="button" class="btn small" data-close>Fermer</button>
|
||||
</div>
|
||||
${d.optOut ? `<p class="error small">Sur la liste d'opposition (${d.optOut.reason === 'bounce' ? 'adresse invalide' : d.optOut.reason === 'refused' ? 'refus' : 'désinscription'}) : ne plus contacter.</p>` : ''}
|
||||
${p.hook ? `<p class="hook">« ${esc(p.hook)} »</p>` : ''}
|
||||
${source ? `<p class="small muted">Email trouvé sur : <a href="${esc(source)}" target="_blank" rel="noopener noreferrer">${esc(source)}</a></p>` : ''}
|
||||
|
||||
<h4>Historique</h4>
|
||||
${events.length ? `<ol class="timeline">${events.map((e) => `<li><time>${fmtDate(e.at)}</time><div>${e.html}</div></li>`).join('')}</ol>` : '<p class="muted small">Pas encore contacté.</p>'}
|
||||
|
||||
<h4>Prochaine action</h4>
|
||||
<form data-dlg="next" class="inline">
|
||||
<label>Quoi<input name="action" value="${esc(p.next_action || '')}" placeholder="ex. Rappeler après les vacances" maxlength="200"></label>
|
||||
<label>Quand<input type="date" name="day" value="${isoDay(p.next_action_at)}"></label>
|
||||
<button class="btn">Enregistrer</button>
|
||||
${p.next_action ? '<button type="button" class="btn small" data-clear-next>Effacer</button>' : ''}
|
||||
</form>
|
||||
|
||||
<h4>Notes</h4>
|
||||
<form data-dlg="note">
|
||||
<textarea name="body" rows="3" maxlength="2000" placeholder="Ce qu'il a dit, le contexte, ce qu'il faut retenir…"></textarea>
|
||||
<button class="btn">Ajouter la note</button>
|
||||
</form>
|
||||
<ul class="notes">${d.notes.map((n) => `<li><div class="small muted">${fmtDate(n.created_at)} · <button type="button" class="link small" data-del-note="${n.id}">supprimer</button></div><div class="note-body">${esc(n.body)}</div></li>`).join('')}</ul>`;
|
||||
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 ? `<div class="table-wrap"><table><thead><tr><th>Entreprise</th><th>Email</th><th>Ville</th><th>Score</th><th>Contacté</th><th>Statut</th></tr></thead><tbody>
|
||||
${r.rows.map((x) => `<tr data-row="${x.id}"><td>${safeUrl(x.website) ? `<a href="${esc(safeUrl(x.website))}" target="_blank" rel="noopener noreferrer">${esc(x.company)}</a>` : esc(x.company)}</td>
|
||||
${r.rows.map((x) => `<tr data-row="${x.id}"><td><button type="button" class="link" data-open-prospect="${x.id}">${esc(x.company)}</button>
|
||||
${x.next_action ? `<div class="small ${x.next_action_at * 1000 <= Date.now() ? 'warn' : 'muted'}">→ ${esc(x.next_action)} (${fmtDay(x.next_action_at)})</div>` : ''}</td>
|
||||
<td>${esc(x.email)}</td><td>${esc(x.city)}</td><td>${x.score ?? ''}</td>
|
||||
<td>${fmtDay(x.sent_at)}${x.followup_at ? ' <span class="muted small">+ relance</span>' : ''}</td>
|
||||
<td><select data-prospect="${x.id}" class="st-${x.status}">${Object.entries(STATUS).map(([k, v]) => `<option value="${k}" ${k === x.status ? 'selected' : ''}>${v}</option>`).join('')}</select></td></tr>`).join('')}
|
||||
|
|
|
|||
12
src/db.js
12
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) {
|
||||
|
|
|
|||
|
|
@ -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 }); });
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -184,6 +184,7 @@ function projectItem(p, smtp, dbCfg, imap) {
|
|||
<input type="search" name="q" placeholder="Rechercher : entreprise, email, ville, secteur" aria-label="Rechercher">
|
||||
<select name="status" aria-label="Statut"><option value="">Tous les statuts</option>${Object.entries(STATUSES).map(([k, l]) => `<option value="${k}">${l}</option>`).join('')}</select>
|
||||
<select name="minScore" aria-label="Score minimum"><option value="0">Tous les scores</option><option value="5">Score ≥ 5</option><option value="7">Score ≥ 7</option><option value="9">Score ≥ 9</option></select>
|
||||
<label class="check todo"><input type="checkbox" name="todo" value="1"> Actions à faire</label>
|
||||
<select name="sort" aria-label="Tri"><option value="score">Tri : score</option><option value="recent">Plus récents</option><option value="contacted">Dernier contact</option><option value="company">Entreprise A → Z</option></select>
|
||||
</form>
|
||||
<div data-prospects></div>
|
||||
|
|
@ -229,6 +230,7 @@ export function dashboardPage({ email, projects, forgejoHost }) {
|
|||
<button class="btn primary">Créer et analyser</button>
|
||||
</form>
|
||||
</details>
|
||||
<dialog class="prospect-dialog" id="prospect-dialog" aria-label="Fiche prospect"><div data-dialog-body></div></dialog>
|
||||
<div class="projects">
|
||||
${projects.length ? projects.map((x) => projectItem(x.project, x.smtp, x.dbCfg, x.imap)).join('\n') : '<p class="muted">Aucun projet pour l\'instant.</p>'}
|
||||
</div>`,
|
||||
|
|
|
|||
|
|
@ -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');
|
||||
});
|
||||
|
|
|
|||
|
|
@ -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: '<script>x</script>' });
|
||||
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, '<script>x</script>', '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');
|
||||
});
|
||||
|
|
|
|||
Loading…
Reference in a new issue