From b2b73644189a9ca612723e2ccfa97f4bf3b08c34 Mon Sep 17 00:00:00 2001 From: Rafael Lopes Date: Wed, 7 Jan 2026 08:31:39 -0300 Subject: [PATCH] HOTFIX: Deletado arquivos legado que entravam em conflito --- .../tickets/repositories/ticket.repository.js | 8 +- src/shared/infra/database/glpi.pool.js | 17 -- src/shared/infra/database/hubglpi.pool.js | 15 -- src/shared/infra/database/hubsoft.pool.js | 14 -- src/shared/infra/database/index.js | 7 - src/shared/model/glpi.model.js | 38 ---- src/shared/model/hubglpi.model.js | 100 --------- src/shared/repositories/glpi.repository.js | 93 -------- src/shared/repositories/hubglpi.repository.js | 205 ------------------ src/shared/repositories/hubsoft.repository.js | 119 ---------- 10 files changed, 4 insertions(+), 612 deletions(-) delete mode 100644 src/shared/infra/database/glpi.pool.js delete mode 100644 src/shared/infra/database/hubglpi.pool.js delete mode 100644 src/shared/infra/database/hubsoft.pool.js delete mode 100644 src/shared/infra/database/index.js delete mode 100644 src/shared/model/glpi.model.js delete mode 100644 src/shared/model/hubglpi.model.js delete mode 100644 src/shared/repositories/glpi.repository.js delete mode 100644 src/shared/repositories/hubglpi.repository.js delete mode 100644 src/shared/repositories/hubsoft.repository.js diff --git a/src/modules/tickets/repositories/ticket.repository.js b/src/modules/tickets/repositories/ticket.repository.js index d94eab5..63fd175 100644 --- a/src/modules/tickets/repositories/ticket.repository.js +++ b/src/modules/tickets/repositories/ticket.repository.js @@ -116,15 +116,15 @@ async function sendHubsoftMessage(hubId, message){ return hubsoftApiClient.sendHubsoftMessage(hubId, message) } -async function sendHubglpiMessage(glpiId, message) { - const syncDataId = await hubglpiSyncRepo.getSyncIdByHubsoftId(glpiId); +async function sendHubglpiMessage(hubId, message) { + const syncDataId = await hubglpiSyncRepo.getSyncIdByHubsoftId(hubId); if (!syncDataId) { - throw new Error(`sync_data não encontrado para ticket ${glpiId}`); + throw new Error(`sync_data não encontrado para ticket ${hubId}`); } return hubglpiCommentsRepo.insertSyncComment({ - syncDataId, + syncDataId: syncDataId.id, content: message, author: 'hubsoft-sync' }); diff --git a/src/shared/infra/database/glpi.pool.js b/src/shared/infra/database/glpi.pool.js deleted file mode 100644 index b330413..0000000 --- a/src/shared/infra/database/glpi.pool.js +++ /dev/null @@ -1,17 +0,0 @@ -// src/shared/infra/database/glpi.pool.js -// MySQL / MariaDB - GLPI -const mysql = require('mysql2/promise'); -const { Pool } = require('pg'); - -const pool = mysql.createPool({ - host: process.env.GLPI_DB_HOST, - port: process.env.GLPI_DB_PORT, - user: process.env.GLPI_DB_USER, - password: process.env.GLPI_DB_PASSWORD, - database: process.env.GLPI_DB_NAME, - waitForConnections: true, - connectionLimit: 20, - queueLimit: 0, -}); - -module.exports = pool; diff --git a/src/shared/infra/database/hubglpi.pool.js b/src/shared/infra/database/hubglpi.pool.js deleted file mode 100644 index 45af961..0000000 --- a/src/shared/infra/database/hubglpi.pool.js +++ /dev/null @@ -1,15 +0,0 @@ -// src/shared/infra/database/hubglpi.pool.js -// PostgreSQL - HUBSOFT -const { Pool } = require("pg"); - -const hubglpiPool = new Pool({ - host: process.env.HUBGLPI_DB_HOST, - port: process.env.HUBGLPI_DB_PORT, - user: process.env.HUBGLPI_DB_USER, - password: process.env.HUBGLPI_DB_PASSWORD, - database: process.env.HUBGLPI_DB_NAME, - max: 20, - idleTimeoutMillis: 30000, -}); - -module.exports = hubglpiPool; diff --git a/src/shared/infra/database/hubsoft.pool.js b/src/shared/infra/database/hubsoft.pool.js deleted file mode 100644 index 5c38f07..0000000 --- a/src/shared/infra/database/hubsoft.pool.js +++ /dev/null @@ -1,14 +0,0 @@ -// PostgreSQL - HUBSOFT -const { Pool } = require("pg"); - -const hubsoftPool = new Pool({ - host: process.env.HUBSOFT_DATABASE_HOST, - port: process.env.HUBSOFT_DATABASE_PORT, - user: process.env.HUBSOFT_DATABASE_USER, - password: process.env.HUBSOFT_DATABASE_PASSWORD, - database: process.env.HUBSOFT_DATABASE_NAME, - max: 20, - idleTimeoutMillis: 30000, -}); - -module.exports = hubsoftPool; diff --git a/src/shared/infra/database/index.js b/src/shared/infra/database/index.js deleted file mode 100644 index 1821b4b..0000000 --- a/src/shared/infra/database/index.js +++ /dev/null @@ -1,7 +0,0 @@ -// src/shared/infra/database/index.js - -module.exports = { - hubsoft: require("./hubsoft.pool"), - hubglpi: require("./hubglpi.pool"), - glpi: require("./glpi.pool") -}; diff --git a/src/shared/model/glpi.model.js b/src/shared/model/glpi.model.js deleted file mode 100644 index ddd0f0c..0000000 --- a/src/shared/model/glpi.model.js +++ /dev/null @@ -1,38 +0,0 @@ -// src/shared/model/glpi.model.js - -function mapHubGlpiToGlpi(ticket) { - return { - entities_id: ticket.entities_id || 0, - name: ticket.name, - date: ticket.created_at, - status: defineStatusGlpi(ticket.status), - users_id_recipient: parseInt(process.env.GLPI_USER_ID) || 0, - content: ticket.content, - urgency: 3, - impact: 3, - priority: 3, - type: 2, - requesttypes_id: 2, - date_creation : ticket.date_creation || new Date(), - itilcategories_id: 1, - slas_id_ttr: 37 - }; -} - -function defineStatusGlpi(Status) { - const mapStatusDBtoGLPI = { - 'Novo': 1, - 'Pendente': 4, - 'Em atendimento': 2, - 'Resolvido': 5 - }; - - return mapStatusDBtoGLPI[Status] || 1; -}; - - - -module.exports = { - mapHubGlpiToGlpi, - defineStatusGlpi -}; diff --git a/src/shared/model/hubglpi.model.js b/src/shared/model/hubglpi.model.js deleted file mode 100644 index b6c0069..0000000 --- a/src/shared/model/hubglpi.model.js +++ /dev/null @@ -1,100 +0,0 @@ -// src/shared/model/hubglpi.model.js - -function mapHubsoftToHubglpi(ticket, type) { - return { - id_atendimento: ticket.id_atendimento, - codigo_cliente: ticket.codigo_cliente, - status_atendimento: defineStatusHubglpi(ticket.id_atendimento_status), - servico_nome: ticket.descricao, - protocolo_hub: ticket.protocolo, - - // Extrai número do protocolo do Mundiale - ticket_mundiale: extractMundiale(ticket.descricao_abertura, type), - - codigo_servico: ticket.id_cliente_servico, - cliente_nome: ticket.nome_contato, - descricao_fechamento: ticket.descricao_fechamento || null, - data_fechamento: ticket.data_fechamento || null, - created_at: ticket.data_cadastro, - ticket_type: type, - descricao_abertura: ticket.descricao_abertura || null, - endereco: endereco(ticket), - telefone: sanitizePhone(ticket.telefone), - - cpf_cnpj: sanitizeCpfCnpj(ticket.cpf_cnpj), - - tipo_pessoa: ticket.tipo_pessoa || null, - email: ticket.email || null, - nome_razaosocial: ticket.nome_razaosocial || null - }; -} - -/* ----------------- - Sanitização ------------------- */ - -function sanitizeCpfCnpj(value) { - if (!value) return null; - - // Se vier número gigantesco do JS tipo 3.2e+22 → converte pra string - const str = String(value); - - // Remove qualquer coisa que não seja número - const clean = str.replace(/\D/g, ""); - - return clean.length > 0 ? clean : null; -} - -function sanitizePhone(phone) { - if (!phone) return null; - const clean = String(phone).replace(/\D/g, ""); - return clean || null; -} - -function extractMundiale(descricao, type) { - if (type === 'IMPLANTACAO') return null; - - if (!descricao) return null; - - // Extrai apenas dígitos - const num = descricao.replace(/\D/g, ""); - - // Previne NaN - return num ? parseInt(num, 10) : null; -} - -/* ----------------- - Endereço ------------------- */ - -function endereco(ticket) { - if (!ticket.endereco || !ticket.numero || !ticket.cidade || !ticket.estado) { - return null; - } - - const complemento = ticket.complemento ? ` - ${ticket.complemento}` : ""; - const bairro = ticket.bairro ? `${ticket.bairro}` : ""; - const cep = ticket.cep ? ticket.cep : ""; - - return `${ticket.endereco}, ${ticket.numero}${complemento}, ${bairro} - ${ticket.cidade}/${ticket.estado} - CEP ${cep}`; -} - -/* ----------------- - Status Mapper ------------------- */ - -function defineStatusHubglpi(hubsoftStatus) { - const statusMap = { - 1: "Pendente", - 2: "Em atendimento", - 3: "Resolvido", - 31: "Pendente", - 32: "Pendente", - 33: "Novo" - }; - return statusMap[hubsoftStatus] || "Novo"; -} - -module.exports = { - mapHubsoftToHubglpi -}; diff --git a/src/shared/repositories/glpi.repository.js b/src/shared/repositories/glpi.repository.js deleted file mode 100644 index 76a7122..0000000 --- a/src/shared/repositories/glpi.repository.js +++ /dev/null @@ -1,93 +0,0 @@ -// src/shared/repositories/glpi.repository.js -const { glpi } = require("../../shared/infra/database"); -const { logInfo, logError } = require('../../utils/logger.js'); - -async function insertTicket(ticket) { - const sql = ` - INSERT INTO glpi_tickets - (entities_id, name, date, date_mod, status, users_id_recipient, content, urgency, impact, priority, type, itilcategories_id, date_creation, slas_id_ttr) - VALUES (?, ?, ?, NOW(), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) - `; - - const values = [ - ticket.entities_id, - ticket.name, - ticket.date, - ticket.status, - ticket.users_id_recipient, - ticket.content, - ticket.urgency, - ticket.impact, - ticket.priority, - ticket.type, - ticket.itilcategories_id, - ticket.date_creation, - ticket.slas_id_ttr - ]; - - const [result] = await glpi.execute(sql, values); - return result.insertId; -} - -async function getEntitiesByService(codigoCliente, codigoServico) { - try { - const sql = `SELECT id FROM glpi_entities WHERE name LIKE ? or name LIKE ? or name LIKE ? LIMIT 1;`; - const values = [`${codigoCliente}-${codigoServico}-%`, `${codigoCliente} -${codigoServico}-%`, `${codigoCliente} - ${codigoServico} -%`]; - const [rows] = await glpi.execute(sql, values); - if (rows.length > 0) { - return rows[0].id; - } - return null; - } catch (error) { - logError(`Erro ao buscar entidade por código de serviço: ${error}`); - throw error; - } -} - -async function getEntitiesByClient(codigoCliente) { - try { - const sql = `SELECT id FROM glpi_entities WHERE name LIKE ? or name LIKE ? LIMIT 1;`; - const values = [`${codigoCliente}-%`, `${codigoCliente} -%`]; - const [rows] = await glpi.execute(sql, values); - if (rows.length > 0) { - return rows[0].id; - } - return null; - } catch (error) { - logError(`Erro ao buscar entidade por código de cliente: ${error}`); - throw error; - } -} - -async function insertEntity(entity_name){ - -} - -async function insertGroupTicket(ticketId, type) { - try { - - let groupId = 25; // Grupo padrão (Operação NOC) - - if (type === 'IMPLANTACAO') { - groupId = 36; // Grupo de Implantação - } - - const sql = `INSERT INTO glpi_groups_tickets (tickets_id, groups_id, type) - VALUES (?, ?, 2) - `; - const values = [ticketId, groupId]; - await glpi.execute(sql, values); - logInfo(`Grupo associado ao ticket GLPI ID: ${ticketId}`); - } catch (error) { - logError(`Erro ao associar grupo ao ticket GLPI ID ${ticketId}: ${error}`); - throw error; - } - -} - -module.exports = { - insertTicket, - getEntitiesByService, - getEntitiesByClient, - insertGroupTicket -}; \ No newline at end of file diff --git a/src/shared/repositories/hubglpi.repository.js b/src/shared/repositories/hubglpi.repository.js deleted file mode 100644 index 61c7e5c..0000000 --- a/src/shared/repositories/hubglpi.repository.js +++ /dev/null @@ -1,205 +0,0 @@ -// src/shared/repositories/hubglpi.repository.js - -const { hubglpi } = require("../../shared/infra/database"); -const { logInfo, logError } = require("../../utils/logger.js"); - -async function insertTickets(tickets) { - try { - const values = tickets.map(t => [ - t.id_atendimento, - t.codigo_cliente, - t.status_atendimento, - t.servico_nome, - t.protocolo_hub, - t.ticket_mundiale, - t.codigo_servico, - t.cliente_nome, - t.descricao_fechamento, - t.data_fechamento, - t.created_at, - t.updated_at, - t.ticket_type, - t.descricao_abertura, - t.endereco, - t.telefone, - t.cpf_cnpj, - t.tipo_pessoa, - t.email, - t.nome_razaosocial - ]); - - const totalColumns = 20; - - const rowPlaceholders = values - .map( - (_, rowIndex) => - `(${Array.from({ length: totalColumns }) - .map((_, colIndex) => `$${rowIndex * totalColumns + colIndex + 1}`) - .join(", ")})` - ) - .join(", "); - - const query = ` - INSERT INTO public.hubsoft_tickets - ( - id_atendimento, - codigo_cliente, - status_atendimento, - servico_nome, - protocolo_hub, - ticket_mundiale, - codigo_servico, - cliente_nome, - descricao_fechamento, - data_fechamento, - created_at, - updated_at, - ticket_type, - descricao_abertura, - endereco, - telefone, - cpf_cnpj, - tipo_pessoa, - email, - nome_razaosocial - ) - VALUES ${rowPlaceholders} - ON CONFLICT (id_atendimento) - DO UPDATE SET - codigo_cliente = EXCLUDED.codigo_cliente, - status_atendimento = EXCLUDED.status_atendimento, - servico_nome = EXCLUDED.servico_nome, - protocolo_hub = EXCLUDED.protocolo_hub, - ticket_mundiale = EXCLUDED.ticket_mundiale, - codigo_servico = EXCLUDED.codigo_servico, - cliente_nome = EXCLUDED.cliente_nome, - descricao_fechamento = EXCLUDED.descricao_fechamento, - data_fechamento = EXCLUDED.data_fechamento, - updated_at = EXCLUDED.updated_at, - ticket_type = EXCLUDED.ticket_type, - descricao_abertura = EXCLUDED.descricao_abertura, - endereco = EXCLUDED.endereco, - telefone = EXCLUDED.telefone, - cpf_cnpj = EXCLUDED.cpf_cnpj, - tipo_pessoa = EXCLUDED.tipo_pessoa, - email = EXCLUDED.email, - nome_razaosocial = EXCLUDED.nome_razaosocial - `; - - const flattened = values.flat(); - - await hubglpi.query(query, flattened); - - logInfo(`Tickets salvos/atualizados: ${tickets.length}`); - - return { success: true, ids: tickets.map(t => t.id_atendimento) }; - - } catch (error) { - logError("Erro ao inserir tickets no HubGLPI:", error); - throw error; - } -} - -async function insertSyncData(ids) { - try { - const rowPlaceholders = ids - .map((_, i) => `($${i + 1})`) - .join(", "); - - const query = ` - INSERT INTO sync_data (hubsoft_ticket_id) - VALUES ${rowPlaceholders} - ON CONFLICT (hubsoft_ticket_id) - DO UPDATE SET hubsoft_ticket_id = EXCLUDED.hubsoft_ticket_id - `; - - await hubglpi.query(query, ids); - - logInfo(`Sync data criada/atualizada para ${ids.length} tickets.`); - - return true; - - } catch (error) { - logError("Erro ao inserir dados de sincronização no HubGLPI:", error); - throw error; - } -} - -async function fetchPendingTickets() { - try { - const query = ` - SELECT - ht.id_atendimento, - ht.codigo_cliente, - ht.status_atendimento, - ht.codigo_servico, - ht.servico_nome, - ht.protocolo_hub, - ht.ticket_mundiale, - ht.cliente_nome, - ht.created_at, - ht.ticket_type, - - -- NOVOS CAMPOS - ht.descricao_abertura, - ht.endereco, - ht.telefone, - ht.cpf_cnpj, - ht.tipo_pessoa, - ht.email, - ht.nome_razaosocial, - - -- CAMPOS DA SYNC_DATA - sd.id AS sync_data_id, - sd.glpi_ticket_id, - sd.status_sync, - sd.sync_metadata, - sd.last_sync_attempt, - sd.sync_error_message, - sd.created_at AS sync_created_at, - sd.updated_at AS sync_updated_at - - FROM hubsoft_tickets AS ht - LEFT JOIN sync_data AS sd - ON ht.id_atendimento = sd.hubsoft_ticket_id - WHERE sd.status_sync IS NULL - OR sd.status_sync = 'pending_create' - ORDER BY ht.created_at ASC; - `; - - const result = await hubglpi.query(query); - return result.rows; - - } catch (error) { - logError("Erro ao buscar tickets pendentes no HubGLPI:", error); - throw error; - } -} - - -async function updateSyncDataCreated(hubsoftTicketId, glpiId) { - try { - const sql = ` - UPDATE sync_data - SET - status_sync = 'created_glpi', - updated_at = NOW(), - last_sync_attempt = NOW(), - glpi_ticket_id = $1 - WHERE hubsoft_ticket_id = $2 - `; - - await hubglpi.query(sql, [glpiId, hubsoftTicketId]); - - } catch (error) { - logError("Erro ao atualizar sync_data para ticket criado no GLPI:", error); - throw error; - } -} - -module.exports = { - insertTickets, - insertSyncData, - fetchPendingTickets, - updateSyncDataCreated -}; diff --git a/src/shared/repositories/hubsoft.repository.js b/src/shared/repositories/hubsoft.repository.js deleted file mode 100644 index 44b2b52..0000000 --- a/src/shared/repositories/hubsoft.repository.js +++ /dev/null @@ -1,119 +0,0 @@ -// src/shared/repositories/hubsoft.repository.js -const { get } = require('pm2'); -const { hubsoft } = require("../../shared/infra/database"); -const { logInfo, logError } = require('../../utils/logger.js'); - - -async function getMundialeTickets() { - - try { - const query = `SELECT a.id_atendimento, a.id_usuario_abertura, a.id_atendimento_status, a.protocolo, a.descricao_abertura, a.data_cadastro, a.nome_contato, c.codigo_cliente, s.descricao, cs.id_cliente_servico FROM atendimento AS a INNER JOIN cliente_servico AS cs ON a.id_cliente_servico = cs.id_cliente_servico INNER JOIN cliente AS c ON cs.id_cliente = c.id_cliente INNER JOIN servico AS s ON cs.id_servico = s.id_servico WHERE a.id_tipo_atendimento = 4 AND a.id_usuario_abertura = 248 AND a.id_atendimento_status IN (1, 2, 33) AND s.ativo = true;`; - const { rows } = await hubsoft.query(query); - return rows; - } catch (error) { - logError("Erro ao buscar tickets Mundiale:", error); - throw error; - } -} - -async function getImplantacaoTickets() { - try { - const query = ` - SELECT - a.id_atendimento, - a.id_usuario_abertura, - a.id_atendimento_status, - a.protocolo, - a.descricao_abertura, - a.data_cadastro, - a.nome_contato, - - -- DADOS DO CLIENTE (novos) - c.nome_razaosocial, - c.telefone_primario AS telefone, - c.cpf_cnpj, - c.tipo_pessoa, - c.email_principal AS email, - - c.codigo_cliente, - s.descricao AS descricao, - cs.id_cliente_servico, - - -- ENDEREÇO DE INSTALAÇÃO - en.endereco, - en.numero, - en.complemento, - en.bairro, - en.cep, - ci.nome AS cidade, - es.sigla AS estado - - FROM atendimento AS a - - INNER JOIN cliente_servico AS cs - ON a.id_cliente_servico = cs.id_cliente_servico - - INNER JOIN cliente AS c - ON cs.id_cliente = c.id_cliente - - INNER JOIN servico AS s - ON cs.id_servico = s.id_servico - - -- endereço do cliente - INNER JOIN cliente_servico_endereco AS cse - ON cse.id_cliente_servico = cs.id_cliente_servico - AND cse.tipo = 'instalacao' - - INNER JOIN endereco_numero AS en - ON en.id_endereco_numero = cse.id_endereco_numero - - INNER JOIN cidade AS ci - ON ci.id_cidade = en.id_cidade - - INNER JOIN estado AS es - ON es.id_estado = ci.id_estado - - WHERE - a.id_tipo_atendimento = 21 - AND a.id_atendimento_status IN (1, 2, 33) - AND s.ativo = TRUE; - `; - const { rows } = await hubsoft.query(query); - return rows; - - } catch (error) { - logError("Erro ao buscar tickets Implantação:", error); - throw error; - } -} - -async function getCancelamentoTickets() { - try { - const query = `SELECT a.id_atendimento, a.id_usuario_abertura, a.id_atendimento_status, a.protocolo, a.descricao_abertura, a.data_cadastro, a.nome_contato, c.codigo_cliente, s.descricao, cs.id_cliente_servico FROM atendimento AS a INNER JOIN cliente_servico AS cs ON a.id_cliente_servico = cs.id_cliente_servico INNER JOIN cliente AS c ON cs.id_cliente = c.id_cliente INNER JOIN servico AS s ON cs.id_servico = s.id_servico WHERE a.id_tipo_atendimento = 27 AND a.id_atendimento_status IN (1, 2, 33) AND s.ativo = true;`; - const { rows } = await hubsoft.query(query); - return rows; - } catch (error) { - logError("Erro ao buscar tickets Cancelamento:", error); - throw error; - } -} - -async function getSacTickets() { - try { - const query = `SELECT a.id_atendimento, a.id_usuario_abertura, a.id_atendimento_status, a.protocolo, a.descricao_abertura, a.data_cadastro, a.nome_contato, c.codigo_cliente, s.descricao, cs.id_cliente_servico FROM atendimento AS a INNER JOIN cliente_servico AS cs ON a.id_cliente_servico = cs.id_cliente_servico INNER JOIN cliente AS c ON cs.id_cliente = c.id_cliente INNER JOIN servico AS s ON cs.id_servico = s.id_servico WHERE a.id_tipo_atendimento = 41 AND a.id_atendimento_status IN (1, 2, 33) AND s.ativo = true;`; - const { rows } = await hubsoft.query(query); - return rows; - } catch (error) { - logError("Erro ao buscar tickets SAC:", error); - throw error; - } -} - - -module.exports = { - getMundialeTickets, - getImplantacaoTickets, - getCancelamentoTickets, - getSacTickets - -}; \ No newline at end of file