From 15c1a0247e1dc8316580afe605bf6fb74ab92756 Mon Sep 17 00:00:00 2001 From: fcarraUniSa Date: Tue, 17 Feb 2026 10:50:38 +0100 Subject: [PATCH] Update db.js --- backend/db.js | 42 +++++++++++++++++++++++++++++++++--------- 1 file changed, 33 insertions(+), 9 deletions(-) diff --git a/backend/db.js b/backend/db.js index 73dc080..c028bd4 100644 --- a/backend/db.js +++ b/backend/db.js @@ -13,7 +13,7 @@ const __dirname = path.dirname(__filename); // Configurazione DB con gestione esplicita della porta e casting a numero const dbConfig = { host: process.env.DB_HOST || 'db', - port: Number(process.env.DB_PORT) || 3306, // Importante: converte la stringa ENV in numero + port: Number(process.env.DB_PORT) || 3306, user: process.env.DB_USER || 'omni_user', password: process.env.DB_PASSWORD || 'omni_pass', database: process.env.DB_NAME || 'omnisupport', @@ -40,7 +40,6 @@ export const checkConnection = async () => { const connection = await pool.getConnection(); await connection.ping(); connection.release(); - // Log che conferma l'host e la porta utilizzati (utile per debug esterni) console.log(`✅ Connected to MySQL Database at ${dbConfig.host}:${dbConfig.port}`); return true; } catch (error) { @@ -53,28 +52,53 @@ export const initDb = async () => { try { console.log(`🔌 Attempting connection to database at ${dbConfig.host}:${dbConfig.port}...`); - // Verifica che la connessione sia attiva prima di provare a inizializzare const isConnected = await checkConnection(); if (!isConnected) { console.error("❌ Skipping initialization due to connection failure."); return; } - // Controlla se la tabella 'agents' esiste già - // Se esiste, assumiamo che il DB sia già popolato e non facciamo nulla per evitare sovrascritture - const [rows] = await pool.query("SHOW TABLES LIKE 'agents'"); + // Check if main tables exist + const [agentsExist] = await pool.query("SHOW TABLES LIKE 'agents'"); + const [settingsExist] = await pool.query("SHOW TABLES LIKE 'settings'"); - if (Array.isArray(rows) && rows.length > 0) { + // Scenario 1: DB completely initialized + if (agentsExist.length > 0 && settingsExist.length > 0) { console.log('ℹ️ Database tables already exist. Skipping initialization.'); return; } - console.log('⚠️ Database empty or uninitialized. Running schema.sql...'); + // Scenario 2: Partial migration (Agents exist but Settings missing) + if (agentsExist.length > 0 && settingsExist.length === 0) { + console.log('⚠️ Settings table missing (Partial Migration). Creating...'); + const createSettingsSql = ` + CREATE TABLE IF NOT EXISTS settings ( + id INT PRIMARY KEY DEFAULT 1, + branding JSON, + smtp JSON, + email_templates JSON, + features JSON, + ai_config JSON + ); + INSERT INTO settings (id, branding, smtp, email_templates, features, ai_config) VALUES ( + 1, + '{"appName": "OmniSupport AI", "primaryColor": "#0284c7", "logoUrl": "https://via.placeholder.com/150"}', + '{"host": "smtp.example.com", "port": 587, "user": "notifications@omnisupport.ai", "pass": "password", "secure": true, "fromEmail": "noreply@omnisupport.ai"}', + '[{"id": "t1", "name": "Conferma Apertura Ticket", "trigger": "ticket_created", "audience": "client", "subject": "Ticket #{ticket_id} Creato", "body": "Grazie per averci contattato.", "isActive": true}]', + '{"kbEnabled": true, "maxKbArticles": 50, "maxSupervisors": 2, "aiKnowledgeAgentEnabled": true, "maxAiGeneratedArticles": 10, "maxAgents": 10}', + '{"provider": "gemini", "apiKey": "", "model": "gemini-3-flash-preview", "isActive": true}' + ); + `; + await pool.query(createSettingsSql); + console.log('✅ Settings table created successfully.'); + return; + } + // Scenario 3: Fresh Install + console.log('⚠️ Database empty. Running full schema.sql...'); const schemaPath = path.join(__dirname, 'schema.sql'); const schemaSql = fs.readFileSync(schemaPath, 'utf8'); - // Eseguiamo lo script SQL completo await pool.query(schemaSql); console.log('✅ Database initialized successfully with schema and seed data.');