Add popup flag to browser notifications

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
Ilya Mukhortov 2026-10-15 11:17:44 +10:00
parent fad699d40b
commit 95b231ae0a
7 changed files with 45 additions and 1 deletions

View File

@ -77,6 +77,23 @@ create_notification(
Повтор с тем же `idempotency_key` возвращает уже созданную строку и не добавляет новые файлы. `content_object` — сохранённый экземпляр любой модели; в базе это пара `content_type` и `object_id`. Несохранённый экземпляр даёт `ValueError`. `group=True` при заданном `content_object` увеличивает `data["count"]` у непрочитанного browser-уведомления того же типа, того же `content_type` и того же `object_id` и не создаёт новую строку. Две разные модели с одинаковым pk не схлопываются. Пустая ссылка всегда создаёт новую строку. Файлы такого вызова копируются и на схлопнутое уведомление, и на новое, если часть получателей не схлопнулась. Удаление объекта, на который указывает ссылка, уведомление не удаляет. Повтор с тем же `idempotency_key` возвращает уже созданную строку и не добавляет новые файлы. `content_object` — сохранённый экземпляр любой модели; в базе это пара `content_type` и `object_id`. Несохранённый экземпляр даёт `ValueError`. `group=True` при заданном `content_object` увеличивает `data["count"]` у непрочитанного browser-уведомления того же типа, того же `content_type` и того же `object_id` и не создаёт новую строку. Две разные модели с одинаковым pk не схлопываются. Пустая ссылка всегда создаёт новую строку. Файлы такого вызова копируются и на схлопнутое уведомление, и на новое, если часть получателей не схлопнулась. Удаление объекта, на который указывает ссылка, уведомление не удаляет.
`show_popup=True` помечает уведомление для всплывающего показа в интерфейсе. По умолчанию флаг выключен. Библиотека только сохраняет и отдаёт его через browser API: отрисовка toast и учёт уже показанных уведомлений остаются на стороне клиента хост-приложения.
```python
create_notification(
notification_type="appointment.patient_arrived",
show_popup=True,
content_object=visit,
idempotency_key=f"visit:{visit.pk}:arrived",
recipients=[
{
"user": visit.doctor.user,
"channels": [{"channel": "browser"}],
}
],
)
```
`attachments` — список Django-файлов (`UploadedFile`, `File`, `ContentFile` с именем). Пустое имя, больше 10 файлов или файл больше 10 МБ дают `ValueError`, уведомление не сохраняется. Лимиты переопределяются настройками `NOTIFY_MAX_ATTACHMENTS` и `NOTIFY_MAX_ATTACHMENT_BYTES`. Файлы лежат в default storage по пути `notify/attachments/` и не раздаются через `MEDIA_URL`. Удаление уведомления удаляет файлы из хранилища. В письмо они попадают вложением. Telegram, MAX и SMS остаются текстом. `attachments` — список Django-файлов (`UploadedFile`, `File`, `ContentFile` с именем). Пустое имя, больше 10 файлов или файл больше 10 МБ дают `ValueError`, уведомление не сохраняется. Лимиты переопределяются настройками `NOTIFY_MAX_ATTACHMENTS` и `NOTIFY_MAX_ATTACHMENT_BYTES`. Файлы лежат в default storage по пути `notify/attachments/` и не раздаются через `MEDIA_URL`. Удаление уведомления удаляет файлы из хранилища. В письмо они попадают вложением. Telegram, MAX и SMS остаются текстом.
## Реестр типов ## Реестр типов
@ -217,7 +234,7 @@ NOTIFY_CODE_RESEND_INTERVAL = 60 # секунд, 0 — без ограниче
Просроченные уведомления в эти выборки не входят. Некорректный id возвращает 404. Просроченные уведомления в эти выборки не входят. Некорректный id возвращает 404.
`GET list/` отдаёт `content_type` (`app_label.model` или `null`), `object_id` и `attachments`: `id`, `name`, `size`, `content_type`, `url`. Фильтры списка: `content_type`, `object_id`, `object_id__ne`, `object_id__ne__in`. `GET attachments/{id}/` скачивает файл, если у текущего пользователя есть получатель этого уведомления и срок не истёк. Чужой и просроченный файл возвращают 404. `GET list/` отдаёт `content_type` (`app_label.model` или `null`), `object_id`, `show_popup` и `attachments`: `id`, `name`, `size`, `content_type`, `url`. Тот же `show_popup` входит в ответы `POST make-read/{id}/` и `POST make-unread/{id}/`. Фильтры списка: `content_type`, `object_id`, `object_id__ne`, `object_id__ne__in`. `GET attachments/{id}/` скачивает файл, если у текущего пользователя есть получатель этого уведомления и срок не истёк. Чужой и просроченный файл возвращают 404.
`GET preferences/` отдаёт список активных типов с `is_configurable=True`: `code`, `name`, `group_name` и `channels` (`channel`, `is_enabled`). Нет сохранённого предпочтения — `is_enabled` равен `is_enabled_by_default` типа. Сохранённое предпочтение перекрывает флаг. `POST preferences/` принимает `{"items": [{"code", "channels": [{"channel", "is_enabled"}]}]}` и возвращает `{"ok": true}`. Неизвестный канал и тип с `is_configurable=False` дают 400 с `detail`. Пустой `items` ничего не меняет. `GET preferences/` отдаёт список активных типов с `is_configurable=True`: `code`, `name`, `group_name` и `channels` (`channel`, `is_enabled`). Нет сохранённого предпочтения — `is_enabled` равен `is_enabled_by_default` типа. Сохранённое предпочтение перекрывает флаг. `POST preferences/` принимает `{"items": [{"code", "channels": [{"channel", "is_enabled"}]}]}` и возвращает `{"ok": true}`. Неизвестный канал и тип с `is_configurable=False` дают 400 с `detail`. Пустой `items` ничего не меняет.

View File

@ -34,6 +34,7 @@ class NotificationResponseSchema(ModelSchema):
object_id: str = Field("", alias="notification.object_id") object_id: str = Field("", alias="notification.object_id")
description: Optional[str] = Field(alias="notification.description") description: Optional[str] = Field(alias="notification.description")
data: dict = Field(alias="notification.data") data: dict = Field(alias="notification.data")
show_popup: bool = Field(alias="notification.show_popup")
attachments: list[AttachmentSchema] attachments: list[AttachmentSchema]
class Meta: class Meta:

View File

@ -0,0 +1,15 @@
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("notify", "0001_initial"),
]
operations = [
migrations.AddField(
model_name="notification",
name="show_popup",
field=models.BooleanField(default=False),
),
]

View File

@ -39,6 +39,7 @@ class Notification(models.Model):
content_object = GenericForeignKey("content_type", "object_id") content_object = GenericForeignKey("content_type", "object_id")
description = models.TextField(blank=True, null=True) description = models.TextField(blank=True, null=True)
data = models.JSONField(blank=True, default=dict) data = models.JSONField(blank=True, default=dict)
show_popup = models.BooleanField(default=False)
idempotency_key = models.CharField(max_length=255, null=True, blank=True, unique=True) idempotency_key = models.CharField(max_length=255, null=True, blank=True, unique=True)
expires_at = models.DateTimeField(default=default_expires_at, db_index=True) expires_at = models.DateTimeField(default=default_expires_at, db_index=True)
created_at = models.DateTimeField(db_index=True, auto_now_add=True) created_at = models.DateTimeField(db_index=True, auto_now_add=True)

View File

@ -169,6 +169,7 @@ def create_notification(
content_object=None, content_object=None,
description: str | None = None, description: str | None = None,
data: dict | None = None, data: dict | None = None,
show_popup: bool = False,
expires_at=None, expires_at=None,
idempotency_key: str | None = None, idempotency_key: str | None = None,
group: bool = False, group: bool = False,
@ -223,6 +224,7 @@ def create_notification(
object_id=object_id, object_id=object_id,
description=description, description=description,
data=data or {}, data=data or {},
show_popup=show_popup,
idempotency_key=idempotency_key, idempotency_key=idempotency_key,
) )
if expires_at is not None: if expires_at is not None:

View File

@ -97,6 +97,7 @@ class ApiTests(TestCase):
content_object=subject, content_object=subject,
description="wire", description="wire",
data={"n": 1}, data={"n": 1},
show_popup=True,
level="success", level="success",
) )
self._browser(self.other, "foreign") self._browser(self.other, "foreign")
@ -121,9 +122,11 @@ class ApiTests(TestCase):
self.assertEqual(item["object_id"], str(subject.pk)) self.assertEqual(item["object_id"], str(subject.pk))
self.assertEqual(item["description"], "wire") self.assertEqual(item["description"], "wire")
self.assertEqual(item["data"], {"n": 1}) self.assertEqual(item["data"], {"n": 1})
self.assertTrue(item["show_popup"])
self.assertTrue(item["unread"]) self.assertTrue(item["unread"])
self.assertNotIn("channel", item) self.assertNotIn("channel", item)
self.assertNotIn("target", item) self.assertNotIn("target", item)
self.assertFalse(body["results"][0]["show_popup"])
count = self.client.get("/api/count/") count = self.client.get("/api/count/")
self.assertEqual(count.json()["result"], 2) self.assertEqual(count.json()["result"], 2)

View File

@ -46,6 +46,7 @@ class CreateNotificationTests(TestCase):
self.assertEqual(notification.notification_type, self.kind) self.assertEqual(notification.notification_type, self.kind)
self.assertEqual(notification.level, NotificationLevel.INFO) self.assertEqual(notification.level, NotificationLevel.INFO)
self.assertEqual(notification.data, {}) self.assertEqual(notification.data, {})
self.assertFalse(notification.show_popup)
self.assertIsNone(notification.content_type) self.assertIsNone(notification.content_type)
self.assertEqual(notification.object_id, "") self.assertEqual(notification.object_id, "")
self.assertIsNone(notification.content_object) self.assertIsNone(notification.content_object)
@ -73,6 +74,7 @@ class CreateNotificationTests(TestCase):
content_object=self.other, content_object=self.other,
description="Done", description="Done",
data={"n": 1}, data={"n": 1},
show_popup=True,
expires_at=when, expires_at=when,
recipients=[ recipients=[
{"user": self.user, "channels": [{"channel": DeliveryChannel.BROWSER}]}, {"user": self.user, "channels": [{"channel": DeliveryChannel.BROWSER}]},
@ -86,6 +88,7 @@ class CreateNotificationTests(TestCase):
self.assertEqual(notification.object_id, str(self.other.pk)) self.assertEqual(notification.object_id, str(self.other.pk))
self.assertEqual(notification.description, "Done") self.assertEqual(notification.description, "Done")
self.assertEqual(notification.data, {"n": 1}) self.assertEqual(notification.data, {"n": 1})
self.assertTrue(notification.show_popup)
self.assertEqual(notification.expires_at, when) self.assertEqual(notification.expires_at, when)
def test_title_is_required(self): def test_title_is_required(self):
@ -756,6 +759,7 @@ class GroupingAndIdempotencyTests(TestCase):
second = create_notification( second = create_notification(
notification_type=self.kind, notification_type=self.kind,
title="Other", title="Other",
show_popup=True,
idempotency_key="approved:9", idempotency_key="approved:9",
group=True, group=True,
content_object=self.user, content_object=self.user,
@ -766,6 +770,7 @@ class GroupingAndIdempotencyTests(TestCase):
self.assertEqual(Notification.objects.count(), 1) self.assertEqual(Notification.objects.count(), 1)
self.assertEqual(second.recipients.count(), 1) self.assertEqual(second.recipients.count(), 1)
self.assertEqual(second.data, {}) self.assertEqual(second.data, {})
self.assertFalse(second.show_popup)
def test_idempotency_conflict_returns_the_existing_row(self): def test_idempotency_conflict_returns_the_existing_row(self):
existing = Notification.objects.create(title="Hi", idempotency_key="race") existing = Notification.objects.create(title="Hi", idempotency_key="race")