Release 0.4 with clearer field names and a generic object link.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
Ilya Mukhortov 2026-10-11 22:17:39 +10:00
parent 9ba745eef3
commit bd765818e9
30 changed files with 545 additions and 452 deletions

View File

@ -39,7 +39,7 @@ from django.core.files.base import ContentFile
from notify.services import create_notification from notify.services import create_notification
create_notification( create_notification(
verb="Заявка одобрена", title="Заявка одобрена",
attachments=[ContentFile(b"...", name="report.pdf")], attachments=[ContentFile(b"...", name="report.pdf")],
recipients=[ recipients=[
{ {
@ -55,9 +55,9 @@ create_notification(
`create_notification` выбрасывает `ValueError`, если тип выключен, канал не входит в тип, канал неизвестен или получатель продублирован. Неактивный тип и пропущенный канал не оставляют пустое уведомление в базе. `create_notification` выбрасывает `ValueError`, если тип выключен, канал не входит в тип, канал неизвестен или получатель продублирован. Неактивный тип и пропущенный канал не оставляют пустое уведомление в базе.
Получатель канала задаётся словарём `target`, который проверяется pydantic-схемой провайдера: `email` — `{"email": ...}`, `telegram` — `{"chat_id": ...}`, `max` — `{"chat_id": ..., "user_id": ...}` (`user_id` необязателен). У `browser` `target` нет. В базе он хранится в `NotificationRecipient.delivery_target`. Если у типа `configurable=True`, канал с `NotificationChannelPreference.enabled=False` не создаётся. Строки предпочтения нет — канал берёт `NotificationType.enabled_by_default` (по умолчанию включён). `configurable=False` не смотрит ни на предпочтения, ни на этот флаг. Если после фильтра не осталось получателей, уведомление откатывается. Получатель канала задаётся словарём `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` не смотрит ни на предпочтения, ни на этот флаг. Если после фильтра не осталось получателей, уведомление откатывается.
Повтор с тем же `idempotency_key` возвращает уже созданную строку и не добавляет новые файлы. `group=True` при непустом `object_id` увеличивает `data["count"]` у непрочитанного browser-уведомления того же типа и объекта и не создаёт новую строку. Файлы такого вызова копируются и на схлопнутое уведомление, и на новое, если часть получателей не схлопнулась. Повтор с тем же `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 остаются текстом.
@ -65,7 +65,7 @@ create_notification(
Каналы `email`, `max` и `telegram` ставятся в Celery-задачу `notify.tasks.deliver_notification` после коммита транзакции. Канал `browser` помечается отправленным сразу и попадает в API. Каналы `email`, `max` и `telegram` ставятся в 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`. Воркер берёт строку получателя с блокировкой. Ошибка SMTP или временная ошибка HTTP повторяется до 5 раз с паузами 1, 2, 4, 8 и 16 минут (плюс до 10% случайной добавки). Таймаут SMTP и HTTP — 10 секунд. Каждая попытка увеличивает `attempts` и пишет `last_error`. Постоянная ошибка и исчерпание попыток ставят статус `failed`. Успех ставит `sent` и `sent_at`.
Нужен брокер Celery и автообнаружение задач установленного приложения `notify`. Расписание удаления просроченных уведомлений (раз в час): Нужен брокер Celery и автообнаружение задач установленного приложения `notify`. Расписание удаления просроченных уведомлений (раз в час):
@ -104,7 +104,7 @@ verify_code(purpose="login", channel="email", target={"email": user.email}, code
В базе лежит только HMAC от `SECRET_KEY` и id строки. Смена `SECRET_KEY` делает выданные коды недействительными. Сам код не пишется в базу, логи и тексты исключений. В базе лежит только HMAC от `SECRET_KEY` и id строки. Смена `SECRET_KEY` делает выданные коды недействительными. Сам код не пишется в базу, логи и тексты исключений.
Текст по умолчанию: «Код подтверждения: 123456. Действует 5 мин.». Чтобы задать свой, передайте `type=` (код или объект `NotificationType`) и создайте `NotificationTemplate` с этим типом и каналом. Контекст шаблона: `code`, `ttl_minutes`, `purpose`, `user.id`, `user.username` (`user` равен `None`, если пользователь не передан). Шаблон канала по умолчанию для кодов не используется. Текст по умолчанию: «Код подтверждения: 123456. Действует 5 мин.». Чтобы задать свой, передайте `notification_type=` (код или объект `NotificationType`) и создайте `NotificationTemplate` с этим типом и каналом. Контекст шаблона: `code`, `ttl_minutes`, `purpose`, `user.id`, `user.username` (`user` равен `None`, если пользователь не передан). Шаблон канала по умолчанию для кодов не используется.
Настройки: Настройки:
@ -133,13 +133,13 @@ NOTIFY_CODE_RESEND_INTERVAL = 60 # секунд, 0 — без ограниче
Просроченные уведомления в эти выборки не входят. Некорректный id возвращает 404. Просроченные уведомления в эти выборки не входят. Некорректный id возвращает 404.
`GET list/` отдаёт `attachments`: `id`, `name`, `size`, `content_type`, `url`. `GET attachments/{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 preferences/` отдаёт список активных типов с `configurable=True`: `code`, `name`, `group_name` и `channels` (`channel`, `enabled`). Нет сохранённого предпочтения — `enabled` равен `enabled_by_default` типа. Сохранённое предпочтение перекрывает флаг. `POST preferences/` принимает `{"items": [{"code", "channels": [{"channel", "enabled"}]}]}` и возвращает `{"ok": true}`. Неизвестный канал и тип с `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` ничего не меняет.
API не кэширует ответы и не требует кэша или Redis. 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`. Шаблоны 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`.
## Тесты ## Тесты

View File

@ -40,12 +40,12 @@
function renderItem(item) { function renderItem(item) {
const card = document.createElement("article"); const card = document.createElement("article");
card.className = "item " + (item.level || "INFO") + (item.unread ? " unread" : ""); card.className = "item " + (item.level || "info") + (item.unread ? " unread" : "");
const verb = document.createElement("div"); const title = document.createElement("div");
verb.className = "verb"; title.className = "title";
verb.textContent = item.verb || ""; title.textContent = item.title || "";
card.appendChild(verb); card.appendChild(title);
if (item.description) { if (item.description) {
const description = document.createElement("div"); const description = document.createElement("div");

View File

@ -111,9 +111,9 @@
background: #fff; background: #fff;
} }
.item.unread { background: #f7f9ff; } .item.unread { background: #f7f9ff; }
.item.SUCCESS { border-left-color: var(--success); } .item.success { border-left-color: var(--success); }
.item.WARNING { border-left-color: var(--warning); } .item.warning { border-left-color: var(--warning); }
.item.ERROR { border-left-color: var(--error); } .item.error { border-left-color: var(--error); }
.item button { justify-self: start; } .item button { justify-self: start; }
.meta { .meta {
display: flex; display: flex;
@ -121,7 +121,7 @@
color: var(--muted); color: var(--muted);
font-size: 12px; font-size: 12px;
} }
.verb { font-weight: 650; } .title { font-weight: 650; }
.files { .files {
display: flex; display: flex;
flex-wrap: wrap; flex-wrap: wrap;
@ -151,7 +151,7 @@
{% csrf_token %} {% csrf_token %}
<label> <label>
Текст Текст
<input name="verb" required maxlength="255" autocomplete="off"> <input name="title" required maxlength="255" autocomplete="off">
</label> </label>
<label> <label>
Описание Описание
@ -161,10 +161,10 @@
<label> <label>
Уровень Уровень
<select name="level"> <select name="level">
<option value="INFO">INFO</option> <option value="info">info</option>
<option value="SUCCESS">SUCCESS</option> <option value="success">success</option>
<option value="WARNING">WARNING</option> <option value="warning">warning</option>
<option value="ERROR">ERROR</option> <option value="error">error</option>
</select> </select>
</label> </label>
<label> <label>

View File

@ -16,7 +16,7 @@ def inbox(request):
@login_required @login_required
@require_POST @require_POST
def create_notification_view(request): def create_notification_view(request):
verb = (request.POST.get("verb") or "").strip() title = (request.POST.get("title") or "").strip()
description = (request.POST.get("description") or "").strip() or None description = (request.POST.get("description") or "").strip() or None
level = (request.POST.get("level") or NotificationLevel.INFO).strip() level = (request.POST.get("level") or NotificationLevel.INFO).strip()
url = (request.POST.get("url") or "").strip() or None url = (request.POST.get("url") or "").strip() or None
@ -31,7 +31,7 @@ def create_notification_view(request):
] ]
try: try:
create_notification( create_notification(
verb=verb, title=title,
description=description, description=description,
level=level, level=level,
url=url, url=url,

View File

@ -143,13 +143,13 @@ class NotificationTemplateAdmin(admin.ModelAdmin):
'id', 'id',
'name', 'name',
'channel', 'channel',
'type', 'notification_type',
'is_default', 'is_default',
) )
readonly_fields = ['id'] readonly_fields = ['id']
form = forms.modelform_factory(NotificationTemplate, fields='__all__', widgets={ form = forms.modelform_factory(NotificationTemplate, fields='__all__', widgets={
'subject_template': AceEditorWidget(mode='django', hide_label=False), 'subject': AceEditorWidget(mode='django', hide_label=False),
'body_template': AceEditorWidget(mode='django', hide_label=False), 'body': AceEditorWidget(mode='django', hide_label=False),
}) })
save_on_top = True save_on_top = True
@ -186,11 +186,11 @@ class NotificationTypeAdmin(admin.ModelAdmin):
'name', 'name',
'group', 'group',
'is_active', 'is_active',
'enabled_by_default', 'is_enabled_by_default',
) )
list_filter = ( list_filter = (
'is_active', 'is_active',
'enabled_by_default', 'is_enabled_by_default',
'group', 'group',
) )
search_fields = ( search_fields = (
@ -203,13 +203,13 @@ class NotificationTypeAdmin(admin.ModelAdmin):
class NotificationChannelPreferenceAdmin(admin.ModelAdmin): class NotificationChannelPreferenceAdmin(admin.ModelAdmin):
list_display = ( list_display = (
'user', 'user',
'type', 'notification_type',
'channel', 'channel',
'enabled', 'is_enabled',
) )
list_filter = ( list_filter = (
'channel', 'channel',
'enabled', 'is_enabled',
) )
@ -232,15 +232,15 @@ class NotificationRecipientInline(admin.TabularInline):
@admin.register(Notification) @admin.register(Notification)
class NotificationAdmin(admin.ModelAdmin): class NotificationAdmin(admin.ModelAdmin):
list_display = ( list_display = (
'verb', 'title',
'description', 'description',
'expires_at', 'expires_at',
'created_at' 'created_at'
) )
search_fields = ( search_fields = (
'id', 'id',
'type__code', 'notification_type__code',
'verb' 'title'
) )
inlines = [NotificationAttachmentInline, NotificationRecipientInline] inlines = [NotificationAttachmentInline, NotificationRecipientInline]
@ -254,13 +254,13 @@ class NotificationRecipientAdmin(admin.ModelAdmin):
'user', 'user',
'notification', 'notification',
'unread', 'unread',
'delivery_channel', 'channel',
'delivery_status', 'status',
'attempts', 'attempts',
) )
list_filter = ( list_filter = (
'delivery_channel', 'channel',
'delivery_status', 'status',
'unread' 'unread'
) )
ordering = ( ordering = (
@ -272,7 +272,7 @@ class NotificationRecipientAdmin(admin.ModelAdmin):
return ( return (
'id', 'id',
f'user__{username_field}', f'user__{username_field}',
'notification__verb', 'notification__title',
) )
def has_change_permission(self, request, obj = ...): def has_change_permission(self, request, obj = ...):

View File

@ -71,9 +71,13 @@ class DetailPath(Schema):
def _base_user_queryset(user): def _base_user_queryset(user):
return NotificationRecipient.objects.filter( return NotificationRecipient.objects.filter(
user=user, user=user,
delivery_channel=DeliveryChannel.BROWSER, channel=DeliveryChannel.BROWSER,
notification__expires_at__gte=timezone.now(), notification__expires_at__gte=timezone.now(),
).select_related("notification", "notification__type").prefetch_related("notification__attachments") ).select_related(
"notification",
"notification__notification_type",
"notification__content_type",
).prefetch_related("notification__attachments")
def _parse_pk(raw_id: str) -> int: def _parse_pk(raw_id: str) -> int:
@ -169,7 +173,7 @@ def preferences(request):
} }
types = NotificationType.objects.filter( types = NotificationType.objects.filter(
is_active=True, is_active=True,
configurable=True, is_configurable=True,
).select_related("group") ).select_related("group")
return [ return [
{ {

View File

@ -13,19 +13,31 @@ __all__ = [
class NotificationFilterSchema(FilterSchema): class NotificationFilterSchema(FilterSchema):
unread: Optional[bool] = None unread: Optional[bool] = None
type: Annotated[Optional[str], FilterLookup("notification__type__code")] = None type: Annotated[Optional[str], FilterLookup("notification__notification_type__code")] = None
type__startswith: Annotated[Optional[str], FilterLookup("notification__type__code__startswith")] = None type__startswith: Annotated[Optional[str], FilterLookup("notification__notification_type__code__startswith")] = None
content_type: Optional[str] = None
object_id: Annotated[Optional[str], FilterLookup("notification__object_id")] = None object_id: Annotated[Optional[str], FilterLookup("notification__object_id")] = None
search: Annotated[ search: Annotated[
Optional[str], Optional[str],
FilterLookup( FilterLookup(
["notification__verb__icontains", "notification__description__icontains"], ["notification__title__icontains", "notification__description__icontains"],
expression_connector="OR" expression_connector="OR"
) )
] = None ] = None
object_id__ne: Optional[List[str]] = None object_id__ne: Optional[List[str]] = None
object_id__ne__in: Optional[str] = None object_id__ne__in: Optional[str] = None
def filter_content_type(self, value: str) -> Q:
if not value:
return Q()
app_label, separator, model = value.partition(".")
if not separator or not app_label or not model:
return Q(pk__in=[])
return Q(
notification__content_type__app_label=app_label,
notification__content_type__model=model,
)
def filter_object_id__ne(self, value: List[str]) -> Q: def filter_object_id__ne(self, value: List[str]) -> Q:
return ~Q(notification__object_id__in=value) return ~Q(notification__object_id__in=value)

View File

@ -29,8 +29,9 @@ class NotificationResponseSchema(ModelSchema):
url: Optional[str] = Field(alias="notification.url") url: Optional[str] = Field(alias="notification.url")
type: Optional[str] = None type: Optional[str] = None
level: Optional[str] = Field(alias="notification.level") level: Optional[str] = Field(alias="notification.level")
verb: Optional[str] = Field(alias="notification.verb") title: Optional[str] = Field(alias="notification.title")
object_id: Optional[str] = Field(alias="notification.object_id") content_type: Optional[str] = None
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")
attachments: list[AttachmentSchema] attachments: list[AttachmentSchema]
@ -45,11 +46,18 @@ class NotificationResponseSchema(ModelSchema):
@staticmethod @staticmethod
def resolve_type(obj): def resolve_type(obj):
notification_type = obj.notification.type notification_type = obj.notification.notification_type
if notification_type is None: if notification_type is None:
return None return None
return notification_type.code return notification_type.code
@staticmethod
def resolve_content_type(obj):
content_type = obj.notification.content_type
if content_type is None:
return None
return f"{content_type.app_label}.{content_type.model}"
@staticmethod @staticmethod
def resolve_attachments(obj): def resolve_attachments(obj):
return [ return [
@ -66,7 +74,7 @@ class NotificationResponseSchema(ModelSchema):
class ChannelPreferenceChannelSchema(Schema): class ChannelPreferenceChannelSchema(Schema):
channel: str channel: str
enabled: bool is_enabled: bool
class Preference(Schema): class Preference(Schema):

View File

@ -72,7 +72,7 @@ def _render(channel, notification_type, code, ttl, purpose, user):
template = None template = None
if notification_type is not None: if notification_type is not None:
template = ( template = (
NotificationTemplate.objects.filter(channel=channel, type=notification_type) NotificationTemplate.objects.filter(channel=channel, notification_type=notification_type)
.order_by("id") .order_by("id")
.first() .first()
) )
@ -107,12 +107,12 @@ def send_code(
channel: str, channel: str,
target: dict | None = None, target: dict | None = None,
user=None, user=None,
type: NotificationType | str | None = None, notification_type: NotificationType | str | None = None,
) -> VerificationCode: ) -> VerificationCode:
if not purpose: if not purpose:
raise ValueError("purpose is required") raise ValueError("purpose is required")
provider, target, target_key = _resolve_target(channel, target) provider, target, target_key = _resolve_target(channel, target)
notification_type = _resolve_type(type) notification_type = _resolve_type(notification_type)
now = timezone.now() now = timezone.now()
ttl = _code_ttl() ttl = _code_ttl()
resend_interval = _code_resend_interval() resend_interval = _code_resend_interval()
@ -137,7 +137,7 @@ def send_code(
purpose=purpose, purpose=purpose,
channel=channel, channel=channel,
target_key=target_key, target_key=target_key,
delivery_target=target.model_dump(), target=target.model_dump(),
expires_at=now + timedelta(seconds=ttl), expires_at=now + timedelta(seconds=ttl),
max_attempts=_code_max_attempts(), max_attempts=_code_max_attempts(),
) )

View File

@ -32,14 +32,19 @@ def template_context(notification_recipient: NotificationRecipient) -> dict:
return { return {
"recipient": { "recipient": {
"id": str(notification_recipient.id), "id": str(notification_recipient.id),
"delivery_channel": notification_recipient.delivery_channel, "channel": notification_recipient.channel,
"delivery_target": notification_recipient.delivery_target, "target": notification_recipient.target,
}, },
"notification": { "notification": {
"id": str(notification.id), "id": str(notification.id),
"url": notification.url, "url": notification.url,
"level": notification.level, "level": notification.level,
"verb": notification.verb, "title": notification.title,
"content_type": (
f"{notification.content_type.app_label}.{notification.content_type.model}"
if notification.content_type_id
else None
),
"object_id": notification.object_id, "object_id": notification.object_id,
"description": notification.description, "description": notification.description,
"data": notification.data, "data": notification.data,
@ -52,17 +57,17 @@ def template_context(notification_recipient: NotificationRecipient) -> dict:
def render_notification_template( def render_notification_template(
delivery_channel: DeliveryChannel, channel: DeliveryChannel,
notification_recipient: NotificationRecipient, notification_recipient: NotificationRecipient,
) -> tuple[str, str | None]: ) -> tuple[str, str | None]:
notification = notification_recipient.notification notification = notification_recipient.notification
template = NotificationTemplate.for_delivery(delivery_channel, notification.type) template = NotificationTemplate.for_delivery(channel, notification.notification_type)
if template: if template:
context = template_context(notification_recipient) context = template_context(notification_recipient)
subject = _single_line(template.render_subject(context)) subject = _single_line(template.render_subject(context))
body = template.render_body(context) body = template.render_body(context)
else: else:
subject = _single_line(notification.verb) subject = _single_line(notification.title)
body = linebreaks(notification.description or "", autoescape=True) body = linebreaks(notification.description or "", autoescape=True)
return subject, body return subject, body
@ -110,10 +115,10 @@ class DeliveryProvider(ABC):
raise NotImplementedError(f"{type(self).__name__} does not support codes") raise NotImplementedError(f"{type(self).__name__} does not support codes")
def mark_sent(self, recipient: NotificationRecipient) -> None: def mark_sent(self, recipient: NotificationRecipient) -> None:
recipient.delivery_status = DeliveryStatus.SENT recipient.status = DeliveryStatus.SENT
recipient.sent_at = timezone.now() recipient.sent_at = timezone.now()
recipient.last_error = "" recipient.last_error = ""
recipient.save(update_fields=["delivery_status", "sent_at", "last_error"]) recipient.save(update_fields=["status", "sent_at", "last_error"])
def enqueue(self, recipient_id) -> None: def enqueue(self, recipient_id) -> None:
from notify.tasks import deliver_notification from notify.tasks import deliver_notification

View File

@ -28,7 +28,7 @@ class EmailDeliveryProvider(DeliveryProvider):
def send(self, recipient: NotificationRecipient) -> None: def send(self, recipient: NotificationRecipient) -> None:
subject, body = render_notification_template(DeliveryChannel.EMAIL, recipient) subject, body = render_notification_template(DeliveryChannel.EMAIL, recipient)
self.send_message( self.send_message(
self.parse_target(recipient.delivery_target), self.parse_target(recipient.target),
subject, subject,
body, body,
attachments=recipient.notification.attachments.all(), attachments=recipient.notification.attachments.all(),

View File

@ -42,7 +42,7 @@ class MaxDeliveryProvider(DeliveryProvider):
def send(self, recipient: NotificationRecipient) -> None: def send(self, recipient: NotificationRecipient) -> None:
_, body = render_notification_template(DeliveryChannel.MAX, recipient) _, body = render_notification_template(DeliveryChannel.MAX, recipient)
self.send_message(self.parse_target(recipient.delivery_target), "", body) self.send_message(self.parse_target(recipient.target), "", body)
self.mark_sent(recipient) self.mark_sent(recipient)
def send_message( def send_message(

View File

@ -30,7 +30,7 @@ class TelegramDeliveryProvider(DeliveryProvider):
def send(self, recipient: NotificationRecipient) -> None: def send(self, recipient: NotificationRecipient) -> None:
_, body = render_notification_template(DeliveryChannel.TELEGRAM, recipient) _, body = render_notification_template(DeliveryChannel.TELEGRAM, recipient)
self.send_message(self.parse_target(recipient.delivery_target), "", body) self.send_message(self.parse_target(recipient.target), "", body)
self.mark_sent(recipient) self.mark_sent(recipient)
def send_message( def send_message(

View File

@ -1,4 +1,4 @@
# Generated by Django 5.0.6 on 2026-10-11 11:02 # Generated by Django 5.0.6 on 2026-10-11 12:17
import django.db.models.deletion import django.db.models.deletion
import notify.fields import notify.fields
@ -13,6 +13,7 @@ class Migration(migrations.Migration):
initial = True initial = True
dependencies = [ dependencies = [
('contenttypes', '0002_remove_content_type_name'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL), migrations.swappable_dependency(settings.AUTH_USER_MODEL),
] ]
@ -31,9 +32,9 @@ class Migration(migrations.Migration):
fields=[ fields=[
('id', models.BigAutoField(primary_key=True, serialize=False)), ('id', models.BigAutoField(primary_key=True, serialize=False)),
('url', models.TextField(null=True)), ('url', models.TextField(null=True)),
('level', models.CharField(choices=[('SUCCESS', 'Success'), ('INFO', 'Info'), ('WARNING', 'Warning'), ('ERROR', 'Error')], default='INFO', max_length=20)), ('level', models.CharField(choices=[('success', 'Success'), ('info', 'Info'), ('warning', 'Warning'), ('error', 'Error')], default='info', max_length=20)),
('verb', models.CharField(max_length=255)), ('title', models.CharField(max_length=255)),
('object_id', models.CharField(default='', max_length=255)), ('object_id', models.CharField(blank=True, default='', max_length=255)),
('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)),
('idempotency_key', models.CharField(blank=True, max_length=255, null=True, unique=True)), ('idempotency_key', models.CharField(blank=True, max_length=255, null=True, unique=True)),
@ -63,7 +64,7 @@ class Migration(migrations.Migration):
fields=[ fields=[
('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)), ('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')], max_length=20)),
('enabled', models.BooleanField(default=True)), ('is_enabled', models.BooleanField(default=True)),
], ],
), ),
migrations.CreateModel( migrations.CreateModel(
@ -81,9 +82,9 @@ class Migration(migrations.Migration):
name='NotificationRecipient', name='NotificationRecipient',
fields=[ fields=[
('id', models.BigAutoField(primary_key=True, serialize=False)), ('id', models.BigAutoField(primary_key=True, serialize=False)),
('delivery_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')], max_length=20)),
('delivery_target', models.JSONField(blank=True, default=None, null=True)), ('target', models.JSONField(blank=True, default=None, null=True)),
('delivery_status', models.CharField(choices=[('UNSENT', 'Unsent'), ('SENT', 'Sent'), ('FAILED', 'Failed')], default='UNSENT', max_length=10)), ('status', models.CharField(choices=[('unsent', 'Unsent'), ('sent', 'Sent'), ('failed', 'Failed')], default='unsent', max_length=10)),
('sent_at', models.DateTimeField(blank=True, null=True)), ('sent_at', models.DateTimeField(blank=True, null=True)),
('attempts', models.PositiveSmallIntegerField(default=0)), ('attempts', models.PositiveSmallIntegerField(default=0)),
('last_error', models.TextField(blank=True, default='')), ('last_error', models.TextField(blank=True, default='')),
@ -98,8 +99,8 @@ class Migration(migrations.Migration):
('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')], max_length=20)),
('name', models.CharField(max_length=255, unique=True)), ('name', models.CharField(max_length=255, unique=True)),
('is_default', models.BooleanField(default=False)), ('is_default', models.BooleanField(default=False)),
('subject_template', models.TextField(blank=True, default='')), ('subject', models.TextField(blank=True, default='')),
('body_template', models.TextField()), ('body', models.TextField()),
], ],
), ),
migrations.CreateModel( migrations.CreateModel(
@ -109,11 +110,11 @@ class Migration(migrations.Migration):
('code', models.CharField(max_length=100, unique=True)), ('code', models.CharField(max_length=100, unique=True)),
('name', models.CharField(max_length=100)), ('name', models.CharField(max_length=100)),
('channels', models.JSONField(blank=True, default=list, validators=[notify.models.validate_delivery_channels])), ('channels', models.JSONField(blank=True, default=list, validators=[notify.models.validate_delivery_channels])),
('verb', models.CharField(blank=True, max_length=255, null=True)), ('title', models.CharField(blank=True, max_length=255, null=True)),
('position', models.IntegerField(default=0)), ('position', models.IntegerField(default=0)),
('is_active', models.BooleanField(default=True)), ('is_active', models.BooleanField(default=True)),
('configurable', models.BooleanField(default=True)), ('is_configurable', models.BooleanField(default=True)),
('enabled_by_default', models.BooleanField(default=True)), ('is_enabled_by_default', models.BooleanField(default=True)),
], ],
options={ options={
'ordering': ('position', 'code'), 'ordering': ('position', 'code'),
@ -126,7 +127,7 @@ class Migration(migrations.Migration):
('purpose', models.CharField(max_length=100)), ('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')], max_length=20)),
('target_key', models.CharField(max_length=255)), ('target_key', models.CharField(max_length=255)),
('delivery_target', models.JSONField(blank=True, default=None, null=True)), ('target', models.JSONField(blank=True, default=None, null=True)),
('code_hash', models.CharField(max_length=128)), ('code_hash', models.CharField(max_length=128)),
('expires_at', models.DateTimeField(db_index=True)), ('expires_at', models.DateTimeField(db_index=True)),
('attempts', models.PositiveSmallIntegerField(default=0)), ('attempts', models.PositiveSmallIntegerField(default=0)),
@ -165,6 +166,11 @@ class Migration(migrations.Migration):
model_name='deliveryconfig', model_name='deliveryconfig',
constraint=models.UniqueConstraint(condition=models.Q(('is_default', True)), fields=('channel',), name='uniq_default_delivery_cfg'), constraint=models.UniqueConstraint(condition=models.Q(('is_default', True)), fields=('channel',), name='uniq_default_delivery_cfg'),
), ),
migrations.AddField(
model_name='notification',
name='content_type',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='contenttypes.contenttype'),
),
migrations.AddField( migrations.AddField(
model_name='notificationattachment', model_name='notificationattachment',
name='notification', name='notification',
@ -192,17 +198,17 @@ class Migration(migrations.Migration):
), ),
migrations.AddField( migrations.AddField(
model_name='notificationtemplate', model_name='notificationtemplate',
name='type', name='notification_type',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='templates', to='notify.notificationtype'), field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='templates', to='notify.notificationtype'),
), ),
migrations.AddField( migrations.AddField(
model_name='notificationchannelpreference', model_name='notificationchannelpreference',
name='type', name='notification_type',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='channel_preferences', to='notify.notificationtype'), field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='channel_preferences', to='notify.notificationtype'),
), ),
migrations.AddField( migrations.AddField(
model_name='notification', model_name='notification',
name='type', name='notification_type',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='notifications', to='notify.notificationtype'), field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='notifications', to='notify.notificationtype'),
), ),
migrations.AddField( migrations.AddField(
@ -212,23 +218,23 @@ class Migration(migrations.Migration):
), ),
migrations.AddIndex( migrations.AddIndex(
model_name='notificationrecipient', model_name='notificationrecipient',
index=models.Index(fields=['user', 'delivery_channel', 'created_at'], name='idx_recipient_inbox'), index=models.Index(fields=['user', 'channel', 'created_at'], name='idx_recipient_inbox'),
), ),
migrations.AddConstraint( migrations.AddConstraint(
model_name='notificationrecipient', model_name='notificationrecipient',
constraint=models.UniqueConstraint(fields=('notification', 'user', 'delivery_channel'), name='uniq_recipient_channel'), constraint=models.UniqueConstraint(fields=('notification', 'user', 'channel'), name='uniq_recipient_channel'),
), ),
migrations.AddConstraint( migrations.AddConstraint(
model_name='notificationtemplate', model_name='notificationtemplate',
constraint=models.UniqueConstraint(condition=models.Q(('is_default', True), ('type__isnull', True)), fields=('channel',), name='uniq_default_template_channel'), constraint=models.UniqueConstraint(condition=models.Q(('is_default', True), ('notification_type__isnull', True)), fields=('channel',), name='uniq_default_template_channel'),
), ),
migrations.AddConstraint( migrations.AddConstraint(
model_name='notificationtemplate', model_name='notificationtemplate',
constraint=models.UniqueConstraint(condition=models.Q(('type__isnull', False)), fields=('type', 'channel'), name='uniq_template_type_channel'), constraint=models.UniqueConstraint(condition=models.Q(('notification_type__isnull', False)), fields=('notification_type', 'channel'), name='uniq_template_type_channel'),
), ),
migrations.AddConstraint( migrations.AddConstraint(
model_name='notificationchannelpreference', model_name='notificationchannelpreference',
constraint=models.UniqueConstraint(fields=('user', 'type', 'channel'), name='uniq_user_type_channel_pref'), constraint=models.UniqueConstraint(fields=('user', 'notification_type', 'channel'), name='uniq_user_type_channel_pref'),
), ),
migrations.AddIndex( migrations.AddIndex(
model_name='verificationcode', model_name='verificationcode',

View File

@ -17,16 +17,16 @@ class DeliveryChannel(models.TextChoices):
class DeliveryStatus(models.TextChoices): class DeliveryStatus(models.TextChoices):
UNSENT = "UNSENT" UNSENT = "unsent"
SENT = "SENT" SENT = "sent"
FAILED = "FAILED" FAILED = "failed"
class NotificationLevel(models.TextChoices): class NotificationLevel(models.TextChoices):
SUCCESS = "SUCCESS" SUCCESS = "success"
INFO = "INFO" INFO = "info"
WARNING = "WARNING" WARNING = "warning"
ERROR = "ERROR" ERROR = "error"
def validate_delivery_channels(value): def validate_delivery_channels(value):

View File

@ -26,7 +26,7 @@ class VerificationCode(models.Model):
purpose = models.CharField(max_length=100) purpose = models.CharField(max_length=100)
channel = models.CharField(max_length=20, choices=DeliveryChannel.choices) channel = models.CharField(max_length=20, choices=DeliveryChannel.choices)
target_key = models.CharField(max_length=255) target_key = models.CharField(max_length=255)
delivery_target = models.JSONField(null=True, blank=True, default=None) target = models.JSONField(null=True, blank=True, default=None)
code_hash = models.CharField(max_length=128) code_hash = models.CharField(max_length=128)
expires_at = models.DateTimeField(db_index=True) expires_at = models.DateTimeField(db_index=True)
attempts = models.PositiveSmallIntegerField(default=0) attempts = models.PositiveSmallIntegerField(default=0)

View File

@ -2,6 +2,8 @@ from datetime import timedelta
from urllib.parse import urlparse from urllib.parse import urlparse
from django.conf import settings from django.conf import settings
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.db import models from django.db import models
from django.utils import timezone from django.utils import timezone
@ -23,7 +25,7 @@ def default_expires_at():
class Notification(models.Model): class Notification(models.Model):
id = models.BigAutoField(primary_key=True) id = models.BigAutoField(primary_key=True)
url = models.TextField(null=True) url = models.TextField(null=True)
type = models.ForeignKey( notification_type = models.ForeignKey(
NotificationType, NotificationType,
null=True, null=True,
blank=True, blank=True,
@ -31,8 +33,10 @@ class Notification(models.Model):
related_name="notifications", related_name="notifications",
) )
level = models.CharField(max_length=20, choices=NotificationLevel.choices, default=NotificationLevel.INFO) level = models.CharField(max_length=20, choices=NotificationLevel.choices, default=NotificationLevel.INFO)
verb = models.CharField(max_length=255) title = models.CharField(max_length=255)
object_id = models.CharField(max_length=255, default="") 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")
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)
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)
@ -43,7 +47,7 @@ class Notification(models.Model):
ordering = ("-created_at",) ordering = ("-created_at",)
def __str__(self): def __str__(self):
return self.verb return self.title
@property @property
def relative_url(self): def relative_url(self):
@ -77,9 +81,9 @@ class NotificationRecipient(models.Model):
on_delete=models.CASCADE, on_delete=models.CASCADE,
related_name="notification_recipients", related_name="notification_recipients",
) )
delivery_channel = models.CharField(max_length=20, choices=DeliveryChannel.choices) channel = models.CharField(max_length=20, choices=DeliveryChannel.choices)
delivery_target = models.JSONField(null=True, blank=True, default=None) target = models.JSONField(null=True, blank=True, default=None)
delivery_status = models.CharField(max_length=10, choices=DeliveryStatus.choices, default=DeliveryStatus.UNSENT) status = models.CharField(max_length=10, choices=DeliveryStatus.choices, default=DeliveryStatus.UNSENT)
sent_at = models.DateTimeField(null=True, blank=True) sent_at = models.DateTimeField(null=True, blank=True)
attempts = models.PositiveSmallIntegerField(default=0) attempts = models.PositiveSmallIntegerField(default=0)
last_error = models.TextField(blank=True, default="") last_error = models.TextField(blank=True, default="")
@ -89,24 +93,24 @@ class NotificationRecipient(models.Model):
class Meta: class Meta:
constraints = [ constraints = [
models.UniqueConstraint( models.UniqueConstraint(
fields=["notification", "user", "delivery_channel"], fields=["notification", "user", "channel"],
name="uniq_recipient_channel", name="uniq_recipient_channel",
), ),
] ]
indexes = [ indexes = [
models.Index(fields=["user", "delivery_channel", "created_at"], name="idx_recipient_inbox"), models.Index(fields=["user", "channel", "created_at"], name="idx_recipient_inbox"),
] ]
def __str__(self): def __str__(self):
target = self.delivery_target target = self.target
if isinstance(target, dict) and target.get("email"): if isinstance(target, dict) and target.get("email"):
target = target["email"] target = target["email"]
target_info = f" to {target}" if target else "" target_info = f" to {target}" if target else ""
return f"{self.delivery_channel}{target_info} ({self.delivery_status})" return f"{self.channel}{target_info} ({self.status})"
def save(self, *args, **kwargs): def save(self, *args, **kwargs):
if self.delivery_channel == DeliveryChannel.BROWSER: if self.channel == DeliveryChannel.BROWSER:
self.delivery_status = DeliveryStatus.SENT self.status = DeliveryStatus.SENT
if self.sent_at is None: if self.sent_at is None:
self.sent_at = timezone.now() self.sent_at = timezone.now()
super().save(*args, **kwargs) super().save(*args, **kwargs)

View File

@ -19,11 +19,11 @@ class NotificationType(models.Model):
name = models.CharField(max_length=100) name = models.CharField(max_length=100)
channels = models.JSONField(default=list, blank=True, validators=[validate_delivery_channels]) channels = models.JSONField(default=list, blank=True, validators=[validate_delivery_channels])
group = models.ForeignKey(NotificationGroup, on_delete=models.PROTECT, related_name="types") group = models.ForeignKey(NotificationGroup, on_delete=models.PROTECT, related_name="types")
verb = models.CharField(max_length=255, null=True, blank=True) title = models.CharField(max_length=255, null=True, blank=True)
position = models.IntegerField(default=0) position = models.IntegerField(default=0)
is_active = models.BooleanField(default=True) is_active = models.BooleanField(default=True)
configurable = models.BooleanField(default=True) is_configurable = models.BooleanField(default=True)
enabled_by_default = models.BooleanField(default=True) is_enabled_by_default = models.BooleanField(default=True)
objects = NotificationTypeManager() objects = NotificationTypeManager()
@ -44,22 +44,22 @@ class NotificationChannelPreference(models.Model):
on_delete=models.CASCADE, on_delete=models.CASCADE,
related_name="notification_channel_preferences", related_name="notification_channel_preferences",
) )
type = models.ForeignKey( notification_type = models.ForeignKey(
NotificationType, NotificationType,
on_delete=models.CASCADE, on_delete=models.CASCADE,
related_name="channel_preferences", related_name="channel_preferences",
) )
channel = models.CharField(max_length=20, choices=DeliveryChannel.choices) channel = models.CharField(max_length=20, choices=DeliveryChannel.choices)
enabled = models.BooleanField(default=True) is_enabled = models.BooleanField(default=True)
class Meta: class Meta:
constraints = [ constraints = [
models.UniqueConstraint( models.UniqueConstraint(
fields=["user", "type", "channel"], fields=["user", "notification_type", "channel"],
name="uniq_user_type_channel_pref", name="uniq_user_type_channel_pref",
), ),
] ]
def __str__(self): def __str__(self):
state = "on" if self.enabled else "off" state = "on" if self.is_enabled else "off"
return f"{self.user_id} {self.channel} {state}" return f"{self.user_id} {self.channel} {state}"

View File

@ -13,7 +13,7 @@ __all__ = [
class NotificationTemplate(models.Model): class NotificationTemplate(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
channel = models.CharField(max_length=20, choices=DeliveryChannel.choices) channel = models.CharField(max_length=20, choices=DeliveryChannel.choices)
type = models.ForeignKey( notification_type = models.ForeignKey(
"notify.NotificationType", "notify.NotificationType",
null=True, null=True,
blank=True, blank=True,
@ -22,19 +22,19 @@ class NotificationTemplate(models.Model):
) )
name = models.CharField(unique=True, max_length=255) name = models.CharField(unique=True, max_length=255)
is_default = models.BooleanField(default=False) is_default = models.BooleanField(default=False)
subject_template = models.TextField(default="", blank=True) subject = models.TextField(default="", blank=True)
body_template = models.TextField() body = models.TextField()
class Meta: class Meta:
constraints = [ constraints = [
models.UniqueConstraint( models.UniqueConstraint(
fields=["channel"], fields=["channel"],
condition=models.Q(is_default=True, type__isnull=True), condition=models.Q(is_default=True, notification_type__isnull=True),
name="uniq_default_template_channel", name="uniq_default_template_channel",
), ),
models.UniqueConstraint( models.UniqueConstraint(
fields=["type", "channel"], fields=["notification_type", "channel"],
condition=models.Q(type__isnull=False), condition=models.Q(notification_type__isnull=False),
name="uniq_template_type_channel", name="uniq_template_type_channel",
), ),
] ]
@ -46,10 +46,10 @@ class NotificationTemplate(models.Model):
update_fields = kwargs.get("update_fields") update_fields = kwargs.get("update_fields")
touches_default = update_fields is None or "is_default" in update_fields touches_default = update_fields is None or "is_default" in update_fields
with transaction.atomic(): with transaction.atomic():
if self.is_default and touches_default and self.type_id is None: if self.is_default and touches_default and self.notification_type_id is None:
others = type(self).objects.filter( others = type(self).objects.filter(
channel=self.channel, channel=self.channel,
type__isnull=True, notification_type__isnull=True,
is_default=True, is_default=True,
) )
if self.pk: if self.pk:
@ -60,7 +60,7 @@ class NotificationTemplate(models.Model):
@classmethod @classmethod
def default(cls, channel): def default(cls, channel):
return ( return (
cls.objects.filter(channel=channel, type__isnull=True, is_default=True) cls.objects.filter(channel=channel, notification_type__isnull=True, is_default=True)
.order_by("id") .order_by("id")
.first() .first()
) )
@ -68,13 +68,13 @@ class NotificationTemplate(models.Model):
@classmethod @classmethod
def for_delivery(cls, channel, notification_type): def for_delivery(cls, channel, notification_type):
if notification_type is not None: if notification_type is not None:
typed = cls.objects.filter(channel=channel, type=notification_type).order_by("id").first() typed = cls.objects.filter(channel=channel, notification_type=notification_type).order_by("id").first()
if typed is not None: if typed is not None:
return typed return typed
return cls.default(channel) return cls.default(channel)
def render_subject(self, context): def render_subject(self, context):
return render(self.subject_template, context) return render(self.subject, context)
def render_body(self, context): def render_body(self, context):
return render(self.body_template, context) return render(self.body, context)

View File

@ -15,13 +15,13 @@ __all__ = [
def post_save_notification(sender, instance: NotificationRecipient, created, **kwargs): def post_save_notification(sender, instance: NotificationRecipient, created, **kwargs):
if not created: if not created:
return return
provider = get_provider(instance.delivery_channel) provider = get_provider(instance.channel)
if provider is None or not provider.requires_async_delivery: if provider is None or not provider.requires_async_delivery:
return return
recipient_id = instance.id recipient_id = instance.id
def enqueue(): def enqueue():
current = get_provider(instance.delivery_channel) current = get_provider(instance.channel)
if current is not None: if current is not None:
current.enqueue(recipient_id) current.enqueue(recipient_id)

View File

@ -1,3 +1,4 @@
from django.contrib.contenttypes.models import ContentType
from django.db import IntegrityError, transaction from django.db import IntegrityError, transaction
from django.utils import timezone from django.utils import timezone
@ -34,14 +35,14 @@ def _existing_idempotent(idempotency_key):
def _allowed_channels(notification_type, user, channels): def _allowed_channels(notification_type, user, channels):
if notification_type is None or not notification_type.configurable: if notification_type is None or not notification_type.is_configurable:
return channels return channels
allowed = set(notification_type.channels) allowed = set(notification_type.channels)
prefs = { prefs = {
pref.channel: pref.enabled pref.channel: pref.is_enabled
for pref in NotificationChannelPreference.objects.filter( for pref in NotificationChannelPreference.objects.filter(
user=user, user=user,
type=notification_type, notification_type=notification_type,
channel__in=allowed, channel__in=allowed,
) )
} }
@ -52,22 +53,31 @@ def _allowed_channels(notification_type, user, channels):
raise ValueError( raise ValueError(
f"Channel {channel} is not allowed for notification type {notification_type.code}" f"Channel {channel} is not allowed for notification type {notification_type.code}"
) )
if prefs.get(channel, notification_type.enabled_by_default): if prefs.get(channel, notification_type.is_enabled_by_default):
kept.append(channel_data) kept.append(channel_data)
return kept return kept
def _grouped_notification(notification_type, user, object_id): def _content_link(content_object):
if notification_type is None or not object_id: if content_object is None:
return None, ""
if content_object.pk is None:
raise ValueError("content_object must be saved")
return ContentType.objects.get_for_model(content_object), str(content_object.pk)
def _grouped_notification(notification_type, user, content_type, object_id):
if notification_type is None or content_type is None or not object_id:
return None return None
return ( return (
Notification.objects.select_for_update() Notification.objects.select_for_update()
.filter( .filter(
type=notification_type, notification_type=notification_type,
content_type=content_type,
object_id=object_id, object_id=object_id,
expires_at__gte=timezone.now(), expires_at__gte=timezone.now(),
recipients__user=user, recipients__user=user,
recipients__delivery_channel=DeliveryChannel.BROWSER, recipients__channel=DeliveryChannel.BROWSER,
recipients__unread=True, recipients__unread=True,
) )
.order_by("-created_at") .order_by("-created_at")
@ -75,22 +85,22 @@ def _grouped_notification(notification_type, user, object_id):
) )
def _bump_group(notification, verb): def _bump_group(notification, title):
payload = dict(notification.data or {}) payload = dict(notification.data or {})
payload["count"] = int(payload.get("count", 1)) + 1 payload["count"] = int(payload.get("count", 1)) + 1
notification.data = payload notification.data = payload
if verb: if title:
notification.verb = verb notification.title = title
notification.save(update_fields=["data", "verb"]) notification.save(update_fields=["data", "title"])
return notification return notification
def _collapse_grouped(notification_type, recipients, object_id, verb): def _collapse_grouped(notification_type, recipients, content_type, object_id, title):
pending = [] pending = []
grouped = [] grouped = []
seen = set() seen = set()
for recipient_data in recipients: for recipient_data in recipients:
found = _grouped_notification(notification_type, recipient_data["user"], object_id) found = _grouped_notification(notification_type, recipient_data["user"], content_type, object_id)
if found is None: if found is None:
pending.append(recipient_data) pending.append(recipient_data)
continue continue
@ -98,7 +108,7 @@ def _collapse_grouped(notification_type, recipients, object_id, verb):
seen.add(found.pk) seen.add(found.pk)
grouped.append(found) grouped.append(found)
for notification in grouped: for notification in grouped:
_bump_group(notification, verb) _bump_group(notification, title)
return pending, grouped return pending, grouped
@ -129,8 +139,8 @@ def _attach_recipients(notification, recipients, notification_type):
NotificationRecipient.objects.create( NotificationRecipient.objects.create(
notification=notification, notification=notification,
user=user, user=user,
delivery_channel=channel, channel=channel,
delivery_target=target.model_dump() if target is not None else None, target=target.model_dump() if target is not None else None,
) )
created += 1 created += 1
if created == 0: if created == 0:
@ -141,11 +151,11 @@ def _attach_recipients(notification, recipients, notification_type):
def create_notification( def create_notification(
*, *,
recipients: list[dict], recipients: list[dict],
verb: str | None = None, title: str | None = None,
url: str | None = None, url: str | None = None,
type: NotificationType | str | None = None, notification_type: NotificationType | str | None = None,
level: str = NotificationLevel.INFO, level: str = NotificationLevel.INFO,
object_id: str = "", content_object=None,
description: str | None = None, description: str | None = None,
data: dict | None = None, data: dict | None = None,
expires_at=None, expires_at=None,
@ -160,14 +170,16 @@ def create_notification(
return existing return existing
prepared_attachments = prepare_attachments(attachments) prepared_attachments = prepare_attachments(attachments)
notification_type = _resolve_type(type) notification_type = _resolve_type(notification_type)
if notification_type is not None and not notification_type.is_active: if notification_type is not None and not notification_type.is_active:
raise ValueError(f"Notification type {notification_type.code} is inactive") raise ValueError(f"Notification type {notification_type.code} is inactive")
if not verb: if not title:
verb = notification_type.verb if notification_type is not None else None title = notification_type.title if notification_type is not None else None
if not verb: if not title:
raise ValueError("verb is required") raise ValueError("title is required")
content_type, object_id = _content_link(content_object)
if not recipients: if not recipients:
raise ValueError("At least one recipient is required") raise ValueError("At least one recipient is required")
@ -183,8 +195,9 @@ def create_notification(
to_create, grouped = _collapse_grouped( to_create, grouped = _collapse_grouped(
notification_type, notification_type,
recipients, recipients,
object_id or "", content_type,
verb, object_id,
title,
) )
for grouped_notification in grouped: for grouped_notification in grouped:
store_attachments(grouped_notification, prepared_attachments, stored_attachments) store_attachments(grouped_notification, prepared_attachments, stored_attachments)
@ -192,10 +205,11 @@ def create_notification(
return grouped[0] return grouped[0]
fields = dict( fields = dict(
url=url, url=url,
type=notification_type, notification_type=notification_type,
level=level, level=level,
verb=verb, title=title,
object_id=object_id or "", content_type=content_type,
object_id=object_id,
description=description, description=description,
data=data or {}, data=data or {},
idempotency_key=idempotency_key, idempotency_key=idempotency_key,
@ -218,9 +232,9 @@ def create_notification(
def channel_preferences(user): def channel_preferences(user):
types = NotificationType.objects.filter(is_active=True, configurable=True) types = NotificationType.objects.filter(is_active=True, is_configurable=True)
saved = { saved = {
(pref.type_id, pref.channel): pref.enabled (pref.notification_type_id, pref.channel): pref.is_enabled
for pref in NotificationChannelPreference.objects.filter(user=user) for pref in NotificationChannelPreference.objects.filter(user=user)
} }
return [ return [
@ -229,9 +243,9 @@ def channel_preferences(user):
"channels": [ "channels": [
{ {
"channel": channel, "channel": channel,
"enabled": saved.get( "is_enabled": saved.get(
(notification_type.id, channel), (notification_type.id, channel),
notification_type.enabled_by_default, notification_type.is_enabled_by_default,
), ),
} }
for channel in notification_type.channels for channel in notification_type.channels
@ -243,7 +257,7 @@ def channel_preferences(user):
def save_channel_preferences(user, items): def save_channel_preferences(user, items):
for item in items: for item in items:
notification_type = NotificationType.objects.get(code=item["code"], configurable=True) notification_type = NotificationType.objects.get(code=item["code"], is_configurable=True)
for channel_item in item["channels"]: for channel_item in item["channels"]:
channel = channel_item["channel"] channel = channel_item["channel"]
if channel not in notification_type.channels: if channel not in notification_type.channels:
@ -252,7 +266,7 @@ def save_channel_preferences(user, items):
) )
NotificationChannelPreference.objects.update_or_create( NotificationChannelPreference.objects.update_or_create(
user=user, user=user,
type=notification_type, notification_type=notification_type,
channel=channel, channel=channel,
defaults={"enabled": channel_item["enabled"]}, defaults={"is_enabled": channel_item["is_enabled"]},
) )

View File

@ -38,9 +38,9 @@ BEAT_SCHEDULE = {
def _mark_failed(notification_recipient_id: str, error: str) -> None: def _mark_failed(notification_recipient_id: str, error: str) -> None:
NotificationRecipient.objects.filter( NotificationRecipient.objects.filter(
id=notification_recipient_id, id=notification_recipient_id,
delivery_status=DeliveryStatus.UNSENT, status=DeliveryStatus.UNSENT,
).update( ).update(
delivery_status=DeliveryStatus.FAILED, status=DeliveryStatus.FAILED,
last_error=error[:2000], last_error=error[:2000],
) )
@ -50,18 +50,18 @@ def _deliver_notification(notification_recipient_id: str) -> None:
with transaction.atomic(): with transaction.atomic():
recipient = ( recipient = (
NotificationRecipient.objects.select_for_update(of=("self",)) NotificationRecipient.objects.select_for_update(of=("self",))
.select_related("notification__type", "user") .select_related("notification__notification_type", "user")
.filter(id=notification_recipient_id) .filter(id=notification_recipient_id)
.first() .first()
) )
if recipient is None or recipient.delivery_status != DeliveryStatus.UNSENT: if recipient is None or recipient.status != DeliveryStatus.UNSENT:
return return
NotificationRecipient.objects.filter(pk=recipient.pk).update( NotificationRecipient.objects.filter(pk=recipient.pk).update(
attempts=F("attempts") + 1, attempts=F("attempts") + 1,
) )
recipient.refresh_from_db(fields=["attempts"]) recipient.refresh_from_db(fields=["attempts"])
try: try:
provider = get_provider_or_raise(recipient.delivery_channel) provider = get_provider_or_raise(recipient.channel)
provider.send(recipient) provider.send(recipient)
except Exception as exc: except Exception as exc:
if isinstance(exc, KeyError): if isinstance(exc, KeyError):

View File

@ -1,6 +1,6 @@
[project] [project]
name = "notify" name = "notify"
version = "0.1.0" version = "0.4.0"
description = "Django app for user notifications" description = "Django app for user notifications"
readme = "Readme.md" readme = "Readme.md"
requires-python = ">=3.10" requires-python = ">=3.10"

View File

@ -221,7 +221,7 @@ class NotificationAdminTests(TestCase):
def setUp(self): def setUp(self):
self.admin_user = User.objects.create_superuser("admin", "admin@example.com", "pass") self.admin_user = User.objects.create_superuser("admin", "admin@example.com", "pass")
self.client.force_login(self.admin_user) self.client.force_login(self.admin_user)
self.note = Notification.objects.create(verb="Hello") self.note = Notification.objects.create(title="Hello")
def test_notifications_are_read_only(self): def test_notifications_are_read_only(self):
request = RequestFactory().get("/") request = RequestFactory().get("/")
@ -239,8 +239,8 @@ class NotificationAdminTests(TestCase):
response = self.client.get(change) response = self.client.get(change)
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
self.assertFalse(response.context["has_change_permission"]) self.assertFalse(response.context["has_change_permission"])
self.assertEqual(self.client.post(change, {"verb": "Changed"}).status_code, 403) self.assertEqual(self.client.post(change, {"title": "Changed"}).status_code, 403)
self.note.refresh_from_db() self.note.refresh_from_db()
self.assertEqual(self.note.verb, "Hello") self.assertEqual(self.note.title, "Hello")
listing = reverse("admin:notify_notification_changelist") listing = reverse("admin:notify_notification_changelist")
self.assertEqual(self.client.get(listing).status_code, 200) self.assertEqual(self.client.get(listing).status_code, 200)

View File

@ -24,11 +24,11 @@ class ApiTests(TestCase):
self.other = User.objects.create_user("bob", "bob@example.com", "pass") self.other = User.objects.create_user("bob", "bob@example.com", "pass")
self.client.force_login(self.user) self.client.force_login(self.user)
def _browser(self, user, verb, expires_at=None, **extra): def _browser(self, user, title, expires_at=None, **extra):
if expires_at is not None: if expires_at is not None:
extra["expires_at"] = expires_at extra["expires_at"] = expires_at
return create_notification( return create_notification(
verb=verb, title=title,
recipients=[{"user": user, "channels": [{"channel": DeliveryChannel.BROWSER}]}], recipients=[{"user": user, "channels": [{"channel": DeliveryChannel.BROWSER}]}],
**extra, **extra,
) )
@ -43,7 +43,7 @@ class ApiTests(TestCase):
name=code, name=code,
group=group, group=group,
channels=[DeliveryChannel.BROWSER, DeliveryChannel.EMAIL], channels=[DeliveryChannel.BROWSER, DeliveryChannel.EMAIL],
verb=code, title=code,
) )
def test_expired_notifications_are_hidden(self): def test_expired_notifications_are_hidden(self):
@ -57,7 +57,7 @@ class ApiTests(TestCase):
listing = self.client.get("/api/list/") listing = self.client.get("/api/list/")
self.assertEqual(listing.status_code, 200) self.assertEqual(listing.status_code, 200)
verbs = [item["verb"] for item in listing.json()["results"]] verbs = [item["title"] for item in listing.json()["results"]]
self.assertEqual(verbs, ["fresh"]) self.assertEqual(verbs, ["fresh"])
def test_invalid_recipient_id_is_not_found(self): def test_invalid_recipient_id_is_not_found(self):
@ -87,16 +87,17 @@ class ApiTests(TestCase):
def test_list_returns_the_browser_inbox(self): def test_list_returns_the_browser_inbox(self):
kind = self._type("orders.approved") kind = self._type("orders.approved")
when = timezone.now() + timedelta(days=3) when = timezone.now() + timedelta(days=3)
subject = User.objects.create_user("carol", "carol@example.com", "pass")
notification = self._browser( notification = self._browser(
self.user, self.user,
"Invoice paid", "Invoice paid",
expires_at=when, expires_at=when,
type=kind, notification_type=kind,
url="https://example.com/orders/1?x=1", url="https://example.com/orders/1?x=1",
object_id="1", content_object=subject,
description="wire", description="wire",
data={"n": 1}, data={"n": 1},
level="SUCCESS", level="success",
) )
self._browser(self.other, "foreign") self._browser(self.other, "foreign")
older = notification.recipients.get() older = notification.recipients.get()
@ -109,26 +110,27 @@ class ApiTests(TestCase):
body = listing.json() body = listing.json()
self.assertEqual(body["total"], 2) self.assertEqual(body["total"], 2)
self.assertEqual(body["pagination"], {"page": 1, "total_pages": 1}) self.assertEqual(body["pagination"], {"page": 1, "total_pages": 1})
self.assertEqual([item["verb"] for item in body["results"]], ["Newer", "Invoice paid"]) self.assertEqual([item["title"] for item in body["results"]], ["Newer", "Invoice paid"])
item = body["results"][1] item = body["results"][1]
self.assertEqual(item["id"], older.id) self.assertEqual(item["id"], older.id)
self.assertEqual(item["type"], "orders.approved") self.assertEqual(item["type"], "orders.approved")
self.assertEqual(item["level"], "SUCCESS") self.assertEqual(item["level"], "success")
self.assertEqual(item["url"], "https://example.com/orders/1?x=1") self.assertEqual(item["url"], "https://example.com/orders/1?x=1")
self.assertEqual(item["object_id"], "1") self.assertEqual(item["content_type"], "auth.user")
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["unread"]) self.assertTrue(item["unread"])
self.assertNotIn("delivery_channel", item) self.assertNotIn("channel", item)
self.assertNotIn("delivery_target", item) self.assertNotIn("target", item)
count = self.client.get("/api/count/") count = self.client.get("/api/count/")
self.assertEqual(count.json()["result"], 2) self.assertEqual(count.json()["result"], 2)
def test_other_channels_and_other_users_stay_out_of_the_inbox(self): def test_other_channels_and_other_users_stay_out_of_the_inbox(self):
create_notification( create_notification(
verb="mail", title="mail",
recipients=[ recipients=[
{ {
"user": self.user, "user": self.user,
@ -140,7 +142,7 @@ class ApiTests(TestCase):
self._browser(self.user, "mine") self._browser(self.user, "mine")
listing = self.client.get("/api/list/") listing = self.client.get("/api/list/")
self.assertEqual([item["verb"] for item in listing.json()["results"]], ["mine"]) self.assertEqual([item["title"] for item in listing.json()["results"]], ["mine"])
foreign_id = foreign.recipients.get().id foreign_id = foreign.recipients.get().id
denied = self.client.post(f"/api/make-read/{foreign_id}/") denied = self.client.post(f"/api/make-read/{foreign_id}/")
@ -148,7 +150,7 @@ class ApiTests(TestCase):
foreign.recipients.get().refresh_from_db() foreign.recipients.get().refresh_from_db()
self.assertTrue(foreign.recipients.get().unread) self.assertTrue(foreign.recipients.get().unread)
email_id = NotificationRecipient.objects.get(delivery_channel=DeliveryChannel.EMAIL).id email_id = NotificationRecipient.objects.get(channel=DeliveryChannel.EMAIL).id
self.assertEqual(self.client.post(f"/api/make-read/{email_id}/").status_code, 404) self.assertEqual(self.client.post(f"/api/make-read/{email_id}/").status_code, 404)
def test_expired_recipient_cannot_be_marked(self): def test_expired_recipient_cannot_be_marked(self):
@ -165,7 +167,7 @@ class ApiTests(TestCase):
read = self.client.post(f"/api/make-read/{recipient.id}/") read = self.client.post(f"/api/make-read/{recipient.id}/")
self.assertEqual(read.status_code, 200) self.assertEqual(read.status_code, 200)
self.assertFalse(read.json()["unread"]) self.assertFalse(read.json()["unread"])
self.assertEqual(read.json()["verb"], "fresh") self.assertEqual(read.json()["title"], "fresh")
self.assertEqual(self.client.get("/api/unread-count/").json()["result"], 0) self.assertEqual(self.client.get("/api/unread-count/").json()["result"], 0)
again = self.client.post(f"/api/make-unread/{recipient.id}/") again = self.client.post(f"/api/make-unread/{recipient.id}/")
@ -178,26 +180,29 @@ class ApiTests(TestCase):
approved = self._type("orders.approved") approved = self._type("orders.approved")
rejected = self._type("orders.rejected") rejected = self._type("orders.rejected")
billing = self._type("billing.due") billing = self._type("billing.due")
invoice = User.objects.create_user("invoice", "invoice@example.com", "pass")
card = User.objects.create_user("card", "card@example.com", "pass")
reminder = User.objects.create_user("reminder", "reminder@example.com", "pass")
self._browser( self._browser(
self.user, self.user,
"Invoice paid", "Invoice paid",
type=approved, notification_type=approved,
object_id="1", content_object=invoice,
description="wire", description="wire",
) )
self._browser(self.user, "Nope", type=rejected, object_id="2", description="card") self._browser(self.user, "Nope", notification_type=rejected, content_object=card, description="card")
self._browser( self._browser(
self.user, self.user,
"Due", "Due",
type=billing, notification_type=billing,
object_id="3", content_object=reminder,
description="Invoice reminder", description="Invoice reminder",
) )
paid = NotificationRecipient.objects.get(notification__object_id="1") paid = NotificationRecipient.objects.get(notification__object_id=str(invoice.pk))
paid.make_read() paid.make_read()
def verbs(response): def verbs(response):
return [item["verb"] for item in response.json()["results"]] return [item["title"] for item in response.json()["results"]]
self.assertEqual( self.assertEqual(
verbs(self.client.get("/api/list/", {"type": "orders.approved"})), verbs(self.client.get("/api/list/", {"type": "orders.approved"})),
@ -208,7 +213,11 @@ class ApiTests(TestCase):
["Invoice paid", "Nope"], ["Invoice paid", "Nope"],
) )
self.assertEqual( self.assertEqual(
verbs(self.client.get("/api/list/", {"object_id": "2"})), verbs(self.client.get("/api/list/", {"object_id": str(card.pk)})),
["Nope"],
)
self.assertEqual(
verbs(self.client.get("/api/list/", {"content_type": "auth.user", "object_id": str(card.pk)})),
["Nope"], ["Nope"],
) )
self.assertCountEqual( self.assertCountEqual(
@ -224,11 +233,11 @@ class ApiTests(TestCase):
["Invoice paid"], ["Invoice paid"],
) )
self.assertCountEqual( self.assertCountEqual(
verbs(self.client.get("/api/list/", {"object_id__ne": ["2"]})), verbs(self.client.get("/api/list/", {"object_id__ne": [str(card.pk)]})),
["Invoice paid", "Due"], ["Invoice paid", "Due"],
) )
self.assertEqual( self.assertEqual(
verbs(self.client.get("/api/list/", {"object_id__ne__in": "1,3"})), verbs(self.client.get("/api/list/", {"object_id__ne__in": f"{invoice.pk},{reminder.pk}"})),
["Nope"], ["Nope"],
) )
self.assertEqual( self.assertEqual(
@ -239,17 +248,17 @@ class ApiTests(TestCase):
def test_make_all_read_respects_filters(self): def test_make_all_read_respects_filters(self):
orders = self._type("orders.approved") orders = self._type("orders.approved")
billing = self._type("billing.due") billing = self._type("billing.due")
self._browser(self.user, "order", type=orders) self._browser(self.user, "order", notification_type=orders)
self._browser(self.user, "bill", type=billing) self._browser(self.user, "bill", notification_type=billing)
self._browser(self.other, "foreign", type=orders) self._browser(self.other, "foreign", notification_type=orders)
self._browser( self._browser(
self.user, self.user,
"old order", "old order",
type=orders, notification_type=orders,
expires_at=timezone.now() - timedelta(minutes=1), expires_at=timezone.now() - timedelta(minutes=1),
) )
mailed = create_notification( mailed = create_notification(
type=orders, notification_type=orders,
recipients=[ recipients=[
{ {
"user": self.user, "user": self.user,
@ -262,8 +271,8 @@ class ApiTests(TestCase):
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
self.assertEqual(response.json(), {}) self.assertEqual(response.json(), {})
def unread(verb): def unread(title):
return NotificationRecipient.objects.get(notification__verb=verb).unread return NotificationRecipient.objects.get(notification__title=title).unread
self.assertFalse(unread("order")) self.assertFalse(unread("order"))
self.assertTrue(unread("bill")) self.assertTrue(unread("bill"))
@ -306,7 +315,7 @@ class ApiTests(TestCase):
name="Security", name="Security",
group=group, group=group,
channels=[DeliveryChannel.EMAIL], channels=[DeliveryChannel.EMAIL],
configurable=False, is_configurable=False,
) )
NotificationType.objects.create( NotificationType.objects.create(
code="retired", code="retired",
@ -317,9 +326,9 @@ class ApiTests(TestCase):
) )
NotificationChannelPreference.objects.create( NotificationChannelPreference.objects.create(
user=self.user, user=self.user,
type=approved, notification_type=approved,
channel=DeliveryChannel.EMAIL, channel=DeliveryChannel.EMAIL,
enabled=False, is_enabled=False,
) )
response = self.client.get("/api/preferences/") response = self.client.get("/api/preferences/")
@ -332,8 +341,8 @@ class ApiTests(TestCase):
"name": "Approved", "name": "Approved",
"group_name": "Orders", "group_name": "Orders",
"channels": [ "channels": [
{"channel": DeliveryChannel.EMAIL, "enabled": False}, {"channel": DeliveryChannel.EMAIL, "is_enabled": False},
{"channel": DeliveryChannel.BROWSER, "enabled": True}, {"channel": DeliveryChannel.BROWSER, "is_enabled": True},
], ],
}, },
{ {
@ -341,7 +350,7 @@ class ApiTests(TestCase):
"name": "Later", "name": "Later",
"group_name": "Orders", "group_name": "Orders",
"channels": [ "channels": [
{"channel": DeliveryChannel.BROWSER, "enabled": True}, {"channel": DeliveryChannel.BROWSER, "is_enabled": True},
], ],
}, },
], ],
@ -360,7 +369,7 @@ class ApiTests(TestCase):
{ {
"code": "orders.approved", "code": "orders.approved",
"channels": [ "channels": [
{"channel": DeliveryChannel.EMAIL, "enabled": False}, {"channel": DeliveryChannel.EMAIL, "is_enabled": False},
], ],
} }
] ]
@ -371,7 +380,7 @@ class ApiTests(TestCase):
listing = self.client.get("/api/preferences/") listing = self.client.get("/api/preferences/")
channels = { channels = {
item["channel"]: item["enabled"] item["channel"]: item["is_enabled"]
for item in listing.json()[0]["channels"] for item in listing.json()[0]["channels"]
} }
self.assertEqual( self.assertEqual(
@ -387,7 +396,7 @@ class ApiTests(TestCase):
name="Security", name="Security",
group=group, group=group,
channels=[DeliveryChannel.EMAIL], channels=[DeliveryChannel.EMAIL],
configurable=False, is_configurable=False,
) )
unknown_channel = self._post_preferences( unknown_channel = self._post_preferences(
@ -395,7 +404,7 @@ class ApiTests(TestCase):
"items": [ "items": [
{ {
"code": "orders.approved", "code": "orders.approved",
"channels": [{"channel": DeliveryChannel.MAX, "enabled": True}], "channels": [{"channel": DeliveryChannel.MAX, "is_enabled": True}],
} }
] ]
} }
@ -408,7 +417,7 @@ class ApiTests(TestCase):
"items": [ "items": [
{ {
"code": "security", "code": "security",
"channels": [{"channel": DeliveryChannel.EMAIL, "enabled": False}], "channels": [{"channel": DeliveryChannel.EMAIL, "is_enabled": False}],
} }
] ]
} }
@ -417,18 +426,18 @@ class ApiTests(TestCase):
self.assertIn("detail", locked.json()) self.assertIn("detail", locked.json())
self.assertFalse(NotificationChannelPreference.objects.exists()) self.assertFalse(NotificationChannelPreference.objects.exists())
def test_preferences_use_enabled_by_default_until_overridden(self): def test_preferences_use_is_enabled_by_default_until_overridden(self):
kind = self._type("orders.digest") kind = self._type("orders.digest")
kind.enabled_by_default = False kind.is_enabled_by_default = False
kind.save(update_fields=["enabled_by_default"]) kind.save(update_fields=["is_enabled_by_default"])
listing = self.client.get("/api/preferences/") listing = self.client.get("/api/preferences/")
self.assertEqual(listing.status_code, 200) self.assertEqual(listing.status_code, 200)
self.assertEqual( self.assertEqual(
listing.json()[0]["channels"], listing.json()[0]["channels"],
[ [
{"channel": DeliveryChannel.BROWSER, "enabled": False}, {"channel": DeliveryChannel.BROWSER, "is_enabled": False},
{"channel": DeliveryChannel.EMAIL, "enabled": False}, {"channel": DeliveryChannel.EMAIL, "is_enabled": False},
], ],
) )
@ -438,7 +447,7 @@ class ApiTests(TestCase):
{ {
"code": "orders.digest", "code": "orders.digest",
"channels": [ "channels": [
{"channel": DeliveryChannel.EMAIL, "enabled": True}, {"channel": DeliveryChannel.EMAIL, "is_enabled": True},
], ],
} }
] ]
@ -446,7 +455,7 @@ class ApiTests(TestCase):
) )
self.assertEqual(saved.status_code, 200) self.assertEqual(saved.status_code, 200)
channels = { channels = {
item["channel"]: item["enabled"] item["channel"]: item["is_enabled"]
for item in self.client.get("/api/preferences/").json()[0]["channels"] for item in self.client.get("/api/preferences/").json()[0]["channels"]
} }
self.assertEqual( self.assertEqual(
@ -460,23 +469,23 @@ class PaginationTests(TestCase):
self.user = User.objects.create_user("alice", "alice@example.com", "pass") self.user = User.objects.create_user("alice", "alice@example.com", "pass")
def test_pages_are_counted_from_the_queryset(self): def test_pages_are_counted_from_the_queryset(self):
for verb in ("a", "b", "c"): for title in ("a", "b", "c"):
create_notification( create_notification(
verb=verb, title=title,
recipients=[ recipients=[
{"user": self.user, "channels": [{"channel": DeliveryChannel.BROWSER}]}, {"user": self.user, "channels": [{"channel": DeliveryChannel.BROWSER}]},
], ],
) )
paginator = CustomPagination(page_size=2) paginator = CustomPagination(page_size=2)
queryset = NotificationRecipient.objects.order_by("notification__verb") queryset = NotificationRecipient.objects.order_by("notification__title")
first = paginator.paginate_queryset(queryset, CustomPagination.Input(page=1)) first = paginator.paginate_queryset(queryset, CustomPagination.Input(page=1))
self.assertEqual(first["total"], 3) self.assertEqual(first["total"], 3)
self.assertEqual(first["pagination"], {"page": 1, "total_pages": 2}) self.assertEqual(first["pagination"], {"page": 1, "total_pages": 2})
self.assertEqual([item.notification.verb for item in first["results"]], ["a", "b"]) self.assertEqual([item.notification.title for item in first["results"]], ["a", "b"])
second = paginator.paginate_queryset(queryset, CustomPagination.Input(page=2)) second = paginator.paginate_queryset(queryset, CustomPagination.Input(page=2))
self.assertEqual([item.notification.verb for item in second["results"]], ["c"]) self.assertEqual([item.notification.title for item in second["results"]], ["c"])
empty = paginator.paginate_queryset( empty = paginator.paginate_queryset(
NotificationRecipient.objects.none(), NotificationRecipient.objects.none(),

View File

@ -39,12 +39,12 @@ class AttachmentServiceTests(TestCase):
name="Approved", name="Approved",
group=self.group, group=self.group,
channels=[DeliveryChannel.BROWSER, DeliveryChannel.EMAIL], channels=[DeliveryChannel.BROWSER, DeliveryChannel.EMAIL],
verb="Approved", title="Approved",
) )
def _browser(self, user, **extra): def _browser(self, user, **extra):
return create_notification( return create_notification(
verb=extra.pop("verb", "Hello"), title=extra.pop("title", "Hello"),
recipients=[{"user": user, "channels": [{"channel": DeliveryChannel.BROWSER}]}], recipients=[{"user": user, "channels": [{"channel": DeliveryChannel.BROWSER}]}],
**extra, **extra,
) )
@ -129,7 +129,7 @@ class AttachmentServiceTests(TestCase):
with override_settings(NOTIFY_MAX_ATTACHMENT_BYTES=1): with override_settings(NOTIFY_MAX_ATTACHMENT_BYTES=1):
second = self._browser( second = self._browser(
self.user, self.user,
verb="Other", title="Other",
idempotency_key="approved:9", idempotency_key="approved:9",
attachments=[ContentFile(b"hello", name="late.txt")], attachments=[ContentFile(b"hello", name="late.txt")],
) )
@ -138,15 +138,15 @@ class AttachmentServiceTests(TestCase):
def test_group_copies_files_onto_collapsed_and_new_notifications(self): def test_group_copies_files_onto_collapsed_and_new_notifications(self):
first = create_notification( first = create_notification(
type=self.kind, notification_type=self.kind,
object_id="post-9", content_object=self.user,
group=True, group=True,
recipients=[{"user": self.user, "channels": [{"channel": DeliveryChannel.BROWSER}]}], recipients=[{"user": self.user, "channels": [{"channel": DeliveryChannel.BROWSER}]}],
) )
second = create_notification( second = create_notification(
type=self.kind, notification_type=self.kind,
object_id="post-9", content_object=self.user,
verb="Ещё", title="Ещё",
group=True, group=True,
attachments=[ContentFile(b"note", name="note.txt")], attachments=[ContentFile(b"note", name="note.txt")],
recipients=[ recipients=[
@ -161,8 +161,8 @@ class AttachmentServiceTests(TestCase):
self.assertNotEqual(first.attachments.get().file.name, second.attachments.get().file.name) self.assertNotEqual(first.attachments.get().file.name, second.attachments.get().file.name)
collapsed = create_notification( collapsed = create_notification(
type=self.kind, notification_type=self.kind,
object_id="post-9", content_object=self.user,
group=True, group=True,
attachments=[ContentFile(b"more", name="more.txt")], attachments=[ContentFile(b"more", name="more.txt")],
recipients=[{"user": self.user, "channels": [{"channel": DeliveryChannel.BROWSER}]}], recipients=[{"user": self.user, "channels": [{"channel": DeliveryChannel.BROWSER}]}],
@ -191,19 +191,19 @@ class AttachmentApiTests(TestCase):
def test_list_and_download_are_limited_to_the_recipient(self): def test_list_and_download_are_limited_to_the_recipient(self):
create_notification( create_notification(
verb="With file", title="With file",
attachments=[ContentFile(b"hello", name="report.txt")], attachments=[ContentFile(b"hello", name="report.txt")],
recipients=[{"user": self.user, "channels": [{"channel": DeliveryChannel.BROWSER}]}], recipients=[{"user": self.user, "channels": [{"channel": DeliveryChannel.BROWSER}]}],
) )
create_notification( create_notification(
verb="Foreign", title="Foreign",
attachments=[ContentFile(b"secret", name="secret.txt")], attachments=[ContentFile(b"secret", name="secret.txt")],
recipients=[{"user": self.other, "channels": [{"channel": DeliveryChannel.BROWSER}]}], recipients=[{"user": self.other, "channels": [{"channel": DeliveryChannel.BROWSER}]}],
) )
listing = self.client.get("/api/list/") listing = self.client.get("/api/list/")
self.assertEqual(listing.status_code, 200) self.assertEqual(listing.status_code, 200)
item = listing.json()["results"][0] item = listing.json()["results"][0]
self.assertEqual(item["verb"], "With file") self.assertEqual(item["title"], "With file")
self.assertEqual(len(item["attachments"]), 1) self.assertEqual(len(item["attachments"]), 1)
attachment = item["attachments"][0] attachment = item["attachments"][0]
self.assertEqual(attachment["name"], "report.txt") self.assertEqual(attachment["name"], "report.txt")
@ -227,7 +227,7 @@ class AttachmentApiTests(TestCase):
def test_expired_and_invalid_ids_are_hidden(self): def test_expired_and_invalid_ids_are_hidden(self):
notification = create_notification( notification = create_notification(
verb="Stale", title="Stale",
expires_at=timezone.now() - timedelta(minutes=1), expires_at=timezone.now() - timedelta(minutes=1),
attachments=[ContentFile(b"old", name="old.txt")], attachments=[ContentFile(b"old", name="old.txt")],
recipients=[{"user": self.user, "channels": [{"channel": DeliveryChannel.BROWSER}]}], recipients=[{"user": self.user, "channels": [{"channel": DeliveryChannel.BROWSER}]}],
@ -240,7 +240,7 @@ class AttachmentApiTests(TestCase):
def test_email_recipient_can_download(self): def test_email_recipient_can_download(self):
notification = create_notification( notification = create_notification(
verb="Mail", title="Mail",
attachments=[ContentFile(b"body", name="body.txt")], attachments=[ContentFile(b"body", name="body.txt")],
recipients=[ recipients=[
{ {
@ -272,7 +272,7 @@ class AttachmentEmailTests(TestCase):
def test_email_includes_the_file(self): def test_email_includes_the_file(self):
notification = create_notification( notification = create_notification(
verb="Hello", title="Hello",
description="Body", description="Body",
attachments=[ContentFile(b"pdf-bytes", name="report.pdf")], attachments=[ContentFile(b"pdf-bytes", name="report.pdf")],
recipients=[ recipients=[

View File

@ -89,7 +89,7 @@ class CodeTests(TestCase):
self.assertEqual(post.call_args.kwargs["params"], {"user_id": 7}) self.assertEqual(post.call_args.kwargs["params"], {"user_id": 7})
verification = VerificationCode.objects.get() verification = VerificationCode.objects.get()
self.assertEqual(verification.target_key, "user:7") self.assertEqual(verification.target_key, "user:7")
self.assertEqual(verification.delivery_target, target) self.assertEqual(verification.target, target)
self.assertTrue(verify_code(purpose="login", channel="max", target=target, code=code)) self.assertTrue(verify_code(purpose="login", channel="max", target=target, code=code))
def test_wrong_code_counts_attempt(self): def test_wrong_code_counts_attempt(self):
@ -173,16 +173,16 @@ class CodeTests(TestCase):
def test_custom_template_by_type(self): def test_custom_template_by_type(self):
group = NotificationGroup.objects.create(code="auth", name="Auth") group = NotificationGroup.objects.create(code="auth", name="Auth")
notification_type = NotificationType.objects.create( notification_type = NotificationType.objects.create(
code="otp", name="OTP", verb="OTP", channels=["email"], group=group code="otp", name="OTP", title="OTP", channels=["email"], group=group
) )
NotificationTemplate.objects.create( NotificationTemplate.objects.create(
name="otp-email", name="otp-email",
channel="email", channel="email",
type=notification_type, notification_type=notification_type,
subject_template="Вход для {{ user.username }}", subject="Вход для {{ user.username }}",
body_template="<b>{{ code }}</b> на {{ ttl_minutes }} мин ({{ purpose }})", body="<b>{{ code }}</b> на {{ ttl_minutes }} мин ({{ purpose }})",
) )
code = self._send_email(user=self.user, type="otp") code = self._send_email(user=self.user, notification_type="otp")
message = mail.outbox[-1] message = mail.outbox[-1]
self.assertEqual(message.subject, "Вход для alice") self.assertEqual(message.subject, "Вход для alice")
self.assertEqual(message.body, f"<b>{code}</b> на 5 мин (login)") self.assertEqual(message.body, f"<b>{code}</b> на 5 мин (login)")
@ -192,8 +192,8 @@ class CodeTests(TestCase):
name="default-email", name="default-email",
channel="email", channel="email",
is_default=True, is_default=True,
subject_template="{{ notification.verb }}", subject="{{ notification.title }}",
body_template="{{ notification.description }}", body="{{ notification.description }}",
) )
code = self._send_email() code = self._send_email()
self.assertIn(code, mail.outbox[-1].body) self.assertIn(code, mail.outbox[-1].body)

View File

@ -56,7 +56,7 @@ class DeliveryTests(TestCase):
def _email_recipient(self, **notification_kwargs): def _email_recipient(self, **notification_kwargs):
notification = create_notification( notification = create_notification(
verb=notification_kwargs.pop("verb", "Hello"), title=notification_kwargs.pop("title", "Hello"),
description=notification_kwargs.pop("description", "Body"), description=notification_kwargs.pop("description", "Body"),
recipients=[ recipients=[
{ {
@ -68,19 +68,19 @@ class DeliveryTests(TestCase):
) )
return notification.recipients.get() return notification.recipients.get()
def _max_recipient(self, delivery_target=None): def _max_recipient(self, target=None):
DeliveryTokenConfig.objects.create( DeliveryTokenConfig.objects.create(
name="max", name="max",
channel=DeliveryChannel.MAX, channel=DeliveryChannel.MAX,
is_default=True, is_default=True,
token="token", token="token",
) )
notification = Notification.objects.create(verb="Hello", description="Body") notification = Notification.objects.create(title="Hello", description="Body")
return NotificationRecipient.objects.create( return NotificationRecipient.objects.create(
notification=notification, notification=notification,
user=self.user, user=self.user,
delivery_channel=DeliveryChannel.MAX, channel=DeliveryChannel.MAX,
delivery_target={"chat_id": -10} if delivery_target is None else delivery_target, target={"chat_id": -10} if target is None else target,
) )
def test_email_failure_is_not_marked_sent(self): def test_email_failure_is_not_marked_sent(self):
@ -92,7 +92,7 @@ class DeliveryTests(TestCase):
result = deliver_notification.apply(args=[str(recipient.id)], throw=False) result = deliver_notification.apply(args=[str(recipient.id)], throw=False)
self.assertEqual(result.state, "FAILURE") self.assertEqual(result.state, "FAILURE")
recipient.refresh_from_db() recipient.refresh_from_db()
self.assertEqual(recipient.delivery_status, DeliveryStatus.FAILED) self.assertEqual(recipient.status, DeliveryStatus.FAILED)
self.assertEqual(recipient.attempts, 6) self.assertEqual(recipient.attempts, 6)
self.assertIn("Email delivery failed", recipient.last_error) self.assertIn("Email delivery failed", recipient.last_error)
self.assertIsNone(recipient.sent_at) self.assertIsNone(recipient.sent_at)
@ -104,29 +104,29 @@ class DeliveryTests(TestCase):
result = deliver_notification.apply(args=[str(recipient.id)], throw=False) result = deliver_notification.apply(args=[str(recipient.id)], throw=False)
self.assertEqual(result.state, "FAILURE") self.assertEqual(result.state, "FAILURE")
recipient.refresh_from_db() recipient.refresh_from_db()
self.assertEqual(recipient.delivery_status, DeliveryStatus.FAILED) self.assertEqual(recipient.status, DeliveryStatus.FAILED)
def test_missing_address_is_permanent_failure(self): def test_missing_address_is_permanent_failure(self):
notification = Notification.objects.create(verb="Hello", description="Body") notification = Notification.objects.create(title="Hello", description="Body")
recipient = NotificationRecipient.objects.create( recipient = NotificationRecipient.objects.create(
notification=notification, notification=notification,
user=self.user, user=self.user,
delivery_channel=DeliveryChannel.EMAIL, channel=DeliveryChannel.EMAIL,
delivery_target=None, target=None,
) )
deliver_notification.apply(args=[str(recipient.id)], throw=True) deliver_notification.apply(args=[str(recipient.id)], throw=True)
recipient.refresh_from_db() recipient.refresh_from_db()
self.assertEqual(recipient.delivery_status, DeliveryStatus.FAILED) self.assertEqual(recipient.status, DeliveryStatus.FAILED)
def test_successful_email_is_sent_once_and_escapes_html(self): def test_successful_email_is_sent_once_and_escapes_html(self):
recipient = self._email_recipient( recipient = self._email_recipient(
verb="Hello\r\nBcc: leak", title="Hello\r\nBcc: leak",
description="<script>alert(1)</script>", description="<script>alert(1)</script>",
) )
deliver_notification.apply(args=[str(recipient.id)], throw=True) deliver_notification.apply(args=[str(recipient.id)], throw=True)
deliver_notification.apply(args=[str(recipient.id)], throw=True) deliver_notification.apply(args=[str(recipient.id)], throw=True)
recipient.refresh_from_db() recipient.refresh_from_db()
self.assertEqual(recipient.delivery_status, DeliveryStatus.SENT) self.assertEqual(recipient.status, DeliveryStatus.SENT)
self.assertEqual(recipient.attempts, 1) self.assertEqual(recipient.attempts, 1)
self.assertEqual(recipient.last_error, "") self.assertEqual(recipient.last_error, "")
self.assertIsNotNone(recipient.sent_at) self.assertIsNotNone(recipient.sent_at)
@ -142,13 +142,13 @@ class DeliveryTests(TestCase):
channel=DeliveryChannel.EMAIL, channel=DeliveryChannel.EMAIL,
name="email-default", name="email-default",
is_default=True, is_default=True,
subject_template="{{ notification.verb }}", subject="{{ notification.title }}",
body_template="hash={{ user.password }} verb={{ notification.verb }}", body="hash={{ user.password }} title={{ notification.title }}",
) )
recipient = self._email_recipient(verb="Approved", description="<b>x</b>") recipient = self._email_recipient(title="Approved", description="<b>x</b>")
deliver_notification.apply(args=[str(recipient.id)], throw=True) deliver_notification.apply(args=[str(recipient.id)], throw=True)
body = mail.outbox[0].body body = mail.outbox[0].body
self.assertIn("verb=Approved", body) self.assertIn("title=Approved", body)
self.assertNotIn(self.user.password, body) self.assertNotIn(self.user.password, body)
self.assertNotIn("<b>", body) self.assertNotIn("<b>", body)
@ -159,11 +159,11 @@ class DeliveryTests(TestCase):
name="Approved", name="Approved",
group=group, group=group,
channels=[DeliveryChannel.EMAIL], channels=[DeliveryChannel.EMAIL],
verb="Approved", title="Approved",
) )
with self.assertRaisesMessage(ValueError, "not allowed"): with self.assertRaisesMessage(ValueError, "not allowed"):
create_notification( create_notification(
type="approved", notification_type="approved",
recipients=[ recipients=[
{"user": self.user, "channels": [{"channel": DeliveryChannel.BROWSER}]}, {"user": self.user, "channels": [{"channel": DeliveryChannel.BROWSER}]},
], ],
@ -173,7 +173,7 @@ class DeliveryTests(TestCase):
def test_unknown_channel_does_not_create_recipient(self): def test_unknown_channel_does_not_create_recipient(self):
with self.assertRaisesMessage(ValueError, "No delivery provider"): with self.assertRaisesMessage(ValueError, "No delivery provider"):
create_notification( create_notification(
verb="Ping", title="Ping",
recipients=[ recipients=[
{"user": self.user, "channels": [{"channel": "sms"}]}, {"user": self.user, "channels": [{"channel": "sms"}]},
], ],
@ -188,12 +188,12 @@ class DeliveryTests(TestCase):
name="Approved", name="Approved",
group=group, group=group,
channels=[DeliveryChannel.BROWSER], channels=[DeliveryChannel.BROWSER],
verb="Approved", title="Approved",
is_active=False, is_active=False,
) )
with self.assertRaisesMessage(ValueError, "inactive"): with self.assertRaisesMessage(ValueError, "inactive"):
create_notification( create_notification(
type="approved", notification_type="approved",
recipients=[ recipients=[
{"user": self.user, "channels": [{"channel": DeliveryChannel.BROWSER}]}, {"user": self.user, "channels": [{"channel": DeliveryChannel.BROWSER}]},
], ],
@ -203,7 +203,7 @@ class DeliveryTests(TestCase):
def test_duplicate_channel_rolls_back(self): def test_duplicate_channel_rolls_back(self):
with self.assertRaisesMessage(ValueError, "Duplicate"): with self.assertRaisesMessage(ValueError, "Duplicate"):
create_notification( create_notification(
verb="Ping", title="Ping",
recipients=[ recipients=[
{ {
"user": self.user, "user": self.user,
@ -217,20 +217,20 @@ class DeliveryTests(TestCase):
self.assertEqual(Notification.objects.count(), 0) self.assertEqual(Notification.objects.count(), 0)
def test_recipient_channel_is_unique(self): def test_recipient_channel_is_unique(self):
notification = Notification.objects.create(verb="Hello") notification = Notification.objects.create(title="Hello")
NotificationRecipient.objects.create( NotificationRecipient.objects.create(
notification=notification, notification=notification,
user=self.user, user=self.user,
delivery_channel=DeliveryChannel.EMAIL, channel=DeliveryChannel.EMAIL,
delivery_target={"email": "alice@example.com"}, target={"email": "alice@example.com"},
) )
with self.assertRaises(IntegrityError): with self.assertRaises(IntegrityError):
with transaction.atomic(): with transaction.atomic():
NotificationRecipient.objects.create( NotificationRecipient.objects.create(
notification=notification, notification=notification,
user=self.user, user=self.user,
delivery_channel=DeliveryChannel.EMAIL, channel=DeliveryChannel.EMAIL,
delivery_target={"email": "other@example.com"}, target={"email": "other@example.com"},
) )
def test_max_request_has_timeout_and_retries_server_errors(self): def test_max_request_has_timeout_and_retries_server_errors(self):
@ -240,12 +240,12 @@ class DeliveryTests(TestCase):
is_default=True, is_default=True,
token="token", token="token",
) )
notification = Notification.objects.create(verb="Hello", description="Body") notification = Notification.objects.create(title="Hello", description="Body")
recipient = NotificationRecipient.objects.create( recipient = NotificationRecipient.objects.create(
notification=notification, notification=notification,
user=self.user, user=self.user,
delivery_channel=DeliveryChannel.MAX, channel=DeliveryChannel.MAX,
delivery_target={"chat_id": -10}, target={"chat_id": -10},
) )
response = requests.Response() response = requests.Response()
response.status_code = 503 response.status_code = 503
@ -258,7 +258,7 @@ class DeliveryTests(TestCase):
self.assertGreater(post.call_count, 1) self.assertGreater(post.call_count, 1)
self.assertEqual(post.call_args.kwargs["timeout"], MAX_API_TIMEOUT) self.assertEqual(post.call_args.kwargs["timeout"], MAX_API_TIMEOUT)
recipient.refresh_from_db() recipient.refresh_from_db()
self.assertEqual(recipient.delivery_status, DeliveryStatus.FAILED) self.assertEqual(recipient.status, DeliveryStatus.FAILED)
def test_max_client_error_is_not_retried(self): def test_max_client_error_is_not_retried(self):
DeliveryTokenConfig.objects.create( DeliveryTokenConfig.objects.create(
@ -267,12 +267,12 @@ class DeliveryTests(TestCase):
is_default=True, is_default=True,
token="token", token="token",
) )
notification = Notification.objects.create(verb="Hello", description="Body") notification = Notification.objects.create(title="Hello", description="Body")
recipient = NotificationRecipient.objects.create( recipient = NotificationRecipient.objects.create(
notification=notification, notification=notification,
user=self.user, user=self.user,
delivery_channel=DeliveryChannel.MAX, channel=DeliveryChannel.MAX,
delivery_target={"chat_id": -10}, target={"chat_id": -10},
) )
response = requests.Response() response = requests.Response()
response.status_code = 400 response.status_code = 400
@ -283,7 +283,7 @@ class DeliveryTests(TestCase):
deliver_notification.apply(args=[str(recipient.id)], throw=True) deliver_notification.apply(args=[str(recipient.id)], throw=True)
self.assertEqual(post.call_count, 1) self.assertEqual(post.call_count, 1)
recipient.refresh_from_db() recipient.refresh_from_db()
self.assertEqual(recipient.delivery_status, DeliveryStatus.FAILED) self.assertEqual(recipient.status, DeliveryStatus.FAILED)
def test_second_default_config_replaces_the_first(self): def test_second_default_config_replaces_the_first(self):
second = DeliveryEmailConfig.objects.create( second = DeliveryEmailConfig.objects.create(
@ -323,7 +323,7 @@ class DeliveryTests(TestCase):
def test_expired_notifications_stay_until_the_cleanup_task(self): def test_expired_notifications_stay_until_the_cleanup_task(self):
old = Notification.objects.create( old = Notification.objects.create(
verb="old", title="old",
expires_at=timezone.now() - timedelta(minutes=1), expires_at=timezone.now() - timedelta(minutes=1),
) )
from notify.tasks import delete_expired_notifications from notify.tasks import delete_expired_notifications
@ -333,7 +333,7 @@ class DeliveryTests(TestCase):
self.assertFalse(Notification.objects.filter(pk=old.pk).exists()) self.assertFalse(Notification.objects.filter(pk=old.pk).exists())
def test_cleanup_keeps_notifications_that_have_not_expired(self): def test_cleanup_keeps_notifications_that_have_not_expired(self):
fresh = Notification.objects.create(verb="fresh") fresh = Notification.objects.create(title="fresh")
from notify.tasks import delete_expired_notifications from notify.tasks import delete_expired_notifications
self.assertEqual(delete_expired_notifications(), 0) self.assertEqual(delete_expired_notifications(), 0)
@ -370,23 +370,23 @@ class DeliveryTests(TestCase):
def test_failed_recipient_is_not_sent_again(self): def test_failed_recipient_is_not_sent_again(self):
recipient = self._email_recipient() recipient = self._email_recipient()
recipient.delivery_status = DeliveryStatus.FAILED recipient.status = DeliveryStatus.FAILED
recipient.save(update_fields=["delivery_status"]) recipient.save(update_fields=["status"])
with patch("notify.delivery.providers.email.EmailMessage.send") as send: with patch("notify.delivery.providers.email.EmailMessage.send") as send:
deliver_notification.apply(args=[str(recipient.id)], throw=True) deliver_notification.apply(args=[str(recipient.id)], throw=True)
send.assert_not_called() send.assert_not_called()
self.assertEqual(len(mail.outbox), 0) self.assertEqual(len(mail.outbox), 0)
def test_unknown_channel_fails_without_retry(self): def test_unknown_channel_fails_without_retry(self):
notification = Notification.objects.create(verb="Hello", description="Body") notification = Notification.objects.create(title="Hello", description="Body")
recipient = NotificationRecipient.objects.create( recipient = NotificationRecipient.objects.create(
notification=notification, notification=notification,
user=self.user, user=self.user,
delivery_channel="sms", channel="sms",
) )
deliver_notification.apply(args=[str(recipient.id)], throw=True) deliver_notification.apply(args=[str(recipient.id)], throw=True)
recipient.refresh_from_db() recipient.refresh_from_db()
self.assertEqual(recipient.delivery_status, DeliveryStatus.FAILED) self.assertEqual(recipient.status, DeliveryStatus.FAILED)
def test_invalid_email_message_is_not_retried(self): def test_invalid_email_message_is_not_retried(self):
recipient = self._email_recipient() recipient = self._email_recipient()
@ -397,7 +397,7 @@ class DeliveryTests(TestCase):
deliver_notification.apply(args=[str(recipient.id)], throw=True) deliver_notification.apply(args=[str(recipient.id)], throw=True)
self.assertEqual(send.call_count, 1) self.assertEqual(send.call_count, 1)
recipient.refresh_from_db() recipient.refresh_from_db()
self.assertEqual(recipient.delivery_status, DeliveryStatus.FAILED) self.assertEqual(recipient.status, DeliveryStatus.FAILED)
def test_unaccepted_email_is_retried(self): def test_unaccepted_email_is_retried(self):
recipient = self._email_recipient() recipient = self._email_recipient()
@ -406,7 +406,7 @@ class DeliveryTests(TestCase):
self.assertEqual(result.state, "FAILURE") self.assertEqual(result.state, "FAILURE")
self.assertEqual(send.call_count, 6) self.assertEqual(send.call_count, 6)
recipient.refresh_from_db() recipient.refresh_from_db()
self.assertEqual(recipient.delivery_status, DeliveryStatus.FAILED) self.assertEqual(recipient.status, DeliveryStatus.FAILED)
def test_typed_template_wins_over_the_channel_default(self): def test_typed_template_wins_over_the_channel_default(self):
group = NotificationGroup.objects.create(code="orders", name="Orders") group = NotificationGroup.objects.create(code="orders", name="Orders")
@ -415,25 +415,25 @@ class DeliveryTests(TestCase):
name="Approved", name="Approved",
group=group, group=group,
channels=[DeliveryChannel.EMAIL], channels=[DeliveryChannel.EMAIL],
verb="Approved", title="Approved",
) )
NotificationTemplate.objects.create( NotificationTemplate.objects.create(
channel=DeliveryChannel.EMAIL, channel=DeliveryChannel.EMAIL,
name="email-default", name="email-default",
is_default=True, is_default=True,
subject_template="default {{ notification.verb }}", subject="default {{ notification.title }}",
body_template="DEFAULT {{ notification.url }}", body="DEFAULT {{ notification.url }}",
) )
NotificationTemplate.objects.create( NotificationTemplate.objects.create(
channel=DeliveryChannel.EMAIL, channel=DeliveryChannel.EMAIL,
type=kind, notification_type=kind,
name="approved-email", name="approved-email",
subject_template="typed {{ notification.verb }}", subject="typed {{ notification.title }}",
body_template="TYPED {{ notification.url }}", body="TYPED {{ notification.url }}",
) )
recipient = self._email_recipient( recipient = self._email_recipient(
type=kind, notification_type=kind,
verb="Approved", title="Approved",
url="https://example.com/orders/9", url="https://example.com/orders/9",
description="plain", description="plain",
) )
@ -447,9 +447,9 @@ class DeliveryTests(TestCase):
channel=DeliveryChannel.MAX, channel=DeliveryChannel.MAX,
name="max-only", name="max-only",
is_default=True, is_default=True,
body_template="MAX-ONLY {{ notification.verb }}", body="MAX-ONLY {{ notification.title }}",
) )
recipient = self._email_recipient(verb="Approved", description="plain") recipient = self._email_recipient(title="Approved", description="plain")
deliver_notification.apply(args=[str(recipient.id)], throw=True) deliver_notification.apply(args=[str(recipient.id)], throw=True)
self.assertNotIn("MAX-ONLY", mail.outbox[0].body) self.assertNotIn("MAX-ONLY", mail.outbox[0].body)
self.assertIn("plain", mail.outbox[0].body) self.assertIn("plain", mail.outbox[0].body)
@ -467,7 +467,7 @@ class DeliveryTests(TestCase):
self.assertEqual(post.call_args.kwargs["timeout"], MAX_API_TIMEOUT) self.assertEqual(post.call_args.kwargs["timeout"], MAX_API_TIMEOUT)
self.assertIn("Body", post.call_args.kwargs["json"]["text"]) self.assertIn("Body", post.call_args.kwargs["json"]["text"])
recipient.refresh_from_db() recipient.refresh_from_db()
self.assertEqual(recipient.delivery_status, DeliveryStatus.SENT) self.assertEqual(recipient.status, DeliveryStatus.SENT)
def test_max_without_user_id_uses_chat_id(self): def test_max_without_user_id_uses_chat_id(self):
recipient = self._max_recipient() recipient = self._max_recipient()
@ -477,7 +477,7 @@ class DeliveryTests(TestCase):
deliver_notification.apply(args=[str(recipient.id)], throw=True) deliver_notification.apply(args=[str(recipient.id)], throw=True)
self.assertEqual(post.call_args.kwargs["params"], {"chat_id": -10}) self.assertEqual(post.call_args.kwargs["params"], {"chat_id": -10})
recipient.refresh_from_db() recipient.refresh_from_db()
self.assertEqual(recipient.delivery_status, DeliveryStatus.SENT) self.assertEqual(recipient.status, DeliveryStatus.SENT)
def test_max_without_chat_id_is_permanent(self): def test_max_without_chat_id_is_permanent(self):
recipient = self._max_recipient({}) recipient = self._max_recipient({})
@ -485,20 +485,20 @@ class DeliveryTests(TestCase):
deliver_notification.apply(args=[str(recipient.id)], throw=True) deliver_notification.apply(args=[str(recipient.id)], throw=True)
post.assert_not_called() post.assert_not_called()
recipient.refresh_from_db() recipient.refresh_from_db()
self.assertEqual(recipient.delivery_status, DeliveryStatus.FAILED) self.assertEqual(recipient.status, DeliveryStatus.FAILED)
def test_missing_max_config_is_retried(self): def test_missing_max_config_is_retried(self):
notification = Notification.objects.create(verb="Hello", description="Body") notification = Notification.objects.create(title="Hello", description="Body")
recipient = NotificationRecipient.objects.create( recipient = NotificationRecipient.objects.create(
notification=notification, notification=notification,
user=self.user, user=self.user,
delivery_channel=DeliveryChannel.MAX, channel=DeliveryChannel.MAX,
delivery_target={"chat_id": -10}, target={"chat_id": -10},
) )
result = deliver_notification.apply(args=[str(recipient.id)], throw=False) result = deliver_notification.apply(args=[str(recipient.id)], throw=False)
self.assertEqual(result.state, "FAILURE") self.assertEqual(result.state, "FAILURE")
recipient.refresh_from_db() recipient.refresh_from_db()
self.assertEqual(recipient.delivery_status, DeliveryStatus.FAILED) self.assertEqual(recipient.status, DeliveryStatus.FAILED)
def test_max_timeout_is_retried(self): def test_max_timeout_is_retried(self):
recipient = self._max_recipient() recipient = self._max_recipient()
@ -510,7 +510,7 @@ class DeliveryTests(TestCase):
self.assertEqual(result.state, "FAILURE") self.assertEqual(result.state, "FAILURE")
self.assertEqual(post.call_count, 6) self.assertEqual(post.call_count, 6)
recipient.refresh_from_db() recipient.refresh_from_db()
self.assertEqual(recipient.delivery_status, DeliveryStatus.FAILED) self.assertEqual(recipient.status, DeliveryStatus.FAILED)
def test_max_network_error_is_retried(self): def test_max_network_error_is_retried(self):
recipient = self._max_recipient() recipient = self._max_recipient()
@ -522,7 +522,7 @@ class DeliveryTests(TestCase):
self.assertEqual(result.state, "FAILURE") self.assertEqual(result.state, "FAILURE")
self.assertEqual(post.call_count, 6) self.assertEqual(post.call_count, 6)
recipient.refresh_from_db() recipient.refresh_from_db()
self.assertEqual(recipient.delivery_status, DeliveryStatus.FAILED) self.assertEqual(recipient.status, DeliveryStatus.FAILED)
def test_telegram_message_is_sent_and_marked(self): def test_telegram_message_is_sent_and_marked(self):
DeliveryTokenConfig.objects.create( DeliveryTokenConfig.objects.create(
@ -532,7 +532,7 @@ class DeliveryTests(TestCase):
token="bot-token", token="bot-token",
) )
notification = create_notification( notification = create_notification(
verb="Hello", title="Hello",
description="Body", description="Body",
recipients=[ recipients=[
{ {
@ -555,13 +555,13 @@ class DeliveryTests(TestCase):
self.assertIn("Body", post.call_args.kwargs["json"]["text"]) self.assertIn("Body", post.call_args.kwargs["json"]["text"])
self.assertEqual(post.call_args.kwargs["timeout"], TELEGRAM_API_TIMEOUT) self.assertEqual(post.call_args.kwargs["timeout"], TELEGRAM_API_TIMEOUT)
recipient.refresh_from_db() recipient.refresh_from_db()
self.assertEqual(recipient.delivery_status, DeliveryStatus.SENT) self.assertEqual(recipient.status, DeliveryStatus.SENT)
self.assertEqual(recipient.attempts, 1) self.assertEqual(recipient.attempts, 1)
def test_telegram_requires_target(self): def test_telegram_requires_target(self):
with self.assertRaisesMessage(ValueError, "target is required"): with self.assertRaisesMessage(ValueError, "target is required"):
create_notification( create_notification(
verb="Hi", title="Hi",
recipients=[ recipients=[
{"user": self.user, "channels": [{"channel": DeliveryChannel.TELEGRAM}]}, {"user": self.user, "channels": [{"channel": DeliveryChannel.TELEGRAM}]},
], ],
@ -575,12 +575,12 @@ class DeliveryTests(TestCase):
is_default=True, is_default=True,
token="bot-token", token="bot-token",
) )
notification = Notification.objects.create(verb="Hello", description="Body") notification = Notification.objects.create(title="Hello", description="Body")
recipient = NotificationRecipient.objects.create( recipient = NotificationRecipient.objects.create(
notification=notification, notification=notification,
user=self.user, user=self.user,
delivery_channel=DeliveryChannel.TELEGRAM, channel=DeliveryChannel.TELEGRAM,
delivery_target={"chat_id": 42}, target={"chat_id": 42},
) )
response = requests.Response() response = requests.Response()
response.status_code = 400 response.status_code = 400
@ -591,7 +591,7 @@ class DeliveryTests(TestCase):
deliver_notification.apply(args=[str(recipient.id)], throw=True) deliver_notification.apply(args=[str(recipient.id)], throw=True)
self.assertEqual(post.call_count, 1) self.assertEqual(post.call_count, 1)
recipient.refresh_from_db() recipient.refresh_from_db()
self.assertEqual(recipient.delivery_status, DeliveryStatus.FAILED) self.assertEqual(recipient.status, DeliveryStatus.FAILED)
self.assertEqual(recipient.attempts, 1) self.assertEqual(recipient.attempts, 1)
self.assertIn("400", recipient.last_error) self.assertIn("400", recipient.last_error)
@ -602,12 +602,12 @@ class DeliveryTests(TestCase):
is_default=True, is_default=True,
token="bot-token", token="bot-token",
) )
notification = Notification.objects.create(verb="Hello", description="Body") notification = Notification.objects.create(title="Hello", description="Body")
recipient = NotificationRecipient.objects.create( recipient = NotificationRecipient.objects.create(
notification=notification, notification=notification,
user=self.user, user=self.user,
delivery_channel=DeliveryChannel.TELEGRAM, channel=DeliveryChannel.TELEGRAM,
delivery_target={"chat_id": 42}, target={"chat_id": 42},
) )
with patch( with patch(
"notify.delivery.providers.telegram.requests.post", "notify.delivery.providers.telegram.requests.post",
@ -617,7 +617,7 @@ class DeliveryTests(TestCase):
self.assertEqual(result.state, "FAILURE") self.assertEqual(result.state, "FAILURE")
self.assertEqual(post.call_count, 6) self.assertEqual(post.call_count, 6)
recipient.refresh_from_db() recipient.refresh_from_db()
self.assertEqual(recipient.delivery_status, DeliveryStatus.FAILED) self.assertEqual(recipient.status, DeliveryStatus.FAILED)
self.assertEqual(recipient.attempts, 6) self.assertEqual(recipient.attempts, 6)
def test_markdown_filter_renders_fenced_code(self): def test_markdown_filter_renders_fenced_code(self):

View File

@ -78,7 +78,7 @@ class ModelTests(TestCase):
) )
def test_relative_url_keeps_only_the_path(self): def test_relative_url_keeps_only_the_path(self):
note = Notification(verb="Hi", url="https://example.com/orders/1?x=1") note = Notification(title="Hi", url="https://example.com/orders/1?x=1")
self.assertEqual(note.relative_url, "/orders/1") self.assertEqual(note.relative_url, "/orders/1")
note.url = "/inbox" note.url = "/inbox"
self.assertEqual(note.relative_url, "/inbox") self.assertEqual(note.relative_url, "/inbox")
@ -87,35 +87,35 @@ class ModelTests(TestCase):
self.assertEqual(str(note), "Hi") self.assertEqual(str(note), "Hi")
def test_default_expiry_is_about_thirty_days(self): def test_default_expiry_is_about_thirty_days(self):
note = Notification.objects.create(verb="Hi") note = Notification.objects.create(title="Hi")
remaining = note.expires_at - timezone.now() remaining = note.expires_at - timezone.now()
self.assertGreater(remaining, timedelta(days=29)) self.assertGreater(remaining, timedelta(days=29))
self.assertLess(remaining, timedelta(days=31)) self.assertLess(remaining, timedelta(days=31))
def test_browser_recipient_is_sent_on_save(self): def test_browser_recipient_is_sent_on_save(self):
note = Notification.objects.create(verb="Hi") note = Notification.objects.create(title="Hi")
recipient = NotificationRecipient.objects.create( recipient = NotificationRecipient.objects.create(
notification=note, notification=note,
user=self.user, user=self.user,
delivery_channel=DeliveryChannel.BROWSER, channel=DeliveryChannel.BROWSER,
delivery_status=DeliveryStatus.UNSENT, status=DeliveryStatus.UNSENT,
) )
self.assertEqual(recipient.delivery_status, DeliveryStatus.SENT) self.assertEqual(recipient.status, DeliveryStatus.SENT)
self.assertEqual(str(recipient), f"{DeliveryChannel.BROWSER} ({DeliveryStatus.SENT})") self.assertEqual(str(recipient), f"{DeliveryChannel.BROWSER} ({DeliveryStatus.SENT})")
def test_read_flags(self): def test_read_flags(self):
note = Notification.objects.create(verb="Hi") note = Notification.objects.create(title="Hi")
recipient = NotificationRecipient.objects.create( recipient = NotificationRecipient.objects.create(
notification=note, notification=note,
user=self.user, user=self.user,
delivery_channel=DeliveryChannel.EMAIL, channel=DeliveryChannel.EMAIL,
delivery_target={"email": "alice@example.com"}, target={"email": "alice@example.com"},
) )
self.assertIn("alice@example.com", str(recipient)) self.assertIn("alice@example.com", str(recipient))
recipient.make_read() recipient.make_read()
recipient.refresh_from_db() recipient.refresh_from_db()
self.assertFalse(recipient.unread) self.assertFalse(recipient.unread)
self.assertEqual(recipient.delivery_status, DeliveryStatus.UNSENT) self.assertEqual(recipient.status, DeliveryStatus.UNSENT)
recipient.make_unread() recipient.make_unread()
recipient.refresh_from_db() recipient.refresh_from_db()
self.assertTrue(recipient.unread) self.assertTrue(recipient.unread)
@ -125,13 +125,13 @@ class ModelTests(TestCase):
channel=DeliveryChannel.EMAIL, channel=DeliveryChannel.EMAIL,
name="first", name="first",
is_default=True, is_default=True,
body_template="A", body="A",
) )
second = NotificationTemplate.objects.create( second = NotificationTemplate.objects.create(
channel=DeliveryChannel.EMAIL, channel=DeliveryChannel.EMAIL,
name="second", name="second",
is_default=True, is_default=True,
body_template="B", body="B",
) )
first.refresh_from_db() first.refresh_from_db()
self.assertFalse(first.is_default) self.assertFalse(first.is_default)
@ -145,14 +145,14 @@ class ModelTests(TestCase):
channel=DeliveryChannel.EMAIL, channel=DeliveryChannel.EMAIL,
name="fallback", name="fallback",
is_default=True, is_default=True,
body_template="FALLBACK", body="FALLBACK",
) )
typed = NotificationTemplate.objects.create( typed = NotificationTemplate.objects.create(
channel=DeliveryChannel.EMAIL, channel=DeliveryChannel.EMAIL,
type=kind, notification_type=kind,
name="approved-email", name="approved-email",
is_default=True, is_default=True,
body_template="TYPED", body="TYPED",
) )
fallback.refresh_from_db() fallback.refresh_from_db()
self.assertTrue(fallback.is_default) self.assertTrue(fallback.is_default)
@ -167,10 +167,10 @@ class ModelTests(TestCase):
template = NotificationTemplate( template = NotificationTemplate(
channel=DeliveryChannel.EMAIL, channel=DeliveryChannel.EMAIL,
name="t", name="t",
subject_template="Hello {{ user.username }}", subject="Hello {{ user.username }}",
body_template="{{ notification.verb }}", body="{{ notification.title }}",
) )
context = {"user": {"username": "alice"}, "notification": {"verb": "Go"}} context = {"user": {"username": "alice"}, "notification": {"title": "Go"}}
self.assertEqual(template.render_subject(context), "Hello alice") self.assertEqual(template.render_subject(context), "Hello alice")
self.assertEqual(template.render_body(context), "Go") self.assertEqual(template.render_body(context), "Go")
self.assertEqual(str(template), "t") self.assertEqual(str(template), "t")
@ -179,9 +179,9 @@ class ModelTests(TestCase):
template = NotificationTemplate( template = NotificationTemplate(
channel=DeliveryChannel.EMAIL, channel=DeliveryChannel.EMAIL,
name="t", name="t",
body_template="{{ notification.verb }}", body="{{ notification.title }}",
) )
rendered = template.render_body({"notification": {"verb": "<script>alert(1)</script>"}}) rendered = template.render_body({"notification": {"title": "<script>alert(1)</script>"}})
self.assertNotIn("<script>", rendered) self.assertNotIn("<script>", rendered)
self.assertIn("&lt;script&gt;", rendered) self.assertIn("&lt;script&gt;", rendered)
@ -189,7 +189,7 @@ class ModelTests(TestCase):
template = NotificationTemplate( template = NotificationTemplate(
channel=DeliveryChannel.EMAIL, channel=DeliveryChannel.EMAIL,
name="t", name="t",
body_template="[{{ notification.url }}]", body="[{{ notification.url }}]",
) )
self.assertEqual(template.render_body({"notification": {}}), "[]") self.assertEqual(template.render_body({"notification": {}}), "[]")

View File

@ -2,6 +2,7 @@ from datetime import timedelta
from unittest.mock import patch from unittest.mock import patch
from django.contrib.auth import get_user_model from django.contrib.auth import get_user_model
from django.contrib.auth.models import Group
from django.core import mail from django.core import mail
from django.test import TestCase from django.test import TestCase
from django.utils import timezone from django.utils import timezone
@ -31,43 +32,45 @@ class CreateNotificationTests(TestCase):
name="Approved", name="Approved",
group=self.group, group=self.group,
channels=[DeliveryChannel.EMAIL, DeliveryChannel.BROWSER, DeliveryChannel.MAX], channels=[DeliveryChannel.EMAIL, DeliveryChannel.BROWSER, DeliveryChannel.MAX],
verb="Approved", title="Approved",
) )
def test_type_supplies_the_verb_and_links_the_row(self): def test_type_supplies_the_verb_and_links_the_row(self):
notification = create_notification( notification = create_notification(
type=self.kind, notification_type=self.kind,
recipients=[ recipients=[
{"user": self.user, "channels": [{"channel": DeliveryChannel.BROWSER}]}, {"user": self.user, "channels": [{"channel": DeliveryChannel.BROWSER}]},
], ],
) )
self.assertEqual(notification.verb, "Approved") self.assertEqual(notification.title, "Approved")
self.assertEqual(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.assertIsNone(notification.content_type)
self.assertEqual(notification.object_id, "") self.assertEqual(notification.object_id, "")
self.assertIsNone(notification.content_object)
recipient = notification.recipients.get() recipient = notification.recipients.get()
self.assertEqual(recipient.delivery_status, DeliveryStatus.SENT) self.assertEqual(recipient.status, DeliveryStatus.SENT)
self.assertTrue(recipient.unread) self.assertTrue(recipient.unread)
def test_code_resolves_to_the_same_type(self): def test_code_resolves_to_the_same_type(self):
notification = create_notification( notification = create_notification(
type="approved", notification_type="approved",
recipients=[ recipients=[
{"user": self.user, "channels": [{"channel": DeliveryChannel.BROWSER}]}, {"user": self.user, "channels": [{"channel": DeliveryChannel.BROWSER}]},
], ],
) )
self.assertEqual(notification.type, self.kind) self.assertEqual(notification.notification_type, self.kind)
self.assertEqual(notification.verb, "Approved") self.assertEqual(notification.title, "Approved")
def test_explicit_fields_override_the_type(self): def test_explicit_fields_override_the_type(self):
when = timezone.now() + timedelta(days=2) when = timezone.now() + timedelta(days=2)
notification = create_notification( notification = create_notification(
type="approved", notification_type="approved",
verb="Custom", title="Custom",
url="https://example.com/orders/9?x=1", url="https://example.com/orders/9?x=1",
level=NotificationLevel.ERROR, level=NotificationLevel.ERROR,
object_id="9", content_object=self.other,
description="Done", description="Done",
data={"n": 1}, data={"n": 1},
expires_at=when, expires_at=when,
@ -75,21 +78,22 @@ class CreateNotificationTests(TestCase):
{"user": self.user, "channels": [{"channel": DeliveryChannel.BROWSER}]}, {"user": self.user, "channels": [{"channel": DeliveryChannel.BROWSER}]},
], ],
) )
self.assertEqual(notification.verb, "Custom") self.assertEqual(notification.title, "Custom")
self.assertEqual(notification.url, "https://example.com/orders/9?x=1") self.assertEqual(notification.url, "https://example.com/orders/9?x=1")
self.assertEqual(notification.relative_url, "/orders/9") self.assertEqual(notification.relative_url, "/orders/9")
self.assertEqual(notification.level, NotificationLevel.ERROR) self.assertEqual(notification.level, NotificationLevel.ERROR)
self.assertEqual(notification.object_id, "9") self.assertEqual(notification.content_object, self.other)
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.assertEqual(notification.expires_at, when) self.assertEqual(notification.expires_at, when)
def test_verb_is_required(self): def test_title_is_required(self):
self.kind.verb = "" self.kind.title = ""
self.kind.save(update_fields=["verb"]) self.kind.save(update_fields=["title"])
with self.assertRaisesMessage(ValueError, "verb is required"): with self.assertRaisesMessage(ValueError, "title is required"):
create_notification( create_notification(
type="approved", notification_type="approved",
recipients=[ recipients=[
{"user": self.user, "channels": [{"channel": DeliveryChannel.BROWSER}]}, {"user": self.user, "channels": [{"channel": DeliveryChannel.BROWSER}]},
], ],
@ -99,8 +103,8 @@ class CreateNotificationTests(TestCase):
def test_unknown_type_creates_nothing(self): def test_unknown_type_creates_nothing(self):
with self.assertRaises(NotificationType.DoesNotExist): with self.assertRaises(NotificationType.DoesNotExist):
create_notification( create_notification(
type="missing", notification_type="missing",
verb="Hi", title="Hi",
recipients=[ recipients=[
{"user": self.user, "channels": [{"channel": DeliveryChannel.BROWSER}]}, {"user": self.user, "channels": [{"channel": DeliveryChannel.BROWSER}]},
], ],
@ -109,13 +113,13 @@ class CreateNotificationTests(TestCase):
def test_empty_recipient_list_is_rejected(self): def test_empty_recipient_list_is_rejected(self):
with self.assertRaisesMessage(ValueError, "At least one recipient"): with self.assertRaisesMessage(ValueError, "At least one recipient"):
create_notification(verb="Hi", recipients=[]) create_notification(title="Hi", recipients=[])
self.assertEqual(Notification.objects.count(), 0) self.assertEqual(Notification.objects.count(), 0)
def test_recipient_without_channels_rolls_back(self): def test_recipient_without_channels_rolls_back(self):
with self.assertRaisesMessage(ValueError, "no channels"): with self.assertRaisesMessage(ValueError, "no channels"):
create_notification( create_notification(
verb="Hi", title="Hi",
recipients=[ recipients=[
{"user": self.user, "channels": [{"channel": DeliveryChannel.BROWSER}]}, {"user": self.user, "channels": [{"channel": DeliveryChannel.BROWSER}]},
{"user": self.other, "channels": []}, {"user": self.other, "channels": []},
@ -127,7 +131,7 @@ class CreateNotificationTests(TestCase):
def test_same_user_and_channel_twice_rolls_back(self): def test_same_user_and_channel_twice_rolls_back(self):
with self.assertRaisesMessage(ValueError, "Duplicate"): with self.assertRaisesMessage(ValueError, "Duplicate"):
create_notification( create_notification(
verb="Hi", title="Hi",
recipients=[ recipients=[
{"user": self.user, "channels": [{"channel": DeliveryChannel.BROWSER}]}, {"user": self.user, "channels": [{"channel": DeliveryChannel.BROWSER}]},
{"user": self.user, "channels": [{"channel": DeliveryChannel.BROWSER}]}, {"user": self.user, "channels": [{"channel": DeliveryChannel.BROWSER}]},
@ -137,7 +141,7 @@ class CreateNotificationTests(TestCase):
def test_each_user_gets_a_recipient(self): def test_each_user_gets_a_recipient(self):
notification = create_notification( notification = create_notification(
verb="Hi", title="Hi",
recipients=[ recipients=[
{"user": self.user, "channels": [{"channel": DeliveryChannel.BROWSER}]}, {"user": self.user, "channels": [{"channel": DeliveryChannel.BROWSER}]},
{"user": self.other, "channels": [{"channel": DeliveryChannel.BROWSER}]}, {"user": self.other, "channels": [{"channel": DeliveryChannel.BROWSER}]},
@ -151,7 +155,7 @@ class CreateNotificationTests(TestCase):
def test_invalid_email_rolls_back(self): def test_invalid_email_rolls_back(self):
with self.assertRaisesMessage(ValueError, "valid email"): with self.assertRaisesMessage(ValueError, "valid email"):
create_notification( create_notification(
verb="Hi", title="Hi",
recipients=[ recipients=[
{ {
"user": self.user, "user": self.user,
@ -168,7 +172,7 @@ class CreateNotificationTests(TestCase):
def test_blank_email_is_rejected(self): def test_blank_email_is_rejected(self):
with self.assertRaisesMessage(ValueError, "valid email"): with self.assertRaisesMessage(ValueError, "valid email"):
create_notification( create_notification(
verb="Hi", title="Hi",
recipients=[ recipients=[
{ {
"user": self.user, "user": self.user,
@ -181,7 +185,7 @@ class CreateNotificationTests(TestCase):
def test_email_requires_target(self): def test_email_requires_target(self):
with self.assertRaisesMessage(ValueError, "target is required"): with self.assertRaisesMessage(ValueError, "target is required"):
create_notification( create_notification(
verb="Hi", title="Hi",
recipients=[ recipients=[
{"user": self.user, "channels": [{"channel": DeliveryChannel.EMAIL}]}, {"user": self.user, "channels": [{"channel": DeliveryChannel.EMAIL}]},
], ],
@ -190,7 +194,7 @@ class CreateNotificationTests(TestCase):
def test_email_target_is_stored(self): def test_email_target_is_stored(self):
notification = create_notification( notification = create_notification(
verb="Hi", title="Hi",
recipients=[ recipients=[
{ {
"user": self.user, "user": self.user,
@ -198,12 +202,12 @@ class CreateNotificationTests(TestCase):
} }
], ],
) )
self.assertEqual(notification.recipients.get().delivery_target, {"email": "alice@example.com"}) self.assertEqual(notification.recipients.get().target, {"email": "alice@example.com"})
def test_browser_rejects_target(self): def test_browser_rejects_target(self):
with self.assertRaisesMessage(ValueError, "target is not supported"): with self.assertRaisesMessage(ValueError, "target is not supported"):
create_notification( create_notification(
verb="Hi", title="Hi",
recipients=[ recipients=[
{ {
"user": self.user, "user": self.user,
@ -215,7 +219,7 @@ class CreateNotificationTests(TestCase):
def test_max_chat_is_stored(self): def test_max_chat_is_stored(self):
notification = create_notification( notification = create_notification(
verb="Hi", title="Hi",
recipients=[ recipients=[
{ {
"user": self.user, "user": self.user,
@ -224,14 +228,14 @@ class CreateNotificationTests(TestCase):
], ],
) )
self.assertEqual( self.assertEqual(
notification.recipients.get().delivery_target, notification.recipients.get().target,
{"chat_id": -5, "user_id": None}, {"chat_id": -5, "user_id": None},
) )
self.assertEqual(notification.recipients.get().delivery_status, DeliveryStatus.UNSENT) self.assertEqual(notification.recipients.get().status, DeliveryStatus.UNSENT)
def test_max_user_and_chat_are_stored(self): def test_max_user_and_chat_are_stored(self):
notification = create_notification( notification = create_notification(
verb="Hi", title="Hi",
recipients=[ recipients=[
{ {
"user": self.other, "user": self.other,
@ -245,14 +249,14 @@ class CreateNotificationTests(TestCase):
], ],
) )
self.assertEqual( self.assertEqual(
notification.recipients.get().delivery_target, notification.recipients.get().target,
{"chat_id": 3, "user_id": 8}, {"chat_id": 3, "user_id": 8},
) )
def test_max_requires_target(self): def test_max_requires_target(self):
with self.assertRaisesMessage(ValueError, "target is required"): with self.assertRaisesMessage(ValueError, "target is required"):
create_notification( create_notification(
verb="Hi", title="Hi",
recipients=[ recipients=[
{"user": self.user, "channels": [{"channel": DeliveryChannel.MAX}]}, {"user": self.user, "channels": [{"channel": DeliveryChannel.MAX}]},
], ],
@ -262,7 +266,7 @@ class CreateNotificationTests(TestCase):
def test_max_rejects_a_positive_chat_without_user(self): def test_max_rejects_a_positive_chat_without_user(self):
with self.assertRaisesMessage(ValueError, "negative"): with self.assertRaisesMessage(ValueError, "negative"):
create_notification( create_notification(
verb="Hi", title="Hi",
recipients=[ recipients=[
{ {
"user": self.user, "user": self.user,
@ -275,7 +279,7 @@ class CreateNotificationTests(TestCase):
def test_max_rejects_a_non_positive_pair(self): def test_max_rejects_a_non_positive_pair(self):
with self.assertRaisesMessage(ValueError, "positive"): with self.assertRaisesMessage(ValueError, "positive"):
create_notification( create_notification(
verb="Hi", title="Hi",
recipients=[ recipients=[
{ {
"user": self.user, "user": self.user,
@ -299,7 +303,7 @@ class DeliveryEnqueueTests(TestCase):
with patch("notify.tasks.deliver_notification.apply_async") as apply_async: with patch("notify.tasks.deliver_notification.apply_async") as apply_async:
with self.captureOnCommitCallbacks(execute=True): with self.captureOnCommitCallbacks(execute=True):
notification = create_notification( notification = create_notification(
verb="Hi", title="Hi",
recipients=[ recipients=[
{ {
"user": self.user, "user": self.user,
@ -313,10 +317,10 @@ class DeliveryEnqueueTests(TestCase):
} }
], ],
) )
email = notification.recipients.get(delivery_channel=DeliveryChannel.EMAIL) email = notification.recipients.get(channel=DeliveryChannel.EMAIL)
browser = notification.recipients.get(delivery_channel=DeliveryChannel.BROWSER) browser = notification.recipients.get(channel=DeliveryChannel.BROWSER)
self.assertEqual(email.delivery_status, DeliveryStatus.UNSENT) self.assertEqual(email.status, DeliveryStatus.UNSENT)
self.assertEqual(browser.delivery_status, DeliveryStatus.SENT) self.assertEqual(browser.status, DeliveryStatus.SENT)
apply_async.assert_called_once_with(args=(str(email.id),)) apply_async.assert_called_once_with(args=(str(email.id),))
self.assertEqual(len(mail.outbox), 0) self.assertEqual(len(mail.outbox), 0)
@ -324,7 +328,7 @@ class DeliveryEnqueueTests(TestCase):
with patch("notify.tasks.deliver_notification.apply_async") as apply_async: with patch("notify.tasks.deliver_notification.apply_async") as apply_async:
with self.captureOnCommitCallbacks(execute=True): with self.captureOnCommitCallbacks(execute=True):
create_notification( create_notification(
verb="Hi", title="Hi",
recipients=[ recipients=[
{"user": self.user, "channels": [{"channel": DeliveryChannel.BROWSER}]}, {"user": self.user, "channels": [{"channel": DeliveryChannel.BROWSER}]},
], ],
@ -336,7 +340,7 @@ class DeliveryEnqueueTests(TestCase):
with self.captureOnCommitCallbacks(execute=True): with self.captureOnCommitCallbacks(execute=True):
with self.assertRaisesMessage(ValueError, "Duplicate"): with self.assertRaisesMessage(ValueError, "Duplicate"):
create_notification( create_notification(
verb="Hi", title="Hi",
recipients=[ recipients=[
{ {
"user": self.user, "user": self.user,
@ -367,19 +371,19 @@ class ChannelPreferenceTests(TestCase):
name="Approved", name="Approved",
group=self.group, group=self.group,
channels=[DeliveryChannel.EMAIL, DeliveryChannel.BROWSER], channels=[DeliveryChannel.EMAIL, DeliveryChannel.BROWSER],
verb="Approved", title="Approved",
configurable=True, is_configurable=True,
) )
def test_disabled_channel_is_omitted_and_an_empty_result_rolls_back(self): def test_disabled_channel_is_omitted_and_an_empty_result_rolls_back(self):
NotificationChannelPreference.objects.create( NotificationChannelPreference.objects.create(
user=self.user, user=self.user,
type=self.kind, notification_type=self.kind,
channel=DeliveryChannel.EMAIL, channel=DeliveryChannel.EMAIL,
enabled=False, is_enabled=False,
) )
notification = create_notification( notification = create_notification(
type="approved", notification_type="approved",
recipients=[ recipients=[
{ {
"user": self.user, "user": self.user,
@ -391,19 +395,19 @@ class ChannelPreferenceTests(TestCase):
], ],
) )
self.assertEqual( self.assertEqual(
list(notification.recipients.values_list("delivery_channel", flat=True)), list(notification.recipients.values_list("channel", flat=True)),
[DeliveryChannel.BROWSER], [DeliveryChannel.BROWSER],
) )
NotificationChannelPreference.objects.create( NotificationChannelPreference.objects.create(
user=self.user, user=self.user,
type=self.kind, notification_type=self.kind,
channel=DeliveryChannel.BROWSER, channel=DeliveryChannel.BROWSER,
enabled=False, is_enabled=False,
) )
with self.assertRaisesMessage(ValueError, "No recipients to deliver"): with self.assertRaisesMessage(ValueError, "No recipients to deliver"):
create_notification( create_notification(
type="approved", notification_type="approved",
recipients=[ recipients=[
{"user": self.user, "channels": [{"channel": DeliveryChannel.BROWSER}]}, {"user": self.user, "channels": [{"channel": DeliveryChannel.BROWSER}]},
], ],
@ -412,7 +416,7 @@ class ChannelPreferenceTests(TestCase):
def test_missing_preference_keeps_the_channel(self): def test_missing_preference_keeps_the_channel(self):
notification = create_notification( notification = create_notification(
type="approved", notification_type="approved",
recipients=[ recipients=[
{ {
"user": self.user, "user": self.user,
@ -422,21 +426,21 @@ class ChannelPreferenceTests(TestCase):
} }
], ],
) )
self.assertEqual(notification.recipients.get().delivery_channel, DeliveryChannel.EMAIL) self.assertEqual(notification.recipients.get().channel, DeliveryChannel.EMAIL)
def test_missing_preference_drops_a_channel_disabled_by_default(self): def test_missing_preference_drops_a_channel_disabled_by_default(self):
self.kind.enabled_by_default = False self.kind.is_enabled_by_default = False
self.kind.save(update_fields=["enabled_by_default"]) self.kind.save(update_fields=["is_enabled_by_default"])
self.assertEqual( self.assertEqual(
channel_preferences(self.user)[0]["channels"], channel_preferences(self.user)[0]["channels"],
[ [
{"channel": DeliveryChannel.EMAIL, "enabled": False}, {"channel": DeliveryChannel.EMAIL, "is_enabled": False},
{"channel": DeliveryChannel.BROWSER, "enabled": False}, {"channel": DeliveryChannel.BROWSER, "is_enabled": False},
], ],
) )
with self.assertRaisesMessage(ValueError, "No recipients to deliver"): with self.assertRaisesMessage(ValueError, "No recipients to deliver"):
create_notification( create_notification(
type="approved", notification_type="approved",
recipients=[ recipients=[
{ {
"user": self.user, "user": self.user,
@ -450,12 +454,12 @@ class ChannelPreferenceTests(TestCase):
NotificationChannelPreference.objects.create( NotificationChannelPreference.objects.create(
user=self.user, user=self.user,
type=self.kind, notification_type=self.kind,
channel=DeliveryChannel.EMAIL, channel=DeliveryChannel.EMAIL,
enabled=True, is_enabled=True,
) )
notification = create_notification( notification = create_notification(
type="approved", notification_type="approved",
recipients=[ recipients=[
{ {
"user": self.user, "user": self.user,
@ -465,19 +469,19 @@ class ChannelPreferenceTests(TestCase):
} }
], ],
) )
self.assertEqual(notification.recipients.get().delivery_channel, DeliveryChannel.EMAIL) self.assertEqual(notification.recipients.get().channel, DeliveryChannel.EMAIL)
def test_locked_type_ignores_a_disabled_preference(self): def test_locked_type_ignores_a_disabled_preference(self):
self.kind.configurable = False self.kind.is_configurable = False
self.kind.save(update_fields=["configurable"]) self.kind.save(update_fields=["is_configurable"])
NotificationChannelPreference.objects.create( NotificationChannelPreference.objects.create(
user=self.user, user=self.user,
type=self.kind, notification_type=self.kind,
channel=DeliveryChannel.EMAIL, channel=DeliveryChannel.EMAIL,
enabled=False, is_enabled=False,
) )
notification = create_notification( notification = create_notification(
type="approved", notification_type="approved",
recipients=[ recipients=[
{ {
"user": self.user, "user": self.user,
@ -487,7 +491,7 @@ class ChannelPreferenceTests(TestCase):
} }
], ],
) )
self.assertEqual(notification.recipients.get().delivery_channel, DeliveryChannel.EMAIL) self.assertEqual(notification.recipients.get().channel, DeliveryChannel.EMAIL)
def test_preference_screen_reads_and_writes_switchable_channels(self): def test_preference_screen_reads_and_writes_switchable_channels(self):
hidden = NotificationType.objects.create( hidden = NotificationType.objects.create(
@ -495,7 +499,7 @@ class ChannelPreferenceTests(TestCase):
name="Security", name="Security",
group=self.group, group=self.group,
channels=[DeliveryChannel.EMAIL], channels=[DeliveryChannel.EMAIL],
configurable=False, is_configurable=False,
) )
self.assertEqual( self.assertEqual(
channel_preferences(self.user), channel_preferences(self.user),
@ -503,8 +507,8 @@ class ChannelPreferenceTests(TestCase):
{ {
"code": "approved", "code": "approved",
"channels": [ "channels": [
{"channel": DeliveryChannel.EMAIL, "enabled": True}, {"channel": DeliveryChannel.EMAIL, "is_enabled": True},
{"channel": DeliveryChannel.BROWSER, "enabled": True}, {"channel": DeliveryChannel.BROWSER, "is_enabled": True},
], ],
} }
], ],
@ -515,8 +519,8 @@ class ChannelPreferenceTests(TestCase):
{ {
"code": "approved", "code": "approved",
"channels": [ "channels": [
{"channel": DeliveryChannel.EMAIL, "enabled": False}, {"channel": DeliveryChannel.EMAIL, "is_enabled": False},
{"channel": DeliveryChannel.BROWSER, "enabled": True}, {"channel": DeliveryChannel.BROWSER, "is_enabled": True},
], ],
} }
], ],
@ -524,20 +528,20 @@ class ChannelPreferenceTests(TestCase):
self.assertFalse( self.assertFalse(
NotificationChannelPreference.objects.get( NotificationChannelPreference.objects.get(
user=self.user, user=self.user,
type=self.kind, notification_type=self.kind,
channel=DeliveryChannel.EMAIL, channel=DeliveryChannel.EMAIL,
).enabled ).is_enabled
) )
self.assertEqual(channel_preferences(self.user)[0]["channels"][0]["enabled"], False) self.assertEqual(channel_preferences(self.user)[0]["channels"][0]["is_enabled"], False)
with self.assertRaisesMessage(ValueError, "not allowed"): with self.assertRaisesMessage(ValueError, "not allowed"):
save_channel_preferences( save_channel_preferences(
self.user, self.user,
[{"code": "approved", "channels": [{"channel": DeliveryChannel.MAX, "enabled": True}]}], [{"code": "approved", "channels": [{"channel": DeliveryChannel.MAX, "is_enabled": True}]}],
) )
with self.assertRaises(NotificationType.DoesNotExist): with self.assertRaises(NotificationType.DoesNotExist):
save_channel_preferences( save_channel_preferences(
self.user, self.user,
[{"code": hidden.code, "channels": [{"channel": DeliveryChannel.EMAIL, "enabled": False}]}], [{"code": hidden.code, "channels": [{"channel": DeliveryChannel.EMAIL, "is_enabled": False}]}],
) )
@ -550,7 +554,7 @@ class GroupingAndIdempotencyTests(TestCase):
name="Comment", name="Comment",
group=self.group, group=self.group,
channels=[DeliveryChannel.BROWSER, DeliveryChannel.EMAIL], channels=[DeliveryChannel.BROWSER, DeliveryChannel.EMAIL],
verb="Comment", title="Comment",
) )
def _recipients(self): def _recipients(self):
@ -568,18 +572,18 @@ class GroupingAndIdempotencyTests(TestCase):
with patch("notify.tasks.deliver_notification.apply_async") as apply_async: with patch("notify.tasks.deliver_notification.apply_async") as apply_async:
with self.captureOnCommitCallbacks(execute=True): with self.captureOnCommitCallbacks(execute=True):
first = create_notification( first = create_notification(
type=self.kind, notification_type=self.kind,
object_id="post-9", content_object=self.user,
verb="Новый комментарий", title="Новый комментарий",
group=True, group=True,
recipients=self._recipients(), recipients=self._recipients(),
) )
self.assertEqual(apply_async.call_count, 1) self.assertEqual(apply_async.call_count, 1)
with self.captureOnCommitCallbacks(execute=True): with self.captureOnCommitCallbacks(execute=True):
second = create_notification( second = create_notification(
type=self.kind, notification_type=self.kind,
object_id="post-9", content_object=self.user,
verb="Ещё комментарий", title="Ещё комментарий",
group=True, group=True,
recipients=self._recipients(), recipients=self._recipients(),
) )
@ -587,21 +591,48 @@ class GroupingAndIdempotencyTests(TestCase):
self.assertEqual(second.pk, first.pk) self.assertEqual(second.pk, first.pk)
second.refresh_from_db() second.refresh_from_db()
self.assertEqual(second.data["count"], 2) self.assertEqual(second.data["count"], 2)
self.assertEqual(second.verb, "Ещё комментарий") self.assertEqual(second.title, "Ещё комментарий")
self.assertEqual(Notification.objects.count(), 1) self.assertEqual(Notification.objects.count(), 1)
self.assertEqual(second.recipients.count(), 2) self.assertEqual(second.recipients.count(), 2)
def test_group_does_not_collapse_across_models_with_the_same_pk(self):
other_model = Group.objects.create(name="same-pk", pk=self.user.pk)
first = create_notification(
notification_type=self.kind,
content_object=self.user,
group=True,
recipients=[{"user": self.user, "channels": [{"channel": DeliveryChannel.BROWSER}]}],
)
second = create_notification(
notification_type=self.kind,
content_object=other_model,
group=True,
recipients=[{"user": self.user, "channels": [{"channel": DeliveryChannel.BROWSER}]}],
)
self.assertNotEqual(second.pk, first.pk)
self.assertEqual(second.object_id, first.object_id)
self.assertNotEqual(second.content_type_id, first.content_type_id)
def test_unsaved_content_object_is_rejected(self):
with self.assertRaisesMessage(ValueError, "content_object must be saved"):
create_notification(
notification_type=self.kind,
content_object=User(username="ghost"),
recipients=[{"user": self.user, "channels": [{"channel": DeliveryChannel.BROWSER}]}],
)
self.assertEqual(Notification.objects.count(), 0)
def test_group_starts_over_after_the_browser_row_is_read(self): def test_group_starts_over_after_the_browser_row_is_read(self):
first = create_notification( first = create_notification(
type=self.kind, notification_type=self.kind,
object_id="post-9", content_object=self.user,
group=True, group=True,
recipients=self._recipients(), recipients=self._recipients(),
) )
first.recipients.filter(delivery_channel=DeliveryChannel.BROWSER).update(unread=False) first.recipients.filter(channel=DeliveryChannel.BROWSER).update(unread=False)
second = create_notification( second = create_notification(
type=self.kind, notification_type=self.kind,
object_id="post-9", content_object=self.user,
group=True, group=True,
recipients=[{"user": self.user, "channels": [{"channel": DeliveryChannel.BROWSER}]}], recipients=[{"user": self.user, "channels": [{"channel": DeliveryChannel.BROWSER}]}],
) )
@ -610,32 +641,32 @@ class GroupingAndIdempotencyTests(TestCase):
def test_same_idempotency_key_returns_the_original_row(self): def test_same_idempotency_key_returns_the_original_row(self):
first = create_notification( first = create_notification(
type=self.kind, notification_type=self.kind,
idempotency_key="approved:9", idempotency_key="approved:9",
recipients=[{"user": self.user, "channels": [{"channel": DeliveryChannel.BROWSER}]}], recipients=[{"user": self.user, "channels": [{"channel": DeliveryChannel.BROWSER}]}],
) )
second = create_notification( second = create_notification(
type=self.kind, notification_type=self.kind,
verb="Other", title="Other",
idempotency_key="approved:9", idempotency_key="approved:9",
group=True, group=True,
object_id="post-9", content_object=self.user,
recipients=self._recipients(), recipients=self._recipients(),
) )
self.assertEqual(second.pk, first.pk) self.assertEqual(second.pk, first.pk)
self.assertEqual(second.verb, first.verb) self.assertEqual(second.title, first.title)
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, {})
def test_idempotency_conflict_returns_the_existing_row(self): def test_idempotency_conflict_returns_the_existing_row(self):
existing = Notification.objects.create(verb="Hi", idempotency_key="race") existing = Notification.objects.create(title="Hi", idempotency_key="race")
with patch( with patch(
"notify.services._existing_idempotent", "notify.services._existing_idempotent",
side_effect=[None, existing], side_effect=[None, existing],
): ):
returned = create_notification( returned = create_notification(
verb="Hi", title="Hi",
idempotency_key="race", idempotency_key="race",
recipients=[{"user": self.user, "channels": [{"channel": DeliveryChannel.BROWSER}]}], recipients=[{"user": self.user, "channels": [{"channel": DeliveryChannel.BROWSER}]}],
) )