diff --git a/lacommunaute/notification/tasks.py b/lacommunaute/notification/tasks.py index 09e90c710..fe081d1d7 100644 --- a/lacommunaute/notification/tasks.py +++ b/lacommunaute/notification/tasks.py @@ -1,6 +1,7 @@ from django.conf import settings from django.template.defaultfilters import pluralize from django.urls import reverse +from django.utils import timezone from config.settings.base import DEFAULT_FROM_EMAIL, NEW_MESSAGES_EMAIL_MAX_PREVIEW, SIB_NEW_MESSAGES_TEMPLATE from lacommunaute.forum.models import Forum @@ -14,12 +15,12 @@ def send_messages_notifications(delay: NotificationDelay): """Notifications are scheduled in the application and then processed later by this task""" + notifications = Notification.objects.filter(delay=delay, sent_at__isnull=True, post__isnull=False).select_related( + "post", "post__topic", "post__poster" + ) + def get_grouped_notifications(): - return ( - Notification.objects.filter(delay=delay, sent_at__isnull=True, post__isnull=False) - .select_related("post", "post__topic", "post__poster") - .group_by_recipient() - ) + return notifications.group_by_recipient() grouped_notifications = get_grouped_notifications() for recipient in grouped_notifications.keys(): @@ -40,6 +41,8 @@ def get_grouped_notifications(): template_id=SIB_NEW_MESSAGES_TEMPLATE, ) + notifications.update(sent_at=timezone.now()) + def add_user_to_list_when_register(): new_users = collect_new_users_for_onboarding() diff --git a/lacommunaute/notification/tests/tests_tasks.py b/lacommunaute/notification/tests/tests_tasks.py index 89fcaf3cc..c3cf633f8 100644 --- a/lacommunaute/notification/tests/tests_tasks.py +++ b/lacommunaute/notification/tests/tests_tasks.py @@ -83,6 +83,9 @@ def test_send_messages_notifications_asap(self): email_sent_track.datas, self.get_expected_email_payload(Notification.objects.filter(id=notification.id)) ) + self.assertIsNone(Notification.objects.filter(sent_at__isnull=True).first()) + self.assertEqual(Notification.objects.all().values("sent_at").distinct().count(), 1) + @respx.mock def test_send_messages_notifications_day(self): topic = TopicFactory(with_post=True) @@ -97,6 +100,9 @@ def test_send_messages_notifications_day(self): email_sent_track.datas, self.get_expected_email_payload(Notification.objects.filter(id=notification.id)) ) + self.assertIsNone(Notification.objects.filter(sent_at__isnull=True).first()) + self.assertEqual(Notification.objects.all().values("sent_at").distinct().count(), 1) + @respx.mock def test_send_messages_notifications_max_messages_preview(self): topic = TopicFactory(with_post=True) @@ -121,7 +127,7 @@ def test_send_messages_notifications_max_messages_preview(self): @respx.mock def test_send_messages_notifications_num_queries(self): - expected_queries = 1 + expected_queries = 2 NotificationFactory(delay=NotificationDelay.ASAP)