diff --git a/Readme.md b/Readme.md index f9f2da8..adb2aca 100644 --- a/Readme.md +++ b/Readme.md @@ -125,14 +125,18 @@ NOTIFY_CODE_RESEND_INTERVAL = 60 # секунд, 0 — без ограниче - `GET count/` - `GET list/` - `GET attachments/{id}/` +- `GET preferences/` - `POST make-read/{id}/` - `POST make-unread/{id}/` - `POST make-all-read/` +- `POST preferences/` Просроченные уведомления в эти выборки не входят. Некорректный id возвращает 404. `GET list/` отдаёт `attachments`: `id`, `name`, `size`, `content_type`, `url`. `GET attachments/{id}/` скачивает файл, если у текущего пользователя есть получатель этого уведомления и срок не истёк. Чужой и просроченный файл возвращают 404. +`GET preferences/` отдаёт список активных типов с `can_switch=True`: `code`, `name`, `group_name` и `channels` (`channel`, `enabled`). Нет сохранённого предпочтения — канал включён. `POST preferences/` принимает `{"items": [{"code", "channels": [{"channel", "enabled"}]}]}` и возвращает `{"ok": true}`. Неизвестный канал и тип без `can_switch` дают 400 с `detail`. Пустой `items` ничего не меняет. + API не кэширует ответы и не требует кэша или Redis. Шаблоны subject и body пишутся на Jinja2 и экранируют HTML. Фильтр `markdown` рендерит текст в HTML, предварительно экранируя сырой HTML: `{{ notification.description | markdown }}`. Пропущенное поле остаётся пустой строкой. Контекст — обычные словари, не модели: `notification.verb`, `notification.description`, `notification.url`, `notification.level`, `notification.data`, `notification.object_id`, `recipient.delivery_target` (например, `recipient.delivery_target.email`), `recipient.delivery_channel`, `user.username`. diff --git a/notify/admin.py b/notify/admin.py index 0facd27..5b7b490 100644 --- a/notify/admin.py +++ b/notify/admin.py @@ -85,16 +85,27 @@ class DeliveryEmailConfigAdmin(admin.ModelAdmin): form = DeliveryEmailConfigForm readonly_fields = ['id'] + def _admin_action_url(self, request, action, object_id): + info = self.model._meta.app_label, self.model._meta.model_name + url_name = '%s_%s_%s' % (*info, action) + match = getattr(request, 'resolver_match', None) + if match is not None: + if match.namespace: + url_name = '%s:%s' % (match.namespace, url_name) + return reverse(url_name, args=[object_id]) + return reverse( + 'admin:%s' % url_name, + args=[object_id], + current_app=self.admin_site.name, + ) + def change_view(self, request, object_id, form_url='', extra_context=None): extra_context = extra_context or {} - info = self.model._meta.app_label, self.model._meta.model_name - extra_context['mailbox_test_connection_url'] = reverse( - 'admin:%s_%s_test_connection' % info, - args=[object_id], + extra_context['mailbox_test_connection_url'] = self._admin_action_url( + request, 'test_connection', object_id, ) - extra_context['mailbox_send_test_email_url'] = reverse( - 'admin:%s_%s_send_test_email' % info, - args=[object_id], + extra_context['mailbox_send_test_email_url'] = self._admin_action_url( + request, 'send_test_email', object_id, ) return super().change_view(request, object_id, form_url, extra_context) diff --git a/notify/api.py b/notify/api.py index 98ce51f..fa8c231 100644 --- a/notify/api.py +++ b/notify/api.py @@ -11,8 +11,20 @@ from ninja.security import django_auth from .api_filters import NotificationFilterSchema from .api_pagination import CustomPagination -from .api_schema import NotificationResponseSchema -from .models import DeliveryChannel, NotificationAttachment, NotificationRecipient +from .api_schema import ( + ChannelPreferenceSaveSchema, + DetailSchema, + NotificationResponseSchema, + OkSchema, + Preference, +) +from .models import ( + DeliveryChannel, + NotificationAttachment, + NotificationRecipient, + NotificationType, +) +from .services import channel_preferences, save_channel_preferences __all__ = [ "api", @@ -147,3 +159,36 @@ def list(request, filters: NotificationFilterSchema = Query(...)): qs = filters.filter(_base_user_queryset(request.user)) qs = qs.order_by("-created_at") return qs + + +@api.get("preferences/", response=List[Preference]) +def preferences(request): + saved = { + item["code"]: item["channels"] + for item in channel_preferences(request.user) + } + types = NotificationType.objects.filter( + is_active=True, + can_switch=True, + ).select_related("group") + return [ + { + "code": notification_type.code, + "name": notification_type.name, + "group_name": notification_type.group.name, + "channels": saved.get(notification_type.code, []), + } + for notification_type in types + ] + + +@api.post("preferences/", response={200: OkSchema, 400: DetailSchema}) +def save_preferences(request, payload: ChannelPreferenceSaveSchema): + try: + save_channel_preferences( + request.user, + [item.model_dump() for item in payload.items], + ) + except (ValueError, NotificationType.DoesNotExist) as exc: + return 400, {"detail": str(exc)} + return {"ok": True} diff --git a/notify/api_schema.py b/notify/api_schema.py index f18c41a..46c7517 100644 --- a/notify/api_schema.py +++ b/notify/api_schema.py @@ -7,7 +7,13 @@ from .models import NotificationRecipient __all__ = [ "AttachmentSchema", + "ChannelPreferenceChannelSchema", + "ChannelPreferenceInputSchema", + "ChannelPreferenceSaveSchema", + "Preference", + "DetailSchema", "NotificationResponseSchema", + "OkSchema", ] @@ -56,3 +62,32 @@ class NotificationResponseSchema(ModelSchema): } for attachment in obj.notification.attachments.all() ] + + +class ChannelPreferenceChannelSchema(Schema): + channel: str + enabled: bool + + +class Preference(Schema): + code: str + name: str + group_name: str + channels: list[ChannelPreferenceChannelSchema] + + +class ChannelPreferenceInputSchema(Schema): + code: str + channels: list[ChannelPreferenceChannelSchema] + + +class ChannelPreferenceSaveSchema(Schema): + items: list[ChannelPreferenceInputSchema] = Field(default_factory=list) + + +class OkSchema(Schema): + ok: bool + + +class DetailSchema(Schema): + detail: str diff --git a/tests/test_admin.py b/tests/test_admin.py index 9c9e592..71f8b6c 100644 --- a/tests/test_admin.py +++ b/tests/test_admin.py @@ -4,8 +4,8 @@ from unittest.mock import patch from django.contrib import admin from django.contrib.auth import get_user_model from django.core import mail -from django.test import RequestFactory, TestCase -from django.urls import reverse +from django.test import RequestFactory, TestCase, override_settings +from django.urls import resolve, reverse from notify.admin import ( DeliveryEmailConfigAdmin, @@ -142,6 +142,31 @@ class EmailAdminTests(TestCase): self.assertContains(response, self.connection_url) self.assertContains(response, self.send_url) + @override_settings(ROOT_URLCONF="tests.urls_admin_nonamespace") + def test_change_view_links_without_admin_namespace(self): + object_id = str(self.config.pk) + request = RequestFactory().get( + f"/admin/notify/deliveryemailconfig/{object_id}/change/" + ) + request.user = self.admin + request.resolver_match = resolve(request.path) + self.assertEqual(request.resolver_match.namespace, "") + + # AdminSite.each_context reverses admin:app_list with no fallback. + with patch.object(admin.site, "each_context", return_value={}): + response = DeliveryEmailConfigAdmin( + DeliveryEmailConfig, admin.site + ).change_view(request, object_id) + + self.assertEqual( + response.context_data["mailbox_test_connection_url"], + reverse("notify_deliveryemailconfig_test_connection", args=[self.config.pk]), + ) + self.assertEqual( + response.context_data["mailbox_send_test_email_url"], + reverse("notify_deliveryemailconfig_send_test_email", args=[self.config.pk]), + ) + def test_connection_check_reports_success_without_the_secret(self): response = self.client.post(self.connection_url) body = response.content.decode() diff --git a/tests/test_api.py b/tests/test_api.py index f338f8e..6c5598b 100644 --- a/tests/test_api.py +++ b/tests/test_api.py @@ -1,3 +1,4 @@ +import json from datetime import timedelta from django.contrib.auth import get_user_model @@ -5,7 +6,13 @@ from django.test import TestCase from django.utils import timezone from notify.api_pagination import CustomPagination -from notify.models import DeliveryChannel, NotificationGroup, NotificationRecipient, NotificationType +from notify.models import ( + DeliveryChannel, + NotificationChannelPreference, + NotificationGroup, + NotificationRecipient, + NotificationType, +) from notify.services import create_notification User = get_user_model() @@ -65,13 +72,14 @@ class ApiTests(TestCase): def test_anonymous_requests_are_rejected(self): self.client.logout() recipient_id = 1 - for url in ("/api/unread-count/", "/api/count/", "/api/list/"): + for url in ("/api/unread-count/", "/api/count/", "/api/list/", "/api/preferences/"): with self.subTest(url=url): self.assertEqual(self.client.get(url).status_code, 401) for url in ( f"/api/make-read/{recipient_id}/", f"/api/make-unread/{recipient_id}/", "/api/make-all-read/", + "/api/preferences/", ): with self.subTest(url=url): self.assertEqual(self.client.post(url).status_code, 401) @@ -270,6 +278,145 @@ class ApiTests(TestCase): self.assertEqual(response.status_code, 422) self.assertIn("detail", response.json()) + def _post_preferences(self, payload): + return self.client.post( + "/api/preferences/", + data=json.dumps(payload), + content_type="application/json", + ) + + def test_preferences_list_switchable_types(self): + group = NotificationGroup.objects.create(code="orders", name="Orders") + NotificationType.objects.create( + code="later", + name="Later", + group=group, + channels=[DeliveryChannel.BROWSER], + position=2, + ) + approved = NotificationType.objects.create( + code="approved", + name="Approved", + group=group, + channels=[DeliveryChannel.EMAIL, DeliveryChannel.BROWSER], + position=1, + ) + NotificationType.objects.create( + code="security", + name="Security", + group=group, + channels=[DeliveryChannel.EMAIL], + can_switch=False, + ) + NotificationType.objects.create( + code="retired", + name="Retired", + group=group, + channels=[DeliveryChannel.EMAIL], + is_active=False, + ) + NotificationChannelPreference.objects.create( + user=self.user, + type=approved, + channel=DeliveryChannel.EMAIL, + enabled=False, + ) + + response = self.client.get("/api/preferences/") + self.assertEqual(response.status_code, 200) + self.assertEqual( + response.json(), + [ + { + "code": "approved", + "name": "Approved", + "group_name": "Orders", + "channels": [ + {"channel": DeliveryChannel.EMAIL, "enabled": False}, + {"channel": DeliveryChannel.BROWSER, "enabled": True}, + ], + }, + { + "code": "later", + "name": "Later", + "group_name": "Orders", + "channels": [ + {"channel": DeliveryChannel.BROWSER, "enabled": True}, + ], + }, + ], + ) + + def test_preferences_save_and_reread(self): + self._type("orders.approved") + empty = self._post_preferences({}) + self.assertEqual(empty.status_code, 200) + self.assertEqual(empty.json(), {"ok": True}) + self.assertFalse(NotificationChannelPreference.objects.exists()) + + saved = self._post_preferences( + { + "items": [ + { + "code": "orders.approved", + "channels": [ + {"channel": DeliveryChannel.EMAIL, "enabled": False}, + ], + } + ] + } + ) + self.assertEqual(saved.status_code, 200) + self.assertEqual(saved.json(), {"ok": True}) + + listing = self.client.get("/api/preferences/") + channels = { + item["channel"]: item["enabled"] + for item in listing.json()[0]["channels"] + } + self.assertEqual( + channels, + {DeliveryChannel.EMAIL: False, DeliveryChannel.BROWSER: True}, + ) + + def test_preferences_reject_unknown_channel_and_locked_type(self): + self._type("orders.approved") + group = NotificationGroup.objects.get(code="catalog") + NotificationType.objects.create( + code="security", + name="Security", + group=group, + channels=[DeliveryChannel.EMAIL], + can_switch=False, + ) + + unknown_channel = self._post_preferences( + { + "items": [ + { + "code": "orders.approved", + "channels": [{"channel": DeliveryChannel.MAX, "enabled": True}], + } + ] + } + ) + self.assertEqual(unknown_channel.status_code, 400) + self.assertIn("not allowed", unknown_channel.json()["detail"]) + + locked = self._post_preferences( + { + "items": [ + { + "code": "security", + "channels": [{"channel": DeliveryChannel.EMAIL, "enabled": False}], + } + ] + } + ) + self.assertEqual(locked.status_code, 400) + self.assertIn("detail", locked.json()) + self.assertFalse(NotificationChannelPreference.objects.exists()) + class PaginationTests(TestCase): def setUp(self): diff --git a/tests/urls_admin_nonamespace.py b/tests/urls_admin_nonamespace.py new file mode 100644 index 0000000..34107ed --- /dev/null +++ b/tests/urls_admin_nonamespace.py @@ -0,0 +1,6 @@ +from django.contrib import admin +from django.urls import include, path + +urlpatterns = [ + path("admin/", include(admin.site.get_urls())), +]