Send notifications to a Django user group and keep a type mandatory for that group.
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
parent
8e91d2179d
commit
86361bb986
42
Readme.md
42
Readme.md
|
|
@ -57,6 +57,20 @@ create_notification(
|
|||
|
||||
`user` в получателе необязателен для `email`, `sms`, `max` и `telegram`. Без пользователя адрес берётся только из `target`. Рядом можно передать `content_object` — сохранённый экземпляр любой модели, например пациента или клиента. Это кто получает сообщение, и это не то же поле, что `content_object` у самого уведомления. Несохранённый экземпляр даёт `ValueError`. `browser` без `user` даёт `ValueError`: входящие читает только авторизованный пользователь. Предпочтения канала и `group=True` применяются только к получателю с `user`. Дубль — тот же `user` и тот же канал внутри одного уведомления. Получатель без `user` повтором не считается.
|
||||
|
||||
`group` в получателе — это группа пользователей Django (`django.contrib.auth.models.Group` или её `name`). Это не категория `NotificationGroup` и не аргумент `group=True`, который схлопывает повторные browser-уведомления. В момент создания активные участники становятся обычными получателями: каждому копируются те же `channels`, тот же `target` и `content_object` получателя, если он передан. Неактивный пользователь пропускается. Пустая группа, неизвестное имя, а также `user` и `group` в одном получателе дают ошибку, уведомление не сохраняется. Один общий `target` уходит отдельной доставкой каждому участнику.
|
||||
|
||||
```python
|
||||
create_notification(
|
||||
notification_type="appointment.online",
|
||||
description="Иванов, 12:00",
|
||||
recipients=[
|
||||
{"group": "registrars", "channels": [{"channel": "browser"}]},
|
||||
],
|
||||
)
|
||||
```
|
||||
|
||||
Если `recipients` не переданы, а у типа есть привязки к группам пользователей, получатели берутся оттуда, каналы — с типа. Канал, которому нужен `target`, так не отправляется: его задают явно в `recipients`.
|
||||
|
||||
```python
|
||||
create_notification(
|
||||
title="Запись подтверждена",
|
||||
|
|
@ -75,6 +89,8 @@ create_notification(
|
|||
|
||||
Получатель канала задаётся словарём `target`, который проверяется pydantic-схемой провайдера: `email` — `{"email": ...}`, `telegram` — `{"chat_id": ...}`, `max` — `{"chat_id": ..., "user_id": ...}` (`user_id` необязателен), `sms` — `{"phone": ...}`. У `browser` `target` нет. В базе он хранится в `NotificationRecipient.target`. Если у типа `is_configurable=True` и у получателя есть `user`, канал с `NotificationChannelPreference.is_enabled=False` не создаётся. Строки предпочтения нет — канал берёт `NotificationType.is_enabled_by_default` (по умолчанию включён). `is_configurable=False` не смотрит ни на предпочтения, ни на этот флаг. Без `user` предпочтения не фильтруют каналы. Если после фильтра не осталось получателей, уведомление откатывается.
|
||||
|
||||
Участник группы из `RecipientGroupSpec` с `is_configurable=False` не может выключить этот тип: предпочтение не смотрится ни при отправке на группу, ни при явной отправке ему. `channel_preferences` такой тип ему не отдаёт, `save_channel_preferences` отвечает `ValueError`. Если пользователь входит в несколько привязок одного типа, неотключаемая побеждает. Когда все привязки отключаемые и своей строки предпочтения нет, канал включён, если хотя бы одна из них включена по умолчанию. Пользователь вне этих групп живёт по флагам типа.
|
||||
|
||||
Повтор с тем же `idempotency_key` возвращает уже созданную строку и не добавляет новые файлы. `content_object` — сохранённый экземпляр любой модели; в базе это пара `content_type` и `object_id`. Несохранённый экземпляр даёт `ValueError`. `group=True` при заданном `content_object` увеличивает `data["count"]` у непрочитанного browser-уведомления того же типа, того же `content_type` и того же `object_id` и не создаёт новую строку. Две разные модели с одинаковым pk не схлопываются. Пустая ссылка всегда создаёт новую строку. Файлы такого вызова копируются и на схлопнутое уведомление, и на новое, если часть получателей не схлопнулась. Удаление объекта, на который указывает ссылка, уведомление не удаляет.
|
||||
|
||||
`show_popup=True` помечает уведомление для всплывающего показа в интерфейсе. По умолчанию флаг выключен. Библиотека только сохраняет и отдаёт его через browser API: отрисовка toast и учёт уже показанных уведомлений остаются на стороне клиента хост-приложения.
|
||||
|
|
@ -159,6 +175,32 @@ create_notification(
|
|||
|
||||
Код перезаписывает имя, каналы, группу, заголовок, флаги и текст шаблонов зарегистрированного типа. Правка этих полей в админке пропадёт на следующем `migrate`. Типы и шаблоны, которых нет в реестре, не меняются. Удаление кода из реестра строку не удаляет и не выключает: чтобы тип перестал отправляться, оставьте его в реестре с `is_active=False`.
|
||||
|
||||
Группу пользователей к типу привязывает `RecipientGroupSpec`. Имя — `name` группы Django. Реестр эту группу не создаёт: состав по-прежнему задаёт хост. `migrate` пишет `NotificationTypeRecipientGroup` и удаляет у этого типа привязки, которых в спеке больше нет. Повторная синхронизация обновляет флаги. Правка привязки в админке пропадёт на следующем `migrate`. Дубль имени в одном типе и пустое имя дают `ValueError` при регистрации.
|
||||
|
||||
`GroupSpec` остаётся категорией типов. `group` у получателя и `RecipientGroupSpec` — группа пользователей. Аргумент `group=True` схлопывает повторные browser-уведомления.
|
||||
|
||||
```python
|
||||
from notify.registry import GroupSpec, RecipientGroupSpec, TypeSpec, register
|
||||
|
||||
register(
|
||||
GroupSpec("appointment", "Записи на приём"),
|
||||
TypeSpec(
|
||||
code="appointment.online",
|
||||
name="Онлайн запись на приём",
|
||||
group="appointment",
|
||||
channels=("browser",),
|
||||
title="Онлайн-запись на приём",
|
||||
is_configurable=True,
|
||||
is_enabled_by_default=False,
|
||||
recipient_groups=(
|
||||
RecipientGroupSpec("registrars", is_configurable=False),
|
||||
),
|
||||
),
|
||||
)
|
||||
```
|
||||
|
||||
`is_configurable=False` у привязки значит, что участникам `registrars` этот тип нельзя выключить. Для остальных пользователей тип остаётся отключаемым. `is_enabled_by_default` привязки заменяет флаг типа, пока у пользователя нет своей строки предпочтения. Без `recipients` такое уведомление уходит активным участникам привязанных групп по каналам типа. Канал с обязательным `target` нужно передать явно.
|
||||
|
||||
## Доставка
|
||||
|
||||
Каналы `email`, `max`, `telegram` и `sms` ставятся в Celery-задачу `notify.tasks.deliver_notification` после коммита транзакции. Канал `browser` помечается отправленным сразу и попадает в API.
|
||||
|
|
|
|||
|
|
@ -18,6 +18,7 @@ from .models import (
|
|||
NotificationGroup,
|
||||
NotificationTemplate,
|
||||
NotificationType,
|
||||
NotificationTypeRecipientGroup,
|
||||
Notification,
|
||||
NotificationRecipient,
|
||||
VerificationCode,
|
||||
|
|
@ -31,6 +32,7 @@ __all__ = [
|
|||
"DeliveryTokenConfigAdmin",
|
||||
"NotificationTemplateAdmin",
|
||||
"NotificationGroupAdmin",
|
||||
"NotificationTypeRecipientGroupInline",
|
||||
"NotificationTypeAdmin",
|
||||
"NotificationAttachmentInline",
|
||||
"NotificationRecipientInline",
|
||||
|
|
@ -184,9 +186,15 @@ class NotificationTypeForm(forms.ModelForm):
|
|||
fields = "__all__"
|
||||
|
||||
|
||||
class NotificationTypeRecipientGroupInline(admin.TabularInline):
|
||||
model = NotificationTypeRecipientGroup
|
||||
extra = 0
|
||||
|
||||
|
||||
@admin.register(NotificationType)
|
||||
class NotificationTypeAdmin(admin.ModelAdmin):
|
||||
form = NotificationTypeForm
|
||||
inlines = [NotificationTypeRecipientGroupInline]
|
||||
list_display = (
|
||||
'code',
|
||||
'name',
|
||||
|
|
|
|||
|
|
@ -174,13 +174,14 @@ def preferences(request):
|
|||
types = NotificationType.objects.filter(
|
||||
is_active=True,
|
||||
is_configurable=True,
|
||||
code__in=saved,
|
||||
).select_related("group")
|
||||
return [
|
||||
{
|
||||
"code": notification_type.code,
|
||||
"name": notification_type.name,
|
||||
"group_name": notification_type.group.name,
|
||||
"channels": saved.get(notification_type.code, []),
|
||||
"channels": saved[notification_type.code],
|
||||
}
|
||||
for notification_type in types
|
||||
]
|
||||
|
|
|
|||
|
|
@ -0,0 +1,48 @@
|
|||
import uuid
|
||||
|
||||
import django.db.models.deletion
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
("notify", "0002_notification_show_popup"),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.CreateModel(
|
||||
name="NotificationTypeRecipientGroup",
|
||||
fields=[
|
||||
(
|
||||
"id",
|
||||
models.UUIDField(
|
||||
default=uuid.uuid4,
|
||||
editable=False,
|
||||
primary_key=True,
|
||||
serialize=False,
|
||||
),
|
||||
),
|
||||
("group_name", models.CharField(max_length=150)),
|
||||
("is_configurable", models.BooleanField(default=True)),
|
||||
("is_enabled_by_default", models.BooleanField(default=True)),
|
||||
(
|
||||
"notification_type",
|
||||
models.ForeignKey(
|
||||
on_delete=django.db.models.deletion.CASCADE,
|
||||
related_name="recipient_groups",
|
||||
to="notify.notificationtype",
|
||||
),
|
||||
),
|
||||
],
|
||||
options={
|
||||
"ordering": ("group_name",),
|
||||
"constraints": [
|
||||
models.UniqueConstraint(
|
||||
fields=("notification_type", "group_name"),
|
||||
name="uniq_type_recipient_group",
|
||||
)
|
||||
],
|
||||
},
|
||||
),
|
||||
]
|
||||
|
|
@ -18,7 +18,11 @@ from notify.models.notification import (
|
|||
NotificationRecipient,
|
||||
default_expires_at,
|
||||
)
|
||||
from notify.models.notification_type import NotificationChannelPreference, NotificationType
|
||||
from notify.models.notification_type import (
|
||||
NotificationChannelPreference,
|
||||
NotificationType,
|
||||
NotificationTypeRecipientGroup,
|
||||
)
|
||||
from notify.models.template import NotificationTemplate
|
||||
|
||||
default_expires_at.__module__ = "notify.models"
|
||||
|
|
@ -39,6 +43,7 @@ __all__ = [
|
|||
"DeliveryTokenConfig",
|
||||
"NotificationTemplate",
|
||||
"NotificationChannelPreference",
|
||||
"NotificationTypeRecipientGroup",
|
||||
"Notification",
|
||||
"NotificationAttachment",
|
||||
"NotificationRecipient",
|
||||
|
|
|
|||
|
|
@ -10,6 +10,7 @@ from notify.models.managers import NotificationTypeManager
|
|||
__all__ = [
|
||||
"NotificationType",
|
||||
"NotificationChannelPreference",
|
||||
"NotificationTypeRecipientGroup",
|
||||
]
|
||||
|
||||
|
||||
|
|
@ -63,3 +64,27 @@ class NotificationChannelPreference(models.Model):
|
|||
def __str__(self):
|
||||
state = "on" if self.is_enabled else "off"
|
||||
return f"{self.user_id} {self.channel} {state}"
|
||||
|
||||
|
||||
class NotificationTypeRecipientGroup(models.Model):
|
||||
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
|
||||
notification_type = models.ForeignKey(
|
||||
NotificationType,
|
||||
on_delete=models.CASCADE,
|
||||
related_name="recipient_groups",
|
||||
)
|
||||
group_name = models.CharField(max_length=150)
|
||||
is_configurable = models.BooleanField(default=True)
|
||||
is_enabled_by_default = models.BooleanField(default=True)
|
||||
|
||||
class Meta:
|
||||
ordering = ("group_name",)
|
||||
constraints = [
|
||||
models.UniqueConstraint(
|
||||
fields=["notification_type", "group_name"],
|
||||
name="uniq_type_recipient_group",
|
||||
),
|
||||
]
|
||||
|
||||
def __str__(self):
|
||||
return self.group_name
|
||||
|
|
|
|||
|
|
@ -3,11 +3,19 @@ from dataclasses import dataclass
|
|||
from django.core.exceptions import ValidationError
|
||||
from django.db import transaction
|
||||
|
||||
from notify.models import NotificationGroup, NotificationTemplate, NotificationType
|
||||
from django.contrib.auth.models import Group as AuthGroup
|
||||
|
||||
from notify.models import (
|
||||
NotificationGroup,
|
||||
NotificationTemplate,
|
||||
NotificationType,
|
||||
NotificationTypeRecipientGroup,
|
||||
)
|
||||
from notify.models.choices import validate_delivery_channels
|
||||
|
||||
__all__ = [
|
||||
"GroupSpec",
|
||||
"RecipientGroupSpec",
|
||||
"TemplateSpec",
|
||||
"TypeSpec",
|
||||
"clear",
|
||||
|
|
@ -48,6 +56,20 @@ class GroupSpec:
|
|||
_require_text(self.name, "Notification group name", NotificationGroup._meta.get_field("name").max_length)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class RecipientGroupSpec:
|
||||
group: str
|
||||
is_configurable: bool = True
|
||||
is_enabled_by_default: bool = True
|
||||
|
||||
def __post_init__(self):
|
||||
_require_text(
|
||||
self.group,
|
||||
"Recipient group name",
|
||||
AuthGroup._meta.get_field("name").max_length,
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class TemplateSpec:
|
||||
channel: str
|
||||
|
|
@ -74,6 +96,7 @@ class TypeSpec:
|
|||
is_configurable: bool = True
|
||||
is_enabled_by_default: bool = True
|
||||
templates: tuple[TemplateSpec, ...] = ()
|
||||
recipient_groups: tuple[RecipientGroupSpec, ...] = ()
|
||||
|
||||
def __post_init__(self):
|
||||
code_field = NotificationType._meta.get_field("code")
|
||||
|
|
@ -100,8 +123,10 @@ class TypeSpec:
|
|||
templates.append(template)
|
||||
if self.title is not None:
|
||||
_require_text(self.title, "title", title_field.max_length)
|
||||
recipient_groups = _check_recipient_groups(self.code, self.recipient_groups)
|
||||
object.__setattr__(self, "channels", channels)
|
||||
object.__setattr__(self, "templates", tuple(sorted(templates, key=lambda item: item.channel)))
|
||||
object.__setattr__(self, "recipient_groups", recipient_groups)
|
||||
|
||||
|
||||
def register(*specs: GroupSpec | TypeSpec) -> None:
|
||||
|
|
@ -143,6 +168,7 @@ def sync_registered() -> None:
|
|||
},
|
||||
)
|
||||
_sync_templates(notification_type, spec)
|
||||
_sync_recipient_groups(notification_type, spec)
|
||||
|
||||
|
||||
def _register_group(spec: GroupSpec) -> None:
|
||||
|
|
@ -161,6 +187,39 @@ def _register_type(spec: TypeSpec) -> None:
|
|||
_types[spec.code] = spec
|
||||
|
||||
|
||||
def _check_recipient_groups(type_code, recipient_groups):
|
||||
if isinstance(recipient_groups, str) or not isinstance(recipient_groups, (list, tuple)):
|
||||
raise ValueError("recipient_groups must be a list")
|
||||
groups = []
|
||||
seen = set()
|
||||
for item in recipient_groups:
|
||||
if not isinstance(item, RecipientGroupSpec):
|
||||
raise ValueError("recipient_groups must be RecipientGroupSpec instances")
|
||||
if item.group in seen:
|
||||
raise ValueError(f"Duplicate recipient group {item.group} for notification type {type_code}")
|
||||
seen.add(item.group)
|
||||
groups.append(item)
|
||||
return tuple(sorted(groups, key=lambda item: item.group))
|
||||
|
||||
|
||||
def _sync_recipient_groups(notification_type: NotificationType, spec: TypeSpec) -> None:
|
||||
kept = []
|
||||
for item in spec.recipient_groups:
|
||||
kept.append(item.group)
|
||||
NotificationTypeRecipientGroup.objects.update_or_create(
|
||||
notification_type=notification_type,
|
||||
group_name=item.group,
|
||||
defaults={
|
||||
"is_configurable": item.is_configurable,
|
||||
"is_enabled_by_default": item.is_enabled_by_default,
|
||||
},
|
||||
)
|
||||
stale = notification_type.recipient_groups.all()
|
||||
if kept:
|
||||
stale = stale.exclude(group_name__in=kept)
|
||||
stale.delete()
|
||||
|
||||
|
||||
def _sync_templates(notification_type: NotificationType, spec: TypeSpec) -> None:
|
||||
kept = []
|
||||
for template in spec.templates:
|
||||
|
|
|
|||
|
|
@ -1,3 +1,4 @@
|
|||
from django.contrib.auth.models import Group
|
||||
from django.contrib.contenttypes.models import ContentType
|
||||
from django.db import IntegrityError, transaction
|
||||
from django.utils import timezone
|
||||
|
|
@ -35,8 +36,32 @@ def _existing_idempotent(idempotency_key):
|
|||
return Notification.objects.filter(idempotency_key=idempotency_key).first()
|
||||
|
||||
|
||||
def _user_group_names(user):
|
||||
if user is None or not getattr(user, "pk", None):
|
||||
return ()
|
||||
return tuple(user.groups.values_list("name", flat=True))
|
||||
|
||||
|
||||
def _delivery_default(notification_type, user, group_names=None):
|
||||
if notification_type is None or not notification_type.is_configurable:
|
||||
return True, True
|
||||
if group_names is None:
|
||||
group_names = _user_group_names(user)
|
||||
links = []
|
||||
if group_names:
|
||||
links = list(notification_type.recipient_groups.filter(group_name__in=group_names))
|
||||
if any(not link.is_configurable for link in links):
|
||||
return True, True
|
||||
if links:
|
||||
return False, any(link.is_enabled_by_default for link in links)
|
||||
return False, notification_type.is_enabled_by_default
|
||||
|
||||
|
||||
def _allowed_channels(notification_type, user, channels):
|
||||
if notification_type is None or not notification_type.is_configurable or user is None:
|
||||
if notification_type is None or user is None:
|
||||
return channels
|
||||
locked, default_enabled = _delivery_default(notification_type, user)
|
||||
if locked:
|
||||
return channels
|
||||
allowed = set(notification_type.channels)
|
||||
prefs = {
|
||||
|
|
@ -54,11 +79,66 @@ 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.is_enabled_by_default):
|
||||
if prefs.get(channel, default_enabled):
|
||||
kept.append(channel_data)
|
||||
return kept
|
||||
|
||||
|
||||
def _resolve_auth_group(group):
|
||||
if isinstance(group, Group):
|
||||
return group
|
||||
if isinstance(group, str):
|
||||
if not group.strip():
|
||||
raise ValueError("group name is required")
|
||||
return Group.objects.get(name=group)
|
||||
raise ValueError("group must be a Group or a name")
|
||||
|
||||
|
||||
def _expand_groups(recipients):
|
||||
expanded = []
|
||||
for recipient_data in recipients:
|
||||
group = recipient_data.get("group")
|
||||
user = recipient_data.get("user")
|
||||
if group is not None and user is not None:
|
||||
raise ValueError("Recipient cannot have both user and group")
|
||||
if group is None:
|
||||
expanded.append(recipient_data)
|
||||
continue
|
||||
group = _resolve_auth_group(group)
|
||||
channels = recipient_data.get("channels") or []
|
||||
members = group.user_set.filter(is_active=True).order_by("pk")
|
||||
if not members.exists():
|
||||
raise ValueError(f"Group {group.name} has no active users")
|
||||
content_object = recipient_data.get("content_object")
|
||||
for member in members:
|
||||
item = {"user": member, "channels": list(channels)}
|
||||
if content_object is not None:
|
||||
item["content_object"] = content_object
|
||||
expanded.append(item)
|
||||
return expanded
|
||||
|
||||
|
||||
def _recipients_from_type(notification_type):
|
||||
if notification_type is None:
|
||||
return None
|
||||
links = list(notification_type.recipient_groups.all())
|
||||
if not links:
|
||||
return None
|
||||
for channel in notification_type.channels:
|
||||
provider = get_provider(channel)
|
||||
if provider is None:
|
||||
raise ValueError(f"No delivery provider registered for channel: {channel}")
|
||||
if provider.target_schema is not None:
|
||||
raise ValueError(f"Channel {channel} requires a target; pass recipients")
|
||||
return [
|
||||
{
|
||||
"group": link.group_name,
|
||||
"channels": [{"channel": channel} for channel in notification_type.channels],
|
||||
}
|
||||
for link in links
|
||||
]
|
||||
|
||||
|
||||
def _content_link(content_object):
|
||||
if content_object is None:
|
||||
return None, ""
|
||||
|
|
@ -162,7 +242,7 @@ def _attach_recipients(notification, recipients, notification_type):
|
|||
|
||||
def create_notification(
|
||||
*,
|
||||
recipients: list[dict],
|
||||
recipients: list[dict] | None = None,
|
||||
title: str | None = None,
|
||||
url: str | None = None,
|
||||
notification_type: NotificationType | str | None = None,
|
||||
|
|
@ -194,12 +274,15 @@ def create_notification(
|
|||
|
||||
content_type, object_id = _content_link(content_object)
|
||||
|
||||
if recipients is None:
|
||||
recipients = _recipients_from_type(notification_type)
|
||||
if not recipients:
|
||||
raise ValueError("At least one recipient is required")
|
||||
|
||||
stored_attachments = []
|
||||
try:
|
||||
with transaction.atomic():
|
||||
recipients = _expand_groups(recipients)
|
||||
for recipient_data in recipients:
|
||||
if not (recipient_data.get("channels") or []):
|
||||
raise ValueError("Recipient has no channels")
|
||||
|
|
@ -246,32 +329,40 @@ def create_notification(
|
|||
|
||||
|
||||
def channel_preferences(user):
|
||||
group_names = _user_group_names(user)
|
||||
types = NotificationType.objects.filter(is_active=True, is_configurable=True)
|
||||
saved = {
|
||||
(pref.notification_type_id, pref.channel): pref.is_enabled
|
||||
for pref in NotificationChannelPreference.objects.filter(user=user)
|
||||
}
|
||||
return [
|
||||
visible = []
|
||||
for notification_type in types:
|
||||
locked, default_enabled = _delivery_default(notification_type, user, group_names)
|
||||
if locked:
|
||||
continue
|
||||
visible.append(
|
||||
{
|
||||
"code": notification_type.code,
|
||||
"channels": [
|
||||
{
|
||||
"channel": channel,
|
||||
"is_enabled": saved.get(
|
||||
(notification_type.id, channel),
|
||||
notification_type.is_enabled_by_default,
|
||||
),
|
||||
"is_enabled": saved.get((notification_type.id, channel), default_enabled),
|
||||
}
|
||||
for channel in notification_type.channels
|
||||
],
|
||||
}
|
||||
for notification_type in types
|
||||
]
|
||||
)
|
||||
return visible
|
||||
|
||||
|
||||
def save_channel_preferences(user, items):
|
||||
for item in items:
|
||||
notification_type = NotificationType.objects.get(code=item["code"], is_configurable=True)
|
||||
locked, _default_enabled = _delivery_default(notification_type, user)
|
||||
if locked:
|
||||
raise ValueError(
|
||||
f"Notification type {notification_type.code} cannot be disabled for this user"
|
||||
)
|
||||
for channel_item in item["channels"]:
|
||||
channel = channel_item["channel"]
|
||||
if channel not in notification_type.channels:
|
||||
|
|
|
|||
|
|
@ -10,8 +10,17 @@ from notify.models import (
|
|||
NotificationGroup,
|
||||
NotificationTemplate,
|
||||
NotificationType,
|
||||
NotificationTypeRecipientGroup,
|
||||
)
|
||||
from notify.registry import (
|
||||
GroupSpec,
|
||||
RecipientGroupSpec,
|
||||
TemplateSpec,
|
||||
TypeSpec,
|
||||
clear,
|
||||
register,
|
||||
sync_registered,
|
||||
)
|
||||
from notify.registry import GroupSpec, TemplateSpec, TypeSpec, clear, register, sync_registered
|
||||
from notify.services import create_notification
|
||||
from notify.tasks import deliver_notification
|
||||
|
||||
|
|
@ -243,6 +252,78 @@ class RegistryTests(TestCase):
|
|||
)
|
||||
)
|
||||
|
||||
def test_sync_writes_recipient_groups_and_drops_removed_ones(self):
|
||||
register(
|
||||
GroupSpec("appointment", "Записи"),
|
||||
TypeSpec(
|
||||
code="appointment.online",
|
||||
name="Онлайн запись",
|
||||
group="appointment",
|
||||
channels=("browser",),
|
||||
title="Онлайн-запись",
|
||||
is_enabled_by_default=False,
|
||||
recipient_groups=(
|
||||
RecipientGroupSpec("registrars", is_configurable=False),
|
||||
RecipientGroupSpec("doctors", is_enabled_by_default=False),
|
||||
),
|
||||
),
|
||||
)
|
||||
sync_registered()
|
||||
kind = NotificationType.objects.get(code="appointment.online")
|
||||
registrars = kind.recipient_groups.get(group_name="registrars")
|
||||
self.assertFalse(registrars.is_configurable)
|
||||
self.assertTrue(registrars.is_enabled_by_default)
|
||||
self.assertFalse(kind.recipient_groups.get(group_name="doctors").is_enabled_by_default)
|
||||
|
||||
other = NotificationType.objects.create(
|
||||
code="invoice",
|
||||
name="Invoice",
|
||||
group=NotificationGroup.objects.create(code="billing", name="Billing"),
|
||||
channels=["browser"],
|
||||
)
|
||||
kept = NotificationTypeRecipientGroup.objects.create(
|
||||
notification_type=other,
|
||||
group_name="billing",
|
||||
)
|
||||
|
||||
clear()
|
||||
register(
|
||||
GroupSpec("appointment", "Записи"),
|
||||
TypeSpec(
|
||||
code="appointment.online",
|
||||
name="Онлайн запись",
|
||||
group="appointment",
|
||||
channels=("browser",),
|
||||
title="Онлайн-запись",
|
||||
recipient_groups=(
|
||||
RecipientGroupSpec("registrars", is_configurable=True, is_enabled_by_default=False),
|
||||
),
|
||||
),
|
||||
)
|
||||
sync_registered()
|
||||
|
||||
registrars.refresh_from_db()
|
||||
self.assertTrue(registrars.is_configurable)
|
||||
self.assertFalse(registrars.is_enabled_by_default)
|
||||
self.assertFalse(kind.recipient_groups.filter(group_name="doctors").exists())
|
||||
kept.refresh_from_db()
|
||||
self.assertEqual(kept.group_name, "billing")
|
||||
|
||||
def test_duplicate_recipient_group_is_rejected(self):
|
||||
with self.assertRaisesMessage(ValueError, "Duplicate recipient group registrars"):
|
||||
TypeSpec(
|
||||
code="appointment.online",
|
||||
name="Онлайн запись",
|
||||
group="appointment",
|
||||
channels=("browser",),
|
||||
recipient_groups=(
|
||||
RecipientGroupSpec("registrars"),
|
||||
RecipientGroupSpec("registrars", is_configurable=False),
|
||||
),
|
||||
)
|
||||
with self.assertRaisesMessage(ValueError, "Recipient group name is required"):
|
||||
RecipientGroupSpec(" ")
|
||||
|
||||
def test_post_migrate_syncs_registered_types(self):
|
||||
register(*appointment_specs())
|
||||
receiver = next(
|
||||
|
|
|
|||
|
|
@ -16,6 +16,7 @@ from notify.models import (
|
|||
NotificationLevel,
|
||||
NotificationRecipient,
|
||||
NotificationType,
|
||||
NotificationTypeRecipientGroup,
|
||||
)
|
||||
from notify.services import channel_preferences, create_notification, save_channel_preferences
|
||||
|
||||
|
|
@ -786,3 +787,212 @@ class GroupingAndIdempotencyTests(TestCase):
|
|||
self.assertEqual(returned.pk, existing.pk)
|
||||
self.assertEqual(Notification.objects.count(), 1)
|
||||
self.assertEqual(existing.recipients.count(), 0)
|
||||
|
||||
|
||||
class RecipientGroupTests(TestCase):
|
||||
def setUp(self):
|
||||
self.alice = User.objects.create_user("alice", "alice@example.com", "pass")
|
||||
self.bob = User.objects.create_user("bob", "bob@example.com", "pass")
|
||||
self.inactive = User.objects.create_user("cara", "cara@example.com", "pass", is_active=False)
|
||||
self.registrars = Group.objects.create(name="registrars")
|
||||
self.registrars.user_set.add(self.alice, self.bob, self.inactive)
|
||||
self.category = NotificationGroup.objects.create(code="appointment", name="Appointments")
|
||||
self.kind = NotificationType.objects.create(
|
||||
code="appointment.online",
|
||||
name="Online",
|
||||
group=self.category,
|
||||
channels=[DeliveryChannel.BROWSER, DeliveryChannel.EMAIL],
|
||||
title="Online",
|
||||
is_configurable=True,
|
||||
is_enabled_by_default=True,
|
||||
)
|
||||
NotificationTypeRecipientGroup.objects.create(
|
||||
notification_type=self.kind,
|
||||
group_name="registrars",
|
||||
is_configurable=False,
|
||||
)
|
||||
|
||||
def test_group_expands_to_active_members_and_copies_the_target(self):
|
||||
patient = NotificationGroup.objects.create(code="patient", name="Patient")
|
||||
notification = create_notification(
|
||||
notification_type=self.kind,
|
||||
recipients=[
|
||||
{
|
||||
"group": self.registrars,
|
||||
"content_object": patient,
|
||||
"channels": [
|
||||
{"channel": DeliveryChannel.BROWSER},
|
||||
{"channel": DeliveryChannel.EMAIL, "target": {"email": "desk@example.com"}},
|
||||
],
|
||||
}
|
||||
],
|
||||
)
|
||||
rows = {
|
||||
(row.user_id, row.channel): row
|
||||
for row in notification.recipients.all()
|
||||
}
|
||||
self.assertEqual(
|
||||
set(rows),
|
||||
{
|
||||
(self.alice.pk, DeliveryChannel.BROWSER),
|
||||
(self.alice.pk, DeliveryChannel.EMAIL),
|
||||
(self.bob.pk, DeliveryChannel.BROWSER),
|
||||
(self.bob.pk, DeliveryChannel.EMAIL),
|
||||
},
|
||||
)
|
||||
self.assertEqual(rows[(self.alice.pk, DeliveryChannel.EMAIL)].target, {"email": "desk@example.com"})
|
||||
self.assertEqual(rows[(self.bob.pk, DeliveryChannel.EMAIL)].target, {"email": "desk@example.com"})
|
||||
self.assertEqual(rows[(self.alice.pk, DeliveryChannel.BROWSER)].content_object, patient)
|
||||
|
||||
def test_group_name_empty_group_and_mixed_recipient_are_rejected(self):
|
||||
notification = create_notification(
|
||||
title="Hi",
|
||||
recipients=[{"group": "registrars", "channels": [{"channel": DeliveryChannel.BROWSER}]}],
|
||||
)
|
||||
self.assertEqual(notification.recipients.count(), 2)
|
||||
|
||||
Group.objects.create(name="empty")
|
||||
with self.assertRaisesMessage(ValueError, "no active users"):
|
||||
create_notification(
|
||||
title="Hi",
|
||||
recipients=[{"group": "empty", "channels": [{"channel": DeliveryChannel.BROWSER}]}],
|
||||
)
|
||||
with self.assertRaises(Group.DoesNotExist):
|
||||
create_notification(
|
||||
title="Hi",
|
||||
recipients=[{"group": "missing", "channels": [{"channel": DeliveryChannel.BROWSER}]}],
|
||||
)
|
||||
with self.assertRaisesMessage(ValueError, "both user and group"):
|
||||
create_notification(
|
||||
title="Hi",
|
||||
recipients=[
|
||||
{
|
||||
"user": self.alice,
|
||||
"group": "registrars",
|
||||
"channels": [{"channel": DeliveryChannel.BROWSER}],
|
||||
}
|
||||
],
|
||||
)
|
||||
with self.assertRaisesMessage(ValueError, "Duplicate"):
|
||||
create_notification(
|
||||
title="Hi",
|
||||
recipients=[
|
||||
{"user": self.alice, "channels": [{"channel": DeliveryChannel.BROWSER}]},
|
||||
{"group": "registrars", "channels": [{"channel": DeliveryChannel.BROWSER}]},
|
||||
],
|
||||
)
|
||||
self.assertEqual(Notification.objects.count(), 1)
|
||||
|
||||
def test_omitted_recipients_use_browser_groups_and_reject_a_target_channel(self):
|
||||
browser_only = NotificationType.objects.create(
|
||||
code="appointment.arrived",
|
||||
name="Arrived",
|
||||
group=self.category,
|
||||
channels=[DeliveryChannel.BROWSER],
|
||||
title="Arrived",
|
||||
)
|
||||
NotificationTypeRecipientGroup.objects.create(
|
||||
notification_type=browser_only,
|
||||
group_name="registrars",
|
||||
)
|
||||
notification = create_notification(notification_type=browser_only)
|
||||
self.assertEqual(
|
||||
set(notification.recipients.values_list("user_id", flat=True)),
|
||||
{self.alice.pk, self.bob.pk},
|
||||
)
|
||||
|
||||
with self.assertRaisesMessage(ValueError, "requires a target"):
|
||||
create_notification(notification_type=self.kind)
|
||||
self.assertEqual(Notification.objects.count(), 1)
|
||||
|
||||
def test_locked_group_ignores_a_disabled_preference(self):
|
||||
NotificationChannelPreference.objects.create(
|
||||
user=self.alice,
|
||||
notification_type=self.kind,
|
||||
channel=DeliveryChannel.BROWSER,
|
||||
is_enabled=False,
|
||||
)
|
||||
self.registrars.user_set.remove(self.bob)
|
||||
doctors = Group.objects.create(name="doctors")
|
||||
doctors.user_set.add(self.bob)
|
||||
NotificationTypeRecipientGroup.objects.create(
|
||||
notification_type=self.kind,
|
||||
group_name="doctors",
|
||||
is_configurable=True,
|
||||
is_enabled_by_default=False,
|
||||
)
|
||||
|
||||
locked = create_notification(
|
||||
notification_type=self.kind,
|
||||
recipients=[{"user": self.alice, "channels": [{"channel": DeliveryChannel.BROWSER}]}],
|
||||
)
|
||||
self.assertEqual(locked.recipients.get().user, self.alice)
|
||||
|
||||
with self.assertRaisesMessage(ValueError, "No recipients to deliver"):
|
||||
create_notification(
|
||||
notification_type=self.kind,
|
||||
recipients=[{"user": self.bob, "channels": [{"channel": DeliveryChannel.BROWSER}]}],
|
||||
)
|
||||
|
||||
nurses = Group.objects.create(name="nurses")
|
||||
nurses.user_set.add(self.bob)
|
||||
NotificationTypeRecipientGroup.objects.create(
|
||||
notification_type=self.kind,
|
||||
group_name="nurses",
|
||||
is_configurable=True,
|
||||
is_enabled_by_default=True,
|
||||
)
|
||||
opened = create_notification(
|
||||
notification_type=self.kind,
|
||||
recipients=[{"group": "doctors", "channels": [{"channel": DeliveryChannel.BROWSER}]}],
|
||||
)
|
||||
self.assertEqual(opened.recipients.get().user, self.bob)
|
||||
|
||||
NotificationChannelPreference.objects.create(
|
||||
user=self.bob,
|
||||
notification_type=self.kind,
|
||||
channel=DeliveryChannel.BROWSER,
|
||||
is_enabled=False,
|
||||
)
|
||||
self.registrars.user_set.add(self.bob)
|
||||
forced = create_notification(
|
||||
notification_type=self.kind,
|
||||
recipients=[{"user": self.bob, "channels": [{"channel": DeliveryChannel.BROWSER}]}],
|
||||
)
|
||||
self.assertEqual(forced.recipients.get().user, self.bob)
|
||||
|
||||
def test_preferences_hide_and_reject_a_locked_group(self):
|
||||
self.assertEqual(
|
||||
[item["code"] for item in channel_preferences(self.alice)],
|
||||
[],
|
||||
)
|
||||
self.registrars.user_set.remove(self.bob)
|
||||
self.assertEqual(channel_preferences(self.bob)[0]["code"], "appointment.online")
|
||||
with self.assertRaisesMessage(ValueError, "cannot be disabled"):
|
||||
save_channel_preferences(
|
||||
self.alice,
|
||||
[
|
||||
{
|
||||
"code": "appointment.online",
|
||||
"channels": [{"channel": DeliveryChannel.BROWSER, "is_enabled": False}],
|
||||
}
|
||||
],
|
||||
)
|
||||
self.assertFalse(NotificationChannelPreference.objects.filter(user=self.alice).exists())
|
||||
|
||||
doctors = Group.objects.create(name="doctors")
|
||||
doctors.user_set.add(self.bob)
|
||||
NotificationTypeRecipientGroup.objects.create(
|
||||
notification_type=self.kind,
|
||||
group_name="doctors",
|
||||
is_configurable=True,
|
||||
is_enabled_by_default=False,
|
||||
)
|
||||
shown = channel_preferences(self.bob)[0]["channels"]
|
||||
self.assertEqual(
|
||||
shown,
|
||||
[
|
||||
{"channel": DeliveryChannel.BROWSER, "is_enabled": False},
|
||||
{"channel": DeliveryChannel.EMAIL, "is_enabled": False},
|
||||
],
|
||||
)
|
||||
|
|
|
|||
Loading…
Reference in New Issue