2025-09-05 20:28:15 -03:00
|
|
|
const pool = require('../data/database');
|
|
|
|
|
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 {
|
|
|
|
|
|
|
|
|
|
static async saveTicket(ticketData, typeTicket) {
|
|
|
|
|
const query = `
|
|
|
|
|
INSERT INTO tickets_sn
|
|
|
|
|
(ticket_number, short_description, description, caller_email,
|
|
|
|
|
location_name, ramal, telefone, opened_at, tipo)
|
|
|
|
|
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)
|
|
|
|
|
ON CONFLICT (ticket_number)
|
|
|
|
|
DO UPDATE SET
|
|
|
|
|
short_description = EXCLUDED.short_description,
|
|
|
|
|
description = EXCLUDED.description,
|
|
|
|
|
location_name = EXCLUDED.location_name,
|
|
|
|
|
caller_email = EXCLUDED.caller_email,
|
|
|
|
|
ramal = EXCLUDED.ramal,
|
|
|
|
|
telefone = EXCLUDED.telefone,
|
|
|
|
|
updated_at = NOW()
|
|
|
|
|
RETURNING id, xmax = 0 as inserted -- xmax = 0 indica INSERT, >0 indica UPDATE`;
|
2025-08-30 19:04:35 -03:00
|
|
|
|
2025-09-05 20:28:15 -03:00
|
|
|
const values = [
|
|
|
|
|
ticketData.number?.value || null,
|
|
|
|
|
ticketData.short_description?.value || null,
|
|
|
|
|
ticketData.description?.value || null,
|
|
|
|
|
ticketData['opened_by.email']?.value || null,
|
|
|
|
|
ticketData.location?.display_value || null,
|
|
|
|
|
ticketData['variables.numero_ramal']?.value || null,
|
|
|
|
|
ticketData['variables.telephone_favorecido_rh']?.value || null,
|
|
|
|
|
ticketData.opened_at?.value ? new Date(ticketData.opened_at.value) : null,
|
|
|
|
|
typeTicket
|
|
|
|
|
];
|
2025-08-30 19:04:35 -03:00
|
|
|
|
2025-09-05 20:28:15 -03:00
|
|
|
try {
|
|
|
|
|
const result = await pool.query(query, values);
|
|
|
|
|
const wasInserted = result.rows[0].inserted; // true = INSERT, false = UPDATE
|
|
|
|
|
|
|
|
|
|
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'
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return result.rows[0].id;
|
|
|
|
|
} catch (error) {
|
|
|
|
|
logError(error, `❌ Erro ao salvar ticket ${values[0]}`);
|
|
|
|
|
throw error;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
}
|
|
|
|
|
module.exports = TicketSnModel;
|