From fad699d40b953da4d897e8bf63fdf7b0bf5df645 Mon Sep 17 00:00:00 2001 From: Ilya Mukhortov Date: Mon, 12 Oct 2026 10:51:38 +1000 Subject: [PATCH] Release 0.5 with SMS via Exolve and recipients who are not users. Co-authored-by: Cursor --- Readme.md | 37 ++++- notify/admin.py | 8 +- notify/delivery/base.py | 20 ++- notify/delivery/providers/__init__.py | 3 + notify/delivery/providers/exolve.py | 102 ++++++++++++ notify/migrations/0001_initial.py | 21 ++- notify/models/choices.py | 1 + notify/models/delivery.py | 1 + notify/models/notification.py | 5 + notify/services.py | 27 +++- pyproject.toml | 2 +- tests/test_admin.py | 14 +- tests/test_codes.py | 20 +++ tests/test_delivery.py | 223 +++++++++++++++++++++++++- tests/test_models.py | 6 +- tests/test_services.py | 110 ++++++++++++- 16 files changed, 560 insertions(+), 40 deletions(-) create mode 100644 notify/delivery/providers/exolve.py diff --git a/Readme.md b/Readme.md index 9018131..ad9f34d 100644 --- a/Readme.md +++ b/Readme.md @@ -55,11 +55,29 @@ create_notification( `create_notification` выбрасывает `ValueError`, если тип выключен, канал не входит в тип, канал неизвестен или получатель продублирован. Неактивный тип и пропущенный канал не оставляют пустое уведомление в базе. -Получатель канала задаётся словарём `target`, который проверяется pydantic-схемой провайдера: `email` — `{"email": ...}`, `telegram` — `{"chat_id": ...}`, `max` — `{"chat_id": ..., "user_id": ...}` (`user_id` необязателен). У `browser` `target` нет. В базе он хранится в `NotificationRecipient.target`. Если у типа `is_configurable=True`, канал с `NotificationChannelPreference.is_enabled=False` не создаётся. Строки предпочтения нет — канал берёт `NotificationType.is_enabled_by_default` (по умолчанию включён). `is_configurable=False` не смотрит ни на предпочтения, ни на этот флаг. Если после фильтра не осталось получателей, уведомление откатывается. +`user` в получателе необязателен для `email`, `sms`, `max` и `telegram`. Без пользователя адрес берётся только из `target`. Рядом можно передать `content_object` — сохранённый экземпляр любой модели, например пациента или клиента. Это кто получает сообщение, и это не то же поле, что `content_object` у самого уведомления. Несохранённый экземпляр даёт `ValueError`. `browser` без `user` даёт `ValueError`: входящие читает только авторизованный пользователь. Предпочтения канала и `group=True` применяются только к получателю с `user`. Дубль — тот же `user` и тот же канал внутри одного уведомления. Получатель без `user` повтором не считается. + +```python +create_notification( + title="Запись подтверждена", + recipients=[ + { + "content_object": patient, + "channels": [ + {"channel": "sms", "target": {"phone": patient.phone}}, + {"channel": "email", "target": {"email": patient.email}}, + ], + }, + {"channels": [{"channel": "sms", "target": {"phone": "79991234567"}}]}, + ], +) +``` + +Получатель канала задаётся словарём `target`, который проверяется pydantic-схемой провайдера: `email` — `{"email": ...}`, `telegram` — `{"chat_id": ...}`, `max` — `{"chat_id": ..., "user_id": ...}` (`user_id` необязателен), `sms` — `{"phone": ...}`. У `browser` `target` нет. В базе он хранится в `NotificationRecipient.target`. Если у типа `is_configurable=True` и у получателя есть `user`, канал с `NotificationChannelPreference.is_enabled=False` не создаётся. Строки предпочтения нет — канал берёт `NotificationType.is_enabled_by_default` (по умолчанию включён). `is_configurable=False` не смотрит ни на предпочтения, ни на этот флаг. Без `user` предпочтения не фильтруют каналы. Если после фильтра не осталось получателей, уведомление откатывается. Повтор с тем же `idempotency_key` возвращает уже созданную строку и не добавляет новые файлы. `content_object` — сохранённый экземпляр любой модели; в базе это пара `content_type` и `object_id`. Несохранённый экземпляр даёт `ValueError`. `group=True` при заданном `content_object` увеличивает `data["count"]` у непрочитанного browser-уведомления того же типа, того же `content_type` и того же `object_id` и не создаёт новую строку. Две разные модели с одинаковым pk не схлопываются. Пустая ссылка всегда создаёт новую строку. Файлы такого вызова копируются и на схлопнутое уведомление, и на новое, если часть получателей не схлопнулась. Удаление объекта, на который указывает ссылка, уведомление не удаляет. -`attachments` — список Django-файлов (`UploadedFile`, `File`, `ContentFile` с именем). Пустое имя, больше 10 файлов или файл больше 10 МБ дают `ValueError`, уведомление не сохраняется. Лимиты переопределяются настройками `NOTIFY_MAX_ATTACHMENTS` и `NOTIFY_MAX_ATTACHMENT_BYTES`. Файлы лежат в default storage по пути `notify/attachments/` и не раздаются через `MEDIA_URL`. Удаление уведомления удаляет файлы из хранилища. В письмо они попадают вложением. Telegram и MAX остаются текстом. +`attachments` — список Django-файлов (`UploadedFile`, `File`, `ContentFile` с именем). Пустое имя, больше 10 файлов или файл больше 10 МБ дают `ValueError`, уведомление не сохраняется. Лимиты переопределяются настройками `NOTIFY_MAX_ATTACHMENTS` и `NOTIFY_MAX_ATTACHMENT_BYTES`. Файлы лежат в default storage по пути `notify/attachments/` и не раздаются через `MEDIA_URL`. Удаление уведомления удаляет файлы из хранилища. В письмо они попадают вложением. Telegram, MAX и SMS остаются текстом. ## Реестр типов @@ -120,13 +138,13 @@ create_notification( ) ``` -Канал `browser` шаблона не требует: API отдаёт `title` и `description`. Для `email`, `telegram` и `max` шаблон из реестра пишется в `NotificationTemplate` и используется при доставке. Имя новой строки — `{код}.{канал}`. Канал шаблона, которого больше нет в спеке, удаляется у этого типа. +Канал `browser` шаблона не требует: API отдаёт `title` и `description`. Для `email`, `telegram`, `max` и `sms` шаблон из реестра пишется в `NotificationTemplate` и используется при доставке. Имя новой строки — `{код}.{канал}`. Канал шаблона, которого больше нет в спеке, удаляется у этого типа. Код перезаписывает имя, каналы, группу, заголовок, флаги и текст шаблонов зарегистрированного типа. Правка этих полей в админке пропадёт на следующем `migrate`. Типы и шаблоны, которых нет в реестре, не меняются. Удаление кода из реестра строку не удаляет и не выключает: чтобы тип перестал отправляться, оставьте его в реестре с `is_active=False`. ## Доставка -Каналы `email`, `max` и `telegram` ставятся в Celery-задачу `notify.tasks.deliver_notification` после коммита транзакции. Канал `browser` помечается отправленным сразу и попадает в API. +Каналы `email`, `max`, `telegram` и `sms` ставятся в Celery-задачу `notify.tasks.deliver_notification` после коммита транзакции. Канал `browser` помечается отправленным сразу и попадает в API. Воркер берёт строку получателя с блокировкой. Ошибка SMTP или временная ошибка HTTP повторяется до 5 раз с паузами 1, 2, 4, 8 и 16 минут (плюс до 10% случайной добавки). Таймаут SMTP и HTTP — 10 секунд. Каждая попытка увеличивает `attempts` и пишет `last_error`. Постоянная ошибка и исчерпание попыток ставят статус `failed`. Успех ставит `sent` и `sent_at`. @@ -142,11 +160,13 @@ app.conf.beat_schedule.update(BEAT_SCHEDULE) Почтовый конфиг по умолчанию: порт `587`, `use_tls=True`, `use_ssl=False`. Одновременно включить SSL и TLS нельзя. Для каждого канала хранится один конфиг и один шаблон с `is_default=True` и пустым типом. Шаблон с указанным типом используется только для этой пары тип+канал, иначе берётся дефолт канала. -Пароль SMTP и токены MAX и Telegram хранятся в базе зашифрованными. В форме админки значение не подставляется обратно в HTML; пустое поле при сохранении оставляет прежний секрет. Проверка SMTP в админке — только POST. +Пароль SMTP и токены MAX, Telegram и SMS хранятся в базе зашифрованными. В форме админки значение не подставляется обратно в HTML; пустое поле при сохранении оставляет прежний секрет. Проверка SMTP в админке — только POST. + +SMS уходит через МТС Exolve: `POST https://api.exolve.ru/messaging/v1/SendSMS` с заголовком `Authorization: Bearer <токен>`. В конфиге токена с каналом `sms` и `is_default=True` поле `sender` обязательно: это номер или альфа-имя отправителя (`number` в запросе). Номер получателя нормализуется: убираются пробелы, скобки, дефисы и ведущий `+`, российский `8XXXXXXXXXX` становится `7XXXXXXXXXX`. В текст попадают заголовок и описание без HTML. Вложения не отправляются. ## Коды подтверждения -Одноразовые коды отправляются в `email`, `telegram` и `max` синхронно, без Celery и без создания `Notification`: +Одноразовые коды отправляются в `email`, `telegram`, `max` и `sms` синхронно, без Celery и без создания `Notification`: ```python from notify.codes import CodeThrottled, send_code, verify_code @@ -157,13 +177,14 @@ except CodeThrottled as exc: ... # exc.retry_after — сколько секунд ждать send_code(purpose="login", channel="telegram", target={"chat_id": 42}) +send_code(purpose="login", channel="sms", target={"phone": "79991234567"}) verify_code(purpose="login", channel="email", target={"email": user.email}, code="123456") # True / False ``` `target` проверяется так же, как в `create_notification`. Неизвестный канал, `browser` или некорректный получатель дают `ValueError`. Ошибка провайдера пробрасывается как `DeliveryError` или `PermanentDeliveryError`. В этом случае новый код не сохраняется, а предыдущий остаётся действующим. -Код ищется по ключу `purpose` + канал + получатель. Email сравнивается без учёта регистра, для MAX ключом служит `user_id`, если он передан, иначе `chat_id`. Новый код гасит предыдущий. Повторная отправка раньше `NOTIFY_CODE_RESEND_INTERVAL` даёт `CodeThrottled`. `verify_code` возвращает `False`, если кода нет, он истёк, уже использован или попытки исчерпаны. Каждая проверка увеличивает `attempts`, успешная помечает код использованным. +Код ищется по ключу `purpose` + канал + получатель. Email сравнивается без учёта регистра, для MAX ключом служит `user_id`, если он передан, иначе `chat_id`. Для SMS ключ — нормализованный номер, поэтому `+7` и `8` совпадают. Новый код гасит предыдущий. Повторная отправка раньше `NOTIFY_CODE_RESEND_INTERVAL` даёт `CodeThrottled`. `verify_code` возвращает `False`, если кода нет, он истёк, уже использован или попытки исчерпаны. Каждая проверка увеличивает `attempts`, успешная помечает код использованным. В базе лежит только HMAC от `SECRET_KEY` и id строки. Смена `SECRET_KEY` делает выданные коды недействительными. Сам код не пишется в базу, логи и тексты исключений. @@ -202,7 +223,7 @@ NOTIFY_CODE_RESEND_INTERVAL = 60 # секунд, 0 — без ограниче API не кэширует ответы и не требует кэша или Redis. -Шаблоны subject и body пишутся на Jinja2 и экранируют HTML. Фильтр `markdown` рендерит текст в HTML, предварительно экранируя сырой HTML: `{{ notification.description | markdown }}`. Пропущенное поле остаётся пустой строкой. Контекст — обычные словари, не модели: `notification.title`, `notification.description`, `notification.url`, `notification.level`, `notification.data`, `notification.content_type` (`app_label.model` или пусто), `notification.object_id`, `recipient.target` (например, `recipient.target.email`), `recipient.channel`, `user.username`. +Шаблоны subject и body пишутся на Jinja2 и экранируют HTML. Фильтр `markdown` рендерит текст в HTML, предварительно экранируя сырой HTML: `{{ notification.description | markdown }}`. Пропущенное поле остаётся пустой строкой. Контекст — обычные словари, не модели: `notification.title`, `notification.description`, `notification.url`, `notification.level`, `notification.data`, `notification.content_type` (`app_label.model` или пусто), `notification.object_id`, `recipient.target` (например, `recipient.target.email`), `recipient.channel`, `recipient.content_type`, `recipient.object_id`. `user` равен `None`, если у получателя нет пользователя; иначе это `user.id` и `user.username`. ## Тесты diff --git a/notify/admin.py b/notify/admin.py index a292fca..2f7b102 100644 --- a/notify/admin.py +++ b/notify/admin.py @@ -65,7 +65,7 @@ class DeliveryTokenConfigForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) - allowed = {DeliveryChannel.MAX, DeliveryChannel.TELEGRAM} + allowed = {DeliveryChannel.MAX, DeliveryChannel.TELEGRAM, DeliveryChannel.SMS} self.fields["channel"].choices = [ choice for choice in DeliveryChannel.choices if choice[0] in allowed ] @@ -76,6 +76,12 @@ class DeliveryTokenConfigForm(forms.ModelForm): return self.instance.token return token + def clean(self): + cleaned = super().clean() + if cleaned.get("channel") == DeliveryChannel.SMS and not (cleaned.get("sender") or "").strip(): + self.add_error("sender", "Sender is required for SMS") + return cleaned + @admin.register(DeliveryEmailConfig) class DeliveryEmailConfigAdmin(admin.ModelAdmin): diff --git a/notify/delivery/base.py b/notify/delivery/base.py index 4b61545..6d0fc5b 100644 --- a/notify/delivery/base.py +++ b/notify/delivery/base.py @@ -28,12 +28,25 @@ def _single_line(value: str | None) -> str: def template_context(notification_recipient: NotificationRecipient) -> dict: notification = notification_recipient.notification user = notification_recipient.user - username_field = user.__class__.USERNAME_FIELD + if user is None: + user_context = None + else: + username_field = user.__class__.USERNAME_FIELD + user_context = { + "id": user.pk, + "username": getattr(user, username_field, ""), + } return { "recipient": { "id": str(notification_recipient.id), "channel": notification_recipient.channel, "target": notification_recipient.target, + "content_type": ( + f"{notification_recipient.content_type.app_label}.{notification_recipient.content_type.model}" + if notification_recipient.content_type_id + else None + ), + "object_id": notification_recipient.object_id, }, "notification": { "id": str(notification.id), @@ -49,10 +62,7 @@ def template_context(notification_recipient: NotificationRecipient) -> dict: "description": notification.description, "data": notification.data, }, - "user": { - "id": user.pk, - "username": getattr(user, username_field, ""), - }, + "user": user_context, } diff --git a/notify/delivery/providers/__init__.py b/notify/delivery/providers/__init__.py index e37dd45..1739cd1 100644 --- a/notify/delivery/providers/__init__.py +++ b/notify/delivery/providers/__init__.py @@ -1,6 +1,7 @@ from notify.delivery.registry import register from .browser import BrowserDeliveryProvider from .email import EmailDeliveryProvider +from .exolve import ExolveDeliveryProvider from .max import MaxDeliveryProvider from .telegram import TelegramDeliveryProvider @@ -8,6 +9,7 @@ __all__ = [ 'register_builtin_providers', 'BrowserDeliveryProvider', 'EmailDeliveryProvider', + 'ExolveDeliveryProvider', 'MaxDeliveryProvider', 'TelegramDeliveryProvider', ] @@ -17,6 +19,7 @@ def register_builtin_providers() -> None: for provider in ( BrowserDeliveryProvider(), EmailDeliveryProvider(), + ExolveDeliveryProvider(), MaxDeliveryProvider(), TelegramDeliveryProvider(), ): diff --git a/notify/delivery/providers/exolve.py b/notify/delivery/providers/exolve.py new file mode 100644 index 0000000..03408bf --- /dev/null +++ b/notify/delivery/providers/exolve.py @@ -0,0 +1,102 @@ +import re +from html import unescape +from typing import Optional + +import requests +from django.utils.html import strip_tags +from pydantic import BaseModel, field_validator + +from notify.delivery.base import DeliveryProvider, render_notification_template +from notify.delivery.exceptions import DeliveryError, PermanentDeliveryError +from notify.models import DeliveryChannel, DeliveryTokenConfig, NotificationRecipient + +__all__ = [ + "EXOLVE_API_TIMEOUT", + "EXOLVE_SMS_URL", + "ExolveTargetSchema", + "ExolveDeliveryProvider", +] + +EXOLVE_API_TIMEOUT = 10 +EXOLVE_SMS_URL = "https://api.exolve.ru/messaging/v1/SendSMS" + + +def _plain_text(value: str | None) -> str: + return unescape(strip_tags(value or "")).strip() + + +def normalize_phone(value: str) -> str: + digits = re.sub(r"\D", "", value or "") + if len(digits) == 11 and digits.startswith("8"): + digits = "7" + digits[1:] + if not digits.isdigit() or not 10 <= len(digits) <= 15: + raise ValueError("phone must contain 10 to 15 digits") + return digits + + +class ExolveTargetSchema(BaseModel): + phone: str + + @field_validator("phone") + @classmethod + def validate_phone(cls, value: str) -> str: + return normalize_phone(value) + + +class ExolveDeliveryProvider(DeliveryProvider): + channel = DeliveryChannel.SMS + target_schema = ExolveTargetSchema + supports_codes = True + + def target_key(self, target: ExolveTargetSchema) -> str: + return target.phone + + def send(self, recipient: NotificationRecipient) -> None: + subject, body = render_notification_template(DeliveryChannel.SMS, recipient) + text = _plain_text(body) + subject = _plain_text(subject) + if subject and subject not in text: + text = f"{subject}\n{text}".strip() + self.send_message(self.parse_target(recipient.target), "", text) + self.mark_sent(recipient) + + def send_message( + self, + target: Optional[ExolveTargetSchema], + subject: str, + body: str, + attachments=(), + ) -> None: + delivery_config = DeliveryTokenConfig.get_default(DeliveryChannel.SMS) + if delivery_config is None: + raise DeliveryError("No default SMS delivery config") + if not delivery_config.sender: + raise DeliveryError("SMS delivery config has no sender") + if target is None: + raise PermanentDeliveryError("SMS recipient has no phone") + + text = _plain_text(body) or _plain_text(subject) + if not text: + raise PermanentDeliveryError("SMS message is empty") + + try: + response = requests.post( + EXOLVE_SMS_URL, + headers={"Authorization": f"Bearer {delivery_config.token}"}, + json={ + "number": delivery_config.sender, + "destination": target.phone, + "text": text, + }, + timeout=EXOLVE_API_TIMEOUT, + ) + response.raise_for_status() + except requests.Timeout as exc: + raise DeliveryError("Exolve request timed out") from exc + except requests.HTTPError as exc: + status = exc.response.status_code if exc.response is not None else 0 + if status == 429 or status >= 500: + raise DeliveryError(f"Exolve API temporary error: {status}") from exc + raise PermanentDeliveryError(f"Exolve API rejected the message: {status}") from exc + except requests.RequestException as exc: + raise DeliveryError("Exolve request failed") from exc diff --git a/notify/migrations/0001_initial.py b/notify/migrations/0001_initial.py index b1c86b9..29890b4 100644 --- a/notify/migrations/0001_initial.py +++ b/notify/migrations/0001_initial.py @@ -1,4 +1,4 @@ -# Generated by Django 5.0.6 on 2026-10-11 12:17 +# Generated by Django 5.0.6 on 2026-10-12 00:51 import django.db.models.deletion import notify.fields @@ -23,7 +23,7 @@ class Migration(migrations.Migration): fields=[ ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)), ('name', models.CharField(max_length=255, unique=True)), - ('channel', models.CharField(choices=[('email', 'Email'), ('telegram', 'Telegram'), ('browser', 'Browser'), ('max', 'Max')], max_length=20)), + ('channel', models.CharField(choices=[('email', 'Email'), ('telegram', 'Telegram'), ('browser', 'Browser'), ('max', 'Max'), ('sms', 'SMS')], max_length=20)), ('is_default', models.BooleanField(default=False)), ], ), @@ -63,7 +63,7 @@ class Migration(migrations.Migration): name='NotificationChannelPreference', fields=[ ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)), - ('channel', models.CharField(choices=[('email', 'Email'), ('telegram', 'Telegram'), ('browser', 'Browser'), ('max', 'Max')], max_length=20)), + ('channel', models.CharField(choices=[('email', 'Email'), ('telegram', 'Telegram'), ('browser', 'Browser'), ('max', 'Max'), ('sms', 'SMS')], max_length=20)), ('is_enabled', models.BooleanField(default=True)), ], ), @@ -82,7 +82,8 @@ class Migration(migrations.Migration): name='NotificationRecipient', fields=[ ('id', models.BigAutoField(primary_key=True, serialize=False)), - ('channel', models.CharField(choices=[('email', 'Email'), ('telegram', 'Telegram'), ('browser', 'Browser'), ('max', 'Max')], max_length=20)), + ('object_id', models.CharField(blank=True, default='', max_length=255)), + ('channel', models.CharField(choices=[('email', 'Email'), ('telegram', 'Telegram'), ('browser', 'Browser'), ('max', 'Max'), ('sms', 'SMS')], max_length=20)), ('target', models.JSONField(blank=True, default=None, null=True)), ('status', models.CharField(choices=[('unsent', 'Unsent'), ('sent', 'Sent'), ('failed', 'Failed')], default='unsent', max_length=10)), ('sent_at', models.DateTimeField(blank=True, null=True)), @@ -96,7 +97,7 @@ class Migration(migrations.Migration): name='NotificationTemplate', fields=[ ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)), - ('channel', models.CharField(choices=[('email', 'Email'), ('telegram', 'Telegram'), ('browser', 'Browser'), ('max', 'Max')], max_length=20)), + ('channel', models.CharField(choices=[('email', 'Email'), ('telegram', 'Telegram'), ('browser', 'Browser'), ('max', 'Max'), ('sms', 'SMS')], max_length=20)), ('name', models.CharField(max_length=255, unique=True)), ('is_default', models.BooleanField(default=False)), ('subject', models.TextField(blank=True, default='')), @@ -125,7 +126,7 @@ class Migration(migrations.Migration): fields=[ ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)), ('purpose', models.CharField(max_length=100)), - ('channel', models.CharField(choices=[('email', 'Email'), ('telegram', 'Telegram'), ('browser', 'Browser'), ('max', 'Max')], max_length=20)), + ('channel', models.CharField(choices=[('email', 'Email'), ('telegram', 'Telegram'), ('browser', 'Browser'), ('max', 'Max'), ('sms', 'SMS')], max_length=20)), ('target_key', models.CharField(max_length=255)), ('target', models.JSONField(blank=True, default=None, null=True)), ('code_hash', models.CharField(max_length=128)), @@ -159,6 +160,7 @@ class Migration(migrations.Migration): fields=[ ('deliveryconfig_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='notify.deliveryconfig')), ('token', notify.fields.EncryptedSecretField(blank=True, max_length=500)), + ('sender', models.CharField(blank=True, default='', max_length=32)), ], bases=('notify.deliveryconfig',), ), @@ -181,6 +183,11 @@ class Migration(migrations.Migration): name='user', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='notification_channel_preferences', to=settings.AUTH_USER_MODEL), ), + migrations.AddField( + model_name='notificationrecipient', + name='content_type', + field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='contenttypes.contenttype'), + ), migrations.AddField( model_name='notificationrecipient', name='notification', @@ -189,7 +196,7 @@ class Migration(migrations.Migration): migrations.AddField( model_name='notificationrecipient', name='user', - field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='notification_recipients', to=settings.AUTH_USER_MODEL), + field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='notification_recipients', to=settings.AUTH_USER_MODEL), ), migrations.AddField( model_name='notificationtype', diff --git a/notify/models/choices.py b/notify/models/choices.py index e5dc139..48c7f4f 100644 --- a/notify/models/choices.py +++ b/notify/models/choices.py @@ -14,6 +14,7 @@ class DeliveryChannel(models.TextChoices): TELEGRAM = "telegram" BROWSER = "browser" MAX = "max" + SMS = "sms", "SMS" class DeliveryStatus(models.TextChoices): diff --git a/notify/models/delivery.py b/notify/models/delivery.py index b50848a..cb6f0f4 100644 --- a/notify/models/delivery.py +++ b/notify/models/delivery.py @@ -87,6 +87,7 @@ class DeliveryEmailConfig(DeliveryConfig): class DeliveryTokenConfig(DeliveryConfig): token = EncryptedSecretField(max_length=500, blank=True) + sender = models.CharField(max_length=32, blank=True, default="") @classmethod def get_default(cls, channel): diff --git a/notify/models/notification.py b/notify/models/notification.py index dc8fc61..422d2f4 100644 --- a/notify/models/notification.py +++ b/notify/models/notification.py @@ -78,9 +78,14 @@ class NotificationRecipient(models.Model): notification = models.ForeignKey(Notification, on_delete=models.CASCADE, related_name="recipients") user = models.ForeignKey( settings.AUTH_USER_MODEL, + null=True, + blank=True, on_delete=models.CASCADE, related_name="notification_recipients", ) + content_type = models.ForeignKey(ContentType, null=True, blank=True, on_delete=models.SET_NULL) + object_id = models.CharField(max_length=255, blank=True, default="") + content_object = GenericForeignKey("content_type", "object_id") channel = models.CharField(max_length=20, choices=DeliveryChannel.choices) target = models.JSONField(null=True, blank=True, default=None) status = models.CharField(max_length=10, choices=DeliveryStatus.choices, default=DeliveryStatus.UNSENT) diff --git a/notify/services.py b/notify/services.py index 685e1ec..b41f4c4 100644 --- a/notify/services.py +++ b/notify/services.py @@ -35,7 +35,7 @@ def _existing_idempotent(idempotency_key): def _allowed_channels(notification_type, user, channels): - if notification_type is None or not notification_type.is_configurable: + if notification_type is None or not notification_type.is_configurable or user is None: return channels allowed = set(notification_type.channels) prefs = { @@ -100,7 +100,11 @@ def _collapse_grouped(notification_type, recipients, content_type, object_id, ti grouped = [] seen = set() for recipient_data in recipients: - found = _grouped_notification(notification_type, recipient_data["user"], content_type, object_id) + user = recipient_data.get("user") + if user is None: + pending.append(recipient_data) + continue + found = _grouped_notification(notification_type, user, content_type, object_id) if found is None: pending.append(recipient_data) continue @@ -120,27 +124,34 @@ def _attach_recipients(notification, recipients, notification_type): channels = recipient_data.get("channels") or [] if not channels: raise ValueError("Recipient has no channels") - user = recipient_data["user"] + user = recipient_data.get("user") + content_type, object_id = _content_link(recipient_data.get("content_object")) channels = _allowed_channels(notification_type, user, channels) for channel_data in channels: channel = channel_data["channel"] + if channel == DeliveryChannel.BROWSER and user is None: + raise ValueError("browser requires a user") if allowed_channels is not None and channel not in allowed_channels: raise ValueError( f"Channel {channel} is not allowed for notification type {notification_type.code}" ) - identity = (user.pk, channel) - if identity in seen: - raise ValueError(f"Duplicate recipient for user {user.pk} and channel {channel}") - seen.add(identity) provider = get_provider(channel) if provider is None: raise ValueError(f"No delivery provider registered for channel: {channel}") target = provider.validate_target(channel_data.get("target")) + raw_target = target.model_dump() if target is not None else None + if user is not None: + identity = (user.pk, channel) + if identity in seen: + raise ValueError(f"Duplicate recipient for user {user.pk} and channel {channel}") + seen.add(identity) NotificationRecipient.objects.create( notification=notification, user=user, + content_type=content_type, + object_id=object_id, channel=channel, - target=target.model_dump() if target is not None else None, + target=raw_target, ) created += 1 if created == 0: diff --git a/pyproject.toml b/pyproject.toml index c37b63f..3217000 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "notify" -version = "0.4.0" +version = "0.5.0" description = "Django app for user notifications" readme = "Readme.md" requires-python = ">=3.10" diff --git a/tests/test_admin.py b/tests/test_admin.py index be52c78..7c1e08d 100644 --- a/tests/test_admin.py +++ b/tests/test_admin.py @@ -96,7 +96,19 @@ class EmailAdminTests(TestCase): html = DeliveryTokenConfigForm(instance=config).as_p() self.assertNotIn("max-token-value", html) channel_values = [choice[0] for choice in DeliveryTokenConfigForm().fields["channel"].choices] - self.assertEqual(channel_values, [DeliveryChannel.TELEGRAM, DeliveryChannel.MAX]) + self.assertEqual(channel_values, [DeliveryChannel.TELEGRAM, DeliveryChannel.MAX, DeliveryChannel.SMS]) + + def test_sms_sender_is_required(self): + missing = DeliveryTokenConfigForm( + data={"name": "sms", "channel": DeliveryChannel.SMS, "token": "key", "sender": ""}, + ) + self.assertFalse(missing.is_valid()) + self.assertIn("sender", missing.errors) + + present = DeliveryTokenConfigForm( + data={"name": "sms", "channel": DeliveryChannel.SMS, "token": "key", "sender": "MTS"}, + ) + self.assertTrue(present.is_valid(), present.errors) def test_empty_token_keeps_the_stored_value_and_a_new_one_replaces_it(self): config = DeliveryTokenConfig.objects.create( diff --git a/tests/test_codes.py b/tests/test_codes.py index d96fff4..ff41a22 100644 --- a/tests/test_codes.py +++ b/tests/test_codes.py @@ -53,6 +53,13 @@ class CodeTests(TestCase): DeliveryTokenConfig.objects.create( name="max", channel=DeliveryChannel.MAX, is_default=True, token="max-token" ) + DeliveryTokenConfig.objects.create( + name="sms", + channel=DeliveryChannel.SMS, + is_default=True, + token="sms-token", + sender="MTS", + ) def _send_email(self, **kwargs): kwargs.setdefault("purpose", "login") @@ -83,6 +90,19 @@ class CodeTests(TestCase): self.assertEqual(post.call_args.kwargs["json"]["chat_id"], 42) self.assertTrue(verify_code(purpose="login", channel="telegram", target={"chat_id": 42}, code=code)) + def test_sms_send_and_verify(self): + post, code = self._send_messenger(DeliveryChannel.SMS, {"phone": "8 (999) 123-45-67"}) + self.assertEqual(post.call_args.args[0], "https://api.exolve.ru/messaging/v1/SendSMS") + self.assertEqual(post.call_args.kwargs["headers"]["Authorization"], "Bearer sms-token") + self.assertEqual(post.call_args.kwargs["json"]["number"], "MTS") + self.assertEqual(post.call_args.kwargs["json"]["destination"], "79991234567") + self.assertIn(code, post.call_args.kwargs["json"]["text"]) + verification = VerificationCode.objects.get() + self.assertEqual(verification.target_key, "79991234567") + self.assertTrue( + verify_code(purpose="login", channel="sms", target={"phone": "+7 999 123-45-67"}, code=code) + ) + def test_max_send_and_verify(self): target = {"chat_id": 5, "user_id": 7} post, code = self._send_messenger(DeliveryChannel.MAX, target) diff --git a/tests/test_delivery.py b/tests/test_delivery.py index b5f744a..b488ac5 100644 --- a/tests/test_delivery.py +++ b/tests/test_delivery.py @@ -10,6 +10,7 @@ from django.test import TestCase from django.utils import timezone from notify.delivery import get_provider, get_provider_or_raise, registered_channels +from notify.delivery.providers.exolve import EXOLVE_API_TIMEOUT, EXOLVE_SMS_URL from notify.delivery.providers.max import MAX_API_TIMEOUT from notify.delivery.providers.telegram import TELEGRAM_API_TIMEOUT from notify.models import ( @@ -175,7 +176,7 @@ class DeliveryTests(TestCase): create_notification( title="Ping", recipients=[ - {"user": self.user, "channels": [{"channel": "sms"}]}, + {"user": self.user, "channels": [{"channel": "push"}]}, ], ) self.assertEqual(Notification.objects.count(), 0) @@ -351,9 +352,10 @@ class DeliveryTests(TestCase): self.assertIsNotNone(get_provider(DeliveryChannel.BROWSER)) self.assertIsNotNone(get_provider(DeliveryChannel.MAX)) self.assertIsNotNone(get_provider(DeliveryChannel.TELEGRAM)) - self.assertIsNone(get_provider("sms")) - with self.assertRaisesMessage(KeyError, "sms"): - get_provider_or_raise("sms") + self.assertIsNotNone(get_provider(DeliveryChannel.SMS)) + self.assertIsNone(get_provider("push")) + with self.assertRaisesMessage(KeyError, "push"): + get_provider_or_raise("push") self.assertCountEqual( list(registered_channels()), [ @@ -361,6 +363,7 @@ class DeliveryTests(TestCase): DeliveryChannel.BROWSER, DeliveryChannel.MAX, DeliveryChannel.TELEGRAM, + DeliveryChannel.SMS, ], ) @@ -382,7 +385,7 @@ class DeliveryTests(TestCase): recipient = NotificationRecipient.objects.create( notification=notification, user=self.user, - channel="sms", + channel="push", ) deliver_notification.apply(args=[str(recipient.id)], throw=True) recipient.refresh_from_db() @@ -620,6 +623,216 @@ class DeliveryTests(TestCase): self.assertEqual(recipient.status, DeliveryStatus.FAILED) self.assertEqual(recipient.attempts, 6) + def test_email_without_user_is_sent(self): + patient = NotificationGroup.objects.create(code="patient", name="Patient") + NotificationTemplate.objects.create( + channel=DeliveryChannel.EMAIL, + name="external", + is_default=True, + subject="{{ recipient.content_type }}", + body="{% if user %}user{% else %}guest{% endif %} {{ recipient.object_id }}", + ) + notification = create_notification( + title="Hello", + description="Body", + recipients=[ + { + "content_object": patient, + "channels": [{"channel": DeliveryChannel.EMAIL, "target": {"email": "guest@example.com"}}], + } + ], + ) + recipient = notification.recipients.get() + self.assertIsNone(recipient.user_id) + deliver_notification.apply(args=[str(recipient.id)], throw=True) + self.assertEqual(mail.outbox[0].to, ["guest@example.com"]) + self.assertEqual(mail.outbox[0].subject, "notify.notificationgroup") + self.assertIn("guest", mail.outbox[0].body) + self.assertIn(str(patient.pk), mail.outbox[0].body) + recipient.refresh_from_db() + self.assertEqual(recipient.status, DeliveryStatus.SENT) + + def test_sms_without_user_is_sent(self): + DeliveryTokenConfig.objects.create( + name="sms", + channel=DeliveryChannel.SMS, + is_default=True, + token="sms-token", + sender="MTS", + ) + notification = create_notification( + title="Hello", + description="Body", + recipients=[ + {"channels": [{"channel": DeliveryChannel.SMS, "target": {"phone": "79991234567"}}]}, + ], + ) + recipient = notification.recipients.get() + response = requests.Response() + response.status_code = 200 + with patch("notify.delivery.providers.exolve.requests.post", return_value=response) as post: + deliver_notification.apply(args=[str(recipient.id)], throw=True) + self.assertEqual(post.call_args.kwargs["json"]["destination"], "79991234567") + self.assertEqual(post.call_args.kwargs["json"]["number"], "MTS") + recipient.refresh_from_db() + self.assertEqual(recipient.status, DeliveryStatus.SENT) + + def test_max_without_user_is_sent(self): + DeliveryTokenConfig.objects.create( + name="max", + channel=DeliveryChannel.MAX, + is_default=True, + token="token", + ) + notification = create_notification( + title="Hello", + description="Body", + recipients=[ + {"channels": [{"channel": DeliveryChannel.MAX, "target": {"chat_id": -5}}]}, + ], + ) + recipient = notification.recipients.get() + response = requests.Response() + response.status_code = 200 + with patch("notify.delivery.providers.max.requests.post", return_value=response) as post: + deliver_notification.apply(args=[str(recipient.id)], throw=True) + self.assertEqual(post.call_args.kwargs["params"], {"chat_id": -5}) + recipient.refresh_from_db() + self.assertEqual(recipient.status, DeliveryStatus.SENT) + + def test_sms_message_is_sent_and_marked(self): + DeliveryTokenConfig.objects.create( + name="sms", + channel=DeliveryChannel.SMS, + is_default=True, + token="sms-token", + sender="MTS", + ) + notification = create_notification( + title="Hello", + description="Body", + recipients=[ + { + "user": self.user, + "channels": [{"channel": DeliveryChannel.SMS, "target": {"phone": "+7 (999) 123-45-67"}}], + } + ], + ) + recipient = notification.recipients.get() + self.assertEqual(recipient.target, {"phone": "79991234567"}) + response = requests.Response() + response.status_code = 200 + with patch("notify.delivery.providers.exolve.requests.post", return_value=response) as post: + deliver_notification.apply(args=[str(recipient.id)], throw=True) + self.assertEqual(post.call_count, 1) + self.assertEqual(post.call_args.args[0], EXOLVE_SMS_URL) + self.assertEqual(post.call_args.kwargs["headers"]["Authorization"], "Bearer sms-token") + self.assertEqual(post.call_args.kwargs["timeout"], EXOLVE_API_TIMEOUT) + self.assertEqual( + post.call_args.kwargs["json"], + {"number": "MTS", "destination": "79991234567", "text": "Hello\nBody"}, + ) + recipient.refresh_from_db() + self.assertEqual(recipient.status, DeliveryStatus.SENT) + self.assertEqual(recipient.attempts, 1) + + def test_sms_requires_target(self): + with self.assertRaisesMessage(ValueError, "target is required"): + create_notification( + title="Hi", + recipients=[ + {"user": self.user, "channels": [{"channel": DeliveryChannel.SMS}]}, + ], + ) + self.assertEqual(Notification.objects.count(), 0) + + def test_sms_rejects_a_short_phone(self): + with self.assertRaisesMessage(ValueError, "10 to 15 digits"): + create_notification( + title="Hi", + recipients=[ + {"user": self.user, "channels": [{"channel": DeliveryChannel.SMS, "target": {"phone": "123"}}]}, + ], + ) + self.assertEqual(Notification.objects.count(), 0) + + def test_sms_client_error_is_not_retried(self): + DeliveryTokenConfig.objects.create( + name="sms", + channel=DeliveryChannel.SMS, + is_default=True, + token="sms-token", + sender="MTS", + ) + notification = Notification.objects.create(title="Hello", description="Body") + recipient = NotificationRecipient.objects.create( + notification=notification, + user=self.user, + channel=DeliveryChannel.SMS, + target={"phone": "79991234567"}, + ) + response = requests.Response() + response.status_code = 400 + error = requests.HTTPError("bad request") + error.response = response + with patch("notify.delivery.providers.exolve.requests.post") as post: + post.return_value.raise_for_status.side_effect = error + deliver_notification.apply(args=[str(recipient.id)], throw=True) + self.assertEqual(post.call_count, 1) + recipient.refresh_from_db() + self.assertEqual(recipient.status, DeliveryStatus.FAILED) + self.assertEqual(recipient.attempts, 1) + self.assertIn("400", recipient.last_error) + + def test_sms_timeout_is_retried(self): + DeliveryTokenConfig.objects.create( + name="sms", + channel=DeliveryChannel.SMS, + is_default=True, + token="sms-token", + sender="MTS", + ) + notification = Notification.objects.create(title="Hello", description="Body") + recipient = NotificationRecipient.objects.create( + notification=notification, + user=self.user, + channel=DeliveryChannel.SMS, + target={"phone": "79991234567"}, + ) + with patch( + "notify.delivery.providers.exolve.requests.post", + side_effect=requests.Timeout(), + ) as post: + result = deliver_notification.apply(args=[str(recipient.id)], throw=False) + self.assertEqual(result.state, "FAILURE") + self.assertEqual(post.call_count, 6) + recipient.refresh_from_db() + self.assertEqual(recipient.status, DeliveryStatus.FAILED) + self.assertEqual(recipient.attempts, 6) + + def test_sms_without_sender_is_retried(self): + DeliveryTokenConfig.objects.create( + name="sms", + channel=DeliveryChannel.SMS, + is_default=True, + token="sms-token", + ) + notification = Notification.objects.create(title="Hello", description="Body") + recipient = NotificationRecipient.objects.create( + notification=notification, + user=self.user, + channel=DeliveryChannel.SMS, + target={"phone": "79991234567"}, + ) + with patch("notify.delivery.providers.exolve.requests.post") as post: + result = deliver_notification.apply(args=[str(recipient.id)], throw=False) + post.assert_not_called() + self.assertEqual(result.state, "FAILURE") + recipient.refresh_from_db() + self.assertEqual(recipient.status, DeliveryStatus.FAILED) + self.assertEqual(recipient.attempts, 6) + self.assertIn("sender", recipient.last_error) + def test_markdown_filter_renders_fenced_code(self): rendered = render("{{ text | markdown }}", {"text": "```\nprint(1)\n```"}) self.assertIn("", rendered) diff --git a/tests/test_models.py b/tests/test_models.py index e730795..4599ca6 100644 --- a/tests/test_models.py +++ b/tests/test_models.py @@ -29,15 +29,15 @@ class ModelTests(TestCase): self.user = User.objects.create_user("alice", "alice@example.com", "pass") def test_channel_validator(self): - validate_delivery_channels(["email", "browser"]) + validate_delivery_channels(["email", "browser", "sms"]) with self.assertRaises(ValidationError): validate_delivery_channels("email") with self.assertRaises(ValidationError): - validate_delivery_channels(["sms"]) + validate_delivery_channels(["push"]) def test_type_rejects_unknown_channels(self): group = NotificationGroup.objects.create(code="g", name="G") - kind = NotificationType(code="t", name="T", group=group, channels=["sms"]) + kind = NotificationType(code="t", name="T", group=group, channels=["push"]) with self.assertRaises(ValidationError): kind.full_clean() diff --git a/tests/test_services.py b/tests/test_services.py index fa0d1c8..64eb26d 100644 --- a/tests/test_services.py +++ b/tests/test_services.py @@ -202,7 +202,8 @@ class CreateNotificationTests(TestCase): } ], ) - self.assertEqual(notification.recipients.get().target, {"email": "alice@example.com"}) + recipient = notification.recipients.get() + self.assertEqual(recipient.target, {"email": "alice@example.com"}) def test_browser_rejects_target(self): with self.assertRaisesMessage(ValueError, "target is not supported"): @@ -295,6 +296,101 @@ class CreateNotificationTests(TestCase): self.assertEqual(Notification.objects.count(), 0) +class ExternalRecipientTests(TestCase): + def test_address_only_recipient_has_no_user(self): + notification = create_notification( + title="Код", + recipients=[ + {"channels": [{"channel": DeliveryChannel.SMS, "target": {"phone": "+79991234567"}}]}, + ], + ) + recipient = notification.recipients.get() + self.assertIsNone(recipient.user_id) + self.assertIsNone(recipient.content_type) + self.assertEqual(recipient.target, {"phone": "79991234567"}) + + def test_content_object_is_stored_separately_from_the_notification_subject(self): + subject = User.objects.create_user("alice", "alice@example.com", "pass") + patient = NotificationGroup.objects.create(code="patient", name="Patient") + notification = create_notification( + title="Запись", + content_object=subject, + recipients=[ + { + "content_object": patient, + "channels": [ + {"channel": DeliveryChannel.SMS, "target": {"phone": "8 (999) 123-45-67"}}, + {"channel": DeliveryChannel.EMAIL, "target": {"email": "patient@example.com"}}, + {"channel": DeliveryChannel.MAX, "target": {"chat_id": -5}}, + ], + } + ], + ) + self.assertEqual(notification.content_object, subject) + rows = {row.channel: row for row in notification.recipients.all()} + self.assertEqual( + set(rows), + {DeliveryChannel.SMS, DeliveryChannel.EMAIL, DeliveryChannel.MAX}, + ) + for row in rows.values(): + self.assertIsNone(row.user_id) + self.assertEqual(row.content_object, patient) + self.assertEqual(rows[DeliveryChannel.SMS].target, {"phone": "79991234567"}) + + def test_browser_without_user_does_not_create_a_notification(self): + with self.assertRaisesMessage(ValueError, "browser requires a user"): + create_notification( + title="Hi", + recipients=[{"channels": [{"channel": DeliveryChannel.BROWSER}]}], + ) + self.assertEqual(Notification.objects.count(), 0) + + def test_same_phone_without_a_user_is_not_a_duplicate(self): + notification = create_notification( + title="Ping", + recipients=[ + {"channels": [{"channel": DeliveryChannel.SMS, "target": {"phone": "79991234567"}}]}, + {"channels": [{"channel": DeliveryChannel.SMS, "target": {"phone": "8 999 123-45-67"}}]}, + ], + ) + self.assertEqual(notification.recipients.count(), 2) + + def test_unsaved_content_object_rolls_back(self): + patient = User(username="ghost") + with self.assertRaisesMessage(ValueError, "must be saved"): + create_notification( + title="Hi", + recipients=[ + { + "content_object": patient, + "channels": [{"channel": DeliveryChannel.SMS, "target": {"phone": "79991234567"}}], + } + ], + ) + self.assertEqual(Notification.objects.count(), 0) + + def test_group_does_not_collapse_a_recipient_without_a_user(self): + subject = NotificationGroup.objects.create(code="visit", name="Visit") + first = create_notification( + title="Hello", + content_object=subject, + group=True, + recipients=[ + {"channels": [{"channel": DeliveryChannel.SMS, "target": {"phone": "79991234567"}}]}, + ], + ) + second = create_notification( + title="Hello again", + content_object=subject, + group=True, + recipients=[ + {"channels": [{"channel": DeliveryChannel.SMS, "target": {"phone": "79991234567"}}]}, + ], + ) + self.assertNotEqual(first.pk, second.pk) + self.assertEqual(Notification.objects.count(), 2) + + class DeliveryEnqueueTests(TestCase): def setUp(self): self.user = User.objects.create_user("alice", "alice@example.com", "pass") @@ -471,6 +567,18 @@ class ChannelPreferenceTests(TestCase): ) self.assertEqual(notification.recipients.get().channel, DeliveryChannel.EMAIL) + def test_external_recipient_ignores_channel_preferences(self): + self.kind.channels = [DeliveryChannel.EMAIL, DeliveryChannel.SMS] + self.kind.is_enabled_by_default = False + self.kind.save(update_fields=["channels", "is_enabled_by_default"]) + notification = create_notification( + notification_type=self.kind, + recipients=[ + {"channels": [{"channel": DeliveryChannel.SMS, "target": {"phone": "79991234567"}}]}, + ], + ) + self.assertEqual(notification.recipients.get().channel, DeliveryChannel.SMS) + def test_locked_type_ignores_a_disabled_preference(self): self.kind.is_configurable = False self.kind.save(update_fields=["is_configurable"])