feat: search, filter and paginate prospects
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01SfihHazrSHXgndJtSNLubJ
This commit is contained in:
parent
ce162e728c
commit
1de83faecb
6 changed files with 153 additions and 15 deletions
|
|
@ -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); }
|
||||
|
|
|
|||
|
|
@ -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 ? `<div class="table-wrap"><table><thead><tr><th>Entreprise</th><th>Email</th><th>Ville</th><th>Score</th><th>Statut</th></tr></thead><tbody>
|
||||
${rows.map((r) => `<tr><td>${r.website ? `<a href="${esc(r.website)}" target="_blank" rel="noopener noreferrer">${esc(r.company)}</a>` : esc(r.company)}</td>
|
||||
<td>${esc(r.email)}</td><td>${esc(r.city)}</td><td>${r.score}</td>
|
||||
<td><select data-prospect="${r.id}">${Object.entries(STATUS).map(([k, v]) => `<option value="${k}" ${k === r.status ? 'selected' : ''}>${v}</option>`).join('')}</select></td></tr>`).join('')}
|
||||
</tbody></table></div>` : '<p class="muted small">Aucun prospect.</p>';
|
||||
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>${x.website ? `<a href="${esc(x.website)}" target="_blank" rel="noopener noreferrer">${esc(x.company)}</a>` : esc(x.company)}</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('')}
|
||||
</tbody></table></div>` : '<p class="muted small">Aucun prospect ne correspond.</p>';
|
||||
$('[data-pager]', d).innerHTML = r.pages > 1
|
||||
? `<button type="button" class="btn small" data-page="${r.page - 1}" ${r.page <= 1 ? 'disabled' : ''}>←</button>
|
||||
<span class="small muted">Page ${r.page} / ${r.pages} · ${r.total} prospect(s)</span>
|
||||
<button type="button" class="btn small" data-page="${r.page + 1}" ${r.page >= r.pages ? 'disabled' : ''}>→</button>`
|
||||
: `<span class="small muted">${r.total} prospect(s)</span>`;
|
||||
} catch (err) { box.innerHTML = `<p class="error small">${esc(err.message)}</p>`; }
|
||||
}));
|
||||
}
|
||||
|
||||
$$('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'); }
|
||||
});
|
||||
})();
|
||||
|
|
|
|||
|
|
@ -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');
|
||||
|
|
|
|||
51
src/services/crm.js
Normal file
51
src/services/crm.js
Normal file
|
|
@ -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 };
|
||||
}
|
||||
|
|
@ -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) {
|
|||
</section>
|
||||
|
||||
<details class="prospects"><summary>Prospects <span data-count></span></summary>
|
||||
<form class="pfilters" data-filters>
|
||||
<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>
|
||||
<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>
|
||||
<div class="pager" data-pager></div>
|
||||
</details>
|
||||
</section>
|
||||
|
||||
|
|
|
|||
51
test/crm.test.js
Normal file
51
test/crm.test.js
Normal file
|
|
@ -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');
|
||||
});
|
||||
Loading…
Reference in a new issue