From ff66bbde522c7ba0751a2e1d49a8296ed77d67e7 Mon Sep 17 00:00:00 2001 From: Ilya Mukhortov Date: Thu, 15 Oct 2026 11:42:50 +1000 Subject: [PATCH] Add unread_count(user) for the browser inbox total. Hosts can read the same number the unread-count API returns. Co-authored-by: Cursor --- Readme.md | 5 +++-- notify/api.py | 7 ++---- notify/services.py | 12 ++++++++++ tests/test_unread_signal.py | 44 ++++++++++++++++++++++++++++++++++++- 4 files changed, 60 insertions(+), 8 deletions(-) diff --git a/Readme.md b/Readme.md index 10d3f87..eee1eae 100644 --- a/Readme.md +++ b/Readme.md @@ -232,16 +232,17 @@ NOTIFY_CODE_RESEND_INTERVAL = 60 # секунд, 0 — без ограниче - `POST make-all-read/` - `POST preferences/` -Когда у пользователя меняются непрочитанные browser-уведомления, после коммита уходит сигнал `unread_count_changed` с аргументом `user`. Подписчик сам решает, что делать, например заново прочитать `GET unread-count/`. +Когда у пользователя меняются непрочитанные browser-уведомления, после коммита уходит сигнал `unread_count_changed` с аргументом `user`. Число для этого пользователя возвращает `unread_count(user)` — то же, что `GET unread-count/`. ```python from django.dispatch import receiver +from notify.services import unread_count from notify.signals import unread_count_changed @receiver(unread_count_changed) def on_unread_changed(sender, user, **kwargs): - ... + unread_count(user) ``` Просроченные уведомления в эти выборки не входят. Некорректный id возвращает 404. diff --git a/notify/api.py b/notify/api.py index 4518bbe..cd47a8c 100644 --- a/notify/api.py +++ b/notify/api.py @@ -24,7 +24,7 @@ from .models import ( NotificationRecipient, NotificationType, ) -from .services import channel_preferences, save_channel_preferences +from .services import channel_preferences, save_channel_preferences, unread_count as user_unread_count from .signals import schedule_unread_count_changed __all__ = [ @@ -113,10 +113,7 @@ def _get_user_recipient(user, raw_id: str) -> NotificationRecipient: @api.get("unread-count/") def unread_count(request): - count = _base_user_queryset(request.user).filter(unread=True).count() - return { - "result": count, - } + return {"result": user_unread_count(request.user)} @api.post("make-read/{id}/", response=NotificationResponseSchema) diff --git a/notify/services.py b/notify/services.py index c6fd686..1ab64dd 100644 --- a/notify/services.py +++ b/notify/services.py @@ -17,6 +17,7 @@ __all__ = [ "create_notification", "channel_preferences", "save_channel_preferences", + "unread_count", ] @@ -283,3 +284,14 @@ def save_channel_preferences(user, items): channel=channel, defaults={"is_enabled": channel_item["is_enabled"]}, ) + + +def unread_count(user) -> int: + if user is None or not getattr(user, "pk", None): + return 0 + return NotificationRecipient.objects.filter( + user=user, + channel=DeliveryChannel.BROWSER, + unread=True, + notification__expires_at__gte=timezone.now(), + ).count() diff --git a/tests/test_unread_signal.py b/tests/test_unread_signal.py index 1c01054..e6b95aa 100644 --- a/tests/test_unread_signal.py +++ b/tests/test_unread_signal.py @@ -1,10 +1,12 @@ +from datetime import timedelta from unittest.mock import patch from django.contrib.auth import get_user_model from django.test import TestCase +from django.utils import timezone from notify.models import DeliveryChannel -from notify.services import create_notification +from notify.services import create_notification, unread_count from notify.signals import unread_count_changed User = get_user_model() @@ -71,3 +73,43 @@ class UnreadCountSignalTests(TestCase): response = self.client.post("/api/make-all-read/") self.assertEqual(response.status_code, 200) self.assertEqual(self.users, [self.user.pk]) + + +class UnreadCountTests(TestCase): + def setUp(self): + self.user = User.objects.create_user("alice", "alice@example.com", "pass") + self.other = User.objects.create_user("bob", "bob@example.com", "pass") + + def test_counts_open_unread_browser_notifications(self): + create_notification( + title="Hi", + recipients=[{"user": self.user, "channels": [{"channel": DeliveryChannel.BROWSER}]}], + ) + read = create_notification( + title="Read", + recipients=[{"user": self.user, "channels": [{"channel": DeliveryChannel.BROWSER}]}], + ) + read.recipients.get().make_read() + create_notification( + title="Old", + expires_at=timezone.now() - timedelta(minutes=1), + recipients=[{"user": self.user, "channels": [{"channel": DeliveryChannel.BROWSER}]}], + ) + with patch("notify.tasks.deliver_notification.apply_async"): + create_notification( + title="Mail", + recipients=[ + { + "user": self.user, + "channels": [{"channel": DeliveryChannel.EMAIL, "target": {"email": "alice@example.com"}}], + } + ], + ) + create_notification( + title="Other", + recipients=[{"user": self.other, "channels": [{"channel": DeliveryChannel.BROWSER}]}], + ) + + self.assertEqual(unread_count(self.user), 1) + self.assertEqual(unread_count(self.other), 1) + self.assertEqual(unread_count(None), 0)