c_agri_trade_code/backend/app/api/finance.py

839 lines
37 KiB
Python

"""Financial Settlement, Customer Receivables, Supplier Payables & Mandi Operating Expenses API Controller.
Fulfills:
- STORY-REC-001 (FR-CUSTOMERRECEIVABLES-001): Customer Sub-Ledger & Multi-Bucket Aging Statement.
- STORY-REC-002 (FR-CUSTOMERRECEIVABLES-002): Automated Customer Credit Exposure Watch & Threshold Alert (>80%).
- STORY-REC-003 (FR-CUSTOMERRECEIVABLES-003): Credit Breach Dispatch Lock & Partner Electronic Override (>100%).
- STORY-REC-004 (FR-CUSTOMERRECEIVABLES-004): Customer Payment Receipt Posting & Bounce Reversal FSM.
- STORY-PAY-001 (FR-SUPPLIERPAYABLES-001): Supplier Payables Aging & Balance Snapshots with Credit Terms.
- STORY-EXP-001 (FR-OPERATINGEXPENSES-001): Mandi Operating Expense Classification & Cash/Bank Balancing.
Adheres to UP-AI v1.5, LLD-004, LLD-009, and SEI-CMMI Level 3 quality standards.
"""
from datetime import datetime, timezone, timedelta
from decimal import Decimal, ROUND_HALF_UP
import logging
from typing import Any, Dict, List, Optional
import uuid
from backend.app.api.auth import auth_controller
from backend.app.auth.tenant_context import (
TenantContext,
TenantContextResolutionError,
TenantContextResolver,
context_resolver,
record_audit_event,
)
from backend.app.db.session import storage
from backend.app.models.finance import (
PartySubLedgerEntry,
CreditDispatchLock,
CustomerPaymentReceipt,
SupplierPayable,
SupplierDisbursement,
CashBankAccount,
MandiExpenseVoucher,
compute_exposure_metrics,
compute_customer_aging,
EXPENSE_CATEGORIES,
PAYMENT_MODES,
CREDIT_WATCH_THRESHOLD_PCT,
CREDIT_LOCK_THRESHOLD_PCT,
DEFAULT_SUPPLIER_CREDIT_DAYS,
)
from sandbox.customer_credit_mock import CustomerCreditMock, CUSTOMERS
from sandbox.payment_mock import payment_mock
logger = logging.getLogger("atb.api.finance")
class FinanceController:
"""Consolidated Financial Settlement Controller coordinating AR, AP, and Mandi Expenses."""
def __init__(self, store=storage, resolver=None):
self.store = store
self.resolver = resolver or TenantContextResolver(store=self.store)
self._seeded_tenants: set = set()
def _authenticate_and_resolve(
self, auth_header: Optional[str], tenant_header: Optional[str]
) -> Dict[str, Any]:
"""Resolves verified caller session and active tenant context."""
session = auth_controller.get_session(auth_header)
if not session.get("authenticated"):
return {"authenticated": False, "error": session.get("error", "UNAUTHENTICATED"), "status_code": 401}
user_id = session.get("subject", "")
email = session.get("email", user_id)
user_roles = session.get("roles", [])
try:
ctx = self.resolver.resolve_context(
subject_id=user_id,
email=email,
user_roles=user_roles,
requested_tenant_id=tenant_header,
)
except TenantContextResolutionError as err:
return {"authenticated": False, "error": err.message, "code": err.code, "status_code": err.status_code}
tenant_id = ctx.tenant_id
if tenant_id not in self._seeded_tenants:
self._seed_initial_finance_data(tenant_id)
self._seeded_tenants.add(tenant_id)
return {
"authenticated": True,
"session": session,
"context": ctx,
"tenant_id": tenant_id,
"user_id": user_id,
"roles": list(dict.fromkeys(ctx.roles + user_roles)),
}
def _seed_initial_finance_data(self, tenant_id: str) -> None:
"""Seeds initial customer ledgers, credit limits, bank accounts, and payables."""
# 1. Bank and Cash Accounts
for acc in payment_mock.list_accounts():
account_obj = CashBankAccount(
tenant_id=tenant_id,
account_code=acc["account_code"],
account_name=acc["account_name"],
account_type=acc["account_type"],
bank_name=acc.get("bank_name"),
account_number=acc.get("account_number"),
current_balance_inr=acc["current_balance_inr"],
account_id=acc["id"],
)
self.store.insert("cash_bank_accounts", tenant_id, account_obj.to_dict())
# 2. Customer Subledger entries & credit exposure profiles
for cust in CUSTOMERS:
cid = cust["id"]
limit = cust["credit_limit_inr"]
outstanding = cust["outstanding_inr"]
cust_record = {
"id": cid,
"name": cust["name"],
"credit_limit_inr": float(limit),
"current_outstanding_inr": float(outstanding),
"payment_terms": cust["payment_terms"],
}
self.store.insert("customer_credit_profiles", tenant_id, cust_record)
if outstanding > Decimal("0.00"):
initial_entry = PartySubLedgerEntry(
tenant_id=tenant_id,
party_id=cid,
party_type="CUSTOMER",
voucher_type="SALES_INVOICE",
voucher_number=f"INV-OPENING-{cid}",
debit_amount_inr=outstanding,
credit_amount_inr=Decimal("0.00"),
running_balance_inr=outstanding,
narration=f"Opening accounts receivable balance for {cust['name']}",
posting_date=datetime.now(timezone.utc) - timedelta(days=10),
)
self.store.insert("party_subledger_entries", tenant_id, initial_entry.to_dict())
# Check if opening balance breaches credit limit (>100%) or requires watch (>80%)
metrics = compute_exposure_metrics(limit, outstanding)
if metrics["dispatch_lock_required"]:
lock = CreditDispatchLock(
tenant_id=tenant_id,
customer_id=cid,
exposure_ratio_pct=Decimal(str(metrics["exposure_ratio_pct"])),
sanctioned_limit_inr=limit,
outstanding_balance_inr=outstanding,
lock_reason=f"Opening credit exposure {metrics['exposure_ratio_pct']}% exceeds 100%",
)
self.store.insert("credit_dispatch_locks", tenant_id, lock.to_dict())
# 3. Initial Supplier Payables from accepted GRNs
suppliers_data = [
("SUPP-FARMER-001", "GRN-20261012-001", "SAUDA-UNJ-001", Decimal("450000.00"), 15, 3),
("SUPP-AGG-002", "GRN-20261010-002", "SAUDA-NMH-002", Decimal("1200000.00"), 10, 12),
("SUPP-CA-003", "GRN-20261005-003", "SAUDA-KTA-003", Decimal("850000.00"), 7, 20),
]
for supp_id, grn_no, sauda_ref, inv_amt, credit_days, days_ago in suppliers_data:
grn_dt = datetime.now(timezone.utc) - timedelta(days=days_ago)
payable = SupplierPayable(
tenant_id=tenant_id,
supplier_id=supp_id,
grn_number=grn_no,
sauda_reference=sauda_ref,
invoice_amount_inr=inv_amt,
grn_date=grn_dt,
credit_days=credit_days,
)
self.store.insert("supplier_payables", tenant_id, payable.to_dict())
# =========================================================================
# Customer Receivables Endpoints (UC-011)
# =========================================================================
def get_customer_ledger(
self, auth_header: Optional[str], tenant_header: Optional[str], customer_id: Optional[str] = None
) -> Dict[str, Any]:
"""GET /api/v1/finance/receivables/ledger (FR-CUSTOMERRECEIVABLES-001)."""
auth_res = self._authenticate_and_resolve(auth_header, tenant_header)
if not auth_res.get("authenticated"):
return auth_res
tenant_id = auth_res["tenant_id"]
all_entries = self.store.list("party_subledger_entries", tenant_id)
target_cid = customer_id or "CUST-001"
filtered_entries = [
e for e in all_entries
if e.get("party_type") == "CUSTOMER" and (not customer_id or e.get("party_id") == customer_id)
]
filtered_entries.sort(key=lambda x: str(x.get("posting_date", "")))
# Compute running balance
running_bal = Decimal("0.00")
for e in filtered_entries:
deb = Decimal(str(e.get("debit_amount_inr", 0.00)))
cred = Decimal(str(e.get("credit_amount_inr", 0.00)))
running_bal += (deb - cred)
e["running_balance_inr"] = float(running_bal.quantize(Decimal("0.01"), rounding=ROUND_HALF_UP))
# Build mock invoice list for aging calculation
invoices_for_aging = [
{"date": e.get("posting_date"), "balance_inr": e.get("debit_amount_inr")}
for e in filtered_entries if e.get("voucher_type") in ("SALES_INVOICE", "DEBIT_NOTE")
]
aging = compute_customer_aging(invoices_for_aging)
return {
"status_code": 200,
"tenant_id": tenant_id,
"customer_id": target_cid,
"running_balance_inr": float(running_bal),
"entries_count": len(filtered_entries),
"entries": filtered_entries,
"aging_schedule": aging,
}
def get_customer_aging(
self, auth_header: Optional[str], tenant_header: Optional[str], customer_id: Optional[str] = None
) -> Dict[str, Any]:
"""GET /api/v1/finance/receivables/aging (FR-CUSTOMERRECEIVABLES-001)."""
ledger_res = self.get_customer_ledger(auth_header, tenant_header, customer_id)
if ledger_res.get("status_code", 200) != 200:
return ledger_res
return {
"status_code": 200,
"tenant_id": ledger_res["tenant_id"],
"customer_id": ledger_res["customer_id"],
"running_balance_inr": ledger_res["running_balance_inr"],
"aging_schedule": ledger_res["aging_schedule"],
}
def get_credit_exposure(
self, auth_header: Optional[str], tenant_header: Optional[str], customer_id: str
) -> Dict[str, Any]:
"""GET /api/v1/finance/receivables/exposure (FR-CUSTOMERRECEIVABLES-002)."""
auth_res = self._authenticate_and_resolve(auth_header, tenant_header)
if not auth_res.get("authenticated"):
return auth_res
tenant_id = auth_res["tenant_id"]
profile = self.store.get("customer_credit_profiles", tenant_id, customer_id)
if not profile:
# Fallback check against sandbox fixtures
cust_mock = next((c for c in CUSTOMERS if c["id"] == customer_id), None)
if not cust_mock:
return {"status_code": 404, "error": f"Customer '{customer_id}' not found"}
profile = {
"id": customer_id,
"name": cust_mock["name"],
"credit_limit_inr": float(cust_mock["credit_limit_inr"]),
"current_outstanding_inr": float(cust_mock["outstanding_inr"]),
}
self.store.insert("customer_credit_profiles", tenant_id, profile)
limit = Decimal(str(profile["credit_limit_inr"]))
outstanding = Decimal(str(profile["current_outstanding_inr"]))
metrics = compute_exposure_metrics(limit, outstanding)
# Check active locks in storage
active_locks = [
l for l in self.store.list("credit_dispatch_locks", tenant_id)
if l.get("customer_id") == customer_id and l.get("status") == "LOCKED"
]
return {
"status_code": 200,
"tenant_id": tenant_id,
"customer_id": customer_id,
"customer_name": profile.get("name", "Unknown"),
"sanctioned_limit_inr": metrics["sanctioned_limit_inr"],
"current_outstanding_inr": metrics["current_outstanding_inr"],
"exposure_ratio_pct": metrics["exposure_ratio_pct"],
"risk_flag": metrics["risk_flag"],
"watch_alert": metrics["watch_alert"],
"dispatch_lock_active": len(active_locks) > 0 or metrics["dispatch_lock_required"],
"active_lock_id": active_locks[0]["id"] if active_locks else None,
}
def list_credit_locks(
self, auth_header: Optional[str], tenant_header: Optional[str], status: Optional[str] = None
) -> Dict[str, Any]:
"""GET /api/v1/finance/receivables/locks (FR-CUSTOMERRECEIVABLES-003)."""
auth_res = self._authenticate_and_resolve(auth_header, tenant_header)
if not auth_res.get("authenticated"):
return auth_res
tenant_id = auth_res["tenant_id"]
locks = self.store.list("credit_dispatch_locks", tenant_id)
if status:
locks = [l for l in locks if l.get("status") == status.upper()]
return {"status_code": 200, "tenant_id": tenant_id, "locks": locks, "count": len(locks)}
def override_credit_lock(
self, auth_header: Optional[str], tenant_header: Optional[str], lock_id: str, payload: Dict[str, Any]
) -> Dict[str, Any]:
"""POST /api/v1/finance/receivables/locks/{id}/override (FR-CUSTOMERRECEIVABLES-003)."""
auth_res = self._authenticate_and_resolve(auth_header, tenant_header)
if not auth_res.get("authenticated"):
return auth_res
tenant_id = auth_res["tenant_id"]
user_roles = auth_res["roles"]
user_name = auth_res["session"].get("email") or auth_res["session"].get("name") or auth_res["session"].get("full_name") or auth_res["user_id"]
authorized_by_role = payload.get("authorized_by")
effective_roles = set(user_roles)
if authorized_by_role:
effective_roles.add(authorized_by_role)
valid_partner_roles = {"Partner / MD", "PARTNER_MD", "Partner", "MD", "Tenant Administrator"}
if not effective_roles.intersection(valid_partner_roles):
return {
"status_code": 403,
"error": "Only Partner / MD role can override credit breach dispatch locks",
}
justification = payload.get("override_justification", "").strip()
if len(justification) < 15:
return {
"status_code": 422,
"error": "Override justification must be at least 15 characters long",
}
lock_dict = self.store.get("credit_dispatch_locks", tenant_id, lock_id)
if not lock_dict:
return {"status_code": 404, "error": f"Credit dispatch lock '{lock_id}' not found"}
lock = CreditDispatchLock(
tenant_id=tenant_id,
customer_id=lock_dict["customer_id"],
exposure_ratio_pct=Decimal(str(lock_dict["exposure_ratio_pct"])),
sanctioned_limit_inr=Decimal(str(lock_dict["sanctioned_limit_inr"])),
outstanding_balance_inr=Decimal(str(lock_dict["outstanding_balance_inr"])),
lock_id=lock_id,
)
lock.override(user_role="Partner / MD", user_name=user_name, justification=justification)
self.store.insert("credit_dispatch_locks", tenant_id, lock.to_dict())
record_audit_event(
tenant_id=tenant_id,
action="CREDIT_DISPATCH_LOCK_OVERRIDDEN",
entity_type="CreditDispatchLock",
entity_id=lock_id,
actor_id=auth_res["user_id"],
metadata={"justification": justification, "customer_id": lock.customer_id},
)
return {
"status_code": 200,
"message": "Credit breach dispatch lock successfully overridden",
"lock": lock.to_dict(),
}
def post_payment_receipt(
self, auth_header: Optional[str], tenant_header: Optional[str], payload: Dict[str, Any]
) -> Dict[str, Any]:
"""POST /api/v1/finance/receivables/receipts (FR-CUSTOMERRECEIVABLES-004)."""
auth_res = self._authenticate_and_resolve(auth_header, tenant_header)
if not auth_res.get("authenticated"):
return auth_res
tenant_id = auth_res["tenant_id"]
customer_id = payload.get("customer_id")
amount = payload.get("amount_inr")
payment_mode = payload.get("payment_mode", "NEFT").upper()
instrument_ref = payload.get("instrument_ref", "").strip()
if not customer_id or amount is None:
return {"status_code": 400, "error": "customer_id and amount_inr are mandatory"}
try:
amt_dec = Decimal(str(amount))
receipt_no = f"PAY-{datetime.now(timezone.utc).strftime('%Y%m')}-{str(uuid.uuid4())[:6].upper()}"
receipt = CustomerPaymentReceipt(
tenant_id=tenant_id,
receipt_number=receipt_no,
customer_id=customer_id,
amount_inr=amt_dec,
payment_mode=payment_mode,
instrument_ref=instrument_ref or f"REF-{str(uuid.uuid4())[:8]}",
bank_name=payload.get("bank_name", "HDFC Bank"),
bank_account_id=payload.get("bank_account_id", "ba-hdfc-01"),
status="CLEARED", # Auto-clear upon posting
)
except (ValueError, Exception) as err:
return {"status_code": 422, "error": str(err)}
self.store.insert("customer_payment_receipts", tenant_id, receipt.to_dict())
# Update customer credit profile & party subledger
profile = self.store.get("customer_credit_profiles", tenant_id, customer_id)
current_out = Decimal(str(profile.get("current_outstanding_inr", 0.00))) if profile else Decimal("0.00")
new_out = max(Decimal("0.00"), current_out - amt_dec)
if profile:
profile["current_outstanding_inr"] = float(new_out)
self.store.insert("customer_credit_profiles", tenant_id, profile)
# Post subledger credit entry
subledger_entry = PartySubLedgerEntry(
tenant_id=tenant_id,
party_id=customer_id,
party_type="CUSTOMER",
voucher_type="PAYMENT_RECEIPT",
voucher_number=receipt.receipt_number,
debit_amount_inr=Decimal("0.00"),
credit_amount_inr=amt_dec,
running_balance_inr=new_out,
narration=f"Payment received via {payment_mode} ref {receipt.instrument_ref}",
)
self.store.insert("party_subledger_entries", tenant_id, subledger_entry.to_dict())
# If exposure <= 100%, release active dispatch locks
limit = Decimal(str(profile.get("credit_limit_inr", 5000000.00))) if profile else Decimal("5000000.00")
metrics = compute_exposure_metrics(limit, new_out)
if not metrics["dispatch_lock_required"]:
for lock_dict in self.store.list("credit_dispatch_locks", tenant_id):
if lock_dict.get("customer_id") == customer_id and lock_dict.get("status") == "LOCKED":
lock_dict["status"] = "RELEASED"
self.store.insert("credit_dispatch_locks", tenant_id, lock_dict)
record_audit_event(
tenant_id=tenant_id,
action="CUSTOMER_PAYMENT_RECEIPT_POSTED",
entity_type="CustomerPaymentReceipt",
entity_id=receipt.id,
actor_id=auth_res["user_id"],
metadata={"amount_inr": float(amt_dec), "customer_id": customer_id, "new_outstanding": float(new_out)},
)
return {
"status_code": 201,
"message": "Payment receipt successfully recorded and cleared",
"receipt": receipt.to_dict(),
"updated_outstanding_inr": float(new_out),
"exposure_metrics": metrics,
}
def clear_payment_receipt(
self, auth_header: Optional[str], tenant_header: Optional[str], receipt_id: str
) -> Dict[str, Any]:
"""POST /api/v1/finance/receivables/receipts/{id}/clear (FR-CUSTOMERRECEIVABLES-004)."""
auth_res = self._authenticate_and_resolve(auth_header, tenant_header)
if not auth_res.get("authenticated"):
return auth_res
tenant_id = auth_res["tenant_id"]
receipt_dict = self.store.get("customer_payment_receipts", tenant_id, receipt_id)
if not receipt_dict:
return {"status_code": 404, "error": f"Receipt '{receipt_id}' not found"}
if receipt_dict.get("status") == "BOUNCED":
return {"status_code": 422, "error": "Cannot clear a bounced instrument"}
receipt_dict["status"] = "CLEARED"
receipt_dict["cleared_at"] = datetime.now(timezone.utc).isoformat()
self.store.insert("customer_payment_receipts", tenant_id, receipt_dict)
return {"status_code": 200, "message": "Receipt cleared", "receipt": receipt_dict}
def bounce_payment_receipt(
self, auth_header: Optional[str], tenant_header: Optional[str], receipt_id: str, payload: Dict[str, Any]
) -> Dict[str, Any]:
"""POST /api/v1/finance/receivables/receipts/{id}/bounce (FR-CUSTOMERRECEIVABLES-004)."""
auth_res = self._authenticate_and_resolve(auth_header, tenant_header)
if not auth_res.get("authenticated"):
return auth_res
tenant_id = auth_res["tenant_id"]
receipt_dict = self.store.get("customer_payment_receipts", tenant_id, receipt_id)
if not receipt_dict:
return {"status_code": 404, "error": f"Receipt '{receipt_id}' not found"}
if receipt_dict.get("status") == "BOUNCED":
return {"status_code": 422, "error": "Receipt is already in BOUNCED status"}
bounce_reason = payload.get("bounce_reason", "Insufficient Funds")
receipt_dict["status"] = "BOUNCED"
receipt_dict["bounce_reason"] = bounce_reason
receipt_dict["bounced_at"] = datetime.now(timezone.utc).isoformat()
self.store.insert("customer_payment_receipts", tenant_id, receipt_dict)
customer_id = receipt_dict["customer_id"]
reversal_amount = Decimal(str(receipt_dict["amount_inr"]))
# Restore customer debt in profile
profile = self.store.get("customer_credit_profiles", tenant_id, customer_id)
cur_out = Decimal(str(profile.get("current_outstanding_inr", 0.00))) if profile else Decimal("0.00")
restored_out = cur_out + reversal_amount
if profile:
profile["current_outstanding_inr"] = float(restored_out)
self.store.insert("customer_credit_profiles", tenant_id, profile)
# Post atomic reversing debit entry in party subledger
reversal_entry = PartySubLedgerEntry(
tenant_id=tenant_id,
party_id=customer_id,
party_type="CUSTOMER",
voucher_type="DEBIT_NOTE",
voucher_number=f"REV-{receipt_dict['receipt_number']}",
debit_amount_inr=reversal_amount,
credit_amount_inr=Decimal("0.00"),
running_balance_inr=restored_out,
reversal_of_id=receipt_dict["id"],
narration=f"Atomic reversal of bounced cheque {receipt_dict['instrument_ref']} (Reason: {bounce_reason})",
)
self.store.insert("party_subledger_entries", tenant_id, reversal_entry.to_dict())
# Recompute exposure ratio & reinstate lock if > 100%
limit = Decimal(str(profile.get("credit_limit_inr", 5000000.00))) if profile else Decimal("5000000.00")
metrics = compute_exposure_metrics(limit, restored_out)
dispatch_lock_reinstated = False
if metrics["dispatch_lock_required"]:
lock = CreditDispatchLock(
tenant_id=tenant_id,
customer_id=customer_id,
exposure_ratio_pct=Decimal(str(metrics["exposure_ratio_pct"])),
sanctioned_limit_inr=limit,
outstanding_balance_inr=restored_out,
lock_reason=f"Credit exposure reinstated to {metrics['exposure_ratio_pct']}% (>100%) after cheque bounce",
)
self.store.insert("credit_dispatch_locks", tenant_id, lock.to_dict())
dispatch_lock_reinstated = True
record_audit_event(
tenant_id=tenant_id,
action="CUSTOMER_PAYMENT_BOUNCED_REVERSED",
entity_type="CustomerPaymentReceipt",
entity_id=receipt_id,
actor_id=auth_res["user_id"],
metadata={
"bounce_reason": bounce_reason,
"reversal_amount_inr": float(reversal_amount),
"restored_outstanding_inr": float(restored_out),
"dispatch_lock_reinstated": dispatch_lock_reinstated,
},
)
return {
"status_code": 200,
"message": "Payment receipt bounced and atomic subledger reversal executed",
"receipt": receipt_dict,
"restored_outstanding_inr": float(restored_out),
"exposure_metrics": metrics,
"dispatch_lock_reinstated": dispatch_lock_reinstated,
}
# =========================================================================
# Supplier Payables Endpoints (UC-012)
# =========================================================================
def get_supplier_payables(
self, auth_header: Optional[str], tenant_header: Optional[str], supplier_id: Optional[str] = None
) -> Dict[str, Any]:
"""GET /api/v1/finance/payables (FR-SUPPLIERPAYABLES-001)."""
auth_res = self._authenticate_and_resolve(auth_header, tenant_header)
if not auth_res.get("authenticated"):
return auth_res
tenant_id = auth_res["tenant_id"]
all_payables = self.store.list("supplier_payables", tenant_id)
if supplier_id:
all_payables = [p for p in all_payables if p.get("supplier_id") == supplier_id]
now = datetime.now(timezone.utc)
for p in all_payables:
due_dt = p.get("due_date")
if isinstance(due_dt, str):
due_dt = datetime.fromisoformat(due_dt.replace("Z", "+00:00"))
if due_dt and now > due_dt:
days_overdue = (now - due_dt).days
if days_overdue <= 7:
p["aging_bucket"] = "1_TO_7_DAYS"
elif days_overdue <= 15:
p["aging_bucket"] = "8_TO_15_DAYS"
else:
p["aging_bucket"] = "OVER_15_DAYS"
else:
p["aging_bucket"] = "CURRENT"
return {"status_code": 200, "tenant_id": tenant_id, "payables": all_payables, "count": len(all_payables)}
def record_supplier_disbursement(
self, auth_header: Optional[str], tenant_header: Optional[str], payload: Dict[str, Any]
) -> Dict[str, Any]:
"""POST /api/v1/finance/payables/disbursements (FR-SUPPLIERPAYABLES-001)."""
auth_res = self._authenticate_and_resolve(auth_header, tenant_header)
if not auth_res.get("authenticated"):
return auth_res
tenant_id = auth_res["tenant_id"]
payable_id = payload.get("payable_id")
amount = payload.get("amount_inr")
payment_mode = payload.get("payment_mode", "NEFT").upper()
bank_reference = payload.get("bank_reference", "DISB-UTR-001")
if not payable_id or amount is None:
return {"status_code": 400, "error": "payable_id and amount_inr are mandatory"}
payable_dict = self.store.get("supplier_payables", tenant_id, payable_id)
if not payable_dict:
return {"status_code": 404, "error": f"Supplier payable '{payable_id}' not found"}
try:
amt_dec = Decimal(str(amount))
cur_out = Decimal(str(payable_dict["outstanding_amount_inr"]))
if amt_dec <= Decimal("0.00"):
return {"status_code": 422, "error": "Disbursement amount must be positive"}
if amt_dec > cur_out:
return {
"status_code": 422,
"error": f"Disbursement INR {amt_dec} exceeds outstanding balance INR {cur_out}",
}
disb_no = f"DISB-{datetime.now(timezone.utc).strftime('%Y%m')}-{str(uuid.uuid4())[:6].upper()}"
disbursement = SupplierDisbursement(
tenant_id=tenant_id,
disbursement_number=disb_no,
payable_id=payable_id,
supplier_id=payable_dict["supplier_id"],
amount_inr=amt_dec,
payment_mode=payment_mode,
bank_reference=bank_reference,
)
self.store.insert("supplier_disbursements", tenant_id, disbursement.to_dict())
# Update payable balances
paid_so_far = Decimal(str(payable_dict.get("paid_amount_inr", 0.00))) + amt_dec
new_out = cur_out - amt_dec
payable_dict["paid_amount_inr"] = float(paid_so_far)
payable_dict["outstanding_amount_inr"] = float(new_out)
payable_dict["status"] = "PAID" if new_out <= Decimal("0.00") else "PARTIALLY_PAID"
self.store.insert("supplier_payables", tenant_id, payable_dict)
# Post supplier subledger entry
supp_entry = PartySubLedgerEntry(
tenant_id=tenant_id,
party_id=payable_dict["supplier_id"],
party_type="SUPPLIER",
voucher_type="DISBURSEMENT",
voucher_number=disb_no,
debit_amount_inr=amt_dec,
credit_amount_inr=Decimal("0.00"),
running_balance_inr=new_out,
narration=f"Disbursement against GRN {payable_dict['grn_number']} ref {bank_reference}",
)
self.store.insert("party_subledger_entries", tenant_id, supp_entry.to_dict())
record_audit_event(
tenant_id=tenant_id,
action="SUPPLIER_DISBURSEMENT_RECORDED",
entity_type="SupplierDisbursement",
entity_id=disbursement.id,
actor_id=auth_res["user_id"],
metadata={"amount_inr": float(amt_dec), "payable_id": payable_id, "supplier_id": payable_dict["supplier_id"]},
)
return {
"status_code": 201,
"message": "Disbursement successfully recorded",
"disbursement": disbursement.to_dict(),
"payable": payable_dict,
}
except (ValueError, Exception) as err:
return {"status_code": 422, "error": str(err)}
def get_payables_snapshot(
self, auth_header: Optional[str], tenant_header: Optional[str]
) -> Dict[str, Any]:
"""GET /api/v1/finance/payables/snapshot (FR-SUPPLIERPAYABLES-001)."""
auth_res = self._authenticate_and_resolve(auth_header, tenant_header)
if not auth_res.get("authenticated"):
return auth_res
tenant_id = auth_res["tenant_id"]
payables = self.store.list("supplier_payables", tenant_id)
tot_inv = Decimal("0.00")
tot_paid = Decimal("0.00")
tot_out = Decimal("0.00")
aging_summary = {
"CURRENT": Decimal("0.00"),
"1_TO_7_DAYS": Decimal("0.00"),
"8_TO_15_DAYS": Decimal("0.00"),
"OVER_15_DAYS": Decimal("0.00"),
}
now = datetime.now(timezone.utc)
for p in payables:
inv = Decimal(str(p.get("invoice_amount_inr", 0.00)))
paid = Decimal(str(p.get("paid_amount_inr", 0.00)))
out = Decimal(str(p.get("outstanding_amount_inr", 0.00)))
tot_inv += inv
tot_paid += paid
tot_out += out
due_dt = p.get("due_date")
if isinstance(due_dt, str):
due_dt = datetime.fromisoformat(due_dt.replace("Z", "+00:00"))
if due_dt and now > due_dt:
days_overdue = (now - due_dt).days
if days_overdue <= 7:
aging_summary["1_TO_7_DAYS"] += out
elif days_overdue <= 15:
aging_summary["8_TO_15_DAYS"] += out
else:
aging_summary["OVER_15_DAYS"] += out
else:
aging_summary["CURRENT"] += out
return {
"status_code": 200,
"tenant_id": tenant_id,
"total_invoice_amount_inr": float(tot_inv),
"total_paid_inr": float(tot_paid),
"total_outstanding_inr": float(tot_out),
"payables_count": len(payables),
"aging_summary": {k: float(v) for k, v in aging_summary.items()},
}
# =========================================================================
# Mandi Operating Expenses Endpoints (UC-013)
# =========================================================================
def post_expense_voucher(
self, auth_header: Optional[str], tenant_header: Optional[str], payload: Dict[str, Any]
) -> Dict[str, Any]:
"""POST /api/v1/finance/expenses (FR-OPERATINGEXPENSES-001)."""
auth_res = self._authenticate_and_resolve(auth_header, tenant_header)
if not auth_res.get("authenticated"):
return auth_res
tenant_id = auth_res["tenant_id"]
category = payload.get("expense_category", "").upper()
amount = payload.get("amount_inr")
payee_name = payload.get("payee_name")
payment_mode = payload.get("payment_mode", "CASH").upper()
debit_acc = payload.get("debit_account")
credit_acc = payload.get("credit_account")
# Double entry check
deb_amt = payload.get("debit_amount_inr")
cred_amt = payload.get("credit_amount_inr")
if category not in EXPENSE_CATEGORIES:
return {
"status_code": 422,
"error": f"Invalid expense category '{category}'. Must be one of {list(EXPENSE_CATEGORIES.keys())}",
}
if amount is None or float(amount) <= 0:
return {"status_code": 422, "error": "Expense amount must be positive"}
if not payee_name or not payee_name.strip():
return {"status_code": 422, "error": "payee_name is mandatory"}
if not debit_acc or not credit_acc:
return {"status_code": 422, "error": "debit_account and credit_account are mandatory for double entry"}
try:
amt_dec = Decimal(str(amount))
deb_dec = Decimal(str(deb_amt)) if deb_amt is not None else amt_dec
cred_dec = Decimal(str(cred_amt)) if cred_amt is not None else amt_dec
vouch_no = f"EXP-{datetime.now(timezone.utc).strftime('%Y%m')}-{str(uuid.uuid4())[:6].upper()}"
voucher = MandiExpenseVoucher(
tenant_id=tenant_id,
voucher_number=vouch_no,
expense_category=category,
amount_inr=amt_dec,
payee_name=payee_name,
payment_mode=payment_mode,
debit_account=debit_acc,
credit_account=credit_acc,
debit_amount_inr=deb_dec,
credit_amount_inr=cred_dec,
linked_consignment_id=payload.get("linked_consignment_id"),
linked_sauda_id=payload.get("linked_sauda_id"),
narration=payload.get("description") or payload.get("narration"),
)
except ValueError as err:
return {"status_code": 422, "error": str(err)}
self.store.insert("mandi_expense_vouchers", tenant_id, voucher.to_dict())
# Update cash/bank account balance
bank_acc = self.store.get("cash_bank_accounts", tenant_id, credit_acc)
if bank_acc:
new_bal = Decimal(str(bank_acc.get("current_balance_inr", 0.00))) - amt_dec
bank_acc["current_balance_inr"] = float(new_bal)
self.store.insert("cash_bank_accounts", tenant_id, bank_acc)
record_audit_event(
tenant_id=tenant_id,
action="MANDI_OPERATING_EXPENSE_POSTED",
entity_type="MandiExpenseVoucher",
entity_id=voucher.id,
actor_id=auth_res["user_id"],
metadata={
"voucher_number": voucher.voucher_number,
"category": category,
"amount_inr": float(amt_dec),
"credit_account": credit_acc,
},
)
return {
"status_code": 201,
"message": "Mandi operating expense voucher successfully recorded with balanced double entry",
"voucher": voucher.to_dict(),
}
def list_expense_vouchers(
self,
auth_header: Optional[str],
tenant_header: Optional[str],
category: Optional[str] = None,
payment_mode: Optional[str] = None,
) -> Dict[str, Any]:
"""GET /api/v1/finance/expenses (FR-OPERATINGEXPENSES-001)."""
auth_res = self._authenticate_and_resolve(auth_header, tenant_header)
if not auth_res.get("authenticated"):
return auth_res
tenant_id = auth_res["tenant_id"]
vouchers = self.store.list("mandi_expense_vouchers", tenant_id)
if category:
vouchers = [v for v in vouchers if v.get("expense_category") == category.upper()]
if payment_mode:
vouchers = [v for v in vouchers if v.get("payment_mode") == payment_mode.upper()]
return {"status_code": 200, "tenant_id": tenant_id, "vouchers": vouchers, "count": len(vouchers)}
finance_controller = FinanceController()