Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 36 additions & 1 deletion controllers/tasks.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ const { updateUserStatusOnTaskUpdate, updateStatusOnTaskCompletion } = require("
const dataAccess = require("../services/dataAccessLayer");
const { parseSearchQuery } = require("../utils/tasks");
const { addTaskCreatedAtAndUpdatedAtFields } = require("../services/tasks");
const tasksService = require("../services/tasks");
const { RQLQueryParser } = require("../utils/RQLParser");
const { getMissedProgressUpdatesUsers } = require("../models/discordactions");
const { logType } = require("../constants/logs");
Expand Down Expand Up @@ -134,7 +135,19 @@ const fetchPaginatedTasks = async (query) => {

const fetchTasks = async (req, res) => {
try {
const { status, page, size, prev, next, q: queryString, assignee, title, userFeatureFlag } = req.query;
const {
status,
page,
size,
prev,
next,
q: queryString,
assignee,
title,
userFeatureFlag,
orphaned,
dev,
} = req.query;
Comment on lines +139 to +150
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Are we using all these query?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yeah I only added orphaned and dev, it's prettier change.

const transformedQuery = transformQuery(status, size, page, assignee, title);

if (queryString !== undefined) {
Expand All @@ -159,6 +172,28 @@ const fetchTasks = async (req, res) => {
});
}

const isOrphaned = orphaned === "true";
const isDev = dev === "true";
if (isOrphaned) {
if (!isDev) {
return res.boom.notFound("Route not found");
}
try {
const orphanedTasks = await tasksService.fetchOrphanedTasks();
if (!orphanedTasks || orphanedTasks.length === 0) {
return res.sendStatus(204);
}
const tasksWithRdsAssigneeInfo = await fetchTasksWithRdsAssigneeInfo(orphanedTasks);
return res.status(200).json({
message: "Orphan tasks fetched successfully",
data: tasksWithRdsAssigneeInfo,
});
} catch (error) {
logger.error("Error in getting tasks which were abandoned", error);
return res.boom.badImplementation(INTERNAL_SERVER_ERROR);
}
}

const paginatedTasks = await fetchPaginatedTasks({ ...transformedQuery, prev, next, userFeatureFlag });
return res.json({
message: "Tasks returned successfully!",
Expand Down
1 change: 1 addition & 0 deletions middlewares/validators/tasks.js
Original file line number Diff line number Diff line change
Expand Up @@ -193,6 +193,7 @@ const getTasksValidator = async (req, res, next) => {
return value;
}, "Invalid query format"),
userFeatureFlag: joi.string().optional(),
orphaned: joi.string().optional(),
});

try {
Expand Down
59 changes: 58 additions & 1 deletion models/tasks.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ const userModel = firestore.collection("users");
const ItemModel = firestore.collection("itemTags");
const dependencyModel = firestore.collection("taskDependencies");
const userUtils = require("../utils/users");
const { updateTaskStatusToDone } = require("../services/tasks");
const { chunks } = require("../utils/array");
const { DOCUMENT_WRITE_SIZE } = require("../constants/constants");
const { fromFirestoreData, toFirestoreData, buildTasks } = require("../utils/tasks");
Expand All @@ -24,6 +23,42 @@ const {
const { OLD_ACTIVE, OLD_BLOCKED, OLD_PENDING, OLD_COMPLETED } = TASK_STATUS_OLD;
const { INTERNAL_SERVER_ERROR } = require("../constants/errorMessages");

/**
* Update multiple tasks' status to DONE in one batch operation.
* @param {Object[]} tasksData - Tasks data to update, must contain 'id' and 'status' fields.
* @returns {Object} - Summary of the batch operation.
* @property {number} totalUpdatedStatus - Number of tasks that has their status updated to DONE.
* @property {number} totalOperationsFailed - Number of tasks that failed to update.
* @property {string[]} updatedTaskDetails - IDs of tasks that has their status updated to DONE.
* @property {string[]} failedTaskDetails - IDs of tasks that failed to update.
*/
const updateTaskStatusToDone = async (tasksData) => {
const batch = firestore.batch();
const tasksBatch = [];
const summary = {
totalUpdatedStatus: 0,
totalOperationsFailed: 0,
updatedTaskDetails: [],
failedTaskDetails: [],
};
tasksData.forEach((task) => {
const updateTaskData = { ...task, status: "DONE" };
batch.update(tasksModel.doc(task.id), updateTaskData);
tasksBatch.push(task.id);
});
try {
await batch.commit();
summary.totalUpdatedStatus += tasksData.length;
summary.updatedTaskDetails = [...tasksBatch];
return { ...summary };
} catch (err) {
logger.error("Firebase batch Operation Failed!");
summary.totalOperationsFailed += tasksData.length;
summary.failedTaskDetails = [...tasksBatch];
return { ...summary };
}
};

/**
* Adds and Updates tasks
*
Expand Down Expand Up @@ -701,6 +736,26 @@ const markUnDoneTasksOfArchivedUsersBacklog = async (users) => {
}
};

/**
* Fetch incomplete tasks assigned to a specific user
* @param {string} userId - The unique identifier for the user.
* @returns {Promise<Array>} - A promise that resolves to an array of incomplete tasks for the given user.
* @throws {Error} - Throws an error if the database query fails.
*/
const fetchIncompleteTaskForUser = async (userId) => {
const COMPLETED_STATUSES = [DONE, COMPLETED];
try {
const incompleteTaskForUser = await tasksModel
.where("assigneeId", "==", userId)
.where("status", "not-in", COMPLETED_STATUSES)
.get();
return incompleteTaskForUser;
} catch (error) {
logger.error("Error when fetching incomplete tasks:", error);
throw error;
}
};

module.exports = {
updateTask,
fetchTasks,
Expand All @@ -720,4 +775,6 @@ module.exports = {
updateTaskStatus,
updateOrphanTasksStatus,
markUnDoneTasksOfArchivedUsersBacklog,
fetchIncompleteTaskForUser,
updateTaskStatusToDone,
};
19 changes: 19 additions & 0 deletions models/users.js
Original file line number Diff line number Diff line change
Expand Up @@ -1030,6 +1030,24 @@ const updateUsersWithNewUsernames = async () => {
}
};

/**
* Fetches users who are not in the Discord server.
* @returns {Promise<FirebaseFirestore.QuerySnapshot>} - A promise that resolves to a Firestore QuerySnapshot containing the users matching the criteria.
* @throws {Error} - Throws an error if the database query fails.
*/
const fetchUsersNotInDiscordServer = async () => {
try {
const usersNotInDiscordServer = await userModel
.where("roles.archived", "==", true)
.where("roles.in_discord", "==", false)
.get();
return usersNotInDiscordServer;
} catch (error) {
logger.error(`Error in getting users who are not in discord server: ${error}`);
throw error;
}
};

module.exports = {
addOrUpdate,
fetchPaginatedUsers,
Expand Down Expand Up @@ -1059,4 +1077,5 @@ module.exports = {
fetchUserForKeyValue,
getNonNickNameSyncedUsers,
updateUsersWithNewUsernames,
fetchUsersNotInDiscordServer,
};
55 changes: 27 additions & 28 deletions services/tasks.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,33 +2,8 @@ const firestore = require("../utils/firestore");
const tasksModel = firestore.collection("tasks");
const { chunks } = require("../utils/array");
const { DOCUMENT_WRITE_SIZE: FIRESTORE_BATCH_OPERATIONS_LIMIT } = require("../constants/constants");

const updateTaskStatusToDone = async (tasksData) => {
const batch = firestore.batch();
const tasksBatch = [];
const summary = {
totalUpdatedStatus: 0,
totalOperationsFailed: 0,
updatedTaskDetails: [],
failedTaskDetails: [],
};
tasksData.forEach((task) => {
const updateTaskData = { ...task, status: "DONE" };
batch.update(tasksModel.doc(task.id), updateTaskData);
tasksBatch.push(task.id);
});
try {
await batch.commit();
summary.totalUpdatedStatus += tasksData.length;
summary.updatedTaskDetails = [...tasksBatch];
return { ...summary };
} catch (err) {
logger.error("Firebase batch Operation Failed!");
summary.totalOperationsFailed += tasksData.length;
summary.failedTaskDetails = [...tasksBatch];
return { ...summary };
}
};
const usersQuery = require("../models/users");
const tasksQuery = require("../models/tasks");

const addTaskCreatedAtAndUpdatedAtFields = async () => {
const operationStats = {
Expand Down Expand Up @@ -83,7 +58,31 @@ const addTaskCreatedAtAndUpdatedAtFields = async () => {
return operationStats;
};

const fetchOrphanedTasks = async () => {
try {
const userSnapshot = await usersQuery.fetchUsersNotInDiscordServer();
if (userSnapshot.empty) {
return [];
}
const userIds = userSnapshot.docs.map((doc) => doc.id);

const abandonedTasks = [];

for (const userId of userIds) {
const abandonedTasksQuerySnapshot = await tasksQuery.fetchIncompleteTaskForUser(userId);

if (!abandonedTasksQuerySnapshot.empty) {
abandonedTasks.push(...abandonedTasksQuerySnapshot.docs.map((doc) => doc.data()));
}
}
return abandonedTasks;
} catch (error) {
logger.error(`Error in getting tasks abandoned by users: ${error}`);
throw error;
}
};

module.exports = {
updateTaskStatusToDone,
addTaskCreatedAtAndUpdatedAtFields,
fetchOrphanedTasks,
};
Loading