"""Operational Alerts, Executive Dashboard & Market Trend Analytics Models. Fulfills: - FR-OPERATIONALALERTS-001 (Real-Time Operational Alerts Engine) - FR-EXECUTIVEREPORTING-001 (Executive Control Centre Dashboard) - FR-EXECUTIVEREPORTING-002 (20-Day Consolidated Trading Trend Reporting) - FR-MARKETTRENDANALYTICS-001 (Intraday Price Trend Analysis & 20-Day Benchmark Analytics) Adheres to LLD-005, HLD-EVENTS-ALERTS, HLD-REPORTING, and UP-AI v1.5 standards. """ from datetime import datetime, timezone, timedelta from decimal import Decimal, ROUND_HALF_UP from typing import Optional, Dict, Any, List import uuid try: from sqlalchemy import Column, String, DateTime, Numeric, Integer, Boolean from backend.app.models.user import Base except ImportError: class Base: pass Column = String = DateTime = Numeric = Integer = Boolean = lambda *args, **kwargs: None # Constants & Thresholds ALERT_CATEGORIES = {"QC_PENDING", "WAREHOUSE_CAPACITY", "CREDIT_RISK", "PROCUREMENT_WINDOW"} ALERT_SEVERITIES = {"INFO", "WARNING", "CRITICAL"} ALERT_STATUSES = {"ACTIVE", "ACKNOWLEDGED", "RESOLVED", "DISMISSED"} QC_OVERDUE_HOURS_THRESHOLD = 24 CAPACITY_WARNING_THRESHOLD_PCT = Decimal("85.0") CREDIT_WATCH_THRESHOLD_PCT = Decimal("80.0") CREDIT_LOCK_THRESHOLD_PCT = Decimal("100.0") DEFAULT_TREND_WINDOW_DAYS = 20 DEFAULT_SMA_WINDOW_DAYS = 20 class OperationalAlert(Base): """Operational alert record tracking hazards across QC, capacity, credit, and market windows.""" __tablename__ = "operational_alerts" id = Column(String(36), primary_key=True) tenant_id = Column(String(36), nullable=False, index=True) category = Column(String(50), nullable=False) severity = Column(String(20), nullable=False) title = Column(String(255), nullable=False) message = Column(String(1000), nullable=False) source_entity_type = Column(String(50), nullable=False) source_entity_id = Column(String(50), nullable=False) status = Column(String(20), nullable=False, default="ACTIVE") created_at = Column(DateTime, nullable=False, default=lambda: datetime.now(timezone.utc)) acknowledged_by = Column(String(100), nullable=True) acknowledged_at = Column(DateTime, nullable=True) action_note = Column(String(1000), nullable=True) resolved_at = Column(DateTime, nullable=True) def __init__( self, tenant_id: str, category: str, severity: str, title: str, message: str, source_entity_type: str, source_entity_id: str, alert_id: Optional[str] = None, created_at: Optional[datetime] = None, ): if category not in ALERT_CATEGORIES: raise ValueError(f"Invalid alert category: {category}. Allowed: {ALERT_CATEGORIES}") if severity not in ALERT_SEVERITIES: raise ValueError(f"Invalid alert severity: {severity}. Allowed: {ALERT_SEVERITIES}") self.id = alert_id or f"alt-{uuid.uuid4().hex[:10]}" self.tenant_id = tenant_id self.category = category self.severity = severity self.title = title self.message = message self.source_entity_type = source_entity_type self.source_entity_id = source_entity_id self.status = "ACTIVE" self.created_at = created_at or datetime.now(timezone.utc) self.acknowledged_by = None self.acknowledged_at = None self.action_note = None self.resolved_at = None def acknowledge(self, user_id: str, note: str) -> None: """Transitions alert to ACKNOWLEDGED state with mandatory audit note (min 5 chars).""" if self.status != "ACTIVE": raise ValueError(f"Cannot acknowledge alert in status '{self.status}'. Must be 'ACTIVE'.") if not note or len(note.strip()) < 5: raise ValueError("Acknowledgment note is mandatory and must contain at least 5 characters.") self.status = "ACKNOWLEDGED" self.acknowledged_by = user_id self.acknowledged_at = datetime.now(timezone.utc) self.action_note = note.strip() def resolve(self) -> None: """Transitions alert to RESOLVED state when hazard condition is eliminated.""" if self.status in ("RESOLVED", "DISMISSED"): return self.status = "RESOLVED" self.resolved_at = datetime.now(timezone.utc) def dismiss(self) -> None: """Transitions alert to DISMISSED state.""" self.status = "DISMISSED" def to_dict(self) -> Dict[str, Any]: return { "id": self.id, "tenant_id": self.tenant_id, "category": self.category, "severity": self.severity, "title": self.title, "message": self.message, "source_entity_type": self.source_entity_type, "source_entity_id": self.source_entity_id, "status": self.status, "created_at": self.created_at.isoformat() if self.created_at else None, "acknowledged_by": self.acknowledged_by, "acknowledged_at": self.acknowledged_at.isoformat() if self.acknowledged_at else None, "action_note": self.action_note, "resolved_at": self.resolved_at.isoformat() if self.resolved_at else None, } class DailyTradingSnapshot(Base): """Daily trading snapshot for rolling 20-day trend reporting.""" __tablename__ = "daily_trading_snapshots" id = Column(String(36), primary_key=True) tenant_id = Column(String(36), nullable=False, index=True) snapshot_date = Column(String(10), nullable=False) # YYYY-MM-DD purchases_mt = Column(Numeric(12, 2), nullable=False, default=0.0) sales_mt = Column(Numeric(12, 2), nullable=False, default=0.0) closing_stock_mt = Column(Numeric(12, 2), nullable=False, default=0.0) total_receivables_inr = Column(Numeric(14, 2), nullable=False, default=0.0) total_payables_inr = Column(Numeric(14, 2), nullable=False, default=0.0) net_cash_flow_inr = Column(Numeric(14, 2), nullable=False, default=0.0) created_at = Column(DateTime, nullable=False, default=lambda: datetime.now(timezone.utc)) def __init__( self, tenant_id: str, snapshot_date: str, purchases_mt: Decimal, sales_mt: Decimal, closing_stock_mt: Decimal, total_receivables_inr: Decimal, total_payables_inr: Decimal, net_cash_flow_inr: Optional[Decimal] = None, snapshot_id: Optional[str] = None, ): self.id = snapshot_id or f"snap-{uuid.uuid4().hex[:10]}" self.tenant_id = tenant_id self.snapshot_date = snapshot_date self.purchases_mt = purchases_mt self.sales_mt = sales_mt self.closing_stock_mt = closing_stock_mt self.total_receivables_inr = total_receivables_inr self.total_payables_inr = total_payables_inr self.net_cash_flow_inr = net_cash_flow_inr if net_cash_flow_inr is not None else (total_receivables_inr - total_payables_inr) self.created_at = datetime.now(timezone.utc) def to_dict(self) -> Dict[str, Any]: return { "id": self.id, "tenant_id": self.tenant_id, "snapshot_date": self.snapshot_date, "purchases_mt": float(self.purchases_mt), "sales_mt": float(self.sales_mt), "closing_stock_mt": float(self.closing_stock_mt), "total_receivables_inr": float(self.total_receivables_inr), "total_payables_inr": float(self.total_payables_inr), "net_cash_flow_inr": float(self.net_cash_flow_inr), "created_at": self.created_at.isoformat() if self.created_at else None, } # Domain Calculation & Analytics Functions def calculate_sma_and_benchmarks( observations: List[Dict[str, Any]], window_days: int = DEFAULT_SMA_WINDOW_DAYS, ) -> Dict[str, Any]: """Calculates Simple Moving Average (SMA), High/Low envelope, and Price Velocity. Formula: SMA = (Sum of Modal Rates in window) / (Number of observations) Period High = Max(Modal Rates) Period Low = Min(Modal Rates) Velocity = (Modal_today - Modal_oldest) / days_count """ if not observations: return { "sma_20": 0.0, "period_high": 0.0, "period_low": 0.0, "price_velocity": 0.0, "data_points_count": 0, } # Sort observations chronologically by date sorted_obs = sorted(observations, key=lambda x: str(x.get("observation_date", ""))) # Window slice: take up to window_days most recent window_slice = sorted_obs[-window_days:] modal_rates = [Decimal(str(o.get("modal_price", 0.0))) for o in window_slice if o.get("modal_price") is not None] if not modal_rates: return { "sma_20": 0.0, "period_high": 0.0, "period_low": 0.0, "price_velocity": 0.0, "data_points_count": 0, } count = len(modal_rates) total_modal = sum(modal_rates) sma = (total_modal / Decimal(count)).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP) p_high = max(modal_rates).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP) p_low = min(modal_rates).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP) # Velocity: delta between most recent and oldest divided by observation days span if count > 1: delta = modal_rates[-1] - modal_rates[0] velocity = (delta / Decimal(count)).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP) else: velocity = Decimal("0.00") return { "sma_20": float(sma), "period_high": float(p_high), "period_low": float(p_low), "price_velocity": float(velocity), "data_points_count": count, } def evaluate_lot_qc_hazard( lot_id: str, status: str, created_at: datetime, now: Optional[datetime] = None, ) -> Optional[Dict[str, Any]]: """Evaluates whether an inward lot presents a QC pending or hold hazard. Rule: - Status == 'QC_HOLD' -> CRITICAL alert. - Status == 'UNDER_QC' or 'PENDING_QC' for > 24 hours -> CRITICAL alert. """ if now is None: now = datetime.now(timezone.utc) # Ensure timezone awareness if created_at.tzinfo is None: created_at = created_at.replace(tzinfo=timezone.utc) age_hours = (now - created_at).total_seconds() / 3600.0 if status.upper() in ("QC_HOLD", "HOLD"): return { "severity": "CRITICAL", "title": f"Lot {lot_id} on Mandatory QC Hold", "message": f"Lot {lot_id} is currently on QC Hold. Dispatch and allocation are restricted.", } elif status.upper() in ("UNDER_QC", "PENDING_QC") and age_hours > QC_OVERDUE_HOURS_THRESHOLD: return { "severity": "CRITICAL", "title": f"Lot {lot_id} QC Inspection Overdue ({age_hours:.1f}h)", "message": f"Lot {lot_id} has been awaiting quality clearance for {age_hours:.1f} hours (>24h SLA).", } return None def evaluate_warehouse_capacity_hazard( warehouse_id: str, warehouse_name: str, current_mt: Decimal, max_capacity_mt: Decimal, ) -> Optional[Dict[str, Any]]: """Evaluates whether a godown exceeds the 85.0% capacity utilization warning threshold.""" if max_capacity_mt <= Decimal("0"): return None utilization_pct = (current_mt / max_capacity_mt) * Decimal("100.0") if utilization_pct > CAPACITY_WARNING_THRESHOLD_PCT: return { "severity": "WARNING", "title": f"Godown {warehouse_id} Capacity Alert ({utilization_pct:.1f}%)", "message": f"{warehouse_name} is operating at {utilization_pct:.1f}% capacity ({current_mt:.1f} / {max_capacity_mt:.1f} MT).", "utilization_pct": float(utilization_pct.quantize(Decimal("0.1"))), } return None def evaluate_customer_credit_hazard( customer_id: str, customer_name: str, current_outstanding: Decimal, sanctioned_limit: Decimal, ) -> Optional[Dict[str, Any]]: """Evaluates customer credit exposure against 80% (Watch) and 100% (Critical Breach) thresholds.""" if sanctioned_limit <= Decimal("0"): return None exposure_pct = (current_outstanding / sanctioned_limit) * Decimal("100.0") if exposure_pct > CREDIT_LOCK_THRESHOLD_PCT: return { "severity": "CRITICAL", "title": f"Credit Breach Hard-Lock: {customer_name} ({exposure_pct:.1f}%)", "message": f"Outstanding balance ₹{current_outstanding:,.2f} exceeds sanctioned limit ₹{sanctioned_limit:,.2f} (100% breach). Dispatches locked.", "exposure_pct": float(exposure_pct.quantize(Decimal("0.1"))), } elif exposure_pct > CREDIT_WATCH_THRESHOLD_PCT: return { "severity": "WARNING", "title": f"Credit Exposure Watch: {customer_name} ({exposure_pct:.1f}%)", "message": f"Customer exposure at {exposure_pct:.1f}% (₹{current_outstanding:,.2f} / ₹{sanctioned_limit:,.2f}). Approaching sanctioned ceiling.", "exposure_pct": float(exposure_pct.quantize(Decimal("0.1"))), } return None