Spaces:
Sleeping
Sleeping
File size: 8,974 Bytes
66821dd 8903e5f 66821dd 8903e5f 66821dd 8903e5f 66821dd 8903e5f 7392f82 8903e5f 7392f82 66821dd 7392f82 66821dd 8903e5f 66821dd 8903e5f 66821dd 8903e5f 66821dd 7392f82 8903e5f 66821dd 8903e5f 66821dd 8903e5f 66821dd 8903e5f 66821dd 8903e5f 66821dd 7392f82 66821dd 7392f82 66821dd 7392f82 66821dd 7392f82 66821dd 7392f82 66821dd 7392f82 66821dd 7392f82 66821dd 7392f82 66821dd 7392f82 66821dd 7392f82 66821dd 7392f82 66821dd | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 | 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 });
}
};
|