194 lines
8.4 KiB
Python
194 lines
8.4 KiB
Python
"""Rural Farmer Settlement, Bikri Parcha & Advance (Paishgi) Models.
|
|
|
|
Fulfills Phase 2 requirements BRD-FR-059, BRD-FR-060, BRD-FR-061, and BRD-FR-062 (UC-029).
|
|
Adheres to UP-AI v1.5 standards.
|
|
"""
|
|
from datetime import datetime, date, 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
|
|
|
|
PARCHA_STATUSES = {"ISSUED", "CLEARED", "CANCELLED"}
|
|
PAYMENT_MODES = {"IMPS", "NEFT", "CASH_VOUCHER"}
|
|
|
|
|
|
def calculate_bikri_parcha_net(
|
|
gross_weight_kg: Decimal,
|
|
tare_bags_kg: Decimal,
|
|
auction_rate_per_qtl: Decimal,
|
|
hamali_rate_per_bag: Decimal = Decimal("4.00"),
|
|
tolai_rate_per_bag: Decimal = Decimal("2.00"),
|
|
bag_count: int = 1,
|
|
advance_principal_netted: Decimal = Decimal("0.00"),
|
|
advance_interest_netted: Decimal = Decimal("0.00"),
|
|
) -> Dict[str, Any]:
|
|
"""Calculates gross realization and net farmer payout on an auction sale slip."""
|
|
if gross_weight_kg <= tare_bags_kg:
|
|
raise ValueError("Gross weight kg must be strictly greater than tare bags kg")
|
|
if auction_rate_per_qtl <= Decimal("0.00"):
|
|
raise ValueError("Auction rate per quintal must be positive")
|
|
if bag_count <= 0:
|
|
raise ValueError("Bag count must be > 0")
|
|
|
|
net_weight_kg = gross_weight_kg - tare_bags_kg
|
|
net_weight_mt = (net_weight_kg / Decimal("1000.0")).quantize(Decimal("0.001"), rounding=ROUND_HALF_UP)
|
|
|
|
# Gross realization = Net MT * 10 * Rate/Qtl
|
|
gross_realization = (net_weight_mt * Decimal("10.0") * auction_rate_per_qtl).quantize(
|
|
Decimal("0.01"), rounding=ROUND_HALF_UP
|
|
)
|
|
|
|
hamali_deduction = (Decimal(bag_count) * hamali_rate_per_bag).quantize(
|
|
Decimal("0.01"), rounding=ROUND_HALF_UP
|
|
)
|
|
tolai_deduction = (Decimal(bag_count) * tolai_rate_per_bag).quantize(
|
|
Decimal("0.01"), rounding=ROUND_HALF_UP
|
|
)
|
|
total_advance_netted = (advance_principal_netted + advance_interest_netted).quantize(
|
|
Decimal("0.01"), rounding=ROUND_HALF_UP
|
|
)
|
|
|
|
net_farmer_payable = gross_realization - hamali_deduction - tolai_deduction - total_advance_netted
|
|
if net_farmer_payable < Decimal("0.00"):
|
|
raise ValueError(
|
|
f"Net farmer payable cannot be negative (gross {gross_realization} vs deductions "
|
|
f"{hamali_deduction + tolai_deduction + total_advance_netted})"
|
|
)
|
|
|
|
return {
|
|
"net_weight_mt": net_weight_mt,
|
|
"gross_realization": gross_realization,
|
|
"hamali_deduction": hamali_deduction,
|
|
"tolai_deduction": tolai_deduction,
|
|
"advance_netted": total_advance_netted,
|
|
"net_farmer_payable": net_farmer_payable,
|
|
}
|
|
|
|
|
|
class FarmerBikriParcha(Base):
|
|
"""Auction Sale Slip and Statutory Self-Purchase Invoice for direct farmer procurement."""
|
|
__tablename__ = "farmer_bikri_parchas"
|
|
__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)
|
|
parcha_number = Column(String(32), nullable=False, unique=True, index=True)
|
|
auction_date = Column(Date, nullable=False, index=True)
|
|
farmer_id = Column(String(36), nullable=False, index=True)
|
|
vehicle_number = Column(String(16), nullable=False)
|
|
commodity_id = Column(String(36), nullable=False)
|
|
variety = Column(String(64), nullable=False)
|
|
bag_count = Column(Integer, nullable=False)
|
|
gross_weight_kg = Column(Numeric(12, 2), nullable=False)
|
|
tare_bags_kg = Column(Numeric(12, 2), nullable=False)
|
|
net_weight_mt = Column(Numeric(12, 3), nullable=False)
|
|
auction_rate_per_qtl = Column(Numeric(10, 2), nullable=False)
|
|
gross_realization_inr = Column(Numeric(14, 2), nullable=False)
|
|
hamali_deduction_inr = Column(Numeric(10, 2), default=0.0)
|
|
tolai_deduction_inr = Column(Numeric(10, 2), default=0.0)
|
|
advance_netted_inr = Column(Numeric(12, 2), default=0.0)
|
|
net_farmer_payable_inr = Column(Numeric(14, 2), nullable=False)
|
|
payment_status = Column(String(32), default="ISSUED")
|
|
disbursement_mode = Column(String(32), nullable=True)
|
|
utr_or_voucher_ref = Column(String(64), nullable=True)
|
|
disbursed_at = Column(DateTime, nullable=True)
|
|
created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
|
|
|
|
def __init__(
|
|
self,
|
|
tenant_id: str,
|
|
parcha_number: str,
|
|
auction_date: date,
|
|
farmer_id: str,
|
|
vehicle_number: str,
|
|
commodity_id: str,
|
|
variety: str,
|
|
bag_count: int,
|
|
gross_weight_kg: Decimal,
|
|
tare_bags_kg: Decimal,
|
|
auction_rate_per_qtl: Decimal,
|
|
hamali_rate_per_bag: Decimal = Decimal("4.00"),
|
|
tolai_rate_per_bag: Decimal = Decimal("2.00"),
|
|
advance_principal_netted: Decimal = Decimal("0.00"),
|
|
advance_interest_netted: Decimal = Decimal("0.00"),
|
|
parcha_id: Optional[str] = None,
|
|
):
|
|
calc = calculate_bikri_parcha_net(
|
|
gross_weight_kg=gross_weight_kg,
|
|
tare_bags_kg=tare_bags_kg,
|
|
auction_rate_per_qtl=auction_rate_per_qtl,
|
|
hamali_rate_per_bag=hamali_rate_per_bag,
|
|
tolai_rate_per_bag=tolai_rate_per_bag,
|
|
bag_count=bag_count,
|
|
advance_principal_netted=advance_principal_netted,
|
|
advance_interest_netted=advance_interest_netted,
|
|
)
|
|
|
|
self.id = parcha_id or str(uuid.uuid4())
|
|
self.tenant_id = tenant_id
|
|
self.parcha_number = parcha_number
|
|
self.auction_date = auction_date
|
|
self.farmer_id = farmer_id
|
|
self.vehicle_number = vehicle_number.replace("-", "").replace(" ", "").upper()
|
|
self.commodity_id = commodity_id
|
|
self.variety = variety
|
|
self.bag_count = bag_count
|
|
self.gross_weight_kg = gross_weight_kg
|
|
self.tare_bags_kg = tare_bags_kg
|
|
self.net_weight_mt = calc["net_weight_mt"]
|
|
self.auction_rate_per_qtl = auction_rate_per_qtl
|
|
self.gross_realization_inr = calc["gross_realization"]
|
|
self.hamali_deduction_inr = calc["hamali_deduction"]
|
|
self.tolai_deduction_inr = calc["tolai_deduction"]
|
|
self.advance_netted_inr = calc["advance_netted"]
|
|
self.net_farmer_payable_inr = calc["net_farmer_payable"]
|
|
self.payment_status = "ISSUED"
|
|
self.created_at = datetime.now(timezone.utc)
|
|
|
|
def mark_disbursed(self, mode: str, reference_no: str) -> None:
|
|
if mode not in PAYMENT_MODES:
|
|
raise ValueError(f"Invalid payment mode '{mode}'. Allowed: {sorted(PAYMENT_MODES)}")
|
|
if not reference_no or not reference_no.strip():
|
|
raise ValueError("Disbursement reference or UTR number is mandatory")
|
|
|
|
self.payment_status = "CLEARED"
|
|
self.disbursement_mode = mode
|
|
self.utr_or_voucher_ref = reference_no.strip()
|
|
self.disbursed_at = datetime.now(timezone.utc)
|
|
|
|
def to_dict(self) -> Dict[str, Any]:
|
|
return {
|
|
"id": self.id,
|
|
"tenant_id": self.tenant_id,
|
|
"parcha_number": self.parcha_number,
|
|
"auction_date": self.auction_date.isoformat() if hasattr(self.auction_date, "isoformat") else str(self.auction_date),
|
|
"farmer_id": self.farmer_id,
|
|
"vehicle_number": self.vehicle_number,
|
|
"commodity_id": self.commodity_id,
|
|
"variety": self.variety,
|
|
"bag_count": self.bag_count,
|
|
"gross_weight_kg": float(self.gross_weight_kg),
|
|
"tare_bags_kg": float(self.tare_bags_kg),
|
|
"net_weight_mt": float(self.net_weight_mt),
|
|
"auction_rate_per_qtl": float(self.auction_rate_per_qtl),
|
|
"gross_realization_inr": float(self.gross_realization_inr),
|
|
"hamali_deduction_inr": float(self.hamali_deduction_inr),
|
|
"tolai_deduction_inr": float(self.tolai_deduction_inr),
|
|
"advance_netted_inr": float(self.advance_netted_inr),
|
|
"net_farmer_payable_inr": float(self.net_farmer_payable_inr),
|
|
"payment_status": self.payment_status,
|
|
"disbursement_mode": self.disbursement_mode,
|
|
"utr_or_voucher_ref": self.utr_or_voucher_ref,
|
|
"disbursed_at": self.disbursed_at.isoformat() if self.disbursed_at else None,
|
|
"created_at": self.created_at.isoformat() if self.created_at else None,
|
|
}
|
|
|