Bot API client (apps/integration/telegram.py):
- sendMessage, getMe, getUpdates over requests, no extra dependencies
- Telegram API errors are surfaced with the provider description
("chat not found", "bot was blocked") instead of a bare HTTP status
- messages longer than the Bot API limit are truncated with a marker
Notifications:
- notifications.py now goes through the client; failures are logged and
never break the exchange
Setup helpers:
- telegram_check: verifies the token, prints the bot name, sends a test
message, and suggests chats when chat_id is missing
- telegram_chats: lists chats that wrote to the bot, --apply saves the
chat_id when exactly one chat is known
- admin action "Detect chat_id from bot messages" does the same in the UI,
with explicit messages for no chats, many chats and API errors
- admin help text explains the BotFather -> /start -> test flow
Docs: Telegram setup section, command reference and limitations
(4096-char limit, negative chat_id for groups/channels, no internet =
no Telegram).
Tests: 12 new cases for the client, both commands and the admin action;
the suite is 45 passing.
297 lines
11 KiB
Python
297 lines
11 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
|
||
from .telegram import TelegramError, recent_chats
|
||
|
||
|
||
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": (
|
||
"1. Создайте бота у @BotFather и вставьте токен.<br>"
|
||
"2. Напишите боту /start (в группе — любое сообщение) и нажмите "
|
||
"действие «Определить chat_id по сообщениям боту».<br>"
|
||
"3. Проверьте канал действием «Отправить тестовое уведомление».<br>"
|
||
"Те же шаги есть командами: <code>telegram_check</code> и "
|
||
"<code>telegram_chats --apply</code>. Если хотя бы одно поле "
|
||
"пустое — Telegram не используется."
|
||
),
|
||
},
|
||
),
|
||
(
|
||
"События",
|
||
{"fields": ("notify_catalog_failure", "notify_outbox_dead")},
|
||
),
|
||
("Служебное", {"fields": ("updated_at",)}),
|
||
)
|
||
readonly_fields = ("updated_at",)
|
||
actions = ("send_test_alert", "detect_chat_id")
|
||
|
||
def has_add_permission(self, request):
|
||
return not NotificationSettings.objects.exists()
|
||
|
||
def has_delete_permission(self, request, obj=None):
|
||
return False
|
||
|
||
@admin.action(description="Определить chat_id по сообщениям боту")
|
||
def detect_chat_id(self, request, queryset):
|
||
"""Fills chat_id from the chats that wrote to the bot."""
|
||
for config in queryset:
|
||
if not config.telegram_bot_token:
|
||
self.message_user(
|
||
request,
|
||
"Сначала укажите токен бота — без него Telegram не ответит.",
|
||
level="error",
|
||
)
|
||
continue
|
||
|
||
try:
|
||
chats = recent_chats(config.telegram_bot_token)
|
||
except TelegramError as exc:
|
||
self.message_user(
|
||
request, f"Не удалось получить чаты: {exc}", level="error"
|
||
)
|
||
continue
|
||
|
||
if not chats:
|
||
self.message_user(
|
||
request,
|
||
"Боту ещё никто не писал. Откройте бота в Telegram, "
|
||
"отправьте /start и повторите действие.",
|
||
level="warning",
|
||
)
|
||
continue
|
||
|
||
if len(chats) == 1:
|
||
config.telegram_chat_id = chats[0]["id"]
|
||
config.save(update_fields=["telegram_chat_id", "updated_at"])
|
||
self.message_user(
|
||
request,
|
||
f"chat_id сохранён: {chats[0]['id']} ({chats[0]['title']}).",
|
||
)
|
||
continue
|
||
|
||
listing = "; ".join(
|
||
f"{chat['title']} — {chat['id']}" for chat in chats[:5]
|
||
)
|
||
self.message_user(
|
||
request,
|
||
f"Боту писали {len(chats)} чата, автоматически выбрать нельзя. "
|
||
f"Укажите нужный id вручную: {listing}",
|
||
level="warning",
|
||
)
|
||
|
||
@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",
|
||
)
|