288 lines
12 KiB
Python
288 lines
12 KiB
Python
"""Inward Yard Gate Entry, Weighbridge and GRN Models.
|
|
|
|
Fulfills FR-INWARDRECEIVING-001..005 (UC-005).
|
|
Adheres to LLD-003 and UP-AI v1.5 standards.
|
|
"""
|
|
from datetime import datetime, timezone
|
|
from decimal import Decimal, ROUND_HALF_UP
|
|
import re
|
|
from typing import Optional, Dict, Any
|
|
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
|
|
|
|
GATE_ENTRY_STATUSES = {
|
|
"GATE_IN", "WEIGHED_GROSS", "UNLOADED", "WEIGHED_TARE", "GRN_ISSUED", "GATE_OUT"
|
|
}
|
|
|
|
EWAY_BILL_REGEX = re.compile(r"^\d{12}$")
|
|
VEHICLE_NUM_REGEX = re.compile(r"^[A-Z]{2}[0-9]{2}[A-Z]{1,3}[0-9]{4}$")
|
|
|
|
|
|
def validate_gate_entry(vehicle_number: str, eway_bill_number: str, driver_mobile: str) -> None:
|
|
"""Validates yard ingress vehicle and regulatory constraints."""
|
|
clean_veh = vehicle_number.replace("-", "").replace(" ", "").upper()
|
|
if not VEHICLE_NUM_REGEX.match(clean_veh):
|
|
raise ValueError(f"Invalid Indian vehicle registration format: '{vehicle_number}'")
|
|
|
|
if not EWAY_BILL_REGEX.match(eway_bill_number):
|
|
raise ValueError(f"Invalid e-Way bill number: '{eway_bill_number}'. Must be exactly 12 numeric digits.")
|
|
|
|
if not (len(driver_mobile) == 10 and driver_mobile.isdigit() and driver_mobile[0] in "6789"):
|
|
raise ValueError(f"Invalid driver mobile number: '{driver_mobile}'. Must be a valid 10-digit Indian phone.")
|
|
|
|
|
|
class InwardGateEntry(Base):
|
|
__tablename__ = "inward_gate_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)
|
|
gate_pass_number = Column(String(32), nullable=False, unique=True, index=True)
|
|
gate_in_timestamp = Column(DateTime, default=lambda: datetime.now(timezone.utc))
|
|
vehicle_number = Column(String(16), nullable=False, index=True)
|
|
eway_bill_number = Column(String(12), nullable=False)
|
|
driver_name = Column(String(100), nullable=False)
|
|
driver_mobile = Column(String(10), nullable=False)
|
|
sauda_id = Column(String(36), nullable=False, index=True)
|
|
supplier_invoice_no = Column(String(64), nullable=False)
|
|
supplier_dispatch_weight_mt = Column(Numeric(12, 3), nullable=False)
|
|
supplier_dispatch_bags = Column(Integer, nullable=False)
|
|
is_seal_intact = Column(Boolean, default=True)
|
|
status = Column(String(32), default="GATE_IN", index=True)
|
|
|
|
def __init__(
|
|
self,
|
|
tenant_id: str,
|
|
gate_pass_number: str,
|
|
vehicle_number: str,
|
|
eway_bill_number: str,
|
|
driver_name: str,
|
|
driver_mobile: str,
|
|
sauda_id: str,
|
|
supplier_invoice_no: str,
|
|
supplier_dispatch_weight_mt: Decimal,
|
|
supplier_dispatch_bags: int,
|
|
is_seal_intact: bool = True,
|
|
entry_id: Optional[str] = None
|
|
):
|
|
validate_gate_entry(vehicle_number, eway_bill_number, driver_mobile)
|
|
if supplier_dispatch_weight_mt <= Decimal("0.000"):
|
|
raise ValueError("Supplier dispatch weight must be > 0.0 MT")
|
|
if supplier_dispatch_bags <= 0:
|
|
raise ValueError("Supplier dispatch bag count must be > 0")
|
|
|
|
self.id = entry_id or str(uuid.uuid4())
|
|
self.tenant_id = tenant_id
|
|
self.gate_pass_number = gate_pass_number
|
|
self.gate_in_timestamp = datetime.now(timezone.utc)
|
|
self.vehicle_number = vehicle_number.replace("-", "").replace(" ", "").upper()
|
|
self.eway_bill_number = eway_bill_number
|
|
self.driver_name = driver_name
|
|
self.driver_mobile = driver_mobile
|
|
self.sauda_id = sauda_id
|
|
self.supplier_invoice_no = supplier_invoice_no
|
|
self.supplier_dispatch_weight_mt = supplier_dispatch_weight_mt
|
|
self.supplier_dispatch_bags = supplier_dispatch_bags
|
|
self.is_seal_intact = is_seal_intact
|
|
self.status = "GATE_IN"
|
|
|
|
def transition_status(self, next_status: str) -> None:
|
|
if next_status not in GATE_ENTRY_STATUSES:
|
|
raise ValueError(f"Invalid gate entry status '{next_status}'")
|
|
self.status = next_status
|
|
|
|
def to_dict(self) -> Dict[str, Any]:
|
|
return {
|
|
"id": self.id,
|
|
"tenant_id": self.tenant_id,
|
|
"gate_pass_number": self.gate_pass_number,
|
|
"gate_in_timestamp": self.gate_in_timestamp.isoformat() if self.gate_in_timestamp else None,
|
|
"vehicle_number": self.vehicle_number,
|
|
"eway_bill_number": self.eway_bill_number,
|
|
"driver_name": self.driver_name,
|
|
"driver_mobile": self.driver_mobile,
|
|
"sauda_id": self.sauda_id,
|
|
"supplier_invoice_no": self.supplier_invoice_no,
|
|
"supplier_dispatch_weight_mt": float(self.supplier_dispatch_weight_mt),
|
|
"supplier_dispatch_bags": self.supplier_dispatch_bags,
|
|
"is_seal_intact": self.is_seal_intact,
|
|
"status": self.status
|
|
}
|
|
|
|
|
|
class WeighbridgeSlip(Base):
|
|
__tablename__ = "weighbridge_slips"
|
|
__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)
|
|
slip_number = Column(String(32), nullable=False, unique=True, index=True)
|
|
gate_pass_id = Column(String(36), nullable=False, index=True)
|
|
gross_weight_mt = Column(Numeric(12, 3), nullable=False)
|
|
gross_timestamp = Column(DateTime, default=lambda: datetime.now(timezone.utc))
|
|
tare_weight_mt = Column(Numeric(12, 3), nullable=True)
|
|
tare_timestamp = Column(DateTime, nullable=True)
|
|
unloaded_weight_mt = Column(Numeric(12, 3), nullable=True)
|
|
bag_packaging_type = Column(String(32), nullable=True)
|
|
bag_tare_rate_kg = Column(Numeric(6, 3), nullable=True)
|
|
actual_bag_count = Column(Integer, default=0)
|
|
bag_tare_deduction_mt = Column(Numeric(12, 3), default=0.0)
|
|
final_net_weight_mt = Column(Numeric(12, 3), nullable=True)
|
|
shortage_weight_mt = Column(Numeric(12, 3), nullable=True)
|
|
shortage_pct = Column(Numeric(5, 2), nullable=True)
|
|
is_shortage_exceeded = Column(Boolean, default=False)
|
|
|
|
def __init__(
|
|
self,
|
|
tenant_id: str,
|
|
slip_number: str,
|
|
gate_pass_id: str,
|
|
gross_weight_mt: Decimal,
|
|
slip_id: Optional[str] = None
|
|
):
|
|
if gross_weight_mt <= Decimal("0.000"):
|
|
raise ValueError("Gross weight must be > 0.0 MT")
|
|
|
|
self.id = slip_id or str(uuid.uuid4())
|
|
self.tenant_id = tenant_id
|
|
self.slip_number = slip_number
|
|
self.gate_pass_id = gate_pass_id
|
|
self.gross_weight_mt = gross_weight_mt
|
|
self.gross_timestamp = datetime.now(timezone.utc)
|
|
self.tare_weight_mt = None
|
|
self.tare_timestamp = None
|
|
self.unloaded_weight_mt = None
|
|
self.bag_packaging_type = None
|
|
self.bag_tare_rate_kg = None
|
|
self.actual_bag_count = 0
|
|
self.bag_tare_deduction_mt = Decimal("0.000")
|
|
self.final_net_weight_mt = None
|
|
self.shortage_weight_mt = None
|
|
self.shortage_pct = None
|
|
self.is_shortage_exceeded = False
|
|
|
|
def record_tare(
|
|
self,
|
|
tare_weight_mt: Decimal,
|
|
bag_packaging_type: str,
|
|
actual_bag_count: int,
|
|
billed_weight_mt: Decimal,
|
|
bag_tare_rate_kg: Optional[Decimal] = None,
|
|
tolerance_pct: Decimal = Decimal("0.50")
|
|
) -> None:
|
|
"""Records tare weighment and computes bag deductions and shortage."""
|
|
if tare_weight_mt >= self.gross_weight_mt:
|
|
raise ValueError("Tare weight must be strictly less than Gross weight")
|
|
|
|
from sandbox.weighbridge_mock import WeighbridgeMock
|
|
calc = WeighbridgeMock.process_weighment(
|
|
gross_weight_mt=self.gross_weight_mt,
|
|
tare_weight_mt=tare_weight_mt,
|
|
packaging_type=bag_packaging_type,
|
|
bag_count=actual_bag_count,
|
|
billed_weight_mt=billed_weight_mt,
|
|
tolerance_pct=tolerance_pct
|
|
)
|
|
|
|
self.tare_weight_mt = Decimal(str(calc["tare_weight_mt"]))
|
|
self.tare_timestamp = datetime.now(timezone.utc)
|
|
self.unloaded_weight_mt = Decimal(str(calc["unloaded_weight_mt"]))
|
|
self.bag_packaging_type = bag_packaging_type
|
|
self.bag_tare_rate_kg = bag_tare_rate_kg or (
|
|
Decimal(str(calc["bag_tare_deduction_mt"])) * Decimal("1000.0") / Decimal(str(actual_bag_count))
|
|
if actual_bag_count > 0 else Decimal("0.000")
|
|
)
|
|
self.actual_bag_count = actual_bag_count
|
|
self.bag_tare_deduction_mt = Decimal(str(calc["bag_tare_deduction_mt"]))
|
|
self.final_net_weight_mt = Decimal(str(calc["final_net_weight_mt"]))
|
|
self.shortage_weight_mt = Decimal(str(calc["shortage_weight_mt"]))
|
|
self.shortage_pct = Decimal(str(calc["shortage_pct"]))
|
|
self.is_shortage_exceeded = calc["is_shortage_exceeded"]
|
|
|
|
def to_dict(self) -> Dict[str, Any]:
|
|
return {
|
|
"id": self.id,
|
|
"tenant_id": self.tenant_id,
|
|
"slip_number": self.slip_number,
|
|
"gate_pass_id": self.gate_pass_id,
|
|
"gross_weight_mt": float(self.gross_weight_mt),
|
|
"gross_timestamp": self.gross_timestamp.isoformat() if self.gross_timestamp else None,
|
|
"tare_weight_mt": float(self.tare_weight_mt) if self.tare_weight_mt is not None else None,
|
|
"tare_timestamp": self.tare_timestamp.isoformat() if self.tare_timestamp else None,
|
|
"unloaded_weight_mt": float(self.unloaded_weight_mt) if self.unloaded_weight_mt is not None else None,
|
|
"bag_packaging_type": self.bag_packaging_type,
|
|
"actual_bag_count": self.actual_bag_count,
|
|
"bag_tare_deduction_mt": float(self.bag_tare_deduction_mt),
|
|
"final_net_weight_mt": float(self.final_net_weight_mt) if self.final_net_weight_mt is not None else None,
|
|
"shortage_weight_mt": float(self.shortage_weight_mt) if self.shortage_weight_mt is not None else None,
|
|
"shortage_pct": float(self.shortage_pct) if self.shortage_pct is not None else None,
|
|
"is_shortage_exceeded": self.is_shortage_exceeded
|
|
}
|
|
|
|
|
|
class GoodsReceiptNote(Base):
|
|
__tablename__ = "goods_receipt_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)
|
|
grn_number = Column(String(32), nullable=False, unique=True, index=True)
|
|
grn_date = Column(DateTime, default=lambda: datetime.now(timezone.utc))
|
|
weighment_slip_id = Column(String(36), nullable=False, index=True)
|
|
sauda_id = Column(String(36), nullable=False, index=True)
|
|
godown_id = Column(String(36), nullable=False)
|
|
godown_stack_id = Column(String(36), nullable=False)
|
|
accepted_quantity_mt = Column(Numeric(12, 3), nullable=False)
|
|
accepted_bags = Column(Integer, nullable=False)
|
|
status = Column(String(32), default="POSTED")
|
|
|
|
def __init__(
|
|
self,
|
|
tenant_id: str,
|
|
grn_number: str,
|
|
weighment_slip_id: str,
|
|
sauda_id: str,
|
|
godown_id: str,
|
|
godown_stack_id: str,
|
|
accepted_quantity_mt: Decimal,
|
|
accepted_bags: int,
|
|
grn_id: Optional[str] = None
|
|
):
|
|
if accepted_quantity_mt <= Decimal("0.000"):
|
|
raise ValueError("Accepted quantity MT must be > 0.0")
|
|
|
|
self.id = grn_id or str(uuid.uuid4())
|
|
self.tenant_id = tenant_id
|
|
self.grn_number = grn_number
|
|
self.grn_date = datetime.now(timezone.utc)
|
|
self.weighment_slip_id = weighment_slip_id
|
|
self.sauda_id = sauda_id
|
|
self.godown_id = godown_id
|
|
self.godown_stack_id = godown_stack_id
|
|
self.accepted_quantity_mt = accepted_quantity_mt
|
|
self.accepted_bags = accepted_bags
|
|
self.status = "POSTED"
|
|
|
|
def to_dict(self) -> Dict[str, Any]:
|
|
return {
|
|
"id": self.id,
|
|
"tenant_id": self.tenant_id,
|
|
"grn_number": self.grn_number,
|
|
"grn_date": self.grn_date.isoformat() if self.grn_date else None,
|
|
"weighment_slip_id": self.weighment_slip_id,
|
|
"sauda_id": self.sauda_id,
|
|
"godown_id": self.godown_id,
|
|
"godown_stack_id": self.godown_stack_id,
|
|
"accepted_quantity_mt": float(self.accepted_quantity_mt),
|
|
"accepted_bags": self.accepted_bags,
|
|
"status": self.status
|
|
}
|
|
|