feat(app): send messages from admin

main
Luca 7 months ago
parent 0679a1cc01
commit 62f470a0d6

@ -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,)

Loading…
Cancel
Save