Mahmoud7456 commited on
Commit
0b68098
·
verified ·
1 Parent(s): 2d16c3f

Upload 8 files

Browse files
controller/authController.js CHANGED
@@ -1,3 +1,4 @@
 
1
  import User from "../models/UserModel.js";
2
  import Tenant from "../models/TenantModel.js";
3
  import {
@@ -8,6 +9,13 @@ import {
8
  toSlug,
9
  } from "../utils/authCookies.js";
10
 
 
 
 
 
 
 
 
11
  const sanitizeTenant = (tenant) => {
12
  if (!tenant) {
13
  return null;
@@ -25,6 +33,12 @@ const sanitizeTenant = (tenant) => {
25
  status: tenant.status,
26
  settings: tenant.settings,
27
  createdAt: tenant.createdAt,
 
 
 
 
 
 
28
  };
29
  };
30
 
@@ -54,6 +68,12 @@ const createUniqueSlug = async (name) => {
54
  return slug;
55
  };
56
 
 
 
 
 
 
 
57
  export const checkAdmin = async (req, res) => {
58
  try {
59
  const count = await User.countDocuments({ role: "super_admin" });
@@ -67,7 +87,7 @@ export const setupAdmin = async (req, res) => {
67
  try {
68
  const count = await User.countDocuments({ role: "super_admin" });
69
  if (count > 0) {
70
- return res.status(400).json({ message: "Platform admin has already been set up" });
71
  }
72
 
73
  const body = req.body || {};
@@ -85,7 +105,7 @@ export const setupAdmin = async (req, res) => {
85
  });
86
 
87
  res.status(201).json({
88
- message: "Platform admin account created successfully",
89
  credentials: {
90
  username,
91
  password,
@@ -102,7 +122,7 @@ export const login = async (req, res) => {
102
  const { password } = req.body;
103
 
104
  if (!identifier || !password) {
105
- return res.status(400).json({ message: "Login credentials are required" });
106
  }
107
 
108
  const user = await User.findOne({
@@ -110,15 +130,15 @@ export const login = async (req, res) => {
110
  }).populate("tenant");
111
 
112
  if (!user || !user.matchPassword(password)) {
113
- return res.status(401).json({ message: "Invalid username or password" });
114
  }
115
 
116
  if (user.status !== "active") {
117
- return res.status(403).json({ message: "User account is suspended" });
118
  }
119
 
120
  if (user.tenant && user.tenant.status !== "active") {
121
- return res.status(403).json({ message: "Tenant account is suspended" });
122
  }
123
 
124
  const token = createSessionToken();
@@ -128,7 +148,7 @@ export const login = async (req, res) => {
128
  setAuthCookie(res, token);
129
 
130
  res.status(200).json({
131
- message: "Login successful",
132
  user: sanitizeUser(user),
133
  token,
134
  });
@@ -144,7 +164,7 @@ export const logout = async (req, res) => {
144
  await req.user.save();
145
  }
146
  clearAuthCookie(res);
147
- res.status(200).json({ message: "Logout successful" });
148
  } catch (err) {
149
  res.status(500).json({ message: err.message });
150
  }
@@ -153,7 +173,7 @@ export const logout = async (req, res) => {
153
  export const getCurrentUser = async (req, res) => {
154
  try {
155
  if (!req.user) {
156
- return res.status(401).json({ message: "Unauthorized" });
157
  }
158
 
159
  res.status(200).json({
@@ -183,11 +203,11 @@ export const getUsers = async (req, res) => {
183
 
184
  export const createUser = async (req, res) => {
185
  if (!req.user?.tenant) {
186
- return res.status(403).json({ message: "Internal user management is only available inside tenant accounts" });
187
  }
188
 
189
  if (!["owner", "admin"].includes(req.user.role)) {
190
- return res.status(403).json({ message: "Only tenant management roles can create users" });
191
  }
192
 
193
  const username = req.body.username?.trim();
@@ -198,23 +218,23 @@ export const createUser = async (req, res) => {
198
  const role = req.body.role || "cashier";
199
 
200
  if (!username || !password) {
201
- return res.status(400).json({ message: "Username and password are required" });
202
  }
203
 
204
  if (!["admin", "cashier"].includes(role)) {
205
- return res.status(400).json({ message: "Unsupported role" });
206
  }
207
 
208
  try {
209
  const usernameExists = await User.findOne({ username });
210
  if (usernameExists) {
211
- return res.status(400).json({ message: "Username is already in use" });
212
  }
213
 
214
  if (email) {
215
  const emailExists = await User.findOne({ email });
216
  if (emailExists) {
217
- return res.status(400).json({ message: "Email is already in use" });
218
  }
219
  }
220
 
@@ -231,7 +251,7 @@ export const createUser = async (req, res) => {
231
  await user.populate("tenant");
232
 
233
  res.status(201).json({
234
- message: "User created successfully",
235
  user: sanitizeUser(user),
236
  });
237
  } catch (err) {
@@ -241,11 +261,11 @@ export const createUser = async (req, res) => {
241
 
242
  export const deleteUser = async (req, res) => {
243
  if (!req.user?.tenant || !["owner", "admin"].includes(req.user.role)) {
244
- return res.status(403).json({ message: "You do not have permission to delete users" });
245
  }
246
 
247
  if (req.user._id.toString() === req.params.id) {
248
- return res.status(400).json({ message: "You cannot delete your own active account" });
249
  }
250
 
251
  try {
@@ -255,15 +275,15 @@ export const deleteUser = async (req, res) => {
255
  });
256
 
257
  if (!targetUser) {
258
- return res.status(404).json({ message: "User not found" });
259
  }
260
 
261
  if (targetUser.role === "owner") {
262
- return res.status(400).json({ message: "Owner accounts cannot be deleted from this screen" });
263
  }
264
 
265
  await targetUser.deleteOne();
266
- res.status(200).json({ message: "User deleted successfully" });
267
  } catch (error) {
268
  res.status(500).json({ message: error.message });
269
  }
@@ -271,7 +291,7 @@ export const deleteUser = async (req, res) => {
271
 
272
  export const updateUser = async (req, res) => {
273
  if (!req.user?.tenant || !["owner", "admin"].includes(req.user.role)) {
274
- return res.status(403).json({ message: "You do not have permission to edit users" });
275
  }
276
 
277
  try {
@@ -281,28 +301,28 @@ export const updateUser = async (req, res) => {
281
  }).populate("tenant");
282
 
283
  if (!targetUser) {
284
- return res.status(404).json({ message: "User not found" });
285
  }
286
 
287
  if (targetUser.role === "owner") {
288
- return res.status(400).json({ message: "Owner accounts cannot be edited from this screen" });
289
  }
290
 
291
  if (req.user.role === "admin" && targetUser.role !== "cashier") {
292
- return res.status(403).json({ message: "Admins can only manage cashier accounts" });
293
  }
294
 
295
  if (req.user._id.toString() === targetUser._id.toString() && req.body.status === "suspended") {
296
- return res.status(400).json({ message: "You cannot suspend your own active session" });
297
  }
298
 
299
  if (req.body.role) {
300
  if (!["admin", "cashier"].includes(req.body.role)) {
301
- return res.status(400).json({ message: "Unsupported role" });
302
  }
303
 
304
  if (req.user.role === "admin" && req.body.role === "admin") {
305
- return res.status(403).json({ message: "Admins cannot promote users to admin" });
306
  }
307
 
308
  targetUser.role = req.body.role;
@@ -310,7 +330,7 @@ export const updateUser = async (req, res) => {
310
 
311
  if (req.body.status) {
312
  if (!["active", "suspended"].includes(req.body.status)) {
313
- return res.status(400).json({ message: "Unsupported status" });
314
  }
315
 
316
  targetUser.status = req.body.status;
@@ -323,7 +343,7 @@ export const updateUser = async (req, res) => {
323
  await targetUser.save();
324
 
325
  res.status(200).json({
326
- message: "User updated successfully",
327
  user: sanitizeUser(targetUser),
328
  });
329
  } catch (error) {
@@ -333,7 +353,7 @@ export const updateUser = async (req, res) => {
333
 
334
  export const getTenants = async (req, res) => {
335
  if (req.user.role !== "super_admin") {
336
- return res.status(403).json({ message: "Only the platform admin can access tenants" });
337
  }
338
 
339
  try {
@@ -346,7 +366,7 @@ export const getTenants = async (req, res) => {
346
 
347
  export const getTenantProfile = async (req, res) => {
348
  if (!req.user?.tenant) {
349
- return res.status(403).json({ message: "This profile is only available for tenant users" });
350
  }
351
 
352
  try {
@@ -360,18 +380,18 @@ export const getTenantProfile = async (req, res) => {
360
 
361
  export const updateTenantProfile = async (req, res) => {
362
  if (!req.user?.tenant) {
363
- return res.status(403).json({ message: "This profile is only available for tenant users" });
364
  }
365
 
366
  if (!["owner", "admin"].includes(req.user.role)) {
367
- return res.status(403).json({ message: "Only tenant management roles can update company settings" });
368
  }
369
 
370
  try {
371
  const tenant = await Tenant.findById(req.user.tenant._id);
372
 
373
  if (!tenant) {
374
- return res.status(404).json({ message: "Tenant not found" });
375
  }
376
 
377
  tenant.name = req.body.name?.trim() || tenant.name;
@@ -402,7 +422,7 @@ export const updateTenantProfile = async (req, res) => {
402
  await req.user.populate("tenant");
403
 
404
  res.status(200).json({
405
- message: "Company profile updated successfully",
406
  tenant: sanitizeTenant(tenant),
407
  });
408
  } catch (error) {
@@ -410,20 +430,56 @@ export const updateTenantProfile = async (req, res) => {
410
  }
411
  };
412
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
413
  export const updateTenantStatus = async (req, res) => {
414
  if (req.user.role !== "super_admin") {
415
- return res.status(403).json({ message: "Only the platform admin can update tenant status" });
416
  }
417
 
418
  const status = req.body.status;
419
  if (!["active", "suspended"].includes(status)) {
420
- return res.status(400).json({ message: "Invalid tenant status" });
421
  }
422
 
423
  try {
424
  const tenant = await Tenant.findById(req.params.id);
425
  if (!tenant) {
426
- return res.status(404).json({ message: "Tenant not found" });
427
  }
428
 
429
  tenant.status = status;
@@ -432,7 +488,70 @@ export const updateTenantStatus = async (req, res) => {
432
  await User.updateMany({ tenant: tenant._id }, { status });
433
 
434
  res.status(200).json({
435
- message: `Tenant marked as ${status}`,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
436
  tenant: sanitizeTenant(tenant),
437
  });
438
  } catch (error) {
@@ -442,7 +561,7 @@ export const updateTenantStatus = async (req, res) => {
442
 
443
  export const createTenantOwner = async (req, res) => {
444
  if (req.user.role !== "super_admin") {
445
- return res.status(403).json({ message: "Only the platform admin can create tenants" });
446
  }
447
 
448
  try {
@@ -456,18 +575,18 @@ export const createTenantOwner = async (req, res) => {
456
  const address = req.body.address?.trim() || "";
457
 
458
  if (!companyName || !ownerName || !username || !password) {
459
- return res.status(400).json({ message: "Company and owner details are required" });
460
  }
461
 
462
  const existingUsername = await User.findOne({ username });
463
  if (existingUsername) {
464
- return res.status(400).json({ message: "Username is already in use" });
465
  }
466
 
467
  if (email) {
468
  const existingEmail = await User.findOne({ email });
469
  if (existingEmail) {
470
- return res.status(400).json({ message: "Email is already in use" });
471
  }
472
  }
473
 
@@ -481,6 +600,9 @@ export const createTenantOwner = async (req, res) => {
481
  ownerPhone: phone,
482
  whatsappNumber,
483
  address,
 
 
 
484
  });
485
 
486
  const owner = await User.create({
@@ -505,7 +627,7 @@ export const createTenantOwner = async (req, res) => {
505
  });
506
 
507
  res.status(201).json({
508
- message: "Tenant owner account created successfully",
509
  tenant: sanitizeTenant(tenant),
510
  owner: sanitizeUser(owner),
511
  onboarding: {
@@ -518,4 +640,4 @@ export const createTenantOwner = async (req, res) => {
518
  } catch (error) {
519
  res.status(500).json({ message: error.message });
520
  }
521
- };
 
1
+ import mongoose from "mongoose";
2
  import User from "../models/UserModel.js";
3
  import Tenant from "../models/TenantModel.js";
4
  import {
 
9
  toSlug,
10
  } from "../utils/authCookies.js";
11
 
12
+ const getPaymentStatus = (tenant) => {
13
+ if (!tenant) return "due";
14
+ const nextDue = tenant.nextPaymentDueAt ? new Date(tenant.nextPaymentDueAt) : null;
15
+ if (!nextDue) return "due";
16
+ return nextDue < new Date() ? "overdue" : "due";
17
+ };
18
+
19
  const sanitizeTenant = (tenant) => {
20
  if (!tenant) {
21
  return null;
 
33
  status: tenant.status,
34
  settings: tenant.settings,
35
  createdAt: tenant.createdAt,
36
+ monthlyFeeAmount: tenant.monthlyFeeAmount || 800,
37
+ monthlyFeeCurrency: tenant.monthlyFeeCurrency || "EGP",
38
+ nextPaymentDueAt: tenant.nextPaymentDueAt || null,
39
+ lastPaymentAt: tenant.lastPaymentAt || null,
40
+ paymentsCount: Array.isArray(tenant.payments) ? tenant.payments.length : 0,
41
+ paymentStatus: getPaymentStatus(tenant),
42
  };
43
  };
44
 
 
68
  return slug;
69
  };
70
 
71
+ const addOneMonth = (date) => {
72
+ const next = new Date(date);
73
+ next.setMonth(next.getMonth() + 1);
74
+ return next;
75
+ };
76
+
77
  export const checkAdmin = async (req, res) => {
78
  try {
79
  const count = await User.countDocuments({ role: "super_admin" });
 
87
  try {
88
  const count = await User.countDocuments({ role: "super_admin" });
89
  if (count > 0) {
90
+ return res.status(400).json({ message: "تم إعداد حساب المسؤول مسبقاً" });
91
  }
92
 
93
  const body = req.body || {};
 
105
  });
106
 
107
  res.status(201).json({
108
+ message: "تم إنشاء حساب المسؤول بنجاح",
109
  credentials: {
110
  username,
111
  password,
 
122
  const { password } = req.body;
123
 
124
  if (!identifier || !password) {
125
+ return res.status(400).json({ message: "بيانات تسجيل الدخول مطلوبة" });
126
  }
127
 
128
  const user = await User.findOne({
 
130
  }).populate("tenant");
131
 
132
  if (!user || !user.matchPassword(password)) {
133
+ return res.status(401).json({ message: "خطا فى اسم المستخدم أو كلمه المرور" });
134
  }
135
 
136
  if (user.status !== "active") {
137
+ return res.status(403).json({ message: "هذا الحساب متوقف" });
138
  }
139
 
140
  if (user.tenant && user.tenant.status !== "active") {
141
+ return res.status(403).json({ message: "تم تعليق حساب المستأجر" });
142
  }
143
 
144
  const token = createSessionToken();
 
148
  setAuthCookie(res, token);
149
 
150
  res.status(200).json({
151
+ message: "تم تسجيل الدخول بنجاح",
152
  user: sanitizeUser(user),
153
  token,
154
  });
 
164
  await req.user.save();
165
  }
166
  clearAuthCookie(res);
167
+ res.status(200).json({ message: "تم تسجيل الخروج بنجاح" });
168
  } catch (err) {
169
  res.status(500).json({ message: err.message });
170
  }
 
173
  export const getCurrentUser = async (req, res) => {
174
  try {
175
  if (!req.user) {
176
+ return res.status(401).json({ message: "غير مصرح بالوصول" });
177
  }
178
 
179
  res.status(200).json({
 
203
 
204
  export const createUser = async (req, res) => {
205
  if (!req.user?.tenant) {
206
+ return res.status(403).json({ message: "إدارة المستخدمين الداخليين متاحة فقط داخل حسابات المستأجرين" });
207
  }
208
 
209
  if (!["owner", "admin"].includes(req.user.role)) {
210
+ return res.status(403).json({ message: "فقط أدوار إدارة المستأجر يمكنها إنشاء مستخدمين" });
211
  }
212
 
213
  const username = req.body.username?.trim();
 
218
  const role = req.body.role || "cashier";
219
 
220
  if (!username || !password) {
221
+ return res.status(400).json({ message: "اسم المستخدم وكلمة المرور مطلوبان" });
222
  }
223
 
224
  if (!["admin", "cashier"].includes(role)) {
225
+ return res.status(400).json({ message: "الدور المحدد غير مدعوم" });
226
  }
227
 
228
  try {
229
  const usernameExists = await User.findOne({ username });
230
  if (usernameExists) {
231
+ return res.status(400).json({ message: "اسم المستخدم مستخدم بالفعل" });
232
  }
233
 
234
  if (email) {
235
  const emailExists = await User.findOne({ email });
236
  if (emailExists) {
237
+ return res.status(400).json({ message: "البريد الإلكتروني مستخدم بالفعل" });
238
  }
239
  }
240
 
 
251
  await user.populate("tenant");
252
 
253
  res.status(201).json({
254
+ message: "تم إنشاء المستخدم بنجاح",
255
  user: sanitizeUser(user),
256
  });
257
  } catch (err) {
 
261
 
262
  export const deleteUser = async (req, res) => {
263
  if (!req.user?.tenant || !["owner", "admin"].includes(req.user.role)) {
264
+ return res.status(403).json({ message: "ليس لديك صلاحية حذف المستخدمين" });
265
  }
266
 
267
  if (req.user._id.toString() === req.params.id) {
268
+ return res.status(400).json({ message: "لا يمكنك حذف حسابك الخاص النشط" });
269
  }
270
 
271
  try {
 
275
  });
276
 
277
  if (!targetUser) {
278
+ return res.status(404).json({ message: "المستخدم غير موجود" });
279
  }
280
 
281
  if (targetUser.role === "owner") {
282
+ return res.status(400).json({ message: "لا يمكن حذف حسابات المالك من هذه الشاشة" });
283
  }
284
 
285
  await targetUser.deleteOne();
286
+ res.status(200).json({ message: "تم حذف المستخدم بنجاح" });
287
  } catch (error) {
288
  res.status(500).json({ message: error.message });
289
  }
 
291
 
292
  export const updateUser = async (req, res) => {
293
  if (!req.user?.tenant || !["owner", "admin"].includes(req.user.role)) {
294
+ return res.status(403).json({ message: "ليس لديك صلاحية تعديل المستخدمين" });
295
  }
296
 
297
  try {
 
301
  }).populate("tenant");
302
 
303
  if (!targetUser) {
304
+ return res.status(404).json({ message: "المستخدم غير موجود" });
305
  }
306
 
307
  if (targetUser.role === "owner") {
308
+ return res.status(400).json({ message: "لا يمكن تعديل حسابات المالك من هذه الشاشة" });
309
  }
310
 
311
  if (req.user.role === "admin" && targetUser.role !== "cashier") {
312
+ return res.status(403).json({ message: "يمكن للمسؤولين إدارة حسابات الكاشير فقط" });
313
  }
314
 
315
  if (req.user._id.toString() === targetUser._id.toString() && req.body.status === "suspended") {
316
+ return res.status(400).json({ message: "لا يمكنك تعليق جلستك النشطة الخاصة" });
317
  }
318
 
319
  if (req.body.role) {
320
  if (!["admin", "cashier"].includes(req.body.role)) {
321
+ return res.status(400).json({ message: "الدور المحدد غير مدعوم" });
322
  }
323
 
324
  if (req.user.role === "admin" && req.body.role === "admin") {
325
+ return res.status(403).json({ message: "لا يمكن للمسؤولين ترقية المستخدمين إلى مسؤول" });
326
  }
327
 
328
  targetUser.role = req.body.role;
 
330
 
331
  if (req.body.status) {
332
  if (!["active", "suspended"].includes(req.body.status)) {
333
+ return res.status(400).json({ message: "الحالة المحددة غير مدعومة" });
334
  }
335
 
336
  targetUser.status = req.body.status;
 
343
  await targetUser.save();
344
 
345
  res.status(200).json({
346
+ message: "تم تحديث بيانات المستخدم بنجاح",
347
  user: sanitizeUser(targetUser),
348
  });
349
  } catch (error) {
 
353
 
354
  export const getTenants = async (req, res) => {
355
  if (req.user.role !== "super_admin") {
356
+ return res.status(403).json({ message: "فقط مسؤول المنصة يمكنه الوصول إلى المستأجرين" });
357
  }
358
 
359
  try {
 
366
 
367
  export const getTenantProfile = async (req, res) => {
368
  if (!req.user?.tenant) {
369
+ return res.status(403).json({ message: "هذا الملف الشخصي متاح فقط لمستخدمي المستأجر" });
370
  }
371
 
372
  try {
 
380
 
381
  export const updateTenantProfile = async (req, res) => {
382
  if (!req.user?.tenant) {
383
+ return res.status(403).json({ message: "هذا الملف الشخصي متاح فقط لمستخدمي المستأجر" });
384
  }
385
 
386
  if (!["owner", "admin"].includes(req.user.role)) {
387
+ return res.status(403).json({ message: "فقط أدوار إدارة المستأجر يمكنها تحديث إعدادات الشركة" });
388
  }
389
 
390
  try {
391
  const tenant = await Tenant.findById(req.user.tenant._id);
392
 
393
  if (!tenant) {
394
+ return res.status(404).json({ message: "المستأجر غير موجود" });
395
  }
396
 
397
  tenant.name = req.body.name?.trim() || tenant.name;
 
422
  await req.user.populate("tenant");
423
 
424
  res.status(200).json({
425
+ message: "تم تحديث ملف الشركة بنجاح",
426
  tenant: sanitizeTenant(tenant),
427
  });
428
  } catch (error) {
 
430
  }
431
  };
432
 
433
+ export const changePassword = async (req, res) => {
434
+ try {
435
+ const oldPassword = req.body.oldPassword?.trim();
436
+ const newPassword = req.body.newPassword?.trim();
437
+ const confirmPassword = req.body.confirmPassword?.trim();
438
+
439
+ if (!oldPassword || !newPassword || !confirmPassword) {
440
+ return res.status(400).json({ message: "جميع حقول كلمة المرور مطلوبة" });
441
+ }
442
+
443
+ if (newPassword.length < 6) {
444
+ return res.status(400).json({ message: "كلمة المرور الجديدة يجب أن تكون 6 أحرف على الأقل" });
445
+ }
446
+
447
+ if (newPassword !== confirmPassword) {
448
+ return res.status(400).json({ message: "كلمة المرور الجديدة وتأكيدها غير متطابقين" });
449
+ }
450
+
451
+ const user = await User.findById(req.user._id);
452
+ if (!user || !user.matchPassword(oldPassword)) {
453
+ return res.status(400).json({ message: "كلمة المرور القديمة غير صحيحة" });
454
+ }
455
+
456
+ if (oldPassword === newPassword) {
457
+ return res.status(400).json({ message: "كلمة المرور الجديدة يجب أن تختلف عن القديمة" });
458
+ }
459
+
460
+ user.password = newPassword;
461
+ await user.save();
462
+
463
+ res.status(200).json({ message: "تم تغيير كلمة المرور بنجاح" });
464
+ } catch (error) {
465
+ res.status(500).json({ message: error.message });
466
+ }
467
+ };
468
+
469
  export const updateTenantStatus = async (req, res) => {
470
  if (req.user.role !== "super_admin") {
471
+ return res.status(403).json({ message: "فقط مسؤول المنصة يمكنه تحديث حالة المستأجر" });
472
  }
473
 
474
  const status = req.body.status;
475
  if (!["active", "suspended"].includes(status)) {
476
+ return res.status(400).json({ message: "حالة المستأجر غير صالحة" });
477
  }
478
 
479
  try {
480
  const tenant = await Tenant.findById(req.params.id);
481
  if (!tenant) {
482
+ return res.status(404).json({ message: "المستأجر غير موجود" });
483
  }
484
 
485
  tenant.status = status;
 
488
  await User.updateMany({ tenant: tenant._id }, { status });
489
 
490
  res.status(200).json({
491
+ message: `تم تحديث حالة المستأجر إلى ${status === "active" ? "نشط" : "موقوف"}`,
492
+ tenant: sanitizeTenant(tenant),
493
+ });
494
+ } catch (error) {
495
+ res.status(500).json({ message: error.message });
496
+ }
497
+ };
498
+
499
+ export const getDbUsage = async (req, res) => {
500
+ if (req.user.role !== 'super_admin') {
501
+ return res.status(403).json({ message: 'فقط مسؤول النظام يمكنه الوصول إلى مقاييس استخدام قاعدة البيانات' });
502
+ }
503
+
504
+ try {
505
+ const stats = await mongoose.connection.db.stats();
506
+ res.status(200).json({
507
+ storageSize: stats.storageSize,
508
+ dataSize: stats.dataSize,
509
+ indexSize: stats.indexSize,
510
+ fileSize: stats.fileSize || null,
511
+ fsTotalSize: stats.fsTotalSize || null,
512
+ fsUsedSize: stats.fsUsedSize || null,
513
+ collections: stats.collections,
514
+ objects: stats.objects,
515
+ indexes: stats.indexes,
516
+ });
517
+ } catch (error) {
518
+ res.status(500).json({ message: error.message });
519
+ }
520
+ };
521
+
522
+ export const recordTenantPayment = async (req, res) => {
523
+ const tenantId = req.params.id;
524
+ const amount = Number(req.body.amount || 800);
525
+ const method = req.body.method?.trim() || 'manual';
526
+ const note = req.body.note?.trim() || 'سداد الرسوم الشهرية';
527
+
528
+ try {
529
+ const tenant = await Tenant.findById(tenantId);
530
+ if (!tenant) {
531
+ return res.status(404).json({ message: 'المستأجر غير موجود' });
532
+ }
533
+
534
+ if (req.user.role !== 'super_admin') {
535
+ if (!req.user.tenant || req.user.tenant._id.toString() !== tenant._id.toString()) {
536
+ return res.status(403).json({ message: 'ليس لديك صلاحية تسجيل المدفوعات لهذا المستأجر' });
537
+ }
538
+ }
539
+
540
+ const paymentDate = new Date();
541
+ tenant.payments = tenant.payments || [];
542
+ tenant.payments.push({
543
+ amount,
544
+ date: paymentDate,
545
+ method,
546
+ note,
547
+ recordedBy: req.user._id,
548
+ });
549
+ tenant.lastPaymentAt = paymentDate;
550
+ tenant.nextPaymentDueAt = addOneMonth(tenant.nextPaymentDueAt || paymentDate);
551
+ await tenant.save();
552
+
553
+ res.status(200).json({
554
+ message: 'تم تسجيل الدفعة بنجاح',
555
  tenant: sanitizeTenant(tenant),
556
  });
557
  } catch (error) {
 
561
 
562
  export const createTenantOwner = async (req, res) => {
563
  if (req.user.role !== "super_admin") {
564
+ return res.status(403).json({ message: "فقط مسؤول المنصة يمكنه إنشاء مستأجرين" });
565
  }
566
 
567
  try {
 
575
  const address = req.body.address?.trim() || "";
576
 
577
  if (!companyName || !ownerName || !username || !password) {
578
+ return res.status(400).json({ message: "بيانات الشركة والمالك مطلوبة" });
579
  }
580
 
581
  const existingUsername = await User.findOne({ username });
582
  if (existingUsername) {
583
+ return res.status(400).json({ message: "اسم المستخدم مستخدم بالفعل" });
584
  }
585
 
586
  if (email) {
587
  const existingEmail = await User.findOne({ email });
588
  if (existingEmail) {
589
+ return res.status(400).json({ message: "البريد الإلكتروني مستخدم بالفعل" });
590
  }
591
  }
592
 
 
600
  ownerPhone: phone,
601
  whatsappNumber,
602
  address,
603
+ monthlyFeeAmount: 800,
604
+ monthlyFeeCurrency: "EGP",
605
+ nextPaymentDueAt: addOneMonth(new Date()),
606
  });
607
 
608
  const owner = await User.create({
 
627
  });
628
 
629
  res.status(201).json({
630
+ message: "تم إنشاء حساب مالك المستأجر بنجاح",
631
  tenant: sanitizeTenant(tenant),
632
  owner: sanitizeUser(owner),
633
  onboarding: {
 
640
  } catch (error) {
641
  res.status(500).json({ message: error.message });
642
  }
643
+ };
controller/customerController.js CHANGED
@@ -7,20 +7,21 @@ export const createCustomer = async (req, res) => {
7
  const name = req.body.name?.trim();
8
 
9
  if (!name) {
10
- return res.status(400).json({ message: "Customer name is required" });
11
  }
12
 
13
  if (name.length < 3) {
14
- return res.status(400).json({ message: "Customer name must be at least 3 characters" });
15
  }
16
 
17
  const exists = await Customer.findOne({
18
  tenant: tenantId,
19
  name: new RegExp(`^${name}$`, "i"),
 
20
  });
21
 
22
  if (exists) {
23
- return res.status(400).json({ message: "Customer already exists" });
24
  }
25
 
26
  const customer = await Customer.create({
@@ -47,8 +48,15 @@ export const getCustomers = async (req, res) => {
47
  const skip = (page - 1) * limit;
48
  const search = req.query.search || "";
49
 
 
 
 
 
 
 
50
  const matchQuery = {
51
  tenant: tenantId,
 
52
  };
53
 
54
  if (search) {
@@ -124,7 +132,7 @@ export const getCustomerById = async (req, res) => {
124
  });
125
 
126
  if (!customer) {
127
- return res.status(404).json({ message: "Customer not found" });
128
  }
129
 
130
  // Pagination & Sorting
@@ -142,6 +150,7 @@ export const getCustomerById = async (req, res) => {
142
  const invoices = await Invoice.find({
143
  customer: customer._id,
144
  tenant: req.user.tenant._id,
 
145
  })
146
  .populate("items.productId", "name price")
147
  .sort({ [sortField]: sortOrder })
@@ -166,17 +175,69 @@ export const getCustomerById = async (req, res) => {
166
  export const deleteCustomer = async (req, res) => {
167
  try {
168
  const customerId = req.params.id;
169
- await Customer.findOneAndDelete({
170
- _id: customerId,
171
- tenant: req.user.tenant._id,
172
- });
173
- await Invoice.deleteMany({
174
- customer: customerId,
175
- tenant: req.user.tenant._id,
176
- });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
177
 
178
- res.status(200).json({ message: "Customer and linked invoices deleted successfully" });
179
  } catch (error) {
180
  res.status(500).json({ message: error.message });
181
  }
182
  };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7
  const name = req.body.name?.trim();
8
 
9
  if (!name) {
10
+ return res.status(400).json({ message: "اسم العميل مطلوب" });
11
  }
12
 
13
  if (name.length < 3) {
14
+ return res.status(400).json({ message: "اسم العميل يجب أن يكون 3 أحرف على الأقل" });
15
  }
16
 
17
  const exists = await Customer.findOne({
18
  tenant: tenantId,
19
  name: new RegExp(`^${name}$`, "i"),
20
+ isDeleted: false,
21
  });
22
 
23
  if (exists) {
24
+ return res.status(400).json({ message: "العميل موجود بالفعل" });
25
  }
26
 
27
  const customer = await Customer.create({
 
48
  const skip = (page - 1) * limit;
49
  const search = req.query.search || "";
50
 
51
+ const showDeleted = req.query.deleted === "true";
52
+
53
+ if (showDeleted && !["owner", "admin"].includes(req.user.role)) {
54
+ return res.status(403).json({ message: "ليس لديك صلاحية عرض العملاء المحذوفين" });
55
+ }
56
+
57
  const matchQuery = {
58
  tenant: tenantId,
59
+ isDeleted: showDeleted,
60
  };
61
 
62
  if (search) {
 
132
  });
133
 
134
  if (!customer) {
135
+ return res.status(404).json({ message: "العميل غير موجود" });
136
  }
137
 
138
  // Pagination & Sorting
 
150
  const invoices = await Invoice.find({
151
  customer: customer._id,
152
  tenant: req.user.tenant._id,
153
+ isDeleted: false,
154
  })
155
  .populate("items.productId", "name price")
156
  .sort({ [sortField]: sortOrder })
 
175
  export const deleteCustomer = async (req, res) => {
176
  try {
177
  const customerId = req.params.id;
178
+ const deletedCustomer = await Customer.findOneAndUpdate(
179
+ {
180
+ _id: customerId,
181
+ tenant: req.user.tenant._id,
182
+ isDeleted: false,
183
+ },
184
+ {
185
+ isDeleted: true,
186
+ deletedAt: new Date(),
187
+ },
188
+ { new: true }
189
+ );
190
+
191
+ if (!deletedCustomer) {
192
+ return res.status(404).json({ message: "العميل غير موجود أو تم حذفه مسبقاً" });
193
+ }
194
+
195
+ await Invoice.updateMany(
196
+ {
197
+ customer: customerId,
198
+ tenant: req.user.tenant._id,
199
+ isDeleted: false,
200
+ },
201
+ { isDeleted: true }
202
+ );
203
 
204
+ res.status(200).json({ message: "تم حذف العميل وأرشفة الفواتير المرتبطة به بنجاح" });
205
  } catch (error) {
206
  res.status(500).json({ message: error.message });
207
  }
208
  };
209
+
210
+ export const restoreCustomer = async (req, res) => {
211
+ try {
212
+ const customerId = req.params.id;
213
+ const restoredCustomer = await Customer.findOneAndUpdate(
214
+ {
215
+ _id: customerId,
216
+ tenant: req.user.tenant._id,
217
+ isDeleted: true,
218
+ },
219
+ {
220
+ isDeleted: false,
221
+ deletedAt: null,
222
+ },
223
+ { new: true }
224
+ );
225
+
226
+ if (!restoredCustomer) {
227
+ return res.status(404).json({ message: "العميل المحذوف غير موجود" });
228
+ }
229
+
230
+ await Invoice.updateMany(
231
+ {
232
+ customer: customerId,
233
+ tenant: req.user.tenant._id,
234
+ isDeleted: true,
235
+ },
236
+ { isDeleted: false }
237
+ );
238
+
239
+ res.status(200).json({ message: "تم استعادة العميل مع جميع الفواتير المرتبطة به" });
240
+ } catch (error) {
241
+ res.status(500).json({ message: error.message });
242
+ }
243
+ };
controller/expenseController.js CHANGED
@@ -19,13 +19,45 @@ export const addExpense = async (req, res) => {
19
  }
20
  };
21
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22
  export const deleteExpense = async (req, res) => {
23
  try {
24
  await Expense.findOneAndDelete({
25
  _id: req.params.id,
26
  tenant: req.user.tenant._id,
27
  });
28
- res.status(200).json({ message: "Expense deleted successfully" });
29
  } catch (error) {
30
  res.status(500).json({ message: error.message });
31
  }
 
19
  }
20
  };
21
 
22
+ export const getExpenses = async (req, res) => {
23
+ try {
24
+ const tenantId = req.user.tenant._id;
25
+ const page = parseInt(req.query.page) || 1;
26
+ const limit = parseInt(req.query.limit) || 5;
27
+ const skip = (page - 1) * limit;
28
+ const search = req.query.search || "";
29
+
30
+ const query = { tenant: tenantId };
31
+ if (search) {
32
+ query.title = { $regex: search, $options: "i" };
33
+ }
34
+
35
+ const [items, total] = await Promise.all([
36
+ Expense.find(query).sort({ date: -1 }).skip(skip).limit(limit),
37
+ Expense.countDocuments(query),
38
+ ]);
39
+
40
+ res.status(200).json({
41
+ data: items,
42
+ pagination: {
43
+ total,
44
+ page,
45
+ limit,
46
+ totalPages: Math.ceil(total / limit),
47
+ },
48
+ });
49
+ } catch (error) {
50
+ res.status(500).json({ message: error.message });
51
+ }
52
+ };
53
+
54
  export const deleteExpense = async (req, res) => {
55
  try {
56
  await Expense.findOneAndDelete({
57
  _id: req.params.id,
58
  tenant: req.user.tenant._id,
59
  });
60
+ res.status(200).json({ message: "تم حذف المصروف بنجاح" });
61
  } catch (error) {
62
  res.status(500).json({ message: error.message });
63
  }
controller/incomeController.js ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import Income from "../models/IncomeModel.js";
2
+
3
+ export const addIncome = async (req, res) => {
4
+ try {
5
+ const tenantId = req.user.tenant._id;
6
+ const title = req.body.title?.trim();
7
+ const amount = Number(req.body.amount);
8
+ const category = req.body.category?.trim() || "general";
9
+ const paymentMethod = req.body.paymentMethod?.trim() || "cash";
10
+ const notes = req.body.notes?.trim() || "";
11
+ const date = req.body.date ? new Date(req.body.date) : new Date();
12
+
13
+ if (!title) {
14
+ return res.status(400).json({ message: "مطلوب عنوان الدخل" });
15
+ }
16
+ if (!amount || amount <= 0) {
17
+ return res.status(400).json({ message: "يجب أن يكون مبلغ الدخل أكبر من الصفر" });
18
+ }
19
+
20
+ const income = await Income.create({
21
+ tenant: tenantId,
22
+ title,
23
+ category,
24
+ amount,
25
+ paymentMethod,
26
+ notes,
27
+ date,
28
+ createdBy: req.user._id,
29
+ });
30
+
31
+ res.status(201).json(income);
32
+ } catch (error) {
33
+ res.status(500).json({ message: error.message });
34
+ }
35
+ };
36
+
37
+ export const getIncomes = async (req, res) => {
38
+ try {
39
+ const tenantId = req.user.tenant._id;
40
+ const page = parseInt(req.query.page) || 1;
41
+ const limit = parseInt(req.query.limit) || 5;
42
+ const skip = (page - 1) * limit;
43
+ const search = req.query.search || "";
44
+
45
+ const query = { tenant: tenantId };
46
+ if (search) {
47
+ query.title = { $regex: search, $options: "i" };
48
+ }
49
+
50
+ const [items, total] = await Promise.all([
51
+ Income.find(query).sort({ date: -1 }).skip(skip).limit(limit),
52
+ Income.countDocuments(query),
53
+ ]);
54
+
55
+ res.status(200).json({
56
+ data: items,
57
+ pagination: {
58
+ total,
59
+ page,
60
+ limit,
61
+ totalPages: Math.ceil(total / limit),
62
+ },
63
+ });
64
+ } catch (error) {
65
+ res.status(500).json({ message: error.message });
66
+ }
67
+ };
68
+
69
+ export const deleteIncome = async (req, res) => {
70
+ try {
71
+ const incomeId = req.params.id;
72
+ const income = await Income.findOneAndDelete({
73
+ _id: incomeId,
74
+ tenant: req.user.tenant._id,
75
+ });
76
+ if (!income) {
77
+ return res.status(404).json({ message: "سجل الإيراد غير موجود" });
78
+ }
79
+ res.status(200).json({ message: "تم حذف سجل الإيراد بنجاح" });
80
+ } catch (error) {
81
+ res.status(500).json({ message: error.message });
82
+ }
83
+ };
controller/invoiceController.js CHANGED
@@ -20,12 +20,12 @@ export const addItemToInvoice = async (req, res) => {
20
  const { items } = req.body;
21
  const tenantId = req.user.tenant?._id;
22
 
23
- if (!tenantId) return res.status(403).json({ message: "No tenant associated with this account" });
24
  if (!Array.isArray(items) || items.length === 0)
25
- return res.status(400).json({ message: "At least one item is required" });
26
 
27
  const customer = await Customer.findOne({ _id: customerId, tenant: tenantId });
28
- if (!customer) return res.status(404).json({ message: "Customer not found" });
29
 
30
  // Find open/partial invoice
31
  let invoice = await Invoice.findOne({
@@ -48,7 +48,7 @@ export const addItemToInvoice = async (req, res) => {
48
  for (const item of items) {
49
  if (item.productId) {
50
  const product = await Product.findOne({ _id: item.productId, tenant: tenantId });
51
- if (!product) return res.status(404).json({ message: `Product not found: ${item.name}` });
52
  if (product.stock < Number(item.quantity))
53
  return res.status(400).json({
54
  message: `Not enough stock for ${item.name}. Available: ${product.stock}`,
@@ -148,7 +148,7 @@ export const getInvoiceById = async (req, res) => {
148
  });
149
 
150
  if (!invoice) {
151
- return res.status(404).json({ message: "Invoice not found" });
152
  }
153
 
154
  res.status(200).json(invoice);
@@ -168,12 +168,12 @@ export const updateInvoiceItem = async (req, res) => {
168
  });
169
 
170
  if (!invoice) {
171
- return res.status(404).json({ message: "Invoice not found" });
172
  }
173
 
174
  const item = invoice.items.id(itemId);
175
  if (!item) {
176
- return res.status(404).json({ message: "Invoice item not found" });
177
  }
178
 
179
  const newQuantity = Number(quantity);
@@ -187,11 +187,11 @@ export const updateInvoiceItem = async (req, res) => {
187
  });
188
 
189
  if (!product) {
190
- return res.status(404).json({ message: "Linked product no longer exists" });
191
  }
192
 
193
  if (quantityDifference > 0 && product.stock < quantityDifference) {
194
- return res.status(400).json({ message: "Current stock is too low for this quantity change" });
195
  }
196
 
197
  if (quantityDifference !== 0) {
@@ -210,7 +210,7 @@ export const updateInvoiceItem = async (req, res) => {
210
  await invoice.save();
211
 
212
  res.status(200).json({
213
- message: "Invoice item updated successfully",
214
  invoice,
215
  });
216
  } catch (error) {
@@ -228,12 +228,12 @@ export const deleteInvoiceItem = async (req, res) => {
228
  });
229
 
230
  if (!invoice) {
231
- return res.status(404).json({ message: "Invoice not found" });
232
  }
233
 
234
  const item = invoice.items.id(itemId);
235
  if (!item) {
236
- return res.status(404).json({ message: "Invoice item not found" });
237
  }
238
 
239
  if (item.productId) {
@@ -258,7 +258,7 @@ export const payInvoice = async (req, res) => {
258
  const amount = Number(req.body.amount);
259
 
260
  if (!amount || amount <= 0) {
261
- return res.status(400).json({ message: "Payment amount must be greater than zero" });
262
  }
263
 
264
  const invoice = await Invoice.findOne({
@@ -268,11 +268,11 @@ export const payInvoice = async (req, res) => {
268
  });
269
 
270
  if (!invoice || invoice.remainingAmount <= 0) {
271
- return res.status(404).json({ message: "There is no outstanding invoice for this customer" });
272
  }
273
 
274
  if (amount > invoice.remainingAmount) {
275
- return res.status(400).json({ message: "Payment amount is greater than the remaining balance" });
276
  }
277
 
278
  invoice.payments.push({
 
20
  const { items } = req.body;
21
  const tenantId = req.user.tenant?._id;
22
 
23
+ if (!tenantId) return res.status(403).json({ message: "لا يوجد مستأجر (Tenant) مرتبط بهذا الحساب" });
24
  if (!Array.isArray(items) || items.length === 0)
25
+ return res.status(400).json({ message: "👉 يجب إدخال عنصر واحد على الأقل" });
26
 
27
  const customer = await Customer.findOne({ _id: customerId, tenant: tenantId });
28
+ if (!customer) return res.status(404).json({ message: "العميل غير موجود" });
29
 
30
  // Find open/partial invoice
31
  let invoice = await Invoice.findOne({
 
48
  for (const item of items) {
49
  if (item.productId) {
50
  const product = await Product.findOne({ _id: item.productId, tenant: tenantId });
51
+ if (!product) return res.status(404).json({ message: `لا يوجد منتج بهذا الاسم: ${item.name}` });
52
  if (product.stock < Number(item.quantity))
53
  return res.status(400).json({
54
  message: `Not enough stock for ${item.name}. Available: ${product.stock}`,
 
148
  });
149
 
150
  if (!invoice) {
151
+ return res.status(404).json({ message: "👉 الفاتورة غير موجودة" });
152
  }
153
 
154
  res.status(200).json(invoice);
 
168
  });
169
 
170
  if (!invoice) {
171
+ return res.status(404).json({ message: "👉 الفاتورة غير موجودة" });
172
  }
173
 
174
  const item = invoice.items.id(itemId);
175
  if (!item) {
176
+ return res.status(404).json({ message: "👉 عنصر الفاتورة غير موجود" });
177
  }
178
 
179
  const newQuantity = Number(quantity);
 
187
  });
188
 
189
  if (!product) {
190
+ return res.status(404).json({ message: "👉 المنتج المرتبط لم يعد موجودًا" });
191
  }
192
 
193
  if (quantityDifference > 0 && product.stock < quantityDifference) {
194
+ return res.status(400).json({ message: "👉 المخزون الحالي غير كافٍ لهذا التغيير في الكمية" });
195
  }
196
 
197
  if (quantityDifference !== 0) {
 
210
  await invoice.save();
211
 
212
  res.status(200).json({
213
+ message: "👉 تم تحديث عنصر الفاتورة بنجاح",
214
  invoice,
215
  });
216
  } catch (error) {
 
228
  });
229
 
230
  if (!invoice) {
231
+ return res.status(404).json({ message: "👉 الفاتورة غير موجودة" });
232
  }
233
 
234
  const item = invoice.items.id(itemId);
235
  if (!item) {
236
+ return res.status(404).json({ message: "👉 المنتج المرتبط لم يعد موجودًا" });
237
  }
238
 
239
  if (item.productId) {
 
258
  const amount = Number(req.body.amount);
259
 
260
  if (!amount || amount <= 0) {
261
+ return res.status(400).json({ message: "👉 يجب أن يكون مبلغ الدفع أكبر من صفر" });
262
  }
263
 
264
  const invoice = await Invoice.findOne({
 
268
  });
269
 
270
  if (!invoice || invoice.remainingAmount <= 0) {
271
+ return res.status(404).json({ message: "👉 لا توجد فاتورة مستحقة لهذا ��لعميل" });
272
  }
273
 
274
  if (amount > invoice.remainingAmount) {
275
+ return res.status(400).json({ message: "👉 مبلغ الدفع أكبر من الرصيد المتبقي" });
276
  }
277
 
278
  invoice.payments.push({
controller/productController.js CHANGED
@@ -11,7 +11,7 @@ export const createProduct = async (req, res) => {
11
  });
12
 
13
  if (exists) {
14
- return res.status(400).json({ message: "Product already exists" });
15
  }
16
 
17
  const product = await Product.create({
@@ -82,7 +82,7 @@ export const updateProduct = async (req, res) => {
82
  });
83
 
84
  if (!product) {
85
- return res.status(404).json({ message: "Product not found" });
86
  }
87
 
88
  product.name = name ?? product.name;
@@ -111,10 +111,10 @@ export const deleteProduct = async (req, res) => {
111
  });
112
 
113
  if (!product) {
114
- return res.status(404).json({ message: "Product not found" });
115
  }
116
 
117
- res.status(200).json({ message: "Product deleted successfully" });
118
  } catch (error) {
119
  res.status(500).json({ message: error.message });
120
  }
 
11
  });
12
 
13
  if (exists) {
14
+ return res.status(400).json({ message: "المنتج موجود بالفعل" });
15
  }
16
 
17
  const product = await Product.create({
 
82
  });
83
 
84
  if (!product) {
85
+ return res.status(404).json({ message: "المنتج غير موجود" });
86
  }
87
 
88
  product.name = name ?? product.name;
 
111
  });
112
 
113
  if (!product) {
114
+ return res.status(404).json({ message: "المنج غير موجودلهف" });
115
  }
116
 
117
+ res.status(200).json({ message: "تم حذف المنتج بنجاح" });
118
  } catch (error) {
119
  res.status(500).json({ message: error.message });
120
  }
controller/reportController.js CHANGED
@@ -1,5 +1,6 @@
1
  import Invoice from "../models/InvoiceModel.js";
2
  import Expense from "../models/ExpenseModel.js";
 
3
  import Product from "../models/ProductModel.js";
4
  import Customer from "../models/CustomerModel.js";
5
  import Supplier from "../models/SupplierModel.js";
@@ -99,10 +100,11 @@ export const getDashboardOverview = async (req, res) => {
99
  const limit = parseInt(req.query.limit) || 5;
100
 
101
  // ── fetch all data in parallel ────────────────────────────────────────
102
- const [invoices, expenses, products, customers, suppliers, supplierInvoices, users] =
103
  await Promise.all([
104
  Invoice.find({ tenant: tenantId }).populate("customer", "name"),
105
  Expense.find({ tenant: tenantId }).sort({ date: -1 }),
 
106
  Product.find({ tenant: tenantId }).sort({ stock: 1, createdAt: -1 }),
107
  Customer.find({ tenant: tenantId }).sort({ createdAt: -1 }),
108
  Supplier.find({ tenant: tenantId }).sort({ createdAt: -1 }),
@@ -123,6 +125,7 @@ export const getDashboardOverview = async (req, res) => {
123
  }, 0);
124
 
125
  const expensesInRange = rangeExpenses.reduce((s, e) => s + toNumber(e.amount), 0);
 
126
  const outstandingReceivables = invoices.reduce((s, inv) => s + toNumber(inv.remainingAmount), 0);
127
  const supplierOutstanding = supplierInvoices.reduce((s, inv) => s + toNumber(inv.remainingAmount), 0);
128
 
@@ -172,6 +175,17 @@ export const getDashboardOverview = async (req, res) => {
172
  .filter((p) => isWithinRange(p.date, start, end))
173
  .sort((a, b) => new Date(b.date) - new Date(a.date));
174
 
 
 
 
 
 
 
 
 
 
 
 
175
  // ── recent invoices (within range, sorted newest first) ───────────────
176
  const allRecentInvoices = [...rangeInvoices]
177
  .sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt))
@@ -205,8 +219,9 @@ export const getDashboardOverview = async (req, res) => {
205
  metrics: {
206
  salesInRange,
207
  collectionsInRange,
 
208
  expensesInRange,
209
- netCashFlow: collectionsInRange - expensesInRange,
210
  outstandingReceivables,
211
  supplierOutstanding,
212
  customersCount: customers.length,
@@ -237,6 +252,7 @@ export const getDashboardOverview = async (req, res) => {
237
  amount: toNumber(e.amount),
238
  date: e.date,
239
  })),
 
240
  });
241
  } catch (error) {
242
  res.status(500).json({ message: error.message });
@@ -260,12 +276,16 @@ export const getDailyReport = async (req, res) => {
260
  endOfDay.setHours(23, 59, 59, 999);
261
 
262
  // ── fetch ─────────────────────────────────────────────────────────────
263
- const [invoices, expenses] = await Promise.all([
264
  Invoice.find({ tenant: tenantId }).populate("customer", "name"),
265
  Expense.find({
266
  tenant: tenantId,
267
  date: { $gte: startOfDay, $lte: endOfDay },
268
  }).sort({ date: -1 }),
 
 
 
 
269
  ]);
270
 
271
  // ── aggregate ─────────────────────────────────────────────────────────
@@ -307,6 +327,7 @@ export const getDailyReport = async (req, res) => {
307
  dailyPaymentsList.sort((a, b) => new Date(b.date) - new Date(a.date));
308
 
309
  const totalExpenses = expenses.reduce((s, e) => s + toNumber(e.amount), 0);
 
310
 
311
  // ── paginate both lists ───────────────────────────────────────────────
312
  const paginatedPayments = paginate(dailyPaymentsList, req.query.paymentsPage, limit);
@@ -320,16 +341,28 @@ export const getDailyReport = async (req, res) => {
320
  req.query.expensesPage,
321
  limit
322
  );
 
 
 
 
 
 
 
 
 
 
323
 
324
  // ── respond ───────────────────────────────────────────────────────────
325
  res.status(200).json({
326
  totalCashCollected,
327
  totalSalesToday,
 
328
  newInvoicesCount,
329
  totalExpenses,
330
- netCashInDrawer: totalCashCollected - totalExpenses,
331
  recentPayments: paginatedPayments, // { data: [...], pagination: {...} }
332
  expensesList: paginatedExpenses, // { data: [...], pagination: {...} }
 
333
  });
334
  } catch (error) {
335
  res.status(500).json({ message: error.message });
 
1
  import Invoice from "../models/InvoiceModel.js";
2
  import Expense from "../models/ExpenseModel.js";
3
+ import Income from "../models/IncomeModel.js";
4
  import Product from "../models/ProductModel.js";
5
  import Customer from "../models/CustomerModel.js";
6
  import Supplier from "../models/SupplierModel.js";
 
100
  const limit = parseInt(req.query.limit) || 5;
101
 
102
  // ── fetch all data in parallel ────────────────────────────────────────
103
+ const [invoices, expenses, incomes, products, customers, suppliers, supplierInvoices, users] =
104
  await Promise.all([
105
  Invoice.find({ tenant: tenantId }).populate("customer", "name"),
106
  Expense.find({ tenant: tenantId }).sort({ date: -1 }),
107
+ Income.find({ tenant: tenantId }).sort({ date: -1 }),
108
  Product.find({ tenant: tenantId }).sort({ stock: 1, createdAt: -1 }),
109
  Customer.find({ tenant: tenantId }).sort({ createdAt: -1 }),
110
  Supplier.find({ tenant: tenantId }).sort({ createdAt: -1 }),
 
125
  }, 0);
126
 
127
  const expensesInRange = rangeExpenses.reduce((s, e) => s + toNumber(e.amount), 0);
128
+ const incomeInRange = incomes.filter((inc) => isWithinRange(inc.date, start, end)).reduce((s, inc) => s + toNumber(inc.amount), 0);
129
  const outstandingReceivables = invoices.reduce((s, inv) => s + toNumber(inv.remainingAmount), 0);
130
  const supplierOutstanding = supplierInvoices.reduce((s, inv) => s + toNumber(inv.remainingAmount), 0);
131
 
 
175
  .filter((p) => isWithinRange(p.date, start, end))
176
  .sort((a, b) => new Date(b.date) - new Date(a.date));
177
 
178
+ const recentIncome = incomes
179
+ .filter((inc) => isWithinRange(inc.date, start, end))
180
+ .sort((a, b) => new Date(b.date) - new Date(a.date))
181
+ .slice(0, 8)
182
+ .map((inc) => ({
183
+ _id: inc._id,
184
+ title: inc.title,
185
+ amount: toNumber(inc.amount),
186
+ date: inc.date,
187
+ }));
188
+
189
  // ── recent invoices (within range, sorted newest first) ───────────────
190
  const allRecentInvoices = [...rangeInvoices]
191
  .sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt))
 
219
  metrics: {
220
  salesInRange,
221
  collectionsInRange,
222
+ incomeInRange,
223
  expensesInRange,
224
+ netCashFlow: collectionsInRange + incomeInRange - expensesInRange,
225
  outstandingReceivables,
226
  supplierOutstanding,
227
  customersCount: customers.length,
 
252
  amount: toNumber(e.amount),
253
  date: e.date,
254
  })),
255
+ recentIncome,
256
  });
257
  } catch (error) {
258
  res.status(500).json({ message: error.message });
 
276
  endOfDay.setHours(23, 59, 59, 999);
277
 
278
  // ── fetch ─────────────────────────────────────────────────────────────
279
+ const [invoices, expenses, incomes] = await Promise.all([
280
  Invoice.find({ tenant: tenantId }).populate("customer", "name"),
281
  Expense.find({
282
  tenant: tenantId,
283
  date: { $gte: startOfDay, $lte: endOfDay },
284
  }).sort({ date: -1 }),
285
+ Income.find({
286
+ tenant: tenantId,
287
+ date: { $gte: startOfDay, $lte: endOfDay },
288
+ }).sort({ date: -1 }),
289
  ]);
290
 
291
  // ── aggregate ─────────────────────────────────────────────────────────
 
327
  dailyPaymentsList.sort((a, b) => new Date(b.date) - new Date(a.date));
328
 
329
  const totalExpenses = expenses.reduce((s, e) => s + toNumber(e.amount), 0);
330
+ const totalIncome = incomes.reduce((s, inc) => s + toNumber(inc.amount), 0);
331
 
332
  // ── paginate both lists ───────────────────────────────────────────────
333
  const paginatedPayments = paginate(dailyPaymentsList, req.query.paymentsPage, limit);
 
341
  req.query.expensesPage,
342
  limit
343
  );
344
+ const paginatedIncome = paginate(
345
+ incomes.map((inc) => ({
346
+ _id: inc._id,
347
+ title: inc.title,
348
+ amount: toNumber(inc.amount),
349
+ date: inc.date,
350
+ })),
351
+ req.query.incomePage,
352
+ limit
353
+ );
354
 
355
  // ── respond ───────────────────────────────────────────────────────────
356
  res.status(200).json({
357
  totalCashCollected,
358
  totalSalesToday,
359
+ totalIncome,
360
  newInvoicesCount,
361
  totalExpenses,
362
+ netCashInDrawer: totalCashCollected + totalIncome - totalExpenses,
363
  recentPayments: paginatedPayments, // { data: [...], pagination: {...} }
364
  expensesList: paginatedExpenses, // { data: [...], pagination: {...} }
365
+ incomeList: paginatedIncome,
366
  });
367
  } catch (error) {
368
  res.status(500).json({ message: error.message });
controller/supplierController.js CHANGED
@@ -8,7 +8,7 @@ export const createSupplier = async (req, res) => {
8
  const tenantId = req.user.tenant._id;
9
 
10
  if (!name) {
11
- return res.status(400).json({ message: "Supplier name is required" });
12
  }
13
 
14
  const exists = await Supplier.findOne({
@@ -16,7 +16,7 @@ export const createSupplier = async (req, res) => {
16
  name: new RegExp(`^${name}$`, "i"),
17
  });
18
  if (exists) {
19
- return res.status(400).json({ message: "Supplier already exists" });
20
  }
21
 
22
  const supplier = await Supplier.create({
@@ -27,6 +27,7 @@ export const createSupplier = async (req, res) => {
27
  notes: req.body.notes?.trim() || "",
28
  createdBy: req.user._id,
29
  });
 
30
  res.status(201).json(supplier);
31
  } catch (err) {
32
  res.status(500).json({ message: err.message });
@@ -85,11 +86,9 @@ export const getSuppliers = async (req, res) => {
85
  },
86
  },
87
  ],
88
- totalCount: [
89
- { $count: "count" }
90
- ]
91
- }
92
- }
93
  ]);
94
 
95
  const suppliers = results[0].data;
@@ -115,14 +114,16 @@ export const getSupplierById = async (req, res) => {
115
  _id: req.params.id,
116
  tenant: req.user.tenant._id,
117
  });
 
118
  if (!supplier) {
119
- return res.status(404).json({ message: "Supplier not found" });
120
  }
121
 
122
  const invoice = await SupplierInvoice.findOne({
123
  supplier: supplier._id,
124
  tenant: req.user.tenant._id,
125
  });
 
126
  res.status(200).json({ ...supplier.toObject(), invoice });
127
  } catch (error) {
128
  res.status(500).json({ message: error.message });
@@ -132,15 +133,20 @@ export const getSupplierById = async (req, res) => {
132
  export const deleteSupplier = async (req, res) => {
133
  try {
134
  const supplierId = req.params.id;
 
135
  await Supplier.findOneAndDelete({
136
  _id: supplierId,
137
  tenant: req.user.tenant._id,
138
  });
 
139
  await SupplierInvoice.deleteMany({
140
  supplier: supplierId,
141
  tenant: req.user.tenant._id,
142
  });
143
- res.status(200).json({ message: "Supplier and linked purchase invoices deleted successfully" });
 
 
 
144
  } catch (error) {
145
  res.status(500).json({ message: error.message });
146
  }
@@ -158,13 +164,14 @@ export const addPurchasesToSupplier = async (req, res) => {
158
  });
159
 
160
  if (!supplier) {
161
- return res.status(404).json({ message: "Supplier not found" });
162
  }
163
 
164
  let invoice = await SupplierInvoice.findOne({
165
  supplier: supplierId,
166
  tenant: tenantId,
167
  });
 
168
  if (!invoice) {
169
  invoice = new SupplierInvoice({
170
  supplier: supplierId,
@@ -209,16 +216,23 @@ export const paySupplier = async (req, res) => {
209
  supplier: supplierId,
210
  tenant: req.user.tenant._id,
211
  });
 
212
  if (!invoice) {
213
- return res.status(404).json({ message: "No purchase invoice was found for this supplier" });
 
 
214
  }
215
 
216
  if (!amount || amount <= 0) {
217
- return res.status(400).json({ message: "Payment amount must be greater than zero" });
 
 
218
  }
219
 
220
  if (amount > invoice.remainingAmount) {
221
- return res.status(400).json({ message: "Payment amount is greater than the remaining balance" });
 
 
222
  }
223
 
224
  invoice.payments.push({
@@ -233,4 +247,4 @@ export const paySupplier = async (req, res) => {
233
  } catch (error) {
234
  res.status(500).json({ message: error.message });
235
  }
236
- };
 
8
  const tenantId = req.user.tenant._id;
9
 
10
  if (!name) {
11
+ return res.status(400).json({ message: "اسم المورد مطلوب" });
12
  }
13
 
14
  const exists = await Supplier.findOne({
 
16
  name: new RegExp(`^${name}$`, "i"),
17
  });
18
  if (exists) {
19
+ return res.status(400).json({ message: "هذا المورد موجود بالفعل" });
20
  }
21
 
22
  const supplier = await Supplier.create({
 
27
  notes: req.body.notes?.trim() || "",
28
  createdBy: req.user._id,
29
  });
30
+
31
  res.status(201).json(supplier);
32
  } catch (err) {
33
  res.status(500).json({ message: err.message });
 
86
  },
87
  },
88
  ],
89
+ totalCount: [{ $count: "count" }],
90
+ },
91
+ },
 
 
92
  ]);
93
 
94
  const suppliers = results[0].data;
 
114
  _id: req.params.id,
115
  tenant: req.user.tenant._id,
116
  });
117
+
118
  if (!supplier) {
119
+ return res.status(404).json({ message: "المورد غير موجود" });
120
  }
121
 
122
  const invoice = await SupplierInvoice.findOne({
123
  supplier: supplier._id,
124
  tenant: req.user.tenant._id,
125
  });
126
+
127
  res.status(200).json({ ...supplier.toObject(), invoice });
128
  } catch (error) {
129
  res.status(500).json({ message: error.message });
 
133
  export const deleteSupplier = async (req, res) => {
134
  try {
135
  const supplierId = req.params.id;
136
+
137
  await Supplier.findOneAndDelete({
138
  _id: supplierId,
139
  tenant: req.user.tenant._id,
140
  });
141
+
142
  await SupplierInvoice.deleteMany({
143
  supplier: supplierId,
144
  tenant: req.user.tenant._id,
145
  });
146
+
147
+ res.status(200).json({
148
+ message: "تم حذف المورد وجميع فواتير الشراء المرتبطة به بنجاح",
149
+ });
150
  } catch (error) {
151
  res.status(500).json({ message: error.message });
152
  }
 
164
  });
165
 
166
  if (!supplier) {
167
+ return res.status(404).json({ message: "المورد غير موجود" });
168
  }
169
 
170
  let invoice = await SupplierInvoice.findOne({
171
  supplier: supplierId,
172
  tenant: tenantId,
173
  });
174
+
175
  if (!invoice) {
176
  invoice = new SupplierInvoice({
177
  supplier: supplierId,
 
216
  supplier: supplierId,
217
  tenant: req.user.tenant._id,
218
  });
219
+
220
  if (!invoice) {
221
+ return res.status(404).json({
222
+ message: "لا توجد فاتورة شراء لهذا المورد",
223
+ });
224
  }
225
 
226
  if (!amount || amount <= 0) {
227
+ return res.status(400).json({
228
+ message: "يجب أن يكون مبلغ الدفع أكبر من صفر",
229
+ });
230
  }
231
 
232
  if (amount > invoice.remainingAmount) {
233
+ return res.status(400).json({
234
+ message: "مبلغ الدفع أكبر من الرصيد المتبقي",
235
+ });
236
  }
237
 
238
  invoice.payments.push({
 
247
  } catch (error) {
248
  res.status(500).json({ message: error.message });
249
  }
250
+ };