HEX
Server: Apache/2.4.52 (Ubuntu)
System: Linux spn-python 5.15.0-89-generic #99-Ubuntu SMP Mon Oct 30 20:42:41 UTC 2023 x86_64
User: arjun (1000)
PHP: 8.1.2-1ubuntu2.20
Disabled: NONE
Upload Files
File: //home/arjun/projects/aigenerator/AI-LG-backend/Ai_logo_generation/payment/tasks.py
from celery import shared_task
from django.utils.timezone import now, timedelta
from django.core.mail import send_mail
from .models import Transaction
from user_notification.models import NotificationToken, InAppNotification
from django.conf import settings
from django.template.loader import render_to_string
import logging
from firebase_admin import messaging
from firebase_admin.exceptions import FirebaseError


logger = logging.getLogger(__name__)

@shared_task
def notify_users_about_expiring_subscriptions():
    today = now()
    tomorrow = today + timedelta(days=1)

    expiring_subscriptions = Transaction.objects.filter(
        subscription_end__date=tomorrow.date(),
        is_subscription=True
    )

    for transaction in expiring_subscriptions:
        user = transaction.customer

        # Prepare email
        context = {
            'username': f"{user.first_name} {user.last_name}",
            'subscription_end': transaction.subscription_end,
        }
        message = render_to_string('reminder-before-expiry.html', context)

        try:
            send_mail(
                subject="Your Subscription is About to Expire - Renew Now!",
                message='',  
                from_email=settings.EMAIL_HOST_USER,
                recipient_list=[user.email],
                fail_silently=False,
                html_message=message,
            )
            logger.info(f"Reminder email sent successfully to {user.email}")
        except Exception as e:
            logger.error(f"Failed to send reminder email to {user.email}: {e}")

        # Prepare and send notification
        notification_token = NotificationToken.objects.filter(user=user)
        for token in notification_token:
            notification_message = messaging.Message(
                notification=messaging.Notification(
                    title="Subscription Expiry Reminder",
                    body=f"Hi {user.first_name}, your subscription ends on {transaction.subscription_end.date()}. Renew now to continue enjoying our services!",
                ),
                token=token.token,
            )
            if token.is_active():
                try:
                    response = messaging.send(notification_message)
                    logger.info(f"Notification sent successfully for token ID {token.id}: {response}")

                    # Log notification in database
                    InAppNotification.objects.create(
                        notification_token=token,
                        title=notification_message.notification.title,
                        body=notification_message.notification.body,
                    )

                    # Increment token's send count
                    token.send_count += 1
                    token.save()
                except FirebaseError as e:
                    logger.error(f"Notification failed for token ID {token.id}: {e}")