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

+141 -4
View File
@@ -1,7 +1,16 @@
from django.contrib import admin
from django.utils import timezone
from django.utils.html import format_html
from .models import IdempotencyKey, OutboxMessage, SyncLog, SyncRun
from .models import (
IdempotencyKey,
NotificationSettings,
OutboxMessage,
SyncLog,
SyncRun,
)
from .notifications import send_alert
from .services import stop_sync_run
class SyncLogInline(admin.TabularInline):
@@ -20,11 +29,12 @@ class SyncRunAdmin(admin.ModelAdmin):
"started_at",
"finished_at",
"duration",
"task_id",
)
list_filter = ("entity", "direction", "status")
readonly_fields = ("started_at", "finished_at", "stats", "error")
readonly_fields = ("started_at", "finished_at", "stats", "error", "task_id")
inlines = [SyncLogInline]
actions = ("run_catalog_sync",)
actions = ("run_catalog_sync", "stop_sync")
@admin.display(description="Статус", ordering="status")
def status_badge(self, obj):
@@ -33,6 +43,7 @@ class SyncRunAdmin(admin.ModelAdmin):
SyncRun.Status.SUCCESS: "#16a34a",
SyncRun.Status.PARTIAL: "#d97706",
SyncRun.Status.FAILED: "#dc2626",
SyncRun.Status.STOPPED: "#6b7280",
}
return format_html(
'<span style="display:inline-block;padding:2px 8px;border-radius:10px;'
@@ -56,11 +67,61 @@ class SyncRunAdmin(admin.ModelAdmin):
task = sync_catalog_from_1c.delay()
except Exception as exc: # noqa: BLE001 - show the broker error to the admin
self.message_user(
request, f"Не удалось поставить задачу: {exc}", level="error"
request,
f"Не удалось поставить задачу: {exc}. Проверьте, что Celery и Redis запущены.",
level="error",
)
return
self.message_user(request, f"Задача поставлена в очередь: {task.id}")
@admin.action(description="Остановить синхронизацию")
def stop_sync(self, request, queryset):
stopped = 0
not_running = 0
no_task = 0
failed = 0
for run in queryset:
if run.status != SyncRun.Status.RUNNING:
not_running += 1
continue
try:
outcome = stop_sync_run(run)
except Exception as exc: # noqa: BLE001 - broker may be unavailable
failed += 1
self.message_user(
request,
f"Не удалось остановить сеанс #{run.pk}: {exc}. "
"Проверьте, что Celery и Redis запущены.",
level="error",
)
continue
if outcome == "stopped":
stopped += 1
elif outcome == "no_task":
no_task += 1
else:
not_running += 1
if stopped:
self.message_user(
request, f"Остановлено сеансов: {stopped}", level="warning"
)
if no_task:
self.message_user(
request,
f"Без ID задачи: {no_task}. Такие сеансы запускались вручную "
"или старой версией задачи — остановить их из админки нельзя.",
level="warning",
)
if not_running:
self.message_user(
request, f"Уже завершены, пропущено: {not_running}", level="info"
)
if not (stopped or not_running or no_task or failed):
self.message_user(request, "Нечего останавливать", level="warning")
@admin.register(SyncLog)
class SyncLogAdmin(admin.ModelAdmin):
@@ -104,3 +165,79 @@ class OutboxMessageAdmin(admin.ModelAdmin):
class IdempotencyKeyAdmin(admin.ModelAdmin):
list_display = ("scope", "key", "status_code", "created_at")
search_fields = ("key", "scope")
@admin.register(NotificationSettings)
class NotificationSettingsAdmin(admin.ModelAdmin):
list_display = ("is_enabled", "email_recipients", "telegram_chat_id", "updated_at")
fieldsets = (
(
"Общие",
{
"fields": ("is_enabled",),
"description": (
"Оповещения приходят администратору при сбоях обмена: ошибка "
"выгрузки каталога и заказ, который не удалось передать в 1С. "
"SMS пока не поддерживается — в проекте нет SMS-шлюза."
),
},
),
("Email", {"fields": ("email_recipients",)}),
(
"Telegram",
{
"fields": ("telegram_bot_token", "telegram_chat_id"),
"description": (
"Создайте бота у @BotFather, получите токен и укажите chat_id "
"чата или канала. Если хотя бы одно поле пустое — Telegram "
"не используется."
),
},
),
(
"События",
{"fields": ("notify_catalog_failure", "notify_outbox_dead")},
),
("Служебное", {"fields": ("updated_at",)}),
)
readonly_fields = ("updated_at",)
actions = ("send_test_alert",)
def has_add_permission(self, request):
return not NotificationSettings.objects.exists()
def has_delete_permission(self, request, obj=None):
return False
@admin.action(description="Отправить тестовое уведомление")
def send_test_alert(self, request, queryset):
result = send_alert(
"[HOMM] Тестовое уведомление",
"Проверка каналов оповещения о сбоях обмена. "
f"Время: {timezone.now():%d.%m.%Y %H:%M:%S}.",
)
if not result["enabled"]:
self.message_user(
request,
"Оповещения выключены — включите «оповещения включены» и повторите.",
level="warning",
)
return
delivered = []
if result["email"]:
delivered.append("email")
if result["telegram"]:
delivered.append("Telegram")
if delivered:
self.message_user(
request, f"Уведомление отправлено: {', '.join(delivered)}"
)
else:
self.message_user(
request,
"Ни один канал не настроен или отправка не удалась. "
"Заполните email получателей или токен и chat_id Telegram, "
"ошибки отправки смотрите в журнале приложения.",
level="error",
)