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 ? `
| Entreprise | Ville | Score | Statut | |
|---|---|---|---|---|
| ${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 ? `| Entreprise | Ville | Score | Contacté | 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) {