343 lines
14 KiB
Python
343 lines
14 KiB
Python
"""Agricultural Master Data Management Domain Models.
|
|
|
|
Fulfills:
|
|
- FR-MASTERDATA-001 (Agricultural Commodity Master Data Management)
|
|
- FR-MASTERDATA-002 (Trading Counterparty and Godown Directory)
|
|
|
|
Adheres to LLD-001, LLD-002, 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 re
|
|
import uuid
|
|
|
|
try:
|
|
from sqlalchemy import Column, String, DateTime, Numeric, Integer, Boolean, ForeignKey
|
|
from sqlalchemy.orm import relationship
|
|
from backend.app.models.user import Base
|
|
except ImportError:
|
|
class Base:
|
|
pass
|
|
Column = String = DateTime = Numeric = Integer = Boolean = ForeignKey = lambda *args, **kwargs: None
|
|
relationship = lambda *args, **kwargs: None
|
|
|
|
# Constants & Allowed Values
|
|
COUNTERPARTY_TYPES = {"FARMER", "COMMISSION_AGENT", "PROCESSOR", "WHOLESALE_BUYER"}
|
|
ALLOWED_CREDIT_TERMS_DAYS = {7, 15, 21}
|
|
PHASE2_CREDIT_TERMS_DAYS = {0, 1, 7, 15, 21} # Phase 2 APMC Sec 37/38 immediate settlement
|
|
PAN_REGEX = re.compile(r"^[A-Z]{5}[0-9]{4}[A-Z]{1}$")
|
|
GSTIN_REGEX = re.compile(r"^[0-9]{2}[A-Z]{5}[0-9]{4}[A-Z]{1}[1-9A-Z]{1}Z[0-9A-Z]{1}$")
|
|
IFSC_REGEX = re.compile(r"^[A-Z]{4}0[A-Z0-9]{6}$")
|
|
|
|
|
|
|
|
|
|
class Commodity(Base):
|
|
"""Agricultural commodity specification including standard bag weight and quality baselines."""
|
|
__tablename__ = "commodities"
|
|
|
|
id = Column(String(36), primary_key=True)
|
|
tenant_id = Column(String(36), nullable=False, index=True)
|
|
code = Column(String(50), nullable=False)
|
|
name = Column(String(150), nullable=False)
|
|
hsn_code = Column(String(20), nullable=True)
|
|
standard_bag_weight_kg = Column(Numeric(8, 2), nullable=False, default=50.00)
|
|
moisture_baseline_pct = Column(Numeric(5, 2), nullable=False, default=10.00)
|
|
foreign_matter_max_pct = Column(Numeric(5, 2), nullable=False, default=2.00)
|
|
damaged_grain_max_pct = Column(Numeric(5, 2), nullable=False, default=3.00)
|
|
qc_required = Column(Boolean, nullable=False, default=True)
|
|
is_active = Column(Boolean, nullable=False, default=True)
|
|
created_at = Column(DateTime, nullable=False, default=lambda: datetime.now(timezone.utc))
|
|
updated_at = Column(DateTime, nullable=False, default=lambda: datetime.now(timezone.utc))
|
|
|
|
def __init__(
|
|
self,
|
|
tenant_id: str,
|
|
code: str,
|
|
name: str,
|
|
hsn_code: Optional[str] = None,
|
|
standard_bag_weight_kg: float = 50.0,
|
|
moisture_baseline_pct: float = 10.0,
|
|
foreign_matter_max_pct: float = 2.0,
|
|
damaged_grain_max_pct: float = 3.0,
|
|
qc_required: bool = True,
|
|
is_active: bool = True,
|
|
id: Optional[str] = None,
|
|
):
|
|
if not code or not code.strip():
|
|
raise ValueError("Commodity code cannot be empty")
|
|
if not name or not name.strip():
|
|
raise ValueError("Commodity name cannot be empty")
|
|
if standard_bag_weight_kg <= 0:
|
|
raise ValueError("Standard bag weight must be positive")
|
|
if not (0.0 <= moisture_baseline_pct <= 30.0):
|
|
raise ValueError("Moisture baseline must be between 0.0% and 30.0%")
|
|
if not (0.0 <= foreign_matter_max_pct <= 15.0):
|
|
raise ValueError("Foreign matter tolerance must be between 0.0% and 15.0%")
|
|
if not (0.0 <= damaged_grain_max_pct <= 20.0):
|
|
raise ValueError("Damaged grain tolerance must be between 0.0% and 20.0%")
|
|
|
|
self.id = id or str(uuid.uuid4())
|
|
self.tenant_id = tenant_id
|
|
self.code = code.strip().upper()
|
|
self.name = name.strip()
|
|
self.hsn_code = hsn_code.strip() if hsn_code else None
|
|
self.standard_bag_weight_kg = Decimal(str(standard_bag_weight_kg))
|
|
self.moisture_baseline_pct = Decimal(str(moisture_baseline_pct))
|
|
self.foreign_matter_max_pct = Decimal(str(foreign_matter_max_pct))
|
|
self.damaged_grain_max_pct = Decimal(str(damaged_grain_max_pct))
|
|
self.qc_required = qc_required
|
|
self.is_active = is_active
|
|
self.created_at = datetime.now(timezone.utc)
|
|
self.updated_at = datetime.now(timezone.utc)
|
|
|
|
def to_dict(self) -> Dict[str, Any]:
|
|
return {
|
|
"id": self.id,
|
|
"tenant_id": self.tenant_id,
|
|
"code": self.code,
|
|
"name": self.name,
|
|
"hsn_code": self.hsn_code,
|
|
"standard_bag_weight_kg": float(self.standard_bag_weight_kg),
|
|
"moisture_baseline_pct": float(self.moisture_baseline_pct),
|
|
"foreign_matter_max_pct": float(self.foreign_matter_max_pct),
|
|
"damaged_grain_max_pct": float(self.damaged_grain_max_pct),
|
|
"qc_required": self.qc_required,
|
|
"is_active": self.is_active,
|
|
"created_at": self.created_at.isoformat() if hasattr(self.created_at, "isoformat") else str(self.created_at),
|
|
"updated_at": self.updated_at.isoformat() if hasattr(self.updated_at, "isoformat") else str(self.updated_at),
|
|
}
|
|
|
|
|
|
class CommodityVariety(Base):
|
|
"""Botanical or commercial variety belonging to a parent commodity."""
|
|
__tablename__ = "commodity_varieties"
|
|
|
|
id = Column(String(36), primary_key=True)
|
|
tenant_id = Column(String(36), nullable=False, index=True)
|
|
commodity_id = Column(String(36), nullable=False, index=True)
|
|
code = Column(String(50), nullable=False)
|
|
name = Column(String(150), nullable=False)
|
|
is_active = Column(Boolean, nullable=False, default=True)
|
|
created_at = Column(DateTime, nullable=False, default=lambda: datetime.now(timezone.utc))
|
|
|
|
def __init__(
|
|
self,
|
|
tenant_id: str,
|
|
commodity_id: str,
|
|
code: str,
|
|
name: str,
|
|
is_active: bool = True,
|
|
id: Optional[str] = None,
|
|
):
|
|
if not tenant_id or not tenant_id.strip():
|
|
raise ValueError("Tenant ID cannot be empty")
|
|
if not commodity_id or not commodity_id.strip():
|
|
raise ValueError("Commodity ID cannot be empty")
|
|
if not code or not code.strip():
|
|
raise ValueError("Variety code cannot be empty")
|
|
if not name or not name.strip():
|
|
raise ValueError("Variety name cannot be empty")
|
|
|
|
self.id = id or str(uuid.uuid4())
|
|
self.tenant_id = tenant_id
|
|
self.commodity_id = commodity_id
|
|
self.code = code.strip().upper()
|
|
self.name = name.strip()
|
|
self.is_active = is_active
|
|
self.created_at = datetime.now(timezone.utc)
|
|
|
|
def to_dict(self) -> Dict[str, Any]:
|
|
return {
|
|
"id": self.id,
|
|
"tenant_id": self.tenant_id,
|
|
"commodity_id": self.commodity_id,
|
|
"code": self.code,
|
|
"name": self.name,
|
|
"is_active": self.is_active,
|
|
"created_at": self.created_at.isoformat() if hasattr(self.created_at, "isoformat") else str(self.created_at),
|
|
}
|
|
|
|
|
|
class TradingCounterparty(Base):
|
|
"""Business partner profile (Farmer, Commission Agent, Processor, Buyer) with statutory info."""
|
|
__tablename__ = "trading_counterparties"
|
|
|
|
id = Column(String(36), primary_key=True)
|
|
tenant_id = Column(String(36), nullable=False, index=True)
|
|
name = Column(String(150), nullable=False)
|
|
counterparty_type = Column(String(50), nullable=False)
|
|
pan_number = Column(String(10), nullable=False)
|
|
gstin = Column(String(15), nullable=True)
|
|
credit_terms_days = Column(Integer, nullable=False, default=7)
|
|
credit_limit_inr = Column(Numeric(14, 2), nullable=False, default=0.00)
|
|
bank_account_number = Column(String(30), nullable=False)
|
|
bank_ifsc_code = Column(String(11), nullable=False)
|
|
bank_name = Column(String(100), nullable=False)
|
|
phone = Column(String(20), nullable=True)
|
|
is_active = Column(Boolean, nullable=False, default=True)
|
|
created_at = Column(DateTime, nullable=False, default=lambda: datetime.now(timezone.utc))
|
|
updated_at = Column(DateTime, nullable=False, default=lambda: datetime.now(timezone.utc))
|
|
|
|
def __init__(
|
|
self,
|
|
tenant_id: str,
|
|
name: str,
|
|
counterparty_type: str,
|
|
pan_number: str,
|
|
bank_account_number: str,
|
|
bank_ifsc_code: str,
|
|
bank_name: str,
|
|
gstin: Optional[str] = None,
|
|
credit_terms_days: int = 7,
|
|
credit_limit_inr: float = 0.0,
|
|
phone: Optional[str] = None,
|
|
is_active: bool = True,
|
|
id: Optional[str] = None,
|
|
allow_immediate_settlement: bool = False,
|
|
is_cash_settlement: bool = False,
|
|
):
|
|
if not tenant_id or not tenant_id.strip():
|
|
raise ValueError("Tenant ID cannot be empty")
|
|
if not name or not name.strip():
|
|
raise ValueError("Counterparty name cannot be empty")
|
|
|
|
c_type = counterparty_type.strip().upper()
|
|
if c_type not in COUNTERPARTY_TYPES:
|
|
raise ValueError(f"Invalid counterparty type '{c_type}'. Allowed: {sorted(COUNTERPARTY_TYPES)}")
|
|
|
|
pan_clean = pan_number.strip().upper() if pan_number else ""
|
|
if c_type == "FARMER" and (not pan_clean or pan_clean in {"FORM60", "FORM-60", "EXEMPT"}):
|
|
pan_clean = "FORM60"
|
|
elif not PAN_REGEX.match(pan_clean):
|
|
raise ValueError(f"Invalid PAN format '{pan_clean}'. Must be 10 characters in [A-Z]{{5}}[0-9]{{4}}[A-Z]{{1}} format.")
|
|
|
|
if gstin:
|
|
gstin_clean = gstin.strip().upper()
|
|
if not GSTIN_REGEX.match(gstin_clean):
|
|
raise ValueError(f"Invalid GSTIN format '{gstin_clean}'. Must be 15 alphanumeric characters.")
|
|
else:
|
|
gstin_clean = None
|
|
|
|
allowed_terms = PHASE2_CREDIT_TERMS_DAYS if (c_type == "FARMER" or allow_immediate_settlement) else ALLOWED_CREDIT_TERMS_DAYS
|
|
if credit_terms_days not in allowed_terms:
|
|
raise ValueError(f"Invalid credit terms {credit_terms_days}. Allowed: {sorted(ALLOWED_CREDIT_TERMS_DAYS)} days strictly.")
|
|
|
|
if credit_limit_inr < 0:
|
|
raise ValueError("Credit limit cannot be negative")
|
|
|
|
if is_cash_settlement and c_type == "FARMER":
|
|
bank_account_number = (bank_account_number or "").strip() or "CASH_SETTLEMENT"
|
|
bank_name = (bank_name or "").strip() or "Cash Counter"
|
|
ifsc_clean = (bank_ifsc_code or "").strip().upper() or "CASH0000000"
|
|
else:
|
|
if not bank_account_number or not str(bank_account_number).strip():
|
|
raise ValueError("Bank account number cannot be empty")
|
|
|
|
if not bank_name or not str(bank_name).strip():
|
|
raise ValueError("Bank name cannot be empty")
|
|
|
|
ifsc_clean = bank_ifsc_code.strip().upper() if bank_ifsc_code else ""
|
|
if not IFSC_REGEX.match(ifsc_clean):
|
|
raise ValueError(f"Invalid IFSC format '{ifsc_clean}'. Must be 11 characters (e.g. SBIN0001234).")
|
|
|
|
|
|
self.id = id or str(uuid.uuid4())
|
|
self.tenant_id = tenant_id
|
|
self.name = name.strip()
|
|
self.counterparty_type = c_type
|
|
self.pan_number = pan_clean
|
|
self.gstin = gstin_clean
|
|
self.credit_terms_days = credit_terms_days
|
|
self.credit_limit_inr = Decimal(str(credit_limit_inr))
|
|
self.bank_account_number = bank_account_number.strip()
|
|
self.bank_ifsc_code = ifsc_clean
|
|
self.bank_name = bank_name.strip() if bank_name else "Unknown Bank"
|
|
self.phone = phone.strip() if phone else None
|
|
self.is_active = is_active
|
|
self.created_at = datetime.now(timezone.utc)
|
|
self.updated_at = datetime.now(timezone.utc)
|
|
|
|
def to_dict(self) -> Dict[str, Any]:
|
|
return {
|
|
"id": self.id,
|
|
"tenant_id": self.tenant_id,
|
|
"name": self.name,
|
|
"counterparty_type": self.counterparty_type,
|
|
"pan_number": self.pan_number,
|
|
"gstin": self.gstin,
|
|
"credit_terms_days": self.credit_terms_days,
|
|
"credit_limit_inr": float(self.credit_limit_inr),
|
|
"bank_account_number": self.bank_account_number,
|
|
"bank_ifsc_code": self.bank_ifsc_code,
|
|
"bank_name": self.bank_name,
|
|
"phone": self.phone,
|
|
"is_active": self.is_active,
|
|
"created_at": self.created_at.isoformat() if hasattr(self.created_at, "isoformat") else str(self.created_at),
|
|
"updated_at": self.updated_at.isoformat() if hasattr(self.updated_at, "isoformat") else str(self.updated_at),
|
|
}
|
|
|
|
|
|
class Godown(Base):
|
|
"""Storage warehouse with capacity and chamber counts."""
|
|
__tablename__ = "godowns"
|
|
|
|
id = Column(String(36), primary_key=True)
|
|
tenant_id = Column(String(36), nullable=False, index=True)
|
|
code = Column(String(50), nullable=False)
|
|
name = Column(String(150), nullable=False)
|
|
capacity_mt = Column(Numeric(12, 2), nullable=False)
|
|
address = Column(String(255), nullable=False)
|
|
chambers_count = Column(Integer, nullable=False, default=1)
|
|
is_active = Column(Boolean, nullable=False, default=True)
|
|
created_at = Column(DateTime, nullable=False, default=lambda: datetime.now(timezone.utc))
|
|
|
|
def __init__(
|
|
self,
|
|
tenant_id: str,
|
|
code: str,
|
|
name: str,
|
|
capacity_mt: float,
|
|
address: str,
|
|
chambers_count: int = 1,
|
|
is_active: bool = True,
|
|
id: Optional[str] = None,
|
|
):
|
|
if not tenant_id or not tenant_id.strip():
|
|
raise ValueError("Tenant ID cannot be empty")
|
|
if not code or not code.strip():
|
|
raise ValueError("Godown code cannot be empty")
|
|
if not name or not name.strip():
|
|
raise ValueError("Godown name cannot be empty")
|
|
if not address or not address.strip():
|
|
raise ValueError("Godown address/location cannot be empty")
|
|
if capacity_mt <= 0:
|
|
raise ValueError("Godown capacity must be positive MT")
|
|
if chambers_count <= 0:
|
|
raise ValueError("Godown must have at least 1 chamber")
|
|
|
|
self.id = id or str(uuid.uuid4())
|
|
self.tenant_id = tenant_id
|
|
self.code = code.strip().upper()
|
|
self.name = name.strip()
|
|
self.capacity_mt = Decimal(str(capacity_mt))
|
|
self.address = address.strip()
|
|
self.chambers_count = chambers_count
|
|
self.is_active = is_active
|
|
self.created_at = datetime.now(timezone.utc)
|
|
|
|
def to_dict(self) -> Dict[str, Any]:
|
|
return {
|
|
"id": self.id,
|
|
"tenant_id": self.tenant_id,
|
|
"code": self.code,
|
|
"name": self.name,
|
|
"capacity_mt": float(self.capacity_mt),
|
|
"address": self.address,
|
|
"chambers_count": self.chambers_count,
|
|
"is_active": self.is_active,
|
|
"created_at": self.created_at.isoformat() if hasattr(self.created_at, "isoformat") else str(self.created_at),
|
|
}
|
|
|