"""Bardana (Packaging Bags) Inventory Ledger & Commercial Terms Models. Fulfills Phase 2 requirements BRD-FR-053, BRD-FR-054, and BRD-FR-055 (UC-027). 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 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 BARDANA_TYPES = { "NEW_JUTE_50KG", "OLD_JUTE_50KG", "NEW_JUTE_100KG", "HDPE_50KG", "PP_25KG", } BARDANA_TRANSACTION_TYPES = { "PURCHASE_RECEIPT", "FARMER_DECANTED", "DISPATCH_PACKED", "BURST_WRITEOFF", "INTER_GODOWN_TRANSFER", } COMMERCIAL_PACKAGING_TERMS = { "BARDANA_SAHIT", # Bags Included in commodity rate "BARDANA_ALAG", # Bags Billed Extra as line-item "BARDANA_WAPSI", # Farmer/Buyer Bags Returned or Decanted } def calculate_packaging_commercials( packaging_term: str, bag_count: int, bag_type: str, bag_unit_rate: Optional[Decimal] = None, filling_rate_per_bag: Decimal = Decimal("2.50"), stitching_rate_per_bag: Decimal = Decimal("1.50"), marking_rate_per_bag: Decimal = Decimal("0.50"), ) -> Dict[str, Any]: """Calculates packaging line-item charges and labor apportioning.""" if packaging_term not in COMMERCIAL_PACKAGING_TERMS: raise ValueError( f"Invalid packaging term '{packaging_term}'. Allowed: {sorted(COMMERCIAL_PACKAGING_TERMS)}" ) if bag_type not in BARDANA_TYPES: raise ValueError(f"Invalid bag type '{bag_type}'. Allowed: {sorted(BARDANA_TYPES)}") if bag_count <= 0: raise ValueError("Bag count must be > 0") # Commercial bag billing amount bag_billing_amount = Decimal("0.00") if packaging_term == "BARDANA_ALAG": if bag_unit_rate is None or bag_unit_rate <= Decimal("0.00"): raise ValueError("Bag unit rate must be > 0.00 when BARDANA_ALAG is selected") bag_billing_amount = (Decimal(bag_count) * bag_unit_rate).quantize( Decimal("0.01"), rounding=ROUND_HALF_UP ) # Labor apportioning total_labor_rate = filling_rate_per_bag + stitching_rate_per_bag + marking_rate_per_bag packaging_labor_amount = (Decimal(bag_count) * total_labor_rate).quantize( Decimal("0.01"), rounding=ROUND_HALF_UP ) return { "packaging_term": packaging_term, "bag_type": bag_type, "bag_count": bag_count, "bag_unit_rate": bag_unit_rate or Decimal("0.00"), "bag_billing_amount": bag_billing_amount, "packaging_labor_amount": packaging_labor_amount, "total_packaging_cost": bag_billing_amount + packaging_labor_amount, } class BardanaStockEntry(Base): """Immutable double-entry stock ledger for physical packaging bags.""" __tablename__ = "bardana_stock_entries" __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) godown_id = Column(String(36), nullable=False, index=True) bag_type = Column(String(32), nullable=False, index=True) transaction_type = Column(String(32), nullable=False, index=True) reference_id = Column(String(64), nullable=False, index=True) opening_count = Column(Integer, nullable=False) inward_count = Column(Integer, default=0) outward_count = Column(Integer, default=0) damaged_count = Column(Integer, default=0) closing_count = Column(Integer, nullable=False) created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc)) def __init__( self, tenant_id: str, godown_id: str, bag_type: str, transaction_type: str, reference_id: str, opening_count: int, inward_count: int = 0, outward_count: int = 0, damaged_count: int = 0, entry_id: Optional[str] = None, ): if bag_type not in BARDANA_TYPES: raise ValueError(f"Invalid bag type '{bag_type}'. Allowed: {sorted(BARDANA_TYPES)}") if transaction_type not in BARDANA_TRANSACTION_TYPES: raise ValueError( f"Invalid transaction type '{transaction_type}'. Allowed: {sorted(BARDANA_TRANSACTION_TYPES)}" ) closing = opening_count + inward_count - outward_count - damaged_count if closing < 0: raise ValueError( f"Non-negative bag stock invariant violated: resulting closing count {closing} cannot be negative" ) self.id = entry_id or str(uuid.uuid4()) self.tenant_id = tenant_id self.godown_id = godown_id self.bag_type = bag_type self.transaction_type = transaction_type self.reference_id = reference_id self.opening_count = opening_count self.inward_count = inward_count self.outward_count = outward_count self.damaged_count = damaged_count self.closing_count = closing self.created_at = datetime.now(timezone.utc) def to_dict(self) -> Dict[str, Any]: return { "id": self.id, "tenant_id": self.tenant_id, "godown_id": self.godown_id, "bag_type": self.bag_type, "transaction_type": self.transaction_type, "reference_id": self.reference_id, "opening_count": self.opening_count, "inward_count": self.inward_count, "outward_count": self.outward_count, "damaged_count": self.damaged_count, "closing_count": self.closing_count, "created_at": self.created_at.isoformat() if self.created_at else None, }