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

Update api/routes.py

Browse files
Files changed (1) hide show
  1. api/routes.py +47 -76
api/routes.py CHANGED
@@ -1,15 +1,15 @@
1
- from fastapi import APIRouter, HTTPException, Depends, Body
2
  from fastapi.security import OAuth2PasswordRequestForm
3
  from models.schemas import SignupForm, TokenResponse, PatientCreate, DoctorCreate, AppointmentCreate
4
  from db.mongo import users_collection, patients_collection, appointments_collection
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 +55,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,79 +82,65 @@ 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 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}})
@@ -181,5 +151,6 @@ async def list_fhir_patients():
181
  "full_name": p.get("full_name"),
182
  "gender": p.get("gender"),
183
  "date_of_birth": p.get("date_of_birth"),
 
184
  })
185
  return patients
 
1
+ from fastapi import APIRouter, HTTPException, Depends
2
  from fastapi.security import OAuth2PasswordRequestForm
3
  from models.schemas import SignupForm, TokenResponse, PatientCreate, DoctorCreate, AppointmentCreate
4
  from db.mongo import users_collection, patients_collection, appointments_collection
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
 
 
 
9
  from pymongo import UpdateOne
10
+ import json
11
+ from pathlib import Path
12
+ import traceback
13
 
14
  router = APIRouter()
15
 
 
55
  await users_collection.insert_one(user_doc)
56
  return {"success": True, "message": "Doctor account created"}
57
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58
  # --- LOGIN ---
59
  @router.post("/login", response_model=TokenResponse)
60
  async def login(form_data: OAuth2PasswordRequestForm = Depends()):
 
82
  "created_at": user.get("created_at", "")
83
  }
84
 
85
+ # --- IMPORT MOCKED FHIR PATIENTS ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86
  @router.post("/ehr/fetch-from-api")
87
  async def fetch_and_store_patients_from_fhir():
88
+ json_path = Path("fhir_mock_patients.json")
 
 
89
 
90
+ if not json_path.exists():
91
+ raise HTTPException(status_code=404, detail="Mock FHIR JSON file not found")
92
 
93
+ try:
94
+ with open(json_path, "r", encoding="utf-8") as f:
95
+ data = json.load(f)
96
 
97
+ valid_patients = []
98
+ for patient in data.get("entry", []):
99
+ resource = patient.get("resource", {})
100
+ fhir_id = resource.get("id")
101
+ name = resource.get("name", [{}])[0]
102
+ full_name = f"{name.get('given', [''])[0]} {name.get('family', '')}".strip()
103
+ gender = resource.get("gender")
104
+ birth_date = resource.get("birthDate")
105
+
106
+ address_data = resource.get("address", [{}])[0]
107
+ address = address_data.get("line", [""])[0]
108
+ city = address_data.get("city", "")
109
+ state = address_data.get("state", "")
110
+ zip_code = address_data.get("postalCode", "")
111
+
112
+ notes = []
113
+ for n in resource.get("note", []):
114
+ if n.get("text"):
115
+ notes.append(n["text"])
116
+
117
+ if not all([fhir_id, full_name, gender, birth_date, address, city, state, zip_code, notes]):
118
  continue
119
 
120
  valid_patients.append({
121
+ "fhir_id": fhir_id,
122
+ "full_name": full_name,
123
+ "gender": gender,
124
+ "date_of_birth": birth_date,
125
+ "address": address,
126
+ "city": city,
127
+ "state": state,
128
+ "zip": zip_code,
129
+ "notes": notes,
130
  "created_at": datetime.utcnow()
131
  })
132
 
133
  if not valid_patients:
134
+ return {"message": "No valid patients found in JSON."}
135
 
136
  result = await patients_collection.insert_many(valid_patients)
137
+ return {"message": "Patients imported", "count": len(result.inserted_ids)}
138
 
139
  except Exception as e:
140
+ traceback.print_exc()
141
  raise HTTPException(status_code=500, detail=str(e))
142
 
143
+ # --- GET FHIR PATIENTS ---
144
  @router.get("/ehr/fhir-patients")
145
  async def list_fhir_patients():
146
  cursor = patients_collection.find({"fhir_id": {"$exists": True}})
 
151
  "full_name": p.get("full_name"),
152
  "gender": p.get("gender"),
153
  "date_of_birth": p.get("date_of_birth"),
154
+ "notes": p.get("notes", [])
155
  })
156
  return patients