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

+185 -1
View File
@@ -1,12 +1,18 @@
from decimal import Decimal
from unittest import mock
from django.conf import settings
from django.test import TestCase
from django.core import mail
from django.test import TestCase, override_settings
from django.utils import timezone
from rest_framework.test import APIClient
from apps.catalog.models import Product
from apps.orders.models import Order
from .models import NotificationSettings, OutboxMessage, SyncLog, SyncRun
from .services import process_outbox, pull_catalog_from_1c, stop_sync_run
class IntegrationApiTests(TestCase):
def setUp(self):
@@ -80,3 +86,181 @@ class IntegrationApiTests(TestCase):
)
self.assertEqual(response.status_code, 400)
self.assertEqual(response.data["error"]["code"], "unknown_status")
@override_settings(
EMAIL_BACKEND="django.core.mail.backends.locmem.EmailBackend",
DEFAULT_FROM_EMAIL="robot@homm.test",
)
class ExchangeAlertTests(TestCase):
def setUp(self):
self.config = NotificationSettings.load()
self.config.email_recipients = "admin@homm.test, ops@homm.test"
self.config.save()
def test_sync_failure_sends_email(self):
with mock.patch(
"apps.integration.services.OneCClient.fetch_catalog",
side_effect=RuntimeError("1C недоступна"),
):
with self.assertRaises(RuntimeError):
pull_catalog_from_1c()
self.assertEqual(len(mail.outbox), 1)
message = mail.outbox[0]
self.assertIn("Сбой обмена с 1С", message.subject)
self.assertIn("1C недоступна", message.body)
self.assertEqual(
sorted(message.to), ["admin@homm.test", "ops@homm.test"]
)
run = SyncRun.objects.latest("started_at")
self.assertEqual(run.status, SyncRun.Status.FAILED)
self.assertIn("1C недоступна", run.error)
def test_sync_failure_keeps_task_id(self):
with mock.patch(
"apps.integration.services.OneCClient.fetch_catalog",
side_effect=RuntimeError("нет связи"),
):
with self.assertRaises(RuntimeError):
pull_catalog_from_1c(task_id="task-42")
run = SyncRun.objects.latest("started_at")
self.assertEqual(run.task_id, "task-42")
def test_disabled_alerts_are_not_sent(self):
self.config.is_enabled = False
self.config.save()
with mock.patch(
"apps.integration.services.OneCClient.fetch_catalog",
side_effect=RuntimeError("1C недоступна"),
):
with self.assertRaises(RuntimeError):
pull_catalog_from_1c()
self.assertEqual(len(mail.outbox), 0)
def test_catalog_failure_flag_is_respected(self):
self.config.notify_catalog_failure = False
self.config.save()
with mock.patch(
"apps.integration.services.OneCClient.fetch_catalog",
side_effect=RuntimeError("1C недоступна"),
):
with self.assertRaises(RuntimeError):
pull_catalog_from_1c()
self.assertEqual(len(mail.outbox), 0)
def test_inbound_catalog_error_notifies_admin(self):
client = APIClient()
with mock.patch(
"apps.integration.views.upsert_catalog",
side_effect=RuntimeError("битый пакет"),
):
response = client.post(
"/api/v1/integration/1c/catalog/sync/",
{"products": []},
format="json",
HTTP_X_INTEGRATION_TOKEN=settings.INTEGRATION_API_TOKEN,
)
self.assertEqual(response.status_code, 400)
self.assertEqual(len(mail.outbox), 1)
self.assertIn("битый пакет", mail.outbox[0].body)
def test_outbox_dead_letter_notifies_admin(self):
message = OutboxMessage.objects.create(
topic="order.created",
payload={"order_id": 999999},
attempts=4,
)
process_outbox()
message.refresh_from_db()
self.assertEqual(message.status, OutboxMessage.Status.DEAD)
self.assertEqual(len(mail.outbox), 1)
self.assertIn("Заказ не доставлен в 1С", mail.outbox[0].subject)
def test_telegram_alert_uses_bot_api(self):
self.config.email_recipients = ""
self.config.telegram_bot_token = "123:ABC"
self.config.telegram_chat_id = "-100500"
self.config.save()
with mock.patch(
"apps.integration.services.OneCClient.fetch_catalog",
side_effect=RuntimeError("1C недоступна"),
):
with mock.patch(
"apps.integration.notifications.requests.post"
) as post:
post.return_value.raise_for_status.return_value = None
with self.assertRaises(RuntimeError):
pull_catalog_from_1c()
self.assertEqual(len(mail.outbox), 0)
post.assert_called_once()
url = post.call_args.args[0]
payload = post.call_args.kwargs["json"]
self.assertIn("123:ABC", url)
self.assertEqual(payload["chat_id"], "-100500")
self.assertIn("Сбой обмена", payload["text"])
def test_email_list_parses_separators(self):
self.config.email_recipients = "a@x.ru; b@x.ru,\nc@x.ru"
self.config.save()
self.assertEqual(
self.config.email_list(), ["a@x.ru", "b@x.ru", "c@x.ru"]
)
class StopSyncRunTests(TestCase):
def _run(self, **kwargs):
defaults = {
"direction": SyncRun.Direction.INBOUND,
"entity": SyncRun.Entity.CATALOG,
"status": SyncRun.Status.RUNNING,
"started_at": timezone.now(),
}
defaults.update(kwargs)
return SyncRun.objects.create(**defaults)
def test_stop_revokes_task_and_marks_run(self):
run = self._run(task_id="task-777")
with mock.patch("apps.integration.services.revoke_task") as revoke:
outcome = stop_sync_run(run)
self.assertEqual(outcome, "stopped")
revoke.assert_called_once_with("task-777")
run.refresh_from_db()
self.assertEqual(run.status, SyncRun.Status.STOPPED)
self.assertIsNotNone(run.finished_at)
self.assertEqual(run.logs.count(), 1)
self.assertEqual(run.logs.first().level, SyncLog.Level.WARNING)
def test_stop_skips_finished_run(self):
run = self._run(status=SyncRun.Status.SUCCESS, task_id="task-1")
with mock.patch("apps.integration.services.revoke_task") as revoke:
self.assertEqual(stop_sync_run(run), "not_running")
revoke.assert_not_called()
run.refresh_from_db()
self.assertEqual(run.status, SyncRun.Status.SUCCESS)
def test_stop_without_task_id_reports_no_task(self):
run = self._run()
with mock.patch("apps.integration.services.revoke_task") as revoke:
self.assertEqual(stop_sync_run(run), "no_task")
revoke.assert_not_called()
run.refresh_from_db()
self.assertEqual(run.status, SyncRun.Status.RUNNING)