File size: 7,727 Bytes
0159174
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e2bc494
 
 
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
import Service from "../models/ServiceModel.js";
import Income from "../models/IncomeModel.js";
import Invoice from "../models/InvoiceModel.js";
import mongoose from "mongoose";

/**

 * Get all services for a tenant/branch

 */
export const getServices = async (req, res) => {
   try {
      const { branchId } = req.query;
      const tenantId = req.user.tenant._id;

      const query = { tenant: tenantId, isDeleted: false };
      if (branchId && branchId !== "all") {
         query.branch = branchId;
      }

      const services = await Service.find(query)
         .select("_id name description defaultPrice category isActive")
         .sort({ createdAt: -1 });

      res.json({
         success: true,
         data: services,
         count: services.length,
      });
   } catch (error) {
      console.error("Error fetching services:", error);
      res.status(500).json({ success: false, error: error.message });
   }
};

/**

 * Create a new service

 */
export const createService = async (req, res) => {
   try {
      const { name, description, category, notes, isActive } = req.body;
      const defaultPrice = Number(req.body.defaultPrice);
      const tenantId = req.user.tenant._id;
      const branchId = req.user.activeBranchScopeKey || null;
      const userId = req.user._id;

      if (!name || isNaN(defaultPrice) || defaultPrice < 0) {
         return res.status(400).json({
            success: false,
            error: "اسم الخدمة والسعر الافتراضي الصحيح مطلوبان",
         });
      }

      const existing = await Service.findOne({
         tenant: tenantId,
         branch: branchId,
         name: name.trim(),
         isDeleted: false,
      });

      if (existing) {
         return res.status(409).json({
            success: false,
            error: "توجد خدمة بهذا الاسم بالفعل",
         });
      }

      const service = await Service.create({
         tenant: tenantId,
         branch: branchId,
         name: name.trim(),
         description: description || "",
         defaultPrice,
         category: category || "other",
         notes: notes || "",
         isActive: isActive !== false,
         createdBy: userId,
      });

      res.status(201).json({
         success: true,
         message: "تم إنشاء الخدمة بنجاح",
         data: service,
      });
   } catch (error) {
      console.error("Error creating service:", error);
      res.status(500).json({ success: false, error: "حدث خطأ أثناء إنشاء الخدمة" });
   }
};

/**

 * Update a service

 */
export const updateService = async (req, res) => {
   try {
      const { serviceId } = req.params;
      const { name, description, defaultPrice, category, notes, isActive } = req.body;
      const tenantId = req.user.tenant._id;

      // Find and validate
      const service = await Service.findOne({
         _id: serviceId,
         tenant: tenantId,
         isDeleted: false,
      });

      if (!service) {
         return res.status(404).json({
            success: false,
            error: "Service not found",
         });
      }

      // Check for duplicate name
      if (name && name !== service.name) {
         const existing = await Service.findOne({
            tenant: tenantId,
            branch: service.branch,
            name: name.trim(),
            _id: { $ne: serviceId },
            isDeleted: false,
         });

         if (existing) {
            return res.status(409).json({
               success: false,
               error: "Service with this name already exists",
            });
         }
      }

      // Update fields
      if (name) service.name = name.trim();
      if (description !== undefined) service.description = description;
      if (defaultPrice !== undefined && defaultPrice !== "") {
         service.defaultPrice = Number(defaultPrice);
      }
      if (category) service.category = category;
      if (notes !== undefined) service.notes = notes;
      if (isActive !== undefined) service.isActive = isActive;

      await service.save();

      res.json({
         success: true,
         message: "Service updated successfully",
         data: service,
      });
   } catch (error) {
      console.error("Error updating service:", error);
      res.status(500).json({ success: false, error: error.message });
   }
};

/**

 * Delete a service

 */
export const deleteService = async (req, res) => {
   try {
      const { serviceId } = req.params;
      const tenantId = req.user.tenant._id;

      const service = await Service.findOne({
         _id: serviceId,
         tenant: tenantId,
         isDeleted: false,
      });

      if (!service) {
         return res.status(404).json({
            success: false,
            error: "Service not found",
         });
      }

      // Soft delete
      service.isDeleted = true;
      await service.save();

      res.json({
         success: true,
         message: "Service deleted successfully",
      });
   } catch (error) {
      console.error("Error deleting service:", error);
      res.status(500).json({ success: false, error: error.message });
   }
};

/**

 * Get service revenue report

 */
export const getServiceRevenueReport = async (req, res) => {
   try {
      const { startDate, endDate, branchId } = req.query;
      const tenantId = req.user.tenant._id;

      const query = {
         tenant: tenantId,
         sourceType: "invoice_payment",
         category: "service_income",
      };

      if (branchId && branchId !== "all") {
         query.branch = branchId;
      }

      if (startDate || endDate) {
         query.date = {};
         if (startDate) query.date.$gte = new Date(startDate);
         if (endDate) {
            const end = new Date(endDate);
            end.setHours(23, 59, 59, 999);
            query.date.$lte = end;
         }
      }

      const serviceIncome = await Income.aggregate([
         { $match: query },
         {
            $group: {
               _id: "$category",
               totalAmount: { $sum: "$amount" },
               count: { $sum: 1 },
               avgAmount: { $avg: "$amount" },
            },
         },
      ]);

      res.json({
         success: true,
         data: serviceIncome,
      });
   } catch (error) {
      console.error("Error fetching service revenue report:", error);
      res.status(500).json({ success: false, error: error.message });
   }
};

/**

 * Get services by category

 */
export const getServicesByCategory = async (req, res) => {
   try {
      const tenantId = req.user.tenant._id;
      const branchId = req.user.activeBranchScopeKey || null;

      const query = { tenant: tenantId, isDeleted: false, isActive: true };
      if (branchId) {
         query.branch = branchId;
      }

      const services = await Service.find(query).select(
         "_id name defaultPrice category"
      );

      // Group by category
      const byCategory = {};
      services.forEach((service) => {
         if (!byCategory[service.category]) {
            byCategory[service.category] = [];
         }
         byCategory[service.category].push(service);
      });

      res.json({
         success: true,
         data: byCategory,
      });
   } catch (error) {
      console.error("Error fetching services by category:", error);
      res.status(500).json({ success: false, error: error.message });
   }
};