operations_project/apps/common/services/notification_service.py

51 lines
1.8 KiB
Python
Raw Normal View History

2025-05-07 22:24:02 +08:00
# apps/common/services/notification_service.py
import logging
from asgiref.sync import async_to_sync
from channels.layers import get_channel_layer
2025-05-13 11:58:17 +08:00
from apps.notification.models import Notification
2025-05-07 22:24:02 +08:00
logger = logging.getLogger(__name__)
class NotificationService:
def send_notification(self, user, title, content, notification_type, related_object_id, sender=None):
"""发送通知并通过WebSocket推送"""
try:
notification = Notification.objects.create(
sender=sender,
receiver=user,
title=title,
content=content,
type=notification_type,
related_resource=related_object_id,
)
2025-05-13 11:58:17 +08:00
# 准备发送到WebSocket的数据
notification_data = {
"id": str(notification.id),
"title": notification.title,
"content": notification.content,
"type": notification.type,
"created_at": notification.created_at.isoformat(),
}
# 只有当sender不为None时才添加sender信息
if notification.sender:
notification_data["sender"] = {
"id": str(notification.sender.id),
"name": notification.sender.name
}
2025-05-07 22:24:02 +08:00
channel_layer = get_channel_layer()
async_to_sync(channel_layer.group_send)(
f"notification_user_{user.id}",
{
"type": "notification",
2025-05-13 11:58:17 +08:00
"data": notification_data
2025-05-07 22:24:02 +08:00
}
)
2025-05-13 11:58:17 +08:00
return notification
2025-05-07 22:24:02 +08:00
except Exception as e:
logger.error(f"发送通知失败: {str(e)}")
2025-05-13 11:58:17 +08:00
return None
2025-05-07 22:24:02 +08:00