Spaces:
Sleeping
Sleeping
Download backend/controller/customerController.js from Mahmoud7456/MultiUsersSalesSystem: direct link, hf CLI and curl.
- Browser
- Download file 7.19 kB
-
https://huggingface.co/spaces/Mahmoud7456/MultiUsersSalesSystem/resolve/hf/backend/controller/customerController.js
- Command line
-
hf download hf://spaces/Mahmoud7456/MultiUsersSalesSystem@hf/backend/controller/customerController.js
-
curl -L -o customerController.js https://huggingface.co/spaces/Mahmoud7456/MultiUsersSalesSystem/resolve/hf/backend/controller/customerController.js
7.19 kB
| import Customer from "../models/CustomerModel.js"; | |
| import Invoice from "../models/InvoiceModel.js"; | |
| export const createCustomer = async (req, res) => { | |
| try { | |
| const tenantId = req.user.tenant._id; | |
| const name = req.body.name?.trim(); | |
| if (!name) { | |
| return res.status(400).json({ message: "اسم العميل مطلوب" }); | |
| } | |
| if (name.length < 3) { | |
| return res.status(400).json({ message: "اسم العميل يجب أن يكون 3 أحرف على الأقل" }); | |
| } | |
| const exists = await Customer.findOne({ | |
| tenant: tenantId, | |
| name: new RegExp(`^${name}$`, "i"), | |
| isDeleted: false, | |
| }); | |
| if (exists) { | |
| return res.status(400).json({ message: "العميل موجود بالفعل" }); | |
| } | |
| const customer = await Customer.create({ | |
| tenant: tenantId, | |
| name, | |
| phone: req.body.phone?.trim() || "", | |
| email: req.body.email?.trim()?.toLowerCase() || "", | |
| address: req.body.address?.trim() || "", | |
| notes: req.body.notes?.trim() || "", | |
| createdBy: req.user._id, | |
| }); | |
| res.status(201).json(customer); | |
| } catch (err) { | |
| res.status(500).json({ message: err.message }); | |
| } | |
| }; | |
| export const getCustomers = async (req, res) => { | |
| try { | |
| const tenantId = req.user.tenant._id; | |
| 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 showDeleted = req.query.deleted === "true"; | |
| if (showDeleted && !["owner", "admin"].includes(req.user.role)) { | |
| return res.status(403).json({ message: "ليس لديك صلاحية عرض العملاء المحذوفين" }); | |
| } | |
| const matchQuery = { | |
| tenant: tenantId, | |
| isDeleted: showDeleted, | |
| }; | |
| if (search) { | |
| matchQuery.name = { $regex: search, $options: "i" }; | |
| } | |
| const results = await Customer.aggregate([ | |
| { $match: matchQuery }, | |
| { | |
| $facet: { | |
| data: [ | |
| { $sort: { createdAt: -1 } }, | |
| { $skip: skip }, | |
| { $limit: limit }, | |
| { | |
| $lookup: { | |
| from: "invoices", | |
| let: { | |
| customerId: "$_id", | |
| tenantId: "$tenant", | |
| }, | |
| pipeline: [ | |
| { | |
| $match: { | |
| $expr: { | |
| $and: [ | |
| { $eq: ["$customer", "$$customerId"] }, | |
| { $eq: ["$tenant", "$$tenantId"] }, | |
| ], | |
| }, | |
| }, | |
| }, | |
| ], | |
| as: "invoices", | |
| }, | |
| }, | |
| { | |
| $addFields: { | |
| totalInvoicesAmount: { $sum: "$invoices.totalAmount" }, | |
| totalDebt: { $sum: "$invoices.remainingAmount" }, | |
| }, | |
| }, | |
| ], | |
| totalCount: [ | |
| { $count: "count" } | |
| ] | |
| } | |
| } | |
| ]); | |
| const customers = results[0].data; | |
| const total = results[0].totalCount[0]?.count || 0; | |
| res.status(200).json({ | |
| data: customers, | |
| pagination: { | |
| total, | |
| page, | |
| limit, | |
| totalPages: Math.ceil(total / limit), | |
| }, | |
| }); | |
| } catch (error) { | |
| res.status(500).json({ message: error.message }); | |
| } | |
| }; | |
| export const getCustomerById = async (req, res) => { | |
| try { | |
| const customer = await Customer.findOne({ | |
| _id: req.params.id, | |
| tenant: req.user.tenant._id, | |
| }); | |
| if (!customer) { | |
| return res.status(404).json({ message: "العميل غير موجود" }); | |
| } | |
| // Pagination & Sorting | |
| const page = parseInt(req.query.page) || 1; | |
| const limit = parseInt(req.query.limit) || 5; | |
| const sortField = req.query.sortField || "createdAt"; | |
| const sortOrder = req.query.sortOrder === "asc" ? 1 : -1; | |
| const skip = (page - 1) * limit; | |
| const totalInvoices = await Invoice.countDocuments({ | |
| customer: customer._id, | |
| tenant: req.user.tenant._id, | |
| }); | |
| const invoices = await Invoice.find({ | |
| customer: customer._id, | |
| tenant: req.user.tenant._id, | |
| isDeleted: false, | |
| }) | |
| .populate("items.productId", "name price") | |
| .sort({ [sortField]: sortOrder }) | |
| .skip(skip) | |
| .limit(limit); | |
| res.status(200).json({ | |
| ...customer.toObject(), | |
| invoices, | |
| pagination: { | |
| total: totalInvoices, | |
| page, | |
| limit, | |
| totalPages: Math.ceil(totalInvoices / limit), | |
| }, | |
| }); | |
| } catch (error) { | |
| res.status(500).json({ message: error.message }); | |
| } | |
| }; | |
| export const deleteCustomer = async (req, res) => { | |
| try { | |
| const customerId = req.params.id; | |
| const deletedCustomer = await Customer.findOneAndUpdate( | |
| { | |
| _id: customerId, | |
| tenant: req.user.tenant._id, | |
| isDeleted: false, | |
| }, | |
| { | |
| isDeleted: true, | |
| deletedAt: new Date(), | |
| }, | |
| { new: true } | |
| ); | |
| if (!deletedCustomer) { | |
| return res.status(404).json({ message: "العميل غير موجود أو تم حذفه مسبقاً" }); | |
| } | |
| await Invoice.updateMany( | |
| { | |
| customer: customerId, | |
| tenant: req.user.tenant._id, | |
| isDeleted: false, | |
| }, | |
| { isDeleted: true } | |
| ); | |
| res.status(200).json({ message: "تم حذف العميل وأرشفة الفواتير المرتبطة به بنجاح" }); | |
| } catch (error) { | |
| res.status(500).json({ message: error.message }); | |
| } | |
| }; | |
| export const restoreCustomer = async (req, res) => { | |
| try { | |
| const customerId = req.params.id; | |
| const restoredCustomer = await Customer.findOneAndUpdate( | |
| { | |
| _id: customerId, | |
| tenant: req.user.tenant._id, | |
| isDeleted: true, | |
| }, | |
| { | |
| isDeleted: false, | |
| deletedAt: null, | |
| }, | |
| { new: true } | |
| ); | |
| if (!restoredCustomer) { | |
| return res.status(404).json({ message: "العميل المحذوف غير موجود" }); | |
| } | |
| await Invoice.updateMany( | |
| { | |
| customer: customerId, | |
| tenant: req.user.tenant._id, | |
| isDeleted: true, | |
| }, | |
| { isDeleted: false } | |
| ); | |
| res.status(200).json({ message: "تم استعادة العميل مع جميع الفواتير المرتبطة به" }); | |
| } catch (error) { | |
| res.status(500).json({ message: error.message }); | |
| } | |
| }; |