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
12 changes: 12 additions & 0 deletions controllers/tasks.js
Original file line number Diff line number Diff line change
Expand Up @@ -532,6 +532,17 @@ const getUsersHandler = async (req, res) => {
}
};

const getOrphanedTasks = async (req, res) => {
try {
const data = await tasks.fetchOrphanedTasks();

return res.status(200).json({ message: "Orphan tasks fetched successfully", data });
} catch (error) {
logger.error("Error in getting tasks which were abandoned", error);
return res.boom.badImplementation(INTERNAL_SERVER_ERROR);
}
};

module.exports = {
addNewTask,
fetchTasks,
Expand All @@ -545,4 +556,5 @@ module.exports = {
updateStatus,
getUsersHandler,
orphanTasks,
getOrphanedTasks,
};
11 changes: 11 additions & 0 deletions controllers/users.js
Original file line number Diff line number Diff line change
Expand Up @@ -1029,6 +1029,16 @@ const updateUsernames = async (req, res) => {
}
};

const getUsersWithAbandonedTasks = async (req, res) => {
try {
const data = await userQuery.fetchUsersWithAbandonedTasks();
return res.status(200).json({ message: "Users with abandoned tasks fetched successfully", data });
} catch (error) {
logger.error("Error in getting user who abandoned tasks:", error);
return res.boom.badImplementation(INTERNAL_SERVER_ERROR);
}
};

module.exports = {
verifyUser,
generateChaincode,
Expand Down Expand Up @@ -1061,4 +1071,5 @@ module.exports = {
isDeveloper,
getIdentityStats,
updateUsernames,
getUsersWithAbandonedTasks,
};
30 changes: 30 additions & 0 deletions models/tasks.js
Original file line number Diff line number Diff line change
Expand Up @@ -701,6 +701,35 @@ const markUnDoneTasksOfArchivedUsersBacklog = async (users) => {
}
};

const fetchOrphanedTasks = async () => {
try {
const COMPLETED_STATUSES = [DONE, COMPLETED];
const abandonedTasks = [];

const userSnapshot = await userModel
.where("roles.archived", "==", true)
.where("roles.in_discord", "==", false)
.get();

for (const userDoc of userSnapshot.docs) {
const user = userDoc.data();
const abandonedTasksQuerySnapshot = await tasksModel
.where("assigneeId", "==", user.id || "")
.where("status", "not-in", COMPLETED_STATUSES)
.get();

// Check if the user has any tasks with status not in [Done, Complete]
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 = {
updateTask,
fetchTasks,
Expand All @@ -720,4 +749,5 @@ module.exports = {
updateTaskStatus,
updateOrphanTasksStatus,
markUnDoneTasksOfArchivedUsersBacklog,
fetchOrphanedTasks,
};
35 changes: 34 additions & 1 deletion models/users.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,9 @@ const admin = require("firebase-admin");
const { INTERNAL_SERVER_ERROR } = require("../constants/errorMessages");
const { AUTHORITIES } = require("../constants/authorities");
const { formatUsername } = require("../utils/username");

const tasksModel = firestore.collection("tasks");
const { TASK_STATUS } = require("../constants/tasks");
const { COMPLETED, DONE } = TASK_STATUS;
/**
* Adds or updates the user data
*
Expand Down Expand Up @@ -1013,6 +1015,36 @@ const updateUsersWithNewUsernames = async () => {
}
};

const fetchUsersWithAbandonedTasks = async () => {
try {
const COMPLETED_STATUSES = [DONE, COMPLETED];
const eligibleUsersWithTasks = [];

const userSnapshot = await userModel
.where("roles.archived", "==", true)
.where("roles.in_discord", "==", false)
.get();

for (const userDoc of userSnapshot.docs) {
const user = userDoc.data();

// Check if the user has any tasks with status not in [Done, Complete]
const abandonedTasksQuerySnapshot = await tasksModel
.where("assigneeId", "==", user.id)
.where("status", "not-in", COMPLETED_STATUSES)
.get();

if (!abandonedTasksQuerySnapshot.empty) {
eligibleUsersWithTasks.push(user);
}
}
return eligibleUsersWithTasks;
} catch (error) {
logger.error(`Error in getting users who abandoned tasks: ${error}`);
throw error;
}
};

module.exports = {
addOrUpdate,
fetchPaginatedUsers,
Expand Down Expand Up @@ -1042,4 +1074,5 @@ module.exports = {
fetchUserForKeyValue,
getNonNickNameSyncedUsers,
updateUsersWithNewUsernames,
fetchUsersWithAbandonedTasks,
};
1 change: 1 addition & 0 deletions routes/tasks.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ const enableDevModeMiddleware = (req, res, next) => {
}
};

router.get("/orphaned-tasks", tasks.getOrphanedTasks);
router.get("/", getTasksValidator, cacheResponse({ invalidationKey: ALL_TASKS, expiry: 10 }), tasks.fetchTasks);
router.get("/self", authenticate, tasks.getSelfTasks);
router.get("/overdue", authenticate, authorizeRoles([SUPERUSER]), tasks.overdueTasks);
Expand Down
2 changes: 2 additions & 0 deletions routes/users.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ const ROLES = require("../constants/roles");
const { Services } = require("../constants/bot");
const authenticateProfile = require("../middlewares/authenticateProfile");

router.get("/departed-users", users.getUsersWithAbandonedTasks);
router.post("/", authorizeAndAuthenticate([ROLES.SUPERUSER], [Services.CRON_JOB_HANDLER]), users.markUnverified);
router.post("/update-in-discord", authenticate, authorizeRoles([SUPERUSER]), users.setInDiscordScript);
router.post("/verify", authenticate, users.verifyUser);
Expand Down Expand Up @@ -67,6 +68,7 @@ router.patch("/profileURL", authenticate, userValidator.updateProfileURL, users.
router.patch("/rejectDiff", authenticate, authorizeRoles([SUPERUSER]), users.rejectProfileDiff);
router.patch("/:userId", authenticate, authorizeRoles([SUPERUSER]), users.updateUser);
router.get("/suggestedUsers/:skillId", authenticate, authorizeRoles([SUPERUSER]), users.getSuggestedUsers);

module.exports = router;
router.post("/batch-username-update", authenticate, authorizeRoles([SUPERUSER]), users.updateUsernames);
module.exports = router;
84 changes: 84 additions & 0 deletions test/fixtures/tasks/tasks.js
Original file line number Diff line number Diff line change
Expand Up @@ -140,5 +140,89 @@ module.exports = () => {
createdAt: 1644753600,
updatedAt: 1644753600,
},
{
id: "task1_id",
title: "Abandoned Task 1",
type: "feature",
status: "IN_PROGRESS",
priority: "HIGH",
percentCompleted: 50,
createdAt: 1727027666,
updatedAt: 1727027999,
startedOn: 1727027777,
endsOn: 1731542400,
assignee: "archived_user1",
assigneeId: "user1_id",
github: {
issue: {
html_url: "https://github.com/org/repo/issues/1",
url: "https://api.github.com/repos/org/repo/issues/1",
},
},
dependsOn: [],
},
{
id: "task2_id",
title: "Abandoned Task 2",
type: "bug",
status: "BLOCKED",
priority: "MEDIUM",
percentCompleted: 30,
createdAt: 1727027666,
updatedAt: 1727027999,
startedOn: 1727027777,
endsOn: 1731542400,
assignee: "archived_user2",
assigneeId: "user2_id",
github: {
issue: {
html_url: "https://github.com/org/repo/issues/2",
url: "https://api.github.com/repos/org/repo/issues/2",
},
},
dependsOn: [],
},
{
id: "task3_id",
title: "Completed Archived Task",
type: "feature",
status: "DONE",
priority: "LOW",
percentCompleted: 100,
createdAt: 1727027666,
updatedAt: 1727027999,
startedOn: 1727027777,
endsOn: 1731542400,
assignee: "archived_user1",
assigneeId: "user1_id",
github: {
issue: {
html_url: "https://github.com/org/repo/issues/3",
url: "https://api.github.com/repos/org/repo/issues/3",
},
},
dependsOn: [],
},
{
id: "task4_id",
title: "Active User Task",
type: "feature",
status: "IN_PROGRESS",
priority: "HIGH",
percentCompleted: 75,
createdAt: 1727027666,
updatedAt: 1727027999,
startedOn: 1727027777,
endsOn: 1731542400,
assignee: "active_user",
assigneeId: "user3_id",
github: {
issue: {
html_url: "https://github.com/org/repo/issues/4",
url: "https://api.github.com/repos/org/repo/issues/4",
},
},
dependsOn: [],
},
];
};
63 changes: 63 additions & 0 deletions test/fixtures/user/user.js
Original file line number Diff line number Diff line change
Expand Up @@ -442,5 +442,68 @@ module.exports = () => {
url: "https://res.cloudinary.com/realdevsquad/image/upload/v1667685133/profile/mtS4DhUvNYsKqI7oCWVB/aenklfhtjldc5ytei3ar.jpg",
},
},
{
id: "user1_id",
discordId: "123456789",
github_id: "github_user1",
username: "archived_user1",
first_name: "Archived",
last_name: "User One",
linkedin_id: "archived_user1",
github_display_name: "archived-user-1",
phone: "1234567890",
email: "[email protected]",
roles: {
archived: true,
in_discord: false,
},
discordJoinedAt: "2024-01-01T00:00:00.000Z",
picture: {
publicId: "profile/user1",
url: "https://example.com/user1.jpg",
},
},
{
id: "user2_id",
discordId: "987654321",
github_id: "github_user2",
username: "archived_user2",
first_name: "Archived",
last_name: "User Two",
linkedin_id: "archived_user2",
github_display_name: "archived-user-2",
phone: "0987654321",
email: "[email protected]",
roles: {
archived: true,
in_discord: false,
},
discordJoinedAt: "2024-01-02T00:00:00.000Z",
picture: {
publicId: "profile/user2",
url: "https://example.com/user2.jpg",
},
},
{
id: "user3_id",
discordId: "555555555",
github_id: "github_user3",
username: "active_user",
first_name: "Active",
last_name: "User",
linkedin_id: "active_user",
github_display_name: "active-user",
phone: "5555555555",
email: "[email protected]",
roles: {
archived: false,
in_discord: true,
},
discordJoinedAt: "2024-01-03T00:00:00.000Z",
picture: {
publicId: "profile/user3",
url: "https://example.com/user3.jpg",
},
},
];
};
58 changes: 58 additions & 0 deletions test/integration/tasks.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -1633,4 +1633,62 @@ describe("Tasks", function () {
});
});
});

describe("fetchOrphanedTasks", function () {
beforeEach(async function () {
// Clean the database
await cleanDb();

// Add test users to the database
const userPromises = userData.map((user) => userDBModel.add(user));
await Promise.all(userPromises);

// Add test tasks to the database
const taskPromises = tasksData.map((task) => tasksModel.add(task));
await Promise.all(taskPromises);
});

afterEach(async function () {
await cleanDb();
});

it("should fetch tasks assigned to archived and non-discord users", async function () {
const abandonedTasks = await tasks.fetchOrphanedTasks();

expect(abandonedTasks).to.be.an("array");
expect(abandonedTasks).to.have.lengthOf(2); // Two tasks abandoned by users
});

it("should not include completed or done tasks", async function () {
const abandonedTasks = await tasks.fetchOrphanedTasks();

abandonedTasks.forEach((task) => {
expect(task.status).to.not.be.oneOf(["DONE", "COMPLETED"]);
});
});

it("should not include tasks from active users", async function () {
const abandonedTasks = await tasks.fetchOrphanedTasks();

abandonedTasks.forEach((task) => {
expect(task.assignee).to.not.equal("active_user");
});
});

it("should handle case when no users are archived", async function () {
await cleanDb();

// Add only active users
const activeUser = userData[11]; // Using the active user from our test data
await userDBModel.add(activeUser);

// Add a task assigned to the active user
const activeTask = tasksData[11]; // Using the active user's task
await tasksModel.add(activeTask);

const abandonedTasks = await tasks.fetchOrphanedTasks();
expect(abandonedTasks).to.be.an("array");
expect(abandonedTasks).to.have.lengthOf(0);
});
});
});
Loading