from django.contrib.auth.mixins import LoginRequiredMixin, PermissionRequiredMixin from django.shortcuts import render from rest_framework.views import APIView from core.forms import NotificationRuleForm, NotificationSettingsForm from core.models import NotificationRule, NotificationSettings from core.views.helpers import ObjectCreate, ObjectDelete, ObjectList, ObjectUpdate # Notifications - we create a new notification settings object if there isn't one # Hence, there is only an update view, not a create view. class NotificationsUpdate(LoginRequiredMixin, PermissionRequiredMixin, ObjectUpdate): permission_required = "use_rules" model = NotificationSettings form_class = NotificationSettingsForm page_title = "Update your notification settings" page_subtitle = ( "At least the topic must be set if you want to receive notifications." ) submit_url_name = "notifications_update" submit_url_args = ["type"] pk_required = False hide_cancel = True def get_object(self, **kwargs): notification_settings, _ = NotificationSettings.objects.get_or_create( user=self.request.user ) return notification_settings class RuleList(LoginRequiredMixin, ObjectList): list_template = "partials/rule-list.html" model = NotificationRule page_title = "List of notification rules" list_url_name = "rules" list_url_args = ["type"] submit_url_name = "rule_create" class RuleCreate(LoginRequiredMixin, PermissionRequiredMixin, ObjectCreate): permission_required = "use_rules" model = NotificationRule form_class = NotificationRuleForm submit_url_name = "rule_create" class RuleUpdate(LoginRequiredMixin, PermissionRequiredMixin, ObjectUpdate): permission_required = "use_rules" model = NotificationRule form_class = NotificationRuleForm submit_url_name = "rule_update" class RuleDelete(LoginRequiredMixin, PermissionRequiredMixin, ObjectDelete): permission_required = "use_rules" model = NotificationRule class RuleClear(LoginRequiredMixin, PermissionRequiredMixin, APIView): permission_required = "use_rules" def post(self, request, type, pk): template_name = "partials/notify.html" rule = NotificationRule.objects.get(pk=pk, user=request.user) if isinstance(rule.match, dict): for index in rule.match: rule.match[index] = False rule.save() cleared_indices = ", ".join(rule.match) context = { "message": f"Cleared match status for indices: {cleared_indices}", "class": "success", } response = render(request, template_name, context) response["HX-Trigger"] = "notificationruleEvent" return response