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

+47 -1
View File
@@ -16,6 +16,7 @@ from apps.orders.models import Order, OrderStatusHistory
from .client import OneCClient
from .models import OutboxMessage, SyncLog, SyncRun
from .notifications import notify_outbox_dead, notify_sync_failed
from .status_map import map_1c_status
logger = logging.getLogger(__name__)
@@ -288,27 +289,70 @@ def push_customer_to_1c(user: User) -> dict:
)
def pull_catalog_from_1c(since=None) -> dict:
def revoke_task(task_id: str) -> None:
"""Revokes a Celery task. Raises if the broker is unreachable."""
from config.celery import app as celery_app
celery_app.control.revoke(task_id, terminate=True)
def stop_sync_run(run: SyncRun) -> str:
"""Stops a running exchange session and marks it as stopped.
Returns one of ``stopped``, ``not_running``, ``no_task``. Broker errors are
propagated to the caller so the admin can be told the truth.
"""
if run.status != SyncRun.Status.RUNNING:
return "not_running"
if not run.task_id:
return "no_task"
revoke_task(run.task_id)
run.status = SyncRun.Status.STOPPED
run.finished_at = timezone.now()
run.save(update_fields=["status", "finished_at", "updated_at"])
SyncLog.objects.create(
run=run,
level=SyncLog.Level.WARNING,
message="Синхронизация остановлена администратором",
)
return "stopped"
def pull_catalog_from_1c(since=None, task_id: str = "") -> dict:
run = SyncRun.objects.create(
direction=SyncRun.Direction.INBOUND,
entity=SyncRun.Entity.CATALOG,
status=SyncRun.Status.RUNNING,
started_at=timezone.now(),
task_id=task_id or "",
)
try:
payload = OneCClient().fetch_catalog(since=since)
stats = upsert_catalog(payload, run=run)
# The run may have been stopped from the admin while the batch was applied.
run.refresh_from_db(fields=["status"])
if run.status == SyncRun.Status.STOPPED:
_log(run, SyncLog.Level.WARNING, "Синхронизация остановлена администратором")
return {"cancelled": True, **stats}
run.status = SyncRun.Status.SUCCESS
run.stats = stats
run.finished_at = timezone.now()
run.save(update_fields=["status", "stats", "finished_at", "updated_at"])
return stats
except Exception as exc:
run.refresh_from_db(fields=["status"])
if run.status == SyncRun.Status.STOPPED:
raise
run.status = SyncRun.Status.FAILED
run.error = str(exc)
run.finished_at = timezone.now()
run.save(update_fields=["status", "error", "finished_at", "updated_at"])
_log(run, SyncLog.Level.ERROR, str(exc))
notify_sync_failed(run)
raise
@@ -355,6 +399,8 @@ def process_outbox(limit: int = 100) -> int:
)
logger.warning("Outbox %s failed: %s", message.pk, exc)
message.save()
if message.status == OutboxMessage.Status.DEAD:
notify_outbox_dead(message)
processed += 1
return processed