diff --git a/src/agenda/agenda.service.ts b/src/agenda/agenda.service.ts index c1a2d52..7b55829 100644 --- a/src/agenda/agenda.service.ts +++ b/src/agenda/agenda.service.ts @@ -3,6 +3,7 @@ import { env } from '../config/config'; import mongoose from 'mongoose'; import testJob from './jobs/testJob'; import sendPrescriptions from './jobs/sendPrecriptions'; +import deletePrescriptions from './jobs/deletePrescriptions'; import { Collection } from 'mongodb'; class AgendaService { @@ -10,7 +11,7 @@ class AgendaService { private agenda!: Agenda; private isInitialized = false; - private constructor() {} + private constructor() { } public static getInstance(): AgendaService { if (!AgendaService.instance) { @@ -63,6 +64,11 @@ class AgendaService { this.agenda.define('send-prescriptions', { concurrency: 10 }, async (job: Job) => { await sendPrescriptions(job); }); + + // Job para eliminación física de recetas eliminadas lógicamente + this.agenda.define('delete-prescriptions', { concurrency: 1 }, async (job: Job) => { + await deletePrescriptions(job); + }); } private getCollection(): Collection { @@ -145,6 +151,15 @@ class AgendaService { await this.scheduleJob('send prescription', {}, when); } + // programar eliminación de recetas + public async scheduleDeletePrescriptionJob(data: { + days?: number; + when?: string | Date; + }): Promise { + const { when, days } = data; + await this.scheduleJob('delete-prescriptions', { days }, when || '0 0 * * *'); // Default to every day at midnight if no 'when' + } + public async getAgendaInstance(): Promise { await this.initialize(); return this.agenda; diff --git a/src/agenda/jobs/deletePrescriptions.ts b/src/agenda/jobs/deletePrescriptions.ts new file mode 100644 index 0000000..b892e02 --- /dev/null +++ b/src/agenda/jobs/deletePrescriptions.ts @@ -0,0 +1,28 @@ +import { Job } from 'agenda'; +import Prescription from '../../models/prescription.model'; +import moment = require('moment'); + +async function deletePrescriptions(job: Job) { + const { days = 30 } = job.attrs.data || {}; + const limitDate = moment().subtract(days, 'days').toDate(); + + try { + const result = await Prescription.deleteMany({ + status: 'eliminada', + $or: [ + { updatedAt: { $lt: limitDate } }, + { updatedAt: { $exists: false }, createdAt: { $lt: limitDate } }, + { updatedAt: { $exists: false }, createdAt: { $exists: false }, date: { $lt: limitDate } } + ] + }); + + // eslint-disable-next-line no-console + console.log(`[Job: delete-prescriptions] Se han eliminado físicamente ${result.deletedCount} recetas marcadas como 'Eliminada' antes de ${limitDate}`); + } catch (error) { + // eslint-disable-next-line no-console + console.error('[Job: delete-prescriptions] Error al eliminar las recetas:', error); + return job.fail(`Error en el trabajo delete-prescriptions: ${error}`); + } +} + +export default deletePrescriptions;