Update db.js
This commit is contained in:
@@ -13,7 +13,7 @@ const __dirname = path.dirname(__filename);
|
|||||||
// Configurazione DB con gestione esplicita della porta e casting a numero
|
// Configurazione DB con gestione esplicita della porta e casting a numero
|
||||||
const dbConfig = {
|
const dbConfig = {
|
||||||
host: process.env.DB_HOST || 'db',
|
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',
|
user: process.env.DB_USER || 'omni_user',
|
||||||
password: process.env.DB_PASSWORD || 'omni_pass',
|
password: process.env.DB_PASSWORD || 'omni_pass',
|
||||||
database: process.env.DB_NAME || 'omnisupport',
|
database: process.env.DB_NAME || 'omnisupport',
|
||||||
@@ -40,7 +40,6 @@ export const checkConnection = async () => {
|
|||||||
const connection = await pool.getConnection();
|
const connection = await pool.getConnection();
|
||||||
await connection.ping();
|
await connection.ping();
|
||||||
connection.release();
|
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}`);
|
console.log(`✅ Connected to MySQL Database at ${dbConfig.host}:${dbConfig.port}`);
|
||||||
return true;
|
return true;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
@@ -53,28 +52,53 @@ export const initDb = async () => {
|
|||||||
try {
|
try {
|
||||||
console.log(`🔌 Attempting connection to database at ${dbConfig.host}:${dbConfig.port}...`);
|
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();
|
const isConnected = await checkConnection();
|
||||||
if (!isConnected) {
|
if (!isConnected) {
|
||||||
console.error("❌ Skipping initialization due to connection failure.");
|
console.error("❌ Skipping initialization due to connection failure.");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Controlla se la tabella 'agents' esiste già
|
// Check if main tables exist
|
||||||
// Se esiste, assumiamo che il DB sia già popolato e non facciamo nulla per evitare sovrascritture
|
const [agentsExist] = await pool.query("SHOW TABLES LIKE 'agents'");
|
||||||
const [rows] = 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.');
|
console.log('ℹ️ Database tables already exist. Skipping initialization.');
|
||||||
return;
|
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 schemaPath = path.join(__dirname, 'schema.sql');
|
||||||
const schemaSql = fs.readFileSync(schemaPath, 'utf8');
|
const schemaSql = fs.readFileSync(schemaPath, 'utf8');
|
||||||
|
|
||||||
// Eseguiamo lo script SQL completo
|
|
||||||
await pool.query(schemaSql);
|
await pool.query(schemaSql);
|
||||||
|
|
||||||
console.log('✅ Database initialized successfully with schema and seed data.');
|
console.log('✅ Database initialized successfully with schema and seed data.');
|
||||||
|
|||||||
Reference in New Issue
Block a user