-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathserver.js
More file actions
1564 lines (1416 loc) · 50.9 KB
/
server.js
File metadata and controls
1564 lines (1416 loc) · 50.9 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
// importing libraries
const express = require("express");
const app = express();
const { pool } = require("./dbConfig");
const bcrypt = require("bcrypt");
const session = require("express-session");
const flash = require("express-flash");
const passport = require("passport");
const initializePassport = require("./passportConfig");
initializePassport(passport);
const PORT = process.env.PORT || 4000;
const bodyParser = require('body-parser');
const multer = require('multer');
const storage = multer.diskStorage({
destination: './public/uploads/',
filename: function (req, file, cb) {
cb(null, new Date().toISOString().replace(/:/g, '-') + file.originalname);
}
});
const fileFilter = (req, file, cb) => {
if (file.mimetype === 'image/jpeg' || file.mimetype === 'image/png' || file.mimetype === 'image/jpg') {
cb(null, true);
} else {
cb(new Error('Unsupported files type'), false);
}
};
const upload = multer({
storage: storage,
fileFilter: fileFilter
}).array('scan_folder');
const upload_profile_img = multer({
storage: storage,
limits: {
fileSize: 1024 * 1024 * 20
},
fileFilter: fileFilter
}).single('picture');
const path = require('path');
const { log } = require("console");
const ROOT_DIR = path.resolve(__dirname);
app.set('view engine', 'ejs');
app.set('views', path.join(ROOT_DIR, 'views'));
app.use(express.urlencoded({ extended: true }));
app.use(session({
secret: 'absolete',
resave: false,
saveUninitialized: false
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
function allowOnly(role) {
return function (req, res, next) {
if (req.isAuthenticated() && req.user.type === role) {
return next();
}
if (req.user.type === 'admin') {
return res.redirect('/admin');
} else if (req.user.type === 'doctor') {
return res.redirect('/doctor');
}
else if (req.user.type === 'patient') {
return res.redirect('/patient');
}
else if (req.user.type === 'radiologist') {
return res.redirect('/radiologist');
}
else {
return res.redirect('/');
}
}
}
function checkAuthenticated(req, res, next) {
if (req.isAuthenticated()) {
return next();
}
res.redirect('/');
}
function checkNotAuthenticated(req, res, next) {
if (req.isAuthenticated()) {
if (req.user.type === 'admin') {
return res.redirect('/admin');
} else if (req.user.type === 'doctor') {
return res.redirect('/doctor');
}
else if (req.user.type === 'patient') {
return res.redirect('/patient');
}
else if (req.user.type === 'radiologist') {
return res.redirect('/radiologist');
}
else {
return res.redirect('/');
}
}
next();
}
// routes
// visitors page route
app.get('/', (req, res) => {
res.render("visitors.ejs")
});
// sign in route
app.get('/login', checkNotAuthenticated, (req, res) => {
res.render("login.ejs")
});
// sign up route
app.get('/signup', (req, res) => {
res.render("signup.ejs")
});
// logout route
app.get('/logout', (req, res, next) => {
req.logout((err) => {
if (err) {
return next(err);
}
res.redirect('/login'); // Redirect to login page after logout
});
});
// patient window route
let msg_p = '';
let count_p = 0;
app.get('/patient', checkAuthenticated, allowOnly('patient'), async (req, res) => {
if (count_p == 1) {
msg_p = '';
count_p--;
}
if (msg_p != '') {
count_p++;
}
const patientScans = req.session.patient || [];
let scans_type = await pool.query(
'SELECT scan_type FROM take_appointment WHERE patient_id = $1 ',
[req.user.id]
);
let scans_date = await pool.query(
'SELECT scan_date FROM take_appointment WHERE patient_id = $1 ',
[req.user.id]
);
let scans_id = await pool.query(
'SELECT scan_id FROM take_appointment WHERE patient_id = $1 ',
[req.user.id]
);
scans_type = scans_type.rows;
scans_date = scans_date.rows;
scans_id = scans_id.rows;
console.log(scans_type);
console.log(scans_date);
console.log(scans_id);
let num_of_appointments = scans_id.length;
for (let i = num_of_appointments; i > 0; i--) {
const now = new Date();
if (now > scans_date[i - 1].scan_date) {
pool.query(
'INSERT INTO reports (report_no) ' +
'SELECT $1 WHERE NOT EXISTS (SELECT 1 FROM reports WHERE report_no = $1)',
[scans_id[i - 1].scan_id]);
}
}
const capitalize = (str) => str.charAt(0).toUpperCase() + str.slice(1).toLowerCase();
const fname = capitalize(req.user.fname);
const lname = capitalize(req.user.lname);
res.render("patient.ejs", {
type: req.user.type,
email: req.user.email,
fname: fname,
lname: lname,
address: req.user.address,
age: req.user.age,
sex: req.user.sex,
phone_no: req.user.phone_no,
password: req.user.password,
picture: req.user.picture,
scans_type,
scans_date,
scans_id,
//reports_no,
scans: patientScans,
msg_p
})
});
app.post("/take_appointment", async (req, res) => {
const patientId = req.user.id; // Assuming `req.user.id` contains the patient's ID
const { scanType, date, time } = req.body;
console.log(scanType, date, time);
let errors = [];
// Validate the input
if (!scanType || !date || !time) {
msg_p = 'error bro';
}
const scanDateTime = new Date(`${date}T${time}:00`);
// Check if the chosen date and time are in the past
const now = new Date();
if (scanDateTime < now) {
msg_p = 'This date has passed. Please pick a valid date.';
}
if (errors.length > 0) {
msg_p = 'This slot has already been reserved';
//req.flash('errors', errors);
// return res.render("patient.ejs", { errors });
return res.redirect('back')
}
try {
// Combine date and time into a single timestamp string
const scanDate = `${date} ${time}:00`;
// Check if the scan type, date, and time are already reserved
const result = await pool.query(
`SELECT * FROM take_appointment WHERE scan_type = $1 AND scan_date = $2`,
[scanType, scanDate]
);
if (result.rows.length > 0) {
msg_p = 'This slot has already been reserved';
// return res.render("patient.ejs", { errors });
//req.flash('errors', errors);
return res.redirect('back')
}
// Find an available radiologist
const radiologistResult = await pool.query(
`SELECT r.radiologist_id
FROM radiologist r
JOIN users u ON r.radiologist_id = u.id
WHERE $1::time >= r.start_shift AND $1::time < r.end_shift
AND NOT EXISTS (
SELECT * FROM take_appointment ta
WHERE ta.radiologist_id = r.radiologist_id AND ta.scan_date = $2
)
LIMIT 1`,
[time, scanDate]
);
if (radiologistResult.rows.length === 0) {
msg_p = 'There will be no available radiologists at this date. Please choose another time.';
// return res.render("patient.ejs", { errors });
//req.flash('errors', errors);
return res.redirect('back')
}
const radiologistId = radiologistResult.rows[0].radiologist_id;
// Insert the new reservation
await pool.query(
`INSERT INTO take_appointment (patient_id, radiologist_id, scan_type, scan_date) VALUES ($1, $2, $3, $4)`,
[patientId, radiologistId, scanType, scanDate]
);
req.flash("success_msg", "Your reservation was successful");
res.redirect("/patient");
} catch (err) {
console.error(err);
errors.push({ message: "Server error" });
// res.render("patient.ejs", { errors });
req.flash('errors', errors);
return res.redirect('back')
}
});
app.post('/delete_appointment', async (req, res) => {
const { scanId } = req.body;
try {
await pool.query(
'DELETE FROM take_appointment WHERE scan_id = $1 AND patient_id = $2',
[scanId, req.user.id]
);
return res.redirect('back')
//res.status(200).send({ message: 'Appointment deleted successfully' });
} catch (err) {
console.error(err);
//res.status(500).send({ message: 'Failed to delete appointment' });
return res.redirect('back')
}
});
// radiologist window route
let msg = '';
let count = 0;
app.get('/radiologist', checkAuthenticated, allowOnly('radiologist'), async (req, res) => {
if (count == 1) {
msg = '';
count--;
}
if (msg != '') {
count++;
}
let salary = await pool.query(
'SELECT salary FROM radiologist WHERE radiologist_id = $1',
[req.user.id]
);
let start_shift = await pool.query(
'SELECT start_shift FROM radiologist WHERE radiologist_id = $1',
[req.user.id]
);
let end_shift = await pool.query(
'SELECT end_shift FROM radiologist WHERE radiologist_id = $1',
[req.user.id]
);
salary = salary.rows[0].salary
start_shift = start_shift.rows[0].start_shift
end_shift = end_shift.rows[0].end_shift
let patients_id = await pool.query(
'SELECT patient_id FROM take_appointment WHERE radiologist_id = $1',
[req.user.id]
);
let scans_type = await pool.query(
'SELECT scan_type FROM take_appointment WHERE radiologist_id = $1 ',
[req.user.id]
);
let scans_date = await pool.query(
'SELECT scan_date FROM take_appointment WHERE radiologist_id = $1 ',
[req.user.id]
);
let scans_id = await pool.query(
'SELECT scan_id FROM take_appointment WHERE radiologist_id = $1 ',
[req.user.id]
);
patients_id = patients_id.rows;
scans_type = scans_type.rows;
scans_date = scans_date.rows;
scans_id = scans_id.rows;
let num_of_appointments = patients_id.length;
for (let i = num_of_appointments; i > 0; i--) {
const now = new Date();
if (now > scans_date[i - 1].scan_date) {
pool.query(
'INSERT INTO scans (scan_id, radiologist_id) ' +
'SELECT $1, $2 WHERE NOT EXISTS (SELECT 1 FROM scans WHERE scan_id = $1)',
[scans_id[i - 1].scan_id, req.user.id]);
}
}
let scans_no = await pool.query(
'SELECT scan_id FROM scans WHERE radiologist_id = $1 AND dr_id IS NULL',
[req.user.id]
);
scans_no = scans_no.rows;
// console.log(scans_no);
let scan_pics = await pool.query('SELECT scan_pics FROM scans WHERE radiologist_id = $1 AND dr_id IS NULL', [req.user.id]);
scan_pics = scan_pics.rows;
// console.log(scan_pics.rows);
const capitalize = (str) => str.charAt(0).toUpperCase() + str.slice(1).toLowerCase();
const fname = capitalize(req.user.fname);
const lname = capitalize(req.user.lname);
res.render("radiologist.ejs", {
type: req.user.type,
email: req.user.email,
fname: fname,
lname: lname,
address: req.user.address,
age: req.user.age,
sex: req.user.sex,
phone_no: req.user.phone_no,
salary,
start_shift,
end_shift,
password: req.user.password,
picture: req.user.picture,
patients_id,
scans_type,
scans_date,
scans_no,
scan_pics,
msg
})
});
// admin home window route
// engineers_admin window route
app.get('/engineers_admin', checkAuthenticated, allowOnly('admin'), (req, res) => {
res.render("engineers_admin.ejs")
});
app.get('/reports_dr_admin', async (req, res) => {
try {
const scanResult = await pool.query(`
SELECT
scans.scan_id,
scans.scan_folder,
scans.scan_pics,
reports.case_description
FROM
scans
JOIN
reports
ON
scans.scan_id = reports.scan_id
JOIN
doctor
ON
doctor.doctor_id = scans.dr_id
`);
const scans = scanResult.rows
if (scans === 0) {
return res.status(404).send("Scan not found");
}
res.render("reports_dr_admin.ejs", { scans });
} catch (err) {
console.error("Error executing query:", err);
res.status(500).send("Internal Server Error");
}
});
// radiologists_admin window route
app.get('/radiologists_admin', checkAuthenticated, allowOnly('admin'), async (req, res) => {
try {
const radiologistsResult = await pool.query(`
SELECT
r.*,
u.fname,
u.lname,
u.email,
u.address,
u.phone_no,
u.age,
u.sex,
u.type,
u.password,
u.picture,
s.scan_id,
s.scan_pics
FROM
radiologist r
JOIN
users u ON r.radiologist_id = u.id
LEFT JOIN
scans s ON r.radiologist_id = s.radiologist_id
`);
const statsResult = await pool.query(`
SELECT
(SELECT COUNT(*) FROM users JOIN radiologist ON users.id = radiologist.radiologist_id) AS total_doctors,
(SELECT COUNT(*) FROM users JOIN radiologist ON users.id = radiologist.radiologist_id WHERE users.sex = 'female') AS total_women,
(SELECT COUNT(*) FROM users JOIN radiologist ON users.id = radiologist.radiologist_id WHERE users.sex = 'male') AS total_men
`);
// Extract data from result
const { total_doctors, total_women, total_men } = statsResult.rows[0];
// Calculate percentages
const women_percentage = (total_women / total_doctors) * 100;
const men_percentage = (total_men / total_doctors) * 100;
// Group scans by radiologist
const radiologists = radiologistsResult.rows.reduce((acc, row) => {
const {
radiologist_id,
fname,
lname,
email,
address,
phone_no,
age,
sex,
type,
password,
picture,
salary,
start_shift,
end_shift,
scan_id,
scan_pics
} = row;
// Check if radiologist already exists in the accumulator
let radiologist = acc.find(r => r.radiologist_id === radiologist_id);
if (!radiologist) {
radiologist = {
radiologist_id,
fname,
lname,
email,
address,
phone_no,
age,
sex,
type,
password,
picture,
salary,
start_shift,
end_shift,
scans: []
};
acc.push(radiologist);
}
// Push scans to the radiologist's scans array
if (scan_id) {
radiologist.scans.push({
scan_id,
scan_pics
});
}
return acc;
}, []);
// Render the view with radiologists data
res.render('radiologists_admin.ejs', { radiologists, women_percentage });
} catch (err) {
console.error('Error retrieving radiologist data:', err.message, err.stack);
res.send('Error retrieving radiologist data');
}
});
app.get('/scan_img', async (req, res) => {
const { scan_id } = req.query;
try {
const result = await pool.query(
'SELECT scan_pics FROM scans WHERE scan_id = $1',
[scan_id]
);
if (result.rowCount > 0) {
const scanPics = result.rows[0].scan_pics;
res.render('scan_img', { scanPics });
} else {
res.status(404).send('Scan not found');
}
} catch (err) {
console.error('Error fetching scan images:', err);
res.status(500).send('Internal Server Error');
}
});
// add_radiologist window route
app.get('/add_radiologist', checkAuthenticated, allowOnly('admin'), (req, res) => {
res.render("add_radiologist.ejs")
});
app.post('/add_radiologist', async (req, res) => {
upload_profile_img(req, res, async (err) => {
let picture = req.file;
console.log(picture)
picture = picture.path
console.log(picture)
if (picture != null) {
picture = picture.replace(/\\/g, '/');
picture = picture.replace('public', '');
}
console.log(picture)
let { name, address, email, start_shift, end_shift, sex, age, salary, password, phone_no } = req.body;
let type = 'radiologist'
const parts = name.trim().split(' ');
const fname = parts.shift() || ''; // First element as first name, default to empty string if undefined
const lname = parts.pop() || ''; // Last element as last name, default to empty string if undefined
console.log({
fname,
email,
type,
start_shift,
end_shift,
salary
}); // Set a default password or generate one
let hashedPassword = await bcrypt.hash(password, 10);
pool.query(
`INSERT INTO users ( email, password, type, fname,lname,address, age, sex,phone_no, picture)
VALUES ($1, $2, $3, $4, $5, $6, $7,$8,$9, $10)
RETURNING id`,
[email, hashedPassword, type, fname, lname, address, age, sex, phone_no, picture],
(err, results) => {
if (err) {
throw err;
}
const userId = results.rows[0].id;
pool.query(
`INSERT INTO radiologist (radiologist_id, salary, start_shift, end_shift)
VALUES ($1, $2, $3, $4)`,
[userId, salary, start_shift, end_shift],
(err) => {
if (err) {
throw err;
}
req.flash('success_msg', 'Doctor added successfully.');
res.redirect('/radiologists_admin');
}
);
}
)
});
});
// add_doctor window route
app.get('/add_doctor', checkAuthenticated, allowOnly('admin'), (req, res) => {
res.render("add_doctor.ejs")
});
app.get('/doctors_admin', checkAuthenticated, allowOnly('admin'), async (req, res) => {
try {
// Query to get doctors' information
const doctorsResult = await pool.query(`
SELECT
doctor.*,
users.fname,
users.lname,
users.email,
users.address,
users.phone_no,
users.age,
users.sex,
users.type,
users.picture,
scans.scan_id,
scans.scan_folder,
users.picture,
scans.scan_pics
FROM
doctor
JOIN
users
ON
doctor.doctor_id = users.id
LEFT JOIN scans ON scans.dr_id = doctor.doctor_id
`);
const doctors = doctorsResult.rows.reduce((acc, row) => {
const {
doctor_id,
fname,
lname,
email,
address,
phone_no,
salary,
ass_name,
dr_room,
special,
age,
sex,
type,
picture,
scan_id,
start_time,
end_time,
scan_pics
} = row;
// Check if radiologist already exists in the accumulator
let doctor = acc.find(doctor => doctor.doctor_id === doctor_id);
if (!doctor) {
doctor = {
doctor_id,
fname,
lname,
email,
address,
phone_no,
age,
salary,
ass_name,
dr_room,
special,
start_time,
end_time,
scan_id,
sex,
type,
picture,
scans: []
};
acc.push(doctor);
}
// Push scans to the radiologist's scans array
if (scan_id) {
doctor.scans.push({
scan_id,
scan_pics
});
}
return acc;
}, []);
// Query to get the statistics
const statsResult = await pool.query(`
SELECT
(SELECT COUNT(*) FROM users JOIN doctor ON users.id = doctor.doctor_id) AS total_doctors,
(SELECT COUNT(*) FROM users JOIN doctor ON users.id = doctor.doctor_id WHERE users.sex = 'female') AS total_women,
(SELECT COUNT(*) FROM users JOIN doctor ON users.id = doctor.doctor_id WHERE users.sex = 'male') AS total_men
`);
// Extract data from results
const { total_doctors, total_women, total_men } = statsResult.rows[0];
// Calculate percentages
const women_percentage = (total_women / total_doctors) * 100;
const men_percentage = (total_men / total_doctors) * 100;
// Render the template with the required data
res.render("doctors_admin.ejs", { doctors, women_percentage, men_percentage });
} catch (err) {
console.error("Error executing query:", err);
res.status(500).send("Internal Server Error");
}
});
app.post('/add_doctor', async (req, res) => {
upload_profile_img(req, res, async (err) => {
let picture = req.file;
console.log(picture)
picture = picture.path
console.log(picture)
if (picture != null) {
picture = picture.replace(/\\/g, '/');
picture = picture.replace('public', '');
}
console.log(picture)
let { name, address, email, start_time, end_time, sex, age, salary, password, phone_no, ass_name, special, dr_room } = req.body;
let type = 'doctor'
const parts = name.trim().split(' ');
const fname = parts.shift() || ''; // First element as first name, default to empty string if undefined
const lname = parts.pop() || ''; // Last element as last name, default to empty string if undefined
console.log({
fname,
email,
type,
start_time,
end_time,
salary
}); // Set a default password or generate one
let hashedPassword = await bcrypt.hash(password, 10);
pool.query(
`INSERT INTO users ( email, password, type, fname,lname,address, age, sex,phone_no, picture)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
RETURNING id`,
[email, hashedPassword, type, fname, lname, address, age, sex, phone_no, picture],
(err, results) => {
if (err) {
throw err;
}
const userId = results.rows[0].id;
pool.query(
`INSERT INTO doctor (doctor_id, start_time, end_time, salary, ass_name, dr_room, special)
VALUES ($1, $2, $3, $4,$5,$6,$7)`,
[userId, start_time, end_time, salary, ass_name, dr_room, special],
(err) => {
if (err) {
throw err;
}
req.flash('success_msg', 'Doctor added successfully.');
res.redirect('/doctors_admin');
}
);
}
);
})
});
app.get('/reports_dr_admin', async (req, res) => {
try {
const scanResult = await pool.query(`
SELECT
scans.scan_id,
scans.scan_folder,
scans.scan_pics,
reports.case_description
FROM
scans
JOIN
reports
ON
scans.scan_id = reports.scan_id
JOIN
doctor
ON
doctor.doctor_id = scans.dr_id
`);
const scans = scanResult.rows
if (scans === 0) {
return res.status(404).send("Scan not found");
}
res.render("reports_dr_admin.ejs", { scans });
} catch (err) {
console.error("Error executing query:", err);
res.status(500).send("Internal Server Error");
}
});
app.get('/admin', checkAuthenticated, allowOnly('admin'), async (req, res) => {
try {
// Query to get doctors' information
const doctorsResult = await pool.query(`
SELECT
doctor.*,
users.fname,
users.lname,
users.email,
users.address,
users.phone_no,
users.age,
users.sex,
users.type
FROM
doctor
JOIN
users
ON
doctor.doctor_id = users.id
`);
const statsResult = await pool.query(`
SELECT
(SELECT COUNT(*) FROM scans) AS scansno,
(SELECT COUNT(*) FROM users JOIN doctor ON users.id = doctor.doctor_id) AS total_doctors,
(SELECT COUNT(*) FROM users JOIN doctor ON users.id = doctor.doctor_id WHERE doctor.special = 'orthopedist') AS orthopedist_count,
(SELECT COUNT(*) FROM users JOIN doctor ON users.id = doctor.doctor_id WHERE doctor.special = 'oncologist') AS oncologist_count,
(SELECT COUNT(*) FROM users JOIN doctor ON users.id = doctor.doctor_id WHERE doctor.special = 'neurologist') AS neurologist_count,
(SELECT COUNT(*) FROM users JOIN radiologist ON users.id=radiologist.radiologist_id) AS radiologistsno
`);
const { scansno, total_doctors, orthopedist_count, oncologist_count, neurologist_count, radiologistsno } = statsResult.rows[0];
const doctors = doctorsResult.rows;
// Calculate percentages
const orthopedist_percentage = (orthopedist_count / total_doctors) * 100;
const oncologist_percentage = (oncologist_count / total_doctors) * 100;
const neurologist_percentage = (neurologist_count / total_doctors) * 100;
// Render the template with the required data
res.render("admin.ejs", {
email: req.user.email,
fname: req.user.fname,
lname: req.user.lname,
address: req.user.address,
age: req.user.age,
sex: req.user.sex,
phone_no: req.user.phone_no,
password: req.user.password,
picture: req.user.picture,
scansno, radiologistsno, doctors, total_doctors, orthopedist_percentage, oncologist_percentage, neurologist_percentage
});
} catch (err) {
console.error("Error executing query:", err);
res.status(500).send("Internal Server Error");
}
});
// form window route
app.get('/forms', checkAuthenticated, allowOnly('admin'), async (req, res) => {
try {
const result = await pool.query('SELECT * FROM forms');
const forms = result.rows;
res.render('forms', { forms });
} catch (err) {
throw (err)
}
});
app.post('/forms', async (req, res) => {
const { formId, remail, write } = req.body;
try {
const result = await pool.query(
'UPDATE forms SET reply = $1 WHERE form_id = $2 AND user_email = $3 RETURNING *',
[write, formId, remail]
);
if (result.rowCount > 0) {
req.flash('success_msg', 'Reply added successfully');
} else {
req.flash('error_msg', 'No form found for the given email and form ID');
}
res.redirect('/forms');
} catch (err) {
console.error('Error adding reply:', err);
req.flash('error_msg', 'Failed to add reply. Please try again later.');
res.redirect('/forms');
}
});
app.get('/replies', checkAuthenticated, async (req, res) => {
try {
const result = await pool.query('SELECT * FROM forms where user_email=$1 and reply IS NOT NULL', [req.user.email]);
const replies = result.rows;
res.render('replies', { replies });
} catch (err) {
throw (err)
}
});
app.get('/patient_report', checkAuthenticated, allowOnly('patient'), (req, res) => {
const { scan_id, pic_index } = req.query;
pool.query(
'SELECT scans.scan_pics, reports.case_description FROM scans JOIN reports ON scans.scan_id = reports.scan_id WHERE scans.scan_id = $1',
[scan_id],
(err, result) => {
if (result.rows.length > 0) {
const scanPics = result.rows[0].scan_pics;
const caseDescriptions = result.rows[0].case_description;
const selectedPic = scanPics[pic_index];
const selectedReport = caseDescriptions[pic_index];
res.render('patient_report', { selectedPic, selectedReport });
} else {
throw (err)
}
})
});
app.get('/doctor_scan', checkAuthenticated, async (req, res) => {
const { scan_id, pic_index } = req.query;
const result = await pool.query(
'SELECT scan_pics FROM scans WHERE scan_id = $1',
[scan_id]);
if (result.rows.length > 0) {
const scanPics = result.rows[0].scan_pics;
const selectedPic = scanPics[pic_index];
console.log(selectedPic)
res.render('doctor_scan', { selectedPic });
} else {
res.status(404).send('Scan not found');
}
});
app.get('/doctor', checkAuthenticated, allowOnly('doctor'), (req, res) => {
const user = req.session.user;
const scans = req.session.doctorScans;
const scansNo = req.session.scansNo;
const capitalize = (str) => str.charAt(0).toUpperCase() + str.slice(1).toLowerCase();
const fname = capitalize(req.user.fname);
res.render("doctor.ejs", {
password: user.password,
email: user.email,
fname: fname,
address: user.address,
picture: user.picture,
salary: user.salary,
age: user.age,
ass_name: user.ass_name,
phone_no: user.phone_no,
dr_room: user.dr_room,
special: user.special,
start_time: user.start_time,
end_time: user.end_time,
scans: scans,
scansNo: scansNo
})
});
app.post("/contact_form", async (req, res) => {
const user = req.session.user;
const { why, body } = req.body;
// console.log(user_email)
console.log(why)
console.log(body)
pool.query(
'insert into forms (user_email, about, body) values($1,$2,$3)',
[user.email, why, body],
(err, contact_form_res) => {
if (err) {
throw err;
}
else {