health-apps-backend/apis/endpoints/appointments.py

118 lines
3.5 KiB
Python

from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from typing import List
# database
from database import get_db
from schemas.ResponseSchemas import AppointmentDetailed, AppointmentSchema
from models.Appointments import Appointments
from schemas.CreateSchemas import AppointmentCreate, AppointmentCreateWithNames
from models.Doctors import Doctors
from models.Patients import Patients
router = APIRouter()
@router.get(
"/", response_model=List[AppointmentDetailed], status_code=status.HTTP_200_OK
)
def get_appointments(
doc_name: str | None = None,
patient_name: str | None = None,
skip: int = 0,
limit: int = 100,
db: Session = Depends(get_db),
):
"""
Get a list of appointments with optional pagination.
"""
try:
query = db.query(Appointments)
if doc_name:
query = query.join(Appointments.doctor).filter(
Doctors.name.ilike(f"%{doc_name}%")
)
if patient_name:
query = query.join(Appointments.patient).filter(
Patients.name.ilike(f"%{patient_name}%")
)
appointments = query.offset(skip).limit(limit).all()
return appointments
except Exception as e:
raise HTTPException(
status_code=500,
detail=str(e.__cause__),
) from e
# @router.post("/", response_model=AppointmentSchema, status_code=status.HTTP_201_CREATED)
# def create_appointment(appointment: AppointmentCreate, db: Session = Depends(get_db)):
# """
# Create a new appointment.
# """
# try:
# db_appointment = Appointments(**appointment.model_dump())
# db.add(db_appointment)
# db.commit()
# db.refresh(db_appointment)
# return db_appointment
# except Exception as e:
# db.rollback()
# raise HTTPException(
# status_code=500,
# detail=str(e.__cause__),
# ) from e
@router.post("/", response_model=AppointmentSchema, status_code=status.HTTP_201_CREATED)
def create_appointment_with_names(
appointment: AppointmentCreateWithNames, db: Session = Depends(get_db)
):
"""
Create a new appointment using doctor name and patient name instead of IDs.
"""
try:
# Find doctor by name
doctor = (
db.query(Doctors).filter(Doctors.name == appointment.doctor_name).first()
)
if not doctor:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"Doctor with name '{appointment.doctor_name}' not found",
)
# Find patient by name
patient = (
db.query(Patients).filter(Patients.name == appointment.patient_name).first()
)
if not patient:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"Patient with name '{appointment.patient_name}' not found",
)
# Create appointment with doctor_id and patient_id
db_appointment = Appointments(
doctor_id=doctor.id,
patient_id=patient.id,
appointment_time=appointment.appointment_time,
status=appointment.status,
)
db.add(db_appointment)
db.commit()
db.refresh(db_appointment)
return db_appointment
except HTTPException:
db.rollback()
raise
except Exception as e:
db.rollback()
raise HTTPException(
status_code=500,
detail=str(e.__cause__),
) from e