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

Samarth B Job CC feature #1165

Open
wants to merge 2 commits into
base: development
Choose a base branch
from
Open
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
159 changes: 159 additions & 0 deletions src/controllers/jobNotificationListControllers.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,159 @@
const mongoose = require('mongoose');
const jobs = require('models/jobs');
const JobsNotificationList = require('models/jobsNotificationList');

const { ObjectId } = mongoose.Types;

const isOwner = async (req, res, next) => {
const { requestor } = req.body; // Correctly access the requestor

try {
if (!requestor || requestor.role.toLowerCase() !== 'owner') {
return res.status(403).json({ error: 'Access denied' }); // Check ownership
}
next(); // Proceed if the user is an owner
} catch (err) {
res.status(500).json({ error: 'Internal server error' }); // Handle unexpected errors
}
};

const getJobWatchList = async (req, res) => {
const { jobId, category, title } = req.query;

try {
const match = {};
if (jobId) match._id = ObjectId(jobId); // Convert jobId to ObjectId
if (category) match.category = category; // Match by category
if (title) match.title = new RegExp(title, 'i'); // Search by job title (case-insensitive)

const jobsWithCC = await jobs.aggregate([
{ $match: match }, // Apply filters
{
$lookup: {
from: 'jobsnotificationlists', // Match CC list collection
localField: '_id',
foreignField: 'jobId',
as: 'ccList', // Name for the joined data
},
},
{
$project: {
_id: 1, // Ensure the job's _id is included
title: 1,
category: 1,
datePosted: 1,
'ccList._id': 1, // Include the _id of each CC entry
'ccList.email': 1, // Only include emails from the CC list
},
},
{ $sort: { datePosted: -1 } }, // Sort by most recent jobs
]);

res.status(200).json(jobsWithCC);
} catch (err) {
console.error(err); // Log error for debugging
res.status(500).json({ error: 'Internal server error' });
}
};

const addCCByJob = async (req, res) => {
const { email, jobId } = req.body;

if (!email || !jobId) {
return res.status(400).json({ error: 'Email, Job ID, and Category are required' });
}

try {
let job;
if (jobId) {
job = await jobs.findById(jobId);
if (!job) {
return res.status(404).json({ error: 'Job not found' });
}
}

const ccEntry = new JobsNotificationList({
email,
jobId: jobId || null,
category: job.category || null,
});

await ccEntry.save();

res.status(201).json({ message: 'Email added to CC list successfully' });
} catch (err) {
if (err.code === 11000) {
return res.status(409).json({ error: 'Email already exists in the CC list' });
}
res.status(500).json({ error: 'Internal server error' });
}
};

const addCCByCategory = async (req, res) => {
const { email, category } = req.body;

// Validate input
if (!email || !category) {
return res.status(400).json({ error: 'Email and Category are required' });
}

try {
// Check if the category exists
const categoryExists = await jobs.exists({ category });
if (!categoryExists) {
return res.status(404).json({ error: 'Category not found' });
}

// Find all jobs in the specified category
const jobArr = await jobs.find({ category });

if (jobArr.length === 0) {
return res.status(404).json({ error: 'No jobs found in this category' });
}

// Create bulk operations for all jobs in the category
const bulkOps = jobArr.map((job) => ({
updateOne: {
filter: { email, jobId: job._id, category: job.category },
update: { $setOnInsert: { email, jobId: job._id, category: job.category } },
upsert: true, // Perform upsert to avoid duplicates
},
}));

// Execute bulkWrite operation
const result = await JobsNotificationList.bulkWrite(bulkOps);

res.status(201).json({
message: 'Email added to CC list successfully',
matchedCount: result.matchedCount,
modifiedCount: result.modifiedCount,
upsertedCount: result.upsertedCount,
});
} catch (err) {
console.error(err);
res.status(500).json({ error: 'Internal server error' });
}
};

const removeEmailFromCCList = async (req, res) => {
const { id } = req.params; // ID of the CC entry

try {
const result = await JobsNotificationList.findByIdAndDelete(id);
if (!result) {
return res.status(404).json({ error: 'CC entry not found' });
}
res.status(200).json({ message: 'CC entry removed successfully' });
} catch (err) {
res.status(500).json({ error: 'Internal server error' });
}
};


module.exports = {
isOwner,
getJobWatchList,
addCCByJob,
addCCByCategory,
removeEmailFromCCList
};
11 changes: 11 additions & 0 deletions src/models/jobsNotificationList.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
const mongoose = require('mongoose');

const jobsNotificationListSchema = new mongoose.Schema({
email: { type: String, required: true },
jobId: { type: mongoose.Schema.Types.ObjectId, ref: 'Job', default: null },
category: { type: String, default: null },
});

jobsNotificationListSchema.index({ email: 1, jobId: 1, category: 1 }, { unique: true });

module.exports = mongoose.model('JobsNotificationList', jobsNotificationListSchema);
11 changes: 11 additions & 0 deletions src/routes/jobNotificationListRouter.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
const express = require('express');
const jobNotificationListControllers = require('../controllers/jobNotificationListControllers');

const router = express.Router();

router.get('/', jobNotificationListControllers.isOwner, jobNotificationListControllers.getJobWatchList);
router.post('/job', jobNotificationListControllers.isOwner, jobNotificationListControllers.addCCByJob);
router.post('/category', jobNotificationListControllers.isOwner, jobNotificationListControllers.addCCByCategory);
router.delete('/:id', jobNotificationListControllers.isOwner, jobNotificationListControllers.removeEmailFromCCList);

module.exports = router;
2 changes: 2 additions & 0 deletions src/startup/routes.js
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@ const permissionChangeLogRouter = require('../routes/permissionChangeLogsRouter'
permissionChangeLog,
);
const isEmailExistsRouter = require('../routes/isEmailExistsRouter')();
const jobNotificationListRouter = require('../routes/jobNotificationListRouter');

const taskEditSuggestion = require('../models/taskEditSuggestion');
const taskEditSuggestionRouter = require('../routes/taskEditSuggestionRouter')(taskEditSuggestion);
Expand Down Expand Up @@ -163,6 +164,7 @@ module.exports = function (app) {
app.use('/api', followUpRouter);
app.use('/api', blueSquareEmailAssignmentRouter);
app.use('/api/jobs', jobsRouter)
app.use('/api/job-notification-list/', jobNotificationListRouter)
// bm dashboard
app.use('/api/bm', bmLoginRouter);
app.use('/api/bm', bmMaterialsRouter);
Expand Down