408 lines
22 KiB
JavaScript
408 lines
22 KiB
JavaScript
const mysql = require('mysql2/promise');
|
|
const crypto = require('crypto');
|
|
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 official ecosystem companies exist: Telcotronics, XSYSTEM, DOMUS
|
|
// Migrate legacy demo / testcorp / nuevaemp if present
|
|
await conn.query(`UPDATE companies SET name = 'Telcotronics', slug = 'telcotronics', plan = 'enterprise', max_users = 100, max_tickets = 10000 WHERE slug = 'demo' OR id = 1`);
|
|
await conn.query(`UPDATE companies SET name = 'XSYSTEM', slug = 'xsystem', plan = 'enterprise', max_users = 100, max_tickets = 10000 WHERE slug = 'testcorp' OR id = 2`);
|
|
await conn.query(`UPDATE companies SET name = 'DOMUS', slug = 'domus', plan = 'enterprise', max_users = 100, max_tickets = 10000 WHERE slug = 'nuevaemp' OR id = 3`);
|
|
|
|
const ecosystemCompanies = [
|
|
{ id: 1, name: 'Telcotronics', slug: 'telcotronics', plan: 'enterprise', max_users: 100, max_tickets: 10000 },
|
|
{ id: 2, name: 'XSYSTEM', slug: 'xsystem', plan: 'enterprise', max_users: 100, max_tickets: 10000 },
|
|
{ id: 3, name: 'DOMUS', slug: 'domus', plan: 'enterprise', max_users: 100, max_tickets: 10000 }
|
|
];
|
|
|
|
for (const ec of ecosystemCompanies) {
|
|
const [found] = await conn.query('SELECT id FROM companies WHERE slug = ? OR id = ?', [ec.slug, ec.id]);
|
|
if (found.length === 0) {
|
|
await conn.query(
|
|
'INSERT INTO companies (id, name, slug, plan, max_users, max_tickets) VALUES (?, ?, ?, ?, ?, ?)',
|
|
[ec.id, ec.name, ec.slug, ec.plan, ec.max_users, ec.max_tickets]
|
|
);
|
|
console.log(`+ Empresa ${ec.name} creada (id=${ec.id})`);
|
|
} else {
|
|
await conn.query(
|
|
'UPDATE companies SET name = ?, slug = ?, plan = ?, max_users = ?, max_tickets = ? WHERE id = ?',
|
|
[ec.name, ec.slug, ec.plan, ec.max_users, ec.max_tickets, found[0].id]
|
|
);
|
|
console.log(`~ Empresa ${ec.name} sincronizada (id=${found[0].id})`);
|
|
}
|
|
}
|
|
|
|
const companyId = 1;
|
|
const defCompanyId = 1;
|
|
|
|
// 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');
|
|
await migrateColumn('users', 'provider', "provider VARCHAR(50) DEFAULT 'local'");
|
|
await migrateColumn('users', 'provider_id', "provider_id VARCHAR(150) NULL");
|
|
await migrateColumn('users', 'avatar_url', "avatar_url VARCHAR(255) NULL");
|
|
|
|
try {
|
|
await conn.query("ALTER TABLE users MODIFY COLUMN provider VARCHAR(50) DEFAULT 'local'");
|
|
} catch (e) {
|
|
// Ignorar
|
|
}
|
|
|
|
try {
|
|
await conn.query("ALTER TABLE users MODIFY COLUMN password VARCHAR(255) NULL");
|
|
console.log(' + users.password modificado a nullable');
|
|
} catch (e) {
|
|
// Ignorar si ya es nullable
|
|
}
|
|
|
|
// 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; }
|
|
|
|
// Columnas M2M / sigma-robot en tickets
|
|
await migrateColumn('tickets', 'origen', "origen VARCHAR(50) DEFAULT 'web'");
|
|
await migrateColumn('tickets', 'origen_externo_id', 'origen_externo_id VARCHAR(100) NULL');
|
|
await migrateColumn('tickets', 'app_origen', 'app_origen VARCHAR(100) NULL');
|
|
await migrateColumn('tickets', 'solicitante_nombre', 'solicitante_nombre VARCHAR(150) NULL');
|
|
await migrateColumn('tickets', 'solicitante_email', 'solicitante_email VARCHAR(150) NULL');
|
|
await migrateColumn('tickets', 'solicitante_telefono', 'solicitante_telefono VARCHAR(50) NULL');
|
|
await migrateColumn('tickets', 'tipo', "tipo VARCHAR(50) DEFAULT 'consulta'");
|
|
|
|
try {
|
|
await conn.query('ALTER TABLE tickets ADD UNIQUE KEY idx_tickets_origen_ext (company_id, origen, origen_externo_id)');
|
|
console.log(' + indice unico idx_tickets_origen_ext creado');
|
|
} catch (e) {
|
|
if (e.errno === 1061) console.log(' ~ indice idx_tickets_origen_ext ya existe');
|
|
}
|
|
|
|
// Create ticket_visitas table
|
|
await conn.query(`
|
|
CREATE TABLE IF NOT EXISTS ticket_visitas (
|
|
id INT AUTO_INCREMENT PRIMARY KEY,
|
|
company_id INT NOT NULL,
|
|
ticket_id INT NOT NULL,
|
|
external_id VARCHAR(100) NULL,
|
|
tecnico_email VARCHAR(150) NOT NULL,
|
|
tecnico_nombre VARCHAR(150) NULL,
|
|
titulo VARCHAR(255) NOT NULL,
|
|
descripcion TEXT NULL,
|
|
ubicacion VARCHAR(255) NULL,
|
|
latitud DECIMAL(10, 7) NULL,
|
|
longitud DECIMAL(10, 7) NULL,
|
|
fecha_visita DATETIME NULL,
|
|
fecha_fin DATETIME NULL,
|
|
estado ENUM('programada', 'en_camino', 'en_sitio', 'completada', 'cancelada') DEFAULT 'programada',
|
|
checklist_json TEXT NULL,
|
|
historial_json LONGTEXT NULL,
|
|
set_herramientas_id INT NULL,
|
|
set_herramientas_nombre VARCHAR(150) NULL,
|
|
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
|
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
|
INDEX (ticket_id),
|
|
INDEX (company_id),
|
|
INDEX (external_id),
|
|
FOREIGN KEY (ticket_id) REFERENCES tickets(id) ON DELETE CASCADE,
|
|
FOREIGN KEY (company_id) REFERENCES companies(id) ON DELETE CASCADE
|
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
|
`);
|
|
|
|
await migrateColumn('ticket_visitas', 'set_herramientas_id', 'set_herramientas_id INT NULL');
|
|
await migrateColumn('ticket_visitas', 'set_herramientas_nombre', 'set_herramientas_nombre VARCHAR(150) NULL');
|
|
|
|
// Create herramientas (Catálogo detallado de herramientas físicas e instrumentos)
|
|
await conn.query(`
|
|
CREATE TABLE IF NOT EXISTS herramientas (
|
|
id INT AUTO_INCREMENT PRIMARY KEY,
|
|
company_id INT NOT NULL,
|
|
nombre VARCHAR(150) NOT NULL,
|
|
codigo VARCHAR(50) NULL,
|
|
numero_serie VARCHAR(100) NULL,
|
|
categoria VARCHAR(100) DEFAULT 'general',
|
|
marca VARCHAR(100) NULL,
|
|
modelo VARCHAR(100) NULL,
|
|
estado ENUM('operativo', 'en_mantenimiento', 'danado', 'baja') DEFAULT 'operativo',
|
|
ubicacion_bodega VARCHAR(150) NULL,
|
|
notas TEXT NULL,
|
|
foto_url VARCHAR(255) NULL,
|
|
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
|
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
|
INDEX (company_id),
|
|
INDEX (codigo),
|
|
INDEX (estado),
|
|
FOREIGN KEY (company_id) REFERENCES companies(id) ON DELETE CASCADE
|
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
|
`);
|
|
|
|
// Create herramientas_sets (Agrupaciones lógicas / Kits de herramientas reutilizables)
|
|
await conn.query(`
|
|
CREATE TABLE IF NOT EXISTS herramientas_sets (
|
|
id INT AUTO_INCREMENT PRIMARY KEY,
|
|
company_id INT NOT NULL,
|
|
nombre VARCHAR(150) NOT NULL,
|
|
codigo VARCHAR(50) NULL,
|
|
qr_token VARCHAR(64) NULL,
|
|
descripcion TEXT NULL,
|
|
categoria VARCHAR(100) DEFAULT 'general',
|
|
foto_url VARCHAR(255) NULL,
|
|
is_active TINYINT(1) DEFAULT 1,
|
|
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
|
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
|
INDEX (company_id),
|
|
INDEX (codigo),
|
|
INDEX (qr_token),
|
|
FOREIGN KEY (company_id) REFERENCES companies(id) ON DELETE CASCADE
|
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
|
`);
|
|
|
|
// Create herramientas_set_items (Herramientas incluidas en cada Set/Kit)
|
|
await conn.query(`
|
|
CREATE TABLE IF NOT EXISTS herramientas_set_items (
|
|
id INT AUTO_INCREMENT PRIMARY KEY,
|
|
set_id INT NOT NULL,
|
|
herramienta_id INT NOT NULL,
|
|
cantidad INT DEFAULT 1,
|
|
FOREIGN KEY (set_id) REFERENCES herramientas_sets(id) ON DELETE CASCADE,
|
|
FOREIGN KEY (herramienta_id) REFERENCES herramientas(id) ON DELETE CASCADE,
|
|
UNIQUE KEY idx_set_herramienta (set_id, herramienta_id)
|
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
|
`);
|
|
|
|
// Create tecnico_herramientas_asignaciones (Asignación mixta: Dotación fija o por Visita FSM)
|
|
await conn.query(`
|
|
CREATE TABLE IF NOT EXISTS tecnico_herramientas_asignaciones (
|
|
id INT AUTO_INCREMENT PRIMARY KEY,
|
|
company_id INT NOT NULL,
|
|
tecnico_id INT NOT NULL,
|
|
set_id INT NULL,
|
|
herramienta_id INT NULL,
|
|
ticket_visita_id INT NULL,
|
|
tipo_asignacion ENUM('dotacion_fija', 'visita_fsm') DEFAULT 'dotacion_fija',
|
|
qr_token VARCHAR(64) NULL,
|
|
fecha_asignacion DATETIME DEFAULT CURRENT_TIMESTAMP,
|
|
fecha_devolucion DATETIME NULL,
|
|
estado ENUM('asignado', 'devuelto', 'observado') DEFAULT 'asignado',
|
|
observaciones_entrega TEXT NULL,
|
|
foto_entrega_url VARCHAR(255) NULL,
|
|
observaciones_devolucion TEXT NULL,
|
|
foto_devolucion_url VARCHAR(255) NULL,
|
|
asignado_por INT NULL,
|
|
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
|
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
|
INDEX (company_id),
|
|
INDEX (tecnico_id),
|
|
INDEX (ticket_visita_id),
|
|
INDEX (qr_token),
|
|
FOREIGN KEY (company_id) REFERENCES companies(id) ON DELETE CASCADE,
|
|
FOREIGN KEY (tecnico_id) REFERENCES users(id) ON DELETE CASCADE,
|
|
FOREIGN KEY (set_id) REFERENCES herramientas_sets(id) ON DELETE SET NULL,
|
|
FOREIGN KEY (herramienta_id) REFERENCES herramientas(id) ON DELETE SET NULL,
|
|
FOREIGN KEY (ticket_visita_id) REFERENCES ticket_visitas(id) ON DELETE SET NULL,
|
|
FOREIGN KEY (asignado_por) REFERENCES users(id) ON DELETE SET NULL
|
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
|
`);
|
|
|
|
// Migraciones de columnas para fotografías y evidencias
|
|
await migrateColumn('herramientas', 'foto_url', 'foto_url VARCHAR(255) NULL AFTER notas');
|
|
await migrateColumn('herramientas_sets', 'foto_url', 'foto_url VARCHAR(255) NULL AFTER descripcion');
|
|
await migrateColumn('tecnico_herramientas_asignaciones', 'foto_entrega_url', 'foto_entrega_url VARCHAR(255) NULL AFTER observaciones_entrega');
|
|
await migrateColumn('tecnico_herramientas_asignaciones', 'foto_devolucion_url', 'foto_devolucion_url VARCHAR(255) NULL AFTER observaciones_devolucion');
|
|
|
|
// Migraciones de tokens QR para escaneo e impresión de etiquetas
|
|
await migrateColumn('herramientas_sets', 'qr_token', 'qr_token VARCHAR(64) NULL AFTER codigo');
|
|
await migrateColumn('tecnico_herramientas_asignaciones', 'qr_token', 'qr_token VARCHAR(64) NULL AFTER tipo_asignacion');
|
|
|
|
// Backfill de qr_token para sets que aún no tengan uno generado
|
|
const [setsSinToken] = await conn.query('SELECT id FROM herramientas_sets WHERE qr_token IS NULL');
|
|
for (const s of setsSinToken) {
|
|
const token = crypto.randomBytes(12).toString('hex');
|
|
await conn.query('UPDATE herramientas_sets SET qr_token = ? WHERE id = ?', [token, s.id]);
|
|
}
|
|
|
|
// Backfill de qr_token para asignaciones sin token
|
|
const [asigSinToken] = await conn.query('SELECT id FROM tecnico_herramientas_asignaciones WHERE qr_token IS NULL');
|
|
for (const a of asigSinToken) {
|
|
const token = crypto.randomBytes(12).toString('hex');
|
|
await conn.query('UPDATE tecnico_herramientas_asignaciones SET qr_token = ? WHERE id = ?', [token, a.id]);
|
|
}
|
|
|
|
// Seed herramientas y sets iniciales para Telcotronics si no existen
|
|
const [existingTools] = await conn.query('SELECT COUNT(*) as c FROM herramientas WHERE company_id = 1');
|
|
if (existingTools[0].c === 0) {
|
|
console.log('+ Sembrando catálogo de herramientas para Telcotronics...');
|
|
const initialTools = [
|
|
[1, 'Fusionadora de Fibra Óptica', 'TOOL-FIB-01', 'SN-FIB7021', 'fibra_optica', 'Fujikura', '70S', 'operativo', 'Bodega Central - Estante A1'],
|
|
[1, 'OTDR Mini Pro de Precisión', 'TOOL-OTDR-01', 'SN-OTDR4402', 'medicion', 'Anritsu', 'MT9090', 'operativo', 'Bodega Central - Estante A1'],
|
|
[1, 'Crimpadora RJ45/RJ11 Pro', 'TOOL-CRIMP-01', 'SN-CRIMP-88', 'redes', 'Klein Tools', 'VDV226', 'operativo', 'Bodega Central - Caja 3'],
|
|
[1, 'Tester Certificador Cable de Red PoE', 'TOOL-TEST-01', 'SN-FLK8891', 'medicion', 'Fluke Networks', 'MicroScanner', 'operativo', 'Bodega Central - Estante B2'],
|
|
[1, 'Monitor Portátil de Prueba CCTV AHD/IP', 'TOOL-CCTV-01', 'SN-HK9012', 'cctv', 'Hikvision', 'TestScreen Pro 4K', 'operativo', 'Bodega Central - Estante C1'],
|
|
[1, 'Taladro Percutor Inalámbrico 20V Max', 'TOOL-TAL-01', 'SN-DW2019', 'mano', 'DeWalt', 'DCD778', 'operativo', 'Bodega Central - Gaveta 5'],
|
|
[1, 'Multímetro Digital True RMS', 'TOOL-MULT-01', 'SN-FLK1174', 'electricidad', 'Fluke', '117 Electrician', 'operativo', 'Bodega Central - Estante B2'],
|
|
[1, 'Escalera Telescópica de Aluminio 3.8m', 'TOOL-ESC-01', 'SN-ESC-901', 'mano', 'Werner', 'Telescop 3.8', 'operativo', 'Área de Vehículos']
|
|
];
|
|
for (const t of initialTools) {
|
|
await conn.query(
|
|
`INSERT INTO herramientas (company_id, nombre, codigo, numero_serie, categoria, marca, modelo, estado, ubicacion_bodega)
|
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
|
t
|
|
);
|
|
}
|
|
|
|
// Crear sets
|
|
console.log('+ Sembrando Sets / Kits de Herramientas para Telcotronics...');
|
|
const [set1] = await conn.query(
|
|
`INSERT INTO herramientas_sets (company_id, nombre, codigo, descripcion, categoria)
|
|
VALUES (1, 'Kit Fibra Óptica & Enlaces', 'SET-FIB-PRO', 'Kit completo para tendido, fusión y certificación de enlaces de fibra óptica.', 'fibra_optica')`
|
|
);
|
|
const [set2] = await conn.query(
|
|
`INSERT INTO herramientas_sets (company_id, nombre, codigo, descripcion, categoria)
|
|
VALUES (1, 'Kit Seguridad Electrónica & CCTV', 'SET-CCTV-01', 'Herramientas indispensables para montaje, alineación y pruebas de cámaras IP y analógicas.', 'cctv')`
|
|
);
|
|
const [set3] = await conn.query(
|
|
`INSERT INTO herramientas_sets (company_id, nombre, codigo, descripcion, categoria)
|
|
VALUES (1, 'Kit Redes & Cableado Estructurado', 'SET-RED-01', 'Instrumentos para certificación de puntos de red, crimpado y pruebas PoE.', 'redes')`
|
|
);
|
|
|
|
// Asociar herramientas a los sets
|
|
const [toolsRows] = await conn.query('SELECT id, codigo FROM herramientas WHERE company_id = 1');
|
|
const toolMap = {};
|
|
toolsRows.forEach(r => { toolMap[r.codigo] = r.id; });
|
|
|
|
// Set 1 items: Fusionadora + OTDR + Crimpadora
|
|
if (toolMap['TOOL-FIB-01'] && toolMap['TOOL-OTDR-01']) {
|
|
await conn.query('INSERT INTO herramientas_set_items (set_id, herramienta_id, cantidad) VALUES (?, ?, 1), (?, ?, 1)',
|
|
[set1.insertId, toolMap['TOOL-FIB-01'], set1.insertId, toolMap['TOOL-OTDR-01']]);
|
|
}
|
|
// Set 2 items: Monitor CCTV + Taladro + Multímetro
|
|
if (toolMap['TOOL-CCTV-01'] && toolMap['TOOL-TAL-01'] && toolMap['TOOL-MULT-01']) {
|
|
await conn.query('INSERT INTO herramientas_set_items (set_id, herramienta_id, cantidad) VALUES (?, ?, 1), (?, ?, 1), (?, ?, 1)',
|
|
[set2.insertId, toolMap['TOOL-CCTV-01'], set2.insertId, toolMap['TOOL-TAL-01'], set2.insertId, toolMap['TOOL-MULT-01']]);
|
|
}
|
|
// Set 3 items: Tester Fluke + Crimpadora + Multímetro
|
|
if (toolMap['TOOL-TEST-01'] && toolMap['TOOL-CRIMP-01'] && toolMap['TOOL-MULT-01']) {
|
|
await conn.query('INSERT INTO herramientas_set_items (set_id, herramienta_id, cantidad) VALUES (?, ?, 1), (?, ?, 1), (?, ?, 1)',
|
|
[set3.insertId, toolMap['TOOL-TEST-01'], set3.insertId, toolMap['TOOL-CRIMP-01'], set3.insertId, toolMap['TOOL-MULT-01']]);
|
|
}
|
|
}
|
|
|
|
// Seed departments for all ecosystem companies
|
|
for (const ec of ecosystemCompanies) {
|
|
const [depts] = await conn.query('SELECT COUNT(*) as c FROM departments WHERE company_id = ?', [ec.id]);
|
|
if (depts[0].c === 0) {
|
|
await conn.query(
|
|
'INSERT INTO departments (company_id, nombre, descripcion) VALUES ?',
|
|
[[
|
|
[ec.id, 'Soporte Técnico', 'Problemas técnicos y de software'],
|
|
[ec.id, 'Facturación', 'Problemas de facturación y pagos'],
|
|
[ec.id, 'Ventas', 'Consultas sobre ventas y productos'],
|
|
[ec.id, 'General', 'Consultas generales']
|
|
]]
|
|
);
|
|
console.log(`+ Departamentos seed insertados para ${ec.name}`);
|
|
} else {
|
|
console.log(`~ Departamentos ya existen para ${ec.name}`);
|
|
}
|
|
}
|
|
|
|
// Seed users and company admins
|
|
const bcrypt = require('bcryptjs');
|
|
const hash = await bcrypt.hash('123456', 10);
|
|
const users = [
|
|
[1, 'super@helpdesk.com', 'Super Admin', 'superadmin'],
|
|
[1, 'admin@telcotronics.local', 'Admin Telcotronics', 'admin'],
|
|
[2, 'admin@xsystem.com', 'Admin XSYSTEM', 'admin'],
|
|
[3, 'admin@domus.com', 'Admin DOMUS', 'admin'],
|
|
[1, 'agent@helpdesk.com', 'Agente', 'agent'],
|
|
[1, 'client@helpdesk.com', 'Cliente', 'client']
|
|
];
|
|
for (const [cId, email, nombre, rol] of users) {
|
|
const [u] = await conn.query('SELECT id, rol FROM users WHERE email = ?', [email]);
|
|
if (u.length === 0) {
|
|
await conn.query(
|
|
'INSERT INTO users (company_id, nombre, email, password, rol) VALUES (?, ?, ?, ?, ?)',
|
|
[cId, nombre, email, hash, rol]
|
|
);
|
|
console.log(`+ Usuario ${email} (${rol}) creado en empresa ${cId}`);
|
|
} else {
|
|
const finalRole = u[0].rol === 'superadmin' ? 'superadmin' : rol;
|
|
await conn.query('UPDATE users SET company_id = ?, nombre = ?, rol = ? WHERE email = ?', [cId, nombre, finalRole, email]);
|
|
console.log(`~ Usuario ${email} actualizado en empresa ${cId}`);
|
|
}
|
|
}
|
|
|
|
// 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);
|
|
});
|