Add unread_count(user) for the browser inbox total.

Hosts can read the same number the unread-count API returns.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
Ilya Mukhortov 2026-10-15 11:42:50 +10:00
parent 6e2f2f29b9
commit bd0221cfcc
4 changed files with 60 additions and 8 deletions

View File

@ -232,16 +232,17 @@ NOTIFY_CODE_RESEND_INTERVAL = 60 # секунд, 0 — без ограниче
- `POST make-all-read/` - `POST make-all-read/`
- `POST preferences/` - `POST preferences/`
Когда у пользователя меняются непрочитанные browser-уведомления, после коммита уходит сигнал `unread_count_changed` с аргументом `user`. Подписчик сам решает, что делать, например заново прочитать `GET unread-count/`. Когда у пользователя меняются непрочитанные browser-уведомления, после коммита уходит сигнал `unread_count_changed` с аргументом `user`. Число для этого пользователя возвращает `unread_count(user)` — то же, что `GET unread-count/`.
```python ```python
from django.dispatch import receiver from django.dispatch import receiver
from notify.services import unread_count
from notify.signals import unread_count_changed from notify.signals import unread_count_changed
@receiver(unread_count_changed) @receiver(unread_count_changed)
def on_unread_changed(sender, user, **kwargs): def on_unread_changed(sender, user, **kwargs):
... unread_count(user)
``` ```
Просроченные уведомления в эти выборки не входят. Некорректный id возвращает 404. Просроченные уведомления в эти выборки не входят. Некорректный id возвращает 404.

View File

@ -24,7 +24,7 @@ from .models import (
NotificationRecipient, NotificationRecipient,
NotificationType, 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 from .signals import schedule_unread_count_changed
__all__ = [ __all__ = [
@ -113,10 +113,7 @@ def _get_user_recipient(user, raw_id: str) -> NotificationRecipient:
@api.get("unread-count/") @api.get("unread-count/")
def unread_count(request): def unread_count(request):
count = _base_user_queryset(request.user).filter(unread=True).count() return {"result": user_unread_count(request.user)}
return {
"result": count,
}
@api.post("make-read/{id}/", response=NotificationResponseSchema) @api.post("make-read/{id}/", response=NotificationResponseSchema)

View File

@ -17,6 +17,7 @@ __all__ = [
"create_notification", "create_notification",
"channel_preferences", "channel_preferences",
"save_channel_preferences", "save_channel_preferences",
"unread_count",
] ]
@ -283,3 +284,14 @@ def save_channel_preferences(user, items):
channel=channel, channel=channel,
defaults={"is_enabled": channel_item["is_enabled"]}, 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()

View File

@ -1,10 +1,12 @@
from datetime import timedelta
from unittest.mock import patch from unittest.mock import patch
from django.contrib.auth import get_user_model from django.contrib.auth import get_user_model
from django.test import TestCase from django.test import TestCase
from django.utils import timezone
from notify.models import DeliveryChannel 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 from notify.signals import unread_count_changed
User = get_user_model() User = get_user_model()
@ -71,3 +73,43 @@ class UnreadCountSignalTests(TestCase):
response = self.client.post("/api/make-all-read/") response = self.client.post("/api/make-all-read/")
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
self.assertEqual(self.users, [self.user.pk]) 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)