From 1de83faecb16080a69e46eab3b25e5fa8400245b Mon Sep 17 00:00:00 2001 From: Tony Averty Date: Wed, 21 Oct 2026 16:07:53 +0200 Subject: [PATCH] feat: search, filter and paginate prospects Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01SfihHazrSHXgndJtSNLubJ --- public/app.css | 7 +++++++ public/app.js | 42 ++++++++++++++++++++++++++++--------- src/routes.js | 9 ++++---- src/services/crm.js | 51 +++++++++++++++++++++++++++++++++++++++++++++ src/views.js | 8 +++++++ test/crm.test.js | 51 +++++++++++++++++++++++++++++++++++++++++++++ 6 files changed, 153 insertions(+), 15 deletions(-) create mode 100644 src/services/crm.js create mode 100644 test/crm.test.js diff --git a/public/app.css b/public/app.css index d9e3dec..817b301 100644 --- a/public/app.css +++ b/public/app.css @@ -104,3 +104,10 @@ 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 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); } diff --git a/public/app.js b/public/app.js index 427a554..4dddb33 100644 --- a/public/app.js +++ b/public/app.js @@ -357,24 +357,46 @@ // ---------- Liste des prospects (mini CRM) ---------- const STATUS = { new: 'À contacter', sent: 'Contacté', replied: 'A répondu', client: 'Client', refused: 'Refus', bounced: 'Rejeté' }; - $$('details.prospects').forEach((d) => d.addEventListener('toggle', async () => { - if (!d.open) return; + 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 rows = await api(`/api/projects/${proj.dataset.id}/prospects`); - box.innerHTML = rows.length ? `
- ${rows.map((r) => ` - - `).join('')} -
EntrepriseEmailVilleScoreStatut
${r.website ? `${esc(r.company)}` : esc(r.company)}${esc(r.email)}${esc(r.city)}${r.score}
` : '

Aucun prospect.

'; + const r = await api(`/api/projects/${proj.dataset.id}/prospects?${qs}`); + d.dataset.page = r.page; + box.innerHTML = r.rows.length ? `
+ ${r.rows.map((x) => ` + + + `).join('')} +
EntrepriseEmailVilleScoreContactéStatut
${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 }); toast('Statut mis à jour'); } + 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'); } }); })(); diff --git a/src/routes.js b/src/routes.js index 19f9b3f..cd5cf26 100644 --- a/src/routes.js +++ b/src/routes.js @@ -14,6 +14,7 @@ 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 { getProject, listProjects, createProject, saveSecretConfig, publicConfig, globalSmtp, prospectStats, sentSince, repoDir, getTemplate, saveTemplate, abStats, @@ -302,14 +303,12 @@ export function registerRoutes(router, app) { json(res, { business, error, stats, aiCostUsd: cost }); }); - router.get('/api/projects/:id/prospects', ({ res, params }) => { + router.get('/api/projects/:id/prospects', ({ res, params, url }) => { const p = getProject(app, pid(params)); - const rows = db.prepare(`SELECT id, company, email, website, city, sector, score, status, sent_at FROM prospects - WHERE project_id = ? ORDER BY CASE status WHEN 'new' THEN 0 ELSE 1 END, score DESC, id DESC LIMIT 500`).all(p.id); - json(res, rows); + json(res, listProspects(db, p.id, parseFilters(url.searchParams))); }); - const STATUSES = ['new', 'sent', 'replied', 'client', 'refused', 'bounced']; + const STATUSES = Object.keys(PROSPECT_STATUSES); router.post('/api/prospects/:id/status', async ({ req, res, params }) => { const b = await readBody(req); if (!STATUSES.includes(b.status)) throw new HttpError(400, 'Statut invalide'); diff --git a/src/services/crm.js b/src/services/crm.js new file mode 100644 index 0000000..4026d28 --- /dev/null +++ b/src/services/crm.js @@ -0,0 +1,51 @@ +// Prospects : filtres, tri, pagination. Partagé par la liste et l'export CSV. + +export const STATUSES = { + new: 'À contacter', sent: 'Contacté', replied: 'A répondu', client: 'Client', refused: 'Refus', bounced: 'Rejeté', +}; + +const SORTS = { + score: 'score DESC, id DESC', + recent: 'created_at DESC, id DESC', + contacted: 'COALESCE(sent_at, 0) DESC, id DESC', + company: 'company COLLATE NOCASE, id', +}; + +const int = (v, min, max, def) => { + const n = Math.floor(Number(v)); + return Number.isFinite(n) ? Math.max(min, Math.min(max, n)) : def; +}; + +/** Filtres depuis une query string (valeurs inconnues ignorées, jamais injectées dans le SQL). */ +export function parseFilters(sp) { + return { + q: String(sp.get('q') || '').trim().slice(0, 100), + 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', + page: int(sp.get('page'), 1, 100_000, 1), + }; +} + +export function filterWhere(projectId, f) { + const where = ['project_id = ?']; + const args = [projectId]; + if (f.q) { + const like = `%${f.q.replace(/[\\%_]/g, (c) => `\\${c}`)}%`; + where.push("(company LIKE ? ESCAPE '\\' OR email LIKE ? ESCAPE '\\' OR city LIKE ? ESCAPE '\\' OR sector LIKE ? ESCAPE '\\')"); + args.push(like, like, like, like); + } + if (f.status) { where.push('status = ?'); args.push(f.status); } + if (f.minScore) { where.push('score >= ?'); args.push(f.minScore); } + return { sql: where.join(' AND '), args, order: SORTS[f.sort] || SORTS.score }; +} + +export function listProspects(db, projectId, f, { limit = 100 } = {}) { + const { sql, args, order } = filterWhere(projectId, f); + 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 + FROM prospects WHERE ${sql} ORDER BY ${order} LIMIT ? OFFSET ?`).all(...args, limit, (page - 1) * limit); + return { total, page, pages, rows }; +} diff --git a/src/views.js b/src/views.js index 053719c..20dce14 100644 --- a/src/views.js +++ b/src/views.js @@ -1,4 +1,5 @@ import { esc } from './http.js'; +import { STATUSES } from './services/crm.js'; const fmtDate = (ts) => (ts ? new Date(ts * 1000).toLocaleString('fr-FR', { dateStyle: 'short', timeStyle: 'short', timeZone: 'Europe/Paris' }) : '—'); @@ -179,7 +180,14 @@ function projectItem(p, smtp, dbCfg, imap) {
Prospects +
+ + + + +
+
diff --git a/test/crm.test.js b/test/crm.test.js new file mode 100644 index 0000000..f729214 --- /dev/null +++ b/test/crm.test.js @@ -0,0 +1,51 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { openDb, now } from '../src/db.js'; +import { parseFilters, listProspects } from '../src/services/crm.js'; + +function setup() { + const db = openDb(':memory:'); + db.prepare("INSERT INTO projects(name, git_url, created_at) VALUES('A', 'a', ?), ('B', 'b', ?)").run(now(), now()); + const add = (project, company, email, o = {}) => db.prepare(`INSERT INTO prospects(project_id, company, email, city, sector, score, status, sent_at, created_at) + VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(project, company, email, o.city ?? 'Rennes', o.sector ?? 'boulangerie', o.score ?? 5, o.status ?? 'new', o.sent ?? null, o.created ?? now()); + add(1, 'Le Fournil', 'contact@fournil.fr', { score: 9, status: 'replied', sent: now() - 100 }); + add(1, 'Coiffure Zen', 'hello@zen.fr', { city: 'Vern-sur-Seiche', sector: 'coiffeur', score: 6, status: 'sent', sent: now() - 50 }); + add(1, 'Fleurs & Co', 'bonjour@fleurs.fr', { sector: 'fleuriste', score: 3, created: now() - 1000 }); + add(1, '100% Bio', 'bio@100pourcent.fr', { score: 7 }); + add(2, 'Le Fournil', 'contact@fournil.fr', { score: 10 }); + return db; +} +const f = (o = {}) => parseFilters(new URLSearchParams(o)); +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 }); +}); + +test('recherche, filtres, tri, et isolation entre projets', () => { + const db = setup(); + assert.deepEqual(names(listProspects(db, 1, f())), ['Le Fournil', '100% Bio', 'Coiffure Zen', 'Fleurs & Co'], 'tri par score'); + assert.deepEqual(names(listProspects(db, 1, f({ q: 'ZEN' }))), ['Coiffure Zen'], 'insensible à la casse'); + assert.deepEqual(names(listProspects(db, 1, f({ q: 'vern' }))), ['Coiffure Zen'], 'par ville'); + assert.deepEqual(names(listProspects(db, 1, f({ q: 'fleuriste' }))), ['Fleurs & Co'], 'par secteur'); + assert.deepEqual(names(listProspects(db, 1, f({ q: '100%' }))), ['100% Bio'], '% littéral, pas un joker'); + assert.deepEqual(names(listProspects(db, 1, f({ q: '_' }))), [], '_ littéral, pas un joker'); + assert.deepEqual(names(listProspects(db, 1, f({ status: 'sent' }))), ['Coiffure Zen']); + assert.deepEqual(names(listProspects(db, 1, f({ minScore: '7' }))), ['Le Fournil', '100% Bio']); + assert.deepEqual(names(listProspects(db, 1, f({ sort: 'company' }))), ['100% Bio', 'Coiffure Zen', 'Fleurs & Co', 'Le Fournil']); + assert.deepEqual(names(listProspects(db, 1, f({ sort: 'contacted' }))).slice(0, 2), ['Coiffure Zen', 'Le Fournil']); + assert.equal(listProspects(db, 2, f()).total, 1, 'jamais les prospects d\'un autre projet'); +}); + +test('pagination', () => { + const db = setup(); + for (let i = 0; i < 250; i++) db.prepare("INSERT INTO prospects(project_id, company, email, score, created_at) VALUES(1, ?, ?, 1, ?)").run(`E${i}`, `e${i}@x.fr`, now()); + const p1 = listProspects(db, 1, f()); + assert.deepEqual({ total: p1.total, pages: p1.pages, n: p1.rows.length }, { total: 254, pages: 3, n: 100 }); + const p3 = listProspects(db, 1, f({ page: '3' })); + assert.equal(p3.rows.length, 54); + assert.equal(listProspects(db, 1, f({ page: '99' })).page, 3, 'page trop grande ramenée à la dernière'); + 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'); +});