738 lines
32 KiB
Python
738 lines
32 KiB
Python
"""Financial Settlement, Customer Receivables, Supplier Payables & Operating Expense Models.
|
||
|
||
Fulfills:
|
||
- FR-CUSTOMERRECEIVABLES-001 (Customer Sub-Ledger & Multi-Bucket Aging)
|
||
- FR-CUSTOMERRECEIVABLES-002 (Credit Exposure Watch & Threshold Alert >80%)
|
||
- FR-CUSTOMERRECEIVABLES-003 (Credit Breach Dispatch Lock & Partner Override >100%)
|
||
- FR-CUSTOMERRECEIVABLES-004 (Payment Receipt Posting & Bounce Reversal FSM)
|
||
- FR-SUPPLIERPAYABLES-001 (Supplier Payables Aging & Balance Snapshots)
|
||
- FR-OPERATINGEXPENSES-001 (Mandi Operating Expense Classification & Balancing)
|
||
|
||
Adheres to LLD-004, LLD-009, and UP-AI v1.5 standards.
|
||
"""
|
||
from datetime import datetime, timezone, timedelta
|
||
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, ForeignKey
|
||
from backend.app.models.user import Base
|
||
except ImportError:
|
||
class Base:
|
||
pass
|
||
Column = String = DateTime = Numeric = Integer = Boolean = ForeignKey = lambda *args, **kwargs: None
|
||
|
||
# Constants & Standards
|
||
EXPENSE_CATEGORIES = {
|
||
"HAMALI": "Labor / Hamali (loading/unloading)",
|
||
"FREIGHT": "Freight / Cartage",
|
||
"TOLAI": "Weighbridge Fees",
|
||
"GODOWN_RENT": "Godown Rent",
|
||
"MANDI_CESS": "Mandi Cess",
|
||
"FUMIGATION": "Pest Control / Fumigation",
|
||
"OFFICE": "Office Expenses",
|
||
}
|
||
|
||
PAYMENT_MODES = {"NEFT", "RTGS", "CHEQUE", "CASH", "UPI", "BANK_TRANSFER"}
|
||
RECEIPT_STATUSES = {"PENDING_CLEARANCE", "CLEARED", "BOUNCED"}
|
||
LOCK_STATUSES = {"LOCKED", "OVERRIDDEN", "RELEASED"}
|
||
PAYABLE_STATUSES = {"UNPAID", "PARTIALLY_PAID", "PAID"}
|
||
VOUCHER_TYPES = {"SALES_INVOICE", "PAYMENT_RECEIPT", "CREDIT_NOTE", "DEBIT_NOTE", "DISBURSEMENT"}
|
||
|
||
CREDIT_WATCH_THRESHOLD_PCT = Decimal("80.0")
|
||
CREDIT_LOCK_THRESHOLD_PCT = Decimal("100.0")
|
||
DEFAULT_SUPPLIER_CREDIT_DAYS = 15
|
||
|
||
|
||
class PartySubLedgerEntry(Base):
|
||
"""Immutable party sub-ledger entry for accounts receivable and payable."""
|
||
__tablename__ = "party_subledger_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)
|
||
party_id = Column(String(36), nullable=False, index=True)
|
||
party_type = Column(String(32), nullable=False) # "CUSTOMER" or "SUPPLIER"
|
||
posting_date = Column(DateTime, default=lambda: datetime.now(timezone.utc))
|
||
voucher_type = Column(String(32), nullable=False)
|
||
voucher_number = Column(String(64), nullable=False, index=True)
|
||
debit_amount_inr = Column(Numeric(14, 2), default=Decimal("0.00"))
|
||
credit_amount_inr = Column(Numeric(14, 2), default=Decimal("0.00"))
|
||
running_balance_inr = Column(Numeric(14, 2), nullable=False)
|
||
reversal_of_id = Column(String(36), nullable=True)
|
||
narration = Column(String(255), nullable=True)
|
||
created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
|
||
|
||
def __init__(
|
||
self,
|
||
tenant_id: str,
|
||
party_id: str,
|
||
party_type: str,
|
||
voucher_type: str,
|
||
voucher_number: str,
|
||
debit_amount_inr: Decimal = Decimal("0.00"),
|
||
credit_amount_inr: Decimal = Decimal("0.00"),
|
||
running_balance_inr: Decimal = Decimal("0.00"),
|
||
reversal_of_id: Optional[str] = None,
|
||
narration: Optional[str] = None,
|
||
posting_date: Optional[datetime] = None,
|
||
entry_id: Optional[str] = None,
|
||
):
|
||
self.id = entry_id or str(uuid.uuid4())
|
||
self.tenant_id = tenant_id
|
||
self.party_id = party_id
|
||
self.party_type = party_type.upper()
|
||
if voucher_type.upper() not in VOUCHER_TYPES:
|
||
raise ValueError(f"Invalid voucher_type: {voucher_type}. Must be one of {VOUCHER_TYPES}")
|
||
self.voucher_type = voucher_type.upper()
|
||
self.voucher_number = voucher_number
|
||
self.debit_amount_inr = Decimal(str(debit_amount_inr)).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
|
||
self.credit_amount_inr = Decimal(str(credit_amount_inr)).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
|
||
self.running_balance_inr = Decimal(str(running_balance_inr)).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
|
||
self.reversal_of_id = reversal_of_id
|
||
self.narration = narration
|
||
self.posting_date = posting_date or datetime.now(timezone.utc)
|
||
self.created_at = datetime.now(timezone.utc)
|
||
|
||
def to_dict(self) -> Dict[str, Any]:
|
||
return {
|
||
"id": self.id,
|
||
"tenant_id": self.tenant_id,
|
||
"party_id": self.party_id,
|
||
"party_type": self.party_type,
|
||
"posting_date": self.posting_date.isoformat() if isinstance(self.posting_date, datetime) else self.posting_date,
|
||
"voucher_type": self.voucher_type,
|
||
"voucher_number": self.voucher_number,
|
||
"debit_amount_inr": float(self.debit_amount_inr),
|
||
"credit_amount_inr": float(self.credit_amount_inr),
|
||
"running_balance_inr": float(self.running_balance_inr),
|
||
"reversal_of_id": self.reversal_of_id,
|
||
"narration": self.narration,
|
||
"created_at": self.created_at.isoformat() if isinstance(self.created_at, datetime) else self.created_at,
|
||
}
|
||
|
||
|
||
class CreditDispatchLock(Base):
|
||
"""Credit breach dispatch lock blocking outbound shipments when credit exposure > 100%."""
|
||
__tablename__ = "credit_dispatch_locks"
|
||
__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)
|
||
customer_id = Column(String(36), nullable=False, index=True)
|
||
exposure_ratio_pct = Column(Numeric(6, 2), nullable=False)
|
||
sanctioned_limit_inr = Column(Numeric(14, 2), nullable=False)
|
||
outstanding_balance_inr = Column(Numeric(14, 2), nullable=False)
|
||
status = Column(String(32), default="LOCKED")
|
||
lock_reason = Column(String(255), nullable=False)
|
||
overridden_by = Column(String(64), nullable=True)
|
||
override_justification = Column(String(500), nullable=True)
|
||
overridden_at = Column(DateTime, nullable=True)
|
||
created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
|
||
|
||
def __init__(
|
||
self,
|
||
tenant_id: str,
|
||
customer_id: str,
|
||
exposure_ratio_pct: Decimal,
|
||
sanctioned_limit_inr: Decimal,
|
||
outstanding_balance_inr: Decimal,
|
||
lock_reason: Optional[str] = None,
|
||
status: str = "LOCKED",
|
||
lock_id: Optional[str] = None,
|
||
):
|
||
self.id = lock_id or str(uuid.uuid4())
|
||
self.tenant_id = tenant_id
|
||
self.customer_id = customer_id
|
||
self.exposure_ratio_pct = Decimal(str(exposure_ratio_pct)).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
|
||
self.sanctioned_limit_inr = Decimal(str(sanctioned_limit_inr)).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
|
||
self.outstanding_balance_inr = Decimal(str(outstanding_balance_inr)).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
|
||
self.lock_reason = lock_reason or f"Credit exposure {self.exposure_ratio_pct}% exceeds sanctioned limit 100%"
|
||
self.status = status.upper()
|
||
self.overridden_by = None
|
||
self.override_justification = None
|
||
self.overridden_at = None
|
||
self.created_at = datetime.now(timezone.utc)
|
||
|
||
def override(self, user_role: str, user_name: str, justification: str) -> None:
|
||
"""Apply Partner / MD electronic override with mandatory justification."""
|
||
valid_partner_roles = {"Partner / MD", "PARTNER_MD", "Partner", "MD", "Tenant Administrator"}
|
||
if user_role not in valid_partner_roles:
|
||
raise PermissionError("Only Partner / MD role can override credit breach dispatch locks")
|
||
if not justification or len(justification.strip()) < 15:
|
||
raise ValueError("Override justification must be at least 15 characters long")
|
||
self.status = "OVERRIDDEN"
|
||
self.overridden_by = user_name
|
||
self.override_justification = justification.strip()
|
||
self.overridden_at = datetime.now(timezone.utc)
|
||
|
||
def release(self) -> None:
|
||
"""Release lock when credit exposure returns to <= 100%."""
|
||
self.status = "RELEASED"
|
||
|
||
def to_dict(self) -> Dict[str, Any]:
|
||
return {
|
||
"id": self.id,
|
||
"tenant_id": self.tenant_id,
|
||
"customer_id": self.customer_id,
|
||
"exposure_ratio_pct": float(self.exposure_ratio_pct),
|
||
"sanctioned_limit_inr": float(self.sanctioned_limit_inr),
|
||
"outstanding_balance_inr": float(self.outstanding_balance_inr),
|
||
"status": self.status,
|
||
"lock_reason": self.lock_reason,
|
||
"overridden_by": self.overridden_by,
|
||
"override_justification": self.override_justification,
|
||
"overridden_at": self.overridden_at.isoformat() if isinstance(self.overridden_at, datetime) else self.overridden_at,
|
||
"created_at": self.created_at.isoformat() if isinstance(self.created_at, datetime) else self.created_at,
|
||
}
|
||
|
||
|
||
class CustomerPaymentReceipt(Base):
|
||
"""Customer payment receipt with instrument clearance and atomic bounce reversal FSM."""
|
||
__tablename__ = "customer_payment_receipts"
|
||
__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)
|
||
receipt_number = Column(String(32), nullable=False, unique=True, index=True)
|
||
customer_id = Column(String(36), nullable=False, index=True)
|
||
receipt_date = Column(DateTime, default=lambda: datetime.now(timezone.utc))
|
||
amount_inr = Column(Numeric(14, 2), nullable=False)
|
||
payment_mode = Column(String(32), nullable=False)
|
||
instrument_ref = Column(String(64), nullable=False)
|
||
bank_name = Column(String(64), nullable=True)
|
||
bank_account_id = Column(String(36), nullable=True)
|
||
status = Column(String(32), default="PENDING_CLEARANCE")
|
||
bounce_reason = Column(String(255), nullable=True)
|
||
bounced_at = Column(DateTime, nullable=True)
|
||
cleared_at = Column(DateTime, nullable=True)
|
||
created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
|
||
|
||
def __init__(
|
||
self,
|
||
tenant_id: str,
|
||
receipt_number: str,
|
||
customer_id: str,
|
||
amount_inr: Decimal,
|
||
payment_mode: str,
|
||
instrument_ref: str,
|
||
bank_name: Optional[str] = None,
|
||
bank_account_id: Optional[str] = None,
|
||
status: str = "PENDING_CLEARANCE",
|
||
receipt_date: Optional[datetime] = None,
|
||
receipt_id: Optional[str] = None,
|
||
):
|
||
self.id = receipt_id or str(uuid.uuid4())
|
||
self.tenant_id = tenant_id
|
||
self.receipt_number = receipt_number
|
||
self.customer_id = customer_id
|
||
amt = Decimal(str(amount_inr)).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
|
||
if amt <= Decimal("0.00"):
|
||
raise ValueError(f"Receipt amount must be positive, got {amt}")
|
||
self.amount_inr = amt
|
||
mode = payment_mode.upper()
|
||
if mode not in PAYMENT_MODES:
|
||
raise ValueError(f"Invalid payment mode: {payment_mode}. Must be one of {PAYMENT_MODES}")
|
||
self.payment_mode = mode
|
||
if not instrument_ref or not instrument_ref.strip():
|
||
raise ValueError("Instrument reference (UTR/Cheque/Ref) is mandatory")
|
||
self.instrument_ref = instrument_ref.strip()
|
||
self.bank_name = bank_name
|
||
self.bank_account_id = bank_account_id
|
||
self.status = status.upper()
|
||
self.bounce_reason = None
|
||
self.bounced_at = None
|
||
self.cleared_at = datetime.now(timezone.utc) if self.status == "CLEARED" else None
|
||
self.receipt_date = receipt_date or datetime.now(timezone.utc)
|
||
self.created_at = datetime.now(timezone.utc)
|
||
|
||
def mark_cleared(self) -> None:
|
||
"""Clear payment instrument."""
|
||
if self.status == "BOUNCED":
|
||
raise ValueError("Cannot clear a bounced instrument")
|
||
self.status = "CLEARED"
|
||
self.cleared_at = datetime.now(timezone.utc)
|
||
|
||
def mark_bounced(self, reason: str = "Insufficient Funds") -> None:
|
||
"""Mark instrument as bounced (clearing reversal)."""
|
||
if self.status == "BOUNCED":
|
||
raise ValueError("Receipt is already in BOUNCED status")
|
||
self.status = "BOUNCED"
|
||
self.bounce_reason = reason or "Instrument bounced / returned unpaid"
|
||
self.bounced_at = datetime.now(timezone.utc)
|
||
|
||
def to_dict(self) -> Dict[str, Any]:
|
||
return {
|
||
"id": self.id,
|
||
"tenant_id": self.tenant_id,
|
||
"receipt_number": self.receipt_number,
|
||
"customer_id": self.customer_id,
|
||
"receipt_date": self.receipt_date.isoformat() if isinstance(self.receipt_date, datetime) else self.receipt_date,
|
||
"amount_inr": float(self.amount_inr),
|
||
"payment_mode": self.payment_mode,
|
||
"instrument_ref": self.instrument_ref,
|
||
"bank_name": self.bank_name,
|
||
"bank_account_id": self.bank_account_id,
|
||
"status": self.status,
|
||
"bounce_reason": self.bounce_reason,
|
||
"bounced_at": self.bounced_at.isoformat() if isinstance(self.bounced_at, datetime) else self.bounced_at,
|
||
"cleared_at": self.cleared_at.isoformat() if isinstance(self.cleared_at, datetime) else self.cleared_at,
|
||
"created_at": self.created_at.isoformat() if isinstance(self.created_at, datetime) else self.created_at,
|
||
}
|
||
|
||
|
||
class SupplierPayable(Base):
|
||
"""Supplier accounts payable liability generated from accepted GRNs."""
|
||
__tablename__ = "supplier_payables"
|
||
__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)
|
||
supplier_id = Column(String(36), nullable=False, index=True)
|
||
grn_number = Column(String(64), nullable=False, index=True)
|
||
sauda_reference = Column(String(64), nullable=True)
|
||
invoice_amount_inr = Column(Numeric(14, 2), nullable=False)
|
||
paid_amount_inr = Column(Numeric(14, 2), default=Decimal("0.00"))
|
||
outstanding_amount_inr = Column(Numeric(14, 2), nullable=False)
|
||
grn_date = Column(DateTime, nullable=False)
|
||
credit_days = Column(Integer, default=DEFAULT_SUPPLIER_CREDIT_DAYS)
|
||
due_date = Column(DateTime, nullable=False)
|
||
status = Column(String(32), default="UNPAID")
|
||
created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
|
||
|
||
def __init__(
|
||
self,
|
||
tenant_id: str,
|
||
supplier_id: str,
|
||
grn_number: str,
|
||
invoice_amount_inr: Decimal,
|
||
grn_date: datetime,
|
||
credit_days: int = DEFAULT_SUPPLIER_CREDIT_DAYS,
|
||
sauda_reference: Optional[str] = None,
|
||
paid_amount_inr: Decimal = Decimal("0.00"),
|
||
payable_id: Optional[str] = None,
|
||
):
|
||
self.id = payable_id or str(uuid.uuid4())
|
||
self.tenant_id = tenant_id
|
||
self.supplier_id = supplier_id
|
||
self.grn_number = grn_number
|
||
self.sauda_reference = sauda_reference
|
||
amt = Decimal(str(invoice_amount_inr)).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
|
||
if amt <= Decimal("0.00"):
|
||
raise ValueError(f"Payable invoice amount must be positive, got {amt}")
|
||
self.invoice_amount_inr = amt
|
||
paid = Decimal(str(paid_amount_inr)).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
|
||
self.paid_amount_inr = paid
|
||
self.outstanding_amount_inr = (self.invoice_amount_inr - self.paid_amount_inr).quantize(
|
||
Decimal("0.01"), rounding=ROUND_HALF_UP
|
||
)
|
||
self.grn_date = grn_date
|
||
self.credit_days = max(0, credit_days)
|
||
self.due_date = self.grn_date + timedelta(days=self.credit_days)
|
||
self._update_status()
|
||
self.created_at = datetime.now(timezone.utc)
|
||
|
||
def _update_status(self) -> None:
|
||
if self.outstanding_amount_inr <= Decimal("0.00"):
|
||
self.status = "PAID"
|
||
elif self.paid_amount_inr > Decimal("0.00"):
|
||
self.status = "PARTIALLY_PAID"
|
||
else:
|
||
self.status = "UNPAID"
|
||
|
||
def record_payment(self, amount_inr: Decimal) -> Decimal:
|
||
"""Apply disbursement payment to reduce payable liability."""
|
||
amt = Decimal(str(amount_inr)).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
|
||
if amt <= Decimal("0.00"):
|
||
raise ValueError(f"Payment amount must be positive, got {amt}")
|
||
if amt > self.outstanding_amount_inr:
|
||
raise ValueError(
|
||
f"Disbursement INR {amt} exceeds outstanding balance INR {self.outstanding_amount_inr}"
|
||
)
|
||
self.paid_amount_inr = (self.paid_amount_inr + amt).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
|
||
self.outstanding_amount_inr = (self.invoice_amount_inr - self.paid_amount_inr).quantize(
|
||
Decimal("0.01"), rounding=ROUND_HALF_UP
|
||
)
|
||
self._update_status()
|
||
return self.outstanding_amount_inr
|
||
|
||
def get_aging_bucket(self, as_of_date: Optional[datetime] = None) -> str:
|
||
"""Classify into aging buckets based on due date:
|
||
- Current (Not Due)
|
||
- 1–7 days overdue
|
||
- 8–15 days overdue
|
||
- >15 days overdue
|
||
"""
|
||
ref_date = as_of_date or datetime.now(timezone.utc)
|
||
if ref_date <= self.due_date:
|
||
return "CURRENT"
|
||
days_overdue = (ref_date - self.due_date).days
|
||
if days_overdue <= 7:
|
||
return "1_TO_7_DAYS"
|
||
elif days_overdue <= 15:
|
||
return "8_TO_15_DAYS"
|
||
else:
|
||
return "OVER_15_DAYS"
|
||
|
||
def to_dict(self) -> Dict[str, Any]:
|
||
return {
|
||
"id": self.id,
|
||
"tenant_id": self.tenant_id,
|
||
"supplier_id": self.supplier_id,
|
||
"grn_number": self.grn_number,
|
||
"sauda_reference": self.sauda_reference,
|
||
"invoice_amount_inr": float(self.invoice_amount_inr),
|
||
"paid_amount_inr": float(self.paid_amount_inr),
|
||
"outstanding_amount_inr": float(self.outstanding_amount_inr),
|
||
"grn_date": self.grn_date.isoformat() if isinstance(self.grn_date, datetime) else self.grn_date,
|
||
"credit_days": self.credit_days,
|
||
"due_date": self.due_date.isoformat() if isinstance(self.due_date, datetime) else self.due_date,
|
||
"status": self.status,
|
||
"aging_bucket": self.get_aging_bucket(),
|
||
"created_at": self.created_at.isoformat() if isinstance(self.created_at, datetime) else self.created_at,
|
||
}
|
||
|
||
|
||
class SupplierDisbursement(Base):
|
||
"""Disbursement payment to suppliers reducing accounts payable."""
|
||
__tablename__ = "supplier_disbursements"
|
||
__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)
|
||
disbursement_number = Column(String(32), nullable=False, unique=True, index=True)
|
||
payable_id = Column(String(36), nullable=False, index=True)
|
||
supplier_id = Column(String(36), nullable=False, index=True)
|
||
amount_inr = Column(Numeric(14, 2), nullable=False)
|
||
disbursement_date = Column(DateTime, default=lambda: datetime.now(timezone.utc))
|
||
payment_mode = Column(String(32), nullable=False)
|
||
bank_reference = Column(String(64), nullable=False)
|
||
created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
|
||
|
||
def __init__(
|
||
self,
|
||
tenant_id: str,
|
||
disbursement_number: str,
|
||
payable_id: str,
|
||
supplier_id: str,
|
||
amount_inr: Decimal,
|
||
payment_mode: str,
|
||
bank_reference: str,
|
||
disbursement_date: Optional[datetime] = None,
|
||
disbursement_id: Optional[str] = None,
|
||
):
|
||
self.id = disbursement_id or str(uuid.uuid4())
|
||
self.tenant_id = tenant_id
|
||
self.disbursement_number = disbursement_number
|
||
self.payable_id = payable_id
|
||
self.supplier_id = supplier_id
|
||
amt = Decimal(str(amount_inr)).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
|
||
if amt <= Decimal("0.00"):
|
||
raise ValueError(f"Disbursement amount must be positive, got {amt}")
|
||
self.amount_inr = amt
|
||
mode = payment_mode.upper()
|
||
if mode not in PAYMENT_MODES:
|
||
raise ValueError(f"Invalid payment mode: {payment_mode}. Must be one of {PAYMENT_MODES}")
|
||
self.payment_mode = mode
|
||
if not bank_reference or not bank_reference.strip():
|
||
raise ValueError("Bank reference is mandatory")
|
||
self.bank_reference = bank_reference.strip()
|
||
self.disbursement_date = disbursement_date or datetime.now(timezone.utc)
|
||
self.created_at = datetime.now(timezone.utc)
|
||
|
||
def to_dict(self) -> Dict[str, Any]:
|
||
return {
|
||
"id": self.id,
|
||
"tenant_id": self.tenant_id,
|
||
"disbursement_number": self.disbursement_number,
|
||
"payable_id": self.payable_id,
|
||
"supplier_id": self.supplier_id,
|
||
"amount_inr": float(self.amount_inr),
|
||
"disbursement_date": self.disbursement_date.isoformat() if isinstance(self.disbursement_date, datetime) else self.disbursement_date,
|
||
"payment_mode": self.payment_mode,
|
||
"bank_reference": self.bank_reference,
|
||
"created_at": self.created_at.isoformat() if isinstance(self.created_at, datetime) else self.created_at,
|
||
}
|
||
|
||
|
||
class CashBankAccount(Base):
|
||
"""Cash chest or bank asset account for Mandi operating expenditures."""
|
||
__tablename__ = "cash_bank_accounts"
|
||
__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)
|
||
account_code = Column(String(32), nullable=False, unique=True, index=True)
|
||
account_name = Column(String(128), nullable=False)
|
||
account_type = Column(String(32), nullable=False) # "BANK" or "CASH"
|
||
bank_name = Column(String(64), nullable=True)
|
||
account_number = Column(String(64), nullable=True)
|
||
current_balance_inr = Column(Numeric(14, 2), nullable=False, default=Decimal("0.00"))
|
||
is_active = Column(Boolean, default=True)
|
||
created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
|
||
|
||
def __init__(
|
||
self,
|
||
tenant_id: str,
|
||
account_code: str,
|
||
account_name: str,
|
||
account_type: str,
|
||
current_balance_inr: Decimal = Decimal("0.00"),
|
||
bank_name: Optional[str] = None,
|
||
account_number: Optional[str] = None,
|
||
is_active: bool = True,
|
||
account_id: Optional[str] = None,
|
||
):
|
||
self.id = account_id or str(uuid.uuid4())
|
||
self.tenant_id = tenant_id
|
||
self.account_code = account_code
|
||
self.account_name = account_name
|
||
self.account_type = account_type.upper()
|
||
self.bank_name = bank_name
|
||
self.account_number = account_number
|
||
self.current_balance_inr = Decimal(str(current_balance_inr)).quantize(
|
||
Decimal("0.01"), rounding=ROUND_HALF_UP
|
||
)
|
||
self.is_active = is_active
|
||
self.created_at = datetime.now(timezone.utc)
|
||
|
||
def credit(self, amount_inr: Decimal) -> Decimal:
|
||
amt = Decimal(str(amount_inr)).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
|
||
self.current_balance_inr = (self.current_balance_inr + amt).quantize(
|
||
Decimal("0.01"), rounding=ROUND_HALF_UP
|
||
)
|
||
return self.current_balance_inr
|
||
|
||
def debit(self, amount_inr: Decimal) -> Decimal:
|
||
amt = Decimal(str(amount_inr)).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
|
||
if self.current_balance_inr < amt:
|
||
raise ValueError(
|
||
f"Insufficient funds in {self.account_code}. Available: INR {self.current_balance_inr}, Requested: INR {amt}"
|
||
)
|
||
self.current_balance_inr = (self.current_balance_inr - amt).quantize(
|
||
Decimal("0.01"), rounding=ROUND_HALF_UP
|
||
)
|
||
return self.current_balance_inr
|
||
|
||
def to_dict(self) -> Dict[str, Any]:
|
||
return {
|
||
"id": self.id,
|
||
"tenant_id": self.tenant_id,
|
||
"account_code": self.account_code,
|
||
"account_name": self.account_name,
|
||
"account_type": self.account_type,
|
||
"bank_name": self.bank_name,
|
||
"account_number": self.account_number,
|
||
"current_balance_inr": float(self.current_balance_inr),
|
||
"is_active": self.is_active,
|
||
"created_at": self.created_at.isoformat() if isinstance(self.created_at, datetime) else self.created_at,
|
||
}
|
||
|
||
|
||
class MandiExpenseVoucher(Base):
|
||
"""Mandi daily operating expense voucher with double-entry balancing invariant."""
|
||
__tablename__ = "mandi_expense_vouchers"
|
||
__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)
|
||
voucher_number = Column(String(32), nullable=False, unique=True, index=True)
|
||
voucher_date = Column(DateTime, default=lambda: datetime.now(timezone.utc))
|
||
expense_category = Column(String(64), nullable=False)
|
||
amount_inr = Column(Numeric(14, 2), nullable=False)
|
||
payee_name = Column(String(128), nullable=False)
|
||
linked_consignment_id = Column(String(64), nullable=True)
|
||
linked_sauda_id = Column(String(64), nullable=True)
|
||
payment_mode = Column(String(32), nullable=False)
|
||
debit_account = Column(String(64), nullable=False)
|
||
credit_account = Column(String(64), nullable=False)
|
||
status = Column(String(32), default="POSTED")
|
||
narration = Column(String(255), nullable=True)
|
||
created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
|
||
|
||
def __init__(
|
||
self,
|
||
tenant_id: str,
|
||
voucher_number: str,
|
||
expense_category: str,
|
||
amount_inr: Decimal,
|
||
payee_name: str,
|
||
payment_mode: str,
|
||
debit_account: str,
|
||
credit_account: str,
|
||
debit_amount_inr: Optional[Decimal] = None,
|
||
credit_amount_inr: Optional[Decimal] = None,
|
||
linked_consignment_id: Optional[str] = None,
|
||
linked_sauda_id: Optional[str] = None,
|
||
narration: Optional[str] = None,
|
||
voucher_date: Optional[datetime] = None,
|
||
status: str = "POSTED",
|
||
voucher_id: Optional[str] = None,
|
||
):
|
||
self.id = voucher_id or str(uuid.uuid4())
|
||
self.tenant_id = tenant_id
|
||
self.voucher_number = voucher_number
|
||
cat = expense_category.upper()
|
||
if cat not in EXPENSE_CATEGORIES:
|
||
raise ValueError(
|
||
f"Invalid expense category: '{expense_category}'. "
|
||
f"Must be one of {list(EXPENSE_CATEGORIES.keys())}"
|
||
)
|
||
self.expense_category = cat
|
||
amt = Decimal(str(amount_inr)).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
|
||
if amt <= Decimal("0.00"):
|
||
raise ValueError(f"Expense voucher amount must be positive, got {amt}")
|
||
self.amount_inr = amt
|
||
|
||
# Double-entry balancing invariant enforcement:
|
||
# Debit Amount must equal Credit Amount, and both must equal Voucher Amount
|
||
deb_amt = Decimal(str(debit_amount_inr if debit_amount_inr is not None else amt)).quantize(
|
||
Decimal("0.01"), rounding=ROUND_HALF_UP
|
||
)
|
||
cred_amt = Decimal(str(credit_amount_inr if credit_amount_inr is not None else amt)).quantize(
|
||
Decimal("0.01"), rounding=ROUND_HALF_UP
|
||
)
|
||
if deb_amt != cred_amt or deb_amt != amt:
|
||
raise ValueError(
|
||
f"Double-entry balancing failed: Debit INR {deb_amt} != Credit INR {cred_amt} "
|
||
f"(Voucher Amount: INR {amt})"
|
||
)
|
||
|
||
if not payee_name or not payee_name.strip():
|
||
raise ValueError("Payee/Vendor name is mandatory")
|
||
self.payee_name = payee_name.strip()
|
||
mode = payment_mode.upper()
|
||
if mode not in PAYMENT_MODES:
|
||
raise ValueError(f"Invalid payment mode: {payment_mode}. Must be one of {PAYMENT_MODES}")
|
||
self.payment_mode = mode
|
||
if not debit_account or not debit_account.strip():
|
||
raise ValueError("Debit account identifier is mandatory")
|
||
self.debit_account = debit_account.strip()
|
||
if not credit_account or not credit_account.strip():
|
||
raise ValueError("Credit cash/bank account identifier is mandatory")
|
||
self.credit_account = credit_account.strip()
|
||
self.linked_consignment_id = linked_consignment_id
|
||
self.linked_sauda_id = linked_sauda_id
|
||
self.narration = narration
|
||
self.status = status.upper()
|
||
self.voucher_date = voucher_date or datetime.now(timezone.utc)
|
||
self.created_at = datetime.now(timezone.utc)
|
||
|
||
def to_dict(self) -> Dict[str, Any]:
|
||
return {
|
||
"id": self.id,
|
||
"tenant_id": self.tenant_id,
|
||
"voucher_number": self.voucher_number,
|
||
"voucher_date": self.voucher_date.isoformat() if isinstance(self.voucher_date, datetime) else self.voucher_date,
|
||
"expense_category": self.expense_category,
|
||
"category_label": EXPENSE_CATEGORIES.get(self.expense_category, self.expense_category),
|
||
"amount_inr": float(self.amount_inr),
|
||
"payee_name": self.payee_name,
|
||
"linked_consignment_id": self.linked_consignment_id,
|
||
"linked_sauda_id": self.linked_sauda_id,
|
||
"payment_mode": self.payment_mode,
|
||
"debit_account": self.debit_account,
|
||
"credit_account": self.credit_account,
|
||
"status": self.status,
|
||
"narration": self.narration,
|
||
"created_at": self.created_at.isoformat() if isinstance(self.created_at, datetime) else self.created_at,
|
||
}
|
||
|
||
|
||
# =============================================================================
|
||
# Pure Computation & Valuation Functions
|
||
# =============================================================================
|
||
|
||
def compute_exposure_metrics(
|
||
sanctioned_limit_inr: Decimal,
|
||
current_outstanding_inr: Decimal,
|
||
) -> Dict[str, Any]:
|
||
"""Computes customer credit exposure ratio and risk state:
|
||
- NORMAL: < 80.0%
|
||
- WATCH: >= 80.0% and <= 100.0%
|
||
- CRITICAL: > 100.0%
|
||
"""
|
||
limit = Decimal(str(sanctioned_limit_inr)).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
|
||
outstanding = Decimal(str(current_outstanding_inr)).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
|
||
|
||
if limit <= Decimal("0.00"):
|
||
ratio = Decimal("100.00") if outstanding > Decimal("0.00") else Decimal("0.00")
|
||
else:
|
||
ratio = ((outstanding / limit) * Decimal("100.0")).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
|
||
|
||
if ratio > CREDIT_LOCK_THRESHOLD_PCT:
|
||
risk_flag = "CRITICAL"
|
||
dispatch_lock_required = True
|
||
watch_alert = True
|
||
elif ratio >= CREDIT_WATCH_THRESHOLD_PCT:
|
||
risk_flag = "WATCH"
|
||
dispatch_lock_required = False
|
||
watch_alert = True
|
||
else:
|
||
risk_flag = "NORMAL"
|
||
dispatch_lock_required = False
|
||
watch_alert = False
|
||
|
||
return {
|
||
"sanctioned_limit_inr": float(limit),
|
||
"current_outstanding_inr": float(outstanding),
|
||
"exposure_ratio_pct": float(ratio),
|
||
"risk_flag": risk_flag,
|
||
"watch_alert": watch_alert,
|
||
"dispatch_lock_required": dispatch_lock_required,
|
||
}
|
||
|
||
|
||
def compute_customer_aging(
|
||
invoices: List[Dict[str, Any]],
|
||
as_of_date: Optional[datetime] = None,
|
||
) -> Dict[str, Any]:
|
||
"""Computes 4-bucket aging schedule for customer unpaid receivables:
|
||
- 0–7 days
|
||
- 8–15 days
|
||
- 16–30 days
|
||
- >30 days
|
||
"""
|
||
ref_date = as_of_date or datetime.now(timezone.utc)
|
||
buckets = {
|
||
"0_TO_7_DAYS": Decimal("0.00"),
|
||
"8_TO_15_DAYS": Decimal("0.00"),
|
||
"16_TO_30_DAYS": Decimal("0.00"),
|
||
"OVER_30_DAYS": Decimal("0.00"),
|
||
}
|
||
total_due = Decimal("0.00")
|
||
|
||
for inv in invoices:
|
||
balance = Decimal(str(inv.get("balance_inr", 0.00))).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
|
||
if balance <= Decimal("0.00"):
|
||
continue
|
||
inv_date = inv.get("date")
|
||
if isinstance(inv_date, str):
|
||
inv_date = datetime.fromisoformat(inv_date.replace("Z", "+00:00"))
|
||
elif not isinstance(inv_date, datetime):
|
||
inv_date = ref_date
|
||
|
||
days = (ref_date - inv_date).days
|
||
if days < 0:
|
||
days = 0
|
||
|
||
total_due += balance
|
||
if days <= 7:
|
||
buckets["0_TO_7_DAYS"] += balance
|
||
elif days <= 15:
|
||
buckets["8_TO_15_DAYS"] += balance
|
||
elif days <= 30:
|
||
buckets["16_TO_30_DAYS"] += balance
|
||
else:
|
||
buckets["OVER_30_DAYS"] += balance
|
||
|
||
return {
|
||
"total_outstanding_inr": float(total_due),
|
||
"bucket_0_to_7_days_inr": float(buckets["0_TO_7_DAYS"]),
|
||
"bucket_8_to_15_days_inr": float(buckets["8_TO_15_DAYS"]),
|
||
"bucket_16_to_30_days_inr": float(buckets["16_TO_30_DAYS"]),
|
||
"bucket_over_30_days_inr": float(buckets["OVER_30_DAYS"]),
|
||
}
|
||
|