|
| 1 | +// Recurring tasks — HTTP handlers. CRUD on definitions + a manual run-now / |
| 2 | +// run-due (the scheduled job in cron.js runs production-only, so these let the |
| 3 | +// feature be exercised in dev). Definitions and instances are company-scoped. |
| 4 | +const mongoose = require('mongoose'); |
| 5 | +const helper = require('./helper'); |
| 6 | +const { SCHEMA_TYPE } = require('../../Config/schemaType'); |
| 7 | +const { MongoDbCrudOpration } = require('../../utils/mongo-handler/mongoQueries'); |
| 8 | +const logger = require('../../Config/loggerConfig'); |
| 9 | + |
| 10 | +// Build a valid task `data` template from the request (mirrors the defaults in |
| 11 | +// taskMongo.createSubTaskWithAi so taskMongo.create accepts it). |
| 12 | +function buildTemplateFromBody(body) { |
| 13 | + const project = body.projectData || {}; |
| 14 | + return { |
| 15 | + TaskName: body.taskName, |
| 16 | + TaskKey: '-', |
| 17 | + AssigneeUserId: Array.isArray(body.assignees) ? body.assignees : [], |
| 18 | + watchers: [], |
| 19 | + DueDate: '', |
| 20 | + dueDateDeadLine: [], |
| 21 | + TaskType: body.taskType || 'task', |
| 22 | + TaskTypeKey: Number(body.taskTypeKey) || 1, |
| 23 | + ParentTaskId: '', |
| 24 | + ProjectID: project._id, |
| 25 | + CompanyId: project.CompanyId, |
| 26 | + status: { text: 'To Do', key: 1, type: 'default_active' }, |
| 27 | + isParentTask: true, |
| 28 | + Task_Leader: (body.userData && body.userData.id) || '', |
| 29 | + Task_Priority: body.priority || 'MEDIUM', |
| 30 | + deletedStatusKey: 0, |
| 31 | + statusType: 'default_active', |
| 32 | + statusKey: 1, |
| 33 | + points: (body.points === undefined || body.points === null || body.points === '') ? null : Number(body.points), |
| 34 | + rawDescription: body.rawDescription || '', |
| 35 | + descriptionBlock: body.descriptionBlock || {}, |
| 36 | + }; |
| 37 | +} |
| 38 | + |
| 39 | +exports.createDefinition = async (req, res) => { |
| 40 | + try { |
| 41 | + const companyId = req.headers['companyid']; |
| 42 | + const b = req.body || {}; |
| 43 | + if (!companyId || !b.name || !b.taskName || !b.projectData || !b.projectData._id || !b.freq) { |
| 44 | + return res.send({ status: false, statusText: 'Missing required fields (name, taskName, projectData, freq)' }); |
| 45 | + } |
| 46 | + const def = { |
| 47 | + _id: new mongoose.Types.ObjectId(), |
| 48 | + name: b.name, |
| 49 | + ProjectID: new mongoose.Types.ObjectId(b.projectData._id), |
| 50 | + sprintId: b.sprintId || (b.sprintArray && (b.sprintArray.id || b.sprintArray._id)) || '', |
| 51 | + enabled: true, |
| 52 | + freq: b.freq, |
| 53 | + interval: Math.max(1, Number(b.interval) || 1), |
| 54 | + byweekday: Array.isArray(b.byweekday) ? b.byweekday.map(Number) : [], |
| 55 | + monthday: b.monthday ? Number(b.monthday) : undefined, |
| 56 | + runHour: Number.isFinite(Number(b.runHour)) ? Number(b.runHour) : 9, |
| 57 | + skipIfOpen: !!b.skipIfOpen, |
| 58 | + until: b.until ? new Date(b.until) : undefined, |
| 59 | + runCount: 0, |
| 60 | + templateSnapshot: buildTemplateFromBody(b), |
| 61 | + projectSnapshot: { |
| 62 | + _id: b.projectData._id, |
| 63 | + CompanyId: b.projectData.CompanyId, |
| 64 | + ProjectCode: b.projectData.ProjectCode, |
| 65 | + ProjectName: b.projectData.ProjectName, |
| 66 | + }, |
| 67 | + userSnapshot: { |
| 68 | + id: b.userData && b.userData.id, |
| 69 | + Employee_Name: b.userData && b.userData.Employee_Name, |
| 70 | + companyOwnerId: b.userData && b.userData.companyOwnerId, |
| 71 | + }, |
| 72 | + sprintArray: b.sprintArray || {}, |
| 73 | + createdBy: (b.userData && b.userData.id) || '', |
| 74 | + deletedStatusKey: 0, |
| 75 | + }; |
| 76 | + def.nextRunAt = helper.computeNextRun(def, new Date()); |
| 77 | + const saved = await MongoDbCrudOpration(companyId, { type: SCHEMA_TYPE.RECURRING_TASKS, data: def }, 'save'); |
| 78 | + res.send({ status: true, statusText: 'Recurring task created', data: saved }); |
| 79 | + } catch (error) { |
| 80 | + logger.error(`[recurringTasks] create failed: ${error.message}`); |
| 81 | + res.send({ status: false, statusText: error.message }); |
| 82 | + } |
| 83 | +}; |
| 84 | + |
| 85 | +exports.listByProject = async (req, res) => { |
| 86 | + try { |
| 87 | + const companyId = req.headers['companyid']; |
| 88 | + const projectId = req.params.pid; |
| 89 | + const defs = await MongoDbCrudOpration(companyId, { |
| 90 | + type: SCHEMA_TYPE.RECURRING_TASKS, |
| 91 | + data: [{ ProjectID: new mongoose.Types.ObjectId(projectId), deletedStatusKey: 0 }], |
| 92 | + }, 'find'); |
| 93 | + res.send({ status: true, data: defs || [] }); |
| 94 | + } catch (error) { |
| 95 | + logger.error(`[recurringTasks] list failed: ${error.message}`); |
| 96 | + res.send({ status: false, statusText: error.message }); |
| 97 | + } |
| 98 | +}; |
| 99 | + |
| 100 | +exports.updateDefinition = async (req, res) => { |
| 101 | + try { |
| 102 | + const companyId = req.headers['companyid']; |
| 103 | + const id = req.params.id; |
| 104 | + const b = req.body || {}; |
| 105 | + const patch = {}; |
| 106 | + ['name', 'enabled', 'freq', 'interval', 'byweekday', 'monthday', 'runHour', 'skipIfOpen'].forEach((k) => { |
| 107 | + if (b[k] !== undefined) patch[k] = b[k]; |
| 108 | + }); |
| 109 | + if (b.until !== undefined) patch.until = b.until ? new Date(b.until) : null; |
| 110 | + |
| 111 | + // If the schedule changed, recompute nextRunAt from the merged definition. |
| 112 | + const scheduleChanged = ['freq', 'interval', 'byweekday', 'monthday', 'runHour'].some((k) => b[k] !== undefined); |
| 113 | + if (scheduleChanged) { |
| 114 | + const existing = await MongoDbCrudOpration(companyId, { |
| 115 | + type: SCHEMA_TYPE.RECURRING_TASKS, |
| 116 | + data: [{ _id: new mongoose.Types.ObjectId(id) }], |
| 117 | + }, 'findOne'); |
| 118 | + if (existing) { |
| 119 | + patch.nextRunAt = helper.computeNextRun(Object.assign({}, existing.toObject ? existing.toObject() : existing, patch), new Date()); |
| 120 | + } |
| 121 | + } |
| 122 | + await helper.updateDef(companyId, id, patch); |
| 123 | + res.send({ status: true, statusText: 'Updated' }); |
| 124 | + } catch (error) { |
| 125 | + logger.error(`[recurringTasks] update failed: ${error.message}`); |
| 126 | + res.send({ status: false, statusText: error.message }); |
| 127 | + } |
| 128 | +}; |
| 129 | + |
| 130 | +exports.deleteDefinition = async (req, res) => { |
| 131 | + try { |
| 132 | + const companyId = req.headers['companyid']; |
| 133 | + const id = req.params.id; |
| 134 | + await helper.updateDef(companyId, id, { deletedStatusKey: 1, enabled: false }); |
| 135 | + res.send({ status: true, statusText: 'Deleted' }); |
| 136 | + } catch (error) { |
| 137 | + logger.error(`[recurringTasks] delete failed: ${error.message}`); |
| 138 | + res.send({ status: false, statusText: error.message }); |
| 139 | + } |
| 140 | +}; |
| 141 | + |
| 142 | +// Instantiate one task right now from a definition (testing / manual trigger). |
| 143 | +exports.runNow = async (req, res) => { |
| 144 | + try { |
| 145 | + const companyId = req.headers['companyid']; |
| 146 | + const id = req.params.id; |
| 147 | + const def = await MongoDbCrudOpration(companyId, { |
| 148 | + type: SCHEMA_TYPE.RECURRING_TASKS, |
| 149 | + data: [{ _id: new mongoose.Types.ObjectId(id) }], |
| 150 | + }, 'findOne'); |
| 151 | + if (!def) return res.send({ status: false, statusText: 'Definition not found' }); |
| 152 | + const out = await helper.instantiateOne(companyId, def); |
| 153 | + const patch = { lastRunAt: new Date(), runCount: (Number(def.runCount) || 0) + (out.created ? 1 : 0) }; |
| 154 | + if (out.id) patch.lastInstanceTaskId = String(out.id); |
| 155 | + await helper.updateDef(companyId, id, patch); |
| 156 | + res.send({ |
| 157 | + status: !!(out.created || out.skipped), |
| 158 | + statusText: out.skipped ? 'Skipped — previous instance still open' : 'Task created', |
| 159 | + data: { id: out.id || null, skipped: !!out.skipped }, |
| 160 | + }); |
| 161 | + } catch (error) { |
| 162 | + logger.error(`[recurringTasks] runNow failed: ${error.message}`); |
| 163 | + res.send({ status: false, statusText: error.message }); |
| 164 | + } |
| 165 | +}; |
| 166 | + |
| 167 | +// Process all due definitions for the caller's company (manual trigger; the |
| 168 | +// cron does this for every company in production). |
| 169 | +exports.runDueForCompany = async (req, res) => { |
| 170 | + try { |
| 171 | + const companyId = req.headers['companyid']; |
| 172 | + const result = await helper.processDueForCompany(companyId); |
| 173 | + res.send({ status: true, statusText: 'Processed due recurring tasks', data: result }); |
| 174 | + } catch (error) { |
| 175 | + logger.error(`[recurringTasks] runDue failed: ${error.message}`); |
| 176 | + res.send({ status: false, statusText: error.message }); |
| 177 | + } |
| 178 | +}; |
| 179 | + |
| 180 | +// Cron entry (all companies) — consumed by cron.js. |
| 181 | +exports.runRecurringForAllCompanies = helper.runRecurringForAllCompanies; |
0 commit comments