86 lines
2.5 KiB
JavaScript
86 lines
2.5 KiB
JavaScript
const Product = require('../models/Product');
|
|
const InventoryHistory = require('../models/InventoryHistory');
|
|
const { successResponse, errorResponse } = require('../utils/apiResponse');
|
|
|
|
// @desc Get stock overview & alerts (Admin)
|
|
// @route GET /api/inventory/overview
|
|
// @access Private/Admin
|
|
const getStockOverview = async (req, res, next) => {
|
|
try {
|
|
const products = await Product.find({})
|
|
.select('name sku stock lowStockThreshold price category brand images')
|
|
.populate('category', 'name')
|
|
.populate('brand', 'name');
|
|
|
|
const lowStock = products.filter(p => p.stock > 0 && p.stock <= p.lowStockThreshold);
|
|
const outOfStock = products.filter(p => p.stock === 0);
|
|
|
|
return successResponse(res, 'Stock overview retrieved', {
|
|
totalProducts: products.length,
|
|
lowStockCount: lowStock.length,
|
|
outOfStockCount: outOfStock.length,
|
|
lowStock,
|
|
outOfStock,
|
|
products
|
|
});
|
|
} catch (error) {
|
|
next(error);
|
|
}
|
|
};
|
|
|
|
// @desc Adjust inventory stock level (Admin)
|
|
// @route POST /api/inventory/adjust
|
|
// @access Private/Admin
|
|
const adjustStock = async (req, res, next) => {
|
|
try {
|
|
const { productId, newStock, reason, changeType = 'Manual Adjustment' } = req.body;
|
|
|
|
const product = await Product.findById(productId);
|
|
if (!product) {
|
|
return errorResponse(res, 'Product not found', [], 404);
|
|
}
|
|
|
|
const previousStock = product.stock;
|
|
const quantityChanged = Number(newStock) - previousStock;
|
|
|
|
product.stock = Number(newStock);
|
|
await product.save();
|
|
|
|
// Log history
|
|
const history = await InventoryHistory.create({
|
|
product: product._id,
|
|
sku: product.sku,
|
|
changeType,
|
|
quantityChanged,
|
|
previousStock,
|
|
newStock: product.stock,
|
|
reason: reason || 'Manual admin inventory adjustment',
|
|
performedBy: req.user._id
|
|
});
|
|
|
|
return successResponse(res, 'Stock adjusted successfully', { product, history });
|
|
} catch (error) {
|
|
next(error);
|
|
}
|
|
};
|
|
|
|
// @desc Get complete inventory change audit log (Admin)
|
|
// @route GET /api/inventory/history
|
|
// @access Private/Admin
|
|
const getInventoryHistory = async (req, res, next) => {
|
|
try {
|
|
const history = await InventoryHistory.find({})
|
|
.populate('product', 'name images')
|
|
.populate('performedBy', 'name email')
|
|
.sort({ createdAt: -1 })
|
|
.limit(100);
|
|
|
|
return successResponse(res, 'Inventory history audit log retrieved', history);
|
|
} catch (error) {
|
|
next(error);
|
|
}
|
|
};
|
|
|
|
module.exports = { getStockOverview, adjustStock, getInventoryHistory };
|
|
|