"""Outbound Dispatch, Outward Weighbridge, Bilty, POD and Fleet Registry Models. Fulfills FR-DISPATCHDELIVERY-001, FR-DISPATCHDELIVERY-002, FR-DISPATCHDELIVERY-003 (UC-009) and FR-FLEETREGISTRY-001 (UC-010). Adheres to LLD-004, LLD-009, and UP-AI v1.5 standards. """ from datetime import datetime, date, 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 VEHICLE_STATUSES = {"Available", "On Route", "Maintenance"} OWNERSHIP_TYPES = {"Own", "Contract"} DISPATCH_STATUSES = {"SCHEDULED", "LOADING", "IN_TRANSIT", "DELIVERED", "CANCELLED"} class TransportVehicle(Base): """Transport Fleet Vehicle with payload capacity and maintenance gating.""" __tablename__ = "transport_fleet" __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) reg_no = Column(String(32), nullable=False, unique=True, index=True) make_model = Column(String(64), nullable=False) payload_capacity_mt = Column(Numeric(8, 3), nullable=False) ownership_type = Column(String(32), nullable=False) transporter_name = Column(String(128), nullable=False) status = Column(String(32), default="Available") fitness_expiry = Column(String(32), nullable=False) is_active = Column(Boolean, default=True) created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc)) def __init__( self, tenant_id: str, reg_no: str, make_model: str, payload_capacity_mt: Decimal, ownership_type: str, transporter_name: str, fitness_expiry: str, status: str = "Available", is_active: bool = True, vehicle_id: Optional[str] = None, ): clean_reg = reg_no.strip().upper() if not clean_reg: raise ValueError("Vehicle registration number cannot be empty") if payload_capacity_mt <= Decimal("0.000"): raise ValueError("Payload capacity MT must be positive") if ownership_type not in OWNERSHIP_TYPES: raise ValueError( f"Invalid ownership type '{ownership_type}'. Allowed: {sorted(OWNERSHIP_TYPES)}" ) if status not in VEHICLE_STATUSES: raise ValueError(f"Invalid status '{status}'. Allowed: {sorted(VEHICLE_STATUSES)}") self.id = vehicle_id or str(uuid.uuid4()) self.tenant_id = tenant_id self.reg_no = clean_reg self.make_model = make_model self.payload_capacity_mt = payload_capacity_mt self.ownership_type = ownership_type self.transporter_name = transporter_name self.status = status self.fitness_expiry = fitness_expiry self.is_active = is_active self.created_at = datetime.now(timezone.utc) def assert_can_assign(self, reference_date: Optional[date] = None) -> None: """Gating check before assigning vehicle to an outbound dispatch consignment.""" if not self.is_active: raise ValueError(f"Vehicle '{self.reg_no}' is marked inactive in fleet registry") if self.status == "Maintenance": raise ValueError(f"Vehicle '{self.reg_no}' is under Maintenance and cannot be dispatched") if self.status == "On Route": raise ValueError(f"Vehicle '{self.reg_no}' is currently On Route on another trip") today = reference_date or date.today() expiry_dt = datetime.strptime(self.fitness_expiry, "%Y-%m-%d").date() if expiry_dt < today: raise ValueError( f"Vehicle '{self.reg_no}' fitness certificate expired on {self.fitness_expiry}" ) def to_dict(self) -> Dict[str, Any]: return { "id": self.id, "tenant_id": self.tenant_id, "reg_no": self.reg_no, "make_model": self.make_model, "payload_capacity_mt": float(self.payload_capacity_mt), "ownership_type": self.ownership_type, "transporter_name": self.transporter_name, "status": self.status, "fitness_expiry": self.fitness_expiry, "is_active": self.is_active, "created_at": self.created_at.isoformat() if self.created_at else None, } class OutboundDispatch(Base): """Consignment dispatch schedule linking sales orders, allocations and vehicles.""" __tablename__ = "outbound_dispatches" __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) dispatch_number = Column(String(32), nullable=False, unique=True, index=True) sales_order_id = Column(String(36), nullable=False, index=True) allocation_id = Column(String(36), nullable=False, index=True) vehicle_id = Column(String(36), nullable=False, index=True) origin_warehouse_id = Column(String(36), nullable=False, index=True) destination_city = Column(String(64), nullable=False) scheduled_date = Column(DateTime, default=lambda: datetime.now(timezone.utc)) status = Column(String(32), default="SCHEDULED") created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc)) def __init__( self, tenant_id: str, dispatch_number: str, sales_order_id: str, allocation_id: str, vehicle_id: str, origin_warehouse_id: str, destination_city: str, dispatch_id: Optional[str] = None, ): if not all([sales_order_id, allocation_id, vehicle_id, origin_warehouse_id]): raise ValueError( "Dispatch requires sales_order_id, allocation_id, vehicle_id, and origin_warehouse_id" ) self.id = dispatch_id or str(uuid.uuid4()) self.tenant_id = tenant_id self.dispatch_number = dispatch_number self.sales_order_id = sales_order_id self.allocation_id = allocation_id self.vehicle_id = vehicle_id self.origin_warehouse_id = origin_warehouse_id self.destination_city = destination_city self.scheduled_date = datetime.now(timezone.utc) self.status = "SCHEDULED" self.created_at = datetime.now(timezone.utc) def transition_status(self, next_status: str) -> None: if next_status not in DISPATCH_STATUSES: raise ValueError(f"Invalid dispatch status '{next_status}'") self.status = next_status def to_dict(self) -> Dict[str, Any]: return { "id": self.id, "tenant_id": self.tenant_id, "dispatch_number": self.dispatch_number, "sales_order_id": self.sales_order_id, "allocation_id": self.allocation_id, "vehicle_id": self.vehicle_id, "origin_warehouse_id": self.origin_warehouse_id, "destination_city": self.destination_city, "scheduled_date": self.scheduled_date.isoformat() if self.scheduled_date else None, "status": self.status, "created_at": self.created_at.isoformat() if self.created_at else None, } class OutwardWeighment(Base): """Outward weighbridge reading with loading tolerance and bilty trigger.""" __tablename__ = "outward_weighments" __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) dispatch_id = Column(String(36), nullable=False, index=True) tare_weight_kg = Column(Numeric(10, 2), nullable=False) gross_weight_kg = Column(Numeric(10, 2), nullable=False) net_weight_mt = Column(Numeric(10, 3), nullable=False) allocated_mt = Column(Numeric(10, 3), nullable=False) weight_variance_pct = Column(Numeric(6, 2), nullable=False) loaded_bags = Column(Integer, nullable=False) transporter_bilty_no = Column(String(64), nullable=False) eway_bill_no = Column(String(64), nullable=False) weighed_at = Column(DateTime, default=lambda: datetime.now(timezone.utc)) def __init__( self, tenant_id: str, dispatch_id: str, tare_weight_kg: Decimal, gross_weight_kg: Decimal, allocated_mt: Decimal, loaded_bags: int, transporter_bilty_no: str, eway_bill_no: str, weighment_id: Optional[str] = None, ): if gross_weight_kg <= tare_weight_kg: raise ValueError( f"Gross weight ({gross_weight_kg} kg) must be greater than Tare weight ({tare_weight_kg} kg)" ) if loaded_bags <= 0: raise ValueError("Loaded bag count must be positive") if not transporter_bilty_no or not eway_bill_no: raise ValueError("Transporter Bilty No and e-Way Bill No are mandatory") net_weight_mt = ((gross_weight_kg - tare_weight_kg) / Decimal("1000.0")).quantize( Decimal("0.001"), rounding=ROUND_HALF_UP ) variance_mt = abs(net_weight_mt - allocated_mt) variance_pct = ((variance_mt / allocated_mt) * Decimal("100.0")).quantize( Decimal("0.01"), rounding=ROUND_HALF_UP ) # Loading tolerance check: +/- 1.0% if variance_pct > Decimal("1.00"): raise ValueError( f"Net loaded weight {net_weight_mt} MT deviates from allocated {allocated_mt} MT " f"by {variance_pct}% (exceeds +/-1.0% loading tolerance)" ) self.id = weighment_id or str(uuid.uuid4()) self.tenant_id = tenant_id self.dispatch_id = dispatch_id self.tare_weight_kg = tare_weight_kg self.gross_weight_kg = gross_weight_kg self.net_weight_mt = net_weight_mt self.allocated_mt = allocated_mt self.weight_variance_pct = variance_pct self.loaded_bags = loaded_bags self.transporter_bilty_no = transporter_bilty_no self.eway_bill_no = eway_bill_no self.weighed_at = datetime.now(timezone.utc) def to_dict(self) -> Dict[str, Any]: return { "id": self.id, "tenant_id": self.tenant_id, "dispatch_id": self.dispatch_id, "tare_weight_kg": float(self.tare_weight_kg), "gross_weight_kg": float(self.gross_weight_kg), "net_weight_mt": float(self.net_weight_mt), "allocated_mt": float(self.allocated_mt), "weight_variance_pct": float(self.weight_variance_pct), "loaded_bags": self.loaded_bags, "transporter_bilty_no": self.transporter_bilty_no, "eway_bill_no": self.eway_bill_no, "weighed_at": self.weighed_at.isoformat() if self.weighed_at else None, } class DispatchBilty(Base): """Immutable transport consignment note (Bilty) and manifest record.""" __tablename__ = "dispatch_bilties" __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) dispatch_id = Column(String(36), nullable=False, index=True) bilty_number = Column(String(32), nullable=False, unique=True, index=True) consignor_name = Column(String(128), nullable=False) consignee_name = Column(String(128), nullable=False) vehicle_reg_no = Column(String(32), nullable=False) net_weight_mt = Column(Numeric(10, 3), nullable=False) bags = Column(Integer, nullable=False) eway_bill_no = Column(String(64), nullable=False) issued_at = Column(DateTime, default=lambda: datetime.now(timezone.utc)) is_immutable = Column(Boolean, default=True) def __init__( self, tenant_id: str, dispatch_id: str, bilty_number: str, consignor_name: str, consignee_name: str, vehicle_reg_no: str, net_weight_mt: Decimal, bags: int, eway_bill_no: str, bilty_id: Optional[str] = None, ): self.id = bilty_id or str(uuid.uuid4()) self.tenant_id = tenant_id self.dispatch_id = dispatch_id self.bilty_number = bilty_number self.consignor_name = consignor_name self.consignee_name = consignee_name self.vehicle_reg_no = vehicle_reg_no self.net_weight_mt = net_weight_mt self.bags = bags self.eway_bill_no = eway_bill_no self.issued_at = datetime.now(timezone.utc) self.is_immutable = True def to_dict(self) -> Dict[str, Any]: return { "id": self.id, "tenant_id": self.tenant_id, "dispatch_id": self.dispatch_id, "bilty_number": self.bilty_number, "consignor_name": self.consignor_name, "consignee_name": self.consignee_name, "vehicle_reg_no": self.vehicle_reg_no, "net_weight_mt": float(self.net_weight_mt), "bags": self.bags, "eway_bill_no": self.eway_bill_no, "issued_at": self.issued_at.isoformat() if self.issued_at else None, "is_immutable": self.is_immutable, } class ProofOfDelivery(Base): """Consignee destination receipt, in-transit shortage, and automated invoice trigger.""" __tablename__ = "proof_of_deliveries" __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) dispatch_id = Column(String(36), nullable=False, index=True) delivery_date = Column(DateTime, default=lambda: datetime.now(timezone.utc)) dispatched_net_mt = Column(Numeric(10, 3), nullable=False) dest_weighbridge_net_mt = Column(Numeric(10, 3), nullable=False) transit_loss_mt = Column(Numeric(10, 3), nullable=False) shortage_pct = Column(Numeric(6, 2), nullable=False) consignee_ack_note = Column(String(255), nullable=False) pod_ref = Column(String(64), nullable=False) sales_invoice_number = Column(String(32), nullable=False) credit_note_required = Column(Boolean, default=False) created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc)) def __init__( self, tenant_id: str, dispatch_id: str, dispatched_net_mt: Decimal, dest_weighbridge_net_mt: Decimal, consignee_ack_note: str, pod_ref: str, sales_invoice_number: str, pod_id: Optional[str] = None, ): if dest_weighbridge_net_mt <= Decimal("0.000"): raise ValueError("Destination weighbridge net MT must be positive") transit_loss = max(Decimal("0.000"), dispatched_net_mt - dest_weighbridge_net_mt).quantize( Decimal("0.001"), rounding=ROUND_HALF_UP ) shortage_pct = ((transit_loss / dispatched_net_mt) * Decimal("100.0")).quantize( Decimal("0.01"), rounding=ROUND_HALF_UP ) credit_note_required = transit_loss > Decimal("0.000") self.id = pod_id or str(uuid.uuid4()) self.tenant_id = tenant_id self.dispatch_id = dispatch_id self.delivery_date = datetime.now(timezone.utc) self.dispatched_net_mt = dispatched_net_mt self.dest_weighbridge_net_mt = dest_weighbridge_net_mt self.transit_loss_mt = transit_loss self.shortage_pct = shortage_pct self.consignee_ack_note = consignee_ack_note self.pod_ref = pod_ref self.sales_invoice_number = sales_invoice_number self.credit_note_required = credit_note_required self.created_at = datetime.now(timezone.utc) def to_dict(self) -> Dict[str, Any]: return { "id": self.id, "tenant_id": self.tenant_id, "dispatch_id": self.dispatch_id, "delivery_date": self.delivery_date.isoformat() if self.delivery_date else None, "dispatched_net_mt": float(self.dispatched_net_mt), "dest_weighbridge_net_mt": float(self.dest_weighbridge_net_mt), "transit_loss_mt": float(self.transit_loss_mt), "shortage_pct": float(self.shortage_pct), "consignee_ack_note": self.consignee_ack_note, "pod_ref": self.pod_ref, "sales_invoice_number": self.sales_invoice_number, "credit_note_required": self.credit_note_required, "created_at": self.created_at.isoformat() if self.created_at else None, } class SalesCreditNote(Base): """Compensating credit note for transit shortage without modifying immutable Bilty.""" __tablename__ = "sales_credit_notes" __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) credit_note_number = Column(String(32), nullable=False, unique=True, index=True) sales_order_id = Column(String(36), nullable=False, index=True) dispatch_id = Column(String(36), nullable=False, index=True) customer_id = Column(String(36), nullable=False, index=True) shortage_mt = Column(Numeric(10, 3), nullable=False) shortage_pct = Column(Numeric(6, 2), nullable=False) rate_per_qtl = Column(Numeric(10, 2), nullable=False) credit_amount_inr = Column(Numeric(12, 2), nullable=False) manager_approval_required = Column(Boolean, default=False) manager_approved = Column(Boolean, default=False) approved_by = Column(String(64), nullable=True) created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc)) def __init__( self, tenant_id: str, credit_note_number: str, sales_order_id: str, dispatch_id: str, customer_id: str, shortage_mt: Decimal, shortage_pct: Decimal, rate_per_qtl: Decimal, credit_note_id: Optional[str] = None, ): if shortage_mt <= Decimal("0.000"): raise ValueError("Shortage MT must be positive to issue a credit note") if rate_per_qtl <= Decimal("0.00"): raise ValueError("Rate per quintal must be positive") credit_amount = (shortage_mt * Decimal("10.0") * rate_per_qtl).quantize( Decimal("0.01"), rounding=ROUND_HALF_UP ) manager_approval_required = shortage_pct > Decimal("2.00") self.id = credit_note_id or str(uuid.uuid4()) self.tenant_id = tenant_id self.credit_note_number = credit_note_number self.sales_order_id = sales_order_id self.dispatch_id = dispatch_id self.customer_id = customer_id self.shortage_mt = shortage_mt self.shortage_pct = shortage_pct self.rate_per_qtl = rate_per_qtl self.credit_amount_inr = credit_amount self.manager_approval_required = manager_approval_required self.manager_approved = not manager_approval_required self.approved_by = None self.created_at = datetime.now(timezone.utc) def approve_credit_note(self, sales_manager_id: str) -> None: """Applies Sales Manager electronic sign-off for shortage > 2.0%.""" if not sales_manager_id: raise ValueError("Sales Manager ID required for credit note sign-off") self.manager_approved = True self.approved_by = sales_manager_id def to_dict(self) -> Dict[str, Any]: return { "id": self.id, "tenant_id": self.tenant_id, "credit_note_number": self.credit_note_number, "sales_order_id": self.sales_order_id, "dispatch_id": self.dispatch_id, "customer_id": self.customer_id, "shortage_mt": float(self.shortage_mt), "shortage_pct": float(self.shortage_pct), "rate_per_qtl": float(self.rate_per_qtl), "credit_amount_inr": float(self.credit_amount_inr), "manager_approval_required": self.manager_approval_required, "manager_approved": self.manager_approved, "approved_by": self.approved_by, "created_at": self.created_at.isoformat() if self.created_at else None, }