You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

43 lines
1.5 KiB

import asyncio
import logging
from apps.account.models import Notification
from apps.account.tasks import send_notification
logger = logging.getLogger(__name__)
def create_and_send_notification(user, title_en, body_en, title_fa, body_fa, service='imam-javad', data=None):
"""
Creates a Notification record in the database and sends a push notification to FCM.
Resolves localized title and body based on user.language.
"""
lang = getattr(user, 'language', None)
lang_code = lang.code if lang and hasattr(lang, 'code') else 'fa'
title = title_fa if lang_code == 'fa' else title_en
message = body_fa if lang_code == 'fa' else body_en
# Save to database
notif = Notification.objects.create(
user=user,
title=title,
message=message,
service=service
)
fcm_token = getattr(user, 'fcm', None)
if fcm_token:
try:
try:
loop = asyncio.get_event_loop()
except RuntimeError:
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
if loop.is_running():
loop.create_task(send_notification([fcm_token], title, message, data))
else:
loop.run_until_complete(send_notification([fcm_token], title, message, data))
except Exception as e:
logger.error(f"Failed to send push notification via FCM: {e}")
return notif