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:
parent
6e2f2f29b9
commit
bd0221cfcc
|
|
@ -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.
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
|
|
|
|||
|
|
@ -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()
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
|
|
|
|||
Loading…
Reference in New Issue