Files
homm/backend/apps/integration/notifications.py
T
apuc e1cc6dbaad 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.
2026-11-22 22:19:43 +03:00

130 lines
4.7 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Delivery of critical exchange alerts to administrators.
Admins configure the channels in the admin panel
(:class:`apps.integration.models.NotificationSettings`): email, Telegram or
both. Alerts are best-effort — a failure to notify must never break the
exchange itself, so every transport swallows its own errors and only logs them.
"""
import logging
import requests
from django.conf import settings
from django.core.mail import send_mail
from django.utils import timezone
from .models import NotificationSettings
logger = logging.getLogger(__name__)
TELEGRAM_API_URL = "https://api.telegram.org/bot{token}/sendMessage"
TELEGRAM_TIMEOUT = 10
ADMIN_SYNC_URL = "/admin/integration/syncrun/{pk}/change/"
def _send_email(config: NotificationSettings, subject: str, message: str) -> bool:
recipients = config.email_list()
if not recipients:
return False
try:
send_mail(
subject,
message,
settings.DEFAULT_FROM_EMAIL,
recipients,
fail_silently=False,
)
except Exception: # noqa: BLE001 - alerting must never break the workflow
logger.exception("Не удалось отправить оповещение на email: %s", recipients)
return False
return True
def _send_telegram(config: NotificationSettings, subject: str, message: str) -> bool:
if not config.telegram_configured:
return False
url = TELEGRAM_API_URL.format(token=config.telegram_bot_token)
try:
response = requests.post(
url,
json={
"chat_id": config.telegram_chat_id,
"text": f"{subject}\n\n{message}",
"disable_web_page_preview": True,
},
timeout=TELEGRAM_TIMEOUT,
)
response.raise_for_status()
except Exception as exc: # noqa: BLE001 - alerting must never break the workflow
logger.warning("Не удалось отправить оповещение в Telegram: %s", exc)
return False
return True
def send_alert(subject: str, message: str) -> dict[str, bool]:
"""Sends an alert through every configured channel.
Returns which transports actually delivered the message.
"""
config = NotificationSettings.load()
result = {"enabled": config.is_enabled, "email": False, "telegram": False}
logger.warning("Оповещение обмена: %s | %s", subject, message)
if not config.is_enabled:
return result
result["email"] = _send_email(config, subject, message)
result["telegram"] = _send_telegram(config, subject, message)
return result
def notify_sync_failed(run) -> dict[str, bool]:
"""Reports a failed exchange session."""
config = NotificationSettings.load()
if not config.notify_catalog_failure:
return {"enabled": False, "email": False, "telegram": False}
finished = run.finished_at or timezone.now()
duration = ""
if run.started_at:
seconds = int((finished - run.started_at).total_seconds())
duration = f"{seconds} с"
subject = f"[HOMM] Сбой обмена с 1С: {run.get_entity_display()}"
message = "\n".join(
[
f"Процесс: {run.get_entity_display()} ({run.get_direction_display()})",
f"Статус: {run.get_status_display()}",
f"Начало: {run.started_at:%d.%m.%Y %H:%M:%S}",
f"Длительность: {duration or '—'}",
f"Ошибка: {run.error or 'без текста'}",
f"Сеанс: #{run.pk}",
f"Админка: {ADMIN_SYNC_URL.format(pk=run.pk)}",
]
)
return send_alert(subject, message)
def notify_outbox_dead(message, attempts_limit: int = 5) -> dict[str, bool]:
"""Reports an outbox message that exhausted its retries."""
config = NotificationSettings.load()
if not config.notify_outbox_dead:
return {"enabled": False, "email": False, "telegram": False}
order_id = (message.payload or {}).get("order_id")
order_hint = f"Заказ в базе: #{order_id}" if order_id else ""
subject = "[HOMM] Заказ не доставлен в 1С"
text = "\n".join(
part
for part in [
f"Сообщение: {message.topic}",
f"Попыток: {message.attempts} из {attempts_limit}",
f"Последняя ошибка: {message.last_error or 'без текста'}",
order_hint,
f"Сообщение outbox: #{message.pk}",
"Админка: /admin/integration/outboxmessage/",
"Проверьте доступность 1С и повторите отправку из админки.",
]
if part
)
return send_alert(subject, text)