File size: 8,244 Bytes
4dbde5b
 
 
0159174
4dbde5b
 
 
 
 
0159174
4dbde5b
 
0b68098
4dbde5b
 
 
 
0159174
4dbde5b
 
 
0b68098
4dbde5b
 
 
 
0159174
4dbde5b
 
 
 
 
 
0b68098
4dbde5b
 
 
 
 
 
 
 
 
0159174
4dbde5b
 
 
 
 
 
 
0159174
4dbde5b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0159174
4dbde5b
 
 
 
 
 
 
 
0159174
4dbde5b
 
 
 
 
 
 
 
 
 
 
 
 
 
0b68098
 
 
4dbde5b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0159174
4dbde5b
 
 
0159174
4dbde5b
0b68098
4dbde5b
0b68098
4dbde5b
 
 
 
 
0159174
4dbde5b
0b68098
4dbde5b
 
 
 
 
 
 
 
 
0159174
0b68098
4dbde5b
 
 
0159174
4dbde5b
0b68098
4dbde5b
 
 
0159174
4dbde5b
0b68098
 
 
 
4dbde5b
 
 
 
 
 
 
 
 
 
0159174
 
4dbde5b
 
 
 
0159174
4dbde5b
 
 
0b68098
4dbde5b
 
 
 
 
0159174
4dbde5b
0b68098
4dbde5b
 
 
 
0159174
4dbde5b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0159174
4dbde5b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0159174
4dbde5b
 
 
 
0159174
4dbde5b
0b68098
4dbde5b
0b68098
 
 
4dbde5b
 
 
0b68098
 
 
4dbde5b
 
 
0b68098
 
 
4dbde5b
 
 
 
 
 
 
 
 
 
 
 
 
 
0159174
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
import Supplier from "../models/SupplierModel.js";
import SupplierInvoice from "../models/SupplierInvoiceModel.js";
import Product from "../models/ProductModel.js";
import { resolveBranchForWrite, resolveScopedBranch } from "../utils/branchContext.js";

export const createSupplier = async (req, res) => {
   try {
      const name = req.body.name?.trim();
      const tenantId = req.user.tenant._id;
      const branch = await resolveBranchForWrite(req);

      if (!name) {
         return res.status(400).json({ message: "اسم المورد مطلوب" });
      }

      const exists = await Supplier.findOne({
         tenant: tenantId,
         branch: branch._id,
         name: new RegExp(`^${name}$`, "i"),
      });
      if (exists) {
         return res.status(400).json({ message: "هذا المورد موجود بالفعل" });
      }

      const supplier = await Supplier.create({
         tenant: tenantId,
         branch: branch._id,
         name,
         phone: req.body.phone?.trim() || "",
         whatsappNumber: req.body.whatsappNumber?.trim() || "",
         notes: req.body.notes?.trim() || "",
         createdBy: req.user._id,
      });

      res.status(201).json(supplier);
   } catch (err) {
      res.status(500).json({ message: err.message });
   }
};

export const getSuppliers = 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 matchQuery = {
         tenant: tenantId,
         ...branchFilter,
      };

      if (search) {
         matchQuery.name = { $regex: search, $options: "i" };
      }

      const results = await Supplier.aggregate([
         { $match: matchQuery },
         {
            $facet: {
               data: [
                  { $sort: { createdAt: -1 } },
                  { $skip: skip },
                  { $limit: limit },
                  {
                     $lookup: {
                        from: "supplierinvoices",
                        let: {
                           supplierId: "$_id",
                           tenantId: "$tenant",
                           branchId: "$branch",
                        },
                        pipeline: [
                           {
                              $match: {
                                 $expr: {
                                    $and: [
                                       { $eq: ["$supplier", "$$supplierId"] },
                                       { $eq: ["$tenant", "$$tenantId"] },
                                       ...(branchId ? [{ $eq: ["$branch", "$$branchId"] }] : []),
                                    ],
                                 },
                              },
                           },
                        ],
                        as: "invoices",
                     },
                  },
                  {
                     $addFields: {
                        totalDebt: { $sum: "$invoices.remainingAmount" },
                     },
                  },
               ],
               totalCount: [{ $count: "count" }],
            },
         },
      ]);

      const suppliers = results[0].data;
      const total = results[0].totalCount[0]?.count || 0;

      res.status(200).json({
         data: suppliers,
         pagination: {
            total,
            page,
            limit,
            totalPages: Math.ceil(total / limit),
         },
      });
   } catch (error) {
      res.status(500).json({ message: error.message });
   }
};

export const getSupplierById = async (req, res) => {
   try {
      const { branchFilter } = await resolveScopedBranch(req);
      const supplier = await Supplier.findOne({
         _id: req.params.id,
         tenant: req.user.tenant._id,
         ...branchFilter,
      });

      if (!supplier) {
         return res.status(404).json({ message: "المورد غير موجود" });
      }

      const invoice = await SupplierInvoice.findOne({
         supplier: supplier._id,
         tenant: req.user.tenant._id,
         ...branchFilter,
      });

      res.status(200).json({ ...supplier.toObject(), invoice });
   } catch (error) {
      res.status(500).json({ message: error.message });
   }
};

export const deleteSupplier = async (req, res) => {
   try {
      const supplierId = req.params.id;
      const { branchFilter } = await resolveScopedBranch(req);

      await Supplier.findOneAndDelete({
         _id: supplierId,
         tenant: req.user.tenant._id,
         ...branchFilter,
      });

      await SupplierInvoice.deleteMany({
         supplier: supplierId,
         tenant: req.user.tenant._id,
         ...branchFilter,
      });

      res.status(200).json({
         message: "تم حذف المورد وجميع فواتير الشراء المرتبطة به بنجاح",
      });
   } catch (error) {
      res.status(500).json({ message: error.message });
   }
};

export const addPurchasesToSupplier = async (req, res) => {
   try {
      const { items } = req.body;
      const supplierId = req.params.id;
      const tenantId = req.user.tenant._id;
      const branch = await resolveBranchForWrite(req);
      const branchId = branch._id;

      const supplier = await Supplier.findOne({
         _id: supplierId,
         tenant: tenantId,
         branch: branchId,
      });

      if (!supplier) {
         return res.status(404).json({ message: "المورد غير موجود" });
      }

      let invoice = await SupplierInvoice.findOne({
         supplier: supplierId,
         tenant: tenantId,
         branch: branchId,
      });

      if (!invoice) {
         invoice = new SupplierInvoice({
            supplier: supplierId,
            tenant: tenantId,
            branch: branchId,
            createdBy: req.user._id,
         });
      }

      for (const item of items) {
         const quantity = Number(item.quantity || 0);
         const price = Number(item.price || 0);
         const total = price * quantity;

         invoice.items.push({
            ...item,
            quantity,
            price,
            total,
         });

         if (item.productId) {
            await Product.findOneAndUpdate(
               { _id: item.productId, tenant: tenantId, branch: branchId },
               { $inc: { stock: quantity } }
            );
         }
      }

      await invoice.save();
      res.status(200).json(invoice);
   } catch (error) {
      res.status(500).json({ message: error.message });
   }
};

export const paySupplier = async (req, res) => {
   try {
      const amount = Number(req.body.amount);
      const supplierId = req.params.id;
      const { branchFilter } = await resolveScopedBranch(req);

      const invoice = await SupplierInvoice.findOne({
         supplier: supplierId,
         tenant: req.user.tenant._id,
         ...branchFilter,
      });

      if (!invoice) {
         return res.status(404).json({
            message: "لا توجد فاتورة شراء لهذا المورد",
         });
      }

      if (!amount || amount <= 0) {
         return res.status(400).json({
            message: "يجب أن يكون مبلغ الدفع أكبر من صفر",
         });
      }

      if (amount > invoice.remainingAmount) {
         return res.status(400).json({
            message: "مبلغ الدفع أكبر من الرصيد المتبقي",
         });
      }

      invoice.payments.push({
         amount,
         date: new Date(),
         method: req.body.paymentMethod || "cash",
         paidBy: req.user._id,
      });

      await invoice.save();
      res.status(200).json(invoice);
   } catch (error) {
      res.status(500).json({ message: error.message });
   }
};