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

Update api/routes.py

Browse files
Files changed (1) hide show
  1. api/routes.py +26 -11
api/routes.py CHANGED
@@ -9,6 +9,7 @@ from bson.errors import InvalidId
9
  from typing import Optional, List
10
  from pydantic import BaseModel
11
  import httpx
 
12
 
13
  router = APIRouter()
14
 
@@ -132,6 +133,7 @@ async def list_patients(current_user: dict = Depends(get_current_user)):
132
  return patients
133
 
134
  # --- IMPORT FROM PUBLIC FHIR API ---
 
135
  @router.post("/ehr/fetch-from-api")
136
  async def fetch_and_store_patients_from_fhir():
137
  fhir_api = "https://hapi.fhir.org/baseR4/Patient?_count=50"
@@ -148,29 +150,42 @@ async def fetch_and_store_patients_from_fhir():
148
  if not entries:
149
  return {"message": "No patients found."}
150
 
151
- patients = []
152
 
153
  for entry in entries:
154
  resource = entry.get("resource", {})
155
  name = resource.get("name", [{}])[0]
156
  full_name = f"{name.get('given', [''])[0]} {name.get('family', '')}".strip()
157
 
158
- patient = {
159
- "fhir_id": resource.get("id"),
160
- "full_name": full_name,
161
- "gender": resource.get("gender"),
162
- "date_of_birth": resource.get("birthDate"),
163
- "created_at": datetime.utcnow()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
164
  }
165
- patients.append(patient)
166
 
167
- result = await patients_collection.insert_many(patients)
168
- return {"message": "Fetched and stored successfully", "count": len(result.inserted_ids)}
169
 
170
  except Exception as e:
171
  raise HTTPException(status_code=500, detail=str(e))
172
 
173
-
174
  @router.get("/ehr/fhir-patients")
175
  async def list_fhir_patients():
176
  cursor = patients_collection.find({"fhir_id": {"$exists": True}})
 
9
  from typing import Optional, List
10
  from pydantic import BaseModel
11
  import httpx
12
+ from pymongo import UpdateOne
13
 
14
  router = APIRouter()
15
 
 
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
  fhir_api = "https://hapi.fhir.org/baseR4/Patient?_count=50"
 
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},
166
+ {"$set": {
167
+ "fhir_id": fhir_id,
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}})