diff --git a/appointment/app/api/appointment_route.py b/appointment/app/api/appointment_route.py index 196be70..7e340ff 100644 --- a/appointment/app/api/appointment_route.py +++ b/appointment/app/api/appointment_route.py @@ -7,6 +7,8 @@ from appointment.app.db import get_db from doctor.app.db import get_db as get_doctor_db from patient.app.db import get_db as get_patient_db +from patient_report.app.db import get_db as get_patient_report_db +from medicine.app.db import get_db as get_medicine_db from appointment.app.api import controller @@ -29,13 +31,13 @@ async def create_file(file=File(None),filepath=str): async def add_new_appointment(first_name: str = Form(), last_name: str = Form(), mobile_number: str = Form(), booking_time: str = Form(), - status_id: str = Form(default=''),file_data: UploadFile = Form(default=None), + file_data: UploadFile = Form(default=None), hospital_id: str = Form(default=''),patient_id: str = Form(), doctor_id: str = Form(),time_slot: str = Form(), staff_id: str = Form(default=''), patient_profile_pic: UploadFile = Form(default=None), disease :str = Form(default=''), appointment_date: str = Form(), - db: Session = Depends(get_db),patient_db: Session = Depends(get_patient_db)): + db: Session = Depends(get_db),patient_db: Session = Depends(get_patient_db),doctor_db: Session = Depends(get_doctor_db)): """Function to return final response while adding new appointment data""" # Authentication().authenticate(request.headers.get('Authorization'),db) filename = "" @@ -46,18 +48,25 @@ async def add_new_appointment(first_name: str = Form(), last_name: str = Form(), if patient_profile_pic is not None: profile_pic = patient_profile_pic.filename await create_file(patient_profile_pic,PROFILE_DIR_PATH) - return controller.add_new_appointment(db, patient_db,first_name, last_name, - mobile_number,booking_time, status_id, hospital_id, + return controller.add_new_appointment(db, patient_db,doctor_db,first_name, last_name, + mobile_number,booking_time, hospital_id, patient_id,doctor_id,staff_id,filename,profile_pic,time_slot,disease,appointment_date) @appointment_router.post("/get_appointment_details") -async def get_appointment_details(request:Request, database: Session = Depends(get_db),patient_db: Session = Depends(get_patient_db),doctor_database: Session = Depends(get_doctor_db)): +async def get_appointment_details(request:Request, database: Session = Depends(get_db),patient_report_db: Session = Depends(get_patient_report_db),patient_db: Session = Depends(get_patient_db),doctor_database: Session = Depends(get_doctor_db), +medicine_database: Session = Depends(get_medicine_db)): """Function to return Appointment details (specific and all Appointment data can be fetched)""" # patient_id = Authentication().authenticate(request.headers.get('Authorization'),database)[0].id request_json = await request.json() - return controller.get_appointment_by_id(database,patient_db,request_json["id"],request_json["date"],doctor_database) + doctor_id = "" + patient_id = "" + if "doctor_id" in request_json: + doctor_id = request_json["doctor_id"] + else: + patient_id = request_json["id"] + return controller.get_appointment_by_id(database,patient_report_db,patient_db,patient_id,doctor_id,request_json["date"],doctor_database,medicine_database) @appointment_router.post("/get_appointment_by_date") async def get_appointment_details_by_date(request:Request, database: Session = Depends(get_db),doctor_database: Session = Depends(get_doctor_db)): @@ -74,27 +83,18 @@ def delete_appointment_details(request:Request,appointment_id: schemas.Appointme # Authentication().authenticate(request.headers.get('Authorization'),database) return controller.delete_appointment_details(database, id = appointment_id.id) -# @appointment_router.post("/update_appointment_details") -# def update_appointment_details(request:Request,appointment_details: schemas.AddNewAppointment, database: Session = Depends(get_db)): -# """Function to update particular Appointment details""" -# Authentication().authenticate(request.headers.get('Authorization'),database) -# return controller.update_appointment_details(database, appointment = appointment_details) - -# @appointment_router.post("/update_appointment_details") -# def update_appointment_details(request:Request,appointment_details: schemas.AddNewAppointment, database: Session = Depends(get_db)): -# """Function to update particular Appointment details""" -# Authentication().authenticate(request.headers.get('Authorization'),database) -# return controller.update_appointment_details(database, appointment = appointment_details) - @appointment_router.post("/update_appointment_details") -async def update_appointment_details(request: Request,appointment_id: str = Form(),first_name: str = Form(), last_name: str = Form(), - mobile_number: str = Form(), - booking_time: str = Form(), +async def update_appointment_details(request: Request,appointment_id: str = Form(),first_name: str = Form(default=''), last_name: str = Form(default=''), + mobile_number: str = Form(default=''), + booking_time: str = Form(default=''), status_id: str = Form(default=''),file_data: UploadFile = Form(default=None),patient_profile_pic: UploadFile = Form(default=None), - hospital_id: str = Form(default=''),patient_id: str = Form(default=''), doctor_id: str = Form(), + report_description: str = Form(default=''),medicine_id: str = Form(default=''), + patient_report_file: UploadFile = Form(default=None), + hospital_id: str = Form(default=''),patient_id: str = Form(default=''), doctor_id: str = Form(default=''), staff_id: str = Form(default=''), time_slot: str = Form(default=''),appointment_date: str = Form(default=''), - db: Session = Depends(get_db),doctor_database: Session = Depends(get_doctor_db)): + db: Session = Depends(get_db),patient_report_db: Session = Depends(get_patient_report_db),doctor_database: Session = Depends(get_doctor_db), + medicine_database: Session = Depends(get_medicine_db)): """Function to update particular appointment detail""" # Authentication().authenticate(request.headers.get('Authorization'),db) filename = "" @@ -105,9 +105,9 @@ async def update_appointment_details(request: Request,appointment_id: str = Form if patient_profile_pic is not None: profile_pic = patient_profile_pic.filename await create_file(patient_profile_pic,PROFILE_DIR_PATH) - return controller.update_appointment_details(db,doctor_database, first_name, last_name, - mobile_number,booking_time, status_id, hospital_id, - patient_id,doctor_id,staff_id,filename,profile_pic,appointment_id,time_slot,appointment_date) + return controller.update_appointment_details(db,patient_report_db,doctor_database,medicine_database, first_name, last_name, + mobile_number,booking_time, status_id, hospital_id,patient_id,doctor_id,staff_id,filename,profile_pic, + report_description,medicine_id,patient_report_file,appointment_id,time_slot,appointment_date) @appointment_router.get("/get_appointment_by_pagination") async def get_appointment_by_pagination(database: Session = Depends(get_db),page: int = 0, size: int = 5): @@ -115,16 +115,21 @@ async def get_appointment_by_pagination(database: Session = Depends(get_db),page return controller.get_appointment_by_pagination(database,page,size) @appointment_router.post("/add_appointment_status", response_model=schemas.AddAppointmentStatusResponse) -def add_appointment_status(appointment_status: schemas.AppointmentStatusBase, database: Session = Depends(get_db)): +async def add_appointment_status(request:Request, database: Session = Depends(get_db)): """Function to return final response while adding new Appointment status details""" - return controller.add_new_appointment_status(database,appointment_status) + request_json = await request.json() + return controller.add_new_appointment_status(database,request_json["appointment_status"]) @appointment_router.post("/get_appointment_status") -def get_appointment_status(appointment_status_id: schemas.AppointmentStatusId, database: Session = Depends(get_db)): +async def get_appointment_status(request:Request, database: Session = Depends(get_db)): """Function to return Appointment details (specific and all Appointment status data can be fetched)""" - return controller.get_appointment_status_by_id_or_without_id(database, id = appointment_status_id.id) + id = "" + request_json = await request.json() + if request_json['id'] != "": + id = request_json["id"] + return controller.get_appointment_status_by_id_or_without_id(database,id) @appointment_router.post("/delete_appointment_status") diff --git a/appointment/app/api/controller.py b/appointment/app/api/controller.py index 3b63389..5eaa7fc 100644 --- a/appointment/app/api/controller.py +++ b/appointment/app/api/controller.py @@ -4,6 +4,8 @@ from fastapi import HTTPException, UploadFile from sqlalchemy import Integer +import patient + sys.path.append({os.getcwd()}) """Controller file for writing db queries""" from typing import Optional @@ -11,7 +13,9 @@ from sqlalchemy.orm import Session from appointment.app.models import models,schemas from doctor.app.models import models as doctorModels +from medicine.app.models import models as medicineModels from patient.app.models import models as patientModels +from patient_report.app.models import models as PatientReportModels from appointment.app.response import Response as ResponseData from hospital.app.api.controller import check_if_hospital_id_is_valid from appointment.app.error_handling import Error @@ -24,16 +28,23 @@ def Merge(dict1, dict2): """Function to merge dict using update method""" return dict2.update(dict1) -def add_new_appointment(database: Session,patientDatabase: Session, first_name: str, last_name: str, mobile_number: str,booking_time: str, - status_id: str, hospital_id: str, +def add_new_appointment(database: Session,patientDatabase: Session,doctorDatabase:Session, first_name: str, last_name: str, mobile_number: str,booking_time: str, + hospital_id: str, patient_id: str, doctor_id: str,staff_id: str,file : UploadFile,profile_pic: UploadFile,time_slot: str,disease: str,appointment_date: str): """Function to add new appointment data""" # db_patient_number = database.query(models.Appointment).filter(models.Appointment.mobile_number == mobile_number).first() # if not db_patient_number: # return ResponseData.success_without_data("Mobile number entered is not valid") db_patient_id = patientDatabase.query(patientModels.Patient).filter(patientModels.Patient.id == int(patient_id)).first() + db_doctor_id = doctorDatabase.query(doctorModels.Doctor).filter(doctorModels.Doctor.id == int(doctor_id)).first() + status = database.query(models.AppointmentStatus).filter(models.AppointmentStatus.status == 'Pending').first() + status_id = '' + if status: + status_id = str(status.a_id) if not db_patient_id: return ResponseData.success_without_data("Patient id is invalid") + if not db_doctor_id: + return ResponseData.success_without_data("Doctor id is invalid") appointment_data = { "first_name": first_name, "last_name": last_name, @@ -56,37 +67,63 @@ def add_new_appointment(database: Session,patientDatabase: Session, first_name: database.refresh(db_appointment) return ResponseData.success(db_appointment.__dict__,"Appointment booked successfully") -def get_appointment_by_id(database: Session,patientDatabase: Session,patient_id,date,get_doctor_database: Session): +def get_appointment_by_id(database: Session,patient_report_database: Session,patientDatabase: Session,patient_id,doctor_id,date,get_doctor_database: Session,medicine_database : Session): """Function to get appointment details based on appointment id generated while booking new appointment""" - print(f"patient_id {patient_id}") - db_patient_id = patientDatabase.query(patientModels.Patient).filter(patientModels.Patient.id == int(patient_id)).first() - if not db_patient_id: - return ResponseData.success_without_data("Patient id is invalid") - if date == "": - db_appointment = database.query(models.Appointment).filter(models.Appointment.patient_id == patient_id).all() + if doctor_id == "": + db_patient_id = patientDatabase.query(patientModels.Patient).filter(patientModels.Patient.id == patient_id).first() + if not db_patient_id: + return ResponseData.error("Patient id is invalid") + if date == "": + db_appointment = database.query(models.Appointment).filter(models.Appointment.patient_id == patient_id).all() + else: + db_appointment = database.query(models.Appointment).filter(models.Appointment.patient_id == patient_id,models.Appointment.appointment_date == date).all() + if len(db_appointment) == 0 and date == "": + return ResponseData.success([],"No appointment found for this patient") + if len(db_appointment) == 0 and date != "": + return ResponseData.success([],"No appointment found for this date") else: - db_appointment = database.query(models.Appointment).filter(models.Appointment.patient_id == patient_id,models.Appointment.appointment_date == date).all() - if len(db_appointment) == 0 and date == "": - return ResponseData.success([],"No appointment found for this patient") - if len(db_appointment) == 0 and date != "": - return ResponseData.success([],"No appointment found for this date") - db_doctor = get_doctor_database.query(doctorModels.DoctorDetails,doctorModels.Doctor).filter(doctorModels.Doctor.id == db_appointment[0].doctor_id).first() - if db_doctor is not None: - dict1 = db_doctor["DoctorDetails"] - dict2 = db_doctor["Doctor"] - dict1.__dict__.update(dict2.__dict__) - print(f"dict2.__dict__ {dict1.__dict__}") - for i in range(0,len(db_appointment)): - db_appointment[i].__dict__["doctor_data"] = dict1.__dict__ - db_appointment[i].__dict__.pop("doctor_id") - # Merge(db_doctor.__dict__,db_appointment.__dict__) + db_doctor_id = get_doctor_database.query(doctorModels.Doctor).filter(doctorModels.Doctor.id == int(doctor_id)).first() + if not db_doctor_id: + return ResponseData.error("Doctor id is invalid") + if date == "": + db_appointment = database.query(models.Appointment).filter(models.Appointment.doctor_id == doctor_id).all() + else: + db_appointment = database.query(models.Appointment).filter(models.Appointment.doctor_id == doctor_id,models.Appointment.appointment_date == date).all() + if len(db_appointment) == 0 and date == "": + return ResponseData.success([],"No appointment found for this patient") + if len(db_appointment) == 0 and date != "": + return ResponseData.success([],"No appointment found for this date") + for i in range(0,len(db_appointment)): + db_doctor = get_doctor_database.query(doctorModels.DoctorDetails,doctorModels.Doctor).filter(doctorModels.Doctor.id == doctorModels.DoctorDetails.id,doctorModels.Doctor.id == db_appointment[i].doctor_id).first() + if db_doctor is not None: + dict1 = db_doctor["DoctorDetails"] + dict2 = db_doctor["Doctor"] + dict1.__dict__.update(dict2.__dict__) + print(f"dict2.__dict__ {dict1.__dict__}") + db_appointment[i].__dict__["doctor_data"] = dict1.__dict__ + db_appointment[i].__dict__.pop("doctor_id") + db_patient_report = patient_report_database.query(PatientReportModels.PatientReport).filter(PatientReportModels.PatientReport.appointment_id == str(db_appointment[i].__dict__["id"])).first() + if db_patient_report: + db_appointment[i].__dict__["patient_report_data"] = db_patient_report.__dict__ + # else: + # db_appointment[i].__dict__["patient_report_data"] = db_patient_report.__dict__ + db_patient_updated_report_medicine_details = patient_report_database.query(PatientReportModels.PatientReportMedicineDetails).filter().all() + for j in range(0,len(db_patient_updated_report_medicine_details)): + print(f'db_patient_updated_report_medicine_details[i].__dict__["medicine_id"] {db_patient_updated_report_medicine_details[j].__dict__["medicine_id"]}') + medicine_name = medicine_database.query(medicineModels.Medicine).filter((medicineModels.Medicine.id == int(db_patient_updated_report_medicine_details[j].__dict__["medicine_id"]))).first() + if not medicine_name: + return ResponseData.error("medicine id is invalid") + db_patient_updated_report_medicine_details[j].__dict__["medicine_name"] = medicine_name.name + db_patient_updated_report_medicine_details[j].__dict__.pop("medicine_id") + if db_patient_report: + db_appointment[i].__dict__["patient_report_data"]["medicine_details"] = db_patient_updated_report_medicine_details return ResponseData.success(db_appointment,"Appointment details fetched successfully") def get_appointment_by_date(database: Session,date,get_doctor_database: Session): """Function to get appointment details based on appointment id generated while booking new appointment""" db_appointment = database.query(models.Appointment).filter(models.Appointment.appointment_date == date).all() if len(db_appointment) == 0: - return ResponseData.success([],"patient id is invalid") + return ResponseData.error("patient id is invalid") db_doctor = get_doctor_database.query(doctorModels.DoctorDetails,doctorModels.Doctor).filter(doctorModels.Doctor.id == db_appointment[0].doctor_id).first() if db_doctor is not None: dict1 = db_doctor["DoctorDetails"] @@ -122,13 +159,16 @@ def delete_appointment_details(database: Session, id : Optional[int] = None): def update_fields(actualDict,key,value): if key != '' or key is not None: actualDict[f"{key}"] = value -def update_appointment_details(database: Session,get_doctor_database: Session, first_name: str, last_name: str, mobile_number: str,booking_time: str, +def update_appointment_details(database: Session,patient_report_database: Session,get_doctor_database: Session, medicine_database: Session,first_name: str, last_name: str, mobile_number: str,booking_time: str, status_id: str, hospital_id: str, - patient_id: str, doctor_id: str,staff_id: str,file : UploadFile,profile_pic: UploadFile, appointment_id: Integer,time_slot: str,appointment_date: str): + patient_id: str, doctor_id: str,staff_id: str,file : UploadFile,profile_pic: UploadFile, report_description:str,medicine_id:str,patient_report_file:str,appointment_id: Integer,time_slot: str,appointment_date: str): """Function to update appointment details""" db_appointment = database.query(models.Appointment).filter(models.Appointment.id == appointment_id).first() if db_appointment is None: return ResponseData.success_without_data("Appointment with this id does not exists") + status = database.query(models.AppointmentStatus).filter(models.AppointmentStatus.a_id == int(status_id)).first() + if not status: + return ResponseData.success_without_data("Status with this id does not exists") dict1 = { "first_name": first_name if first_name != "" else db_appointment.first_name, "last_name": last_name if last_name != "" else db_appointment.last_name, @@ -164,7 +204,79 @@ def update_appointment_details(database: Session,get_doctor_database: Session, f database.flush() database.commit() db_appointment_updated = database.query(models.Appointment).filter(models.Appointment.id == appointment_id).first() + db_patient_report_details = patient_report_database.query(PatientReportModels.PatientReport).filter(PatientReportModels.PatientReport.appointment_id == str(appointment_id)).first() + if not db_patient_report_details: + patientreportdata = { + "patient_id": db_appointment_updated.patient_id, + "report_description": report_description, + "doctor_id": db_appointment_updated.doctor_id, + "hospital_id": db_appointment_updated.hospital_id, + "appointment_id" : db_appointment_updated.id + } + db_patient_report = PatientReportModels.PatientReport(**patientreportdata) + patient_report_database.add(db_patient_report) + patient_report_database.commit() + patient_report_database.refresh(db_patient_report) + medicine_list = medicine_id.split(",") + patientreportmedicinedata = { + "patient_id": db_appointment_updated.patient_id, + "medicine_id": "", + } + print(f"medicine_list {medicine_list}") + for i in range(0,len(medicine_list)): + patientreportmedicinedata["medicine_id"] = medicine_list[i], + db_patient_report_medicine_data = patient_report_database.query(PatientReportModels.PatientReportMedicineDetails).filter(PatientReportModels.PatientReportMedicineDetails.medicine_id == medicine_list[i]).first() + if not db_patient_report_medicine_data: + db_patient_report_medicine_details = PatientReportModels.PatientReportMedicineDetails(**patientreportmedicinedata) + patient_report_database.add(db_patient_report_medicine_details) + patient_report_database.commit() + patient_report_database.refresh(db_patient_report_medicine_details) + else: + dict2 = { + "patient_id": patient_id if patient_id != "" else db_patient_report_details.patient_id, + "report_description": report_description if report_description != "" else db_patient_report_details.report_description, + "doctor_id": doctor_id if doctor_id != "" else db_patient_report_details.doctor_id, + "hospital_id": hospital_id if hospital_id != "" else db_patient_report_details.hospital_id, + } + for key,value in dict2.items(): + update_fields(dict2,key,value) + patient_report_database.query(PatientReportModels.PatientReport).filter(PatientReportModels.PatientReport.id == db_patient_report_details.id).update({PatientReportModels.PatientReport.id : db_patient_report_details.id, + PatientReportModels.PatientReport.patient_id: dict2["patient_id"], + PatientReportModels.PatientReport.report_description: dict2["report_description"], + PatientReportModels.PatientReport.doctor_id: dict2["doctor_id"], + PatientReportModels.PatientReport.hospital_id: dict2["hospital_id"], + }) + patient_report_database.flush() + patient_report_database.commit() + medicine_list = medicine_id.split(",") + patient_report_database.query(PatientReportModels.PatientReportMedicineDetails).delete() + for i in range(0,len(medicine_list)): + dict3 = { + "patient_id": patient_id if patient_id != "" else db_patient_report_details.patient_id, + } + for key,value in dict3.items(): + update_fields(dict3,key,value) + patientreportmedicinedata = { + "patient_id": db_appointment_updated.patient_id, + "medicine_id": medicine_list[i], + } + db_patient_report_medicine_details = PatientReportModels.PatientReportMedicineDetails(**patientreportmedicinedata) + patient_report_database.add(db_patient_report_medicine_details) + patient_report_database.commit() + patient_report_database.refresh(db_patient_report_medicine_details) + db_patient_updated_report_details = patient_report_database.query(PatientReportModels.PatientReport).filter(PatientReportModels.PatientReport.appointment_id == str(appointment_id)).first() + db_appointment_updated.__dict__["patient_report_data"] = db_patient_updated_report_details.__dict__ + db_patient_updated_report_medicine_details = patient_report_database.query(PatientReportModels.PatientReportMedicineDetails).filter().all() + for i in range(0,len(db_patient_updated_report_medicine_details)): + print(f'db_patient_updated_report_medicine_details[i].__dict__["medicine_id"] {db_patient_updated_report_medicine_details[i].__dict__["medicine_id"]}') + medicine_name = medicine_database.query(medicineModels.Medicine).filter((medicineModels.Medicine.id == int(db_patient_updated_report_medicine_details[i].__dict__["medicine_id"]))).first() + if not medicine_name: + return ResponseData.error("medicine id is invalid") + db_patient_updated_report_medicine_details[i].__dict__["medicine_name"] = medicine_name.name + db_patient_updated_report_medicine_details[i].__dict__.pop("medicine_id") + db_appointment_updated.__dict__["patient_report_data"]["medicine_details"] = db_patient_updated_report_medicine_details db_doctor = get_doctor_database.query(doctorModels.DoctorDetails,doctorModels.Doctor).filter(doctorModels.Doctor.id == db_appointment_updated.doctor_id).first() + print(f"db_doctor {db_doctor}") if db_doctor is not None: dict1 = db_doctor["DoctorDetails"] dict2 = db_doctor["Doctor"] @@ -174,9 +286,9 @@ def update_appointment_details(database: Session,get_doctor_database: Session, f return ResponseData.success(db_appointment_updated,"Appointment details updated successfully") -def add_new_appointment_status(database: Session, appointment_status: schemas.AppointmentStatusBase): +def add_new_appointment_status(database: Session, appointment_status): """Function to return query based data while creating new appointment status creation api""" - appointment_status_dict = {'status': appointment_status.dict()["status"]} + appointment_status_dict = {'status': appointment_status} db_appointment_status = models.AppointmentStatus(**appointment_status_dict) database.add(db_appointment_status) database.commit() @@ -186,15 +298,15 @@ def add_new_appointment_status(database: Session, appointment_status: schemas.Ap db_appointment_status.__dict__["a_id"] = db_appointment_status.a_id return ResponseData.success(db_appointment_status.__dict__,"Appointment status added successfully") -def get_appointment_status_by_id_or_without_id(database: Session, a_id : Optional[int] = None): +def get_appointment_status_by_id_or_without_id(database: Session, id): """Function to get appointment status details""" - if a_id is None: + if id == "": db_appointment_status_details = database.query(models.AppointmentStatus).filter().all() - return ResponseData.success(db_appointment_status_details.__dict__,"Appointment status details fetched successfully") - db_appointment_status = database.query(models.AppointmentStatus).filter(models.AppointmentStatus.a_id == a_id).first() + return ResponseData.success(db_appointment_status_details,"Appointment status details fetched successfully") + db_appointment_status = database.query(models.AppointmentStatus).filter(models.AppointmentStatus.a_id == id).first() if db_appointment_status is None: return ResponseData.success([],"Appointment status id is invalid") - db_appointment_status_details = database.query(models.AppointmentStatus).filter(models.AppointmentStatus.a_id == a_id).first() + db_appointment_status_details = database.query(models.AppointmentStatus).filter(models.AppointmentStatus.a_id == id).first() return ResponseData.success(db_appointment_status_details.__dict__,"Appointment status details fetched successfully") def delete_appointment_status(database: Session, a_id : Optional[int] = None): diff --git a/appointment/app/appointment_files/CS_ OUT ON HIRE.pdf b/appointment/app/appointment_files/CS_ OUT ON HIRE.pdf new file mode 100644 index 0000000..7b87403 Binary files /dev/null and b/appointment/app/appointment_files/CS_ OUT ON HIRE.pdf differ diff --git a/appointment/app/appointment_files/IMG_20220805_134049.jpg b/appointment/app/appointment_files/IMG_20220805_134049.jpg new file mode 100644 index 0000000..b81fd07 Binary files /dev/null and b/appointment/app/appointment_files/IMG_20220805_134049.jpg differ diff --git a/doctor/app/api/controller.py b/doctor/app/api/controller.py index f9d662a..5caf657 100644 --- a/doctor/app/api/controller.py +++ b/doctor/app/api/controller.py @@ -1,13 +1,20 @@ """Controller file for writing db queries""" +from datetime import datetime +import math +import random from typing import Optional -from fastapi import UploadFile +from fastapi import HTTPException, UploadFile from sqlalchemy import Integer from sqlalchemy.orm import Session from doctor.app.error_handling import Error from doctor.app.response import Response as ResponseData from doctor.app.models import models +from jwt_utility import JWTUtility from patient.app.models import models as patientModels - +from patient.email_manager import EmailManager +# from hospital.app.api.controller import check_if_hospital_id_is_valid +from patient.app.api.controller import check_if_patient_id_is_valid +# from staff.app.api.controller import check_if_staff_id_is_valid # Python code to merge dict using update() method def Merge(dict1, dict2): @@ -23,9 +30,9 @@ def check_if_doctor_id_is_valid(database: Session, id : Optional[int] = None): return False def add_new_doctor(database: Session,file: UploadFile, first_name: str, last_name: str, contact_number: str, - email: str, gender: str, + email: str,password:str, gender: str, date_of_birth: str, blood_group: str, - years_of_experience: str,next_available_at: str, specialist_field: str, education: str,about : str, + years_of_experience: str,next_available_at: str, specialist_field: str, education: str,about : str,hospital_id:str, in_clinic_appointment_fees: str,rating:str): """Function to add new doctor data""" # db_doctor_email = database.query(models.Doctor).filter(models.Doctor.email == email).first() @@ -38,9 +45,11 @@ def add_new_doctor(database: Session,file: UploadFile, first_name: str, last_nam "contact_number": contact_number, "profile_pic" : f'doctor/app/doctor_images/{file}' if file != "" else "", "email": email, + "password" : password, "gender": gender, "date_of_birth": date_of_birth, "blood_group": blood_group, + "hospital_id" : hospital_id } db_doctor = models.Doctor(**doctordata) database.add(db_doctor) @@ -67,22 +76,47 @@ def get_doctor(database: Session, contact_number : str): """Function to tell user if doctor with given contact number already exists or not""" return database.query(models.Doctor).filter(models.Doctor.contact_number == contact_number).first() -def get_doctor_by_id(database: Session,patientDatabase: Session,specialist_field): +def get_doctor_by_id(database: Session,patientDatabase: Session,specialist_field,doctor_id): """Function to tell user if doctor with given contact number already exists or not""" - if specialist_field == "": + is_doctor_id = False + if specialist_field == "" and doctor_id != "": + is_doctor_id = True + data = database.query(models.DoctorDetails,models.Doctor).filter(models.Doctor.id == doctor_id,models.Doctor.id == models.DoctorDetails.id).first() + elif specialist_field == "": data = database.query(models.DoctorDetails,models.Doctor).filter(models.Doctor.id == models.DoctorDetails.id).all() else: data = database.query(models.DoctorDetails,models.Doctor).filter(models.Doctor.id == models.DoctorDetails.id,models.DoctorDetails.specialist_field == specialist_field).all() list = [] - if(len(data) > 0): - for i, ele in enumerate(data): - dict1 = ele["DoctorDetails"] - dict2 = ele["Doctor"] - # dict3 = ele["PatientCommentDetails"] + if is_doctor_id and data is not None: + dict1 = data["DoctorDetails"] + dict2 = data["Doctor"] dict1.__dict__.update(dict2.__dict__) - # dict1.__dict__["Feedback"] = ele["PatientCommentDetails"] - list.append(dict1) - for i, ele in enumerate(list): + feedback_data = database.query(models.PatientCommentDetails).filter(models.PatientCommentDetails.doctor_id == str(dict1.__dict__["id"])).all() + if len(feedback_data) > 0: + for j, ele1 in enumerate(feedback_data): + db_patient = patientDatabase.query(patientModels.Patient).filter(patientModels.Patient.id == int(ele1.__dict__["patient_id"])).first() + if db_patient is not None: + ele1.__dict__["patient_id"] = db_patient.id + ele1.__dict__["patient_name"] = db_patient.first_name + feedback_data[j].__dict__.pop("doctor_id") + feedback_data[j].__dict__.pop("staff_id") + feedback_data[j].__dict__.pop("patient_id") + feedback_data[j].__dict__.pop("hospital_id") + dict1.__dict__["feedbacks"] = feedback_data + else: + dict1.__dict__["feedbacks"] = [] + return ResponseData.success(dict1.__dict__,"Doctor details fetched successfully") + # list.append(dict1) + elif (data is not None): + if(len(data) > 0): + for i, ele in enumerate(data): + dict1 = ele["DoctorDetails"] + dict2 = ele["Doctor"] + # dict3 = ele["PatientCommentDetails"] + dict1.__dict__.update(dict2.__dict__) + # dict1.__dict__["Feedback"] = ele["PatientCommentDetails"] + list.append(dict1) + for i, ele in enumerate(list): feedback_data = database.query(models.PatientCommentDetails).filter(models.PatientCommentDetails.doctor_id == str(ele.__dict__["id"])).all() if len(feedback_data) > 0: for j, ele1 in enumerate(feedback_data): @@ -148,6 +182,12 @@ def add_feeback_of_doctor(database: Session,patientDatabase: Session, comment : staff_id : Optional[str] = None,doctor_id : Optional[str] = None, hospital_id : Optional[str] = None): """Function to add doctor's feedback""" + # if not check_if_hospital_id_is_valid(database,hospital_id): + # raise HTTPException(status_code=400, detail="Hospital id is invalid") + if not check_if_patient_id_is_valid(patientDatabase,patient_id): + raise HTTPException(status_code=400, detail="Patient id is invalid") + if not check_if_doctor_id_is_valid(database,doctor_id): + raise HTTPException(status_code=400, detail="Doctor id is invalid") feedback_data = { "comment" : comment, "rating" : rating, @@ -182,10 +222,10 @@ def update_fields(actualDict,key,value): if key != '' or key is not None: actualDict[f"{key}"] = value -def update_doctor_details(database: Session,file: UploadFile, first_name: str, last_name: str, contact_number: str, - email: str, gender: str, +def update_doctor_details(database: Session,patientDatabase: Session,file: UploadFile, first_name: str, last_name: str, contact_number: str, + email: str,gender: str, date_of_birth: str, blood_group: str, - years_of_experience: str,next_available_at: str, specialist_field: str, education: str,about : str, + years_of_experience: str,next_available_at: str, specialist_field: str, education: str,about : str,hospital_id:str, in_clinic_appointment_fees: str,rating:str, doctor_id: Integer): """Function to update doctor details""" db_doctor = database.query(models.Doctor).filter(models.Doctor.id == doctor_id).first() @@ -195,11 +235,13 @@ def update_doctor_details(database: Session,file: UploadFile, first_name: str, l "first_name": first_name if first_name != "" else db_doctor.first_name, "last_name": last_name if last_name != "" else db_doctor.last_name, "contact_number": contact_number if contact_number != "" else db_doctor.contact_number, - 'profile_pic' : f"patient/app/patient_images/{file}" if file != "" else f"{db_doctor.profile_pic}", + 'profile_pic' : f"doctor/app/doctor_images/{file}" if file != "" else f"{db_doctor.profile_pic}", "email": email if email != "" else db_doctor.email, +# "password": password if password != "" else db_doctor.password, "gender": gender if gender != "" else db_doctor.gender, "date_of_birth": date_of_birth if date_of_birth != "" else db_doctor.date_of_birth, "blood_group": blood_group if blood_group != "" else db_doctor.blood_group, + "hospital_id": hospital_id if hospital_id != "" else db_doctor.hospital_id, } for key,value in dict2.items(): update_fields(dict2,key,value) @@ -212,7 +254,7 @@ def update_doctor_details(database: Session,file: UploadFile, first_name: str, l "about": about if about != "" else db_doctor_details.about, "in_clinic_appointment_fees": in_clinic_appointment_fees if in_clinic_appointment_fees != "" else db_doctor_details.in_clinic_appointment_fees, "create_at" : "", - "rating" : rating if rating != "" else db_doctor_details.rating, +# "rating" : rating if rating != "" else db_doctor_details.rating, } database.query(models.Doctor).filter(models.Doctor.id == doctor_id).update({ models.Doctor.id : doctor_id, models.Doctor.first_name: dict2["first_name"], @@ -220,6 +262,8 @@ def update_doctor_details(database: Session,file: UploadFile, first_name: str, l models.Doctor.contact_number : dict2["contact_number"], models.Doctor.profile_pic : dict2["profile_pic"], models.Doctor.email : dict2["email"], + # models.Doctor.password : dict2["password"], + models.Doctor.hospital_id : dict2["hospital_id"], models.Doctor.gender : dict2["gender"], models.Doctor.date_of_birth : dict2["date_of_birth"], models.Doctor.blood_group : dict2["blood_group"] @@ -233,8 +277,123 @@ def update_doctor_details(database: Session,file: UploadFile, first_name: str, l models.DoctorDetails.about : dict1["about"], models.DoctorDetails.in_clinic_appointment_fees : dict1["in_clinic_appointment_fees"], models.DoctorDetails.create_at : dict1["create_at"], - models.DoctorDetails.rating : dict1["rating"], + # models.DoctorDetails.rating : dict1["rating"], }) database.flush() database.commit() - return ResponseData.success_without_data("Doctor details updated successfully") \ No newline at end of file + data = database.query(models.DoctorDetails,models.Doctor).filter(models.Doctor.id == doctor_id,models.Doctor.id == models.DoctorDetails.id).first() + dict1 = data["DoctorDetails"] + dict2 = data["Doctor"] + # dict3 = ele["PatientCommentDetails"] + dict1.__dict__.update(dict2.__dict__) + # dict1.__dict__["Feedback"] = ele["PatientCommentDetails"] + feedback_data = database.query(models.PatientCommentDetails).filter(models.PatientCommentDetails.doctor_id == str(dict1.__dict__["id"])).all() + if len(feedback_data) > 0: + for j, ele1 in enumerate(feedback_data): + print(f'ele1.__dict__["patient_id"] {ele1.__dict__["patient_id"]}') + db_patient = patientDatabase.query(patientModels.Patient).filter(patientModels.Patient.id == int(ele1.__dict__["patient_id"])).first() + print(f"db_patient {db_patient}") + if db_patient is not None: + ele1.__dict__["patient_id"] = db_patient.id + ele1.__dict__["patient_name"] = db_patient.first_name + feedback_data[j].__dict__.pop("doctor_id") + feedback_data[j].__dict__.pop("staff_id") + feedback_data[j].__dict__.pop("patient_id") + feedback_data[j].__dict__.pop("hospital_id") + dict1.__dict__["feedbacks"] = feedback_data + else: + dict1.__dict__["feedbacks"] = [] + return ResponseData.success(dict1.__dict__,"Doctor details updated successfully") + +async def doctor_forget_password(database: Session, email : Optional[str] = None): + """Function to tell user if doctor with given contact number already exists or not""" + db_doctor_email = database.query(models.Doctor).filter(models.Doctor.email == email).first() + if not db_doctor_email: + return ResponseData.success_without_data("Email id is invalid") + digits = "0123456789" + OTP = "" + for i in range(6): + OTP += digits[math.floor(random.random() * 10)] + otp = list(OTP) + if otp[0] == "0": + otp[0] = "1" + OTP = "" + for i in range(0,len(otp)): + OTP+=otp[i] + template = ''' + + +
+ +Your otp is {0}
+ + + +'''.format(OTP) + print("sdds") + await EmailManager().forgot_password( + email, + "Forgot Password", + template + ), + db_patient_otp = database.query(models.Doctor_Otp_For_Password).filter(models.Doctor_Otp_For_Password.doctor_id == db_doctor_email.id).first() + if db_patient_otp: + database.query(models.Doctor_Otp_For_Password).filter(db_patient_otp.doctor_id == db_doctor_email.id).update({ + models.Doctor_Otp_For_Password.doctor_id : db_doctor_email.id, + models.Doctor_Otp_For_Password.otp: OTP, + models.Doctor_Otp_For_Password.updated_at: str(datetime.now()), + }) + database.flush() + database.commit() + else: + doctor_data = { + "doctor_id" : db_doctor_email.id, + "otp" : OTP, + "created_at" : str(datetime.now()) + } + db_doctor = models.Doctor_Otp_For_Password(**doctor_data) + database.add(db_doctor) + database.commit() + database.refresh(db_doctor) + return ResponseData.success_without_data("Otp has been successfully sent on doctor's email address") + + +def reset_password_for_doctor(database: Session, otp : str,new_password : str): + """Function to reset password for a particular doctor""" + doctor_otp_data = database.query(models.Doctor_Otp_For_Password).filter(models.Doctor_Otp_For_Password.otp == otp).first() + if not doctor_otp_data: + return ResponseData.failure_without_data("Otp entered is invalid") + fmt = '%Y-%m-%d %H:%M:%S' + current_date = datetime.strptime(str(datetime.now()).split(".")[0],fmt) + if doctor_otp_data.updated_at is not None: + otp_generated_date = datetime.strptime(str(doctor_otp_data.updated_at).split(".")[0],fmt) + else: + otp_generated_date = datetime.strptime(str(doctor_otp_data.created_at).split(".")[0],fmt) + diff = current_date - otp_generated_date + if diff.seconds > 60 : + database.query(models.Doctor_Otp_For_Password).filter(models.Doctor_Otp_For_Password.doctor_id == doctor_otp_data.doctor_id).delete() + database.commit() + return ResponseData.success_without_data("Entered otp is expired or is invalid") + database.query(models.Doctor).filter(models.Doctor.id == doctor_otp_data.doctor_id).update({ + models.Doctor.password : new_password, + }) + database.flush() + database.commit() + return ResponseData.success_without_data("Password has been updated successfully") + +def doctor_sign_in_api(database: Session,email : Optional[str] = None,password : Optional[str] = None): + """Function to sign in a doctor""" + db_doctor = database.query(models.Doctor).filter(models.Doctor.email == email,models.Doctor.password == password).first() + if not db_doctor: + return ResponseData.error("Credentials are invalid") + db_doctor_details = database.query(models.Doctor).filter(models.Doctor.email == email).first() + token = { + 'authentication_token' : JWTUtility.encode_token(db_doctor_details.email,db_doctor_details.contact_number) + } + Merge(token, db_doctor_details.__dict__) + if db_doctor_details.__dict__["hospital_id"] is None: + db_doctor_details.__dict__["hospital_id"] = "" + db_doctor_details.__dict__.pop("password") + return ResponseData.success(db_doctor_details.__dict__,"Doctor signed in successfully") diff --git a/doctor/app/api/doctor_route.py b/doctor/app/api/doctor_route.py index d40f7cf..724fab0 100644 --- a/doctor/app/api/doctor_route.py +++ b/doctor/app/api/doctor_route.py @@ -25,10 +25,10 @@ async def create_file(file=File(None)): async def add_doctor( first_name: str = Form(), last_name: str = Form(), contact_number: str = Form(), - email: str = Form(),profile_pic: UploadFile = Form(default = None), gender: str = Form(), + email: str = Form(),password: str = Form(),profile_pic: UploadFile = Form(default = None), gender: str = Form(), date_of_birth: str = Form(default=''), blood_group: str = Form(), years_of_experience: str = Form(default=''),next_available_at: str = Form(default=''), specialist_field: str = Form(default=''), - education: str = Form(default=''),about: str = Form(default=''), + education: str = Form(default=''),about: str = Form(default=''),hospital_id: str = Form(default=''), in_clinic_appointment_fees: str = Form(default=''),rating: str = Form(default=''),database: Session = Depends(get_db)): """Function to return final response while adding new doctor details""" filename = "" @@ -40,7 +40,7 @@ async def add_doctor( # if db_doctor: # raise HTTPException(status_code=400, detail="Doctor already registered with same contact number") return controller.add_new_doctor(database,filename, first_name, last_name, - contact_number, email,gender,date_of_birth,blood_group,years_of_experience,next_available_at,specialist_field,education,about,in_clinic_appointment_fees,rating ) + contact_number, email,password,gender,date_of_birth,blood_group,years_of_experience,next_available_at,specialist_field,education,about,hospital_id,in_clinic_appointment_fees,rating ) @doctor_router.post("/get_doctor_details") @@ -48,7 +48,9 @@ async def get_doctor(request: Request,database: Session = Depends(get_db),patien """Function to return doctor details (specific and all doctor data can be fetched)""" request_json = await request.json() - return controller.get_doctor_by_id(database,patientDatabase,request_json["specialist_field"]) + if 'specialist_field' not in request_json: + return controller.get_doctor_by_id(database,patientDatabase,"",request_json["id"]) + return controller.get_doctor_by_id(database,patientDatabase,request_json["specialist_field"],"") @doctor_router.post("/get_doctor_filter") async def get_doctor_filter(request: Request,database: Session = Depends(get_db),patientDatabase: Session = Depends(get_patient_db)): @@ -80,20 +82,41 @@ async def update_doctor_detail(request: Request,doctor_id: str = Form(),first_na email: str = Form(default=''),profile_pic: UploadFile = File(None), gender: str = Form(default=''), date_of_birth: str = Form(default=''), blood_group: str = Form(default=''), years_of_experience: str = Form(default=''),next_available_at: str = Form(default=''), specialist_field: str = Form(default=''), - education: str = Form(default=''),about: str = Form(default=''), - in_clinic_appointment_fees: str = Form(default=''),rating: str = Form(default=''),database: Session = Depends(get_db)): + education: str = Form(default=''),about: str = Form(default=''),hospital_id: str = Form(default=''), + in_clinic_appointment_fees: str = Form(default=''),rating: str = Form(default=''),database: Session = Depends(get_db),patientDatabase: Session = Depends(get_patient_db)): """Function to update particular doctor details""" # Authentication().authenticate(request.headers.get('Authorization'),db) filename = "" if profile_pic is not None: filename = profile_pic.filename await create_file(profile_pic) - return controller.update_doctor_details(database,filename, first_name, last_name, - contact_number, email,gender,date_of_birth,blood_group,years_of_experience,next_available_at,specialist_field,education,about,in_clinic_appointment_fees,rating,doctor_id) + return controller.update_doctor_details(database,patientDatabase,filename, first_name, last_name, + contact_number, email,gender,date_of_birth,blood_group,years_of_experience,next_available_at,specialist_field,education,about,hospital_id,in_clinic_appointment_fees,rating,doctor_id) @doctor_router.post("/add_doctor_feedback") async def add_doctor_feedback(request: Request,database: Session = Depends(get_db),patientDatabase: Session = Depends(get_patient_db)): """Function to add doctor feedback""" request_json = await request.json() return controller.add_feeback_of_doctor(database,patientDatabase,comment = request_json["comment"],rating = request_json["rating"],patient_id = request_json["patient_id"], - staff_id = request_json["staff_id"],doctor_id = request_json["doctor_id"],hospital_id = request_json["hospital_id"],) \ No newline at end of file + staff_id = request_json["staff_id"],doctor_id = request_json["doctor_id"],hospital_id = request_json["hospital_id"],) + + +import asyncio + +@doctor_router.post("/forget_password") +def forgot_password(request: Request,email: schemas.DoctorEmail,database: Session = Depends(get_db)): + """Function to send activation link on email id""" + return asyncio.run(controller.doctor_forget_password(database, email = email.email)) + +@doctor_router.post("/doctor_sign_in") +async def sign_in_doctor(request: Request, database: Session = Depends(get_db)): + """Function to sign in patient""" + request_json = await request.json() + return controller.doctor_sign_in_api(database, email = request_json["email"],password = request_json["password"]) + +@doctor_router.post("/doctor_reset_password") +async def doctor_reset_password(request: Request, database: Session = Depends(get_db)): + """Function to return patient details + (specific and all patient data can be fetched)""" + request_json = await request.json() + return controller.reset_password_for_doctor(database,otp=request_json["otp"],new_password=request_json["new_password"]) \ No newline at end of file diff --git a/doctor/app/doctor_images/MicrosoftTeams-image (35).png b/doctor/app/doctor_images/MicrosoftTeams-image (35).png new file mode 100644 index 0000000..22f14e8 Binary files /dev/null and b/doctor/app/doctor_images/MicrosoftTeams-image (35).png differ diff --git a/doctor/app/doctor_images/MicrosoftTeams-image (36).png b/doctor/app/doctor_images/MicrosoftTeams-image (36).png new file mode 100644 index 0000000..f4abda7 Binary files /dev/null and b/doctor/app/doctor_images/MicrosoftTeams-image (36).png differ diff --git a/doctor/app/doctor_images/MicrosoftTeams-image (37).png b/doctor/app/doctor_images/MicrosoftTeams-image (37).png new file mode 100644 index 0000000..b3a9a44 Binary files /dev/null and b/doctor/app/doctor_images/MicrosoftTeams-image (37).png differ diff --git a/doctor/app/doctor_images/MicrosoftTeams-image (38).png b/doctor/app/doctor_images/MicrosoftTeams-image (38).png new file mode 100644 index 0000000..c574653 Binary files /dev/null and b/doctor/app/doctor_images/MicrosoftTeams-image (38).png differ diff --git a/doctor/app/doctor_images/MicrosoftTeams-image (39).png b/doctor/app/doctor_images/MicrosoftTeams-image (39).png new file mode 100644 index 0000000..1914b16 Binary files /dev/null and b/doctor/app/doctor_images/MicrosoftTeams-image (39).png differ diff --git a/doctor/app/doctor_images/MicrosoftTeams-image (40).png b/doctor/app/doctor_images/MicrosoftTeams-image (40).png new file mode 100644 index 0000000..0388bef Binary files /dev/null and b/doctor/app/doctor_images/MicrosoftTeams-image (40).png differ diff --git a/doctor/app/doctor_images/MicrosoftTeams-image (41).png b/doctor/app/doctor_images/MicrosoftTeams-image (41).png new file mode 100644 index 0000000..00afeb4 Binary files /dev/null and b/doctor/app/doctor_images/MicrosoftTeams-image (41).png differ diff --git a/doctor/app/doctor_images/scaled_38ecbc0a-c9f1-4147-893f-2bf80ff26bfa4968218195350166919.jpg b/doctor/app/doctor_images/scaled_38ecbc0a-c9f1-4147-893f-2bf80ff26bfa4968218195350166919.jpg new file mode 100644 index 0000000..bd0e56b Binary files /dev/null and b/doctor/app/doctor_images/scaled_38ecbc0a-c9f1-4147-893f-2bf80ff26bfa4968218195350166919.jpg differ diff --git a/doctor/app/doctor_images/scaled_82b5d344-4047-4baa-bbe3-a2517ee60bb91251654362374482091.jpg b/doctor/app/doctor_images/scaled_82b5d344-4047-4baa-bbe3-a2517ee60bb91251654362374482091.jpg new file mode 100644 index 0000000..bfa4ef5 Binary files /dev/null and b/doctor/app/doctor_images/scaled_82b5d344-4047-4baa-bbe3-a2517ee60bb91251654362374482091.jpg differ diff --git a/doctor/app/doctor_images/scaled_b4edee09-76c5-443b-9f9b-ecca192915398959856493916930364.jpg b/doctor/app/doctor_images/scaled_b4edee09-76c5-443b-9f9b-ecca192915398959856493916930364.jpg new file mode 100644 index 0000000..24a5e77 Binary files /dev/null and b/doctor/app/doctor_images/scaled_b4edee09-76c5-443b-9f9b-ecca192915398959856493916930364.jpg differ diff --git a/doctor/app/models/models.py b/doctor/app/models/models.py index 1cebaf3..37ca5de 100644 --- a/doctor/app/models/models.py +++ b/doctor/app/models/models.py @@ -14,12 +14,14 @@ class Doctor(Base): id = Column(Integer, primary_key=True, index=True) first_name = Column(String, index=True) last_name = Column(String, index=True) + password = Column(String, index=True) contact_number = Column(String, index=True) profile_pic = Column(String, index=True) email = Column(String, index=True) gender = Column(String, index=True) date_of_birth = Column(String, index=True) blood_group = Column(String, index=True) + hospital_id = Column(String,index = True) class DoctorDetails(Base): """Class for creating doctor details model""" @@ -43,4 +45,12 @@ class PatientCommentDetails(Base): patient_id = Column(String, index=True) staff_id = Column(String, index=True) hospital_id = Column(String, index=True) - \ No newline at end of file + +class Doctor_Otp_For_Password(Base): + """Class for creating doctor otp for password model""" + __tablename__ = 'doctor_otp_for_password' + id = Column(Integer, primary_key=True, index=True) + doctor_id = Column(Integer, index=True) + otp = Column(String, index=True) + created_at = Column(String,index=True) + updated_at = Column(String,index=True) \ No newline at end of file diff --git a/doctor/app/models/schemas.py b/doctor/app/models/schemas.py index 165989f..3b0d3d4 100644 --- a/doctor/app/models/schemas.py +++ b/doctor/app/models/schemas.py @@ -14,6 +14,7 @@ class DoctorBase(BaseModel): contact_number: Optional[str] = None profile_pic: Optional[bytes] = File(None) email: Optional[str] = None + password: Optional[str] = None blood_group: Optional[str] = None gender: Optional[str] = None date_of_birth: Optional[str] = None @@ -47,6 +48,7 @@ class AddNewDoctor(DoctorBase): contact_number: Optional[str] = None profile_pic: Optional[bytes] = File(None) email: Optional[str] = None + password: Optional[str] = None blood_group: Optional[str] = None gender: Optional[str] = None date_of_birth: Optional[str] = None @@ -95,4 +97,9 @@ class DoctorId(BaseModel): class PatientCommentId(BaseModel): """Create class model for requesting id param in get patient comment api""" - id : Optional[int] = None \ No newline at end of file + id : Optional[int] = None + +class DoctorEmail(BaseModel): + """Create class model for requesting id param in get doctor api""" + email : Optional[str] = None + password : Optional[str] = None \ No newline at end of file diff --git a/doctor/app/response.py b/doctor/app/response.py index d91c9f4..a8debb4 100644 --- a/doctor/app/response.py +++ b/doctor/app/response.py @@ -22,6 +22,13 @@ def success_without_data(cls, message): """ return {"success": True, "message": message} + @classmethod + def failure_without_data(cls, message): + """ + Common success_without_data method for API response + """ + return {"success": False, "message": message} + @classmethod def error(cls, error): """ diff --git a/main.py b/main.py index 76b63db..6b2d968 100644 --- a/main.py +++ b/main.py @@ -5,17 +5,23 @@ from fastapi import FastAPI import uvicorn from doctor.app.db import Base as doctorBase,doctor_engine +from medicine.app.db import Base as medicineBase,medicine_engine from appointment.app.db import Base as appointmentBase,appointment_engine from patient.app.db import Base as patientBase,patient_engine +from patient_report.app.db import Base as patientReportBase,patient_report_engine from fastapi.staticfiles import StaticFiles #new from appointment.app.api.appointment_route import appointment_router +from medicine.app.api.medicine_route import medicine_router from doctor.app.api.doctor_route import doctor_router from patient.app.api.patient_route import patient_router +from patient_report.app.api.patient_report_route import patient_report_router from fastapi.middleware.cors import CORSMiddleware doctorBase.metadata.create_all(doctor_engine) appointmentBase.metadata.create_all(appointment_engine) patientBase.metadata.create_all(patient_engine) +medicineBase.metadata.create_all(medicine_engine) +patientReportBase.metadata.create_all(patient_report_engine) app = FastAPI() @@ -37,6 +43,8 @@ def configure_static(app): #new app.include_router(router=doctor_router,prefix="/doctor") app.include_router(router=appointment_router,prefix="/appointment") app.include_router(router=patient_router,prefix="/patient") +app.include_router(router=medicine_router,prefix="/medicine") +app.include_router(router=patient_report_router,prefix="/patient_report") if __name__ == "__main__": uvicorn.run(app) diff --git a/medicine/app/api/controller.py b/medicine/app/api/controller.py index 81d383d..61500f5 100644 --- a/medicine/app/api/controller.py +++ b/medicine/app/api/controller.py @@ -18,23 +18,27 @@ def Merge(dict1, dict2): return dict2.update(dict1) -def add_new_medicine(database: Session, medicine: schemas.MedicineBase): +def add_new_medicine(database: Session, medicine): """Function to return query based data while creating new medicine creation api""" - for key,value in medicine.dict().items(): + for key,value in medicine.items(): if key == "name" or key == "cost" or key == "production_date": - is_error = Error.if_param_is_null_or_empty(medicine.dict()[key],key) + is_error = Error.if_param_is_null_or_empty(medicine[key],key) if is_error: return ResponseData.success_without_data(f"{key} cannot be empty") - medicine_dict = {'name': medicine.dict()["name"], 'type': medicine.dict()["type"],"cost" : medicine.dict()["cost"], - "description" : medicine.dict()["description"]} + medicine_dict = {'name': medicine["name"] if medicine["name"] is not None else "", 'type': medicine["type"]if medicine["type"] is not None else "", + "cost" : medicine["cost"] if medicine["cost"] is not None else "", + "description" : medicine["description"] if medicine["description"] is not None else ""} + db_medicine = database.query(models.Medicine).filter(models.Medicine.name == medicine["name"]).first() + if db_medicine is not None: + return ResponseData.success([],"Medicine with this name already exists") db_medicine = models.Medicine(**medicine_dict) database.add(db_medicine) database.commit() database.refresh(db_medicine) - medicine_report_dict = {'company': medicine.dict()["company"],"quantity" : medicine.dict()["quantity"], - "production_date" : medicine.dict()["production_date"],"expire_date" : medicine.dict()["expire_date"], - "country" : medicine.dict()["country"], - "supplier_id" : medicine.dict()["supplier_id"],"id" : db_medicine.id,} + medicine_report_dict = {'company': medicine["company"]if medicine["company"] is not None else "","quantity" : medicine["quantity"]if medicine["quantity"] is not None else "", + "production_date" : medicine["production_date"] if medicine["production_date"] is not None else "","expire_date" : medicine["expire_date"]if medicine["expire_date"] is not None else "", + "country" : medicine["country"]if medicine["country"] is not None else "", + "supplier_id" : medicine["supplier_id"]if medicine["supplier_id"] is not None else "","id" : db_medicine.id,} db_medicine_report = models.MedicineReport(**medicine_report_dict) database.add(db_medicine_report) database.commit() @@ -42,14 +46,29 @@ def add_new_medicine(database: Session, medicine: schemas.MedicineBase): Merge(medicine_dict, medicine_report_dict) return ResponseData.success(medicine_report_dict,"Medicine added successfully") -def get_medicine_by_id(database: Session, id : Optional[int] = None): +def get_medicine_by_id(database: Session, id): """Function to tell user if medicine with given id already exists or not""" - db_medicine = database.query(models.Medicine).filter(models.Medicine.id == id).first() - if db_medicine is None: - return ResponseData.success([],"Medicine with this id does not exists") - db_medicine_report = database.query(models.MedicineReport).filter(models.MedicineReport.id == id).first() - Merge(db_medicine.__dict__, db_medicine_report.__dict__) - return ResponseData.success(db_medicine_report.__dict__,"Medicine details fetched successfully") + if id == "": + data = database.query(models.Medicine,models.MedicineReport).filter(models.Medicine.id == models.MedicineReport.id).all() + else: + data = database.query(models.Medicine,models.MedicineReport).filter(models.Medicine.id == models.MedicineReport.id,models.MedicineReport.id == id).first() + listdata = [] + if(len(data) > 1): + if id != "": + dict1 = data["MedicineReport"] + dict2 = data["Medicine"] + dict1.__dict__.update(dict2.__dict__) + listdata.append(dict1) + else: + for i, ele in enumerate(data): + dict1 = ele["MedicineReport"] + dict2 = ele["Medicine"] + dict1.__dict__.update(dict2.__dict__) + listdata.append(dict1) + if len(listdata) > 0: + return ResponseData.success(listdata,"Medicine details fetched successfully") + return ResponseData.success([],"No Medicine found") + return ResponseData.success(listdata,"No Medicine found") def get_medicine_by_pagination(database: Session,page : int,size:int): """Function to get medicine details by pagination""" @@ -82,26 +101,26 @@ def update_medicine_details(database: Session, medicine: schemas.AddNewMedicine) data = database.query(models.MedicineReport,models.Medicine).filter(models.Medicine.id == medicine.id).all() dict1 = data[0]["MedicineReport"] dict2 = data[0]["Medicine"] - if medicine.dict()["name"] is not None : - dict2.__dict__["name"] = medicine.dict()["name"] - if medicine.dict()["type"] is not None : - dict2.__dict__["type"] = medicine.dict()["type"] - if medicine.dict()["cost"] is not None : - dict2.__dict__["cost"] = medicine.dict()["cost"] - if medicine.dict()["description"] is not None : - dict2.__dict__["description"] = medicine.dict()["description"] - if medicine.dict()["company"] is not None : - dict1.__dict__["company"] = medicine.dict()["company"] - if medicine.dict()["quantity"] is not None : - dict1.__dict__["quantity"] = medicine.dict()["quantity"] - if medicine.dict()["production_date"] is not None : - dict1.__dict__["production_date"] = medicine.dict()["production_date"] - if medicine.dict()["expire_date"] is not None : - dict1.__dict__["expire_date"] = medicine.dict()["expire_date"] - if medicine.dict()["country"] is not None : - dict1.__dict__["country"] = medicine.dict()["country"] - if medicine.dict()["supplier_id"] is not None : - dict1.__dict__["supplier_id"] = medicine.dict()["supplier_id"] + if medicine["name"] is not None : + dict2.__dict__["name"] = medicine["name"] + if medicine["type"] is not None : + dict2.__dict__["type"] = medicine["type"] + if medicine["cost"] is not None : + dict2.__dict__["cost"] = medicine["cost"] + if medicine["description"] is not None : + dict2.__dict__["description"] = medicine["description"] + if medicine["company"] is not None : + dict1.__dict__["company"] = medicine["company"] + if medicine["quantity"] is not None : + dict1.__dict__["quantity"] = medicine["quantity"] + if medicine["production_date"] is not None : + dict1.__dict__["production_date"] = medicine["production_date"] + if medicine["expire_date"] is not None : + dict1.__dict__["expire_date"] = medicine["expire_date"] + if medicine["country"] is not None : + dict1.__dict__["country"] = medicine["country"] + if medicine["supplier_id"] is not None : + dict1.__dict__["supplier_id"] = medicine["supplier_id"] database.query(models.Medicine).filter(models.Medicine.id == medicine.id).update({ models.Medicine.id : medicine.id, models.Medicine.name: dict2.__dict__["name"], models.Medicine.type : dict2.__dict__["type"], diff --git a/medicine/app/api/medicine_route.py b/medicine/app/api/medicine_route.py index df0d536..a3f27fc 100644 --- a/medicine/app/api/medicine_route.py +++ b/medicine/app/api/medicine_route.py @@ -1,27 +1,32 @@ """File for patient route""" import sys,os sys.path.append(os.getcwd()) -from fastapi import Depends, APIRouter +from fastapi import Depends, APIRouter,Request from sqlalchemy.orm import Session from medicine.app.models import schemas -from db import get_db +from medicine.app.db import get_db -from api import controller +from medicine.app.api import controller medicine_router = APIRouter() -@medicine_router.post("/add_medicine", response_model=schemas.AddMedicineResponse) -def add_medicine(medicine: schemas.MedicineBase, database: Session = Depends(get_db)): +@medicine_router.post("/add_medicine") +async def add_medicine(request:Request, database: Session = Depends(get_db)): """Function to return final response while adding new medicine details""" - return controller.add_new_medicine(database,medicine) + request_json = await request.json() + return controller.add_new_medicine(database,request_json) @medicine_router.post("/get_medicine_details") -def get_medicine_details(medicineid: schemas.MedicineId, database: Session = Depends(get_db)): +async def get_medicine_details(request:Request, database: Session = Depends(get_db)): """Function to return medicine details (specific and all medicine data can be fetched)""" - return controller.get_medicine_by_id(database, id = medicineid.id) + request_json = await request.json() + id = "" + if request_json["id"] != "": + id = request_json["id"] + return controller.get_medicine_by_id(database, id) @medicine_router.get("/get_medicine_by_pagination") async def get_medicine_by_pagination(database: Session = Depends(get_db),page: int = 0, size: int = 5): diff --git a/medicine/app/db.py b/medicine/app/db.py index 31ae5aa..9fb6100 100644 --- a/medicine/app/db.py +++ b/medicine/app/db.py @@ -5,9 +5,9 @@ import medicine.config DATABASE_URL = medicine.config.Config.DATABASE_URL -engine = create_engine(url=DATABASE_URL) +medicine_engine = create_engine(url='postgresql://anirudh.chawla:123@localhost/medicine') -SessionLocal = sessionmaker(bind=engine,autocommit=False,autoflush=False) +SessionLocal = sessionmaker(bind=medicine_engine,autocommit=False,autoflush=False) Base = declarative_base() diff --git a/medicine/app/models/models.py b/medicine/app/models/models.py index 1d60067..ce3de60 100644 --- a/medicine/app/models/models.py +++ b/medicine/app/models/models.py @@ -3,7 +3,7 @@ from operator import index from fastapi import File from sqlalchemy import Column, Integer, String -from db import Base +from medicine.app.db import Base class Medicine(Base): """Class for creating medicine model""" diff --git a/patient/app/api/controller.py b/patient/app/api/controller.py index f8e92f7..f3d45fe 100644 --- a/patient/app/api/controller.py +++ b/patient/app/api/controller.py @@ -13,7 +13,10 @@ import patient from patient.email_manager import EmailManager from patient.app.response import Response as ResponseData -from patient.app.models import models,schemas +from patient.app.models import models +from appointment.app.models import models as appointmentModel +from patient_report.app.models import models as patientReportModel +from medicine.app.models import models as medicineModel from hospital.app.api.controller import check_if_hospital_id_is_valid from patient.app.error_handling import Error import ast @@ -232,7 +235,7 @@ def reset_password_for_patient(database: Session, otp : str,new_password : str): """Function to reset password for a particular patient""" patient_otp_data = database.query(models.Patient_Otp_For_Password).filter(models.Patient_Otp_For_Password.otp == otp).first() if not patient_otp_data: - return ResponseData.success_without_data("Otp entered is invalid") + return ResponseData.failure_without_data("Otp entered is invalid") fmt = '%Y-%m-%d %H:%M:%S' current_date = datetime.strptime(str(datetime.now()).split(".")[0],fmt) print(f"patient_otp_data.updated_at {patient_otp_data.updated_at}") @@ -259,7 +262,7 @@ def patient_sign_in_api(database: Session,email : Optional[str] = None,password """Function to sign in a patient""" db_patient = database.query(models.Patient).filter(models.Patient.email == email,models.Patient.password == password).first() if not db_patient: - return ResponseData.success_without_data("Credentials are invalid") + return ResponseData.error("Credentials are invalid") db_patient_details = database.query(models.Patient).filter(models.Patient.email == email).first() token = { 'authentication_token' : JWTUtility.encode_token(db_patient_details.email,db_patient_details.contact_number) @@ -270,68 +273,109 @@ def patient_sign_in_api(database: Session,email : Optional[str] = None,password db_patient_details.__dict__.pop("password") return ResponseData.success(db_patient_details.__dict__,"Patient signed in successfully") -def get_patient_by_id(database: Session, id : Optional[int] = None): +def get_patient_by_id(database: Session,appointment_database :Session,patient_report_database :Session,medicine_database :Session,doctor_id,search, id : Optional[int] = None): """Function to tell user if patient with given contact number already exists or not""" - if id is None: - # db_patient = database.query(models.Patient).filter().first() - # db_patient_details = database.query(models.PatientDetails).filter().first() + if id is None and doctor_id == "": data = database.query(models.Patient,models.PatientDetails).filter(models.Patient.id == models.PatientDetails.id).all() list = [] if(len(data) > 0): for i, ele in enumerate(data): dict1 = ele["PatientDetails"] dict2 = ele["Patient"] - # dict3 = ele["PatientCommentDetails"] dict1.__dict__.update(dict2.__dict__) dict1.__dict__["hospital_id"] = "" - # dict1.__dict__["Feedback"] = ele["PatientCommentDetails"] list.append(dict1) - # Merge(db_patient.__dict__, db_patient_details.__dict__) return ResponseData.success(list,"Patient details fetched successfully") return ResponseData.success([],"No patient details found") - db_patient = database.query(models.Patient).filter(models.Patient.id == id).first() - if db_patient is None: - return ResponseData.success([],"Patient with this id does not exists") - db_patient_details = database.query(models.PatientDetails).filter(models.PatientDetails.id == id).first() - Merge(db_patient.__dict__, db_patient_details.__dict__) - allergies_list = database.query(models.Patient_Allergies).filter(models.Patient_Allergies.patient_id == str(db_patient.id)).all() - allergies = [] - for i in range(0,len(allergies_list)): - allergy = database.query(models.Allergies).filter(models.Allergies.id == str(allergies_list[i].allergy_id)).first() - if allergy is not None: - allergies.append(allergy) - db_patient_details.__dict__["patient_allergies"] = allergies - medications_list = database.query(models.Patient_CurrentMedications).filter(models.Patient_CurrentMedications.patient_id == str(db_patient.id)).all() - medications = [] - for i in range(0,len(medications_list)): - medication = database.query(models.CurrentMedications).filter(models.CurrentMedications.id == str(medications_list[i].current_medication_id)).first() - if medication is not None: - medications.append(medication) - db_patient_details.__dict__["patient_current_medications"] = medications - injuries_list = database.query(models.Patient_PastInjuries).filter(models.Patient_PastInjuries.patient_id == str(db_patient.id)).all() - injuries = [] - for i in range(0,len(injuries_list)): - injury = database.query(models.PastInjuries).filter(models.PastInjuries.id == str(injuries_list[i].past_injury_id)).first() - if injury is not None: - injuries.append(injury) - db_patient_details.__dict__["patient_past_injuries"] = injuries - surgeries_list = database.query(models.Patient_PastSurgeries).filter(models.Patient_PastSurgeries.patient_id == str(db_patient.id)).all() - surgeries = [] - for i in range(0,len(surgeries_list)): - surgery = database.query(models.PastSurgeries).filter(models.PastSurgeries.id == str(surgeries_list[i].past_surgery_id)).first() - if surgery is not None: - surgeries.append(surgery) - db_patient_details.__dict__["patient_past_surgeries"] = surgeries - food_preference_list = database.query(models.Patient_FoodPreference).filter(models.Patient_FoodPreference.patient_id == str(db_patient.id)).all() - food_preference = [] - for i in range(0,len(food_preference_list)): - food = database.query(models.FoodPreference).filter(models.FoodPreference.id == str(food_preference_list[i].food_preference_id)).first() - if food is not None: - food_preference.append(food) - db_patient_details.__dict__["patient_food_preferences"] = food_preference - if db_patient_details.__dict__["hospital_id"] is None: - db_patient_details.__dict__["hospital_id"] = "" - return ResponseData.success(db_patient_details.__dict__,"Patient details fetched successfully") + if doctor_id != "": + appointment_data = appointment_database.query(appointmentModel.Appointment).filter(appointmentModel.Appointment.doctor_id == doctor_id).all() + completed_status = appointment_database.query(appointmentModel.AppointmentStatus).filter(appointmentModel.AppointmentStatus.status == 'Done').first() + completed_status_id = '' + if completed_status: + completed_status_id = completed_status.a_id + else: + return ResponseData.success([],"Appointment status Done does not exists in database") + finalPatientList = [] + patientIds = [] + if len(appointment_data) > 0: + for i in range(0,len(appointment_data)): + if appointment_data[i].__dict__["status_id"] == str(completed_status_id): + if appointment_data[i].__dict__["patient_id"] not in patientIds: + patientIds.append(appointment_data[i].__dict__["patient_id"]) + print(f"patientIds {patientIds}") + for i in range(0,len(patientIds)): + db_patient = database.query(models.Patient).filter(models.Patient.id == patientIds[i]).all() + db_patient_report_data = patient_report_database.query(patientReportModel.PatientReport).filter(patientReportModel.PatientReport.patient_id == patientIds[i]).first() + db_patient_updated_report_medicine_details = patient_report_database.query(patientReportModel.PatientReportMedicineDetails).filter().all() + for j in range(0,len(db_patient_updated_report_medicine_details)): + medicine_name = medicine_database.query(medicineModel.Medicine).filter((medicineModel.Medicine.id == int(db_patient_updated_report_medicine_details[j].__dict__["medicine_id"]))).first() + if not medicine_name: + return ResponseData.error("medicine id is invalid") + db_patient_updated_report_medicine_details[j].__dict__["medicine_name"] = medicine_name.name + if len(db_patient) == 0: + return ResponseData.success([],"No patient details found") + for k in range(0,len(db_patient)): + db_patient[k].__dict__["patient_report_data"] = db_patient_report_data.__dict__ + db_patient[k].__dict__["patient_report_data"]["medicine_details"] = db_patient_updated_report_medicine_details + db_patient[k].__dict__["hospital_id"] = '' + finalPatientList.append(db_patient[k].__dict__) + newList = [] + if search != '': + for k in range(0,len(finalPatientList)): + if str(finalPatientList[k]['first_name']).lower().__contains__(str(search).lower()) or str(finalPatientList[k]['last_name']).lower().__contains__(str(search).lower()) or str(finalPatientList[k]['contact_number']).__contains__(search): + newList.append(finalPatientList[k]) + if len(newList) == 0 and search != '': + return ResponseData.success([],"No patient details found") + if search != '': + return ResponseData.success(newList,"Patient details fetched successfully") + else: + return ResponseData.success(finalPatientList,"Patient details fetched successfully") + else: + return ResponseData.success([],"No patient details found") + else: + db_patient = database.query(models.Patient).filter(models.Patient.id == id).first() + if db_patient is None: + return ResponseData.success([],"Patient with this id does not exists") + db_patient_details = database.query(models.PatientDetails).filter(models.PatientDetails.id == id).first() + Merge(db_patient.__dict__, db_patient_details.__dict__) + allergies_list = database.query(models.Patient_Allergies).filter(models.Patient_Allergies.patient_id == str(db_patient.id)).all() + allergies = [] + for i in range(0,len(allergies_list)): + allergy = database.query(models.Allergies).filter(models.Allergies.id == str(allergies_list[i].allergy_id)).first() + if allergy is not None: + allergies.append(allergy) + db_patient_details.__dict__["patient_allergies"] = allergies + medications_list = database.query(models.Patient_CurrentMedications).filter(models.Patient_CurrentMedications.patient_id == str(db_patient.id)).all() + medications = [] + for i in range(0,len(medications_list)): + medication = database.query(models.CurrentMedications).filter(models.CurrentMedications.id == str(medications_list[i].current_medication_id)).first() + if medication is not None: + medications.append(medication) + db_patient_details.__dict__["patient_current_medications"] = medications + injuries_list = database.query(models.Patient_PastInjuries).filter(models.Patient_PastInjuries.patient_id == str(db_patient.id)).all() + injuries = [] + for i in range(0,len(injuries_list)): + injury = database.query(models.PastInjuries).filter(models.PastInjuries.id == str(injuries_list[i].past_injury_id)).first() + if injury is not None: + injuries.append(injury) + db_patient_details.__dict__["patient_past_injuries"] = injuries + surgeries_list = database.query(models.Patient_PastSurgeries).filter(models.Patient_PastSurgeries.patient_id == str(db_patient.id)).all() + surgeries = [] + for i in range(0,len(surgeries_list)): + surgery = database.query(models.PastSurgeries).filter(models.PastSurgeries.id == str(surgeries_list[i].past_surgery_id)).first() + if surgery is not None: + surgeries.append(surgery) + db_patient_details.__dict__["patient_past_surgeries"] = surgeries + food_preference_list = database.query(models.Patient_FoodPreference).filter(models.Patient_FoodPreference.patient_id == str(db_patient.id)).all() + food_preference = [] + for i in range(0,len(food_preference_list)): + food = database.query(models.FoodPreference).filter(models.FoodPreference.id == str(food_preference_list[i].food_preference_id)).first() + if food is not None: + food_preference.append(food) + db_patient_details.__dict__["patient_food_preferences"] = food_preference + if db_patient_details.__dict__["hospital_id"] is None: + db_patient_details.__dict__["hospital_id"] = "" + return ResponseData.success(db_patient_details.__dict__,"Patient details fetched successfully") def get_patient_by_pagination(database: Session,page : int,size:int): """Function to get patient details by pagination""" diff --git a/patient/app/api/patient_route.py b/patient/app/api/patient_route.py index 2695432..479f5ea 100644 --- a/patient/app/api/patient_route.py +++ b/patient/app/api/patient_route.py @@ -9,7 +9,9 @@ from sqlalchemy.orm import Session from patient.app.models import schemas from patient.app.db import get_db - +from patient_report.app.db import get_db as patient_report_db +from appointment.app.db import get_db as get_appointment_db +from medicine.app.db import get_db as get_medicine_db from patient.app.api import controller IMAGE_DIR_PATH = f"{os.getcwd()}/patient/app/patient_images" @@ -71,13 +73,21 @@ async def patient_reset_password(request: Request, database: Session = Depends(g return controller.reset_password_for_patient(database,otp=request_json["otp"],new_password=request_json["new_password"]) @patient_router.post("/get_patient_details") -def get_patient(request: Request, database: Session = Depends(get_db)): +async def get_patient(request: Request, database: Session = Depends(get_db),appointment_database: Session = Depends(get_appointment_db), +patient_report_database: Session = Depends(patient_report_db),medicine_database: Session = Depends(get_medicine_db)): """Function to return patient details (specific and all patient data can be fetched)""" patientid = None - if request.headers.get('Authorization') is not None: + request_json = await request.json() + if request.headers.get('Authorization') is not None and 'doctor_id' not in request_json: patientid = Authentication().authenticate(request.headers.get('Authorization'),database)[0].id - return controller.get_patient_by_id(database, id = patientid) + doctor_id = '' + search = '' + if 'doctor_id' in request_json: + doctor_id = request_json['doctor_id'] + if 'search' in request_json: + search = request_json['search'] + return controller.get_patient_by_id(database,appointment_database,patient_report_database,medicine_database,doctor_id,search, id = patientid) @patient_router.get("/get_allergies") def get_allergies(request: Request, database: Session = Depends(get_db)): diff --git a/patient/app/patient_images/MicrosoftTeams-image (34).png b/patient/app/patient_images/MicrosoftTeams-image (34).png new file mode 100644 index 0000000..55df761 Binary files /dev/null and b/patient/app/patient_images/MicrosoftTeams-image (34).png differ diff --git a/patient/app/patient_images/Screenshot 2022-09-02 at 2.19.37 PM.png b/patient/app/patient_images/Screenshot 2022-09-02 at 2.19.37 PM.png new file mode 100644 index 0000000..a1c1c68 Binary files /dev/null and b/patient/app/patient_images/Screenshot 2022-09-02 at 2.19.37 PM.png differ diff --git a/patient/app/patient_images/scaled_14031fc2-7006-40ab-8393-1df4f3c14a438454342806381879235.jpg b/patient/app/patient_images/scaled_14031fc2-7006-40ab-8393-1df4f3c14a438454342806381879235.jpg new file mode 100644 index 0000000..6df1985 Binary files /dev/null and b/patient/app/patient_images/scaled_14031fc2-7006-40ab-8393-1df4f3c14a438454342806381879235.jpg differ diff --git a/patient/app/patient_profile_pic_files/MicrosoftTeams-image (34).png b/patient/app/patient_profile_pic_files/MicrosoftTeams-image (34).png new file mode 100644 index 0000000..55df761 Binary files /dev/null and b/patient/app/patient_profile_pic_files/MicrosoftTeams-image (34).png differ diff --git a/patient/app/patient_profile_pic_files/Screenshot 2022-09-02 at 2.19.37 PM.png b/patient/app/patient_profile_pic_files/Screenshot 2022-09-02 at 2.19.37 PM.png new file mode 100644 index 0000000..a1c1c68 Binary files /dev/null and b/patient/app/patient_profile_pic_files/Screenshot 2022-09-02 at 2.19.37 PM.png differ diff --git a/patient/app/patient_profile_pic_files/scaled_1d79c35a-e93c-4477-9064-51b466bf5aa78908030505557873250.jpg b/patient/app/patient_profile_pic_files/scaled_1d79c35a-e93c-4477-9064-51b466bf5aa78908030505557873250.jpg new file mode 100644 index 0000000..5bea122 Binary files /dev/null and b/patient/app/patient_profile_pic_files/scaled_1d79c35a-e93c-4477-9064-51b466bf5aa78908030505557873250.jpg differ diff --git a/patient/app/patient_profile_pic_files/scaled_290c04ae-b651-464a-828d-2df3ba89370e7285644070243544874.jpg b/patient/app/patient_profile_pic_files/scaled_290c04ae-b651-464a-828d-2df3ba89370e7285644070243544874.jpg new file mode 100644 index 0000000..96c18aa Binary files /dev/null and b/patient/app/patient_profile_pic_files/scaled_290c04ae-b651-464a-828d-2df3ba89370e7285644070243544874.jpg differ diff --git a/patient/app/patient_profile_pic_files/scaled_99868eb7-93a9-42ee-9098-cffbf14537239033807240845713408.jpg b/patient/app/patient_profile_pic_files/scaled_99868eb7-93a9-42ee-9098-cffbf14537239033807240845713408.jpg new file mode 100644 index 0000000..eb71b6e Binary files /dev/null and b/patient/app/patient_profile_pic_files/scaled_99868eb7-93a9-42ee-9098-cffbf14537239033807240845713408.jpg differ diff --git a/patient/app/patient_profile_pic_files/scaled_b16ed58e-80a8-4f0d-8672-5d5c88f3409f2495983041992746909.jpg b/patient/app/patient_profile_pic_files/scaled_b16ed58e-80a8-4f0d-8672-5d5c88f3409f2495983041992746909.jpg new file mode 100644 index 0000000..b4476db Binary files /dev/null and b/patient/app/patient_profile_pic_files/scaled_b16ed58e-80a8-4f0d-8672-5d5c88f3409f2495983041992746909.jpg differ diff --git a/patient/app/patient_profile_pic_files/scaled_image_picker2333537032771494040.jpg b/patient/app/patient_profile_pic_files/scaled_image_picker2333537032771494040.jpg new file mode 100644 index 0000000..73109b9 Binary files /dev/null and b/patient/app/patient_profile_pic_files/scaled_image_picker2333537032771494040.jpg differ diff --git a/patient/app/response.py b/patient/app/response.py index d91c9f4..a8debb4 100644 --- a/patient/app/response.py +++ b/patient/app/response.py @@ -22,6 +22,13 @@ def success_without_data(cls, message): """ return {"success": True, "message": message} + @classmethod + def failure_without_data(cls, message): + """ + Common success_without_data method for API response + """ + return {"success": False, "message": message} + @classmethod def error(cls, error): """ diff --git a/patient_report/app/api/controller.py b/patient_report/app/api/controller.py index d4a36a6..8825e7e 100644 --- a/patient_report/app/api/controller.py +++ b/patient_report/app/api/controller.py @@ -7,7 +7,7 @@ from typing import Optional import sys from sqlalchemy.orm import Session -from models import models,schemas +from patient_report.app.models import models,schemas from response import Response as ResponseData from hospital.app.api.controller import check_if_hospital_id_is_valid from patient.app.api.controller import check_if_patient_id_is_valid diff --git a/patient_report/app/api/patient_report_route.py b/patient_report/app/api/patient_report_route.py index dfbcc18..6d1e365 100644 --- a/patient_report/app/api/patient_report_route.py +++ b/patient_report/app/api/patient_report_route.py @@ -3,15 +3,15 @@ from fastapi import Depends, APIRouter, File, Form, Request, UploadFile from sqlalchemy.orm import Session from authentication import Authentication -from models import schemas -from db import get_db +from patient_report.app.models import schemas +from patient_report.app.db import get_db from datetime import datetime -from api import controller +from patient_report.app.api import controller patient_report_router = APIRouter() -IMAGE_DIR_PATH = f"{os.getcwd()}/patient_report/patient_report_images" +IMAGE_DIR_PATH = f"{os.getcwd()}/patient_report/app/patient_report_images" async def create_file(file=File(None)): try: diff --git a/patient_report/app/db.py b/patient_report/app/db.py index e7ddc0d..4b06101 100644 --- a/patient_report/app/db.py +++ b/patient_report/app/db.py @@ -5,9 +5,9 @@ import patient_report.config DATABASE_URL = patient_report.config.Config.DATABASE_URL -engine = create_engine(url=DATABASE_URL) +patient_report_engine = create_engine(url='postgresql://anirudh.chawla:123@localhost/patient_report') -SessionLocal = sessionmaker(bind=engine,autocommit=False,autoflush=False) +SessionLocal = sessionmaker(bind=patient_report_engine,autocommit=False,autoflush=False) Base = declarative_base() diff --git a/patient_report/app/models/models.py b/patient_report/app/models/models.py index 8425a77..87ca1b4 100644 --- a/patient_report/app/models/models.py +++ b/patient_report/app/models/models.py @@ -1,7 +1,7 @@ """File for creating models of the project""" from sqlalchemy import Column, TIMESTAMP, Integer, String,Boolean -from db import Base +from patient_report.app.db import Base class PatientReport(Base): """Class for creating patient report model""" @@ -9,12 +9,14 @@ class PatientReport(Base): id = Column(Integer, primary_key=True, index=True) patient_id = Column(String, index=True) - report_id = Column(String, index=True) - diagnose = Column(String, index=True) - reference = Column(String, index=True) - medicine_id = Column(String, index=True) - medicine_name = Column(String, index=True) + report_description = Column(String, index=True) doctor_id = Column(String, index=True) hospital_id = Column(String, index=True) - patient_report_file = Column(String,index=True) + appointment_id = Column(String, index=True) + +class PatientReportMedicineDetails(Base): + """Class for creating patient report medicine details model""" + __tablename__ = 'patient_report_medicine_details' + patient_id = Column(String, index=True) + medicine_id = Column(String, primary_key=True,index=True) \ No newline at end of file diff --git a/patient_report/app/models/schemas.py b/patient_report/app/models/schemas.py index 0c3787c..da98732 100644 --- a/patient_report/app/models/schemas.py +++ b/patient_report/app/models/schemas.py @@ -8,27 +8,23 @@ class PatientReportBase(BaseModel): """Base class model for patient report""" patient_id: Optional[str] = None - report_id: Optional[str] = None - diagnose: Optional[str] = None - reference: Optional[str] = None medicine_id: Optional[str] = None - medicine_name: Optional[str] = None doctor_id: Optional[str] = None hospital_id: Optional[str] = None - patient_report_file: Optional[str] = None + appointment_id: Optional[str] = None + report_description: Optional[str] = None + # patient_report_file: Optional[str] = None class AddNewPatientReport(PatientReportBase): """Create class model for patient report""" id : int patient_id: Optional[str] = None - report_id: Optional[str] = None - diagnose: Optional[str] = None - reference: Optional[str] = None medicine_id: Optional[str] = None - medicine_name: Optional[str] = None doctor_id: Optional[str] = None hospital_id: Optional[str] = None - patient_report_file: Optional[str] = None + appointment_id: Optional[str] = None + report_description: Optional[str] = None + # patient_report_file: Optional[str] = None class AddPatientReportResponse(BaseModel): """Create class model for response of new patient report to be added""" diff --git a/staff/app/models/models.py b/staff/app/models/models.py index 1204d3c..940f1a7 100644 --- a/staff/app/models/models.py +++ b/staff/app/models/models.py @@ -5,7 +5,7 @@ from fastapi import File from pydantic import FilePath from sqlalchemy import Column, TIMESTAMP, Integer, String -from db import Base +from staff.app.db import Base class Staff(Base): """Class for creating staff model""" diff --git a/staff/app/models/schemas.py b/staff/app/models/schemas.py index 4a5d8d7..0c2fc8c 100644 --- a/staff/app/models/schemas.py +++ b/staff/app/models/schemas.py @@ -1,8 +1,9 @@ """Schema file for hospital table""" +import re from typing import Optional -from pydantic import BaseModel +from pydantic import BaseModel, EmailStr, validator class StaffBase(BaseModel):