c_agri_trade_code/backend/app/models/quality.py

282 lines
12 KiB
Python

"""Quality Assay, Laboratory Inspection and Inventory Lot Models.
Fulfills FR-INWARDRECEIVING-006 (UC-005) and FR-QUALITYANDLOTCONTROL-001..004 (UC-006).
Adheres to 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, ForeignKey
from backend.app.models.user import Base
except ImportError:
class Base:
pass
Column = String = DateTime = Numeric = ForeignKey = lambda *args, **kwargs: None
LOT_QC_STATES = {"QUALITY_HOLD", "RELEASED", "REJECTED"}
VALID_QC_TRANSITIONS = {
"QUALITY_HOLD": {"RELEASED", "REJECTED"},
"RELEASED": set(), # Released lots do not move back to Hold without formal re-sample
"REJECTED": set(), # Terminal state
}
def calculate_quality_rebates(
lot_quantity_mt: Decimal,
trade_rate_per_qtl: Decimal,
moisture_pct: Decimal,
foreign_matter_pct: Decimal,
standard_moisture_max: Decimal = Decimal("10.0"),
standard_foreign_max: Decimal = Decimal("1.5")
) -> Dict[str, Any]:
"""Calculates commercial weight haircuts and rate cuts (Karda) against FAQ benchmarks."""
for p_name, val in [("moisture_pct", moisture_pct), ("foreign_matter_pct", foreign_matter_pct)]:
if not (Decimal("0.0") <= val <= Decimal("100.0")):
raise ValueError(f"{p_name} must be between 0.0 and 100.0 percent")
# Excess moisture leads to physical weight deduction
excess_moisture = max(Decimal("0.0"), moisture_pct - standard_moisture_max)
weight_deduction_mt = (lot_quantity_mt * (excess_moisture / Decimal("100.0"))).quantize(
Decimal("0.001"), rounding=ROUND_HALF_UP
)
net_billable_weight_mt = (lot_quantity_mt - weight_deduction_mt).quantize(
Decimal("0.001"), rounding=ROUND_HALF_UP
)
# Excess foreign matter leads to price rate cut (₹/Qtl)
excess_foreign = max(Decimal("0.0"), foreign_matter_pct - standard_foreign_max)
# Standard formula: 1% excess admixture = ₹ 30.00 / Qtl rate cut
rate_deduction_per_qtl = (excess_foreign * Decimal("30.00")).quantize(
Decimal("0.01"), rounding=ROUND_HALF_UP
)
# Total rebate amount = (weight deduction value) + (remaining qtl * rate cut)
weight_cut_val = weight_deduction_mt * Decimal("10.0") * trade_rate_per_qtl
rate_cut_val = net_billable_weight_mt * Decimal("10.0") * rate_deduction_per_qtl
total_rebate_amount = (weight_cut_val + rate_cut_val).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
return {
"excess_moisture_pct": excess_moisture,
"weight_deduction_mt": weight_deduction_mt,
"net_billable_weight_mt": net_billable_weight_mt,
"excess_foreign_pct": excess_foreign,
"rate_deduction_per_qtl": rate_deduction_per_qtl,
"total_rebate_amount": total_rebate_amount
}
class InventoryLot(Base):
__tablename__ = "inventory_lots"
__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)
lot_number = Column(String(32), nullable=False, unique=True, index=True)
grn_id = Column(String(36), nullable=False, index=True)
commodity_id = Column(String(36), nullable=False)
variety = Column(String(64), nullable=False)
grade = Column(String(32), default="FAQ")
godown_stack_id = Column(String(36), nullable=False)
initial_quantity_mt = Column(Numeric(12, 3), nullable=False)
current_quantity_mt = Column(Numeric(12, 3), nullable=False)
qc_status = Column(String(32), default="QUALITY_HOLD", index=True)
parent_lot_id = Column(String(36), nullable=True, index=True)
created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
def __init__(
self,
tenant_id: str,
lot_number: str,
grn_id: str,
commodity_id: str,
variety: str,
godown_stack_id: str,
initial_quantity_mt: Decimal,
grade: str = "FAQ",
parent_lot_id: Optional[str] = None,
lot_id: Optional[str] = None
):
if initial_quantity_mt <= Decimal("0.000"):
raise ValueError("Lot initial quantity MT must be > 0.0")
self.id = lot_id or str(uuid.uuid4())
self.tenant_id = tenant_id
self.lot_number = lot_number
self.grn_id = grn_id
self.commodity_id = commodity_id
self.variety = variety
self.grade = grade
self.godown_stack_id = godown_stack_id
self.initial_quantity_mt = initial_quantity_mt
self.current_quantity_mt = initial_quantity_mt
self.qc_status = "QUALITY_HOLD"
self.parent_lot_id = parent_lot_id
self.created_at = datetime.now(timezone.utc)
def transition_qc_status(self, new_status: str) -> None:
"""Executes strict finite state machine transition on lot quality status."""
if new_status not in LOT_QC_STATES:
raise ValueError(f"Invalid QC status '{new_status}'")
if self.qc_status == new_status:
return
allowed = VALID_QC_TRANSITIONS.get(self.qc_status, set())
if new_status not in allowed:
raise ValueError(
f"Illegal QC state transition from '{self.qc_status}' to '{new_status}'. "
f"Allowed: {list(allowed) if allowed else 'None (terminal)'}."
)
self.qc_status = new_status
def assert_can_dispatch(self) -> None:
"""Enforces invariant: Produce in QUALITY_HOLD or REJECTED cannot be dispatched."""
if self.qc_status == "QUALITY_HOLD":
raise ValueError(f"Cannot dispatch lot '{self.lot_number}' under Quality Hold")
if self.qc_status == "REJECTED":
raise ValueError(f"Cannot dispatch lot '{self.lot_number}' with status REJECTED")
def split_lot(self, split_quantities_mt: List[Decimal]) -> List["InventoryLot"]:
"""Splits this lot into child sub-lots preserving ancestry lineage."""
self.assert_can_dispatch()
total_split = sum(split_quantities_mt)
if total_split > self.current_quantity_mt:
raise ValueError(f"Split quantity ({total_split} MT) exceeds available lot balance ({self.current_quantity_mt} MT)")
children = []
for idx, q_mt in enumerate(split_quantities_mt):
child_num = f"{self.lot_number}-SPLIT-{idx + 1}"
child = InventoryLot(
tenant_id=self.tenant_id,
lot_number=child_num,
grn_id=self.grn_id,
commodity_id=self.commodity_id,
variety=self.variety,
godown_stack_id=self.godown_stack_id,
initial_quantity_mt=q_mt,
grade=self.grade,
parent_lot_id=self.id
)
# Inherit parent's approved QC status
child.qc_status = self.qc_status
children.append(child)
self.current_quantity_mt = (self.current_quantity_mt - total_split).quantize(Decimal("0.001"))
return children
def to_dict(self) -> Dict[str, Any]:
return {
"id": self.id,
"tenant_id": self.tenant_id,
"lot_number": self.lot_number,
"grn_id": self.grn_id,
"commodity_id": self.commodity_id,
"variety": self.variety,
"grade": self.grade,
"godown_stack_id": self.godown_stack_id,
"initial_quantity_mt": float(self.initial_quantity_mt),
"current_quantity_mt": float(self.current_quantity_mt),
"qc_status": self.qc_status,
"parent_lot_id": self.parent_lot_id,
"created_at": self.created_at.isoformat() if self.created_at else None
}
class QualityInspection(Base):
__tablename__ = "quality_inspections"
__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)
lot_id = Column(String(36), nullable=False, index=True)
sample_code = Column(String(32), nullable=False)
inspection_timestamp = Column(DateTime, default=lambda: datetime.now(timezone.utc))
inspector_email = Column(String(255), nullable=False)
moisture_pct = Column(Numeric(5, 2), nullable=False)
foreign_matter_pct = Column(Numeric(5, 2), nullable=False)
damaged_grain_pct = Column(Numeric(5, 2), default=0.0)
oil_content_pct = Column(Numeric(5, 2), default=0.0)
moisture_weight_deduction_mt = Column(Numeric(12, 3), default=0.0)
net_billable_weight_mt = Column(Numeric(12, 3), nullable=False)
rate_deduction_per_qtl = Column(Numeric(10, 2), default=0.0)
total_rebate_amount = Column(Numeric(12, 2), default=0.0)
decision = Column(String(32), nullable=False)
rejection_reason = Column(String(255), nullable=True)
remarks = Column(String(255), nullable=True)
def __init__(
self,
tenant_id: str,
lot_id: str,
sample_code: str,
inspector_email: str,
lot_quantity_mt: Decimal,
trade_rate_per_qtl: Decimal,
moisture_pct: Decimal,
foreign_matter_pct: Decimal,
decision: str,
damaged_grain_pct: Decimal = Decimal("0.0"),
oil_content_pct: Decimal = Decimal("0.0"),
rejection_reason: Optional[str] = None,
remarks: Optional[str] = None,
standard_moisture_max: Decimal = Decimal("10.0"),
standard_foreign_max: Decimal = Decimal("1.5"),
inspection_id: Optional[str] = None
):
if decision not in {"RELEASED", "CONDITIONAL_RELEASE", "REJECTED"}:
raise ValueError(f"Invalid inspection decision '{decision}'")
if decision == "REJECTED" and not rejection_reason:
raise ValueError("Rejection reason is mandatory when decision is REJECTED")
calc = calculate_quality_rebates(
lot_quantity_mt=lot_quantity_mt,
trade_rate_per_qtl=trade_rate_per_qtl,
moisture_pct=moisture_pct,
foreign_matter_pct=foreign_matter_pct,
standard_moisture_max=standard_moisture_max,
standard_foreign_max=standard_foreign_max
)
self.id = inspection_id or str(uuid.uuid4())
self.tenant_id = tenant_id
self.lot_id = lot_id
self.sample_code = sample_code
self.inspection_timestamp = datetime.now(timezone.utc)
self.inspector_email = inspector_email
self.moisture_pct = moisture_pct
self.foreign_matter_pct = foreign_matter_pct
self.damaged_grain_pct = damaged_grain_pct
self.oil_content_pct = oil_content_pct
self.moisture_weight_deduction_mt = calc["weight_deduction_mt"]
self.net_billable_weight_mt = calc["net_billable_weight_mt"]
self.rate_deduction_per_qtl = calc["rate_deduction_per_qtl"]
self.total_rebate_amount = calc["total_rebate_amount"]
self.decision = decision
self.rejection_reason = rejection_reason
self.remarks = remarks
def to_dict(self) -> Dict[str, Any]:
return {
"id": self.id,
"tenant_id": self.tenant_id,
"lot_id": self.lot_id,
"sample_code": self.sample_code,
"inspection_timestamp": self.inspection_timestamp.isoformat() if self.inspection_timestamp else None,
"inspector_email": self.inspector_email,
"moisture_pct": float(self.moisture_pct),
"foreign_matter_pct": float(self.foreign_matter_pct),
"damaged_grain_pct": float(self.damaged_grain_pct),
"oil_content_pct": float(self.oil_content_pct),
"moisture_weight_deduction_mt": float(self.moisture_weight_deduction_mt),
"net_billable_weight_mt": float(self.net_billable_weight_mt),
"rate_deduction_per_qtl": float(self.rate_deduction_per_qtl),
"total_rebate_amount": float(self.total_rebate_amount),
"decision": self.decision,
"rejection_reason": self.rejection_reason,
"remarks": self.remarks
}