Skip to content

Commit

Permalink
Merge pull request #1031 from OneCommunityGlobal/development
Browse files Browse the repository at this point in the history
Backend Release to Main [1.85]
  • Loading branch information
one-community authored Jul 17, 2024
2 parents 46981d7 + 061e6f1 commit 790aff3
Show file tree
Hide file tree
Showing 17 changed files with 414 additions and 75 deletions.
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,10 @@ SMTPPort=<smtp port>
SMTPUser=<smtp user>
TOKEN_LIFETIME=<number>
TOKEN_LIFETIME_UNITS=<unit like days, second, hours etc>
NODE_ENV= `local` | `development` | `production` <br/>
JWT_SECRET=<secret value>


To make the process easy create a .env file and put the above text in the file and replace values with the correct values, which you can get from your teammates. Then do an npm run-script build followed by an npm start. By default, the services will start on port 4500 and you can http://localhost:4500/api/<routename> to access the methods. A tools like Postman will be your best friend here, you will need to have an auth token placed in the 'Authorization' header which you can get through the networking tab of the local frontend when you login.

- `npm run lint` -- fix lint
Expand Down
11 changes: 10 additions & 1 deletion src/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,22 @@ const Sentry = require('@sentry/node');

const app = express();
const logger = require('./startup/logger');
const globalErrorHandler = require('./utilities/errorHandling/globalErrorHandler').default;

logger.init();

// The request handler must be the first middleware on the app
app.use(Sentry.Handlers.requestHandler());

require('./startup/cors')(app);
require('./startup/bodyParser')(app);
require('./startup/middleware')(app);
require('./startup/routes')(app);

module.exports = { app, logger, Sentry };
// The error handler must be before any other error middleware and after all controllers
app.use(Sentry.Handlers.errorHandler());

// Make it the last middleware since it returns a response and do not call next()
app.use(globalErrorHandler);

module.exports = { app, logger };
128 changes: 118 additions & 10 deletions src/controllers/profileInitialSetupController.js
Original file line number Diff line number Diff line change
Expand Up @@ -161,10 +161,11 @@ const profileInitialSetupController = function (
const existingEmail = await userProfile.findOne({
email,
});

if (existingEmail) {
return res.status(400).send('email already in use');
}
session.startTransaction();
}

await ProfileInitialSetupToken.findOneAndDelete({ email });

const newToken = new ProfileInitialSetupToken({
Expand Down Expand Up @@ -259,8 +260,115 @@ const profileInitialSetupController = function (
});

if (existingEmail) {
res.status(400).send('email already in use');
return;
return res.status(400).send('email already in use');
}
if (foundToken) {
const expirationMoment = moment(foundToken.expiration);

if (expirationMoment.isAfter(currentMoment)) {
const defaultProject = await Project.findOne({
projectName: "Orientation and Initial Setup",
});

const newUser = new userProfile();
newUser.password = req.body.password;
newUser.role = "Volunteer";
newUser.firstName = req.body.firstName;
newUser.lastName = req.body.lastName;
newUser.jobTitle = req.body.jobTitle;
newUser.phoneNumber = req.body.phoneNumber;
newUser.bio = "";
newUser.weeklycommittedHours = foundToken.weeklyCommittedHours;
newUser.weeklycommittedHoursHistory = [
{
hours: newUser.weeklycommittedHours,
dateChanged: Date.now(),
},
];
newUser.personalLinks = [];
newUser.adminLinks = [];
newUser.teams = Array.from(new Set([]));
newUser.projects = Array.from(new Set([defaultProject]));
newUser.createdDate = Date.now();
newUser.email = req.body.email;
newUser.weeklySummaries = [{ summary: "" }];
newUser.weeklySummariesCount = 0;
newUser.weeklySummaryOption = "Required";
newUser.mediaUrl = "";
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: [],
};
newUser.bioPosted = "default";
newUser.privacySettings.email = req.body.privacySettings.email;
newUser.privacySettings.phoneNumber =
req.body.privacySettings.phoneNumber;
newUser.teamCode = "";
newUser.isFirstTimelog = true;

const savedUser = await newUser.save();

emailSender(
process.env.MANAGER_EMAIL || "[email protected]", // "[email protected]"
`NEW USER REGISTERED: ${savedUser.firstName} ${savedUser.lastName}`,
informManagerMessage(savedUser),
null,
null
);
await ProfileInitialSetupToken.findByIdAndDelete(foundToken._id);

const jwtPayload = {
userid: savedUser._id,
role: savedUser.role,
permissions: savedUser.permissions,
expiryTimestamp: moment().add(
config.TOKEN.Lifetime,
config.TOKEN.Units
),
};

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

const locationData = {
title: "",
firstName: req.body.firstName,
lastName: req.body.lastName,
jobTitle: req.body.jobTitle,
location: req.body.homeCountry,
isActive: true,
};

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,
weeklycommittedHours: savedUser.weeklycommittedHours,
createdDate: savedUser.createdDate.toISOString(),
_id: savedUser._id,
role: savedUser.role,
firstName: savedUser.firstName,
lastName: savedUser.lastName,
email: savedUser.email,
};

const allUserCache = JSON.parse(cache.getCache("allusers"));
allUserCache.push(NewUserCache);
cache.setCache("allusers", JSON.stringify(allUserCache));
} else {
return res.status(400).send('Token is expired');
}
} else {
return res.status(400).send('Invalid token');
}

const expirationMoment = moment(foundToken.expiration);
Expand Down Expand Up @@ -390,10 +498,9 @@ const profileInitialSetupController = function (
const foundToken = await ProfileInitialSetupToken.findOne({ token });

if (foundToken) {
res.status(200).send({ userAPIKey: premiumKey });
} else {
res.status(403).send("Unauthorized Request");
}
return res.status(200).send({ userAPIKey: premiumKey });
}
return res.status(403).send('Unauthorized Request');
};

function calculateTotalHours(hoursByCategory) {
Expand Down Expand Up @@ -432,9 +539,10 @@ const profileInitialSetupController = function (
const combined = [...modifiedUsers, ...mapUsers];
const countries = combined.map(user => user.location.country);
const totalUniqueCountries = [...new Set(countries)].length;
res.status(200).send({ CountryCount: totalUniqueCountries });
return res.status(200).send({ CountryCount: totalUniqueCountries });
} catch (error) {
res.status(500).send(`Error: ${error}`);
LOGGER.logException(error, 'Error in getTotalCountryCount');
return res.status(500).send(`Error: ${error}`);
}
};

Expand Down
66 changes: 66 additions & 0 deletions src/controllers/teamController.js
Original file line number Diff line number Diff line change
Expand Up @@ -228,6 +228,71 @@ const teamcontroller = function (Team) {
res.status(500).send(error);
});
};
const updateTeamVisibility = async (req, res) => {
console.log("==============> 9 ");

const { visibility, teamId, userId } = req.body;

try {
Team.findById(teamId, (error, team) => {
if (error || team === null) {
res.status(400).send('No valid records found');
return;
}

const memberIndex = team.members.findIndex(member => member.userId.toString() === userId);
if (memberIndex === -1) {
res.status(400).send('Member not found in the team.');
return;
}

team.members[memberIndex].visible = visibility;
team.modifiedDatetime = Date.now();

team.save()
.then(updatedTeam => {
// Additional operations after team.save()
const assignlist = [];
const unassignlist = [];
team.members.forEach(member => {
if (member.userId.toString() === userId) {
// Current user, no need to process further
return;
}

if (visibility) {
assignlist.push(member.userId);
} else {
console.log("Visiblity set to false so removing it");
unassignlist.push(member.userId);
}
});

const addTeamToUserProfile = userProfile
.updateMany({ _id: { $in: assignlist } }, { $addToSet: { teams: teamId } })
.exec();
const removeTeamFromUserProfile = userProfile
.updateMany({ _id: { $in: unassignlist } }, { $pull: { teams: teamId } })
.exec();

Promise.all([addTeamToUserProfile, removeTeamFromUserProfile])
.then(() => {
res.status(200).send({ result: 'Done' });
})
.catch((error) => {
res.status(500).send({ error });
});
})
.catch(errors => {
console.error('Error saving team:', errors);
res.status(400).send(errors);
});

});
} catch (error) {
res.status(500).send('Error updating team visibility: ' + error.message);
}
};

return {
getAllTeams,
Expand All @@ -237,6 +302,7 @@ const teamcontroller = function (Team) {
putTeam,
assignTeamToUsers,
getTeamMembership,
updateTeamVisibility,
};
};

Expand Down
12 changes: 11 additions & 1 deletion src/helpers/dashboardhelper.js
Original file line number Diff line number Diff line change
Expand Up @@ -175,10 +175,20 @@ const dashboardhelper = function () {
{ members: 1 },
);

console.log(teamsResult);
teamsResult.forEach((_myTeam) => {
let isUserVisible = false;
_myTeam.members.forEach((teamMember) => {
if (!teamMember.userId.equals(userid)) teamMemberIds.push(teamMember.userId);
if (teamMember.userId.equals(userid) && teamMember.visible) isUserVisible = true;
});
if(isUserVisible)
{
_myTeam.members.forEach((teamMember) => {
if (!teamMember.userId.equals(userid))
teamMemberIds.push(teamMember.userId);
});
}

});

teamMembers = await userProfile.find(
Expand Down
29 changes: 18 additions & 11 deletions src/helpers/userHelper.js
Original file line number Diff line number Diff line change
Expand Up @@ -980,7 +980,8 @@ const userHelper = function () {
},
);

logger.logInfo(results);
logger.logInfo(`Job deleting blue squares older than 1 year finished
at ${moment().tz('America/Los_Angeles').format()} \nReulst: ${JSON.stringify(results)}`);
} catch (err) {
logger.logException(err);
}
Expand Down Expand Up @@ -1891,13 +1892,19 @@ const userHelper = function () {
const { endDate } = user;
endDate.setHours(endDate.getHours() + 7);
if (moment().isAfter(moment(endDate).add(1, 'days'))) {
await userProfile.findByIdAndUpdate(
user._id,
user.set({
isActive: false,
}),
{ new: true },
);
try {
await userProfile.findByIdAndUpdate(
user._id,
user.set({
isActive: false,
}),
{ new: true },
);
} catch (err) {
// Log the error and continue to the next user
logger.logException(err, `Error in deActivateUser. Failed to update User ${user._id}`);
continue;
}
const id = user._id;
const person = await userProfile.findById(id);

Expand All @@ -1920,7 +1927,7 @@ const userHelper = function () {
}
}
} catch (err) {
logger.logException(err);
logger.logException(err, 'Unexpected rrror in deActivateUser');
}
};

Expand All @@ -1934,7 +1941,7 @@ const userHelper = function () {
try {
await token.deleteMany({ isCancelled: true, expiration: { $lt: ninetyDaysAgo } });
} catch (error) {
logger.logException(error);
logger.logException(error, `Error in deleteExpiredTokens. Date ${currentDate}`);
}
};

Expand All @@ -1945,7 +1952,7 @@ const userHelper = function () {
try {
await timeOffRequest.deleteMany({ endingDate: { $lte: utcEndMoment } });
} catch (error) {
console.error('Error deleting expired time off requests:', error);
logger.logException(error, `Error deleting expired time-off requests: utcEndMoment ${utcEndMoment}`);
}
};

Expand Down
1 change: 1 addition & 0 deletions src/models/team.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ const team = new Schema({
{
userId: { type: mongoose.SchemaTypes.ObjectId, required: true },
addDateTime: { type: Date, default: Date.now(), ref: 'userProfile' },
visible: { type : 'Boolean', default:true},
},
],
teamCode: {
Expand Down
4 changes: 3 additions & 1 deletion src/routes/teamRouter.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@ const router = function (team) {

teamRouter.route('/team')
.get(controller.getAllTeams)
.post(controller.postTeam);
.post(controller.postTeam)
.put(controller.updateTeamVisibility);


teamRouter.route('/team/:teamId')
.get(controller.getTeamById)
Expand Down
Loading

0 comments on commit 790aff3

Please sign in to comment.