243 lines
11 KiB
Python
243 lines
11 KiB
Python
"""Procurement Contracts & Sauda Booking Models and Invariants.
|
|
|
|
Fulfills FR-PROCUREMENTCONTRACTS-001..004 (UC-004).
|
|
Adheres to LLD-004 and UP-AI v1.5 standards.
|
|
"""
|
|
from datetime import datetime, date, timedelta, timezone
|
|
from decimal import Decimal, ROUND_HALF_UP
|
|
from typing import Optional, Dict, Any
|
|
import uuid
|
|
|
|
try:
|
|
from sqlalchemy import Column, String, DateTime, Date, Numeric, Integer, Boolean
|
|
from backend.app.models.user import Base
|
|
except ImportError:
|
|
class Base:
|
|
pass
|
|
Column = String = DateTime = Date = Numeric = Integer = Boolean = lambda *args, **kwargs: None
|
|
|
|
SAUDA_STATUSES = {"ACTIVE", "PARTIALLY_RECEIVED", "FULFILLED", "CANCELLED"}
|
|
|
|
|
|
def calculate_sauda_commercials(
|
|
booked_quantity_mt: Decimal,
|
|
trade_rate_per_qtl: Decimal,
|
|
contract_date: date,
|
|
credit_period_days: int,
|
|
mandi_cess_pct: Decimal = Decimal("1.50"),
|
|
krishi_kalyan_pct: Decimal = Decimal("0.50"),
|
|
brokerage_rate_pct: Decimal = Decimal("1.00"),
|
|
benchmark_modal_rate: Optional[Decimal] = None,
|
|
variance_acknowledged: bool = False
|
|
) -> Dict[str, Any]:
|
|
"""Calculates all financial commercial terms and validates variance alerts."""
|
|
if booked_quantity_mt <= Decimal("0.0"):
|
|
raise ValueError("Booked quantity MT must be > 0.0")
|
|
|
|
if trade_rate_per_qtl <= Decimal("0.0"):
|
|
raise ValueError("Trade rate per quintal must be > 0.0")
|
|
|
|
if credit_period_days < 0:
|
|
raise ValueError("Credit period days must be >= 0")
|
|
|
|
# Gross value = Booked MT * 10 Qtl/MT * Rate/Qtl
|
|
gross_amount = (booked_quantity_mt * Decimal("10.0") * trade_rate_per_qtl).quantize(
|
|
Decimal("0.01"), rounding=ROUND_HALF_UP
|
|
)
|
|
|
|
# Variance alert check
|
|
variance_pct = Decimal("0.00")
|
|
if benchmark_modal_rate is not None and benchmark_modal_rate > Decimal("0.0"):
|
|
diff = trade_rate_per_qtl - benchmark_modal_rate
|
|
variance_pct = ((diff / benchmark_modal_rate) * Decimal("100.0")).quantize(
|
|
Decimal("0.01"), rounding=ROUND_HALF_UP
|
|
)
|
|
if variance_pct > Decimal("5.00") and not variance_acknowledged:
|
|
raise ValueError(
|
|
f"Offered trade rate ({trade_rate_per_qtl}) exceeds benchmark modal rate ({benchmark_modal_rate}) "
|
|
f"by +{variance_pct}%, which is > 5.0% threshold. Explicit variance acknowledgment is required."
|
|
)
|
|
|
|
# Statutory APMC Cess and Levies
|
|
mandi_cess_amount = (gross_amount * (mandi_cess_pct / Decimal("100.0"))).quantize(
|
|
Decimal("0.01"), rounding=ROUND_HALF_UP
|
|
)
|
|
krishi_kalyan_amount = (gross_amount * (krishi_kalyan_pct / Decimal("100.0"))).quantize(
|
|
Decimal("0.01"), rounding=ROUND_HALF_UP
|
|
)
|
|
brokerage_amount = (gross_amount * (brokerage_rate_pct / Decimal("100.0"))).quantize(
|
|
Decimal("0.01"), rounding=ROUND_HALF_UP
|
|
)
|
|
total_landed_amount = gross_amount + mandi_cess_amount + krishi_kalyan_amount + brokerage_amount
|
|
|
|
# Due date arithmetic
|
|
payment_due_date = contract_date + timedelta(days=credit_period_days)
|
|
|
|
return {
|
|
"gross_amount": gross_amount,
|
|
"variance_pct": variance_pct,
|
|
"mandi_cess_amount": mandi_cess_amount,
|
|
"krishi_kalyan_amount": krishi_kalyan_amount,
|
|
"brokerage_amount": brokerage_amount,
|
|
"total_landed_amount": total_landed_amount,
|
|
"payment_due_date": payment_due_date
|
|
}
|
|
|
|
|
|
class ProcurementSauda(Base):
|
|
__tablename__ = "procurement_sauda"
|
|
__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)
|
|
sauda_number = Column(String(32), nullable=False, unique=True, index=True)
|
|
contract_date = Column(Date, nullable=False, index=True)
|
|
delivery_due_date = Column(Date, nullable=False)
|
|
supplier_id = Column(String(36), nullable=False, index=True)
|
|
mandi_id = Column(String(36), nullable=False)
|
|
trade_type = Column(String(32), default="MANDI_AUCTION")
|
|
commodity_id = Column(String(36), nullable=False)
|
|
variety = Column(String(64), nullable=False)
|
|
grade = Column(String(32), default="FAQ")
|
|
booked_quantity_mt = Column(Numeric(12, 3), nullable=False)
|
|
estimated_bags = Column(Integer, default=0)
|
|
trade_rate_per_qtl = Column(Numeric(10, 2), nullable=False)
|
|
cumulative_received_mt = Column(Numeric(12, 3), default=0.0)
|
|
balance_mt = Column(Numeric(12, 3), nullable=False)
|
|
credit_period_days = Column(Integer, default=0)
|
|
payment_due_date = Column(Date, nullable=False)
|
|
advance_amount = Column(Numeric(12, 2), default=0.0)
|
|
mandi_cess_pct = Column(Numeric(5, 2), default=1.50)
|
|
krishi_kalyan_pct = Column(Numeric(5, 2), default=0.50)
|
|
brokerage_rate_pct = Column(Numeric(5, 2), default=1.00)
|
|
gross_amount = Column(Numeric(14, 2), nullable=False)
|
|
mandi_cess_amount = Column(Numeric(12, 2), nullable=False)
|
|
krishi_kalyan_amount = Column(Numeric(12, 2), nullable=False)
|
|
brokerage_amount = Column(Numeric(12, 2), nullable=False)
|
|
total_landed_amount = Column(Numeric(14, 2), nullable=False)
|
|
variance_pct = Column(Numeric(5, 2), default=0.0)
|
|
variance_acknowledged = Column(Boolean, default=False)
|
|
status = Column(String(32), default="ACTIVE", index=True)
|
|
created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
|
|
|
|
def __init__(
|
|
self,
|
|
tenant_id: str,
|
|
sauda_number: str,
|
|
contract_date: date,
|
|
delivery_due_date: date,
|
|
supplier_id: str,
|
|
mandi_id: str,
|
|
commodity_id: str,
|
|
variety: str,
|
|
booked_quantity_mt: Decimal,
|
|
trade_rate_per_qtl: Decimal,
|
|
grade: str = "FAQ",
|
|
trade_type: str = "MANDI_AUCTION",
|
|
estimated_bags: int = 0,
|
|
credit_period_days: int = 0,
|
|
advance_amount: Decimal = Decimal("0.00"),
|
|
mandi_cess_pct: Decimal = Decimal("1.50"),
|
|
krishi_kalyan_pct: Decimal = Decimal("0.50"),
|
|
brokerage_rate_pct: Decimal = Decimal("1.00"),
|
|
benchmark_modal_rate: Optional[Decimal] = None,
|
|
variance_acknowledged: bool = False,
|
|
sauda_id: Optional[str] = None
|
|
):
|
|
calc = calculate_sauda_commercials(
|
|
booked_quantity_mt=booked_quantity_mt,
|
|
trade_rate_per_qtl=trade_rate_per_qtl,
|
|
contract_date=contract_date,
|
|
credit_period_days=credit_period_days,
|
|
mandi_cess_pct=mandi_cess_pct,
|
|
krishi_kalyan_pct=krishi_kalyan_pct,
|
|
brokerage_rate_pct=brokerage_rate_pct,
|
|
benchmark_modal_rate=benchmark_modal_rate,
|
|
variance_acknowledged=variance_acknowledged
|
|
)
|
|
|
|
self.id = sauda_id or str(uuid.uuid4())
|
|
self.tenant_id = tenant_id
|
|
self.sauda_number = sauda_number
|
|
self.contract_date = contract_date
|
|
self.delivery_due_date = delivery_due_date
|
|
self.supplier_id = supplier_id
|
|
self.mandi_id = mandi_id
|
|
self.trade_type = trade_type
|
|
self.commodity_id = commodity_id
|
|
self.variety = variety
|
|
self.grade = grade
|
|
self.booked_quantity_mt = booked_quantity_mt
|
|
self.estimated_bags = estimated_bags
|
|
self.trade_rate_per_qtl = trade_rate_per_qtl
|
|
self.cumulative_received_mt = Decimal("0.000")
|
|
self.balance_mt = booked_quantity_mt
|
|
self.credit_period_days = credit_period_days
|
|
self.payment_due_date = calc["payment_due_date"]
|
|
self.advance_amount = advance_amount
|
|
self.mandi_cess_pct = mandi_cess_pct
|
|
self.krishi_kalyan_pct = krishi_kalyan_pct
|
|
self.brokerage_rate_pct = brokerage_rate_pct
|
|
self.gross_amount = calc["gross_amount"]
|
|
self.mandi_cess_amount = calc["mandi_cess_amount"]
|
|
self.krishi_kalyan_amount = calc["krishi_kalyan_amount"]
|
|
self.brokerage_amount = calc["brokerage_amount"]
|
|
self.total_landed_amount = calc["total_landed_amount"]
|
|
self.variance_pct = calc["variance_pct"]
|
|
self.variance_acknowledged = variance_acknowledged
|
|
self.status = "ACTIVE"
|
|
self.created_at = datetime.now(timezone.utc)
|
|
|
|
def record_receipt(self, received_mt: Decimal, tolerance_pct: Decimal = Decimal("0.50")) -> None:
|
|
"""Records partial delivery receipt and transitions lifecycle state machine."""
|
|
if self.status in {"FULFILLED", "CANCELLED"}:
|
|
raise ValueError(f"Cannot record receipt on sauda in terminal status '{self.status}'")
|
|
|
|
if received_mt <= Decimal("0.000"):
|
|
raise ValueError("Received metric tonnes must be > 0.0")
|
|
|
|
self.cumulative_received_mt = (self.cumulative_received_mt + received_mt).quantize(Decimal("0.001"))
|
|
self.balance_mt = max(Decimal("0.000"), (self.booked_quantity_mt - self.cumulative_received_mt).quantize(Decimal("0.001")))
|
|
|
|
tolerance_mt = (self.booked_quantity_mt * (tolerance_pct / Decimal("100.0"))).quantize(Decimal("0.001"))
|
|
if self.cumulative_received_mt >= (self.booked_quantity_mt - tolerance_mt):
|
|
self.status = "FULFILLED"
|
|
else:
|
|
self.status = "PARTIALLY_RECEIVED"
|
|
|
|
def to_dict(self) -> Dict[str, Any]:
|
|
return {
|
|
"id": self.id,
|
|
"tenant_id": self.tenant_id,
|
|
"sauda_number": self.sauda_number,
|
|
"contract_date": str(self.contract_date),
|
|
"delivery_due_date": str(self.delivery_due_date),
|
|
"supplier_id": self.supplier_id,
|
|
"mandi_id": self.mandi_id,
|
|
"trade_type": self.trade_type,
|
|
"commodity_id": self.commodity_id,
|
|
"variety": self.variety,
|
|
"grade": self.grade,
|
|
"booked_quantity_mt": float(self.booked_quantity_mt),
|
|
"estimated_bags": self.estimated_bags,
|
|
"trade_rate_per_qtl": float(self.trade_rate_per_qtl),
|
|
"cumulative_received_mt": float(self.cumulative_received_mt),
|
|
"balance_mt": float(self.balance_mt),
|
|
"credit_period_days": self.credit_period_days,
|
|
"payment_due_date": str(self.payment_due_date),
|
|
"advance_amount": float(self.advance_amount),
|
|
"mandi_cess_pct": float(self.mandi_cess_pct),
|
|
"krishi_kalyan_pct": float(self.krishi_kalyan_pct),
|
|
"brokerage_rate_pct": float(self.brokerage_rate_pct),
|
|
"gross_amount": float(self.gross_amount),
|
|
"mandi_cess_amount": float(self.mandi_cess_amount),
|
|
"krishi_kalyan_amount": float(self.krishi_kalyan_amount),
|
|
"brokerage_amount": float(self.brokerage_amount),
|
|
"total_landed_amount": float(self.total_landed_amount),
|
|
"variance_pct": float(self.variance_pct),
|
|
"variance_acknowledged": self.variance_acknowledged,
|
|
"status": self.status,
|
|
"created_at": self.created_at.isoformat() if self.created_at else None
|
|
}
|
|
|