-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFlask_App.py
2135 lines (1635 loc) · 84.4 KB
/
Flask_App.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Import Modules
from flask import Flask, redirect, url_for, render_template, request, session, jsonify
from flask_mysqldb import MySQL
import secrets
from datetime import datetime
from datetime import date
import random
import string
import os
from werkzeug.utils import secure_filename
import re
from flask_mail import Mail, Message
app = Flask(__name__)
app.secret_key = secrets.token_hex(8)
# Set the session app object
app.config['SESSION_TYPE'] = 'filesystem'
app.config['SESSION_PERMANENT'] = True
app.config['SESSION_USE_SIGNER'] = True
# Configure Flask-Mail settings
app.config['MAIL_SERVER'] = 'smtp.gmail.com'
app.config['MAIL_PORT'] = 587
app.config['MAIL_USE_TLS'] = True
app.config['MAIL_USERNAME'] = 'pms.write@gmail.com'
app.config['MAIL_PASSWORD'] = 'iwhchxznwifqddkv'
app.config['MAIL_DEFAULT_SENDER'] = 'pms.write@gmail.com'
# Configure the MySQL and OAuth instances
mysql = MySQL(app)
mail = Mail(app)
# MySQL Configuration
app.config['MYSQL_HOST'] = 'pranikmedicalservices.mysql.pythonanywhere-services.com'
app.config['MYSQL_USER'] = 'pranikmedicalser'
app.config['MYSQL_PASSWORD'] = 'pms@1504'
app.config['MYSQL_DB'] = 'pranikmedicalser$default'
# Generate a random verification code and store it in the session
def generate_verification_code():
verification_code = ''.join(random.choices(string.digits, k=6))
session['verification_code'] = verification_code
return verification_code
# ------------------------------------------------------------------------------------------------------------------------------
# ------------------------------------------------------------------------------------------------------------------------------
@app.route("/")
def home():
if 'loggedin' in session:
return redirect(url_for('index'))
session['error']=''
return render_template("home.html")
@app.route('/about')
def about():
if 'loggedin' in session:
return redirect(url_for('index'))
return render_template("about.html")
@app.route("/contact")
def contact():
if 'loggedin' in session:
return redirect(url_for('contact_us'))
return render_template('contact.html')
@app.route('/register')
def register():
return render_template('register.html')
@app.route("/terms-condition")
def terms_condition():
if 'loggedin' in session:
return redirect(url_for('terms_condition_user'))
return render_template("terms-condition.html")
@app.route("/terms-condition-user")
def terms_condition_user():
if 'loggedin' not in session:
return redirect(url_for('terms_condition'))
return render_template("terms-condition-user.html")
@app.route("/coming-soon")
def coming_soon():
if 'loggedin' not in session:
return render_template('coming.html')
return render_template("coming-soon.html")
@app.route('/subscribe', methods=['POST'])
def subscribe():
email = request.form['email']
# Send thank you email
send_thank_you_email(email)
return redirect(url_for('home'))
def send_thank_you_email(email):
message = Message('Thank You for Subscribing', recipients=[email])
message.body = f"Dear Subscriber,\n\nThank you for subscribing to our newsletter! We're excited to have you on board and look forward to sharing valuable updates, news, and offers with you.\n\nIf you have any questions or need assistance, feel free to reach out to our team. Stay tuned for exciting content!\n\nBest regards,\nThe PMS Team"
try:
mail.send(message)
print("Thank you email sent successfully")
except Exception as e:
print(f"Failed to send thank you email: {str(e)}")
@app.route("/unauthorized")
def unauthorized():
if 'loggedin' not in session:
return redirect(url_for('home'))
# Get user information from the session
name = session.get('name_pms')
profile = session.get('profile_pms')
user = session.get('user_pms')
url = session.get('url_pms')
dashboard = session.get('dashboard_pms')
error = session.get('error')
return render_template("404.html", error=error, name=name, profile=profile, user=user, url=url, dashboard=dashboard)
@app.route("/index")
def index():
if 'loggedin' not in session:
return redirect(url_for('logout'))
session['error']=''
# Get user information from the session
name = session.get('name_pms')
profile = session.get('profile_pms')
user = session.get('user_pms')
url = session.get('url_pms')
dashboard = session.get('dashboard_pms')
return render_template("index.html", name=name, profile=profile, user=user, url=url, dashboard=dashboard)
@app.route("/about-us")
def about_us():
if 'loggedin' not in session:
return redirect(url_for('about'))
# Get user information from the session
name = session.get('name_pms')
profile = session.get('profile_pms')
user = session.get('user_pms')
url = session.get('url_pms')
dashboard = session.get('dashboard_pms')
return render_template('about-us.html', name=name, profile=profile, user=user, url=url, dashboard=dashboard)
@app.route("/contact-us")
def contact_us():
if 'loggedin' not in session:
return redirect(url_for('contact'))
# Get user information from the session
name = session.get('name_pms')
profile = session.get('profile_pms')
user = session.get('user_pms')
url = session.get('url_pms')
dashboard = session.get('dashboard_pms')
return render_template('contact-us.html', name=name, profile=profile, user=user, url=url, dashboard=dashboard)
# /login-phone
# /forgot-password
# Search Doctors for unregistered users:
@app.route('/search-doctors-pms', methods=['GET', 'POST'])
def search_doctors_pms():
if request.method == 'POST':
name = request.form["name"]
location = request.form["location"]
doctor_id = request.form["doctor_id"]
# Construct the SQL query and parameters based on the search criteria
query = "SELECT * FROM registered_doctors WHERE "
conditions = []
params = []
if name and name != "":
conditions.append("Name LIKE %s")
params.append(f"%{name}%")
if location and location != "":
conditions.append("Clinic_Address LIKE %s OR City LIKE %s OR State LIKE %s OR Address_Line1 LIKE %s OR Address_Line2 LIKE %s")
params.extend([f"%{location}%", f"%{location}%", f"%{location}%", f"%{location}%", f"%{location}%"])
if doctor_id and doctor_id != "":
conditions.append("Doctor_ID LIKE %s")
params.append(f"%{doctor_id}%")
if conditions:
query += " OR ".join(conditions)
else:
query += "1" # Dummy condition to retrieve all doctors if no specific criteria are provided
# Execute the query and fetch the search results
cur = mysql.connection.cursor()
cur.execute(query, tuple(params))
rows = cur.fetchall()
# Count the number of doctors found
num_doctors_found = len(rows)
msg = f"{num_doctors_found} Doctors found:" if location else ""
msg1 = f" in {location}" if location else ""
if num_doctors_found == 0:
return render_template('search-not-found.html')
# Get the column names
column_names = [desc[0] for desc in cur.description]
# Prepare the list of doctor data dictionaries
doctor_data_list = []
for row in rows:
doctor_data = dict(zip(column_names, row))
# Filter out None values from the doctor_data dictionary
doctor_data = {k: v for k, v in doctor_data.items() if v is not None}
doctor_data_list.append(doctor_data)
cur.close()
# Render the search results on the search.html template
return render_template('search-only.html', search_results=doctor_data_list, msg=msg, msg1=msg1)
# Render the search form template for GET requests
return render_template('home.html')
# ------------------------------------------------------------------------------------------------------------------------------
# APPOINMENTS RECORDS FOR REGISTERED PATIENTS:
# ------------------------------------------------------------------------------------------------------------------------------
@app.route('/search-doctors', methods=['GET', 'POST'])
def search_doctors():
l=['patient','doctor','admin']
if session.get('user_type') not in l:
return redirect(url_for('search_doctors_pms'))
# Get user information from the session
name = session.get('name_pms')
profile = session.get('profile_pms')
user = session.get('user_pms')
url = session.get('url_pms')
dashboard = session.get('dashboard_pms')
if request.method == 'POST':
name = request.form["name"]
location = request.form["location"]
doctor_id = request.form["doctor_id"]
# Construct the SQL query and parameters based on the search criteria
query = "SELECT * FROM registered_doctors WHERE "
conditions = []
params = []
if name and name != "":
conditions.append("Name LIKE %s")
params.append(f"%{name}%")
if location and location != "":
conditions.append("Clinic_Address LIKE %s OR City LIKE %s OR State LIKE %s OR Address_Line1 LIKE %s OR Address_Line2 LIKE %s")
params.extend([f"%{location}%", f"%{location}%", f"%{location}%", f"%{location}%", f"%{location}%"])
if doctor_id and doctor_id != "":
conditions.append("Doctor_ID LIKE %s")
params.append(f"%{doctor_id}%")
if conditions:
query += " OR ".join(conditions)
else:
query += "1" # Dummy condition to retrieve all doctors if no specific criteria are provided
# Execute the query and fetch the search results
cur = mysql.connection.cursor()
cur.execute(query, tuple(params))
rows = cur.fetchall()
# Count the number of doctors found
num_doctors_found = len(rows)
msg = f"{num_doctors_found} Doctors found:" if location else ""
msg1 = f" in {location}" if location else ""
if num_doctors_found == 0:
return render_template("search_not_found.html", name=name, profile=profile, user=user, url=url, dashboard=dashboard)
# Get the column names
column_names = [desc[0] for desc in cur.description]
# Prepare the list of doctor data dictionaries
doctor_data_list = []
for row in rows:
doctor_data = dict(zip(column_names, row))
# Filter out None values from the doctor_data dictionary
doctor_data = {k: v for k, v in doctor_data.items() if v is not None}
doctor_data_list.append(doctor_data)
cur.close()
# Render the search results on the search.html template
return render_template('search.html', search_results=doctor_data_list, msg=msg, msg1=msg1, name=name, profile=profile, user=user, url=url, dashboard=dashboard)
# Render the search form template for GET requests
return redirect(url_for('index'))
@app.route('/book-appointment/<string:doctor_id>', methods=['GET', 'POST'])
def book_appointment(doctor_id):
if session.get('user_type') != 'patient':
session['error'] = "You are not an authorized patient. Only authorized patients have access to this page."
return redirect(url_for('unauthorized'))
# Retrieve the doctor's details based on the doctor ID
cur = mysql.connection.cursor()
cur.execute("SELECT * FROM registered_doctors WHERE Doctor_ID = %s", (doctor_id,))
row = cur.fetchone()
column_names = [desc[0] for desc in cur.description] # Get the column names
doctor_data = dict(zip(column_names, row))
# Filter out None values from the doctor_data dictionary
doctor_data = {k: v for k, v in doctor_data.items() if v is not None}
cur.close()
# Get user information from the session
name = session.get('name_pms')
profile = session.get('profile_pms')
user = session.get('user_pms')
url = session.get('url_pms')
dashboard = session.get('dashboard_pms')
if request.method == 'POST':
# Retrieve the form data for the appointment details
appointment_date = request.form['appointment_date']
appointment_time = request.form['appointment_time']
insurance = request.form.get('insurance', 'No')
reason = request.form['reason']
symptoms = request.form['symptoms']
patient_id = session['patient_id']
if appointment_time == '':
date_error = "Please select time."
return render_template('booking.html', doctor_data=doctor_data, date_error=date_error, name=name, profile=profile, user=user, url=url, dashboard=dashboard)
# Check if the appointment date is in the past
selected_date = datetime.strptime(appointment_date, '%d/%m/%Y').date()
current_date = datetime.now().date()
if selected_date < current_date:
date_error = "Please select a date in the present or future."
return render_template('booking.html', doctor_data=doctor_data, date_error=date_error, name=name, profile=profile, user=user, url=url, dashboard=dashboard)
# Change the date format to 'YYYY-MM-DD' for MySQL
appointment_date_mysql = selected_date.strftime('%Y-%m-%d')
# Change the time format to 'HH:MM:SS' for MySQL
appointment_time_mysql = datetime.strptime(appointment_time, '%I:%M %p').strftime('%H:%M:%S')
# Check if the appointment already exists
cur = mysql.connection.cursor()
query = """
SELECT * FROM appointments
WHERE Patient_ID = %s AND Doctor_ID = %s AND Appointment_Date = %s
"""
cur.execute(query, (patient_id, doctor_id, appointment_date_mysql))
existing_appointment = cur.fetchone()
if existing_appointment:
# An appointment with the same doctor, date, and time already exists
error_message = "Your appointment is already booked with this doctor."
return render_template('booking.html', doctor_data=doctor_data, date_error=error_message, name=name, profile=profile, user=user, url=url, dashboard=dashboard)
# Store the appointment details in session
session['doctor_id'] = doctor_id
session['appointment_date_view'] = appointment_date
session['appointment_time_view'] = appointment_time
session['appointment_date'] = appointment_date_mysql
session['appointment_time'] = appointment_time_mysql
session['insurance'] = insurance
session['reason'] = reason
session['symptoms'] = symptoms
# Redirect to the payment page
return redirect(url_for('payment', doctor_id=doctor_id))
# Render the appointment booking form with the doctor's details and today's date
return render_template('booking.html', doctor_data=doctor_data, name=name, profile=profile, user=user, url=url, dashboard=dashboard)
@app.route('/book-appointment/<string:doctor_id>/payment', methods=['GET', 'POST'])
def payment(doctor_id):
if session.get('user_type') != 'patient':
session['error'] = "You are not an authorized patient. Only authorized patients have access to this page."
return redirect(url_for('unauthorized'))
# Get user information from the session
name = session.get('name_pms')
profile = session.get('profile_pms')
user = session.get('user_pms')
url = session.get('url_pms')
dashboard = session.get('dashboard_pms')
email = session.get('patient_email')
# Retrieve the appointment data from session
patient_id = session['patient_id']
doctor_id = session['doctor_id']
appointment_date = session['appointment_date_view']
appointment_time = session['appointment_time_view']
appointment_date_mysql = session['appointment_date']
appointment_time_mysql = session['appointment_time']
insurance = session['insurance']
reason = session['reason']
symptoms = session['symptoms']
# Retrieve the doctor's details based on the doctor ID
cur = mysql.connection.cursor()
cur.execute("SELECT * FROM registered_doctors WHERE Doctor_ID = %s", (doctor_id,))
row = cur.fetchone()
column_names = [desc[0] for desc in cur.description] # Get the column names
doctor_data = dict(zip(column_names, row))
# Filter out None values from the doctor_data dictionary
doctor_data = {k: v for k, v in doctor_data.items() if v is not None}
print(doctor_data.keys()) # Add this line to print the keys
cur.close()
# Check if the 'Fee' key is present in the dictionary
if 'Fee' in doctor_data:
if doctor_data['Fee'] != None:
doctor_fee = float(doctor_data['Fee'])
else:
doctor_fee = 0.0
else:
doctor_fee = 100.0
booking_fee_amount = 2.0
tax_amount = (doctor_fee * 3) / 100
total_fee = doctor_fee + booking_fee_amount + tax_amount
if request.method == 'POST':
# Perform payment validation and processing here
#payment = request.form["payment"]
#print(payment)
# Save the appointment details with the doctor ID
# Insert the appointment data into the appointments table
cur = mysql.connection.cursor()
query = """
INSERT INTO appointments (Patient_ID, Doctor_ID, Appointment_Date, Appointment_Time, Insurance, Reason, Symptoms)
VALUES (%s, %s, %s, %s, %s, %s, %s)
"""
appointment_values = (
patient_id,
doctor_id,
appointment_date_mysql,
appointment_time_mysql,
insurance,
reason,
symptoms
)
cur.execute(query, appointment_values)
mysql.connection.commit()
cur.close()
#session.pop('patient_id', None)
session.pop('doctor_id', None)
session.pop('appointment_date_view', None)
session.pop('appointment_time_view', None)
session.pop('appointment_date', None)
session.pop('appointment_time', None)
session.pop('insurance', None)
session.pop('reason', None)
session.pop('symptoms', None)
if 'Name' in doctor_data:
doctor_name = doctor_data['Name']
else:
doctor_name = "Unknown"
# Send email to the patient with appointment details
msg = Message('Appointment Confirmation', recipients=[email])
msg.body = f"Dear {name},\n\nThank you for booking an appointment with Pranik Medical Services (PMS).\n\nYour appointment details are as follows:\n\nDoctor: {doctor_name}\nAppointment Date: {appointment_date}\nAppointment Time: {appointment_time}\n\nWe look forward to seeing you!\n\nBest regards,\nThe PMS Team"
mail.send(msg)
# Redirect to a success page or show a success message
return render_template('successful.html', doctor=doctor_data, appointment_date=appointment_date, appointment_time=appointment_time, name=name, profile=profile, user=user, url=url, dashboard=dashboard)
# Redirect to a success page or show a success message
return render_template('successful.html', doctor=doctor_data, appointment_date = appointment_date, appointment_time = appointment_time, name=name, profile=profile, user=user, url=url, dashboard=dashboard)
return render_template('payment.html', doctor=doctor_data,doctor_id = doctor_id, appointment_date = appointment_date, appointment_time = appointment_time,
doctor_fee = doctor_fee, booking_fee=booking_fee_amount, tax=tax_amount, total_fee=total_fee, name=name, profile=profile, user=user, url=url, dashboard=dashboard)
# ------------------------------------------------------------------------------------------------------------------------------
# PATIENTS RECORDS:
@app.route("/patient-register", methods=['GET', 'POST'])
def patient_register():
if request.method == 'POST':
full_name = request.form["fullname"]
email = request.form["email"]
phone_no = request.form["phone"]
password = request.form["password"]
# Regular expression patterns
email_pattern = r'^[\w\.-]+@[\w\.-]+\.\w+$'
phone_pattern = r'^\d{10}$'
password_pattern = r'^.{8,}$'
# Validate email
if not re.match(email_pattern, email):
error_message = "Invalid email address. Please enter a valid email."
return render_template("patient-register.html", error=error_message)
# Validate phone number
if not re.match(phone_pattern, phone_no):
error_message = "Invalid phone number. Please enter a 10-digit phone number."
return render_template("patient-register.html", error=error_message)
# Validate password
if not re.match(password_pattern, password):
error_message = "Invalid password. Password should be at least 8 characters long."
return render_template("patient-register.html", error=error_message)
# Check if the patient already exists in the database
cur = mysql.connection.cursor()
query = "SELECT * FROM registered_patients WHERE Email = %s OR Phone = %s"
cur.execute(query, (email, phone_no))
row = cur.fetchone()
if row is not None:
column_names = [desc[0] for desc in cur.description] # Get the column names
patient_data = dict(zip(column_names, row))
cur.close()
# Check if email or phone number is already registered
if patient_data['Email'] == email:
error_message = "Email is already registered."
else:
error_message = "Phone number is already registered."
return render_template("patient-register.html", error=error_message)
cur.close()
# Generate a unique patient ID
patient_id = generate_patient_id(full_name)
# Register the patient if not already registered
cur = mysql.connection.cursor()
query = "INSERT INTO registered_patients (Name, Email, Phone, Password, Patient_ID) VALUES (%s, %s, %s, %s, %s)"
cur.execute(query, (full_name, email, phone_no, password, patient_id))
mysql.connection.commit()
cur.close()
# Send registration email to the user
msg = Message('Registration Confirmation', recipients=[email])
msg.body = f"Dear {full_name},\n\nThank you for registering with Pranik Medical Services (PMS).\n\nYou can now log in to access all the services and features offered by PMS.\n\nWe look forward to serving you!\n\nBest regards,\nThe PMS Team"
mail.send(msg)
return render_template('success.html')
return render_template("patient-register.html")
def generate_patient_id(full_name):
# Generate random digits
random_digits = ''.join(random.choices(string.digits, k=4))
# Get the current date and time
now = datetime.now()
day_digit = str(now.day)[0]
month_digit = str(now.month)[0]
minute_digit = str(now.minute)[0]
second_digit = str(now.second)[0]
# Create the patient ID by combining name characters, digits, and the date
patient_id = f"{full_name[:3].upper()}{random_digits}{day_digit}{month_digit}{minute_digit}{second_digit}"
return patient_id
@app.route('/patient-dashboard')
def patient_dashboard():
if session['user_type'] == 'patient':
email = session['email'] # Retrieve the logged-in doctor's email from the session
cur = mysql.connection.cursor()
query = "SELECT * FROM registered_patients WHERE Email = %s"
cur.execute(query, (email,))
row = cur.fetchone()
column_names = [desc[0] for desc in cur.description] # Get the column names
patient_data = dict(zip(column_names, row))
cur.close()
# Check if the 'Profile_URL' key exists in the row_dict dictionary
if 'Profile_URL' in patient_data and patient_data['Profile_URL'] is not None:
session['profile_pms'] = 'patients/' + patient_data['Profile_URL']
if 'Name' in patient_data and patient_data['Name'] is not None:
session['name_pms'] = patient_data['Name']
# Get user information from the session
name = session.get('name_pms')
profile = session.get('profile_pms')
user = session.get('user_pms')
url = session.get('url_pms')
dashboard = session.get('dashboard_pms')
patient_id = patient_data['Patient_ID']
cur = mysql.connection.cursor()
query = """
SELECT appointments.*, registered_doctors.Name AS Doctor_Name, registered_doctors.Profile_URL AS Profile_URL, registered_doctors.Doctor_ID, registered_doctors.Specialization AS Specialization
FROM appointments
JOIN registered_doctors ON appointments.Doctor_ID = registered_doctors.Doctor_ID
WHERE Patient_ID = %s
ORDER BY Appointment_Date >= CURDATE() DESC, Appointment_Date ASC
"""
cur.execute(query, (patient_id,))
rows = cur.fetchall()
# Get the column names
column_names = [desc[0] for desc in cur.description]
# Prepare the list of appointment data dictionaries
appointment_data_list = []
for row in rows:
appointment_data = dict(zip(column_names, row))
# Filter out None values from the appointment_data dictionary
appointment_data = {k: v for k, v in appointment_data.items() if v is not None}
appointment_data_list.append(appointment_data)
cur.close()
amount_paid = "--"
# Render the doctor dashboard template
return render_template('patient-dashboard.html', appointment_data_list=appointment_data_list, amount_paid=amount_paid, patient_data=patient_data, name=name, profile=profile, user=user, url=url, dashboard=dashboard)
else:
session['error'] = "You are not an authorized patient. Only authorized patients have access to this page."
return redirect(url_for('unauthorized'))
@app.route("/patient-profile-settings", methods=['GET', 'POST'])
def patient_profile_settings():
# Get user information from the session
name = session.get('name_pms')
profile = session.get('profile_pms')
user = session.get('user_pms')
url = session.get('url_pms')
dashboard = session.get('dashboard_pms')
if session['user_type'] == 'patient':
if request.method == 'POST':
# Get the updated patient data from the form
name = request.form['name']
dob = request.form['dob']
blood_group = request.form['blood_group']
phone = request.form['phone']
address = request.form['address']
city = request.form['city']
state = request.form['state']
pincode = request.form['pincode']
country = request.form['country']
email = session['email'] # Retrieve the logged-in patient's email from the session
# Construct the SQL query and parameters based on the updated fields
query = "UPDATE registered_patients SET"
params = []
if name:
query += " Name = %s,"
params.append(name)
if dob:
query += " Date_of_Birth = %s,"
params.append(dob)
if blood_group:
query += " Blood_Group = %s,"
params.append(blood_group)
if phone:
query += " Phone = %s,"
params.append(phone)
if address:
query += " Address = %s,"
params.append(address)
if city:
query += " City = %s,"
params.append(city)
if state:
query += " State = %s,"
params.append(state)
if pincode:
query += " Pin_Code = %s,"
params.append(pincode)
if country:
query += " Country = %s,"
params.append(country)
# Remove the trailing comma from the query
query = query.rstrip(',')
# Add the WHERE clause to update the specific patient's record
query += " WHERE Email = %s"
params.append(email)
# Update the patient data in the database
cur = mysql.connection.cursor()
cur.execute(query, tuple(params))
mysql.connection.commit()
cur.close()
# Handle image upload
if 'photo' in request.files:
photo = request.files['photo']
if photo.filename != '':
email = session['email']
cur = mysql.connection.cursor()
# Generate a secure filename and specify the upload folder path
filename = secure_filename(session['patient_id'] + os.path.splitext(photo.filename)[1])
upload_folder = os.path.join(app.root_path, 'static', 'assets', 'img', 'patients')
# Save the uploaded image with the patient_id as the filename
photo.save(os.path.join(upload_folder, filename))
# Update the image filename in the database
cur = mysql.connection.cursor()
query = "UPDATE registered_patients SET Profile_URL = %s WHERE Email = %s"
cur.execute(query, (filename, email))
mysql.connection.commit()
cur.close()
# Redirect to the patient dashboard or any other appropriate page
return redirect(url_for('patient_dashboard'))
# Retrieve the patient's data from the database for display
email = session['email'] # Retrieve the logged-in patient's email from the session
cur = mysql.connection.cursor()
query = "SELECT * FROM registered_patients WHERE Email = %s"
cur.execute(query, (email,))
row = cur.fetchone()
if row:
column_names = [desc[0] for desc in cur.description] # Get the column names
patient_data = dict(zip(column_names, row))
# Filter out None values from the patient_data dictionary
patient_data = {k: v for k, v in patient_data.items() if v is not None}
session['patient_id'] = patient_data['Patient_ID']
cur.close()
# Render the patient profile settings template with the patient's data
return render_template('patient-profile-settings.html', patient_data=patient_data, name=name, profile=profile, user=user, url=url, dashboard=dashboard)
else:
session['error'] = "You are not an authorized patient. Only authorized patients have access to this page."
return redirect(url_for('unauthorized'))
@app.route('/patient-change-password', methods=['GET', 'POST'])
def patient_change_password():
if session.get('user_type') != 'patient':
session['error'] = "You are not an authorized patient. Only authorized patients have access to this page."
return redirect(url_for('unauthorized'))
# Get user information from the session
name = session.get('name_pms')
profile = session.get('profile_pms')
user = session.get('user_pms')
url = session.get('url_pms')
dashboard = session.get('dashboard_pms')
# Retrieve the patient's data from the database for display
f_email = session['email'] # Retrieve the logged-in patient's email from the session
cur = mysql.connection.cursor()
query = "SELECT * FROM registered_patients WHERE Email = %s"
cur.execute(query, (f_email,))
row = cur.fetchone()
column_names = [desc[0] for desc in cur.description] # Get the column names
patient_data = dict(zip(column_names, row))
session['old_password'] = patient_data['Password']
cur.close()
if request.method == 'POST':
# Access the form data
old_password = request.form['old_password']
new_password = request.form['new_password']
confirm_password = request.form['confirm_password']
# Perform validation
# Example: Check if the old password matches the current password for the patient
if old_password != session['old_password']:
error_message = "Old password is incorrect."
return render_template('patient-change-password.html', error=error_message, patient_data=patient_data, name=name, profile=profile, user=user, url=url, dashboard=dashboard)
# Example: Check if the new password meets the desired criteria
if new_password != confirm_password:
error_message = "New password and confirm password do not match."
return render_template('patient-change-password.html', error=error_message, patient_data=patient_data, name=name, profile=profile, user=user, url=url, dashboard=dashboard)
# Update the password in the database for the patient
patient_id = patient_data['Patient_ID']
update_password_in_p_database(patient_id, new_password)
success_message = "Password changed successfully."
return render_template('patient-change-password.html', error=success_message, patient_data=patient_data, name=name, profile=profile, user=user, url=url, dashboard=dashboard)
return render_template('patient-change-password.html', patient_data=patient_data, name=name, profile=profile, user=user, url=url, dashboard=dashboard)
def update_password_in_p_database(patient_id, new_password):
cur = mysql.connection.cursor()
query = "UPDATE registered_patients SET Password = %s WHERE Patient_ID = %s"
cur.execute(query, (new_password, patient_id))
mysql.connection.commit()
cur.close()
# -----------------------------------------------------------------------------------------------------------------------------
# DOCTORS RECORDS:
@app.route("/doctor-register", methods=['GET', 'POST'])
def doctor_register():
if request.method == 'POST':
# Handle the POST request for the "/doctor-register" URL
name = request.form['name']
gender = request.form["gender"]
clinic_name = request.form["clinic_name"]
clinic_address = request.form["clinic_address"]
email = request.form['email']
phone = request.form['phone']
password = request.form['password']
# Regular expression patterns
email_pattern = r'^[\w\.-]+@[\w\.-]+\.\w+$'
phone_pattern = r'^\d{10}$'
password_pattern = r'^.{8,}$'
# Validate email
if not re.match(email_pattern, email):
error = "Invalid email address. Please enter a valid email."
return render_template("doctor-register.html",error=error)
# Validate phone number
if not re.match(phone_pattern, phone):
error = "Invalid phone number. Please enter a 10-digit phone number."
return render_template("doctor-register.html",error=error)
# Validate password
if not re.match(password_pattern, password):
error = "Invalid password. Password should be at least 8 characters long."
return render_template("doctor-register.html",error=error)
# Check if the patient already exists in the database
cur = mysql.connection.cursor()
query = "SELECT * FROM registered_doctors WHERE Email = %s OR Phone = %s"
cur.execute(query, (email, phone))
row = cur.fetchone()
if row is not None:
column_names = [desc[0] for desc in cur.description] # Get the column names
doctor_data = dict(zip(column_names, row))
cur.close()
# Check if email or phone number is already registered
if doctor_data['Email'] == email:
error_message = "Email is already registered."
else:
error_message = "Phone number is already registered."
return render_template("patient-register.html", error=error_message)
cur.close()
# Generate a verification code
verification_code = generate_verification_code()
# Send verification email
msg = Message('Account Verification', recipients=[email])
msg.body = f"Your verification code is: {verification_code}"
mail.send(msg)
print(verification_code)
# Generate a unique doctor ID
doctor_id = generate_doctor_id(name)
# Store user data, verification code, and doctor ID in the session
session['doctor_id'] = doctor_id
session['doctor_name'] = name
session['gender'] = gender
session['clinic_name'] = clinic_name
session['clinic_address'] = clinic_address
session['doctor_email'] = email
session['doctor_phone'] = phone
session['doctor_password'] = password
session['verification_code'] = verification_code
return redirect(url_for('verify', email=email))
return render_template("doctor-register.html")
@app.route('/verify/<email>', methods=['GET', 'POST'])
def verify(email):
if request.method == 'POST':
verification_code = request.form['verification_code']
# Retrieve the stored verification code and doctor ID from the session
stored_verification_code = session.get('verification_code')
doctor_id = session.get('doctor_id')
# Compare the codes
if verification_code == stored_verification_code:
# Code is correct, store doctor data in the database
name = session['doctor_name']
gender = session['gender']
clinic_name = session['clinic_name']
clinic_address = session['clinic_address']
email = session['doctor_email']
phone = session['doctor_phone']
password = session['doctor_password']
# Insert doctor data into the database
cur = mysql.connection.cursor()
query = "INSERT INTO registered_doctors (Doctor_ID, Name, Gender, Clinic_Name, Clinic_Address, Email, Phone, Password) VALUES (%s, %s, %s, %s, %s, %s, %s, %s)"
cur.execute(query, (doctor_id, name, gender, clinic_name, clinic_address, email, phone, password))
mysql.connection.commit()
cur.close()
# Clear the session data
session.pop('doctor_id', None)
session.pop('doctor_name', None)
session.pop('gender',None)
session.pop('clinic_name',None)
session.pop('clinic_address',None)
session.pop('doctor_email', None)
session.pop('doctor_phone', None)
session.pop('doctor_password', None)
session.pop('verification_code', None)
# Send registration email to the user
msg = Message('Registration Confirmation', recipients=[email])
msg.body = f"Dear Dr. {name},\n\nThank you for registering with Pranik Medical Services (PMS).\n\nYou can now log in to access all the services and features offered by PMS.\n\nWe look forward to serving you!\n\nBest regards,\nThe PMS Team"
mail.send(msg)
return render_template('success.html')
else:
error = 'Incorrect OTP'
# Code is incorrect, display an error message
return render_template('verify.html', email=email, error=error)