Skip to content
This repository has been archived by the owner on Oct 29, 2024. It is now read-only.

Commit

Permalink
Merge pull request #80 from BiswajitSahoo-tech/inv-mgmt
Browse files Browse the repository at this point in the history
Added inventory management
  • Loading branch information
roopeshsn authored Oct 9, 2022
2 parents 3746f7c + 438d825 commit 54b2b78
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 1 deletion.
22 changes: 21 additions & 1 deletion backend/controllers/orderControllers.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
const asyncHandler = require('express-async-handler')
const Order = require('../models/orderModel')
const Product = require('../models/productModel')
const productController = require('./../controllers/productController')

// @desc Create new order
// @route POST /api/orders
Expand All @@ -17,7 +18,7 @@ const addOrderItems = asyncHandler(async (req, res) => {
// Product price validation
orderItems.forEach(async (item) => {
let lookupItem = await Product.findById(item.product)
if (item.price !== lookupItem.price) {
if (parseFloat(item.price) !== lookupItem.price) {
res.status(400)
throw new Error(
'There is a discrepancy between the prices of the items, and whats in the Database, please try again!',
Expand Down Expand Up @@ -91,6 +92,25 @@ const updateOrderToPaid = asyncHandler(async (req, res) => {
const order = await Order.findById(req.params.id)

if (order) {
//below .map() function return an array of promises
const updatePromises = order.orderItems.map(async (item) => {
await productController.updateStockCount(
req,
res,
item.product,
parseInt(item.qty),
)
})
//below function to resolve the array of promises
try {
await Promise.all(updatePromises)
} catch (error) {
return res.status(404).json({
status: 'fail',
message: error.message,
})
}

order.isPaid = true
order.paidAt = Date.now()
const updatedOrder = await order.save()
Expand Down
23 changes: 23 additions & 0 deletions backend/controllers/productController.js
Original file line number Diff line number Diff line change
Expand Up @@ -127,10 +127,33 @@ const updateProduct = asyncHandler(async (req, res) => {
}
})

const updateStockCount = asyncHandler(async (req, res, id, qty) => {
try {
var product = await Product.findById(id)
} catch (err) {
throw new Error(err.message)
}

if (product.countInStock < qty) {
throw new Error(
'We are really sorry. We have not ' +
qty +
' amount of ' +
product.name +
' currently on stock. Either you wait for stock to fullfilled or you can decrease your ordered quantity of ' +
product.name,
)
}
product.countInStock -= qty
const updatedProduct = await product.save()
return updateProduct
})

module.exports = {
getProducts,
getProductById,
deleteProduct,
createProduct,
updateProduct,
updateStockCount,
}

0 comments on commit 54b2b78

Please sign in to comment.