"""Customer Sales Contracts, Credit Exposure Verification and Lot Allocation Models. Fulfills FR-SALESCONTRACTS-001, FR-SALESCONTRACTS-002, and FR-SALESCONTRACTS-003 (UC-008). Adheres to LLD-004, LLD-003, 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, ForeignKey from backend.app.models.user import Base except ImportError: class Base: pass Column = String = DateTime = Numeric = Integer = Boolean = ForeignKey = lambda *args, **kwargs: None CUSTOMER_SEGMENTS = {"Wholesale", "Processor", "Institutional", "Distributor"} PAYMENT_TERMS = {"Advance", "CAD", "15 Days", "30 Days"} SALES_ORDER_STATUSES = { "CONFIRMED", "PARTIALLY_ALLOCATED", "FULLY_ALLOCATED", "FULFILLED", "CANCELLED", } class CustomerSalesOrder(Base): """Customer Sales Order Contract with commercial terms and credit limits.""" __tablename__ = "customer_sales_orders" __table_args__ = {"schema": "public"} id = Column(String(36), primary_key=True, default=lambda: str(uuid.uuid4())) tenant_id = Column(String(36), nullable=False, index=True) sales_order_number = Column(String(32), nullable=False, unique=True, index=True) order_date = Column(DateTime, default=lambda: datetime.now(timezone.utc)) customer_id = Column(String(36), nullable=False, index=True) destination_city = Column(String(64), nullable=False) customer_segment = Column(String(32), nullable=False) commodity_id = Column(String(36), nullable=False, index=True) variety = Column(String(64), nullable=False) grade = Column(String(32), default="FAQ") contract_qty_mt = Column(Numeric(12, 3), nullable=False) contract_rate_per_qtl = Column(Numeric(10, 2), nullable=False) total_sales_value_inr = Column(Numeric(14, 2), nullable=False) payment_terms = Column(String(32), nullable=False) credit_exposure_ratio = Column(Numeric(6, 2), nullable=False) credit_warning = Column(Boolean, default=False) credit_override = Column(Boolean, default=False) override_approved_by = Column(String(64), nullable=True) allocated_qty_mt = Column(Numeric(12, 3), default=Decimal("0.000")) status = Column(String(32), default="CONFIRMED") created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc)) def __init__( self, tenant_id: str, sales_order_number: str, customer_id: str, destination_city: str, customer_segment: str, commodity_id: str, variety: str, contract_qty_mt: Decimal, contract_rate_per_qtl: Decimal, payment_terms: str, credit_exposure_ratio: Decimal, credit_override: bool = False, override_approved_by: Optional[str] = None, grade: str = "FAQ", order_id: Optional[str] = None, ): if customer_segment not in CUSTOMER_SEGMENTS: raise ValueError( f"Invalid customer segment '{customer_segment}'. Allowed: {sorted(CUSTOMER_SEGMENTS)}" ) if payment_terms not in PAYMENT_TERMS: raise ValueError( f"Invalid payment terms '{payment_terms}'. Allowed: {sorted(PAYMENT_TERMS)}" ) if contract_qty_mt <= Decimal("0.000"): raise ValueError("Contract quantity MT must be positive") if contract_rate_per_qtl <= Decimal("0.00"): raise ValueError("Contract rate per quintal must be positive") # Commercial arithmetic: Total = MT * 10 (Qtl/MT) * Rate/Qtl total_sales_value = (contract_qty_mt * Decimal("10.0") * contract_rate_per_qtl).quantize( Decimal("0.01"), rounding=ROUND_HALF_UP ) credit_warning = credit_exposure_ratio > Decimal("80.00") if credit_exposure_ratio > Decimal("100.00") and not credit_override: raise ValueError( f"Credit limit exceeded: projected exposure ratio {credit_exposure_ratio}% > 100%. " f"Requires Partner authorization to confirm." ) if credit_override and not override_approved_by: raise ValueError("Partner approval ID is mandatory when credit_override is True") self.id = order_id or str(uuid.uuid4()) self.tenant_id = tenant_id self.sales_order_number = sales_order_number self.order_date = datetime.now(timezone.utc) self.customer_id = customer_id self.destination_city = destination_city self.customer_segment = customer_segment self.commodity_id = commodity_id self.variety = variety self.grade = grade self.contract_qty_mt = contract_qty_mt self.contract_rate_per_qtl = contract_rate_per_qtl self.total_sales_value_inr = total_sales_value self.payment_terms = payment_terms self.credit_exposure_ratio = credit_exposure_ratio self.credit_warning = credit_warning self.credit_override = credit_override self.override_approved_by = override_approved_by self.allocated_qty_mt = Decimal("0.000") self.status = "CONFIRMED" self.created_at = datetime.now(timezone.utc) def apply_allocation(self, allocated_mt: Decimal) -> None: """Updates allocation tally and advances FSM status.""" new_total = (self.allocated_qty_mt + allocated_mt).quantize(Decimal("0.001")) if new_total > self.contract_qty_mt: raise ValueError( f"Total allocated {new_total} MT cannot exceed contract quantity {self.contract_qty_mt} MT" ) self.allocated_qty_mt = new_total if self.allocated_qty_mt == self.contract_qty_mt: self.status = "FULLY_ALLOCATED" elif self.allocated_qty_mt > Decimal("0.000"): self.status = "PARTIALLY_ALLOCATED" def to_dict(self) -> Dict[str, Any]: return { "id": self.id, "tenant_id": self.tenant_id, "sales_order_number": self.sales_order_number, "order_date": self.order_date.isoformat() if self.order_date else None, "customer_id": self.customer_id, "destination_city": self.destination_city, "customer_segment": self.customer_segment, "commodity_id": self.commodity_id, "variety": self.variety, "grade": self.grade, "contract_qty_mt": float(self.contract_qty_mt), "contract_rate_per_qtl": float(self.contract_rate_per_qtl), "total_sales_value_inr": float(self.total_sales_value_inr), "payment_terms": self.payment_terms, "credit_exposure_ratio": float(self.credit_exposure_ratio), "credit_warning": self.credit_warning, "credit_override": self.credit_override, "override_approved_by": self.override_approved_by, "allocated_qty_mt": float(self.allocated_qty_mt), "status": self.status, "created_at": self.created_at.isoformat() if self.created_at else None, } class SalesOrderAllocation(Base): """Specific lot inventory reservation allocated to a confirmed customer sales order.""" __tablename__ = "sales_order_allocations" __table_args__ = {"schema": "public"} id = Column(String(36), primary_key=True, default=lambda: str(uuid.uuid4())) tenant_id = Column(String(36), nullable=False, index=True) sales_order_id = Column(String(36), nullable=False, index=True) lot_id = Column(String(36), nullable=False, index=True) warehouse_id = Column(String(36), nullable=False, index=True) allocated_qty_mt = Column(Numeric(12, 3), nullable=False) allocated_bags = Column(Integer, nullable=False) allocated_at = Column(DateTime, default=lambda: datetime.now(timezone.utc)) def __init__( self, tenant_id: str, sales_order_id: str, lot_id: str, warehouse_id: str, allocated_qty_mt: Decimal, allocated_bags: int, lot_qc_status: str, available_unreserved_mt: Decimal, allocation_id: Optional[str] = None, ): if lot_qc_status != "RELEASED": raise ValueError( f"Cannot allocate lot with QC status '{lot_qc_status}'. Only 'RELEASED' lots are eligible." ) if allocated_qty_mt <= Decimal("0.000") or allocated_bags <= 0: raise ValueError("Allocated MT and bags must be positive") if allocated_qty_mt > available_unreserved_mt: raise ValueError( f"Requested allocation {allocated_qty_mt} MT exceeds available unreserved {available_unreserved_mt} MT" ) self.id = allocation_id or str(uuid.uuid4()) self.tenant_id = tenant_id self.sales_order_id = sales_order_id self.lot_id = lot_id self.warehouse_id = warehouse_id self.allocated_qty_mt = allocated_qty_mt self.allocated_bags = allocated_bags self.allocated_at = datetime.now(timezone.utc) def to_dict(self) -> Dict[str, Any]: return { "id": self.id, "tenant_id": self.tenant_id, "sales_order_id": self.sales_order_id, "lot_id": self.lot_id, "warehouse_id": self.warehouse_id, "allocated_qty_mt": float(self.allocated_qty_mt), "allocated_bags": self.allocated_bags, "allocated_at": self.allocated_at.isoformat() if self.allocated_at else None, }