91 lines
2.6 KiB
Python
91 lines
2.6 KiB
Python
import logging
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
from sqlalchemy import select, update, insert
|
|
from app.models.notification import Notification
|
|
from app.models.project import ProjectMember
|
|
from typing import List, Optional
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
class NotificationService:
|
|
async def create_notification(
|
|
self,
|
|
db: AsyncSession,
|
|
user_id: int,
|
|
title: str,
|
|
content: str = None,
|
|
type: str = "info",
|
|
category: str = "system",
|
|
link: str = None
|
|
) -> Notification:
|
|
"""创建单条通知"""
|
|
db_notification = Notification(
|
|
user_id=user_id,
|
|
title=title,
|
|
content=content,
|
|
type=type,
|
|
category=category,
|
|
link=link
|
|
)
|
|
db.add(db_notification)
|
|
await db.flush()
|
|
return db_notification
|
|
|
|
async def broadcast_system_notification(
|
|
self,
|
|
db: AsyncSession,
|
|
title: str,
|
|
content: str,
|
|
user_ids: List[int],
|
|
link: str = None
|
|
):
|
|
"""向指定多个用户发送系统通知"""
|
|
for uid in user_ids:
|
|
db_notification = Notification(
|
|
user_id=uid,
|
|
title=title,
|
|
content=content,
|
|
type="info",
|
|
category="system",
|
|
link=link
|
|
)
|
|
db.add(db_notification)
|
|
await db.flush()
|
|
|
|
async def notify_project_members(
|
|
self,
|
|
db: AsyncSession,
|
|
project_id: int,
|
|
exclude_user_id: int,
|
|
title: str,
|
|
content: str,
|
|
link: str = None,
|
|
category: str = "project"
|
|
):
|
|
"""通知项目中除指定用户外的所有成员"""
|
|
result = await db.execute(
|
|
select(ProjectMember.user_id).where(
|
|
ProjectMember.project_id == project_id,
|
|
ProjectMember.user_id != exclude_user_id
|
|
)
|
|
)
|
|
member_ids = result.scalars().all()
|
|
|
|
logger.info(f"Notifying members of project {project_id}. Found {len(member_ids)} members to notify (excluding user {exclude_user_id}).")
|
|
|
|
if member_ids:
|
|
for uid in member_ids:
|
|
db_notification = Notification(
|
|
user_id=uid,
|
|
title=title,
|
|
content=content,
|
|
type="info",
|
|
category=category,
|
|
link=link
|
|
)
|
|
db.add(db_notification)
|
|
await db.flush()
|
|
|
|
|
|
notification_service = NotificationService()
|