From 8d76fc139bec790c5a42f58f7b65b5e7e81b530b Mon Sep 17 00:00:00 2001 From: Tony Averty Date: Wed, 21 Oct 2026 16:13:16 +0200 Subject: [PATCH] feat: import and export prospects as csv Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01SfihHazrSHXgndJtSNLubJ --- public/app.css | 2 + public/app.js | 28 +++++++++- src/http.js | 4 +- src/routes.js | 20 +++++++ src/services/csv.js | 124 ++++++++++++++++++++++++++++++++++++++++++++ src/views.js | 6 +++ test/csv.test.js | 80 ++++++++++++++++++++++++++++ test/http.test.js | 15 ++++++ 8 files changed, 276 insertions(+), 3 deletions(-) create mode 100644 src/services/csv.js create mode 100644 test/csv.test.js diff --git a/public/app.css b/public/app.css index 593268f..fb4f2d6 100644 --- a/public/app.css +++ b/public/app.css @@ -125,3 +125,5 @@ select.st-new { color: var(--accent); } .note-body { white-space: pre-wrap; } .pfilters .todo { margin: 0; align-self: center; } @media (max-width: 640px) { .pfilters .todo { grid-column: 1 / -1; } } +.csv { justify-content: flex-start; margin: 4px 0 8px; } +label.btn.file { display: inline-block; margin: 0; color: var(--text); font-size: .85rem; } diff --git a/public/app.js b/public/app.js index 67c27c8..6bae10b 100644 --- a/public/app.js +++ b/public/app.js @@ -441,6 +441,29 @@ } catch (err) { toast(err.message, 'error'); } }); } + // Import CSV : Excel enregistre souvent en Windows-1252, on détecte pour ne pas abîmer les accents + document.addEventListener('change', async (e) => { + const input = e.target.closest('[data-import]'); + if (!input?.files?.length) return; + const file = input.files[0]; + input.value = ''; + const d = input.closest('details.prospects'); + const report = $('[data-import-report]', d); + if (file.size > 1024 * 1024) { toast('Fichier trop gros (1 Mo max, environ 2000 lignes)', 'error'); return; } + const buf = await file.arrayBuffer(); + let csv; + try { csv = new TextDecoder('utf-8', { fatal: true }).decode(buf); } + catch { csv = new TextDecoder('windows-1252').decode(buf); } + try { + const r = await api(`/api/projects/${input.dataset.import}/prospects/import`, { csv }); + report.innerHTML = `

${r.imported} importé(s) sur ${r.total} · + ${r.duplicates} déjà présent(s) · ${r.blacklisted} sur liste d'opposition · ${r.invalid.length} invalide(s)

+ ${r.invalid.length ? `
Lignes ignorées
    ${r.invalid.map((x) => `
  • Ligne ${x.line} : ${esc(x.reason)}
  • `).join('')}
` : ''}`; + toast(`${r.imported} prospect(s) importé(s)`); + loadProspects(d); + } catch (err) { report.innerHTML = ''; toast(err.message, 'error'); } + }); + document.addEventListener('click', (e) => { const b = e.target.closest('[data-open-prospect]'); if (b) openProspect(b.dataset.openProspect); @@ -451,7 +474,10 @@ 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 }); + const filters = formData($('[data-filters]', d)); + const qs = new URLSearchParams({ ...filters, page }); + // L'export suit les filtres affichés + $('[data-export]', d).href = `/api/projects/${proj.dataset.id}/prospects.csv?${new URLSearchParams(filters)}`; try { const r = await api(`/api/projects/${proj.dataset.id}/prospects?${qs}`); d.dataset.page = r.page; diff --git a/src/http.js b/src/http.js index c3b61c0..0ef74f5 100644 --- a/src/http.js +++ b/src/http.js @@ -42,12 +42,12 @@ export function setCookie(res, name, value, { maxAge, httpOnly = true } = {}) { const MAX_BODY = 256 * 1024; -export async function readBody(req) { +export async function readBody(req, { max = MAX_BODY } = {}) { const chunks = []; let size = 0; for await (const c of req) { size += c.length; - if (size > MAX_BODY) throw Object.assign(new Error('Requête trop volumineuse'), { status: 413 }); + if (size > max) throw Object.assign(new Error('Requête trop volumineuse'), { status: 413 }); chunks.push(c); } const raw = Buffer.concat(chunks).toString('utf8'); diff --git a/src/routes.js b/src/routes.js index 4eb3f97..70f4bd8 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 { exportProspects, importProspects } from './services/csv.js'; import { listProspects, parseFilters, STATUSES as PROSPECT_STATUSES, prospectDetail, addNote, deleteNote, setNextAction, } from './services/crm.js'; @@ -305,6 +306,25 @@ export function registerRoutes(router, app) { json(res, { business, error, stats, aiCostUsd: cost }); }); + router.get('/api/projects/:id/prospects\\.csv', ({ res, params, url }) => { + const p = getProject(app, pid(params)); + const slug = p.name.normalize('NFD').replace(/[^\w-]+/g, '-').replace(/^-|-$/g, '').toLowerCase() || 'projet'; + const date = new Date().toLocaleDateString('sv-SE', { timeZone: 'Europe/Paris' }); + res.writeHead(200, { + 'Content-Type': 'text/csv; charset=utf-8', + 'Content-Disposition': `attachment; filename="prospects-${slug}-${date}.csv"`, + 'Cache-Control': 'no-store', + }); + res.end(exportProspects(db, p.id, parseFilters(url.searchParams))); + }); + + router.post('/api/projects/:id/prospects/import', async ({ req, res, params }) => { + const p = getProject(app, pid(params)); + const b = await readBody(req, { max: 1024 * 1024 }); + try { json(res, importProspects(db, p.id, String(b.csv || ''))); } + catch (e) { throw new HttpError(400, e.message); } + }); + router.get('/api/projects/:id/prospects', ({ res, params, url }) => { const p = getProject(app, pid(params)); json(res, listProspects(db, p.id, parseFilters(url.searchParams))); diff --git a/src/services/csv.js b/src/services/csv.js new file mode 100644 index 0000000..4f89c04 --- /dev/null +++ b/src/services/csv.js @@ -0,0 +1,124 @@ +// Import / export CSV des prospects. Format Excel FR : ";" + BOM UTF-8. +import { now } from '../db.js'; +import { EMAIL_RE } from './mailer.js'; +import { httpUrl } from '../handlers.js'; +import { filterWhere, STATUSES } from './crm.js'; + +// ---------- Écriture ---------- + +// Excel exécute une cellule qui commence par = + - @ : on la neutralise (OWASP CSV injection) +const FORMULA = /^[=+\-@\t\r]/; + +export function csvCell(v) { + let s = v == null ? '' : String(v); + if (FORMULA.test(s)) s = `'${s}`; + return /[";\r\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s; +} + +export function toCsv(header, rows) { + return '' + [header, ...rows].map((r) => r.map(csvCell).join(';')).join('\r\n') + '\r\n'; +} + +const day = (ts) => (ts ? new Date(ts * 1000).toLocaleString('sv-SE', { timeZone: 'Europe/Paris' }).slice(0, 16) : ''); + +export function exportProspects(db, projectId, filters) { + const { sql, args, order } = filterWhere(projectId, filters); + const rows = db.prepare(`SELECT * FROM prospects WHERE ${sql} ORDER BY ${order} LIMIT 10000`).all(...args); + const header = ['Entreprise', 'Email', 'Site', 'Ville', 'Secteur', 'Score', 'Statut', 'Ajouté le', 'Contacté le', 'Objet', + 'Relancé le', 'Répondu le', 'Prochaine action', 'Échéance', 'Source', 'Accroche']; + return toCsv(header, rows.map((p) => [ + p.company, p.email, p.website, p.city, p.sector, p.score, STATUSES[p.status] || p.status, day(p.created_at), day(p.sent_at), + p.variant, day(p.followup_at), day(p.replied_at), p.next_action, day(p.next_action_at), p.source, p.hook, + ])); +} + +// ---------- Lecture ---------- + +/** CSV RFC 4180 : guillemets, "" échappés, retours à la ligne dans les cellules, séparateur ; , ou tab. */ +export function parseCsv(text) { + const src = String(text).replace(/^/, ''); + const firstLine = src.slice(0, src.search(/\r?\n|$/)); + const count = (c) => firstLine.split(c).length - 1; + const sep = [';', ',', '\t'].sort((a, b) => count(b) - count(a))[0]; + const rows = []; + let row = [], cell = '', quoted = false; + for (let i = 0; i < src.length; i++) { + const c = src[i]; + if (quoted) { + if (c === '"' && src[i + 1] === '"') { cell += '"'; i++; } + else if (c === '"') quoted = false; + else cell += c; + } else if (c === '"' && cell === '') quoted = true; + else if (c === sep) { row.push(cell); cell = ''; } + else if (c === '\n' || c === '\r') { + if (c === '\r' && src[i + 1] === '\n') i++; + row.push(cell); rows.push(row); row = []; cell = ''; + } else cell += c; + } + if (cell !== '' || row.length) { row.push(cell); rows.push(row); } + return rows.filter((r) => r.some((x) => x.trim() !== '')); +} + +const norm = (s) => String(s).normalize('NFD').replace(/[̀-ͯ]/g, '').toLowerCase().replace(/[^a-z]/g, ''); +const ALIASES = { + company: ['entreprise', 'societe', 'company', 'nom', 'raisonsociale', 'name', 'enseigne'], + email: ['email', 'mail', 'courriel', 'adresseemail', 'adressemail', 'emailaddress'], + website: ['site', 'website', 'url', 'siteweb', 'siteinternet'], + city: ['ville', 'city', 'commune', 'localite'], + sector: ['secteur', 'sector', 'activite', 'metier', 'categorie'], + score: ['score', 'note', 'pertinence'], + source: ['source', 'origine'], + hook: ['accroche', 'hook'], +}; +const MAX_ROWS = 2000; + +// Notre propre export préfixe les formules par ' : on l'enlève à la relecture +const unformula = (s) => (/^'[=+\-@]/.test(s) ? s.slice(1) : s); + +export function importProspects(db, projectId, text, { at = now() } = {}) { + const rows = parseCsv(text); + if (rows.length < 2) throw new Error('Fichier vide ou sans en-tête'); + const header = rows[0].map(norm); + const col = {}; + for (const [field, names] of Object.entries(ALIASES)) { + const i = header.findIndex((h) => names.includes(h)); + if (i >= 0) col[field] = i; + } + if (col.email === undefined) throw new Error('Colonne email introuvable (attendu : "email", "mail" ou "courriel")'); + const data = rows.slice(1); + if (data.length > MAX_ROWS) throw new Error(`Maximum ${MAX_ROWS} lignes par import (${data.length} dans le fichier)`); + + const dateLabel = new Date(at * 1000).toLocaleDateString('fr-FR', { timeZone: 'Europe/Paris' }); + const exists = db.prepare('SELECT 1 FROM prospects WHERE project_id = ? AND email = ?'); + const optOut = db.prepare('SELECT 1 FROM blacklist WHERE email = ?'); + const insert = db.prepare(`INSERT INTO prospects(project_id, company, email, website, city, sector, score, source, hook, created_at) + VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`); + const res = { total: data.length, imported: 0, duplicates: 0, blacklisted: 0, invalid: [] }; + const seen = new Set(); + const get = (r, k, max = 200) => (col[k] === undefined ? '' : unformula(String(r[col[k]] ?? '').trim()).slice(0, max)); + + db.exec('BEGIN'); + try { + data.forEach((r, i) => { + const line = i + 2; + const email = get(r, 'email').toLowerCase(); + if (!EMAIL_RE.test(email)) { if (res.invalid.length < 50) res.invalid.push({ line, reason: `email invalide : "${email || 'vide'}"` }); return; } + if (seen.has(email) || exists.get(projectId, email)) { res.duplicates++; return; } + seen.add(email); + if (optOut.get(email)) { res.blacklisted++; return; } + const s = Number(get(r, 'score')); + insert.run( + projectId, get(r, 'company') || email.split('@')[1], email, httpUrl(get(r, 'website', 300)), get(r, 'city', 100) || null, + get(r, 'sector', 100) || null, Number.isFinite(s) && s > 0 ? Math.max(1, Math.min(10, Math.round(s))) : null, + // RGPD : on garde toujours l'origine de la donnée + httpUrl(get(r, 'source', 300)) || get(r, 'source', 300) || `Import CSV du ${dateLabel}`, get(r, 'hook', 400) || null, at, + ); + res.imported++; + }); + db.exec('COMMIT'); + } catch (e) { + db.exec('ROLLBACK'); + throw e; + } + return res; +} diff --git a/src/views.js b/src/views.js index 3af1935..0fb0a96 100644 --- a/src/views.js +++ b/src/views.js @@ -187,6 +187,12 @@ function projectItem(p, smtp, dbCfg, imap) { +
+ Exporter (CSV) + + Colonnes reconnues : entreprise, email, site, ville, secteur, score, source, accroche. +
+
diff --git a/test/csv.test.js b/test/csv.test.js new file mode 100644 index 0000000..9080d20 --- /dev/null +++ b/test/csv.test.js @@ -0,0 +1,80 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { openDb, now } from '../src/db.js'; +import { csvCell, toCsv, parseCsv, exportProspects, importProspects } from '../src/services/csv.js'; +import { parseFilters } from '../src/services/crm.js'; + +const f = (o = {}) => parseFilters(new URLSearchParams(o)); +function setup() { + const db = openDb(':memory:'); + db.prepare("INSERT INTO projects(name, git_url, created_at) VALUES('A', 'a', ?), ('B', 'b', ?)").run(now(), now()); + return db; +} + +test('cellules : guillemets, ; et retours à la ligne échappés, formules neutralisées', () => { + assert.equal(csvCell('Le "Fournil"; Rennes'), '"Le ""Fournil""; Rennes"'); + assert.equal(csvCell('ligne 1\nligne 2'), '"ligne 1\nligne 2"'); + assert.equal(csvCell('=HYPERLINK("http://evil","clic")'), '"\'=HYPERLINK(""http://evil"",""clic"")"'); + for (const s of ['+33612', '-2+3', '@SUM(A1)']) assert.equal(csvCell(s)[0] === '"' ? csvCell(s)[1] : csvCell(s)[0], "'", s); + assert.equal(csvCell(null), ''); + assert.equal(csvCell(7), '7'); + assert.ok(toCsv(['a'], [['b']]).startsWith('a\r\nb'), 'BOM + CRLF pour Excel'); +}); + +test('parseCsv : séparateur détecté, guillemets, retours à la ligne, BOM, lignes vides', () => { + assert.deepEqual(parseCsv('a;b\r\n1;"x;y"\r\n\r\n2;"multi\nligne ""ok"""\n'), [['a', 'b'], ['1', 'x;y'], ['2', 'multi\nligne "ok"']]); + assert.deepEqual(parseCsv('email,company\nx@y.fr,"Dupont, fils"'), [['email', 'company'], ['x@y.fr', 'Dupont, fils']]); + assert.deepEqual(parseCsv('email\tville\nx@y.fr\tBrest'), [['email', 'ville'], ['x@y.fr', 'Brest']]); +}); + +test('import : en-têtes souples, doublons, opposition, invalides, origine RGPD', () => { + const db = setup(); + db.prepare("INSERT INTO prospects(project_id, company, email, created_at) VALUES(1, 'Déjà', 'deja@la.fr', ?)").run(now()); + db.prepare("INSERT INTO blacklist(email, reason, created_at) VALUES('stop@moi.fr', 'unsubscribe', ?)").run(now()); + const csv = [ + 'Raison sociale;E-mail;Site web;Commune;Activité;Note;Origine', + 'Crêperie Ty Breizh;Contact@TyBreizh.bzh;https://tybreizh.bzh;Quimper;crêperie;8;annuaire CCI', + ';sans-nom@atelier.fr;javascript:alert(1);;;;', + 'Déjà;deja@la.fr;;;;;', + 'Doublon;contact@tybreizh.bzh;;;;;', + 'Stop;stop@moi.fr;;;;;', + 'Cassé;pas-un-email;;;;;', + "Formule;f@x.fr;;'=1+1;;99;", + ].join('\r\n'); + const r = importProspects(db, 1, csv, { at: Date.parse('2026-10-21T10:00:00Z') / 1000 }); + assert.deepEqual({ ...r, invalid: r.invalid.map((x) => x.line) }, { total: 7, imported: 3, duplicates: 2, blacklisted: 1, invalid: [7] }); + const get = (email) => db.prepare('SELECT * FROM prospects WHERE project_id = 1 AND email = ?').get(email); + const ty = get('contact@tybreizh.bzh'); + assert.deepEqual([ty.company, ty.website, ty.city, ty.sector, ty.score, ty.source, ty.status], ['Crêperie Ty Breizh', 'https://tybreizh.bzh', 'Quimper', 'crêperie', 8, 'annuaire CCI', 'new']); + const sn = get('sans-nom@atelier.fr'); + assert.equal(sn.company, 'atelier.fr', 'nom déduit du domaine'); + assert.equal(sn.website, null, 'javascript: rejeté'); + assert.equal(sn.source, 'Import CSV du 21/10/2026', 'origine toujours renseignée'); + assert.equal(get('f@x.fr').city, '=1+1', 'apostrophe de notre export retirée'); + assert.equal(get('f@x.fr').score, 10, 'score borné'); + assert.equal(db.prepare('SELECT COUNT(*) n FROM prospects WHERE project_id = 2').get().n, 0, 'rien dans l\'autre projet'); +}); + +test('import : erreurs claires', () => { + const db = setup(); + assert.throws(() => importProspects(db, 1, 'email\n'), /vide ou sans en-tête/); + assert.throws(() => importProspects(db, 1, 'nom;ville\nA;B'), /Colonne email introuvable/); + assert.throws(() => importProspects(db, 1, 'email\n' + 'a@b.fr\n'.repeat(2001)), /Maximum 2000 lignes/); +}); + +test('export puis réimport dans un autre projet : aller-retour sans perte', () => { + const db = setup(); + db.prepare(`INSERT INTO prospects(project_id, company, email, website, city, sector, score, status, source, hook, created_at) + VALUES(1, 'Le "Fournil"; SARL', 'c@fournil.fr', 'https://fournil.fr', 'Rennes', 'boulangerie', 9, 'replied', 'https://fournil.fr/contact', '=Votre pain mérite mieux', ?)`).run(now()); + db.prepare("INSERT INTO prospects(project_id, company, email, score, status, created_at) VALUES(1, 'Zen', 'z@zen.fr', 4, 'new', ?)").run(now()); + const all = exportProspects(db, 1, f()); + assert.match(all, /^Entreprise;Email;Site/); + assert.match(all, /"Le ""Fournil""; SARL";c@fournil\.fr/); + assert.match(all, /'=Votre pain/, 'formule neutralisée'); + assert.match(all, /;A répondu;/, 'statut lisible'); + assert.equal(exportProspects(db, 1, f({ minScore: '5' })).trim().split('\r\n').length, 2, 'l\'export suit les filtres'); + const r = importProspects(db, 2, all); + assert.equal(r.imported, 2); + const back = db.prepare("SELECT company, website, source, hook, score FROM prospects WHERE project_id = 2 AND email = 'c@fournil.fr'").get(); + assert.deepEqual({ ...back }, { company: 'Le "Fournil"; SARL', website: 'https://fournil.fr', source: 'https://fournil.fr/contact', hook: '=Votre pain mérite mieux', score: 9 }); +}); diff --git a/test/http.test.js b/test/http.test.js index 490aad4..a92923b 100644 --- a/test/http.test.js +++ b/test/http.test.js @@ -231,3 +231,18 @@ test('fiche prospect : routes notes et prochaine action', async () => { const list = await (await get(`/api/projects/${pid}/prospects?q=atelier`)).json(); assert.equal(list.rows[0].next_action, 'Rappeler'); }); + +test('CSV : export en pièce jointe, import via l\'API', async () => { + const pid = app.db.prepare('SELECT id FROM projects LIMIT 1').get().id; + let r = await get(`/api/projects/${pid}/prospects.csv?q=atelier`); + assert.equal(r.status, 200); + assert.match(r.headers.get('content-type'), /text\/csv/); + assert.match(r.headers.get('content-disposition'), /attachment; filename="prospects-mep-\d{4}-\d{2}-\d{2}\.csv"/); + assert.match(await r.text(), /a@atelier\.fr/); + r = await post(`/api/projects/${pid}/prospects/import`, { csv: 'email;entreprise\nnouveau@client.fr;Nouveau' }); + assert.deepEqual(await r.json(), { total: 1, imported: 1, duplicates: 0, blacklisted: 0, invalid: [] }); + r = await post(`/api/projects/${pid}/prospects/import`, { csv: 'nom\nx' }); + assert.equal(r.status, 400); + r = await fetch(`${base}/api/projects/${pid}/prospects.csv`); + assert.equal(r.status, 401, 'pas d\'export sans session'); +});