Ali2206 commited on
Commit
a909e24
·
verified ·
1 Parent(s): 36766e8

Update api/routes/patients.py

Browse files
Files changed (1) hide show
  1. api/routes/patients.py +23 -20
api/routes/patients.py CHANGED
@@ -1,3 +1,4 @@
 
1
  from fastapi import APIRouter, HTTPException, Depends, Query, status, Body
2
  from db.mongo import patients_collection
3
  from core.security import get_current_user
@@ -26,14 +27,14 @@ logging.basicConfig(
26
  )
27
  logger = logging.getLogger(__name__)
28
 
29
- router = APIRouter(prefix="/ehr", tags=["patients"])
30
 
31
  # Configuration
32
  BASE_DIR = Path(__file__).resolve().parent.parent.parent
33
  SYNTHEA_DATA_DIR = BASE_DIR / "output" / "fhir"
34
  os.makedirs(SYNTHEA_DATA_DIR, exist_ok=True)
35
 
36
- @router.post("/patients", status_code=status.HTTP_201_CREATED)
37
  async def create_patient(
38
  patient_data: PatientCreate,
39
  current_user: dict = Depends(get_current_user)
@@ -198,7 +199,7 @@ async def process_synthea_patient(bundle: dict, file_path: str) -> Optional[dict
198
  logger.warning(f"No valid patient data found in {file_path}")
199
  return None
200
 
201
- @router.post("/patients/import", status_code=status.HTTP_201_CREATED)
202
  async def import_patients(
203
  limit: int = Query(100, ge=1, le=1000),
204
  current_user: dict = Depends(get_current_user)
@@ -339,15 +340,15 @@ async def import_patients(
339
  )
340
 
341
  @router.get("/patients", response_model=List[dict])
342
- async def get_patients(
343
  search: Optional[str] = Query(None),
344
  min_notes: int = Query(0, ge=0),
345
  min_conditions: int = Query(0, ge=0),
346
- limit: int = Query(10, ge=1, le=100),
347
  skip: int = Query(0, ge=0)
348
  ):
349
- logger.info(f"Retrieving patients with search: {search}, limit: {limit}, skip: {skip}")
350
- query = {}
351
 
352
  if search:
353
  query["$or"] = [
@@ -361,6 +362,7 @@ async def get_patients(
361
  if min_conditions > 0:
362
  query[f"conditions.{min_conditions-1}"] = {"$exists": True}
363
 
 
364
  projection = {
365
  "fhir_id": 1,
366
  "full_name": 1,
@@ -368,10 +370,10 @@ async def get_patients(
368
  "date_of_birth": 1,
369
  "city": 1,
370
  "state": 1,
371
- "conditions": {"$slice": 3},
372
- "medications": {"$slice": 3},
373
- "encounters": {"$slice": 3},
374
- "notes": {"$slice": 3}
375
  }
376
 
377
  try:
@@ -403,15 +405,15 @@ async def get_patients(
403
  return patients
404
 
405
  except Exception as e:
406
- logger.error(f"Failed to retrieve patients: {str(e)}")
407
  raise HTTPException(
408
  status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
409
  detail=f"Failed to retrieve patients: {str(e)}"
410
  )
411
 
412
  @router.get("/patients/{patient_id}", response_model=dict)
413
- async def get_patient_details(patient_id: str):
414
- logger.info(f"Retrieving patient details: {patient_id}")
415
  try:
416
  patient = await patients_collection.find_one({
417
  "$or": [
@@ -458,7 +460,7 @@ async def get_patient_details(patient_id: str):
458
  }
459
  }
460
 
461
- logger.info(f"Successfully retrieved patient details: {patient_id}")
462
  return response
463
 
464
  except ValueError as ve:
@@ -468,14 +470,14 @@ async def get_patient_details(patient_id: str):
468
  detail="Invalid patient ID format"
469
  )
470
  except Exception as e:
471
- logger.error(f"Failed to retrieve patient details {patient_id}: {str(e)}")
472
  raise HTTPException(
473
  status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
474
- detail=f"Failed to retrieve patient details: {str(e)}"
475
  )
476
 
477
- @router.post("/patients/{patient_id}/notes", status_code=status.HTTP_201_CREATED)
478
- async def add_patient_note(
479
  patient_id: str,
480
  note: Note,
481
  current_user: dict = Depends(get_current_user)
@@ -529,4 +531,5 @@ async def add_patient_note(
529
  detail=f"Failed to add note: {str(e)}"
530
  )
531
 
532
- patients = router
 
 
1
+
2
  from fastapi import APIRouter, HTTPException, Depends, Query, status, Body
3
  from db.mongo import patients_collection
4
  from core.security import get_current_user
 
27
  )
28
  logger = logging.getLogger(__name__)
29
 
30
+ router = APIRouter()
31
 
32
  # Configuration
33
  BASE_DIR = Path(__file__).resolve().parent.parent.parent
34
  SYNTHEA_DATA_DIR = BASE_DIR / "output" / "fhir"
35
  os.makedirs(SYNTHEA_DATA_DIR, exist_ok=True)
36
 
37
+ @router.post("/", status_code=status.HTTP_201_CREATED)
38
  async def create_patient(
39
  patient_data: PatientCreate,
40
  current_user: dict = Depends(get_current_user)
 
199
  logger.warning(f"No valid patient data found in {file_path}")
200
  return None
201
 
202
+ @router.post("/import", status_code=status.HTTP_201_CREATED)
203
  async def import_patients(
204
  limit: int = Query(100, ge=1, le=1000),
205
  current_user: dict = Depends(get_current_user)
 
340
  )
341
 
342
  @router.get("/patients", response_model=List[dict])
343
+ async def list_patients(
344
  search: Optional[str] = Query(None),
345
  min_notes: int = Query(0, ge=0),
346
  min_conditions: int = Query(0, ge=0),
347
+ limit: int = Query(100, ge=1, le=500),
348
  skip: int = Query(0, ge=0)
349
  ):
350
+ logger.info(f"Listing patients with search: {search}, limit: {limit}, skip: {skip}")
351
+ query = {"source": "synthea"}
352
 
353
  if search:
354
  query["$or"] = [
 
362
  if min_conditions > 0:
363
  query[f"conditions.{min_conditions-1}"] = {"$exists": True}
364
 
365
+ # Removed $slice to return full arrays for the frontend
366
  projection = {
367
  "fhir_id": 1,
368
  "full_name": 1,
 
370
  "date_of_birth": 1,
371
  "city": 1,
372
  "state": 1,
373
+ "conditions": 1,
374
+ "medications": 1,
375
+ "encounters": 1,
376
+ "notes": 1
377
  }
378
 
379
  try:
 
405
  return patients
406
 
407
  except Exception as e:
408
+ logger.error(f"Failed to list patients: {str(e)}")
409
  raise HTTPException(
410
  status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
411
  detail=f"Failed to retrieve patients: {str(e)}"
412
  )
413
 
414
  @router.get("/patients/{patient_id}", response_model=dict)
415
+ async def get_patient(patient_id: str):
416
+ logger.info(f"Retrieving patient: {patient_id}")
417
  try:
418
  patient = await patients_collection.find_one({
419
  "$or": [
 
460
  }
461
  }
462
 
463
+ logger.info(f"Successfully retrieved patient: {patient_id}")
464
  return response
465
 
466
  except ValueError as ve:
 
470
  detail="Invalid patient ID format"
471
  )
472
  except Exception as e:
473
+ logger.error(f"Failed to retrieve patient {patient_id}: {str(e)}")
474
  raise HTTPException(
475
  status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
476
+ detail=f"Failed to retrieve patient: {str(e)}"
477
  )
478
 
479
+ @router.post("/{patient_id}/notes", status_code=status.HTTP_201_CREATED)
480
+ async def add_note(
481
  patient_id: str,
482
  note: Note,
483
  current_user: dict = Depends(get_current_user)
 
531
  detail=f"Failed to add note: {str(e)}"
532
  )
533
 
534
+ # Export the router as 'patients' for api.__init__.py
535
+ patients = router