Skip to content

Commit

Permalink
Merge pull request #669 from OneCommunityGlobal/development
Browse files Browse the repository at this point in the history
Backend Release to Main [1.28]
  • Loading branch information
one-community authored Dec 24, 2023
2 parents 8e575c6 + 0818af5 commit 5659686
Show file tree
Hide file tree
Showing 9 changed files with 209 additions and 100 deletions.
127 changes: 69 additions & 58 deletions package-lock.json

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@
"cron": "^1.8.2",
"dotenv": "^5.0.1",
"express": "^4.17.1",
"express-validator": "^7.0.1",
"googleapis": "^100.0.0",
"jsonwebtoken": "^9.0.0",
"lodash": "^4.17.21",
Expand Down
30 changes: 29 additions & 1 deletion src/controllers/profileInitialSetupController.js
Original file line number Diff line number Diff line change
Expand Up @@ -97,9 +97,22 @@ const profileInitialSetupController = function (
ProfileInitialSetupToken,
userProfile,
Project,
MapLocation
) {
const { JWT_SECRET } = config;

const setMapLocation = async (locationData) => {

const location = new MapLocation(locationData);

try {
const response = await location.save()
return response
} catch (err) {
return {type: "Error", message: err.message || 'An error occurred while saving the location'}
}
}

/*
Function to handle token generation and email process:
- Generates a new token and saves it to the database.
Expand Down Expand Up @@ -226,6 +239,7 @@ const profileInitialSetupController = function (
newUser.collaborationPreference = req.body.collaborationPreference;
newUser.timeZone = req.body.timeZone || 'America/Los_Angeles';
newUser.location = req.body.location;
newUser.profilePic = req.body.profilePicture;
newUser.permissions = {
frontPermissions: [],
backPermissions: [],
Expand Down Expand Up @@ -259,8 +273,20 @@ const profileInitialSetupController = function (

const token = jwt.sign(jwtPayload, JWT_SECRET);

const locationData = {
firstName: req.body.firstName,
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 NewUserCache = {
permissions: savedUser.permissions,
isActive: true,
Expand Down Expand Up @@ -301,10 +327,12 @@ 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,
setUpNewUser,
Expand Down
29 changes: 19 additions & 10 deletions src/controllers/timeEntryController.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,13 @@ const formatSeconds = function (seconds) {
return values.split(':');
};

const isGeneralTimeEntry = function (type) {
if (type === undefined || type === 'default') {
return true;
}
return false;
};

/**
*
* @param {*} firstName First name of the owner of the time entry that was modified
Expand Down Expand Up @@ -135,6 +142,7 @@ const timeEntrycontroller = function (TimeEntry) {
session.startTransaction();

const type = req.body.entryType;
const isGeneralEntry = isGeneralTimeEntry(type);

try {
if (!req.params.timeEntryId) {
Expand All @@ -147,7 +155,7 @@ const timeEntrycontroller = function (TimeEntry) {

if (
!mongoose.Types.ObjectId.isValid(req.params.timeEntryId)
|| ((type === 'default' || type === 'project')
|| ((isGeneralEntry || type === 'project')
&& !mongoose.Types.ObjectId.isValid(req.body.projectId)
)) {
return res
Expand All @@ -169,7 +177,7 @@ const timeEntrycontroller = function (TimeEntry) {
if (
!(
(await hasPermission(req.body.requestor, 'editTimeEntry'))
|| (type === 'default'
|| (isGeneralEntry
&& timeEntry.personId.toString()
=== req.body.requestor.requestorId.toString()
)
Expand All @@ -183,7 +191,7 @@ const timeEntrycontroller = function (TimeEntry) {
const totalSeconds = moment.duration(`${hours}:${minutes}`).asSeconds();

if (
type === 'default'
isGeneralEntry
&& timeEntry.isTangible === true
&& totalSeconds !== timeEntry.totalSeconds
) {
Expand All @@ -207,13 +215,13 @@ const timeEntrycontroller = function (TimeEntry) {
timeEntry.lastModifiedDateTime = moment().utc().toISOString();
timeEntry.projectId = mongoose.Types.ObjectId(req.body.projectId);
timeEntry.dateOfWork = moment(req.body.dateOfWork).format('YYYY-MM-DD');
timeEntry.entryType = req.body.entryType;
timeEntry.entryType = req.body.entryType === undefined ? 'default' : req.body.entryType;

// Update the hoursLogged field of related tasks based on before and after timeEntries
// initialIsTangible is a bealoon value, req.body.isTangible is a string
// initialProjectId may be a task id or project id, so do not throw error.
try {
if (type === 'default' && findTask) {
if (isGeneralEntry && findTask) {
if (initialIsTangible === true) {
findTask.hoursLogged -= initialSeconds / 3600;
}
Expand All @@ -230,7 +238,7 @@ const timeEntrycontroller = function (TimeEntry) {

// Update edit history
if (
(type === 'default' || type === 'person')
(isGeneralEntry || type === 'person')
&& initialSeconds !== totalSeconds
&& timeEntry.isTangible
&& req.body.requestor.requestorId === timeEntry.personId.toString()
Expand All @@ -245,7 +253,7 @@ const timeEntrycontroller = function (TimeEntry) {
newSeconds: totalSeconds,
});

if (type === 'default') {
if (isGeneralEntry) {
// Issue infraction if edit history contains more than 5 edits in the last year
let totalRecentEdits = 0;

Expand Down Expand Up @@ -303,7 +311,7 @@ const timeEntrycontroller = function (TimeEntry) {
res.status(200).send({ message: 'Successfully updated time entry' });

// If the time entry isn't related to a task (i.e. it's a project), then don't check for overtime (Most likely pr team)
if (type === 'default' && findTask) {
if (isGeneralEntry && findTask) {
// checking if logged in hours exceed estimated time after timeentry edit for a task
const record = await userProfile.findById(
timeEntry.personId.toString(),
Expand All @@ -328,7 +336,8 @@ const timeEntrycontroller = function (TimeEntry) {
}
const items = [];
records.forEach((element) => {
if (element.entryType === 'default' || element.entryType === undefined) {
const isGeneralEntry = isGeneralTimeEntry(element.entryType);
if (isGeneralEntry) {
const timeentry = new TimeEntry();
timeentry.personId = element.personId;
timeentry.projectId = element.projectId;
Expand Down Expand Up @@ -400,7 +409,7 @@ const timeEntrycontroller = function (TimeEntry) {
timeentry.isTangible = req.body.isTangible;
timeentry.createdDateTime = moment().utc().toISOString();
timeentry.lastModifiedDateTime = moment().utc().toISOString();
timeentry.entryType = req.body.entryType;
timeentry.entryType = req.body.entryType === undefined ? 'default' : req.body.entryType;

timeentry
.save()
Expand Down
29 changes: 23 additions & 6 deletions src/helpers/dashboardhelper.js
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,11 @@ const dashboardhelper = function () {
$lte: ['$$timeentry.dateOfWork', pdtend],
},
{
$in: ['$$timeentry.entryType', ['default', null]],
$not: [
{
$in: ['$$timeentry.entryType', ['person', 'team', 'project']],
},
],
},
],
},
Expand Down Expand Up @@ -155,7 +159,7 @@ const dashboardhelper = function () {
return output;
};

const getLeaderboard = function (userId) {
const getLeaderboard = async function (userId) {
const userid = mongoose.Types.ObjectId(userId);
const pdtstart = moment()
.tz('America/Los_Angeles')
Expand All @@ -165,7 +169,7 @@ const dashboardhelper = function () {
.tz('America/Los_Angeles')
.endOf('week')
.format('YYYY-MM-DD');
return myTeam.aggregate([
const output = await myTeam.aggregate([
{
$match: {
_id: userid,
Expand Down Expand Up @@ -287,7 +291,11 @@ const dashboardhelper = function () {
$lte: ['$$timeentry.dateOfWork', pdtend],
},
{
$in: ['$$timeentry.entryType', ['default', null]],
$not: [
{
$in: ['$$timeentry.entryType', ['person', 'team', 'project']],
},
],
},
],
},
Expand Down Expand Up @@ -416,6 +424,7 @@ const dashboardhelper = function () {
},
},
]);
return output;
};

/**
Expand Down Expand Up @@ -583,7 +592,11 @@ const dashboardhelper = function () {
$lte: ['$$timeentry.dateOfWork', todate],
},
{
$in: ['$$timeentry.entryType', ['default', null]],
$not: [
{
$in: ['$$timeentry.entryType', ['person', 'team', 'project']],
},
],
},
],
},
Expand Down Expand Up @@ -663,7 +676,11 @@ const dashboardhelper = function () {
$lte: ['$$timeentry.dateOfWork', todate],
},
{
$in: ['$$timeentry.entryType', ['default', null]],
$not: [
{
$in: ['$$timeentry.entryType', ['person', 'team', 'project']],
},
],
},
],
},
Expand Down
4 changes: 2 additions & 2 deletions src/routes/profileInitialSetupRouter.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
const express = require('express');

const routes = function (ProfileInitialSetupToken, userProfile, Project) {
const routes = function (ProfileInitialSetupToken, userProfile, Project , mapLocations) {
const ProfileInitialSetup = express.Router();
const controller = require('../controllers/profileInitialSetupController')(ProfileInitialSetupToken, userProfile, Project);
const controller = require('../controllers/profileInitialSetupController')(ProfileInitialSetupToken, userProfile, Project , mapLocations);
ProfileInitialSetup.route('/getInitialSetuptoken')
.post(controller.getSetupToken);
ProfileInitialSetup.route('/ProfileInitialSetup').post(controller.setUpNewUser);
Expand Down
77 changes: 59 additions & 18 deletions src/routes/userProfileRouter.js
Original file line number Diff line number Diff line change
@@ -1,53 +1,94 @@
import { body } from 'express-validator';

const express = require('express');


const routes = function (userProfile) {
const controller = require('../controllers/userProfileController')(userProfile);
const controller = require('../controllers/userProfileController')(
userProfile,
);

const userProfileRouter = express.Router();

userProfileRouter.route('/userProfile')
userProfileRouter
.route('/userProfile')
.get(controller.getUserProfiles)
.post(controller.postUserProfile);

userProfileRouter.route('/userProfile/:userId')
.post(
body('firstName').customSanitizer(value => value.trim()),
body('lastName').customSanitizer(value => value.trim()),
controller.postUserProfile,
);

userProfileRouter
.route('/userProfile/:userId')
.get(controller.getUserById)
.put(controller.putUserProfile)
.put(
body('firstName').customSanitizer(value => value.trim()),
body('lastName').customSanitizer(value => value.trim()),
body('personalLinks').customSanitizer(value => value.map((link) => {
if (link.Name.replace(/\s/g, '') || link.Link.replace(/\s/g, '')) {
return {
...link,
Name: link.Name.trim(),
Link: link.Link.replace(/\s/g, ''),
};
}
throw new Error('Url not valid');
})),
body('adminLinks').customSanitizer(value => value.map((link) => {
if (link.Name.replace(/\s/g, '') || link.Link.replace(/\s/g, '')) {
return {
...link,
Name: link.Name.trim(),
Link: link.Link.replace(/\s/g, ''),
};
}
throw new Error('Url not valid');
})),
controller.putUserProfile,
)
.delete(controller.deleteUserProfile)
.patch(controller.changeUserStatus);

userProfileRouter.route('/userProfile/name/:name')
userProfileRouter
.route('/userProfile/name/:name')
.get(controller.getUserByName);

userProfileRouter.route('/refreshToken/:userId')
.get(controller.refreshToken);
userProfileRouter.route('/refreshToken/:userId').get(controller.refreshToken);

userProfileRouter.route('/userProfile/reportees/:userId')
userProfileRouter
.route('/userProfile/reportees/:userId')
.get(controller.getreportees);

userProfileRouter.route('/userProfile/teammembers/:userId')
userProfileRouter
.route('/userProfile/teammembers/:userId')
.get(controller.getTeamMembersofUser);

userProfileRouter.route('/userProfile/:userId/property')
userProfileRouter
.route('/userProfile/:userId/property')
.patch(controller.updateOneProperty);

userProfileRouter.route('/userProfile/:userId/updatePassword')
userProfileRouter
.route('/userProfile/:userId/updatePassword')
.patch(controller.updatepassword);

userProfileRouter.route('/userProfile/:userId/resetPassword')
userProfileRouter
.route('/userProfile/:userId/resetPassword')
.patch(controller.resetPassword);

userProfileRouter.route('/userProfile/name/:userId')
userProfileRouter
.route('/userProfile/name/:userId')
.get(controller.getUserName);

userProfileRouter.route('/userProfile/project/:projectId')
userProfileRouter
.route('/userProfile/project/:projectId')
.get(controller.getProjectMembers);

userProfileRouter.route('/userProfile/socials/facebook')
userProfileRouter
.route('/userProfile/socials/facebook')
.get(controller.getAllUsersWithFacebookLink);

return userProfileRouter;
};


module.exports = routes;
2 changes: 1 addition & 1 deletion src/startup/routes.js
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,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);
const profileInitialSetupRouter = require('../routes/profileInitialSetupRouter')(profileInitialSetuptoken, userProfile, project , mapLocations);
const isEmailExistsRouter = require('../routes/isEmailExistsRouter')();


Expand Down
Loading

0 comments on commit 5659686

Please sign in to comment.