-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.py
More file actions
520 lines (416 loc) · 17.4 KB
/
Copy pathapi.py
File metadata and controls
520 lines (416 loc) · 17.4 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
"""
REST API v1 for ISUFST CareHub.
Provides JSON API for mobile app and third-party integrations.
"""
from flask import Blueprint, jsonify, request
from flask_login import login_required, current_user
from werkzeug.security import check_password_hash
from models import db, User, Appointment, ClinicVisit, Inventory, MedicineReservation, Notification, Queue
from models_extended import VisitFeedback, HealthCertificate
from datetime import datetime, date, time, timedelta
from functools import wraps
api_v1 = Blueprint('api_v1', __name__, url_prefix='/api/v1')
# ──────────────────────────────────────────────
# API Authentication
# ──────────────────────────────────────────────
def api_required(f):
"""Decorator for API authentication."""
@wraps(f)
def decorated_function(*args, **kwargs):
if not current_user.is_authenticated:
return jsonify({'error': 'Authentication required'}), 401
return f(*args, **kwargs)
return decorated_function
def student_only(f):
"""Decorator to restrict to students or admin (for testing)."""
@wraps(f)
def decorated_function(*args, **kwargs):
if current_user.role not in ['student', 'admin']:
from flask import flash, redirect, url_for as _url_for
flash('Access denied.', 'error')
return redirect(_url_for('admin') if current_user.role == 'admin' else _url_for('auth.login'))
return f(*args, **kwargs)
return decorated_function
def staff_only(f):
"""Decorator to restrict to admin only (no staff/nurse roles)."""
@wraps(f)
def decorated_function(*args, **kwargs):
if current_user.role != 'admin':
from flask import flash, redirect, url_for as _url_for
flash('Access denied. Admin only.', 'error')
return redirect(_url_for('patient_dashboard.index') if current_user.role == 'student' else _url_for('auth.login'))
return f(*args, **kwargs)
return decorated_function
# ──────────────────────────────────────────────
# Authentication Endpoints
# ──────────────────────────────────────────────
@api_v1.route('/auth/login', methods=['POST'])
def login():
"""API login endpoint."""
data = request.get_json()
email = data.get('email')
password = data.get('password')
if not email or not password:
return jsonify({'error': 'Email and password required'}), 400
user = User.query.filter_by(email=email).first()
if not user or not user.check_password(password):
return jsonify({'error': 'Invalid credentials'}), 401
if not user.is_active:
return jsonify({'error': 'Account is inactive'}), 403
# In a production API, you would return a JWT token here
return jsonify({
'success': True,
'user': {
'id': user.id,
'email': user.email,
'first_name': user.first_name,
'last_name': user.last_name,
'role': user.role
}
})
@api_v1.route('/auth/me')
@api_required
def me():
"""Get current user info."""
user_data = {
'id': current_user.id,
'email': current_user.email,
'first_name': current_user.first_name,
'last_name': current_user.last_name,
'role': current_user.role,
'is_active': current_user.is_active
}
if current_user.role == 'student' and current_user.student_profile:
profile = current_user.student_profile
user_data['profile'] = {
'student_id_number': profile.student_id_number,
'course': profile.course,
'year_level': profile.year_level,
'contact_number': profile.contact_number,
'blood_type': profile.blood_type
}
return jsonify(user_data)
@api_v1.route('/admin/dashboard-stats', methods=['GET'])
@api_required
@staff_only
def admin_dashboard_stats():
"""Get real-time statistics for admin dashboard."""
from datetime import date
# Queue count
queue_count = Queue.query.filter_by(status='Waiting').count()
# Today's patients
today_patients = ClinicVisit.query.filter(
ClinicVisit.visit_date == date.today()
).count()
# Today's appointments
today_appointments = Appointment.query.filter(
Appointment.appointment_date == date.today()
).count()
# Low stock
low_stock_count = Inventory.query.filter(
Inventory.quantity < 10
).count()
# Pending reservations
pending_reservations_count = MedicineReservation.query.filter_by(
status='Reserved'
).count()
# Total students
total_students = User.query.filter_by(role='student').count()
return jsonify({
'queue_count': queue_count,
'today_patients': today_patients,
'today_appointments': today_appointments,
'low_stock_count': low_stock_count,
'pending_reservations_count': pending_reservations_count,
'total_students': total_students
})
# ──────────────────────────────────────────────
# Appointment Endpoints
# ──────────────────────────────────────────────
@api_v1.route('/appointments', methods=['GET'])
@api_required
@student_only
def get_appointments():
"""Get all appointments for current student."""
appointments = Appointment.query.filter_by(
student_id=current_user.id
).order_by(Appointment.appointment_date.desc()).all()
return jsonify([{
'id': appt.id,
'service_type': appt.service_type,
'appointment_date': appt.appointment_date.isoformat(),
'start_time': appt.start_time.strftime('%H:%M'),
'end_time': appt.end_time.strftime('%H:%M'),
'status': appt.status,
'created_at': appt.created_at.isoformat()
} for appt in appointments])
@api_v1.route('/appointments/<int:id>', methods=['GET'])
@api_required
def get_appointment(id):
"""Get specific appointment details."""
appt = Appointment.query.get_or_404(id)
# Verify access
if current_user.role == 'student' and appt.student_id != current_user.id:
return jsonify({'error': 'Unauthorized'}), 403
return jsonify({
'id': appt.id,
'service_type': appt.service_type,
'appointment_date': appt.appointment_date.isoformat(),
'start_time': appt.start_time.strftime('%H:%M'),
'end_time': appt.end_time.strftime('%H:%M'),
'status': appt.status,
'created_at': appt.created_at.isoformat()
})
@api_v1.route('/appointments', methods=['POST'])
@api_required
@student_only
def book_appointment():
"""Book a new appointment."""
data = request.get_json()
required_fields = ['service_type', 'appointment_date', 'start_time']
for field in required_fields:
if field not in data:
return jsonify({'error': f'{field} is required'}), 400
try:
appt_date = datetime.strptime(data['appointment_date'], '%Y-%m-%d').date()
start_time = datetime.strptime(data['start_time'], '%H:%M').time()
end_time = datetime.strptime(data.get('end_time', ''), '%H:%M').time() if data.get('end_time') else \
(datetime.combine(date.today(), start_time) + timedelta(minutes=30)).time()
except ValueError:
return jsonify({'error': 'Invalid date/time format'}), 400
# Create appointment
appointment = Appointment(
student_id=current_user.id,
service_type=data['service_type'],
appointment_date=appt_date,
start_time=start_time,
end_time=end_time,
status='Pending'
)
db.session.add(appointment)
db.session.commit()
return jsonify({
'success': True,
'appointment_id': appointment.id,
'message': 'Appointment booked successfully'
}), 201
@api_v1.route('/appointments/<int:id>/cancel', methods=['POST'])
@api_required
def cancel_appointment(id):
"""Cancel an appointment."""
appt = Appointment.query.get_or_404(id)
# Verify access
if current_user.role == 'student' and appt.student_id != current_user.id:
return jsonify({'error': 'Unauthorized'}), 403
appt.status = 'Cancelled'
db.session.commit()
return jsonify({
'success': True,
'message': 'Appointment cancelled'
})
@api_v1.route('/appointments/availability', methods=['GET'])
@api_required
def check_availability():
"""Check available slots for a date."""
date_str = request.args.get('date')
service_type = request.args.get('service_type', 'Medical')
if not date_str:
return jsonify({'error': 'date parameter required'}), 400
try:
check_date = datetime.strptime(date_str, '%Y-%m-%d').date()
except ValueError:
return jsonify({'error': 'Invalid date format (use YYYY-MM-DD)'}), 400
# Generate slots and check availability
from datetime import timedelta
slots = []
current = datetime.strptime('09:00', '%H:%M')
end = datetime.strptime('17:00', '%H:%M')
while current < end:
slot_time = current.time()
# Count bookings
booked = Appointment.query.filter(
Appointment.appointment_date == check_date,
Appointment.start_time == slot_time,
Appointment.status.in_(['Pending', 'Confirmed'])
).count()
slots.append({
'time': current.strftime('%H:%M'),
'available': booked < 3,
'booked_count': booked
})
current += timedelta(minutes=30)
return jsonify({
'date': date_str,
'service_type': service_type,
'slots': slots
})
# ──────────────────────────────────────────────
# Medical Records Endpoints
# ──────────────────────────────────────────────
@api_v1.route('/medical-records', methods=['GET'])
@api_required
@student_only
def get_medical_records():
"""Get medical history for current student."""
visits = ClinicVisit.query.filter_by(
student_id=current_user.id
).order_by(ClinicVisit.visit_date.desc()).all()
return jsonify([{
'id': visit.id,
'visit_date': visit.visit_date.isoformat(),
'chief_complaint': visit.chief_complaint,
'diagnosis': visit.diagnosis,
'treatment': visit.treatment,
'status': visit.status
} for visit in visits])
# ──────────────────────────────────────────────
# Medicine & Inventory Endpoints
# ──────────────────────────────────────────────
@api_v1.route('/medicines', methods=['GET'])
@api_required
def get_medicines():
"""Get available medicines."""
medicines = Inventory.query.filter(
Inventory.category == 'Medicine',
Inventory.quantity > 0
).all()
return jsonify([{
'id': med.id,
'name': med.name,
'quantity': med.quantity,
'expiry_date': med.expiry_date.isoformat() if med.expiry_date else None
} for med in medicines])
@api_v1.route('/reservations', methods=['GET'])
@api_required
@student_only
def get_reservations():
"""Get medicine reservations for current student."""
reservations = MedicineReservation.query.filter_by(
student_id=current_user.id
).order_by(MedicineReservation.reserved_at.desc()).all()
return jsonify([{
'id': res.id,
'medicine_name': res.medicine_name,
'quantity': res.quantity,
'status': res.status,
'reserved_at': res.reserved_at.isoformat(),
'picked_up_at': res.picked_up_at.isoformat() if res.picked_up_at else None
} for res in reservations])
@api_v1.route('/reservations', methods=['POST'])
@api_required
@student_only
def create_reservation():
"""Create a new medicine reservation."""
data = request.get_json()
if not data.get('medicine_name') or not data.get('quantity'):
return jsonify({'error': 'medicine_name and quantity required'}), 400
reservation = MedicineReservation(
student_id=current_user.id,
medicine_name=data['medicine_name'],
quantity=data['quantity'],
status='Reserved'
)
db.session.add(reservation)
db.session.commit()
return jsonify({
'success': True,
'reservation_id': reservation.id
}), 201
# ──────────────────────────────────────────────
# Notification Endpoints
# ──────────────────────────────────────────────
@api_v1.route('/notifications', methods=['GET'])
@api_required
def get_notifications():
"""Get notifications for current user."""
unread_only = request.args.get('unread_only', 'false').lower() == 'true'
query = Notification.query.filter_by(user_id=current_user.id)
if unread_only:
query = query.filter_by(is_read=False)
notifications = query.order_by(Notification.created_at.desc()).limit(50).all()
return jsonify([{
'id': notif.id,
'type': notif.type,
'title': notif.title,
'message': notif.message,
'link': notif.link,
'is_read': notif.is_read,
'created_at': notif.created_at.isoformat()
} for notif in notifications])
@api_v1.route('/notifications/<int:id>/read', methods=['POST'])
@api_required
def mark_notification_read(id):
"""Mark notification as read."""
notif = Notification.query.get_or_404(id)
if notif.user_id != current_user.id:
return jsonify({'error': 'Unauthorized'}), 403
notif.is_read = True
db.session.commit()
return jsonify({'success': True})
# ──────────────────────────────────────────────
# Feedback Endpoints
# ──────────────────────────────────────────────
@api_v1.route('/feedback', methods=['POST'])
@api_required
@student_only
def submit_feedback():
"""Submit feedback for a visit."""
data = request.get_json()
if not data.get('visit_id') or not data.get('rating'):
return jsonify({'error': 'visit_id and rating required'}), 400
# Verify the visit belongs to the student
visit = ClinicVisit.query.get_or_404(data['visit_id'])
if visit.student_id != current_user.id:
return jsonify({'error': 'Unauthorized'}), 403
# Check if feedback already exists
existing = VisitFeedback.query.filter_by(visit_id=data['visit_id']).first()
if existing:
return jsonify({'error': 'Feedback already submitted'}), 400
feedback = VisitFeedback(
visit_id=data['visit_id'],
student_id=current_user.id,
rating=data['rating'],
wait_time_rating=data.get('wait_time_rating'),
staff_rating=data.get('staff_rating'),
facility_rating=data.get('facility_rating'),
comments=data.get('comments'),
is_anonymous=data.get('is_anonymous', False)
)
db.session.add(feedback)
db.session.commit()
return jsonify({
'success': True,
'message': 'Thank you for your feedback!'
}), 201
# ──────────────────────────────────────────────
# Health Summary
# ──────────────────────────────────────────────
@api_v1.route('/health-summary', methods=['GET'])
@api_required
@student_only
def health_summary():
"""Get comprehensive health summary for student."""
total_visits = ClinicVisit.query.filter_by(student_id=current_user.id).count()
total_appointments = Appointment.query.filter_by(student_id=current_user.id).count()
active_reservations = MedicineReservation.query.filter_by(
student_id=current_user.id,
status='Reserved'
).count()
upcoming_appointments = Appointment.query.filter(
Appointment.student_id == current_user.id,
Appointment.appointment_date >= date.today(),
Appointment.status.in_(['Pending', 'Confirmed'])
).order_by(Appointment.appointment_date, Appointment.start_time).limit(3).all()
return jsonify({
'statistics': {
'total_visits': total_visits,
'total_appointments': total_appointments,
'active_reservations': active_reservations
},
'upcoming_appointments': [{
'id': appt.id,
'service_type': appt.service_type,
'date': appt.appointment_date.isoformat(),
'time': appt.start_time.strftime('%H:%M')
} for appt in upcoming_appointments]
})