|
| 1 | +const logger = require("../../../../Config/loggerConfig"); |
| 2 | +const { SCHEMA_TYPE } = require('../../../../Config/schemaType'); |
| 3 | +const { MongoDbCrudOpration } = require("../../../../utils/mongo-handler/mongoQueries"); |
| 4 | +const { default: mongoose } = require("mongoose"); |
| 5 | +const socketEmitter = require('../../../../event/socketEventEmitter'); |
| 6 | +const { HandleHistory } = require("../mongo_helper"); |
| 7 | +const { INVERSE_RELATION, RELATION_LABELS, validateTaskRef, validateRelationPair, validateRelationInput } = require('./relationRules'); |
| 8 | + |
| 9 | +// Task-to-task relations (blocks / blocked_by / duplicates / duplicated_by / |
| 10 | +// relates_to). A link is stored on BOTH task documents as an entry in the |
| 11 | +// `relations` array — `{ taskId, type, createdBy, createdAt }` — with the |
| 12 | +// inverse type on the related side, so reading either task shows the link |
| 13 | +// without a join. One link per task pair; changing its type is remove + add. |
| 14 | + |
| 15 | +module.exports = { |
| 16 | + |
| 17 | + /* -------------- ADD A RELATION BETWEEN TWO TASKS -----------------*/ |
| 18 | + // payload: { companyId, taskId, relatedTaskId, type, userData } |
| 19 | + addTaskRelation({ companyId, taskId, relatedTaskId, type, userData }) { |
| 20 | + return new Promise(async (resolve, reject) => { |
| 21 | + try { |
| 22 | + const check = validateRelationInput({ companyId, taskId, relatedTaskId, type }); |
| 23 | + if (!check.valid) { |
| 24 | + return reject(new Error(check.reason)); |
| 25 | + } |
| 26 | + |
| 27 | + const taskObjId = new mongoose.Types.ObjectId(taskId); |
| 28 | + const relatedObjId = new mongoose.Types.ObjectId(relatedTaskId); |
| 29 | + const [task, relatedTask] = await Promise.all([ |
| 30 | + this.findRelationTask(companyId, taskObjId), |
| 31 | + this.findRelationTask(companyId, relatedObjId), |
| 32 | + ]); |
| 33 | + if (!task || !relatedTask) { |
| 34 | + return reject(new Error('Task not found.')); |
| 35 | + } |
| 36 | + const alreadyLinked = (task.relations || []).some((rel) => String(rel.taskId) === String(relatedTaskId)); |
| 37 | + if (alreadyLinked) { |
| 38 | + return reject(new Error(`Tasks ${task.TaskKey} and ${relatedTask.TaskKey} are already linked.`)); |
| 39 | + } |
| 40 | + |
| 41 | + const createdAt = new Date(); |
| 42 | + const createdBy = userData && (userData.id || userData._id) ? String(userData.id || userData._id) : ''; |
| 43 | + const inverseType = INVERSE_RELATION[type]; |
| 44 | + |
| 45 | + const [updatedTask, updatedRelated] = await Promise.all([ |
| 46 | + this.pushRelationEntry(companyId, taskObjId, { taskId: relatedObjId, type, createdBy, createdAt }), |
| 47 | + this.pushRelationEntry(companyId, relatedObjId, { taskId: taskObjId, type: inverseType, createdBy, createdAt }), |
| 48 | + ]); |
| 49 | + |
| 50 | + socketEmitter.emit('update', { type: "update", data: updatedTask, updatedFields: { relations: updatedTask?.relations || [] }, module: 'task' }); |
| 51 | + socketEmitter.emit('update', { type: "update", data: updatedRelated, updatedFields: { relations: updatedRelated?.relations || [] }, module: 'task' }); |
| 52 | + |
| 53 | + this.addRelationHistory({ companyId, task, otherKey: relatedTask.TaskKey, type, userData }); |
| 54 | + this.addRelationHistory({ companyId, task: relatedTask, otherKey: task.TaskKey, type: inverseType, userData }); |
| 55 | + |
| 56 | + resolve({ |
| 57 | + status: true, |
| 58 | + statusText: `${task.TaskKey} now ${RELATION_LABELS[type]} ${relatedTask.TaskKey}.`, |
| 59 | + data: { taskId, relatedTaskId, type, relations: updatedTask?.relations || [] }, |
| 60 | + }); |
| 61 | + } catch (error) { |
| 62 | + logger.error(`ERROR in add task relation: ${error.message}`); |
| 63 | + reject(error); |
| 64 | + } |
| 65 | + }) |
| 66 | + }, |
| 67 | + |
| 68 | + /* -------------- REMOVE A RELATION BETWEEN TWO TASKS -----------------*/ |
| 69 | + // payload: { companyId, taskId, relatedTaskId, userData } |
| 70 | + removeTaskRelation({ companyId, taskId, relatedTaskId, userData }) { |
| 71 | + return new Promise(async (resolve, reject) => { |
| 72 | + try { |
| 73 | + const check = validateRelationPair({ companyId, taskId, relatedTaskId }); |
| 74 | + if (!check.valid) { |
| 75 | + return reject(new Error(check.reason)); |
| 76 | + } |
| 77 | + |
| 78 | + const taskObjId = new mongoose.Types.ObjectId(taskId); |
| 79 | + const relatedObjId = new mongoose.Types.ObjectId(relatedTaskId); |
| 80 | + const [task, relatedTask] = await Promise.all([ |
| 81 | + this.findRelationTask(companyId, taskObjId), |
| 82 | + this.findRelationTask(companyId, relatedObjId), |
| 83 | + ]); |
| 84 | + if (!task) { |
| 85 | + return reject(new Error('Task not found.')); |
| 86 | + } |
| 87 | + const existing = (task.relations || []).some((rel) => String(rel.taskId) === String(relatedTaskId)); |
| 88 | + if (!existing) { |
| 89 | + return reject(new Error('These tasks are not linked.')); |
| 90 | + } |
| 91 | + |
| 92 | + // Pull both sides. The related task may have been deleted in |
| 93 | + // the meantime — pulling from a missing document is a no-op. |
| 94 | + const [updatedTask, updatedRelated] = await Promise.all([ |
| 95 | + this.pullRelationEntry(companyId, taskObjId, relatedObjId), |
| 96 | + this.pullRelationEntry(companyId, relatedObjId, taskObjId), |
| 97 | + ]); |
| 98 | + |
| 99 | + if (updatedTask) { |
| 100 | + socketEmitter.emit('update', { type: "update", data: updatedTask, updatedFields: { relations: updatedTask.relations || [] }, module: 'task' }); |
| 101 | + } |
| 102 | + if (updatedRelated) { |
| 103 | + socketEmitter.emit('update', { type: "update", data: updatedRelated, updatedFields: { relations: updatedRelated.relations || [] }, module: 'task' }); |
| 104 | + } |
| 105 | + |
| 106 | + this.removeRelationHistory({ companyId, task, otherKey: relatedTask ? relatedTask.TaskKey : 'a deleted task', userData }); |
| 107 | + if (relatedTask) { |
| 108 | + this.removeRelationHistory({ companyId, task: relatedTask, otherKey: task.TaskKey, userData }); |
| 109 | + } |
| 110 | + |
| 111 | + resolve({ |
| 112 | + status: true, |
| 113 | + statusText: 'Task link removed successfully.', |
| 114 | + data: { taskId, relatedTaskId, relations: updatedTask?.relations || [] }, |
| 115 | + }); |
| 116 | + } catch (error) { |
| 117 | + logger.error(`ERROR in remove task relation: ${error.message}`); |
| 118 | + reject(error); |
| 119 | + } |
| 120 | + }) |
| 121 | + }, |
| 122 | + |
| 123 | + /* -------------- LIST RELATIONS OF A TASK (WITH TASK SUMMARIES) -----------------*/ |
| 124 | + // payload: { companyId, taskId } |
| 125 | + getTaskRelations({ companyId, taskId }) { |
| 126 | + return new Promise(async (resolve, reject) => { |
| 127 | + try { |
| 128 | + const check = validateTaskRef({ companyId, taskId }); |
| 129 | + if (!check.valid) { |
| 130 | + return reject(new Error(check.reason)); |
| 131 | + } |
| 132 | + |
| 133 | + const task = await this.findRelationTask(companyId, new mongoose.Types.ObjectId(taskId)); |
| 134 | + if (!task) { |
| 135 | + return reject(new Error('Task not found.')); |
| 136 | + } |
| 137 | + const relations = task.relations || []; |
| 138 | + if (!relations.length) { |
| 139 | + return resolve({ status: true, statusText: 'No linked tasks.', data: [] }); |
| 140 | + } |
| 141 | + |
| 142 | + const relatedIds = relations.map((rel) => new mongoose.Types.ObjectId(rel.taskId)); |
| 143 | + const summaryQuery = { |
| 144 | + type: SCHEMA_TYPE.TASKS, |
| 145 | + data: [ |
| 146 | + { _id: { $in: relatedIds } }, |
| 147 | + 'TaskName TaskKey status statusKey statusType ProjectID sprintId folderObjId AssigneeUserId deletedStatusKey isParentTask Task_Priority DueDate', |
| 148 | + ], |
| 149 | + }; |
| 150 | + const relatedDocs = await MongoDbCrudOpration(companyId, summaryQuery, 'find'); |
| 151 | + const docById = new Map((relatedDocs || []).map((doc) => [String(doc._id), doc])); |
| 152 | + |
| 153 | + const data = relations.map((rel) => ({ |
| 154 | + taskId: String(rel.taskId), |
| 155 | + type: rel.type, |
| 156 | + label: RELATION_LABELS[rel.type] || rel.type, |
| 157 | + createdBy: rel.createdBy || '', |
| 158 | + createdAt: rel.createdAt || null, |
| 159 | + task: docById.get(String(rel.taskId)) || null, |
| 160 | + })); |
| 161 | + |
| 162 | + resolve({ status: true, statusText: 'Linked tasks fetched successfully.', data }); |
| 163 | + } catch (error) { |
| 164 | + logger.error(`ERROR in get task relations: ${error.message}`); |
| 165 | + reject(error); |
| 166 | + } |
| 167 | + }) |
| 168 | + }, |
| 169 | + |
| 170 | + /* -------------- INTERNAL HELPERS (RELATIONS) -----------------*/ |
| 171 | + |
| 172 | + findRelationTask(companyId, taskObjId) { |
| 173 | + const query = { |
| 174 | + type: SCHEMA_TYPE.TASKS, |
| 175 | + data: [{ _id: taskObjId, deletedStatusKey: { $ne: 1 } }], |
| 176 | + }; |
| 177 | + return MongoDbCrudOpration(companyId, query, 'findOne'); |
| 178 | + }, |
| 179 | + |
| 180 | + pushRelationEntry(companyId, taskObjId, entry) { |
| 181 | + const query = { |
| 182 | + type: SCHEMA_TYPE.TASKS, |
| 183 | + data: [ |
| 184 | + { _id: taskObjId }, |
| 185 | + { $push: { relations: entry } }, |
| 186 | + { returnDocument: 'after' }, |
| 187 | + ], |
| 188 | + }; |
| 189 | + return MongoDbCrudOpration(companyId, query, 'findOneAndUpdate'); |
| 190 | + }, |
| 191 | + |
| 192 | + pullRelationEntry(companyId, taskObjId, relatedObjId) { |
| 193 | + const query = { |
| 194 | + type: SCHEMA_TYPE.TASKS, |
| 195 | + data: [ |
| 196 | + { _id: taskObjId }, |
| 197 | + { $pull: { relations: { taskId: relatedObjId } } }, |
| 198 | + { returnDocument: 'after' }, |
| 199 | + ], |
| 200 | + }; |
| 201 | + return MongoDbCrudOpration(companyId, query, 'findOneAndUpdate'); |
| 202 | + }, |
| 203 | + |
| 204 | + addRelationHistory({ companyId, task, otherKey, type, userData }) { |
| 205 | + const historyObj = { |
| 206 | + key: 'Task_Relation', |
| 207 | + message: `<b>${userData?.Employee_Name || 'Someone'}</b> has linked this task — it now <b>${RELATION_LABELS[type]}</b> <b>${otherKey}</b>.`, |
| 208 | + sprintId: task.sprintId, |
| 209 | + }; |
| 210 | + HandleHistory('task', companyId, task.ProjectID, task._id, historyObj, userData) |
| 211 | + .catch((error) => { |
| 212 | + logger.error(`ERROR in task relation history: ${error.message}`); |
| 213 | + }); |
| 214 | + }, |
| 215 | + |
| 216 | + removeRelationHistory({ companyId, task, otherKey, userData }) { |
| 217 | + const historyObj = { |
| 218 | + key: 'Task_Relation', |
| 219 | + message: `<b>${userData?.Employee_Name || 'Someone'}</b> has removed the link with <b>${otherKey}</b>.`, |
| 220 | + sprintId: task.sprintId, |
| 221 | + }; |
| 222 | + HandleHistory('task', companyId, task.ProjectID, task._id, historyObj, userData) |
| 223 | + .catch((error) => { |
| 224 | + logger.error(`ERROR in task relation history: ${error.message}`); |
| 225 | + }); |
| 226 | + }, |
| 227 | +}; |
0 commit comments