Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Newell - Fix update quick setup title in title controller. #1171

Merged
merged 2 commits into from
Dec 9, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
248 changes: 162 additions & 86 deletions src/controllers/titleController.js
Original file line number Diff line number Diff line change
@@ -1,139 +1,215 @@
const Team = require('../models/team');
const Project = require('../models/project');
const cacheClosure = require('../utilities/nodeCache');
const { getAllTeamCodeHelper } = require("./userProfileController");
const userProfileController = require("./userProfileController");
const userProfile = require('../models/userProfile');
const project = require('../models/project');

const controller = userProfileController(userProfile, project);
const { getAllTeamCodeHelper } = controller;

const titlecontroller = function (Title) {
const cache = cacheClosure();

const getAllTitles = function (req, res) {
Title.find({})
.then((results) => res.status(200).send(results))
.catch((error) => res.status(404).send(error));
// Update: Confirmed with Jae. Team code is not related to the Team data model. But the team code field within the UserProfile data model.
async function checkTeamCodeExists(teamCode) {
try {
if (cache.getCache('teamCodes')) {
const teamCodes = JSON.parse(cache.getCache('teamCodes'));
return teamCodes.includes(teamCode);
}
const teamCodes = await getAllTeamCodeHelper();
return teamCodes.includes(teamCode);
} catch (error) {
console.error('Error checking if team code exists:', error);
throw error;
}
}

async function checkProjectExists(projectID) {
try {
const proj = await Project.findOne({ _id: projectID }).exec();
return !!proj;
} catch (error) {
console.error('Error checking if project exists:', error);
throw error;
}
}

const getAllTitles = function (req, res) {
Title.find({})
.then((results) => res.status(200).send(results))
.catch((error) => res.status(404).send(error));
};

const getTitleById = function (req, res) {
const { titleId } = req.params;
const getTitleById = function (req, res) {
const { titleId } = req.params;

Title.findById(titleId)
.then((results) => res.send(results))
.catch((error) => res.send(error));
};
Title.findById(titleId)
.then((results) => res.send(results))
.catch((error) => res.send(error));
};

const postTitle = async function (req, res) {
const title = new Title();
title.titleName = req.body.titleName;
title.titleCode = req.body.titleCode;
title.teamCode = req.body.teamCode;
title.projectAssigned = req.body.projectAssigned;
title.mediaFolder = req.body.mediaFolder;
title.teamAssiged = req.body.teamAssiged;

const titleCodeRegex = /^[A-Za-z]+$/;
if (!title.titleCode || !title.titleCode.trim()) {
return res.status(400).send({ message: 'Title code cannot be empty.' });
}

const postTitle = async function (req, res) {
const title = new Title();
if (!titleCodeRegex.test(title.titleCode)) {
return res.status(400).send({ message: 'Title Code must contain only upper or lower case letters.' });
}

// valid title name
if (!title.titleName.trim()) {
res.status(400).send({ message: 'Title cannot be empty.' });
return;
}

title.titleName = req.body.titleName;
title.teamCode = req.body.teamCode;
title.projectAssigned = req.body.projectAssigned;
title.mediaFolder = req.body.mediaFolder;
title.teamAssiged = req.body.teamAssiged;
// if media is empty
if (!title.mediaFolder.trim()) {
res.status(400).send({ message: 'Media folder cannot be empty.' });
return;
}

if (!title.teamCode) {
res.status(400).send({ message: 'Please provide a team code.' });
return;
}

const teamCodeExists = await checkTeamCodeExists(title.teamCode);
if (!teamCodeExists) {
res.status(400).send({ message: 'Invalid team code. Please provide a valid team code.' });
return;
}

// validate if project exist
const projectExist = await checkProjectExists(title.projectAssigned._id);
if (!projectExist) {
res.status(400).send({ message: 'Project lalala is empty or not exist!!!' });
return;
}

// validate if team exist
if (title.teamAssiged && title.teamAssiged._id === 'N/A') {
res.status(400).send({ message: 'Team not exists.' });
return;
}

title
.save()
.then((results) => res.status(200).send(results))
.catch((error) => res.status(404).send(error))
};

// update title function.
const updateTitle = async function (req, res) {
try {

const filter = req.body.id;

// valid title name
if (!title.titleName.trim()) {
if (!req.body.titleName.trim()) {
res.status(400).send({ message: 'Title cannot be empty.' });
return;
}

// if media is empty
if (!title.mediaFolder.trim()) {
res.status(400).send({ message: 'Media folder cannot be empty.' });
if (!req.body.titleCode.trim()) {
res.status(400).send({ message: 'Title code cannot be empty.' });
return;
}

const shortnames = title.titleName.trim().split(' ');
let shortname;
if (shortnames.length > 1) {
shortname = (shortnames[0][0] + shortnames[1][0]).toUpperCase();
} else if (shortnames.length === 1) {
shortname = shortnames[0][0].toUpperCase();
const titleCodeRegex = /^[A-Za-z]+$/;
if (!titleCodeRegex.test(req.body.titleCode)) {
return res.status(400).send({ message: 'Title Code must contain only upper or lower case letters.' });
}
title.shortName = shortname;

// Validate team code by checking if it exists in the database
if (!title.teamCode) {
// if media is empty
if (!req.body.mediaFolder.trim()) {
res.status(400).send({ message: 'Media folder cannot be empty.' });
return;
}

if (!req.body.teamCode) {
res.status(400).send({ message: 'Please provide a team code.' });
return;
}

const teamCodeExists = await checkTeamCodeExists(title.teamCode);
const teamCodeExists = await checkTeamCodeExists(req.body.teamCode);
if (!teamCodeExists) {
res.status(400).send({ message: 'Invalid team code. Please provide a valid team code.' });
return;
}

// validate if project exist
const projectExist = await checkProjectExists(title.projectAssigned._id);
const projectExist = await checkProjectExists(req.body.projectAssigned._id);
if (!projectExist) {
res.status(400).send({ message: 'Project is empty or not exist.' });
res.status(400).send({ message: 'Project is empty or not exist~~~' });
return;
}

// validate if team exist
if (title.teamAssiged && title.teamAssiged._id === 'N/A') {
if (req.body.teamAssiged && req.body.teamAssiged._id === 'N/A') {
res.status(400).send({ message: 'Team not exists.' });
return;
}
const result = await Title.findById(filter);
result.titleName = req.body.titleName;
result.titleCode = req.body.titleCode;
result.teamCode = req.body.teamCode;
result.projectAssigned = req.body.projectAssigned;
result.mediaFolder = req.body.mediaFolder;
result.teamAssiged = req.body.teamAssiged;
const updatedTitle = await result.save();
res.status(200).send({ message: 'Update successful', updatedTitle });

} catch (error) {
console.log(error);
res.status(500).send({ message: 'An error occurred', error });
}

};

const deleteTitleById = async function (req, res) {
const { titleId } = req.params;
Title.deleteOne({ _id: titleId })
.then((result) => res.send(result))
.catch((error) => res.send(error));
};

title
.save()
.then((results) => res.status(200).send(results))
.catch((error) => res.status(404).send(error));
};

const deleteTitleById = async function (req, res) {
const { titleId } = req.params;
Title.deleteOne({ _id: titleId })
.then((result) => res.send(result))
.catch((error) => res.send(error));
};

const deleteAllTitles = async function (req, res) {
Title.deleteMany({})
.then((result) => {
if (result.deletedCount === 0) {
res.send({ message: 'No titles found to delete.' });
} else {
res.send({ message: `${result.deletedCount} titles were deleted successfully.` });
}
})
.catch((error) => {
res.status(500).send(error);
});
};
// Update: Confirmed with Jae. Team code is not related to the Team data model. But the team code field within the UserProfile data model.
async function checkTeamCodeExists(teamCode) {
try {
if (cache.getCache('teamCodes')) {
const teamCodes = JSON.parse(cache.getCache('teamCodes'));
return teamCodes.includes(teamCode);
const deleteAllTitles = async function (req, res) {
Title.deleteMany({})
.then((result) => {
if (result.deletedCount === 0) {
res.send({ message: 'No titles found to delete.' });
} else {
res.send({ message: `${result.deletedCount} titles were deleted successfully.` });
}
const teamCodes = await getAllTeamCodeHelper();
return teamCodes.includes(teamCode);
} catch (error) {
console.error('Error checking if team code exists:', error);
throw error;
}
}
})
.catch((error) => {
console.log(error)
res.status(500).send(error);
});
};



async function checkProjectExists(projectID) {
try {
const project = await Project.findOne({ _id: projectID }).exec();
return !!project;
} catch (error) {
console.error('Error checking if project exists:', error);
throw error;
}
}

return {
getAllTitles,
getTitleById,
postTitle,
deleteTitleById,
deleteAllTitles,
updateTitle
};
};

module.exports = titlecontroller;

module.exports = titlecontroller;
42 changes: 21 additions & 21 deletions src/controllers/userProfileController.js
Original file line number Diff line number Diff line change
Expand Up @@ -1758,28 +1758,28 @@ const userProfileController = function (UserProfile, Project) {

const query = match[1]
? {
$or: [
{
firstName: { $regex: new RegExp(`${escapeRegExp(name)}`, 'i') },
},
{
$and: [
{ firstName: { $regex: new RegExp(`${escapeRegExp(firstName)}`, 'i') } },
{ lastName: { $regex: new RegExp(`${escapeRegExp(lastName)}`, 'i') } },
],
},
],
}
$or: [
{
firstName: { $regex: new RegExp(`${escapeRegExp(name)}`, 'i') },
},
{
$and: [
{ firstName: { $regex: new RegExp(`${escapeRegExp(firstName)}`, 'i') } },
{ lastName: { $regex: new RegExp(`${escapeRegExp(lastName)}`, 'i') } },
],
},
],
}
: {
$or: [
{
firstName: { $regex: new RegExp(`${escapeRegExp(name)}`, 'i') },
},
{
lastName: { $regex: new RegExp(`${escapeRegExp(name)}`, 'i') },
},
],
};
$or: [
{
firstName: { $regex: new RegExp(`${escapeRegExp(name)}`, 'i') },
},
{
lastName: { $regex: new RegExp(`${escapeRegExp(name)}`, 'i') },
},
],
};

const userProfile = await UserProfile.find(query);

Expand Down
6 changes: 4 additions & 2 deletions src/routes/titleRouter.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,14 @@ const express = require('express');

const router = function (title) {
const controller = require('../controllers/titleController')(title);

const titleRouter = express.Router();

titleRouter.route('/title')
.get(controller.getAllTitles)
.post(controller.postTitle);
.post(controller.postTitle)
// .put(controller.putTitle);

titleRouter.route('/title/update').post(controller.updateTitle);

titleRouter.route('/title/:titleId')
.get(controller.getTitleById)
Expand Down
Loading