691 lines
27 KiB
Python
691 lines
27 KiB
Python
"""Unit & Domain Verification Suite for Iteration 06 (Alerts, Reporting & Market Trends).
|
|
|
|
Fulfills:
|
|
- UC-014: Operational Alerts Engine (FR-OPERATIONALALERTS-001)
|
|
- UC-015: Executive Dashboard & 20-Day Trading Snapshots (FR-EXECUTIVEREPORTING-001, FR-EXECUTIVEREPORTING-002)
|
|
- UC-003: Market Desk Price Trend Analytics (FR-MARKETTRENDANALYTICS-001)
|
|
|
|
Adheres to UP-AI v1.5 testing standards:
|
|
- 4 Test Dimensions: Happy Path, Boundary Conditions, Negative / Error Paths, and FSM State Transitions.
|
|
- Strict anti-placeholder rule: Genuine domain calculations and mathematical invariants.
|
|
"""
|
|
from datetime import datetime, timezone, timedelta
|
|
from decimal import Decimal
|
|
import sys
|
|
import unittest
|
|
import uuid
|
|
from pathlib import Path
|
|
from typing import Dict, Any
|
|
|
|
# Ensure code_root is in sys.path
|
|
code_root = Path(__file__).resolve().parents[2]
|
|
repo_root = Path(__file__).resolve().parents[3]
|
|
if str(code_root) not in sys.path:
|
|
sys.path.insert(0, str(code_root))
|
|
if str(repo_root) not in sys.path:
|
|
sys.path.insert(0, str(repo_root))
|
|
|
|
from backend.app.db.session import InMemoryTenantStorage
|
|
from backend.app.auth.tenant_context import TenantContextResolver
|
|
from backend.app.models.tenant import Tenant, TenantMembership
|
|
from backend.app.models.reporting import (
|
|
OperationalAlert,
|
|
DailyTradingSnapshot,
|
|
calculate_sma_and_benchmarks,
|
|
evaluate_lot_qc_hazard,
|
|
evaluate_warehouse_capacity_hazard,
|
|
evaluate_customer_credit_hazard,
|
|
)
|
|
from backend.app.api.alerts import AlertsController
|
|
from backend.app.api.reporting import ReportingController
|
|
from backend.app.api.analytics import AnalyticsController
|
|
from sandbox.identity_mock import mock_idp
|
|
from sandbox.notification_mock import NotificationMock
|
|
|
|
|
|
class TestAlertsAndReportingSuite(unittest.TestCase):
|
|
"""Exhaustive unit test suite covering Domain models, hazard evaluators, controllers, and outbox."""
|
|
|
|
def setUp(self):
|
|
self.store = InMemoryTenantStorage()
|
|
self.resolver = TenantContextResolver(store=self.store)
|
|
self.notifier = NotificationMock()
|
|
# Seed test tenant and memberships
|
|
self.tenant_id = "tenant-ops-01"
|
|
self.tenant = Tenant(
|
|
tenant_id=self.tenant_id,
|
|
business_name="Operations & Trading Co",
|
|
legal_identifier="23AABCT1234F1Z0",
|
|
contact_email="ops@mandi.test",
|
|
primary_mandi="Neemuch APMC",
|
|
status="ACTIVE",
|
|
)
|
|
self.store.save_tenant(self.tenant)
|
|
|
|
# Users
|
|
# 1. Partner / MD
|
|
self.user_partner = "user-partner-01"
|
|
self.token_partner = mock_idp.mint_jwt(
|
|
subject=self.user_partner,
|
|
email="partner@mandi.test",
|
|
name="Partner User",
|
|
roles=["Partner", "Managing Director"],
|
|
tenant_id=self.tenant_id,
|
|
)
|
|
self.store.save_membership(
|
|
TenantMembership(
|
|
tenant_id=self.tenant_id,
|
|
user_id=self.user_partner,
|
|
email="partner@mandi.test",
|
|
role="Partner",
|
|
status="ACTIVE",
|
|
)
|
|
)
|
|
|
|
# 2. Operations Supervisor
|
|
self.user_supervisor = "user-sup-01"
|
|
self.token_supervisor = mock_idp.mint_jwt(
|
|
subject=self.user_supervisor,
|
|
email="supervisor@mandi.test",
|
|
name="Supervisor User",
|
|
roles=["Operations Supervisor"],
|
|
tenant_id=self.tenant_id,
|
|
)
|
|
self.store.save_membership(
|
|
TenantMembership(
|
|
tenant_id=self.tenant_id,
|
|
user_id=self.user_supervisor,
|
|
email="supervisor@mandi.test",
|
|
role="Operations Supervisor",
|
|
status="ACTIVE",
|
|
)
|
|
)
|
|
|
|
# 3. Desk Trader
|
|
self.user_trader = "user-trader-01"
|
|
self.token_trader = mock_idp.mint_jwt(
|
|
subject=self.user_trader,
|
|
email="trader@mandi.test",
|
|
name="Trader User",
|
|
roles=["Desk Trader", "Mandi Buyer"],
|
|
tenant_id=self.tenant_id,
|
|
)
|
|
self.store.save_membership(
|
|
TenantMembership(
|
|
tenant_id=self.tenant_id,
|
|
user_id=self.user_trader,
|
|
email="trader@mandi.test",
|
|
role="Desk Trader",
|
|
status="ACTIVE",
|
|
)
|
|
)
|
|
|
|
# 4. Unauthorized User
|
|
self.user_unauth = "user-unauth-01"
|
|
self.token_unauth = mock_idp.mint_jwt(
|
|
subject=self.user_unauth,
|
|
email="unauth@mandi.test",
|
|
name="Guest User",
|
|
roles=["Guest"],
|
|
tenant_id=self.tenant_id,
|
|
)
|
|
self.store.save_membership(
|
|
TenantMembership(
|
|
tenant_id=self.tenant_id,
|
|
user_id=self.user_unauth,
|
|
email="unauth@mandi.test",
|
|
role="Guest",
|
|
status="ACTIVE",
|
|
)
|
|
)
|
|
|
|
# Controllers under test
|
|
self.alerts_ctrl = AlertsController(store=self.store, resolver=self.resolver, notifier=self.notifier)
|
|
self.reporting_ctrl = ReportingController(store=self.store, resolver=self.resolver)
|
|
self.analytics_ctrl = AnalyticsController(store=self.store, resolver=self.resolver)
|
|
|
|
# =========================================================================
|
|
# 1. Domain Model: OperationalAlert
|
|
# =========================================================================
|
|
|
|
def test_operational_alert_lifecycle_and_invariants(self):
|
|
"""Happy Path & FSM: OperationalAlert creation, acknowledgment, and resolution."""
|
|
alert = OperationalAlert(
|
|
tenant_id=self.tenant_id,
|
|
category="CREDIT_RISK",
|
|
severity="CRITICAL",
|
|
title="Credit Breach",
|
|
message="Customer exceeded 100% limit",
|
|
source_entity_type="CUSTOMER",
|
|
source_entity_id="CUST-001",
|
|
)
|
|
self.assertEqual(alert.status, "ACTIVE")
|
|
self.assertIsNone(alert.acknowledged_by)
|
|
self.assertIsNone(alert.acknowledged_at)
|
|
|
|
# Negative: Acknowledgment note must be >= 5 chars
|
|
with self.assertRaises(ValueError):
|
|
alert.acknowledge("user-01", "abc")
|
|
|
|
# Happy Path: Acknowledge
|
|
alert.acknowledge("user-01", "Customer promised RTGS remittance by 4 PM.")
|
|
self.assertEqual(alert.status, "ACKNOWLEDGED")
|
|
self.assertEqual(alert.acknowledged_by, "user-01")
|
|
self.assertIsNotNone(alert.acknowledged_at)
|
|
self.assertEqual(alert.action_note, "Customer promised RTGS remittance by 4 PM.")
|
|
|
|
# Negative: Cannot acknowledge when not ACTIVE
|
|
with self.assertRaises(ValueError):
|
|
alert.acknowledge("user-02", "Second note attempt")
|
|
|
|
# Resolve
|
|
alert.resolve()
|
|
self.assertEqual(alert.status, "RESOLVED")
|
|
self.assertIsNotNone(alert.resolved_at)
|
|
|
|
# Idempotent resolve
|
|
alert.resolve()
|
|
self.assertEqual(alert.status, "RESOLVED")
|
|
|
|
# Dismiss
|
|
alert.dismiss()
|
|
self.assertEqual(alert.status, "DISMISSED")
|
|
|
|
# Serialization
|
|
d = alert.to_dict()
|
|
self.assertEqual(d["tenant_id"], self.tenant_id)
|
|
self.assertEqual(d["category"], "CREDIT_RISK")
|
|
self.assertEqual(d["status"], "DISMISSED")
|
|
|
|
def test_operational_alert_invalid_parameters(self):
|
|
"""Negative: OperationalAlert category and severity validation."""
|
|
with self.assertRaises(ValueError):
|
|
OperationalAlert(
|
|
tenant_id=self.tenant_id,
|
|
category="INVALID_CAT",
|
|
severity="CRITICAL",
|
|
title="T",
|
|
message="M",
|
|
source_entity_type="E",
|
|
source_entity_id="ID",
|
|
)
|
|
|
|
with self.assertRaises(ValueError):
|
|
OperationalAlert(
|
|
tenant_id=self.tenant_id,
|
|
category="CREDIT_RISK",
|
|
severity="SUPER_HIGH",
|
|
title="T",
|
|
message="M",
|
|
source_entity_type="E",
|
|
source_entity_id="ID",
|
|
)
|
|
|
|
# =========================================================================
|
|
# 2. Domain Model: DailyTradingSnapshot
|
|
# =========================================================================
|
|
|
|
def test_daily_trading_snapshot_calculations(self):
|
|
"""Happy Path: DailyTradingSnapshot metrics and cash flow calculations."""
|
|
snap = DailyTradingSnapshot(
|
|
tenant_id=self.tenant_id,
|
|
snapshot_date="2026-10-12",
|
|
purchases_mt=Decimal("185.50"),
|
|
sales_mt=Decimal("140.00"),
|
|
closing_stock_mt=Decimal("4250.80"),
|
|
total_receivables_inr=Decimal("4250000.00"),
|
|
total_payables_inr=Decimal("3540000.00"),
|
|
)
|
|
self.assertEqual(snap.net_cash_flow_inr, Decimal("710000.00"))
|
|
d = snap.to_dict()
|
|
self.assertEqual(d["purchases_mt"], 185.5)
|
|
self.assertEqual(d["sales_mt"], 140.0)
|
|
self.assertEqual(d["net_cash_flow_inr"], 710000.0)
|
|
|
|
# =========================================================================
|
|
# 3. Domain Analytics: calculate_sma_and_benchmarks
|
|
# =========================================================================
|
|
|
|
def test_calculate_sma_and_benchmarks(self):
|
|
"""Happy & Boundary: Moving Average, Channels, and Price Velocity."""
|
|
# 1. Empty observations
|
|
res_empty = calculate_sma_and_benchmarks([])
|
|
self.assertEqual(res_empty["sma_20"], 0.0)
|
|
self.assertEqual(res_empty["data_points_count"], 0)
|
|
|
|
# 2. Observations without modal price
|
|
res_none = calculate_sma_and_benchmarks([{"observation_date": "2026-10-01"}])
|
|
self.assertEqual(res_none["sma_20"], 0.0)
|
|
|
|
# 3. Single observation
|
|
res_single = calculate_sma_and_benchmarks([{"observation_date": "2026-10-01", "modal_price": 5000.0}])
|
|
self.assertEqual(res_single["sma_20"], 5000.0)
|
|
self.assertEqual(res_single["period_high"], 5000.0)
|
|
self.assertEqual(res_single["period_low"], 5000.0)
|
|
self.assertEqual(res_single["price_velocity"], 0.0)
|
|
self.assertEqual(res_single["data_points_count"], 1)
|
|
|
|
# 4. Multi-day series: 5000 -> 5200 over 5 days
|
|
obs_series = [
|
|
{"observation_date": "2026-10-01", "modal_price": 5000.0},
|
|
{"observation_date": "2026-10-02", "modal_price": 5050.0},
|
|
{"observation_date": "2026-10-03", "modal_price": 5100.0},
|
|
{"observation_date": "2026-10-04", "modal_price": 5150.0},
|
|
{"observation_date": "2026-10-05", "modal_price": 5200.0},
|
|
]
|
|
res_multi = calculate_sma_and_benchmarks(obs_series, window_days=5)
|
|
# Sum = 25500 / 5 = 5100.0
|
|
self.assertEqual(res_multi["sma_20"], 5100.0)
|
|
self.assertEqual(res_multi["period_high"], 5200.0)
|
|
self.assertEqual(res_multi["period_low"], 5000.0)
|
|
# Velocity = (5200 - 5000) / 5 = 200 / 5 = 40.0
|
|
self.assertEqual(res_multi["price_velocity"], 40.0)
|
|
self.assertEqual(res_multi["data_points_count"], 5)
|
|
|
|
# =========================================================================
|
|
# 4. Hazard Evaluation Rules
|
|
# =========================================================================
|
|
|
|
def test_evaluate_lot_qc_hazard(self):
|
|
"""Boundary & Invariant: QC Hold vs Overdue vs Healthy inward lot."""
|
|
now = datetime(2026, 10, 12, 12, 0, tzinfo=timezone.utc)
|
|
|
|
# QC_HOLD -> CRITICAL
|
|
h_hold = evaluate_lot_qc_hazard("LOT-01", "QC_HOLD", now - timedelta(hours=2), now=now)
|
|
self.assertIsNotNone(h_hold)
|
|
self.assertEqual(h_hold["severity"], "CRITICAL")
|
|
self.assertIn("QC Hold", h_hold["title"])
|
|
|
|
# PENDING_QC > 24 hours -> CRITICAL
|
|
h_overdue = evaluate_lot_qc_hazard("LOT-02", "PENDING_QC", now - timedelta(hours=25), now=now)
|
|
self.assertIsNotNone(h_overdue)
|
|
self.assertEqual(h_overdue["severity"], "CRITICAL")
|
|
self.assertIn("Overdue", h_overdue["title"])
|
|
|
|
# UNDER_QC within SLA (5 hours) -> None
|
|
h_ok = evaluate_lot_qc_hazard("LOT-03", "UNDER_QC", now - timedelta(hours=5), now=now)
|
|
self.assertIsNone(h_ok)
|
|
|
|
# QC_APPROVED -> None
|
|
h_approved = evaluate_lot_qc_hazard("LOT-04", "QC_APPROVED", now - timedelta(hours=48), now=now)
|
|
self.assertIsNone(h_approved)
|
|
|
|
def test_evaluate_warehouse_capacity_hazard(self):
|
|
"""Boundary: Godown capacity warning at >85.0%."""
|
|
# 88.5% -> WARNING
|
|
h_warn = evaluate_warehouse_capacity_hazard("WH-02", "Indore Godown", Decimal("2655.0"), Decimal("3000.0"))
|
|
self.assertIsNotNone(h_warn)
|
|
self.assertEqual(h_warn["severity"], "WARNING")
|
|
self.assertEqual(h_warn["utilization_pct"], 88.5)
|
|
|
|
# 84.0% -> None
|
|
h_ok = evaluate_warehouse_capacity_hazard("WH-01", "Neemuch Main", Decimal("1680.0"), Decimal("2000.0"))
|
|
self.assertIsNone(h_ok)
|
|
|
|
# 0 capacity -> None
|
|
h_zero = evaluate_warehouse_capacity_hazard("WH-03", "Zero Cap", Decimal("0.0"), Decimal("0.0"))
|
|
self.assertIsNone(h_zero)
|
|
|
|
def test_evaluate_customer_credit_hazard(self):
|
|
"""Boundary: Credit watch (>80%) and hard lock (>100%)."""
|
|
# 104% -> CRITICAL
|
|
h_crit = evaluate_customer_credit_hazard("CUST-04", "Shanti Agro", Decimal("5200000.0"), Decimal("5000000.0"))
|
|
self.assertIsNotNone(h_crit)
|
|
self.assertEqual(h_crit["severity"], "CRITICAL")
|
|
self.assertEqual(h_crit["exposure_pct"], 104.0)
|
|
|
|
# 85% -> WARNING
|
|
h_warn = evaluate_customer_credit_hazard("CUST-02", "Patanjali Foods", Decimal("6375000.0"), Decimal("7500000.0"))
|
|
self.assertIsNotNone(h_warn)
|
|
self.assertEqual(h_warn["severity"], "WARNING")
|
|
self.assertEqual(h_warn["exposure_pct"], 85.0)
|
|
|
|
# 60% -> None
|
|
h_ok = evaluate_customer_credit_hazard("CUST-01", "Adani Wilmar", Decimal("3000000.0"), Decimal("5000000.0"))
|
|
self.assertIsNone(h_ok)
|
|
|
|
# 0 sanctioned limit -> None
|
|
h_zero = evaluate_customer_credit_hazard("CUST-05", "Zero Limit", Decimal("100.0"), Decimal("0.0"))
|
|
self.assertIsNone(h_zero)
|
|
|
|
# =========================================================================
|
|
# 5. Controller: AlertsController
|
|
# =========================================================================
|
|
|
|
def test_alerts_controller_queries_and_filters(self):
|
|
"""Happy & Boundary: Listing and filtering operational alerts."""
|
|
# Unauthenticated
|
|
res_unauth = self.alerts_ctrl.list_alerts(None, self.tenant_id)
|
|
self.assertEqual(res_unauth["status_code"], 401)
|
|
|
|
# List all active alerts (triggers seed of 4 default alerts)
|
|
res = self.alerts_ctrl.list_alerts(f"Bearer {self.token_supervisor}", self.tenant_id)
|
|
self.assertEqual(res["status_code"], 200)
|
|
self.assertGreaterEqual(res["count"], 4)
|
|
|
|
# Filter by severity = CRITICAL
|
|
res_crit = self.alerts_ctrl.list_alerts(
|
|
f"Bearer {self.token_supervisor}",
|
|
self.tenant_id,
|
|
severity_filter="CRITICAL",
|
|
)
|
|
self.assertEqual(res_crit["status_code"], 200)
|
|
for a in res_crit["alerts"]:
|
|
self.assertEqual(a["severity"], "CRITICAL")
|
|
|
|
# Filter by category = CREDIT_RISK
|
|
res_cat = self.alerts_ctrl.list_alerts(
|
|
f"Bearer {self.token_supervisor}",
|
|
self.tenant_id,
|
|
category_filter="CREDIT_RISK",
|
|
)
|
|
self.assertEqual(res_cat["status_code"], 200)
|
|
for a in res_cat["alerts"]:
|
|
self.assertEqual(a["category"], "CREDIT_RISK")
|
|
|
|
def test_alerts_controller_acknowledgment_workflow(self):
|
|
"""Happy, Boundary & Negative: Acknowledging alerts with RBAC and note validation."""
|
|
# 1. Unauthenticated -> 401
|
|
res_unauth = self.alerts_ctrl.acknowledge_alert(None, self.tenant_id, "alt-123", {"action_note": "Test note"})
|
|
self.assertEqual(res_unauth["status_code"], 401)
|
|
|
|
# 2. Unauthorized role (Guest) -> 403
|
|
res_perm = self.alerts_ctrl.acknowledge_alert(
|
|
f"Bearer {self.token_unauth}", self.tenant_id, "alt-123", {"action_note": "Test note"}
|
|
)
|
|
self.assertEqual(res_perm["status_code"], 403)
|
|
|
|
# 3. Seed alert
|
|
res_list = self.alerts_ctrl.list_alerts(f"Bearer {self.token_supervisor}", self.tenant_id)
|
|
alert_id = res_list["alerts"][0]["id"]
|
|
|
|
# 4. Short note (<5 chars) -> 422
|
|
res_short = self.alerts_ctrl.acknowledge_alert(
|
|
f"Bearer {self.token_supervisor}", self.tenant_id, alert_id, {"action_note": "abc"}
|
|
)
|
|
self.assertEqual(res_short["status_code"], 422)
|
|
|
|
# 5. Non-existent alert -> 404
|
|
res_404 = self.alerts_ctrl.acknowledge_alert(
|
|
f"Bearer {self.token_supervisor}", self.tenant_id, "alt-nonexistent", {"action_note": "Valid audit note"}
|
|
)
|
|
self.assertEqual(res_404["status_code"], 404)
|
|
|
|
# 6. Happy path acknowledgment -> 200
|
|
res_ack = self.alerts_ctrl.acknowledge_alert(
|
|
f"Bearer {self.token_supervisor}",
|
|
self.tenant_id,
|
|
alert_id,
|
|
{"action_note": "Spoke to customer accounts; RTGS expected by 3 PM."},
|
|
)
|
|
self.assertEqual(res_ack["status_code"], 200)
|
|
self.assertEqual(res_ack["alert"]["status"], "ACKNOWLEDGED")
|
|
self.assertEqual(res_ack["alert"]["acknowledged_by"], self.user_supervisor)
|
|
|
|
# Verify notification outbox recorded event
|
|
events = self.notifier.get_dispatched_notifications(tenant_id=self.tenant_id)
|
|
self.assertTrue(any(e.get("event_type") == "OPERATIONAL_ALERT_ACKNOWLEDGED" for e in events))
|
|
|
|
# 7. Repeat acknowledgment -> 409
|
|
res_repeat = self.alerts_ctrl.acknowledge_alert(
|
|
f"Bearer {self.token_supervisor}",
|
|
self.tenant_id,
|
|
alert_id,
|
|
{"action_note": "Duplicate attempt"},
|
|
)
|
|
self.assertEqual(res_repeat["status_code"], 409)
|
|
|
|
def test_alerts_controller_evaluation(self):
|
|
"""Happy Path: Evaluating operational hazards across 4 categories."""
|
|
# Insert a lot under QC > 24 hours to trigger an alert
|
|
now = datetime.now(timezone.utc)
|
|
lot_id = f"lot-hazard-{uuid.uuid4().hex[:6]}"
|
|
self.store.insert(
|
|
"inward_lots",
|
|
self.tenant_id,
|
|
{
|
|
"id": lot_id,
|
|
"status": "UNDER_QC",
|
|
"created_at": (now - timedelta(hours=30)).isoformat(),
|
|
},
|
|
)
|
|
|
|
res_eval = self.alerts_ctrl.evaluate_operational_hazards(
|
|
f"Bearer {self.token_supervisor}", self.tenant_id
|
|
)
|
|
self.assertEqual(res_eval["status_code"], 200)
|
|
self.assertEqual(res_eval["evaluated_categories"], 4)
|
|
self.assertGreaterEqual(res_eval["total_active_alerts"], 1)
|
|
|
|
# =========================================================================
|
|
# 6. Controller: ReportingController
|
|
# =========================================================================
|
|
|
|
def test_reporting_controller_dashboard(self):
|
|
"""Happy & Negative: Executive Control Centre Dashboard metrics."""
|
|
# Unauthenticated -> 401
|
|
res_unauth = self.reporting_ctrl.get_dashboard(None, self.tenant_id)
|
|
self.assertEqual(res_unauth["status_code"], 401)
|
|
|
|
# Unauthorized role -> 403
|
|
res_perm = self.reporting_ctrl.get_dashboard(f"Bearer {self.token_unauth}", self.tenant_id)
|
|
self.assertEqual(res_perm["status_code"], 403)
|
|
|
|
# Partner access -> 200
|
|
res = self.reporting_ctrl.get_dashboard(f"Bearer {self.token_partner}", self.tenant_id)
|
|
self.assertEqual(res["status_code"], 200)
|
|
self.assertTrue(res["success"])
|
|
metrics = res["metrics"]
|
|
self.assertGreater(metrics["stock_on_hand_mt"], 0.0)
|
|
self.assertGreater(metrics["total_receivables_inr"], 0.0)
|
|
self.assertIn("top_stock_lines", res)
|
|
self.assertIn("godown_utilization", res)
|
|
self.assertIn("alerts_summary", res)
|
|
|
|
def test_reporting_controller_20day_trends(self):
|
|
"""Happy Path: Rolling 20-day trading snapshots and aggregates."""
|
|
res = self.reporting_ctrl.get_20day_trends(
|
|
f"Bearer {self.token_partner}", self.tenant_id, window_days=20
|
|
)
|
|
self.assertEqual(res["status_code"], 200)
|
|
self.assertEqual(res["window_days"], 20)
|
|
self.assertEqual(res["data_points_count"], 20)
|
|
self.assertIn("summary", res)
|
|
self.assertGreater(res["summary"]["total_purchases_mt"], 0.0)
|
|
self.assertGreater(res["summary"]["total_sales_mt"], 0.0)
|
|
self.assertEqual(len(res["snapshots"]), 20)
|
|
|
|
# =========================================================================
|
|
# 7. Controller: AnalyticsController
|
|
# =========================================================================
|
|
|
|
def test_analytics_controller_market_trends(self):
|
|
"""Happy & Negative: Market desk commodity price trends and SMA-20."""
|
|
# Unauthenticated -> 401
|
|
res_unauth = self.analytics_ctrl.get_market_trends(None, self.tenant_id)
|
|
self.assertEqual(res_unauth["status_code"], 401)
|
|
|
|
# Unauthorized role -> 403
|
|
res_perm = self.analytics_ctrl.get_market_trends(f"Bearer {self.token_unauth}", self.tenant_id)
|
|
self.assertEqual(res_perm["status_code"], 403)
|
|
|
|
# Trader access -> 200
|
|
res = self.analytics_ctrl.get_market_trends(
|
|
f"Bearer {self.token_trader}",
|
|
self.tenant_id,
|
|
commodity_id="COMM-SOYBEAN",
|
|
window_days=20,
|
|
)
|
|
self.assertEqual(res["status_code"], 200)
|
|
self.assertEqual(res["commodity_id"], "COMM-SOYBEAN")
|
|
self.assertEqual(res["window_days"], 20)
|
|
self.assertEqual(res["data_points_count"], 20)
|
|
self.assertGreater(res["sma_20"], 0.0)
|
|
self.assertGreaterEqual(res["period_high"], res["sma_20"])
|
|
self.assertLessEqual(res["period_low"], res["sma_20"])
|
|
self.assertIn("price_velocity", res)
|
|
self.assertEqual(len(res["time_series"]), 20)
|
|
|
|
# =========================================================================
|
|
# 8. Notification Sandbox
|
|
# =========================================================================
|
|
|
|
def test_notification_mock_dispatch_and_inbox(self):
|
|
"""Happy & Boundary: Notification sandbox dispatching, failure simulation, and filtering."""
|
|
mock = NotificationMock()
|
|
mock.reset_for_tests()
|
|
|
|
# Normal dispatch
|
|
events = mock.dispatch_alert_notification(
|
|
tenant_id=self.tenant_id,
|
|
alert_id="alt-01",
|
|
category="CREDIT_RISK",
|
|
severity="CRITICAL",
|
|
title="Breach",
|
|
message="100% breach",
|
|
recipients=["ops@mandi.test", "md@mandi.test"],
|
|
)
|
|
self.assertEqual(len(events), 4) # 2 recipients * 2 channels (IN_APP, SMS)
|
|
self.assertEqual(events[0]["status"], "DELIVERED")
|
|
|
|
# Simulate recipient failure
|
|
mock.simulate_recipient_failure("bad@mandi.test", reason="INVALID_PHONE")
|
|
failed_events = mock.dispatch_alert_notification(
|
|
tenant_id=self.tenant_id,
|
|
alert_id="alt-02",
|
|
category="QC_PENDING",
|
|
severity="CRITICAL",
|
|
title="QC Hold",
|
|
message="Hold",
|
|
recipients=["bad@mandi.test"],
|
|
)
|
|
self.assertTrue(all(e["status"] == "FAILED" for e in failed_events))
|
|
|
|
# Query filters
|
|
self.assertEqual(len(mock.get_recipient_inbox("bad@mandi.test")), 2)
|
|
self.assertEqual(len(mock.get_dispatched_notifications(alert_id="alt-01")), 4)
|
|
|
|
def test_branch_coverage_alerts_and_reporting_stores(self):
|
|
"""Branch coverage: Seeded store collections for lots, warehouses, customers, and mandis."""
|
|
now = datetime.now(timezone.utc)
|
|
# 1. Seed custom lots
|
|
self.store.insert(
|
|
"lots",
|
|
self.tenant_id,
|
|
{
|
|
"id": "lot-custom-01",
|
|
"commodity": "Soybean",
|
|
"variety": "JS-335",
|
|
"warehouse_id": "WH-01",
|
|
"available_quantity_mt": 500.0,
|
|
"bags_count": 5000,
|
|
"rate_per_qtl": 5250.0,
|
|
"status": "QC_HOLD",
|
|
"created_at": (now - timedelta(hours=36)).isoformat(),
|
|
},
|
|
)
|
|
# Also lot with invalid created_at date format to cover exception path
|
|
self.store.insert(
|
|
"inward_lots",
|
|
self.tenant_id,
|
|
{
|
|
"id": "lot-bad-date",
|
|
"status": "UNDER_QC",
|
|
"created_at": "not-an-iso-date",
|
|
},
|
|
)
|
|
|
|
# 2. Seed custom warehouses
|
|
self.store.insert(
|
|
"warehouses",
|
|
self.tenant_id,
|
|
{
|
|
"id": "WH-99",
|
|
"name": "Overflow Godown",
|
|
"location": "Neemuch Industrial",
|
|
"current_occupancy_mt": 920.0,
|
|
"capacity_mt": 1000.0,
|
|
},
|
|
)
|
|
|
|
# 3. Seed custom customers
|
|
self.store.insert(
|
|
"customers",
|
|
self.tenant_id,
|
|
{
|
|
"id": "CUST-99",
|
|
"name": "Overdrawn Trader",
|
|
"current_outstanding_inr": 2500000.0,
|
|
"credit_limit_inr": 2000000.0,
|
|
},
|
|
)
|
|
|
|
# 4. Seed custom mandis
|
|
self.store.insert(
|
|
"mandis",
|
|
self.tenant_id,
|
|
{
|
|
"id": "MANDI-KOTA",
|
|
"name": "Kota Mandi",
|
|
"window_status": "OPEN",
|
|
},
|
|
)
|
|
|
|
# List alerts with "ALL" filters
|
|
res_all = self.alerts_ctrl.list_alerts(
|
|
f"Bearer {self.token_supervisor}",
|
|
self.tenant_id,
|
|
status_filter="ALL",
|
|
category_filter="ALL",
|
|
severity_filter="ALL",
|
|
)
|
|
self.assertEqual(res_all["status_code"], 200)
|
|
|
|
# Evaluate operational hazards with seeded stores
|
|
res_eval = self.alerts_ctrl.evaluate_operational_hazards(
|
|
f"Bearer {self.token_supervisor}", self.tenant_id
|
|
)
|
|
self.assertEqual(res_eval["status_code"], 200)
|
|
|
|
# Dashboard with seeded stores
|
|
res_dash = self.reporting_ctrl.get_dashboard(f"Bearer {self.token_partner}", self.tenant_id)
|
|
self.assertEqual(res_dash["status_code"], 200)
|
|
self.assertGreater(res_dash["metrics"]["stock_on_hand_mt"], 0.0)
|
|
|
|
# Analytics with mandi filter and closed observation
|
|
self.store.insert(
|
|
"market_observations",
|
|
self.tenant_id,
|
|
{
|
|
"id": "obs-closed",
|
|
"commodity_id": "COMM-SOYBEAN",
|
|
"mandi_id": "MANDI-NMH",
|
|
"observation_date": "2026-10-13",
|
|
"is_market_closed": True,
|
|
"modal_rate": 5300.0,
|
|
},
|
|
)
|
|
res_mandi = self.analytics_ctrl.get_market_trends(
|
|
f"Bearer {self.token_trader}",
|
|
self.tenant_id,
|
|
commodity_id="COMM-SOYBEAN",
|
|
mandi_id="MANDI-NMH",
|
|
window_days=10,
|
|
)
|
|
self.assertEqual(res_mandi["status_code"], 200)
|
|
|
|
# Unmatched mandi
|
|
res_unmatched = self.analytics_ctrl.get_market_trends(
|
|
f"Bearer {self.token_trader}",
|
|
self.tenant_id,
|
|
commodity_id="COMM-SOYBEAN",
|
|
mandi_id="MANDI-NONEXISTENT",
|
|
window_days=10,
|
|
)
|
|
self.assertEqual(res_unmatched["status_code"], 200)
|
|
self.assertEqual(res_unmatched["data_points_count"], 0)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|