Files
goodtimes/manage_notifications/api/views.py
2024-03-14 13:48:41 +05:30

76 lines
2.7 KiB
Python

from rest_framework import status
from rest_framework.views import APIView
from django.conf import settings
from manage_notifications.api.serializers import (
IAmPrincipalNotificationSettingsSerializer,
)
from manage_notifications.models import (
IAmPrincipalNotificationSettings,
NotificationCategoryChoices,
)
from goodtimes import constants
from goodtimes.utils import ApiResponse
from rest_framework.permissions import IsAuthenticated
from rest_framework_simplejwt.authentication import JWTAuthentication
class NotificationSettingToggle(APIView):
authentication_classes = [JWTAuthentication]
permission_classes = [IsAuthenticated]
def post(self, request, *args, **kwargs):
notification_category = request.data.get("notification_category")
enable = request.data.get("enable", True)
if (
not notification_category
or notification_category not in NotificationCategoryChoices.values
):
return ApiResponse.error(
errors="Invalid notification category",
message=constants.FAILURE,
status=status.HTTP_400_BAD_REQUEST,
)
# Assuming IAmPrincipal model has a user field that relates to Django's User model
# You might need to adjust the query depending on your user-principal relationship
notification_setting, created = (
IAmPrincipalNotificationSettings.objects.get_or_create(
principal=request.user,
notification_category=notification_category,
defaults={"is_enabled": enable},
)
)
if not created:
notification_setting.is_enabled = enable
notification_setting.save()
return ApiResponse.success(
data=f"{notification_category}: { enable}.",
message=constants.SUCCESS,
status=status.HTTP_200_OK,
)
class UserNotificationsAPIView(APIView):
authentication_classes = [JWTAuthentication]
permission_classes = [IsAuthenticated]
def get(self, request, *args, **kwargs):
# Assuming your IAmPrincipal model has a user field linking to the User model
principal = request.user
notifications = (
IAmPrincipalNotificationSettings.objects.filter(principal=principal)
.exclude(notification_category=NotificationCategoryChoices.GENERAL)
.exclude(notification_category=NotificationCategoryChoices.PROMOTIONS)
)
serializer = IAmPrincipalNotificationSettingsSerializer(
notifications, many=True
)
return ApiResponse.success(
data=serializer.data,
message=constants.SUCCESS,
status=status.HTTP_200_OK,
)