${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) {
+