Add exchange monitoring controls: stop sync and admin alerts

Stop a running exchange:
- SyncRun gets a Celery task_id and a "stopped" status
- The task is bound and passes its id into the run, so the admin can
  revoke it with app.control.revoke(..., terminate=True)
- Admin action "Stop synchronization" reports stopped, already finished,
  runs without a task id and broker errors separately
- A stopped run is never overwritten by the task result

Alerts about exchange failures:
- NotificationSettings singleton (admin section): on/off, email
  recipients, Telegram bot token and chat id, per-event flags
- notifications.py sends through email and Telegram, best effort:
  delivery errors are logged and never break the exchange
- Fired on catalog apply failure (pull from 1C and inbound push) and on
  outbox messages that exhausted retries
- Admin action "Send test notification" verifies the channels
- SMTP settings added to base.py and .env.example so email really works
  in production; SMS is not implemented (no SMS gateway in the project)

Tests: 11 new cases (email/Telegram delivery, flags, outbox dead-letter,
stop semantics); the suite is 33 passing.
This commit is contained in:
apuc committed 2026-11-22 22:19:43 +03:00
1 parent 3b3e5c429a
commit e1cc6dbaad
11 files changed
+667 -13

No files matched your search

+61
View File
@@ -1,3 +1,5 @@
import re
from django.db import models
from apps.common.models import TimeStampedModel
@@ -22,6 +24,7 @@ class SyncRun(TimeStampedModel):
SUCCESS = "success", "Успешно"
PARTIAL = "partial", "Частично"
FAILED = "failed", "Ошибка"
STOPPED = "stopped", "Остановлено"
direction = models.CharField(max_length=10, choices=Direction.choices)
entity = models.CharField(max_length=20, choices=Entity.choices)
@@ -32,6 +35,9 @@ class SyncRun(TimeStampedModel):
finished_at = models.DateTimeField(null=True, blank=True)
stats = models.JSONField(default=dict, blank=True)
error = models.TextField(blank=True)
task_id = models.CharField(
"ID задачи Celery", max_length=64, blank=True, db_index=True
)
class Meta:
db_table = "integration_sync_run"
@@ -115,3 +121,58 @@ class IdempotencyKey(TimeStampedModel):
def __str__(self) -> str:
return f"{self.scope}:{self.key}"
class NotificationSettings(TimeStampedModel):
"""Singleton with delivery settings for critical exchange alerts.
Administrators configure where failures are reported: email, Telegram or
both. SMS is not implemented yet — there is no SMS provider in the project.
"""
is_enabled = models.BooleanField("оповещения включены", default=True)
email_recipients = models.TextField(
"email получателей",
blank=True,
help_text="Несколько адресов — через запятую, точку с запятой или с новой строки.",
)
telegram_bot_token = models.CharField(
"токен Telegram-бота",
max_length=200,
blank=True,
help_text="Токен от @BotFather. Оставьте пустым, чтобы не отправлять в Telegram.",
)
telegram_chat_id = models.CharField(
"chat_id в Telegram",
max_length=64,
blank=True,
help_text="ID чата или канала, куда писать. Можно узнать у @userinfobot.",
)
notify_catalog_failure = models.BooleanField(
"сообщать о сбоях обмена каталогом", default=True
)
notify_outbox_dead = models.BooleanField(
"сообщать о недоставленных заказах в 1С", default=True
)
class Meta:
db_table = "integration_notification_settings"
verbose_name = "настройки оповещений об обмене"
verbose_name_plural = "настройки оповещений об обмене"
def __str__(self) -> str:
return "Настройки оповещений об обмене"
@classmethod
def load(cls) -> "NotificationSettings":
obj, _ = cls.objects.get_or_create(pk=1)
return obj
def email_list(self) -> list[str]:
chunks = re.split(r"[,;\s]+", self.email_recipients or "")
return [chunk.strip() for chunk in chunks if chunk.strip()]
@property
def telegram_configured(self) -> bool:
return bool(self.telegram_bot_token and self.telegram_chat_id)