import CatalogCategory from "../models/CatalogCategoryModel.js"; import CatalogItem from "../models/CatalogItemModel.js"; import { resolveBranchForWrite, resolveScopedBranch } from "../utils/branchContext.js"; const normalizeName = (value) => String(value || "").trim(); const getScopedCategory = async ({ categoryId, tenantId, branchId }) => { if (!categoryId) { return null; } return CatalogCategory.findOne({ _id: categoryId, tenant: tenantId, branch: branchId, }); }; export const getCatalogCategories = async (req, res) => { try { const search = normalizeName(req.query.search); const activeOnly = req.query.activeOnly === "true"; const { tenantId, branchFilter } = await resolveScopedBranch(req); const query = { tenant: tenantId, ...branchFilter, }; if (search) { query.name = { $regex: search, $options: "i" }; } if (activeOnly) { query.isActive = true; } const categories = await CatalogCategory.find(query).sort({ sortOrder: 1, name: 1 }); res.status(200).json({ data: categories }); } catch (error) { res.status(500).json({ message: error.message }); } }; export const createCatalogCategory = async (req, res) => { try { const branch = await resolveBranchForWrite(req); const tenantId = req.user.tenant._id; const name = normalizeName(req.body.name); if (!name) { return res.status(400).json({ message: "اسم الفئة مطلوب" }); } const existing = await CatalogCategory.findOne({ tenant: tenantId, branch: branch._id, name, }); if (existing) { return res.status(400).json({ message: "الفئة موجودة بالفعل" }); } const category = await CatalogCategory.create({ tenant: tenantId, branch: branch._id, name, description: normalizeName(req.body.description), sortOrder: Number(req.body.sortOrder || 0), isActive: req.body.isActive ?? true, createdBy: req.user._id, }); res.status(201).json(category); } catch (error) { res.status(500).json({ message: error.message }); } }; export const updateCatalogCategory = async (req, res) => { try { const { branchFilter } = await resolveScopedBranch(req); const category = await CatalogCategory.findOne({ _id: req.params.id, tenant: req.user.tenant._id, ...branchFilter, }); if (!category) { return res.status(404).json({ message: "الفئة غير موجودة" }); } const nextName = normalizeName(req.body.name); if (nextName && nextName !== category.name) { const duplicate = await CatalogCategory.findOne({ _id: { $ne: category._id }, tenant: category.tenant, branch: category.branch, name: nextName, }); if (duplicate) { return res.status(400).json({ message: "اسم الفئة مستخدم بالفعل" }); } category.name = nextName; } if (req.body.description !== undefined) { category.description = normalizeName(req.body.description); } if (req.body.sortOrder !== undefined) { category.sortOrder = Number(req.body.sortOrder || 0); } if (req.body.isActive !== undefined) { category.isActive = Boolean(req.body.isActive); } await category.save(); res.status(200).json(category); } catch (error) { res.status(500).json({ message: error.message }); } }; export const deleteCatalogCategory = async (req, res) => { try { const { branchFilter } = await resolveScopedBranch(req); const category = await CatalogCategory.findOne({ _id: req.params.id, tenant: req.user.tenant._id, ...branchFilter, }); if (!category) { return res.status(404).json({ message: "الفئة غير موجودة" }); } const linkedItems = await CatalogItem.countDocuments({ tenant: req.user.tenant._id, category: category._id, ...branchFilter, }); if (linkedItems > 0) { return res.status(400).json({ message: "احذف عناصر الفئة أولاً قبل حذفها" }); } await category.deleteOne(); res.status(200).json({ message: "تم حذف الفئة بنجاح" }); } catch (error) { res.status(500).json({ message: error.message }); } }; export const getCatalogItems = async (req, res) => { try { const page = Math.max(1, parseInt(req.query.page) || 1); const limit = Math.max(1, parseInt(req.query.limit) || 20); const skip = (page - 1) * limit; const search = normalizeName(req.query.search); const categoryId = req.query.categoryId || ""; const activeOnly = req.query.activeOnly === "true"; const { tenantId, branchFilter } = await resolveScopedBranch(req); const query = { tenant: tenantId, ...branchFilter, }; if (search) { query.name = { $regex: search, $options: "i" }; } if (categoryId) { query.category = categoryId; } if (activeOnly) { query.isActive = true; } const total = await CatalogItem.countDocuments(query); const items = await CatalogItem.find(query) .populate("category", "name") .sort({ sortOrder: 1, createdAt: -1 }) .skip(skip) .limit(limit); res.status(200).json({ data: items.map((item) => ({ ...item.toObject(), categoryName: item.category?.name || "", })), pagination: { total, page, limit, totalPages: Math.ceil(total / limit), }, }); } catch (error) { res.status(500).json({ message: error.message }); } }; export const createCatalogItem = async (req, res) => { try { const branch = await resolveBranchForWrite(req); const tenantId = req.user.tenant._id; const name = normalizeName(req.body.name); if (!name) { return res.status(400).json({ message: "اسم العنصر مطلوب" }); } const category = await getScopedCategory({ categoryId: req.body.categoryId, tenantId, branchId: branch._id, }); if (!category) { return res.status(400).json({ message: "فئة الكتالوج غير موجودة" }); } const duplicate = await CatalogItem.findOne({ tenant: tenantId, branch: branch._id, category: category._id, name, }); if (duplicate) { return res.status(400).json({ message: "العنصر موجود بالفعل داخل هذه الفئة" }); } const item = await CatalogItem.create({ tenant: tenantId, branch: branch._id, category: category._id, name, description: normalizeName(req.body.description), price: Number(req.body.price || 0), costPrice: Number(req.body.costPrice || 0), sortOrder: Number(req.body.sortOrder || 0), isActive: req.body.isActive ?? true, createdBy: req.user._id, }); const populated = await CatalogItem.findById(item._id).populate("category", "name"); res.status(201).json({ ...populated.toObject(), categoryName: populated.category?.name || "", }); } catch (error) { res.status(500).json({ message: error.message }); } }; export const updateCatalogItem = async (req, res) => { try { const { branchFilter, branchId } = await resolveScopedBranch(req); const item = await CatalogItem.findOne({ _id: req.params.id, tenant: req.user.tenant._id, ...branchFilter, }); if (!item) { return res.status(404).json({ message: "عنصر الكتالوج غير موجود" }); } if (req.body.categoryId && String(req.body.categoryId) !== String(item.category)) { const targetCategory = await getScopedCategory({ categoryId: req.body.categoryId, tenantId: req.user.tenant._id, branchId, }); if (!targetCategory) { return res.status(400).json({ message: "فئة الكتالوج غير موجودة" }); } item.category = targetCategory._id; } const nextName = normalizeName(req.body.name); if (nextName && nextName !== item.name) { const duplicate = await CatalogItem.findOne({ _id: { $ne: item._id }, tenant: item.tenant, branch: item.branch, category: item.category, name: nextName, }); if (duplicate) { return res.status(400).json({ message: "اسم العنصر مستخدم بالفعل داخل هذه الفئة" }); } item.name = nextName; } if (req.body.description !== undefined) { item.description = normalizeName(req.body.description); } if (req.body.price !== undefined) { item.price = Number(req.body.price || 0); } if (req.body.costPrice !== undefined) { item.costPrice = Number(req.body.costPrice || 0); } if (req.body.sortOrder !== undefined) { item.sortOrder = Number(req.body.sortOrder || 0); } if (req.body.isActive !== undefined) { item.isActive = Boolean(req.body.isActive); } await item.save(); const populated = await CatalogItem.findById(item._id).populate("category", "name"); res.status(200).json({ ...populated.toObject(), categoryName: populated.category?.name || "", }); } catch (error) { res.status(500).json({ message: error.message }); } }; export const deleteCatalogItem = async (req, res) => { try { const { branchFilter } = await resolveScopedBranch(req); const item = await CatalogItem.findOneAndDelete({ _id: req.params.id, tenant: req.user.tenant._id, ...branchFilter, }); if (!item) { return res.status(404).json({ message: "عنصر الكتالوج غير موجود" }); } res.status(200).json({ message: "تم حذف عنصر الكتالوج بنجاح" }); } catch (error) { res.status(500).json({ message: error.message }); } };