-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.js
1641 lines (1280 loc) · 60.1 KB
/
server.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
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
//importring evrironment variable
if (process.env.NODE_ENV !== 'production') {
require('dotenv').config()
}
//importing
const express = require("express")
const app = express()
const nodemailer = require("nodemailer")
app.use(express.urlencoded({ extended: false }))
//initializing db
const db = require('./database')
const session = require('express-session')
// app.set('trustproxy', true)
// Static Files
app.use(express.static('public'));
app.use('/css', express.static(__dirname + 'public/css'))
app.use('/img', express.static(__dirname + 'public/img'))
//setting up ejs
app.set('views', './views');
app.set('view engine', 'ejs')
// const session = require('./routes/login')
app.use(session({
secret: '123',
cookie: { maxAge: 30000000000000 },
resave: false,
saveUninitialized: false
}))
// middleware
// app.use(express.urlencoded({ extended: true }));
//function to check if user is not authenticated
function checkAuthenticated(req, res, next) {
if (req.session.authenticated) {
return next()
}
res.status(200).redirect('/login')
}
//function to check if user is not authenticated
function checkNotAuthenticated(req, res, next) {
if (req.session.authenticated) {
return res.status(200).redirect('/profile')
}
next()
}
// check if admin
function checkAdmin(req, res, next) {
if (req.session.authenticated && (req.session.user.permissionLevel.localeCompare('admin') === 0)) {
return next()
}
res.redirect('/')
}
// check if current user is a doctor
function checkDoctor(req, res, next) {
if (!req.session.authenticated) {
// redirect to login if user is not logged in
return res.status(403).redirect('/login')
}
// check if they are a doctor
else if (req.session.user.permissionLevel.localeCompare('doctor') === 0)
return next()
// 403 forbidden if the user is not a doctor
return res.status(403).redirect('/')
}
// check if current user is a doctor
function checkHealthOfficial(req, res, next) {
if (!req.session.authenticated) {
// redirect to login if user is not logged in
return res.status(403).redirect('/login')
}
// check if they are a doctor
else if (req.session.user.permissionLevel.localeCompare('health official') === 0)
return next()
// 403 forbidden if the user is not a doctor
return res.status(403).redirect('/')
}
//path for home
app.get('/', (req, res) => {
res.render('index.ejs', { authenticated: req.session.authenticated })
})
//logout
app.get('/logout', checkAuthenticated, (req, res) => {
req.session.destroy()
// req.logout()
res.redirect('/')
})
// importing routers
// signup
const signupRouter = require('./routes/signup')
app.use('/signup', checkNotAuthenticated, signupRouter)
// profile
const profileRouter = require('./routes/profile')
app.use('/profile', checkAuthenticated, profileRouter)
// login
const loginRouter = require('./routes/login')
app.use('/login', checkNotAuthenticated, loginRouter)
//messaging
const messagingRouter = require('./routes/messaging')
app.use('/messaging', checkAuthenticated, messagingRouter)
//sesion middleware functions
// check if authenticated
//added newly from front-end- probably need fixes on the backend
app.get('/approveRoles', checkAdmin, (req, res) => {
var doctorList = []
var nurseList = []
var healthOffList = []
var immigrationOffList = []
//Queries for the list of workers that have yet to be approved by the admin
db.connect((err) => {
if (err) console.log(err)
console.log("Connected!")
//query that selects info from worker and user based of a join on user id
var sql = `
SELECT Worker.role, User.first_name, User.last_name, Worker.user_uuid, User.email
FROM Worker, User
WHERE Worker.user_uuid = User.uuid
AND verified = 0`;
db.query(sql, function(err, result) {
if (err) console.log(err)
//iterate through worker list length and sort workers by their type (nurse, doctor etc.)
for (let i = 0; i < result.length; i++) {
role = result[i].role
//Sorts users based on role
switch (role) {
case "doctor":
doctorList.push(result[i])
break;
case "nurse":
nurseList.push(result[i])
break;
case "health official":
healthOffList.push(result[i])
break;
case "immigration officer":
immigrationOffList.push(result[i])
break;
default:
throw "Error: No role found when retrieving worker!"
}
}
//render approve roles page passing to it the list of roles
res.render('approve_roles.ejs', { doctors: doctorList, nurses: nurseList, healthOfficials: healthOffList, immigrationOfficers: immigrationOffList })
})
})
})
//Approves a worker and changes their verification status from 0 to 1 in the database
app.post('/verifyWorker', checkAdmin, function(req, res) {
var user_uuid = req.body.uuid
db.connect(function(err) {
if (err) throw err;
//update worker verified status in worked database, finds worker by user id
var sql = "UPDATE Worker SET verified = 1 WHERE ( user_uuid = '" + user_uuid + "' );";
db.query(sql, function(err, result) {
if (err) throw err;
console.log(result);
});
});
res.redirect('./approveRoles/')
})
//Denies a worker and removes them from the Worker table in the database, thus removing their application
app.post('/denyWorker', checkAdmin, function(req, res) {
var user_uuid = req.body.uuid
db.connect(function(err) {
if (err) throw err;
//delete worker from database if role is denied
var sql = "DELETE FROM Worker WHERE ( user_uuid = '" + user_uuid + "' );";
db.query(sql, function(err, result) {
if (err) throw err;
console.log(result);
});
});
res.redirect('./approveRoles/')
})
//app get requests for doctor and admin pages
app.get('/doctorMonitor', checkAdmin, (req, res) => {
const sql = `
SELECT *
FROM User
WHERE (permission_level = 'patient' OR (permission_level='doctor' AND User.uuid IN (SELECT Worker.user_uuid
FROM Worker
WHERE Worker.verified = 1)))
AND User.uuid NOT IN (SELECT Doctor.patient_uuid
FROM Doctor)`
db.query(sql, (err, result) => {
if (err) throw new Error()
let patients = []
let doctors = []
let doctorCount = 0
let patientCount = 0
for (let i = 0; i < result.length; i++) {
if (result[i].permission_level == 'patient') {
patients[patientCount] = result[i]
patientCount++
} else {
doctors[doctorCount] = result[i]
doctorCount++
}
}
const countSql = `SELECT Doctor.user_uuid, COUNT(*) As count FROM Doctor GROUP BY Doctor.user_uuid`
db.query(countSql, (err, result1) => {
if (err) console.log(err)
// console.log(result1, 'result1')
for (let i = 0; i < doctors.length; i++) {
doctors[i].count = 0
for (let j = 0; j < result1.length; j++) {
if (doctors[i].uuid === result1[j].user_uuid) {
doctors[i].count = result1[j].count
continue
}
// console.log(doctors[i])
}
}
res.render('doctor_monitor.ejs', { doctors: doctors })
})
})
})
app.get('/assignedPatients', checkAdmin, (req, res) => {
res.render('assigned_patients.ejs')
})
app.get('/adminIndex', checkAdmin, (req, res) => {
res.render('admin_index.ejs')
})
app.get('/patientsAssign', checkAdmin, (req, res) => {
try {
// select all patients who don't have a doctor
// and all doctors
const sql = `
SELECT *
FROM User
WHERE (permission_level = 'patient' OR (permission_level='doctor' AND User.uuid IN (SELECT Worker.user_uuid
FROM Worker
WHERE Worker.verified = 1)))
AND User.uuid NOT IN (SELECT Doctor.patient_uuid
FROM Doctor)`
db.query(sql, (err, result) => {
if (err) throw new Error()
try {
let patients = []
let doctors = []
let doctorCount = 0
let patientCount = 0
for (let i = 0; i < result.length; i++) {
if (result[i].permission_level == 'patient') {
patients[patientCount] = result[i]
patientCount++
} else {
doctors[doctorCount] = result[i]
doctorCount++
}
}
const countSql = `SELECT Doctor.user_uuid, COUNT(*) As count FROM Doctor GROUP BY Doctor.user_uuid`
db.query(countSql, (err, result1) => {
if (err) console.log(err)
// console.log(result1, 'result1')
for (let i = 0; i < doctors.length; i++) {
doctors[i].count = 0
for (let j = 0; j < result1.length; j++) {
if (doctors[i].uuid === result1[j].user_uuid) {
doctors[i].count = result1[j].count
continue
}
// console.log(doctors[i])
}
}
result1.forEach(element => {
console.log(element)
})
res.status(200).render("patients_assign.ejs", { patients: patients, doctors: doctors })
})
} catch {
res.status(403).render("patients_assign.ejs", { error: err })
}
})
} catch (err) {
res.status(403).render("patients_assign.ejs", { error: err })
}
})
app.post('/patientsAssign', checkAdmin, (req, res) => {
const sql = `INSERT INTO Doctor (user_uuid, patient_uuid)
VALUES ('${req.body.doctor}', '${req.body.patient_uuid}')`
db.query(sql, (err, result) => {
if (err) console.log(err)
else
console.log(result[0])
})
res.status(200).redirect('/patientsAssign')
})
app.get('/selectDoctor', checkAdmin, (req, res) => {
res.render('select_doctor.ejs')
})
app.get('/doctorsPatientList', checkDoctor, (req, res) => {
const doctor_uuid = req.session.user.uuid
var positivepatientList = []
var negativepatientList = []
var allpatients = []
//Queries for the list of workers that have yet to be approved by the admin
db.query(`SELECT * FROM Patient`, (err, result) => {
console.log(result[0])
})
var sql = `
Select u1.first_name, u1.last_name, u1.email, Patient.covid, Patient.symptoms, u1.uuid, Patient.criticality
FROM User u1, Patient
WHERE Patient.user_uuid in (SELECT Patient.user_uuid from Doctor, Patient
WHERE Doctor.user_uuid = '${doctor_uuid}'
AND Doctor.patient_uuid = Patient.user_uuid)
AND Patient.user_uuid = u1.uuid order by Patient.criticality asc;`
db.query(sql, (err, result) => {
if (err) console.log(err)
for (let i = 0; i < result.length; i++) {
// console.log(result[i])
covid = result[i].covid
allpatients.push(result[i])
//Sorts users based on role
switch (covid) {
case 1:
positivepatientList.push(result[i])
break;
case 0:
negativepatientList.push(result[i])
break;
default:
throw "Error: No patient found when retrieving assigned patients for this doctor!"
}
}
res.render('doctors_patient_list.ejs', { allpatients: allpatients })
})
})
app.get('/doctorsPatientProfile/:patient_id', checkDoctor, function(req, res) {
// patient uuid
const patient_uuid = req.params.patient_id
// initialize patient list
var patientinfo = []
//Query for the list of patients of the logged in doctor
var sql = `
Select u1.uuid ,u1.first_name, u1.last_name, u1.email, Patient.covid, Patient.symptoms,Patient.diary, Patient.criticality, Address.street_number,Address.street_name , Address.apartment_number, Address.city, Address.province, Address.country, Address.zipcode
FROM User u1, Patient,Address
WHERE Patient.user_uuid = '${patient_uuid}'
AND Patient.user_uuid = u1.uuid AND Address.uuid = u1.uuid;`
// query the database with above query
db.query(sql, function(err, result) {
// if error, print it
if (err) console.log(err)
// create list of patients returned from the query
for (let i = 0; i < result.length; i++)
patientinfo.push(result[i])
res.render('doctors_patient_profile.ejs', { patientinfo: patientinfo[0] })
})
})
app.post('/doctorsPatientProfile/:patient_id', checkDoctor, function(req, res) {
// patient uuid
const patient_uuid = req.params.patient_id
// initialize patient list
var patientinfo = []
const sqlSeverity = `UPDATE Patient SET criticality=${req.body.severity} WHERE Patient.user_uuid='${patient_uuid}'`
// result/error handling
db.query(sqlSeverity, (err, result) => {
if (err) console.log(err)
else
console.log("Number of records inserted: " + result)
})
//Query for the list of patients of the logged in doctor
var sql = `
Select u1.uuid ,u1.first_name, u1.last_name, u1.email, Patient.covid, Patient.symptoms,Patient.diary, Patient.criticality, Address.street_number,Address.street_name , Address.apartment_number, Address.city, Address.province, Address.country, Address.zipcode
FROM User u1, Patient,Address
WHERE Patient.user_uuid = '${patient_uuid}'
AND Patient.user_uuid = u1.uuid AND Address.uuid = u1.uuid;`
// query the database with above query
db.query(sql, function(err, result) {
// if error, print it
if (err) console.log(err)
// create list of patients returned from the query
for (let i = 0; i < result.length; i++)
patientinfo.push(result[i])
res.render('doctors_patient_profile.ejs', { patientinfo: patientinfo[0] })
})
})
// action="/signup" method="POST"
//Approves a worker and changes their verification status from 0 to 1 in the database
app.post('/changeCovidStatus', checkDoctor, function(req, res) {
var user_uuid = req.body.uuid
var covid = req.body.covid
// check if status is 1, then change it to 0 and vice versa
if (covid == 1) {
db.connect(function(err) {
if (err) throw err;
var sql = "UPDATE Patient SET covid = " + 0 + " WHERE (user_uuid = '" + user_uuid + "');";
db.query(sql, function(err, result) {
if (err) throw err;
console.log("SET TO 0");
});
});
res.redirect('./doctorsPatientList')
} else {
db.connect(function(err) {
if (err) throw err;
var sql = "UPDATE Patient SET covid = " + 1 + " WHERE (user_uuid = '" + user_uuid + "');";
db.query(sql, function(err, result) {
if (err) throw err;
console.log("SET TO 1");
});
});
res.status(200).redirect('./doctorsPatientList')
}
})
app.get('/doctorMessaging/:patient_uuid', checkDoctor, function(req, res) {
const patient_uuid = req.params.patient_uuid
const doctor_uuid = req.session.user.uuid
var messageList = []
// This query will get the list of messages that the doctor and patient engaged in ordered by time
const sql = `
SELECT * FROM (SELECT message.sender_uuid,message.receiver_uuid,message.message,message.first_name as senderFirstName, message.last_name AS senderLastName, message.date_time,receiver.first_name AS receiverFirstName, receiver.last_name AS receiverLastName
FROM (Select sender_uuid,receiver_uuid,message,date_time,User.first_name,User.last_name
FROM Messages, User
WHERE sender_uuid = '${doctor_uuid}'
AND receiver_uuid = '${patient_uuid}'
AND sender_uuid = User.uuid
ORDER BY date_time DESC) As message,
(SELECT User.first_name,User.last_name,User.uuid
FROM User
WHERE User.uuid = '${patient_uuid}') AS receiver
WHERE message.receiver_uuid = receiver.uuid
UNION
SELECT message.sender_uuid, message.receiver_uuid, message.message, message.first_name as senderFirstName, message.last_name AS senderLastName, message.date_time, receiver.first_name AS receiverFirstName, receiver.last_name AS receiverLastName
FROM (Select sender_uuid, receiver_uuid, message, date_time, User.first_name, User.last_name
FROM Messages, User
WHERE sender_uuid = '${patient_uuid}'
AND receiver_uuid = '${doctor_uuid}'
AND sender_uuid = User.uuid
ORDER BY date_time DESC) AS message,
(SELECT User.first_name, User.last_name, User.uuid
FROM User
WHERE User.uuid = '${doctor_uuid}') AS receiver
WHERE message.receiver_uuid = receiver.uuid ) X
ORDER BY X.date_time ASC`
db.query(sql, function(err, result) {
if (err) console.log(err)
doctorFirstName = ""
doctorLastName = ""
patientFirstName = ""
patientLastName = ""
if (result.length == 0) {
// This query will display only the patient's name when there is no previous conversation with his/her doctor
var sql2 = "SELECT User.first_name,User.last_name FROM User WHERE User.uuid = '" + patient_uuid + "';"
db.query(sql2, function(err, result1) {
if (err) console.log(err)
console.log(result1)
patientFirstName = result1[0].first_name
patientLastName = result1[0].last_name
console.log("I m inside am empty message for doctor")
console.log(patientFirstName)
console.log(patientLastName)
res.render('doctor_messaging.ejs', { doctor_uuid: doctor_uuid, patient_uuid: patient_uuid, patientFirstName: patientFirstName, patientLastName: patientLastName, messageList: messageList })
})
} else { // if doctor is sender:
if (doctor_uuid == result[0].sender_uuid) {
doctorFirstName = result[0].senderFirstName
doctorLastName = result[0].senderLastName
patientFirstName = result[0].receiverFirstName
patientLastName = result[0].receiverLastName
}
// if patient is sender:
else if (patient_uuid == result[0].sender_uuid) {
doctorFirstName = result[0].receiverFirstName
doctorLastName = result[0].receiverLastName
patientFirstName = result[0].senderFirstName
patientLastName = result[0].senderLastName
}
for (let i = 0; i < result.length; i++) // loop to get all the messages and their data.
{ messageList.push(result[i]) }
res.render('doctor_messaging.ejs', { doctor_uuid: doctor_uuid, patient_uuid: patient_uuid, patientFirstName: patientFirstName, patientLastName: patientLastName, messageList: messageList })
}
//res.render('doctor_messaging.ejs', { doctor_uuid: doctor_uuid, patient_uuid: patient_uuid, patientFirstName: patientFirstName, patientLastName: patientLastName, messageList: messageList })
console.log("after sedning message")
})
})
app.post('/doctorMessaging/:patient_uuid', checkDoctor, function(req, res) {
db.connect(function(err) {
if (err) throw err;
patient_uuid = req.params.patient_uuid
doctor_uuid = req.session.user.uuid
message = req.body.doctormessage
console.log(patient_uuid)
let date_ob = new Date();
// current date
// adjust 0 before single digit date
let date = ("0" + date_ob.getDate()).slice(-2);
// current month
let month = ("0" + (date_ob.getMonth() + 1)).slice(-2);
// current year
let year = date_ob.getFullYear();
// current hours
let hours = date_ob.getHours();
// current minutes
let minutes = date_ob.getMinutes();
// current seconds
let seconds = date_ob.getSeconds();
// This query will insert the message that the doctor sent to the Messages table in the database
var sql = "INSERT INTO Messages VALUES ('" + doctor_uuid + "','" + patient_uuid + "','" + message + "','" + year + "-" + month + "-" + date + " " + hours + ":" + minutes + ":" + seconds + "')";
db.query(sql, function(err, result) {
if (err) throw err;
res.status(200).redirect(req.originalUrl)
});
})
})
app.get('/patientMessaging', checkAuthenticated, function(req, res) {
const patient_uuid = req.session.user.uuid
db.connect(function(err) {
// This query will check if the patient is assigned to a doctor. if yes, he/she will be able to message the doctor.
var sql = `SELECT Doctor.user_uuid FROM Doctor WhERE Doctor.patient_uuid = '${patient_uuid}'`
db.query(sql, function(err, result) {
if (err) throw err;
if (result.length == 0) {
res.redirect('/profile')
} else {
const doctor_uuid = result[0].user_uuid
var messageList = []
// This query will get the list of messages that the doctor and patient engaged in ordered by time
var sql = `
SELECT * FROM (SELECT message.sender_uuid,message.receiver_uuid,message.message,message.first_name as senderFirstName, message.last_name AS senderLastName, message.date_time,receiver.first_name AS receiverFirstName, receiver.last_name AS receiverLastName
FROM (Select sender_uuid,receiver_uuid,message,date_time,User.first_name,User.last_name
FROM Messages, User
WHERE sender_uuid = '${patient_uuid}'
AND receiver_uuid = '${doctor_uuid}'
AND sender_uuid = User.uuid
ORDER BY date_time DESC) As message,
(SELECT User.first_name,User.last_name,User.uuid
FROM User
WHERE User.uuid = '${doctor_uuid}') AS receiver
WHERE message.receiver_uuid = receiver.uuid
UNION
SELECT message.sender_uuid, message.receiver_uuid, message.message, message.first_name as senderFirstName, message.last_name AS senderLastName, message.date_time, receiver.first_name AS receiverFirstName, receiver.last_name AS receiverLastName
FROM (Select sender_uuid, receiver_uuid, message, date_time, User.first_name, User.last_name
FROM Messages, User
WHERE sender_uuid = '${doctor_uuid}'
AND receiver_uuid = '${patient_uuid}'
AND sender_uuid = User.uuid
ORDER BY date_time DESC) AS message,
(SELECT User.first_name, User.last_name, User.uuid
FROM User
WHERE User.uuid = '${patient_uuid}') AS receiver
WHERE message.receiver_uuid = receiver.uuid ) X
ORDER BY X.date_time ASC`
db.query(sql, function(err, result) {
if (err) console.log(err)
doctorFirstName = ""
doctorLastName = ""
patientFirstName = ""
patientLastName = ""
if (result.length == 0) {
console.log("I am inside empty message for patient")
console.log(doctor_uuid)
console.log(patient_uuid)
var sql2 = "SELECT User.first_name,User.last_name FROM User WHERE User.uuid = '" + doctor_uuid + "';"
db.query(sql2, function(err, result1) {
if (err) console.log(err)
console.log(result1)
doctorFirstName = result1[0].first_name
doctorLastName = result1[0].last_name
console.log(doctorFirstName)
console.log(doctorLastName)
res.render('patient_messaging.ejs', { doctor_uuid: doctor_uuid, doctorLastName: doctorLastName, patient_uuid: patient_uuid, patientFirstName: patientFirstName, patientLastName: patientLastName, messageList: messageList })
})
} else { // if doctor is the sender of the message
if (doctor_uuid == result[0].sender_uuid) {
doctorFirstName = result[0].senderFirstName
doctorLastName = result[0].senderLastName
patientFirstName = result[0].receiverFirstName
patientLastName = result[0].receiverLastName
}
// if patient is the sender of the message
else if (patient_uuid == result[0].sender_uuid) {
doctorFirstName = result[0].receiverFirstName
doctorLastName = result[0].receiverLastName
patientFirstName = result[0].senderFirstName
patientLastName = result[0].senderLastName
}
for (let i = 0; i < result.length; i++) { messageList.push(result[i]) }
console.log("I am desplaying messaginges")
console.log(messageList)
res.render('patient_messaging.ejs', { doctor_uuid: doctor_uuid, doctorLastName: doctorLastName, patient_uuid: patient_uuid, patientFirstName: patientFirstName, patientLastName: patientLastName, messageList: messageList })
}
})
}
})
})
})
app.post('/patientMessaging', checkAuthenticated, function(req, res) {
patient_uuid = req.session.user.uuid
message = req.body.patientmessage
console.log(patient_uuid)
let date_ob = new Date();
// current date
// adjust 0 before single digit date
let date = ("0" + date_ob.getDate()).slice(-2);
// current month
let month = ("0" + (date_ob.getMonth() + 1)).slice(-2);
// current year
let year = date_ob.getFullYear();
// current hours
let hours = date_ob.getHours();
// current minutes
let minutes = date_ob.getMinutes();
// current seconds
let seconds = date_ob.getSeconds();
db.connect(function(err) {
var sql = `SELECT Doctor.user_uuid FROM Doctor WhERE Doctor.patient_uuid = '${patient_uuid}'` // fetch the doctor's uuid
db.query(sql, function(err, result1) {
if (err) throw err;
const doctor_uuid = result1[0].user_uuid
db.connect(function(err) {
if (err) throw err;
// insert into the message table the message that was sent by the patient to the doctor
var sql = "INSERT INTO Messages VALUES ('" + patient_uuid + "','" + doctor_uuid + "','" + message + "','" + year + "-" + month + "-" + date + " " + hours + ":" + minutes + ":" + seconds + "')";
db.query(sql, function(err, result) {
if (err) throw err;
})
})
res.status(200).redirect(req.originalUrl)
});
})
})
//load index page of doctor
app.get('/doctorIndex', checkDoctor, (req, res) => {
res.render('doctor_index.ejs', { name: req.session.user.name, lastname: req.session.user.lastname })
})
//query symptoms from database
app.get('/symptoms', checkAuthenticated, (req, res) => {
try {
console.log(req.session.user.uuid)
//fetching the info from history ordered by descending time where its the current user uuid
var sql = "SELECT * FROM History WHERE uuid = '" + req.session.user.uuid + "' order by datetime desc;"
var symptoms = [];
db.query(sql, function(err, rows) {
try {
//console.log(rows[0])
if (err) console.log(err);
for (let i = 0; i < rows.length; i++) {
//converting the date time into a different format
rows[i].datetime = rows[i].datetime.toISOString().slice(0, 19).replace('T', ' ')
symptoms.push(rows[i])
// dates.push(rows[i].datetime)
}
//console.log(symptoms);
//rendering the patient symptom page
res.render('patient_symptoms.ejs', { symptoms: symptoms })
} catch (err) {
console.log(err)
}
})
} catch (err) {
console.log('error')
}
})
//post postal symptoms into database from form
app.post('/symptoms', checkAuthenticated, (req, res) => {
try {
let date_ob = new Date();
// current date
// adjust 0 before single digit date
let date = ("0" + date_ob.getDate()).slice(-2);
// current month
let month = ("0" + (date_ob.getMonth() + 1)).slice(-2);
// current year
let year = date_ob.getFullYear();
// current hours
let hours = date_ob.getHours();
// current minutes
let minutes = date_ob.getMinutes();
// current seconds
let seconds = date_ob.getSeconds();
//This query will insert the new symptom in the symptoms history table
var sql = "INSERT INTO History(uuid, symptom, datetime) Values ('" + req.session.user.uuid +
"', '" + req.body.newSymptom + "', '" + year + "-" + month + "-" + date + " " + hours + ":" + minutes + ":" + seconds + "');"
db.query(sql, (err, result) => {
try {
if (err) console.log(err);
//console.log('hi')
} catch (err) {
//console.log(err)
}
})
// This query will fetch the doctor uuid of the patient
var sql1 = "Select * from Doctor Where patient_uuid = '" + req.session.user.uuid + "'"
db.query(sql1, (err1, result1) => {
try {
console.log(result1)
if (err1) console.log(err1);
if (result1.length > 0) {
console.log(result1.user_uuid)
var message = "Hi! I have a new Symptom: " + req.body.newSymptom + " on date " + year + "-" + month + "-" + date + " " + hours + ":" + minutes + ":" + seconds
//This query will send the message to the doctor when a new symptom is added
var sql2 = "Insert into Messages Values ('" + req.session.user.uuid + "','" + result1[0].user_uuid + "' , '" + message + "', '" + year + "-" + month + "-" + date + " " + hours + ":" + minutes + ":" + seconds + "')"
console.log(sql2)
db.query(sql2, (err2, result2) => {
try {
if (err2) console.log(err2);
console.log('hi')
} catch (err2) {
console.log(err2)
}
})
} else if (result1.length <= 0) { // if this patient has no doctor
console.log("No doctor Available")
}
} catch (err1) {
console.log(err1)
}
})
res.redirect('./symptoms')
} catch (err) {
console.log(err)
}
})
//post postal codes into database from form
app.post('/locations', checkAuthenticated, (req, res) => {
try {
let date_ob = new Date();
// current date
// adjust 0 before single digit date
let date = ("0" + date_ob.getDate()).slice(-2);
// current month
let month = ("0" + (date_ob.getMonth() + 1)).slice(-2);
// current year
let year = date_ob.getFullYear();
// current hours
let hours = date_ob.getHours();
// current minutes
let minutes = date_ob.getMinutes();
// current seconds
let seconds = date_ob.getSeconds();
// inserting the values into the database
var sql = "INSERT INTO Tracking(uuid, postalcode, datetime) Values ('" + req.session.user.uuid +
"', '" + req.body.postalCode + "', '" + year + "-" + month + "-" + date + " " + hours + ":" + minutes + ":" + seconds + "');"
db.query(sql, (err, result) => {
try {
if (err) console.log(err);
} catch (err) {
console.log(err)
}
})
res.redirect('./locations')
} catch (err) {
}
})
//query locations from database
app.get('/locations', checkAuthenticated, (req, res) => {
try {
console.log(req.session.user.uuid)
//fetching the info from the current user by descending date time
var sql = "SELECT * FROM Tracking WHERE uuid = '" + req.session.user.uuid + "' order by datetime desc;"
var postalCodes = [];
db.query(sql, function(err, rows) {
try {
console.log(rows[0])
if (err) console.log(err);
for (let i = 0; i < rows.length; i++) {
//converting the datetime into a different format
rows[i].datetime = rows[i].datetime.toISOString().slice(0, 19).replace('T', ' ')
postalCodes.push(rows[i])
}
console.log(postalCodes);
//rendering the location page
res.render('locations.ejs', { postalCodes: postalCodes })
} catch (err) {
console.log(err)
}
})
} catch (err) {
console.log('error')
}
})
//page where doctors can see patients symptoms history
app.get('/symptomsMonitor/:patient_id', checkDoctor, (req, res) => {
//store patient_uuid from parameters
const patient_uuid = req.params.patient_id
//fetching the info from history ordered by descending time where its the current user uuid
var sql = "SELECT * FROM History WHERE uuid = '" + req.params.patient_id + "' order by datetime desc;"
var symptoms = [];
db.query(sql, function(err, rows) {
try {
if (err) console.log(err);
for (let i = 0; i < rows.length; i++) {
//converting the date time into a different format
rows[i].datetime = rows[i].datetime.toISOString().slice(0, 19).replace('T', ' ')
symptoms.push(rows[i])
}
//rendering the doctors patient symptom page
res.render('doctor_symptoms.ejs', { symptoms: symptoms, patient_id: patient_uuid })
} catch (err) {
console.log(err)
}
})
})
//render the booking appointments page with dynamic data (doctor name)
app.get('/patientAppointment', checkAuthenticated, (req, res) => {
// this query will get the name of the doctor for this patient if exist
var sql = "Select uuid as doctoruuid,first_name as doctorfn, last_name as doctorln from User,Doctor where User.uuid = user_uuid AND Doctor.patient_uuid = '" + req.session.user.uuid + "'"
db.query(sql, (err, result) => {
//try{
if (err) console.log(err);
if (result.length > 0) {
const DfirstName = result[0].doctorfn
const DlastName = result[0].doctorln
const Duuid = result[0].doctoruuid
res.render('patient_appointments.ejs', { doctor_first_name: DfirstName, doctor_last_name: DlastName, doctor_uuid: Duuid })
//date format YYYY-MM-DD hh:mm:ss
} else
{