75 lines
2.2 KiB
Python
75 lines
2.2 KiB
Python
from fastapi import APIRouter, Depends, HTTPException
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
|
|
from app.core.deps import get_current_user
|
|
from app.db.database import get_db
|
|
from app.db.models import User
|
|
from app.schemas.notification import NotificationOut, UnreadCount
|
|
from app.schemas.common import PageResponse
|
|
from app.services.notification_service import (
|
|
list_notifications,
|
|
get_unread_count,
|
|
mark_as_read,
|
|
mark_all_as_read,
|
|
)
|
|
|
|
router = APIRouter(prefix="/api/notifications", tags=["notifications"])
|
|
|
|
|
|
@router.get("/", response_model=PageResponse[NotificationOut])
|
|
async def get_notifications(
|
|
page: int = 1,
|
|
page_size: int = 20,
|
|
user: User = Depends(get_current_user),
|
|
db: AsyncSession = Depends(get_db),
|
|
):
|
|
notifications, total = await list_notifications(db, user.id, page, page_size)
|
|
total_pages = (total + page_size - 1) // page_size
|
|
|
|
items = [
|
|
NotificationOut(
|
|
id=n.id,
|
|
type=n.type,
|
|
title=n.title,
|
|
content=n.content,
|
|
related_id=n.related_id,
|
|
is_read=n.is_read,
|
|
created_at=n.created_at,
|
|
)
|
|
for n in notifications
|
|
]
|
|
|
|
return PageResponse(
|
|
items=items, total=total, page=page, page_size=page_size, total_pages=total_pages
|
|
)
|
|
|
|
|
|
@router.get("/unread-count", response_model=UnreadCount)
|
|
async def get_unread_count_api(
|
|
user: User = Depends(get_current_user),
|
|
db: AsyncSession = Depends(get_db),
|
|
):
|
|
count = await get_unread_count(db, user.id)
|
|
return UnreadCount(count=count)
|
|
|
|
|
|
@router.put("/{notification_id}/read")
|
|
async def mark_notification_read(
|
|
notification_id: int,
|
|
user: User = Depends(get_current_user),
|
|
db: AsyncSession = Depends(get_db),
|
|
):
|
|
success = await mark_as_read(db, notification_id, user.id)
|
|
if not success:
|
|
raise HTTPException(status_code=404, detail="Notification not found")
|
|
return {"message": "Marked as read"}
|
|
|
|
|
|
@router.put("/read-all")
|
|
async def mark_all_notifications_read(
|
|
user: User = Depends(get_current_user),
|
|
db: AsyncSession = Depends(get_db),
|
|
):
|
|
count = await mark_all_as_read(db, user.id)
|
|
return {"message": f"Marked {count} notifications as read"}
|