Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
165 changes: 100 additions & 65 deletions routes/doctor_routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -790,48 +790,6 @@ def add_prescription():
# need to test this
@doctor_bp.route('/appointment/meal', methods=['POST'])
def assign_plan_to_patient():
"""
Assign a meal plan to a patient
---
tags:
- Appointment
requestBody:
required: true
content:
application/json:
schema:
type: object
required:
- appt_id
- meal_plan_id
properties:
appt_id:
type: integer
meal_plan_id:
type: integer
example:
appt_id: 1
meal_plan_id: 2
responses:
200:
description: Meal plan assigned successfully
content:
application/json:
schema:
type: object
properties:
message:
type: string
400:
description: Validation or database error
content:
application/json:
schema:
type: object
properties:
error:
type: string
"""
data = request.get_json()
appt_id = data.get('appt_id')
meal_plan_id = data.get('meal_plan_id')
Expand All @@ -841,32 +799,36 @@ def assign_plan_to_patient():

cursor = mysql.connection.cursor()

query = """
UPDATE PATIENT_APPOINTMENT
SET meal_prescribed = %s, updated_at = CURRENT_TIMESTAMP
WHERE appt_id = %s
"""
values = (meal_plan_id, appt_id)
cursor.execute(query, values)
try:
# Update the appointment
update_query = """
UPDATE PATIENT_APPOINTMENT
SET meal_prescribed = %s, updated_at = CURRENT_TIMESTAMP
WHERE patient_appt_id = %s
"""
cursor.execute(update_query, (meal_plan_id, appt_id))

patient_id_query = """
SELECT patient_id FROM PATIENT_APPOINTMENT
WHERE patient_appt_id = %s"""
cursor.execute(patient_id_query, (appt_id,))
# Fetch patient_id using consistent column name
patient_id_query = """
SELECT patient_id FROM PATIENT_APPOINTMENT
WHERE patient_appt_id = %s
"""
cursor.execute(patient_id_query, (appt_id,))
result = cursor.fetchone()

patient_id = cursor.fetchone()
if result is None:
return jsonify({"error": "No appointment found for this ID."}), 404

add_to_patient_plans = """
INSERT INTO PATIENT_MEAL_PLAN (patient_id, meal_plan_id)
VALUES (%s, %s)
"""

cursor.execute(add_to_patient_plans, (patient_id, meal_plan_id))
try:
mysql.connection.commit()
if cursor.rowcount == 0:
return jsonify({"error": "No appointment found for this patient."}), 404
patient_id = result[0] # Extract value

# ✅ FIXED: Correct argument order
insert_query = """
INSERT INTO PATIENT_PLANS (meal_plan_id, user_id, created_at, updated_at)
VALUES (%s, %s, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)
"""
cursor.execute(insert_query, (meal_plan_id, patient_id)) # Corrected order

mysql.connection.commit()
return jsonify({"message": "Meal plan assigned successfully."}), 200

except Exception as e:
Expand All @@ -875,6 +837,8 @@ def assign_plan_to_patient():
finally:
cursor.close()



# accepting patients - general
@doctor_bp.route('/doctor-accepting-status/<int:doctor_id>', methods=['PATCH'])
def update_accepting_status(doctor_id):
Expand Down Expand Up @@ -1228,7 +1192,8 @@ def get_past_appointments_by_doctor(doctor_id):
FROM PATIENT_APPOINTMENT pa
JOIN PATIENT p ON pa.patient_id = p.patient_id
JOIN MEAL_PLAN mp ON pa.meal_prescribed = mp.meal_plan_id
WHERE p.doctor_id = %s AND pa.appointment_datetime < NOW()
WHERE p.doctor_id = %s
AND (pa.appointment_datetime < NOW() OR pa.appt_status = 2)
ORDER BY pa.appointment_datetime DESC
"""

Expand Down Expand Up @@ -1577,3 +1542,73 @@ def get_top_doctors():
return jsonify({"error": str(e)}), 400
finally:
cursor.close()
@doctor_bp.route('/appt-status/<int:appointment_id>', methods=['PUT'])
def update_app_status(appointment_id):
"""
Update appointment status
---
tags:
- Appointment
parameters:
- name: appointment_id
in: path
required: true
schema:
type: integer
requestBody:
required: true
content:
application/json:
schema:
type: object
properties:
appt_status:
type: integer
enum: [0, 1, 2]
description: "0 = upcoming, 1 = ongoing, 2 = ended"
responses:
200:
description: Appointment status updated successfully
content:
application/json:
schema:
type: object
properties:
message: { type: string }
appt_status: { type: integer }
400:
description: Update error
content:
application/json:
schema:
type: object
properties:
error: { type: string }
"""
data = request.get_json()
appt_status = data.get('appt_status')

if appt_status is None or appt_status not in [0, 1, 2]:
return jsonify({'error': 'Invalid or missing appt_status'}), 400

cursor = mysql.connection.cursor()

try:
update_query = """
UPDATE PATIENT_APPOINTMENT
SET appt_status = %s, updated_at = NOW()
WHERE patient_appt_id = %s
"""
cursor.execute(update_query, (appt_status, appointment_id))
mysql.connection.commit()

if cursor.rowcount == 0:
return jsonify({'error': 'Appointment not found'}), 404

return jsonify({
'message': 'Appointment status updated',
'appt_status': appt_status
}), 200

except Exception as e:
return jsonify({'error': str(e)}), 400
62 changes: 51 additions & 11 deletions routes/patient_routes.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,18 @@
from flask import Blueprint, request, jsonify
from datetime import datetime
from db import mysql
import bcrypt
import bcrypt, base64
from google.cloud import storage
import time
import os

patient_bp = Blueprint('patient_bp', __name__)

credentials_path = os.getenv("GOOGLE_APPLICATION_CREDENTIALS")
os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = credentials_path
GCS_BUCKET = "image-bucket-490"
storage_client = storage.Client()

#--------------------REGISTRATION END POINTS------------------------------
# register patient + init survey combined
@patient_bp.route('/register-patient-with-survey', methods=['POST'])
Expand Down Expand Up @@ -91,6 +99,7 @@ def register_patient_with_survey():
cursor = mysql.connection.cursor()

try:

# hash the password ---
password = data['patient_password']
hashed_password = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt())
Expand All @@ -112,12 +121,25 @@ def register_patient_with_survey():
return jsonify({"error": "Pharmacy not found. Please register the pharmacy first."}), 400
pharmacy_id = pharmacy[0]

patient_picture_url = None
patient_picture = data.get('patient_picture') # Base64 encoded image data
if patient_picture:
try:
patient_picture = base64.b64decode(patient_picture)
filename = f"patients/{data['first_name']}_{data['last_name']}_{int(time.time())}.png"
bucket = storage_client.bucket(GCS_BUCKET)
blob = bucket.blob(filename)
blob.upload_from_string(patient_picture, content_type='image/png')

patient_picture_url = f"https://storage.googleapis.com/{GCS_BUCKET}/{filename}"
except Exception as e:
return jsonify({"error": f"Failed to upload image: {str(e)}"}), 400
# Insert patient ---
insert_patient_query = """
INSERT INTO PATIENT (
patient_email, patient_password, first_name, last_name,
pharmacy_id, insurance_provider, insurance_policy_number, insurance_expiration_date
) VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
pharmacy_id, insurance_provider, insurance_policy_number, insurance_expiration_date, profile_pic
) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)
"""
patient_values = (
data['patient_email'],
Expand All @@ -127,7 +149,8 @@ def register_patient_with_survey():
pharmacy_id,
data.get('insurance_provider'),
data.get('insurance_policy_number'),
data.get('insurance_expiration_date')
data.get('insurance_expiration_date'),
patient_picture_url
)
cursor.execute(insert_patient_query, patient_values)

Expand Down Expand Up @@ -412,6 +435,7 @@ def init_patient_survey():
mysql.connection.rollback()
return jsonify({"error": str(e)}), 400


@patient_bp.route('/init-patient-survey/<int:patient_id>', methods=['GET'])
def get_patient_init_survey(patient_id):
"""
Expand Down Expand Up @@ -499,7 +523,8 @@ def get_patient_init_survey(patient_id):
p.first_name,
p.last_name,
pis.favorite_meal,
pis.health_goals
pis.health_goals,
p.profile_pic
FROM PATIENT as p
JOIN PATIENT_INIT_SURVEY as pis ON p.patient_id = pis.patient_id
WHERE p.patient_id = %s
Expand All @@ -514,7 +539,7 @@ def get_patient_init_survey(patient_id):
'is_id', 'patient_id', 'mobile_number', 'dob', 'gender',
'height', 'weight', 'dietary_restrictions', 'blood_type', 'patient_address',
'patient_zipcode', 'patient_city', 'patient_state', 'medical_conditions',
'family_history', 'past_procedures', 'patient_email', 'first_name', 'last_name', 'favorite_meal', 'health_goals'
'family_history', 'past_procedures', 'patient_email', 'first_name', 'last_name', 'favorite_meal', 'health_goals', 'picture'
]
survey_info = dict(zip(keys, result))
return jsonify(survey_info), 200
Expand Down Expand Up @@ -1312,7 +1337,7 @@ def get_past_appointments(patient_id):
DOCTOR D ON PA.doctor_id = D.doctor_id
WHERE
PA.patient_id = %s
AND PA.appointment_datetime < NOW()
AND (pa.appointment_datetime < NOW() OR pa.appt_status = 2)
ORDER BY
PA.appointment_datetime DESC;

Expand Down Expand Up @@ -2203,16 +2228,30 @@ def edit_patient():
address = data.get('address')
zipcode = data.get('zipcode')
city = data.get('city')
state = data.get('state')
state = data.get('state')

patient_picture_url = None
patient_picture = data.get('patient_picture') # Base64 encoded image data
if patient_picture:
try:
patient_picture = base64.b64decode(patient_picture)
filename = f"patients/{data['first_name']}_{data['last_name']}_{int(time.time())}.png"
bucket = storage_client.bucket(GCS_BUCKET)
blob = bucket.blob(filename)
blob.upload_from_string(patient_picture, content_type='image/png')

patient_picture_url = f"https://storage.googleapis.com/{GCS_BUCKET}/{filename}"
except Exception as e:
return jsonify({"error": f"Failed to upload image: {str(e)}"}), 400

cursor = mysql.connection.cursor()
try:
# Update PATIENT table
cursor.execute("""
UPDATE PATIENT
SET patient_email = %s, first_name = %s, last_name = %s
SET patient_email = %s, first_name = %s, last_name = %s, patient_picture_url = %s
WHERE patient_id = %s
""", (patient_email, first, last, patient_id))
""", (patient_email, first, last, patient_id), patient_picture_url)

# Update PATIENT_INIT_SURVEY table
cursor.execute("""
Expand Down Expand Up @@ -2308,7 +2347,8 @@ def get_past_appointments_with_doctor(patient_id, doctor_id):

query = """
SELECT * FROM PATIENT_APPOINTMENT
WHERE patient_id = %s AND doctor_id = %s AND appointment_datetime < NOW()
WHERE patient_id = %s AND doctor_id = %s
AND (pa.appointment_datetime < NOW() OR pa.appt_status = 2)
ORDER BY appointment_datetime DESC
"""

Expand Down
Loading