Spaces:
Running
Running
| 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, | |
| }; | |