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.
244 lines
8.8 KiB
Python
244 lines
8.8 KiB
Python
from django.contrib import admin
|
||
from django.utils import timezone
|
||
from django.utils.html import format_html
|
||
|
||
from .models import (
|
||
IdempotencyKey,
|
||
NotificationSettings,
|
||
OutboxMessage,
|
||
SyncLog,
|
||
SyncRun,
|
||
)
|
||
from .notifications import send_alert
|
||
from .services import stop_sync_run
|
||
|
||
|
||
class SyncLogInline(admin.TabularInline):
|
||
model = SyncLog
|
||
extra = 0
|
||
readonly_fields = ("level", "message", "payload", "created_at")
|
||
can_delete = False
|
||
|
||
|
||
@admin.register(SyncRun)
|
||
class SyncRunAdmin(admin.ModelAdmin):
|
||
list_display = (
|
||
"entity",
|
||
"direction",
|
||
"status_badge",
|
||
"started_at",
|
||
"finished_at",
|
||
"duration",
|
||
"task_id",
|
||
)
|
||
list_filter = ("entity", "direction", "status")
|
||
readonly_fields = ("started_at", "finished_at", "stats", "error", "task_id")
|
||
inlines = [SyncLogInline]
|
||
actions = ("run_catalog_sync", "stop_sync")
|
||
|
||
@admin.display(description="Статус", ordering="status")
|
||
def status_badge(self, obj):
|
||
colors = {
|
||
SyncRun.Status.RUNNING: "#2563eb",
|
||
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;'
|
||
'background:{};color:#fff;font-size:12px;">{}</span>',
|
||
colors.get(obj.status, "#6b7280"),
|
||
obj.get_status_display(),
|
||
)
|
||
|
||
@admin.display(description="Длительность")
|
||
def duration(self, obj):
|
||
if not obj.finished_at:
|
||
return "—"
|
||
seconds = int((obj.finished_at - obj.started_at).total_seconds())
|
||
return f"{seconds} с"
|
||
|
||
@admin.action(description="Запустить синхронизацию каталога")
|
||
def run_catalog_sync(self, request, queryset):
|
||
from .tasks import sync_catalog_from_1c
|
||
|
||
try:
|
||
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}. Проверьте, что 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):
|
||
list_display = ("run", "level", "message", "created_at")
|
||
list_filter = ("level",)
|
||
search_fields = ("message",)
|
||
|
||
|
||
@admin.register(OutboxMessage)
|
||
class OutboxMessageAdmin(admin.ModelAdmin):
|
||
list_display = (
|
||
"topic",
|
||
"status",
|
||
"attempts",
|
||
"next_attempt_at",
|
||
"sent_at",
|
||
"created_at",
|
||
)
|
||
list_filter = ("status", "topic")
|
||
search_fields = ("topic", "last_error")
|
||
readonly_fields = ("created_at", "updated_at")
|
||
actions = ("retry", "mark_dead")
|
||
|
||
@admin.action(description="Повторить отправку")
|
||
def retry(self, request, queryset):
|
||
updated = queryset.update(
|
||
status=OutboxMessage.Status.PENDING,
|
||
attempts=0,
|
||
next_attempt_at=None,
|
||
last_error="",
|
||
)
|
||
self.message_user(request, f"Поставлено в очередь: {updated}")
|
||
|
||
@admin.action(description="Пометить как dead-letter")
|
||
def mark_dead(self, request, queryset):
|
||
updated = queryset.update(status=OutboxMessage.Status.DEAD)
|
||
self.message_user(request, f"Помечено: {updated}")
|
||
|
||
|
||
@admin.register(IdempotencyKey)
|
||
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",
|
||
)
|