58 lines
2.0 KiB
JavaScript
58 lines
2.0 KiB
JavaScript
const cron = require('node-cron')
|
|
const BookingConfigModel = require('../models/BookingConfigModel')
|
|
const { notifyUser } = require('../utils/notifyUser')
|
|
|
|
let ioInstance = null
|
|
|
|
/** Called once from index.js right after the socket.io server is created — cron jobs have no `req`. */
|
|
function setIo (io) {
|
|
ioInstance = io
|
|
}
|
|
|
|
/** Auto-deactivate configs whose "تکرار هفته" window has ended, and notify the owner so they can renew it themselves. */
|
|
const expireWeeklyRepeatConfigs = async () => {
|
|
try {
|
|
const configs = await BookingConfigModel.find({
|
|
status: 'active',
|
|
weeklyRepeatCount: { $ne: null },
|
|
repeatStartedAt: { $ne: null }
|
|
})
|
|
|
|
const now = Date.now()
|
|
let expiredCount = 0
|
|
|
|
for (const config of configs) {
|
|
const expiresAt = new Date(config.repeatStartedAt).getTime() + config.weeklyRepeatCount * 7 * 24 * 60 * 60 * 1000
|
|
if (expiresAt > now) continue
|
|
|
|
try {
|
|
config.status = 'inactive'
|
|
await config.save()
|
|
expiredCount += 1
|
|
await notifyUser(ioInstance, config.owner, {
|
|
project_post_id: config._id,
|
|
type: 'booking',
|
|
title: 'پایان تکرار هفتگی رزرو',
|
|
description: `مهلت تکرار هفتگی (${config.weeklyRepeatCount} هفته) برای رزرو «${config.name}» به پایان رسید و غیرفعال شد. برای ادامه، آن را دوباره فعال کنید.`
|
|
})
|
|
} catch (err) {
|
|
console.error(`[BookingRepeatExpiryCron] failed to expire config ${config._id}:`, err)
|
|
}
|
|
}
|
|
|
|
if (expiredCount) {
|
|
console.log(`[BookingRepeatExpiryCron] auto-deactivated ${expiredCount} config(s) whose weekly repeat window ended`)
|
|
}
|
|
} catch (error) {
|
|
console.error('[BookingRepeatExpiryCron] check failed:', error)
|
|
}
|
|
}
|
|
|
|
// هر ساعت: بررسی پایان مهلت تکرار هفتگی رزروها
|
|
cron.schedule('0 * * * *', expireWeeklyRepeatConfigs)
|
|
|
|
module.exports = {
|
|
expireWeeklyRepeatConfigs,
|
|
setIo
|
|
}
|