File size: 9,030 Bytes
4dbde5b
 
0159174
1e65df5
4dbde5b
 
 
 
0159174
4dbde5b
1e65df5
 
4dbde5b
 
0b68098
4dbde5b
 
 
0b68098
4dbde5b
 
0159174
 
 
1e65df5
 
 
0159174
 
 
4dbde5b
 
0b68098
4dbde5b
 
 
 
0159174
4dbde5b
1e65df5
4dbde5b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0159174
4dbde5b
 
 
 
 
0b68098
 
 
 
 
 
0159174
 
 
 
 
 
4dbde5b
 
1e65df5
 
 
 
 
4dbde5b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0159174
4dbde5b
 
 
 
 
 
 
 
0159174
4dbde5b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0159174
4dbde5b
 
 
0159174
4dbde5b
 
 
0b68098
4dbde5b
 
 
 
 
 
 
 
ba7fcc6
 
 
4dbde5b
ba7fcc6
4dbde5b
 
0b68098
ba7fcc6
 
 
 
 
 
 
4dbde5b
ba7fcc6
4dbde5b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0159174
0b68098
0159174
 
 
 
 
 
 
0b68098
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0159174
0b68098
 
 
 
4dbde5b
0b68098
4dbde5b
 
 
 
0b68098
 
 
 
0159174
0b68098
0159174
 
 
 
 
 
 
0b68098
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0159174
0b68098
 
 
 
 
 
 
 
 
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
273
274
275
276
277
278
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 });
   }
};