diff --git a/src/db.js b/src/db.js index e42528b..6818c41 100644 --- a/src/db.js +++ b/src/db.js @@ -1,169 +1,240 @@ +// Couche d'accès aux données : une seule API asynchrone, deux drivers. +// - MySQL / MariaDB (mysql2/promise, pool) en production ; +// - SQLite en mémoire (node:sqlite) pour les tests locaux, sans serveur à installer. +// Le SQL de l'application est écrit dans un sous-ensemble commun ; translate() ne fait que le strict +// minimum entre dialectes (voir plus bas). Les requêtes vraiment différentes sont réécrites à la source. import { DatabaseSync } from 'node:sqlite'; import { mkdirSync } from 'node:fs'; -import { join } from 'node:path'; +import { dirname } from 'node:path'; +import { MIGRATIONS } from './migrations.js'; -// Chaque entrée = une migration. Ne jamais modifier une migration déjà livrée, en ajouter une. -export const MIGRATIONS = [ - ` - CREATE TABLE sessions ( - id TEXT PRIMARY KEY, email TEXT NOT NULL, - created_at INTEGER NOT NULL, expires_at INTEGER NOT NULL - ); - CREATE TABLE oauth_states ( - state TEXT PRIMARY KEY, verifier TEXT NOT NULL, nonce TEXT NOT NULL, created_at INTEGER NOT NULL - ); - CREATE TABLE settings (key TEXT PRIMARY KEY, value TEXT); - CREATE TABLE projects ( - id INTEGER PRIMARY KEY, - name TEXT NOT NULL, - git_url TEXT NOT NULL UNIQUE, - profile_json TEXT, -- fiche projet générée par Claude - profile_commit TEXT, -- commit analysé - profile_at INTEGER, - target_json TEXT, -- cible déduite (modifiable) - target_validated INTEGER NOT NULL DEFAULT 0, - smtp_enc TEXT, -- config SMTP chiffrée - db_enc TEXT, -- accès BDD chiffré (récap) - daily_mail_cap INTEGER NOT NULL DEFAULT 30, - created_at INTEGER NOT NULL - ); - CREATE TABLE mail_templates ( - project_id INTEGER PRIMARY KEY REFERENCES projects(id) ON DELETE CASCADE, - subject TEXT NOT NULL, body TEXT NOT NULL, - status TEXT NOT NULL DEFAULT 'draft', -- draft | validated - updated_at INTEGER NOT NULL - ); - CREATE TABLE prospects ( - id INTEGER PRIMARY KEY, - project_id INTEGER NOT NULL REFERENCES projects(id) ON DELETE CASCADE, - company TEXT NOT NULL, email TEXT NOT NULL, website TEXT, city TEXT, sector TEXT, - hook TEXT, -- accroche perso (1 phrase) - source TEXT, -- page où l'email a été trouvé (RGPD : origine des données) - score INTEGER, - status TEXT NOT NULL DEFAULT 'new', -- new | sent | replied | client | refused | bounced - sent_at INTEGER, created_at INTEGER NOT NULL, - UNIQUE(project_id, email) - ); - CREATE INDEX prospects_project ON prospects(project_id, status); - CREATE TABLE blacklist (email TEXT PRIMARY KEY, reason TEXT, created_at INTEGER NOT NULL); - CREATE TABLE jobs ( - id INTEGER PRIMARY KEY, - project_id INTEGER REFERENCES projects(id) ON DELETE CASCADE, - type TEXT NOT NULL, -- analyze | prospect | template | send | evolution - status TEXT NOT NULL DEFAULT 'queued', -- queued | running | done | error | cancelled - params_json TEXT, progress_json TEXT, result_json TEXT, error TEXT, - cost_usd REAL, tokens_in INTEGER, tokens_out INTEGER, - created_at INTEGER NOT NULL, started_at INTEGER, finished_at INTEGER - ); - CREATE INDEX jobs_status ON jobs(status, id); - CREATE TABLE mail_log ( - id INTEGER PRIMARY KEY, - project_id INTEGER NOT NULL REFERENCES projects(id) ON DELETE CASCADE, - prospect_id INTEGER, email TEXT NOT NULL, sent_at INTEGER NOT NULL, error TEXT - ); - CREATE INDEX mail_log_day ON mail_log(project_id, sent_at); - `, - // 2 — modèles de mail par type (premier mail / relance) - ` - CREATE TABLE templates ( - project_id INTEGER NOT NULL REFERENCES projects(id) ON DELETE CASCADE, - kind TEXT NOT NULL CHECK (kind IN ('initial', 'followup')), - subject TEXT NOT NULL DEFAULT '', -- relance : vide = "Re: " - body TEXT NOT NULL, - status TEXT NOT NULL DEFAULT 'draft', - updated_at INTEGER NOT NULL, - PRIMARY KEY (project_id, kind) - ); - INSERT INTO templates(project_id, kind, subject, body, status, updated_at) - SELECT project_id, 'initial', subject, body, status, updated_at FROM mail_templates; - DROP TABLE mail_templates; - `, - // 3 — suivi des mails envoyés + test A/B de l'objet - ` - ALTER TABLE templates ADD COLUMN subject_b TEXT; -- objet B (premier mail uniquement) - ALTER TABLE prospects ADD COLUMN variant TEXT; -- A | B - ALTER TABLE mail_log ADD COLUMN kind TEXT NOT NULL DEFAULT 'initial'; - ALTER TABLE mail_log ADD COLUMN variant TEXT; - ALTER TABLE mail_log ADD COLUMN subject TEXT; - ALTER TABLE mail_log ADD COLUMN message_id TEXT; - CREATE INDEX mail_log_msgid ON mail_log(message_id); - `, - // 4 — détection des réponses via IMAP - ` - ALTER TABLE prospects ADD COLUMN replied_at INTEGER; - ALTER TABLE prospects ADD COLUMN reply_subject TEXT; - ALTER TABLE projects ADD COLUMN imap_enc TEXT; - ALTER TABLE projects ADD COLUMN inbox_json TEXT; -- état de la dernière lecture IMAP - `, - // 5 — relance automatique - ` - ALTER TABLE prospects ADD COLUMN followup_at INTEGER; - ALTER TABLE projects ADD COLUMN followup_enabled INTEGER NOT NULL DEFAULT 0; - ALTER TABLE projects ADD COLUMN followup_days INTEGER NOT NULL DEFAULT 7; - `, - // 6 — jobs programmés (la nuit) - ` - ALTER TABLE jobs ADD COLUMN run_after INTEGER; -- ne pas démarrer avant (epoch s) - `, - // 7 — fiche prospect : notes et prochaine action - ` - CREATE TABLE prospect_notes ( - id INTEGER PRIMARY KEY, - prospect_id INTEGER NOT NULL REFERENCES prospects(id) ON DELETE CASCADE, - body TEXT NOT NULL, - created_at INTEGER NOT NULL - ); - CREATE INDEX prospect_notes_p ON prospect_notes(prospect_id, created_at); - ALTER TABLE prospects ADD COLUMN next_action TEXT; - ALTER TABLE prospects ADD COLUMN next_action_at INTEGER; - `, - // 8 — historique quotidien des KPI business (pour les courbes) - ` - CREATE TABLE metrics_daily ( - project_id INTEGER NOT NULL REFERENCES projects(id) ON DELETE CASCADE, - day TEXT NOT NULL, -- AAAA-MM-JJ, heure de Paris - users REAL, clients REAL, revenue REAL, - PRIMARY KEY (project_id, day) - ); - `, -]; +export { MIGRATIONS }; -export function openDb(dataDir) { - let db; - if (dataDir === ':memory:') db = new DatabaseSync(':memory:'); - else { - mkdirSync(dataDir, { recursive: true }); - db = new DatabaseSync(join(dataDir, 'aitools.sqlite')); +/** Paramètres de connexion depuis les variables d'environnement (DB_HOST, DB_PORT, DB_USER, DB_PASSWORD, DB_NAME). */ +export function dbConfigFromEnv(env = process.env, prefix = 'DB_') { + const get = (k) => env[`${prefix}${k}`]; + if (get('DRIVER') === 'sqlite') return { driver: 'sqlite', file: get('FILE') || ':memory:' }; + for (const k of ['HOST', 'USER', 'NAME']) { + if (!get(k)) throw new Error(`Variable d'environnement manquante : ${prefix}${k}`); } - // WAL + synchronous NORMAL : moins d'écritures sur la carte SD / SSD - db.exec('PRAGMA journal_mode = WAL; PRAGMA synchronous = NORMAL; PRAGMA foreign_keys = ON; PRAGMA busy_timeout = 5000;'); - migrate(db); + return { + driver: 'mysql', host: get('HOST'), port: Number(get('PORT') || 3306), user: get('USER'), + password: get('PASSWORD') ?? '', database: get('NAME'), + }; +} + +/** + * Traduit le SQL "canonique" (écrit une seule fois dans le code) vers le dialecte cible. + * Forme canonique = celle de SQLite : INSERT OR IGNORE, ON CONFLICT(cols) DO UPDATE SET x = excluded.x. + * Les noms réservés (`key`) sont entre accents graves, acceptés par les deux moteurs. + */ +export function translate(sql, dialect) { + if (dialect !== 'mysql') return sql; + return sql + .replace(/\bINSERT\s+OR\s+IGNORE\b/gi, 'INSERT IGNORE') + .replace(/\bON\s+CONFLICT\s*\([^)]*\)\s*DO\s+UPDATE\s+SET\b/gi, 'ON DUPLICATE KEY UPDATE') + .replace(/\bexcluded\.(\w+)/gi, 'VALUES($1)') + .replace(/\s+COLLATE\s+NOCASE\b/gi, ''); // MySQL compare déjà sans casse (utf8mb4_unicode_ci) +} + +// undefined et NaN (Number('abc') dans une route) deviennent NULL, comme avec SQLite +const norm = (params) => params.map((p) => (p === undefined || (typeof p === 'number' && !Number.isFinite(p)) ? null : p)); + +// API commune : db.prepare(sql).get / all / run(...params), toutes asynchrones. +// Les sous-classes fournissent _exec(sql, params, mode) avec mode = 'get' | 'all' | 'run'. +class Executor { + prepare(sql) { + return { + get: (...params) => this._exec(sql, norm(params), 'get'), + all: (...params) => this._exec(sql, norm(params), 'all'), + /** @returns {Promise<{changes: number, lastInsertRowid: number}>} */ + run: (...params) => this._exec(sql, norm(params), 'run'), + }; + } + + /** Requête libre (renvoie les lignes). */ + query(sql, params = []) { return this._exec(sql, norm(params), 'all'); } +} + +// ---------- MySQL / MariaDB ---------- + +class MysqlExecutor extends Executor { + constructor(conn) { super(); this.conn = conn; } + + async _exec(sql, params, mode) { + const [r] = await this.conn.query(translate(sql, 'mysql'), params); + if (mode === 'get') return r[0]; + if (mode === 'all') return r; + return { changes: r.affectedRows ?? 0, lastInsertRowid: r.insertId ?? 0 }; + } +} + +class MysqlDb extends MysqlExecutor { + constructor(pool) { super(pool); this.pool = pool; this.dialect = 'mysql'; } + + /** fn(tx) reçoit un exécuteur lié à UNE connexion ; commit si tout va bien, rollback sinon. */ + async transaction(fn) { + const conn = await this.pool.getConnection(); + try { + await conn.beginTransaction(); + const result = await fn(new MysqlExecutor(conn)); + await conn.commit(); + return result; + } catch (e) { + await conn.rollback().catch(() => {}); + throw e; + } finally { + conn.release(); + } + } + + close() { return this.pool.end(); } +} + +async function openMysql(cfg) { + const { default: mysql } = await import('mysql2/promise'); + const pool = mysql.createPool({ + host: cfg.host, port: cfg.port || 3306, user: cfg.user, password: cfg.password, database: cfg.database, + charset: 'UTF8MB4_UNICODE_CI', + waitForConnections: true, connectionLimit: cfg.connectionLimit || 10, + decimalNumbers: true, // SUM()/AVG() en nombres, pas en chaînes + supportBigNumbers: true, bigNumberStrings: false, + flags: ['+FOUND_ROWS'], // affectedRows = lignes trouvées (comme SQLite), pas seulement modifiées + timezone: 'Z', + }); + const db = new MysqlDb(pool); + try { await migrateMysql(db); } + catch (e) { await pool.end().catch(() => {}); throw e; } return db; } -function migrate(db) { - const { user_version: current } = db.prepare('PRAGMA user_version').get(); - for (let i = current; i < MIGRATIONS.length; i++) { - db.exec('BEGIN'); +// Verrou applicatif (GET_LOCK) : deux instances qui démarrent en même temps ne migrent pas en parallèle. +// Le verrou est lié à la connexion : on garde la même du début à la fin. +async function migrateMysql(db) { + const conn = await db.pool.getConnection(); + const LOCK = 'aitools_migrate'; + try { + const [[lock]] = await conn.query('SELECT GET_LOCK(?, 60) ok', [LOCK]); + if (lock.ok !== 1) throw new Error('Migrations : verrou non obtenu (une autre instance migre ?)'); try { - db.exec(MIGRATIONS[i]); - db.exec(`PRAGMA user_version = ${i + 1}`); - db.exec('COMMIT'); + await conn.query(`CREATE TABLE IF NOT EXISTS schema_migrations ( + version INT NOT NULL PRIMARY KEY, name VARCHAR(100) NOT NULL, applied_at BIGINT NOT NULL + ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci`); + const [rows] = await conn.query('SELECT version FROM schema_migrations'); + const done = new Set(rows.map((r) => r.version)); + for (let i = 0; i < MIGRATIONS.length; i++) { + const version = i + 1; + if (done.has(version)) continue; + for (const sql of MIGRATIONS[i].mysql) await conn.query(sql); + await conn.query('INSERT INTO schema_migrations(version, name, applied_at) VALUES(?, ?, ?)', + [version, MIGRATIONS[i].name, now()]); + } + } finally { + await conn.query('SELECT RELEASE_LOCK(?)', [LOCK]).catch(() => {}); + } + } finally { + conn.release(); + } +} + +// ---------- SQLite (tests locaux) ---------- + +class SqliteExecutor extends Executor { + constructor(raw) { super(); this.raw = raw; this.cache = new Map(); } + + _stmt(sql) { + let s = this.cache.get(sql); + if (!s) { s = this.raw.prepare(translate(sql, 'sqlite')); this.cache.set(sql, s); } + return s; + } + + _run(sql, params, mode) { + const s = this._stmt(sql); + if (mode === 'get') return s.get(...params); + if (mode === 'all') return s.all(...params); + const r = s.run(...params); + return { changes: Number(r.changes), lastInsertRowid: Number(r.lastInsertRowid) }; + } + + async _exec(sql, params, mode) { return this._run(sql, params, mode); } +} + +class SqliteDb extends SqliteExecutor { + constructor(raw) { super(raw); this.dialect = 'sqlite'; this.txLock = null; } + + // Une seule connexion : pendant une transaction, les autres requêtes attendent sa fin + // (sinon elles s'exécuteraient DANS la transaction). Ne pas appeler db.* depuis le callback : utiliser tx.*. + async _exec(sql, params, mode) { + while (this.txLock) await this.txLock; + return this._run(sql, params, mode); + } + + async transaction(fn) { + while (this.txLock) await this.txLock; + let release; + this.txLock = new Promise((r) => { release = r; }); + this.raw.exec('BEGIN'); + try { + const result = await fn(new SqliteExecutor(this.raw)); + this.raw.exec('COMMIT'); + return result; } catch (e) { - db.exec('ROLLBACK'); + try { this.raw.exec('ROLLBACK'); } catch { /* déjà annulée */ } + throw e; + } finally { + this.txLock = null; + release(); + } + } + + async close() { this.raw.close(); } +} + +function openSqlite(file = ':memory:') { + if (file !== ':memory:') mkdirSync(dirname(file), { recursive: true }); + const raw = new DatabaseSync(file); + raw.exec('PRAGMA foreign_keys = ON; PRAGMA busy_timeout = 5000;'); + const db = new SqliteDb(raw); + raw.exec(`CREATE TABLE IF NOT EXISTS schema_migrations ( + version INTEGER PRIMARY KEY, name TEXT NOT NULL, applied_at INTEGER NOT NULL + )`); + const done = new Set(raw.prepare('SELECT version FROM schema_migrations').all().map((r) => r.version)); + for (let i = 0; i < MIGRATIONS.length; i++) { + const version = i + 1; + if (done.has(version)) continue; + raw.exec('BEGIN'); + try { + for (const sql of MIGRATIONS[i].sqlite) raw.exec(sql); + raw.prepare('INSERT INTO schema_migrations(version, name, applied_at) VALUES(?, ?, ?)').run(version, MIGRATIONS[i].name, now()); + raw.exec('COMMIT'); + } catch (e) { + raw.exec('ROLLBACK'); + raw.close(); throw e; } } + return db; +} + +/** + * Ouvre la base et applique les migrations en attente. + * cfg = { driver: 'mysql', host, port, user, password, database } ou { driver: 'sqlite', file } ; + * sans argument (ou ':memory:') : SQLite en mémoire. + */ +export async function openDb(cfg = ':memory:') { + if (typeof cfg === 'string') return openSqlite(cfg); + if (cfg.driver === 'sqlite') return openSqlite(cfg.file); + return openMysql(cfg); } export const now = () => Math.floor(Date.now() / 1000); -export function getSetting(db, key, fallback = null) { - const row = db.prepare('SELECT value FROM settings WHERE key = ?').get(key); +export async function getSetting(db, key, fallback = null) { + const row = await db.prepare('SELECT value FROM settings WHERE `key` = ?').get(key); return row ? row.value : fallback; } -export function setSetting(db, key, value) { - db.prepare('INSERT INTO settings(key, value) VALUES(?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value') +export async function setSetting(db, key, value) { + await db.prepare('INSERT INTO settings(`key`, value) VALUES(?, ?) ON CONFLICT(`key`) DO UPDATE SET value = excluded.value') .run(key, value); } diff --git a/src/migrations.js b/src/migrations.js new file mode 100644 index 0000000..bf60d28 --- /dev/null +++ b/src/migrations.js @@ -0,0 +1,207 @@ +// Migrations versionnées, en deux dialectes maintenus ENSEMBLE : MySQL/MariaDB (production) +// et SQLite en mémoire (tests locaux). Une entrée = une version, avec les mêmes tables et colonnes +// des deux côtés (test/schema.test.js le vérifie). Ne jamais modifier une migration déjà livrée, +// en ajouter une. Côté MySQL, chaque instruction est idempotente (CREATE ... IF NOT EXISTS) : MySQL +// valide implicitement chaque DDL, une migration interrompue peut donc être rejouée. + +const T = 'ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci'; + +export const MIGRATIONS = [ + { + // Schéma initial = consolidation des 8 migrations SQLite historiques de l'instance perso + name: 'initial', + sqlite: [ + `CREATE TABLE sessions ( + id TEXT PRIMARY KEY, email TEXT NOT NULL, + created_at INTEGER NOT NULL, expires_at INTEGER NOT NULL + )`, + `CREATE TABLE oauth_states ( + state TEXT PRIMARY KEY, verifier TEXT NOT NULL, nonce TEXT NOT NULL, created_at INTEGER NOT NULL + )`, + 'CREATE TABLE settings (key TEXT PRIMARY KEY, value TEXT)', + `CREATE TABLE projects ( + id INTEGER PRIMARY KEY, + name TEXT NOT NULL, + git_url TEXT NOT NULL UNIQUE, + profile_json TEXT, -- fiche projet générée par Claude + profile_commit TEXT, -- commit analysé + profile_at INTEGER, + target_json TEXT, -- cible déduite (modifiable) + target_validated INTEGER NOT NULL DEFAULT 0, + smtp_enc TEXT, -- config SMTP chiffrée + db_enc TEXT, -- accès BDD chiffré (récap) + imap_enc TEXT, -- config IMAP chiffrée + inbox_json TEXT, -- état de la dernière lecture IMAP + daily_mail_cap INTEGER NOT NULL DEFAULT 30, + followup_enabled INTEGER NOT NULL DEFAULT 0, + followup_days INTEGER NOT NULL DEFAULT 7, + created_at INTEGER NOT NULL + )`, + `CREATE TABLE templates ( + project_id INTEGER NOT NULL REFERENCES projects(id) ON DELETE CASCADE, + kind TEXT NOT NULL CHECK (kind IN ('initial', 'followup')), + subject TEXT NOT NULL DEFAULT '', -- relance : vide = "Re: " + subject_b TEXT, -- objet B (premier mail uniquement) + body TEXT NOT NULL, + status TEXT NOT NULL DEFAULT 'draft', + updated_at INTEGER NOT NULL, + PRIMARY KEY (project_id, kind) + )`, + `CREATE TABLE prospects ( + id INTEGER PRIMARY KEY, + project_id INTEGER NOT NULL REFERENCES projects(id) ON DELETE CASCADE, + company TEXT NOT NULL, email TEXT NOT NULL, website TEXT, city TEXT, sector TEXT, + hook TEXT, -- accroche perso (1 phrase) + source TEXT, -- page où l'email a été trouvé (RGPD : origine des données) + score INTEGER, + status TEXT NOT NULL DEFAULT 'new', -- new | sent | replied | client | refused | bounced + variant TEXT, -- A | B + sent_at INTEGER, created_at INTEGER NOT NULL, + replied_at INTEGER, reply_subject TEXT, + followup_at INTEGER, + next_action TEXT, next_action_at INTEGER, + UNIQUE(project_id, email) + )`, + 'CREATE INDEX prospects_project ON prospects(project_id, status)', + 'CREATE TABLE blacklist (email TEXT PRIMARY KEY, reason TEXT, created_at INTEGER NOT NULL)', + `CREATE TABLE jobs ( + id INTEGER PRIMARY KEY, + project_id INTEGER REFERENCES projects(id) ON DELETE CASCADE, + type TEXT NOT NULL, -- analyze | prospect | template | send | evolution… + status TEXT NOT NULL DEFAULT 'queued', -- queued | running | done | error | cancelled + params_json TEXT, progress_json TEXT, result_json TEXT, error TEXT, + cost_usd REAL, tokens_in INTEGER, tokens_out INTEGER, + created_at INTEGER NOT NULL, started_at INTEGER, finished_at INTEGER, + run_after INTEGER -- ne pas démarrer avant (epoch s) + )`, + 'CREATE INDEX jobs_status ON jobs(status, id)', + `CREATE TABLE mail_log ( + id INTEGER PRIMARY KEY, + project_id INTEGER NOT NULL REFERENCES projects(id) ON DELETE CASCADE, + prospect_id INTEGER, email TEXT NOT NULL, sent_at INTEGER NOT NULL, error TEXT, + kind TEXT NOT NULL DEFAULT 'initial', + variant TEXT, subject TEXT, message_id TEXT + )`, + 'CREATE INDEX mail_log_day ON mail_log(project_id, sent_at)', + 'CREATE INDEX mail_log_msgid ON mail_log(message_id)', + `CREATE TABLE prospect_notes ( + id INTEGER PRIMARY KEY, + prospect_id INTEGER NOT NULL REFERENCES prospects(id) ON DELETE CASCADE, + body TEXT NOT NULL, + created_at INTEGER NOT NULL + )`, + 'CREATE INDEX prospect_notes_p ON prospect_notes(prospect_id, created_at)', + `CREATE TABLE metrics_daily ( + project_id INTEGER NOT NULL REFERENCES projects(id) ON DELETE CASCADE, + day TEXT NOT NULL, -- AAAA-MM-JJ, heure de Paris + users REAL, clients REAL, revenue REAL, + PRIMARY KEY (project_id, day) + )`, + ], + mysql: [ + // Identifiants sensibles à la casse (base64url) : collation binaire + `CREATE TABLE IF NOT EXISTS sessions ( + id VARCHAR(128) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL PRIMARY KEY, + email VARCHAR(255) NOT NULL, + created_at BIGINT NOT NULL, expires_at BIGINT NOT NULL + ) ${T}`, + `CREATE TABLE IF NOT EXISTS oauth_states ( + state VARCHAR(128) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL PRIMARY KEY, + verifier VARCHAR(255) NOT NULL, nonce VARCHAR(255) NOT NULL, created_at BIGINT NOT NULL + ) ${T}`, + `CREATE TABLE IF NOT EXISTS settings ( + \`key\` VARCHAR(190) NOT NULL PRIMARY KEY, + value TEXT + ) ${T}`, + `CREATE TABLE IF NOT EXISTS projects ( + id BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY, + name VARCHAR(255) NOT NULL, + git_url VARCHAR(500) NOT NULL, + profile_json MEDIUMTEXT, -- fiche projet générée par Claude + profile_commit VARCHAR(64), -- commit analysé + profile_at BIGINT, + target_json TEXT, -- cible déduite (modifiable) + target_validated TINYINT NOT NULL DEFAULT 0, + smtp_enc TEXT, -- config SMTP chiffrée + db_enc TEXT, -- accès BDD chiffré (récap) + imap_enc TEXT, -- config IMAP chiffrée + inbox_json TEXT, -- état de la dernière lecture IMAP + daily_mail_cap INT NOT NULL DEFAULT 30, + followup_enabled TINYINT NOT NULL DEFAULT 0, + followup_days INT NOT NULL DEFAULT 7, + created_at BIGINT NOT NULL, + UNIQUE KEY projects_git_url (git_url) + ) ${T}`, + `CREATE TABLE IF NOT EXISTS templates ( + project_id BIGINT NOT NULL, + kind VARCHAR(20) NOT NULL, + subject VARCHAR(500) NOT NULL DEFAULT '', -- relance : vide = "Re: " + subject_b VARCHAR(500), -- objet B (premier mail uniquement) + body TEXT NOT NULL, + status VARCHAR(20) NOT NULL DEFAULT 'draft', + updated_at BIGINT NOT NULL, + PRIMARY KEY (project_id, kind), + CONSTRAINT templates_kind CHECK (kind IN ('initial', 'followup')), + CONSTRAINT templates_project FOREIGN KEY (project_id) REFERENCES projects(id) ON DELETE CASCADE + ) ${T}`, + `CREATE TABLE IF NOT EXISTS prospects ( + id BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY, + project_id BIGINT NOT NULL, + company VARCHAR(255) NOT NULL, email VARCHAR(255) NOT NULL, + website VARCHAR(500), city VARCHAR(255), sector VARCHAR(255), + hook TEXT, -- accroche perso (1 phrase) + source TEXT, -- page où l'email a été trouvé (RGPD : origine des données) + score INT, + status VARCHAR(20) NOT NULL DEFAULT 'new', -- new | sent | replied | client | refused | bounced + variant VARCHAR(4), -- A | B + sent_at BIGINT, created_at BIGINT NOT NULL, + replied_at BIGINT, reply_subject TEXT, + followup_at BIGINT, + next_action VARCHAR(255), next_action_at BIGINT, + UNIQUE KEY prospects_project_email (project_id, email), + KEY prospects_project (project_id, status), + CONSTRAINT prospects_project_fk FOREIGN KEY (project_id) REFERENCES projects(id) ON DELETE CASCADE + ) ${T}`, + `CREATE TABLE IF NOT EXISTS blacklist ( + email VARCHAR(255) NOT NULL PRIMARY KEY, reason VARCHAR(255), created_at BIGINT NOT NULL + ) ${T}`, + `CREATE TABLE IF NOT EXISTS jobs ( + id BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY, + project_id BIGINT NULL, + type VARCHAR(40) NOT NULL, -- analyze | prospect | template | send | evolution… + status VARCHAR(20) NOT NULL DEFAULT 'queued', -- queued | running | done | error | cancelled + params_json TEXT, progress_json TEXT, result_json MEDIUMTEXT, error TEXT, + cost_usd DOUBLE, tokens_in BIGINT, tokens_out BIGINT, + created_at BIGINT NOT NULL, started_at BIGINT, finished_at BIGINT, + run_after BIGINT, -- ne pas démarrer avant (epoch s) + KEY jobs_status (status, id), + CONSTRAINT jobs_project FOREIGN KEY (project_id) REFERENCES projects(id) ON DELETE CASCADE + ) ${T}`, + `CREATE TABLE IF NOT EXISTS mail_log ( + id BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY, + project_id BIGINT NOT NULL, + prospect_id BIGINT, email VARCHAR(255) NOT NULL, sent_at BIGINT NOT NULL, error TEXT, + kind VARCHAR(20) NOT NULL DEFAULT 'initial', + variant VARCHAR(4), subject TEXT, message_id VARCHAR(255), + KEY mail_log_day (project_id, sent_at), + KEY mail_log_msgid (message_id), + CONSTRAINT mail_log_project FOREIGN KEY (project_id) REFERENCES projects(id) ON DELETE CASCADE + ) ${T}`, + `CREATE TABLE IF NOT EXISTS prospect_notes ( + id BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY, + prospect_id BIGINT NOT NULL, + body TEXT NOT NULL, + created_at BIGINT NOT NULL, + KEY prospect_notes_p (prospect_id, created_at), + CONSTRAINT prospect_notes_prospect FOREIGN KEY (prospect_id) REFERENCES prospects(id) ON DELETE CASCADE + ) ${T}`, + `CREATE TABLE IF NOT EXISTS metrics_daily ( + project_id BIGINT NOT NULL, + day VARCHAR(10) NOT NULL, -- AAAA-MM-JJ, heure de Paris + users DOUBLE, clients DOUBLE, revenue DOUBLE, + PRIMARY KEY (project_id, day), + CONSTRAINT metrics_daily_project FOREIGN KEY (project_id) REFERENCES projects(id) ON DELETE CASCADE + ) ${T}`, + ], + }, +]; diff --git a/test/db.test.js b/test/db.test.js new file mode 100644 index 0000000..caa06b5 --- /dev/null +++ b/test/db.test.js @@ -0,0 +1,119 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { openDb, translate, dbConfigFromEnv, getSetting, setSetting, now } from '../src/db.js'; +import { testDb } from './helpers/db.js'; + +test('translate : MySQL reçoit INSERT IGNORE, ON DUPLICATE KEY, VALUES() et pas de NOCASE', () => { + const up = 'INSERT INTO t(a, b) VALUES(?, ?) ON CONFLICT(a, b) DO UPDATE SET x = excluded.x, y = excluded.y'; + assert.equal(translate('INSERT OR IGNORE INTO t VALUES(?)', 'mysql'), 'INSERT IGNORE INTO t VALUES(?)'); + assert.equal(translate(up, 'mysql'), 'INSERT INTO t(a, b) VALUES(?, ?) ON DUPLICATE KEY UPDATE x = VALUES(x), y = VALUES(y)'); + assert.equal(translate('SELECT * FROM t ORDER BY name COLLATE NOCASE', 'mysql'), 'SELECT * FROM t ORDER BY name'); + // SQLite : la forme canonique passe telle quelle + assert.equal(translate(up, 'sqlite'), up); + assert.equal(translate('INSERT OR IGNORE INTO t VALUES(?)', 'sqlite'), 'INSERT OR IGNORE INTO t VALUES(?)'); +}); + +test('dbConfigFromEnv : variables DB_*, port par défaut, erreur claire', () => { + assert.deepEqual( + dbConfigFromEnv({ DB_HOST: 'h', DB_USER: 'u', DB_PASSWORD: 'p', DB_NAME: 'n' }), + { driver: 'mysql', host: 'h', port: 3306, user: 'u', password: 'p', database: 'n' }, + ); + assert.equal(dbConfigFromEnv({ DB_HOST: 'h', DB_USER: 'u', DB_NAME: 'n', DB_PORT: '3307' }).port, 3307); + assert.throws(() => dbConfigFromEnv({ DB_HOST: 'h' }), /DB_USER/); + assert.deepEqual(dbConfigFromEnv({ DB_DRIVER: 'sqlite' }), { driver: 'sqlite', file: ':memory:' }); +}); + +test('shim : get / all / run asynchrones, run → changes + lastInsertRowid', async () => { + const db = await testDb(); + const pending = db.prepare('INSERT INTO projects(name, git_url, created_at) VALUES(?, ?, ?)').run('A', 'u1', now()); + assert.ok(pending instanceof Promise); + await pending; + const r1 = await db.prepare('INSERT INTO projects(name, git_url, created_at) VALUES(?, ?, ?)').run('B', 'u2', now()); + assert.equal(r1.changes, 1); + assert.ok(r1.lastInsertRowid > 0); + assert.equal((await db.prepare('SELECT name FROM projects WHERE id = ?').get(r1.lastInsertRowid)).name, 'B'); + assert.equal((await db.prepare('SELECT * FROM projects').all()).length, 2); + assert.equal(await db.prepare('SELECT * FROM projects WHERE id = ?').get(99999), undefined); + assert.equal((await db.prepare('UPDATE projects SET name = ? WHERE git_url = ?').run('Z', 'u2')).changes, 1); + assert.equal((await db.prepare('UPDATE projects SET name = ? WHERE git_url = ?').run('Z', 'nope')).changes, 0); +}); + +test('shim : undefined et NaN deviennent NULL', async () => { + const db = await testDb(); + await db.prepare('INSERT INTO projects(name, git_url, created_at, profile_at) VALUES(?, ?, ?, ?)').run('A', 'u', now(), Number('abc')); + await db.prepare('UPDATE projects SET profile_commit = ? WHERE git_url = ?').run(undefined, 'u'); + const p = await db.prepare('SELECT profile_at, profile_commit FROM projects').get(); + assert.equal(p.profile_at, null); + assert.equal(p.profile_commit, null); +}); + +test('upsert (ON CONFLICT) et INSERT OR IGNORE dans le sous-ensemble commun', async () => { + const db = await testDb(); + await setSetting(db, 'a', '1'); await setSetting(db, 'a', '2'); + assert.equal(await getSetting(db, 'a'), '2'); + assert.equal(await getSetting(db, 'nope', 'x'), 'x'); + await setSetting(db, 'a', null); + assert.equal(await getSetting(db, 'a', 'fallback'), null); + + const ins = db.prepare("INSERT OR IGNORE INTO blacklist(email, reason, created_at) VALUES(?, 'x', ?)"); + assert.equal((await ins.run('a@b.fr', now())).changes, 1); + assert.equal((await ins.run('a@b.fr', now())).changes, 0); +}); + +test('clés étrangères : supprimer un projet supprime ses dépendances (CASCADE)', async () => { + const db = await testDb(); + const { lastInsertRowid: pid } = await db.prepare('INSERT INTO projects(name, git_url, created_at) VALUES(?, ?, ?)').run('A', 'u', now()); + const { lastInsertRowid: prid } = await db.prepare('INSERT INTO prospects(project_id, company, email, created_at) VALUES(?, ?, ?, ?)').run(pid, 'C', 'c@d.fr', now()); + await db.prepare('INSERT INTO prospect_notes(prospect_id, body, created_at) VALUES(?, ?, ?)').run(prid, 'n', now()); + await db.prepare('INSERT INTO jobs(project_id, type, created_at) VALUES(?, ?, ?)').run(pid, 'analyze', now()); + await db.prepare('DELETE FROM projects WHERE id = ?').run(pid); + for (const t of ['prospects', 'prospect_notes', 'jobs']) assert.equal((await db.prepare(`SELECT COUNT(*) n FROM ${t}`).get()).n, 0, t); +}); + +test('transaction : commit, rollback sur erreur, résultat renvoyé', async () => { + const db = await testDb(); + const out = await db.transaction(async (tx) => { + await tx.prepare("INSERT INTO blacklist(email, created_at) VALUES('a@b.fr', ?)").run(now()); + return 42; + }); + assert.equal(out, 42); + await assert.rejects(db.transaction(async (tx) => { + await tx.prepare("INSERT INTO blacklist(email, created_at) VALUES('c@d.fr', ?)").run(now()); + throw new Error('boum'); + }), /boum/); + const rows = await db.prepare('SELECT email FROM blacklist').all(); + assert.deepEqual(rows.map((r) => r.email), ['a@b.fr']); +}); + +test('transaction : une requête hors transaction ne voit jamais une écriture annulée', async () => { + const db = await testDb(); + let seen; + const tx = db.transaction(async (t) => { + await t.prepare("INSERT INTO blacklist(email, created_at) VALUES('x@y.fr', ?)").run(now()); + await new Promise((r) => setTimeout(r, 30)); + throw new Error('annulée'); + }); + const outside = new Promise((r) => setTimeout(r, 10)).then(async () => { + seen = await db.prepare('SELECT COUNT(*) n FROM blacklist').get(); + }); + await assert.rejects(tx, /annulée/); + await outside; + assert.equal(seen.n, 0); +}); + +test('migrations idempotentes : rouvrir une base déjà migrée ne casse rien (SQLite fichier)', async () => { + const { mkdtempSync, rmSync } = await import('node:fs'); + const { join } = await import('node:path'); + const { tmpdir } = await import('node:os'); + const dir = mkdtempSync(join(tmpdir(), 'mig-')); + try { + const file = join(dir, 't.sqlite'); + const a = await openDb({ driver: 'sqlite', file }); + await setSetting(a, 'k', 'v'); + await a.close(); + const b = await openDb({ driver: 'sqlite', file }); + assert.equal(await getSetting(b, 'k'), 'v'); + assert.equal((await b.prepare('SELECT COUNT(*) n FROM schema_migrations').get()).n, 1); + await b.close(); + } finally { rmSync(dir, { recursive: true, force: true }); } +}); diff --git a/test/helpers/db.js b/test/helpers/db.js new file mode 100644 index 0000000..0a95544 --- /dev/null +++ b/test/helpers/db.js @@ -0,0 +1,37 @@ +// Base de test : SQLite en mémoire par défaut ; si TEST_DB_HOST est défini, le même test tourne +// contre un vrai MySQL/MariaDB (TEST_DB_PORT, TEST_DB_USER, TEST_DB_PASSWORD, TEST_DB_NAME). +// ATTENTION : toutes les tables de cette base sont supprimées à chaque ouverture. Utiliser une base +// dédiée aux tests, et lancer avec --test-concurrency=1 (npm run test:mysql) : les fichiers de test +// partagent la même base. +import { after } from 'node:test'; +import { openDb, dbConfigFromEnv } from '../../src/db.js'; + +export const USING_MYSQL = !!process.env.TEST_DB_HOST; + +const opened = []; +if (USING_MYSQL) after(() => Promise.all(opened.map((d) => d.close().catch(() => {})))); + +async function wipe(db) { + const tables = (await db.query('SHOW TABLES')).map((r) => Object.values(r)[0]); + await db.transaction(async (tx) => { + await tx.query('SET FOREIGN_KEY_CHECKS = 0'); + for (const t of tables) await tx.query(`DROP TABLE IF EXISTS \`${t}\``); + await tx.query('SET FOREIGN_KEY_CHECKS = 1'); + }); +} + +export function testDbConfig() { + return dbConfigFromEnv(process.env, 'TEST_DB_'); +} + +/** Base vide, schéma migré. */ +export async function testDb() { + if (!USING_MYSQL) return openDb(':memory:'); + const cfg = { ...testDbConfig(), connectionLimit: 4 }; + const raw = await openDb(cfg); + await wipe(raw); + await raw.close(); + const db = await openDb(cfg); + opened.push(db); + return db; +} diff --git a/test/schema.test.js b/test/schema.test.js new file mode 100644 index 0000000..60a1dcb --- /dev/null +++ b/test/schema.test.js @@ -0,0 +1,90 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { MIGRATIONS } from '../src/db.js'; +import { testDb, USING_MYSQL } from './helpers/db.js'; + +// Découpe "a, b(c, d), e" sur les virgules de premier niveau +function splitTop(s) { + const out = []; + let depth = 0, cur = ''; + for (const c of s) { + if (c === '(') depth++; + if (c === ')') depth--; + if (c === ',' && depth === 0) { out.push(cur); cur = ''; } else cur += c; + } + if (cur.trim()) out.push(cur); + return out; +} + +// Tables, colonnes et clés étrangères déclarées par une liste d'instructions CREATE TABLE +function parseDdl(statements) { + const tables = new Map(); + for (const raw of statements) { + const sql = raw.replace(/--[^\n]*/g, ''); + const m = /CREATE TABLE (?:IF NOT EXISTS )?`?(\w+)`?\s*\(/i.exec(sql); + if (!m) continue; + let depth = 1, i = m.index + m[0].length; + const start = i; + for (; i < sql.length && depth > 0; i++) { if (sql[i] === '(') depth++; else if (sql[i] === ')') depth--; } + const columns = new Set(), refs = []; + for (const item of splitTop(sql.slice(start, i - 1)).map((x) => x.trim())) { + for (const r of item.matchAll(/REFERENCES\s+`?(\w+)`?\s*\([^)]*\)\s*ON DELETE CASCADE/gi)) refs.push(r[1]); + if (/^(?:PRIMARY\s+KEY|UNIQUE|KEY\s+\w+\s*\(|INDEX|CONSTRAINT|FOREIGN\s+KEY|CHECK)/i.test(item)) continue; + columns.add(item.match(/^`?(\w+)`?/)[1]); + } + tables.set(m[1], { columns, refs: refs.sort() }); + } + return tables; +} + +const ddl = (dialect) => parseDdl(MIGRATIONS.flatMap((m) => m[dialect])); +const shape = (tables) => Object.fromEntries([...tables].map(([t, v]) => [t, { columns: [...v.columns].sort(), refs: v.refs }])); + +test('schémas SQLite et MySQL : mêmes tables et mêmes colonnes', () => { + const sqlite = ddl('sqlite'); + const mysql = ddl('mysql'); + assert.ok(sqlite.size >= 10, 'le parseur doit voir les tables'); + assert.deepEqual([...mysql.keys()].sort(), [...sqlite.keys()].sort()); + for (const [t, v] of sqlite) assert.deepEqual([...mysql.get(t).columns].sort(), [...v.columns].sort(), `colonnes de ${t}`); +}); + +test('schémas : mêmes clés étrangères ON DELETE CASCADE des deux côtés', () => { + const s = shape(ddl('sqlite')), m = shape(ddl('mysql')); + for (const t of Object.keys(s)) assert.deepEqual(m[t].refs, s[t].refs, `FK de ${t}`); + assert.deepEqual(m.prospects.refs, ['projects']); + assert.deepEqual(m.prospect_notes.refs, ['prospects']); +}); + +test('MySQL : InnoDB, utf8mb4, migrations rejouables', () => { + for (const m of MIGRATIONS) { + for (const sql of m.mysql.filter((x) => /CREATE TABLE/i.test(x))) { + assert.match(sql, /ENGINE=InnoDB/); + assert.match(sql, /CHARSET=utf8mb4/); + assert.match(sql, /IF NOT EXISTS/, 'migration rejouable'); + } + assert.ok(m.name); + } +}); + +test('la base réellement migrée correspond au DDL déclaré', async () => { + const db = await testDb(); + const declared = shape(ddl(db.dialect)); + const live = {}; + if (db.dialect === 'sqlite') { + const tables = await db.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' AND name <> 'schema_migrations'").all(); + for (const { name } of tables) live[name] = (await db.query(`PRAGMA table_info(${name})`)).map((c) => c.name).sort(); + } else { + const rows = await db.query(`SELECT table_name t, column_name c FROM information_schema.columns + WHERE table_schema = DATABASE() AND table_name <> 'schema_migrations'`); + for (const r of rows) (live[r.t ?? r.T] ||= []).push(r.c ?? r.C); + for (const k of Object.keys(live)) live[k].sort(); + } + assert.deepEqual(live, Object.fromEntries(Object.entries(declared).map(([t, v]) => [t, v.columns]))); + const v = await db.prepare('SELECT COUNT(*) n, MAX(version) v FROM schema_migrations').get(); + assert.equal(v.n, MIGRATIONS.length); + assert.equal(v.v, MIGRATIONS.length); + if (USING_MYSQL) { + const t = await db.query("SELECT engine e FROM information_schema.tables WHERE table_schema = DATABASE() AND table_name = 'prospects'"); + assert.equal(t[0].e ?? t[0].ENGINE, 'InnoDB'); + } +});