from __future__ import annotations from django.contrib.auth import get_user_model from .models import UserNotification, UserProfile def create_user_notification(*, user, title: str, body: str = '', level: str = UserNotification.LEVEL_INFO, link_url: str = '') -> UserNotification: return UserNotification.objects.create( user=user, title=(title or '').strip(), body=(body or '').strip(), level=level, link_url=(link_url or '').strip(), ) def notify_user(*, user, title: str, body: str = '', level: str = UserNotification.LEVEL_INFO, link_url: str = '', event_key: str = '') -> bool: if not user or not getattr(user, 'is_authenticated', False): return False profile, _ = UserProfile.objects.get_or_create(user=user) if event_key and not profile.notification_enabled(event_key): return False create_user_notification(user=user, title=title, body=body, level=level, link_url=link_url) return True def notify_user_by_email(*, email: str, title: str, body: str = '', level: str = UserNotification.LEVEL_INFO, link_url: str = '', event_key: str = '') -> bool: normalized_email = (email or '').strip().lower() if not normalized_email: return False user = get_user_model().objects.filter(email__iexact=normalized_email).first() if not user: return False return notify_user(user=user, title=title, body=body, level=level, link_url=link_url, event_key=event_key)