hubxglpi/src/modules/watchdog/job/job.js

67 lines
2.4 KiB
JavaScript
Raw Normal View History

// src/modules/watchdog/job/job.js
require('dotenv').config({ path: '.env.development' })
const { logError, logInfo } = require('../../../shared/utils/logger')
const repository = require('../repository/watchdog.repository.js')
const model = require('../model/email.model.js')
async function runWatchdog() {
logInfo('[WATCHDOG] [JOB] Coletando chamados fechados há 31 minutos')
const thresholdDate = new Date(Date.now() - 31 * 60 * 1000)
const closedTickets = await repository.getClosedTicketsSince(thresholdDate)
logInfo(`[WATCHDOG] [JOB] Encontrados ${closedTickets.length} chamados fechados`)
for (const ticket of closedTickets) {
const hubGlpiTicket = await repository.checkTicketInHubGlpi(ticket.id_atendimento)
if (!hubGlpiTicket.exists) {
logInfo(`[WATCHDOG] [JOB] Chamado ${ticket.id_atendimento} não encontrado no HubGlpi. Ignorando.`)
continue
}
if (hubGlpiTicket.status === 'closed') {
logInfo(`[WATCHDOG] [JOB] Chamado ${ticket.id_atendimento} já está fechado no HubGlpi. Ignorando.`)
continue
}
if (await repository.notificationAlreadySent(ticket.id_atendimento)) {
logInfo(`[WATCHDOG] [JOB] Notificação já enviada para o chamado ${ticket.id_atendimento}.`)
continue
}
await repository.markNotificationsAsPending([ticket.id_atendimento])
}
const ticketsToNotify = await repository.getPendingTicketsForNotification()
logInfo(`[WATCHDOG] [JOB] ${ticketsToNotify.length} chamados pendentes para notificação.`)
if (!ticketsToNotify.length) {
logInfo('[WATCHDOG] [JOB] Nenhum chamado pendente para notificação')
return
}
const payload = await model.prepareNotificationPayload(ticketsToNotify)
const hubsoftTicketIds = ticketsToNotify.map(t => Number(t.hubsoft_ticket_id)).filter(Number.isFinite);
try {
await repository.sendClosureNotifications(payload)
await repository.markNotificationsAsSent(hubsoftTicketIds)
} catch (err) {
logError('[WATCHDOG] Erro ao enviar notificações', err)
await repository.markNotificationsAsFailed(hubsoftTicketIds)
}
logInfo(`[WATCHDOG] [JOB] Enviadas ${ticketsToNotify.length} notificações`)
}
runWatchdog().catch((error) => {
logError('[WATCHDOG] [JOB] Erro ao executar o job do Watchdog', error)
})
module.exports = { runWatchdog}