diff --git a/Readme.md b/Readme.md index ad9f34d..0ce8c9a 100644 --- a/Readme.md +++ b/Readme.md @@ -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 не схлопываются. Пустая ссылка всегда создаёт новую строку. Файлы такого вызова копируются и на схлопнутое уведомление, и на новое, если часть получателей не схлопнулась. Удаление объекта, на который указывает ссылка, уведомление не удаляет. +`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 остаются текстом. ## Реестр типов @@ -217,7 +234,7 @@ NOTIFY_CODE_RESEND_INTERVAL = 60 # секунд, 0 — без ограниче Просроченные уведомления в эти выборки не входят. Некорректный 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` ничего не меняет. diff --git a/notify/api_schema.py b/notify/api_schema.py index 9f38b8f..ce16d61 100644 --- a/notify/api_schema.py +++ b/notify/api_schema.py @@ -34,6 +34,7 @@ class NotificationResponseSchema(ModelSchema): object_id: str = Field("", alias="notification.object_id") description: Optional[str] = Field(alias="notification.description") data: dict = Field(alias="notification.data") + show_popup: bool = Field(alias="notification.show_popup") attachments: list[AttachmentSchema] class Meta: diff --git a/notify/migrations/0002_notification_show_popup.py b/notify/migrations/0002_notification_show_popup.py new file mode 100644 index 0000000..15de795 --- /dev/null +++ b/notify/migrations/0002_notification_show_popup.py @@ -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), + ), + ] diff --git a/notify/models/notification.py b/notify/models/notification.py index 422d2f4..27c4739 100644 --- a/notify/models/notification.py +++ b/notify/models/notification.py @@ -39,6 +39,7 @@ class Notification(models.Model): content_object = GenericForeignKey("content_type", "object_id") description = models.TextField(blank=True, null=True) 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) expires_at = models.DateTimeField(default=default_expires_at, db_index=True) created_at = models.DateTimeField(db_index=True, auto_now_add=True) diff --git a/notify/services.py b/notify/services.py index b41f4c4..c6fd686 100644 --- a/notify/services.py +++ b/notify/services.py @@ -169,6 +169,7 @@ def create_notification( content_object=None, description: str | None = None, data: dict | None = None, + show_popup: bool = False, expires_at=None, idempotency_key: str | None = None, group: bool = False, @@ -223,6 +224,7 @@ def create_notification( object_id=object_id, description=description, data=data or {}, + show_popup=show_popup, idempotency_key=idempotency_key, ) if expires_at is not None: diff --git a/tests/test_api.py b/tests/test_api.py index 221482f..383669c 100644 --- a/tests/test_api.py +++ b/tests/test_api.py @@ -97,6 +97,7 @@ class ApiTests(TestCase): content_object=subject, description="wire", data={"n": 1}, + show_popup=True, level="success", ) self._browser(self.other, "foreign") @@ -121,9 +122,11 @@ class ApiTests(TestCase): self.assertEqual(item["object_id"], str(subject.pk)) self.assertEqual(item["description"], "wire") self.assertEqual(item["data"], {"n": 1}) + self.assertTrue(item["show_popup"]) self.assertTrue(item["unread"]) self.assertNotIn("channel", item) self.assertNotIn("target", item) + self.assertFalse(body["results"][0]["show_popup"]) count = self.client.get("/api/count/") self.assertEqual(count.json()["result"], 2) diff --git a/tests/test_services.py b/tests/test_services.py index 64eb26d..cf20175 100644 --- a/tests/test_services.py +++ b/tests/test_services.py @@ -46,6 +46,7 @@ class CreateNotificationTests(TestCase): self.assertEqual(notification.notification_type, self.kind) self.assertEqual(notification.level, NotificationLevel.INFO) self.assertEqual(notification.data, {}) + self.assertFalse(notification.show_popup) self.assertIsNone(notification.content_type) self.assertEqual(notification.object_id, "") self.assertIsNone(notification.content_object) @@ -73,6 +74,7 @@ class CreateNotificationTests(TestCase): content_object=self.other, description="Done", data={"n": 1}, + show_popup=True, expires_at=when, recipients=[ {"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.description, "Done") self.assertEqual(notification.data, {"n": 1}) + self.assertTrue(notification.show_popup) self.assertEqual(notification.expires_at, when) def test_title_is_required(self): @@ -756,6 +759,7 @@ class GroupingAndIdempotencyTests(TestCase): second = create_notification( notification_type=self.kind, title="Other", + show_popup=True, idempotency_key="approved:9", group=True, content_object=self.user, @@ -766,6 +770,7 @@ class GroupingAndIdempotencyTests(TestCase): self.assertEqual(Notification.objects.count(), 1) self.assertEqual(second.recipients.count(), 1) self.assertEqual(second.data, {}) + self.assertFalse(second.show_popup) def test_idempotency_conflict_returns_the_existing_row(self): existing = Notification.objects.create(title="Hi", idempotency_key="race")