From 62f470a0d6603fc73b1f8acb850ea5108b95069a Mon Sep 17 00:00:00 2001 From: Luca Date: Mon, 27 May 2024 16:32:05 +0200 Subject: [PATCH] feat(app): send messages from admin --- shiftregister/app/admin.py | 44 +++++++++++++++++++++++++++++++++++++- 1 file changed, 43 insertions(+), 1 deletion(-) diff --git a/shiftregister/app/admin.py b/shiftregister/app/admin.py index 35764df..cb881c0 100644 --- a/shiftregister/app/admin.py +++ b/shiftregister/app/admin.py @@ -1,8 +1,17 @@ -from django.contrib import admin +import logging + +import sentry_sdk +from django.contrib import admin, messages from django.contrib.admin import DateFieldListFilter +from django.db import transaction +from django.utils import timezone + +from shiftregister.messaging.outbound import send from .models import Helper, LoginToken, Message, Room, Shift, ShiftRegistration +logger = logging.getLogger(__name__) + @admin.register(Room) class RoomAdmin(admin.ModelAdmin): @@ -65,6 +74,38 @@ class ShiftRegistrationAdmin(admin.ModelAdmin): return obj.helper.name +def send_messages(modeladmin, request, queryset): + msgs = queryset.select_for_update() + with transaction.atomic(): + sent_msg_ids = [] + try: + for msg in send(msg.as_outbound() for msg in msgs if not msg.sent_at): + sent_msg_ids.append(msg.key) + except Exception as e: + logger.error(e) + sentry_sdk.capture_exception(e) + + Message.objects.select_for_update().filter(id__in=sent_msg_ids).update( + sent_at=timezone.now() + ) + + num_sent_msgs = len(sent_msg_ids) + if num_sent_msgs == 0: + modeladmin.message_user( + request, "Keine Nachrichten wurden versendet.", messages.WARNING + ) + elif num_sent_msgs == 1: + modeladmin.message_user( + request, "Eine Nachricht wurde erfolgreich versendet.", messages.SUCCESS + ) + else: + modeladmin.message_user( + request, + f"{num_sent_msgs} Nachrichten wurden erfolgreich versendet.", + messages.SUCCESS, + ) + + class WasSentListFilter(admin.SimpleListFilter): parameter_name = "sent" title = "sent status" @@ -81,6 +122,7 @@ class WasSentListFilter(admin.SimpleListFilter): @admin.register(Message) class MessageAdmin(admin.ModelAdmin): + actions = (send_messages,) list_display = ("__str__", "was_sent") list_filter = (WasSentListFilter,)