Files
goodtimes/manage_notifications/api/cron_views.py
2024-05-08 12:32:27 +05:30

72 lines
2.8 KiB
Python

from goodtimes.utils import ApiResponse
from rest_framework.views import APIView
from rest_framework import status
from django.utils import timezone
from django.conf import settings
from datetime import timedelta
from onesignal_sdk.client import Client as OneSignalClient
from manage_notifications.models import (
IAmPrincipalNotificationSettings,
InAppNotification,
NotificationCategoryChoices,
)
from manage_subscriptions.models import SubscriptionStatus
class OneWeekSubscriptionAlertView(APIView):
authentication_classes = []
permission_classes = []
def post(self, request, *args, **kwargs):
self.client = OneSignalClient(
app_id=settings.ONE_SIGNAL_APP_ID, rest_api_key=settings.ONE_SIGNAL_API_KEY
)
eligible_principals = self.eligible_principals()
for principal in eligible_principals:
try:
player_id = principal.principal.player_id
except AttributeError:
# Handle the case where principal is null or does not have a player_id field
continue
notification_title = "Subscription Expiry Reminder"
notification_message = "Your subscription is going to expire in a week."
notification_category = NotificationCategoryChoices.SUBSCRIPTION
# Send notification to principal
notification_payload = {
"headings": {"en": notification_title},
"contents": {"en": notification_message},
"include_player_ids": [player_id],
}
response = self.client.send_notification(notification_payload)
# Save notification to InAppNotification table
in_app_notification = InAppNotification(
principal=principal.principal,
title=notification_title,
message=notification_message,
notification_category=notification_category,
)
in_app_notification.save()
return ApiResponse.success(
message="Notifications sent successfully",
data="Notifications sent successfully",
status=status.HTTP_200_OK,
)
def eligible_principals(self):
one_week_from_now = timezone.now().date() + timedelta(days=7)
eligible_principals = IAmPrincipalNotificationSettings.objects.filter(
principal__principal_subscription__end_date=one_week_from_now,
principal__principal_subscription__status=SubscriptionStatus.ACTIVE,
principal__principal_subscription__cancelled=False,
principal__principal_subscription__deleted=False,
notification_category=NotificationCategoryChoices.SUBSCRIPTION,
is_enabled=True,
).select_related("principal")
return eligible_principals