Spaces:
Runtime error
Runtime error
Update endpoints.py
Browse files- endpoints.py +21 -39
endpoints.py
CHANGED
|
@@ -13,6 +13,7 @@ import io
|
|
| 13 |
from datetime import datetime
|
| 14 |
from bson import ObjectId
|
| 15 |
import asyncio
|
|
|
|
| 16 |
|
| 17 |
def create_router(agent, logger, patients_collection, analysis_collection, users_collection):
|
| 18 |
router = APIRouter()
|
|
@@ -34,10 +35,6 @@ def create_router(agent, logger, patients_collection, analysis_collection, users
|
|
| 34 |
):
|
| 35 |
logger.info(f"Fetching analysis results by {current_user['email']}")
|
| 36 |
try:
|
| 37 |
-
# Get all existing user emails to filter out analyses for deleted users
|
| 38 |
-
existing_users = await users_collection.find({}, {"email": 1}).to_list(length=None)
|
| 39 |
-
existing_user_emails = {user["email"] for user in existing_users}
|
| 40 |
-
|
| 41 |
query = {}
|
| 42 |
if name:
|
| 43 |
name_regex = re.compile(name, re.IGNORECASE)
|
|
@@ -53,12 +50,6 @@ def create_router(agent, logger, patients_collection, analysis_collection, users
|
|
| 53 |
patient = await patients_collection.find_one({"fhir_id": analysis.get("patient_id")})
|
| 54 |
if not patient:
|
| 55 |
continue # Skip if patient no longer exists
|
| 56 |
-
|
| 57 |
-
# Check if the patient is associated with an existing user
|
| 58 |
-
patient_owner = await users_collection.find_one({"email": patient.get("created_by")})
|
| 59 |
-
if not patient_owner or patient_owner["email"] not in existing_user_emails:
|
| 60 |
-
continue # Skip if the patient's owner (user) no longer exists
|
| 61 |
-
|
| 62 |
analysis["full_name"] = patient.get("full_name", "Unknown")
|
| 63 |
analysis["_id"] = str(analysis["_id"])
|
| 64 |
enriched_results.append(analysis)
|
|
@@ -255,45 +246,36 @@ def create_router(agent, logger, patients_collection, analysis_collection, users
|
|
| 255 |
detail=f"Failed to analyze report: {str(e)}"
|
| 256 |
)
|
| 257 |
|
| 258 |
-
@router.delete("/
|
| 259 |
-
async def
|
| 260 |
-
|
| 261 |
current_user: dict = Depends(get_current_user)
|
| 262 |
):
|
| 263 |
-
logger.info(f"
|
| 264 |
try:
|
| 265 |
-
# Check if the
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
# Find the user to delete
|
| 270 |
-
user_to_delete = await users_collection.find_one({"email": user_email})
|
| 271 |
-
if not user_to_delete:
|
| 272 |
-
raise HTTPException(status_code=404, detail="User not found")
|
| 273 |
-
|
| 274 |
-
# Find all patients created by this user
|
| 275 |
-
user_patients = await patients_collection.find({"created_by": user_email}).to_list(length=None)
|
| 276 |
-
patient_ids = [patient["fhir_id"] for patient in user_patients if "fhir_id" in patient]
|
| 277 |
|
| 278 |
-
#
|
| 279 |
-
if
|
| 280 |
-
|
| 281 |
-
logger.info(f"Deleted analyses for {len(patient_ids)} patients associated with user {user_email}")
|
| 282 |
|
| 283 |
-
# Delete
|
| 284 |
-
await
|
| 285 |
-
logger.info(f"Deleted
|
| 286 |
|
| 287 |
-
# Delete the
|
| 288 |
-
await
|
| 289 |
-
logger.info(f"
|
| 290 |
|
| 291 |
-
return {"status": "success", "message": f"
|
| 292 |
|
| 293 |
except HTTPException:
|
| 294 |
raise
|
| 295 |
except Exception as e:
|
| 296 |
-
logger.error(f"Error deleting
|
| 297 |
-
raise HTTPException(status_code=500, detail=f"Failed to delete
|
| 298 |
|
| 299 |
return router
|
|
|
|
| 13 |
from datetime import datetime
|
| 14 |
from bson import ObjectId
|
| 15 |
import asyncio
|
| 16 |
+
from bson.errors import InvalidId
|
| 17 |
|
| 18 |
def create_router(agent, logger, patients_collection, analysis_collection, users_collection):
|
| 19 |
router = APIRouter()
|
|
|
|
| 35 |
):
|
| 36 |
logger.info(f"Fetching analysis results by {current_user['email']}")
|
| 37 |
try:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 38 |
query = {}
|
| 39 |
if name:
|
| 40 |
name_regex = re.compile(name, re.IGNORECASE)
|
|
|
|
| 50 |
patient = await patients_collection.find_one({"fhir_id": analysis.get("patient_id")})
|
| 51 |
if not patient:
|
| 52 |
continue # Skip if patient no longer exists
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 53 |
analysis["full_name"] = patient.get("full_name", "Unknown")
|
| 54 |
analysis["_id"] = str(analysis["_id"])
|
| 55 |
enriched_results.append(analysis)
|
|
|
|
| 246 |
detail=f"Failed to analyze report: {str(e)}"
|
| 247 |
)
|
| 248 |
|
| 249 |
+
@router.delete("/patients/{patient_id}")
|
| 250 |
+
async def delete_patient(
|
| 251 |
+
patient_id: str,
|
| 252 |
current_user: dict = Depends(get_current_user)
|
| 253 |
):
|
| 254 |
+
logger.info(f"Patient deletion initiated by {current_user['email']} for patient {patient_id}")
|
| 255 |
try:
|
| 256 |
+
# Check if the patient exists
|
| 257 |
+
patient = await patients_collection.find_one({"fhir_id": patient_id})
|
| 258 |
+
if not patient:
|
| 259 |
+
raise HTTPException(status_code=404, detail="Patient not found")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 260 |
|
| 261 |
+
# Check if the current user is authorized (e.g., created_by matches or is admin)
|
| 262 |
+
if patient.get("created_by") != current_user["email"] and not current_user.get("is_admin", False):
|
| 263 |
+
raise HTTPException(status_code=403, detail="Not authorized to delete this patient")
|
|
|
|
| 264 |
|
| 265 |
+
# Delete all analyses associated with this patient
|
| 266 |
+
await analysis_collection.delete_many({"patient_id": patient_id})
|
| 267 |
+
logger.info(f"Deleted analyses for patient {patient_id}")
|
| 268 |
|
| 269 |
+
# Delete the patient
|
| 270 |
+
await patients_collection.delete_one({"fhir_id": patient_id})
|
| 271 |
+
logger.info(f"Patient {patient_id} deleted successfully")
|
| 272 |
|
| 273 |
+
return {"status": "success", "message": f"Patient {patient_id} and associated analyses deleted"}
|
| 274 |
|
| 275 |
except HTTPException:
|
| 276 |
raise
|
| 277 |
except Exception as e:
|
| 278 |
+
logger.error(f"Error deleting patient {patient_id}: {str(e)}")
|
| 279 |
+
raise HTTPException(status_code=500, detail=f"Failed to delete patient: {str(e)}")
|
| 280 |
|
| 281 |
return router
|