Let notification types start off and call the preference flag configurable.
A missing channel preference now follows enabled_by_default, and can_switch is renamed so it matches that choice. The schema stays a single initial migration. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
parent
512e5e56f6
commit
ee2a97a11b
|
|
@ -55,7 +55,7 @@ create_notification(
|
|||
|
||||
`create_notification` выбрасывает `ValueError`, если тип выключен, канал не входит в тип, канал неизвестен или получатель продублирован. Неактивный тип и пропущенный канал не оставляют пустое уведомление в базе.
|
||||
|
||||
Получатель канала задаётся словарём `target`, который проверяется pydantic-схемой провайдера: `email` — `{"email": ...}`, `telegram` — `{"chat_id": ...}`, `max` — `{"chat_id": ..., "user_id": ...}` (`user_id` необязателен). У `browser` `target` нет. В базе он хранится в `NotificationRecipient.delivery_target`. Если у типа `can_switch=True`, канал с `NotificationChannelPreference.enabled=False` не создаётся. Строки предпочтения нет — канал остаётся включённым. `can_switch=False` не смотрит на предпочтения. Если после фильтра не осталось получателей, уведомление откатывается.
|
||||
Получатель канала задаётся словарём `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` не смотрит ни на предпочтения, ни на этот флаг. Если после фильтра не осталось получателей, уведомление откатывается.
|
||||
|
||||
Повтор с тем же `idempotency_key` возвращает уже созданную строку и не добавляет новые файлы. `group=True` при непустом `object_id` увеличивает `data["count"]` у непрочитанного browser-уведомления того же типа и объекта и не создаёт новую строку. Файлы такого вызова копируются и на схлопнутое уведомление, и на новое, если часть получателей не схлопнулась.
|
||||
|
||||
|
|
@ -135,7 +135,7 @@ NOTIFY_CODE_RESEND_INTERVAL = 60 # секунд, 0 — без ограниче
|
|||
|
||||
`GET list/` отдаёт `attachments`: `id`, `name`, `size`, `content_type`, `url`. `GET attachments/{id}/` скачивает файл, если у текущего пользователя есть получатель этого уведомления и срок не истёк. Чужой и просроченный файл возвращают 404.
|
||||
|
||||
`GET preferences/` отдаёт список активных типов с `can_switch=True`: `code`, `name`, `group_name` и `channels` (`channel`, `enabled`). Нет сохранённого предпочтения — канал включён. `POST preferences/` принимает `{"items": [{"code", "channels": [{"channel", "enabled"}]}]}` и возвращает `{"ok": true}`. Неизвестный канал и тип без `can_switch` дают 400 с `detail`. Пустой `items` ничего не меняет.
|
||||
`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` ничего не меняет.
|
||||
|
||||
API не кэширует ответы и не требует кэша или Redis.
|
||||
|
||||
|
|
|
|||
|
|
@ -186,9 +186,11 @@ class NotificationTypeAdmin(admin.ModelAdmin):
|
|||
'name',
|
||||
'group',
|
||||
'is_active',
|
||||
'enabled_by_default',
|
||||
)
|
||||
list_filter = (
|
||||
'is_active',
|
||||
'enabled_by_default',
|
||||
'group',
|
||||
)
|
||||
search_fields = (
|
||||
|
|
|
|||
|
|
@ -169,7 +169,7 @@ def preferences(request):
|
|||
}
|
||||
types = NotificationType.objects.filter(
|
||||
is_active=True,
|
||||
can_switch=True,
|
||||
configurable=True,
|
||||
).select_related("group")
|
||||
return [
|
||||
{
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
# Generated by Django 5.0.6 on 2026-10-09 13:49
|
||||
# Generated by Django 5.0.6 on 2026-10-11 11:02
|
||||
|
||||
import django.db.models.deletion
|
||||
import notify.fields
|
||||
|
|
@ -112,7 +112,8 @@ class Migration(migrations.Migration):
|
|||
('verb', models.CharField(blank=True, max_length=255, null=True)),
|
||||
('position', models.IntegerField(default=0)),
|
||||
('is_active', models.BooleanField(default=True)),
|
||||
('can_switch', models.BooleanField(default=True)),
|
||||
('configurable', models.BooleanField(default=True)),
|
||||
('enabled_by_default', models.BooleanField(default=True)),
|
||||
],
|
||||
options={
|
||||
'ordering': ('position', 'code'),
|
||||
|
|
|
|||
|
|
@ -22,7 +22,8 @@ class NotificationType(models.Model):
|
|||
verb = models.CharField(max_length=255, null=True, blank=True)
|
||||
position = models.IntegerField(default=0)
|
||||
is_active = models.BooleanField(default=True)
|
||||
can_switch = models.BooleanField(default=True)
|
||||
configurable = models.BooleanField(default=True)
|
||||
enabled_by_default = models.BooleanField(default=True)
|
||||
|
||||
objects = NotificationTypeManager()
|
||||
|
||||
|
|
|
|||
|
|
@ -34,7 +34,7 @@ def _existing_idempotent(idempotency_key):
|
|||
|
||||
|
||||
def _allowed_channels(notification_type, user, channels):
|
||||
if notification_type is None or not notification_type.can_switch:
|
||||
if notification_type is None or not notification_type.configurable:
|
||||
return channels
|
||||
allowed = set(notification_type.channels)
|
||||
prefs = {
|
||||
|
|
@ -52,7 +52,7 @@ 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, True):
|
||||
if prefs.get(channel, notification_type.enabled_by_default):
|
||||
kept.append(channel_data)
|
||||
return kept
|
||||
|
||||
|
|
@ -218,7 +218,7 @@ def create_notification(
|
|||
|
||||
|
||||
def channel_preferences(user):
|
||||
types = NotificationType.objects.filter(is_active=True, can_switch=True)
|
||||
types = NotificationType.objects.filter(is_active=True, configurable=True)
|
||||
saved = {
|
||||
(pref.type_id, pref.channel): pref.enabled
|
||||
for pref in NotificationChannelPreference.objects.filter(user=user)
|
||||
|
|
@ -229,7 +229,10 @@ def channel_preferences(user):
|
|||
"channels": [
|
||||
{
|
||||
"channel": channel,
|
||||
"enabled": saved.get((notification_type.id, channel), True),
|
||||
"enabled": saved.get(
|
||||
(notification_type.id, channel),
|
||||
notification_type.enabled_by_default,
|
||||
),
|
||||
}
|
||||
for channel in notification_type.channels
|
||||
],
|
||||
|
|
@ -240,7 +243,7 @@ def channel_preferences(user):
|
|||
|
||||
def save_channel_preferences(user, items):
|
||||
for item in items:
|
||||
notification_type = NotificationType.objects.get(code=item["code"], can_switch=True)
|
||||
notification_type = NotificationType.objects.get(code=item["code"], configurable=True)
|
||||
for channel_item in item["channels"]:
|
||||
channel = channel_item["channel"]
|
||||
if channel not in notification_type.channels:
|
||||
|
|
|
|||
|
|
@ -306,7 +306,7 @@ class ApiTests(TestCase):
|
|||
name="Security",
|
||||
group=group,
|
||||
channels=[DeliveryChannel.EMAIL],
|
||||
can_switch=False,
|
||||
configurable=False,
|
||||
)
|
||||
NotificationType.objects.create(
|
||||
code="retired",
|
||||
|
|
@ -387,7 +387,7 @@ class ApiTests(TestCase):
|
|||
name="Security",
|
||||
group=group,
|
||||
channels=[DeliveryChannel.EMAIL],
|
||||
can_switch=False,
|
||||
configurable=False,
|
||||
)
|
||||
|
||||
unknown_channel = self._post_preferences(
|
||||
|
|
@ -417,6 +417,43 @@ class ApiTests(TestCase):
|
|||
self.assertIn("detail", locked.json())
|
||||
self.assertFalse(NotificationChannelPreference.objects.exists())
|
||||
|
||||
def test_preferences_use_enabled_by_default_until_overridden(self):
|
||||
kind = self._type("orders.digest")
|
||||
kind.enabled_by_default = False
|
||||
kind.save(update_fields=["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},
|
||||
],
|
||||
)
|
||||
|
||||
saved = self._post_preferences(
|
||||
{
|
||||
"items": [
|
||||
{
|
||||
"code": "orders.digest",
|
||||
"channels": [
|
||||
{"channel": DeliveryChannel.EMAIL, "enabled": True},
|
||||
],
|
||||
}
|
||||
]
|
||||
}
|
||||
)
|
||||
self.assertEqual(saved.status_code, 200)
|
||||
channels = {
|
||||
item["channel"]: item["enabled"]
|
||||
for item in self.client.get("/api/preferences/").json()[0]["channels"]
|
||||
}
|
||||
self.assertEqual(
|
||||
channels,
|
||||
{DeliveryChannel.BROWSER: False, DeliveryChannel.EMAIL: True},
|
||||
)
|
||||
|
||||
|
||||
class PaginationTests(TestCase):
|
||||
def setUp(self):
|
||||
|
|
|
|||
|
|
@ -368,7 +368,7 @@ class ChannelPreferenceTests(TestCase):
|
|||
group=self.group,
|
||||
channels=[DeliveryChannel.EMAIL, DeliveryChannel.BROWSER],
|
||||
verb="Approved",
|
||||
can_switch=True,
|
||||
configurable=True,
|
||||
)
|
||||
|
||||
def test_disabled_channel_is_omitted_and_an_empty_result_rolls_back(self):
|
||||
|
|
@ -424,9 +424,52 @@ class ChannelPreferenceTests(TestCase):
|
|||
)
|
||||
self.assertEqual(notification.recipients.get().delivery_channel, DeliveryChannel.EMAIL)
|
||||
|
||||
def test_missing_preference_drops_a_channel_disabled_by_default(self):
|
||||
self.kind.enabled_by_default = False
|
||||
self.kind.save(update_fields=["enabled_by_default"])
|
||||
self.assertEqual(
|
||||
channel_preferences(self.user)[0]["channels"],
|
||||
[
|
||||
{"channel": DeliveryChannel.EMAIL, "enabled": False},
|
||||
{"channel": DeliveryChannel.BROWSER, "enabled": False},
|
||||
],
|
||||
)
|
||||
with self.assertRaisesMessage(ValueError, "No recipients to deliver"):
|
||||
create_notification(
|
||||
type="approved",
|
||||
recipients=[
|
||||
{
|
||||
"user": self.user,
|
||||
"channels": [
|
||||
{"channel": DeliveryChannel.EMAIL, "target": {"email": self.user.email}},
|
||||
],
|
||||
}
|
||||
],
|
||||
)
|
||||
self.assertEqual(Notification.objects.count(), 0)
|
||||
|
||||
NotificationChannelPreference.objects.create(
|
||||
user=self.user,
|
||||
type=self.kind,
|
||||
channel=DeliveryChannel.EMAIL,
|
||||
enabled=True,
|
||||
)
|
||||
notification = create_notification(
|
||||
type="approved",
|
||||
recipients=[
|
||||
{
|
||||
"user": self.user,
|
||||
"channels": [
|
||||
{"channel": DeliveryChannel.EMAIL, "target": {"email": self.user.email}},
|
||||
],
|
||||
}
|
||||
],
|
||||
)
|
||||
self.assertEqual(notification.recipients.get().delivery_channel, DeliveryChannel.EMAIL)
|
||||
|
||||
def test_locked_type_ignores_a_disabled_preference(self):
|
||||
self.kind.can_switch = False
|
||||
self.kind.save(update_fields=["can_switch"])
|
||||
self.kind.configurable = False
|
||||
self.kind.save(update_fields=["configurable"])
|
||||
NotificationChannelPreference.objects.create(
|
||||
user=self.user,
|
||||
type=self.kind,
|
||||
|
|
@ -452,7 +495,7 @@ class ChannelPreferenceTests(TestCase):
|
|||
name="Security",
|
||||
group=self.group,
|
||||
channels=[DeliveryChannel.EMAIL],
|
||||
can_switch=False,
|
||||
configurable=False,
|
||||
)
|
||||
self.assertEqual(
|
||||
channel_preferences(self.user),
|
||||
|
|
|
|||
Loading…
Reference in New Issue