forked from aleeshasujithabraham/Patient_dashboard
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
327 lines (254 loc) · 10.7 KB
/
app.py
File metadata and controls
327 lines (254 loc) · 10.7 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
from flask import Flask, request, jsonify
import mysql.connector
from flask_cors import CORS
from datetime import date
# --- 1. CONFIGURATION ---
DB_CONFIG = {
'user': 'root',
'password': '#aleesha123',
'host': '127.0.0.1',
'database': 'hospital_db',
}
# IMPORTANT: Flask serves index.html, admin.html, and styles.css from the 'static' folder
app = Flask(__name__, static_folder='static')
CORS(app)
# --- 2. DATABASE UTILITY FUNCTION ---
def get_db_connection():
"""Establishes and returns a connection to the MySQL database."""
try:
conn = mysql.connector.connect(**DB_CONFIG)
return conn
except mysql.connector.Error as err:
print(f"Error connecting to MySQL: {err}")
return None
# --- 3. HTML PAGE ROUTES ---
@app.route('/', methods=['GET'])
def serve_index_page():
"""Serves the main Patient Login/Dashboard page."""
return app.send_static_file('index.html')
@app.route('/admin', methods=['GET'])
def serve_admin_page():
"""Serves the dedicated Admin Data Entry page."""
return app.send_static_file('admin.html')
# --- 4. API ENDPOINTS (Authentication, Data Retrieval, Deletion) ---
@app.route('/api/check_user', methods=['POST'])
def check_user_existence():
"""Checks if a user exists for two-step authentication."""
data = request.json
name = data.get('name')
phone = data.get('phone')
if not name or not phone:
return jsonify({'success': False, 'message': 'Name and phone are required.'}), 400
conn = get_db_connection()
if conn is None:
return jsonify({'success': False, 'message': 'Database connection failed.'}), 500
cursor = conn.cursor(dictionary=True)
try:
cursor.execute("SELECT P_ID FROM PATIENT WHERE P_Name = %s AND P_Phone = %s", (name, phone))
patient_record = cursor.fetchone()
if patient_record:
return jsonify({'success': True,'is_new': False,'p_id': patient_record['P_ID']})
else:
return jsonify({'success': True,'is_new': True})
except mysql.connector.Error as err:
print(f"MySQL Error during user check: {err}")
return jsonify({'success': False, 'message': f'Database error during check: {err}'}), 500
finally:
cursor.close()
conn.close()
@app.route('/api/register', methods=['POST'])
def handle_registration():
"""Handles the detailed patient signup (INSERT), including optional Doctor/Room/Date."""
data = request.json
name = data.get('name')
phone = data.get('phone')
address = data.get('address')
age = data.get('age')
gender = data.get('gender')
# NEW: Get the optional fields. Convert empty strings to None (NULL)
# The 'or None' ensures that if the field is empty in the form, it sends NULL to the DB.
doctor_id = data.get('doctor_id') or None
room_id = data.get('room_id') or None
# Admission Date: Use input if provided, otherwise use today's date
input_date = data.get('admission_date')
admission_date = input_date if input_date else date.today()
# Core validation remains the same
if not all([name, phone, address, age, gender]):
return jsonify({'success': False, 'message': 'Core registration fields are required.'}), 400
conn = get_db_connection()
if conn is None:
return jsonify({'success': False, 'message': 'Database connection failed.'}), 500
cursor = conn.cursor()
try:
insert_query = """
INSERT INTO PATIENT
(P_Name, P_Phone, P_Address, P_Age, P_Gender, Admission_Date, Doctor_ID, Room_ID)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
"""
cursor.execute(insert_query, (name, phone, address, age, gender,
admission_date, doctor_id, room_id))
conn.commit()
p_id = cursor.lastrowid
return jsonify({
'success': True,
'message': 'Registration successful. Welcome!',
'p_id': p_id
})
except mysql.connector.Error as err:
conn.rollback()
print(f"MySQL Error during registration: {err}")
return jsonify({'success': False, 'message': f'Database error during registration: {err}'}), 500
finally:
cursor.close()
conn.close()
@app.route('/api/patient_data/<int:p_id>', methods=['GET'])
def get_patient_dashboard_data(p_id):
"""Retrieves all related patient, doctor, room, and treatment data using JOINs."""
conn = get_db_connection()
if conn is None:
return jsonify({'success': False, 'message': 'Database connection failed.'}), 500
cursor = conn.cursor(dictionary=True)
try:
patient_info_query = """
SELECT
P.P_ID, P.P_Name, P.P_Age, P.P_Gender, P.Admission_Date, P.P_Address,
D.D_Name AS Doctor_Name, D.D_Specialization, D.D_Phone AS Doctor_Phone,
R.Room_ID, R.Allocation_Details
FROM PATIENT P
LEFT JOIN DOCTOR D ON P.Doctor_ID = D.Doctor_ID
LEFT JOIN ROOM R ON P.Room_ID = R.Room_ID
WHERE P.P_ID = %s
"""
cursor.execute(patient_info_query, (p_id,))
patient_data = cursor.fetchone()
if not patient_data:
return jsonify({'success': False, 'message': 'Patient not found.'}), 404
treatment_query = """
SELECT
Diagnosis, Treatment_Details, T_Date
FROM TREATMENT
WHERE P_ID = %s
ORDER BY T_Date DESC
"""
cursor.execute(treatment_query, (p_id,))
treatment_history = cursor.fetchall()
response_data = {
'patient': patient_data,
'treatments': treatment_history
}
return jsonify({'success': True, 'data': response_data})
except mysql.connector.Error as err:
print(f"MySQL Error during data retrieval: {err}")
return jsonify({'success': False, 'message': f'Database error during data retrieval: {err}'}), 500
finally:
cursor.close()
conn.close()
@app.route('/api/patient/<int:p_id>', methods=['DELETE'])
def delete_patient_record(p_id):
"""Deletes a patient record and associated treatments."""
conn = get_db_connection()
if conn is None:
return jsonify({'success': False, 'message': 'Database connection failed.'}), 500
cursor = conn.cursor()
try:
conn.start_transaction()
cursor.execute("DELETE FROM TREATMENT WHERE P_ID = %s", (p_id,))
cursor.execute("DELETE FROM PATIENT WHERE P_ID = %s", (p_id,))
conn.commit()
if cursor.rowcount == 0:
return jsonify({'success': False, 'message': 'Patient not found to delete.'}), 404
return jsonify({'success': True, 'message': f'Patient (ID: {p_id}) and related records deleted.'})
except mysql.connector.Error as err:
conn.rollback()
print(f"MySQL Error during deletion: {err}")
return jsonify({'success': False, 'message': f'Database error during deletion: {err}'}), 500
finally:
cursor.close()
conn.close()
# --- 5. ADMIN/DATA ENTRY ENDPOINTS ---
@app.route('/api/add_doctor', methods=['POST'])
def add_doctor_record():
"""Adds a new doctor record to the DOCTOR table."""
data = request.json
name = data.get('name')
phone = data.get('phone')
email = data.get('email')
specialization = data.get('specialization')
if not all([name, specialization]):
return jsonify({'success': False, 'message': 'Doctor Name and Specialization are required.'}), 400
conn = get_db_connection()
if conn is None:
return jsonify({'success': False, 'message': 'Database connection failed.'}), 500
cursor = conn.cursor()
try:
insert_query = """
INSERT INTO DOCTOR (D_Name, D_Phone, D_Email, D_Specialization)
VALUES (%s, %s, %s, %s)
"""
cursor.execute(insert_query, (name, phone, email, specialization))
conn.commit()
return jsonify({'success': True, 'message': f'Doctor {name} added successfully with ID: {cursor.lastrowid}'})
except mysql.connector.Error as err:
conn.rollback()
print(f"MySQL Error during doctor add: {err}")
return jsonify({'success': False, 'message': f'Database error: {err}'}), 500
finally:
cursor.close()
conn.close()
@app.route('/api/add_room', methods=['POST'])
def add_room_record():
"""Adds a new room record to the ROOM table."""
data = request.json
room_id = data.get('id')
details = data.get('details')
if not all([room_id, details]):
return jsonify({'success': False, 'message': 'Room ID and Allocation Details are required.'}), 400
conn = get_db_connection()
if conn is None:
return jsonify({'success': False, 'message': 'Database connection failed.'}), 500
cursor = conn.cursor()
try:
insert_query = "INSERT INTO ROOM (Room_ID, Allocation_Details) VALUES (%s, %s)"
cursor.execute(insert_query, (room_id, details))
conn.commit()
return jsonify({'success': True, 'message': f'Room {room_id} added successfully.'})
except mysql.connector.Error as err:
conn.rollback()
print(f"MySQL Error during room add: {err}")
return jsonify({'success': False, 'message': f'Database error: {err}'}), 500
finally:
cursor.close()
conn.close()
@app.route('/api/add_treatment', methods=['POST'])
def add_treatment_record():
"""Adds a new treatment record to the TREATMENT table."""
data = request.json
p_id = data.get('p_id')
doctor_id = data.get('doctor_id')
diagnosis = data.get('diagnosis')
details = data.get('details')
t_date = data.get('date')
if not all([p_id, doctor_id, diagnosis, t_date]):
return jsonify({'success': False, 'message': 'Patient ID, Doctor ID, Diagnosis, and Date are required.'}), 400
conn = get_db_connection()
if conn is None:
return jsonify({'success': False, 'message': 'Database connection failed.'}), 500
cursor = conn.cursor()
try:
insert_query = """
INSERT INTO TREATMENT (P_ID, Doctor_ID, Diagnosis, Treatment_Details, T_Date)
VALUES (%s, %s, %s, %s, %s)
"""
cursor.execute(insert_query, (p_id, doctor_id, diagnosis, details, t_date))
conn.commit()
return jsonify({'success': True, 'message': f'Treatment added for Patient ID {p_id}.'})
except mysql.connector.Error as err:
conn.rollback()
print(f"MySQL Error during treatment add: {err}")
return jsonify({'success': False, 'message': f'Database error: {err}'}), 500
finally:
cursor.close()
conn.close()
# --- 6. RUN THE FLASK APP ---
if __name__ == '__main__':
app.run(debug=True)