"""Tenant Operating Policy Configuration API Controller. Fulfills: - STORY-POLICY-001 (FR-TENANTOPERATINGPOLICIES-001): Effective-Dated Tenant Operating Policy Engine (UC-026). Adheres to LLD-001, LLD-002, and UP-AI v1.5 standards. """ from datetime import datetime, 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, record_audit_event, ) from backend.app.db.session import storage from backend.app.models.policy import ( TenantOperatingPolicy, check_policy_intervals_overlap, ) from sandbox.notification_mock import notification_mock logger = logging.getLogger("atb.api.policies") class PolicyController: """Handles effective-dated policy publishing, version history, and as-of queries.""" def __init__(self, store=storage, resolver=None, notifier=notification_mock): self.store = store self.resolver = resolver or TenantContextResolver(store=self.store) self.notifier = notifier 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, ) return { "authenticated": True, "context": ctx, "user_id": user_id, "email": email, "roles": ctx.roles, } except TenantContextResolutionError as err: return {"authenticated": False, "error": err.message, "code": err.code, "status_code": err.status_code} def create_policy( self, auth_header: Optional[str], tenant_header: Optional[str], payload: Dict[str, Any] ) -> Dict[str, Any]: """POST /api/v1/policies""" auth = self._authenticate_and_resolve(auth_header, tenant_header) if not auth["authenticated"]: return auth ctx: TenantContext = auth["context"] tenant_id = ctx.tenant_id actor_email = auth["email"] # Parse effective dates ef_raw = payload.get("effective_from") if not ef_raw: return {"error": "EFFECTIVE_FROM_REQUIRED", "message": "effective_from timestamp is required", "status_code": 422} try: effective_from = datetime.fromisoformat(ef_raw.replace("Z", "+00:00")) except (ValueError, TypeError): return {"error": "INVALID_DATE_FORMAT", "message": "Invalid effective_from ISO format", "status_code": 422} et_raw = payload.get("effective_to") effective_to = None if et_raw: try: effective_to = datetime.fromisoformat(et_raw.replace("Z", "+00:00")) except (ValueError, TypeError): return {"error": "INVALID_DATE_FORMAT", "message": "Invalid effective_to ISO format", "status_code": 422} # Check existing policies for version calculation and interval overlap existing = self.store.list("tenant_operating_policies", tenant_id) existing_models = [] for p in existing: try: ef = datetime.fromisoformat(p["effective_from"]) et = datetime.fromisoformat(p["effective_to"]) if p.get("effective_to") else None pol_obj = TenantOperatingPolicy( tenant_id=tenant_id, created_by=p.get("created_by", "system"), change_reason=p.get("change_reason", "initial"), effective_from=ef, effective_to=et, version=p.get("version", 1), weighbridge_tolerance_pct=float(p.get("weighbridge_tolerance_pct", 0.5)), moisture_deduction_threshold_pct=float(p.get("moisture_deduction_threshold_pct", 12.0)), credit_watch_threshold_pct=float(p.get("credit_watch_threshold_pct", 80.0)), credit_lock_threshold_pct=float(p.get("credit_lock_threshold_pct", 100.0)), qc_required_default=bool(p.get("qc_required_default", True)), partner_dispatch_override_ceiling_inr=float(p.get("partner_dispatch_override_ceiling_inr", 5000000.0)), id=p.get("id"), ) existing_models.append(pol_obj) except Exception: pass # Check interval overlap if existing_models and check_policy_intervals_overlap(existing_models, effective_from, effective_to): # Check if auto-closing open-ended prior policy is requested auto_close = payload.get("auto_close_prior", False) if auto_close: for p_dict in existing: if not p_dict.get("effective_to"): p_dict["effective_to"] = effective_from.isoformat() self.store.update("tenant_operating_policies", tenant_id, p_dict["id"], p_dict) else: return { "error": "OVERLAPPING_POLICY_INTERVAL", "message": "The proposed policy effective interval conflicts with an existing published policy version. Set effective dates to a non-overlapping window or provide auto_close_prior=True.", "status_code": 409, } next_version = len(existing) + 1 try: policy = TenantOperatingPolicy( tenant_id=tenant_id, created_by=actor_email, change_reason=payload.get("change_reason", ""), effective_from=effective_from, effective_to=effective_to, version=next_version, weighbridge_tolerance_pct=float(payload.get("weighbridge_tolerance_pct", 0.50)), moisture_deduction_threshold_pct=float(payload.get("moisture_deduction_threshold_pct", 12.00)), credit_watch_threshold_pct=float(payload.get("credit_watch_threshold_pct", 80.00)), credit_lock_threshold_pct=float(payload.get("credit_lock_threshold_pct", 100.00)), qc_required_default=bool(payload.get("qc_required_default", True)), partner_dispatch_override_ceiling_inr=float(payload.get("partner_dispatch_override_ceiling_inr", 5000000.00)), id=payload.get("id"), ) except (ValueError, TypeError) as e: return {"error": "VALIDATION_ERROR", "message": str(e), "status_code": 422} self.store.insert("tenant_operating_policies", tenant_id, policy.to_dict()) # Notify outbox and record audit log self.notifier.record_event( tenant_id=tenant_id, event_type="OPERATING_POLICY_PUBLISHED", payload={ "policy_id": policy.id, "version": policy.version, "author": actor_email, "effective_from": policy.effective_from.isoformat(), }, ) record_audit_event( store=self.store, tenant_id=tenant_id, actor_id=actor_email, action="PUBLISH_OPERATING_POLICY", entity_type="TENANT_OPERATING_POLICY", entity_id=policy.id, details={"version": policy.version, "reason": policy.change_reason}, ) resp = policy.to_dict() resp["status_code"] = 201 return resp def get_effective_policy( self, auth_header: Optional[str], tenant_header: Optional[str], as_of: Optional[str] = None ) -> Dict[str, Any]: """GET /api/v1/policies/effective""" auth = self._authenticate_and_resolve(auth_header, tenant_header) if not auth["authenticated"]: return auth ctx: TenantContext = auth["context"] tenant_id = ctx.tenant_id # Determine reference time ref_time = datetime.now(timezone.utc) if as_of: try: ref_time = datetime.fromisoformat(as_of.replace("Z", "+00:00")) except (ValueError, TypeError): return {"error": "INVALID_DATE_FORMAT", "message": "Invalid as_of ISO timestamp format", "status_code": 422} policies = self.store.list("tenant_operating_policies", tenant_id) # If tenant has no configured policies, synthesize and persist default baseline policy v1 if not policies: default_policy = TenantOperatingPolicy( tenant_id=tenant_id, created_by="system.baseline", change_reason="Default system operational policy baseline", effective_from=datetime(2026, 1, 1, 0, 0, 0, tzinfo=timezone.utc), effective_to=None, version=1, weighbridge_tolerance_pct=0.50, moisture_deduction_threshold_pct=12.00, credit_watch_threshold_pct=80.00, credit_lock_threshold_pct=100.00, qc_required_default=True, partner_dispatch_override_ceiling_inr=5000000.00, ) self.store.insert("tenant_operating_policies", tenant_id, default_policy.to_dict()) policies = [default_policy.to_dict()] # Find matching policy matching = [] for p in policies: try: ef = datetime.fromisoformat(p["effective_from"]) et = datetime.fromisoformat(p["effective_to"]) if p.get("effective_to") else None if ef.tzinfo is None: ef = ef.replace(tzinfo=timezone.utc) if et and et.tzinfo is None: et = et.replace(tzinfo=timezone.utc) if ef <= ref_time and (et is None or ref_time <= et): matching.append(p) except Exception: pass if matching: # Pick highest version matching.sort(key=lambda x: x.get("version", 0), reverse=True) res = dict(matching[0]) res["status_code"] = 200 return res # Fallback to latest published version policies.sort(key=lambda x: x.get("version", 0), reverse=True) res = dict(policies[0]) res["status_code"] = 200 return res def list_policies( self, auth_header: Optional[str], tenant_header: Optional[str] ) -> Dict[str, Any]: """GET /api/v1/policies""" auth = self._authenticate_and_resolve(auth_header, tenant_header) if not auth["authenticated"]: return auth ctx: TenantContext = auth["context"] tenant_id = ctx.tenant_id policies = self.store.list("tenant_operating_policies", tenant_id) policies.sort(key=lambda x: x.get("version", 0), reverse=True) return {"policies": policies, "count": len(policies), "status_code": 200} policy_controller = PolicyController()