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

Update api/routes/patients.py

Browse files
Files changed (1) hide show
  1. api/routes/patients.py +21 -84
api/routes/patients.py CHANGED
@@ -1,4 +1,4 @@
1
- from fastapi import APIRouter, HTTPException, Depends, Query, status
2
  from db.mongo import patients_collection
3
  from core.security import get_current_user
4
  from utils.db import create_indexes
@@ -26,76 +26,14 @@ logging.basicConfig(
26
  )
27
  logger = logging.getLogger(__name__)
28
 
29
- router = APIRouter()
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("/ehr/patients/add", status_code=status.HTTP_201_CREATED)
37
- async def create_patient_ehr(
38
- patient_data: PatientCreate,
39
- current_user: dict = Depends(get_current_user)
40
- ):
41
- """Create a new patient in the database via /ehr/patients endpoint"""
42
- logger.info(f"Creating new patient via /ehr/patients by user {current_user.get('email')}")
43
-
44
- if current_user.get('role') not in ['admin', 'doctor']:
45
- logger.warning(f"Unauthorized create attempt by {current_user.get('email')}")
46
- raise HTTPException(
47
- status_code=status.HTTP_403_FORBIDDEN,
48
- detail="Only administrators and doctors can create patients"
49
- )
50
-
51
- try:
52
- # Prepare the patient document
53
- patient_doc = patient_data.dict()
54
- now = datetime.utcnow().isoformat()
55
-
56
- # Add system-generated fields
57
- patient_doc.update({
58
- "fhir_id": str(uuid.uuid4()),
59
- "import_date": now,
60
- "last_updated": now,
61
- "source": "manual",
62
- "created_by": current_user.get('email')
63
- })
64
-
65
- # Ensure arrays exist even if empty
66
- for field in ['conditions', 'medications', 'encounters', 'notes']:
67
- if field not in patient_doc:
68
- patient_doc[field] = []
69
-
70
- # Insert the patient document
71
- result = await patients_collection.insert_one(patient_doc)
72
-
73
- # Return the created patient with the generated ID
74
- created_patient = await patients_collection.find_one(
75
- {"_id": result.inserted_id}
76
- )
77
-
78
- if not created_patient:
79
- logger.error("Failed to retrieve created patient")
80
- raise HTTPException(
81
- status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
82
- detail="Failed to retrieve created patient"
83
- )
84
-
85
- created_patient["id"] = str(created_patient["_id"])
86
- del created_patient["_id"]
87
-
88
- logger.info(f"Successfully created patient {created_patient['fhir_id']} via /ehr/patients")
89
- return created_patient
90
-
91
- except Exception as e:
92
- logger.error(f"Failed to create patient via /ehr/patients: {str(e)}")
93
- raise HTTPException(
94
- status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
95
- detail=f"Failed to create patient: {str(e)}"
96
- )
97
-
98
- @router.post("/", status_code=status.HTTP_201_CREATED)
99
  async def create_patient(
100
  patient_data: PatientCreate,
101
  current_user: dict = Depends(get_current_user)
@@ -260,7 +198,7 @@ async def process_synthea_patient(bundle: dict, file_path: str) -> Optional[dict
260
  logger.warning(f"No valid patient data found in {file_path}")
261
  return None
262
 
263
- @router.post("/import", status_code=status.HTTP_201_CREATED)
264
  async def import_patients(
265
  limit: int = Query(100, ge=1, le=1000),
266
  current_user: dict = Depends(get_current_user)
@@ -401,15 +339,15 @@ async def import_patients(
401
  )
402
 
403
  @router.get("/patients", response_model=List[dict])
404
- async def list_patients(
405
  search: Optional[str] = Query(None),
406
  min_notes: int = Query(0, ge=0),
407
  min_conditions: int = Query(0, ge=0),
408
- limit: int = Query(100, ge=1, le=500),
409
  skip: int = Query(0, ge=0)
410
  ):
411
- logger.info(f"Listing patients with search: {search}, limit: {limit}, skip: {skip}")
412
- query = {"source": "synthea"}
413
 
414
  if search:
415
  query["$or"] = [
@@ -430,10 +368,10 @@ async def list_patients(
430
  "date_of_birth": 1,
431
  "city": 1,
432
  "state": 1,
433
- "conditions": 1,
434
- "medications": 1,
435
- "encounters": 1,
436
- "notes": 1
437
  }
438
 
439
  try:
@@ -465,15 +403,15 @@ async def list_patients(
465
  return patients
466
 
467
  except Exception as e:
468
- logger.error(f"Failed to list patients: {str(e)}")
469
  raise HTTPException(
470
  status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
471
  detail=f"Failed to retrieve patients: {str(e)}"
472
  )
473
 
474
  @router.get("/patients/{patient_id}", response_model=dict)
475
- async def get_patient(patient_id: str):
476
- logger.info(f"Retrieving patient: {patient_id}")
477
  try:
478
  patient = await patients_collection.find_one({
479
  "$or": [
@@ -520,7 +458,7 @@ async def get_patient(patient_id: str):
520
  }
521
  }
522
 
523
- logger.info(f"Successfully retrieved patient: {patient_id}")
524
  return response
525
 
526
  except ValueError as ve:
@@ -530,14 +468,14 @@ async def get_patient(patient_id: str):
530
  detail="Invalid patient ID format"
531
  )
532
  except Exception as e:
533
- logger.error(f"Failed to retrieve patient {patient_id}: {str(e)}")
534
  raise HTTPException(
535
  status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
536
- detail=f"Failed to retrieve patient: {str(e)}"
537
  )
538
 
539
- @router.post("/{patient_id}/notes", status_code=status.HTTP_201_CREATED)
540
- async def add_note(
541
  patient_id: str,
542
  note: Note,
543
  current_user: dict = Depends(get_current_user)
@@ -591,5 +529,4 @@ async def add_note(
591
  detail=f"Failed to add note: {str(e)}"
592
  )
593
 
594
- # Export the router as 'patients' for api.__init__.py
595
- patients = router
 
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
4
  from utils.db import create_indexes
 
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
  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
  )
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"] = [
 
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
  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
  }
459
  }
460
 
461
+ logger.info(f"Successfully retrieved patient details: {patient_id}")
462
  return response
463
 
464
  except ValueError as ve:
 
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
  detail=f"Failed to add note: {str(e)}"
530
  )
531
 
532
+ patients = router