Ali2206 commited on
Commit
36bd59b
·
verified ·
1 Parent(s): 5cfc8ca

Update api/routes.py

Browse files
Files changed (1) hide show
  1. api/routes.py +51 -18
api/routes.py CHANGED
@@ -136,30 +136,59 @@ 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_api = "https://hapi.fhir.org/baseR4/Patient?_count=50"
 
140
 
141
  try:
142
  async with httpx.AsyncClient() as client:
143
- response = await client.get(fhir_api)
144
-
145
- if response.status_code != 200:
146
- raise HTTPException(status_code=502, detail="Failed to fetch from FHIR server.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
147
 
148
- data = response.json()
149
- entries = data.get("entry", [])
150
- if not entries:
151
- return {"message": "No patients found."}
152
 
153
  operations = []
154
-
155
- for entry in entries:
156
  resource = entry.get("resource", {})
157
- name = resource.get("name", [{}])[0]
158
- full_name = f"{name.get('given', [''])[0]} {name.get('family', '')}".strip()
159
-
160
  fhir_id = resource.get("id")
 
 
 
 
 
 
 
161
  gender = resource.get("gender")
162
  birth_date = resource.get("birthDate")
 
 
 
 
 
 
 
 
 
 
163
 
164
  operations.append(UpdateOne(
165
  {"fhir_id": fhir_id},
@@ -168,24 +197,28 @@ async def fetch_and_store_patients_from_fhir():
168
  "full_name": full_name,
169
  "gender": gender,
170
  "date_of_birth": birth_date,
 
 
 
 
 
171
  "created_at": datetime.utcnow()
172
  }},
173
- upsert=True # 👈 This avoids duplicates
174
  ))
175
 
176
  if operations:
177
  result = await patients_collection.bulk_write(operations)
178
  return {
179
- "message": "Fetched and stored successfully",
180
  "inserted": result.upserted_count,
181
  "modified": result.modified_count
182
  }
183
 
184
- return {"message": "No patients to store"}
185
 
186
  except Exception as e:
187
  raise HTTPException(status_code=500, detail=str(e))
188
-
189
  @router.get("/ehr/fhir-patients")
190
  async def list_fhir_patients():
191
  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
+ 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},
 
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}})