From 4fa62cbb8fd4f2581aa75b1cf89b499ed3d7eeca Mon Sep 17 00:00:00 2001 From: Ilya Mukhortov Date: Mon, 12 Oct 2026 10:16:35 +1000 Subject: [PATCH] Add a code registry that syncs notification types and templates on migrate. Co-authored-by: Cursor --- Readme.md | 63 +++++++++ notify/apps.py | 10 ++ notify/registry.py | 188 ++++++++++++++++++++++++++ tests/test_registry.py | 292 +++++++++++++++++++++++++++++++++++++++++ 4 files changed, 553 insertions(+) create mode 100644 notify/registry.py create mode 100644 tests/test_registry.py diff --git a/Readme.md b/Readme.md index a1e0be3..9018131 100644 --- a/Readme.md +++ b/Readme.md @@ -61,6 +61,69 @@ create_notification( `attachments` — список Django-файлов (`UploadedFile`, `File`, `ContentFile` с именем). Пустое имя, больше 10 файлов или файл больше 10 МБ дают `ValueError`, уведомление не сохраняется. Лимиты переопределяются настройками `NOTIFY_MAX_ATTACHMENTS` и `NOTIFY_MAX_ATTACHMENT_BYTES`. Файлы лежат в default storage по пути `notify/attachments/` и не раздаются через `MEDIA_URL`. Удаление уведомления удаляет файлы из хранилища. В письмо они попадают вложением. Telegram и MAX остаются текстом. +## Реестр типов + +Группы, типы и шаблоны можно описать в коде приложения. Модуль нужно импортировать из `AppConfig.ready`, иначе регистрация произойдёт слишком поздно. `migrate` записывает реестр в базу и делает это даже без новых миграций. + +```python +# appointment/notifications.py +from notify.registry import GroupSpec, TemplateSpec, TypeSpec, register + +register( + GroupSpec("appointment", "Записи"), + TypeSpec( + code="appointment.created", + name="Запись создана", + group="appointment", + channels=("browser", "email"), + title="Запись создана", + templates=( + TemplateSpec( + "email", + subject="Запись создана", + body="{{ notification.description }}", + ), + ), + ), +) +``` + +```python +# appointment/apps.py +from django.apps import AppConfig + + +class AppointmentConfig(AppConfig): + name = "appointment" + + def ready(self): + from appointment import notifications # noqa: F401 +``` + +Повторная регистрация тех же данных ничего не меняет. Другие данные для того же кода дают `ValueError` при старте. Группа типа должна быть зарегистрирована раньше, в том же вызове `register` или в предыдущем. + +Отправка по-прежнему идёт через `create_notification`. Заголовок можно не передавать: его возьмёт тип. + +```python +create_notification( + notification_type="appointment.created", + description="12 октября, 10:00", + recipients=[ + { + "user": user, + "channels": [ + {"channel": "browser"}, + {"channel": "email", "target": {"email": user.email}}, + ], + } + ], +) +``` + +Канал `browser` шаблона не требует: API отдаёт `title` и `description`. Для `email`, `telegram` и `max` шаблон из реестра пишется в `NotificationTemplate` и используется при доставке. Имя новой строки — `{код}.{канал}`. Канал шаблона, которого больше нет в спеке, удаляется у этого типа. + +Код перезаписывает имя, каналы, группу, заголовок, флаги и текст шаблонов зарегистрированного типа. Правка этих полей в админке пропадёт на следующем `migrate`. Типы и шаблоны, которых нет в реестре, не меняются. Удаление кода из реестра строку не удаляет и не выключает: чтобы тип перестал отправляться, оставьте его в реестре с `is_active=False`. + ## Доставка Каналы `email`, `max` и `telegram` ставятся в Celery-задачу `notify.tasks.deliver_notification` после коммита транзакции. Канал `browser` помечается отправленным сразу и попадает в API. diff --git a/notify/apps.py b/notify/apps.py index 9e4ecc3..96e5a24 100644 --- a/notify/apps.py +++ b/notify/apps.py @@ -11,7 +11,17 @@ class NotifyConfig(AppConfig): verbose_name = "Notifications" def ready(self): + from django.db.models.signals import post_migrate + from notify.delivery.providers import register_builtin_providers + from notify.registry import sync_on_migrate register_builtin_providers() import notify.receivers # noqa: F401 + + post_migrate.connect( + sync_on_migrate, + sender=self, + weak=False, + dispatch_uid="notify.sync_registered", + ) diff --git a/notify/registry.py b/notify/registry.py new file mode 100644 index 0000000..a50af54 --- /dev/null +++ b/notify/registry.py @@ -0,0 +1,188 @@ +from dataclasses import dataclass + +from django.core.exceptions import ValidationError +from django.db import transaction + +from notify.models import NotificationGroup, NotificationTemplate, NotificationType +from notify.models.choices import validate_delivery_channels + +__all__ = [ + "GroupSpec", + "TemplateSpec", + "TypeSpec", + "clear", + "register", + "sync_registered", +] + +_groups: dict[str, "GroupSpec"] = {} +_types: dict[str, "TypeSpec"] = {} + + +def _require_text(value, label, max_length): + if not isinstance(value, str) or not value.strip(): + raise ValueError(f"{label} is required") + if len(value) > max_length: + raise ValueError(f"{label} is longer than {max_length} characters") + + +def _check_channels(channels): + if isinstance(channels, str) or not isinstance(channels, (list, tuple)): + raise ValueError("channels must be a list") + try: + validate_delivery_channels(list(channels)) + except ValidationError as exc: + raise ValueError(exc.messages[0]) from exc + if len(set(channels)) != len(channels): + raise ValueError("channels must be unique") + return tuple(channels) + + +@dataclass(frozen=True) +class GroupSpec: + code: str + name: str + + def __post_init__(self): + _require_text(self.code, "Notification group code", NotificationGroup._meta.get_field("code").max_length) + _require_text(self.name, "Notification group name", NotificationGroup._meta.get_field("name").max_length) + + +@dataclass(frozen=True) +class TemplateSpec: + channel: str + body: str + subject: str = "" + + def __post_init__(self): + _check_channels((self.channel,)) + if not isinstance(self.body, str) or not self.body: + raise ValueError("template body is required") + if not isinstance(self.subject, str): + raise ValueError("template subject must be a string") + + +@dataclass(frozen=True) +class TypeSpec: + code: str + name: str + group: str + channels: tuple[str, ...] = () + title: str | None = None + position: int = 0 + is_active: bool = True + is_configurable: bool = True + is_enabled_by_default: bool = True + templates: tuple[TemplateSpec, ...] = () + + def __post_init__(self): + code_field = NotificationType._meta.get_field("code") + name_field = NotificationType._meta.get_field("name") + title_field = NotificationType._meta.get_field("title") + _require_text(self.code, "Notification type code", code_field.max_length) + _require_text(self.name, "Notification type name", name_field.max_length) + _require_text(self.group, "Notification group code", NotificationGroup._meta.get_field("code").max_length) + channels = _check_channels(self.channels) + templates = [] + seen = set() + for template in self.templates: + if not isinstance(template, TemplateSpec): + raise ValueError("templates must be TemplateSpec instances") + if template.channel not in channels: + raise ValueError( + f"Template channel {template.channel} is not allowed for notification type {self.code}" + ) + if template.channel in seen: + raise ValueError( + f"Duplicate template channel {template.channel} for notification type {self.code}" + ) + seen.add(template.channel) + templates.append(template) + if self.title is not None: + _require_text(self.title, "title", title_field.max_length) + object.__setattr__(self, "channels", channels) + object.__setattr__(self, "templates", tuple(sorted(templates, key=lambda item: item.channel))) + + +def register(*specs: GroupSpec | TypeSpec) -> None: + for spec in specs: + if isinstance(spec, GroupSpec): + _register_group(spec) + elif isinstance(spec, TypeSpec): + _register_type(spec) + else: + raise TypeError(f"Expected GroupSpec or TypeSpec, got {type(spec).__name__}") + + +def clear() -> None: + _groups.clear() + _types.clear() + + +def sync_on_migrate(sender, **kwargs) -> None: + sync_registered() + + +def sync_registered() -> None: + with transaction.atomic(): + for spec in _groups.values(): + NotificationGroup.objects.update_or_create(code=spec.code, defaults={"name": spec.name}) + for spec in _types.values(): + group = NotificationGroup.objects.get(code=spec.group) + notification_type, _created = NotificationType.objects.update_or_create( + code=spec.code, + defaults={ + "name": spec.name, + "channels": list(spec.channels), + "group": group, + "title": spec.title, + "position": spec.position, + "is_active": spec.is_active, + "is_configurable": spec.is_configurable, + "is_enabled_by_default": spec.is_enabled_by_default, + }, + ) + _sync_templates(notification_type, spec) + + +def _register_group(spec: GroupSpec) -> None: + existing = _groups.get(spec.code) + if existing is not None and existing != spec: + raise ValueError(f"Notification group {spec.code} is already registered with different data") + _groups[spec.code] = spec + + +def _register_type(spec: TypeSpec) -> None: + if spec.group not in _groups: + raise ValueError(f"Notification group {spec.group} is not registered") + existing = _types.get(spec.code) + if existing is not None and existing != spec: + raise ValueError(f"Notification type {spec.code} is already registered with different data") + _types[spec.code] = spec + + +def _sync_templates(notification_type: NotificationType, spec: TypeSpec) -> None: + kept = [] + for template in spec.templates: + kept.append(template.channel) + try: + row = NotificationTemplate.objects.get( + notification_type=notification_type, + channel=template.channel, + ) + except NotificationTemplate.DoesNotExist: + NotificationTemplate.objects.create( + notification_type=notification_type, + channel=template.channel, + name=f"{spec.code}.{template.channel}", + subject=template.subject, + body=template.body, + ) + else: + row.subject = template.subject + row.body = template.body + row.save(update_fields=["subject", "body"]) + stale = NotificationTemplate.objects.filter(notification_type=notification_type) + if kept: + stale = stale.exclude(channel__in=kept) + stale.delete() diff --git a/tests/test_registry.py b/tests/test_registry.py new file mode 100644 index 0000000..9ab7b04 --- /dev/null +++ b/tests/test_registry.py @@ -0,0 +1,292 @@ +from django.apps import apps +from django.contrib.auth import get_user_model +from django.core import mail +from django.db.models.signals import post_migrate +from django.test import TestCase + +from notify.models import ( + DeliveryChannel, + DeliveryEmailConfig, + NotificationGroup, + NotificationTemplate, + NotificationType, +) +from notify.registry import GroupSpec, TemplateSpec, TypeSpec, clear, register, sync_registered +from notify.services import create_notification +from notify.tasks import deliver_notification + +User = get_user_model() + + +def appointment_specs( + *, + group_name="Записи", + created_body="когда={{ notification.description }}", + created_templates=None, +): + if created_templates is None: + created_templates = ( + TemplateSpec( + "email", + subject="Создана: {{ notification.title }}", + body=created_body, + ), + TemplateSpec("telegram", subject="Запись", body="Новая запись"), + ) + return ( + GroupSpec("appointment", group_name), + TypeSpec( + code="appointment.created", + name="Запись создана", + group="appointment", + channels=("browser", "email", "telegram"), + title="Запись создана", + templates=created_templates, + ), + TypeSpec( + code="appointment.confirmed", + name="Запись подтверждена", + group="appointment", + channels=("browser", "email"), + title="Запись подтверждена", + position=1, + templates=( + TemplateSpec("email", subject="Подтверждена", body="Запись подтверждена"), + ), + ), + TypeSpec( + code="appointment.cancelled", + name="Запись отменена", + group="appointment", + channels=("browser", "email"), + title="Запись отменена", + position=2, + templates=( + TemplateSpec("email", subject="Отменена", body="Запись отменена"), + ), + ), + TypeSpec( + code="appointment.reminder", + name="Напоминание о записи", + group="appointment", + channels=("browser", "email"), + title="Напоминание о записи", + position=3, + is_configurable=False, + templates=( + TemplateSpec("email", subject="Напоминание", body="Скоро запись"), + ), + ), + ) + + +class RegistryTests(TestCase): + def setUp(self): + clear() + + def tearDown(self): + clear() + + def test_sync_creates_group_types_and_templates(self): + register(*appointment_specs()) + register(*appointment_specs()) + sync_registered() + first_ids = self._ids() + sync_registered() + + self.assertEqual(self._ids(), first_ids) + group = NotificationGroup.objects.get(code="appointment") + self.assertEqual(group.name, "Записи") + self.assertEqual( + list(NotificationType.objects.filter(group=group).values_list("code", flat=True)), + [ + "appointment.created", + "appointment.confirmed", + "appointment.cancelled", + "appointment.reminder", + ], + ) + created = NotificationType.objects.get(code="appointment.created") + self.assertEqual(created.channels, ["browser", "email", "telegram"]) + self.assertEqual(created.title, "Запись создана") + email = created.templates.get(channel=DeliveryChannel.EMAIL) + self.assertEqual(email.name, "appointment.created.email") + self.assertEqual(email.subject, "Создана: {{ notification.title }}") + self.assertEqual(email.body, "когда={{ notification.description }}") + reminder = NotificationType.objects.get(code="appointment.reminder") + self.assertEqual(reminder.position, 3) + self.assertFalse(reminder.is_configurable) + self.assertEqual(NotificationTemplate.objects.filter(notification_type__group=group).count(), 5) + + def test_sync_overwrites_template_body_and_keeps_the_row(self): + register(*appointment_specs()) + sync_registered() + template = NotificationTemplate.objects.get( + notification_type__code="appointment.created", + channel=DeliveryChannel.EMAIL, + ) + template.name = "custom-email" + template.save(update_fields=["name"]) + + clear() + register(*appointment_specs(group_name="Записи к врачу", created_body="обновлено")) + sync_registered() + + template.refresh_from_db() + self.assertEqual(template.body, "обновлено") + self.assertEqual(template.name, "custom-email") + self.assertEqual(NotificationGroup.objects.get(code="appointment").name, "Записи к врачу") + + def test_sync_deletes_template_removed_from_the_spec(self): + register(*appointment_specs()) + sync_registered() + created = NotificationType.objects.get(code="appointment.created") + self.assertTrue(created.templates.filter(channel=DeliveryChannel.TELEGRAM).exists()) + + clear() + register( + *appointment_specs( + created_templates=( + TemplateSpec( + "email", + subject="Создана: {{ notification.title }}", + body="когда={{ notification.description }}", + ), + ) + ) + ) + sync_registered() + + self.assertFalse(created.templates.filter(channel=DeliveryChannel.TELEGRAM).exists()) + self.assertTrue(created.templates.filter(channel=DeliveryChannel.EMAIL).exists()) + + def test_sync_leaves_unregistered_rows(self): + group = NotificationGroup.objects.create(code="billing", name="Billing") + kind = NotificationType.objects.create( + code="invoice", + name="Invoice", + group=group, + channels=[DeliveryChannel.EMAIL], + title="Invoice", + ) + typed = NotificationTemplate.objects.create( + name="invoice-email", + channel=DeliveryChannel.EMAIL, + notification_type=kind, + subject="Invoice", + body="Pay", + ) + default = NotificationTemplate.objects.create( + name="default-email", + channel=DeliveryChannel.EMAIL, + is_default=True, + subject="Default", + body="Default body", + ) + register(*appointment_specs()) + sync_registered() + + typed.refresh_from_db() + default.refresh_from_db() + kind.refresh_from_db() + self.assertEqual(typed.body, "Pay") + self.assertEqual(default.body, "Default body") + self.assertEqual(kind.name, "Invoice") + self.assertTrue(NotificationGroup.objects.filter(code="billing").exists()) + + def test_same_code_with_different_data_is_rejected(self): + register(*appointment_specs()) + with self.assertRaisesMessage(ValueError, "already registered"): + register( + TypeSpec( + code="appointment.created", + name="Другое имя", + group="appointment", + channels=("browser",), + title="Другое", + ) + ) + with self.assertRaisesMessage(ValueError, "already registered"): + register(GroupSpec("appointment", "Другое")) + self.assertFalse(NotificationType.objects.exists()) + + def test_unknown_channel_is_rejected(self): + with self.assertRaisesMessage(ValueError, "Unknown channels"): + TypeSpec( + code="appointment.created", + name="Запись создана", + group="appointment", + channels=("fax",), + title="Запись создана", + ) + + def test_template_channel_must_belong_to_the_type(self): + with self.assertRaisesMessage(ValueError, "is not allowed"): + TypeSpec( + code="appointment.created", + name="Запись создана", + group="appointment", + channels=("browser",), + title="Запись создана", + templates=(TemplateSpec("email", subject="Тема", body="Текст"),), + ) + + def test_type_requires_a_registered_group(self): + with self.assertRaisesMessage(ValueError, "is not registered"): + register( + TypeSpec( + code="appointment.created", + name="Запись создана", + group="appointment", + channels=("browser",), + title="Запись создана", + ) + ) + + def test_post_migrate_syncs_registered_types(self): + register(*appointment_specs()) + receiver = next( + receiver + for (receiver_key, _), receiver, _is_async in post_migrate.receivers + if receiver_key == "notify.sync_registered" + ) + receiver(sender=apps.get_app_config("notify")) + self.assertTrue(NotificationType.objects.filter(code="appointment.confirmed").exists()) + + def test_create_notification_uses_the_synced_email_template(self): + user = User.objects.create_user("alice", "alice@example.com", "pass") + DeliveryEmailConfig.objects.create( + name="default-smtp", + channel=DeliveryChannel.EMAIL, + is_default=True, + host="smtp.example.com", + port=587, + from_email="noreply@example.com", + use_ssl=False, + use_tls=False, + ) + register(*appointment_specs()) + sync_registered() + notification = create_notification( + notification_type="appointment.created", + description="12 октября, 10:00", + recipients=[ + { + "user": user, + "channels": [ + {"channel": DeliveryChannel.EMAIL, "target": {"email": "alice@example.com"}}, + ], + } + ], + ) + self.assertEqual(notification.title, "Запись создана") + deliver_notification.apply(args=[str(notification.recipients.get().id)], throw=True) + self.assertEqual(mail.outbox[0].subject, "Создана: Запись создана") + self.assertIn("когда=12 октября, 10:00", mail.outbox[0].body) + + def _ids(self): + return { + "group": NotificationGroup.objects.get(code="appointment").pk, + "types": set(NotificationType.objects.values_list("pk", flat=True)), + "templates": set(NotificationTemplate.objects.values_list("pk", flat=True)), + }