# apps/common/services/notification_service.py import logging from asgiref.sync import async_to_sync from channels.layers import get_channel_layer from apps.notifications.models import Notification 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, ) channel_layer = get_channel_layer() async_to_sync(channel_layer.group_send)( f"notification_user_{user.id}", { "type": "notification", "data": { "id": str(notification.id), "title": notification.title, "content": notification.content, "type": notification.type, "created_at": notification.created_at.isoformat(), "sender": { "id": str(notification.sender.id), "name": notification.sender.name } if notification.sender else None } } ) except Exception as e: logger.error(f"发送通知失败: {str(e)}")