samoulla-backend / utils /orderUtils.js
Samoulla Sync Bot
Auto-deploy Samoulla Backend: 8574a71f0fc617aeb1ce9b5e35dac24c5319a12a
59c49c1
const Product = require('../models/productModel');
/**
* Restore stock for a group of items (usually from a cancelled order)
* @param {Array} items - Array of order items with product and quantity
*/
const restoreOrderStock = async (items) => {
const bulkOps = items
.filter((item) => item.product)
.map((item) => {
const productId = item.product._id || item.product;
return {
updateOne: {
filter: { _id: productId },
update: { $inc: { stock: item.quantity } },
},
};
});
if (bulkOps.length > 0) {
await Product.bulkWrite(bulkOps);
}
};
/**
* Deduct stock for a group of items (usually for a new order)
* @param {Array} items - Array of order items with product and quantity
*/
const deductOrderStock = async (items) => {
const bulkOps = items
.filter((item) => item.product)
.map((item) => {
const productId = item.product._id || item.product;
return {
updateOne: {
filter: { _id: productId },
update: { $inc: { stock: -item.quantity } },
},
};
});
if (bulkOps.length > 0) {
await Product.bulkWrite(bulkOps);
}
};
module.exports = {
restoreOrderStock,
deductOrderStock,
};