Mahmoud7456 commited on
Commit
2671db8
·
verified ·
1 Parent(s): 4946913

Upload 18 files

Browse files
controller/invoiceController.js CHANGED
@@ -6,15 +6,22 @@ import Income from "../models/IncomeModel.js";
6
 
7
  const WALK_IN_CUSTOMER_NAME = "Walking-in Customer";
8
 
9
- const generateInvoiceNumber = async (tenantId) => {
 
10
  const counter = await Counter.findOneAndUpdate(
11
  { tenant: tenantId },
12
  { $inc: { invoiceNumber: 1 } },
13
- { new: true, upsert: true }
 
 
 
 
14
  );
15
 
16
- return `INV-${String(counter.invoiceNumber).padStart(5, "0")}`;
17
- };
 
 
18
 
19
  const getOrCreateWalkInCustomer = async (tenantId, userId) => {
20
  let customer = await Customer.findOne({ tenant: tenantId, isWalkIn: true });
@@ -96,9 +103,10 @@ const createIncomeForPayment = async ({ tenantId, invoice, customer, amount, use
96
  };
97
 
98
  export const addItemToInvoice = async (req, res) => {
 
99
  try {
100
  const { customerId } = req.params;
101
- const { items } = req.body;
102
  const tenantId = req.user.tenant?._id;
103
 
104
  if (!tenantId) {
@@ -108,43 +116,67 @@ export const addItemToInvoice = async (req, res) => {
108
  return res.status(400).json({ message: "يجب إضافة صنف واحد على الأقل" });
109
  }
110
 
111
- const customer = await Customer.findOne({ _id: customerId, tenant: tenantId });
 
 
 
 
 
 
 
112
  if (!customer) {
 
113
  return res.status(404).json({ message: "العميل غير موجود" });
114
  }
115
  if (customer.isWalkIn) {
 
116
  return res.status(400).json({ message: "استخدم مسار بيع الزائر النقدي لفواتير العملاء الزائرين" });
117
  }
118
 
119
- let invoice = await Invoice.findOne({
120
- customer: customerId,
121
- tenant: tenantId,
122
- status: { $in: ["open", "partial"] },
123
- });
124
-
125
- if (!invoice) {
126
- invoice = new Invoice({
127
  tenant: tenantId,
128
- customer: customerId,
129
- invoiceNumber: await generateInvoiceNumber(tenantId),
130
  issuedBy: req.user._id,
 
131
  });
132
- }
133
 
134
- await ensureStockAvailability(items, tenantId);
135
- await applyInvoiceItemsAndStock(invoice, items, tenantId);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
136
 
137
- await invoice.save();
138
- res.status(200).json(invoice);
 
 
 
 
 
139
  } catch (err) {
 
140
  res.status(err.statusCode || 500).json({ message: err.message });
141
  }
142
  };
143
 
144
  export const createWalkInCashSale = async (req, res) => {
 
145
  try {
146
  const tenantId = req.user.tenant?._id;
147
- const { items, paidAmount, notes = "" } = req.body;
148
 
149
  if (!tenantId) {
150
  return res.status(403).json({ message: "لا يوجد مستأجر مرتبط بهذا الحساب" });
@@ -153,46 +185,76 @@ export const createWalkInCashSale = async (req, res) => {
153
  return res.status(400).json({ message: "يجب إضافة صنف واحد على الأقل" });
154
  }
155
 
156
- await ensureStockAvailability(items, tenantId);
 
 
 
 
157
 
158
- const customer = await getOrCreateWalkInCustomer(tenantId, req.user._id);
159
- const invoice = new Invoice({
160
- tenant: tenantId,
161
- customer: customer._id,
162
- invoiceNumber: await generateInvoiceNumber(tenantId),
163
- issuedBy: req.user._id,
164
- notes: notes.trim(),
165
- });
166
 
167
- await applyInvoiceItemsAndStock(invoice, items, tenantId);
168
- invoice.calculateTotals();
 
 
 
 
 
169
 
170
- const paymentAmount = Number(paidAmount);
171
- if (!paymentAmount || Number(paymentAmount.toFixed(2)) !== Number(invoice.totalAmount.toFixed(2))) {
172
- return res.status(400).json({
173
- message: "فاتورة الزائر يجب أن تكون نقدية بالكامل، ويجب أن يساوي المبلغ المدفوع إجمالي الفاتورة",
 
174
  });
175
- }
176
 
177
- invoice.payments.push({
178
- amount: paymentAmount,
179
- method: "cash",
180
- receivedBy: req.user._id,
181
- });
 
 
 
 
 
 
 
 
 
 
 
182
 
183
- await invoice.save();
184
- await createIncomeForPayment({
185
- tenantId,
186
- invoice,
187
- customer,
188
- amount: paymentAmount,
189
- userId: req.user._id,
190
- notes: "Walk-in cash sale",
191
- });
 
192
 
193
- const populatedInvoice = await Invoice.findById(invoice._id).populate("customer", "name isWalkIn");
194
- res.status(201).json(populatedInvoice);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
195
  } catch (err) {
 
196
  res.status(err.statusCode || 500).json({ message: err.message });
197
  }
198
  };
@@ -280,9 +342,6 @@ export const updateInvoiceItem = async (req, res) => {
280
  if (!invoice) {
281
  return res.status(404).json({ message: "الفاتورة غير موجودة" });
282
  }
283
- if (invoice.customer?.isWalkIn) {
284
- return res.status(400).json({ message: "لا يمكن تعديل فاتورة الزائر النقدية بعد حفظها" });
285
- }
286
 
287
  const item = invoice.items.id(itemId);
288
  if (!item) {
@@ -343,9 +402,6 @@ export const deleteInvoiceItem = async (req, res) => {
343
  if (!invoice) {
344
  return res.status(404).json({ message: "الفاتورة غير موجودة" });
345
  }
346
- if (invoice.customer?.isWalkIn) {
347
- return res.status(400).json({ message: "لا يمكن تعديل فاتورة الزائر النقدية بعد حفظها" });
348
- }
349
 
350
  const item = invoice.items.id(itemId);
351
  if (!item) {
@@ -414,4 +470,4 @@ export const payInvoice = async (req, res) => {
414
  } catch (err) {
415
  res.status(500).json({ message: err.message });
416
  }
417
- };
 
6
 
7
  const WALK_IN_CUSTOMER_NAME = "Walking-in Customer";
8
 
9
+
10
+ async function generateInvoiceNumber(tenantId) {
11
  const counter = await Counter.findOneAndUpdate(
12
  { tenant: tenantId },
13
  { $inc: { invoiceNumber: 1 } },
14
+ {
15
+ new: true,
16
+ upsert: true,
17
+ setDefaultsOnInsert: true
18
+ }
19
  );
20
 
21
+ const padded = String(counter.invoiceNumber).padStart(5, '0');
22
+ return `INV-${padded}`;
23
+ }
24
+
25
 
26
  const getOrCreateWalkInCustomer = async (tenantId, userId) => {
27
  let customer = await Customer.findOne({ tenant: tenantId, isWalkIn: true });
 
103
  };
104
 
105
  export const addItemToInvoice = async (req, res) => {
106
+ let createdCustomer = null;
107
  try {
108
  const { customerId } = req.params;
109
+ const { items, customerName, notes = "" } = req.body;
110
  const tenantId = req.user.tenant?._id;
111
 
112
  if (!tenantId) {
 
116
  return res.status(400).json({ message: "يجب إضافة صنف واحد على الأقل" });
117
  }
118
 
119
+ let finalCustomerId = customerId;
120
+ if (customerId === "new") {
121
+ if (!customerName) return res.status(400).json({ message: "اسم العميل مطلوب لإنشاء حساب جديد" });
122
+ createdCustomer = await Customer.create({ name: customerName.trim(), tenant: tenantId, createdBy: req.user._id });
123
+ finalCustomerId = createdCustomer._id;
124
+ }
125
+
126
+ const customer = await Customer.findOne({ _id: finalCustomerId, tenant: tenantId });
127
  if (!customer) {
128
+ if (createdCustomer) await Customer.deleteOne({ _id: createdCustomer._id });
129
  return res.status(404).json({ message: "العميل غير موجود" });
130
  }
131
  if (customer.isWalkIn) {
132
+ if (createdCustomer) await Customer.deleteOne({ _id: createdCustomer._id });
133
  return res.status(400).json({ message: "استخدم مسار بيع الزائر النقدي لفواتير العملاء الزائرين" });
134
  }
135
 
136
+ try {
137
+ const invoice = new Invoice({
 
 
 
 
 
 
138
  tenant: tenantId,
139
+ customer: finalCustomerId,
 
140
  issuedBy: req.user._id,
141
+ notes: notes.trim(),
142
  });
 
143
 
144
+ await ensureStockAvailability(items, tenantId);
145
+ await applyInvoiceItemsAndStock(invoice, items, tenantId);
146
+
147
+ // Robust duplicate key retry logic for missing/corrupted counters
148
+ let saved = false;
149
+ for (let i = 0; i < 3; i++) {
150
+ try {
151
+ invoice.invoiceNumber = await generateInvoiceNumber(tenantId);
152
+ invoice.calculateTotals();
153
+ await invoice.save();
154
+ saved = true;
155
+ break;
156
+ } catch (saveErr) {
157
+ if (saveErr.code === 11000 && i < 2) continue; // Retry
158
+ throw saveErr;
159
+ }
160
+ }
161
 
162
+ if (!saved) throw new Error("تعذر حفظ الفاتورة لخطأ تزامن، حاول مجدداً");
163
+
164
+ res.status(200).json(invoice);
165
+ } catch (err) {
166
+ if (createdCustomer) await Customer.deleteOne({ _id: createdCustomer._id });
167
+ throw err; // cascade to main catch block
168
+ }
169
  } catch (err) {
170
+ if (createdCustomer) await Customer.deleteOne({ _id: createdCustomer._id });
171
  res.status(err.statusCode || 500).json({ message: err.message });
172
  }
173
  };
174
 
175
  export const createWalkInCashSale = async (req, res) => {
176
+ let createdCustomer = null;
177
  try {
178
  const tenantId = req.user.tenant?._id;
179
+ const { items, paidAmount, notes = "", customerId, customerName } = req.body;
180
 
181
  if (!tenantId) {
182
  return res.status(403).json({ message: "لا يوجد مستأجر مرتبط بهذا الحساب" });
 
185
  return res.status(400).json({ message: "يجب إضافة صنف واحد على الأقل" });
186
  }
187
 
188
+ let finalCustomerId = customerId;
189
+ if (!finalCustomerId && customerName) {
190
+ createdCustomer = await Customer.create({ name: customerName.trim(), tenant: tenantId, createdBy: req.user._id });
191
+ finalCustomerId = createdCustomer._id;
192
+ }
193
 
194
+ try {
195
+ await ensureStockAvailability(items, tenantId);
 
 
 
 
 
 
196
 
197
+ let customer;
198
+ if (finalCustomerId) {
199
+ customer = await Customer.findOne({ _id: finalCustomerId, tenant: tenantId });
200
+ if (!customer) throw new Error("العميل المحدد غير موجود");
201
+ } else {
202
+ customer = await getOrCreateWalkInCustomer(tenantId, req.user._id);
203
+ }
204
 
205
+ const invoice = new Invoice({
206
+ tenant: tenantId,
207
+ customer: customer._id,
208
+ issuedBy: req.user._id,
209
+ notes: notes.trim(),
210
  });
 
211
 
212
+ await applyInvoiceItemsAndStock(invoice, items, tenantId);
213
+
214
+ let saved = false;
215
+ for (let i = 0; i < 3; i++) {
216
+ try {
217
+ invoice.invoiceNumber = await generateInvoiceNumber(tenantId);
218
+ invoice.calculateTotals();
219
+ await invoice.save();
220
+ saved = true;
221
+ break;
222
+ } catch (saveErr) {
223
+ if (saveErr.code === 11000 && i < 2) continue;
224
+ throw saveErr;
225
+ }
226
+ }
227
+ if (!saved) throw new Error("تعذر حفظ الفاتورة لخطأ تزامن بالرقم");
228
 
229
+ const paymentAmount = Number(paidAmount);
230
+ if (!paymentAmount || Number(paymentAmount.toFixed(2)) !== Number(invoice.totalAmount.toFixed(2))) {
231
+ throw new Error("فاتورة الزائر يجب أن تكون نقدية بالكامل، ويجب أن يساوي المبلغ المدفوع إجمالي الفاتورة");
232
+ }
233
+
234
+ invoice.payments.push({
235
+ amount: paymentAmount,
236
+ method: "cash",
237
+ receivedBy: req.user._id,
238
+ });
239
 
240
+ await invoice.save();
241
+ await createIncomeForPayment({
242
+ tenantId,
243
+ invoice,
244
+ customer,
245
+ amount: paymentAmount,
246
+ userId: req.user._id,
247
+ notes: "Walk-in cash sale",
248
+ });
249
+
250
+ const populatedInvoice = await Invoice.findById(invoice._id).populate("customer", "name isWalkIn");
251
+ res.status(201).json(populatedInvoice);
252
+ } catch (err) {
253
+ if (createdCustomer) await Customer.deleteOne({ _id: createdCustomer._id });
254
+ throw err;
255
+ }
256
  } catch (err) {
257
+ if (createdCustomer) await Customer.deleteOne({ _id: createdCustomer._id });
258
  res.status(err.statusCode || 500).json({ message: err.message });
259
  }
260
  };
 
342
  if (!invoice) {
343
  return res.status(404).json({ message: "الفاتورة غير موجودة" });
344
  }
 
 
 
345
 
346
  const item = invoice.items.id(itemId);
347
  if (!item) {
 
402
  if (!invoice) {
403
  return res.status(404).json({ message: "الفاتورة غير موجودة" });
404
  }
 
 
 
405
 
406
  const item = invoice.items.id(itemId);
407
  if (!item) {
 
470
  } catch (err) {
471
  res.status(500).json({ message: err.message });
472
  }
473
+ };
controller/productController.js CHANGED
@@ -2,7 +2,7 @@ import Product from "../models/ProductModel.js";
2
 
3
  export const createProduct = async (req, res) => {
4
  try {
5
- const { name, price, stock, description, barcode, sku, unit, lowStockThreshold, costPrice } = req.body;
6
  const tenantId = req.user.tenant._id;
7
 
8
  const exists = await Product.findOne({
@@ -23,6 +23,7 @@ export const createProduct = async (req, res) => {
23
  barcode,
24
  sku,
25
  unit,
 
26
  lowStockThreshold: lowStockThreshold || req.user.tenant.settings?.lowStockThreshold || 5,
27
  costPrice: costPrice || 0,
28
  createdBy: req.user._id,
@@ -93,7 +94,7 @@ export const getProducts = async (req, res) => {
93
  export const updateProduct = async (req, res) => {
94
  try {
95
  const { id } = req.params;
96
- const { name, price, stock, description, barcode, sku, unit, lowStockThreshold, costPrice } = req.body;
97
 
98
  const product = await Product.findOne({
99
  _id: id,
@@ -111,6 +112,7 @@ export const updateProduct = async (req, res) => {
111
  product.barcode = barcode ?? product.barcode;
112
  product.sku = sku ?? product.sku;
113
  product.unit = unit ?? product.unit;
 
114
  product.lowStockThreshold = lowStockThreshold ?? product.lowStockThreshold;
115
  product.costPrice = costPrice ?? product.costPrice;
116
  await product.save();
 
2
 
3
  export const createProduct = async (req, res) => {
4
  try {
5
+ const { name, price, stock, description, barcode, sku, unit, category, lowStockThreshold, costPrice } = req.body;
6
  const tenantId = req.user.tenant._id;
7
 
8
  const exists = await Product.findOne({
 
23
  barcode,
24
  sku,
25
  unit,
26
+ category: category || "عام",
27
  lowStockThreshold: lowStockThreshold || req.user.tenant.settings?.lowStockThreshold || 5,
28
  costPrice: costPrice || 0,
29
  createdBy: req.user._id,
 
94
  export const updateProduct = async (req, res) => {
95
  try {
96
  const { id } = req.params;
97
+ const { name, price, stock, description, barcode, sku, unit, category, lowStockThreshold, costPrice } = req.body;
98
 
99
  const product = await Product.findOne({
100
  _id: id,
 
112
  product.barcode = barcode ?? product.barcode;
113
  product.sku = sku ?? product.sku;
114
  product.unit = unit ?? product.unit;
115
+ product.category = category ?? product.category;
116
  product.lowStockThreshold = lowStockThreshold ?? product.lowStockThreshold;
117
  product.costPrice = costPrice ?? product.costPrice;
118
  await product.save();
models/ProductModel.js CHANGED
@@ -41,6 +41,10 @@ const productSchema = new mongoose.Schema(
41
  type: String,
42
  default: "piece",
43
  },
 
 
 
 
44
  lowStockThreshold: {
45
  type: Number,
46
  default: 5,
 
41
  type: String,
42
  default: "piece",
43
  },
44
+ category: {
45
+ type: String,
46
+ default: "عام",
47
+ },
48
  lowStockThreshold: {
49
  type: Number,
50
  default: 5,