MultiUsersSalesSystem / controller /productController.js
Mahmoud7456's picture
Upload 38 files
5f8e928 verified
Raw History Blame Contribute Delete
5.14 kB
import Product from "../models/ProductModel.js";
import { resolveBranchForWrite, resolveScopedBranch } from "../utils/branchContext.js";
const normalizeBarcode = (value) =>
value && value.trim() !== "" ? value.trim() : null;
export const createProduct = async (req, res) => {
try {
const { name, price, stock, description, barcode, sku, unit, category, lowStockThreshold, costPrice } = req.body;
const tenantId = req.user.tenant._id;
const branch = await resolveBranchForWrite(req);
const exists = await Product.findOne({
tenant: tenantId,
branch: branch._id,
$or: [{ name }, ...(barcode ? [{ barcode }] : [])],
});
if (exists) {
return res.status(400).json({ message: "المنتج موجود بالفعل" });
}
const product = await Product.create({
tenant: tenantId,
branch: branch._id,
name,
price,
stock,
description,
barcode: normalizeBarcode(barcode),
sku,
unit,
category: category || "عام",
lowStockThreshold: lowStockThreshold || req.user.tenant.settings?.lowStockThreshold || 5,
costPrice: costPrice || 0,
createdBy: req.user._id,
});
res.status(201).json(product);
} catch (error) {
res.status(500).json({ message: error.message });
}
};
export const getProducts = async (req, res) => {
try {
const page = parseInt(req.query.page) || 1;
const limit = parseInt(req.query.limit) || 5;
const skip = (page - 1) * limit;
const search = req.query.search || "";
const filter = req.query.filter || "all";
const defaultThreshold = Number(req.user.tenant.settings?.lowStockThreshold || 5);
const { tenantId, branchFilter } = await resolveScopedBranch(req);
const query = { tenant: tenantId, ...branchFilter };
if (search) {
query.name = { $regex: search, $options: "i" };
}
if (filter === "low") {
query.$expr = {
$lte: [
{ $toDouble: "$stock" },
{ $toDouble: { $ifNull: ["$lowStockThreshold", defaultThreshold] } },
],
};
} else if (filter === "available") {
query.$expr = {
$gt: [
{ $toDouble: "$stock" },
{ $toDouble: { $ifNull: ["$lowStockThreshold", defaultThreshold] } },
],
};
}
const total = await Product.countDocuments(query);
const products = await Product.find(query)
.sort({ createdAt: -1 })
.skip(skip)
.limit(limit);
res.status(200).json({
data: products.map((product) => ({
...product.toObject(),
isLowStock:
Number(product.stock) <=
Number(product.lowStockThreshold || defaultThreshold),
})),
pagination: {
total,
page,
limit,
totalPages: Math.ceil(total / limit),
},
});
} catch (error) {
res.status(500).json({ message: error.message });
}
};
export const updateProduct = async (req, res) => {
try {
const { id } = req.params;
const { name, price, stock, description, barcode, sku, unit, category, lowStockThreshold, costPrice } = req.body;
const { branchFilter } = await resolveScopedBranch(req);
const product = await Product.findOne({
_id: id,
tenant: req.user.tenant._id,
...branchFilter,
});
if (!product) {
return res.status(404).json({ message: "المنتج غير موجود" });
}
product.name = name ?? product.name;
product.price = price ?? product.price;
product.stock = stock ?? product.stock;
product.description = description ?? product.description;
product.barcode = barcode !== undefined ? normalizeBarcode(barcode) : product.barcode;
product.sku = sku ?? product.sku;
product.unit = unit ?? product.unit;
product.category = category ?? product.category;
product.lowStockThreshold = lowStockThreshold ?? product.lowStockThreshold;
product.costPrice = costPrice ?? product.costPrice;
await product.save();
res.status(200).json(product);
} catch (error) {
res.status(500).json({ message: error.message });
}
};
export const deleteProduct = async (req, res) => {
try {
const { id } = req.params;
const { branchFilter } = await resolveScopedBranch(req);
const product = await Product.findOneAndDelete({
_id: id,
tenant: req.user.tenant._id,
...branchFilter,
});
if (!product) {
return res.status(404).json({ message: "المنتج غير موجود" });
}
res.status(200).json({ message: "تم حذف المنتج بنجاح" });
} catch (error) {
res.status(500).json({ message: error.message });
}
};