From 552529cd6b610680fb90396d2298c100a67dccd4 Mon Sep 17 00:00:00 2001 From: Luca Date: Fri, 20 May 2022 00:50:49 +0200 Subject: [PATCH] Send messages on shift changes --- shiftregister/app/apps.py | 3 +++ shiftregister/app/signals.py | 39 ++++++++++++++++++++++++++++++++++ shiftregister/metrics/views.py | 18 ++++++++++++---- 3 files changed, 56 insertions(+), 4 deletions(-) create mode 100644 shiftregister/app/signals.py diff --git a/shiftregister/app/apps.py b/shiftregister/app/apps.py index efe78aa..278aad2 100644 --- a/shiftregister/app/apps.py +++ b/shiftregister/app/apps.py @@ -4,3 +4,6 @@ from django.apps import AppConfig class AppConfig(AppConfig): default_auto_field = "django.db.models.BigAutoField" name = "shiftregister.app" + + def ready(self): + from . import signals diff --git a/shiftregister/app/signals.py b/shiftregister/app/signals.py new file mode 100644 index 0000000..d3980d0 --- /dev/null +++ b/shiftregister/app/signals.py @@ -0,0 +1,39 @@ +from django.db.models.signals import pre_save +from django.dispatch import receiver +from django.shortcuts import reverse +from django.template import Context, Template +from .models import Message, Shift + + +@receiver(pre_save, dispatch_uid="notify_shift_changed") +def notify_shift_changed(sender, **kwargs): + if issubclass(sender, Shift): + instance = kwargs["instance"] + try: + prev = Shift.objects.get(pk=instance.id) + except Shift.DoesNotExist: + return + + if ( + prev.room == instance.room + and prev.start_at == instance.start_at + and prev.duration == instance.duration + and prev.deleted == instance.deleted + ): + return + + message = f"Eine deiner kontakt-Schichten hat sich geändert: https://kontakt.rocks{reverse('shift', kwargs={'shiftid': instance.id})}" + if instance.deleted: + template = Template( + 'Deine kontakt-Schicht "{{ room }}" am {{ start_at|date:"l" }} um {{ start_at|date:"H:i" }} Uhr entfällt.' + ) + message = template.render( + Context({"room": prev.room, "start_at": prev.start_at}) + ) + + Message.objects.bulk_create( + ( + Message(text=message, to=reg.helper) + for reg in instance.shiftregistration_set.all() + ) + ) diff --git a/shiftregister/metrics/views.py b/shiftregister/metrics/views.py index f316446..29a51f9 100644 --- a/shiftregister/metrics/views.py +++ b/shiftregister/metrics/views.py @@ -3,10 +3,20 @@ from shiftregister.app.models import Helper def metrics(request): - response = HttpResponse("\n".join((f"shiftregister_{name} {value}" for name, value in ( - ("helpers_total", Helper.objects.count()), - ("helpers_confirmed_total", Helper.objects.filter(number_validated=True).count()), - )))) + response = HttpResponse( + "\n".join( + ( + f"shiftregister_{name} {value}" + for name, value in ( + ("helpers_total", Helper.objects.count()), + ( + "helpers_confirmed_total", + Helper.objects.filter(number_validated=True).count(), + ), + ) + ) + ) + ) response.headers["Content-Type"] = "text/plain" return response