Ali2206 commited on
Commit
c9c1c50
·
verified ·
1 Parent(s): b2fd94d

Update api/routes.py

Browse files
Files changed (1) hide show
  1. api/routes.py +34 -17
api/routes.py CHANGED
@@ -85,18 +85,21 @@ async def get_me(current_user: dict = Depends(get_current_user)):
85
  # --- IMPORT MOCKED FHIR PATIENTS ---
86
  @router.post("/ehr/fetch-from-api")
87
  async def fetch_and_store_patients_from_fhir():
88
- json_path = Path("fhir_mock_patients.json")
89
-
90
- if not json_path.exists():
91
- raise HTTPException(status_code=404, detail="Mock FHIR JSON file not found")
92
 
93
  try:
94
- with open(json_path, "r", encoding="utf-8") as f:
95
- data = json.load(f)
 
 
 
 
 
96
 
97
- valid_patients = []
98
- for patient in data.get("entry", []):
99
- resource = patient.get("resource", {})
100
  fhir_id = resource.get("id")
101
  name = resource.get("name", [{}])[0]
102
  full_name = f"{name.get('given', [''])[0]} {name.get('family', '')}".strip()
@@ -109,14 +112,25 @@ async def fetch_and_store_patients_from_fhir():
109
  state = address_data.get("state", "")
110
  zip_code = address_data.get("postalCode", "")
111
 
112
- notes = []
113
- for n in resource.get("note", []):
114
- if n.get("text"):
115
- notes.append(n["text"])
116
 
117
- if not all([fhir_id, full_name, gender, birth_date, address, city, state, zip_code, notes]):
118
  continue
119
 
 
 
 
 
 
 
 
 
 
 
 
 
120
  valid_patients.append({
121
  "fhir_id": fhir_id,
122
  "full_name": full_name,
@@ -131,15 +145,18 @@ async def fetch_and_store_patients_from_fhir():
131
  })
132
 
133
  if not valid_patients:
134
- return {"message": "No valid patients found in JSON."}
135
 
136
  result = await patients_collection.insert_many(valid_patients)
137
- return {"message": "Patients imported", "count": len(result.inserted_ids)}
 
 
 
138
 
139
  except Exception as e:
140
- traceback.print_exc()
141
  raise HTTPException(status_code=500, detail=str(e))
142
 
 
143
  # --- GET FHIR PATIENTS ---
144
  @router.get("/ehr/fhir-patients")
145
  async def list_fhir_patients():
 
85
  # --- IMPORT MOCKED FHIR PATIENTS ---
86
  @router.post("/ehr/fetch-from-api")
87
  async def fetch_and_store_patients_from_fhir():
88
+ base_url = "https://launch.smarthealthit.org/v/r4/fhir"
89
+ patient_url = f"{base_url}/Patient?_count=50"
90
+ valid_patients = []
 
91
 
92
  try:
93
+ async with httpx.AsyncClient(timeout=30.0) as client:
94
+ patient_response = await client.get(patient_url)
95
+
96
+ if patient_response.status_code != 200:
97
+ raise HTTPException(status_code=502, detail="Failed to fetch patients")
98
+
99
+ patients_data = patient_response.json().get("entry", [])
100
 
101
+ for p_entry in patients_data:
102
+ resource = p_entry.get("resource", {})
 
103
  fhir_id = resource.get("id")
104
  name = resource.get("name", [{}])[0]
105
  full_name = f"{name.get('given', [''])[0]} {name.get('family', '')}".strip()
 
112
  state = address_data.get("state", "")
113
  zip_code = address_data.get("postalCode", "")
114
 
115
+ # Fetch encounters for this patient
116
+ async with httpx.AsyncClient(timeout=30.0) as client:
117
+ encounter_response = await client.get(f"{base_url}/Encounter?subject=Patient/{fhir_id}")
 
118
 
119
+ if encounter_response.status_code != 200:
120
  continue
121
 
122
+ encounter_entries = encounter_response.json().get("entry", [])
123
+ notes = []
124
+
125
+ for enc in encounter_entries:
126
+ enc_resource = enc.get("resource", {})
127
+ for n in enc_resource.get("note", []):
128
+ if n.get("text"):
129
+ notes.append(n["text"])
130
+
131
+ if not encounter_entries:
132
+ continue # Skip if no notes
133
+
134
  valid_patients.append({
135
  "fhir_id": fhir_id,
136
  "full_name": full_name,
 
145
  })
146
 
147
  if not valid_patients:
148
+ return {"message": "No patients with complete info and notes were found."}
149
 
150
  result = await patients_collection.insert_many(valid_patients)
151
+ return {
152
+ "message": "Imported patients with notes",
153
+ "count": len(result.inserted_ids)
154
+ }
155
 
156
  except Exception as e:
 
157
  raise HTTPException(status_code=500, detail=str(e))
158
 
159
+
160
  # --- GET FHIR PATIENTS ---
161
  @router.get("/ehr/fhir-patients")
162
  async def list_fhir_patients():