feat: inicializacion de Help Desk segun estandar Telcotronics con bitacora de errores e integracion MCP
This commit is contained in:
+146
@@ -0,0 +1,146 @@
|
||||
const mysql = require('mysql2/promise');
|
||||
require('dotenv').config();
|
||||
|
||||
async function setup() {
|
||||
const conn = await mysql.createConnection({
|
||||
host: process.env.DB_HOST,
|
||||
user: process.env.DB_USER,
|
||||
password: process.env.DB_PASSWORD,
|
||||
multipleStatements: true
|
||||
});
|
||||
|
||||
await conn.query(`CREATE DATABASE IF NOT EXISTS \`${process.env.DB_NAME}\` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci`);
|
||||
await conn.query(`USE \`${process.env.DB_NAME}\``);
|
||||
|
||||
// Create companies table
|
||||
await conn.query(`
|
||||
CREATE TABLE IF NOT EXISTS companies (
|
||||
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||
name VARCHAR(200) NOT NULL,
|
||||
slug VARCHAR(100) NOT NULL UNIQUE,
|
||||
plan ENUM('free', 'pro', 'enterprise') DEFAULT 'free',
|
||||
max_users INT DEFAULT 5,
|
||||
max_tickets INT DEFAULT 100,
|
||||
is_active TINYINT(1) DEFAULT 1,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
|
||||
)
|
||||
`);
|
||||
|
||||
// Ensure demo company exists FIRST (before migrations reference it)
|
||||
const [existing] = await conn.query('SELECT id FROM companies WHERE slug = ?', ['demo']);
|
||||
let companyId;
|
||||
if (existing.length === 0) {
|
||||
await conn.query(
|
||||
'INSERT INTO companies (name, slug, plan, max_users, max_tickets) VALUES (?, ?, ?, ?, ?)',
|
||||
['Demo Company', 'demo', 'enterprise', 100, 10000]
|
||||
);
|
||||
companyId = 1;
|
||||
console.log('+ Empresa demo creada');
|
||||
} else {
|
||||
companyId = existing[0].id;
|
||||
console.log('~ Empresa demo ya existe (id=' + companyId + ')');
|
||||
}
|
||||
|
||||
// Ensure company_id default value references existing company
|
||||
const defCompanyId = companyId;
|
||||
|
||||
// Migrate existing tables
|
||||
const migrateColumn = async (table, column, definition) => {
|
||||
try {
|
||||
await conn.query(`ALTER TABLE \`${table}\` ADD COLUMN ${definition}`);
|
||||
console.log(` + columna ${column} agregada a ${table}`);
|
||||
} catch (e) {
|
||||
if (e.errno === 1060) console.log(` ~ ${table}.${column} ya existe`);
|
||||
else throw e;
|
||||
}
|
||||
};
|
||||
|
||||
console.log('Migrando tablas...');
|
||||
await migrateColumn('users', 'company_id', `company_id INT NOT NULL DEFAULT ${defCompanyId} AFTER id`);
|
||||
await migrateColumn('users', 'is_active', 'is_active TINYINT(1) DEFAULT 1');
|
||||
await migrateColumn('users', 'invite_token', 'invite_token VARCHAR(100) NULL');
|
||||
await migrateColumn('users', 'invite_token_expires', 'invite_token_expires TIMESTAMP NULL');
|
||||
await migrateColumn('users', 'invited_by', 'invited_by INT NULL');
|
||||
|
||||
// Alter users.rol to include superadmin
|
||||
try {
|
||||
await conn.query("ALTER TABLE users MODIFY COLUMN rol ENUM('superadmin','admin','agent','client') DEFAULT 'client'");
|
||||
console.log(' + users.rol actualizado a superadmin');
|
||||
} catch (e) {
|
||||
if (e.errno === 1060 || e.errno === 1062 || e.errno === 1265) console.log(' ~ users.rol ya actualizado');
|
||||
else throw e;
|
||||
}
|
||||
|
||||
// Add FKs for users
|
||||
for (const fk of [
|
||||
'ALTER TABLE users ADD FOREIGN KEY (company_id) REFERENCES companies(id) ON DELETE CASCADE',
|
||||
'ALTER TABLE users ADD FOREIGN KEY (invited_by) REFERENCES users(id) ON DELETE SET NULL'
|
||||
]) {
|
||||
try { await conn.query(fk); } catch (e) { if (e.errno !== 1826 && e.errno !== 1005) { throw e; } }
|
||||
}
|
||||
|
||||
await migrateColumn('departments', 'company_id', `company_id INT NOT NULL DEFAULT ${defCompanyId} AFTER id`);
|
||||
try {
|
||||
await conn.query('ALTER TABLE departments ADD FOREIGN KEY (company_id) REFERENCES companies(id) ON DELETE CASCADE');
|
||||
} catch (e) { if (e.errno !== 1826 && e.errno !== 1005) throw e; }
|
||||
|
||||
await migrateColumn('tickets', 'company_id', `company_id INT NOT NULL DEFAULT ${defCompanyId} AFTER id`);
|
||||
try {
|
||||
await conn.query('ALTER TABLE tickets ADD FOREIGN KEY (company_id) REFERENCES companies(id) ON DELETE CASCADE');
|
||||
} catch (e) { if (e.errno !== 1826 && e.errno !== 1005) throw e; }
|
||||
|
||||
// Seed departments
|
||||
const [depts] = await conn.query('SELECT COUNT(*) as c FROM departments WHERE company_id = ?', [companyId]);
|
||||
if (depts[0].c === 0) {
|
||||
await conn.query(
|
||||
'INSERT INTO departments (company_id, nombre, descripcion) VALUES ?',
|
||||
[[
|
||||
[companyId, 'Soporte Técnico', 'Problemas técnicos y de software'],
|
||||
[companyId, 'Facturación', 'Problemas de facturación y pagos'],
|
||||
[companyId, 'Ventas', 'Consultas sobre ventas y productos'],
|
||||
[companyId, 'General', 'Consultas generales']
|
||||
]]
|
||||
);
|
||||
console.log('+ Departamentos seed insertados');
|
||||
} else {
|
||||
console.log('~ Departamentos ya existen');
|
||||
}
|
||||
|
||||
// Seed users
|
||||
const bcrypt = require('bcryptjs');
|
||||
const hash = await bcrypt.hash('123456', 10);
|
||||
const users = [
|
||||
['super@helpdesk.com', 'Super Admin', 'superadmin'],
|
||||
['admin@helpdesk.com', 'Admin', 'admin'],
|
||||
['agent@helpdesk.com', 'Agente', 'agent'],
|
||||
['client@helpdesk.com', 'Cliente', 'client']
|
||||
];
|
||||
for (const [email, nombre, rol] of users) {
|
||||
const [u] = await conn.query('SELECT id FROM users WHERE email = ?', [email]);
|
||||
if (u.length === 0) {
|
||||
await conn.query(
|
||||
'INSERT INTO users (company_id, nombre, email, password, rol) VALUES (?, ?, ?, ?, ?)',
|
||||
[companyId, nombre, email, hash, rol]
|
||||
);
|
||||
console.log(`+ Usuario ${email} creado`);
|
||||
} else {
|
||||
await conn.query('UPDATE users SET company_id = ?, rol = ? WHERE email = ? AND rol != ?', [companyId, rol, email, 'superadmin']);
|
||||
console.log(`~ Usuario ${email} actualizado`);
|
||||
}
|
||||
}
|
||||
|
||||
// Ensure company_id is set for all orphan records
|
||||
await conn.query('UPDATE users SET company_id = ? WHERE company_id IS NULL OR company_id = 0', [companyId]);
|
||||
await conn.query('UPDATE departments SET company_id = ? WHERE company_id IS NULL OR company_id = 0', [companyId]);
|
||||
await conn.query('UPDATE tickets SET company_id = ? WHERE company_id IS NULL OR company_id = 0', [companyId]);
|
||||
|
||||
console.log('\nBase de datos configurada correctamente');
|
||||
await conn.end();
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
setup().catch(err => {
|
||||
console.error('Error:', err.message);
|
||||
process.exit(1);
|
||||
});
|
||||
Reference in New Issue
Block a user