Ali2206 commited on
Commit
6c3d40b
·
verified ·
1 Parent(s): 90eef61

Update endpoints.py

Browse files
Files changed (1) hide show
  1. endpoints.py +56 -4
endpoints.py CHANGED
@@ -1,6 +1,7 @@
1
  from fastapi import APIRouter, Depends, HTTPException, UploadFile, File, Query, Form
2
  from fastapi.responses import StreamingResponse, JSONResponse
3
  from fastapi.encoders import jsonable_encoder
 
4
  from models import ChatRequest, VoiceOutputRequest, RiskLevel
5
  from auth import get_current_user
6
  from utils import clean_text_response
@@ -12,9 +13,8 @@ import io
12
  from datetime import datetime
13
  from bson import ObjectId
14
  import asyncio
15
- from typing import Optional
16
 
17
- def create_router(agent, logger, patients_collection, analysis_collection):
18
  router = APIRouter()
19
 
20
  @router.get("/status")
@@ -34,6 +34,10 @@ def create_router(agent, logger, patients_collection, analysis_collection):
34
  ):
35
  logger.info(f"Fetching analysis results by {current_user['email']}")
36
  try:
 
 
 
 
37
  query = {}
38
  if name:
39
  name_regex = re.compile(name, re.IGNORECASE)
@@ -47,8 +51,15 @@ def create_router(agent, logger, patients_collection, analysis_collection):
47
  enriched_results = []
48
  for analysis in analyses:
49
  patient = await patients_collection.find_one({"fhir_id": analysis.get("patient_id")})
50
- if patient:
51
- analysis["full_name"] = patient.get("full_name", "Unknown")
 
 
 
 
 
 
 
52
  analysis["_id"] = str(analysis["_id"])
53
  enriched_results.append(analysis)
54
 
@@ -244,4 +255,45 @@ def create_router(agent, logger, patients_collection, analysis_collection):
244
  detail=f"Failed to analyze report: {str(e)}"
245
  )
246
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
247
  return router
 
1
  from fastapi import APIRouter, Depends, HTTPException, UploadFile, File, Query, Form
2
  from fastapi.responses import StreamingResponse, JSONResponse
3
  from fastapi.encoders import jsonable_encoder
4
+ from typing import Optional
5
  from models import ChatRequest, VoiceOutputRequest, RiskLevel
6
  from auth import get_current_user
7
  from utils import clean_text_response
 
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()
19
 
20
  @router.get("/status")
 
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)
 
51
  enriched_results = []
52
  for analysis in analyses:
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)
65
 
 
255
  detail=f"Failed to analyze report: {str(e)}"
256
  )
257
 
258
+ @router.delete("/users/{user_email}")
259
+ async def delete_user(
260
+ user_email: str,
261
+ current_user: dict = Depends(get_current_user)
262
+ ):
263
+ logger.info(f"User deletion initiated by {current_user['email']} for user {user_email}")
264
+ try:
265
+ # Check if the current user has permission to delete (e.g., admin or self)
266
+ if current_user["email"] != user_email and not current_user.get("is_admin", False):
267
+ raise HTTPException(status_code=403, detail="Not authorized to delete this user")
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
+ # Delete all analyses associated with these patients
279
+ if patient_ids:
280
+ await analysis_collection.delete_many({"patient_id": {"$in": patient_ids}})
281
+ logger.info(f"Deleted analyses for {len(patient_ids)} patients associated with user {user_email}")
282
+
283
+ # Delete the patients
284
+ await patients_collection.delete_many({"created_by": user_email})
285
+ logger.info(f"Deleted {len(patient_ids)} patients associated with user {user_email}")
286
+
287
+ # Delete the user
288
+ await users_collection.delete_one({"email": user_email})
289
+ logger.info(f"User {user_email} deleted successfully")
290
+
291
+ return {"status": "success", "message": f"User {user_email} and associated data deleted"}
292
+
293
+ except HTTPException:
294
+ raise
295
+ except Exception as e:
296
+ logger.error(f"Error deleting user {user_email}: {str(e)}")
297
+ raise HTTPException(status_code=500, detail=f"Failed to delete user: {str(e)}")
298
+
299
  return router