import random from django.template.loader import render_to_string from liveview.decorators import liveview_handler from liveview.connections import send from app.models import Alert ALERT_TYPES = [Alert.TYPE_INFO, Alert.TYPE_WARNING, Alert.TYPE_CRITICAL] DESCRIPTIONS = [ "CPU usage above 90%", "Memory leak detected in worker", "Disk space below 10%", "Network timeout on upstream", "Service unreachable: auth", "Database slow query detected", "HTTP 5xx rate spike", "SSL certificate expiring soon", "Replica lag too high", "Queue backlog growing", ] def _random_alert(): return Alert.objects.create( alert_type=random.choice(ALERT_TYPES), description=random.choice(DESCRIPTIONS), ) def _send_table(consumer, alerts): html = render_to_string("components/_alerts_table.html", {"alerts": alerts}) send(consumer, {"target": "#alerts-container", "html": html}) send(consumer, {"target": "#alert-count", "html": str(len(alerts))}) @liveview_handler("add_alert") def add_alert(consumer, content): _random_alert() _send_table(consumer, list(Alert.objects.all())) @liveview_handler("delete_alert") def delete_alert(consumer, content): alert_id = content.get("data", {}).get("alert_id") if alert_id: Alert.objects.filter(id=alert_id).delete() _send_table(consumer, list(Alert.objects.all())) @liveview_handler("search_alerts") def search_alerts(consumer, content): query = content.get("form", {}).get("query", "") if query: alerts = list(Alert.objects.filter(description__icontains=query)) else: alerts = list(Alert.objects.all()) _send_table(consumer, alerts)