import Product from "../models/ProductModel.js"; export const createProduct = async (req, res) => { try { const { name, price, stock, description, barcode, sku, unit, lowStockThreshold, costPrice } = req.body; const tenantId = req.user.tenant._id; const exists = await Product.findOne({ tenant: tenantId, $or: [{ name }, ...(barcode ? [{ barcode }] : [])], }); if (exists) { return res.status(400).json({ message: "المنتج موجود بالفعل" }); } const product = await Product.create({ tenant: tenantId, name, price, stock, description, barcode, sku, unit, 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 query = { tenant: req.user.tenant._id }; if (search) { query.name = { $regex: search, $options: "i" }; } 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 || req.user.tenant.settings?.lowStockThreshold || 5), })), 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, lowStockThreshold, costPrice } = req.body; const product = await Product.findOne({ _id: id, tenant: req.user.tenant._id, }); 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 ?? product.barcode; product.sku = sku ?? product.sku; product.unit = unit ?? product.unit; 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 product = await Product.findOneAndDelete({ _id: id, tenant: req.user.tenant._id, }); if (!product) { return res.status(404).json({ message: "المنج غير موجودلهف" }); } res.status(200).json({ message: "تم حذف المنتج بنجاح" }); } catch (error) { res.status(500).json({ message: error.message }); } };