MultiUsersSalesSystem / backend /controller /invoiceController.js
mahmoud
translate en validation errors to ar
7392f82
Raw History Blame
8.97 kB
import Invoice from "../models/InvoiceModel.js";
import Customer from "../models/CustomerModel.js";
import Product from "../models/ProductModel.js";
import Counter from "../models/CounterModel.js";
// Safe invoice number generator
const generateInvoiceNumber = async (tenantId) => {
const counter = await Counter.findOneAndUpdate(
{ tenant: tenantId },
{ $inc: { invoiceNumber: 1 } },
{ new: true, upsert: true }
);
return `INV-${String(counter.invoiceNumber).padStart(5, "0")}`;
};
export const addItemToInvoice = async (req, res) => {
try {
const { customerId } = req.params;
const { items } = req.body;
const tenantId = req.user.tenant?._id;
if (!tenantId) return res.status(403).json({ message: "لا يوجد مستأجر (Tenant) مرتبط بهذا الحساب" });
if (!Array.isArray(items) || items.length === 0)
return res.status(400).json({ message: "👉 يجب إدخال عنصر واحد على الأقل" });
const customer = await Customer.findOne({ _id: customerId, tenant: tenantId });
if (!customer) return res.status(404).json({ message: "العميل غير موجود" });
// Find open/partial invoice
let invoice = await Invoice.findOne({
customer: customerId,
tenant: tenantId,
status: { $in: ["open", "partial"] },
});
// If no invoice exists, create new with safe invoice number
if (!invoice) {
invoice = new Invoice({
tenant: tenantId,
customer: customerId,
invoiceNumber: await generateInvoiceNumber(tenantId),
issuedBy: req.user._id,
});
}
// Check stock availability
for (const item of items) {
if (item.productId) {
const product = await Product.findOne({ _id: item.productId, tenant: tenantId });
if (!product) return res.status(404).json({ message: `لا يوجد منتج بهذا الاسم: ${item.name}` });
if (product.stock < Number(item.quantity))
return res.status(400).json({
message: `Not enough stock for ${item.name}. Available: ${product.stock}`,
});
}
}
// Add items to invoice and update stock
for (const item of items) {
const quantity = Number(item.quantity || 0);
const price = Number(item.price || 0);
const total = quantity * price;
invoice.items.push({
name: item.name,
quantity,
price,
total,
...(item.productId ? { productId: item.productId } : {}),
});
if (item.productId) {
await Product.findOneAndUpdate(
{ _id: item.productId, tenant: tenantId },
{ $inc: { stock: -quantity } }
);
}
}
// Save invoice with updated totals
await invoice.save();
res.status(200).json(invoice);
} catch (err) {
console.log("❌ ERROR:", err.message);
console.log("❌ STACK:", err.stack);
res.status(500).json({ message: err.message });
}
};
export const getInvoices = 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.invoiceNumber = { $regex: search, $options: "i" };
}
const total = await Invoice.countDocuments(query);
const invoices = await Invoice.find(query)
.populate("customer")
.sort({ createdAt: -1 })
.skip(skip)
.limit(limit);
res.status(200).json({
data: invoices,
pagination: {
total,
page,
limit,
totalPages: Math.ceil(total / limit),
},
});
} catch (err) {
res.status(500).json({ message: err.message });
}
};
export const getInvoicesByCustomer = async (req, res) => {
try {
const invoices = await Invoice.find({
customer: req.params.customerId,
tenant: req.user.tenant._id,
});
res.json(invoices);
} catch (err) {
res.status(500).json({ message: err.message });
}
};
export const getInvoiceById = async (req, res) => {
try {
const { id } = req.params;
const invoice = await Invoice.findOne({
_id: id,
tenant: req.user.tenant._id,
})
.populate("customer", "name")
.populate({
path: "items.productId",
select: "name price", // fields from Product you want
});
if (!invoice) {
return res.status(404).json({ message: "👉 الفاتورة غير موجودة" });
}
res.status(200).json(invoice);
} catch (error) {
res.status(500).json({ message: error.message });
}
};
export const updateInvoiceItem = async (req, res) => {
try {
const { invoiceId, itemId } = req.params;
const { name, quantity, price } = req.body;
const invoice = await Invoice.findOne({
_id: invoiceId,
tenant: req.user.tenant._id,
});
if (!invoice) {
return res.status(404).json({ message: "👉 الفاتورة غير موجودة" });
}
const item = invoice.items.id(itemId);
if (!item) {
return res.status(404).json({ message: "👉 عنصر الفاتورة غير موجود" });
}
const newQuantity = Number(quantity);
const newPrice = Number(price);
if (item.productId) {
const quantityDifference = newQuantity - Number(item.quantity);
const product = await Product.findOne({
_id: item.productId,
tenant: req.user.tenant._id,
});
if (!product) {
return res.status(404).json({ message: "👉 المنتج المرتبط لم يعد موجودًا" });
}
if (quantityDifference > 0 && product.stock < quantityDifference) {
return res.status(400).json({ message: "👉 المخزون الحالي غير كافٍ لهذا التغيير في الكمية" });
}
if (quantityDifference !== 0) {
await Product.findOneAndUpdate(
{ _id: item.productId, tenant: req.user.tenant._id },
{ $inc: { stock: -quantityDifference } }
);
}
}
item.name = name;
item.quantity = newQuantity;
item.price = newPrice;
item.total = newQuantity * newPrice;
await invoice.save();
res.status(200).json({
message: "👉 تم تحديث عنصر الفاتورة بنجاح",
invoice,
});
} catch (error) {
res.status(500).json({ message: error.message });
}
};
export const deleteInvoiceItem = async (req, res) => {
try {
const { invoiceId, itemId } = req.params;
const invoice = await Invoice.findOne({
_id: invoiceId,
tenant: req.user.tenant._id,
});
if (!invoice) {
return res.status(404).json({ message: "👉 الفاتورة غير موجودة" });
}
const item = invoice.items.id(itemId);
if (!item) {
return res.status(404).json({ message: "👉 المنتج المرتبط لم يعد موجودًا" });
}
if (item.productId) {
await Product.findOneAndUpdate(
{ _id: item.productId, tenant: req.user.tenant._id },
{ $inc: { stock: Number(item.quantity) } }
);
}
item.deleteOne();
await invoice.save();
res.json(invoice);
} catch (error) {
res.status(500).json({ message: error.message });
}
};
export const payInvoice = async (req, res) => {
try {
const { customerId } = req.params;
const amount = Number(req.body.amount);
if (!amount || amount <= 0) {
return res.status(400).json({ message: "👉 يجب أن يكون مبلغ الدفع أكبر من صفر" });
}
const invoice = await Invoice.findOne({
customer: customerId,
tenant: req.user.tenant._id,
status: { $in: ["open", "partial"] },
});
if (!invoice || invoice.remainingAmount <= 0) {
return res.status(404).json({ message: "👉 لا توجد فاتورة مستحقة لهذا العميل" });
}
if (amount > invoice.remainingAmount) {
return res.status(400).json({ message: "👉 مبلغ الدفع أكبر من الرصيد المتبقي" });
}
invoice.payments.push({
amount,
method: req.body.paymentMethod || "cash",
receivedBy: req.user._id,
});
await invoice.save();
res.json(invoice);
} catch (err) {
res.status(500).json({ message: err.message });
}
};