Ali2206 commited on
Commit
5a83597
·
verified ·
1 Parent(s): 203ffde

Update api/routes.py

Browse files
Files changed (1) hide show
  1. api/routes.py +23 -63
api/routes.py CHANGED
@@ -5,11 +5,10 @@ from db.mongo import users_collection, patients_collection, appointments_collect
5
  from core.security import hash_password, verify_password, create_access_token, get_current_user
6
  from datetime import datetime
7
  from bson import ObjectId
8
- from bson.errors import InvalidId
9
  from typing import Optional, List
10
  from pydantic import BaseModel
11
- import httpx
12
  from pymongo import UpdateOne
 
13
 
14
  router = APIRouter()
15
 
@@ -55,22 +54,6 @@ async def create_doctor(data: DoctorCreate):
55
  await users_collection.insert_one(user_doc)
56
  return {"success": True, "message": "Doctor account created"}
57
 
58
- # --- GET ALL DOCTORS ---
59
- @router.get("/doctors")
60
- async def list_doctors():
61
- cursor = users_collection.find({"role": "doctor"})
62
- doctors = []
63
- async for doc in cursor:
64
- doctors.append({
65
- "id": str(doc["_id"]),
66
- "full_name": doc.get("full_name", ""),
67
- "email": doc.get("email", ""),
68
- "matricule": doc.get("matricule", ""),
69
- "specialty": doc.get("specialty", ""),
70
- "created_at": doc.get("created_at"),
71
- })
72
- return doctors
73
-
74
  # --- LOGIN ---
75
  @router.post("/login", response_model=TokenResponse)
76
  async def login(form_data: OAuth2PasswordRequestForm = Depends()):
@@ -98,42 +81,7 @@ async def get_me(current_user: dict = Depends(get_current_user)):
98
  "created_at": user.get("created_at", "")
99
  }
100
 
101
- # --- ADD NEW PATIENT ---
102
- @router.post("/patients")
103
- async def add_patient(data: PatientCreate, current_user: dict = Depends(get_current_user)):
104
- if current_user.get("role") != "doctor":
105
- raise HTTPException(status_code=403, detail="Only doctors can add patients")
106
-
107
- patient_doc = {
108
- **data.dict(),
109
- "date_of_birth": datetime.combine(data.date_of_birth, datetime.min.time()),
110
- "contact": data.contact.dict() if data.contact else {},
111
- "created_by": current_user["email"],
112
- "created_at": datetime.utcnow()
113
- }
114
- result = await patients_collection.insert_one(patient_doc)
115
- return {"id": str(result.inserted_id), "message": "Patient created successfully"}
116
-
117
- # --- GET ALL PATIENTS ---
118
- @router.get("/patients")
119
- async def list_patients(current_user: dict = Depends(get_current_user)):
120
- if current_user.get("role") != "doctor":
121
- raise HTTPException(status_code=403, detail="Only doctors can view patients")
122
-
123
- cursor = patients_collection.find({"created_by": current_user["email"]})
124
- patients = []
125
- async for p in cursor:
126
- patients.append({
127
- "id": str(p["_id"]),
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
  fhir_patients_url = "https://hapi.fhir.org/baseR4/Patient?_count=50"
@@ -141,23 +89,20 @@ async def fetch_and_store_patients_from_fhir():
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
 
@@ -173,10 +118,7 @@ async def fetch_and_store_patients_from_fhir():
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]
@@ -184,7 +126,6 @@ async def fetch_and_store_patients_from_fhir():
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
 
@@ -219,6 +160,8 @@ async def fetch_and_store_patients_from_fhir():
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}})
@@ -229,5 +172,22 @@ async def list_fhir_patients():
229
  "full_name": p.get("full_name"),
230
  "gender": p.get("gender"),
231
  "date_of_birth": p.get("date_of_birth"),
 
232
  })
233
  return patients
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
  from core.security import hash_password, verify_password, create_access_token, get_current_user
6
  from datetime import datetime
7
  from bson import ObjectId
 
8
  from typing import Optional, List
9
  from pydantic import BaseModel
 
10
  from pymongo import UpdateOne
11
+ import httpx
12
 
13
  router = APIRouter()
14
 
 
54
  await users_collection.insert_one(user_doc)
55
  return {"success": True, "message": "Doctor account created"}
56
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57
  # --- LOGIN ---
58
  @router.post("/login", response_model=TokenResponse)
59
  async def login(form_data: OAuth2PasswordRequestForm = Depends()):
 
81
  "created_at": user.get("created_at", "")
82
  }
83
 
84
+ # --- FETCH AND STORE FHIR PATIENTS ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85
  @router.post("/ehr/fetch-from-api")
86
  async def fetch_and_store_patients_from_fhir():
87
  fhir_patients_url = "https://hapi.fhir.org/baseR4/Patient?_count=50"
 
89
 
90
  try:
91
  async with httpx.AsyncClient() as client:
 
92
  patient_res = await client.get(fhir_patients_url)
93
  if patient_res.status_code != 200:
94
  raise HTTPException(status_code=502, detail="Failed to fetch patients")
95
  patient_entries = patient_res.json().get("entry", [])
96
 
 
97
  encounter_res = await client.get(fhir_encounters_url)
98
  if encounter_res.status_code != 200:
99
  raise HTTPException(status_code=502, detail="Failed to fetch encounters")
100
  encounter_entries = encounter_res.json().get("entry", [])
101
 
 
102
  patient_notes = {}
103
  for entry in encounter_entries:
104
  resource = entry.get("resource", {})
105
+ ref = resource.get("subject", {}).get("reference")
106
  if not ref or "note" not in resource:
107
  continue
108
 
 
118
  name_info = resource.get("name", [{}])[0]
119
  address_info = resource.get("address", [{}])[0]
120
 
121
+ full_name = f"{name_info.get('given', [''])[0]} {name_info.get('family', '')}".strip()
 
 
 
122
  gender = resource.get("gender")
123
  birth_date = resource.get("birthDate")
124
  address = address_info.get("line", [""])[0]
 
126
  state = address_info.get("state", "")
127
  zip_code = address_info.get("postalCode", "")
128
 
 
129
  if not all([fhir_id, full_name, gender, birth_date, address, city, state, zip_code]):
130
  continue
131
 
 
160
 
161
  except Exception as e:
162
  raise HTTPException(status_code=500, detail=str(e))
163
+
164
+ # --- GET FHIR PATIENTS ---
165
  @router.get("/ehr/fhir-patients")
166
  async def list_fhir_patients():
167
  cursor = patients_collection.find({"fhir_id": {"$exists": True}})
 
172
  "full_name": p.get("full_name"),
173
  "gender": p.get("gender"),
174
  "date_of_birth": p.get("date_of_birth"),
175
+ "notes": p.get("notes", [])
176
  })
177
  return patients
178
+
179
+ # --- UPDATE A FHIR PATIENT ---
180
+ @router.patch("/ehr/fhir-patients/{patient_id}")
181
+ async def update_fhir_patient(patient_id: str, payload: dict = Body(...), current_user: dict = Depends(get_current_user)):
182
+ if current_user.get("role") != "doctor":
183
+ raise HTTPException(status_code=403, detail="Only doctors can update patient records")
184
+
185
+ try:
186
+ patient = await patients_collection.find_one({"_id": ObjectId(patient_id)})
187
+ if not patient:
188
+ raise HTTPException(status_code=404, detail="Patient not found")
189
+
190
+ await patients_collection.update_one({"_id": ObjectId(patient_id)}, {"$set": payload})
191
+ return {"message": "Patient updated successfully"}
192
+ except Exception as e:
193
+ raise HTTPException(status_code=500, detail=str(e))