2025-09-11 20:57:43 -03:00
|
|
|
// src/models/ticketSnModel.js
|
2025-09-05 20:28:15 -03:00
|
|
|
const pool = require('../data/database');
|
2025-09-15 20:55:19 -03:00
|
|
|
const { logInfo, logError, logWarning } = require('../utils/logger');
|
2025-08-30 19:04:35 -03:00
|
|
|
|
2025-09-05 20:28:15 -03:00
|
|
|
class TicketSnModel {
|
2025-09-15 20:55:19 -03:00
|
|
|
|
|
|
|
|
// Salva ou atualiza um ticket no banco de dados
|
2025-09-05 20:28:15 -03:00
|
|
|
static async saveTicket(ticketData, typeTicket) {
|
2025-09-08 20:35:49 -03:00
|
|
|
const query = `
|
2025-09-05 20:28:15 -03:00
|
|
|
INSERT INTO tickets_sn
|
2025-09-15 20:55:19 -03:00
|
|
|
(ticket_number, sys_id, short_description, status, description, caller_id, caller_email,
|
2025-09-08 20:35:49 -03:00
|
|
|
location_id, location_name, ramal, telefone, opened_at, tipo)
|
2025-09-15 20:55:19 -03:00
|
|
|
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13)
|
2025-09-05 20:28:15 -03:00
|
|
|
ON CONFLICT (ticket_number)
|
|
|
|
|
DO UPDATE SET
|
2025-09-15 20:55:19 -03:00
|
|
|
sys_id = EXCLUDED.sys_id,
|
2025-09-05 20:28:15 -03:00
|
|
|
short_description = EXCLUDED.short_description,
|
2025-09-11 20:57:43 -03:00
|
|
|
status = EXCLUDED.status,
|
2025-09-05 20:28:15 -03:00
|
|
|
description = EXCLUDED.description,
|
2025-09-08 20:35:49 -03:00
|
|
|
caller_id = EXCLUDED.caller_id,
|
2025-09-05 20:28:15 -03:00
|
|
|
caller_email = EXCLUDED.caller_email,
|
2025-09-11 20:57:43 -03:00
|
|
|
location_id = EXCLUDED.location_id,
|
|
|
|
|
location_name = EXCLUDED.location_name,
|
2025-09-05 20:28:15 -03:00
|
|
|
ramal = EXCLUDED.ramal,
|
|
|
|
|
telefone = EXCLUDED.telefone,
|
2025-09-11 20:57:43 -03:00
|
|
|
opened_at = EXCLUDED.opened_at,
|
2025-10-13 06:06:52 -03:00
|
|
|
tipo = EXCLUDED.tipo
|
2025-10-23 17:30:03 -03:00
|
|
|
RETURNING id, (xmax = 0) AS "wasInserted"`; // xmax=0 é um truque do PostgreSQL para saber se foi INSERT
|
2025-08-30 19:04:35 -03:00
|
|
|
|
2025-10-24 13:13:08 -03:00
|
|
|
// Trata a diferença na estrutura do campo 'number' entre Incidentes e Requisições
|
|
|
|
|
const ticketNumber = typeof ticketData.number === 'object' ? ticketData.number?.value : ticketData.number;
|
|
|
|
|
|
|
|
|
|
// Mapeamento inteligente de campos baseado no tipo de ticket
|
|
|
|
|
let callerName, callerEmail, ramal, telefone, sysId, shortDescription, state, description, locationId, locationName, openedAt;
|
|
|
|
|
|
|
|
|
|
if (typeTicket === 'incidente') {
|
|
|
|
|
callerName = ticketData.caller_id?.display_value;
|
|
|
|
|
// O campo de email para incidentes vem como um objeto, precisamos extrair o valor.
|
|
|
|
|
const emailObject = ticketData['caller_id.email'] || {};
|
|
|
|
|
callerEmail = (typeof emailObject === 'object' ? emailObject.value : emailObject) || null;
|
|
|
|
|
ramal = null; // Incidentes não têm essa variável por padrão
|
|
|
|
|
telefone = null; // Incidentes não têm essa variável por padrão
|
|
|
|
|
sysId = ticketData.sys_id?.value || null;
|
|
|
|
|
shortDescription = ticketData.short_description?.value || null;
|
|
|
|
|
state = ticketData.state?.display_value || null;
|
|
|
|
|
description = ticketData.description?.value || null;
|
|
|
|
|
locationId = ticketData.location?.value || null;
|
|
|
|
|
locationName = ticketData.location?.display_value || null;
|
|
|
|
|
openedAt = ticketData.opened_at?.value || null;
|
|
|
|
|
} else { // 'requisicao'
|
|
|
|
|
callerName = ticketData.opened_by?.display_value || null;
|
|
|
|
|
callerEmail = ticketData['opened_by.email'] || null;
|
|
|
|
|
ramal = ticketData['variables.numero_ramal'] || null;
|
|
|
|
|
telefone = ticketData['variables.telephone_favorecido_rh'] || null;
|
|
|
|
|
sysId = ticketData.sys_id || null;
|
|
|
|
|
shortDescription = ticketData.short_description || null;
|
|
|
|
|
state = ticketData.state || null;
|
|
|
|
|
description = ticketData.description || null;
|
|
|
|
|
// Para requisições, o sys_id da localização vem no final da URL do link
|
|
|
|
|
const locationLink = ticketData.location?.link;
|
|
|
|
|
locationId = locationLink ? locationLink.substring(locationLink.lastIndexOf('/') + 1) : null;
|
|
|
|
|
locationName = ticketData.location?.display_value || null;
|
|
|
|
|
openedAt = ticketData.opened_at || null;
|
|
|
|
|
}
|
|
|
|
|
|
2025-09-15 20:55:19 -03:00
|
|
|
const values = [
|
2025-10-24 13:13:08 -03:00
|
|
|
ticketNumber,
|
|
|
|
|
sysId,
|
|
|
|
|
shortDescription,
|
|
|
|
|
state,
|
|
|
|
|
description,
|
|
|
|
|
callerName,
|
|
|
|
|
callerEmail,
|
|
|
|
|
locationId,
|
|
|
|
|
locationName,
|
|
|
|
|
ramal,
|
|
|
|
|
telefone,
|
|
|
|
|
openedAt
|
|
|
|
|
? (typeof openedAt === 'string' && openedAt.includes('/')
|
|
|
|
|
? new Date(openedAt.replace(/(\d{2})\/(\d{2})\/(\d{4})/, '$3-$2-$1'))
|
|
|
|
|
: new Date(openedAt))
|
|
|
|
|
: null,
|
2025-09-15 20:55:19 -03:00
|
|
|
typeTicket
|
2025-09-05 20:28:15 -03:00
|
|
|
];
|
2025-09-15 20:55:19 -03:00
|
|
|
|
2025-09-08 20:35:49 -03:00
|
|
|
|
2025-09-11 20:57:43 -03:00
|
|
|
try {
|
|
|
|
|
const result = await pool.query(query, values);
|
2025-10-23 17:30:03 -03:00
|
|
|
const wasInserted = result.rows[0].wasInserted; // Corrigido para corresponder ao alias "wasInserted"
|
2025-09-11 20:57:43 -03:00
|
|
|
|
|
|
|
|
if (wasInserted) {
|
|
|
|
|
logInfo(`✅ NOVO ticket salvo! ID: ${result.rows[0].id}`, {
|
|
|
|
|
ticket_id: result.rows[0].id,
|
|
|
|
|
ticket_number: values[0],
|
|
|
|
|
action: 'insert'
|
|
|
|
|
});
|
|
|
|
|
} else {
|
|
|
|
|
logInfo(`🔄 Ticket atualizado! ID: ${result.rows[0].id}`, {
|
|
|
|
|
ticket_id: result.rows[0].id,
|
|
|
|
|
ticket_number: values[0],
|
|
|
|
|
action: 'update'
|
|
|
|
|
});
|
|
|
|
|
}
|
2025-09-15 20:55:19 -03:00
|
|
|
|
2025-10-23 17:30:03 -03:00
|
|
|
return { id: result.rows[0].id, wasInserted };
|
2025-09-11 20:57:43 -03:00
|
|
|
} catch (error) {
|
|
|
|
|
logError(error, `❌ Erro ao salvar ticket ${values[0]}`);
|
2025-09-15 20:55:19 -03:00
|
|
|
throw error;
|
2025-09-11 20:57:43 -03:00
|
|
|
}
|
|
|
|
|
}
|
2025-08-30 19:04:35 -03:00
|
|
|
|
2025-09-15 20:55:19 -03:00
|
|
|
// Busca tickets que ainda não foram sincronizados com o GLPI
|
|
|
|
|
static async getPendingTickets() {
|
2025-09-11 20:57:43 -03:00
|
|
|
try {
|
|
|
|
|
const query = `
|
|
|
|
|
SELECT
|
2025-09-17 20:56:32 -03:00
|
|
|
ts.id,
|
|
|
|
|
ts.ticket_number,
|
|
|
|
|
ts.short_description,
|
|
|
|
|
ts.description,
|
|
|
|
|
ts.status,
|
|
|
|
|
ts.caller_id,
|
|
|
|
|
ts.caller_email,
|
|
|
|
|
ts.location_id,
|
|
|
|
|
ts.location_name,
|
|
|
|
|
ts.ramal,
|
|
|
|
|
ts.telefone,
|
|
|
|
|
ts.opened_at,
|
|
|
|
|
ts.tipo,
|
|
|
|
|
ts.created_at,
|
2025-10-17 16:58:14 -03:00
|
|
|
ts.updated_at,
|
|
|
|
|
tsync.glpi_ticket_id
|
2025-09-17 20:56:32 -03:00
|
|
|
FROM tickets_sn ts
|
|
|
|
|
LEFT JOIN ticket_sync tsync ON ts.id = tsync.sn_ticket_id
|
2025-10-13 06:06:52 -03:00
|
|
|
WHERE tsync.glpi_sync_status = 'pending_check'
|
2025-09-17 20:56:32 -03:00
|
|
|
ORDER BY ts.opened_at
|
2025-09-11 20:57:43 -03:00
|
|
|
`;
|
2025-09-15 20:55:19 -03:00
|
|
|
|
|
|
|
|
const result = await pool.query(query);
|
2025-09-11 20:57:43 -03:00
|
|
|
logInfo(`📋 Tickets pendentes encontrados: ${result.rows.length}`);
|
|
|
|
|
return result.rows;
|
2025-09-15 20:55:19 -03:00
|
|
|
|
2025-09-11 20:57:43 -03:00
|
|
|
} catch (error) {
|
|
|
|
|
logError(error, '❌ Erro ao buscar tickets pendentes');
|
|
|
|
|
return [];
|
2025-09-05 20:28:15 -03:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2025-09-17 20:56:32 -03:00
|
|
|
// Busca um ticket pelo número
|
|
|
|
|
static async findByTicketNumber(ticketNumber) {
|
2025-09-11 20:57:43 -03:00
|
|
|
try {
|
|
|
|
|
const query = `
|
2025-09-17 20:56:32 -03:00
|
|
|
SELECT * FROM tickets_sn
|
|
|
|
|
WHERE ticket_number = $1
|
2025-09-11 20:57:43 -03:00
|
|
|
`;
|
2025-09-15 20:55:19 -03:00
|
|
|
|
2025-09-17 20:56:32 -03:00
|
|
|
const result = await pool.query(query, [ticketNumber]);
|
|
|
|
|
return result.rows[0] || null;
|
2025-09-15 20:55:19 -03:00
|
|
|
|
2025-09-11 20:57:43 -03:00
|
|
|
} catch (error) {
|
2025-09-17 20:56:32 -03:00
|
|
|
logError(error, `❌ Erro ao buscar ticket por número: ${ticketNumber}`);
|
|
|
|
|
return null;
|
2025-09-11 20:57:43 -03:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2025-10-23 17:30:03 -03:00
|
|
|
|
|
|
|
|
// Busca o status de um ticket pelo ID
|
|
|
|
|
static async getStatus(ticketId) {
|
|
|
|
|
try {
|
|
|
|
|
const query = `
|
|
|
|
|
SELECT status,tipo FROM tickets_sn
|
|
|
|
|
WHERE id = $1`;
|
|
|
|
|
const result = await pool.query(query, [ticketId]);
|
|
|
|
|
return result.rows || null;
|
|
|
|
|
} catch (error) {
|
|
|
|
|
logError(error, `❌ Erro ao buscar status do ticket: ${ticketId}`);
|
|
|
|
|
return null;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
2025-09-17 20:56:32 -03:00
|
|
|
// Busca um ticket pelo ID
|
|
|
|
|
static async findById(ticketId) {
|
|
|
|
|
try {
|
|
|
|
|
const query = `
|
|
|
|
|
SELECT * FROM tickets_sn
|
|
|
|
|
WHERE id = $1
|
|
|
|
|
`;
|
|
|
|
|
|
|
|
|
|
const result = await pool.query(query, [ticketId]);
|
|
|
|
|
return result.rows[0] || null;
|
2025-09-05 20:28:15 -03:00
|
|
|
|
2025-09-17 20:56:32 -03:00
|
|
|
} catch (error) {
|
|
|
|
|
logError(error, `❌ Erro ao buscar ticket por ID: ${ticketId}`);
|
|
|
|
|
return null;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Atualiza os dados de um ticket
|
|
|
|
|
static async updateTicket(ticketId, updateData) {
|
2025-09-11 20:57:43 -03:00
|
|
|
try {
|
2025-09-17 20:56:32 -03:00
|
|
|
const fields = [];
|
|
|
|
|
const values = [];
|
|
|
|
|
let paramCount = 1;
|
|
|
|
|
|
|
|
|
|
// Construir dinamicamente a query baseada nos campos fornecidos
|
|
|
|
|
for (const [key, value] of Object.entries(updateData)) {
|
|
|
|
|
fields.push(`${key} = $${paramCount}`);
|
|
|
|
|
values.push(value);
|
|
|
|
|
paramCount++;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Adicionar updated_at
|
|
|
|
|
fields.push(`updated_at = NOW()`);
|
|
|
|
|
|
|
|
|
|
// Adicionar o ID no final dos valores
|
|
|
|
|
values.push(ticketId);
|
|
|
|
|
|
2025-09-11 20:57:43 -03:00
|
|
|
const query = `
|
2025-09-17 20:56:32 -03:00
|
|
|
UPDATE tickets_sn
|
|
|
|
|
SET ${fields.join(', ')}
|
|
|
|
|
WHERE id = $${paramCount}
|
|
|
|
|
RETURNING *
|
2025-09-11 20:57:43 -03:00
|
|
|
`;
|
2025-09-15 20:55:19 -03:00
|
|
|
|
2025-09-17 20:56:32 -03:00
|
|
|
const result = await pool.query(query, values);
|
|
|
|
|
|
|
|
|
|
if (result.rows.length > 0) {
|
|
|
|
|
logInfo(`✅ Ticket atualizado: ${ticketId}`);
|
|
|
|
|
return result.rows[0];
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return null;
|
2025-09-15 20:55:19 -03:00
|
|
|
|
2025-09-11 20:57:43 -03:00
|
|
|
} catch (error) {
|
2025-09-17 20:56:32 -03:00
|
|
|
logError(error, `❌ Erro ao atualizar ticket ${ticketId}`);
|
|
|
|
|
throw error;
|
2025-09-11 20:57:43 -03:00
|
|
|
}
|
|
|
|
|
}
|
2025-09-23 21:01:01 -03:00
|
|
|
|
|
|
|
|
|
2025-09-05 20:28:15 -03:00
|
|
|
}
|
2025-09-11 20:57:43 -03:00
|
|
|
|
2025-09-15 20:55:19 -03:00
|
|
|
/**
|
|
|
|
|
* @module TicketSnModel
|
|
|
|
|
* @description Este módulo fornece métodos para interagir com a tabela de tickets do ServiceNow (tickets_sn) no banco de dados.
|
|
|
|
|
* Inclui funcionalidades para salvar um ticket, buscar tickets pendentes para sincronização com o GLPI,
|
2025-09-17 20:56:32 -03:00
|
|
|
* e buscar/atualizar tickets específicos.
|
2025-09-15 20:55:19 -03:00
|
|
|
*
|
|
|
|
|
* A função saveTicket insere ou atualiza um ticket na tabela tickets_sn.
|
2025-09-17 20:56:32 -03:00
|
|
|
* A função getPendingTickets busca tickets que ainda não foram sincronizados com o GLPI (não possuem registro em ticket_sync)
|
|
|
|
|
* e ignora os tickets com status 'Encerrado' ou 'Encerrado - Omitido'.
|
2025-09-15 20:55:19 -03:00
|
|
|
*/
|
2025-09-05 20:28:15 -03:00
|
|
|
module.exports = TicketSnModel;
|