-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
2236 lines (1902 loc) · 68.4 KB
/
server.js
File metadata and controls
2236 lines (1902 loc) · 68.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import express from 'express';
import bcrypt from 'bcryptjs';
import bodyParser from 'body-parser';
import cookieParser from 'cookie-parser';
import mongoose from 'mongoose';
import cors from 'cors';
import client from './redisClient.js';
import dotenv from 'dotenv';
dotenv.config();
import swaggerUi from 'swagger-ui-express';
import { specs } from './config/swagger.config.js';
import { connecttomongodb } from './backend/models/connect.js';
import { User } from './backend/models/UserSchema.js';
import {Product} from './backend/models/ProductSchema.js';
import {Booking} from './backend/models/Bookings.js';
import { Manager } from './backend/models/ManagerSchema.js';
import {Location} from './backend/models/Location.js';
import { Admin } from './backend/models/Admin.js';
import {Review} from './backend/models/ReviewSchema.js';
import adminRoutes from './backend/controllers/adminRoutes.js';
import managerRoutes from './backend/controllers/managerRoutes.js';
import userRoutes from './backend/controllers/userRoutes.js';
import nodemailer from "nodemailer";
import path from 'path';
import morgan from 'morgan';
import helmet from 'helmet';
import { createStream } from 'rotating-file-stream';
import { fileURLToPath } from 'url';
import { dirname, join } from 'path';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const MONGODB_URL=process.env.MONGODB_URL || 'mongodb://localhost:27017/Rentals';
const app = express();
connecttomongodb(MONGODB_URL)
.then(() => console.log('Connected to MongoDB Atlas !'))
.catch(err => {
console.error('Failed to connect to MongoDB', err);
});
// Run only once for index syncing after modifications
// await User.syncIndexes();
// await Booking.syncIndexes();
// await Manager.syncIndexesc();
// await Admin.syncIndexes();
// await Product.syncIndexes();
//middlewares
// Parse the FRONTEND_URL to handle multiple origins if needed
const FRONTEND_URL = process.env.FRONTEND_URL || 'http://localhost:5173';
const allowedOrigins = [
FRONTEND_URL,
'http://http://13.201.99.37:5173', // EC2 public IP
'http://localhost:5173', // Local development
];
app.use(cors({
origin: function(origin, callback) {
// Allow requests with no origin (like mobile apps, curl requests, etc)
if (!origin) return callback(null, true);
if (allowedOrigins.indexOf(origin) === -1) {
const msg = `The CORS policy for this site does not allow access from the specified Origin: ${origin}`;
return callback(new Error(msg), false);
}
return callback(null, true);
},
credentials: true
}));
//custom application level middleware
app.use((req, res, next) => {
console.log(`${req.method} ${req.url} - ${new Date().toISOString()}`);
next(); // Moves to the next middleware
});
// built-in middleware
app.use(express.json({limit:'50mb'}));
app.use(express.urlencoded({limit:'50mb', extended: true }));
//third -party middleware
app.use(cookieParser());
app.use(bodyParser.json({limit:'50mb'}));
app.use(helmet());
// app.use(bodyParser.json({ limit: '50mb' }));
morgan.token("username", (req) => req.username || "Unknown");
morgan.token("role", (req) => req.role || "Unknown");
const loginLogStream =createStream((time, index) => {
if (!time) return "login.log";
const date = new Date(time);
return `login-${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}-${date.getHours()}.log`;
}, {
interval: '1d', // Rotate every hour
path: path.join(__dirname, 'log')
});
//intentionally throws an error
app.get('/error-test', (req, res, next) => {
try{
throw new Error("Forced error for testing ! ");
}catch(err){
next(err);}
});
app.get('/xx', (req, res) => {
try{ res.send('Hello World!')}
catch(err){next(err)}
});
// error-handling middleware
app.use((err, req, res, next) => {
const statusCode = err.status || 500;
res.status(statusCode).json({
in:"error-handling-middleware",
success: false,
message: err.message || 'Internal Server Error'
});
});
app.use((req, res, next) => {
req.username = req.cookies?.user_id || "Guest"; // Fetch user from cookie
req.role = req.cookies?.role || "Guest";
next();
});
// router -level middleware
const adminMiddleware = async (req, res, next) => {
console.log(`\nAdmin entered ${req.originalUrl} !`);
next();
}
const managerMiddleware = async (req, res, next) => {
console.log(`\nManager entered ${req.originalUrl} !`);
next();
}
app.use('/admindashboard',adminMiddleware,adminRoutes);
app.use('/manager',managerMiddleware, managerRoutes);
app.use('/user', userRoutes);
app.get('/locations', async (req, res) => {
try {
const locations = await Location.find({});
res.json({ locations: locations[0].locations });
} catch (error) {
console.error('Error fetching locations:', error);
res.status(500).json({ message: 'Internal Server Error' });
}
});
//Signup
app.post('/signup', async (req, res) => {
const { username, email, dateofbirth,password } = req.body;
if (!username || !email || !dateofbirth || !password) {
return res.status(409).json({ errormessage: 'All fields are required' });
}
try {
const existingUser = await User.findOne({ username });
const existingEmail = await User.findOne({ email });
if (existingEmail) {
return res.status(409).json({ errormessage: 'Email already exists' });
}
if (existingUser) {
return res.status(409).json({ errormessage: 'Username already exists' });
}
const hashedPassword = await bcrypt.hash(password, 10);
const newUser = new User({
username,
email,
dateofbirth,
password: hashedPassword,
expired:false,
});
await newUser.save();
res.status(201).json({ errormessage: 'User registered successfully' });
} catch (error) {
console.error('Error registering user:', error);
res.status(500).json({ errormessage: 'Error registering user' });
}
});
app.post('/login', async (req, res,next) => {
const { username, password, role } = req.body;
if (!username || !password) {
return res.status(400).json({ errormessage: 'All fields are required' });
}
try {
let user_id;
if (role === "Manager") {
const existingManager = await Manager.findOne({ username });
if (existingManager) {
const checkManagerPassword = await bcrypt.compare(password, existingManager.password);
if (!checkManagerPassword) {
return res.status(401).json({ errormessage: 'Password is incorrect for Manager!' });
}
user_id = existingManager._id.toString(); // Set user_id for Manager
} else {
return res.status(401).json({ errormessage: 'Manager not found!' });
}
} else if (role === "User") {
const existingUser = await User.findOne({ username });
if (!existingUser) {
return res.status(401).json({ errormessage: 'Username not found!' });
}
if(role=='User' && existingUser.expired)
{
return res.status(401).json({errormessage: "Account not found !"})
}
const checkpassword = await bcrypt.compare(password, existingUser.password);
if (!checkpassword) {
return res.status(401).json({ errormessage: 'Password is incorrect!' });
}
user_id = existingUser._id.toString(); // Set user_id for User
} else {
const existingUser = await Admin.findOne({ username });
if (!existingUser) {
return res.status(401).json({ errormessage: 'Username not found!' });
}
const checkpassword = password === existingUser.password;
if (!checkpassword) {
return res.status(401).json({ errormessage: 'Password is incorrect!' });
}
user_id = existingUser._id.toString();
}
// Attach user details for Morgan middleware (used in logs)
req.user_id = user_id;
req.username = username;
req.role = role;
// Set cookie for user (either Manager or User)
res.cookie('user_id', user_id, {
httpOnly: false,
secure: false,
sameSite: 'lax',
path: '/'
});
res.cookie('role', role, {
httpOnly: false,
secure: false,
sameSite: 'lax',
path: '/'
});
morgan(':date[iso] | User: :username | Role: :role | IP: :remote-addr | Status: :status | :method :url - :response-time ms',
{ stream: loginLogStream })(req, res, () => {});
res.status(200).json({ successmessage: `${role} Login successfully `});
} catch (error) {
console.error('Error occurred while logging in:', error);
res.status(500).json({ errormessage: 'Error while user logging in!' });
}
});
//RentForm
app.post('/RentForm', async (req, res) => {
const { productType,
productName,
locationName,
fromDate,
toDate,
price,
image,} = req.body;
if (!productType||!productName||!locationName||!fromDate||!toDate||!price||!image) {
return res.status(409).json({ errormessage: 'All fields are required' });
}
try {
const cookieuserid=req.cookies.user_id;
if (!cookieuserid) {
return res.status(401).json({ errormessage: 'Unauthorized: No userid cookie found' });
}
const exist_user = await User.findOne({ _id: cookieuserid });
if (!exist_user) {
return res.status(404).json({ errormessage: 'User not found' });
}
const newProduct = new Product({
userid: cookieuserid, // Use 'username' to match schema
productType,
productName,
locationName,
fromDateTime: new Date(fromDate), // Convert to Date object
toDateTime: new Date(toDate), // Convert to Date object
price,
photo: image, // Use 'photo' to match schema
uploadDate:new Date(),
bookingdates:[],
bookingids:[],
expired:true,
});
const savedProduct = await newProduct.save();
exist_user.rentals.push(savedProduct._id);
await exist_user.save();
const notifyupdate=await Manager.findOneAndUpdate({branch:savedProduct.locationName},{$push:{notifications:{message:savedProduct._id,seen:false}}},{new:true});
res.status(201).json({ errormessage: 'Uploaded successfully'});
} catch (error) {
console.error('Error occured :', error);
res.status(500).json({ errormessage: 'Upload failed' });
}
});
// correct one
// app.post('/products', async (req, res) => {
// try {
// const { productType, locationName, fromDateTime, toDateTime, price } = req.body;
// const query = { expired: false };
// if (productType) query.productType = productType;
// if (locationName) query.locationName = locationName;
// if (fromDateTime) query.fromDateTime = { $lte: new Date(fromDateTime) };
// if (toDateTime) query.toDateTime = { ...query.toDateTime, $gte: new Date(toDateTime) };
// if (price) query.price = { $lte: price };
// const cacheKey = JSON.stringify(query);
// // Check Redis for cached IDs
// const cachedIds = await client.get(cacheKey);
// if (cachedIds) {
// console.log('🧠 Cache hit! Fetching products by ID');
// const productIds = JSON.parse(cachedIds);
// const products = await Product.find({ _id: { $in: productIds } });
// return res.status(200).json(products);
// }
// // If not in cache, query DB
// const products = await Product.find(query);
// const productIds = products.map(p => p._id);
// // Cache IDs only
// await client.set(cacheKey, JSON.stringify(productIds), { EX: 3600 });
// console.log('💾 DB hit. Cached product IDs');
// res.status(200).json(products);
// } catch (error) {
// console.error('Error fetching products:', error);
// res.status(500).json({ errormessage: 'Failed to fetch products' });
// }
// });
app.get('/autocomplete', async (req, res) => {
try {
const { query } = req.query;
if (!query || query.length < 2) {
return res.status(400).json({ error: 'Query must be at least 2 characters' });
}
const cacheKey = `autocomplete:${query.toLowerCase()}`;
// Try to get from cache
const cachedResults = await client.get(cacheKey);
if (cachedResults) {
console.log('🧠 Autocomplete cache hit');
return res.json(JSON.parse(cachedResults));
}
// Query database
const suggestions = await Product.find({
productName: { $regex: `^${query}`, $options: 'i' },
expired: false
})
.select('productName _id')
.limit(10)
.sort({ uploadDate: -1 });
// Cache results for 15 minutes
await client.set(cacheKey, JSON.stringify(suggestions), { EX: 7200 });
console.log('💾 Cached autocomplete results');
res.json(suggestions);
} catch (error) {
console.error('Autocomplete error:', error);
res.status(500).json({ error: 'Internal server error' });
}
});
// app.post('/products', async (req, res) => {
// try {
// const { productType, locationName, fromDateTime, toDateTime, price, searchQuery } = req.body;
// // Build base query
// const query = { expired: false };
// if (productType) query.productType = productType;
// if (locationName) query.locationName = locationName;
// if (fromDateTime) query.fromDateTime = { $lte: new Date(fromDateTime) };
// if (toDateTime) query.toDateTime = { $gte: new Date(toDateTime) };
// if (price) query.price = { $lte: parseFloat(price) };
// // Add text search if searchQuery exists
// if (searchQuery) {
// query.$text = { $search: searchQuery }; // 🔄 replaced regex with text search
// }
// // const cacheKey = JSON.stringify(query);
// // Check Redis cache
// // const cachedIds = await client.get(cacheKey);
// // if (cachedIds) {
// // console.log('🧠 Cache hit! Fetching products by ID');
// // const productIds = JSON.parse(cachedIds);
// // // Fixed: removed extra semicolon and moved allowDiskUse to correct position
// // const products = await Product.find({ _id: { $in: productIds } })
// // .sort({ uploadDate: -1 })
// // .allowDiskUse(true);
// // return res.status(200).json(products);
// // }
// // If not in cache, query DB
// console.log('💽 Cache miss! Querying database directly');
// // Use aggregation pipeline with allowDiskUse for better performance with sorting
// const products = await Product.aggregate([
// { $match: query },
// { $sort: { uploadDate: -1 } },
// { $limit: 50 },
// { $project: {
// productName: 1,
// price: 1,
// uploadDate: 1,
// photo: 1,
// locationName: 1,
// productType: 1,
// fromDateTime: 1,
// toDateTime: 1
// }
// }
// ], { allowDiskUse: true });
// if (products.length === 0) {
// return res.status(200).json([]);
// }
// // const productIds = products.map(p => p._id);
// // Cache results for 1 hour
// // await client.set(cacheKey, JSON.stringify(productIds), { EX: 3600 });
// // console.log('💾 DB hit. Cached product IDs');
// res.status(200).json(products);
// } catch (error) {
// console.error('Error fetching products:', error);
// res.status(500).json({ errormessage: 'Failed to fetch products', details: error.message });
// }
// });
app.post('/products', async (req, res) => {
try {
const { productType, locationName, fromDateTime, toDateTime, price, searchQuery } = req.body;
if (!productType) {
return res.status(400).json({ errormessage: 'productType is required.' });
}
const redisKey = `products:${productType}`;
let products = await client.get(redisKey);
if (products) {
console.log(`🧠 Redis cache hit: ${redisKey}`);
products = JSON.parse(products);
} else
{
console.log(`💽 Redis cache miss: ${redisKey}. Querying MongoDB...`);
// Fetch and cache all valid products of this type
products = await Product.find({
expired: false,
productType,
toDateTime: { $gte: new Date() }
}).lean();
await client.set(redisKey, JSON.stringify(products), { EX: 7200 }); // Cache for 1 hour
}
// 🧠 In-memory filtering
const filtered = products.filter(p => {
if (locationName && p.locationName !== locationName) return false;
if (fromDateTime && new Date(p.fromDateTime) > new Date(fromDateTime)) return false;
if (toDateTime && new Date(p.toDateTime) < new Date(toDateTime)) return false;
if (price && p.price > parseFloat(price)) return false;
if (searchQuery && !p.productName.toLowerCase().includes(searchQuery.toLowerCase())) return false;
return true;
});
res.status(200).json(filtered);
} catch (error) {
console.error('Error fetching products:', error);
res.status(500).json({ errormessage: 'Failed to fetch products', details: error.message });
}
});
app.post('/checkconflict', async (req, res) => {
try {
const { product_id, fromDateTime, toDateTime } = req.body;
const product = await Product.findById(product_id);
if (!product) {
return res.status(404).json({ message: 'Product not found' });
}
const from = new Date(fromDateTime);
const to = new Date(toDateTime);
const conflict = await Booking.findOne({
product_id,
$or: [
{ fromDateTime: { $lt: to }, toDateTime: { $gt: from } }
],
});
if (conflict) {
console.log("true");
return res.status(200).json({ conflict: true });
} else {
console.log("false");
return res.status(200).json({ conflict: false });
}
} catch (error) {
console.error("Error checking conflicts:", error);
res.status(500).json({ message: 'Internal Server Error' });
}
});
app.post('/product/:product_id',async(req,res)=>{
const {product_id}=req.params;
try{
const reqproduct=await Product.findById(product_id);
if(!reqproduct)
{
return res.status(404).json({error :'product not found !'});
}
return res.status(200).json(reqproduct);
}catch(error)
{
res.status(500).json({error:"server error !"});
}
})
// app.post('/booking',async (req,res)=>{
// try{
// const {product_id,fromDateTime,toDateTime,price}=await req.body;
// const bookingDate=new Date();
// const buyerid=req.cookies.user_id;
// if (!buyerid || !/^[0-9a-fA-F]{24}$/.test(buyerid)) {
// return res.status(400).json({ message: "Invalid buyer ID format!" });
// }
// const from = new Date(fromDateTime);
// const to = new Date(toDateTime);
// const conflict = await Booking.findOne({
// product_id,
// $or: [
// { fromDateTime: { $lt: to }, toDateTime: { $gt: from } }
// ],
// });
// if(conflict)
// {
// return res.status(401).json({message:"Not available"});
// }
// const newbooking = new Booking({
// product_id,
// buyerid,
// fromDateTime,
// toDateTime,
// price,
// bookingDate,
// });
// const y=await newbooking.save();
// const newbookingid=newbooking._id.toString();
// const x=await User.findOneAndUpdate({_id:buyerid},{$push:{bookings:newbookingid}},{new:true});
// if(!y)
// {console.log("booking ot successful")
// return res.status(401).json({message:"booking not successful !"})
// }
// else if(!x)
// { console.log("couldnt update booking")
// return res.status(401).json({ message: "Couldn't update the booking!" });
// }
// const product = await Product.findById(product_id);
// product.bookingdates.push([new Date(fromDateTime),new Date(toDateTime)]);
// await product.save();
// const z=await User.findOneAndUpdate({_id:product.userid},{$push:{notifications:{message:newbookingid,seen:false}}},{new:true})
// await z.save();
// const Managernotify=await Manager.findOneAndUpdate({branch:product.locationName},{$push:{bookingnotifications:{bookingid:y._id}}},{new:true});
// res.status(200).json({message:"Booking successful !"});
// console.log("booking successful !");
// }
// catch(error){
// console.log(error);
// res.status(500).json({message:"server error !"});
// }
// })
app.post('/booking', async (req, res) => {
try {
const { product_id, fromDateTime, toDateTime, price } = req.body;
const bookingDate = new Date();
const buyerid = req.cookies.user_id;
if (!buyerid || !/^[0-9a-fA-F]{24}$/.test(buyerid)) {
return res.status(400).json({ message: "Invalid buyer ID format!" });
}
const from = new Date(fromDateTime);
const to = new Date(toDateTime);
const conflict = await Booking.findOne({
product_id,
$or: [{ fromDateTime: { $lt: to }, toDateTime: { $gt: from } }],
});
if (conflict) {
return res.status(401).json({ message: "Not available" });
}
const newbooking = new Booking({
product_id,
buyerid,
fromDateTime,
toDateTime,
price,
bookingDate,
});
const savedBooking = await newbooking.save();
const newBookingId = savedBooking._id.toString();
const updatedUser = await User.findByIdAndUpdate(
buyerid,
{ $push: { bookings: newBookingId } },
{ new: true }
);
if (!savedBooking || !updatedUser) {
return res.status(401).json({ message: "Booking not successful!" });
}
const product = await Product.findById(product_id);
product.bookingdates.push([from, to]);
await product.save();
// 🔔 Push notification to seller (product.userid)
const notificationObj = { message: newBookingId, seen: false };
await User.findByIdAndUpdate(product.userid, {
$push: { notifications: notificationObj },
});
// 🧠 Update Redis cache for seller's notifications (if exists)
const notifCacheKey = `user:${product.userid}:notifications`;
const cachedNotif = await client.get(notifCacheKey);
if (cachedNotif) {
const parsed = JSON.parse(cachedNotif);
parsed.push(notificationObj);
await client.set(notifCacheKey, JSON.stringify(parsed), { EX: 7200 }); // keep TTL as before
console.log('🔄 Redis cache updated for seller notifications');
}
await Manager.findOneAndUpdate(
{ branch: product.locationName },
{ $push: { bookingnotifications: { bookingid: savedBooking._id } } }
);
// ✅ Update Redis cache for the buyer's bookings/products
const cacheKey = `user_bookings_ids:${buyerid}`;
const cached = await client.get(cacheKey);
if (cached) {
const parsed = JSON.parse(cached);
const updatedCache = {
bookingIds: [...new Set([...parsed.bookingIds, newBookingId])],
productIds: [...new Set([...parsed.productIds, product_id.toString()])]
};
await client.set(cacheKey, JSON.stringify(updatedCache), { EX: 7200 });
console.log('🧠 Redis cache updated for user:', buyerid);
}
res.status(200).json({ message: "Booking successful!" });
console.log("✅ Booking successful!");
} catch (error) {
console.error("❌ Booking error:", error);
res.status(500).json({ message: "Server error!" });
}
});
app.get("/grabAdmin", async (req, res) => {
const userId = req.cookies.user_id;
console.log("User ID from cookie:", userId); // Log user ID
if (!userId) {
return res.status(400).json({ message: "No user ID found in cookies" });
}
try {
const admin = await Admin.findById(userId);
console.log("admin", admin);
if (!admin) {
console.log("No Admin found for user ID:", userId); // Log if no admin found
return res.status(404).json({ message: "Admin not found" });
}
const name = admin.username;
res.json({ name }); // Return the name inside an object
} catch (err) {
console.error("Error fetching Name", err);
res.status(500).json({ message: "Error fetching Name", error: err.message });
}
});
app.post('/api/addBranch', async (req, res) => {
const { name } = req.body;
try {
let locationDoc = await Location.findOne();
if (locationDoc) {
if (locationDoc.locations.includes(name)) {
return res.status(400).json({ message: 'Branch is already in existence' });
}
locationDoc.locations.push(name);
await locationDoc.save();
} else {
locationDoc = new Location({ locations: [name] });
await locationDoc.save();
}
res.status(201).json({ message: 'Location added successfully', locations: locationDoc.locations });
} catch (error) {
res.status(500).json({ message: ' location', error });
}
});
// app.get('/admindashboard/registeredusers',async(req,res)=>{
// try{
// const users=await User.find({expired:false});
// const usercount = await User.countDocuments({expired:false});
// if(!users)
// {
// return res.status(200).json({error :'Users not found !'});
// }
// return res.status(200).json({registercount:usercount,users:users,});
// }catch(error)
// {
// res.status(500).json({error:"server error !"});
// }
// })
// app.post('/admindashboard/deleteusers', async (req, res) => {
// const { user_id, forceDelete } = req.body;
// try {
// // Check if user has bookings
// const bookings = await Booking.findOne({ buyerid: user_id });
// if (bookings && !forceDelete) {
// // If bookings exist and forceDelete is false, return an alert
// return res.status(200).json({ alert: true, });
// }
// // If forceDelete is true or there are no bookings, proceed with deletion
// await Product.updateMany({ userid: user_id }, { $set: { expired: true } }, { new: true });
// const deletedUser = await User.findOneAndUpdate({_id:user_id},{$set:{expired :true}},{new:true});
// if (!deletedUser) {
// return res.status(200).json({ message: 'User not found in database!' });
// }
// return res.status(200).json({ message: 'User and their bookings/products deleted successfully!' });
// } catch (error) {
// console.error(error);
// return res.status(500).json({ message: 'Server error!' });
// }
// });
// app.post('/admindashboard/createmanager',async(req,res)=>{
// console.log(req.body);
// const { username, email,password ,branch} = req.body;
// if (!username || !email || !branch || !password) {
// return res.status(409).json({ errormessage: 'All fields are required' });
// }
// try {
// const existingUser = await Manager.findOne({ username });
// const existingEmail = await Manager.findOne({ email });
// const existingbranch= await Manager.findOne({branch});
// if(existingbranch)
// {
// return res.status(404).json({ errormessage: 'Manager for branch already exists !'});
// }
// if (existingEmail) {
// return res.status(404).json({ errormessage: 'Email already exists' });
// }
// if (existingUser) {
// return res.status(404).json({ errormessage: 'Username already exists' });
// }
// const hashedPassword = await bcrypt.hash(password, 10);
// const newManager = new Manager({
// username,
// email,
// password: hashedPassword,
// branch:branch,
// notifications:[],
// });
// await newManager.save();
// res.status(201).json({ errormessage: 'Manager created successfully !' });
// } catch (error) {
// console.error('Error registering user:', error);
// res.status(500).json({ errormessage: 'Error creating Manager' });
// }
// })
// app.get('/admindashboard/registeredmanagers', async (req, res) => {
// try {
// const users = await Manager.find({});
// const usercount = await Manager.countDocuments({});
// if (users.length === 0) {
// return res.status(200).json({ error: 'No managers found!' });
// }
// return res.status(200).json({ registercount: usercount, managers: users });
// } catch (error) {
// console.error(error);
// return res.status(500).json({ error: 'Server error!' });
// }
// });
// app.post('/admindashboard/deletemanagers',async(req,res)=>{
// const { manager_id, forceDelete } = req.body;
// try {
// if (!forceDelete) {
// return res.status(200).json({ alert: true, });
// }
// const deletedUser = await Manager.findByIdAndDelete(manager_id);
// if (!deletedUser) {
// return res.status(404).json({ message: 'Manager not found in database!' });
// }
// return res.status(200).json({ message: 'Manager deleted successfully!' });
// } catch (error) {
// console.error(error);
// return res.status(500).json({ message: 'Server error!' });
// }
// })
app.get("/grabBookings", async (req, res) => {
try {
const userId = req.cookies.user_id;
if (!userId) {
return res.status(400).json({ message: "No userid cookie found" });
}
const cacheKey = `user_bookings_ids:${userId}`;
const cached = await client.get(cacheKey);
let bookingIds = [];
let productIds = [];
if (cached) {
console.log('✅ Serving Booking IDs from Redis cache');
const parsed = JSON.parse(cached);
bookingIds = parsed.bookingIds;
productIds = parsed.productIds;
} else
{
console.log('💾 Fetching Booking/Product IDs from DB');
const user = await User.findById(userId);
if (!user) {
return res.status(404).json({ message: "User not found" });
}
bookingIds = user.bookings;
const bookings = await Booking.find({ _id: { $in: bookingIds } });
productIds = bookings.map(b => b.product_id);
// Save just the IDs to cache
await client.set(cacheKey, JSON.stringify({ bookingIds, productIds }), { EX: 7200 });
}
// Fetch full documents from DB using IDs
const bookings = await Booking.find({ _id: { $in: bookingIds } });
const products = await Product.find(
{ _id: { $in: productIds } },
{ photo: 0 } // exclude 'photo' field
);
if (!bookings.length) {
return res.status(404).json({ message: "No booking details found for this user" });
}
res.json({
BookingDetails: bookings,
ProductDetails: products,
});
} catch (err) {
console.error("❌ Error:", err);
res.status(500).json({ message: "An error occurred", error: err.message });
}
});
// app.get("/grabBookings", async (req, res) => {
// try {
// if (req.cookies.user_id) {
// const userid = req.cookies.user_id;
// const exist_user = await User.findOne({ _id: userid });
// if (exist_user) {
// const bookingIds = exist_user.bookings;
// const bookings = await Booking.find({ _id: { $in: bookingIds } });
// if (bookings.length > 0) {
// const productIds = bookings.map(booking => booking.product_id);
// const products = await Product.find({ _id: { $in: productIds } });
// res.json({
// BookingDetails: bookings,
// ProductDetails: products,
// });
// } else {
// res.status(404).json({ message: "No booking details found for this user" });
// }
// } else {
// res.status(404).json({ message: "User not found" });
// }
// } else {
// res.status(400).json({ message: "No userid cookie found" });
// }
// } catch (err) {
// res.status(500).json({ message: "An error occurred", error: err.message });
// }
// });
app.post("/settings", async (req, res) => {
try {
const { editUsername, email,password } = req.body;
const currentUserid = req.cookies.user_id;
if (!currentUserid) {
return res.status(401).json({ message: "Unauthorized: No user logged in" });
}
const existingUser = await User.findOne({ _id: currentUserid });
if (!existingUser) {
return res.status(404).json({ message: "User not found" });
}
if (email && email !== existingUser.email) {
const emailExists = await User.findOne({ email });
if (emailExists) {
return res.status(409).json({ message: "Email already in use" });
}
existingUser.email = email;
}
if (editUsername && editUsername !== existingUser.username) {
const usernameExists = await User.findOne({ username: editUsername });