import Supplier from "../models/SupplierModel.js"; import SupplierInvoice from "../models/SupplierInvoiceModel.js"; import Product from "../models/ProductModel.js"; import { resolveBranchForWrite, resolveScopedBranch } from "../utils/branchContext.js"; export const createSupplier = async (req, res) => { try { const name = req.body.name?.trim(); const tenantId = req.user.tenant._id; const branch = await resolveBranchForWrite(req); if (!name) { return res.status(400).json({ message: "اسم المورد مطلوب" }); } const exists = await Supplier.findOne({ tenant: tenantId, branch: branch._id, name: new RegExp(`^${name}$`, "i"), }); if (exists) { return res.status(400).json({ message: "هذا المورد موجود بالفعل" }); } const supplier = await Supplier.create({ tenant: tenantId, branch: branch._id, name, phone: req.body.phone?.trim() || "", whatsappNumber: req.body.whatsappNumber?.trim() || "", notes: req.body.notes?.trim() || "", createdBy: req.user._id, }); res.status(201).json(supplier); } catch (err) { res.status(500).json({ message: err.message }); } }; export const getSuppliers = async (req, res) => { try { const tenantId = req.user.tenant._id; const { branchFilter, branchId } = await resolveScopedBranch(req); 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 matchQuery = { tenant: tenantId, ...branchFilter, }; if (search) { matchQuery.name = { $regex: search, $options: "i" }; } const results = await Supplier.aggregate([ { $match: matchQuery }, { $facet: { data: [ { $sort: { createdAt: -1 } }, { $skip: skip }, { $limit: limit }, { $lookup: { from: "supplierinvoices", let: { supplierId: "$_id", tenantId: "$tenant", branchId: "$branch", }, pipeline: [ { $match: { $expr: { $and: [ { $eq: ["$supplier", "$$supplierId"] }, { $eq: ["$tenant", "$$tenantId"] }, ...(branchId ? [{ $eq: ["$branch", "$$branchId"] }] : []), ], }, }, }, ], as: "invoices", }, }, { $addFields: { totalDebt: { $sum: "$invoices.remainingAmount" }, }, }, ], totalCount: [{ $count: "count" }], }, }, ]); const suppliers = results[0].data; const total = results[0].totalCount[0]?.count || 0; res.status(200).json({ data: suppliers, pagination: { total, page, limit, totalPages: Math.ceil(total / limit), }, }); } catch (error) { res.status(500).json({ message: error.message }); } }; export const getSupplierById = async (req, res) => { try { const { branchFilter } = await resolveScopedBranch(req); const supplier = await Supplier.findOne({ _id: req.params.id, tenant: req.user.tenant._id, ...branchFilter, }); if (!supplier) { return res.status(404).json({ message: "المورد غير موجود" }); } const invoice = await SupplierInvoice.findOne({ supplier: supplier._id, tenant: req.user.tenant._id, ...branchFilter, }); res.status(200).json({ ...supplier.toObject(), invoice }); } catch (error) { res.status(500).json({ message: error.message }); } }; export const deleteSupplier = async (req, res) => { try { const supplierId = req.params.id; const { branchFilter } = await resolveScopedBranch(req); await Supplier.findOneAndDelete({ _id: supplierId, tenant: req.user.tenant._id, ...branchFilter, }); await SupplierInvoice.deleteMany({ supplier: supplierId, tenant: req.user.tenant._id, ...branchFilter, }); res.status(200).json({ message: "تم حذف المورد وجميع فواتير الشراء المرتبطة به بنجاح", }); } catch (error) { res.status(500).json({ message: error.message }); } }; export const addPurchasesToSupplier = async (req, res) => { try { const { items } = req.body; const supplierId = req.params.id; const tenantId = req.user.tenant._id; const branch = await resolveBranchForWrite(req); const branchId = branch._id; const supplier = await Supplier.findOne({ _id: supplierId, tenant: tenantId, branch: branchId, }); if (!supplier) { return res.status(404).json({ message: "المورد غير موجود" }); } let invoice = await SupplierInvoice.findOne({ supplier: supplierId, tenant: tenantId, branch: branchId, }); if (!invoice) { invoice = new SupplierInvoice({ supplier: supplierId, tenant: tenantId, branch: branchId, createdBy: req.user._id, }); } for (const item of items) { const quantity = Number(item.quantity || 0); const price = Number(item.price || 0); const total = price * quantity; invoice.items.push({ ...item, quantity, price, total, }); if (item.productId) { await Product.findOneAndUpdate( { _id: item.productId, tenant: tenantId, branch: branchId }, { $inc: { stock: quantity } } ); } } await invoice.save(); res.status(200).json(invoice); } catch (error) { res.status(500).json({ message: error.message }); } }; export const paySupplier = async (req, res) => { try { const amount = Number(req.body.amount); const supplierId = req.params.id; const { branchFilter } = await resolveScopedBranch(req); const invoice = await SupplierInvoice.findOne({ supplier: supplierId, tenant: req.user.tenant._id, ...branchFilter, }); if (!invoice) { return res.status(404).json({ message: "لا توجد فاتورة شراء لهذا المورد", }); } if (!amount || amount <= 0) { return res.status(400).json({ message: "يجب أن يكون مبلغ الدفع أكبر من صفر", }); } if (amount > invoice.remainingAmount) { return res.status(400).json({ message: "مبلغ الدفع أكبر من الرصيد المتبقي", }); } invoice.payments.push({ amount, date: new Date(), method: req.body.paymentMethod || "cash", paidBy: req.user._id, }); await invoice.save(); res.status(200).json(invoice); } catch (error) { res.status(500).json({ message: error.message }); } };