393 lines
16 KiB
Python
393 lines
16 KiB
Python
"""Multi-Godown Stock Ledger, Capacity Tracking and Inter-Godown Transfers Models.
|
|
|
|
Fulfills FR-WAREHOUSEINVENTORY-001, FR-WAREHOUSEINVENTORY-002, and FR-WAREHOUSEINVENTORY-003 (UC-007).
|
|
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, Integer, Boolean
|
|
from backend.app.models.user import Base
|
|
except ImportError:
|
|
class Base:
|
|
pass
|
|
Column = String = DateTime = Numeric = Integer = Boolean = lambda *args, **kwargs: None
|
|
|
|
TRANSACTION_TYPES = {
|
|
"INWARD",
|
|
"OUTWARD",
|
|
"TRANSFER_IN",
|
|
"TRANSFER_OUT",
|
|
"AUDIT_ADJUSTMENT",
|
|
}
|
|
|
|
VALID_ADJUSTMENT_REASONS = {
|
|
"Moisture Loss / Ghat",
|
|
"Handling Spillage",
|
|
"Bag Burst",
|
|
"Seasonal Humidity Gain",
|
|
}
|
|
|
|
TRANSFER_STATUSES = {"INITIATED", "IN_TRANSIT", "COMPLETED", "SHORTAGE_ALERT"}
|
|
|
|
|
|
class StockLedgerEntry(Base):
|
|
"""Immutable double-entry stock ledger transaction record."""
|
|
__tablename__ = "stock_ledger_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)
|
|
warehouse_id = Column(String(36), nullable=False, index=True)
|
|
commodity_id = Column(String(36), nullable=False, index=True)
|
|
variety = Column(String(64), nullable=False)
|
|
grade = Column(String(32), default="FAQ")
|
|
transaction_type = Column(String(32), nullable=False, index=True)
|
|
reference_id = Column(String(64), nullable=False, index=True)
|
|
opening_mt = Column(Numeric(12, 3), nullable=False)
|
|
opening_bags = Column(Integer, nullable=False)
|
|
quantity_mt = Column(Numeric(12, 3), nullable=False)
|
|
bags = Column(Integer, nullable=False)
|
|
closing_mt = Column(Numeric(12, 3), nullable=False)
|
|
closing_bags = Column(Integer, nullable=False)
|
|
created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
|
|
|
|
def __init__(
|
|
self,
|
|
tenant_id: str,
|
|
warehouse_id: str,
|
|
commodity_id: str,
|
|
variety: str,
|
|
transaction_type: str,
|
|
reference_id: str,
|
|
opening_mt: Decimal,
|
|
opening_bags: int,
|
|
quantity_mt: Decimal,
|
|
bags: int,
|
|
grade: str = "FAQ",
|
|
entry_id: Optional[str] = None,
|
|
):
|
|
if transaction_type not in TRANSACTION_TYPES:
|
|
raise ValueError(f"Invalid transaction type '{transaction_type}'")
|
|
|
|
if transaction_type in {"INWARD", "TRANSFER_IN"}:
|
|
closing_mt = opening_mt + quantity_mt
|
|
closing_bags = opening_bags + bags
|
|
elif transaction_type in {"OUTWARD", "TRANSFER_OUT"}:
|
|
closing_mt = opening_mt - quantity_mt
|
|
closing_bags = opening_bags - bags
|
|
elif transaction_type == "AUDIT_ADJUSTMENT":
|
|
# quantity_mt can be positive (gain) or negative (loss)
|
|
closing_mt = opening_mt + quantity_mt
|
|
closing_bags = opening_bags + bags
|
|
else:
|
|
closing_mt = opening_mt + quantity_mt
|
|
closing_bags = opening_bags + bags
|
|
|
|
if closing_mt < Decimal("0.000") or closing_bags < 0:
|
|
raise ValueError(
|
|
f"Non-negative stock invariant violated: resulting closing MT {closing_mt} "
|
|
f"or bags {closing_bags} cannot be negative"
|
|
)
|
|
|
|
self.id = entry_id or str(uuid.uuid4())
|
|
self.tenant_id = tenant_id
|
|
self.warehouse_id = warehouse_id
|
|
self.commodity_id = commodity_id
|
|
self.variety = variety
|
|
self.grade = grade
|
|
self.transaction_type = transaction_type
|
|
self.reference_id = reference_id
|
|
self.opening_mt = opening_mt
|
|
self.opening_bags = opening_bags
|
|
self.quantity_mt = quantity_mt
|
|
self.bags = bags
|
|
self.closing_mt = closing_mt
|
|
self.closing_bags = closing_bags
|
|
self.created_at = datetime.now(timezone.utc)
|
|
|
|
def to_dict(self) -> Dict[str, Any]:
|
|
return {
|
|
"id": self.id,
|
|
"tenant_id": self.tenant_id,
|
|
"warehouse_id": self.warehouse_id,
|
|
"commodity_id": self.commodity_id,
|
|
"variety": self.variety,
|
|
"grade": self.grade,
|
|
"transaction_type": self.transaction_type,
|
|
"reference_id": self.reference_id,
|
|
"opening_mt": float(self.opening_mt),
|
|
"opening_bags": self.opening_bags,
|
|
"quantity_mt": float(self.quantity_mt),
|
|
"bags": self.bags,
|
|
"closing_mt": float(self.closing_mt),
|
|
"closing_bags": self.closing_bags,
|
|
"created_at": self.created_at.isoformat() if self.created_at else None,
|
|
}
|
|
|
|
|
|
class StockAdjustment(Base):
|
|
"""Stock count variance adjustment voucher requiring Partner sign-off above +/-1.0%."""
|
|
__tablename__ = "stock_adjustments"
|
|
__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)
|
|
warehouse_id = Column(String(36), nullable=False, index=True)
|
|
commodity_id = Column(String(36), nullable=False, index=True)
|
|
variety = Column(String(64), nullable=False)
|
|
grade = Column(String(32), default="FAQ")
|
|
variance_mt = Column(Numeric(12, 3), nullable=False)
|
|
variance_bags = Column(Integer, nullable=False)
|
|
reason_code = Column(String(64), nullable=False)
|
|
balance_before_mt = Column(Numeric(12, 3), nullable=False)
|
|
balance_before_bags = Column(Integer, default=0)
|
|
variance_pct = Column(Numeric(6, 2), nullable=False)
|
|
partner_approval_required = Column(Boolean, default=False)
|
|
partner_approved_by = Column(String(64), nullable=True)
|
|
status = Column(String(32), default="PENDING_APPROVAL")
|
|
created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
|
|
|
|
def __init__(
|
|
self,
|
|
tenant_id: str,
|
|
warehouse_id: str,
|
|
commodity_id: str,
|
|
variety: str,
|
|
variance_mt: Decimal,
|
|
variance_bags: int,
|
|
reason_code: str,
|
|
balance_before_mt: Decimal,
|
|
balance_before_bags: int = 0,
|
|
grade: str = "FAQ",
|
|
adjustment_id: Optional[str] = None,
|
|
):
|
|
if reason_code not in VALID_ADJUSTMENT_REASONS:
|
|
raise ValueError(
|
|
f"Invalid reason code '{reason_code}'. Must be one of {sorted(VALID_ADJUSTMENT_REASONS)}"
|
|
)
|
|
|
|
if balance_before_mt <= Decimal("0.000"):
|
|
variance_pct = Decimal("100.00") if variance_mt != Decimal("0.000") else Decimal("0.00")
|
|
else:
|
|
variance_pct = ((abs(variance_mt) / balance_before_mt) * Decimal("100.0")).quantize(
|
|
Decimal("0.01"), rounding=ROUND_HALF_UP
|
|
)
|
|
|
|
partner_approval_required = abs(variance_pct) > Decimal("1.00")
|
|
|
|
self.id = adjustment_id or str(uuid.uuid4())
|
|
self.tenant_id = tenant_id
|
|
self.warehouse_id = warehouse_id
|
|
self.commodity_id = commodity_id
|
|
self.variety = variety
|
|
self.grade = grade
|
|
self.variance_mt = variance_mt
|
|
self.variance_bags = variance_bags
|
|
self.reason_code = reason_code
|
|
self.balance_before_mt = balance_before_mt
|
|
self.balance_before_bags = balance_before_bags
|
|
self.variance_pct = variance_pct
|
|
self.partner_approval_required = partner_approval_required
|
|
self.partner_approved_by = None
|
|
self.status = "PENDING_APPROVAL" if partner_approval_required else "COMMITTED"
|
|
self.created_at = datetime.now(timezone.utc)
|
|
|
|
def approve_and_commit(self, partner_id: str) -> None:
|
|
"""Applies Partner electronic signature and commits the adjustment."""
|
|
if not partner_id:
|
|
raise ValueError("Partner ID is required for adjustment sign-off")
|
|
self.partner_approved_by = partner_id
|
|
self.status = "COMMITTED"
|
|
|
|
def to_dict(self) -> Dict[str, Any]:
|
|
return {
|
|
"id": self.id,
|
|
"tenant_id": self.tenant_id,
|
|
"warehouse_id": self.warehouse_id,
|
|
"commodity_id": self.commodity_id,
|
|
"variety": self.variety,
|
|
"grade": self.grade,
|
|
"variance_mt": float(self.variance_mt),
|
|
"variance_bags": self.variance_bags,
|
|
"reason_code": self.reason_code,
|
|
"balance_before_mt": float(self.balance_before_mt),
|
|
"balance_before_bags": self.balance_before_bags,
|
|
"variance_pct": float(self.variance_pct),
|
|
"partner_approval_required": self.partner_approval_required,
|
|
"partner_approved_by": self.partner_approved_by,
|
|
"status": self.status,
|
|
"created_at": self.created_at.isoformat() if self.created_at else None,
|
|
}
|
|
|
|
|
|
class WarehouseCapacity(Base):
|
|
"""Warehouse storage capacity and utilization monitoring record."""
|
|
__tablename__ = "warehouse_capacities"
|
|
__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)
|
|
warehouse_id = Column(String(36), nullable=False, unique=True, index=True)
|
|
name = Column(String(128), nullable=False)
|
|
city = Column(String(64), nullable=False)
|
|
total_capacity_mt = Column(Numeric(12, 3), nullable=False)
|
|
current_closing_stock_mt = Column(Numeric(12, 3), default=Decimal("0.000"))
|
|
allocated_stock_mt = Column(Numeric(12, 3), default=Decimal("0.000"))
|
|
available_capacity_mt = Column(Numeric(12, 3), nullable=False)
|
|
utilization_pct = Column(Numeric(6, 2), nullable=False)
|
|
warning_flag = Column(Boolean, default=False)
|
|
|
|
def __init__(
|
|
self,
|
|
tenant_id: str,
|
|
warehouse_id: str,
|
|
name: str,
|
|
city: str,
|
|
total_capacity_mt: Decimal,
|
|
current_closing_stock_mt: Decimal = Decimal("0.000"),
|
|
allocated_stock_mt: Decimal = Decimal("0.000"),
|
|
capacity_id: Optional[str] = None,
|
|
):
|
|
if total_capacity_mt <= Decimal("0.000"):
|
|
raise ValueError("Total warehouse capacity MT must be > 0.0")
|
|
|
|
self.id = capacity_id or str(uuid.uuid4())
|
|
self.tenant_id = tenant_id
|
|
self.warehouse_id = warehouse_id
|
|
self.name = name
|
|
self.city = city
|
|
self.total_capacity_mt = total_capacity_mt
|
|
self.current_closing_stock_mt = current_closing_stock_mt
|
|
self.allocated_stock_mt = allocated_stock_mt
|
|
self.recompute_utilization()
|
|
|
|
def recompute_utilization(self) -> None:
|
|
self.available_capacity_mt = max(
|
|
Decimal("0.000"), self.total_capacity_mt - self.current_closing_stock_mt
|
|
)
|
|
self.utilization_pct = (
|
|
(self.current_closing_stock_mt / self.total_capacity_mt) * Decimal("100.0")
|
|
).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
|
|
self.warning_flag = self.utilization_pct > Decimal("85.00")
|
|
|
|
def to_dict(self) -> Dict[str, Any]:
|
|
return {
|
|
"id": self.id,
|
|
"tenant_id": self.tenant_id,
|
|
"warehouse_id": self.warehouse_id,
|
|
"name": self.name,
|
|
"city": self.city,
|
|
"total_capacity_mt": float(self.total_capacity_mt),
|
|
"current_closing_stock_mt": float(self.current_closing_stock_mt),
|
|
"allocated_stock_mt": float(self.allocated_stock_mt),
|
|
"available_capacity_mt": float(self.available_capacity_mt),
|
|
"utilization_pct": float(self.utilization_pct),
|
|
"warning_flag": self.warning_flag,
|
|
}
|
|
|
|
|
|
class StockTransfer(Base):
|
|
"""Inter-Godown Internal Stock Movement with Transit Reconciliation."""
|
|
__tablename__ = "stock_transfers"
|
|
__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)
|
|
transfer_number = Column(String(32), nullable=False, unique=True, index=True)
|
|
origin_warehouse_id = Column(String(36), nullable=False, index=True)
|
|
destination_warehouse_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")
|
|
dispatched_mt = Column(Numeric(12, 3), nullable=False)
|
|
dispatched_bags = Column(Integer, nullable=False)
|
|
received_mt = Column(Numeric(12, 3), nullable=True)
|
|
received_bags = Column(Integer, nullable=True)
|
|
variance_mt = Column(Numeric(12, 3), nullable=True)
|
|
variance_pct = Column(Numeric(6, 2), nullable=True)
|
|
status = Column(String(32), default="INITIATED")
|
|
created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
|
|
completed_at = Column(DateTime, nullable=True)
|
|
|
|
def __init__(
|
|
self,
|
|
tenant_id: str,
|
|
transfer_number: str,
|
|
origin_warehouse_id: str,
|
|
destination_warehouse_id: str,
|
|
commodity_id: str,
|
|
variety: str,
|
|
dispatched_mt: Decimal,
|
|
dispatched_bags: int,
|
|
grade: str = "FAQ",
|
|
transfer_id: Optional[str] = None,
|
|
):
|
|
if origin_warehouse_id == destination_warehouse_id:
|
|
raise ValueError("Origin and destination warehouse cannot be the same")
|
|
if dispatched_mt <= Decimal("0.000") or dispatched_bags <= 0:
|
|
raise ValueError("Dispatched MT and bags must be positive")
|
|
|
|
self.id = transfer_id or str(uuid.uuid4())
|
|
self.tenant_id = tenant_id
|
|
self.transfer_number = transfer_number
|
|
self.origin_warehouse_id = origin_warehouse_id
|
|
self.destination_warehouse_id = destination_warehouse_id
|
|
self.commodity_id = commodity_id
|
|
self.variety = variety
|
|
self.grade = grade
|
|
self.dispatched_mt = dispatched_mt
|
|
self.dispatched_bags = dispatched_bags
|
|
self.received_mt = None
|
|
self.received_bags = None
|
|
self.variance_mt = None
|
|
self.variance_pct = None
|
|
self.status = "IN_TRANSIT"
|
|
self.created_at = datetime.now(timezone.utc)
|
|
self.completed_at = None
|
|
|
|
def record_receipt(self, received_mt: Decimal, received_bags: int) -> None:
|
|
"""Records destination weighment and reconciles against +/-0.2% tolerance."""
|
|
if received_mt <= Decimal("0.000") or received_bags < 0:
|
|
raise ValueError("Received MT must be > 0.0 and bags must be non-negative")
|
|
|
|
self.received_mt = received_mt
|
|
self.received_bags = received_bags
|
|
self.variance_mt = (self.dispatched_mt - received_mt).quantize(
|
|
Decimal("0.001"), rounding=ROUND_HALF_UP
|
|
)
|
|
self.variance_pct = (
|
|
(abs(self.variance_mt) / self.dispatched_mt) * Decimal("100.0")
|
|
).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
|
|
self.completed_at = datetime.now(timezone.utc)
|
|
|
|
# Tolerance check: +/- 0.20%
|
|
if self.variance_pct > Decimal("0.20"):
|
|
self.status = "SHORTAGE_ALERT"
|
|
else:
|
|
self.status = "COMPLETED"
|
|
|
|
def to_dict(self) -> Dict[str, Any]:
|
|
return {
|
|
"id": self.id,
|
|
"tenant_id": self.tenant_id,
|
|
"transfer_number": self.transfer_number,
|
|
"origin_warehouse_id": self.origin_warehouse_id,
|
|
"destination_warehouse_id": self.destination_warehouse_id,
|
|
"commodity_id": self.commodity_id,
|
|
"variety": self.variety,
|
|
"grade": self.grade,
|
|
"dispatched_mt": float(self.dispatched_mt),
|
|
"dispatched_bags": self.dispatched_bags,
|
|
"received_mt": float(self.received_mt) if self.received_mt is not None else None,
|
|
"received_bags": self.received_bags,
|
|
"variance_mt": float(self.variance_mt) if self.variance_mt is not None else None,
|
|
"variance_pct": float(self.variance_pct) if self.variance_pct is not None else None,
|
|
"status": self.status,
|
|
"created_at": self.created_at.isoformat() if self.created_at else None,
|
|
"completed_at": self.completed_at.isoformat() if self.completed_at else None,
|
|
}
|