File size: 10,968 Bytes
ba7fcc6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
import CatalogCategory from "../models/CatalogCategoryModel.js";
import CatalogItem from "../models/CatalogItemModel.js";
import { resolveBranchForWrite, resolveScopedBranch } from "../utils/branchContext.js";

const normalizeName = (value) => String(value || "").trim();

const getScopedCategory = async ({ categoryId, tenantId, branchId }) => {
   if (!categoryId) {
      return null;
   }

   return CatalogCategory.findOne({
      _id: categoryId,
      tenant: tenantId,
      branch: branchId,
   });
};

export const getCatalogCategories = async (req, res) => {
   try {
      const search = normalizeName(req.query.search);
      const activeOnly = req.query.activeOnly === "true";
      const { tenantId, branchFilter } = await resolveScopedBranch(req);

      const query = {
         tenant: tenantId,
         ...branchFilter,
      };

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

      if (activeOnly) {
         query.isActive = true;
      }

      const categories = await CatalogCategory.find(query).sort({ sortOrder: 1, name: 1 });
      res.status(200).json({ data: categories });
   } catch (error) {
      res.status(500).json({ message: error.message });
   }
};

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

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

      const existing = await CatalogCategory.findOne({
         tenant: tenantId,
         branch: branch._id,
         name,
      });

      if (existing) {
         return res.status(400).json({ message: "الفئة موجودة بالفعل" });
      }

      const category = await CatalogCategory.create({
         tenant: tenantId,
         branch: branch._id,
         name,
         description: normalizeName(req.body.description),
         sortOrder: Number(req.body.sortOrder || 0),
         isActive: req.body.isActive ?? true,
         createdBy: req.user._id,
      });

      res.status(201).json(category);
   } catch (error) {
      res.status(500).json({ message: error.message });
   }
};

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

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

      const nextName = normalizeName(req.body.name);
      if (nextName && nextName !== category.name) {
         const duplicate = await CatalogCategory.findOne({
            _id: { $ne: category._id },
            tenant: category.tenant,
            branch: category.branch,
            name: nextName,
         });

         if (duplicate) {
            return res.status(400).json({ message: "اسم الفئة مستخدم بالفعل" });
         }

         category.name = nextName;
      }

      if (req.body.description !== undefined) {
         category.description = normalizeName(req.body.description);
      }
      if (req.body.sortOrder !== undefined) {
         category.sortOrder = Number(req.body.sortOrder || 0);
      }
      if (req.body.isActive !== undefined) {
         category.isActive = Boolean(req.body.isActive);
      }

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

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

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

      const linkedItems = await CatalogItem.countDocuments({
         tenant: req.user.tenant._id,
         category: category._id,
         ...branchFilter,
      });

      if (linkedItems > 0) {
         return res.status(400).json({ message: "احذف عناصر الفئة أولاً قبل حذفها" });
      }

      await category.deleteOne();
      res.status(200).json({ message: "تم حذف الفئة بنجاح" });
   } catch (error) {
      res.status(500).json({ message: error.message });
   }
};

export const getCatalogItems = async (req, res) => {
   try {
      const page = Math.max(1, parseInt(req.query.page) || 1);
      const limit = Math.max(1, parseInt(req.query.limit) || 20);
      const skip = (page - 1) * limit;
      const search = normalizeName(req.query.search);
      const categoryId = req.query.categoryId || "";
      const activeOnly = req.query.activeOnly === "true";
      const { tenantId, branchFilter } = await resolveScopedBranch(req);

      const query = {
         tenant: tenantId,
         ...branchFilter,
      };

      if (search) {
         query.name = { $regex: search, $options: "i" };
      }
      if (categoryId) {
         query.category = categoryId;
      }
      if (activeOnly) {
         query.isActive = true;
      }

      const total = await CatalogItem.countDocuments(query);
      const items = await CatalogItem.find(query)
         .populate("category", "name")
         .sort({ sortOrder: 1, createdAt: -1 })
         .skip(skip)
         .limit(limit);

      res.status(200).json({
         data: items.map((item) => ({
            ...item.toObject(),
            categoryName: item.category?.name || "",
         })),
         pagination: {
            total,
            page,
            limit,
            totalPages: Math.ceil(total / limit),
         },
      });
   } catch (error) {
      res.status(500).json({ message: error.message });
   }
};

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

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

      const category = await getScopedCategory({
         categoryId: req.body.categoryId,
         tenantId,
         branchId: branch._id,
      });

      if (!category) {
         return res.status(400).json({ message: "فئة الكتالوج غير موجودة" });
      }

      const duplicate = await CatalogItem.findOne({
         tenant: tenantId,
         branch: branch._id,
         category: category._id,
         name,
      });

      if (duplicate) {
         return res.status(400).json({ message: "العنصر موجود بالفعل داخل هذه الفئة" });
      }

      const item = await CatalogItem.create({
         tenant: tenantId,
         branch: branch._id,
         category: category._id,
         name,
         description: normalizeName(req.body.description),
         price: Number(req.body.price || 0),
         costPrice: Number(req.body.costPrice || 0),
         sortOrder: Number(req.body.sortOrder || 0),
         isActive: req.body.isActive ?? true,
         createdBy: req.user._id,
      });

      const populated = await CatalogItem.findById(item._id).populate("category", "name");
      res.status(201).json({
         ...populated.toObject(),
         categoryName: populated.category?.name || "",
      });
   } catch (error) {
      res.status(500).json({ message: error.message });
   }
};

export const updateCatalogItem = async (req, res) => {
   try {
      const { branchFilter, branchId } = await resolveScopedBranch(req);
      const item = await CatalogItem.findOne({
         _id: req.params.id,
         tenant: req.user.tenant._id,
         ...branchFilter,
      });

      if (!item) {
         return res.status(404).json({ message: "عنصر الكتالوج غير موجود" });
      }

      if (req.body.categoryId && String(req.body.categoryId) !== String(item.category)) {
         const targetCategory = await getScopedCategory({
            categoryId: req.body.categoryId,
            tenantId: req.user.tenant._id,
            branchId,
         });

         if (!targetCategory) {
            return res.status(400).json({ message: "فئة الكتالوج غير موجودة" });
         }

         item.category = targetCategory._id;
      }

      const nextName = normalizeName(req.body.name);
      if (nextName && nextName !== item.name) {
         const duplicate = await CatalogItem.findOne({
            _id: { $ne: item._id },
            tenant: item.tenant,
            branch: item.branch,
            category: item.category,
            name: nextName,
         });

         if (duplicate) {
            return res.status(400).json({ message: "اسم العنصر مستخدم بالفعل داخل هذه الفئة" });
         }

         item.name = nextName;
      }

      if (req.body.description !== undefined) {
         item.description = normalizeName(req.body.description);
      }
      if (req.body.price !== undefined) {
         item.price = Number(req.body.price || 0);
      }
      if (req.body.costPrice !== undefined) {
         item.costPrice = Number(req.body.costPrice || 0);
      }
      if (req.body.sortOrder !== undefined) {
         item.sortOrder = Number(req.body.sortOrder || 0);
      }
      if (req.body.isActive !== undefined) {
         item.isActive = Boolean(req.body.isActive);
      }

      await item.save();
      const populated = await CatalogItem.findById(item._id).populate("category", "name");

      res.status(200).json({
         ...populated.toObject(),
         categoryName: populated.category?.name || "",
      });
   } catch (error) {
      res.status(500).json({ message: error.message });
   }
};

export const deleteCatalogItem = async (req, res) => {
   try {
      const { branchFilter } = await resolveScopedBranch(req);
      const item = await CatalogItem.findOneAndDelete({
         _id: req.params.id,
         tenant: req.user.tenant._id,
         ...branchFilter,
      });

      if (!item) {
         return res.status(404).json({ message: "عنصر الكتالوج غير موجود" });
      }

      res.status(200).json({ message: "تم حذف عنصر الكتالوج بنجاح" });
   } catch (error) {
      res.status(500).json({ message: error.message });
   }
};