Skip to content

Commit

Permalink
merge to development
Browse files Browse the repository at this point in the history
  • Loading branch information
abdel-lall committed Mar 10, 2024
2 parents 9056026 + 0d96b77 commit eb507c2
Show file tree
Hide file tree
Showing 14 changed files with 480 additions and 85 deletions.
Binary file modified .DS_Store
Binary file not shown.
13 changes: 13 additions & 0 deletions src/controllers/bmdashboard/bmInventoryTypeController.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,18 @@ function bmInventoryTypeController(InvType, MatType, ConsType, ReusType, ToolTyp
}
}

async function fetchReusableTypes(req, res) {
try {
ReusType
.find()
.exec()
.then((result) => res.status(200).send(result))
.catch((error) => res.status(500).send(error));
} catch (err) {
res.json(err);
}
}

const fetchToolTypes = async (req, res) => {
try {
ToolType
Expand Down Expand Up @@ -228,6 +240,7 @@ function bmInventoryTypeController(InvType, MatType, ConsType, ReusType, ToolTyp
};
return {
fetchMaterialTypes,
fetchReusableTypes,
fetchToolTypes,
addEquipmentType,
fetchSingleInventoryType,
Expand Down
133 changes: 67 additions & 66 deletions src/controllers/bmdashboard/bmMaterialsController.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,47 +4,48 @@ const bmMaterialsController = function (BuildingMaterial) {
const bmMaterialsList = async function _matsList(req, res) {
try {
BuildingMaterial.find()
.populate([
{
path: 'project',
select: '_id name',
},
{
path: 'itemType',
select: '_id name unit',
},
{
path: 'updateRecord',
populate: {
path: 'createdBy',
select: '_id firstName lastName',
.populate([
{
path: 'project',
select: '_id name',
},
},
{
path: 'purchaseRecord',
populate: {
path: 'requestedBy',
select: '_id firstName lastName',
{
path: 'itemType',
select: '_id name unit',
},
},
])
.exec()
.then(results => res.status(200).send(results))
.catch(error => res.status(500).send(error));
{
path: 'updateRecord',
populate: {
path: 'createdBy',
select: '_id firstName lastName',
},
},
{
path: 'purchaseRecord',
populate: {
path: 'requestedBy',
select: '_id firstName lastName',
},
},
])
.exec()
.then((results) => res.status(200).send(results))
.catch((error) => res.status(500).send(error));
} catch (err) {
res.json(err);
}
};

const bmPurchaseMaterials = async function (req, res) {
const {
projectId,
matTypeId,
primaryId: projectId,
secondaryId: matTypeId,
quantity,
priority,
brand: brandPref,
requestor: { requestorId },
} = req.body;

try {
// check if requestor has permission to make purchase request
//! Note: this code is disabled until permissions are added
Expand All @@ -71,17 +72,17 @@ const bmMaterialsController = function (BuildingMaterial) {
project: projectId,
purchaseRecord: [newPurchaseRecord],
};
BuildingMaterial
.create(newDoc)
.then(() => res.status(201).send())
.catch(error => res.status(500).send(error));
return;
BuildingMaterial
.create(newDoc)
.then(() => res.status(201).send())
.catch((error) => res.status(500).send(error));
return;
}
BuildingMaterial
.findOneAndUpdate(
{ _id: mongoose.Types.ObjectId(doc._id) },
{ $push: { purchaseRecord: newPurchaseRecord } },
)
)
.exec()
.then(() => res.status(201).send())
.catch(error => res.status(500).send(error));
Expand All @@ -96,44 +97,44 @@ const bmMaterialsController = function (BuildingMaterial) {
let quantityWasted = +req.body.quantityWasted;
const { material } = req.body;
if (payload.QtyUsedLogUnit == 'percent' && quantityWasted >= 0) {
quantityUsed = +((+quantityUsed / 100) * material.stockAvailable).toFixed(4);
}
if (payload.QtyWastedLogUnit == 'percent' && quantityUsed >= 0) {
quantityWasted = +((+quantityWasted / 100) * material.stockAvailable).toFixed(4);
}
quantityUsed = +((+quantityUsed / 100) * material.stockAvailable).toFixed(4);
}
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 {
let newStockUsed = +material.stockUsed + parseFloat(quantityUsed);
let newStockWasted = +material.stockWasted + parseFloat(quantityWasted);
let newAvailable = +material.stockAvailable - parseFloat(quantityUsed) - parseFloat(quantityWasted);
newStockUsed = parseFloat(newStockUsed.toFixed(4));
newStockWasted = parseFloat(newStockWasted.toFixed(4));
newAvailable = parseFloat(newAvailable.toFixed(4));
BuildingMaterial.updateOne(
let newStockUsed = +material.stockUsed + parseFloat(quantityUsed);
let newStockWasted = +material.stockWasted + parseFloat(quantityWasted);
let newAvailable = +material.stockAvailable - parseFloat(quantityUsed) - parseFloat(quantityWasted);
newStockUsed = parseFloat(newStockUsed.toFixed(4));
newStockWasted = parseFloat(newStockWasted.toFixed(4));
newAvailable = parseFloat(newAvailable.toFixed(4));
BuildingMaterial.updateOne(
{ _id: req.body.material._id },

{
$set: {
{
$set: {
stockUsed: newStockUsed,
stockWasted: newStockWasted,
stockAvailable: newAvailable,
},
$push: {
updateRecord: {
date: req.body.date,
createdBy: req.body.requestor.requestorId,
quantityUsed,
quantityWasted,
},
$push: {
updateRecord: {
date: req.body.date,
createdBy: req.body.requestor.requestorId,
quantityUsed,
quantityWasted,
},
},
},

)
)
.then((results) => { res.status(200).send(results); })
.catch(error => res.status(500).send({ message: error }));
}
.catch((error) => res.status(500).send({ message: error }));
}
};

const bmPostMaterialUpdateBulk = function (req, res) {
Expand Down Expand Up @@ -175,26 +176,26 @@ const bmMaterialsController = function (BuildingMaterial) {
quantityWasted,
date: req.body.date,
},
});
}
});
}

try {
if (errorFlag) {
res.status(500).send('Stock quantities submitted seems to be invalid');
return;
}
const updatePromises = updateRecordsToBeAdded.map(updateItem => BuildingMaterial.updateOne(
const updatePromises = updateRecordsToBeAdded.map((updateItem) => BuildingMaterial.updateOne(
{ _id: updateItem.updateId },
{
$set: updateItem.set,
$push: { updateRecord: updateItem.updateValue },
},
).exec());
Promise.all(updatePromises)
.then((results) => {
res.status(200).send({ result: `Successfully posted log for ${results.length} Material records.` });
})
.catch(error => res.status(500).send(error));
Promise.all(updatePromises)
.then((results) => {
res.status(200).send({ result: `Successfully posted log for ${results.length} Material records.` });
})
.catch((error) => res.status(500).send(error));
} catch (err) {
res.json(err);
}
Expand All @@ -204,7 +205,7 @@ const bmMaterialsController = function (BuildingMaterial) {
bmPostMaterialUpdateRecord,
bmPostMaterialUpdateBulk,
bmPurchaseMaterials,
};
};
};

module.exports = bmMaterialsController;
112 changes: 112 additions & 0 deletions src/controllers/bmdashboard/bmReusableController.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
const mongoose = require('mongoose');
const {
reusableType: ReusableType
} = require('../../models/bmdashboard/buildingInventoryType');

function isValidDate(dateString) {
const date = new Date(dateString);
return !isNaN(date.getTime());
}

const bmReusableController = function (BuildingReusable) {
const fetchBMReusables = async (req, res) => {
try {
BuildingReusable
.find()
.populate([
{
path: 'project',
select: '_id name',
},
{
path: 'itemType',
select: '_id name',
},
{
path: 'updateRecord',
populate: {
path: 'createdBy',
select: '_id firstName lastName',
},
},
{
path: 'purchaseRecord',
populate: {
path: 'requestedBy',
select: '_id firstName lastName',
},
},
])
.exec()
.then((result) => {
res.status(200).send(result);
})
.catch(error => res.status(500).send(error));
} catch (err) {
res.json(err);
}
};

const purchaseReusable = async (req, res) => {
const {
primaryId: projectId,
secondaryId: itemTypeId,
quantity,
priority,
brand: brandPref,
requestor: { requestorId },
} = req.body;

try {
if (!mongoose.Types.ObjectId.isValid(itemTypeId) || !mongoose.Types.ObjectId.isValid(projectId)) {
return res.status(400).send('Invalid itemTypeId or projectId.');
}

const itemType = await ReusableType.findById(itemTypeId);
if (!itemType || itemType.__t !== 'reusable_type') {
return res.status(400).send('ItemTypeId does not correspond to a valid reusable_type.');
}

const allowedPriorities = ['Low', 'Medium', 'High'];
if (!allowedPriorities.includes(priority)) {
return res.status(400).send('Invalid priority. Must be one of: Low, Medium, High.');
}

const newPurchaseRecord = {
date: new Date(),
requestedBy: requestorId,
quantity,
priority,
brandPref,
};

const doc = await BuildingReusable.findOne({ project: projectId, itemType: itemTypeId });

if (!doc) {
const newDoc = new BuildingReusable({
itemType: itemTypeId,
project: projectId,
purchaseRecord: [newPurchaseRecord],
});
await newDoc.save();
res.status(201).send('New reusable purchase record created successfully');
} else {
await BuildingReusable.findByIdAndUpdate(
{ _id: mongoose.Types.ObjectId(doc._id) },
{ $push: { purchaseRecord: newPurchaseRecord } },
);
res.status(201).send('Reusable purchase record updated successfully');
}
} catch (error) {
console.error('Error processing reusable purchase:', error);
res.status(500).send('Internal Server Error');
}
};

return {
fetchBMReusables,
purchaseReusable,
};
};

module.exports = bmReusableController;
Loading

0 comments on commit eb507c2

Please sign in to comment.