Fixed updating of stock and stopped duplication on page refresh

master
Mark Moffat 2020-03-20 19:58:15 +10:30
parent 8314b7686f
commit 5f68a5bc1f
1 changed files with 29 additions and 15 deletions

View File

@ -36,22 +36,36 @@ router.get('/payment/:orderId', async (req, res, next) => {
// If stock management is turned on payment approved update stock level // If stock management is turned on payment approved update stock level
if(config.trackStock && req.session.paymentApproved){ if(config.trackStock && req.session.paymentApproved){
order.orderProducts.forEach(async (product) => { // Check to see if already updated to avoid duplicate updating of stock
const dbProduct = await db.products.findOne({ _id: getId(product.productId) }); if(order.productStockUpdated !== true){
let newStockLevel = dbProduct.productStock - product.quantity; Object.keys(order.orderProducts).forEach(async (productKey) => {
if(newStockLevel < 1){ const product = order.orderProducts[productKey];
newStockLevel = 0; const dbProduct = await db.products.findOne({ _id: getId(product.productId) });
} let newStockLevel = dbProduct.productStock - product.quantity;
if(newStockLevel < 1){
// Update product stock newStockLevel = 0;
await db.products.updateOne({
_id: getId(product.productId)
}, {
$set: {
productStock: newStockLevel
} }
}, { multi: false });
}); // Update product stock
await db.products.updateOne({
_id: getId(product.productId)
}, {
$set: {
productStock: newStockLevel
}
}, { multi: false });
// Add stock updated flag to order
await db.orders.updateOne({
_id: getId(order._id)
}, {
$set: {
productStockUpdated: true
}
}, { multi: false });
});
console.info('Updated stock levels');
}
} }
// If hooks are configured, send hook // If hooks are configured, send hook