Skip to content

Commit

Permalink
Fix Patient mobility list CRUD functions
Browse files Browse the repository at this point in the history
  • Loading branch information
Yuandjom committed Jan 12, 2025
1 parent e97f09b commit 0b1297b
Show file tree
Hide file tree
Showing 18 changed files with 238 additions and 263 deletions.
59 changes: 0 additions & 59 deletions app/crud/patient_mobility_crud.py

This file was deleted.

97 changes: 97 additions & 0 deletions app/crud/patient_mobility_list_crud.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
from sqlalchemy.orm import Session
from datetime import datetime
from fastapi import HTTPException
from ..models.patient_mobility_list_model import PatientMobilityList
from ..models.patient_mobility_mapping_model import PatientMobility
from ..schemas.patient_mobility_list import (
PatientMobilityListCreate,
PatientMobilityListUpdate,
)
from ..schemas.patient_mobility_mapping import (
PatientMobilityCreate,
PatientMobilityUpdate,
)

# CRUD for PATIENT_MOBILITY_LIST

# Get all mobility list entries
def get_all_mobility_list_entries(db: Session):
try:
entries = db.query(PatientMobilityList).filter(PatientMobilityList.IsDeleted == "0").all()
if not entries:
raise HTTPException(status_code=404, detail="No mobility list entries found.")
return entries
except Exception as e:
raise HTTPException(status_code=500, detail=f"Error querying mobility list: {str(e)}")


# Get a single mobility list entry by ID
def get_mobility_list_entry_by_id(db: Session, mobility_list_id: int):
entry = db.query(PatientMobilityList).filter(
PatientMobilityList.MobilityListId == mobility_list_id,
PatientMobilityList.IsDeleted == '0'
).first()
if not entry:
raise HTTPException(status_code=404, detail=f"Mobility list entry with ID {mobility_list_id} not found.")
return entry

# Create a new mobility list entry
def create_mobility_list_entry(db: Session, mobility_list_data: PatientMobilityListCreate, created_by: int):
new_entry = PatientMobilityList(
**mobility_list_data.dict(exclude={"CreatedDateTime", "ModifiedDateTime", "CreatedById", "ModifiedById"}), # Corrected set syntax
CreatedDateTime=datetime.utcnow(),
ModifiedDateTime=datetime.utcnow(),
CreatedById=created_by,
ModifiedById=created_by,
)
db.add(new_entry)
db.commit()
db.refresh(new_entry)
return new_entry

# Update a mobility list entry
def update_mobility_list_entry(
db: Session, mobility_list_id: int, mobility_list_data: PatientMobilityListUpdate, modified_by: int
):
db_entry = db.query(PatientMobilityList).filter(
PatientMobilityList.MobilityListId == mobility_list_id,
PatientMobilityList.IsDeleted == '0',
).first()

if db_entry:
for key, value in mobility_list_data.dict(exclude={"MobilityListId"}).items(): # Exclude MobilityListId
setattr(db_entry, key, value)

db_entry.ModifiedDateTime = datetime.utcnow()
db_entry.ModifiedById = modified_by

db.commit()
db.refresh(db_entry)
return db_entry
return None

# Soft delete a mobility list entry (set IsDeleted to '1')

def delete_mobility_list_entry(db: Session, mobility_list_id: int, modified_by: int):
# Query for the entry to be deleted
db_entry = db.query(PatientMobilityList).filter(
PatientMobilityList.MobilityListId == mobility_list_id,
PatientMobilityList.IsDeleted == "0" # Use boolean False for filtering
).first()

# Raise an exception if the entry is not found
if not db_entry:
raise HTTPException(
status_code=404,
detail=f"Mobility list entry with ID {mobility_list_id} not found."
)

# Soft delete the entry by setting IsDeleted to True
db_entry.IsDeleted = "1" # Use boolean True
db_entry.ModifiedDateTime = datetime.utcnow()
db_entry.ModifiedById = modified_by

# Commit the transaction to save the changes
db.commit()
db.refresh(db_entry) # Refresh the entry to return the updated instance
return db_entry
7 changes: 4 additions & 3 deletions app/main.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from fastapi import FastAPI,Request
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse

from sqlalchemy.orm import clear_mappers # Import clear_mappers
from .database import engine, Base
from app.routers import (
allergy_reaction_type_router,
Expand All @@ -25,6 +25,8 @@
from dotenv import load_dotenv

load_dotenv()
# clear_mappers()


app = FastAPI(
title="NTU FYP PEAR PATIENT SERVICE",
Expand Down Expand Up @@ -60,8 +62,7 @@ async def validation_exception_handler(request: Request, exc: RequestValidationE
status_code=400,
content={"detail": exc.errors(), "body": exc.body},
)


# Base.metadata.drop_all(bind=engine)
Base.metadata.create_all(bind=engine)

# Include the routers with prefixes and tags
Expand Down
2 changes: 1 addition & 1 deletion app/models/patient_list_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,6 @@ class PatientList(Base):
# allergy_reactions = relationship("PatientAllergy", back_populates="allergy_reaction_list", foreign_keys="[PatientAllergy.allergyReactionListId]")
photos = relationship("PatientPhoto", back_populates="album_category")
# dementia_assignments = relationship("PatientAssignedDementia", back_populates="dementia_type")
mobility_records = relationship("PatientMobility", back_populates="mobility_list")
# mobility_records = relationship("PatientMobility", back_populates="mobility_list")
# prescriptions = relationship("PatientPrescription", back_populates="prescription_list")
# social_history_mappings = relationship("PatientSocialHistoryListMapping", back_populates="list_entry")
23 changes: 14 additions & 9 deletions app/models/patient_mobility_list_model.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,21 @@
from sqlalchemy import Column, Integer, String, DateTime, Boolean, ForeignKey
from sqlalchemy.orm import relationship
from datetime import datetime, timezone
from datetime import datetime
from app.database import Base

class PatientMobilityList(Base):
__tablename__ = "PATIENT_MOBILITY_LIST_MAPPING"
__tablename__ = "PATIENT_MOBILITY_LIST"

id = Column(Integer, primary_key=True, index=True)
mobilityListId = Column(Integer, ForeignKey('PATIENT_MOBILITY_LIST_MAPPING.id'), nullable=False)
IsDeleted = Column(Boolean, default=False, nullable=False)
createdDate = Column(DateTime, nullable=False, default=DateTime)
modifiedDate = Column(DateTime, nullable=False, default=DateTime)
value = Column(String(255), nullable=False)
MobilityListId = Column(Integer, primary_key=True, index=True)
IsDeleted = Column(Integer, default=False, nullable=False)
CreatedDateTime = Column(DateTime, nullable=False, default=datetime.utcnow)
ModifiedDateTime = Column(DateTime, nullable=False, default=datetime.utcnow)
CreatedById = Column(Integer, nullable=False) # Changed to Integer
ModifiedById = Column(Integer, nullable=False) # Changed to Integer
Value = Column(String(255), nullable=False)

mobility_records = relationship("PatientMobility", secondary="PATIENT_MOBILITY_PATIENT_MOBILITY_LIST", back_populates="mobility_lists")
mobility_records = relationship(
"PatientMobility",
back_populates="mobility_list",
primaryjoin="PatientMobility.MobilityListId == PatientMobilityList.MobilityListId"
)
27 changes: 27 additions & 0 deletions app/models/patient_mobility_mapping_model.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
from sqlalchemy import Column, Integer, String, DateTime, ForeignKey, Boolean
from sqlalchemy.orm import relationship
from datetime import datetime, timezone
from app.database import Base

class PatientMobility(Base):
__tablename__ = "PATIENT_MOBILITY_MAPPING"

MobilityID = Column(Integer, primary_key=True, index=True)
PatientID = Column(Integer, ForeignKey('PATIENT.id'), nullable=False)
MobilityListId = Column(Integer, ForeignKey('PATIENT_MOBILITY_LIST.MobilityListId'), nullable=False) # Foreign Key
MobilityRemarks = Column(String(255))
IsRecovered = Column(Boolean, default=False, nullable=False)
IsDeleted = Column(Boolean, default=False, nullable=False)
CreatedDateTime = Column(DateTime, nullable=False, default=datetime.utcnow)
ModifiedDateTime = Column(DateTime, nullable=False, default=datetime.utcnow)
CreatedById = Column(Integer, nullable=False)
ModifiedById = Column(Integer, nullable=False)

mobility_list = relationship(
"PatientMobilityList",
back_populates="mobility_records",
primaryjoin="PatientMobility.MobilityListId == PatientMobilityList.MobilityListId"
)

# Relationship with Patient
patient = relationship("Patient", back_populates="mobility_records")
21 changes: 0 additions & 21 deletions app/models/patient_mobility_model.py

This file was deleted.

16 changes: 0 additions & 16 deletions app/models/patient_mobility_patient_mobility_list_model.py

This file was deleted.

70 changes: 34 additions & 36 deletions app/routers/patient_mobility_router.py
Original file line number Diff line number Diff line change
@@ -1,46 +1,44 @@
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from ..database import get_db
from ..crud import patient_mobility_crud as crud_mobility
from ..schemas import patient_mobility as schemas_mobility
from ..crud import patient_mobility_list_crud as crud_mobility_list, patient_mobility_list_crud as crud_mobility
from ..schemas import patient_mobility_mapping as schemas_mobility
from ..schemas import patient_mobility_list as schemas_mobility_list

router = APIRouter()

@router.get("/Mobility/PatientMobility", response_model=list[schemas_mobility.PatientMobility])
def get_patient_mobility(patient_id: int, db: Session = Depends(get_db)):
return crud_mobility.get_patient_mobility(db, patient_id)
# Routes for PATIENT_MOBILITY_LIST

@router.post("/Mobility/add", response_model=schemas_mobility.PatientMobility)
def create_patient_mobility(mobility: schemas_mobility.PatientMobilityCreate, db: Session = Depends(get_db)):
return crud_mobility.create_patient_mobility(db, mobility)
# Get all mobility list entries
@router.get("/Mobility/List", response_model=list[schemas_mobility_list.PatientMobilityList])
def get_all_mobility_lists(db: Session = Depends(get_db)):
return crud_mobility_list.get_all_mobility_list_entries(db)

# @router.put("/Mobility/update", response_model=schemas_mobility.PatientMobility)
# def update_patient_mobility(mobility_id: int, mobility: schemas_mobility.PatientMobilityUpdate, db: Session = Depends(get_db)):
# db_mobility = crud_mobility.update_patient_mobility(db, mobility_id, mobility)
# if not db_mobility:
# raise HTTPException(status_code=404, detail="Patient mobility not found")
# return db_mobility
# Ask if another other updates are needed
@router.put("/Mobility/update", response_model=schemas_mobility.PatientMobility)
def update_patient_mobility(patient_id: int, mobilityListId: int, db: Session = Depends(get_db)):
db_mobility = crud_mobility.update_patient_mobility_by_patient_id(db, patient_id, mobilityListId)
if not db_mobility:
raise HTTPException(status_code=404, detail="Patient mobility not found")

return db_mobility
# Get a single mobility list entry by ID
@router.get("/Mobility/List/{mobility_list_id}", response_model=schemas_mobility_list.PatientMobilityList)
def get_mobility_list_by_id(mobility_list_id: int, db: Session = Depends(get_db)):
mobility_list = crud_mobility_list.get_mobility_list_entry_by_id(db, mobility_list_id)
if not mobility_list:
raise HTTPException(status_code=404, detail="Mobility list entry not found")
return mobility_list

# Create a new mobility list entry
@router.post("/Mobility/List", response_model=schemas_mobility_list.PatientMobilityList)
def create_mobility_list_entry(mobility_list: schemas_mobility_list.PatientMobilityListCreate, db: Session = Depends(get_db)):
return crud_mobility_list.create_mobility_list_entry(db, mobility_list, created_by=1) # Replace 1 with dynamic user ID if needed

# @router.put("/Mobility/delete", response_model=schemas_mobility.PatientMobility)
# def delete_patient_mobility(mobility_id: int, mobility: schemas_mobility.PatientMobilityUpdate, db: Session = Depends(get_db)):
# db_mobility = crud_mobility.delete_patient_mobility(db, mobility_id, mobility)
# if not db_mobility:
# raise HTTPException(status_code=404, detail="Patient mobility not found")
# return db_mobility
@router.put("/Mobility/delete", response_model=schemas_mobility.PatientMobility)
def delete_patient_mobility(mobilityListId: int, db: Session = Depends(get_db)):
db_mobility = crud_mobility.delete_patient_mobility(db, mobilityListId)

if not db_mobility:
raise HTTPException(status_code=404, detail="Patient mobility not found")

return db_mobility
# Update a mobility list entry
@router.put("/Mobility/List/{mobility_list_id}", response_model=schemas_mobility_list.PatientMobilityList)
def update_mobility_list_entry(mobility_list_id: int, mobility_list: schemas_mobility_list.PatientMobilityListUpdate, db: Session = Depends(get_db)):
updated_entry = crud_mobility_list.update_mobility_list_entry(db, mobility_list_id, mobility_list, modified_by=1) # Replace 1 with dynamic user ID if needed
if not updated_entry:
raise HTTPException(status_code=404, detail="Mobility list entry not found")
return updated_entry

# Soft delete a mobility list entry
@router.delete("/Mobility/List/delete/{mobility_list_id}", response_model=schemas_mobility_list.PatientMobilityList)
def delete_mobility_list_entry(mobility_list_id: int, db: Session = Depends(get_db)):
deleted_entry = crud_mobility_list.delete_mobility_list_entry(db, mobility_list_id, modified_by=1) # Replace 1 with dynamic user ID if needed
if not deleted_entry:
raise HTTPException(status_code=404, detail="Mobility list entry not found")
return deleted_entry
Loading

0 comments on commit 0b1297b

Please sign in to comment.