Update endpoints.py
Browse files- endpoints.py +45 -6
endpoints.py
CHANGED
@@ -1,4 +1,4 @@
|
|
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, List
|
@@ -35,7 +35,7 @@ class RiskLevel(BaseModel):
|
|
35 |
score: float
|
36 |
factors: Optional[List[str]] = None
|
37 |
|
38 |
-
def create_router(agent, logger, patients_collection, analysis_collection, users_collection, chats_collection):
|
39 |
router = APIRouter()
|
40 |
|
41 |
@router.get("/status")
|
@@ -181,15 +181,16 @@ def create_router(agent, logger, patients_collection, analysis_collection, users
|
|
181 |
):
|
182 |
logger.info(f"Fetching notifications for {current_user['email']}")
|
183 |
try:
|
184 |
-
# Fetch notifications for the current user
|
185 |
notifications = await notifications_collection.find({"user_id": current_user["email"]}).sort("timestamp", -1).to_list(length=10)
|
186 |
return [
|
187 |
{
|
188 |
"id": str(notification["_id"]),
|
|
|
189 |
"message": notification.get("message", "No message"),
|
190 |
"timestamp": notification.get("timestamp", datetime.utcnow()).isoformat(),
|
191 |
-
"
|
192 |
-
"
|
193 |
}
|
194 |
for notification in notifications
|
195 |
]
|
@@ -197,6 +198,43 @@ def create_router(agent, logger, patients_collection, analysis_collection, users
|
|
197 |
logger.error(f"Error fetching notifications: {e}")
|
198 |
raise HTTPException(status_code=500, detail="Failed to retrieve notifications")
|
199 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
200 |
@router.post("/voice/transcribe")
|
201 |
async def transcribe_voice(
|
202 |
audio: UploadFile = File(...),
|
@@ -352,7 +390,8 @@ def create_router(agent, logger, patients_collection, analysis_collection, users
|
|
352 |
"message": f"Suicide risk alert for patient {patient_id}: {analysis['suicide_risk']['level'].upper()} (Score: {analysis['suicide_risk']['score']})",
|
353 |
"patient_id": patient_id,
|
354 |
"timestamp": datetime.utcnow(),
|
355 |
-
"severity": "high" if analysis["suicide_risk"]["level"] in ["moderate", "severe"] else "medium"
|
|
|
356 |
}
|
357 |
await notifications_collection.insert_one(notification)
|
358 |
logger.info(f"✅ Created notification for suicide risk alert: {notification}")
|
|
|
1 |
+
from fastapi import APIRouter, Depends, HTTPException, UploadFile, File, Query, Form, Path
|
2 |
from fastapi.responses import StreamingResponse, JSONResponse
|
3 |
from fastapi.encoders import jsonable_encoder
|
4 |
from typing import Optional, List
|
|
|
35 |
score: float
|
36 |
factors: Optional[List[str]] = None
|
37 |
|
38 |
+
def create_router(agent, logger, patients_collection, analysis_collection, users_collection, chats_collection, notifications_collection):
|
39 |
router = APIRouter()
|
40 |
|
41 |
@router.get("/status")
|
|
|
181 |
):
|
182 |
logger.info(f"Fetching notifications for {current_user['email']}")
|
183 |
try:
|
184 |
+
# Fetch notifications for the current user
|
185 |
notifications = await notifications_collection.find({"user_id": current_user["email"]}).sort("timestamp", -1).to_list(length=10)
|
186 |
return [
|
187 |
{
|
188 |
"id": str(notification["_id"]),
|
189 |
+
"title": f"Alert for Patient {notification.get('patient_id', 'Unknown')}",
|
190 |
"message": notification.get("message", "No message"),
|
191 |
"timestamp": notification.get("timestamp", datetime.utcnow()).isoformat(),
|
192 |
+
"severity": notification.get("severity", "info"),
|
193 |
+
"read": notification.get("read", False)
|
194 |
}
|
195 |
for notification in notifications
|
196 |
]
|
|
|
198 |
logger.error(f"Error fetching notifications: {e}")
|
199 |
raise HTTPException(status_code=500, detail="Failed to retrieve notifications")
|
200 |
|
201 |
+
@router.post("/notifications/{notification_id}/read")
|
202 |
+
async def mark_notification_as_read(
|
203 |
+
notification_id: str = Path(..., description="The ID of the notification to mark as read"),
|
204 |
+
current_user: dict = Depends(get_current_user)
|
205 |
+
):
|
206 |
+
logger.info(f"Marking notification {notification_id} as read for {current_user['email']}")
|
207 |
+
try:
|
208 |
+
result = await notifications_collection.update_one(
|
209 |
+
{"_id": ObjectId(notification_id), "user_id": current_user["email"]},
|
210 |
+
{"$set": {"read": True}}
|
211 |
+
)
|
212 |
+
if result.matched_count == 0:
|
213 |
+
raise HTTPException(status_code=404, detail="Notification not found or not authorized")
|
214 |
+
return {"status": "success", "message": "Notification marked as read"}
|
215 |
+
except InvalidId:
|
216 |
+
raise HTTPException(status_code=400, detail="Invalid notification ID format")
|
217 |
+
except Exception as e:
|
218 |
+
logger.error(f"Error marking notification as read: {e}")
|
219 |
+
raise HTTPException(status_code=500, detail="Failed to mark notification as read")
|
220 |
+
|
221 |
+
@router.post("/notifications/read-all")
|
222 |
+
async def mark_all_notifications_as_read(
|
223 |
+
current_user: dict = Depends(get_current_user)
|
224 |
+
):
|
225 |
+
logger.info(f"Marking all notifications as read for {current_user['email']}")
|
226 |
+
try:
|
227 |
+
result = await notifications_collection.update_many(
|
228 |
+
{"user_id": current_user["email"], "read": False},
|
229 |
+
{"$set": {"read": True}}
|
230 |
+
)
|
231 |
+
if result.matched_count == 0:
|
232 |
+
logger.info("No unread notifications to mark as read")
|
233 |
+
return {"status": "success", "message": f"Marked {result.modified_count} notifications as read"}
|
234 |
+
except Exception as e:
|
235 |
+
logger.error(f"Error marking all notifications as read: {e}")
|
236 |
+
raise HTTPException(status_code=500, detail="Failed to mark all notifications as read")
|
237 |
+
|
238 |
@router.post("/voice/transcribe")
|
239 |
async def transcribe_voice(
|
240 |
audio: UploadFile = File(...),
|
|
|
390 |
"message": f"Suicide risk alert for patient {patient_id}: {analysis['suicide_risk']['level'].upper()} (Score: {analysis['suicide_risk']['score']})",
|
391 |
"patient_id": patient_id,
|
392 |
"timestamp": datetime.utcnow(),
|
393 |
+
"severity": "high" if analysis["suicide_risk"]["level"] in ["moderate", "severe"] else "medium",
|
394 |
+
"read": False
|
395 |
}
|
396 |
await notifications_collection.insert_one(notification)
|
397 |
logger.info(f"✅ Created notification for suicide risk alert: {notification}")
|