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

Update api/routes.py

Browse files
Files changed (1) hide show
  1. api/routes.py +43 -35
api/routes.py CHANGED
@@ -101,60 +101,68 @@ async def fetch_and_store_patients_from_fhir():
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()
106
  gender = resource.get("gender")
107
  birth_date = resource.get("birthDate")
108
 
109
  address_data = resource.get("address", [{}])[0]
110
- address = address_data.get("line", [""])[0]
111
  city = address_data.get("city", "")
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,
137
- "gender": gender,
138
- "date_of_birth": birth_date,
139
- "address": address,
140
- "city": city,
141
- "state": state,
142
- "zip": zip_code,
143
- "notes": notes,
144
- "created_at": datetime.utcnow()
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 ---
 
101
  for p_entry in patients_data:
102
  resource = p_entry.get("resource", {})
103
  fhir_id = resource.get("id")
104
+ name_data = resource.get("name", [{}])[0]
105
+ full_name = f"{name_data.get('given', [''])[0]} {name_data.get('family', '')}".strip()
106
  gender = resource.get("gender")
107
  birth_date = resource.get("birthDate")
108
 
109
  address_data = resource.get("address", [{}])[0]
110
+ address = address_data.get("line", [""])[0] if "line" in address_data else ""
111
  city = address_data.get("city", "")
112
  state = address_data.get("state", "")
113
  zip_code = address_data.get("postalCode", "")
114
 
115
+ # Ensure required fields are present
116
+ if not all([fhir_id, full_name, gender, birth_date, address, city, state, zip_code]):
 
 
 
117
  continue
118
 
119
+ # Fetch encounters with notes
120
+ try:
121
+ async with httpx.AsyncClient(timeout=20.0) as client:
122
+ enc_response = await client.get(f"{base_url}/Encounter?subject=Patient/{fhir_id}")
123
+
124
+ encounter_entries = enc_response.json().get("entry", []) if enc_response.status_code == 200 else []
125
+ notes = []
126
+
127
+ for enc in encounter_entries:
128
+ enc_res = enc.get("resource", {})
129
+ for note in enc_res.get("note", []):
130
+ text = note.get("text")
131
+ if text:
132
+ notes.append(text)
133
+
134
+ if not notes:
135
+ continue # Skip if no notes
136
+
137
+ valid_patients.append({
138
+ "fhir_id": fhir_id,
139
+ "full_name": full_name,
140
+ "gender": gender,
141
+ "date_of_birth": birth_date,
142
+ "address": address,
143
+ "city": city,
144
+ "state": state,
145
+ "zip": zip_code,
146
+ "notes": notes,
147
+ "created_at": datetime.utcnow()
148
+ })
149
+
150
+ except Exception as enc_err:
151
+ print(f"Skipping encounter fetch error for {fhir_id}: {enc_err}")
152
+ continue
153
 
154
  if not valid_patients:
155
+ return {"message": "No valid patients found with complete data and notes."}
156
 
157
  result = await patients_collection.insert_many(valid_patients)
158
  return {
159
+ "message": "Imported valid patients with notes",
160
  "count": len(result.inserted_ids)
161
  }
162
 
163
  except Exception as e:
164
+ print("❌ Server-side error during FHIR import:", e)
165
+ raise HTTPException(status_code=500, detail="Server error during patient import.")
166
 
167
 
168
  # --- GET FHIR PATIENTS ---