MultiUsersSalesSystem / controller /customerController.js
Mahmoud7456's picture
Upload 71 files
1e65df5 verified
Raw History Blame Contribute Delete
9.03 kB
import Customer from "../models/CustomerModel.js";
import Invoice from "../models/InvoiceModel.js";
import { resolveBranchForWrite, resolveScopedBranch } from "../utils/branchContext.js";
import { normalizeCustomerName, normalizeCustomerPhone } from "../utils/customerNormalization.js";
export const createCustomer = async (req, res) => {
try {
const tenantId = req.user.tenant._id;
const branch = await resolveBranchForWrite(req);
const name = req.body.name?.trim();
const normalizedName = normalizeCustomerName(name);
const normalizedPhone = normalizeCustomerPhone(req.body.phone);
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,
branch: branch._id,
...(normalizedPhone
? { phone: normalizedPhone }
: { normalizedName }),
isDeleted: false,
isWalkIn: { $ne: true },
});
if (exists) {
return res.status(400).json({ message: "العميل موجود بالفعل" });
}
const customer = await Customer.create({
tenant: tenantId,
branch: branch._id,
name,
phone: normalizedPhone || "",
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 { 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 showDeleted = req.query.deleted === "true";
if (showDeleted && !["owner", "admin"].includes(req.user.role)) {
return res.status(403).json({ message: "ليس لديك صلاحية عرض العملاء المحذوفين" });
}
const matchQuery = {
tenant: tenantId,
...branchFilter,
isDeleted: showDeleted,
isWalkIn: { $ne: true },
};
if (search) {
const normalizedSearch = normalizeCustomerName(search);
matchQuery.$or = [
{ name: { $regex: search, $options: "i" } },
{ normalizedName: { $regex: normalizedSearch, $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",
branchId: "$branch",
},
pipeline: [
{
$match: {
$expr: {
$and: [
{ $eq: ["$customer", "$$customerId"] },
{ $eq: ["$tenant", "$$tenantId"] },
...(branchId ? [{ $eq: ["$branch", "$$branchId"] }] : []),
],
},
},
},
],
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 { branchFilter } = await resolveScopedBranch(req);
const customer = await Customer.findOne({
_id: req.params.id,
tenant: req.user.tenant._id,
...branchFilter,
});
if (!customer) {
return res.status(404).json({ message: "العميل غير موجود" });
}
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 statusFilter = req.query.status && req.query.status !== "all"
? { status: req.query.status }
: {};
const invoiceQuery = {
customer: customer._id,
tenant: req.user.tenant._id,
isDeleted: false,
...branchFilter,
...statusFilter,
};
const totalInvoices = await Invoice.countDocuments(invoiceQuery);
const invoices = await Invoice.find(invoiceQuery)
.populate("items.productId", "name price")
.populate("items.catalogItemId", "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 { branchFilter } = await resolveScopedBranch(req);
const deletedCustomer = await Customer.findOneAndUpdate(
{
_id: customerId,
tenant: req.user.tenant._id,
...branchFilter,
isDeleted: false,
isWalkIn: { $ne: true },
},
{
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,
...branchFilter,
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 { branchFilter } = await resolveScopedBranch(req);
const restoredCustomer = await Customer.findOneAndUpdate(
{
_id: customerId,
tenant: req.user.tenant._id,
...branchFilter,
isDeleted: true,
isWalkIn: { $ne: 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,
...branchFilter,
isDeleted: true,
},
{ isDeleted: false }
);
res.status(200).json({ message: "تم استعادة العميل مع جميع الفواتير المرتبطة به" });
} catch (error) {
res.status(500).json({ message: error.message });
}
};