Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
104 changes: 104 additions & 0 deletions backend/app/api/v1/notifications.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
import uuid

from fastapi import APIRouter, Depends, Response, status
from sqlalchemy.orm import Session

from app.core.deps import get_current_user, require_roles
from app.db.session import get_db
from app.models.enums import UserRole
from app.models.user import User
from app.schemas.notification import (
NotificationCreate,
NotificationListItem,
NotificationRead,
NotificationUpdate,
)
from app.services.notification import NotificationService

router = APIRouter(prefix="/notifications", tags=["notifications"])

ADMIN_ONLY = [UserRole.ADMIN]
ALL_ROLES = [UserRole.ADMIN, UserRole.MENTOR, UserRole.INTERN]
USER_ROLES = [UserRole.MENTOR, UserRole.INTERN]


@router.post("", response_model=NotificationRead, status_code=status.HTTP_201_CREATED)
def create_notification(
payload: NotificationCreate,
current_user: User = Depends(require_roles(ADMIN_ONLY)),
db: Session = Depends(get_db),
):
"""Admin tạo và gửi thông báo."""
return NotificationService.create_notification(db, current_user, payload)


@router.get("", response_model=list[NotificationListItem])
def list_notifications(
current_user: User = Depends(get_current_user),
db: Session = Depends(get_db),
):
"""Admin: xem tất cả thông báo đã gửi. Intern/Mentor: xem thông báo dành cho mình."""
if str(current_user.role) == UserRole.ADMIN:
return NotificationService.list_notifications_admin(db, current_user)
return NotificationService.list_notifications_user(db, current_user)


@router.post("/read-all", response_model=dict)
def mark_all_as_read(
current_user: User = Depends(require_roles(USER_ROLES)),
db: Session = Depends(get_db),
):
"""Intern/Mentor đánh dấu tất cả thông báo đã đọc."""
return NotificationService.mark_all_as_read(db, current_user)


@router.get("/unread-count", response_model=dict)
def get_unread_count(
current_user: User = Depends(get_current_user),
db: Session = Depends(get_db),
):
"""Lấy số thông báo chưa đọc của người dùng hiện tại."""
count = NotificationService.get_unread_count(db, current_user)
return {"unread_count": count}


@router.get("/{notification_id}", response_model=NotificationRead)
def get_notification(
notification_id: uuid.UUID,
current_user: User = Depends(get_current_user),
db: Session = Depends(get_db),
):
"""Xem chi tiết một thông báo."""
return NotificationService.get_notification_detail(db, current_user, notification_id)


@router.post("/{notification_id}/read", response_model=NotificationRead)
def mark_as_read(
notification_id: uuid.UUID,
current_user: User = Depends(require_roles(USER_ROLES)),
db: Session = Depends(get_db),
):
"""Intern/Mentor đánh dấu thông báo đã đọc."""
return NotificationService.mark_as_read(db, current_user, notification_id)


@router.put("/{notification_id}", response_model=NotificationRead)
def update_notification(
notification_id: uuid.UUID,
payload: NotificationUpdate,
current_user: User = Depends(require_roles(ADMIN_ONLY)),
db: Session = Depends(get_db),
):
"""Admin chỉnh sửa thông báo (tiêu đề, nội dung, đối tượng nhận)."""
return NotificationService.update_notification(db, current_user, notification_id, payload)


@router.delete("/{notification_id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_notification(
notification_id: uuid.UUID,
current_user: User = Depends(require_roles(ADMIN_ONLY)),
db: Session = Depends(get_db),
) -> Response:
"""Admin xóa thông báo."""
NotificationService.delete_notification(db, current_user, notification_id)
return Response(status_code=status.HTTP_204_NO_CONTENT)
2 changes: 2 additions & 0 deletions backend/app/api/v1/router.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
from app.api.v1.learning import router as learning_router
from app.api.v1.me import router as me_router
from app.api.v1.mentor import router as mentor_router
from app.api.v1.notifications import router as notifications_router
from app.api.v1.profile import router as profile_router
from app.api.v1.tasks import router as tasks_router
from app.api.v1.training import router as training_router
Expand All @@ -26,3 +27,4 @@
api_router.include_router(tasks_router)
api_router.include_router(learning_router)
api_router.include_router(training_router)
api_router.include_router(notifications_router)
72 changes: 72 additions & 0 deletions backend/app/schemas/notification.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
from __future__ import annotations

import uuid
from datetime import datetime
from typing import Any

from pydantic import Field, field_validator

from app.schemas.base import BaseSchema

TARGET_TYPES = ("ALL", "ROLE", "USER")
VALID_ROLES = ("INTERN", "MENTOR", "ADMIN")


class NotificationCreate(BaseSchema):
title: str = Field(..., min_length=1, max_length=255)
content: str = Field(..., min_length=1)
target_type: str = Field(default="ALL")
target_data: list[Any] | None = Field(
None, description="Danh sách role hoặc user_id tuỳ target_type"
)

@field_validator("target_type")
@classmethod
def _check_target_type(cls, v: str) -> str:
if v not in TARGET_TYPES:
raise ValueError(f"target_type must be one of {TARGET_TYPES}")
return v


class NotificationUpdate(BaseSchema):
title: str | None = Field(None, min_length=1, max_length=255)
content: str | None = Field(None, min_length=1)
target_type: str | None = None
target_data: list[Any] | None = Field(
None, description="Danh sách role hoặc user_id tuỳ target_type"
)

@field_validator("target_type")
@classmethod
def _check_target_type(cls, v: str | None) -> str | None:
if v is not None and v not in TARGET_TYPES:
raise ValueError(f"target_type must be one of {TARGET_TYPES}")
return v


class NotificationRead(BaseSchema):
id: uuid.UUID
title: str
content: str
target_type: str
target_data: list[Any] | None = None
recipient_names: list[str] | None = None
created_by: uuid.UUID
created_at: datetime
creator_name: str | None = None
is_read: bool = False
read_at: datetime | None = None


class NotificationListItem(BaseSchema):
id: uuid.UUID
title: str
content: str
target_type: str
target_data: list[Any] | None = None
recipient_names: list[str] | None = None
created_by: uuid.UUID
created_at: datetime
creator_name: str | None = None
is_read: bool = False
read_count: int = 0
Loading
Loading