diff --git a/src/controllers/bmdashboard/bmMaterialsController.js b/src/controllers/bmdashboard/bmMaterialsController.js index 911ca0b55..da45aad1d 100644 --- a/src/controllers/bmdashboard/bmMaterialsController.js +++ b/src/controllers/bmdashboard/bmMaterialsController.js @@ -1,6 +1,6 @@ const mongoose = require('mongoose'); -const bmMaterialsController = function (ItemMaterial,BuildingMaterial) { +const bmMaterialsController = function (ItemMaterial, BuildingMaterial) { const bmMaterialsList = async function _matsList(req, res) { try { BuildingMaterial.find() @@ -91,25 +91,20 @@ const bmMaterialsController = function (ItemMaterial,BuildingMaterial) { }; const bmPostMaterialUpdateRecord = function (req, res) { - let payload = req.body; + const payload = req.body; let quantityUsed = +req.body.quantityUsed; let quantityWasted = +req.body.quantityWasted; - let material = req.body.material; - if(payload.QtyUsedLogUnit=='percent' && quantityWasted>=0) - { + const { material } = req.body; + if (payload.QtyUsedLogUnit == 'percent' && quantityWasted >= 0) { quantityUsed = +((+quantityUsed / 100) * material.stockAvailable).toFixed(4); } - if(payload.QtyWastedLogUnit=='percent' && quantityUsed>=0) - { + if (payload.QtyWastedLogUnit == 'percent' && quantityUsed >= 0) { quantityWasted = +((+quantityWasted / 100) * material.stockAvailable).toFixed(4); } - if(quantityUsed>material.stockAvailable || quantityWasted>material.stockAvailable || (quantityUsed+quantityWasted)>material.stockAvailable) - { - res.status(500).send('Please check the used and wasted stock values. Either individual values or their sum exceeds the total stock available.') - } - else - { + if (quantityUsed > material.stockAvailable || quantityWasted > material.stockAvailable || (quantityUsed + quantityWasted) > material.stockAvailable) { + res.status(500).send('Please check the used and wasted stock values. Either individual values or their sum exceeds the total stock available.'); + } else { let newStockUsed = +material.stockUsed + parseFloat(quantityUsed); let newStockWasted = +material.stockWasted + parseFloat(quantityWasted); let newAvailable = +material.stockAvailable - parseFloat(quantityUsed) - parseFloat(quantityWasted); @@ -118,45 +113,42 @@ const bmMaterialsController = function (ItemMaterial,BuildingMaterial) { newAvailable = parseFloat(newAvailable.toFixed(4)); BuildingMaterial.updateOne( { _id: req.body.material._id }, - + { $set: { - 'stockUsed': newStockUsed, - 'stockWasted': newStockWasted, - 'stockAvailable': newAvailable + stockUsed: newStockUsed, + stockWasted: newStockWasted, + stockAvailable: newAvailable, }, $push: { updateRecord: { date: req.body.date, createdBy: req.body.requestor.requestorId, - quantityUsed: quantityUsed, - quantityWasted: quantityWasted + quantityUsed, + quantityWasted, }, - } - } - + }, + }, + ) - .then(results => {res.status(200).send(results)}) - .catch(error => res.status(500).send({'message':error})); + .then((results) => { res.status(200).send(results); }) + .catch(error => res.status(500).send({ message: error })); } }; const bmPostMaterialUpdateBulk = function (req, res) { - const materialUpdates= req.body.upadateMaterials; + const materialUpdates = req.body.upadateMaterials; let errorFlag = false; const updateRecordsToBeAdded = []; - for(let i=0;i=0) - { + const { material } = payload; + if (payload.QtyUsedLogUnit == 'percent' && quantityWasted >= 0) { quantityUsed = +((+quantityUsed / 100) * material.stockAvailable).toFixed(4); } - if(payload.QtyWastedLogUnit=='percent' && quantityUsed>=0) - { + if (payload.QtyWastedLogUnit == 'percent' && quantityUsed >= 0) { quantityWasted = +((+quantityWasted / 100) * material.stockAvailable).toFixed(4); } @@ -166,38 +158,36 @@ const bmMaterialsController = function (ItemMaterial,BuildingMaterial) { newStockUsed = parseFloat(newStockUsed.toFixed(4)); newStockWasted = parseFloat(newStockWasted.toFixed(4)); newAvailable = parseFloat(newAvailable.toFixed(4)); - if(newAvailable<0) - { + if (newAvailable < 0) { errorFlag = true; break; } - updateRecordsToBeAdded.push ({ + updateRecordsToBeAdded.push({ updateId: material._id, set: { - 'stockUsed': newStockUsed, - 'stockWasted': newStockWasted, - 'stockAvailable': newAvailable + stockUsed: newStockUsed, + stockWasted: newStockWasted, + stockAvailable: newAvailable, }, updateValue: { createdBy: req.body.requestor.requestorId, - quantityUsed: quantityUsed, - quantityWasted: quantityWasted, + quantityUsed, + quantityWasted, date: req.body.date, - }}); - + }, +}); } try { - if(errorFlag) - { - res.status(500).send('Stock quantities submitted seems to be invalid') + if (errorFlag) { + res.status(500).send('Stock quantities submitted seems to be invalid'); return; } const updatePromises = updateRecordsToBeAdded.map(updateItem => BuildingMaterial.updateOne( { _id: updateItem.updateId }, - { - $set : updateItem.set, - $push: { updateRecord: updateItem.updateValue } + { + $set: updateItem.set, + $push: { updateRecord: updateItem.updateValue }, }, ).exec()); Promise.all(updatePromises) @@ -213,7 +203,7 @@ const bmMaterialsController = function (ItemMaterial,BuildingMaterial) { bmMaterialsList, bmPostMaterialUpdateRecord, bmPostMaterialUpdateBulk, - bmPurchaseMaterials + bmPurchaseMaterials, }; }; diff --git a/src/controllers/dashBoardController.js b/src/controllers/dashBoardController.js index 30bddc871..19e44af85 100644 --- a/src/controllers/dashBoardController.js +++ b/src/controllers/dashBoardController.js @@ -3,6 +3,7 @@ const fs = require('fs/promises'); const mongoose = require('mongoose'); const dashboardhelper = require('../helpers/dashboardhelper')(); const emailSender = require('../utilities/emailSender'); +const AIPrompt = require('../models/weeklySummaryAIPrompt'); const dashboardcontroller = function () { const dashboarddata = function (req, res) { @@ -15,6 +16,39 @@ const dashboardcontroller = function () { }); }; + const updateAIPrompt = function (req, res) { + if (req.body.requestor.role === 'Owner') { + AIPrompt.findOneAndUpdate({ _id: 'ai-prompt' }, { ...req.body, aIPromptText: req.body.aIPromptText }) + .then(() => { + res.status(200).send('Successfully saved AI prompt.'); + }).catch(error => res.status(500).send(error)); + } + }; + + const getAIPrompt = function (req, res) { + AIPrompt.findById({ _id: 'ai-prompt' }) + .then((result) => { + if (result) { + // If the GPT prompt exists, send it back. + res.status(200).send(result); + } else { + // If the GPT prompt does not exist, create it. + const defaultPrompt = { + _id: 'ai-prompt', + aIPromptText: "Please edit the following summary of my week's work. Make sure it is professionally written in 3rd person format.\nWrite it as only one paragraph. It must be only one paragraph. Keep it less than 500 words. Start the paragraph with 'This week'.\nMake sure the paragraph contains no links or URLs and write it in a tone that is matter-of-fact and without embellishment.\nDo not add flowery language, keep it simple and factual. Do not add a final summary sentence. Apply all this to the following:", + }; + AIPrompt.create(defaultPrompt) + .then((newResult) => { + res.status(200).send(newResult); + }) + .catch((creationError) => { + res.status(500).send(creationError); + }); + } + }) + .catch(error => res.status(500).send(error)); + }; + const monthlydata = function (req, res) { const userId = mongoose.Types.ObjectId(req.params.userId); const laborthismonth = dashboardhelper.laborthismonth( @@ -211,7 +245,7 @@ const dashboardcontroller = function () { null, null, email, - null + null, ); res.status(200).send('Success'); } catch { @@ -263,6 +297,8 @@ const dashboardcontroller = function () { return { dashboarddata, + getAIPrompt, + updateAIPrompt, monthlydata, weeklydata, leaderboarddata, @@ -274,4 +310,4 @@ const dashboardcontroller = function () { }; }; -module.exports = dashboardcontroller; \ No newline at end of file +module.exports = dashboardcontroller; diff --git a/src/controllers/mapLocationsController.js b/src/controllers/mapLocationsController.js index 29af9e3d6..76fad59f9 100644 --- a/src/controllers/mapLocationsController.js +++ b/src/controllers/mapLocationsController.js @@ -4,17 +4,15 @@ const cache = require('../utilities/nodeCache')(); const mapLocationsController = function (MapLocation) { const getAllLocations = async function (req, res) { - try { const users = []; const results = await UserProfile.find({}, - '_id firstName lastName isActive location jobTitle totalTangibleHrs hoursByCategory' - ); + '_id firstName lastName isActive location jobTitle totalTangibleHrs hoursByCategory'); results.forEach((item) => { if ( - (item.location?.coords.lat && item.location?.coords.lng && item.totalTangibleHrs >= 10) || - (item.location?.coords.lat && item.location?.coords.lng && calculateTotalHours(item.hoursByCategory) >= 10) + (item.location?.coords.lat && item.location?.coords.lng && item.totalTangibleHrs >= 10) + || (item.location?.coords.lat && item.location?.coords.lng && calculateTotalHours(item.hoursByCategory) >= 10) ) { users.push(item); } @@ -25,7 +23,7 @@ const mapLocationsController = function (MapLocation) { jobTitle: item.jobTitle[0], _id: item._id, firstName: item.firstName, - lastName: item.lastName + lastName: item.lastName, })); const mUsers = await MapLocation.find({}); @@ -33,22 +31,19 @@ const mapLocationsController = function (MapLocation) { } catch (err) { res.status(404).send(err); } - }; const deleteLocation = async function (req, res) { - if (!req.body.requestor.role === 'Administrator' || !req.body.requestor.role === 'Owner') { res.status(403).send('You are not authorized to make changes in the teams.'); return; } - const locationId = req.params.locationId + const { locationId } = req.params; MapLocation.findOneAndDelete({ _id: locationId }) - .then(() => res.status(200).send({ message: "The location was successfully removed!" })) + .then(() => res.status(200).send({ message: 'The location was successfully removed!' })) .catch(error => res.status(500).send({ message: error || "Couldn't remove the location" })); }; const putUserLocation = async function (req, res) { - if (!req.body.requestor.role === 'Owner') { res.status(403).send('You are not authorized to make changes in the teams.'); return; @@ -58,17 +53,17 @@ const mapLocationsController = function (MapLocation) { lastName: req.body.lastName, jobTitle: req.body.jobTitle, location: req.body.location, - } + }; const location = new MapLocation(locationData); try { - const response = await location.save() + const response = await location.save(); if (!response) { - throw new Error('Something went wrong during saving the location...') + throw new Error('Something went wrong during saving the location...'); } res.status(200).send(response); } catch (err) { - console.log(err.message) + console.log(err.message); res.status(500).json({ message: err.message || 'Something went wrong...' }); } }; @@ -84,26 +79,26 @@ const mapLocationsController = function (MapLocation) { lastName: req.body.lastName, jobTitle: req.body.jobTitle, location: req.body.location, - } + }; if (req.body.timeZone) { - updateData.timeZone = req.body.timeZone + updateData.timeZone = req.body.timeZone; } try { let response; if (userType === 'user') { response = await UserProfile.findOneAndUpdate({ _id: userId }, { $set: { ...updateData, jobTitle: [updateData.jobTitle] } }, { new: true }); - cache.removeCache('allusers') + cache.removeCache('allusers'); cache.removeCache(`user-${userId}`); cache.setCache(`user-${userId}`, JSON.stringify(response)); } else { - response = await MapLocation.findOneAndUpdate({ _id: userId }, { $set: updateData }, { new: true }) + response = await MapLocation.findOneAndUpdate({ _id: userId }, { $set: updateData }, { new: true }); } if (!response) { - throw new Error('Something went wrong during saving the location...') + throw new Error('Something went wrong during saving the location...'); } const newData = { firstName: response.firstName, @@ -111,12 +106,12 @@ const mapLocationsController = function (MapLocation) { jobTitle: response.jobTitle, location: response.location, _id: response._id, - type: userType - } + type: userType, + }; res.status(200).send(newData); } catch (err) { - console.log(err.message) + console.log(err.message); res.status(500).json({ message: err.message || 'Something went wrong...' }); } }; @@ -128,12 +123,12 @@ const mapLocationsController = function (MapLocation) { }); return hours; } - + return { getAllLocations, deleteLocation, putUserLocation, - updateUserLocation + updateUserLocation, }; }; diff --git a/src/controllers/profileInitialSetupController.js b/src/controllers/profileInitialSetupController.js index 12776442e..84f801671 100644 --- a/src/controllers/profileInitialSetupController.js +++ b/src/controllers/profileInitialSetupController.js @@ -76,8 +76,7 @@ function informManagerMessage(user) { return message; } -const sendEmailWithAcknowledgment = (email, subject, message) => { - return new Promise((resolve, reject) => { +const sendEmailWithAcknowledgment = (email, subject, message) => new Promise((resolve, reject) => { emailSender( email, subject, @@ -85,33 +84,31 @@ const sendEmailWithAcknowledgment = (email, subject, message) => { null, null, null, - (error,result) => { - if (result) resolve(result) - if (error) reject(result) - } + (error, result) => { + if (result) resolve(result); + if (error) reject(result); + }, ); }); -}; const profileInitialSetupController = function ( ProfileInitialSetupToken, userProfile, Project, - MapLocation + MapLocation, ) { const { JWT_SECRET } = config; const setMapLocation = async (locationData) => { - const location = new MapLocation(locationData); try { - const response = await location.save() - return response + const response = await location.save(); + return response; } catch (err) { - return {type: "Error", message: err.message || 'An error occurred while saving the location'} + return { type: 'Error', message: err.message || 'An error occurred while saving the location' }; } - } + }; /* Function to handle token generation and email process: @@ -146,10 +143,10 @@ const profileInitialSetupController = function ( const acknowledgment = await sendEmailWithAcknowledgment( email, - "NEEDED: Complete your One Community profile setup", - sendLinkMessage(link) + 'NEEDED: Complete your One Community profile setup', + sendLinkMessage(link), ); - + res.status(200).send(acknowledgment); } } catch (error) { @@ -278,15 +275,15 @@ const profileInitialSetupController = function ( lastName: req.body.lastName, jobTitle: req.body.jobTitle, location: req.body.homeCountry, - } + }; res.send({ token }).status(200); - const mapEntryResult = await setMapLocation(locationData) - if(mapEntryResult.type === "Error"){ - console.log(mapEntryResult.message) + const mapEntryResult = await setMapLocation(locationData); + if (mapEntryResult.type === 'Error') { + console.log(mapEntryResult.message); } - + const NewUserCache = { permissions: savedUser.permissions, isActive: true, @@ -327,11 +324,10 @@ const profileInitialSetupController = function ( if (foundToken) { res.status(200).send({ userAPIKey: premiumKey }); } else { - res.status(403).send("Unauthorized Request"); + res.status(403).send('Unauthorized Request'); } }; - return { getSetupToken, diff --git a/src/controllers/reasonSchedulingController.js b/src/controllers/reasonSchedulingController.js index e310049c2..6f872f338 100644 --- a/src/controllers/reasonSchedulingController.js +++ b/src/controllers/reasonSchedulingController.js @@ -2,7 +2,7 @@ const moment = require('moment-timezone'); const UserModel = require('../models/userProfile'); const ReasonModel = require('../models/reason'); -const emailSender = require("../utilities/emailSender"); +const emailSender = require('../utilities/emailSender'); const postReason = async (req, res) => { @@ -39,7 +39,7 @@ const postReason = async (req, res) => { }); } - //Commented this condition to make reason scheduler available to all the users. + // Commented this condition to make reason scheduler available to all the users. // error case 1 // if (requestor.role !== 'Owner' && requestor.role !== 'Administrator') { // return res.status(403).json({ @@ -86,13 +86,11 @@ const postReason = async (req, res) => { userId, }); - - //await newReason.save(); + + // await newReason.save(); const savedData = await newReason.save(); - if(savedData) - { - - //Upon clicking the "Save" button in the Blue Square Reason Scheduler, an email will be automatically sent to the user and Jae. + if (savedData) { + // Upon clicking the "Save" button in the Blue Square Reason Scheduler, an email will be automatically sent to the user and Jae. const subject = `Blue Square Reason for ${foundUser.firstName} ${foundUser.lastName} has been set`; const emailBody = `

Hi !

@@ -104,19 +102,18 @@ const postReason = async (req, res) => {

Thank you,
One Community

`; - - + + // 1 hardcoded email- emailSender('@gmail.com', subject, emailBody, null, null); - // 2 user email - + // 2 user email - emailSender(`${foundUser.email}`, subject, emailBody, null, null); - //3 - user email and hardcoded email ( After PR approval hardcode Jae's email) + // 3 - user email and hardcoded email ( After PR approval hardcode Jae's email) // emailSender(`${foundUser.email},@gmail.com`, subject, emailBody, null, null); } - - return res.sendStatus(200); + return res.sendStatus(200); } catch (error) { console.log(error); return res.status(400).json({ @@ -259,12 +256,10 @@ const patchReason = async (req, res) => { } foundReason.reason = reasonData.message; - + const savedData = await foundReason.save(); - if(savedData) - { - - //Upon clicking the "Save" button in the Blue Square Reason Scheduler, an email will be automatically sent to the user and Jae. + if (savedData) { + // Upon clicking the "Save" button in the Blue Square Reason Scheduler, an email will be automatically sent to the user and Jae. const subject = `Blue Square Reason for ${foundUser.firstName} ${foundUser.lastName} has been updated`; const emailBody = `

Hi !

@@ -276,17 +271,15 @@ const patchReason = async (req, res) => {

Thank you,
One Community

`; - - + + // 1 hardcoded email- emailSender('@gmail.com', subject, emailBody, null, null); - // 2 user email - + // 2 user email - emailSender(`${foundUser.email}`, subject, emailBody, null, null); - //3 - user email and hardcoded email ( After PR approval hardcode Jae's email) + // 3 - user email and hardcoded email ( After PR approval hardcode Jae's email) // emailSender(`${foundUser.email},@gmail.com`, subject, emailBody, null, null); - - } return res.status(200).json({ @@ -304,7 +297,7 @@ const deleteReason = async (req, res) => { const { reasonData, requestor } = req.body; const { userId } = req.params; - //error case 1 + // error case 1 if (requestor.role !== 'Owner' && requestor.role !== 'Administrator') { return res.status(403).json({ message: diff --git a/src/controllers/taskController.js b/src/controllers/taskController.js index 126d17914..a91a2b90d 100644 --- a/src/controllers/taskController.js +++ b/src/controllers/taskController.js @@ -1,10 +1,10 @@ -const mongoose = require("mongoose"); -const WBS = require("../models/wbs"); -const UserProfile = require("../models/userProfile"); -const timeEntryHelper = require("../helpers/timeEntryHelper")(); -const taskHelper = require("../helpers/taskHelper")(); -const { hasPermission } = require("../utilities/permissions"); -const emailSender = require("../utilities/emailSender"); +const mongoose = require('mongoose'); +const WBS = require('../models/wbs'); +const UserProfile = require('../models/userProfile'); +const timeEntryHelper = require('../helpers/timeEntryHelper')(); +const taskHelper = require('../helpers/taskHelper')(); +const { hasPermission } = require('../utilities/permissions'); +const emailSender = require('../utilities/emailSender'); const taskController = function (Task) { const getTasks = (req, res) => { @@ -17,7 +17,7 @@ const taskController = function (Task) { const { mother } = req.params; - if (mother !== "0") { + if (mother !== '0') { query = { wbsId: { $in: [req.params.wbsId] }, level: { $in: [level] }, @@ -26,16 +26,16 @@ const taskController = function (Task) { } Task.find(query) - .then((results) => res.status(200).send(results)) - .catch((error) => res.status(404).send(error)); + .then(results => res.status(200).send(results)) + .catch(error => res.status(404).send(error)); }; const getWBSId = (req, res) => { const { wbsId } = req.params; WBS.findById(wbsId) - .then((results) => res.status(200).send(results)) - .catch((error) => res.status(404).send(error)); + .then(results => res.status(200).send(results)) + .catch(error => res.status(404).send(error)); }; const updateSumUp = ( @@ -45,7 +45,7 @@ const taskController = function (Task) { hoursMost, hoursLogged, estimatedHours, - resources + resources, ) => { Task.findById(taskId, (error, task) => { task.hoursBest = hoursBest; @@ -81,10 +81,10 @@ const taskController = function (Task) { }; const calculateSubTasks = (level, tasks) => { - const parentTasks = tasks.filter((task) => task.level === level); + const parentTasks = tasks.filter(task => task.level === level); parentTasks.forEach((task) => { const childTasks = tasks.filter( - (taskChild) => taskChild.level === level + 1 + taskChild => taskChild.level === level + 1, ); let sumHoursBest = 0; let sumHoursWorst = 0; @@ -96,19 +96,14 @@ const taskController = function (Task) { childTasks.forEach((childTask) => { if (childTask.mother.equals(task.taskId)) { hasChild = true; - sumHoursBest = - parseFloat(childTask.hoursBest, 10) + parseFloat(sumHoursBest, 10); - sumHoursWorst = - parseFloat(childTask.hoursWorst, 10) + - parseFloat(sumHoursWorst, 10); - sumHoursMost = - parseFloat(childTask.hoursMost, 10) + parseFloat(sumHoursMost, 10); - sumHoursLogged = - parseFloat(childTask.hoursLogged, 10) + - parseFloat(sumHoursLogged, 10); - sumEstimatedHours = - parseFloat(childTask.estimatedHours, 10) + - parseFloat(sumEstimatedHours, 10); + sumHoursBest = parseFloat(childTask.hoursBest, 10) + parseFloat(sumHoursBest, 10); + sumHoursWorst = parseFloat(childTask.hoursWorst, 10) + + parseFloat(sumHoursWorst, 10); + sumHoursMost = parseFloat(childTask.hoursMost, 10) + parseFloat(sumHoursMost, 10); + sumHoursLogged = parseFloat(childTask.hoursLogged, 10) + + parseFloat(sumHoursLogged, 10); + sumEstimatedHours = parseFloat(childTask.estimatedHours, 10) + + parseFloat(sumEstimatedHours, 10); childTask.resources.forEach((member) => { let isInResource = false; resources.forEach((mem) => { @@ -141,7 +136,7 @@ const taskController = function (Task) { sumHoursMost, sumHoursLogged, sumEstimatedHours, - resources + resources, ); } }); @@ -149,10 +144,10 @@ const taskController = function (Task) { }; const setDatesSubTasks = (level, tasks) => { - const parentTasks = tasks.filter((task) => task.level === level); + const parentTasks = tasks.filter(task => task.level === level); parentTasks.forEach((task) => { const childTasks = tasks.filter( - (taskChild) => taskChild.level === level + 1 + taskChild => taskChild.level === level + 1, ); let minStartedDate = task.startedDatetime; let maxDueDatetime = task.dueDatetime; @@ -183,10 +178,10 @@ const taskController = function (Task) { }; const calculatePriority = (level, tasks) => { - const parentTasks = tasks.filter((task) => task.level === level); + const parentTasks = tasks.filter(task => task.level === level); parentTasks.forEach((task) => { const childTasks = tasks.filter( - (taskChild) => taskChild.level === level + 1 + taskChild => taskChild.level === level + 1, ); let totalNumberPriority = 0; let totalChild = 0; @@ -195,11 +190,11 @@ const taskController = function (Task) { if (childTask.mother.equals(task.taskId)) { hasChild = true; totalChild += 1; - if (childTask.priority === "Primary") { + if (childTask.priority === 'Primary') { totalNumberPriority += 3; - } else if (childTask.priority === "Secondary") { + } else if (childTask.priority === 'Secondary') { totalNumberPriority += 2; - } else if (childTask.priority === "Tertiary") { + } else if (childTask.priority === 'Tertiary') { totalNumberPriority += 1; } } @@ -212,11 +207,11 @@ const taskController = function (Task) { if (mainTask._id.equals(task._id)) { const avg = totalNumberPriority / totalChild; if (avg <= 1.6) { - priority = "Tertiary"; + priority = 'Tertiary'; } else if (avg > 1.6 && avg < 2.5) { - priority = "Secondary"; + priority = 'Secondary'; } else { - priority = "Primary"; + priority = 'Primary'; } } }); @@ -227,10 +222,10 @@ const taskController = function (Task) { }; const setAssigned = (level, tasks) => { - const parentTasks = tasks.filter((task) => task.level === level); + const parentTasks = tasks.filter(task => task.level === level); parentTasks.forEach((task) => { const childTasks = tasks.filter( - (taskChild) => taskChild.level === level + 1 + taskChild => taskChild.level === level + 1, ); let isAssigned = false; let hasChild = false; @@ -264,7 +259,7 @@ const taskController = function (Task) { { wbsId: { $in: [wbsId] } }, ], }).then((tasks) => { - tasks = [...new Set(tasks.map((item) => item))]; + tasks = [...new Set(tasks.map(item => item))]; for (let lv = 3; lv > 0; lv -= 1) { calculateSubTasks(lv, tasks); setDatesSubTasks(lv, tasks); @@ -290,7 +285,7 @@ const taskController = function (Task) { const tasksWithId = tasks.map((task) => { const _id = new mongoose.Types.ObjectId(); const resources = task.resources.map((resource) => { - const [name, userID, profilePic] = resource.split("|"); + const [name, userID, profilePic] = resource.split('|'); return { name, userID, profilePic }; }); @@ -303,7 +298,7 @@ const taskController = function (Task) { // update tasks makes sure its parentIds and mother props are correct assigned, tasksWithId.forEach((task) => { - const taskNumArr = task.num.split("."); + const taskNumArr = task.num.split('.'); switch (task.level) { case 1: // task.num is x, no parentId1 or mother task.parentId1 = null; // no parent so its value is null @@ -313,7 +308,7 @@ const taskController = function (Task) { break; case 2: // task.num is x.x, only has one level of parent (x) task.parentId1 = tasksWithId.find( - (pTask) => pTask.num === taskNumArr[0] + pTask => pTask.num === taskNumArr[0], )._id; // task of parentId1 has num prop of x task.parentId2 = null; task.parentId3 = null; @@ -321,24 +316,23 @@ const taskController = function (Task) { break; case 3: // task.num is x.x.x, has two levels of parent (parent: x.x and grandparent: x) task.parentId1 = tasksWithId.find( - (pTask) => pTask.num === taskNumArr[0] + pTask => pTask.num === taskNumArr[0], )._id; // task of parentId1 has num prop of x task.parentId2 = tasksWithId.find( - (pTask) => pTask.num === `${taskNumArr[0]}.${taskNumArr[1]}` + pTask => pTask.num === `${taskNumArr[0]}.${taskNumArr[1]}`, )._id; // task of parentId2 has num prop of x.x task.parentId3 = null; task.mother = task.parentId2; // parent task num prop is x.x break; case 4: // task.num is x.x.x.x, has three levels of parent (x.x.x, x.x and x) task.parentId1 = tasksWithId.find( - (pTask) => pTask.num === taskNumArr[0] + pTask => pTask.num === taskNumArr[0], )._id; // x task.parentId2 = tasksWithId.find( - (pTask) => pTask.num === `${taskNumArr[0]}.${taskNumArr[1]}` + pTask => pTask.num === `${taskNumArr[0]}.${taskNumArr[1]}`, )._id; // x.x task.parentId3 = tasksWithId.find( - (pTask) => - pTask.num === `${taskNumArr[0]}.${taskNumArr[1]}.${taskNumArr[2]}` + pTask => pTask.num === `${taskNumArr[0]}.${taskNumArr[1]}.${taskNumArr[2]}`, )._id; // x.x.x task.mother = task.parentId3; // parent task num prop is x.x.x break; @@ -382,11 +376,11 @@ const taskController = function (Task) { task.estimatedHours += childTask.estimatedHours; task.startedDatetime = Math.min( task.startedDatetime, - childTask.startedDatetime + childTask.startedDatetime, ); task.dueDatetime = Math.max( task.dueDatetime, - childTask.dueDatetime + childTask.dueDatetime, ); task.childrenQty = (task.childrenQty || 0) + 1; task.isAssigned = task.isAssigned || childTask.isAssigned; @@ -394,18 +388,17 @@ const taskController = function (Task) { (resources, childTaskMember) => { if ( task.resources.every( - (member) => member.name !== childTaskMember.name + member => member.name !== childTaskMember.name, ) - ) - return [...resources, childTaskMember]; + ) return [...resources, childTaskMember]; return resources; }, - [...task.resources] + [...task.resources], ); // add priority pts for task.priority - if (childTask.priority === "Primary") { + if (childTask.priority === 'Primary') { priorityPts += 3; - } else if (childTask.priority === "Secondary") { + } else if (childTask.priority === 'Secondary') { priorityPts += 2; } else { priorityPts += 1; @@ -415,11 +408,11 @@ const taskController = function (Task) { }); const averagePts = priorityPts / task.childrenQty; if (averagePts >= 2.5) { - task.priority = "Primary"; + task.priority = 'Primary'; } else if (averagePts >= 1.6) { - task.priority = "Secondary"; + task.priority = 'Secondary'; } else { - task.priority = "Tertiary"; + task.priority = 'Tertiary'; } }); } @@ -428,10 +421,10 @@ const taskController = function (Task) { }; const importTask = async (req, res) => { - if (!(await hasPermission(req.body.requestor, "importTask"))) { + if (!(await hasPermission(req.body.requestor, 'importTask'))) { res .status(403) - .send({ error: "You are not authorized to create new Task." }); + .send({ error: 'You are not authorized to create new Task.' }); return; } @@ -457,20 +450,20 @@ const taskController = function (Task) { }); }); - res.status(201).send("done"); + res.status(201).send('done'); }; const postTask = async (req, res) => { - if (!(await hasPermission(req.body.requestor, "postTask"))) { + if (!(await hasPermission(req.body.requestor, 'postTask'))) { res .status(403) - .send({ error: "You are not authorized to create new Task." }); + .send({ error: 'You are not authorized to create new Task.' }); return; } if (!req.body.taskName || !req.body.isActive) { res.status(400).send({ - error: "Task Name, Active status, Task Number are mandatory fields", + error: 'Task Name, Active status, Task Number are mandatory fields', }); return; } @@ -494,22 +487,22 @@ const taskController = function (Task) { }); Promise.all([saveTask, saveWbs]) - .then((results) => res.status(201).send(results[0])) + .then(results => res.status(201).send(results[0])) .catch((errors) => { res.status(400).send(errors); }); }; const updateNum = async (req, res) => { - if (!(await hasPermission(req.body.requestor, "updateNum"))) { + if (!(await hasPermission(req.body.requestor, 'updateNum'))) { res .status(403) - .send({ error: "You are not authorized to create new projects." }); + .send({ error: 'You are not authorized to create new projects.' }); return; } if (!req.body.nums) { - res.status(400).send({ error: "Num is a mandatory fields" }); + res.status(400).send({ error: 'Num is a mandatory fields' }); return; } @@ -520,7 +513,7 @@ const taskController = function (Task) { task .save() .then() - .catch((errors) => res.status(400).send(errors)); + .catch(errors => res.status(400).send(errors)); }); // level 2 @@ -530,13 +523,13 @@ const taskController = function (Task) { childTasks1.forEach((childTask1) => { childTask1.num = childTask1.num.replace( childTask1.num.substring(0, elm.num.length), - elm.num + elm.num, ); childTask1 .save() .then(true) - .catch((errors) => res.status(400).send(errors)); + .catch(errors => res.status(400).send(errors)); // level 3 Task.find({ parentId: { $in: [childTask1._id] } }) @@ -545,13 +538,13 @@ const taskController = function (Task) { childTasks2.forEach((childTask2) => { childTask2.num = childTask2.num.replace( childTask2.num.substring(0, childTask1.num.length), - childTask1.num + childTask1.num, ); childTask2 .save() .then(true) - .catch((errors) => res.status(400).send(errors)); + .catch(errors => res.status(400).send(errors)); // level 4 Task.find({ parentId: { $in: [childTask2._id] } }) @@ -561,29 +554,27 @@ const taskController = function (Task) { childTask3.num = childTask3.num.replace( childTask3.num.substring( 0, - childTask2.num.length + childTask2.num.length, ), - childTask2.num + childTask2.num, ); childTask3 .save() .then(true) - .catch((errors) => - res.status(400).send(errors) - ); + .catch(errors => res.status(400).send(errors)); }); } }) - .catch((error) => res.status(404).send(error)); + .catch(error => res.status(404).send(error)); }); } }) - .catch((error) => res.status(404).send(error)); + .catch(error => res.status(404).send(error)); }); } }) - .catch((error) => res.status(404).send(error)); + .catch(error => res.status(404).send(error)); }); res.status(200).send(true); @@ -593,13 +584,13 @@ const taskController = function (Task) { if (!req.body.fromNum || !req.body.toNum) { res .status(400) - .send({ error: "wbsId, fromNum, toNum are mandatory fields" }); + .send({ error: 'wbsId, fromNum, toNum are mandatory fields' }); return; } Task.find({ wbsId: { $in: req.params.wbsId } }).then((tasks) => { - const fromNumArr = req.body.fromNum.replace(/\.0/g, "").split("."); - const toNumArr = req.body.toNum.replace(/\.0/g, "").split("."); + const fromNumArr = req.body.fromNum.replace(/\.0/g, '').split('.'); + const toNumArr = req.body.toNum.replace(/\.0/g, '').split('.'); const changedLvl = fromNumArr.length; @@ -607,8 +598,8 @@ const taskController = function (Task) { const toLastLvl = parseInt(toNumArr.pop(), 10); const leadingLvls = fromNumArr.length - ? fromNumArr.join(".").concat(".") - : ""; // in a format of x, x.x, or x.x.x, also could be '' if move level one tasks + ? fromNumArr.join('.').concat('.') + : ''; // in a format of x, x.x, or x.x.x, also could be '' if move level one tasks const changingNums = []; for ( @@ -620,39 +611,37 @@ const taskController = function (Task) { } const changingNumTasks = tasks.filter((task) => { const taskLeadingNum = task.num - .split(".") + .split('.') .slice(0, changedLvl) - .join("."); + .join('.'); return changingNums.includes(taskLeadingNum); }); const queries = []; changingNumTasks.forEach((task) => { - const taskNumArr = task.num.split("."); + const taskNumArr = task.num.split('.'); const taskChanedLvlNum = parseInt(taskNumArr[changedLvl - 1], 10); let newTaskLastLvl; if (fromLastLvl > toLastLvl) { - newTaskLastLvl = - taskChanedLvlNum === fromLastLvl ? toLastLvl : taskChanedLvlNum + 1; + newTaskLastLvl = taskChanedLvlNum === fromLastLvl ? toLastLvl : taskChanedLvlNum + 1; } else { - newTaskLastLvl = - taskChanedLvlNum === fromLastLvl ? toLastLvl : taskChanedLvlNum - 1; + newTaskLastLvl = taskChanedLvlNum === fromLastLvl ? toLastLvl : taskChanedLvlNum - 1; } taskNumArr[changedLvl - 1] = String(newTaskLastLvl); - task.num = taskNumArr.join("."); + task.num = taskNumArr.join('.'); queries.push(task.save()); }); Promise.all(queries) - .then(() => res.status(200).send("Success!")) - .catch((err) => res.status(400).send(err)); + .then(() => res.status(200).send('Success!')) + .catch(err => res.status(400).send(err)); }); }; const deleteTask = async (req, res) => { - if (!(await hasPermission(req.body.requestor, "deleteTask"))) { - res.status(403).send({ error: "You are not authorized to deleteTasks." }); + if (!(await hasPermission(req.body.requestor, 'deleteTask'))) { + res.status(403).send({ error: 'You are not authorized to deleteTasks.' }); return; } @@ -667,14 +656,12 @@ const taskController = function (Task) { { parentId3: taskId }, ], }).then((record) => { - if (!record || record === null || record.length === 0) - return res.status(400).send({ error: "No valid records found" }); - const removeTasks = record.map((rec) => rec.remove()); + if (!record || record === null || record.length === 0) return res.status(400).send({ error: 'No valid records found' }); + const removeTasks = record.map(rec => rec.remove()); return removeTasks; }); - const updateMotherChildrenQty = - mother !== "null" + const updateMotherChildrenQty = mother !== 'null' ? Task.findById(mother).then((task) => { let newQty = 0; let child = true; @@ -691,15 +678,13 @@ const taskController = function (Task) { : Promise.resolve(1); Promise.all([removeChildTasks, updateMotherChildrenQty]) - .then(() => - res.status(200).send({ message: "Task successfully deleted" }) - ) // no need to resetNum(taskId, mother); - .catch((errors) => res.status(400).send(errors)); + .then(() => res.status(200).send({ message: 'Task successfully deleted' })) // no need to resetNum(taskId, mother); + .catch(errors => res.status(400).send(errors)); }; const deleteTaskByWBS = async (req, res) => { - if (!(await hasPermission(req.body.requestor, "deleteTask"))) { - res.status(403).send({ error: "You are not authorized to deleteTasks." }); + if (!(await hasPermission(req.body.requestor, 'deleteTask'))) { + res.status(403).send({ error: 'You are not authorized to deleteTasks.' }); return; } @@ -707,7 +692,7 @@ const taskController = function (Task) { Task.find({ wbsId: { $in: [wbsId] } }, (error, record) => { if (error || !record || record === null || record.length === 0) { - res.status(400).send({ error: "No valid records found" }); + res.status(400).send({ error: 'No valid records found' }); return; } @@ -717,9 +702,7 @@ const taskController = function (Task) { }); Promise.all([...removeTasks]) - .then(() => - res.status(200).send({ message: " Tasks were successfully deleted" }) - ) + .then(() => res.status(200).send({ message: ' Tasks were successfully deleted' })) .catch((errors) => { res.status(400).send(errors); }); @@ -729,8 +712,8 @@ const taskController = function (Task) { }; const updateTask = async (req, res) => { - if (!(await hasPermission(req.body.requestor, "updateTask"))) { - res.status(403).send({ error: "You are not authorized to update Task." }); + if (!(await hasPermission(req.body.requestor, 'updateTask'))) { + res.status(403).send({ error: 'You are not authorized to update Task.' }); return; } @@ -738,46 +721,46 @@ const taskController = function (Task) { Task.findOneAndUpdate( { _id: mongoose.Types.ObjectId(taskId) }, - { ...req.body, modifiedDatetime: Date.now() } + { ...req.body, modifiedDatetime: Date.now() }, ) .then(() => res.status(201).send()) - .catch((error) => res.status(404).send(error)); + .catch(error => res.status(404).send(error)); }; const swap = async function (req, res) { - if (!(await hasPermission(req.body.requestor, "swapTask"))) { + if (!(await hasPermission(req.body.requestor, 'swapTask'))) { res .status(403) - .send({ error: "You are not authorized to create new projects." }); + .send({ error: 'You are not authorized to create new projects.' }); return; } if (!req.body.taskId1 || !req.body.taskId2) { res .status(400) - .send({ error: "taskId1 and taskId2 are mandatory fields" }); + .send({ error: 'taskId1 and taskId2 are mandatory fields' }); return; } Task.findById(req.body.taskId1, (error1, task1) => { if (error1 || task1 === null) { - res.status(400).send("No valid records found"); + res.status(400).send('No valid records found'); return; } Task.findById(req.body.taskId2, (error2, task2) => { if (error2 || task2 === null) { - res.status(400).send("No valid records found"); + res.status(400).send('No valid records found'); return; } if (task1.parentId.toString() === task2.parentId.toString()) { - let tmpNum = ""; + let tmpNum = ''; tmpNum = task1.num; task1.num = task2.num; task2.num = tmpNum; } else { - let tmpName = ""; + let tmpName = ''; tmpName = task1.taskName; task1.taskName = task2.taskName; task2.taskName = tmpName; @@ -786,18 +769,18 @@ const taskController = function (Task) { task1 .save() .then() - .catch((errors) => res.status(400).send(errors)); + .catch(errors => res.status(400).send(errors)); task2 .save() .then() - .catch((errors) => res.status(400).send(errors)); + .catch(errors => res.status(400).send(errors)); Task.find({ wbsId: { $in: [task1.wbsId] }, }) - .then((results) => res.status(200).send(results)) - .catch((error) => res.status(404).send(error)); + .then(results => res.status(200).send(results)) + .catch(error => res.status(404).send(error)); }); }); }; @@ -807,33 +790,29 @@ const taskController = function (Task) { const taskId = req.params.id; // Ensure the task ID is provided - if (!taskId || taskId === "undefined") { - return res.status(400).send({ error: "Task ID is missing" }); + if (!taskId || taskId === 'undefined') { + return res.status(400).send({ error: 'Task ID is missing' }); } const task = await Task.findById( taskId, - "-__v -createdDatetime -modifiedDatetime" + '-__v -createdDatetime -modifiedDatetime', ); if (!task) { - return res.status(400).send({ error: "This is not a valid task" }); + return res.status(400).send({ error: 'This is not a valid task' }); } - const hoursLogged = - await timeEntryHelper.getAllHoursLoggedForSpecifiedProject(taskId); - task.set("hoursLogged", hoursLogged, { strict: false }); + const hoursLogged = await timeEntryHelper.getAllHoursLoggedForSpecifiedProject(taskId); + task.set('hoursLogged', hoursLogged, { strict: false }); // Fetch the resource names for all resources - const resourceNamesPromises = task.resources.map((resource) => - taskHelper.getUserProfileFirstAndLastName(resource.userID) - ); + const resourceNamesPromises = task.resources.map(resource => taskHelper.getUserProfileFirstAndLastName(resource.userID)); const resourceNames = await Promise.all(resourceNamesPromises); // Update the task's resources with the fetched names task.resources.forEach((resource, index) => { - resource.name = - resourceNames[index] !== " " ? resourceNames[index] : resource.name; + resource.name = resourceNames[index] !== ' ' ? resourceNames[index] : resource.name; }); res.status(200).send(task); @@ -841,7 +820,7 @@ const taskController = function (Task) { // Generic error message, you can adjust as needed res .status(500) - .send({ error: "Internal Server Error", details: error.message }); + .send({ error: 'Internal Server Error', details: error.message }); } }; @@ -850,20 +829,20 @@ const taskController = function (Task) { try { Task.find({ wbsId: { $in: [wbsId] } }).then((tasks) => { - tasks = tasks.filter((task) => task.level === 1); + tasks = tasks.filter(task => task.level === 1); tasks.forEach((task) => { updateParents(task.wbsId, task.taskId.toString()); }); - res.status(200).send("done"); + res.status(200).send('done'); }); - res.status(200).send("done"); + res.status(200).send('done'); } catch (error) { res.status(400).send(error); } }; const fixTasks = function (req, res) { - res.status(200).send("done"); + res.status(200).send('done'); }; const getTasksByUserId = async (req, res) => { @@ -871,19 +850,19 @@ const taskController = function (Task) { try { Task.find( { - "resources.userID": mongoose.Types.ObjectId(userId), + 'resources.userID': mongoose.Types.ObjectId(userId), }, - "-resources.profilePic" + '-resources.profilePic', ).then((results) => { WBS.find({ - _id: { $in: results.map((item) => item.wbsId) }, + _id: { $in: results.map(item => item.wbsId) }, }).then((WBSs) => { const resultsWithProjectsIds = results.map((item) => { item.set( - "projectId", - WBSs?.find((wbs) => wbs._id.toString() === item.wbsId.toString()) + 'projectId', + WBSs?.find(wbs => wbs._id.toString() === item.wbsId.toString()) ?.projectId, - { strict: false } + { strict: false }, ); return item; }); @@ -918,10 +897,10 @@ const taskController = function (Task) { Task.findOneAndUpdate( { _id: mongoose.Types.ObjectId(taskId) }, - { ...req.body, modifiedDatetime: Date.now() } + { ...req.body, modifiedDatetime: Date.now() }, ) .then(() => res.status(201).send()) - .catch((error) => res.status(404).send(error)); + .catch(error => res.status(404).send(error)); }; const getReviewReqEmailBody = function (name, taskName) { @@ -938,10 +917,10 @@ const taskController = function (Task) { const recipients = []; const user = await UserProfile.findById(myUserId); const membership = await UserProfile.find({ - role: { $in: ["Administrator", "Manager", "Mentor"] }, + role: { $in: ['Administrator', 'Manager', 'Mentor'] }, }); membership.forEach((member) => { - if (member.teams.some((team) => user.teams.includes(team))) { + if (member.teams.some(team => user.teams.includes(team))) { recipients.push(member.email); } }); @@ -959,11 +938,11 @@ const taskController = function (Task) { `Review Request from ${name}`, emailBody, null, - null + null, ); - res.status(200).send("Success"); + res.status(200).send('Success'); } catch (err) { - res.status(500).send("Failed"); + res.status(500).send('Failed'); } }; diff --git a/src/helpers/dashboardhelper.js b/src/helpers/dashboardhelper.js index 929b5781b..9bedb0e8f 100644 --- a/src/helpers/dashboardhelper.js +++ b/src/helpers/dashboardhelper.js @@ -163,10 +163,10 @@ const dashboardhelper = function () { const getLeaderboard = async function (userId) { const userid = mongoose.Types.ObjectId(userId); - const userById = await userProfile.findOne({ _id: userid , isActive:true}, {role:1}) - .then((res)=>{ return res; }).catch((e)=>{}); + const userById = await userProfile.findOne({ _id: userid, isActive: true }, { role: 1 }) + .then(res => res).catch((e) => {}); - if(userById==null) return null; + if (userById == null) return null; const userRole = userById.role; const pdtstart = moment() .tz('America/Los_Angeles') @@ -177,42 +177,39 @@ const dashboardhelper = function () { .endOf('week') .format('YYYY-MM-DD'); - let teamMemberIds = [userid] + let teamMemberIds = [userid]; let teamMembers = []; - if(userRole!='Administrator' && userRole!='Owner' && userRole!='Core Team') //Manager , Mentor , Volunteer ... , Show only team members + if (userRole != 'Administrator' && userRole != 'Owner' && userRole != 'Core Team') // Manager , Mentor , Volunteer ... , Show only team members { - - const teamsResult = await team.find( { "members.userId": { $in: [userid] } }, {members:1} ) - .then((res)=>{ return res; }).catch((e)=>{}) - - teamsResult.map((_myTeam)=>{ - _myTeam.members.map((teamMember)=> { - if(!teamMember.userId.equals(userid)) - teamMemberIds.push( teamMember.userId ); - } ) - }) - - teamMembers = await userProfile.find({ _id: { $in: teamMemberIds } , isActive:true }, - {role:1,firstName:1,lastName:1,isVisible:1,weeklycommittedHours:1,weeklySummaries:1}) - .then((res)=>{ return res; }).catch((e)=>{}) - - } - else { - if(userRole == 'Administrator'){ //All users except Owner and Core Team + const teamsResult = await team.find({ 'members.userId': { $in: [userid] } }, { members: 1 }) + .then(res => res).catch((e) => {}); + + teamsResult.map((_myTeam) => { + _myTeam.members.map((teamMember) => { + if (!teamMember.userId.equals(userid)) teamMemberIds.push(teamMember.userId); + }); + }); + + teamMembers = await userProfile.find({ _id: { $in: teamMemberIds }, isActive: true }, + { + role: 1, firstName: 1, lastName: 1, isVisible: 1, weeklycommittedHours: 1, weeklySummaries: 1, +}) + .then(res => res).catch((e) => {}); + } else if (userRole == 'Administrator') { // All users except Owner and Core Team const excludedRoles = ['Core Team', 'Owner']; - teamMembers = await userProfile.find({ isActive:true , role: { $nin: excludedRoles } }, - {role:1,firstName:1,lastName:1,isVisible:1,weeklycommittedHours:1,weeklySummaries:1}) - .then((res)=>{ return res; }).catch((e)=>{}) + teamMembers = await userProfile.find({ isActive: true, role: { $nin: excludedRoles } }, + { + role: 1, firstName: 1, lastName: 1, isVisible: 1, weeklycommittedHours: 1, weeklySummaries: 1, +}) + .then(res => res).catch((e) => {}); + } else { // 'Core Team', 'Owner' //All users + teamMembers = await userProfile.find({ isActive: true }, + { + role: 1, firstName: 1, lastName: 1, isVisible: 1, weeklycommittedHours: 1, weeklySummaries: 1, +}) + .then(res => res).catch((e) => {}); } - else{ //'Core Team', 'Owner' //All users - teamMembers = await userProfile.find({ isActive:true}, - {role:1,firstName:1,lastName:1,isVisible:1,weeklycommittedHours:1,weeklySummaries:1}) - .then((res)=>{ return res; }).catch((e)=>{}) - } - - - } teamMemberIds = teamMembers.map(member => member._id); @@ -221,16 +218,14 @@ const dashboardhelper = function () { $gte: pdtstart, $lte: pdtend, }, - personId: { $in: teamMemberIds } + personId: { $in: teamMemberIds }, }); - let timeEntryByPerson = {} - timeEntries.map((timeEntry)=>{ - - let personIdStr = timeEntry.personId.toString(); + const timeEntryByPerson = {}; + timeEntries.map((timeEntry) => { + const personIdStr = timeEntry.personId.toString(); - if(timeEntryByPerson[personIdStr]==null) - timeEntryByPerson[personIdStr] = {tangibleSeconds:0,intangibleSeconds:0,totalSeconds:0}; + if (timeEntryByPerson[personIdStr] == null) { timeEntryByPerson[personIdStr] = { tangibleSeconds: 0, intangibleSeconds: 0, totalSeconds: 0 }; } if (timeEntry.isTangible === true) { timeEntryByPerson[personIdStr].tangibleSeconds += timeEntry.totalSeconds; @@ -239,41 +234,40 @@ const dashboardhelper = function () { } timeEntryByPerson[personIdStr].totalSeconds += timeEntry.totalSeconds; - }) - - - let leaderBoardData = []; - teamMembers.map((teamMember)=>{ - let obj = { - personId : teamMember._id, - role : teamMember.role, - name : teamMember.firstName + ' ' + teamMember.lastName, - isVisible : teamMember.isVisible, - hasSummary : teamMember.weeklySummaries?.length > 0 ? teamMember.weeklySummaries[0].summary!='' : false, - weeklycommittedHours : teamMember.weeklycommittedHours, - totaltangibletime_hrs : ((timeEntryByPerson[teamMember._id.toString()]?.tangibleSeconds / 3600) || 0), - totalintangibletime_hrs : ((timeEntryByPerson[teamMember._id.toString()]?.intangibleSeconds / 3600) || 0), - totaltime_hrs : ((timeEntryByPerson[teamMember._id.toString()]?.totalSeconds / 3600) || 0), - percentagespentintangible : - (timeEntryByPerson[teamMember._id.toString()] && timeEntryByPerson[teamMember._id.toString()]?.totalSeconds !=0 && timeEntryByPerson[teamMember._id.toString()]?.tangibleSeconds !=0) ? - (timeEntryByPerson[teamMember._id.toString()]?.tangibleSeconds / timeEntryByPerson[teamMember._id.toString()]?.totalSeconds) * 100 - : - 0 - } + }); + + + const leaderBoardData = []; + teamMembers.map((teamMember) => { + const obj = { + personId: teamMember._id, + role: teamMember.role, + name: `${teamMember.firstName } ${ teamMember.lastName}`, + isVisible: teamMember.isVisible, + hasSummary: teamMember.weeklySummaries?.length > 0 ? teamMember.weeklySummaries[0].summary != '' : false, + weeklycommittedHours: teamMember.weeklycommittedHours, + totaltangibletime_hrs: ((timeEntryByPerson[teamMember._id.toString()]?.tangibleSeconds / 3600) || 0), + totalintangibletime_hrs: ((timeEntryByPerson[teamMember._id.toString()]?.intangibleSeconds / 3600) || 0), + totaltime_hrs: ((timeEntryByPerson[teamMember._id.toString()]?.totalSeconds / 3600) || 0), + percentagespentintangible: + (timeEntryByPerson[teamMember._id.toString()] && timeEntryByPerson[teamMember._id.toString()]?.totalSeconds != 0 && timeEntryByPerson[teamMember._id.toString()]?.tangibleSeconds != 0) + ? (timeEntryByPerson[teamMember._id.toString()]?.tangibleSeconds / timeEntryByPerson[teamMember._id.toString()]?.totalSeconds) * 100 + : 0, + }; leaderBoardData.push(obj); - }) + }); - let sortedLBData = leaderBoardData.sort((a, b) => { + const sortedLBData = leaderBoardData.sort((a, b) => { // Sort by totaltangibletime_hrs in descending order if (b.totaltangibletime_hrs !== a.totaltangibletime_hrs) { return b.totaltangibletime_hrs - a.totaltangibletime_hrs; } - + // Then sort by name in ascending order if (a.name !== b.name) { return a.name.localeCompare(b.name); } - + // Finally, sort by role in ascending order return a.role.localeCompare(b.role); }); diff --git a/src/helpers/taskHelper.js b/src/helpers/taskHelper.js index 8c45df737..800d1ee6b 100644 --- a/src/helpers/taskHelper.js +++ b/src/helpers/taskHelper.js @@ -1,4 +1,5 @@ const moment = require('moment-timezone'); +const mongoose = require('mongoose'); const userProfile = require('../models/userProfile'); const timeentry = require('../models/timeentry'); const myTeam = require('../helpers/helperModels/myTeam'); @@ -6,15 +7,16 @@ const team = require('../models/team'); const Task = require('../models/task'); const TaskNotification = require('../models/taskNotification'); const Wbs = require('../models/wbs'); -const mongoose = require('mongoose'); const taskHelper = function () { const getTasksForTeams = async function (userId) { const userid = mongoose.Types.ObjectId(userId); - const userById = await userProfile.findOne({ _id: userid , isActive:true}, {role:1,firstName:1, lastName:1, role:1, isVisible:1, weeklycommittedHours:1, weeklySummaries:1}) - .then((res)=>{ return res; }).catch((e)=>{}); + const userById = await userProfile.findOne({ _id: userid, isActive: true }, { + role: 1, firstName: 1, lastName: 1, role: 1, isVisible: 1, weeklycommittedHours: 1, weeklySummaries: 1, +}) + .then(res => res).catch((e) => {}); - if(userById==null) return null; + if (userById == null) return null; const userRole = userById.role; const pdtstart = moment() @@ -26,39 +28,39 @@ const taskHelper = function () { .endOf('week') .format('YYYY-MM-DD'); - let teamMemberIds = [userid] + let teamMemberIds = [userid]; let teamMembers = []; - if(userRole!='Administrator' && userRole!='Owner' && userRole!='Core Team') //Manager , Mentor , Volunteer ... , Show only team members + if (userRole != 'Administrator' && userRole != 'Owner' && userRole != 'Core Team') // Manager , Mentor , Volunteer ... , Show only team members { - - const teamsResult = await team.find( { "members.userId": { $in: [userid] } }, {members:1} ) - .then((res)=>{ return res; }).catch((e)=>{}) + const teamsResult = await team.find({ 'members.userId': { $in: [userid] } }, { members: 1 }) + .then(res => res).catch((e) => {}); - teamsResult.map((_myTeam)=>{ - _myTeam.members.map((teamMember)=> { - if(!teamMember.userId.equals(userid)) - teamMemberIds.push( teamMember.userId ); - } ) - }) + teamsResult.map((_myTeam) => { + _myTeam.members.map((teamMember) => { + if (!teamMember.userId.equals(userid)) teamMemberIds.push(teamMember.userId); + }); + }); - teamMembers = await userProfile.find({ _id: { $in: teamMemberIds } , isActive:true }, - {role:1,firstName:1,lastName:1,weeklycommittedHours:1}) - .then((res)=>{ return res; }).catch((e)=>{}) - } - else { - if(userRole == 'Administrator'){ //All users except Owner and Core Team + teamMembers = await userProfile.find({ _id: { $in: teamMemberIds }, isActive: true }, + { + role: 1, firstName: 1, lastName: 1, weeklycommittedHours: 1, +}) + .then(res => res).catch((e) => {}); + } else if (userRole == 'Administrator') { // All users except Owner and Core Team const excludedRoles = ['Core Team', 'Owner']; - teamMembers = await userProfile.find({ isActive:true , role: { $nin: excludedRoles } }, - {role:1,firstName:1,lastName:1,weeklycommittedHours:1}) - .then((res)=>{ return res; }).catch((e)=>{}) + teamMembers = await userProfile.find({ isActive: true, role: { $nin: excludedRoles } }, + { + role: 1, firstName: 1, lastName: 1, weeklycommittedHours: 1, +}) + .then(res => res).catch((e) => {}); + } else { // 'Core Team', 'Owner' //All users + teamMembers = await userProfile.find({ isActive: true }, + { + role: 1, firstName: 1, lastName: 1, weeklycommittedHours: 1, +}) + .then(res => res).catch((e) => {}); } - else{ //'Core Team', 'Owner' //All users - teamMembers = await userProfile.find({ isActive:true}, - {role:1,firstName:1,lastName:1,weeklycommittedHours:1}) - .then((res)=>{ return res; }).catch((e)=>{}) - } - } teamMemberIds = teamMembers.map(member => member._id); @@ -67,88 +69,80 @@ const taskHelper = function () { $gte: pdtstart, $lte: pdtend, }, - personId: { $in: teamMemberIds } + personId: { $in: teamMemberIds }, }); - - let timeEntryByPerson = {} - timeEntries.map((timeEntry)=>{ - - let personIdStr = timeEntry.personId.toString(); - - if(timeEntryByPerson[personIdStr]==null) - timeEntryByPerson[personIdStr] = {tangibleSeconds:0,intangibleSeconds:0,totalSeconds:0}; - + + const timeEntryByPerson = {}; + timeEntries.map((timeEntry) => { + const personIdStr = timeEntry.personId.toString(); + + if (timeEntryByPerson[personIdStr] == null) { timeEntryByPerson[personIdStr] = { tangibleSeconds: 0, intangibleSeconds: 0, totalSeconds: 0 }; } + if (timeEntry.isTangible === true) { timeEntryByPerson[personIdStr].tangibleSeconds += timeEntry.totalSeconds; - } + } timeEntryByPerson[personIdStr].totalSeconds += timeEntry.totalSeconds; - }) + }); - const teamMemberTasks = await Task.find({"resources.userID" : {$in : teamMemberIds }}, { 'resources.profilePic': 0 }) - .populate( { + const teamMemberTasks = await Task.find({ 'resources.userID': { $in: teamMemberIds } }, { 'resources.profilePic': 0 }) + .populate({ path: 'wbsId', select: 'projectId', - }) + }); const teamMemberTaskIds = teamMemberTasks.map(task => task._id); - const teamMemberTaskNotifications = await TaskNotification.find({"taskId" : {$in : teamMemberTaskIds }}) - - const taskNotificationByTaskNdUser = [] - teamMemberTaskNotifications.map(teamMemberTaskNotification => { + const teamMemberTaskNotifications = await TaskNotification.find({ taskId: { $in: teamMemberTaskIds } }); - let taskIdStr = teamMemberTaskNotification.taskId.toString(); - let userIdStr = teamMemberTaskNotification.userId.toString(); - let taskNdUserID = taskIdStr+","+userIdStr; + const taskNotificationByTaskNdUser = []; + teamMemberTaskNotifications.map((teamMemberTaskNotification) => { + const taskIdStr = teamMemberTaskNotification.taskId.toString(); + const userIdStr = teamMemberTaskNotification.userId.toString(); + const taskNdUserID = `${taskIdStr},${userIdStr}`; - if(taskNotificationByTaskNdUser[taskNdUserID]) { - taskNotificationByTaskNdUser[taskNdUserID].push(teamMemberTaskNotification) - } - else{ - taskNotificationByTaskNdUser[taskNdUserID] = [teamMemberTaskNotification] + if (taskNotificationByTaskNdUser[taskNdUserID]) { + taskNotificationByTaskNdUser[taskNdUserID].push(teamMemberTaskNotification); + } else { + taskNotificationByTaskNdUser[taskNdUserID] = [teamMemberTaskNotification]; } + }); - }) - - const taskByPerson = [] - - teamMemberTasks.map(teamMemberTask => { + const taskByPerson = []; - let projId = teamMemberTask.wbsId?.projectId; - let _teamMemberTask = {...teamMemberTask._doc} + teamMemberTasks.map((teamMemberTask) => { + const projId = teamMemberTask.wbsId?.projectId; + const _teamMemberTask = { ...teamMemberTask._doc }; _teamMemberTask.projectId = projId; - let taskIdStr = _teamMemberTask._id.toString(); + const taskIdStr = _teamMemberTask._id.toString(); - teamMemberTask.resources.map(resource => { - - let resourceIdStr = resource.userID.toString(); - let taskNdUserID = taskIdStr+","+resourceIdStr; - _teamMemberTask.taskNotifications = taskNotificationByTaskNdUser[taskNdUserID] || [] - if(taskByPerson[resourceIdStr]) { - taskByPerson[resourceIdStr].push(_teamMemberTask) - } - else{ - taskByPerson[resourceIdStr] = [_teamMemberTask] + teamMemberTask.resources.map((resource) => { + const resourceIdStr = resource.userID.toString(); + const taskNdUserID = `${taskIdStr},${resourceIdStr}`; + _teamMemberTask.taskNotifications = taskNotificationByTaskNdUser[taskNdUserID] || []; + if (taskByPerson[resourceIdStr]) { + taskByPerson[resourceIdStr].push(_teamMemberTask); + } else { + taskByPerson[resourceIdStr] = [_teamMemberTask]; } - }) - }) + }); + }); - - let teamMemberTasksData = []; - teamMembers.map((teamMember)=>{ - let obj = { - personId : teamMember._id, - role : teamMember.role, - name : teamMember.firstName + ' ' + teamMember.lastName, - weeklycommittedHours : teamMember.weeklycommittedHours, - totaltangibletime_hrs : ((timeEntryByPerson[teamMember._id.toString()]?.tangibleSeconds / 3600) || 0), - totaltime_hrs : ((timeEntryByPerson[teamMember._id.toString()]?.totalSeconds / 3600) || 0), - tasks : taskByPerson[teamMember._id.toString()] || [] - } + + const teamMemberTasksData = []; + teamMembers.map((teamMember) => { + const obj = { + personId: teamMember._id, + role: teamMember.role, + name: `${teamMember.firstName } ${ teamMember.lastName}`, + weeklycommittedHours: teamMember.weeklycommittedHours, + totaltangibletime_hrs: ((timeEntryByPerson[teamMember._id.toString()]?.tangibleSeconds / 3600) || 0), + totaltime_hrs: ((timeEntryByPerson[teamMember._id.toString()]?.totalSeconds / 3600) || 0), + tasks: taskByPerson[teamMember._id.toString()] || [], + }; teamMemberTasksData.push(obj); - }) + }); return teamMemberTasksData; - + // return myteam.aggregate([ // { diff --git a/src/models/mapLocation.js b/src/models/mapLocation.js index 851587dc3..cb5644d31 100644 --- a/src/models/mapLocation.js +++ b/src/models/mapLocation.js @@ -5,7 +5,7 @@ const { Schema } = mongoose; const mapLocation = new Schema({ title: { type: String, - default: 'Prior to HGN Data Collection' + default: 'Prior to HGN Data Collection', }, firstName: String, lastName: String, @@ -27,7 +27,7 @@ const mapLocation = new Schema({ lng: { type: String, required: true, - } + }, }, country: { type: String, diff --git a/src/models/weeklySummaryAIPrompt.js b/src/models/weeklySummaryAIPrompt.js new file mode 100644 index 000000000..a55db4a97 --- /dev/null +++ b/src/models/weeklySummaryAIPrompt.js @@ -0,0 +1,10 @@ +const mongoose = require('mongoose'); + +const { Schema } = mongoose; + +const WeeklySummaryAIPrompt = new Schema({ + _id: { type: mongoose.Schema.Types.String }, + aIPromptText: { type: String }, +}); + +module.exports = mongoose.model('weeklySummaryAIPrompt', WeeklySummaryAIPrompt, 'weeklySummaryAIPrompt'); diff --git a/src/routes/bmdashboard/bmMaterialsRouter.js b/src/routes/bmdashboard/bmMaterialsRouter.js index 51c5f437f..9a520d7d6 100644 --- a/src/routes/bmdashboard/bmMaterialsRouter.js +++ b/src/routes/bmdashboard/bmMaterialsRouter.js @@ -9,11 +9,11 @@ const routes = function (itemMaterial, buildingMaterial) { materialsRouter.route('/updateMaterialRecord') .post(controller.bmPostMaterialUpdateRecord); - + materialsRouter.route('/updateMaterialRecordBulk') .post(controller.bmPostMaterialUpdateBulk); - - + + return materialsRouter; }; diff --git a/src/routes/dashboardRouter.js b/src/routes/dashboardRouter.js index 664c1c802..fc54a43a1 100644 --- a/src/routes/dashboardRouter.js +++ b/src/routes/dashboardRouter.js @@ -5,6 +5,10 @@ const route = function () { const Dashboardrouter = express.Router(); + Dashboardrouter.route('/dashboard/aiPrompt') + .get(controller.getAIPrompt) + .put(controller.updateAIPrompt); + Dashboardrouter.route('/dashboard/:userId') .get(controller.dashboarddata); diff --git a/src/routes/mapLocationsRouter.js b/src/routes/mapLocationsRouter.js index db004ff18..84cb85feb 100644 --- a/src/routes/mapLocationsRouter.js +++ b/src/routes/mapLocationsRouter.js @@ -11,7 +11,7 @@ const router = function (mapLocations) { .patch(controller.updateUserLocation); mapRouter.route('/mapLocations/:locationId') - .delete(controller.deleteLocation) + .delete(controller.deleteLocation); return mapRouter; }; diff --git a/src/routes/profileInitialSetupRouter.js b/src/routes/profileInitialSetupRouter.js index 12f677224..544c5c878 100644 --- a/src/routes/profileInitialSetupRouter.js +++ b/src/routes/profileInitialSetupRouter.js @@ -1,8 +1,8 @@ const express = require('express'); -const routes = function (ProfileInitialSetupToken, userProfile, Project , mapLocations) { +const routes = function (ProfileInitialSetupToken, userProfile, Project, mapLocations) { const ProfileInitialSetup = express.Router(); - const controller = require('../controllers/profileInitialSetupController')(ProfileInitialSetupToken, userProfile, Project , mapLocations); + const controller = require('../controllers/profileInitialSetupController')(ProfileInitialSetupToken, userProfile, Project, mapLocations); ProfileInitialSetup.route('/getInitialSetuptoken') .post(controller.getSetupToken); ProfileInitialSetup.route('/ProfileInitialSetup').post(controller.setUpNewUser); diff --git a/src/startup/routes.js b/src/startup/routes.js index 620e8c9f8..e10a8d686 100644 --- a/src/startup/routes.js +++ b/src/startup/routes.js @@ -16,6 +16,8 @@ const inventoryItemType = require('../models/inventoryItemType'); const role = require('../models/role'); const rolePreset = require('../models/rolePreset'); const ownerMessage = require('../models/ownerMessage'); + +const weeklySummaryAIPrompt = require('../models/weeklySummaryAIPrompt'); const profileInitialSetuptoken = require('../models/profileInitialSetupToken'); const reason = require('../models/reason'); const mouseoverText = require('../models/mouseoverText'); @@ -27,7 +29,7 @@ const buildingMaterial = require('../models/bmdashboard/buildingMaterial'); const userProfileRouter = require('../routes/userProfileRouter')(userProfile); const badgeRouter = require('../routes/badgeRouter')(badge); -const dashboardRouter = require('../routes/dashboardRouter')(); +const dashboardRouter = require('../routes/dashboardRouter')(weeklySummaryAIPrompt); const timeEntryRouter = require('../routes/timeentryRouter')(timeEntry); const projectRouter = require('../routes/projectRouter')(project); const informationRouter = require('../routes/informationRouter')(information); @@ -45,7 +47,7 @@ const popupBackupRouter = require('../routes/popupEditorBackupRouter')(popupBack const taskNotificationRouter = require('../routes/taskNotificationRouter')(taskNotification); const inventoryRouter = require('../routes/inventoryRouter')(inventoryItem, inventoryItemType); const timeZoneAPIRouter = require('../routes/timeZoneAPIRoutes')(); -const profileInitialSetupRouter = require('../routes/profileInitialSetupRouter')(profileInitialSetuptoken, userProfile, project , mapLocations); +const profileInitialSetupRouter = require('../routes/profileInitialSetupRouter')(profileInitialSetuptoken, userProfile, project, mapLocations); const isEmailExistsRouter = require('../routes/isEmailExistsRouter')(); diff --git a/src/utilities/emailSender.js b/src/utilities/emailSender.js index b07f9a8c9..7199202e9 100644 --- a/src/utilities/emailSender.js +++ b/src/utilities/emailSender.js @@ -35,7 +35,7 @@ const closure = () => { if (!nextItem) return; const { - recipient, subject, message, cc, bcc, replyTo, acknowledgingReceipt + recipient, subject, message, cc, bcc, replyTo, acknowledgingReceipt, } = nextItem; try { @@ -60,13 +60,13 @@ const closure = () => { const result = await transporter.sendMail(mailOptions); if (typeof acknowledgingReceipt === 'function') { - acknowledgingReceipt(null,result); - } + acknowledgingReceipt(null, result); + } logger.logInfo(result); } catch (error) { if (typeof acknowledgingReceipt === 'function') { - acknowledgingReceipt(error,null); - } + acknowledgingReceipt(error, null); + } logger.logException(error); } }, process.env.MAIL_QUEUE_INTERVAL || 1000); @@ -88,7 +88,7 @@ const closure = () => { cc, bcc, replyTo, - acknowledgingReceipt + acknowledgingReceipt, }); } };