"""Market Desk API Controller. Fulfills: - STORY-MKT-001 (FR-MKT-001): Capture Daily Mandi Arrival Observations. - STORY-MKT-002 (FR-MKT-002): Capture Daily Mandi Price Range and Modal Rate. """ from datetime import datetime, date, timezone 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, context_resolver, record_audit_event, ) from backend.app.db.session import storage from backend.app.models.market import MarketObservation, validate_market_observation logger = logging.getLogger("atb.api.market") class MarketController: """Handles daily mandi observations and modal price bulletin endpoints.""" def __init__(self, store=storage, resolver=None): self.store = store self.resolver = resolver or TenantContextResolver(store=self.store) 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} return { "authenticated": True, "session": session, "context": ctx, "tenant_id": ctx.tenant_id, "user_id": user_id } def record_observation( self, auth_header: Optional[str], tenant_header: Optional[str], payload: Dict[str, Any] ) -> Dict[str, Any]: """POST /api/v1/market/observations (FR-MKT-001, FR-MKT-002).""" 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"] # Check required roles allowed_roles = {"Mandi Buyer", "Desk Trader", "Procurement Officer", "Tenant Administrator"} if not any(r in allowed_roles for r in ctx.roles): return { "error": "INSUFFICIENT_PERMISSIONS", "message": "Only Mandi Buyers, Desk Traders, or Tenant Admins can record daily observations", "status_code": 403 } # Parse inputs try: mandi_id = payload.get("mandi_id") commodity_id = payload.get("commodity_id") variety = payload.get("variety", "") grade = payload.get("grade", "FAQ") date_str = payload.get("observation_date") obs_date = datetime.strptime(date_str, "%Y-%m-%d").date() if isinstance(date_str, str) else date_str is_market_closed = payload.get("is_market_closed", False) arrival_mt = Decimal(str(payload.get("arrival_mt", "0.0"))) internal_stock_mt = Decimal(str(payload["internal_stock_mt"])) if payload.get("internal_stock_mt") is not None else None min_rate = Decimal(str(payload["min_rate"])) if payload.get("min_rate") is not None else None max_rate = Decimal(str(payload["max_rate"])) if payload.get("max_rate") is not None else None modal_rate = Decimal(str(payload["modal_rate"])) if payload.get("modal_rate") is not None else None source = payload.get("source", "APMC_BULLETIN") if not mandi_id or not commodity_id or not variety or not obs_date: return { "error": "VALIDATION_ERROR", "message": "mandi_id, commodity_id, variety, and observation_date are mandatory", "status_code": 422 } # Enforce duplicate observation constraint dup = self.store.query( "market_observations", tenant_id, lambda o: ( o.get("mandi_id") == mandi_id and o.get("commodity_id") == commodity_id and o.get("variety") == variety and o.get("observation_date") == str(obs_date) ) ) if dup: return { "error": "DUPLICATE_OBSERVATION", "message": "Duplicate observation already exists for this market, commodity, variety, and date", "status_code": 409 } # Create observation model obs = MarketObservation( tenant_id=tenant_id, mandi_id=mandi_id, observation_date=obs_date, commodity_id=commodity_id, variety=variety, grade=grade, arrival_mt=arrival_mt, internal_stock_mt=internal_stock_mt, min_rate=min_rate, max_rate=max_rate, modal_rate=modal_rate, source=source, is_market_closed=is_market_closed ) # Persist data = obs.to_dict() self.store.insert("market_observations", tenant_id, data) # Audit trail record_audit_event( store=self.store, tenant_id=tenant_id, actor_user_id=auth_res["user_id"], action_type="RECORD_MARKET_OBSERVATION", resource_type="market_observation", resource_id=obs.id, before_state=None, after_state={"mandi_id": mandi_id, "commodity": commodity_id, "modal_rate": float(modal_rate) if modal_rate else None} ) return { "success": True, "observation": data, "status_code": 201 } except ValueError as e: return {"error": "VALIDATION_ERROR", "message": str(e), "status_code": 422} except Exception as e: logger.exception("Failed to record market observation") return {"error": "INTERNAL_ERROR", "message": str(e), "status_code": 500} def list_observations( self, auth_header: Optional[str], tenant_header: Optional[str], mandi_id: Optional[str] = None, date_filter: Optional[str] = None ) -> Dict[str, Any]: """GET /api/v1/market/observations (FR-MKT-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(o): if mandi_id and o.get("mandi_id") != mandi_id: return False if date_filter and o.get("observation_date") != date_filter: return False return True records = self.store.query("market_observations", tenant_id, predicate) return { "success": True, "count": len(records), "observations": records, "status_code": 200 } def get_latest_rates( self, auth_header: Optional[str], tenant_header: Optional[str], commodity_id: str, mandi_id: Optional[str] = None ) -> Dict[str, Any]: """GET /api/v1/market/rates/latest (FR-MKT-002).""" 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(o): if o.get("commodity_id") != commodity_id: return False if mandi_id and o.get("mandi_id") != mandi_id: return False return not o.get("is_market_closed", False) records = self.store.query("market_observations", tenant_id, predicate) if not records: return { "success": True, "commodity_id": commodity_id, "mandi_id": mandi_id, "benchmark_modal_rate": None, "message": "No active observations found for commodity", "status_code": 200 } # Sort by date descending records.sort(key=lambda x: x.get("observation_date", ""), reverse=True) latest = records[0] return { "success": True, "commodity_id": commodity_id, "mandi_id": latest.get("mandi_id"), "observation_date": latest.get("observation_date"), "benchmark_modal_rate": latest.get("modal_rate"), "min_rate": latest.get("min_rate"), "max_rate": latest.get("max_rate"), "status_code": 200 } market_controller = MarketController()