Ali2206 commited on
Commit
92f7ec1
·
verified ·
1 Parent(s): 69db116

Update api/routes.py

Browse files
Files changed (1) hide show
  1. api/routes.py +20 -61
api/routes.py CHANGED
@@ -128,90 +128,49 @@ async def list_patients(current_user: dict = Depends(get_current_user)):
128
  "full_name": p.get("full_name", ""),
129
  "date_of_birth": p.get("date_of_birth"),
130
  "gender": p.get("gender", ""),
131
- "notes": p.get("notes", "")
132
  })
133
  return patients
134
 
135
- # --- IMPORT FROM PUBLIC FHIR API ---
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 encounter_entries:
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}})
 
128
  "full_name": p.get("full_name", ""),
129
  "date_of_birth": p.get("date_of_birth"),
130
  "gender": p.get("gender", ""),
131
+ "notes": p.get("notes", [])
132
  })
133
  return patients
134
 
135
+ # --- IMPORT FROM FHIR (Switch to mock source with full data) ---
 
136
  @router.post("/ehr/fetch-from-api")
137
  async def fetch_and_store_patients_from_fhir():
 
 
 
 
138
  try:
139
  async with httpx.AsyncClient(timeout=30.0) as client:
140
+ response = await client.get("https://txagent-medical-data.s3.amazonaws.com/fhir_mock_patients.json")
 
 
 
141
 
142
+ if response.status_code != 200:
143
+ raise HTTPException(status_code=502, detail="Failed to fetch mock FHIR patients")
144
 
145
+ raw_data = response.json()
146
+ valid_patients = []
 
 
 
 
 
147
 
148
+ for resource in raw_data:
149
+ if not all(k in resource for k in ("fhir_id", "full_name", "gender", "date_of_birth", "address", "city", "state", "zip", "notes")):
 
 
 
 
 
 
150
  continue
151
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
152
  valid_patients.append({
153
+ "fhir_id": resource["fhir_id"],
154
+ "full_name": resource["full_name"],
155
+ "gender": resource["gender"],
156
+ "date_of_birth": resource["date_of_birth"],
157
+ "address": resource["address"],
158
+ "city": resource["city"],
159
+ "state": resource["state"],
160
+ "zip": resource["zip"],
161
+ "notes": resource["notes"],
162
  "created_at": datetime.utcnow()
163
  })
164
 
165
  if not valid_patients:
166
+ return {"message": "No complete patients in mock file."}
167
 
168
  result = await patients_collection.insert_many(valid_patients)
169
+ return {"message": "Mock FHIR patients imported", "count": len(result.inserted_ids)}
 
 
 
170
 
171
  except Exception as e:
172
  raise HTTPException(status_code=500, detail=str(e))
173
 
 
174
  @router.get("/ehr/fhir-patients")
175
  async def list_fhir_patients():
176
  cursor = patients_collection.find({"fhir_id": {"$exists": True}})