snglpi/src/models/ticketUpdateModel.js

106 lines
3.6 KiB
JavaScript
Raw Normal View History

// src/models/ticketUpdateModel.js
const ticketSyncModel = require('./ticketSyncModel');
const pool = require('../data/database');
const { logError } = require('../utils/logger');
class TicketUpdateModel {
static async insert(updateData) {
const query = `
INSERT INTO ticket_updates (ticket_sync_id, update_type, source_system, content, author, created_at, updated_at, source_id, destiny_id)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)
2025-10-10 08:12:26 -03:00
ON CONFLICT (source_id) DO UPDATE SET
ticket_sync_id = $1,
update_type = $2,
source_system = $3,
content = $4,
author = $5,
created_at = $6,
updated_at = $7,
destiny_id = $9
RETURNING *;
`;
const values = [
updateData.ticket_sync_id,
updateData.update_type, // Corrigido para usar o tipo de atualização dinâmico
updateData.source_system,
updateData.content,
2025-10-10 08:12:26 -03:00
updateData.author,
updateData.created_at,
updateData.updated_at,
updateData.source_id,
updateData.destiny_id
];
try {
const { rows } = await pool.query(query, values);
return { success: true, newId: rows[0].id };
} catch (error) {
logError(error, '❌ Erro ao inserir ticket_update');
return { success: false, error: error.message };
}
}
static async getBySourceId(sourceId) {
2025-10-10 08:12:26 -03:00
try {
const query = 'SELECT * FROM ticket_updates WHERE source_id = $1';
2025-10-10 08:12:26 -03:00
const { rows } = await pool.query(query, [sourceId]);
return rows[0] || null;
} catch (error) {
logError(error, `❌ Erro ao buscar ticket_update por source_id: ${sourceId}`);
throw error;
}
}
static async getDestinyIdBySourceId(sourceId) {
try {
const query = `
SELECT destiny_id FROM ticket_updates
WHERE source_id = $1
`;
const { rows } = await pool.query(query, [sourceId]);
return rows[0] ? rows[0].destiny_id : null;
} catch (error) {
logError(error, '❌ Erro ao buscar destiny_id por source_id');
throw error;
}
}
static async updateDestinyId(sourceId, destinyId) {
try {
const query = `
UPDATE ticket_updates
SET destiny_id = $1
WHERE source_id = $2
`;
await pool.query(query, [destinyId, sourceId]);
return { success: true, destiny_id: destinyId };
} catch (error) {
logError(error, '❌ Erro ao atualizar destiny_id por source_id');
throw error;
}
}
static async getLatestUpdate(ticketSyncId, sourceSystem, updateType = null) {
try {
let query = `
SELECT * FROM ticket_updates
WHERE ticket_sync_id = $1 AND source_system = $2
`;
const values = [ticketSyncId, sourceSystem];
if (updateType) {
query += ` AND update_type = $3`;
values.push(updateType);
}
query += ` ORDER BY created_at DESC LIMIT 1`;
const { rows } = await pool.query(query, values);
return rows[0] || null;
} catch (error) {
logError(error, `❌ Erro ao buscar último update para ticket_sync_id: ${ticketSyncId}`);
throw error;
}
}
}
module.exports = TicketUpdateModel;