diff --git a/Readme.md b/Readme.md
index dcb5d42..a1e0be3 100644
--- a/Readme.md
+++ b/Readme.md
@@ -39,7 +39,7 @@ from django.core.files.base import ContentFile
from notify.services import create_notification
create_notification(
- verb="Заявка одобрена",
+ title="Заявка одобрена",
attachments=[ContentFile(b"...", name="report.pdf")],
recipients=[
{
@@ -55,9 +55,9 @@ create_notification(
`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 остаются текстом.
@@ -65,7 +65,7 @@ create_notification(
Каналы `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`. Расписание удаления просроченных уведомлений (раз в час):
@@ -104,7 +104,7 @@ verify_code(purpose="login", channel="email", target={"email": user.email}, code
В базе лежит только 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.
-`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.
-Шаблоны 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`.
## Тесты
diff --git a/demo/demo/static/demo/inbox.js b/demo/demo/static/demo/inbox.js
index a8961eb..fe1b90b 100644
--- a/demo/demo/static/demo/inbox.js
+++ b/demo/demo/static/demo/inbox.js
@@ -40,12 +40,12 @@
function renderItem(item) {
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");
- verb.className = "verb";
- verb.textContent = item.verb || "";
- card.appendChild(verb);
+ const title = document.createElement("div");
+ title.className = "title";
+ title.textContent = item.title || "";
+ card.appendChild(title);
if (item.description) {
const description = document.createElement("div");
diff --git a/demo/demo/templates/demo/inbox.html b/demo/demo/templates/demo/inbox.html
index a6a3900..6c47af3 100644
--- a/demo/demo/templates/demo/inbox.html
+++ b/demo/demo/templates/demo/inbox.html
@@ -111,9 +111,9 @@
background: #fff;
}
.item.unread { background: #f7f9ff; }
- .item.SUCCESS { border-left-color: var(--success); }
- .item.WARNING { border-left-color: var(--warning); }
- .item.ERROR { border-left-color: var(--error); }
+ .item.success { border-left-color: var(--success); }
+ .item.warning { border-left-color: var(--warning); }
+ .item.error { border-left-color: var(--error); }
.item button { justify-self: start; }
.meta {
display: flex;
@@ -121,7 +121,7 @@
color: var(--muted);
font-size: 12px;
}
- .verb { font-weight: 650; }
+ .title { font-weight: 650; }
.files {
display: flex;
flex-wrap: wrap;
@@ -151,7 +151,7 @@
{% csrf_token %}
Текст
-
+
Описание
@@ -161,10 +161,10 @@
Уровень
- INFO
- SUCCESS
- WARNING
- ERROR
+ info
+ success
+ warning
+ error
diff --git a/demo/demo/views.py b/demo/demo/views.py
index 4e802e5..a423145 100644
--- a/demo/demo/views.py
+++ b/demo/demo/views.py
@@ -16,7 +16,7 @@ def inbox(request):
@login_required
@require_POST
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
level = (request.POST.get("level") or NotificationLevel.INFO).strip()
url = (request.POST.get("url") or "").strip() or None
@@ -31,7 +31,7 @@ def create_notification_view(request):
]
try:
create_notification(
- verb=verb,
+ title=title,
description=description,
level=level,
url=url,
diff --git a/notify/admin.py b/notify/admin.py
index 49ee3d9..a292fca 100644
--- a/notify/admin.py
+++ b/notify/admin.py
@@ -143,13 +143,13 @@ class NotificationTemplateAdmin(admin.ModelAdmin):
'id',
'name',
'channel',
- 'type',
+ 'notification_type',
'is_default',
)
readonly_fields = ['id']
form = forms.modelform_factory(NotificationTemplate, fields='__all__', widgets={
- 'subject_template': AceEditorWidget(mode='django', hide_label=False),
- 'body_template': AceEditorWidget(mode='django', hide_label=False),
+ 'subject': AceEditorWidget(mode='django', hide_label=False),
+ 'body': AceEditorWidget(mode='django', hide_label=False),
})
save_on_top = True
@@ -186,11 +186,11 @@ class NotificationTypeAdmin(admin.ModelAdmin):
'name',
'group',
'is_active',
- 'enabled_by_default',
+ 'is_enabled_by_default',
)
list_filter = (
'is_active',
- 'enabled_by_default',
+ 'is_enabled_by_default',
'group',
)
search_fields = (
@@ -203,13 +203,13 @@ class NotificationTypeAdmin(admin.ModelAdmin):
class NotificationChannelPreferenceAdmin(admin.ModelAdmin):
list_display = (
'user',
- 'type',
+ 'notification_type',
'channel',
- 'enabled',
+ 'is_enabled',
)
list_filter = (
'channel',
- 'enabled',
+ 'is_enabled',
)
@@ -232,15 +232,15 @@ class NotificationRecipientInline(admin.TabularInline):
@admin.register(Notification)
class NotificationAdmin(admin.ModelAdmin):
list_display = (
- 'verb',
+ 'title',
'description',
'expires_at',
'created_at'
)
search_fields = (
'id',
- 'type__code',
- 'verb'
+ 'notification_type__code',
+ 'title'
)
inlines = [NotificationAttachmentInline, NotificationRecipientInline]
@@ -254,13 +254,13 @@ class NotificationRecipientAdmin(admin.ModelAdmin):
'user',
'notification',
'unread',
- 'delivery_channel',
- 'delivery_status',
+ 'channel',
+ 'status',
'attempts',
)
list_filter = (
- 'delivery_channel',
- 'delivery_status',
+ 'channel',
+ 'status',
'unread'
)
ordering = (
@@ -272,7 +272,7 @@ class NotificationRecipientAdmin(admin.ModelAdmin):
return (
'id',
f'user__{username_field}',
- 'notification__verb',
+ 'notification__title',
)
def has_change_permission(self, request, obj = ...):
diff --git a/notify/api.py b/notify/api.py
index 1a9036d..94724bf 100644
--- a/notify/api.py
+++ b/notify/api.py
@@ -71,9 +71,13 @@ class DetailPath(Schema):
def _base_user_queryset(user):
return NotificationRecipient.objects.filter(
user=user,
- delivery_channel=DeliveryChannel.BROWSER,
+ channel=DeliveryChannel.BROWSER,
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:
@@ -169,7 +173,7 @@ def preferences(request):
}
types = NotificationType.objects.filter(
is_active=True,
- configurable=True,
+ is_configurable=True,
).select_related("group")
return [
{
diff --git a/notify/api_filters.py b/notify/api_filters.py
index dddf330..9451ff4 100644
--- a/notify/api_filters.py
+++ b/notify/api_filters.py
@@ -13,19 +13,31 @@ __all__ = [
class NotificationFilterSchema(FilterSchema):
unread: Optional[bool] = None
- type: Annotated[Optional[str], FilterLookup("notification__type__code")] = None
- type__startswith: Annotated[Optional[str], FilterLookup("notification__type__code__startswith")] = None
+ type: Annotated[Optional[str], FilterLookup("notification__notification_type__code")] = 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
search: Annotated[
Optional[str],
FilterLookup(
- ["notification__verb__icontains", "notification__description__icontains"],
+ ["notification__title__icontains", "notification__description__icontains"],
expression_connector="OR"
)
] = None
object_id__ne: Optional[List[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:
return ~Q(notification__object_id__in=value)
diff --git a/notify/api_schema.py b/notify/api_schema.py
index 46c7517..9f38b8f 100644
--- a/notify/api_schema.py
+++ b/notify/api_schema.py
@@ -29,8 +29,9 @@ class NotificationResponseSchema(ModelSchema):
url: Optional[str] = Field(alias="notification.url")
type: Optional[str] = None
level: Optional[str] = Field(alias="notification.level")
- verb: Optional[str] = Field(alias="notification.verb")
- object_id: Optional[str] = Field(alias="notification.object_id")
+ title: Optional[str] = Field(alias="notification.title")
+ content_type: Optional[str] = None
+ object_id: str = Field("", alias="notification.object_id")
description: Optional[str] = Field(alias="notification.description")
data: dict = Field(alias="notification.data")
attachments: list[AttachmentSchema]
@@ -45,11 +46,18 @@ class NotificationResponseSchema(ModelSchema):
@staticmethod
def resolve_type(obj):
- notification_type = obj.notification.type
+ notification_type = obj.notification.notification_type
if notification_type is None:
return None
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
def resolve_attachments(obj):
return [
@@ -66,7 +74,7 @@ class NotificationResponseSchema(ModelSchema):
class ChannelPreferenceChannelSchema(Schema):
channel: str
- enabled: bool
+ is_enabled: bool
class Preference(Schema):
diff --git a/notify/codes.py b/notify/codes.py
index d73abbc..132669f 100644
--- a/notify/codes.py
+++ b/notify/codes.py
@@ -72,7 +72,7 @@ def _render(channel, notification_type, code, ttl, purpose, user):
template = None
if notification_type is not None:
template = (
- NotificationTemplate.objects.filter(channel=channel, type=notification_type)
+ NotificationTemplate.objects.filter(channel=channel, notification_type=notification_type)
.order_by("id")
.first()
)
@@ -107,12 +107,12 @@ def send_code(
channel: str,
target: dict | None = None,
user=None,
- type: NotificationType | str | None = None,
+ notification_type: NotificationType | str | None = None,
) -> VerificationCode:
if not purpose:
raise ValueError("purpose is required")
provider, target, target_key = _resolve_target(channel, target)
- notification_type = _resolve_type(type)
+ notification_type = _resolve_type(notification_type)
now = timezone.now()
ttl = _code_ttl()
resend_interval = _code_resend_interval()
@@ -137,7 +137,7 @@ def send_code(
purpose=purpose,
channel=channel,
target_key=target_key,
- delivery_target=target.model_dump(),
+ target=target.model_dump(),
expires_at=now + timedelta(seconds=ttl),
max_attempts=_code_max_attempts(),
)
diff --git a/notify/delivery/base.py b/notify/delivery/base.py
index 0fdd8da..4b61545 100644
--- a/notify/delivery/base.py
+++ b/notify/delivery/base.py
@@ -32,14 +32,19 @@ def template_context(notification_recipient: NotificationRecipient) -> dict:
return {
"recipient": {
"id": str(notification_recipient.id),
- "delivery_channel": notification_recipient.delivery_channel,
- "delivery_target": notification_recipient.delivery_target,
+ "channel": notification_recipient.channel,
+ "target": notification_recipient.target,
},
"notification": {
"id": str(notification.id),
"url": notification.url,
"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,
"description": notification.description,
"data": notification.data,
@@ -52,17 +57,17 @@ def template_context(notification_recipient: NotificationRecipient) -> dict:
def render_notification_template(
- delivery_channel: DeliveryChannel,
+ channel: DeliveryChannel,
notification_recipient: NotificationRecipient,
) -> tuple[str, str | None]:
notification = notification_recipient.notification
- template = NotificationTemplate.for_delivery(delivery_channel, notification.type)
+ template = NotificationTemplate.for_delivery(channel, notification.notification_type)
if template:
context = template_context(notification_recipient)
subject = _single_line(template.render_subject(context))
body = template.render_body(context)
else:
- subject = _single_line(notification.verb)
+ subject = _single_line(notification.title)
body = linebreaks(notification.description or "", autoescape=True)
return subject, body
@@ -110,10 +115,10 @@ class DeliveryProvider(ABC):
raise NotImplementedError(f"{type(self).__name__} does not support codes")
def mark_sent(self, recipient: NotificationRecipient) -> None:
- recipient.delivery_status = DeliveryStatus.SENT
+ recipient.status = DeliveryStatus.SENT
recipient.sent_at = timezone.now()
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:
from notify.tasks import deliver_notification
diff --git a/notify/delivery/providers/email.py b/notify/delivery/providers/email.py
index fbe4d56..6f97cb8 100644
--- a/notify/delivery/providers/email.py
+++ b/notify/delivery/providers/email.py
@@ -28,7 +28,7 @@ class EmailDeliveryProvider(DeliveryProvider):
def send(self, recipient: NotificationRecipient) -> None:
subject, body = render_notification_template(DeliveryChannel.EMAIL, recipient)
self.send_message(
- self.parse_target(recipient.delivery_target),
+ self.parse_target(recipient.target),
subject,
body,
attachments=recipient.notification.attachments.all(),
diff --git a/notify/delivery/providers/max.py b/notify/delivery/providers/max.py
index af05a39..a9e98a1 100644
--- a/notify/delivery/providers/max.py
+++ b/notify/delivery/providers/max.py
@@ -42,7 +42,7 @@ class MaxDeliveryProvider(DeliveryProvider):
def send(self, recipient: NotificationRecipient) -> None:
_, 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)
def send_message(
diff --git a/notify/delivery/providers/telegram.py b/notify/delivery/providers/telegram.py
index dfd1d85..c53998a 100644
--- a/notify/delivery/providers/telegram.py
+++ b/notify/delivery/providers/telegram.py
@@ -30,7 +30,7 @@ class TelegramDeliveryProvider(DeliveryProvider):
def send(self, recipient: NotificationRecipient) -> None:
_, 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)
def send_message(
diff --git a/notify/migrations/0001_initial.py b/notify/migrations/0001_initial.py
index cf96d8c..b1c86b9 100644
--- a/notify/migrations/0001_initial.py
+++ b/notify/migrations/0001_initial.py
@@ -1,4 +1,4 @@
-# Generated by Django 5.0.6 on 2026-10-11 11:02
+# Generated by Django 5.0.6 on 2026-10-11 12:17
import django.db.models.deletion
import notify.fields
@@ -13,6 +13,7 @@ class Migration(migrations.Migration):
initial = True
dependencies = [
+ ('contenttypes', '0002_remove_content_type_name'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
@@ -31,9 +32,9 @@ class Migration(migrations.Migration):
fields=[
('id', models.BigAutoField(primary_key=True, serialize=False)),
('url', models.TextField(null=True)),
- ('level', models.CharField(choices=[('SUCCESS', 'Success'), ('INFO', 'Info'), ('WARNING', 'Warning'), ('ERROR', 'Error')], default='INFO', max_length=20)),
- ('verb', models.CharField(max_length=255)),
- ('object_id', models.CharField(default='', max_length=255)),
+ ('level', models.CharField(choices=[('success', 'Success'), ('info', 'Info'), ('warning', 'Warning'), ('error', 'Error')], default='info', max_length=20)),
+ ('title', models.CharField(max_length=255)),
+ ('object_id', models.CharField(blank=True, default='', max_length=255)),
('description', models.TextField(blank=True, null=True)),
('data', models.JSONField(blank=True, default=dict)),
('idempotency_key', models.CharField(blank=True, max_length=255, null=True, unique=True)),
@@ -63,7 +64,7 @@ class Migration(migrations.Migration):
fields=[
('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
('channel', models.CharField(choices=[('email', 'Email'), ('telegram', 'Telegram'), ('browser', 'Browser'), ('max', 'Max')], max_length=20)),
- ('enabled', models.BooleanField(default=True)),
+ ('is_enabled', models.BooleanField(default=True)),
],
),
migrations.CreateModel(
@@ -81,9 +82,9 @@ class Migration(migrations.Migration):
name='NotificationRecipient',
fields=[
('id', models.BigAutoField(primary_key=True, serialize=False)),
- ('delivery_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)),
- ('delivery_status', models.CharField(choices=[('UNSENT', 'Unsent'), ('SENT', 'Sent'), ('FAILED', 'Failed')], default='UNSENT', max_length=10)),
+ ('channel', models.CharField(choices=[('email', 'Email'), ('telegram', 'Telegram'), ('browser', 'Browser'), ('max', 'Max')], max_length=20)),
+ ('target', models.JSONField(blank=True, default=None, null=True)),
+ ('status', models.CharField(choices=[('unsent', 'Unsent'), ('sent', 'Sent'), ('failed', 'Failed')], default='unsent', max_length=10)),
('sent_at', models.DateTimeField(blank=True, null=True)),
('attempts', models.PositiveSmallIntegerField(default=0)),
('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)),
('name', models.CharField(max_length=255, unique=True)),
('is_default', models.BooleanField(default=False)),
- ('subject_template', models.TextField(blank=True, default='')),
- ('body_template', models.TextField()),
+ ('subject', models.TextField(blank=True, default='')),
+ ('body', models.TextField()),
],
),
migrations.CreateModel(
@@ -109,11 +110,11 @@ class Migration(migrations.Migration):
('code', models.CharField(max_length=100, unique=True)),
('name', models.CharField(max_length=100)),
('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)),
('is_active', models.BooleanField(default=True)),
- ('configurable', models.BooleanField(default=True)),
- ('enabled_by_default', models.BooleanField(default=True)),
+ ('is_configurable', models.BooleanField(default=True)),
+ ('is_enabled_by_default', models.BooleanField(default=True)),
],
options={
'ordering': ('position', 'code'),
@@ -126,7 +127,7 @@ class Migration(migrations.Migration):
('purpose', models.CharField(max_length=100)),
('channel', models.CharField(choices=[('email', 'Email'), ('telegram', 'Telegram'), ('browser', 'Browser'), ('max', 'Max')], max_length=20)),
('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)),
('expires_at', models.DateTimeField(db_index=True)),
('attempts', models.PositiveSmallIntegerField(default=0)),
@@ -165,6 +166,11 @@ class Migration(migrations.Migration):
model_name='deliveryconfig',
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(
model_name='notificationattachment',
name='notification',
@@ -192,17 +198,17 @@ class Migration(migrations.Migration):
),
migrations.AddField(
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'),
),
migrations.AddField(
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'),
),
migrations.AddField(
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'),
),
migrations.AddField(
@@ -212,23 +218,23 @@ class Migration(migrations.Migration):
),
migrations.AddIndex(
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(
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(
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(
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(
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(
model_name='verificationcode',
diff --git a/notify/models/choices.py b/notify/models/choices.py
index 6a793f3..e5dc139 100644
--- a/notify/models/choices.py
+++ b/notify/models/choices.py
@@ -17,16 +17,16 @@ class DeliveryChannel(models.TextChoices):
class DeliveryStatus(models.TextChoices):
- UNSENT = "UNSENT"
- SENT = "SENT"
- FAILED = "FAILED"
+ UNSENT = "unsent"
+ SENT = "sent"
+ FAILED = "failed"
class NotificationLevel(models.TextChoices):
- SUCCESS = "SUCCESS"
- INFO = "INFO"
- WARNING = "WARNING"
- ERROR = "ERROR"
+ SUCCESS = "success"
+ INFO = "info"
+ WARNING = "warning"
+ ERROR = "error"
def validate_delivery_channels(value):
diff --git a/notify/models/code.py b/notify/models/code.py
index 472bd73..e7b4f95 100644
--- a/notify/models/code.py
+++ b/notify/models/code.py
@@ -26,7 +26,7 @@ class VerificationCode(models.Model):
purpose = models.CharField(max_length=100)
channel = models.CharField(max_length=20, choices=DeliveryChannel.choices)
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)
expires_at = models.DateTimeField(db_index=True)
attempts = models.PositiveSmallIntegerField(default=0)
diff --git a/notify/models/notification.py b/notify/models/notification.py
index e736b31..dc8fc61 100644
--- a/notify/models/notification.py
+++ b/notify/models/notification.py
@@ -2,6 +2,8 @@ from datetime import timedelta
from urllib.parse import urlparse
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.utils import timezone
@@ -23,7 +25,7 @@ def default_expires_at():
class Notification(models.Model):
id = models.BigAutoField(primary_key=True)
url = models.TextField(null=True)
- type = models.ForeignKey(
+ notification_type = models.ForeignKey(
NotificationType,
null=True,
blank=True,
@@ -31,8 +33,10 @@ class Notification(models.Model):
related_name="notifications",
)
level = models.CharField(max_length=20, choices=NotificationLevel.choices, default=NotificationLevel.INFO)
- verb = models.CharField(max_length=255)
- object_id = models.CharField(max_length=255, default="")
+ title = models.CharField(max_length=255)
+ 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)
data = models.JSONField(blank=True, default=dict)
idempotency_key = models.CharField(max_length=255, null=True, blank=True, unique=True)
@@ -43,7 +47,7 @@ class Notification(models.Model):
ordering = ("-created_at",)
def __str__(self):
- return self.verb
+ return self.title
@property
def relative_url(self):
@@ -77,9 +81,9 @@ class NotificationRecipient(models.Model):
on_delete=models.CASCADE,
related_name="notification_recipients",
)
- delivery_channel = models.CharField(max_length=20, choices=DeliveryChannel.choices)
- delivery_target = models.JSONField(null=True, blank=True, default=None)
- delivery_status = models.CharField(max_length=10, choices=DeliveryStatus.choices, default=DeliveryStatus.UNSENT)
+ channel = models.CharField(max_length=20, choices=DeliveryChannel.choices)
+ target = models.JSONField(null=True, blank=True, default=None)
+ status = models.CharField(max_length=10, choices=DeliveryStatus.choices, default=DeliveryStatus.UNSENT)
sent_at = models.DateTimeField(null=True, blank=True)
attempts = models.PositiveSmallIntegerField(default=0)
last_error = models.TextField(blank=True, default="")
@@ -89,24 +93,24 @@ class NotificationRecipient(models.Model):
class Meta:
constraints = [
models.UniqueConstraint(
- fields=["notification", "user", "delivery_channel"],
+ fields=["notification", "user", "channel"],
name="uniq_recipient_channel",
),
]
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):
- target = self.delivery_target
+ target = self.target
if isinstance(target, dict) and target.get("email"):
target = target["email"]
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):
- if self.delivery_channel == DeliveryChannel.BROWSER:
- self.delivery_status = DeliveryStatus.SENT
+ if self.channel == DeliveryChannel.BROWSER:
+ self.status = DeliveryStatus.SENT
if self.sent_at is None:
self.sent_at = timezone.now()
super().save(*args, **kwargs)
diff --git a/notify/models/notification_type.py b/notify/models/notification_type.py
index b331aa3..ff12520 100644
--- a/notify/models/notification_type.py
+++ b/notify/models/notification_type.py
@@ -19,11 +19,11 @@ class NotificationType(models.Model):
name = models.CharField(max_length=100)
channels = models.JSONField(default=list, blank=True, validators=[validate_delivery_channels])
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)
is_active = models.BooleanField(default=True)
- configurable = models.BooleanField(default=True)
- enabled_by_default = models.BooleanField(default=True)
+ is_configurable = models.BooleanField(default=True)
+ is_enabled_by_default = models.BooleanField(default=True)
objects = NotificationTypeManager()
@@ -44,22 +44,22 @@ class NotificationChannelPreference(models.Model):
on_delete=models.CASCADE,
related_name="notification_channel_preferences",
)
- type = models.ForeignKey(
+ notification_type = models.ForeignKey(
NotificationType,
on_delete=models.CASCADE,
related_name="channel_preferences",
)
channel = models.CharField(max_length=20, choices=DeliveryChannel.choices)
- enabled = models.BooleanField(default=True)
+ is_enabled = models.BooleanField(default=True)
class Meta:
constraints = [
models.UniqueConstraint(
- fields=["user", "type", "channel"],
+ fields=["user", "notification_type", "channel"],
name="uniq_user_type_channel_pref",
),
]
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}"
diff --git a/notify/models/template.py b/notify/models/template.py
index c3916f6..6253cce 100644
--- a/notify/models/template.py
+++ b/notify/models/template.py
@@ -13,7 +13,7 @@ __all__ = [
class NotificationTemplate(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
channel = models.CharField(max_length=20, choices=DeliveryChannel.choices)
- type = models.ForeignKey(
+ notification_type = models.ForeignKey(
"notify.NotificationType",
null=True,
blank=True,
@@ -22,19 +22,19 @@ class NotificationTemplate(models.Model):
)
name = models.CharField(unique=True, max_length=255)
is_default = models.BooleanField(default=False)
- subject_template = models.TextField(default="", blank=True)
- body_template = models.TextField()
+ subject = models.TextField(default="", blank=True)
+ body = models.TextField()
class Meta:
constraints = [
models.UniqueConstraint(
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",
),
models.UniqueConstraint(
- fields=["type", "channel"],
- condition=models.Q(type__isnull=False),
+ fields=["notification_type", "channel"],
+ condition=models.Q(notification_type__isnull=False),
name="uniq_template_type_channel",
),
]
@@ -46,10 +46,10 @@ class NotificationTemplate(models.Model):
update_fields = kwargs.get("update_fields")
touches_default = update_fields is None or "is_default" in update_fields
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(
channel=self.channel,
- type__isnull=True,
+ notification_type__isnull=True,
is_default=True,
)
if self.pk:
@@ -60,7 +60,7 @@ class NotificationTemplate(models.Model):
@classmethod
def default(cls, channel):
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")
.first()
)
@@ -68,13 +68,13 @@ class NotificationTemplate(models.Model):
@classmethod
def for_delivery(cls, channel, notification_type):
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:
return typed
return cls.default(channel)
def render_subject(self, context):
- return render(self.subject_template, context)
+ return render(self.subject, context)
def render_body(self, context):
- return render(self.body_template, context)
+ return render(self.body, context)
diff --git a/notify/receivers.py b/notify/receivers.py
index 12ceb7f..58ff278 100644
--- a/notify/receivers.py
+++ b/notify/receivers.py
@@ -15,13 +15,13 @@ __all__ = [
def post_save_notification(sender, instance: NotificationRecipient, created, **kwargs):
if not created:
return
- provider = get_provider(instance.delivery_channel)
+ provider = get_provider(instance.channel)
if provider is None or not provider.requires_async_delivery:
return
recipient_id = instance.id
def enqueue():
- current = get_provider(instance.delivery_channel)
+ current = get_provider(instance.channel)
if current is not None:
current.enqueue(recipient_id)
diff --git a/notify/services.py b/notify/services.py
index 4b85247..685e1ec 100644
--- a/notify/services.py
+++ b/notify/services.py
@@ -1,3 +1,4 @@
+from django.contrib.contenttypes.models import ContentType
from django.db import IntegrityError, transaction
from django.utils import timezone
@@ -34,14 +35,14 @@ def _existing_idempotent(idempotency_key):
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
allowed = set(notification_type.channels)
prefs = {
- pref.channel: pref.enabled
+ pref.channel: pref.is_enabled
for pref in NotificationChannelPreference.objects.filter(
user=user,
- type=notification_type,
+ notification_type=notification_type,
channel__in=allowed,
)
}
@@ -52,22 +53,31 @@ def _allowed_channels(notification_type, user, channels):
raise ValueError(
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)
return kept
-def _grouped_notification(notification_type, user, object_id):
- if notification_type is None or not object_id:
+def _content_link(content_object):
+ 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 (
Notification.objects.select_for_update()
.filter(
- type=notification_type,
+ notification_type=notification_type,
+ content_type=content_type,
object_id=object_id,
expires_at__gte=timezone.now(),
recipients__user=user,
- recipients__delivery_channel=DeliveryChannel.BROWSER,
+ recipients__channel=DeliveryChannel.BROWSER,
recipients__unread=True,
)
.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["count"] = int(payload.get("count", 1)) + 1
notification.data = payload
- if verb:
- notification.verb = verb
- notification.save(update_fields=["data", "verb"])
+ if title:
+ notification.title = title
+ notification.save(update_fields=["data", "title"])
return notification
-def _collapse_grouped(notification_type, recipients, object_id, verb):
+def _collapse_grouped(notification_type, recipients, content_type, object_id, title):
pending = []
grouped = []
seen = set()
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:
pending.append(recipient_data)
continue
@@ -98,7 +108,7 @@ def _collapse_grouped(notification_type, recipients, object_id, verb):
seen.add(found.pk)
grouped.append(found)
for notification in grouped:
- _bump_group(notification, verb)
+ _bump_group(notification, title)
return pending, grouped
@@ -129,8 +139,8 @@ def _attach_recipients(notification, recipients, notification_type):
NotificationRecipient.objects.create(
notification=notification,
user=user,
- delivery_channel=channel,
- delivery_target=target.model_dump() if target is not None else None,
+ channel=channel,
+ target=target.model_dump() if target is not None else None,
)
created += 1
if created == 0:
@@ -141,11 +151,11 @@ def _attach_recipients(notification, recipients, notification_type):
def create_notification(
*,
recipients: list[dict],
- verb: str | None = None,
+ title: str | None = None,
url: str | None = None,
- type: NotificationType | str | None = None,
+ notification_type: NotificationType | str | None = None,
level: str = NotificationLevel.INFO,
- object_id: str = "",
+ content_object=None,
description: str | None = None,
data: dict | None = None,
expires_at=None,
@@ -160,14 +170,16 @@ def create_notification(
return existing
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:
raise ValueError(f"Notification type {notification_type.code} is inactive")
- if not verb:
- verb = notification_type.verb if notification_type is not None else None
- if not verb:
- raise ValueError("verb is required")
+ if not title:
+ title = notification_type.title if notification_type is not None else None
+ if not title:
+ raise ValueError("title is required")
+
+ content_type, object_id = _content_link(content_object)
if not recipients:
raise ValueError("At least one recipient is required")
@@ -183,8 +195,9 @@ def create_notification(
to_create, grouped = _collapse_grouped(
notification_type,
recipients,
- object_id or "",
- verb,
+ content_type,
+ object_id,
+ title,
)
for grouped_notification in grouped:
store_attachments(grouped_notification, prepared_attachments, stored_attachments)
@@ -192,10 +205,11 @@ def create_notification(
return grouped[0]
fields = dict(
url=url,
- type=notification_type,
+ notification_type=notification_type,
level=level,
- verb=verb,
- object_id=object_id or "",
+ title=title,
+ content_type=content_type,
+ object_id=object_id,
description=description,
data=data or {},
idempotency_key=idempotency_key,
@@ -218,9 +232,9 @@ def create_notification(
def channel_preferences(user):
- types = NotificationType.objects.filter(is_active=True, configurable=True)
+ types = NotificationType.objects.filter(is_active=True, is_configurable=True)
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)
}
return [
@@ -229,9 +243,9 @@ def channel_preferences(user):
"channels": [
{
"channel": channel,
- "enabled": saved.get(
+ "is_enabled": saved.get(
(notification_type.id, channel),
- notification_type.enabled_by_default,
+ notification_type.is_enabled_by_default,
),
}
for channel in notification_type.channels
@@ -243,7 +257,7 @@ def channel_preferences(user):
def save_channel_preferences(user, 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"]:
channel = channel_item["channel"]
if channel not in notification_type.channels:
@@ -252,7 +266,7 @@ def save_channel_preferences(user, items):
)
NotificationChannelPreference.objects.update_or_create(
user=user,
- type=notification_type,
+ notification_type=notification_type,
channel=channel,
- defaults={"enabled": channel_item["enabled"]},
+ defaults={"is_enabled": channel_item["is_enabled"]},
)
diff --git a/notify/tasks.py b/notify/tasks.py
index f212829..114179d 100644
--- a/notify/tasks.py
+++ b/notify/tasks.py
@@ -38,9 +38,9 @@ BEAT_SCHEDULE = {
def _mark_failed(notification_recipient_id: str, error: str) -> None:
NotificationRecipient.objects.filter(
id=notification_recipient_id,
- delivery_status=DeliveryStatus.UNSENT,
+ status=DeliveryStatus.UNSENT,
).update(
- delivery_status=DeliveryStatus.FAILED,
+ status=DeliveryStatus.FAILED,
last_error=error[:2000],
)
@@ -50,18 +50,18 @@ def _deliver_notification(notification_recipient_id: str) -> None:
with transaction.atomic():
recipient = (
NotificationRecipient.objects.select_for_update(of=("self",))
- .select_related("notification__type", "user")
+ .select_related("notification__notification_type", "user")
.filter(id=notification_recipient_id)
.first()
)
- if recipient is None or recipient.delivery_status != DeliveryStatus.UNSENT:
+ if recipient is None or recipient.status != DeliveryStatus.UNSENT:
return
NotificationRecipient.objects.filter(pk=recipient.pk).update(
attempts=F("attempts") + 1,
)
recipient.refresh_from_db(fields=["attempts"])
try:
- provider = get_provider_or_raise(recipient.delivery_channel)
+ provider = get_provider_or_raise(recipient.channel)
provider.send(recipient)
except Exception as exc:
if isinstance(exc, KeyError):
diff --git a/pyproject.toml b/pyproject.toml
index d6541ef..c37b63f 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -1,6 +1,6 @@
[project]
name = "notify"
-version = "0.1.0"
+version = "0.4.0"
description = "Django app for user notifications"
readme = "Readme.md"
requires-python = ">=3.10"
diff --git a/tests/test_admin.py b/tests/test_admin.py
index 71f8b6c..be52c78 100644
--- a/tests/test_admin.py
+++ b/tests/test_admin.py
@@ -221,7 +221,7 @@ class NotificationAdminTests(TestCase):
def setUp(self):
self.admin_user = User.objects.create_superuser("admin", "admin@example.com", "pass")
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):
request = RequestFactory().get("/")
@@ -239,8 +239,8 @@ class NotificationAdminTests(TestCase):
response = self.client.get(change)
self.assertEqual(response.status_code, 200)
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.assertEqual(self.note.verb, "Hello")
+ self.assertEqual(self.note.title, "Hello")
listing = reverse("admin:notify_notification_changelist")
self.assertEqual(self.client.get(listing).status_code, 200)
diff --git a/tests/test_api.py b/tests/test_api.py
index 3efe2b6..221482f 100644
--- a/tests/test_api.py
+++ b/tests/test_api.py
@@ -24,11 +24,11 @@ class ApiTests(TestCase):
self.other = User.objects.create_user("bob", "bob@example.com", "pass")
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:
extra["expires_at"] = expires_at
return create_notification(
- verb=verb,
+ title=title,
recipients=[{"user": user, "channels": [{"channel": DeliveryChannel.BROWSER}]}],
**extra,
)
@@ -43,7 +43,7 @@ class ApiTests(TestCase):
name=code,
group=group,
channels=[DeliveryChannel.BROWSER, DeliveryChannel.EMAIL],
- verb=code,
+ title=code,
)
def test_expired_notifications_are_hidden(self):
@@ -57,7 +57,7 @@ class ApiTests(TestCase):
listing = self.client.get("/api/list/")
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"])
def test_invalid_recipient_id_is_not_found(self):
@@ -87,16 +87,17 @@ class ApiTests(TestCase):
def test_list_returns_the_browser_inbox(self):
kind = self._type("orders.approved")
when = timezone.now() + timedelta(days=3)
+ subject = User.objects.create_user("carol", "carol@example.com", "pass")
notification = self._browser(
self.user,
"Invoice paid",
expires_at=when,
- type=kind,
+ notification_type=kind,
url="https://example.com/orders/1?x=1",
- object_id="1",
+ content_object=subject,
description="wire",
data={"n": 1},
- level="SUCCESS",
+ level="success",
)
self._browser(self.other, "foreign")
older = notification.recipients.get()
@@ -109,26 +110,27 @@ class ApiTests(TestCase):
body = listing.json()
self.assertEqual(body["total"], 2)
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]
self.assertEqual(item["id"], older.id)
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["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["data"], {"n": 1})
self.assertTrue(item["unread"])
- self.assertNotIn("delivery_channel", item)
- self.assertNotIn("delivery_target", item)
+ self.assertNotIn("channel", item)
+ self.assertNotIn("target", item)
count = self.client.get("/api/count/")
self.assertEqual(count.json()["result"], 2)
def test_other_channels_and_other_users_stay_out_of_the_inbox(self):
create_notification(
- verb="mail",
+ title="mail",
recipients=[
{
"user": self.user,
@@ -140,7 +142,7 @@ class ApiTests(TestCase):
self._browser(self.user, "mine")
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
denied = self.client.post(f"/api/make-read/{foreign_id}/")
@@ -148,7 +150,7 @@ class ApiTests(TestCase):
foreign.recipients.get().refresh_from_db()
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)
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}/")
self.assertEqual(read.status_code, 200)
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)
again = self.client.post(f"/api/make-unread/{recipient.id}/")
@@ -178,26 +180,29 @@ class ApiTests(TestCase):
approved = self._type("orders.approved")
rejected = self._type("orders.rejected")
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.user,
"Invoice paid",
- type=approved,
- object_id="1",
+ notification_type=approved,
+ content_object=invoice,
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.user,
"Due",
- type=billing,
- object_id="3",
+ notification_type=billing,
+ content_object=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()
def verbs(response):
- return [item["verb"] for item in response.json()["results"]]
+ return [item["title"] for item in response.json()["results"]]
self.assertEqual(
verbs(self.client.get("/api/list/", {"type": "orders.approved"})),
@@ -208,7 +213,11 @@ class ApiTests(TestCase):
["Invoice paid", "Nope"],
)
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"],
)
self.assertCountEqual(
@@ -224,11 +233,11 @@ class ApiTests(TestCase):
["Invoice paid"],
)
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"],
)
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"],
)
self.assertEqual(
@@ -239,17 +248,17 @@ class ApiTests(TestCase):
def test_make_all_read_respects_filters(self):
orders = self._type("orders.approved")
billing = self._type("billing.due")
- self._browser(self.user, "order", type=orders)
- self._browser(self.user, "bill", type=billing)
- self._browser(self.other, "foreign", type=orders)
+ self._browser(self.user, "order", notification_type=orders)
+ self._browser(self.user, "bill", notification_type=billing)
+ self._browser(self.other, "foreign", notification_type=orders)
self._browser(
self.user,
"old order",
- type=orders,
+ notification_type=orders,
expires_at=timezone.now() - timedelta(minutes=1),
)
mailed = create_notification(
- type=orders,
+ notification_type=orders,
recipients=[
{
"user": self.user,
@@ -262,8 +271,8 @@ class ApiTests(TestCase):
self.assertEqual(response.status_code, 200)
self.assertEqual(response.json(), {})
- def unread(verb):
- return NotificationRecipient.objects.get(notification__verb=verb).unread
+ def unread(title):
+ return NotificationRecipient.objects.get(notification__title=title).unread
self.assertFalse(unread("order"))
self.assertTrue(unread("bill"))
@@ -306,7 +315,7 @@ class ApiTests(TestCase):
name="Security",
group=group,
channels=[DeliveryChannel.EMAIL],
- configurable=False,
+ is_configurable=False,
)
NotificationType.objects.create(
code="retired",
@@ -317,9 +326,9 @@ class ApiTests(TestCase):
)
NotificationChannelPreference.objects.create(
user=self.user,
- type=approved,
+ notification_type=approved,
channel=DeliveryChannel.EMAIL,
- enabled=False,
+ is_enabled=False,
)
response = self.client.get("/api/preferences/")
@@ -332,8 +341,8 @@ class ApiTests(TestCase):
"name": "Approved",
"group_name": "Orders",
"channels": [
- {"channel": DeliveryChannel.EMAIL, "enabled": False},
- {"channel": DeliveryChannel.BROWSER, "enabled": True},
+ {"channel": DeliveryChannel.EMAIL, "is_enabled": False},
+ {"channel": DeliveryChannel.BROWSER, "is_enabled": True},
],
},
{
@@ -341,7 +350,7 @@ class ApiTests(TestCase):
"name": "Later",
"group_name": "Orders",
"channels": [
- {"channel": DeliveryChannel.BROWSER, "enabled": True},
+ {"channel": DeliveryChannel.BROWSER, "is_enabled": True},
],
},
],
@@ -360,7 +369,7 @@ class ApiTests(TestCase):
{
"code": "orders.approved",
"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/")
channels = {
- item["channel"]: item["enabled"]
+ item["channel"]: item["is_enabled"]
for item in listing.json()[0]["channels"]
}
self.assertEqual(
@@ -387,7 +396,7 @@ class ApiTests(TestCase):
name="Security",
group=group,
channels=[DeliveryChannel.EMAIL],
- configurable=False,
+ is_configurable=False,
)
unknown_channel = self._post_preferences(
@@ -395,7 +404,7 @@ class ApiTests(TestCase):
"items": [
{
"code": "orders.approved",
- "channels": [{"channel": DeliveryChannel.MAX, "enabled": True}],
+ "channels": [{"channel": DeliveryChannel.MAX, "is_enabled": True}],
}
]
}
@@ -408,7 +417,7 @@ class ApiTests(TestCase):
"items": [
{
"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.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.enabled_by_default = False
- kind.save(update_fields=["enabled_by_default"])
+ kind.is_enabled_by_default = False
+ kind.save(update_fields=["is_enabled_by_default"])
listing = self.client.get("/api/preferences/")
self.assertEqual(listing.status_code, 200)
self.assertEqual(
listing.json()[0]["channels"],
[
- {"channel": DeliveryChannel.BROWSER, "enabled": False},
- {"channel": DeliveryChannel.EMAIL, "enabled": False},
+ {"channel": DeliveryChannel.BROWSER, "is_enabled": False},
+ {"channel": DeliveryChannel.EMAIL, "is_enabled": False},
],
)
@@ -438,7 +447,7 @@ class ApiTests(TestCase):
{
"code": "orders.digest",
"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)
channels = {
- item["channel"]: item["enabled"]
+ item["channel"]: item["is_enabled"]
for item in self.client.get("/api/preferences/").json()[0]["channels"]
}
self.assertEqual(
@@ -460,23 +469,23 @@ class PaginationTests(TestCase):
self.user = User.objects.create_user("alice", "alice@example.com", "pass")
def test_pages_are_counted_from_the_queryset(self):
- for verb in ("a", "b", "c"):
+ for title in ("a", "b", "c"):
create_notification(
- verb=verb,
+ title=title,
recipients=[
{"user": self.user, "channels": [{"channel": DeliveryChannel.BROWSER}]},
],
)
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))
self.assertEqual(first["total"], 3)
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))
- 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(
NotificationRecipient.objects.none(),
diff --git a/tests/test_attachments.py b/tests/test_attachments.py
index e64d013..6c8d313 100644
--- a/tests/test_attachments.py
+++ b/tests/test_attachments.py
@@ -39,12 +39,12 @@ class AttachmentServiceTests(TestCase):
name="Approved",
group=self.group,
channels=[DeliveryChannel.BROWSER, DeliveryChannel.EMAIL],
- verb="Approved",
+ title="Approved",
)
def _browser(self, user, **extra):
return create_notification(
- verb=extra.pop("verb", "Hello"),
+ title=extra.pop("title", "Hello"),
recipients=[{"user": user, "channels": [{"channel": DeliveryChannel.BROWSER}]}],
**extra,
)
@@ -129,7 +129,7 @@ class AttachmentServiceTests(TestCase):
with override_settings(NOTIFY_MAX_ATTACHMENT_BYTES=1):
second = self._browser(
self.user,
- verb="Other",
+ title="Other",
idempotency_key="approved:9",
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):
first = create_notification(
- type=self.kind,
- object_id="post-9",
+ notification_type=self.kind,
+ content_object=self.user,
group=True,
recipients=[{"user": self.user, "channels": [{"channel": DeliveryChannel.BROWSER}]}],
)
second = create_notification(
- type=self.kind,
- object_id="post-9",
- verb="Ещё",
+ notification_type=self.kind,
+ content_object=self.user,
+ title="Ещё",
group=True,
attachments=[ContentFile(b"note", name="note.txt")],
recipients=[
@@ -161,8 +161,8 @@ class AttachmentServiceTests(TestCase):
self.assertNotEqual(first.attachments.get().file.name, second.attachments.get().file.name)
collapsed = create_notification(
- type=self.kind,
- object_id="post-9",
+ notification_type=self.kind,
+ content_object=self.user,
group=True,
attachments=[ContentFile(b"more", name="more.txt")],
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):
create_notification(
- verb="With file",
+ title="With file",
attachments=[ContentFile(b"hello", name="report.txt")],
recipients=[{"user": self.user, "channels": [{"channel": DeliveryChannel.BROWSER}]}],
)
create_notification(
- verb="Foreign",
+ title="Foreign",
attachments=[ContentFile(b"secret", name="secret.txt")],
recipients=[{"user": self.other, "channels": [{"channel": DeliveryChannel.BROWSER}]}],
)
listing = self.client.get("/api/list/")
self.assertEqual(listing.status_code, 200)
item = listing.json()["results"][0]
- self.assertEqual(item["verb"], "With file")
+ self.assertEqual(item["title"], "With file")
self.assertEqual(len(item["attachments"]), 1)
attachment = item["attachments"][0]
self.assertEqual(attachment["name"], "report.txt")
@@ -227,7 +227,7 @@ class AttachmentApiTests(TestCase):
def test_expired_and_invalid_ids_are_hidden(self):
notification = create_notification(
- verb="Stale",
+ title="Stale",
expires_at=timezone.now() - timedelta(minutes=1),
attachments=[ContentFile(b"old", name="old.txt")],
recipients=[{"user": self.user, "channels": [{"channel": DeliveryChannel.BROWSER}]}],
@@ -240,7 +240,7 @@ class AttachmentApiTests(TestCase):
def test_email_recipient_can_download(self):
notification = create_notification(
- verb="Mail",
+ title="Mail",
attachments=[ContentFile(b"body", name="body.txt")],
recipients=[
{
@@ -272,7 +272,7 @@ class AttachmentEmailTests(TestCase):
def test_email_includes_the_file(self):
notification = create_notification(
- verb="Hello",
+ title="Hello",
description="Body",
attachments=[ContentFile(b"pdf-bytes", name="report.pdf")],
recipients=[
diff --git a/tests/test_codes.py b/tests/test_codes.py
index d398e26..d96fff4 100644
--- a/tests/test_codes.py
+++ b/tests/test_codes.py
@@ -89,7 +89,7 @@ class CodeTests(TestCase):
self.assertEqual(post.call_args.kwargs["params"], {"user_id": 7})
verification = VerificationCode.objects.get()
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))
def test_wrong_code_counts_attempt(self):
@@ -173,16 +173,16 @@ class CodeTests(TestCase):
def test_custom_template_by_type(self):
group = NotificationGroup.objects.create(code="auth", name="Auth")
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(
name="otp-email",
channel="email",
- type=notification_type,
- subject_template="Вход для {{ user.username }}",
- body_template="{{ code }} на {{ ttl_minutes }} мин ({{ purpose }})",
+ notification_type=notification_type,
+ subject="Вход для {{ user.username }}",
+ body="{{ code }} на {{ 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]
self.assertEqual(message.subject, "Вход для alice")
self.assertEqual(message.body, f"{code} на 5 мин (login)")
@@ -192,8 +192,8 @@ class CodeTests(TestCase):
name="default-email",
channel="email",
is_default=True,
- subject_template="{{ notification.verb }}",
- body_template="{{ notification.description }}",
+ subject="{{ notification.title }}",
+ body="{{ notification.description }}",
)
code = self._send_email()
self.assertIn(code, mail.outbox[-1].body)
diff --git a/tests/test_delivery.py b/tests/test_delivery.py
index 8d6ccac..b5f744a 100644
--- a/tests/test_delivery.py
+++ b/tests/test_delivery.py
@@ -56,7 +56,7 @@ class DeliveryTests(TestCase):
def _email_recipient(self, **notification_kwargs):
notification = create_notification(
- verb=notification_kwargs.pop("verb", "Hello"),
+ title=notification_kwargs.pop("title", "Hello"),
description=notification_kwargs.pop("description", "Body"),
recipients=[
{
@@ -68,19 +68,19 @@ class DeliveryTests(TestCase):
)
return notification.recipients.get()
- def _max_recipient(self, delivery_target=None):
+ def _max_recipient(self, target=None):
DeliveryTokenConfig.objects.create(
name="max",
channel=DeliveryChannel.MAX,
is_default=True,
token="token",
)
- notification = Notification.objects.create(verb="Hello", description="Body")
+ notification = Notification.objects.create(title="Hello", description="Body")
return NotificationRecipient.objects.create(
notification=notification,
user=self.user,
- delivery_channel=DeliveryChannel.MAX,
- delivery_target={"chat_id": -10} if delivery_target is None else delivery_target,
+ channel=DeliveryChannel.MAX,
+ target={"chat_id": -10} if target is None else target,
)
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)
self.assertEqual(result.state, "FAILURE")
recipient.refresh_from_db()
- self.assertEqual(recipient.delivery_status, DeliveryStatus.FAILED)
+ self.assertEqual(recipient.status, DeliveryStatus.FAILED)
self.assertEqual(recipient.attempts, 6)
self.assertIn("Email delivery failed", recipient.last_error)
self.assertIsNone(recipient.sent_at)
@@ -104,29 +104,29 @@ class DeliveryTests(TestCase):
result = deliver_notification.apply(args=[str(recipient.id)], throw=False)
self.assertEqual(result.state, "FAILURE")
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):
- notification = Notification.objects.create(verb="Hello", description="Body")
+ notification = Notification.objects.create(title="Hello", description="Body")
recipient = NotificationRecipient.objects.create(
notification=notification,
user=self.user,
- delivery_channel=DeliveryChannel.EMAIL,
- delivery_target=None,
+ channel=DeliveryChannel.EMAIL,
+ target=None,
)
deliver_notification.apply(args=[str(recipient.id)], throw=True)
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):
recipient = self._email_recipient(
- verb="Hello\r\nBcc: leak",
+ title="Hello\r\nBcc: leak",
description="",
)
deliver_notification.apply(args=[str(recipient.id)], throw=True)
deliver_notification.apply(args=[str(recipient.id)], throw=True)
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.last_error, "")
self.assertIsNotNone(recipient.sent_at)
@@ -142,13 +142,13 @@ class DeliveryTests(TestCase):
channel=DeliveryChannel.EMAIL,
name="email-default",
is_default=True,
- subject_template="{{ notification.verb }}",
- body_template="hash={{ user.password }} verb={{ notification.verb }}",
+ subject="{{ notification.title }}",
+ body="hash={{ user.password }} title={{ notification.title }}",
)
- recipient = self._email_recipient(verb="Approved", description="x ")
+ recipient = self._email_recipient(title="Approved", description="x ")
deliver_notification.apply(args=[str(recipient.id)], throw=True)
body = mail.outbox[0].body
- self.assertIn("verb=Approved", body)
+ self.assertIn("title=Approved", body)
self.assertNotIn(self.user.password, body)
self.assertNotIn("", body)
@@ -159,11 +159,11 @@ class DeliveryTests(TestCase):
name="Approved",
group=group,
channels=[DeliveryChannel.EMAIL],
- verb="Approved",
+ title="Approved",
)
with self.assertRaisesMessage(ValueError, "not allowed"):
create_notification(
- type="approved",
+ notification_type="approved",
recipients=[
{"user": self.user, "channels": [{"channel": DeliveryChannel.BROWSER}]},
],
@@ -173,7 +173,7 @@ class DeliveryTests(TestCase):
def test_unknown_channel_does_not_create_recipient(self):
with self.assertRaisesMessage(ValueError, "No delivery provider"):
create_notification(
- verb="Ping",
+ title="Ping",
recipients=[
{"user": self.user, "channels": [{"channel": "sms"}]},
],
@@ -188,12 +188,12 @@ class DeliveryTests(TestCase):
name="Approved",
group=group,
channels=[DeliveryChannel.BROWSER],
- verb="Approved",
+ title="Approved",
is_active=False,
)
with self.assertRaisesMessage(ValueError, "inactive"):
create_notification(
- type="approved",
+ notification_type="approved",
recipients=[
{"user": self.user, "channels": [{"channel": DeliveryChannel.BROWSER}]},
],
@@ -203,7 +203,7 @@ class DeliveryTests(TestCase):
def test_duplicate_channel_rolls_back(self):
with self.assertRaisesMessage(ValueError, "Duplicate"):
create_notification(
- verb="Ping",
+ title="Ping",
recipients=[
{
"user": self.user,
@@ -217,20 +217,20 @@ class DeliveryTests(TestCase):
self.assertEqual(Notification.objects.count(), 0)
def test_recipient_channel_is_unique(self):
- notification = Notification.objects.create(verb="Hello")
+ notification = Notification.objects.create(title="Hello")
NotificationRecipient.objects.create(
notification=notification,
user=self.user,
- delivery_channel=DeliveryChannel.EMAIL,
- delivery_target={"email": "alice@example.com"},
+ channel=DeliveryChannel.EMAIL,
+ target={"email": "alice@example.com"},
)
with self.assertRaises(IntegrityError):
with transaction.atomic():
NotificationRecipient.objects.create(
notification=notification,
user=self.user,
- delivery_channel=DeliveryChannel.EMAIL,
- delivery_target={"email": "other@example.com"},
+ channel=DeliveryChannel.EMAIL,
+ target={"email": "other@example.com"},
)
def test_max_request_has_timeout_and_retries_server_errors(self):
@@ -240,12 +240,12 @@ class DeliveryTests(TestCase):
is_default=True,
token="token",
)
- notification = Notification.objects.create(verb="Hello", description="Body")
+ notification = Notification.objects.create(title="Hello", description="Body")
recipient = NotificationRecipient.objects.create(
notification=notification,
user=self.user,
- delivery_channel=DeliveryChannel.MAX,
- delivery_target={"chat_id": -10},
+ channel=DeliveryChannel.MAX,
+ target={"chat_id": -10},
)
response = requests.Response()
response.status_code = 503
@@ -258,7 +258,7 @@ class DeliveryTests(TestCase):
self.assertGreater(post.call_count, 1)
self.assertEqual(post.call_args.kwargs["timeout"], MAX_API_TIMEOUT)
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):
DeliveryTokenConfig.objects.create(
@@ -267,12 +267,12 @@ class DeliveryTests(TestCase):
is_default=True,
token="token",
)
- notification = Notification.objects.create(verb="Hello", description="Body")
+ notification = Notification.objects.create(title="Hello", description="Body")
recipient = NotificationRecipient.objects.create(
notification=notification,
user=self.user,
- delivery_channel=DeliveryChannel.MAX,
- delivery_target={"chat_id": -10},
+ channel=DeliveryChannel.MAX,
+ target={"chat_id": -10},
)
response = requests.Response()
response.status_code = 400
@@ -283,7 +283,7 @@ class DeliveryTests(TestCase):
deliver_notification.apply(args=[str(recipient.id)], throw=True)
self.assertEqual(post.call_count, 1)
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):
second = DeliveryEmailConfig.objects.create(
@@ -323,7 +323,7 @@ class DeliveryTests(TestCase):
def test_expired_notifications_stay_until_the_cleanup_task(self):
old = Notification.objects.create(
- verb="old",
+ title="old",
expires_at=timezone.now() - timedelta(minutes=1),
)
from notify.tasks import delete_expired_notifications
@@ -333,7 +333,7 @@ class DeliveryTests(TestCase):
self.assertFalse(Notification.objects.filter(pk=old.pk).exists())
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
self.assertEqual(delete_expired_notifications(), 0)
@@ -370,23 +370,23 @@ class DeliveryTests(TestCase):
def test_failed_recipient_is_not_sent_again(self):
recipient = self._email_recipient()
- recipient.delivery_status = DeliveryStatus.FAILED
- recipient.save(update_fields=["delivery_status"])
+ recipient.status = DeliveryStatus.FAILED
+ recipient.save(update_fields=["status"])
with patch("notify.delivery.providers.email.EmailMessage.send") as send:
deliver_notification.apply(args=[str(recipient.id)], throw=True)
send.assert_not_called()
self.assertEqual(len(mail.outbox), 0)
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(
notification=notification,
user=self.user,
- delivery_channel="sms",
+ channel="sms",
)
deliver_notification.apply(args=[str(recipient.id)], throw=True)
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):
recipient = self._email_recipient()
@@ -397,7 +397,7 @@ class DeliveryTests(TestCase):
deliver_notification.apply(args=[str(recipient.id)], throw=True)
self.assertEqual(send.call_count, 1)
recipient.refresh_from_db()
- self.assertEqual(recipient.delivery_status, DeliveryStatus.FAILED)
+ self.assertEqual(recipient.status, DeliveryStatus.FAILED)
def test_unaccepted_email_is_retried(self):
recipient = self._email_recipient()
@@ -406,7 +406,7 @@ class DeliveryTests(TestCase):
self.assertEqual(result.state, "FAILURE")
self.assertEqual(send.call_count, 6)
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):
group = NotificationGroup.objects.create(code="orders", name="Orders")
@@ -415,25 +415,25 @@ class DeliveryTests(TestCase):
name="Approved",
group=group,
channels=[DeliveryChannel.EMAIL],
- verb="Approved",
+ title="Approved",
)
NotificationTemplate.objects.create(
channel=DeliveryChannel.EMAIL,
name="email-default",
is_default=True,
- subject_template="default {{ notification.verb }}",
- body_template="DEFAULT {{ notification.url }}",
+ subject="default {{ notification.title }}",
+ body="DEFAULT {{ notification.url }}",
)
NotificationTemplate.objects.create(
channel=DeliveryChannel.EMAIL,
- type=kind,
+ notification_type=kind,
name="approved-email",
- subject_template="typed {{ notification.verb }}",
- body_template="TYPED {{ notification.url }}",
+ subject="typed {{ notification.title }}",
+ body="TYPED {{ notification.url }}",
)
recipient = self._email_recipient(
- type=kind,
- verb="Approved",
+ notification_type=kind,
+ title="Approved",
url="https://example.com/orders/9",
description="plain",
)
@@ -447,9 +447,9 @@ class DeliveryTests(TestCase):
channel=DeliveryChannel.MAX,
name="max-only",
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)
self.assertNotIn("MAX-ONLY", 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.assertIn("Body", post.call_args.kwargs["json"]["text"])
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):
recipient = self._max_recipient()
@@ -477,7 +477,7 @@ class DeliveryTests(TestCase):
deliver_notification.apply(args=[str(recipient.id)], throw=True)
self.assertEqual(post.call_args.kwargs["params"], {"chat_id": -10})
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):
recipient = self._max_recipient({})
@@ -485,20 +485,20 @@ class DeliveryTests(TestCase):
deliver_notification.apply(args=[str(recipient.id)], throw=True)
post.assert_not_called()
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):
- notification = Notification.objects.create(verb="Hello", description="Body")
+ notification = Notification.objects.create(title="Hello", description="Body")
recipient = NotificationRecipient.objects.create(
notification=notification,
user=self.user,
- delivery_channel=DeliveryChannel.MAX,
- delivery_target={"chat_id": -10},
+ channel=DeliveryChannel.MAX,
+ target={"chat_id": -10},
)
result = deliver_notification.apply(args=[str(recipient.id)], throw=False)
self.assertEqual(result.state, "FAILURE")
recipient.refresh_from_db()
- self.assertEqual(recipient.delivery_status, DeliveryStatus.FAILED)
+ self.assertEqual(recipient.status, DeliveryStatus.FAILED)
def test_max_timeout_is_retried(self):
recipient = self._max_recipient()
@@ -510,7 +510,7 @@ class DeliveryTests(TestCase):
self.assertEqual(result.state, "FAILURE")
self.assertEqual(post.call_count, 6)
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):
recipient = self._max_recipient()
@@ -522,7 +522,7 @@ class DeliveryTests(TestCase):
self.assertEqual(result.state, "FAILURE")
self.assertEqual(post.call_count, 6)
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):
DeliveryTokenConfig.objects.create(
@@ -532,7 +532,7 @@ class DeliveryTests(TestCase):
token="bot-token",
)
notification = create_notification(
- verb="Hello",
+ title="Hello",
description="Body",
recipients=[
{
@@ -555,13 +555,13 @@ class DeliveryTests(TestCase):
self.assertIn("Body", post.call_args.kwargs["json"]["text"])
self.assertEqual(post.call_args.kwargs["timeout"], TELEGRAM_API_TIMEOUT)
recipient.refresh_from_db()
- self.assertEqual(recipient.delivery_status, DeliveryStatus.SENT)
+ self.assertEqual(recipient.status, DeliveryStatus.SENT)
self.assertEqual(recipient.attempts, 1)
def test_telegram_requires_target(self):
with self.assertRaisesMessage(ValueError, "target is required"):
create_notification(
- verb="Hi",
+ title="Hi",
recipients=[
{"user": self.user, "channels": [{"channel": DeliveryChannel.TELEGRAM}]},
],
@@ -575,12 +575,12 @@ class DeliveryTests(TestCase):
is_default=True,
token="bot-token",
)
- notification = Notification.objects.create(verb="Hello", description="Body")
+ notification = Notification.objects.create(title="Hello", description="Body")
recipient = NotificationRecipient.objects.create(
notification=notification,
user=self.user,
- delivery_channel=DeliveryChannel.TELEGRAM,
- delivery_target={"chat_id": 42},
+ channel=DeliveryChannel.TELEGRAM,
+ target={"chat_id": 42},
)
response = requests.Response()
response.status_code = 400
@@ -591,7 +591,7 @@ class DeliveryTests(TestCase):
deliver_notification.apply(args=[str(recipient.id)], throw=True)
self.assertEqual(post.call_count, 1)
recipient.refresh_from_db()
- self.assertEqual(recipient.delivery_status, DeliveryStatus.FAILED)
+ self.assertEqual(recipient.status, DeliveryStatus.FAILED)
self.assertEqual(recipient.attempts, 1)
self.assertIn("400", recipient.last_error)
@@ -602,12 +602,12 @@ class DeliveryTests(TestCase):
is_default=True,
token="bot-token",
)
- notification = Notification.objects.create(verb="Hello", description="Body")
+ notification = Notification.objects.create(title="Hello", description="Body")
recipient = NotificationRecipient.objects.create(
notification=notification,
user=self.user,
- delivery_channel=DeliveryChannel.TELEGRAM,
- delivery_target={"chat_id": 42},
+ channel=DeliveryChannel.TELEGRAM,
+ target={"chat_id": 42},
)
with patch(
"notify.delivery.providers.telegram.requests.post",
@@ -617,7 +617,7 @@ class DeliveryTests(TestCase):
self.assertEqual(result.state, "FAILURE")
self.assertEqual(post.call_count, 6)
recipient.refresh_from_db()
- self.assertEqual(recipient.delivery_status, DeliveryStatus.FAILED)
+ self.assertEqual(recipient.status, DeliveryStatus.FAILED)
self.assertEqual(recipient.attempts, 6)
def test_markdown_filter_renders_fenced_code(self):
diff --git a/tests/test_models.py b/tests/test_models.py
index 98dfa95..e730795 100644
--- a/tests/test_models.py
+++ b/tests/test_models.py
@@ -78,7 +78,7 @@ class ModelTests(TestCase):
)
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")
note.url = "/inbox"
self.assertEqual(note.relative_url, "/inbox")
@@ -87,35 +87,35 @@ class ModelTests(TestCase):
self.assertEqual(str(note), "Hi")
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()
self.assertGreater(remaining, timedelta(days=29))
self.assertLess(remaining, timedelta(days=31))
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(
notification=note,
user=self.user,
- delivery_channel=DeliveryChannel.BROWSER,
- delivery_status=DeliveryStatus.UNSENT,
+ channel=DeliveryChannel.BROWSER,
+ 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})")
def test_read_flags(self):
- note = Notification.objects.create(verb="Hi")
+ note = Notification.objects.create(title="Hi")
recipient = NotificationRecipient.objects.create(
notification=note,
user=self.user,
- delivery_channel=DeliveryChannel.EMAIL,
- delivery_target={"email": "alice@example.com"},
+ channel=DeliveryChannel.EMAIL,
+ target={"email": "alice@example.com"},
)
self.assertIn("alice@example.com", str(recipient))
recipient.make_read()
recipient.refresh_from_db()
self.assertFalse(recipient.unread)
- self.assertEqual(recipient.delivery_status, DeliveryStatus.UNSENT)
+ self.assertEqual(recipient.status, DeliveryStatus.UNSENT)
recipient.make_unread()
recipient.refresh_from_db()
self.assertTrue(recipient.unread)
@@ -125,13 +125,13 @@ class ModelTests(TestCase):
channel=DeliveryChannel.EMAIL,
name="first",
is_default=True,
- body_template="A",
+ body="A",
)
second = NotificationTemplate.objects.create(
channel=DeliveryChannel.EMAIL,
name="second",
is_default=True,
- body_template="B",
+ body="B",
)
first.refresh_from_db()
self.assertFalse(first.is_default)
@@ -145,14 +145,14 @@ class ModelTests(TestCase):
channel=DeliveryChannel.EMAIL,
name="fallback",
is_default=True,
- body_template="FALLBACK",
+ body="FALLBACK",
)
typed = NotificationTemplate.objects.create(
channel=DeliveryChannel.EMAIL,
- type=kind,
+ notification_type=kind,
name="approved-email",
is_default=True,
- body_template="TYPED",
+ body="TYPED",
)
fallback.refresh_from_db()
self.assertTrue(fallback.is_default)
@@ -167,10 +167,10 @@ class ModelTests(TestCase):
template = NotificationTemplate(
channel=DeliveryChannel.EMAIL,
name="t",
- subject_template="Hello {{ user.username }}",
- body_template="{{ notification.verb }}",
+ subject="Hello {{ user.username }}",
+ 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_body(context), "Go")
self.assertEqual(str(template), "t")
@@ -179,9 +179,9 @@ class ModelTests(TestCase):
template = NotificationTemplate(
channel=DeliveryChannel.EMAIL,
name="t",
- body_template="{{ notification.verb }}",
+ body="{{ notification.title }}",
)
- rendered = template.render_body({"notification": {"verb": ""}})
+ rendered = template.render_body({"notification": {"title": ""}})
self.assertNotIn("