Ali2206 commited on
Commit
0aec591
·
verified ·
1 Parent(s): 36bd59b

Update api/routes.py

Browse files
Files changed (1) hide show
  1. api/routes.py +63 -70
api/routes.py CHANGED
@@ -136,89 +136,82 @@ async def list_patients(current_user: dict = Depends(get_current_user)):
136
 
137
  @router.post("/ehr/fetch-from-api")
138
  async def fetch_and_store_patients_from_fhir():
139
- fhir_patients_url = "https://hapi.fhir.org/baseR4/Patient?_count=50"
140
- fhir_encounters_url = "https://hapi.fhir.org/baseR4/Encounter?_count=100"
 
141
 
142
  try:
143
- async with httpx.AsyncClient() as client:
144
- # Fetch patients
145
- patient_res = await client.get(fhir_patients_url)
146
- if patient_res.status_code != 200:
147
- raise HTTPException(status_code=502, detail="Failed to fetch patients")
148
- patient_entries = patient_res.json().get("entry", [])
149
-
150
- # Fetch encounters
151
- encounter_res = await client.get(fhir_encounters_url)
152
- if encounter_res.status_code != 200:
153
- raise HTTPException(status_code=502, detail="Failed to fetch encounters")
154
- encounter_entries = encounter_res.json().get("entry", [])
155
-
156
- # Parse encounter notes grouped by patient ID
157
- patient_notes = {}
158
- for entry in encounter_entries:
159
- resource = entry.get("resource", {})
160
- ref = resource.get("subject", {}).get("reference") # e.g., "Patient/abc123"
161
- if not ref or "note" not in resource:
162
- continue
163
-
164
- patient_id = ref.split("/")[-1]
165
- notes_texts = [n.get("text") for n in resource.get("note", []) if n.get("text")]
166
- if notes_texts:
167
- patient_notes.setdefault(patient_id, []).extend(notes_texts)
168
 
169
- operations = []
170
- for entry in patient_entries:
171
- resource = entry.get("resource", {})
172
- fhir_id = resource.get("id")
173
- name_info = resource.get("name", [{}])[0]
174
- address_info = resource.get("address", [{}])[0]
175
 
176
- given = name_info.get("given", [""])[0]
177
- family = name_info.get("family", "")
178
- full_name = f"{given} {family}".strip()
179
 
 
 
 
 
 
180
  gender = resource.get("gender")
181
  birth_date = resource.get("birthDate")
182
- address = address_info.get("line", [""])[0]
183
- city = address_info.get("city", "")
184
- state = address_info.get("state", "")
185
- zip_code = address_info.get("postalCode", "")
186
 
187
- # Skip if any essential field is missing
188
- if not all([fhir_id, full_name, gender, birth_date, address, city, state, zip_code]):
 
 
 
 
 
 
189
  continue
190
 
191
- notes = patient_notes.get(fhir_id, [])
192
-
193
- operations.append(UpdateOne(
194
- {"fhir_id": fhir_id},
195
- {"$set": {
196
- "fhir_id": fhir_id,
197
- "full_name": full_name,
198
- "gender": gender,
199
- "date_of_birth": birth_date,
200
- "address": address,
201
- "city": city,
202
- "state": state,
203
- "zip": zip_code,
204
- "notes": notes,
205
- "created_at": datetime.utcnow()
206
- }},
207
- upsert=True
208
- ))
209
-
210
- if operations:
211
- result = await patients_collection.bulk_write(operations)
212
- return {
213
- "message": "Fetched and stored patients with linked notes successfully",
214
- "inserted": result.upserted_count,
215
- "modified": result.modified_count
216
- }
217
-
218
- return {"message": "No valid patients to store"}
 
 
 
 
 
 
 
 
 
 
 
 
219
 
220
  except Exception as e:
221
  raise HTTPException(status_code=500, detail=str(e))
 
 
222
  @router.get("/ehr/fhir-patients")
223
  async def list_fhir_patients():
224
  cursor = patients_collection.find({"fhir_id": {"$exists": True}})
 
136
 
137
  @router.post("/ehr/fetch-from-api")
138
  async def fetch_and_store_patients_from_fhir():
139
+ base_url = "https://hapi.fhir.org/baseR4"
140
+ patient_url = f"{base_url}/Patient?_count=50"
141
+ valid_patients = []
142
 
143
  try:
144
+ async with httpx.AsyncClient(timeout=30.0) as client:
145
+ patient_response = await client.get(patient_url)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
146
 
147
+ if patient_response.status_code != 200:
148
+ raise HTTPException(status_code=502, detail="Failed to fetch patients")
 
 
 
 
149
 
150
+ patients_data = patient_response.json().get("entry", [])
 
 
151
 
152
+ for p_entry in patients_data:
153
+ resource = p_entry.get("resource", {})
154
+ fhir_id = resource.get("id")
155
+ name = resource.get("name", [{}])[0]
156
+ full_name = f"{name.get('given', [''])[0]} {name.get('family', '')}".strip()
157
  gender = resource.get("gender")
158
  birth_date = resource.get("birthDate")
 
 
 
 
159
 
160
+ address_data = resource.get("address", [{}])[0]
161
+ address = address_data.get("line", [""])[0]
162
+ city = address_data.get("city", "")
163
+ state = address_data.get("state", "")
164
+ zip_code = address_data.get("postalCode", "")
165
+
166
+ # Skip incomplete patients
167
+ if not (fhir_id and full_name and gender and birth_date and address and city and state and zip_code):
168
  continue
169
 
170
+ # Fetch encounters for this patient
171
+ async with httpx.AsyncClient(timeout=30.0) as client:
172
+ encounter_response = await client.get(f"{base_url}/Encounter?subject=Patient/{fhir_id}")
173
+
174
+ if encounter_response.status_code != 200:
175
+ continue
176
+
177
+ encounter_entries = encounter_response.json().get("entry", [])
178
+ notes = []
179
+
180
+ for enc in encounter_entries:
181
+ enc_resource = enc.get("resource", {})
182
+ for n in enc_resource.get("note", []):
183
+ if n.get("text"):
184
+ notes.append(n["text"])
185
+
186
+ if not notes:
187
+ continue # ✅ Skip if no notes
188
+
189
+ valid_patients.append({
190
+ "fhir_id": fhir_id,
191
+ "full_name": full_name,
192
+ "gender": gender,
193
+ "date_of_birth": birth_date,
194
+ "address": address,
195
+ "city": city,
196
+ "state": state,
197
+ "zip": zip_code,
198
+ "notes": notes,
199
+ "created_at": datetime.utcnow()
200
+ })
201
+
202
+ if not valid_patients:
203
+ return {"message": "No patients with complete info and notes were found."}
204
+
205
+ result = await patients_collection.insert_many(valid_patients)
206
+ return {
207
+ "message": "Imported patients with notes",
208
+ "count": len(result.inserted_ids)
209
+ }
210
 
211
  except Exception as e:
212
  raise HTTPException(status_code=500, detail=str(e))
213
+
214
+
215
  @router.get("/ehr/fhir-patients")
216
  async def list_fhir_patients():
217
  cursor = patients_collection.find({"fhir_id": {"$exists": True}})