c_agri_trade_code/backend/app/models/policy.py

176 lines
8.3 KiB
Python

"""Tenant Operating Policy Engine Domain Models.
Fulfills:
- FR-TENANTOPERATINGPOLICIES-001 (Effective-Dated Tenant Operating Policy Configuration)
Adheres to LLD-001, LLD-002, and UP-AI v1.5 standards.
"""
from datetime import datetime, timezone
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
class TenantOperatingPolicy(Base):
"""Effective-dated, append-only tenant operating risk policy."""
__tablename__ = "tenant_operating_policies"
id = Column(String(36), primary_key=True)
tenant_id = Column(String(36), nullable=False, index=True)
version = Column(Integer, nullable=False, default=1)
weighbridge_tolerance_pct = Column(Numeric(5, 2), nullable=False, default=0.50)
moisture_deduction_threshold_pct = Column(Numeric(5, 2), nullable=False, default=12.00)
credit_watch_threshold_pct = Column(Numeric(5, 2), nullable=False, default=80.00)
credit_lock_threshold_pct = Column(Numeric(5, 2), nullable=False, default=100.00)
qc_required_default = Column(Boolean, nullable=False, default=True)
partner_dispatch_override_ceiling_inr = Column(Numeric(14, 2), nullable=False, default=5000000.00)
effective_from = Column(DateTime, nullable=False)
effective_to = Column(DateTime, nullable=True)
created_by = Column(String(100), nullable=False)
change_reason = Column(String(500), nullable=False)
created_at = Column(DateTime, nullable=False, default=lambda: datetime.now(timezone.utc))
def __init__(
self,
tenant_id: str,
created_by: str,
change_reason: str,
effective_from: datetime,
effective_to: Optional[datetime] = None,
version: int = 1,
weighbridge_tolerance_pct: float = 0.50,
moisture_deduction_threshold_pct: float = 12.00,
credit_watch_threshold_pct: float = 80.00,
credit_lock_threshold_pct: float = 100.00,
qc_required_default: bool = True,
partner_dispatch_override_ceiling_inr: float = 5000000.00,
id: Optional[str] = None,
):
if not tenant_id or not tenant_id.strip():
raise ValueError("Tenant ID cannot be empty")
if not created_by or not created_by.strip():
raise ValueError("Created by user ID cannot be empty")
if not change_reason or len(change_reason.strip()) < 5:
raise ValueError("Change reason must be at least 5 characters")
if version < 1:
raise ValueError("Policy version must be >= 1")
# Validate ranges
if not (0.01 <= weighbridge_tolerance_pct <= 5.00):
raise ValueError(f"Weighbridge tolerance {weighbridge_tolerance_pct}% must be between 0.01% and 5.00%")
if not (5.00 <= moisture_deduction_threshold_pct <= 25.00):
raise ValueError(f"Moisture deduction trigger {moisture_deduction_threshold_pct}% must be between 5.00% and 25.00%")
if not (50.00 <= credit_watch_threshold_pct <= 95.00):
raise ValueError(f"Credit watch threshold {credit_watch_threshold_pct}% must be between 50.00% and 95.00%")
if not (80.00 <= credit_lock_threshold_pct <= 150.00):
raise ValueError(f"Credit lock threshold {credit_lock_threshold_pct}% must be between 80.00% and 150.00%")
if credit_watch_threshold_pct >= credit_lock_threshold_pct:
raise ValueError(f"Credit watch threshold ({credit_watch_threshold_pct}%) must be strictly less than credit lock threshold ({credit_lock_threshold_pct}%)")
if partner_dispatch_override_ceiling_inr < 0:
raise ValueError("Partner dispatch override ceiling cannot be negative")
# Normalize and validate effective dates
ef = effective_from
if ef.tzinfo is None:
ef = ef.replace(tzinfo=timezone.utc)
et = effective_to
if et is not None:
if et.tzinfo is None:
et = et.replace(tzinfo=timezone.utc)
if et <= ef:
raise ValueError("effective_to must be strictly greater than effective_from")
self.id = id or str(uuid.uuid4())
self.tenant_id = tenant_id.strip()
self.version = version
self.created_by = created_by.strip()
self.change_reason = change_reason.strip()
self.effective_from = ef
self.effective_to = et
self.weighbridge_tolerance_pct = Decimal(str(weighbridge_tolerance_pct))
self.moisture_deduction_threshold_pct = Decimal(str(moisture_deduction_threshold_pct))
self.credit_watch_threshold_pct = Decimal(str(credit_watch_threshold_pct))
self.credit_lock_threshold_pct = Decimal(str(credit_lock_threshold_pct))
self.qc_required_default = qc_required_default
self.partner_dispatch_override_ceiling_inr = Decimal(str(partner_dispatch_override_ceiling_inr))
self.created_at = datetime.now(timezone.utc)
def is_effective_at(self, check_time: Optional[datetime] = None) -> bool:
"""Determines whether this policy is active for the given timestamp."""
t = check_time or datetime.now(timezone.utc)
if t.tzinfo is None:
t = t.replace(tzinfo=timezone.utc)
ef = self.effective_from
if ef.tzinfo is None:
ef = ef.replace(tzinfo=timezone.utc)
if t < ef:
return False
if self.effective_to is not None:
et = self.effective_to
if et.tzinfo is None:
et = et.replace(tzinfo=timezone.utc)
if t > et:
return False
return True
def to_dict(self) -> Dict[str, Any]:
return {
"id": self.id,
"tenant_id": self.tenant_id,
"version": self.version,
"weighbridge_tolerance_pct": float(self.weighbridge_tolerance_pct),
"moisture_deduction_threshold_pct": float(self.moisture_deduction_threshold_pct),
"credit_watch_threshold_pct": float(self.credit_watch_threshold_pct),
"credit_lock_threshold_pct": float(self.credit_lock_threshold_pct),
"qc_required_default": self.qc_required_default,
"partner_dispatch_override_ceiling_inr": float(self.partner_dispatch_override_ceiling_inr),
"effective_from": self.effective_from.isoformat() if hasattr(self.effective_from, "isoformat") else str(self.effective_from),
"effective_to": self.effective_to.isoformat() if hasattr(self.effective_to, "isoformat") and self.effective_to else None,
"created_by": self.created_by,
"change_reason": self.change_reason,
"created_at": self.created_at.isoformat() if hasattr(self.created_at, "isoformat") else str(self.created_at),
}
def check_policy_intervals_overlap(
existing_policies: List[TenantOperatingPolicy],
new_from: datetime,
new_to: Optional[datetime] = None
) -> bool:
"""Verifies that a proposed policy effective interval does not conflict with existing policies."""
nf = new_from.replace(tzinfo=timezone.utc) if new_from.tzinfo is None else new_from
nt = new_to.replace(tzinfo=timezone.utc) if (new_to and new_to.tzinfo is None) else new_to
for pol in existing_policies:
ef = pol.effective_from.replace(tzinfo=timezone.utc) if pol.effective_from.tzinfo is None else pol.effective_from
et = pol.effective_to.replace(tzinfo=timezone.utc) if (pol.effective_to and pol.effective_to.tzinfo is None) else pol.effective_to
# Case 1: Existing policy has no end date (open-ended)
if et is None:
# Overlaps if new policy starts on or after existing open-ended start, OR new policy ends after existing start
if nt is None or nt >= ef:
if nf >= ef or (nt is not None and nt >= ef):
return True
else:
# Existing policy has bounded interval [ef, et]
if nt is None:
if nf <= et:
return True
else:
# Both are bounded: overlap if max(nf, ef) <= min(nt, et)
if max(nf, ef) <= min(nt, et):
return True
return False