Mahmoud7456 commited on
Commit
3afa5bc
·
1 Parent(s): 848548d

Upload 26 files

Browse files
config/database.js ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import mongoose from 'mongoose';
2
+
3
+ export const dbConnection = async () => {
4
+ try {
5
+ await mongoose.connect(process.env.DB_URL);
6
+ console.log('Connected To DB Successfully!');
7
+ }
8
+ catch (err) {
9
+ console.log('DB Connection Failed' + err);
10
+ }
11
+ }
controller/authController.js ADDED
@@ -0,0 +1,520 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import User from "../models/UserModel.js";
2
+ import Tenant from "../models/TenantModel.js";
3
+ import {
4
+ buildTenantCredentialsWhatsApp,
5
+ clearAuthCookie,
6
+ createSessionToken,
7
+ setAuthCookie,
8
+ toSlug,
9
+ } from "../utils/authCookies.js";
10
+
11
+ const sanitizeTenant = (tenant) => {
12
+ if (!tenant) {
13
+ return null;
14
+ }
15
+
16
+ return {
17
+ _id: tenant._id,
18
+ name: tenant.name,
19
+ slug: tenant.slug,
20
+ ownerName: tenant.ownerName,
21
+ ownerEmail: tenant.ownerEmail,
22
+ ownerPhone: tenant.ownerPhone,
23
+ whatsappNumber: tenant.whatsappNumber,
24
+ address: tenant.address,
25
+ status: tenant.status,
26
+ settings: tenant.settings,
27
+ createdAt: tenant.createdAt,
28
+ };
29
+ };
30
+
31
+ const sanitizeUser = (user) => ({
32
+ _id: user._id,
33
+ username: user.username,
34
+ fullName: user.fullName,
35
+ email: user.email,
36
+ phone: user.phone,
37
+ role: user.role,
38
+ status: user.status,
39
+ tenant: sanitizeTenant(user.tenant),
40
+ createdAt: user.createdAt,
41
+ lastLoginAt: user.lastLoginAt,
42
+ });
43
+
44
+ const createUniqueSlug = async (name) => {
45
+ const baseSlug = toSlug(name) || "business";
46
+ let slug = baseSlug;
47
+ let counter = 1;
48
+
49
+ while (await Tenant.findOne({ slug })) {
50
+ counter += 1;
51
+ slug = `${baseSlug}-${counter}`;
52
+ }
53
+
54
+ return slug;
55
+ };
56
+
57
+ export const checkAdmin = async (req, res) => {
58
+ try {
59
+ const count = await User.countDocuments({ role: "super_admin" });
60
+ res.status(200).json({ hasAdmin: count > 0 });
61
+ } catch (error) {
62
+ res.status(500).json({ message: error.message });
63
+ }
64
+ };
65
+
66
+ 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 || {};
74
+ const username = (body.username || "").trim() || "superadmin";
75
+ const password = (body.password || "").trim() || "ChangeMe123!";
76
+ const fullName = (body.fullName || "").trim() || "Platform Admin";
77
+ const email = (body.email || "").trim().toLowerCase() || undefined;
78
+
79
+ await User.create({
80
+ username,
81
+ password,
82
+ fullName,
83
+ email,
84
+ role: "super_admin",
85
+ });
86
+
87
+ res.status(201).json({
88
+ message: "Platform admin account created successfully",
89
+ credentials: {
90
+ username,
91
+ password,
92
+ },
93
+ });
94
+ } catch (err) {
95
+ res.status(500).json({ message: err.message });
96
+ }
97
+ };
98
+
99
+ export const login = async (req, res) => {
100
+ try {
101
+ const identifier = req.body.identifier?.trim() || req.body.username?.trim();
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({
109
+ $or: [{ username: identifier }, { email: identifier.toLowerCase() }],
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();
125
+ user.sessionToken = token;
126
+ user.lastLoginAt = new Date();
127
+ await user.save();
128
+ setAuthCookie(res, token);
129
+
130
+ res.status(200).json({
131
+ message: "Login successful",
132
+ user: sanitizeUser(user),
133
+ });
134
+ } catch (err) {
135
+ res.status(500).json({ message: err.message });
136
+ }
137
+ };
138
+
139
+ export const logout = async (req, res) => {
140
+ try {
141
+ if (req.user) {
142
+ req.user.sessionToken = null;
143
+ await req.user.save();
144
+ }
145
+ clearAuthCookie(res);
146
+ res.status(200).json({ message: "Logout successful" });
147
+ } catch (err) {
148
+ res.status(500).json({ message: err.message });
149
+ }
150
+ };
151
+
152
+ export const getCurrentUser = async (req, res) => {
153
+ try {
154
+ if (!req.user) {
155
+ return res.status(401).json({ message: "Unauthorized" });
156
+ }
157
+
158
+ res.status(200).json({
159
+ user: sanitizeUser(req.user),
160
+ });
161
+ } catch (error) {
162
+ res.status(500).json({ message: error.message });
163
+ }
164
+ };
165
+
166
+ export const getUsers = async (req, res) => {
167
+ try {
168
+ let filter = {};
169
+
170
+ if (req.user.role === "super_admin") {
171
+ filter = req.query.tenantId ? { tenant: req.query.tenantId } : { role: "super_admin" };
172
+ } else {
173
+ filter = { tenant: req.user.tenant._id };
174
+ }
175
+
176
+ const users = await User.find(filter).populate("tenant").sort({ createdAt: -1 });
177
+ res.status(200).json(users.map(sanitizeUser));
178
+ } catch (error) {
179
+ res.status(500).json({ message: error.message });
180
+ }
181
+ };
182
+
183
+ export const createUser = async (req, res) => {
184
+ if (!req.user?.tenant) {
185
+ return res.status(403).json({ message: "Internal user management is only available inside tenant accounts" });
186
+ }
187
+
188
+ if (!["owner", "admin"].includes(req.user.role)) {
189
+ return res.status(403).json({ message: "Only tenant management roles can create users" });
190
+ }
191
+
192
+ const username = req.body.username?.trim();
193
+ const fullName = req.body.fullName?.trim() || username;
194
+ const password = req.body.password?.trim();
195
+ const email = req.body.email?.trim()?.toLowerCase() || undefined;
196
+ const phone = req.body.phone?.trim() || "";
197
+ const role = req.body.role || "cashier";
198
+
199
+ if (!username || !password) {
200
+ return res.status(400).json({ message: "Username and password are required" });
201
+ }
202
+
203
+ if (!["admin", "cashier"].includes(role)) {
204
+ return res.status(400).json({ message: "Unsupported role" });
205
+ }
206
+
207
+ try {
208
+ const usernameExists = await User.findOne({ username });
209
+ if (usernameExists) {
210
+ return res.status(400).json({ message: "Username is already in use" });
211
+ }
212
+
213
+ if (email) {
214
+ const emailExists = await User.findOne({ email });
215
+ if (emailExists) {
216
+ return res.status(400).json({ message: "Email is already in use" });
217
+ }
218
+ }
219
+
220
+ const user = await User.create({
221
+ username,
222
+ fullName,
223
+ email,
224
+ phone,
225
+ password,
226
+ role,
227
+ tenant: req.user.tenant._id,
228
+ });
229
+
230
+ await user.populate("tenant");
231
+
232
+ res.status(201).json({
233
+ message: "User created successfully",
234
+ user: sanitizeUser(user),
235
+ });
236
+ } catch (err) {
237
+ res.status(500).json({ message: err.message });
238
+ }
239
+ };
240
+
241
+ export const deleteUser = async (req, res) => {
242
+ if (!req.user?.tenant || !["owner", "admin"].includes(req.user.role)) {
243
+ return res.status(403).json({ message: "You do not have permission to delete users" });
244
+ }
245
+
246
+ if (req.user._id.toString() === req.params.id) {
247
+ return res.status(400).json({ message: "You cannot delete your own active account" });
248
+ }
249
+
250
+ try {
251
+ const targetUser = await User.findOne({
252
+ _id: req.params.id,
253
+ tenant: req.user.tenant._id,
254
+ });
255
+
256
+ if (!targetUser) {
257
+ return res.status(404).json({ message: "User not found" });
258
+ }
259
+
260
+ if (targetUser.role === "owner") {
261
+ return res.status(400).json({ message: "Owner accounts cannot be deleted from this screen" });
262
+ }
263
+
264
+ await targetUser.deleteOne();
265
+ res.status(200).json({ message: "User deleted successfully" });
266
+ } catch (error) {
267
+ res.status(500).json({ message: error.message });
268
+ }
269
+ };
270
+
271
+ export const updateUser = async (req, res) => {
272
+ if (!req.user?.tenant || !["owner", "admin"].includes(req.user.role)) {
273
+ return res.status(403).json({ message: "You do not have permission to edit users" });
274
+ }
275
+
276
+ try {
277
+ const targetUser = await User.findOne({
278
+ _id: req.params.id,
279
+ tenant: req.user.tenant._id,
280
+ }).populate("tenant");
281
+
282
+ if (!targetUser) {
283
+ return res.status(404).json({ message: "User not found" });
284
+ }
285
+
286
+ if (targetUser.role === "owner") {
287
+ return res.status(400).json({ message: "Owner accounts cannot be edited from this screen" });
288
+ }
289
+
290
+ if (req.user.role === "admin" && targetUser.role !== "cashier") {
291
+ return res.status(403).json({ message: "Admins can only manage cashier accounts" });
292
+ }
293
+
294
+ if (req.user._id.toString() === targetUser._id.toString() && req.body.status === "suspended") {
295
+ return res.status(400).json({ message: "You cannot suspend your own active session" });
296
+ }
297
+
298
+ if (req.body.role) {
299
+ if (!["admin", "cashier"].includes(req.body.role)) {
300
+ return res.status(400).json({ message: "Unsupported role" });
301
+ }
302
+
303
+ if (req.user.role === "admin" && req.body.role === "admin") {
304
+ return res.status(403).json({ message: "Admins cannot promote users to admin" });
305
+ }
306
+
307
+ targetUser.role = req.body.role;
308
+ }
309
+
310
+ if (req.body.status) {
311
+ if (!["active", "suspended"].includes(req.body.status)) {
312
+ return res.status(400).json({ message: "Unsupported status" });
313
+ }
314
+
315
+ targetUser.status = req.body.status;
316
+ }
317
+
318
+ targetUser.fullName = req.body.fullName?.trim() || targetUser.fullName;
319
+ targetUser.email = req.body.email?.trim()?.toLowerCase() || targetUser.email;
320
+ targetUser.phone = req.body.phone?.trim() || targetUser.phone;
321
+
322
+ await targetUser.save();
323
+
324
+ res.status(200).json({
325
+ message: "User updated successfully",
326
+ user: sanitizeUser(targetUser),
327
+ });
328
+ } catch (error) {
329
+ res.status(500).json({ message: error.message });
330
+ }
331
+ };
332
+
333
+ export const getTenants = async (req, res) => {
334
+ if (req.user.role !== "super_admin") {
335
+ return res.status(403).json({ message: "Only the platform admin can access tenants" });
336
+ }
337
+
338
+ try {
339
+ const tenants = await Tenant.find().sort({ createdAt: -1 });
340
+ res.status(200).json(tenants.map(sanitizeTenant));
341
+ } catch (error) {
342
+ res.status(500).json({ message: error.message });
343
+ }
344
+ };
345
+
346
+ export const getTenantProfile = async (req, res) => {
347
+ if (!req.user?.tenant) {
348
+ return res.status(403).json({ message: "This profile is only available for tenant users" });
349
+ }
350
+
351
+ try {
352
+ res.status(200).json({
353
+ tenant: sanitizeTenant(req.user.tenant),
354
+ });
355
+ } catch (error) {
356
+ res.status(500).json({ message: error.message });
357
+ }
358
+ };
359
+
360
+ export const updateTenantProfile = async (req, res) => {
361
+ if (!req.user?.tenant) {
362
+ return res.status(403).json({ message: "This profile is only available for tenant users" });
363
+ }
364
+
365
+ if (!["owner", "admin"].includes(req.user.role)) {
366
+ return res.status(403).json({ message: "Only tenant management roles can update company settings" });
367
+ }
368
+
369
+ try {
370
+ const tenant = await Tenant.findById(req.user.tenant._id);
371
+
372
+ if (!tenant) {
373
+ return res.status(404).json({ message: "Tenant not found" });
374
+ }
375
+
376
+ tenant.name = req.body.name?.trim() || tenant.name;
377
+ tenant.ownerName = req.body.ownerName?.trim() || tenant.ownerName;
378
+ tenant.ownerEmail = req.body.ownerEmail?.trim()?.toLowerCase() || "";
379
+ tenant.ownerPhone = req.body.ownerPhone?.trim() || "";
380
+ tenant.whatsappNumber = req.body.whatsappNumber?.trim() || "";
381
+ tenant.address = req.body.address?.trim() || "";
382
+ tenant.settings = {
383
+ ...tenant.settings,
384
+ currency: req.body.currency?.trim() || tenant.settings?.currency || "EGP",
385
+ lowStockThreshold:
386
+ Number(req.body.lowStockThreshold) > 0
387
+ ? Number(req.body.lowStockThreshold)
388
+ : tenant.settings?.lowStockThreshold || 5,
389
+ };
390
+
391
+ await tenant.save();
392
+
393
+ const owner = await User.findOne({ tenant: tenant._id, role: "owner" });
394
+ if (owner) {
395
+ owner.fullName = tenant.ownerName;
396
+ owner.email = tenant.ownerEmail || undefined;
397
+ owner.phone = tenant.ownerPhone;
398
+ await owner.save();
399
+ }
400
+
401
+ await req.user.populate("tenant");
402
+
403
+ res.status(200).json({
404
+ message: "Company profile updated successfully",
405
+ tenant: sanitizeTenant(tenant),
406
+ });
407
+ } catch (error) {
408
+ res.status(500).json({ message: error.message });
409
+ }
410
+ };
411
+
412
+ export const updateTenantStatus = async (req, res) => {
413
+ if (req.user.role !== "super_admin") {
414
+ return res.status(403).json({ message: "Only the platform admin can update tenant status" });
415
+ }
416
+
417
+ const status = req.body.status;
418
+ if (!["active", "suspended"].includes(status)) {
419
+ return res.status(400).json({ message: "Invalid tenant status" });
420
+ }
421
+
422
+ try {
423
+ const tenant = await Tenant.findById(req.params.id);
424
+ if (!tenant) {
425
+ return res.status(404).json({ message: "Tenant not found" });
426
+ }
427
+
428
+ tenant.status = status;
429
+ await tenant.save();
430
+
431
+ await User.updateMany({ tenant: tenant._id }, { status });
432
+
433
+ res.status(200).json({
434
+ message: `Tenant marked as ${status}`,
435
+ tenant: sanitizeTenant(tenant),
436
+ });
437
+ } catch (error) {
438
+ res.status(500).json({ message: error.message });
439
+ }
440
+ };
441
+
442
+ export const createTenantOwner = async (req, res) => {
443
+ if (req.user.role !== "super_admin") {
444
+ return res.status(403).json({ message: "Only the platform admin can create tenants" });
445
+ }
446
+
447
+ try {
448
+ const companyName = req.body.companyName?.trim();
449
+ const ownerName = req.body.ownerName?.trim();
450
+ const username = req.body.username?.trim();
451
+ const password = req.body.password?.trim();
452
+ const email = req.body.email?.trim()?.toLowerCase() || "";
453
+ const phone = req.body.phone?.trim() || "";
454
+ const whatsappNumber = req.body.whatsappNumber?.trim() || phone;
455
+ const address = req.body.address?.trim() || "";
456
+
457
+ if (!companyName || !ownerName || !username || !password) {
458
+ return res.status(400).json({ message: "Company and owner details are required" });
459
+ }
460
+
461
+ const existingUsername = await User.findOne({ username });
462
+ if (existingUsername) {
463
+ return res.status(400).json({ message: "Username is already in use" });
464
+ }
465
+
466
+ if (email) {
467
+ const existingEmail = await User.findOne({ email });
468
+ if (existingEmail) {
469
+ return res.status(400).json({ message: "Email is already in use" });
470
+ }
471
+ }
472
+
473
+ const slug = await createUniqueSlug(companyName);
474
+
475
+ const tenant = await Tenant.create({
476
+ name: companyName,
477
+ slug,
478
+ ownerName,
479
+ ownerEmail: email,
480
+ ownerPhone: phone,
481
+ whatsappNumber,
482
+ address,
483
+ });
484
+
485
+ const owner = await User.create({
486
+ username,
487
+ fullName: ownerName,
488
+ email: email || undefined,
489
+ phone,
490
+ password,
491
+ role: "owner",
492
+ tenant: tenant._id,
493
+ });
494
+
495
+ await owner.populate("tenant");
496
+
497
+ const loginUrl = `${(process.env.FRONTEND_URL || "http://localhost:5173").replace(/\/$/, "")}/login`;
498
+ const onboarding = buildTenantCredentialsWhatsApp({
499
+ companyName: tenant.name,
500
+ ownerName,
501
+ username,
502
+ temporaryPassword: password,
503
+ loginUrl,
504
+ });
505
+
506
+ res.status(201).json({
507
+ message: "Tenant owner account created successfully",
508
+ tenant: sanitizeTenant(tenant),
509
+ owner: sanitizeUser(owner),
510
+ onboarding: {
511
+ loginUrl,
512
+ temporaryPassword: password,
513
+ whatsappMessage: onboarding.message,
514
+ whatsappLink: onboarding.whatsappLink,
515
+ },
516
+ });
517
+ } catch (error) {
518
+ res.status(500).json({ message: error.message });
519
+ }
520
+ };
controller/customerController.js ADDED
@@ -0,0 +1,182 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import Customer from "../models/CustomerModel.js";
2
+ import Invoice from "../models/InvoiceModel.js";
3
+
4
+ export const createCustomer = async (req, res) => {
5
+ try {
6
+ const tenantId = req.user.tenant._id;
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({
27
+ tenant: tenantId,
28
+ name,
29
+ phone: req.body.phone?.trim() || "",
30
+ email: req.body.email?.trim()?.toLowerCase() || "",
31
+ address: req.body.address?.trim() || "",
32
+ notes: req.body.notes?.trim() || "",
33
+ createdBy: req.user._id,
34
+ });
35
+
36
+ res.status(201).json(customer);
37
+ } catch (err) {
38
+ res.status(500).json({ message: err.message });
39
+ }
40
+ };
41
+
42
+ export const getCustomers = async (req, res) => {
43
+ try {
44
+ const tenantId = req.user.tenant._id;
45
+ const page = parseInt(req.query.page) || 1;
46
+ const limit = parseInt(req.query.limit) || 5;
47
+ const skip = (page - 1) * limit;
48
+ const search = req.query.search || "";
49
+
50
+ const matchQuery = {
51
+ tenant: tenantId,
52
+ };
53
+
54
+ if (search) {
55
+ matchQuery.name = { $regex: search, $options: "i" };
56
+ }
57
+
58
+ const results = await Customer.aggregate([
59
+ { $match: matchQuery },
60
+ {
61
+ $facet: {
62
+ data: [
63
+ { $sort: { createdAt: -1 } },
64
+ { $skip: skip },
65
+ { $limit: limit },
66
+ {
67
+ $lookup: {
68
+ from: "invoices",
69
+ let: {
70
+ customerId: "$_id",
71
+ tenantId: "$tenant",
72
+ },
73
+ pipeline: [
74
+ {
75
+ $match: {
76
+ $expr: {
77
+ $and: [
78
+ { $eq: ["$customer", "$$customerId"] },
79
+ { $eq: ["$tenant", "$$tenantId"] },
80
+ ],
81
+ },
82
+ },
83
+ },
84
+ ],
85
+ as: "invoices",
86
+ },
87
+ },
88
+ {
89
+ $addFields: {
90
+ totalInvoicesAmount: { $sum: "$invoices.totalAmount" },
91
+ totalDebt: { $sum: "$invoices.remainingAmount" },
92
+ },
93
+ },
94
+ ],
95
+ totalCount: [
96
+ { $count: "count" }
97
+ ]
98
+ }
99
+ }
100
+ ]);
101
+
102
+ const customers = results[0].data;
103
+ const total = results[0].totalCount[0]?.count || 0;
104
+
105
+ res.status(200).json({
106
+ data: customers,
107
+ pagination: {
108
+ total,
109
+ page,
110
+ limit,
111
+ totalPages: Math.ceil(total / limit),
112
+ },
113
+ });
114
+ } catch (error) {
115
+ res.status(500).json({ message: error.message });
116
+ }
117
+ };
118
+
119
+ export const getCustomerById = async (req, res) => {
120
+ try {
121
+ const customer = await Customer.findOne({
122
+ _id: req.params.id,
123
+ tenant: req.user.tenant._id,
124
+ });
125
+
126
+ if (!customer) {
127
+ return res.status(404).json({ message: "Customer not found" });
128
+ }
129
+
130
+ // Pagination & Sorting
131
+ const page = parseInt(req.query.page) || 1;
132
+ const limit = parseInt(req.query.limit) || 5;
133
+ const sortField = req.query.sortField || "createdAt";
134
+ const sortOrder = req.query.sortOrder === "asc" ? 1 : -1;
135
+ const skip = (page - 1) * limit;
136
+
137
+ const totalInvoices = await Invoice.countDocuments({
138
+ customer: customer._id,
139
+ tenant: req.user.tenant._id,
140
+ });
141
+
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 })
148
+ .skip(skip)
149
+ .limit(limit);
150
+
151
+ res.status(200).json({
152
+ ...customer.toObject(),
153
+ invoices,
154
+ pagination: {
155
+ total: totalInvoices,
156
+ page,
157
+ limit,
158
+ totalPages: Math.ceil(totalInvoices / limit),
159
+ },
160
+ });
161
+ } catch (error) {
162
+ res.status(500).json({ message: error.message });
163
+ }
164
+ };
165
+
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
+ };
controller/expenseController.js ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import Expense from "../models/ExpenseModel.js";
2
+
3
+ export const addExpense = async (req, res) => {
4
+ try {
5
+ const { title, amount, category, paymentMethod, notes, date } = req.body;
6
+ const expense = await Expense.create({
7
+ tenant: req.user.tenant._id,
8
+ title,
9
+ amount,
10
+ category,
11
+ paymentMethod,
12
+ notes,
13
+ date: date || Date.now(),
14
+ createdBy: req.user._id,
15
+ });
16
+ res.status(201).json(expense);
17
+ } catch (error) {
18
+ res.status(500).json({ message: error.message });
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
+ }
32
+ };
controller/invoiceController.js ADDED
@@ -0,0 +1,289 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
6
+ // Safe invoice number generator
7
+ const generateInvoiceNumber = async (tenantId) => {
8
+ const counter = await Counter.findOneAndUpdate(
9
+ { tenant: tenantId },
10
+ { $inc: { invoiceNumber: 1 } },
11
+ { new: true, upsert: true }
12
+ );
13
+
14
+ return `INV-${String(counter.invoiceNumber).padStart(5, "0")}`;
15
+ };
16
+
17
+ export const addItemToInvoice = async (req, res) => {
18
+ try {
19
+ const { customerId } = req.params;
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({
32
+ customer: customerId,
33
+ tenant: tenantId,
34
+ status: { $in: ["open", "partial"] },
35
+ });
36
+
37
+ // If no invoice exists, create new with safe invoice number
38
+ if (!invoice) {
39
+ invoice = new Invoice({
40
+ tenant: tenantId,
41
+ customer: customerId,
42
+ invoiceNumber: await generateInvoiceNumber(tenantId),
43
+ issuedBy: req.user._id,
44
+ });
45
+ }
46
+
47
+ // Check stock availability
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}`,
55
+ });
56
+ }
57
+ }
58
+
59
+ // Add items to invoice and update stock
60
+ for (const item of items) {
61
+ const quantity = Number(item.quantity || 0);
62
+ const price = Number(item.price || 0);
63
+ const total = quantity * price;
64
+
65
+ invoice.items.push({
66
+ name: item.name,
67
+ quantity,
68
+ price,
69
+ total,
70
+ ...(item.productId ? { productId: item.productId } : {}),
71
+ });
72
+
73
+ if (item.productId) {
74
+ await Product.findOneAndUpdate(
75
+ { _id: item.productId, tenant: tenantId },
76
+ { $inc: { stock: -quantity } }
77
+ );
78
+ }
79
+ }
80
+
81
+ // Save invoice with updated totals
82
+ await invoice.save();
83
+ res.status(200).json(invoice);
84
+ } catch (err) {
85
+ console.log("❌ ERROR:", err.message);
86
+ console.log("❌ STACK:", err.stack);
87
+ res.status(500).json({ message: err.message });
88
+ }
89
+ };
90
+ export const getInvoices = async (req, res) => {
91
+ try {
92
+ const page = parseInt(req.query.page) || 1;
93
+ const limit = parseInt(req.query.limit) || 5;
94
+ const skip = (page - 1) * limit;
95
+ const search = req.query.search || "";
96
+
97
+ const query = { tenant: req.user.tenant._id };
98
+ if (search) {
99
+ query.invoiceNumber = { $regex: search, $options: "i" };
100
+ }
101
+
102
+ const total = await Invoice.countDocuments(query);
103
+ const invoices = await Invoice.find(query)
104
+ .populate("customer")
105
+ .sort({ createdAt: -1 })
106
+ .skip(skip)
107
+ .limit(limit);
108
+
109
+ res.status(200).json({
110
+ data: invoices,
111
+ pagination: {
112
+ total,
113
+ page,
114
+ limit,
115
+ totalPages: Math.ceil(total / limit),
116
+ },
117
+ });
118
+ } catch (err) {
119
+ res.status(500).json({ message: err.message });
120
+ }
121
+ };
122
+
123
+ export const getInvoicesByCustomer = async (req, res) => {
124
+ try {
125
+ const invoices = await Invoice.find({
126
+ customer: req.params.customerId,
127
+ tenant: req.user.tenant._id,
128
+ });
129
+
130
+ res.json(invoices);
131
+ } catch (err) {
132
+ res.status(500).json({ message: err.message });
133
+ }
134
+ };
135
+
136
+ export const getInvoiceById = async (req, res) => {
137
+ try {
138
+ const { id } = req.params;
139
+
140
+ const invoice = await Invoice.findOne({
141
+ _id: id,
142
+ tenant: req.user.tenant._id,
143
+ })
144
+ .populate("customer", "name")
145
+ .populate({
146
+ path: "items.productId",
147
+ select: "name price", // fields from Product you want
148
+ });
149
+
150
+ if (!invoice) {
151
+ return res.status(404).json({ message: "Invoice not found" });
152
+ }
153
+
154
+ res.status(200).json(invoice);
155
+ } catch (error) {
156
+ res.status(500).json({ message: error.message });
157
+ }
158
+ };
159
+
160
+ export const updateInvoiceItem = async (req, res) => {
161
+ try {
162
+ const { invoiceId, itemId } = req.params;
163
+ const { name, quantity, price } = req.body;
164
+
165
+ const invoice = await Invoice.findOne({
166
+ _id: invoiceId,
167
+ tenant: req.user.tenant._id,
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);
180
+ const newPrice = Number(price);
181
+
182
+ if (item.productId) {
183
+ const quantityDifference = newQuantity - Number(item.quantity);
184
+ const product = await Product.findOne({
185
+ _id: item.productId,
186
+ tenant: req.user.tenant._id,
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) {
198
+ await Product.findOneAndUpdate(
199
+ { _id: item.productId, tenant: req.user.tenant._id },
200
+ { $inc: { stock: -quantityDifference } }
201
+ );
202
+ }
203
+ }
204
+
205
+ item.name = name;
206
+ item.quantity = newQuantity;
207
+ item.price = newPrice;
208
+ item.total = newQuantity * newPrice;
209
+
210
+ await invoice.save();
211
+
212
+ res.status(200).json({
213
+ message: "Invoice item updated successfully",
214
+ invoice,
215
+ });
216
+ } catch (error) {
217
+ res.status(500).json({ message: error.message });
218
+ }
219
+ };
220
+
221
+ export const deleteInvoiceItem = async (req, res) => {
222
+ try {
223
+ const { invoiceId, itemId } = req.params;
224
+
225
+ const invoice = await Invoice.findOne({
226
+ _id: invoiceId,
227
+ tenant: req.user.tenant._id,
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) {
240
+ await Product.findOneAndUpdate(
241
+ { _id: item.productId, tenant: req.user.tenant._id },
242
+ { $inc: { stock: Number(item.quantity) } }
243
+ );
244
+ }
245
+
246
+ item.deleteOne();
247
+ await invoice.save();
248
+
249
+ res.json(invoice);
250
+ } catch (error) {
251
+ res.status(500).json({ message: error.message });
252
+ }
253
+ };
254
+
255
+ export const payInvoice = async (req, res) => {
256
+ try {
257
+ const { customerId } = req.params;
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({
265
+ customer: customerId,
266
+ tenant: req.user.tenant._id,
267
+ status: { $in: ["open", "partial"] },
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({
279
+ amount,
280
+ method: req.body.paymentMethod || "cash",
281
+ receivedBy: req.user._id,
282
+ });
283
+
284
+ await invoice.save();
285
+ res.json(invoice);
286
+ } catch (err) {
287
+ res.status(500).json({ message: err.message });
288
+ }
289
+ };
controller/productController.js ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import Product from "../models/ProductModel.js";
2
+
3
+ export const createProduct = async (req, res) => {
4
+ try {
5
+ const { name, price, stock, description, barcode, sku, unit, lowStockThreshold, costPrice } = req.body;
6
+ const tenantId = req.user.tenant._id;
7
+
8
+ const exists = await Product.findOne({
9
+ tenant: tenantId,
10
+ $or: [{ name }, ...(barcode ? [{ barcode }] : [])],
11
+ });
12
+
13
+ if (exists) {
14
+ return res.status(400).json({ message: "Product already exists" });
15
+ }
16
+
17
+ const product = await Product.create({
18
+ tenant: tenantId,
19
+ name,
20
+ price,
21
+ stock,
22
+ description,
23
+ barcode,
24
+ sku,
25
+ unit,
26
+ lowStockThreshold: lowStockThreshold || req.user.tenant.settings?.lowStockThreshold || 5,
27
+ costPrice: costPrice || 0,
28
+ createdBy: req.user._id,
29
+ });
30
+
31
+ res.status(201).json(product);
32
+ } catch (error) {
33
+ res.status(500).json({ message: error.message });
34
+ }
35
+ };
36
+
37
+ export const getProducts = async (req, res) => {
38
+ try {
39
+ const page = parseInt(req.query.page) || 1;
40
+ const limit = parseInt(req.query.limit) || 5;
41
+ const skip = (page - 1) * limit;
42
+ const search = req.query.search || "";
43
+
44
+ const query = { tenant: req.user.tenant._id };
45
+ if (search) {
46
+ query.name = { $regex: search, $options: "i" };
47
+ }
48
+
49
+ const total = await Product.countDocuments(query);
50
+ const products = await Product.find(query)
51
+ .sort({ createdAt: -1 })
52
+ .skip(skip)
53
+ .limit(limit);
54
+
55
+ res.status(200).json({
56
+ data: products.map((product) => ({
57
+ ...product.toObject(),
58
+ isLowStock:
59
+ Number(product.stock) <=
60
+ Number(product.lowStockThreshold || req.user.tenant.settings?.lowStockThreshold || 5),
61
+ })),
62
+ pagination: {
63
+ total,
64
+ page,
65
+ limit,
66
+ totalPages: Math.ceil(total / limit),
67
+ },
68
+ });
69
+ } catch (error) {
70
+ res.status(500).json({ message: error.message });
71
+ }
72
+ };
73
+
74
+ export const updateProduct = async (req, res) => {
75
+ try {
76
+ const { id } = req.params;
77
+ const { name, price, stock, description, barcode, sku, unit, lowStockThreshold, costPrice } = req.body;
78
+
79
+ const product = await Product.findOne({
80
+ _id: id,
81
+ tenant: req.user.tenant._id,
82
+ });
83
+
84
+ if (!product) {
85
+ return res.status(404).json({ message: "Product not found" });
86
+ }
87
+
88
+ product.name = name ?? product.name;
89
+ product.price = price ?? product.price;
90
+ product.stock = stock ?? product.stock;
91
+ product.description = description ?? product.description;
92
+ product.barcode = barcode ?? product.barcode;
93
+ product.sku = sku ?? product.sku;
94
+ product.unit = unit ?? product.unit;
95
+ product.lowStockThreshold = lowStockThreshold ?? product.lowStockThreshold;
96
+ product.costPrice = costPrice ?? product.costPrice;
97
+ await product.save();
98
+
99
+ res.status(200).json(product);
100
+ } catch (error) {
101
+ res.status(500).json({ message: error.message });
102
+ }
103
+ };
104
+
105
+ export const deleteProduct = async (req, res) => {
106
+ try {
107
+ const { id } = req.params;
108
+ const product = await Product.findOneAndDelete({
109
+ _id: id,
110
+ tenant: req.user.tenant._id,
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
+ }
121
+ };
controller/reportController.js ADDED
@@ -0,0 +1,337 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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";
6
+ import SupplierInvoice from "../models/SupplierInvoiceModel.js";
7
+ import User from "../models/UserModel.js";
8
+
9
+ // ─── shared helpers ───────────────────────────────────────────────────────────
10
+
11
+ const isWithinRange = (value, start, end) => {
12
+ const date = new Date(value);
13
+ return date >= start && date <= end;
14
+ };
15
+
16
+ const toNumber = (value) => Number(value || 0);
17
+
18
+ /**
19
+ * Build a { data, pagination } envelope — used everywhere for consistent shape.
20
+ */
21
+ const paginate = (array, page, limit) => {
22
+ const safePage = Math.max(1, parseInt(page) || 1);
23
+ const safeLimit = Math.max(1, parseInt(limit) || 5);
24
+ const skip = (safePage - 1) * safeLimit;
25
+ return {
26
+ data: array.slice(skip, skip + safeLimit),
27
+ pagination: {
28
+ total: array.length,
29
+ page: safePage,
30
+ limit: safeLimit,
31
+ totalPages: Math.ceil(array.length / safeLimit),
32
+ },
33
+ };
34
+ };
35
+
36
+ const createRange = (req) => {
37
+ const end = req.query.end ? new Date(req.query.end) : new Date();
38
+ const start = req.query.start ? new Date(req.query.start) : new Date(end);
39
+
40
+ if (!req.query.start) {
41
+ start.setDate(start.getDate() - 29);
42
+ }
43
+
44
+ start.setHours(0, 0, 0, 0);
45
+ end.setHours(23, 59, 59, 999);
46
+
47
+ return { start, end };
48
+ };
49
+
50
+ const buildDailyBreakdown = (days, invoices, expenses) => {
51
+ const points = [];
52
+
53
+ for (let i = days - 1; i >= 0; i--) {
54
+ const day = new Date();
55
+ day.setDate(day.getDate() - i);
56
+ day.setHours(0, 0, 0, 0);
57
+
58
+ const endOfDay = new Date(day);
59
+ endOfDay.setHours(23, 59, 59, 999);
60
+
61
+ const sales = invoices
62
+ .filter((inv) => isWithinRange(inv.createdAt, day, endOfDay))
63
+ .reduce((sum, inv) => sum + toNumber(inv.totalAmount), 0);
64
+
65
+ const collections = invoices.reduce((sum, inv) => {
66
+ const payments = (inv.payments || []).filter((p) => isWithinRange(p.date, day, endOfDay));
67
+ return sum + payments.reduce((s, p) => s + toNumber(p.amount), 0);
68
+ }, 0);
69
+
70
+ const dayExpenses = expenses
71
+ .filter((e) => isWithinRange(e.date, day, endOfDay))
72
+ .reduce((sum, e) => sum + toNumber(e.amount), 0);
73
+
74
+ points.push({
75
+ date: day.toISOString(),
76
+ label: day.toLocaleDateString("en-US", { month: "short", day: "numeric" }),
77
+ sales,
78
+ collections,
79
+ expenses: dayExpenses,
80
+ });
81
+ }
82
+
83
+ return points;
84
+ };
85
+
86
+ // ─── GET /reports/overview ────────────────────────────────────────────────────
87
+ // Query params supported:
88
+ // start, end — ISO date strings (default: last 30 days)
89
+ // limit — rows per page (default: 5)
90
+ // lowStockPage
91
+ // customersPage
92
+ // paymentsPage
93
+ // invoicesPage
94
+ // ─────────────────────────────────────────────────────────────────────────────
95
+ export const getDashboardOverview = async (req, res) => {
96
+ try {
97
+ const tenantId = req.user.tenant._id;
98
+ const { start, end } = createRange(req);
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 }),
109
+ SupplierInvoice.find({ tenant: tenantId }).populate("supplier", "name"),
110
+ User.find({ tenant: tenantId }).sort({ createdAt: -1 }),
111
+ ]);
112
+
113
+ // ── date-range filters ────────────────────────────────────────────────
114
+ const rangeInvoices = invoices.filter((inv) => isWithinRange(inv.createdAt, start, end));
115
+ const rangeExpenses = expenses.filter((exp) => isWithinRange(exp.date, start, end));
116
+
117
+ // ── aggregate metrics ─────────────────────────────────────────────────
118
+ const salesInRange = rangeInvoices.reduce((s, inv) => s + toNumber(inv.totalAmount), 0);
119
+
120
+ const collectionsInRange = invoices.reduce((sum, inv) => {
121
+ const payments = (inv.payments || []).filter((p) => isWithinRange(p.date, start, end));
122
+ return sum + payments.reduce((s, p) => s + toNumber(p.amount), 0);
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
+
129
+ const lowStockThresholdDefault = req.user.tenant.settings?.lowStockThreshold || 5;
130
+ const lowStockItems = products.filter(
131
+ (p) => toNumber(p.stock) <= toNumber(p.lowStockThreshold || lowStockThresholdDefault)
132
+ );
133
+
134
+ const inventoryValue = products.reduce(
135
+ (s, p) => s + toNumber(p.stock) * toNumber(p.costPrice || p.price), 0
136
+ );
137
+ const inventoryRetailValue = products.reduce(
138
+ (s, p) => s + toNumber(p.stock) * toNumber(p.price), 0
139
+ );
140
+
141
+ // ── top customers (aggregated from invoices) ──────────────────────────
142
+ const topCustomersMap = invoices.reduce((acc, inv) => {
143
+ const key = inv.customer?._id?.toString() || "unknown";
144
+ const current = acc.get(key) || {
145
+ customerId: inv.customer?._id || null,
146
+ customerName: inv.customer?.name || "Walk-in customer",
147
+ sales: 0,
148
+ outstanding: 0,
149
+ invoices: 0,
150
+ };
151
+ current.sales += toNumber(inv.totalAmount);
152
+ current.outstanding += toNumber(inv.remainingAmount);
153
+ current.invoices += 1;
154
+ acc.set(key, current);
155
+ return acc;
156
+ }, new Map());
157
+
158
+ const topCustomersAll = [...topCustomersMap.values()].sort((a, b) => b.sales - a.sales);
159
+
160
+ // ── recent payments (within range, sorted newest first) ───────────────
161
+ const allRecentPayments = invoices
162
+ .flatMap((inv) =>
163
+ (inv.payments || []).map((p) => ({
164
+ amount: toNumber(p.amount),
165
+ date: p.date,
166
+ method: p.method || "cash",
167
+ customerName: inv.customer?.name || "Walk-in customer",
168
+ customerId: inv.customer?._id || null,
169
+ invoiceNumber: inv.invoiceNumber,
170
+ }))
171
+ )
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))
178
+ .map((inv) => ({
179
+ _id: inv._id,
180
+ invoiceNumber: inv.invoiceNumber,
181
+ customerName: inv.customer?.name || "Walk-in customer",
182
+ totalAmount: toNumber(inv.totalAmount),
183
+ remainingAmount: toNumber(inv.remainingAmount),
184
+ status: inv.status,
185
+ createdAt: inv.createdAt,
186
+ }));
187
+
188
+ // ── paginate ──────────────────────────────────────────────────────────
189
+ const paginatedLowStock = paginate(lowStockItems.map((p) => ({
190
+ _id: p._id,
191
+ name: p.name,
192
+ stock: toNumber(p.stock),
193
+ lowStockThreshold: toNumber(p.lowStockThreshold),
194
+ price: toNumber(p.price),
195
+ unit: p.unit,
196
+ })), req.query.lowStockPage, limit);
197
+
198
+ const paginatedTopCustomers = paginate(topCustomersAll, req.query.customersPage, limit);
199
+ const paginatedPayments = paginate(allRecentPayments, req.query.paymentsPage, limit);
200
+ const paginatedInvoices = paginate(allRecentInvoices, req.query.invoicesPage, limit);
201
+
202
+ // ── respond ───────────────────────────────────────────────────────────
203
+ res.status(200).json({
204
+ dateRange: { start, end },
205
+ metrics: {
206
+ salesInRange,
207
+ collectionsInRange,
208
+ expensesInRange,
209
+ netCashFlow: collectionsInRange - expensesInRange,
210
+ outstandingReceivables,
211
+ supplierOutstanding,
212
+ customersCount: customers.length,
213
+ suppliersCount: suppliers.length,
214
+ usersCount: users.length,
215
+ invoicesCount: invoices.length,
216
+ invoicesInRange: rangeInvoices.length,
217
+ paidInvoicesCount: invoices.filter((i) => i.status === "paid").length,
218
+ partialInvoicesCount: invoices.filter((i) => i.status === "partial").length,
219
+ averageInvoiceValue: invoices.length
220
+ ? invoices.reduce((s, i) => s + toNumber(i.totalAmount), 0) / invoices.length
221
+ : 0,
222
+ inventoryUnits: products.reduce((s, p) => s + toNumber(p.stock), 0),
223
+ inventoryValue,
224
+ inventoryRetailValue,
225
+ lowStockCount: lowStockItems.length,
226
+ },
227
+ trends: {
228
+ last7Days: buildDailyBreakdown(7, invoices, expenses),
229
+ },
230
+ lowStockItems: paginatedLowStock,
231
+ topCustomers: paginatedTopCustomers,
232
+ recentPayments: paginatedPayments,
233
+ recentInvoices: paginatedInvoices,
234
+ recentExpenses: rangeExpenses.slice(0, 8).map((e) => ({
235
+ _id: e._id,
236
+ title: e.title,
237
+ amount: toNumber(e.amount),
238
+ date: e.date,
239
+ })),
240
+ });
241
+ } catch (error) {
242
+ res.status(500).json({ message: error.message });
243
+ }
244
+ };
245
+
246
+ // ─── GET /reports/daily ───────────────────────────────────────────────────────
247
+ // Query params supported:
248
+ // limit — rows per page (default: 5)
249
+ // paymentsPage — page for recentPayments
250
+ // expensesPage — page for expensesList
251
+ // ─────────────────────────────────────────────────────────────────────────────
252
+ export const getDailyReport = async (req, res) => {
253
+ try {
254
+ const tenantId = req.user.tenant._id;
255
+ const limit = parseInt(req.query.limit) || 5;
256
+
257
+ const startOfDay = new Date();
258
+ startOfDay.setHours(0, 0, 0, 0);
259
+ const endOfDay = new Date();
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 ─────────────────────────────────────────────────────────
272
+ let totalCashCollected = 0;
273
+ let totalSalesToday = 0;
274
+ let newInvoicesCount = 0;
275
+ const dailyPaymentsList = [];
276
+
277
+ invoices.forEach((invoice) => {
278
+ // cash collected today
279
+ (invoice.payments || []).forEach((payment) => {
280
+ if (isWithinRange(payment.date, startOfDay, endOfDay)) {
281
+ totalCashCollected += toNumber(payment.amount);
282
+ dailyPaymentsList.push({
283
+ amount: toNumber(payment.amount),
284
+ date: payment.date,
285
+ method: payment.method || "cash",
286
+ customerName: invoice.customer?.name || "Deleted customer",
287
+ customerId: invoice.customer?._id || null,
288
+ invoiceNumber: invoice.invoiceNumber,
289
+ });
290
+ }
291
+ });
292
+
293
+ // sales (items sold today)
294
+ (invoice.items || []).forEach((item) => {
295
+ const itemDate = item.date ? new Date(item.date) : new Date(invoice.createdAt);
296
+ if (isWithinRange(itemDate, startOfDay, endOfDay)) {
297
+ totalSalesToday += toNumber(item.total);
298
+ }
299
+ });
300
+
301
+ // new invoices created today
302
+ if (isWithinRange(invoice.createdAt, startOfDay, endOfDay)) {
303
+ newInvoicesCount += 1;
304
+ }
305
+ });
306
+
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);
313
+ const paginatedExpenses = paginate(
314
+ expenses.map((e) => ({
315
+ _id: e._id,
316
+ title: e.title,
317
+ amount: toNumber(e.amount),
318
+ date: e.date,
319
+ })),
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 });
336
+ }
337
+ };
controller/supplierController.js ADDED
@@ -0,0 +1,236 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import Supplier from "../models/SupplierModel.js";
2
+ import SupplierInvoice from "../models/SupplierInvoiceModel.js";
3
+ import Product from "../models/ProductModel.js";
4
+
5
+ export const createSupplier = async (req, res) => {
6
+ try {
7
+ const name = req.body.name?.trim();
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({
15
+ tenant: tenantId,
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({
23
+ tenant: tenantId,
24
+ name,
25
+ phone: req.body.phone?.trim() || "",
26
+ whatsappNumber: req.body.whatsappNumber?.trim() || "",
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 });
33
+ }
34
+ };
35
+
36
+ export const getSuppliers = async (req, res) => {
37
+ try {
38
+ const tenantId = req.user.tenant._id;
39
+ const page = parseInt(req.query.page) || 1;
40
+ const limit = parseInt(req.query.limit) || 5;
41
+ const skip = (page - 1) * limit;
42
+ const search = req.query.search || "";
43
+
44
+ const matchQuery = {
45
+ tenant: tenantId,
46
+ };
47
+
48
+ if (search) {
49
+ matchQuery.name = { $regex: search, $options: "i" };
50
+ }
51
+
52
+ const results = await Supplier.aggregate([
53
+ { $match: matchQuery },
54
+ {
55
+ $facet: {
56
+ data: [
57
+ { $sort: { createdAt: -1 } },
58
+ { $skip: skip },
59
+ { $limit: limit },
60
+ {
61
+ $lookup: {
62
+ from: "supplierinvoices",
63
+ let: {
64
+ supplierId: "$_id",
65
+ tenantId: "$tenant",
66
+ },
67
+ pipeline: [
68
+ {
69
+ $match: {
70
+ $expr: {
71
+ $and: [
72
+ { $eq: ["$supplier", "$$supplierId"] },
73
+ { $eq: ["$tenant", "$$tenantId"] },
74
+ ],
75
+ },
76
+ },
77
+ },
78
+ ],
79
+ as: "invoices",
80
+ },
81
+ },
82
+ {
83
+ $addFields: {
84
+ totalDebt: { $sum: "$invoices.remainingAmount" },
85
+ },
86
+ },
87
+ ],
88
+ totalCount: [
89
+ { $count: "count" }
90
+ ]
91
+ }
92
+ }
93
+ ]);
94
+
95
+ const suppliers = results[0].data;
96
+ const total = results[0].totalCount[0]?.count || 0;
97
+
98
+ res.status(200).json({
99
+ data: suppliers,
100
+ pagination: {
101
+ total,
102
+ page,
103
+ limit,
104
+ totalPages: Math.ceil(total / limit),
105
+ },
106
+ });
107
+ } catch (error) {
108
+ res.status(500).json({ message: error.message });
109
+ }
110
+ };
111
+
112
+ export const getSupplierById = async (req, res) => {
113
+ try {
114
+ const supplier = await Supplier.findOne({
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 });
129
+ }
130
+ };
131
+
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
+ }
147
+ };
148
+
149
+ export const addPurchasesToSupplier = async (req, res) => {
150
+ try {
151
+ const { items } = req.body;
152
+ const supplierId = req.params.id;
153
+ const tenantId = req.user.tenant._id;
154
+
155
+ const supplier = await Supplier.findOne({
156
+ _id: supplierId,
157
+ tenant: tenantId,
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,
171
+ tenant: tenantId,
172
+ createdBy: req.user._id,
173
+ });
174
+ }
175
+
176
+ for (const item of items) {
177
+ const quantity = Number(item.quantity || 0);
178
+ const price = Number(item.price || 0);
179
+ const total = price * quantity;
180
+
181
+ invoice.items.push({
182
+ ...item,
183
+ quantity,
184
+ price,
185
+ total,
186
+ });
187
+
188
+ if (item.productId) {
189
+ await Product.findOneAndUpdate(
190
+ { _id: item.productId, tenant: tenantId },
191
+ { $inc: { stock: quantity } }
192
+ );
193
+ }
194
+ }
195
+
196
+ await invoice.save();
197
+ res.status(200).json(invoice);
198
+ } catch (error) {
199
+ res.status(500).json({ message: error.message });
200
+ }
201
+ };
202
+
203
+ export const paySupplier = async (req, res) => {
204
+ try {
205
+ const amount = Number(req.body.amount);
206
+ const supplierId = req.params.id;
207
+
208
+ const invoice = await SupplierInvoice.findOne({
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({
225
+ amount,
226
+ date: new Date(),
227
+ method: req.body.paymentMethod || "cash",
228
+ paidBy: req.user._id,
229
+ });
230
+
231
+ await invoice.save();
232
+ res.status(200).json(invoice);
233
+ } catch (error) {
234
+ res.status(500).json({ message: error.message });
235
+ }
236
+ };
middleware/authMiddleware.js ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import User from "../models/UserModel.js";
2
+ import { AUTH_COOKIE_NAME, parseCookies } from "../utils/authCookies.js";
3
+
4
+ export const protect = async (req, res, next) => {
5
+ try {
6
+ const cookies = parseCookies(req.headers.cookie);
7
+ let token = cookies[AUTH_COOKIE_NAME];
8
+
9
+ if (!token && req.headers.authorization?.startsWith("Bearer")) {
10
+ token = req.headers.authorization.split(" ")[1];
11
+ }
12
+
13
+ if (!token) {
14
+ return res.status(401).json({ message: "Unauthorized" });
15
+ }
16
+
17
+ const user = await User.findOne({ sessionToken: token }).populate("tenant");
18
+
19
+ if (!user) {
20
+ return res.status(401).json({ message: "Session is invalid or expired" });
21
+ }
22
+
23
+ if (user.status !== "active") {
24
+ return res.status(403).json({ message: "User account is suspended" });
25
+ }
26
+
27
+ if (user.tenant && user.tenant.status !== "active") {
28
+ return res.status(403).json({ message: "Tenant account is suspended" });
29
+ }
30
+
31
+ req.user = user;
32
+ req.tenantId = user.tenant?._id?.toString() || null;
33
+ next();
34
+ } catch (error) {
35
+ res.status(401).json({ message: "Unable to verify session" });
36
+ }
37
+ };
38
+
39
+ export const authorize = (...roles) => (req, res, next) => {
40
+ if (!req.user) {
41
+ return res.status(401).json({ message: "Login required" });
42
+ }
43
+
44
+ if (!roles.includes(req.user.role)) {
45
+ return res.status(403).json({ message: "You do not have permission for this action" });
46
+ }
47
+
48
+ next();
49
+ };
50
+
51
+ export const requireTenantUser = (req, res, next) => {
52
+ if (!req.user?.tenant) {
53
+ return res.status(403).json({ message: "This action is only available to tenant users" });
54
+ }
55
+
56
+ next();
57
+ };
models/CounterModel.js ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ import mongoose from "mongoose";
2
+
3
+ const counterSchema = new mongoose.Schema({
4
+ tenant: { type: mongoose.Schema.Types.ObjectId, ref: "Tenant", required: true, unique: true },
5
+ invoiceNumber: { type: Number, default: 0 },
6
+ });
7
+
8
+ export default mongoose.model("Counter", counterSchema);
models/CustomerModel.js ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import mongoose from "mongoose";
2
+
3
+ const customerSchema = new mongoose.Schema(
4
+ {
5
+ tenant: {
6
+ type: mongoose.Schema.Types.ObjectId,
7
+ ref: "Tenant",
8
+ required: true,
9
+ index: true,
10
+ },
11
+ name: {
12
+ type: String,
13
+ required: [true, "You must enter customer name"],
14
+ minlength: [3, "Customer Name must be at least 3"],
15
+ maxlength: [20, "Customer max 20"],
16
+ trim: true,
17
+ },
18
+ phone: {
19
+ type: String,
20
+ default: "",
21
+ },
22
+ email: {
23
+ type: String,
24
+ trim: true,
25
+ lowercase: true,
26
+ default: "",
27
+ },
28
+ address: {
29
+ type: String,
30
+ default: "",
31
+ },
32
+ notes: {
33
+ type: String,
34
+ default: "",
35
+ },
36
+ createdBy: {
37
+ type: mongoose.Schema.Types.ObjectId,
38
+ ref: "User",
39
+ default: null,
40
+ },
41
+ invoices: [
42
+ {
43
+ type: mongoose.Schema.Types.ObjectId,
44
+ ref: "Invoice",
45
+ },
46
+ ],
47
+ },
48
+ {
49
+ timestamps: true,
50
+ }
51
+ );
52
+
53
+ customerSchema.index({ tenant: 1, name: 1 });
54
+
55
+ export default mongoose.model("Customer", customerSchema);
models/ExpenseModel.js ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import mongoose from "mongoose";
2
+
3
+ const expenseSchema = new mongoose.Schema(
4
+ {
5
+ tenant: {
6
+ type: mongoose.Schema.Types.ObjectId,
7
+ ref: "Tenant",
8
+ required: true,
9
+ index: true,
10
+ },
11
+ title: {
12
+ type: String,
13
+ required: true,
14
+ },
15
+ category: {
16
+ type: String,
17
+ default: "general",
18
+ },
19
+ amount: {
20
+ type: Number,
21
+ required: true,
22
+ },
23
+ paymentMethod: {
24
+ type: String,
25
+ default: "cash",
26
+ },
27
+ notes: {
28
+ type: String,
29
+ default: "",
30
+ },
31
+ date: {
32
+ type: Date,
33
+ default: Date.now,
34
+ },
35
+ createdBy: {
36
+ type: mongoose.Schema.Types.ObjectId,
37
+ ref: "User",
38
+ default: null,
39
+ },
40
+ },
41
+ { timestamps: true }
42
+ );
43
+
44
+ expenseSchema.index({ tenant: 1, date: -1 });
45
+
46
+ export default mongoose.model("Expense", expenseSchema);
models/InvoiceModel.js ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import mongoose from "mongoose";
2
+
3
+ const invoiceSchema = new mongoose.Schema(
4
+ {
5
+ tenant: {
6
+ type: mongoose.Schema.Types.ObjectId,
7
+ ref: "Tenant",
8
+ required: true,
9
+ index: true,
10
+ },
11
+ invoiceNumber: {
12
+ type: String,
13
+ required: true,
14
+ trim: true,
15
+ },
16
+ customer: {
17
+ type: mongoose.Schema.Types.ObjectId,
18
+ ref: "Customer",
19
+ required: true,
20
+ },
21
+ issuedBy: {
22
+ type: mongoose.Schema.Types.ObjectId,
23
+ ref: "User",
24
+ default: null,
25
+ },
26
+ items: [
27
+ {
28
+ name: String,
29
+ price: Number,
30
+ quantity: Number,
31
+ total: Number,
32
+ date: { type: Date, default: Date.now },
33
+ productId: { type: mongoose.Schema.Types.ObjectId, ref: "Product" },
34
+ },
35
+ ],
36
+ subtotal: {
37
+ type: Number,
38
+ default: 0,
39
+ },
40
+ discount: {
41
+ type: Number,
42
+ default: 0,
43
+ },
44
+ taxAmount: {
45
+ type: Number,
46
+ default: 0,
47
+ },
48
+ totalAmount: {
49
+ type: Number,
50
+ default: 0,
51
+ },
52
+ payments: [
53
+ {
54
+ amount: Number,
55
+ date: { type: Date, default: Date.now },
56
+ method: {
57
+ type: String,
58
+ default: "cash",
59
+ },
60
+ receivedBy: {
61
+ type: mongoose.Schema.Types.ObjectId,
62
+ ref: "User",
63
+ default: null,
64
+ },
65
+ },
66
+ ],
67
+ paidAmount: {
68
+ type: Number,
69
+ default: 0,
70
+ },
71
+ remainingAmount: {
72
+ type: Number,
73
+ default: 0,
74
+ },
75
+ status: {
76
+ type: String,
77
+ enum: ["draft", "open", "partial", "paid", "cancelled"],
78
+ default: "open",
79
+ },
80
+ notes: {
81
+ type: String,
82
+ default: "",
83
+ },
84
+ },
85
+ { timestamps: true }
86
+ );
87
+
88
+ invoiceSchema.index({ tenant: 1, invoiceNumber: 1 }, { unique: true });
89
+
90
+ invoiceSchema.methods.calculateTotals = function () {
91
+ this.items.forEach((item) => {
92
+ item.total = Number(item.price || 0) * Number(item.quantity || 0);
93
+ });
94
+
95
+ this.subtotal = this.items.reduce((sum, item) => sum + Number(item.total || 0), 0);
96
+ this.totalAmount = Math.max(this.subtotal - Number(this.discount || 0) + Number(this.taxAmount || 0), 0);
97
+
98
+ if (this.payments?.length || this.isModified("payments")) {
99
+ this.paidAmount = this.payments.reduce(
100
+ (sum, payment) => sum + Number(payment.amount || 0),
101
+ 0
102
+ );
103
+ }
104
+
105
+ this.remainingAmount = Math.max(this.totalAmount - Number(this.paidAmount || 0), 0);
106
+
107
+ if (this.status === "cancelled") {
108
+ return;
109
+ }
110
+
111
+ if (this.remainingAmount <= 0) {
112
+ this.status = "paid";
113
+ } else if (this.paidAmount > 0) {
114
+ this.status = "partial";
115
+ } else {
116
+ this.status = "open";
117
+ }
118
+ };
119
+
120
+ invoiceSchema.pre("save", function () {
121
+ this.calculateTotals();
122
+ });
123
+
124
+ export default mongoose.model("Invoice", invoiceSchema);
models/ProductModel.js ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import mongoose from "mongoose";
2
+
3
+ const productSchema = new mongoose.Schema(
4
+ {
5
+ tenant: {
6
+ type: mongoose.Schema.Types.ObjectId,
7
+ ref: "Tenant",
8
+ required: true,
9
+ index: true,
10
+ },
11
+ name: {
12
+ type: String,
13
+ required: true,
14
+ },
15
+ description: {
16
+ type: String,
17
+ default: "",
18
+ },
19
+ price: {
20
+ type: Number,
21
+ required: true,
22
+ },
23
+ costPrice: {
24
+ type: Number,
25
+ default: 0,
26
+ },
27
+ stock: {
28
+ type: Number,
29
+ required: true,
30
+ default: 0,
31
+ },
32
+ barcode: {
33
+ type: String,
34
+ default: "",
35
+ },
36
+ sku: {
37
+ type: String,
38
+ default: "",
39
+ },
40
+ unit: {
41
+ type: String,
42
+ default: "piece",
43
+ },
44
+ lowStockThreshold: {
45
+ type: Number,
46
+ default: 5,
47
+ },
48
+ createdBy: {
49
+ type: mongoose.Schema.Types.ObjectId,
50
+ ref: "User",
51
+ default: null,
52
+ },
53
+ },
54
+ { timestamps: true }
55
+ );
56
+
57
+ productSchema.index({ tenant: 1, name: 1 });
58
+ productSchema.index(
59
+ { tenant: 1, barcode: 1 },
60
+ { unique: true, partialFilterExpression: { barcode: { $type: "string", $ne: "" } } }
61
+ );
62
+
63
+ export default mongoose.model("Product", productSchema);
models/SupplierInvoiceModel.js ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import mongoose from "mongoose";
2
+
3
+ const supplierInvoiceSchema = new mongoose.Schema(
4
+ {
5
+ tenant: {
6
+ type: mongoose.Schema.Types.ObjectId,
7
+ ref: "Tenant",
8
+ required: true,
9
+ index: true,
10
+ },
11
+ supplier: {
12
+ type: mongoose.Schema.Types.ObjectId,
13
+ ref: "Supplier",
14
+ required: true,
15
+ },
16
+ createdBy: {
17
+ type: mongoose.Schema.Types.ObjectId,
18
+ ref: "User",
19
+ default: null,
20
+ },
21
+ totalAmount: { type: Number, default: 0 },
22
+ paidAmount: { type: Number, default: 0 },
23
+ remainingAmount: { type: Number, default: 0 },
24
+ items: [
25
+ {
26
+ name: String,
27
+ price: Number,
28
+ quantity: Number,
29
+ total: Number,
30
+ date: { type: Date, default: Date.now },
31
+ productId: { type: mongoose.Schema.Types.ObjectId, ref: "Product" },
32
+ },
33
+ ],
34
+ payments: [
35
+ {
36
+ amount: Number,
37
+ date: { type: Date, default: Date.now },
38
+ method: {
39
+ type: String,
40
+ default: "cash",
41
+ },
42
+ paidBy: {
43
+ type: mongoose.Schema.Types.ObjectId,
44
+ ref: "User",
45
+ default: null,
46
+ },
47
+ },
48
+ ],
49
+ },
50
+ { timestamps: true }
51
+ );
52
+
53
+ supplierInvoiceSchema.index({ tenant: 1, supplier: 1 });
54
+
55
+ supplierInvoiceSchema.pre("save", function () {
56
+ this.totalAmount = this.items.reduce((sum, item) => sum + Number(item.total || 0), 0);
57
+ this.paidAmount = this.payments.reduce((sum, payment) => sum + Number(payment.amount || 0), 0);
58
+ this.remainingAmount = Math.max(this.totalAmount - this.paidAmount, 0);
59
+ });
60
+
61
+ export default mongoose.model("SupplierInvoice", supplierInvoiceSchema);
models/SupplierModel.js ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import mongoose from "mongoose";
2
+
3
+ const supplierSchema = new mongoose.Schema(
4
+ {
5
+ tenant: {
6
+ type: mongoose.Schema.Types.ObjectId,
7
+ ref: "Tenant",
8
+ required: true,
9
+ index: true,
10
+ },
11
+ name: {
12
+ type: String,
13
+ required: true,
14
+ },
15
+ phone: {
16
+ type: String,
17
+ default: "",
18
+ },
19
+ whatsappNumber: {
20
+ type: String,
21
+ default: "",
22
+ },
23
+ notes: {
24
+ type: String,
25
+ default: "",
26
+ },
27
+ createdBy: {
28
+ type: mongoose.Schema.Types.ObjectId,
29
+ ref: "User",
30
+ default: null,
31
+ },
32
+ },
33
+ { timestamps: true }
34
+ );
35
+
36
+ supplierSchema.index({ tenant: 1, name: 1 });
37
+
38
+ export default mongoose.model("Supplier", supplierSchema);
models/TenantModel.js ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import mongoose from "mongoose";
2
+
3
+ const tenantSchema = new mongoose.Schema(
4
+ {
5
+ name: {
6
+ type: String,
7
+ required: true,
8
+ trim: true,
9
+ },
10
+ slug: {
11
+ type: String,
12
+ required: true,
13
+ trim: true,
14
+ lowercase: true,
15
+ unique: true,
16
+ },
17
+ ownerName: {
18
+ type: String,
19
+ required: true,
20
+ trim: true,
21
+ },
22
+ ownerEmail: {
23
+ type: String,
24
+ trim: true,
25
+ lowercase: true,
26
+ default: "",
27
+ },
28
+ ownerPhone: {
29
+ type: String,
30
+ trim: true,
31
+ default: "",
32
+ },
33
+ whatsappNumber: {
34
+ type: String,
35
+ trim: true,
36
+ default: "",
37
+ },
38
+ address: {
39
+ type: String,
40
+ trim: true,
41
+ default: "",
42
+ },
43
+ status: {
44
+ type: String,
45
+ enum: ["active", "suspended"],
46
+ default: "active",
47
+ },
48
+ settings: {
49
+ currency: {
50
+ type: String,
51
+ default: "EGP",
52
+ },
53
+ lowStockThreshold: {
54
+ type: Number,
55
+ default: 5,
56
+ },
57
+ },
58
+ },
59
+ { timestamps: true }
60
+ );
61
+
62
+ tenantSchema.index({ name: 1 });
63
+
64
+ export default mongoose.model("Tenant", tenantSchema);
models/UserModel.js ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import mongoose from "mongoose";
2
+ import crypto from "crypto";
3
+
4
+ const userSchema = new mongoose.Schema(
5
+ {
6
+ username: {
7
+ type: String,
8
+ required: true,
9
+ unique: true,
10
+ trim: true,
11
+ },
12
+ fullName: {
13
+ type: String,
14
+ trim: true,
15
+ default: "",
16
+ },
17
+ email: {
18
+ type: String,
19
+ trim: true,
20
+ lowercase: true,
21
+ unique: true,
22
+ sparse: true,
23
+ },
24
+ phone: {
25
+ type: String,
26
+ trim: true,
27
+ default: "",
28
+ },
29
+ password: {
30
+ type: String,
31
+ required: true,
32
+ },
33
+ role: {
34
+ type: String,
35
+ enum: ["super_admin", "owner", "admin", "cashier"],
36
+ default: "cashier",
37
+ },
38
+ status: {
39
+ type: String,
40
+ enum: ["active", "suspended"],
41
+ default: "active",
42
+ },
43
+ tenant: {
44
+ type: mongoose.Schema.Types.ObjectId,
45
+ ref: "Tenant",
46
+ default: null,
47
+ },
48
+ sessionToken: {
49
+ type: String,
50
+ default: null,
51
+ },
52
+ lastLoginAt: {
53
+ type: Date,
54
+ default: null,
55
+ },
56
+ },
57
+ { timestamps: true }
58
+ );
59
+
60
+ userSchema.index({ tenant: 1, role: 1 });
61
+
62
+ userSchema.pre("save", async function () {
63
+ if (!this.isModified("password")) return;
64
+
65
+ const salt = crypto.randomBytes(16).toString("hex");
66
+ const hash = crypto.pbkdf2Sync(this.password, salt, 1000, 64, "sha512").toString("hex");
67
+ this.password = `${salt}:${hash}`;
68
+ });
69
+
70
+ userSchema.methods.matchPassword = function (enteredPassword) {
71
+ try {
72
+ const [salt, originalHash] = this.password.split(":");
73
+ const attemptHash = crypto.pbkdf2Sync(enteredPassword, salt, 1000, 64, "sha512").toString("hex");
74
+ return originalHash === attemptHash;
75
+ } catch (err) {
76
+ return false;
77
+ }
78
+ };
79
+
80
+ export default mongoose.model("User", userSchema);
routes/authRoutes.js ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { Router } from "express";
2
+ import {
3
+ setupAdmin,
4
+ login,
5
+ logout,
6
+ getUsers,
7
+ createUser,
8
+ deleteUser,
9
+ updateUser,
10
+ checkAdmin,
11
+ getCurrentUser,
12
+ getTenants,
13
+ getTenantProfile,
14
+ createTenantOwner,
15
+ updateTenantProfile,
16
+ updateTenantStatus,
17
+ } from "../controller/authController.js";
18
+ import { protect } from "../middleware/authMiddleware.js";
19
+
20
+ const router = Router();
21
+
22
+ router.get("/has-admin", checkAdmin);
23
+ router.post("/setup", setupAdmin);
24
+ router.post("/login", login);
25
+ router.post("/logout", protect, logout);
26
+ router.get("/me", protect, getCurrentUser);
27
+ router.get("/users", protect, getUsers);
28
+ router.post("/users", protect, createUser);
29
+ router.patch("/users/:id", protect, updateUser);
30
+ router.delete("/users/:id", protect, deleteUser);
31
+ router.get("/tenants", protect, getTenants);
32
+ router.post("/tenants", protect, createTenantOwner);
33
+ router.patch("/tenants/:id/status", protect, updateTenantStatus);
34
+ router.get("/tenant-profile", protect, getTenantProfile);
35
+ router.put("/tenant-profile", protect, updateTenantProfile);
36
+
37
+ export default router;
routes/customerRoutes.js ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { Router } from "express";
2
+ import {
3
+ createCustomer,
4
+ getCustomerById,
5
+ getCustomers,
6
+ deleteCustomer,
7
+ } from "../controller/customerController.js";
8
+ import { authorize, protect, requireTenantUser } from "../middleware/authMiddleware.js";
9
+
10
+ const router = Router();
11
+
12
+ router.use(protect, requireTenantUser);
13
+
14
+ router.post("/create", createCustomer);
15
+ router.get("/", getCustomers);
16
+ router.get("/:id", getCustomerById);
17
+ router.delete("/:id", authorize("owner", "admin"), deleteCustomer);
18
+
19
+ export default router;
routes/expenseRoutes.js ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { Router } from "express";
2
+ import { addExpense, deleteExpense } from "../controller/expenseController.js";
3
+ import { authorize, protect, requireTenantUser } from "../middleware/authMiddleware.js";
4
+
5
+ const router = Router();
6
+
7
+ router.use(protect, requireTenantUser, authorize("owner", "admin"));
8
+
9
+ router.post("/", addExpense);
10
+ router.delete("/:id", deleteExpense);
11
+
12
+ export default router;
routes/invoiceRoutes.js ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { Router } from "express";
2
+ import {
3
+ addItemToInvoice,
4
+ deleteInvoiceItem,
5
+ getInvoiceById,
6
+ getInvoices,
7
+ getInvoicesByCustomer,
8
+ payInvoice,
9
+ updateInvoiceItem,
10
+ } from "../controller/invoiceController.js";
11
+ import { protect, requireTenantUser } from "../middleware/authMiddleware.js";
12
+
13
+ const router = Router();
14
+
15
+ router.use(protect, requireTenantUser);
16
+
17
+ router.post("/:customerId/items", addItemToInvoice);
18
+ router.get("/", getInvoices);
19
+ router.get("/customer/:customerId", getInvoicesByCustomer);
20
+ router.get("/:id", getInvoiceById);
21
+ router.delete('/:invoiceId/:itemId', deleteInvoiceItem);
22
+ router.put("/:invoiceId/items/:itemId", updateInvoiceItem);
23
+ router.post("/:customerId/pay", payInvoice);
24
+
25
+ export default router;
routes/productRoutes.js ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { Router } from "express";
2
+ import {
3
+ createProduct,
4
+ getProducts,
5
+ updateProduct,
6
+ deleteProduct,
7
+ } from "../controller/productController.js";
8
+ import { authorize, protect, requireTenantUser } from "../middleware/authMiddleware.js";
9
+
10
+ const router = Router();
11
+
12
+ router.use(protect, requireTenantUser);
13
+
14
+ router.post("/", authorize("owner", "admin"), createProduct);
15
+ router.get("/", getProducts);
16
+ router.put("/:id", authorize("owner", "admin"), updateProduct);
17
+ router.delete("/:id", authorize("owner", "admin"), deleteProduct);
18
+
19
+ export default router;
routes/reportRoutes.js ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { Router } from "express";
2
+ import { getDailyReport, getDashboardOverview } from "../controller/reportController.js";
3
+ import { authorize, protect, requireTenantUser } from "../middleware/authMiddleware.js";
4
+
5
+ const router = Router();
6
+
7
+ router.use(protect, requireTenantUser, authorize("owner", "admin"));
8
+
9
+ router.get("/overview", getDashboardOverview);
10
+ router.get("/daily", getDailyReport);
11
+
12
+ export default router;
routes/supplierRoutes.js ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { Router } from "express";
2
+ import {
3
+ createSupplier,
4
+ getSuppliers,
5
+ getSupplierById,
6
+ deleteSupplier,
7
+ addPurchasesToSupplier,
8
+ paySupplier,
9
+ } from "../controller/supplierController.js";
10
+ import { authorize, protect, requireTenantUser } from "../middleware/authMiddleware.js";
11
+
12
+ const router = Router();
13
+
14
+ router.use(protect, requireTenantUser, authorize("owner", "admin"));
15
+
16
+ router.post("/create", createSupplier);
17
+ router.get("/", getSuppliers);
18
+ router.get("/:id", getSupplierById);
19
+ router.delete("/:id", deleteSupplier);
20
+ router.post("/:id/items", addPurchasesToSupplier);
21
+ router.post("/:id/pay", paySupplier);
22
+
23
+ export default router;
utils/authCookies.js ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import crypto from "crypto";
2
+
3
+ export const AUTH_COOKIE_NAME = "sales_system_session";
4
+
5
+ const SEVEN_DAYS_IN_MS = 7 * 24 * 60 * 60 * 1000;
6
+
7
+ export const createSessionToken = () => crypto.randomBytes(32).toString("hex");
8
+
9
+ export const getAuthCookieOptions = () => ({
10
+ httpOnly: true,
11
+ sameSite: "lax",
12
+ secure: process.env.NODE_ENV === "production",
13
+ maxAge: SEVEN_DAYS_IN_MS,
14
+ path: "/",
15
+ });
16
+
17
+ export const getClearCookieOptions = () => ({
18
+ httpOnly: true,
19
+ sameSite: "lax",
20
+ secure: process.env.NODE_ENV === "production",
21
+ path: "/",
22
+ });
23
+
24
+ export const setAuthCookie = (res, token) => {
25
+ res.cookie(AUTH_COOKIE_NAME, token, getAuthCookieOptions());
26
+ };
27
+
28
+ export const clearAuthCookie = (res) => {
29
+ res.clearCookie(AUTH_COOKIE_NAME, getClearCookieOptions());
30
+ };
31
+
32
+ export const parseCookies = (cookieHeader = "") =>
33
+ cookieHeader.split(";").reduce((cookies, rawCookie) => {
34
+ const [name, ...valueParts] = rawCookie.trim().split("=");
35
+
36
+ if (!name) {
37
+ return cookies;
38
+ }
39
+
40
+ cookies[name] = decodeURIComponent(valueParts.join("="));
41
+ return cookies;
42
+ }, {});
43
+
44
+ export const toSlug = (value = "") =>
45
+ value
46
+ .toString()
47
+ .trim()
48
+ .toLowerCase()
49
+ .replace(/[^a-z0-9]+/g, "-")
50
+ .replace(/^-+|-+$/g, "")
51
+ .replace(/-{2,}/g, "-");
52
+
53
+ export const buildTenantCredentialsWhatsApp = ({
54
+ companyName,
55
+ ownerName,
56
+ username,
57
+ temporaryPassword,
58
+ loginUrl,
59
+ }) => {
60
+ const message = [
61
+ `مرحباً ${ownerName || "صاحب النشاط"}`,
62
+ `تم إنشاء حساب نشاطك التجاري على منصة ${companyName}.`,
63
+ `اسم المستخدم: ${username}`,
64
+ `كلمة المرور المؤقتة: ${temporaryPassword}`,
65
+ `رابط الدخول: ${loginUrl}`,
66
+ "يرجى تسجيل الدخول وتغيير كلمة المرور بعد أول استخدام.",
67
+ ].join("\n");
68
+
69
+ return {
70
+ message,
71
+ whatsappLink: `https://wa.me/?text=${encodeURIComponent(message)}`,
72
+ };
73
+ };