Skip to content

Commit

Permalink
Merge pull request #603 from OneCommunityGlobal/Xiao-F-Create-way-for…
Browse files Browse the repository at this point in the history
…-owner-to-edit-update-ChatGPT-prompt-text

Xiao F Create way for owner to edit & update ChatGPT prompt text
  • Loading branch information
one-community authored Jan 6, 2024
2 parents 15af5fc + ce8d244 commit 13e5c48
Show file tree
Hide file tree
Showing 16 changed files with 454 additions and 461 deletions.
90 changes: 40 additions & 50 deletions src/controllers/bmdashboard/bmMaterialsController.js
Original file line number Diff line number Diff line change
@@ -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()
Expand Down Expand Up @@ -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);
Expand All @@ -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<materialUpdates.length;i++)
{
let payload = materialUpdates[i];
for (let i = 0; i < materialUpdates.length; i++) {
const payload = materialUpdates[i];
let quantityUsed = +payload.quantityUsed;
let quantityWasted = +payload.quantityWasted;
let material = payload.material;
if(payload.QtyUsedLogUnit=='percent' && quantityWasted>=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);
}

Expand All @@ -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)
Expand All @@ -213,7 +203,7 @@ const bmMaterialsController = function (ItemMaterial,BuildingMaterial) {
bmMaterialsList,
bmPostMaterialUpdateRecord,
bmPostMaterialUpdateBulk,
bmPurchaseMaterials
bmPurchaseMaterials,
};
};

Expand Down
40 changes: 38 additions & 2 deletions src/controllers/dashBoardController.js
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand All @@ -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(
Expand Down Expand Up @@ -211,7 +245,7 @@ const dashboardcontroller = function () {
null,
null,
email,
null
null,
);
res.status(200).send('Success');
} catch {
Expand Down Expand Up @@ -263,6 +297,8 @@ const dashboardcontroller = function () {

return {
dashboarddata,
getAIPrompt,
updateAIPrompt,
monthlydata,
weeklydata,
leaderboarddata,
Expand All @@ -274,4 +310,4 @@ const dashboardcontroller = function () {
};
};

module.exports = dashboardcontroller;
module.exports = dashboardcontroller;
45 changes: 20 additions & 25 deletions src/controllers/mapLocationsController.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
Expand All @@ -25,30 +23,27 @@ 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({});
res.status(200).send({ users: modifiedUsers, mUsers });
} 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;
Expand All @@ -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...' });
}
};
Expand All @@ -84,39 +79,39 @@ 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,
lastName: response.lastName,
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...' });
}
};
Expand All @@ -128,12 +123,12 @@ const mapLocationsController = function (MapLocation) {
});
return hours;
}

return {
getAllLocations,
deleteLocation,
putUserLocation,
updateUserLocation
updateUserLocation,
};
};

Expand Down
Loading

0 comments on commit 13e5c48

Please sign in to comment.