-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathindex.js
898 lines (819 loc) · 34.7 KB
/
index.js
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
require('dotenv').config()
const express = require("express");
const app = express();
const mysql = require("mysql");
const path = require('path');
const ejs = require("ejs");
const bcrypt = require("bcrypt");
const jwt = require("jsonwebtoken");
const cookieParser = require("cookie-parser");
const nodemailer = require("nodemailer");
const { decodeToken, authorizeAdmin, authorizeCustomer, authorizeOffice, authroizeAdminOrCustomer, checkWhereToGo} = require('./authServer');
const saltRound = 10;
const cookieOptions = { secure: false }; //change secure to true when deploying
app.set('view engine', 'ejs');
app.use(express.static(path.join(__dirname + '/public')));
app.use(express.static("static"));
app.use(express.urlencoded({ extended: true }));
app.use(cookieParser());
var livereload = require("livereload");
var connectLiveReload = require("connect-livereload");
const db = mysql.createConnection({
host: process.env.DB_HOST,
port: process.env.DB_PORT,
user: process.env.DB_USER,
password: process.env.DB_PASS,
database: process.env.DB_NAME,
});
db.connect();
const transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: process.env.EMAIL,
pass: process.env.PASSWORD
}
});
app.get("/", checkWhereToGo, (req, res) => {
res.sendFile(__dirname + "/views/home.html");
});
app.get("/signin", (req, res) => {
res.sendFile(__dirname + "/views/signin.html");
});
app.get("/signup", checkWhereToGo, (req, res) => {
res.sendFile(__dirname + "/views/signup.html");
});
app.get("/office_signup", checkWhereToGo, (req, res) => {
res.sendFile(__dirname + "/views/office_signup.html");
});
app.get("/new_car", authorizeOffice, (req, res) => {
res.sendFile(__dirname + "/views/car_form.html");
});
app.get("/admin", authorizeAdmin, (req, res) => {
res.sendFile(__dirname + "/views/admin_home.html");
});
app.get("/payments-search", authorizeAdmin, (req, res) => {
res.sendFile(__dirname + "/views/payment_report_search.html");
});
app.get("/cars-status-search", authorizeAdmin, (req, res) => {
res.sendFile(__dirname + "/views/car_status_search.html");
});
app.get("/customer-res-search", authorizeAdmin, (req, res) => {
res.sendFile(__dirname + "/views/customer_res_search.html");
});
app.get("/car-res-search", authorizeAdmin, (req, res) => {
res.sendFile(__dirname + "/views/car_res_search.html");
});
app.get("/res-search", authorizeAdmin, (req, res) => {
res.sendFile(__dirname + "/views/res_search.html");
});
app.get("/reserve", authorizeCustomer, (req, res) => {
res.sendFile(__dirname + "/views/reserve.html");
});
app.get("/advanced-search", authorizeAdmin, (req, res) => {
res.sendFile(__dirname + "/views/advanced_search.html");
});
app.get("/office-home", authorizeOffice, (req, res) => {
res.sendFile(__dirname + "/views/office_home.html");
});
app.get("/customer-home", authorizeCustomer, (req, res) => {
res.sendFile(__dirname + "/views/customer_home.html");
});
app.get("/add-car", authorizeOffice, (req, res) => {
res.sendFile(__dirname + "/views/add_car.html");
});
/*post requests*/
// ---------------------------------------------------------------------------------------------------------------------
app.post("/signup-landing", (req, res) => {
email = req.body.email;
res.render("signup.ejs", { userEmail: email });
});
app.post("/signin", (req, res) => {
//check first in customer, if it doesn't exist check in office
email = req.body.email;
password = req.body.password;
//check in admin in database
db.query("SELECT * FROM admin WHERE email = ?", [email], (err, result) => {
if (err)
return res.send({ message: err });
if (result.length > 0) {
//check if the password is correct
bcrypt.compare(password, result[0].password, function (err, response) {
if (response) {
//authenticating and authorize the user
const user = result[0];
const accessToken = jwt.sign({ user, role: "admin" }, process.env.ACCESS_TOKEN_SECRET, { expiresIn: "1h" });
res.cookie("token", accessToken, cookieOptions);
res.redirect("/admin");
}else{
res.redirect("/signin");
}
});
} else {
//check in customer
db.query("SELECT * FROM customer WHERE email = ?", [email], (err, result) => {
if (err)
return res.send({ message: err });
if (result.length > 0) {
bcrypt.compare(password, result[0].password, function (err, response) {
if (response) {
const user = result[0];
const accessToken = jwt.sign({ user, role: "customer" }, process.env.ACCESS_TOKEN_SECRET, { expiresIn: "1h" });
res.cookie("token", accessToken, cookieOptions);
res.redirect("/customer-home");
}else{
res.redirect("/signin");
}
});
} else {
db.query("SELECT * FROM office WHERE email = ?", [email], (err, result) => {
if (err)
return res.send({ message: err });
if (result.length > 0) {
bcrypt.compare(password, result[0].password, function (err, response) {
if (response) {
const user = result[0];
const accessToken = jwt.sign({ user, role: "office" }, process.env.ACCESS_TOKEN_SECRET, { expiresIn: "1h" });
res.cookie("token", accessToken, cookieOptions);
res.redirect("/office-home")
} else
res.redirect("/signin");
});
} else {
res.redirect("/signin");
}
});
}
});
}
});
});
app.post("/signup", (req, res) => {
//signing up as a customer
let email = req.body.email;
let password = req.body.password;
let fName = req.body.fName;
let lName = req.body.lName;
let ssn = req.body.ssn;
let creditCardNo = req.body.credit_card_no;
let holdreName = req.body.holder_name;
let expDate = req.body.credit_card_expiry_date;
let cvv = req.body.credit_card_cvv;
let phone = req.body.phone_no;
//add credit card info to the database
db.query("INSERT INTO credit_card (card_no, holder_name, exp_date, cvv) VALUES (?,?,?,?)",
[creditCardNo, holdreName, expDate, cvv], (err, result) => {
if (err){
console.log(err);
return res.send({ message: err });
}
});
//convert password to hash
bcrypt.hash(password, saltRound, function (err, hash) {
//store the info inside the database
db.query("INSERT INTO customer (email, password, fname, lname, ssn, phone_no) VALUES (?,?,?,?,?,?)",
[email, hash, fName, lName, ssn, phone], (err, result) => {
if (err){
console.log(err);
return res.send({ message: err });
}
db.query("INSERT INTO customer_credit (ssn, card_no) VALUES (?,?)",
[ssn, creditCardNo], (err, result) => {
if (err) {
console.log(err);
return res.send({ message: err });
} else {
//authenticating and authorize the user
const user = result[0];
const accessToken = jwt.sign({ user, role: "customer" }, process.env.ACCESS_TOKEN_SECRET, { expiresIn: "1h" });
res.cookie("token", accessToken, cookieOptions);
/*Sending mail*/
var mailOptions = {
from: process.env.EMAIL,
to: email,
subject: 'Welcome to VaCarTion🚘💚',
// text: "Welcome to VaCarTion! 😃💚\
// From all of us at VaCarTion, we wish you a splendid experience.\
// \
// Ride away!\
// \
// Regards,\
// The VaCarTion team"
text:"Welcome to VaCarTion!\nFrom all of us at VaCarTion, we wish you a splendid experience Ride away!\n\n\n\nRegards,\nThe VaCarTion team"
};
transporter.sendMail(mailOptions, function (error, info) {
if (error) {
console.log(error);
// res.send("failure");
} else {
console.log('Email sent: ' + info.response);
//res.send("success");
}
});
res.redirect("/signin");
}
});
});
});
});
app.post("/office-signup", (req, res) => {
//signing up as an office
let name = req.body.name;
let email = req.body.email;
let phone = req.body.phone_no;
let password = req.body.password;
let country = req.body.country;
let city = req.body.city;
let building_no = req.body.building_no;
//convert password to hash
bcrypt.hash(password, saltRound, function (err, hash) {
//store the info inside the database
db.query("INSERT INTO office (email, password, name, phone_no, country, city, building_no) VALUES (?,?,?,?,?,?,?)",
[email, hash, name, phone, country, city, building_no], (err, result) => {
if (err)
return res.send({ message: err });
//authenticating and authorize the user
const user = result[0];
const accessToken = jwt.sign({ user, role: "office" }, process.env.ACCESS_TOKEN_SECRET, { expiresIn: "1h" });
res.cookie("token", accessToken, cookieOptions);
res.send({ success: true });
});
});
});
//post request to add a car
app.post("/add-car", authorizeOffice, (req, res) => {
let plateId = req.body.plate_id;
let model = req.body.model;
let make = req.body.make;
let year = req.body.year;
let price = req.body.price;
let token = decodeToken(req.cookies.token);
let officeId = token.user.office_id;
let photo1 = req.body.photo1;
let photo2 = req.body.photo2;
let photo3 = req.body.photo3;
//store the info inside the database
db.query("INSERT INTO car (plate_id, model, make, year, price, office_id) VALUES (?,?,?,?,?,?)",
[plateId, model, make, year, price, officeId], (err, result) => {
if (err){
console.log(err);
return res.send({ message: err });
}
//make the car status = 0 (available) in the car_status table
db.query("INSERT INTO car_status (plate_id) VALUES (?)",
[plateId], (err, result) => {
if (err){
console.log(err);
return res.send({ message: err });
}
if(photo1 !== "")
db.query("INSERT INTO car_photos (plate_id, photo) VALUES (?,?)",
[plateId, photo1], (err, result) => {
if (err){
console.log(err);
return res.send({ message: err });
}
});
if(photo2 !== "")
db.query("INSERT INTO car_photos (plate_id, photo) VALUES (?,?)",
[plateId, photo2], (err, result) => {
if (err){
console.log(err);
return res.send({ message: err });
}
});
if(photo3 !== "")
db.query("INSERT INTO car_photos (plate_id, photo) VALUES (?,?)",
[plateId, photo3], (err, result) => {
if (err){
console.log(err);
return res.send({ message: err });
}
});
res.send({ message: "Car added successfully" });
});
});
});
//post request to add a reservation
app.post("/add-reservation", authorizeCustomer, (req, res) => {
let decodedToken = decodeToken(req.cookies.token);
let ssn = decodedToken.user.ssn;
let plateId = req.body.plateId;
let pickupDate = req.body.pickupDate;
let returnDate = req.body.returnDate;
let payNow = req.body.payNow;
let pickupForCarStatus = pickupDate + " 00:00:00";
let returnForCarStatus = returnDate + " 23:59:59";
var query = '';
if (payNow === "true")
query = "INSERT INTO reservation (ssn, plate_id, pickup_date, return_date, payment_date) VALUES (?,?,?,?, CURDATE())";
else
query = "INSERT INTO reservation (ssn, plate_id, pickup_date, return_date) VALUES (?,?,?,?)";
db.query(query,
[ssn, plateId, pickupDate, returnDate], (err, result) => {
if (err)
return res.send({ message: err });
db.query("INSERT INTO car_status (plate_id, status_code, status_date) VALUES (?,?,?)",
[plateId, 3, pickupForCarStatus], (err, result) => {
if (err)
return res.send({ message: err });
db.query("INSERT INTO car_status (plate_id, status_code, status_date) VALUES (?,?,?)",
[plateId, 0, returnForCarStatus], (err, result) => {
if (err)
return res.send({ message: err });
res.send({ success: true });
});
});
});
});
//check if ssn is already taken in customer
app.post("/check-ssn-customer", (req, res) => {
let ssn = req.body.ssn;
db.query("SELECT * FROM customer WHERE ssn = ?", [ssn], (err, result) => {
if (err)
return res.send({ message: err });
res.send({ taken: result.length > 0 });
});
});
app.post("/delete-car", authorizeOffice, (req, res) => {
let plate_id = req.body.plate_id;
//get office_id from the token
let decodedToken = decodeToken(req.cookies.token);
let office_id = decodedToken.user.office_id;
//check that only the office having that car can delete it
db.query("SELECT office_id FROM `car` WHERE plate_id = ?", [plate_id], (err, result) => {
if (err)
return res.send({ message: err });
if (result[0].office_id == office_id) {
db.query("DELETE FROM `car` WHERE plate_id = ?", [plate_id], (err, result) => {
if (err)
return res.send({ message: err });
res.send({ success: true });
});
} else {
res.send({ success: false, message: "You are not authorized to change the status of this car" });
}
});
});
app.post("/add-new-status", authorizeOffice, (req, res) => {
let status = req.body.status;
let plate_id = req.body.plate_id;
//get office_id from the token
let decodedToken = decodeToken(req.cookies.token);
let office_id = decodedToken.user.office_id;
//check that only the office having that car can changes its status
db.query("SELECT office_id FROM `car` WHERE plate_id = ?", [plate_id], (err, result) => {
if (err)
return res.send({ message: err });
if (result[0].office_id == office_id) {
//DATE_ADD(curDate(), INTERVAL 10 DAY)
db.query("INSERT INTO `car_status`(`plate_id`, `status_code`, `status_date`) VALUES (?,?,CURRENT_TIMESTAMP())", [plate_id, status], (err, result) => {
if (err)
return res.send({ success: false, message: err });
res.send({ success: true });
});
} else {
res.send({ success: false, message: "You are not authorized to change the status of this car" });
}
});
});
//check if email is already taken in customer
app.post("/check-email-customer", (req, res) => {
let email = req.body.email;
db.query("SELECT * FROM customer WHERE email = ?", [email], (err, result) => {
if (err)
return res.send({ message: err });
res.send({ taken: result.length > 0 });
});
});
//check if email is already taken for office
app.post("/check-email-office", (req, res) => {
let email = req.body.email;
db.query("SELECT * FROM office WHERE office.email = ?", [email], (err, result) => {
if (err)
return res.send({ message: err });
res.send({ taken: result.length > 0 });
});
});
//check if phone is already taken for customer
app.post("/check-phone-customer", (req, res) => {
let phone = req.body.phone;
db.query("SELECT * FROM customer WHERE phone_no = ?", [phone], (err, result) => {
if (err)
return res.send({ message: err });
res.send({ taken: result.length > 0 });
});
});
//check if phone is already taken for office
app.post("/check-phone-office", (req, res) => {
let phone = req.body.phone;
db.query("SELECT * FROM office WHERE phone_no = ?", [phone], (err, result) => {
if (err)
return res.send({ message: err });
res.send({ taken: result.length > 0 });
});
});
//car reservation search
app.post("/get-car-reservation", authorizeAdmin, (req, res) => {
var plate_id = req.body.plate_id;
///get the reservation info from the database
db.query("SELECT * FROM reservation NATURAL INNER JOIN car WHERE plate_id = ?",
[plate_id], (err, result) => {
if (err)
return res.send({ message: err });
res.send({ reservation: result, message: "success" });
});
});
//get customer name from ssn
app.post("/get-customer-name", authroizeAdminOrCustomer, (req, res) => {
let token = decodeToken(req.cookies.token);
var ssn = token.user.ssn;
///get the reservation info from the database
db.query("SELECT fname,lname FROM customer WHERE ssn = ?",
[ssn], (err, result) => {
if (err)
return res.send({ message: err });
res.send({ customer: result, message: "success" });
});
});
//get office name from office_id
app.post("/get-office-name", authorizeOffice, (req, res) => {
let token = decodeToken(req.cookies.token);
var id = token.user.office_id;
///get the reservation info from the database
db.query("SELECT name FROM office WHERE office_id = ?",
[id], (err, result) => {
if (err)
return res.send({ message: err });
res.send({ office: result, message: "success" });
});
});
// office reservations search
app.post("/get-office-reservation", authorizeOffice, (req, res) => {
//get decoded token from the request
let token = decodeToken(req.cookies.token);
var id = token.user.office_id;
///get the reservation info from the database
db.query("SELECT * , ((DATEDIFF(return_date,pickup_date)+1)*price ) as revenue FROM reservation JOIN car ON reservation.plate_id = car.plate_id JOIN office on car.office_id = office.office_id JOIN customer ON reservation.ssn = customer.ssn where office.office_id = ?",
[id], (err, result) => {
if (err)
return res.send({ message: err });
res.send({ reservations: result, message: "success" });
});
});
// customer reservation search
app.post("/get-customer-reservation", authroizeAdminOrCustomer, (req, res) => {
//get decoded token from the request
user = decodeToken(req.cookies.token);
var ssn = user.user.ssn;
if (ssn == null)
ssn = req.body.ssn;
///get the reservation info from the database
db.query("SELECT *, ((DATEDIFF(return_date,pickup_date)+1)*price )as revenue FROM reservation as r NATURAL INNER JOIN customer INNER JOIN car as c on c.plate_id = r.plate_id WHERE r.ssn = ?",
[ssn], (err, result) => {
if (err)
return res.send({ message: err });
res.send({ reservation: result, message: "success" });
});
});
//payments at certain period search
app.post("/get-payments-within-period", authorizeAdmin, (req, res) => {
var start_date = req.body.start_date;
var end_date = req.body.end_date;
//get the payments info from the database within the period
db.query("SELECT *,((DATEDIFF(return_date,pickup_date)+1)*price )as revenue FROM reservation NATURAL INNER JOIN car WHERE payment_date BETWEEN ? AND ?",
[start_date, end_date], (err, result) => {
if (err)
return res.send({ message: err });
res.send({ payment: result, message: "success" });
});
});
// reservations at certain period search
app.post("/get-reservations-within-period", authorizeAdmin, (req, res) => {
var start_date = req.body.start_date;
var end_date = req.body.end_date;
//get the reservation info from the database within the period
db.query("SELECT * FROM reservation as r NATURAL INNER JOIN customer INNER JOIN car as c on c.plate_id = r.plate_id WHERE reserve_date BETWEEN ? AND ?",
[start_date, end_date], (err, result) => {
if (err)
return res.send({ message: err });
res.send({ reservation: result, message: "success" });
});
});
// reservation at certain period search for a specific car
app.post("/get-car-reservation-within-period", authorizeAdmin, (req, res) => {
var plate_id = req.body.plate_id;
var start_date = req.body.start_date;
var end_date = req.body.end_date;
///get the reservation info from the database
db.query("SELECT * FROM reservation as r NATURAL INNER JOIN customer INNER JOIN car as c on c.plate_id = r.plate_id WHERE r.plate_id = ? AND reserve_date BETWEEN ? AND ?",
[plate_id, start_date, end_date], (err, result) => {
if (err)
return res.send({ message: err });
res.send({ reservation: result, message: "success" });
});
});
//get all the models of cars
app.post("/get-all-cars-models", (req, res) => {
//get the cars info from the database
db.query("SELECT DISTINCT model FROM car",
(err, result) => {
if (err)
return res.send({ message: err });
res.send({ carModels: result, message: "success" });
});
});
//get all the makes of cars for a specific model
app.post("/get-all-cars-makes", (req, res) => {
var model = req.body.model;
//get the cars info from the database
if (model == 'Any')
db.query("SELECT DISTINCT make FROM car",
[model], (err, result) => {
if (err)
return res.send({ message: err });
res.send({ carMakes: result, message: "success" });
});
else
db.query("SELECT DISTINCT make FROM car WHERE model = ?",
[model], (err, result) => {
if (err)
return res.send({ message: err });
res.send({ carMakes: result, message: "success" });
});
});
//get the cars with specific model
app.post("/get-cars-using-model", (req, res) => {
var model = req.body.model;
//get the cars info from the database
db.query("SELECT * FROM car WHERE model = ?",
[model], (err, result) => {
if (err)
return res.send({ message: err });
res.send({ cars: result, message: "success" });
});
});
app.post("/get-all-offices", (req, res) => {
db.query("SELECT * FROM office",
(err, result) => {
if (err)
return res.send({ message: err });
res.send({ offices: result, message: "success" });
});
});
//get the cars with specific make
app.post("/get-cars-using-make", (req, res) => {
var make = req.body.make;
//get the cars info from the database
db.query("SELECT * FROM car WHERE make = ?",
[make], (err, result) => {
if (err)
return res.send({ message: err });
res.send({ cars: result, message: "success" });
});
});
//get the cars with specific model and make
app.post("/get-cars-using-model-and-make", (req, res) => {
var model = req.body.model;
var make = req.body.make;
//get the cars info from the database
db.query("SELECT * FROM car WHERE model = ? AND make = ?",
[model, make], (err, result) => {
if (err)
return res.send({ message: err });
res.send({ cars: result, message: "success" });
});
});
//get the cars with specific office id
//1
app.post("/get-cars-using-office", authorizeOffice, (req, res) => {
/*let date = req.body.date;
date+=" 23:59:59";
let query = `SELECT *
FROM car_status
NATURAL INNER JOIN car
WHERE (plate_id,status_date) in (SELECT plate_id, MAX(status_date)
FROM car_status
where status_date <= ?
GROUP BY plate_id);`
db.query(query, [date], (err, result) => {
if (err)
return res.send({ message: err });
res.send({ carStatus: result, message: "success" });
});*/
let token = decodeToken(req.cookies.token);
var office_id = token.user.office_id;
db.query(`SELECT *
FROM car_status
NATURAL INNER JOIN car
WHERE (plate_id,status_date) in (SELECT plate_id, MAX(status_date)
FROM car_status
where status_date <= CURRENT_TIMESTAMP()
GROUP BY plate_id) AND office_id = ?`,
[office_id], (err, result) => {
if (err)
return res.send({ message: err });
res.send({ cars: result, message: "success" });
});
});
app.post("/get-most-rented-model", authorizeAdmin, (req, res) => {
db.query("SELECT model, COUNT(*) as count FROM reservation NATURAL INNER JOIN car GROUP BY model ORDER BY count DESC LIMIT 1", (err, result) => {
if (err)
return res.send({ message: err });
res.send({ mostRentedModel: result, message: "success" });
});
});
app.post("/get-most-rented-make", authorizeAdmin, (req, res) => {
db.query("SELECT make, COUNT(*) as count FROM reservation NATURAL INNER JOIN car GROUP BY make ORDER BY count DESC LIMIT 1", (err, result) => {
if (err)
return res.send({ message: err });
res.send({ mostRentedMake: result, message: "success" });
});
});
app.post("/get-most-profitable-office", authorizeAdmin, (req, res) => {
let query = `SELECT o.name, o.office_id, SUM(((DATEDIFF(r.return_date,r.pickup_date)+1)*c.price )) as total
FROM reservation as r
NATURAL INNER JOIN car as c
INNER JOIN office as o ON o.office_id = c.office_id
WHERE r.payment_date is not null
GROUP BY c.office_id
ORDER BY total DESC
LIMIT 1;`
db.query(query, (err, result) => {
if (err)
return res.send({ message: err });
res.send({ mostProfitableOffice: result, message: "success" });
});
});
//2
app.post("/get-car-status-on-a-day", authorizeAdmin, (req, res) => {
let date = req.body.date;
console.log(date);
date+=" 23:59:59";
let query = `SELECT *
FROM car_status
NATURAL INNER JOIN car
WHERE (plate_id,status_date) in (SELECT plate_id, MAX(status_date)
FROM car_status
where status_date <= ?
GROUP BY plate_id);`
db.query(query, [date], (err, result) => {
if (err)
return res.send({ message: err });
res.send({ carStatus: result, message: "success" });
});
});
app.post("/get-car-status-by-plate-id", authorizeOffice, (req, res) => {
let plate_id = req.body.plate_id;
let query = `SELECT *
FROM car_status
NATURAL INNER JOIN car
WHERE (plate_id,status_date) in (SELECT plate_id, MAX(status_date)
FROM car_status
where plate_id = ? and status_date <= current_timestamp()
GROUP BY plate_id);`
db.query(query, [plate_id], (err, result) => {
if (err)
return res.send({ message: err });
res.send({ carStatus: result, message: "success" });
});
});
app.post("/advanced-search", authorizeAdmin, (req, res) => {
let model = req.body.model;
let make = req.body.make;
let year = req.body.year;
let plate_id = req.body.plate_id;
let ssn = req.body.ssn;
let fname = req.body.fName;
let lname = req.body.lName;
let customerEmail = req.body.email;
let customerPhone = req.body.phone_no;
let reservationDate = req.body.reservation_date;
//query reservation and join with customer and car to get the info
let query1 = `SELECT * FROM reservation as r
NATURAL LEFT JOIN car AS c
LEFT JOIN customer AS cu ON cu.ssn = r.ssn
`
let join = `UNION ALL\n`
let query2 = `SELECT * FROM reservation as r
NATURAL RIGHT JOIN car As c
RIGHT JOIN customer AS cu ON cu.ssn = r.ssn
WHERE r.plate_id IS NULL`;
//add the conditions to the query
let conditions = [];
if (model != "" && model != null) {
conditions.push(`c.model = '${model}'`);
}
if (make != "" && make != null) {
conditions.push(`c.make = '${make}'`);
}
if (year != "" && year != null) {
conditions.push(`c.year = '${year}'`);
}
if (plate_id != "" && plate_id != null) {
conditions.push(`c.plate_id = '${plate_id}'`);
}
if (ssn != "" && ssn != null) {
conditions.push(`cu.ssn = '${ssn}'`);
}
if (fname != "" && fname != null) {
conditions.push(`cu.fname = '${fname}'`);
}
if (lname != "" && lname != null) {
conditions.push(`cu.lname = '${lname}'`);
}
if (customerEmail != "" && customerEmail != null) {
conditions.push(`cu.email = '${customerEmail}'`);
}
if (customerPhone != "" && customerPhone != null) {
conditions.push(`cu.phone_no = '${customerPhone}'`);
}
if (reservationDate != "" && reservationDate != null) {
conditions.push(`r.reservation_date = '${reservationDate}'`);
}
if (conditions.length > 0) {
query1 += " WHERE " + conditions.join(" AND ");
}
if (conditions.length > 0) {
query2 += " AND " + conditions.join(" AND ");
}
let query = query1 + join + query2;
db.query
(query, (err, result) => {
if (err)
return res.send({ message: err });
res.send({ reservation: result, message: "success" });
}
);
});
app.post("/show-avaialable-cars", authorizeCustomer, (req, res) => {
let pickup_date = req.body.pickup_date;
let return_date = req.body.return_date;
let date = pickup_date + " 23:59:59";
let model = req.body.model;
let make = req.body.make;
let city = req.body.city;
let country = req.body.country;
let office_name = req.body.office_name;
let office_build_no = req.body.office_build_no;
let conditions = []
let query = `SELECT *
FROM car_status
NATURAL INNER JOIN car as c
NATURAL INNER JOIN office as o
NATURAL INNER JOIN car_photos
WHERE (plate_id,status_date) in (SELECT plate_id, MAX(status_date)
FROM car_status
where status_date <= ?
GROUP BY plate_id) AND c.plate_id NOT IN (SELECT plate_id FROM reservation WHERE (pickup_date <= ? AND return_date >= ?) or (pickup_date <= ? AND return_date >= ?) or (pickup_date >= ? AND return_date <= ?) or (pickup_date <= ? AND return_date >= ?))`;
if (model != "Any") {
conditions.push(`c.model = '${model}'`);
}
if (make != "Any") {
conditions.push(`c.make = '${make}'`);
}
if (city != "") {
conditions.push(`o.city = '${city}'`);
}
if (country != "") {
conditions.push(`o.country = '${country}'`);
}
if (office_name != "") {
conditions.push(`o.name = '${office_name}'`);
}
if (office_build_no != "") {
conditions.push(`o.building_no = '${office_build_no}'`);
}
if (conditions.length > 0) {
query += " AND " + conditions.join(" AND ");
}
db.query(query, [date, pickup_date, pickup_date, pickup_date, return_date, pickup_date, return_date, pickup_date, return_date], (err, result) => {
if (err)
return res.send({ message: err });
if(result != null)
result = result.filter(car => car.status_code == 0);
res.send({ cars: result, message: "success" });
});
});
app.post("/pay-reservation",(req,res)=>{
let reservation_no = req.body.reservation_no;
let query = `UPDATE reservation SET payment_date = CURDATE() WHERE reservation_no = ?`;
db.query(query, [reservation_no], (err, result) => {
if (err)
return res.send({ message: err });
res.send({ message: "success" });
});
});
app.post("/logout", (req, res) => {
res.clearCookie("token");
res.redirect("/");
});
app.use(connectLiveReload());
app.listen(process.env.PORT || 3000, () => {
console.log("server started on port: ", process.env.PORT || 3000)
});
// const liveReloadServer = livereload.createServer();
// liveReloadServer.server.once("connection", () => {
// setTimeout(() => {
// liveReloadServer.refresh("/");
// }, 100);
// });