Mahmoud7456 commited on
Commit
ba7fcc6
·
verified ·
1 Parent(s): e2bc494

Upload 40 files

Browse files
controller/authController.js CHANGED
@@ -74,6 +74,13 @@ const sanitizeTenant = (tenant) => {
74
  const cashierAccountsCount = Number(tenant.cashierAccountsCount || 0);
75
  const cashierUtilizationPercent = computeCashierUtilization(tenant);
76
 
 
 
 
 
 
 
 
77
  return {
78
  _id: tenant._id,
79
  name: tenant.name,
@@ -95,8 +102,11 @@ const sanitizeTenant = (tenant) => {
95
  subscriptionPackage: packageInfo,
96
  cashierAccountsCount,
97
  cashierUtilizationPercent,
98
- availableCashierSlots:
99
- packageInfo.cashierLimit === null ? null : Math.max(0, Number(packageInfo.cashierLimit) - cashierAccountsCount),
 
 
 
100
  };
101
  };
102
 
@@ -370,8 +380,16 @@ export const login = async (req, res) => {
370
  }
371
 
372
  const { token, expiresAt } = createSessionToken();
373
- user.sessionToken = token;
374
- user.sessionTokenExpiresAt = expiresAt;
 
 
 
 
 
 
 
 
375
  user.lastLoginAt = new Date();
376
  await user.save();
377
  setAuthCookie(res, token);
@@ -455,7 +473,7 @@ export const getBranches = async (req, res) => {
455
 
456
  export const createBranch = async (req, res) => {
457
  if (!req.user?.tenant || !["owner", "admin"].includes(req.user.role)) {
458
- return res.status(403).json({ message: "Only tenant management can create branches" });
459
  }
460
 
461
  try {
@@ -466,18 +484,27 @@ export const createBranch = async (req, res) => {
466
  const code = normalizeBranchCode(req.body.code || name);
467
 
468
  if (!name) {
469
- return res.status(400).json({ message: "Branch name is required" });
 
 
 
 
 
 
 
 
 
470
  }
471
 
472
  const existsByName = await Branch.findOne({ tenant: tenantId, name });
473
  if (existsByName) {
474
- return res.status(400).json({ message: "Branch name already exists" });
475
  }
476
 
477
  if (code) {
478
  const existsByCode = await Branch.findOne({ tenant: tenantId, code });
479
  if (existsByCode) {
480
- return res.status(400).json({ message: "Branch code already exists" });
481
  }
482
  }
483
 
@@ -491,8 +518,11 @@ export const createBranch = async (req, res) => {
491
  createdBy: req.user._id,
492
  });
493
 
 
 
 
494
  res.status(201).json({
495
- message: "Branch created successfully",
496
  branch: buildBranchPayload(branch),
497
  });
498
  } catch (error) {
@@ -502,21 +532,21 @@ export const createBranch = async (req, res) => {
502
 
503
  export const updateBranch = async (req, res) => {
504
  if (!req.user?.tenant || !["owner", "admin"].includes(req.user.role)) {
505
- return res.status(403).json({ message: "Only tenant management can update branches" });
506
  }
507
 
508
  try {
509
  const tenantId = req.user.tenant._id;
510
  const branch = await Branch.findOne({ _id: req.params.id, tenant: tenantId });
511
  if (!branch) {
512
- return res.status(404).json({ message: "Branch not found" });
513
  }
514
 
515
  if (typeof req.body.name === "string" && req.body.name.trim()) {
516
  const nextName = req.body.name.trim();
517
  const nameConflict = await Branch.findOne({ tenant: tenantId, name: nextName, _id: { $ne: branch._id } });
518
  if (nameConflict) {
519
- return res.status(400).json({ message: "Branch name already exists" });
520
  }
521
  branch.name = nextName;
522
  }
@@ -526,7 +556,7 @@ export const updateBranch = async (req, res) => {
526
  if (nextCode) {
527
  const codeConflict = await Branch.findOne({ tenant: tenantId, code: nextCode, _id: { $ne: branch._id } });
528
  if (codeConflict) {
529
- return res.status(400).json({ message: "Branch code already exists" });
530
  }
531
  }
532
  branch.code = nextCode;
@@ -542,14 +572,14 @@ export const updateBranch = async (req, res) => {
542
 
543
  if (req.body.status && ["active", "suspended"].includes(req.body.status)) {
544
  if (branch.isPrimary && req.body.status === "suspended") {
545
- return res.status(400).json({ message: "Primary branch cannot be suspended" });
546
  }
547
  branch.status = req.body.status;
548
  }
549
 
550
  await branch.save();
551
  res.status(200).json({
552
- message: "Branch updated successfully",
553
  branch: buildBranchPayload(branch),
554
  });
555
  } catch (error) {
@@ -559,17 +589,17 @@ export const updateBranch = async (req, res) => {
559
 
560
  export const deleteBranch = async (req, res) => {
561
  if (!req.user?.tenant || !["owner", "admin"].includes(req.user.role)) {
562
- return res.status(403).json({ message: "Only tenant management can delete branches" });
563
  }
564
 
565
  try {
566
  const tenantId = req.user.tenant._id;
567
  const branch = await Branch.findOne({ _id: req.params.id, tenant: tenantId });
568
  if (!branch) {
569
- return res.status(404).json({ message: "Branch not found" });
570
  }
571
  if (branch.isPrimary) {
572
- return res.status(400).json({ message: "Primary branch cannot be deleted" });
573
  }
574
 
575
  const [assignedUsers, products, customers, invoices, incomes, expenses, suppliers, supplierInvoices] = await Promise.all([
@@ -594,12 +624,15 @@ export const deleteBranch = async (req, res) => {
594
  supplierInvoices > 0;
595
 
596
  if (hasLinkedData) {
597
- return res.status(400).json({ message: "Cannot delete branch with linked financial or user data" });
598
  }
599
 
600
  await branch.deleteOne();
601
- res.status(200).json({ message: "Branch deleted successfully" });
602
- } catch (error) {
 
 
 
603
  res.status(500).json({ message: error.message });
604
  }
605
  };
@@ -1041,17 +1074,26 @@ export const updateTenantPackage = async (req, res) => {
1041
  await normalizeTenantSubscriptionState(tenant);
1042
 
1043
  const nextPackage = getPackageDetails(packageKey);
1044
- const nextLimit = nextPackage.cashierLimit;
1045
  const currentCashiers = Number(tenant.cashierAccountsCount || 0);
 
 
 
 
 
 
 
 
1046
 
1047
- if (!isUnlimitedCashierLimit(nextLimit) && currentCashiers > nextLimit) {
 
1048
  return res.status(400).json({
1049
- message: "لا يمكن تخفيض الباقة. المستأجر لديه " + currentCashiers + " كاشير وحد الباقة الجديدة " + nextLimit + ".",
1050
  });
1051
  }
1052
 
1053
  tenant.subscriptionPackage = nextPackage.key;
1054
- tenant.cashierLimit = nextLimit;
 
1055
  await tenant.save();
1056
 
1057
  res.status(200).json({
@@ -1170,6 +1212,8 @@ export const createTenantOwner = async (req, res) => {
1170
  subscriptionPackage: packageDetails.key,
1171
  cashierLimit: packageDetails.cashierLimit,
1172
  cashierAccountsCount: 0,
 
 
1173
  });
1174
 
1175
  const primaryBranch = await Branch.create({
 
74
  const cashierAccountsCount = Number(tenant.cashierAccountsCount || 0);
75
  const cashierUtilizationPercent = computeCashierUtilization(tenant);
76
 
77
+ const branchCount = Number(tenant.branchCount || 1);
78
+ const branchLimit = tenant.branchLimit ?? packageInfo.branchLimit ?? 1;
79
+ const branchUtilizationPercent =
80
+ branchLimit === null
81
+ ? null
82
+ : Math.min(100, Math.round((branchCount / branchLimit) * 100));
83
+
84
  return {
85
  _id: tenant._id,
86
  name: tenant.name,
 
102
  subscriptionPackage: packageInfo,
103
  cashierAccountsCount,
104
  cashierUtilizationPercent,
105
+ branchCount,
106
+ branchLimit,
107
+ branchUtilizationPercent,
108
+ availableBranchSlots:
109
+ branchLimit === null ? null : Math.max(0, branchLimit - branchCount),
110
  };
111
  };
112
 
 
380
  }
381
 
382
  const { token, expiresAt } = createSessionToken();
383
+ if (["cashier"].includes(user.role)) {
384
+ // New token overwrites old one → old device gets 401 on next request
385
+ user.sessionToken = token;
386
+ user.sessionTokenExpiresAt = expiresAt;
387
+ }
388
+ else {
389
+ // owners/admins: just update token normally
390
+ user.sessionToken = token;
391
+ user.sessionTokenExpiresAt = expiresAt;
392
+ }
393
  user.lastLoginAt = new Date();
394
  await user.save();
395
  setAuthCookie(res, token);
 
473
 
474
  export const createBranch = async (req, res) => {
475
  if (!req.user?.tenant || !["owner", "admin"].includes(req.user.role)) {
476
+ return res.status(403).json({ message: "فقط إدارة الحساب يمكنها إنشاء فروع" });
477
  }
478
 
479
  try {
 
484
  const code = normalizeBranchCode(req.body.code || name);
485
 
486
  if (!name) {
487
+ return res.status(400).json({ message: "اسم الفرع مطلوب" });
488
+ }
489
+
490
+ // ✅ Enforce branch limit
491
+ const tenant = await Tenant.findById(tenantId);
492
+ const pkg = getPackageDetails(tenant.subscriptionPackage);
493
+ if (pkg.branchLimit !== null && tenant.branchCount >= pkg.branchLimit) {
494
+ return res.status(403).json({
495
+ message: `باقتك الحالية (${pkg.label}) تسمح بـ ${pkg.branchLimit} فرع فقط. يرجى الترقية لإضافة فروع جديدة.`,
496
+ });
497
  }
498
 
499
  const existsByName = await Branch.findOne({ tenant: tenantId, name });
500
  if (existsByName) {
501
+ return res.status(400).json({ message: "اسم الفرع مستخدم بالفعل" });
502
  }
503
 
504
  if (code) {
505
  const existsByCode = await Branch.findOne({ tenant: tenantId, code });
506
  if (existsByCode) {
507
+ return res.status(400).json({ message: "كود الفرع مستخدم بالفعل" });
508
  }
509
  }
510
 
 
518
  createdBy: req.user._id,
519
  });
520
 
521
+ // ✅ Increment branch count
522
+ await Tenant.findByIdAndUpdate(tenantId, { $inc: { branchCount: 1 } });
523
+
524
  res.status(201).json({
525
+ message: "تم إنشاء الفرع بنجاح",
526
  branch: buildBranchPayload(branch),
527
  });
528
  } catch (error) {
 
532
 
533
  export const updateBranch = async (req, res) => {
534
  if (!req.user?.tenant || !["owner", "admin"].includes(req.user.role)) {
535
+ return res.status(403).json({ message: "فقط إدارة الحساب يمكنها تعديل الفروع" });
536
  }
537
 
538
  try {
539
  const tenantId = req.user.tenant._id;
540
  const branch = await Branch.findOne({ _id: req.params.id, tenant: tenantId });
541
  if (!branch) {
542
+ return res.status(404).json({ message: "الفرع غير موجود" });
543
  }
544
 
545
  if (typeof req.body.name === "string" && req.body.name.trim()) {
546
  const nextName = req.body.name.trim();
547
  const nameConflict = await Branch.findOne({ tenant: tenantId, name: nextName, _id: { $ne: branch._id } });
548
  if (nameConflict) {
549
+ return res.status(400).json({ message: "اسم الفرع مستخدم بالفعل" });
550
  }
551
  branch.name = nextName;
552
  }
 
556
  if (nextCode) {
557
  const codeConflict = await Branch.findOne({ tenant: tenantId, code: nextCode, _id: { $ne: branch._id } });
558
  if (codeConflict) {
559
+ return res.status(400).json({ message: "كود الفرع مستخدم بالفعل" });
560
  }
561
  }
562
  branch.code = nextCode;
 
572
 
573
  if (req.body.status && ["active", "suspended"].includes(req.body.status)) {
574
  if (branch.isPrimary && req.body.status === "suspended") {
575
+ return res.status(400).json({ message: "لا يمكن إيقاف الفرع الرئيسي" });
576
  }
577
  branch.status = req.body.status;
578
  }
579
 
580
  await branch.save();
581
  res.status(200).json({
582
+ message: "تم تحديث بيانات الفرع بنجاح",
583
  branch: buildBranchPayload(branch),
584
  });
585
  } catch (error) {
 
589
 
590
  export const deleteBranch = async (req, res) => {
591
  if (!req.user?.tenant || !["owner", "admin"].includes(req.user.role)) {
592
+ return res.status(403).json({ message: "فقط إدارة الحساب يمكنها حذف الفروع" });
593
  }
594
 
595
  try {
596
  const tenantId = req.user.tenant._id;
597
  const branch = await Branch.findOne({ _id: req.params.id, tenant: tenantId });
598
  if (!branch) {
599
+ return res.status(404).json({ message: "الفرع غير موجود" });
600
  }
601
  if (branch.isPrimary) {
602
+ return res.status(400).json({ message: "لا يمكن حذف الفرع الرئيسي" });
603
  }
604
 
605
  const [assignedUsers, products, customers, invoices, incomes, expenses, suppliers, supplierInvoices] = await Promise.all([
 
624
  supplierInvoices > 0;
625
 
626
  if (hasLinkedData) {
627
+ return res.status(400).json({ message: "لا يمكن حذف الفرع لوجود بيانات مرتبطة به (مستخدمين أو معاملات مالية)" });
628
  }
629
 
630
  await branch.deleteOne();
631
+ await Tenant.findByIdAndUpdate(tenantId, { $inc: { branchCount: -1 } });
632
+
633
+ res.status(200).json({ message: "تم حذف الفرع بنجاح" });
634
+ }
635
+ catch (error) {
636
  res.status(500).json({ message: error.message });
637
  }
638
  };
 
1074
  await normalizeTenantSubscriptionState(tenant);
1075
 
1076
  const nextPackage = getPackageDetails(packageKey);
 
1077
  const currentCashiers = Number(tenant.cashierAccountsCount || 0);
1078
+ const currentBranches = Number(tenant.branchCount || 1);
1079
+
1080
+ // ✅ Check cashier limit
1081
+ if (!isUnlimitedCashierLimit(nextPackage.cashierLimit) && currentCashiers > nextPackage.cashierLimit) {
1082
+ return res.status(400).json({
1083
+ message: `لا يمكن تخفيض الباقة. المستأجر لديه ${currentCashiers} كاشير وحد الباقة الجديدة ${nextPackage.cashierLimit}.`,
1084
+ });
1085
+ }
1086
 
1087
+ // ✅ Check branch limit
1088
+ if (nextPackage.branchLimit !== null && currentBranches > nextPackage.branchLimit) {
1089
  return res.status(400).json({
1090
+ message: `لا يمكن تخفيض الباقة. المستأجر لديه ${currentBranches} فرع وحد الباقة الجديدة ${nextPackage.branchLimit}.`,
1091
  });
1092
  }
1093
 
1094
  tenant.subscriptionPackage = nextPackage.key;
1095
+ tenant.cashierLimit = nextPackage.cashierLimit;
1096
+ tenant.branchLimit = nextPackage.branchLimit; // ✅ sync
1097
  await tenant.save();
1098
 
1099
  res.status(200).json({
 
1212
  subscriptionPackage: packageDetails.key,
1213
  cashierLimit: packageDetails.cashierLimit,
1214
  cashierAccountsCount: 0,
1215
+ branchLimit: packageDetails.branchLimit,
1216
+ branchCount: 1,
1217
  });
1218
 
1219
  const primaryBranch = await Branch.create({
controller/catalogController.js ADDED
@@ -0,0 +1,349 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import CatalogCategory from "../models/CatalogCategoryModel.js";
2
+ import CatalogItem from "../models/CatalogItemModel.js";
3
+ import { resolveBranchForWrite, resolveScopedBranch } from "../utils/branchContext.js";
4
+
5
+ const normalizeName = (value) => String(value || "").trim();
6
+
7
+ const getScopedCategory = async ({ categoryId, tenantId, branchId }) => {
8
+ if (!categoryId) {
9
+ return null;
10
+ }
11
+
12
+ return CatalogCategory.findOne({
13
+ _id: categoryId,
14
+ tenant: tenantId,
15
+ branch: branchId,
16
+ });
17
+ };
18
+
19
+ export const getCatalogCategories = async (req, res) => {
20
+ try {
21
+ const search = normalizeName(req.query.search);
22
+ const activeOnly = req.query.activeOnly === "true";
23
+ const { tenantId, branchFilter } = await resolveScopedBranch(req);
24
+
25
+ const query = {
26
+ tenant: tenantId,
27
+ ...branchFilter,
28
+ };
29
+
30
+ if (search) {
31
+ query.name = { $regex: search, $options: "i" };
32
+ }
33
+
34
+ if (activeOnly) {
35
+ query.isActive = true;
36
+ }
37
+
38
+ const categories = await CatalogCategory.find(query).sort({ sortOrder: 1, name: 1 });
39
+ res.status(200).json({ data: categories });
40
+ } catch (error) {
41
+ res.status(500).json({ message: error.message });
42
+ }
43
+ };
44
+
45
+ export const createCatalogCategory = async (req, res) => {
46
+ try {
47
+ const branch = await resolveBranchForWrite(req);
48
+ const tenantId = req.user.tenant._id;
49
+ const name = normalizeName(req.body.name);
50
+
51
+ if (!name) {
52
+ return res.status(400).json({ message: "اسم الفئة مطلوب" });
53
+ }
54
+
55
+ const existing = await CatalogCategory.findOne({
56
+ tenant: tenantId,
57
+ branch: branch._id,
58
+ name,
59
+ });
60
+
61
+ if (existing) {
62
+ return res.status(400).json({ message: "الفئة موجودة بالفعل" });
63
+ }
64
+
65
+ const category = await CatalogCategory.create({
66
+ tenant: tenantId,
67
+ branch: branch._id,
68
+ name,
69
+ description: normalizeName(req.body.description),
70
+ sortOrder: Number(req.body.sortOrder || 0),
71
+ isActive: req.body.isActive ?? true,
72
+ createdBy: req.user._id,
73
+ });
74
+
75
+ res.status(201).json(category);
76
+ } catch (error) {
77
+ res.status(500).json({ message: error.message });
78
+ }
79
+ };
80
+
81
+ export const updateCatalogCategory = async (req, res) => {
82
+ try {
83
+ const { branchFilter } = await resolveScopedBranch(req);
84
+ const category = await CatalogCategory.findOne({
85
+ _id: req.params.id,
86
+ tenant: req.user.tenant._id,
87
+ ...branchFilter,
88
+ });
89
+
90
+ if (!category) {
91
+ return res.status(404).json({ message: "الفئة غير موجودة" });
92
+ }
93
+
94
+ const nextName = normalizeName(req.body.name);
95
+ if (nextName && nextName !== category.name) {
96
+ const duplicate = await CatalogCategory.findOne({
97
+ _id: { $ne: category._id },
98
+ tenant: category.tenant,
99
+ branch: category.branch,
100
+ name: nextName,
101
+ });
102
+
103
+ if (duplicate) {
104
+ return res.status(400).json({ message: "اسم الفئة مستخدم بالفعل" });
105
+ }
106
+
107
+ category.name = nextName;
108
+ }
109
+
110
+ if (req.body.description !== undefined) {
111
+ category.description = normalizeName(req.body.description);
112
+ }
113
+ if (req.body.sortOrder !== undefined) {
114
+ category.sortOrder = Number(req.body.sortOrder || 0);
115
+ }
116
+ if (req.body.isActive !== undefined) {
117
+ category.isActive = Boolean(req.body.isActive);
118
+ }
119
+
120
+ await category.save();
121
+ res.status(200).json(category);
122
+ } catch (error) {
123
+ res.status(500).json({ message: error.message });
124
+ }
125
+ };
126
+
127
+ export const deleteCatalogCategory = async (req, res) => {
128
+ try {
129
+ const { branchFilter } = await resolveScopedBranch(req);
130
+ const category = await CatalogCategory.findOne({
131
+ _id: req.params.id,
132
+ tenant: req.user.tenant._id,
133
+ ...branchFilter,
134
+ });
135
+
136
+ if (!category) {
137
+ return res.status(404).json({ message: "الفئة غير موجودة" });
138
+ }
139
+
140
+ const linkedItems = await CatalogItem.countDocuments({
141
+ tenant: req.user.tenant._id,
142
+ category: category._id,
143
+ ...branchFilter,
144
+ });
145
+
146
+ if (linkedItems > 0) {
147
+ return res.status(400).json({ message: "احذف عناصر الفئة أولاً قبل حذفها" });
148
+ }
149
+
150
+ await category.deleteOne();
151
+ res.status(200).json({ message: "تم حذف الفئة بنجاح" });
152
+ } catch (error) {
153
+ res.status(500).json({ message: error.message });
154
+ }
155
+ };
156
+
157
+ export const getCatalogItems = async (req, res) => {
158
+ try {
159
+ const page = Math.max(1, parseInt(req.query.page) || 1);
160
+ const limit = Math.max(1, parseInt(req.query.limit) || 20);
161
+ const skip = (page - 1) * limit;
162
+ const search = normalizeName(req.query.search);
163
+ const categoryId = req.query.categoryId || "";
164
+ const activeOnly = req.query.activeOnly === "true";
165
+ const { tenantId, branchFilter } = await resolveScopedBranch(req);
166
+
167
+ const query = {
168
+ tenant: tenantId,
169
+ ...branchFilter,
170
+ };
171
+
172
+ if (search) {
173
+ query.name = { $regex: search, $options: "i" };
174
+ }
175
+ if (categoryId) {
176
+ query.category = categoryId;
177
+ }
178
+ if (activeOnly) {
179
+ query.isActive = true;
180
+ }
181
+
182
+ const total = await CatalogItem.countDocuments(query);
183
+ const items = await CatalogItem.find(query)
184
+ .populate("category", "name")
185
+ .sort({ sortOrder: 1, createdAt: -1 })
186
+ .skip(skip)
187
+ .limit(limit);
188
+
189
+ res.status(200).json({
190
+ data: items.map((item) => ({
191
+ ...item.toObject(),
192
+ categoryName: item.category?.name || "",
193
+ })),
194
+ pagination: {
195
+ total,
196
+ page,
197
+ limit,
198
+ totalPages: Math.ceil(total / limit),
199
+ },
200
+ });
201
+ } catch (error) {
202
+ res.status(500).json({ message: error.message });
203
+ }
204
+ };
205
+
206
+ export const createCatalogItem = async (req, res) => {
207
+ try {
208
+ const branch = await resolveBranchForWrite(req);
209
+ const tenantId = req.user.tenant._id;
210
+ const name = normalizeName(req.body.name);
211
+
212
+ if (!name) {
213
+ return res.status(400).json({ message: "اسم العنصر مطلوب" });
214
+ }
215
+
216
+ const category = await getScopedCategory({
217
+ categoryId: req.body.categoryId,
218
+ tenantId,
219
+ branchId: branch._id,
220
+ });
221
+
222
+ if (!category) {
223
+ return res.status(400).json({ message: "فئة الكتالوج غير موجودة" });
224
+ }
225
+
226
+ const duplicate = await CatalogItem.findOne({
227
+ tenant: tenantId,
228
+ branch: branch._id,
229
+ category: category._id,
230
+ name,
231
+ });
232
+
233
+ if (duplicate) {
234
+ return res.status(400).json({ message: "العنصر موجود بالفعل داخل هذه الفئة" });
235
+ }
236
+
237
+ const item = await CatalogItem.create({
238
+ tenant: tenantId,
239
+ branch: branch._id,
240
+ category: category._id,
241
+ name,
242
+ description: normalizeName(req.body.description),
243
+ price: Number(req.body.price || 0),
244
+ costPrice: Number(req.body.costPrice || 0),
245
+ sortOrder: Number(req.body.sortOrder || 0),
246
+ isActive: req.body.isActive ?? true,
247
+ createdBy: req.user._id,
248
+ });
249
+
250
+ const populated = await CatalogItem.findById(item._id).populate("category", "name");
251
+ res.status(201).json({
252
+ ...populated.toObject(),
253
+ categoryName: populated.category?.name || "",
254
+ });
255
+ } catch (error) {
256
+ res.status(500).json({ message: error.message });
257
+ }
258
+ };
259
+
260
+ export const updateCatalogItem = async (req, res) => {
261
+ try {
262
+ const { branchFilter, branchId } = await resolveScopedBranch(req);
263
+ const item = await CatalogItem.findOne({
264
+ _id: req.params.id,
265
+ tenant: req.user.tenant._id,
266
+ ...branchFilter,
267
+ });
268
+
269
+ if (!item) {
270
+ return res.status(404).json({ message: "عنصر الكتالوج غير موجود" });
271
+ }
272
+
273
+ if (req.body.categoryId && String(req.body.categoryId) !== String(item.category)) {
274
+ const targetCategory = await getScopedCategory({
275
+ categoryId: req.body.categoryId,
276
+ tenantId: req.user.tenant._id,
277
+ branchId,
278
+ });
279
+
280
+ if (!targetCategory) {
281
+ return res.status(400).json({ message: "فئة الكتالوج غير موجودة" });
282
+ }
283
+
284
+ item.category = targetCategory._id;
285
+ }
286
+
287
+ const nextName = normalizeName(req.body.name);
288
+ if (nextName && nextName !== item.name) {
289
+ const duplicate = await CatalogItem.findOne({
290
+ _id: { $ne: item._id },
291
+ tenant: item.tenant,
292
+ branch: item.branch,
293
+ category: item.category,
294
+ name: nextName,
295
+ });
296
+
297
+ if (duplicate) {
298
+ return res.status(400).json({ message: "اسم العنصر مستخدم بالفعل داخل هذه الفئة" });
299
+ }
300
+
301
+ item.name = nextName;
302
+ }
303
+
304
+ if (req.body.description !== undefined) {
305
+ item.description = normalizeName(req.body.description);
306
+ }
307
+ if (req.body.price !== undefined) {
308
+ item.price = Number(req.body.price || 0);
309
+ }
310
+ if (req.body.costPrice !== undefined) {
311
+ item.costPrice = Number(req.body.costPrice || 0);
312
+ }
313
+ if (req.body.sortOrder !== undefined) {
314
+ item.sortOrder = Number(req.body.sortOrder || 0);
315
+ }
316
+ if (req.body.isActive !== undefined) {
317
+ item.isActive = Boolean(req.body.isActive);
318
+ }
319
+
320
+ await item.save();
321
+ const populated = await CatalogItem.findById(item._id).populate("category", "name");
322
+
323
+ res.status(200).json({
324
+ ...populated.toObject(),
325
+ categoryName: populated.category?.name || "",
326
+ });
327
+ } catch (error) {
328
+ res.status(500).json({ message: error.message });
329
+ }
330
+ };
331
+
332
+ export const deleteCatalogItem = async (req, res) => {
333
+ try {
334
+ const { branchFilter } = await resolveScopedBranch(req);
335
+ const item = await CatalogItem.findOneAndDelete({
336
+ _id: req.params.id,
337
+ tenant: req.user.tenant._id,
338
+ ...branchFilter,
339
+ });
340
+
341
+ if (!item) {
342
+ return res.status(404).json({ message: "عنصر الكتالوج غير موجود" });
343
+ }
344
+
345
+ res.status(200).json({ message: "تم حذف عنصر الكتالوج بنجاح" });
346
+ } catch (error) {
347
+ res.status(500).json({ message: error.message });
348
+ }
349
+ };
controller/customerController.js CHANGED
@@ -147,26 +147,29 @@ export const getCustomerById = async (req, res) => {
147
  return res.status(404).json({ message: "العميل غير موجود" });
148
  }
149
 
150
- // Pagination & Sorting
151
  const page = parseInt(req.query.page) || 1;
152
  const limit = parseInt(req.query.limit) || 5;
153
  const sortField = req.query.sortField || "createdAt";
154
  const sortOrder = req.query.sortOrder === "asc" ? 1 : -1;
155
  const skip = (page - 1) * limit;
156
 
157
- const totalInvoices = await Invoice.countDocuments({
158
- customer: customer._id,
159
- tenant: req.user.tenant._id,
160
- ...branchFilter,
161
- });
162
 
163
- const invoices = await Invoice.find({
164
  customer: customer._id,
165
  tenant: req.user.tenant._id,
166
- ...branchFilter,
167
  isDeleted: false,
168
- })
 
 
 
 
 
 
169
  .populate("items.productId", "name price")
 
170
  .sort({ [sortField]: sortOrder })
171
  .skip(skip)
172
  .limit(limit);
 
147
  return res.status(404).json({ message: "العميل غير موجود" });
148
  }
149
 
 
150
  const page = parseInt(req.query.page) || 1;
151
  const limit = parseInt(req.query.limit) || 5;
152
  const sortField = req.query.sortField || "createdAt";
153
  const sortOrder = req.query.sortOrder === "asc" ? 1 : -1;
154
  const skip = (page - 1) * limit;
155
 
156
+ const statusFilter = req.query.status && req.query.status !== "all"
157
+ ? { status: req.query.status }
158
+ : {};
 
 
159
 
160
+ const invoiceQuery = {
161
  customer: customer._id,
162
  tenant: req.user.tenant._id,
 
163
  isDeleted: false,
164
+ ...branchFilter,
165
+ ...statusFilter,
166
+ };
167
+
168
+ const totalInvoices = await Invoice.countDocuments(invoiceQuery);
169
+
170
+ const invoices = await Invoice.find(invoiceQuery)
171
  .populate("items.productId", "name price")
172
+ .populate("items.catalogItemId", "name price")
173
  .sort({ [sortField]: sortOrder })
174
  .skip(skip)
175
  .limit(limit);
controller/invoiceController.js CHANGED
@@ -1,12 +1,15 @@
1
  import Invoice from "../models/InvoiceModel.js";
2
  import Customer from "../models/CustomerModel.js";
3
  import Product from "../models/ProductModel.js";
 
4
  import Counter from "../models/CounterModel.js";
5
  import Income from "../models/IncomeModel.js";
6
  import { resolveBranchForWrite, resolveScopedBranch } from "../utils/branchContext.js";
7
 
8
  const WALK_IN_CUSTOMER_NAME = "Walking-in Customer";
9
 
 
 
10
 
11
  async function generateInvoiceNumber(tenantId, branchId) {
12
  const counter = await Counter.findOneAndUpdate(
@@ -43,7 +46,7 @@ const getOrCreateWalkInCustomer = async (tenantId, branchId, userId) => {
43
 
44
  const ensureStockAvailability = async (items, tenantId, branchId) => {
45
  for (const item of items) {
46
- if (!item.productId) {
47
  continue;
48
  }
49
 
@@ -62,22 +65,63 @@ const ensureStockAvailability = async (items, tenantId, branchId) => {
62
  }
63
  };
64
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
65
  const applyInvoiceItemsAndStock = async (invoice, items, tenantId, branchId) => {
66
  for (const item of items) {
67
  const quantity = Number(item.quantity || 0);
68
- const price = Number(item.price || 0);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69
 
70
  invoice.items.push({
71
- name: item.name,
72
  quantity,
73
- price,
74
- total: quantity * price,
75
- type: item.type || (item.productId ? "product" : "service"),
76
  ...(item.productId ? { productId: item.productId } : {}),
77
  ...(item.serviceId ? { serviceId: item.serviceId } : {}),
 
78
  });
79
 
80
- if (item.productId) {
81
  await Product.findOneAndUpdate(
82
  { _id: item.productId, tenant: tenantId, branch: branchId },
83
  { $inc: { stock: -quantity } }
@@ -86,72 +130,78 @@ const applyInvoiceItemsAndStock = async (invoice, items, tenantId, branchId) =>
86
  }
87
  };
88
 
89
- const createIncomeForPayment = async ({ tenantId, branchId, invoice, customer, amount, userId, date, notes }) => {
 
 
 
 
 
 
 
 
 
 
 
90
  if (!amount || amount <= 0) {
91
  return;
92
  }
93
 
94
  // If the invoice has services, calculate the ratio and split the income record
95
- const totalItemRevenue = (invoice.serviceRevenue || 0) + (invoice.productRevenue || 0);
96
-
97
- if (invoice.hasServices && totalItemRevenue > 0) {
98
- const serviceRatio = (invoice.serviceRevenue || 0) / totalItemRevenue;
99
- const serviceAmount = Number((amount * serviceRatio).toFixed(2));
100
- const otherAmount = Number((amount - serviceAmount).toFixed(2));
101
-
102
- // 1. Create service income record
103
- if (serviceAmount > 0) {
104
- await Income.create({
105
- tenant: tenantId,
106
- branch: branchId,
107
- title: `Service Income - ${invoice.invoiceNumber}`,
108
- category: "service_income",
109
- amount: serviceAmount,
110
- paymentMethod: "cash",
111
- notes: notes || `Service portion for invoice ${invoice.invoiceNumber}`,
112
- sourceType: "invoice_payment",
113
- relatedInvoice: invoice._id,
114
- relatedCustomer: customer?._id || null,
115
- date: date || new Date(),
116
- createdBy: userId || null,
117
- });
118
- }
119
 
120
- // 2. Create standard income record for rest
121
- if (otherAmount > 0) {
122
- await Income.create({
123
- tenant: tenantId,
124
- branch: branchId,
125
- title: `Product/Product Sale - ${invoice.invoiceNumber}`,
126
- category: customer?.isWalkIn ? "walk_in_sale" : "invoice_payment",
127
- amount: otherAmount,
128
- paymentMethod: "cash",
129
- notes: notes || `Product portion for invoice ${invoice.invoiceNumber}`,
130
- sourceType: "invoice_payment",
131
- relatedInvoice: invoice._id,
132
- relatedCustomer: customer?._id || null,
133
- date: date || new Date(),
134
- createdBy: userId || null,
135
- });
136
- }
137
  return;
138
  }
139
 
140
- // Standard behavior for non-service invoices
141
- await Income.create({
142
- tenant: tenantId,
143
- branch: branchId,
144
- title: `Invoice payment - ${invoice.invoiceNumber}`,
145
- category: customer?.isWalkIn ? "walk_in_sale" : "invoice_payment",
146
- amount,
147
- paymentMethod: "cash",
148
- notes: notes || `Cash payment recorded for invoice ${invoice.invoiceNumber}`,
149
- sourceType: "invoice_payment",
150
- relatedInvoice: invoice._id,
151
- relatedCustomer: customer?._id || null,
152
- date: date || new Date(),
153
- createdBy: userId || null,
154
- });
 
 
 
 
 
 
 
 
 
 
 
 
 
155
  };
156
 
157
  export const addItemToInvoice = async (req, res) => {
@@ -203,6 +253,7 @@ export const addItemToInvoice = async (req, res) => {
203
  taxAmount: Math.max(Number(tax) || 0, 0),
204
  });
205
 
 
206
  await ensureStockAvailability(items, tenantId, branchId);
207
  await applyInvoiceItemsAndStock(invoice, items, tenantId, branchId);
208
 
@@ -261,6 +312,7 @@ export const createWalkInCashSale = async (req, res) => {
261
  }
262
 
263
  try {
 
264
  await ensureStockAvailability(items, tenantId, branchId);
265
 
266
  let customer;
@@ -318,6 +370,7 @@ export const createWalkInCashSale = async (req, res) => {
318
  amount: paymentAmount,
319
  userId: req.user._id,
320
  notes: "Walk-in cash sale",
 
321
  });
322
 
323
  const populatedInvoice = await Invoice.findById(invoice._id).populate("customer", "name isWalkIn");
@@ -397,6 +450,10 @@ export const getInvoiceById = async (req, res) => {
397
  .populate({
398
  path: "items.productId",
399
  select: "name price",
 
 
 
 
400
  });
401
 
402
  if (!invoice) {
@@ -433,6 +490,29 @@ export const updateInvoiceItem = async (req, res) => {
433
  const newQuantity = Number(quantity);
434
  const newPrice = Number(price);
435
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
436
  if (item.productId) {
437
  const quantityDifference = newQuantity - Number(item.quantity);
438
  const product = await Product.findOne({
@@ -572,6 +652,8 @@ export const payInvoice = async (req, res) => {
572
  customer: invoice.customer,
573
  amount,
574
  userId: req.user._id,
 
 
575
  });
576
 
577
  res.json(invoice);
 
1
  import Invoice from "../models/InvoiceModel.js";
2
  import Customer from "../models/CustomerModel.js";
3
  import Product from "../models/ProductModel.js";
4
+ import CatalogItem from "../models/CatalogItemModel.js";
5
  import Counter from "../models/CounterModel.js";
6
  import Income from "../models/IncomeModel.js";
7
  import { resolveBranchForWrite, resolveScopedBranch } from "../utils/branchContext.js";
8
 
9
  const WALK_IN_CUSTOMER_NAME = "Walking-in Customer";
10
 
11
+ const INVOICE_ITEM_TYPES = ["product", "service", "catalog"];
12
+
13
 
14
  async function generateInvoiceNumber(tenantId, branchId) {
15
  const counter = await Counter.findOneAndUpdate(
 
46
 
47
  const ensureStockAvailability = async (items, tenantId, branchId) => {
48
  for (const item of items) {
49
+ if (item.type !== "product" || !item.productId) {
50
  continue;
51
  }
52
 
 
65
  }
66
  };
67
 
68
+ const validateCatalogItems = async (items, tenantId, branchId) => {
69
+ for (const item of items) {
70
+ if (item.type !== "catalog" || !item.catalogItemId) {
71
+ continue;
72
+ }
73
+
74
+ const catalogItem = await CatalogItem.findOne({
75
+ _id: item.catalogItemId,
76
+ tenant: tenantId,
77
+ branch: branchId,
78
+ isActive: true,
79
+ }).populate("category", "name");
80
+
81
+ if (!catalogItem) {
82
+ const error = new Error(`عنصر الكتالوج غير موجود: ${item.name}`);
83
+ error.statusCode = 404;
84
+ throw error;
85
+ }
86
+ }
87
+ };
88
+
89
  const applyInvoiceItemsAndStock = async (invoice, items, tenantId, branchId) => {
90
  for (const item of items) {
91
  const quantity = Number(item.quantity || 0);
92
+ const normalizedType = INVOICE_ITEM_TYPES.includes(item.type) ? item.type : item.productId ? "product" : "service";
93
+ let resolvedName = item.name;
94
+ let resolvedPrice = Number(item.price || 0);
95
+
96
+ if (normalizedType === "catalog" && item.catalogItemId) {
97
+ const catalogItem = await CatalogItem.findOne({
98
+ _id: item.catalogItemId,
99
+ tenant: tenantId,
100
+ branch: branchId,
101
+ });
102
+
103
+ if (!catalogItem) {
104
+ const error = new Error(`عنصر الكتالوج غير موجود: ${item.name}`);
105
+ error.statusCode = 404;
106
+ throw error;
107
+ }
108
+
109
+ resolvedName = catalogItem.name;
110
+ resolvedPrice = Number(catalogItem.price || 0);
111
+ }
112
 
113
  invoice.items.push({
114
+ name: resolvedName,
115
  quantity,
116
+ price: resolvedPrice,
117
+ total: quantity * resolvedPrice,
118
+ type: normalizedType,
119
  ...(item.productId ? { productId: item.productId } : {}),
120
  ...(item.serviceId ? { serviceId: item.serviceId } : {}),
121
+ ...(item.catalogItemId ? { catalogItemId: item.catalogItemId } : {}),
122
  });
123
 
124
+ if (normalizedType === "product" && item.productId) {
125
  await Product.findOneAndUpdate(
126
  { _id: item.productId, tenant: tenantId, branch: branchId },
127
  { $inc: { stock: -quantity } }
 
130
  }
131
  };
132
 
133
+ const createIncomeForPayment = async ({
134
+ tenantId,
135
+ branchId,
136
+ invoice,
137
+ customer,
138
+ amount,
139
+ userId,
140
+ date,
141
+ notes,
142
+ paymentMethod = "cash",
143
+ transferType = null,
144
+ }) => {
145
  if (!amount || amount <= 0) {
146
  return;
147
  }
148
 
149
  // If the invoice has services, calculate the ratio and split the income record
150
+ const revenueBuckets = [
151
+ {
152
+ amount: Number(invoice.serviceRevenue || 0),
153
+ category: "service_income",
154
+ title: `Service Income - ${invoice.invoiceNumber}`,
155
+ notesFallback: `Service portion for invoice ${invoice.invoiceNumber}`,
156
+ },
157
+ {
158
+ amount: Number(invoice.catalogRevenue || 0),
159
+ category: "catalog_sale",
160
+ title: `Catalog Sale - ${invoice.invoiceNumber}`,
161
+ notesFallback: `Catalog portion for invoice ${invoice.invoiceNumber}`,
162
+ },
163
+ {
164
+ amount: Number(invoice.productRevenue || 0),
165
+ category: customer?.isWalkIn ? "walk_in_sale" : "invoice_payment",
166
+ title: `Invoice payment - ${invoice.invoiceNumber}`,
167
+ notesFallback: `Product portion for invoice ${invoice.invoiceNumber}`,
168
+ },
169
+ ].filter((bucket) => bucket.amount > 0);
 
 
 
 
170
 
171
+ const totalItemRevenue = revenueBuckets.reduce((sum, bucket) => sum + bucket.amount, 0);
172
+
173
+ if (!totalItemRevenue) {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
174
  return;
175
  }
176
 
177
+ let remainingAmount = Number(amount);
178
+ const incomesToCreate = revenueBuckets.map((bucket, index) => {
179
+ const isLastBucket = index === revenueBuckets.length - 1;
180
+ const allocatedAmount = isLastBucket
181
+ ? Number(remainingAmount.toFixed(2))
182
+ : Number(((Number(amount) * bucket.amount) / totalItemRevenue).toFixed(2));
183
+
184
+ remainingAmount = Number((remainingAmount - allocatedAmount).toFixed(2));
185
+
186
+ return {
187
+ tenant: tenantId,
188
+ branch: branchId,
189
+ title: bucket.title,
190
+ category: bucket.category,
191
+ amount: allocatedAmount,
192
+ paymentMethod,
193
+ notes: notes || bucket.notesFallback,
194
+ sourceType: "invoice_payment",
195
+ relatedInvoice: invoice._id,
196
+ relatedCustomer: customer?._id || null,
197
+ date: date || new Date(),
198
+ createdBy: userId || null,
199
+ };
200
+ }).filter((entry) => entry.amount > 0);
201
+
202
+ if (incomesToCreate.length) {
203
+ await Income.insertMany(incomesToCreate);
204
+ }
205
  };
206
 
207
  export const addItemToInvoice = async (req, res) => {
 
253
  taxAmount: Math.max(Number(tax) || 0, 0),
254
  });
255
 
256
+ await validateCatalogItems(items, tenantId, branchId);
257
  await ensureStockAvailability(items, tenantId, branchId);
258
  await applyInvoiceItemsAndStock(invoice, items, tenantId, branchId);
259
 
 
312
  }
313
 
314
  try {
315
+ await validateCatalogItems(items, tenantId, branchId);
316
  await ensureStockAvailability(items, tenantId, branchId);
317
 
318
  let customer;
 
370
  amount: paymentAmount,
371
  userId: req.user._id,
372
  notes: "Walk-in cash sale",
373
+ paymentMethod: "cash",
374
  });
375
 
376
  const populatedInvoice = await Invoice.findById(invoice._id).populate("customer", "name isWalkIn");
 
450
  .populate({
451
  path: "items.productId",
452
  select: "name price",
453
+ })
454
+ .populate({
455
+ path: "items.catalogItemId",
456
+ select: "name price",
457
  });
458
 
459
  if (!invoice) {
 
490
  const newQuantity = Number(quantity);
491
  const newPrice = Number(price);
492
 
493
+ if (item.type === "catalog" && item.catalogItemId) {
494
+ const catalogItem = await CatalogItem.findOne({
495
+ _id: item.catalogItemId,
496
+ tenant: req.user.tenant._id,
497
+ ...branchFilter,
498
+ });
499
+
500
+ if (!catalogItem) {
501
+ return res.status(404).json({ message: "عنصر الكتالوج المرتبط لم يعد موجودًا" });
502
+ }
503
+
504
+ item.name = catalogItem.name;
505
+ item.quantity = newQuantity;
506
+ item.price = Number(catalogItem.price || 0);
507
+ item.total = item.quantity * item.price;
508
+ await invoice.save();
509
+
510
+ return res.status(200).json({
511
+ message: "تم تحديث بند الكتالوج بنجاح",
512
+ invoice,
513
+ });
514
+ }
515
+
516
  if (item.productId) {
517
  const quantityDifference = newQuantity - Number(item.quantity);
518
  const product = await Product.findOne({
 
652
  customer: invoice.customer,
653
  amount,
654
  userId: req.user._id,
655
+ paymentMethod,
656
+ transferType,
657
  });
658
 
659
  res.json(invoice);
controller/reportController.js CHANGED
@@ -6,6 +6,7 @@ import Customer from "../models/CustomerModel.js";
6
  import Supplier from "../models/SupplierModel.js";
7
  import SupplierInvoice from "../models/SupplierInvoiceModel.js";
8
  import User from "../models/UserModel.js";
 
9
  import { resolveScopedBranch } from "../utils/branchContext.js";
10
 
11
  const isWithinRange = (value, start, end) => {
@@ -261,14 +262,16 @@ const buildBestSellingProducts = (invoices) => {
261
 
262
  invoices.forEach((invoice) => {
263
  (invoice.items || []).forEach((item) => {
264
- const key = item.productId?.toString() || item.name;
265
  const existing = products.get(key) || {
266
  productId: item.productId || null,
 
267
  name: item.name,
268
  quantitySold: 0,
269
  revenue: 0,
270
  averagePrice: 0,
271
  invoicesCount: 0,
 
272
  };
273
 
274
  existing.quantitySold += toNumber(item.quantity);
@@ -398,11 +401,12 @@ export const getDashboardOverview = async (req, res) => {
398
  const { start, end } = createRange(req);
399
  const limit = parseInt(req.query.limit) || 5;
400
 
401
- const [invoices, expenses, incomes, products, customers, suppliers, supplierInvoices, users] = await Promise.all([
402
  Invoice.find({ tenant: tenantId, ...branchFilter }).populate("customer", "name isWalkIn"),
403
  Expense.find({ tenant: tenantId, ...branchFilter }).sort({ date: -1 }),
404
  Income.find({ tenant: tenantId, ...branchFilter }).sort({ date: -1 }),
405
  Product.find({ tenant: tenantId, ...branchFilter }).sort({ stock: 1, createdAt: -1 }),
 
406
  Customer.find({ tenant: tenantId, ...branchFilter, isDeleted: false, isWalkIn: { $ne: true } }).sort({ createdAt: -1 }),
407
  Supplier.find({ tenant: tenantId, ...branchFilter }).sort({ createdAt: -1 }),
408
  SupplierInvoice.find({ tenant: tenantId, ...branchFilter }).populate("supplier", "name"),
@@ -416,8 +420,12 @@ export const getDashboardOverview = async (req, res) => {
416
  const rangeServiceIncomes = incomes.filter(
417
  (income) => income.category === "service_income" && isWithinRange(income.date, start, end)
418
  );
 
 
 
419
 
420
  const salesInRange = rangeInvoices.reduce((sum, invoice) => sum + toNumber(invoice.totalAmount), 0);
 
421
  const collectionsInRange = aggregateInvoicePayments(invoices, start, end);
422
  const cashCollectionsInRange = aggregateCashPayments(invoices, start, end);
423
  const transferCollectionsInRange = aggregateTransferPayments(invoices, start, end, false);
@@ -428,6 +436,7 @@ export const getDashboardOverview = async (req, res) => {
428
  const expensesInRange = rangeExpenses.reduce((sum, expense) => sum + toNumber(expense.amount), 0);
429
  const incomeInRange = rangeManualIncomes.reduce((sum, income) => sum + toNumber(income.amount), 0);
430
  const serviceIncomeInRange = rangeServiceIncomes.reduce((sum, income) => sum + toNumber(income.amount), 0);
 
431
  const outstandingReceivables = invoices.reduce(
432
  (sum, invoice) => sum + (invoice.customer?.isWalkIn ? 0 : toNumber(invoice.remainingAmount)),
433
  0
@@ -508,7 +517,9 @@ export const getDashboardOverview = async (req, res) => {
508
  dateRange: { start, end },
509
  metrics: {
510
  salesInRange,
 
511
  serviceIncomeInRange,
 
512
  collectionsInRange,
513
  cashCollectionsInRange,
514
  transferCollectionsInRange,
@@ -520,7 +531,9 @@ export const getDashboardOverview = async (req, res) => {
520
  outstandingReceivables,
521
  supplierOutstanding,
522
  customersCount: customers.length,
523
- productsCount: products.length,
 
 
524
  suppliersCount: suppliers.length,
525
  usersCount: users.length,
526
  invoicesCount: invoices.length,
 
6
  import Supplier from "../models/SupplierModel.js";
7
  import SupplierInvoice from "../models/SupplierInvoiceModel.js";
8
  import User from "../models/UserModel.js";
9
+ import CatalogItem from "../models/CatalogItemModel.js";
10
  import { resolveScopedBranch } from "../utils/branchContext.js";
11
 
12
  const isWithinRange = (value, start, end) => {
 
262
 
263
  invoices.forEach((invoice) => {
264
  (invoice.items || []).forEach((item) => {
265
+ const key = item.catalogItemId?.toString() || item.productId?.toString() || item.name;
266
  const existing = products.get(key) || {
267
  productId: item.productId || null,
268
+ catalogItemId: item.catalogItemId || null,
269
  name: item.name,
270
  quantitySold: 0,
271
  revenue: 0,
272
  averagePrice: 0,
273
  invoicesCount: 0,
274
+ type: item.type || "product",
275
  };
276
 
277
  existing.quantitySold += toNumber(item.quantity);
 
401
  const { start, end } = createRange(req);
402
  const limit = parseInt(req.query.limit) || 5;
403
 
404
+ const [invoices, expenses, incomes, products, catalogItems, customers, suppliers, supplierInvoices, users] = await Promise.all([
405
  Invoice.find({ tenant: tenantId, ...branchFilter }).populate("customer", "name isWalkIn"),
406
  Expense.find({ tenant: tenantId, ...branchFilter }).sort({ date: -1 }),
407
  Income.find({ tenant: tenantId, ...branchFilter }).sort({ date: -1 }),
408
  Product.find({ tenant: tenantId, ...branchFilter }).sort({ stock: 1, createdAt: -1 }),
409
+ CatalogItem.find({ tenant: tenantId, ...branchFilter }).sort({ createdAt: -1 }),
410
  Customer.find({ tenant: tenantId, ...branchFilter, isDeleted: false, isWalkIn: { $ne: true } }).sort({ createdAt: -1 }),
411
  Supplier.find({ tenant: tenantId, ...branchFilter }).sort({ createdAt: -1 }),
412
  SupplierInvoice.find({ tenant: tenantId, ...branchFilter }).populate("supplier", "name"),
 
420
  const rangeServiceIncomes = incomes.filter(
421
  (income) => income.category === "service_income" && isWithinRange(income.date, start, end)
422
  );
423
+ const rangeCatalogIncomes = incomes.filter(
424
+ (income) => income.category === "catalog_sale" && isWithinRange(income.date, start, end)
425
+ );
426
 
427
  const salesInRange = rangeInvoices.reduce((sum, invoice) => sum + toNumber(invoice.totalAmount), 0);
428
+ const catalogSalesInRange = rangeInvoices.reduce((sum, invoice) => sum + toNumber(invoice.catalogRevenue), 0);
429
  const collectionsInRange = aggregateInvoicePayments(invoices, start, end);
430
  const cashCollectionsInRange = aggregateCashPayments(invoices, start, end);
431
  const transferCollectionsInRange = aggregateTransferPayments(invoices, start, end, false);
 
436
  const expensesInRange = rangeExpenses.reduce((sum, expense) => sum + toNumber(expense.amount), 0);
437
  const incomeInRange = rangeManualIncomes.reduce((sum, income) => sum + toNumber(income.amount), 0);
438
  const serviceIncomeInRange = rangeServiceIncomes.reduce((sum, income) => sum + toNumber(income.amount), 0);
439
+ const catalogIncomeInRange = rangeCatalogIncomes.reduce((sum, income) => sum + toNumber(income.amount), 0);
440
  const outstandingReceivables = invoices.reduce(
441
  (sum, invoice) => sum + (invoice.customer?.isWalkIn ? 0 : toNumber(invoice.remainingAmount)),
442
  0
 
517
  dateRange: { start, end },
518
  metrics: {
519
  salesInRange,
520
+ catalogSalesInRange,
521
  serviceIncomeInRange,
522
+ catalogIncomeInRange,
523
  collectionsInRange,
524
  cashCollectionsInRange,
525
  transferCollectionsInRange,
 
531
  outstandingReceivables,
532
  supplierOutstanding,
533
  customersCount: customers.length,
534
+ productsCount: products.length + catalogItems.length,
535
+ stockProductsCount: products.length,
536
+ catalogItemsCount: catalogItems.length,
537
  suppliersCount: suppliers.length,
538
  usersCount: users.length,
539
  invoicesCount: invoices.length,
index.js CHANGED
@@ -12,6 +12,7 @@ import incomeRoutes from "./routes/incomeRoutes.js";
12
  import supplierRoutes from "./routes/supplierRoutes.js";
13
  import serviceRoutes from "./routes/serviceRoutes.js";
14
  import authRoutes from "./routes/authRoutes.js";
 
15
  import { dbConnection } from './config/database.js';
16
 
17
  dotenv.config();
@@ -68,6 +69,7 @@ app.use('/expenses', expenseRoutes);
68
  app.use('/incomes', incomeRoutes);
69
  app.use('/suppliers', supplierRoutes);
70
  app.use('/services', serviceRoutes);
 
71
  app.use('/auth', authRoutes);
72
  app.get('/', (req, res) => {
73
  res.status(200).json({ message: 'App Is running' });
 
12
  import supplierRoutes from "./routes/supplierRoutes.js";
13
  import serviceRoutes from "./routes/serviceRoutes.js";
14
  import authRoutes from "./routes/authRoutes.js";
15
+ import catalogRoutes from "./routes/catalogRoutes.js";
16
  import { dbConnection } from './config/database.js';
17
 
18
  dotenv.config();
 
69
  app.use('/incomes', incomeRoutes);
70
  app.use('/suppliers', supplierRoutes);
71
  app.use('/services', serviceRoutes);
72
+ app.use('/catalog', catalogRoutes);
73
  app.use('/auth', authRoutes);
74
  app.get('/', (req, res) => {
75
  res.status(200).json({ message: 'App Is running' });
models/BranchModel.js CHANGED
@@ -16,7 +16,8 @@ const branchSchema = new mongoose.Schema(
16
  code: {
17
  type: String,
18
  trim: true,
19
- default: "",
 
20
  },
21
  address: {
22
  type: String,
@@ -47,6 +48,14 @@ const branchSchema = new mongoose.Schema(
47
  );
48
 
49
  branchSchema.index({ tenant: 1, name: 1 }, { unique: true });
50
- branchSchema.index({ tenant: 1, code: 1 }, { unique: true, sparse: true });
51
 
 
 
 
 
 
 
 
 
 
52
  export default mongoose.model("Branch", branchSchema);
 
16
  code: {
17
  type: String,
18
  trim: true,
19
+ // default: null,
20
+ // set: v => (v && v.trim() !== "" ? v.trim() : null)
21
  },
22
  address: {
23
  type: String,
 
48
  );
49
 
50
  branchSchema.index({ tenant: 1, name: 1 }, { unique: true });
 
51
 
52
+ branchSchema.index(
53
+ { tenant: 1, code: 1 },
54
+ {
55
+ unique: true,
56
+ partialFilterExpression: {
57
+ code: { $type: "string" }
58
+ }
59
+ }
60
+ );
61
  export default mongoose.model("Branch", branchSchema);
models/CatalogCategoryModel.js ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import mongoose from "mongoose";
2
+
3
+ const catalogCategorySchema = new mongoose.Schema(
4
+ {
5
+ tenant: {
6
+ type: mongoose.Schema.Types.ObjectId,
7
+ ref: "Tenant",
8
+ required: true,
9
+ index: true,
10
+ },
11
+ branch: {
12
+ type: mongoose.Schema.Types.ObjectId,
13
+ ref: "Branch",
14
+ default: null,
15
+ index: true,
16
+ },
17
+ name: {
18
+ type: String,
19
+ required: true,
20
+ trim: true,
21
+ },
22
+ description: {
23
+ type: String,
24
+ default: "",
25
+ trim: true,
26
+ },
27
+ sortOrder: {
28
+ type: Number,
29
+ default: 0,
30
+ },
31
+ isActive: {
32
+ type: Boolean,
33
+ default: true,
34
+ },
35
+ createdBy: {
36
+ type: mongoose.Schema.Types.ObjectId,
37
+ ref: "User",
38
+ default: null,
39
+ },
40
+ },
41
+ { timestamps: true }
42
+ );
43
+
44
+ catalogCategorySchema.index({ tenant: 1, branch: 1, name: 1 }, { unique: true });
45
+
46
+ export default mongoose.model("CatalogCategory", catalogCategorySchema);
models/CatalogItemModel.js ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import mongoose from "mongoose";
2
+
3
+ const catalogItemSchema = new mongoose.Schema(
4
+ {
5
+ tenant: {
6
+ type: mongoose.Schema.Types.ObjectId,
7
+ ref: "Tenant",
8
+ required: true,
9
+ index: true,
10
+ },
11
+ branch: {
12
+ type: mongoose.Schema.Types.ObjectId,
13
+ ref: "Branch",
14
+ default: null,
15
+ index: true,
16
+ },
17
+ category: {
18
+ type: mongoose.Schema.Types.ObjectId,
19
+ ref: "CatalogCategory",
20
+ required: true,
21
+ index: true,
22
+ },
23
+ name: {
24
+ type: String,
25
+ required: true,
26
+ trim: true,
27
+ },
28
+ description: {
29
+ type: String,
30
+ default: "",
31
+ trim: true,
32
+ },
33
+ price: {
34
+ type: Number,
35
+ required: true,
36
+ min: 0,
37
+ },
38
+ costPrice: {
39
+ type: Number,
40
+ default: 0,
41
+ min: 0,
42
+ },
43
+ sortOrder: {
44
+ type: Number,
45
+ default: 0,
46
+ },
47
+ isActive: {
48
+ type: Boolean,
49
+ default: true,
50
+ },
51
+ createdBy: {
52
+ type: mongoose.Schema.Types.ObjectId,
53
+ ref: "User",
54
+ default: null,
55
+ },
56
+ },
57
+ { timestamps: true }
58
+ );
59
+
60
+ catalogItemSchema.index({ tenant: 1, branch: 1, category: 1, name: 1 }, { unique: true });
61
+
62
+ export default mongoose.model("CatalogItem", catalogItemSchema);
models/CounterModel.js CHANGED
@@ -7,5 +7,4 @@ const counterSchema = new mongoose.Schema({
7
  });
8
 
9
  counterSchema.index({ tenant: 1, branch: 1 }, { unique: true });
10
-
11
  export default mongoose.model("Counter", counterSchema);
 
7
  });
8
 
9
  counterSchema.index({ tenant: 1, branch: 1 }, { unique: true });
 
10
  export default mongoose.model("Counter", counterSchema);
models/IncomeModel.js CHANGED
@@ -20,7 +20,7 @@ const incomeSchema = new mongoose.Schema(
20
  },
21
  category: {
22
  type: String,
23
- enum: ["general", "invoice_payment", "walk_in_sale", "service_income", "other"],
24
  default: "general",
25
  },
26
  amount: {
 
20
  },
21
  category: {
22
  type: String,
23
+ enum: ["general", "invoice_payment", "walk_in_sale", "service_income", "catalog_sale", "other"],
24
  default: "general",
25
  },
26
  amount: {
models/InvoiceModel.js CHANGED
@@ -38,11 +38,12 @@ const invoiceSchema = new mongoose.Schema(
38
  date: { type: Date, default: Date.now },
39
  type: {
40
  type: String,
41
- enum: ["product", "service"],
42
  default: "product",
43
  },
44
  productId: { type: mongoose.Schema.Types.ObjectId, ref: "Product" },
45
  serviceId: { type: mongoose.Schema.Types.ObjectId, ref: "Service" },
 
46
  },
47
  ],
48
  subtotal: {
@@ -117,6 +118,10 @@ const invoiceSchema = new mongoose.Schema(
117
  type: Number,
118
  default: 0,
119
  },
 
 
 
 
120
  hasServices: {
121
  type: Boolean,
122
  default: false,
@@ -134,6 +139,7 @@ invoiceSchema.index({ tenant: 1, branch: 1, invoiceNumber: 1 }, { unique: true }
134
  invoiceSchema.methods.calculateTotals = function () {
135
  this.serviceRevenue = 0;
136
  this.productRevenue = 0;
 
137
  this.hasServices = false;
138
 
139
  this.items.forEach((item) => {
@@ -143,6 +149,8 @@ invoiceSchema.methods.calculateTotals = function () {
143
  if (item.type === "service") {
144
  this.serviceRevenue += item.total;
145
  this.hasServices = true;
 
 
146
  } else {
147
  this.productRevenue += item.total;
148
  }
 
38
  date: { type: Date, default: Date.now },
39
  type: {
40
  type: String,
41
+ enum: ["product", "service", "catalog"],
42
  default: "product",
43
  },
44
  productId: { type: mongoose.Schema.Types.ObjectId, ref: "Product" },
45
  serviceId: { type: mongoose.Schema.Types.ObjectId, ref: "Service" },
46
+ catalogItemId: { type: mongoose.Schema.Types.ObjectId, ref: "CatalogItem" },
47
  },
48
  ],
49
  subtotal: {
 
118
  type: Number,
119
  default: 0,
120
  },
121
+ catalogRevenue: {
122
+ type: Number,
123
+ default: 0,
124
+ },
125
  hasServices: {
126
  type: Boolean,
127
  default: false,
 
139
  invoiceSchema.methods.calculateTotals = function () {
140
  this.serviceRevenue = 0;
141
  this.productRevenue = 0;
142
+ this.catalogRevenue = 0;
143
  this.hasServices = false;
144
 
145
  this.items.forEach((item) => {
 
149
  if (item.type === "service") {
150
  this.serviceRevenue += item.total;
151
  this.hasServices = true;
152
+ } else if (item.type === "catalog") {
153
+ this.catalogRevenue += item.total;
154
  } else {
155
  this.productRevenue += item.total;
156
  }
models/ProductModel.js CHANGED
@@ -64,10 +64,20 @@ const productSchema = new mongoose.Schema(
64
  { timestamps: true }
65
  );
66
 
67
- productSchema.index({ tenant: 1, branch: 1, name: 1 });
68
  productSchema.index(
69
- { tenant: 1, branch: 1, barcode: 1 },
70
- { unique: true, partialFilterExpression: { barcode: { $type: "string", $ne: "" } } }
71
  );
72
 
 
 
 
 
 
 
 
 
 
 
73
  export default mongoose.model("Product", productSchema);
 
64
  { timestamps: true }
65
  );
66
 
67
+ // Product name must be unique per branch
68
  productSchema.index(
69
+ { tenant: 1, branch: 1, name: 1 },
70
+ { unique: true }
71
  );
72
 
73
+ // Barcode must be unique per branch (only if exists)
74
+ productSchema.index(
75
+ { tenant: 1, branch: 1, barcode: 1 },
76
+ {
77
+ unique: true,
78
+ partialFilterExpression: {
79
+ barcode: { $type: "string" }
80
+ }
81
+ }
82
+ );
83
  export default mongoose.model("Product", productSchema);
models/TenantModel.js CHANGED
@@ -1,5 +1,5 @@
1
- import mongoose from "mongoose";
2
- import { DEFAULT_SUBSCRIPTION_PACKAGE } from "../utils/subscriptionPackages.js";
3
 
4
  const tenantSchema = new mongoose.Schema(
5
  {
@@ -70,7 +70,7 @@ const tenantSchema = new mongoose.Schema(
70
  lastPaymentAt: {
71
  type: Date,
72
  },
73
- payments: [
74
  {
75
  amount: {
76
  type: Number,
@@ -95,26 +95,35 @@ const tenantSchema = new mongoose.Schema(
95
  default: null,
96
  },
97
  },
98
- ],
99
- subscriptionPackage: {
100
- type: String,
101
- enum: ["basic", "standard", "premium"],
102
- default: DEFAULT_SUBSCRIPTION_PACKAGE,
103
- },
104
- cashierLimit: {
105
- type: Number,
106
- default: 1,
107
- },
108
- cashierAccountsCount: {
109
- type: Number,
110
- default: 0,
111
- min: 0,
112
- },
113
- },
114
- { timestamps: true }
115
- );
116
-
117
- tenantSchema.index({ name: 1 });
118
- tenantSchema.index({ status: 1, subscriptionPackage: 1 });
119
-
120
- export default mongoose.model("Tenant", tenantSchema);
 
 
 
 
 
 
 
 
 
 
1
+ import mongoose from "mongoose";
2
+ import { DEFAULT_SUBSCRIPTION_PACKAGE } from "../utils/subscriptionPackages.js";
3
 
4
  const tenantSchema = new mongoose.Schema(
5
  {
 
70
  lastPaymentAt: {
71
  type: Date,
72
  },
73
+ payments: [
74
  {
75
  amount: {
76
  type: Number,
 
95
  default: null,
96
  },
97
  },
98
+ ],
99
+ subscriptionPackage: {
100
+ type: String,
101
+ enum: ["basic", "standard", "premium"],
102
+ default: DEFAULT_SUBSCRIPTION_PACKAGE,
103
+ },
104
+ cashierLimit: {
105
+ type: Number,
106
+ default: 1,
107
+ },
108
+ cashierAccountsCount: {
109
+ type: Number,
110
+ default: 0,
111
+ min: 0,
112
+ },
113
+ branchLimit: {
114
+ type: Number,
115
+ default: 1,
116
+ },
117
+ branchCount: {
118
+ type: Number,
119
+ default: 1,
120
+ min: 0,
121
+ },
122
+ },
123
+ { timestamps: true }
124
+ );
125
+
126
+ tenantSchema.index({ name: 1 });
127
+ tenantSchema.index({ status: 1, subscriptionPackage: 1 });
128
+
129
+ export default mongoose.model("Tenant", tenantSchema);
routes/catalogRoutes.js ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { Router } from "express";
2
+ import {
3
+ createCatalogCategory,
4
+ createCatalogItem,
5
+ deleteCatalogCategory,
6
+ deleteCatalogItem,
7
+ getCatalogCategories,
8
+ getCatalogItems,
9
+ updateCatalogCategory,
10
+ updateCatalogItem,
11
+ } from "../controller/catalogController.js";
12
+ import { authorize, protect, requireTenantUser } from "../middleware/authMiddleware.js";
13
+
14
+ const router = Router();
15
+
16
+ router.use(protect, requireTenantUser);
17
+
18
+ router.get("/categories", getCatalogCategories);
19
+ router.post("/categories", authorize("owner", "admin"), createCatalogCategory);
20
+ router.put("/categories/:id", authorize("owner", "admin"), updateCatalogCategory);
21
+ router.delete("/categories/:id", authorize("owner", "admin"), deleteCatalogCategory);
22
+
23
+ router.get("/items", getCatalogItems);
24
+ router.post("/items", authorize("owner", "admin"), createCatalogItem);
25
+ router.put("/items/:id", authorize("owner", "admin"), updateCatalogItem);
26
+ router.delete("/items/:id", authorize("owner", "admin"), deleteCatalogItem);
27
+
28
+ export default router;
utils/branchContext.js CHANGED
@@ -1,3 +1,4 @@
 
1
  import Branch from "../models/BranchModel.js";
2
  import Product from "../models/ProductModel.js";
3
  import Customer from "../models/CustomerModel.js";
@@ -10,8 +11,7 @@ import Counter from "../models/CounterModel.js";
10
  import User from "../models/UserModel.js";
11
 
12
  const DEFAULT_BRANCH_NAME = "Main Branch";
13
- const DEFAULT_BRANCH_CODE = "MAIN";
14
-
15
  const isManagementRole = (role) => ["owner", "admin"].includes(role);
16
 
17
  const sanitizeBranchCode = (value) =>
@@ -33,11 +33,13 @@ export const ensurePrimaryBranchForTenant = async (tenantId, userId = null) => {
33
  await anyBranch.save();
34
  return anyBranch;
35
  }
 
 
36
 
37
  const primaryBranch = await Branch.create({
38
  tenant: tenantId,
39
  name: DEFAULT_BRANCH_NAME,
40
- code: DEFAULT_BRANCH_CODE,
41
  isPrimary: true,
42
  status: "active",
43
  createdBy: userId || null,
 
1
+ import { randomUUID } from "crypto";
2
  import Branch from "../models/BranchModel.js";
3
  import Product from "../models/ProductModel.js";
4
  import Customer from "../models/CustomerModel.js";
 
11
  import User from "../models/UserModel.js";
12
 
13
  const DEFAULT_BRANCH_NAME = "Main Branch";
14
+ const DEFAULT_BRANCH_CODE = () => `BR-${randomUUID()}`;
 
15
  const isManagementRole = (role) => ["owner", "admin"].includes(role);
16
 
17
  const sanitizeBranchCode = (value) =>
 
33
  await anyBranch.save();
34
  return anyBranch;
35
  }
36
+ const generatedCode = DEFAULT_BRANCH_CODE();
37
+ console.log("🚨 GENERATED CODE:", generatedCode);
38
 
39
  const primaryBranch = await Branch.create({
40
  tenant: tenantId,
41
  name: DEFAULT_BRANCH_NAME,
42
+ code: generatedCode,
43
  isPrimary: true,
44
  status: "active",
45
  createdBy: userId || null,
utils/subscriptionPackages.js CHANGED
@@ -1,31 +1,36 @@
1
- export const SUBSCRIPTION_PACKAGES = {
2
- basic: {
3
- key: "basic",
4
- label: "Basic",
5
- cashierLimit: 1,
6
- },
7
- standard: {
8
- key: "standard",
9
- label: "Standard",
10
- cashierLimit: 2,
11
- },
12
- premium: {
13
- key: "premium",
14
- label: "Premium",
15
- cashierLimit: null,
16
- },
17
- };
18
-
19
- export const DEFAULT_SUBSCRIPTION_PACKAGE = "basic";
20
-
21
- export const normalizePackageKey = (value) => {
22
- const key = String(value || "").trim().toLowerCase();
23
- return SUBSCRIPTION_PACKAGES[key] ? key : null;
24
- };
25
-
26
- export const getPackageDetails = (value) => {
27
- const key = normalizePackageKey(value) || DEFAULT_SUBSCRIPTION_PACKAGE;
28
- return SUBSCRIPTION_PACKAGES[key];
29
- };
30
-
31
- export const isUnlimitedCashierLimit = (limit) => limit === null;
 
 
 
 
 
 
1
+ export const SUBSCRIPTION_PACKAGES = {
2
+ basic: {
3
+ key: "basic",
4
+ label: "Basic",
5
+ cashierLimit: 1,
6
+ branchLimit: 1,
7
+ },
8
+ standard: {
9
+ key: "standard",
10
+ label: "Standard",
11
+ cashierLimit: 2,
12
+ branchLimit: 2,
13
+ },
14
+ premium: {
15
+ key: "premium",
16
+ label: "Premium",
17
+ cashierLimit: null,
18
+ branchLimit: null,
19
+ },
20
+ };
21
+
22
+ export const DEFAULT_SUBSCRIPTION_PACKAGE = "basic";
23
+
24
+ export const normalizePackageKey = (value) => {
25
+ const key = String(value || "").trim().toLowerCase();
26
+ return SUBSCRIPTION_PACKAGES[key] ? key : null;
27
+ };
28
+
29
+ export const getPackageDetails = (value) => {
30
+ const key = normalizePackageKey(value) || DEFAULT_SUBSCRIPTION_PACKAGE;
31
+ return SUBSCRIPTION_PACKAGES[key];
32
+ };
33
+
34
+ export const isUnlimitedCashierLimit = (limit) => limit === null;
35
+
36
+ export const isUnlimitedBranchLimit = (limit) => limit === null;