snglpi/src/models/ticketSnModel.js

67 lines
2.6 KiB
JavaScript
Raw Normal View History

const pool = require('../data/database');
const { logInfo, logError, logWarning } = require('../utils/logger');
2025-08-30 19:04:35 -03:00
class TicketSnModel {
static async saveTicket(ticketData, typeTicket) {
const query = `
INSERT INTO tickets_sn
(ticket_number, short_description, description, caller_id, caller_email,
location_id, location_name, ramal, telefone, opened_at, tipo)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)
ON CONFLICT (ticket_number)
DO UPDATE SET
short_description = EXCLUDED.short_description,
description = EXCLUDED.description,
location_id = EXCLUDED.location_id,
location_name = EXCLUDED.location_name,
caller_id = EXCLUDED.caller_id,
caller_email = EXCLUDED.caller_email,
ramal = EXCLUDED.ramal,
telefone = EXCLUDED.telefone,
updated_at = NOW()
RETURNING id, xmax = 0 as inserted`;
2025-08-30 19:04:35 -03:00
const values = [
ticketData.number?.value || null,
ticketData.short_description?.value || null,
ticketData.description?.value || null,
ticketData.opened_by?.display_value || null,
ticketData['opened_by.email']?.value || null,
ticketData.location?.value || null, // location_id (value)
ticketData.location?.display_value || null, // location_name (display_value)
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
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;