feat: inicializacion de Help Desk segun estandar Telcotronics con bitacora de errores e integracion MCP

This commit is contained in:
2026-10-16 23:29:32 -05:00
commit 0f2708462e
54 changed files with 7590 additions and 0 deletions
+14
View File
@@ -0,0 +1,14 @@
const mysql = require('mysql2');
require('dotenv').config();
const pool = mysql.createPool({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
waitForConnections: true,
connectionLimit: 10,
queueLimit: 0
});
module.exports = pool.promise();
+160
View File
@@ -0,0 +1,160 @@
const https = require('https');
const http = require('http');
const ENDPOINT = process.env.ERROR_REPORTING_URL || 'https://api.siax-system.net/api/errores';
const API_KEY = process.env.WEBCONTROL_API_KEY || '';
const APP_ORIGEN = 'Help Desk';
const VERSION = '1.0.0';
// Deduplicación en memoria: evitar inundar el endpoint con el mismo error repetido
const cacheErrores = new Map();
const THROTTLE_MS = 10 * 60 * 1000; // 10 minutos
/**
* Reporta un error de runtime hacia API-SIGMA-WEBCONTROL (POST https://api.siax-system.net/api/errores)
*/
async function reportarError({
mensaje,
detalle = '',
categoria = 'sistema', // red, bd, auth, validacion, sistema, desconocido
nivel = 'error',
codigo = null,
clase = null,
metodo = null,
usuario = null,
cuenta = null
}) {
try {
if (!mensaje) return;
// Control de throttle por firma
const firma = `${categoria}:${mensaje}:${codigo || ''}`;
const ahora = Date.now();
const ultimoEnvio = cacheErrores.get(firma);
if (ultimoEnvio && (ahora - ultimoEnvio) < THROTTLE_MS) {
console.log(`[errorReporter] Error en ventana de throttle (${firma}), ignorando duplicado.`);
return;
}
cacheErrores.set(firma, ahora);
if (!API_KEY) {
console.warn(`[errorReporter] WEBCONTROL_API_KEY no configurada. Error no enviado a ${ENDPOINT}: ${mensaje}`);
return;
}
const payload = JSON.stringify({
app_origen: APP_ORIGEN,
mensaje: String(mensaje).substring(0, 500),
detalle: typeof detalle === 'object' ? JSON.stringify(detalle, null, 2) : String(detalle || ''),
categoria,
nivel,
codigo: codigo ? String(codigo) : null,
clase,
metodo,
usuario,
cuenta,
entorno: process.env.NODE_ENV || 'development',
version: VERSION,
fecha_evento: new Date().toISOString()
});
const url = new URL(ENDPOINT);
const client = url.protocol === 'https:' ? https : http;
const options = {
hostname: url.hostname,
port: url.port || (url.protocol === 'https:' ? 443 : 80),
path: url.pathname + url.search,
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(payload),
'x-api-key': API_KEY
},
timeout: 5000
};
const req = client.request(options, (res) => {
let body = '';
res.on('data', (d) => body += d);
res.on('end', () => {
if (res.statusCode >= 200 && res.statusCode < 300) {
console.log(`[errorReporter] Error reportado exitosamente (${res.statusCode}): ${mensaje}`);
} else {
console.warn(`[errorReporter] Fallo al reportar a ${ENDPOINT}: HTTP ${res.statusCode} - ${body}`);
}
});
});
req.on('error', (e) => {
console.warn(`[errorReporter] Error de conexión al reportar a la bitácora:`, e.message);
});
req.on('timeout', () => {
req.destroy();
console.warn(`[errorReporter] Timeout al conectar con ${ENDPOINT}`);
});
req.write(payload);
req.end();
} catch (err) {
console.error(`[errorReporter] Excepción en reporter:`, err.message);
}
}
/**
* Consulta errores reportados por esta app en API-SIGMA-WEBCONTROL (GET https://api.siax-system.net/api/errores)
*/
async function consultarErrores({ page = 1, limit = 20, categoria = null } = {}) {
return new Promise((resolve, reject) => {
if (!API_KEY) {
return reject(new Error('WEBCONTROL_API_KEY no configurada en las variables de entorno.'));
}
const url = new URL(ENDPOINT);
url.searchParams.set('app_origen', APP_ORIGEN);
url.searchParams.set('page', String(page));
url.searchParams.set('limit', String(limit));
if (categoria) url.searchParams.set('categoria', categoria);
const client = url.protocol === 'https:' ? https : http;
const options = {
hostname: url.hostname,
port: url.port || (url.protocol === 'https:' ? 443 : 80),
path: url.pathname + url.search,
method: 'GET',
headers: {
'Accept': 'application/json',
'x-api-key': API_KEY
},
timeout: 10000
};
const req = client.request(options, (res) => {
let data = '';
res.on('data', (chunk) => data += chunk);
res.on('end', () => {
try {
const json = JSON.parse(data);
resolve({ statusCode: res.statusCode, data: json });
} catch (e) {
resolve({ statusCode: res.statusCode, raw: data });
}
});
});
req.on('error', reject);
req.on('timeout', () => {
req.destroy();
reject(new Error('Timeout al consultar API de errores'));
});
req.end();
});
}
module.exports = {
reportarError,
consultarErrores,
APP_ORIGEN
};
+54
View File
@@ -0,0 +1,54 @@
CREATE DATABASE IF NOT EXISTS help_desk;
USE help_desk;
CREATE TABLE IF NOT EXISTS users (
id INT AUTO_INCREMENT PRIMARY KEY,
nombre VARCHAR(100) NOT NULL,
email VARCHAR(100) NOT NULL UNIQUE,
password VARCHAR(255) NOT NULL,
rol ENUM('admin', 'agent', 'client') DEFAULT 'client',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE IF NOT EXISTS departments (
id INT AUTO_INCREMENT PRIMARY KEY,
nombre VARCHAR(100) NOT NULL,
descripcion TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE IF NOT EXISTS tickets (
id INT AUTO_INCREMENT PRIMARY KEY,
user_id INT NOT NULL,
department_id INT,
asunto VARCHAR(200) NOT NULL,
mensaje TEXT NOT NULL,
status ENUM('abierto', 'en_progreso', 'cerrado') DEFAULT 'abierto',
prioridad ENUM('baja', 'media', 'alta', 'critica') DEFAULT 'media',
assigned_to INT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
FOREIGN KEY (department_id) REFERENCES departments(id) ON DELETE SET NULL,
FOREIGN KEY (assigned_to) REFERENCES users(id) ON DELETE SET NULL
);
CREATE TABLE IF NOT EXISTS ticket_respuestas (
id INT AUTO_INCREMENT PRIMARY KEY,
ticket_id INT NOT NULL,
user_id INT NOT NULL,
mensaje TEXT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (ticket_id) REFERENCES tickets(id) ON DELETE CASCADE,
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
);
INSERT INTO departments (nombre, descripcion) VALUES
('Soporte Técnico', 'Problemas técnicos y de software'),
('Facturación', 'Problemas de facturación y pagos'),
('Ventas', 'Consultas sobre ventas y productos'),
('General', 'Consultas generales');
INSERT INTO users (nombre, email, password, rol) VALUES
('Admin', 'admin@helpdesk.com', '$2b$10$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36PQm4sEPhMNPfFhpYN76eO', 'admin');
-- Password: 123456
+146
View File
@@ -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);
});