c_agri_trade/project_code/backend/app/api/alerts.py

434 lines
17 KiB
Python

"""Operational Alerts API Controller.
Fulfills:
- STORY-ALERT-001 (FR-OPERATIONALALERTS-001): Real-Time Operational Alerts Engine & Review Console (UC-014).
Adheres to LLD-005, HLD-EVENTS-ALERTS, and UP-AI v1.5 standards.
"""
from datetime import datetime, timezone, timedelta
from decimal import Decimal
import logging
from typing import Any, Dict, List, Optional
import uuid
from backend.app.api.auth import auth_controller
from backend.app.auth.tenant_context import (
TenantContext,
TenantContextResolutionError,
TenantContextResolver,
record_audit_event,
)
from backend.app.db.session import storage
from backend.app.models.reporting import (
OperationalAlert,
ALERT_CATEGORIES,
ALERT_SEVERITIES,
ALERT_STATUSES,
evaluate_lot_qc_hazard,
evaluate_warehouse_capacity_hazard,
evaluate_customer_credit_hazard,
)
from sandbox.notification_mock import notification_mock
from sandbox.warehouse_mock import warehouse_mock
from sandbox.customer_credit_mock import customer_credit_mock
logger = logging.getLogger("atb.api.alerts")
class AlertsController:
"""Handles operational hazard evaluation, query filtering, and audit-acknowledged resolutions."""
def __init__(self, store=storage, resolver=None, notifier=notification_mock):
self.store = store
self.resolver = resolver or TenantContextResolver(store=self.store)
self.notifier = notifier
self._seeded_tenants: set = set()
def _authenticate_and_resolve(
self, auth_header: Optional[str], tenant_header: Optional[str]
) -> Dict[str, Any]:
"""Resolves verified caller session and active tenant context."""
session = auth_controller.get_session(auth_header)
if not session.get("authenticated"):
return {"authenticated": False, "error": session.get("error", "UNAUTHENTICATED"), "status_code": 401}
user_id = session.get("subject", "")
email = session.get("email", user_id)
user_roles = session.get("roles", [])
try:
ctx = self.resolver.resolve_context(
subject_id=user_id,
email=email,
user_roles=user_roles,
requested_tenant_id=tenant_header,
)
except TenantContextResolutionError as err:
return {"authenticated": False, "error": err.message, "code": err.code, "status_code": err.status_code}
tenant_id = ctx.tenant_id
if tenant_id not in self._seeded_tenants:
self._seed_initial_alerts(tenant_id)
self._seeded_tenants.add(tenant_id)
return {
"authenticated": True,
"session": session,
"context": ctx,
"tenant_id": tenant_id,
"user_id": user_id,
"roles": list(dict.fromkeys(ctx.roles + user_roles)),
}
def _seed_initial_alerts(self, tenant_id: str) -> None:
"""Seeds standard operational alerts representing realistic active hazards."""
existing = self.store.list("operational_alerts", tenant_id)
if existing:
return
now = datetime.now(timezone.utc)
initial_alerts = [
OperationalAlert(
tenant_id=tenant_id,
category="CREDIT_RISK",
severity="CRITICAL",
title="Credit Breach Hard-Lock: Shanti Agro Traders (104.0%)",
message="Outstanding balance ₹52,00,000.00 exceeds sanctioned limit ₹50,00,000.00. Automatic dispatch lock engaged.",
source_entity_type="CUSTOMER",
source_entity_id="CUST-004",
alert_id=f"alt-cred-{tenant_id[:6]}-01",
created_at=now - timedelta(minutes=15),
),
OperationalAlert(
tenant_id=tenant_id,
category="QC_PENDING",
severity="CRITICAL",
title="Lot LOT-202610-004 on Mandatory QC Hold",
message="Lot LOT-202610-004 failed moisture threshold (14.2% > 12.0%). Dispatch and sales allocation restricted.",
source_entity_type="INWARD_LOT",
source_entity_id="LOT-202610-004",
alert_id=f"alt-qc-{tenant_id[:6]}-01",
created_at=now - timedelta(minutes=45),
),
OperationalAlert(
tenant_id=tenant_id,
category="WAREHOUSE_CAPACITY",
severity="WARNING",
title="Godown WH-02 Capacity Alert (88.5%)",
message="Indore Godown is operating at 88.5% capacity (2,655.0 / 3,000.0 MT). Nearing volumetric saturation.",
source_entity_type="WAREHOUSE",
source_entity_id="WH-02",
alert_id=f"alt-cap-{tenant_id[:6]}-01",
created_at=now - timedelta(hours=2),
),
OperationalAlert(
tenant_id=tenant_id,
category="PROCUREMENT_WINDOW",
severity="WARNING",
title="Neemuch Mandi Active Procurement Window Open",
message="Open auction orders active during designated mandi trading hours (10:00 - 16:00 IST).",
source_entity_type="MANDI",
source_entity_id="MANDI-NMH",
alert_id=f"alt-proc-{tenant_id[:6]}-01",
created_at=now - timedelta(hours=3),
),
]
for alt in initial_alerts:
self.store.insert("operational_alerts", tenant_id, alt.to_dict())
def list_alerts(
self,
auth_header: Optional[str],
tenant_header: Optional[str],
status_filter: Optional[str] = None,
category_filter: Optional[str] = None,
severity_filter: Optional[str] = None,
) -> Dict[str, Any]:
"""GET /api/v1/alerts (FR-OPERATIONALALERTS-001)."""
auth_res = self._authenticate_and_resolve(auth_header, tenant_header)
if not auth_res.get("authenticated"):
return auth_res
tenant_id = auth_res["tenant_id"]
def predicate(alt: Dict[str, Any]) -> bool:
if status_filter and status_filter.upper() != "ALL":
if alt.get("status", "").upper() != status_filter.upper():
return False
if category_filter and category_filter.upper() != "ALL":
if alt.get("category", "").upper() != category_filter.upper():
return False
if severity_filter and severity_filter.upper() != "ALL":
if alt.get("severity", "").upper() != severity_filter.upper():
return False
return True
records = self.store.query("operational_alerts", tenant_id, predicate)
# Sort by created_at descending
records.sort(key=lambda x: str(x.get("created_at", "")), reverse=True)
return {
"success": True,
"count": len(records),
"alerts": records,
"status_code": 200,
}
def acknowledge_alert(
self,
auth_header: Optional[str],
tenant_header: Optional[str],
alert_id: str,
payload: Dict[str, Any],
) -> Dict[str, Any]:
"""POST /api/v1/alerts/{id}/acknowledge (FR-OPERATIONALALERTS-001)."""
auth_res = self._authenticate_and_resolve(auth_header, tenant_header)
if not auth_res.get("authenticated"):
return auth_res
tenant_id = auth_res["tenant_id"]
ctx = auth_res["context"]
roles = auth_res["roles"]
# Permission check
allowed_roles = {"Operations Supervisor", "Partner", "Managing Director", "Tenant Admin", "Tenant Administrator"}
if not any(r in allowed_roles for r in roles):
return {
"error": "INSUFFICIENT_PERMISSIONS",
"message": "Only Operations Supervisors, Partners, Managing Directors, or Tenant Admins can acknowledge alerts",
"status_code": 403,
}
action_note = payload.get("action_note", "").strip() if payload else ""
if not action_note or len(action_note) < 5:
return {
"error": "VALIDATION_ERROR",
"message": "Action note is mandatory and must contain at least 5 characters.",
"status_code": 422,
}
alert_data = self.store.get("operational_alerts", tenant_id, alert_id)
if not alert_data:
return {
"error": "ALERT_NOT_FOUND",
"message": f"Operational alert '{alert_id}' was not found.",
"status_code": 404,
}
if alert_data.get("status") != "ACTIVE":
return {
"error": "INVALID_STATE_TRANSITION",
"message": f"Cannot acknowledge alert in status '{alert_data.get('status')}'. Must be ACTIVE.",
"status_code": 409,
}
now = datetime.now(timezone.utc)
alert_data["status"] = "ACKNOWLEDGED"
alert_data["acknowledged_by"] = auth_res["user_id"]
alert_data["acknowledged_at"] = now.isoformat()
alert_data["action_note"] = action_note
self.store.update("operational_alerts", tenant_id, alert_id, alert_data)
# Notify via outbox adapter
self.notifier.record_event(
tenant_id=tenant_id,
event_type="OPERATIONAL_ALERT_ACKNOWLEDGED",
payload={
"alert_id": alert_id,
"category": alert_data.get("category"),
"severity": alert_data.get("severity"),
"acknowledged_by": auth_res["user_id"],
"action_note": action_note,
},
)
# Audit event
record_audit_event(
store=self.store,
tenant_id=tenant_id,
actor_user_id=auth_res["user_id"],
action_type="ACKNOWLEDGE_OPERATIONAL_ALERT",
resource_type="operational_alert",
resource_id=alert_id,
before_state={"status": "ACTIVE"},
after_state={"status": "ACKNOWLEDGED", "acknowledged_by": auth_res["user_id"], "action_note": action_note},
)
return {
"success": True,
"alert": alert_data,
"status_code": 200,
}
def evaluate_operational_hazards(
self,
auth_header: Optional[str],
tenant_header: Optional[str],
) -> Dict[str, Any]:
"""POST /api/v1/alerts/evaluate (FR-OPERATIONALALERTS-001)."""
auth_res = self._authenticate_and_resolve(auth_header, tenant_header)
if not auth_res.get("authenticated"):
return auth_res
tenant_id = auth_res["tenant_id"]
now = datetime.now(timezone.utc)
new_alerts: List[Dict[str, Any]] = []
existing_active = self.store.query(
"operational_alerts",
tenant_id,
lambda a: a.get("status") == "ACTIVE",
)
existing_keys = {
(a.get("category"), a.get("source_entity_type"), a.get("source_entity_id"))
for a in existing_active
}
# 1. Evaluate QC Pending hazards from inward lots
lots = self.store.list("inward_lots", tenant_id)
if not lots:
lots = self.store.list("lots", tenant_id)
for lot in lots:
lot_id = lot.get("id", lot.get("lot_id", ""))
status = lot.get("status", "")
created_str = lot.get("created_at")
created_dt = now
if created_str:
try:
created_dt = datetime.fromisoformat(created_str.replace("Z", "+00:00"))
except Exception:
pass
qc_hazard = evaluate_lot_qc_hazard(lot_id=lot_id, status=status, created_at=created_dt, now=now)
if qc_hazard:
key = ("QC_PENDING", "INWARD_LOT", lot_id)
if key not in existing_keys:
alt = OperationalAlert(
tenant_id=tenant_id,
category="QC_PENDING",
severity=qc_hazard["severity"],
title=qc_hazard["title"],
message=qc_hazard["message"],
source_entity_type="INWARD_LOT",
source_entity_id=lot_id,
created_at=now,
)
self.store.insert("operational_alerts", tenant_id, alt.to_dict())
new_alerts.append(alt.to_dict())
existing_keys.add(key)
# 2. Evaluate Warehouse Capacity hazards
warehouses = self.store.list("warehouses", tenant_id)
if not warehouses:
warehouses = warehouse_mock.list_warehouses()
for wh in warehouses:
wh_id = wh.get("id", wh.get("warehouse_id", ""))
wh_name = wh.get("name", wh.get("warehouse_name", wh_id))
cur_mt = Decimal(str(wh.get("current_occupancy_mt", wh.get("current_mt", 0.0))))
max_mt = Decimal(str(wh.get("capacity_mt", wh.get("max_capacity_mt", 1.0))))
cap_hazard = evaluate_warehouse_capacity_hazard(
warehouse_id=wh_id,
warehouse_name=wh_name,
current_mt=cur_mt,
max_capacity_mt=max_mt,
)
if cap_hazard:
key = ("WAREHOUSE_CAPACITY", "WAREHOUSE", wh_id)
if key not in existing_keys:
alt = OperationalAlert(
tenant_id=tenant_id,
category="WAREHOUSE_CAPACITY",
severity=cap_hazard["severity"],
title=cap_hazard["title"],
message=cap_hazard["message"],
source_entity_type="WAREHOUSE",
source_entity_id=wh_id,
created_at=now,
)
self.store.insert("operational_alerts", tenant_id, alt.to_dict())
new_alerts.append(alt.to_dict())
existing_keys.add(key)
# 3. Evaluate Customer Credit Exposure hazards
customers = self.store.list("customers", tenant_id)
if not customers:
customers = customer_credit_mock.get_all_customers()
for cust in customers:
cid = cust.get("id", cust.get("customer_id", ""))
cname = cust.get("name", cust.get("customer_name", cid))
outstanding = Decimal(str(cust.get("current_outstanding_inr", cust.get("outstanding_inr", 0.0))))
sanctioned = Decimal(str(cust.get("credit_limit_inr", 0.0)))
cred_hazard = evaluate_customer_credit_hazard(
customer_id=cid,
customer_name=cname,
current_outstanding=outstanding,
sanctioned_limit=sanctioned,
)
if cred_hazard:
key = ("CREDIT_RISK", "CUSTOMER", cid)
if key not in existing_keys:
alt = OperationalAlert(
tenant_id=tenant_id,
category="CREDIT_RISK",
severity=cred_hazard["severity"],
title=cred_hazard["title"],
message=cred_hazard["message"],
source_entity_type="CUSTOMER",
source_entity_id=cid,
created_at=now,
)
self.store.insert("operational_alerts", tenant_id, alt.to_dict())
new_alerts.append(alt.to_dict())
existing_keys.add(key)
# 4. Evaluate Procurement Window hazards
mandis = self.store.list("mandis", tenant_id)
if not mandis:
mandis = [{"id": "MANDI-NMH", "name": "Neemuch Mandi", "window_status": "OPEN"}]
for m in mandis:
mid = m.get("id", "")
if m.get("window_status") == "OPEN":
key = ("PROCUREMENT_WINDOW", "MANDI", mid)
if key not in existing_keys:
alt = OperationalAlert(
tenant_id=tenant_id,
category="PROCUREMENT_WINDOW",
severity="WARNING",
title=f"{m.get('name', mid)} Active Procurement Window Open",
message=f"Designated trading hours are currently active for {m.get('name', mid)}. Auction buying is in progress.",
source_entity_type="MANDI",
source_entity_id=mid,
created_at=now,
)
self.store.insert("operational_alerts", tenant_id, alt.to_dict())
new_alerts.append(alt.to_dict())
existing_keys.add(key)
total_active = len(self.store.query("operational_alerts", tenant_id, lambda a: a.get("status") == "ACTIVE"))
# Notify outbox if new alerts emerged
if new_alerts:
self.notifier.record_event(
tenant_id=tenant_id,
event_type="OPERATIONAL_HAZARDS_DETECTED",
payload={
"count": len(new_alerts),
"alert_ids": [a["id"] for a in new_alerts],
},
)
return {
"success": True,
"evaluated_categories": 4,
"new_alerts_created": len(new_alerts),
"total_active_alerts": total_active,
"status_code": 200,
}
alerts_controller = AlertsController()