c_agri_trade/project_code/backend/app/models/processing.py

124 lines
5.4 KiB
Python

"""Godown Processing, Conditioning (Sukhai) & Grading (Chhanai) Models.
Fulfills Phase 2 requirements BRD-FR-065, BRD-FR-066, and BRD-FR-067 (UC-031).
Adheres to 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
PROCESSING_TYPES = {"SUN_DRYING", "MECHANICAL_CLEANING", "GRADING", "BLENDING"}
ORDER_STATUSES = {"DRAFT", "IN_PROGRESS", "COMPLETED", "CANCELLED"}
class GodownProcessingOrder(Base):
"""Post-harvest godown processing work order with mass-conservation validation."""
__tablename__ = "godown_processing_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)
order_number = Column(String(32), nullable=False, unique=True, index=True)
godown_id = Column(String(36), nullable=False, index=True)
process_type = Column(String(32), nullable=False)
input_lot_id = Column(String(36), nullable=False, index=True)
input_weight_mt = Column(Numeric(12, 3), nullable=False)
output_primary_lot_id = Column(String(36), nullable=False)
output_primary_mt = Column(Numeric(12, 3), nullable=False)
output_primary_grade = Column(String(32), default="FAQ")
output_byproduct_lot_id = Column(String(36), nullable=True)
output_byproduct_mt = Column(Numeric(12, 3), default=0.0)
waste_weight_mt = Column(Numeric(12, 3), default=0.0)
shrinkage_loss_mt = Column(Numeric(12, 3), default=0.0)
loss_pct = Column(Numeric(5, 2), default=0.0)
status = Column(String(32), default="COMPLETED")
created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
def __init__(
self,
tenant_id: str,
order_number: str,
godown_id: str,
process_type: str,
input_lot_id: str,
input_weight_mt: Decimal,
output_primary_lot_id: str,
output_primary_mt: Decimal,
output_primary_grade: str = "FAQ",
output_byproduct_lot_id: Optional[str] = None,
output_byproduct_mt: Decimal = Decimal("0.000"),
waste_weight_mt: Decimal = Decimal("0.000"),
shrinkage_loss_mt: Decimal = Decimal("0.000"),
status: str = "COMPLETED",
order_id: Optional[str] = None,
):
if process_type not in PROCESSING_TYPES:
raise ValueError(f"Invalid process type '{process_type}'. Allowed: {sorted(PROCESSING_TYPES)}")
if input_weight_mt <= Decimal("0.000"):
raise ValueError("Input weight MT must be > 0.0")
if output_primary_mt <= Decimal("0.000"):
raise ValueError("Output primary weight MT must be > 0.0")
# Mass conservation: Input = Output Primary + Byproduct + Waste + Shrinkage
total_accounted = (output_primary_mt + output_byproduct_mt + waste_weight_mt + shrinkage_loss_mt).quantize(
Decimal("0.001"), rounding=ROUND_HALF_UP
)
if total_accounted != input_weight_mt.quantize(Decimal("0.001"), rounding=ROUND_HALF_UP):
raise ValueError(
f"Mass conservation violation: total accounted output ({total_accounted} MT) "
f"does not equal input weight ({input_weight_mt} MT)"
)
loss_pct = ((shrinkage_loss_mt / input_weight_mt) * Decimal("100.0")).quantize(
Decimal("0.01"), rounding=ROUND_HALF_UP
)
self.id = order_id or str(uuid.uuid4())
self.tenant_id = tenant_id
self.order_number = order_number
self.godown_id = godown_id
self.process_type = process_type
self.input_lot_id = input_lot_id
self.input_weight_mt = input_weight_mt
self.output_primary_lot_id = output_primary_lot_id
self.output_primary_mt = output_primary_mt
self.output_primary_grade = output_primary_grade
self.output_byproduct_lot_id = output_byproduct_lot_id
self.output_byproduct_mt = output_byproduct_mt
self.waste_weight_mt = waste_weight_mt
self.shrinkage_loss_mt = shrinkage_loss_mt
self.loss_pct = loss_pct
self.status = status
self.created_at = datetime.now(timezone.utc)
def to_dict(self) -> Dict[str, Any]:
return {
"id": self.id,
"tenant_id": self.tenant_id,
"order_number": self.order_number,
"godown_id": self.godown_id,
"process_type": self.process_type,
"input_lot_id": self.input_lot_id,
"input_weight_mt": float(self.input_weight_mt),
"output_primary_lot_id": self.output_primary_lot_id,
"output_primary_mt": float(self.output_primary_mt),
"output_primary_grade": self.output_primary_grade,
"output_byproduct_lot_id": self.output_byproduct_lot_id,
"output_byproduct_mt": float(self.output_byproduct_mt),
"waste_weight_mt": float(self.waste_weight_mt),
"shrinkage_loss_mt": float(self.shrinkage_loss_mt),
"loss_pct": float(self.loss_pct),
"status": self.status,
"created_at": self.created_at.isoformat() if self.created_at else None,
}