Phase 5: Notifications — WebSocket, APScheduler, AI tool, health review
Backend: - Notification model + Alembic migration - Notification service: CRUD, mark read, unread count, pending scheduled - WebSocket manager singleton for real-time push - WebSocket endpoint /ws/notifications with JWT auth via query param - APScheduler integration: periodic notification sender (every 60s), daily proactive health review job (8 AM) - AI tool: schedule_notification (immediate or scheduled) - Health review worker: analyzes user memory via Claude, creates ai_generated notifications with WebSocket push Frontend: - Notification API client + Zustand store - WebSocket hook with auto-reconnect (exponential backoff) - Notification bell in header with unread count badge + dropdown - Notifications page with type badges, mark read, mark all read - WebSocket initialized in AppLayout for app-wide real-time updates - Enabled notifications nav in sidebar - English + Russian translations Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
57
backend/app/api/v1/notifications.py
Normal file
57
backend/app/api/v1/notifications.py
Normal file
@@ -0,0 +1,57 @@
|
||||
import uuid
|
||||
from typing import Annotated
|
||||
|
||||
from fastapi import APIRouter, Depends, Query, status
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.api.deps import get_current_user
|
||||
from app.database import get_db
|
||||
from app.models.user import User
|
||||
from app.schemas.notification import NotificationListResponse, NotificationResponse, UnreadCountResponse
|
||||
from app.services import notification_service
|
||||
|
||||
router = APIRouter(prefix="/notifications", tags=["notifications"])
|
||||
|
||||
|
||||
@router.get("/", response_model=NotificationListResponse)
|
||||
async def list_notifications(
|
||||
user: Annotated[User, Depends(get_current_user)],
|
||||
db: Annotated[AsyncSession, Depends(get_db)],
|
||||
status_filter: str | None = Query(default=None, alias="status"),
|
||||
limit: int = Query(default=50, le=200),
|
||||
offset: int = Query(default=0),
|
||||
):
|
||||
notifications = await notification_service.get_user_notifications(db, user.id, status_filter, limit, offset)
|
||||
unread = await notification_service.get_unread_count(db, user.id)
|
||||
return NotificationListResponse(
|
||||
notifications=[NotificationResponse.model_validate(n) for n in notifications],
|
||||
unread_count=unread,
|
||||
)
|
||||
|
||||
|
||||
@router.get("/unread-count", response_model=UnreadCountResponse)
|
||||
async def unread_count(
|
||||
user: Annotated[User, Depends(get_current_user)],
|
||||
db: Annotated[AsyncSession, Depends(get_db)],
|
||||
):
|
||||
count = await notification_service.get_unread_count(db, user.id)
|
||||
return UnreadCountResponse(count=count)
|
||||
|
||||
|
||||
@router.patch("/{notification_id}/read", response_model=NotificationResponse)
|
||||
async def mark_read(
|
||||
notification_id: uuid.UUID,
|
||||
user: Annotated[User, Depends(get_current_user)],
|
||||
db: Annotated[AsyncSession, Depends(get_db)],
|
||||
):
|
||||
notif = await notification_service.mark_as_read(db, notification_id, user.id)
|
||||
return NotificationResponse.model_validate(notif)
|
||||
|
||||
|
||||
@router.post("/mark-all-read", status_code=status.HTTP_200_OK)
|
||||
async def mark_all_read(
|
||||
user: Annotated[User, Depends(get_current_user)],
|
||||
db: Annotated[AsyncSession, Depends(get_db)],
|
||||
):
|
||||
count = await notification_service.mark_all_read(db, user.id)
|
||||
return {"marked": count}
|
||||
@@ -7,6 +7,8 @@ from app.api.v1.skills import router as skills_router
|
||||
from app.api.v1.users import router as users_router
|
||||
from app.api.v1.documents import router as documents_router
|
||||
from app.api.v1.memory import router as memory_router
|
||||
from app.api.v1.notifications import router as notifications_router
|
||||
from app.api.v1.ws import router as ws_router
|
||||
|
||||
api_v1_router = APIRouter(prefix="/api/v1")
|
||||
|
||||
@@ -17,6 +19,8 @@ api_v1_router.include_router(skills_router)
|
||||
api_v1_router.include_router(users_router)
|
||||
api_v1_router.include_router(documents_router)
|
||||
api_v1_router.include_router(memory_router)
|
||||
api_v1_router.include_router(notifications_router)
|
||||
api_v1_router.include_router(ws_router)
|
||||
|
||||
|
||||
@api_v1_router.get("/health")
|
||||
|
||||
55
backend/app/api/v1/ws.py
Normal file
55
backend/app/api/v1/ws.py
Normal file
@@ -0,0 +1,55 @@
|
||||
import uuid
|
||||
|
||||
from fastapi import APIRouter, WebSocket, WebSocketDisconnect, Query
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.security import decode_access_token
|
||||
from app.database import async_session_factory
|
||||
from app.models.user import User
|
||||
from app.services.ws_manager import manager
|
||||
from app.services.notification_service import get_unread_count
|
||||
|
||||
router = APIRouter(tags=["websocket"])
|
||||
|
||||
|
||||
async def _authenticate_ws(token: str) -> uuid.UUID | None:
|
||||
payload = decode_access_token(token)
|
||||
user_id = payload.get("sub")
|
||||
if not user_id:
|
||||
return None
|
||||
try:
|
||||
uid = uuid.UUID(user_id)
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
async with async_session_factory() as db:
|
||||
result = await db.execute(select(User).where(User.id == uid, User.is_active == True)) # noqa: E712
|
||||
user = result.scalar_one_or_none()
|
||||
if not user:
|
||||
return None
|
||||
return uid
|
||||
|
||||
|
||||
@router.websocket("/ws/notifications")
|
||||
async def ws_notifications(websocket: WebSocket, token: str = Query(...)):
|
||||
user_id = await _authenticate_ws(token)
|
||||
if not user_id:
|
||||
await websocket.close(code=4001, reason="Unauthorized")
|
||||
return
|
||||
|
||||
await manager.connect(user_id, websocket)
|
||||
|
||||
try:
|
||||
# Send initial unread count
|
||||
async with async_session_factory() as db:
|
||||
count = await get_unread_count(db, user_id)
|
||||
await websocket.send_json({"type": "unread_count", "count": count})
|
||||
|
||||
# Keep alive - wait for disconnect
|
||||
while True:
|
||||
await websocket.receive_text()
|
||||
except WebSocketDisconnect:
|
||||
pass
|
||||
finally:
|
||||
manager.disconnect(user_id, websocket)
|
||||
Reference in New Issue
Block a user