c_agri_trade/project_code/tests/backend/test_financial_settlement.py

1014 lines
43 KiB
Python

"""Automated Multi-Path Unit Test Suite for Financial Settlement (Iteration 05).
Fulfills:
- STORY-REC-001 / FR-CUSTOMERRECEIVABLES-001: Customer Sub-Ledger & Multi-Bucket Aging
- STORY-REC-002 / FR-CUSTOMERRECEIVABLES-002: Automated Credit Exposure Watch (>80%)
- STORY-REC-003 / FR-CUSTOMERRECEIVABLES-003: Credit Breach Dispatch Lock & Partner Override (>100%)
- STORY-REC-004 / FR-CUSTOMERRECEIVABLES-004: Payment Receipt Posting & Bounce Reversal FSM
- STORY-PAY-001 / FR-SUPPLIERPAYABLES-001: Supplier Payables Aging & Balance Snapshots
- STORY-EXP-001 / FR-OPERATINGEXPENSES-001: Mandi Operating Expense Classification & Balancing
Exercises all 4 test dimensions:
1. Happy Path
2. Boundary / Threshold Edge Cases
3. Negative / Security Gating
4. FSM Invariant & Concurrency Reversals
"""
import os
import sys
import unittest
from datetime import datetime, timezone, timedelta
from decimal import Decimal
from pathlib import Path
import uuid
# Ensure code_root is in sys.path
code_root = Path(__file__).resolve().parents[2]
repo_root = Path(__file__).resolve().parents[3]
if str(code_root) not in sys.path:
sys.path.insert(0, str(code_root))
if str(repo_root) not in sys.path:
sys.path.insert(0, str(repo_root))
from backend.app.api.finance import FinanceController
from backend.app.api.logistics import LogisticsController
from backend.app.models.finance import (
PartySubLedgerEntry,
CreditDispatchLock,
CustomerPaymentReceipt,
SupplierPayable,
SupplierDisbursement,
CashBankAccount,
MandiExpenseVoucher,
compute_exposure_metrics,
compute_customer_aging,
EXPENSE_CATEGORIES,
)
from backend.app.db.session import InMemoryTenantStorage
from backend.app.models.tenant import Tenant, TenantMembership
from sandbox.identity_mock import mock_idp
from sandbox.payment_mock import PaymentMockAdapter
class TestFinancialSettlementUnit(unittest.TestCase):
"""Comprehensive Unit Tests for Financial Settlement Domain & API."""
def setUp(self):
self.store = InMemoryTenantStorage()
self.controller = FinanceController(store=self.store)
self.logistics_ctrl = LogisticsController(store=self.store)
self.tenant_id = "tenant-alpha"
# Pre-seed active tenant and memberships
self.store.save_tenant(
Tenant(
tenant_id=self.tenant_id,
business_name="Alpha Agro Commodities",
legal_identifier="23ABCDE1234F1Z5",
contact_email="director@alphaagro.com",
primary_mandi="Indore APMC",
status="ACTIVE",
)
)
self.store.save_membership(
TenantMembership(
tenant_id=self.tenant_id,
user_id="usr-partner-01",
email="partner@mandi-alpha.com",
role="Partner / MD",
status="ACTIVE",
)
)
self.store.save_membership(
TenantMembership(
tenant_id=self.tenant_id,
user_id="usr-accounts-01",
email="accounts@mandi-alpha.com",
role="Accounts Executive",
status="ACTIVE",
)
)
self.store.save_membership(
TenantMembership(
tenant_id=self.tenant_id,
user_id="usr-cashier-01",
email="cashier@mandi-alpha.com",
role="Cashier",
status="ACTIVE",
)
)
# Generate test auth headers for various personas
self.partner_jwt = mock_idp.mint_jwt(
subject="usr-partner-01",
email="partner@mandi-alpha.com",
name="Harish Patel (Partner/MD)",
roles=["Partner / MD", "Tenant Administrator"],
tenant_id=self.tenant_id,
)
self.partner_auth = f"Bearer {self.partner_jwt}"
self.accounts_jwt = mock_idp.mint_jwt(
subject="usr-accounts-01",
email="accounts@mandi-alpha.com",
name="Kavita Joshi (Accounts)",
roles=["Accounts Executive"],
tenant_id=self.tenant_id,
)
self.accounts_auth = f"Bearer {self.accounts_jwt}"
self.cashier_jwt = mock_idp.mint_jwt(
subject="usr-cashier-01",
email="cashier@mandi-alpha.com",
name="Ramesh Cashier",
roles=["Cashier"],
tenant_id=self.tenant_id,
)
self.cashier_auth = f"Bearer {self.cashier_jwt}"
# =========================================================================
# 1. STORY-REC-001: Customer Sub-Ledger & Aging Statement
# =========================================================================
def test_customer_subledger_query_and_running_balance(self):
"""Happy Path: Query customer ledger and verify calculated running balance."""
res = self.controller.get_customer_ledger(self.accounts_auth, self.tenant_id, "CUST-001")
self.assertEqual(res["status_code"], 200)
self.assertEqual(res["customer_id"], "CUST-001")
self.assertGreaterEqual(res["entries_count"], 1)
self.assertIn("running_balance_inr", res)
self.assertIn("aging_schedule", res)
self.assertEqual(res["running_balance_inr"], 1250000.00)
def test_customer_aging_calculation_buckets(self):
"""Happy & Boundary: Verify 4-bucket aging schedule calculation."""
now = datetime.now(timezone.utc)
invoices = [
{"date": now - timedelta(days=5), "balance_inr": 100000.00}, # 0-7 days
{"date": now - timedelta(days=12), "balance_inr": 200000.00}, # 8-15 days
{"date": now - timedelta(days=25), "balance_inr": 300000.00}, # 16-30 days
{"date": now - timedelta(days=45), "balance_inr": 400000.00}, # >30 days
]
aging = compute_customer_aging(invoices, as_of_date=now)
self.assertEqual(aging["total_outstanding_inr"], 1000000.00)
self.assertEqual(aging["bucket_0_to_7_days_inr"], 100000.00)
self.assertEqual(aging["bucket_8_to_15_days_inr"], 200000.00)
self.assertEqual(aging["bucket_16_to_30_days_inr"], 300000.00)
self.assertEqual(aging["bucket_over_30_days_inr"], 400000.00)
def test_customer_subledger_immutability(self):
"""Negative / Invariant: Posted subledger entries are append-only."""
entry = PartySubLedgerEntry(
tenant_id=self.tenant_id,
party_id="CUST-001",
party_type="CUSTOMER",
voucher_type="SALES_INVOICE",
voucher_number="INV-2026-TEST",
debit_amount_inr=Decimal("50000.00"),
running_balance_inr=Decimal("1300000.00"),
)
self.assertEqual(entry.voucher_type, "SALES_INVOICE")
# Invalid voucher type is rejected
with self.assertRaises(ValueError):
PartySubLedgerEntry(
tenant_id=self.tenant_id,
party_id="CUST-001",
party_type="CUSTOMER",
voucher_type="INVALID_TYPE",
voucher_number="INV-ERR",
)
# =========================================================================
# 2. STORY-REC-002: Automated Credit Exposure Watch & Threshold Alert
# =========================================================================
def test_credit_exposure_normal_state(self):
"""Happy Path: Normal exposure (<80%) returns NORMAL risk flag and no watch alert."""
metrics = compute_exposure_metrics(
sanctioned_limit_inr=Decimal("5000000.00"),
current_outstanding_inr=Decimal("1250000.00"), # 25%
)
self.assertEqual(metrics["exposure_ratio_pct"], 25.0)
self.assertEqual(metrics["risk_flag"], "NORMAL")
self.assertFalse(metrics["watch_alert"])
self.assertFalse(metrics["dispatch_lock_required"])
def test_credit_exposure_watch_boundary(self):
"""Boundary Path: Exactly 80.0% exposure triggers WATCH flag and amber alert."""
metrics_80 = compute_exposure_metrics(
sanctioned_limit_inr=Decimal("1000000.00"),
current_outstanding_inr=Decimal("800000.00"), # 80.0%
)
self.assertEqual(metrics_80["exposure_ratio_pct"], 80.0)
self.assertEqual(metrics_80["risk_flag"], "WATCH")
self.assertTrue(metrics_80["watch_alert"])
self.assertFalse(metrics_80["dispatch_lock_required"])
def test_credit_exposure_critical_breach(self):
"""Boundary Path: Exposure > 100.0% triggers CRITICAL risk and lock required."""
metrics_101 = compute_exposure_metrics(
sanctioned_limit_inr=Decimal("1000000.00"),
current_outstanding_inr=Decimal("1010000.00"), # 101.0%
)
self.assertEqual(metrics_101["exposure_ratio_pct"], 101.0)
self.assertEqual(metrics_101["risk_flag"], "CRITICAL")
self.assertTrue(metrics_101["watch_alert"])
self.assertTrue(metrics_101["dispatch_lock_required"])
def test_get_credit_exposure_api_endpoint(self):
"""Happy Path: Query credit exposure API endpoint for existing customer."""
res = self.controller.get_credit_exposure(self.accounts_auth, self.tenant_id, "CUST-002")
self.assertEqual(res["status_code"], 200)
self.assertEqual(res["customer_id"], "CUST-002")
self.assertEqual(res["risk_flag"], "WATCH") # CUST-002 has 6.5M / 7.5M = 86.67%
self.assertTrue(res["watch_alert"])
# =========================================================================
# 3. STORY-REC-003: Credit Breach Dispatch Lock & Partner Override
# =========================================================================
def test_credit_breach_dispatch_lock_and_override_workflow(self):
"""Happy & Security: Partner override releases dispatch lock with mandatory justification."""
# Setup customer CUST-003 with credit breach (>100%)
lock = CreditDispatchLock(
tenant_id=self.tenant_id,
customer_id="CUST-003",
exposure_ratio_pct=Decimal("115.00"),
sanctioned_limit_inr=Decimal("2000000.00"),
outstanding_balance_inr=Decimal("2300000.00"),
)
self.store.insert("credit_dispatch_locks", self.tenant_id, lock.to_dict())
# 1. Non-Partner attempt to override rejected with 403
bad_res = self.controller.override_credit_lock(
self.accounts_auth,
self.tenant_id,
lock.id,
{"override_justification": "Accounts executive approving override"},
)
self.assertEqual(bad_res["status_code"], 403)
self.assertIn("Only Partner / MD", bad_res["error"])
# 2. Short justification (<15 chars) rejected with 422
short_res = self.controller.override_credit_lock(
self.partner_auth,
self.tenant_id,
lock.id,
{"override_justification": "Too short"},
)
self.assertEqual(short_res["status_code"], 422)
# 3. Valid Partner override succeeds
ok_res = self.controller.override_credit_lock(
self.partner_auth,
self.tenant_id,
lock.id,
{"override_justification": "Authorized post-dated cheque verified by bank manager"},
)
self.assertEqual(ok_res["status_code"], 200)
self.assertEqual(ok_res["lock"]["status"], "OVERRIDDEN")
self.assertEqual(ok_res["lock"]["overridden_by"], "partner@mandi-alpha.com")
def test_dispatch_creation_blocked_by_active_credit_lock(self):
"""Negative / Invariant: Outbound dispatch creation rejected when customer is locked."""
# Insert active lock for CUST-LOCKED
lock = CreditDispatchLock(
tenant_id=self.tenant_id,
customer_id="CUST-LOCKED",
exposure_ratio_pct=Decimal("120.00"),
sanctioned_limit_inr=Decimal("1000000.00"),
outstanding_balance_inr=Decimal("1200000.00"),
)
self.store.insert("credit_dispatch_locks", self.tenant_id, lock.to_dict())
# Attempt to create dispatch
disp_res = self.logistics_ctrl.create_dispatch(
self.accounts_auth,
self.tenant_id,
{
"sales_order_id": "SO-001",
"allocation_id": "ALLOC-001",
"vehicle_id": "TRUCK-MP09-1234",
"origin_warehouse_id": "WH-01",
"destination_city": "Indore",
"customer_id": "CUST-LOCKED",
},
)
self.assertEqual(disp_res["status_code"], 403)
self.assertIn("CREDIT_BREACH_DISPATCH_LOCKED", disp_res["error"])
# =========================================================================
# 4. STORY-REC-004: Payment Receipts & Atomic Bounce Reversal FSM
# =========================================================================
def test_payment_receipt_posting_and_subledger_update(self):
"""Happy Path: Record payment receipt, credit subledger, and reduce outstanding balance."""
res = self.controller.post_payment_receipt(
self.cashier_auth,
self.tenant_id,
{
"customer_id": "CUST-001",
"amount_inr": 250000.00,
"payment_mode": "NEFT",
"instrument_ref": "UTR-HDFC-20261012-9901",
},
)
self.assertEqual(res["status_code"], 201)
self.assertEqual(res["receipt"]["status"], "CLEARED")
# 1250000 - 250000 = 1000000
self.assertEqual(res["updated_outstanding_inr"], 1000000.00)
def test_cheque_bounce_atomic_reversal_fsm(self):
"""FSM Invariant: Cheque bounce executes atomic reversal, restores debt, and reinstates lock."""
# 1. Post receipt for CUST-003 (Credit Limit: 2.0M, Outstanding: 1.75M)
rec_res = self.controller.post_payment_receipt(
self.cashier_auth,
self.tenant_id,
{
"customer_id": "CUST-003",
"amount_inr": 500000.00,
"payment_mode": "CHEQUE",
"instrument_ref": "CHQ-802914",
},
)
self.assertEqual(rec_res["status_code"], 201)
receipt_id = rec_res["receipt"]["id"]
# Outstanding reduced to 1.75M - 0.5M = 1.25M
self.assertEqual(rec_res["updated_outstanding_inr"], 1250000.00)
# 2. Simulate large invoice that brings debt to 1.8M (90% exposure)
profile = self.store.get("customer_credit_profiles", self.tenant_id, "CUST-003")
profile["current_outstanding_inr"] = 1800000.00
self.store.insert("customer_credit_profiles", self.tenant_id, profile)
# 3. Cheque bounces! Restores +500,000 -> 2.3M (> 2.0M limit = 115% exposure)
bounce_res = self.controller.bounce_payment_receipt(
self.accounts_auth,
self.tenant_id,
receipt_id,
{"bounce_reason": "Insufficient Funds in drawer account"},
)
self.assertEqual(bounce_res["status_code"], 200)
self.assertEqual(bounce_res["receipt"]["status"], "BOUNCED")
self.assertEqual(bounce_res["restored_outstanding_inr"], 2300000.00)
self.assertTrue(bounce_res["dispatch_lock_reinstated"])
# 4. Verify reversing debit note in subledger
entries = self.store.list("party_subledger_entries", self.tenant_id)
rev_entry = next((e for e in entries if e.get("reversal_of_id") == receipt_id), None)
self.assertIsNotNone(rev_entry)
self.assertEqual(rev_entry["voucher_type"], "DEBIT_NOTE")
self.assertEqual(rev_entry["debit_amount_inr"], 500000.00)
# 5. Attempting to bounce again fails
second_bounce = self.controller.bounce_payment_receipt(
self.accounts_auth,
self.tenant_id,
receipt_id,
{"bounce_reason": "Duplicate bounce"},
)
self.assertEqual(second_bounce["status_code"], 422)
# =========================================================================
# 5. STORY-PAY-001: Supplier Payables & Aging Console
# =========================================================================
def test_supplier_payables_and_aging_buckets(self):
"""Happy Path: Query supplier payables with calculated due dates and overdue aging."""
res = self.controller.get_supplier_payables(self.accounts_auth, self.tenant_id)
self.assertEqual(res["status_code"], 200)
self.assertGreaterEqual(res["count"], 3)
for p in res["payables"]:
self.assertIn("due_date", p)
self.assertIn("aging_bucket", p)
def test_supplier_disbursement_recording(self):
"""Happy & Boundary: Record disbursement reducing payable liability."""
payables = self.controller.get_supplier_payables(self.accounts_auth, self.tenant_id)["payables"]
target = payables[0]
initial_outstanding = target["outstanding_amount_inr"]
# Partial disbursement
disb_res = self.controller.record_supplier_disbursement(
self.accounts_auth,
self.tenant_id,
{
"payable_id": target["id"],
"amount_inr": 200000.00,
"payment_mode": "RTGS",
"bank_reference": "UTR-RTGS-20261012-001",
},
)
self.assertEqual(disb_res["status_code"], 201)
self.assertEqual(disb_res["payable"]["status"], "PARTIALLY_PAID")
self.assertEqual(disb_res["payable"]["outstanding_amount_inr"], initial_outstanding - 200000.00)
# Over-disbursement rejected
excess_res = self.controller.record_supplier_disbursement(
self.accounts_auth,
self.tenant_id,
{
"payable_id": target["id"],
"amount_inr": 999999999.00,
"payment_mode": "RTGS",
"bank_reference": "UTR-FAIL",
},
)
self.assertEqual(excess_res["status_code"], 422)
def test_supplier_payables_aggregate_snapshot(self):
"""Happy Path: Aggregate payables snapshot summary."""
snap = self.controller.get_payables_snapshot(self.accounts_auth, self.tenant_id)
self.assertEqual(snap["status_code"], 200)
self.assertGreater(snap["total_invoice_amount_inr"], 0)
self.assertIn("aging_summary", snap)
# =========================================================================
# 6. STORY-EXP-001: Mandi Operating Expenses & Double-Entry Balancing
# =========================================================================
def test_mandi_operating_expense_balanced_posting(self):
"""Happy Path: Record balanced operating expense voucher."""
exp_res = self.controller.post_expense_voucher(
self.cashier_auth,
self.tenant_id,
{
"expense_category": "HAMALI",
"amount_inr": 4500.00,
"debit_amount_inr": 4500.00,
"credit_amount_inr": 4500.00,
"payee_name": "Radheshyam Hamali Toli",
"payment_mode": "CASH",
"debit_account": "EXP-HAMALI-001",
"credit_account": "ca-cash-001",
"description": "Unloading charges for 50 MT soybean consignment",
},
)
self.assertEqual(exp_res["status_code"], 201)
self.assertEqual(exp_res["voucher"]["expense_category"], "HAMALI")
self.assertEqual(exp_res["voucher"]["status"], "POSTED")
def test_mandi_operating_expense_unbalanced_rejected(self):
"""Negative / Invariant: Unbalanced double-entry (Debit != Credit) is strictly rejected."""
unbalanced_res = self.controller.post_expense_voucher(
self.cashier_auth,
self.tenant_id,
{
"expense_category": "HAMALI",
"amount_inr": 5000.00,
"debit_amount_inr": 5000.00,
"credit_amount_inr": 4500.00, # Unbalanced by 500 INR!
"payee_name": "Unbalanced Vendor",
"payment_mode": "CASH",
"debit_account": "EXP-HAMALI-001",
"credit_account": "ca-cash-001",
},
)
self.assertEqual(unbalanced_res["status_code"], 422)
self.assertIn("Double-entry balancing failed", unbalanced_res["error"])
def test_mandi_operating_expense_invalid_category_rejected(self):
"""Negative: Non-standard expense category rejected."""
bad_cat_res = self.controller.post_expense_voucher(
self.cashier_auth,
self.tenant_id,
{
"expense_category": "ENTERTAINMENT", # Not in Mandi approved categories
"amount_inr": 1000.00,
"payee_name": "Local Restaurant",
"payment_mode": "CASH",
"debit_account": "EXP-01",
"credit_account": "ca-cash-001",
},
)
self.assertEqual(bad_cat_res["status_code"], 422)
self.assertIn("Invalid expense category", bad_cat_res["error"])
# =========================================================================
# 7. Wave 0 Payment Mock Tests
# =========================================================================
def test_payment_mock_adapter_verification_and_bounce(self):
"""Adapter: Test UTR and Cheque instrument verification and bounce simulation."""
mock = PaymentMockAdapter()
utr_check = mock.verify_instrument("NEFT", "HDFCN26194829104")
self.assertTrue(utr_check["valid"])
chq_check = mock.verify_instrument("CHEQUE", "123456")
self.assertTrue(chq_check["valid"])
bounce = mock.simulate_cheque_bounce("123456")
self.assertEqual(bounce["clearance_status"], "BOUNCED")
def test_customer_aging_api_endpoint(self):
"""Happy Path: Call get_customer_aging endpoint."""
aging_res = self.controller.get_customer_aging(self.accounts_auth, self.tenant_id, "CUST-001")
self.assertEqual(aging_res["status_code"], 200)
self.assertIn("aging_schedule", aging_res)
def test_list_credit_locks_with_status_filter(self):
"""Happy Path: List credit locks filtered by status."""
all_locks = self.controller.list_credit_locks(self.partner_auth, self.tenant_id)
self.assertEqual(all_locks["status_code"], 200)
filtered = self.controller.list_credit_locks(self.partner_auth, self.tenant_id, status="LOCKED")
self.assertEqual(filtered["status_code"], 200)
def test_clear_payment_receipt_lifecycle(self):
"""FSM & Happy: Clear receipt and handle non-existent receipt or already bounced."""
rec = CustomerPaymentReceipt(
tenant_id=self.tenant_id,
receipt_number="PAY-PENDING-001",
customer_id="CUST-001",
amount_inr=Decimal("50000.00"),
payment_mode="CHEQUE",
instrument_ref="CHQ-PEND-01",
status="PENDING_CLEARANCE",
)
self.store.insert("customer_payment_receipts", self.tenant_id, rec.to_dict())
# Clear it
clear_res = self.controller.clear_payment_receipt(self.accounts_auth, self.tenant_id, rec.id)
self.assertEqual(clear_res["status_code"], 200)
self.assertEqual(clear_res["receipt"]["status"], "CLEARED")
# 404 for non-existent
not_found = self.controller.clear_payment_receipt(self.accounts_auth, self.tenant_id, "non-existent-id")
self.assertEqual(not_found["status_code"], 404)
# Mark bounced and verify cannot clear
rec_bounced = CustomerPaymentReceipt(
tenant_id=self.tenant_id,
receipt_number="PAY-BOUNCED-001",
customer_id="CUST-001",
amount_inr=Decimal("20000.00"),
payment_mode="CHEQUE",
instrument_ref="CHQ-BNC-01",
status="BOUNCED",
)
self.store.insert("customer_payment_receipts", self.tenant_id, rec_bounced.to_dict())
cannot_clear = self.controller.clear_payment_receipt(self.accounts_auth, self.tenant_id, rec_bounced.id)
self.assertEqual(cannot_clear["status_code"], 422)
def test_expense_vouchers_listing_and_filtering(self):
"""Happy Path: List expense vouchers with category and payment mode filters."""
# Create a freight voucher
self.controller.post_expense_voucher(
self.cashier_auth,
self.tenant_id,
{
"expense_category": "FREIGHT",
"amount_inr": 8000.00,
"debit_amount_inr": 8000.00,
"credit_amount_inr": 8000.00,
"payee_name": "Sharma Roadlines",
"payment_mode": "BANK_TRANSFER",
"debit_account": "EXP-FREIGHT-001",
"credit_account": "ba-sbi-001",
},
)
# List all
all_v = self.controller.list_expense_vouchers(self.accounts_auth, self.tenant_id)
self.assertEqual(all_v["status_code"], 200)
# Filter by FREIGHT
freight_v = self.controller.list_expense_vouchers(self.accounts_auth, self.tenant_id, category="FREIGHT")
self.assertEqual(freight_v["status_code"], 200)
self.assertTrue(all(v["expense_category"] == "FREIGHT" for v in freight_v["vouchers"]))
# Filter by mode
bank_v = self.controller.list_expense_vouchers(self.accounts_auth, self.tenant_id, payment_mode="BANK_TRANSFER")
self.assertEqual(bank_v["status_code"], 200)
def test_credit_exposure_and_lock_edge_cases(self):
"""Negative: 404 for unknown customer and non-existent lock override."""
cust_404 = self.controller.get_credit_exposure(self.accounts_auth, self.tenant_id, "CUST-DOES-NOT-EXIST")
self.assertEqual(cust_404["status_code"], 404)
lock_404 = self.controller.override_credit_lock(
self.partner_auth,
self.tenant_id,
"non-existent-lock-id",
{"override_justification": "Authorized by partner with genuine reason"},
)
self.assertEqual(lock_404["status_code"], 404)
def test_post_receipt_validation_failures(self):
"""Negative: Validation failures for payment receipts."""
# Missing customer
bad_c = self.controller.post_payment_receipt(self.cashier_auth, self.tenant_id, {"amount_inr": 1000})
self.assertEqual(bad_c["status_code"], 400)
# Zero amount
zero_a = self.controller.post_payment_receipt(
self.cashier_auth, self.tenant_id, {"customer_id": "CUST-001", "amount_inr": 0}
)
self.assertEqual(zero_a["status_code"], 422)
# Invalid mode
bad_m = self.controller.post_payment_receipt(
self.cashier_auth,
self.tenant_id,
{"customer_id": "CUST-001", "amount_inr": 1000, "payment_mode": "CRYPTO"},
)
self.assertEqual(bad_m["status_code"], 422)
def test_supplier_disbursement_edge_cases(self):
"""Negative: Supplier disbursement validation errors."""
# Missing payable_id
bad_p = self.controller.record_supplier_disbursement(self.accounts_auth, self.tenant_id, {"amount_inr": 1000})
self.assertEqual(bad_p["status_code"], 400)
# Not found payable
nf_p = self.controller.record_supplier_disbursement(
self.accounts_auth, self.tenant_id, {"payable_id": "non-existent", "amount_inr": 1000}
)
self.assertEqual(nf_p["status_code"], 404)
# Non-positive amount
payables = self.controller.get_supplier_payables(self.accounts_auth, self.tenant_id)["payables"]
zero_p = self.controller.record_supplier_disbursement(
self.accounts_auth, self.tenant_id, {"payable_id": payables[0]["id"], "amount_inr": 0}
)
self.assertEqual(zero_p["status_code"], 422)
def test_supplier_disbursement_full_settlement_to_paid(self):
"""Happy Path: Paying full outstanding liability transitions payable status to PAID."""
payables = self.controller.get_supplier_payables(self.accounts_auth, self.tenant_id)["payables"]
target = payables[1] # second payable
out_amt = target["outstanding_amount_inr"]
full_res = self.controller.record_supplier_disbursement(
self.accounts_auth,
self.tenant_id,
{
"payable_id": target["id"],
"amount_inr": out_amt,
"payment_mode": "NEFT",
"bank_reference": "UTR-FULL-PAID-001",
},
)
self.assertEqual(full_res["status_code"], 201)
self.assertEqual(full_res["payable"]["status"], "PAID")
self.assertEqual(full_res["payable"]["outstanding_amount_inr"], 0.0)
def test_mandi_expense_missing_fields_validation(self):
"""Negative: Missing payee or accounts in expense voucher."""
no_payee = self.controller.post_expense_voucher(
self.cashier_auth,
self.tenant_id,
{
"expense_category": "TOLAI",
"amount_inr": 200,
"payee_name": "",
"debit_account": "EXP-TOLAI",
"credit_account": "ca-cash-001",
},
)
self.assertEqual(no_payee["status_code"], 422)
no_acc = self.controller.post_expense_voucher(
self.cashier_auth,
self.tenant_id,
{
"expense_category": "TOLAI",
"amount_inr": 200,
"payee_name": "Weighbridge Master",
"debit_account": "",
"credit_account": "",
},
)
self.assertEqual(no_acc["status_code"], 422)
def test_model_methods_and_domain_functions(self):
"""Domain: Direct unit testing of model methods and pure functions."""
# CashBankAccount operations
cba = CashBankAccount(
tenant_id=self.tenant_id,
account_code="TEST-BANK",
account_name="Test Account",
account_type="BANK",
current_balance_inr=Decimal("1000.00"),
)
self.assertEqual(cba.credit(Decimal("500.00")), Decimal("1500.00"))
self.assertEqual(cba.debit(Decimal("300.00")), Decimal("1200.00"))
with self.assertRaises(ValueError):
cba.debit(Decimal("5000.00"))
# CreditDispatchLock release
lock = CreditDispatchLock(
tenant_id=self.tenant_id,
customer_id="CUST-001",
exposure_ratio_pct=Decimal("105.00"),
sanctioned_limit_inr=Decimal("1000000.00"),
outstanding_balance_inr=Decimal("1050000.00"),
)
lock.release()
self.assertEqual(lock.status, "RELEASED")
# CustomerPaymentReceipt mark_cleared on bounced raises error
rc = CustomerPaymentReceipt(
tenant_id=self.tenant_id,
receipt_number="PAY-DIR-001",
customer_id="CUST-001",
amount_inr=Decimal("1000.00"),
payment_mode="CASH",
instrument_ref="CASH-001",
status="BOUNCED",
)
with self.assertRaises(ValueError):
rc.mark_cleared()
with self.assertRaises(ValueError):
rc.mark_bounced()
# PaymentMockAdapter operations
mock = PaymentMockAdapter()
acc = mock.get_account("ba-sbi-001")
self.assertIsNotNone(acc)
mock.credit_account("ba-sbi-001", Decimal("10000.00"))
mock.debit_account("ba-sbi-001", Decimal("5000.00"))
with self.assertRaises(ValueError):
mock.debit_account("ba-sbi-001", Decimal("9999999999.00"))
with self.assertRaises(ValueError):
mock.debit_account("non-existent-account", Decimal("100.00"))
with self.assertRaises(ValueError):
mock.credit_account("non-existent-account", Decimal("100.00"))
# PaymentMockAdapter instrument validations
self.assertTrue(mock.verify_instrument("CASH", "CASH")["valid"])
self.assertFalse(mock.verify_instrument("BITCOIN", "BTC")["valid"])
def test_additional_model_branches_and_dict_serialization(self):
"""Complete branch coverage across all financial domain models."""
# 1. SupplierPayable validations and aging buckets
now = datetime.now(timezone.utc)
sp = SupplierPayable(
tenant_id=self.tenant_id,
supplier_id="SUPP-01",
grn_number="GRN-01",
invoice_amount_inr=Decimal("10000.00"),
grn_date=now - timedelta(days=25),
credit_days=5, # due 20 days ago -> OVER_15_DAYS
)
self.assertEqual(sp.get_aging_bucket(now), "OVER_15_DAYS")
# Due 10 days ago -> 8_TO_15_DAYS
sp.due_date = now - timedelta(days=10)
self.assertEqual(sp.get_aging_bucket(now), "8_TO_15_DAYS")
# Due 3 days ago -> 1_TO_7_DAYS
sp.due_date = now - timedelta(days=3)
self.assertEqual(sp.get_aging_bucket(now), "1_TO_7_DAYS")
# Current (not due)
sp.due_date = now + timedelta(days=5)
self.assertEqual(sp.get_aging_bucket(now), "CURRENT")
# to_dict checks
sp_dict = sp.to_dict()
self.assertEqual(sp_dict["supplier_id"], "SUPP-01")
with self.assertRaises(ValueError):
SupplierPayable(
tenant_id=self.tenant_id,
supplier_id="SUPP-01",
grn_number="GRN-01",
invoice_amount_inr=Decimal("-10.00"),
grn_date=now,
)
with self.assertRaises(ValueError):
sp.record_payment(Decimal("-10.00"))
with self.assertRaises(ValueError):
sp.record_payment(Decimal("9999999.00"))
# 2. SupplierDisbursement validations and to_dict
sd = SupplierDisbursement(
tenant_id=self.tenant_id,
disbursement_number="DISB-01",
payable_id="PAY-01",
supplier_id="SUPP-01",
amount_inr=Decimal("5000.00"),
payment_mode="NEFT",
bank_reference="REF-01",
)
self.assertEqual(sd.to_dict()["disbursement_number"], "DISB-01")
with self.assertRaises(ValueError):
SupplierDisbursement(
tenant_id=self.tenant_id,
disbursement_number="DISB-01",
payable_id="PAY-01",
supplier_id="SUPP-01",
amount_inr=Decimal("-10.00"),
payment_mode="NEFT",
bank_reference="REF-01",
)
with self.assertRaises(ValueError):
SupplierDisbursement(
tenant_id=self.tenant_id,
disbursement_number="DISB-01",
payable_id="PAY-01",
supplier_id="SUPP-01",
amount_inr=Decimal("100.00"),
payment_mode="INVALID_MODE",
bank_reference="REF-01",
)
with self.assertRaises(ValueError):
SupplierDisbursement(
tenant_id=self.tenant_id,
disbursement_number="DISB-01",
payable_id="PAY-01",
supplier_id="SUPP-01",
amount_inr=Decimal("100.00"),
payment_mode="NEFT",
bank_reference="",
)
# 3. PartySubLedgerEntry to_dict
psl = PartySubLedgerEntry(
tenant_id=self.tenant_id,
party_id="CUST-01",
party_type="CUSTOMER",
voucher_type="PAYMENT_RECEIPT",
voucher_number="V-01",
debit_amount_inr=Decimal("0.00"),
credit_amount_inr=Decimal("1000.00"),
running_balance_inr=Decimal("5000.00"),
)
self.assertEqual(psl.to_dict()["voucher_number"], "V-01")
# 4. CreditDispatchLock to_dict and override errors
cdl = CreditDispatchLock(
tenant_id=self.tenant_id,
customer_id="CUST-01",
exposure_ratio_pct=Decimal("110.00"),
sanctioned_limit_inr=Decimal("1000000.00"),
outstanding_balance_inr=Decimal("1100000.00"),
)
self.assertEqual(cdl.to_dict()["customer_id"], "CUST-01")
with self.assertRaises(PermissionError):
cdl.override(user_role="Sales Executive", user_name="Sales", justification="Valid justification 12345")
with self.assertRaises(ValueError):
cdl.override(user_role="Partner / MD", user_name="MD", justification="short")
# 5. CustomerPaymentReceipt validations and to_dict
cpr = CustomerPaymentReceipt(
tenant_id=self.tenant_id,
receipt_number="RCP-01",
customer_id="CUST-01",
amount_inr=Decimal("2000.00"),
payment_mode="CASH",
instrument_ref="CASH-REF",
)
self.assertEqual(cpr.to_dict()["receipt_number"], "RCP-01")
with self.assertRaises(ValueError):
CustomerPaymentReceipt(
tenant_id=self.tenant_id,
receipt_number="RCP-01",
customer_id="CUST-01",
amount_inr=Decimal("0.00"),
payment_mode="CASH",
instrument_ref="CASH-REF",
)
with self.assertRaises(ValueError):
CustomerPaymentReceipt(
tenant_id=self.tenant_id,
receipt_number="RCP-01",
customer_id="CUST-01",
amount_inr=Decimal("100.00"),
payment_mode="INVALID",
instrument_ref="CASH-REF",
)
with self.assertRaises(ValueError):
CustomerPaymentReceipt(
tenant_id=self.tenant_id,
receipt_number="RCP-01",
customer_id="CUST-01",
amount_inr=Decimal("100.00"),
payment_mode="CASH",
instrument_ref="",
)
# 6. CashBankAccount to_dict
cba = CashBankAccount(
tenant_id=self.tenant_id,
account_code="ACC-01",
account_name="Main Cash",
account_type="CASH",
current_balance_inr=Decimal("1000.00"),
)
self.assertEqual(cba.to_dict()["account_code"], "ACC-01")
# 7. MandiExpenseVoucher validations and to_dict
mev = MandiExpenseVoucher(
tenant_id=self.tenant_id,
voucher_number="V-EXP-01",
expense_category="TOLAI",
amount_inr=Decimal("500.00"),
payee_name="Weighbridge Operator",
payment_mode="CASH",
debit_account="EXP-TOLAI",
credit_account="ca-cash-001",
narration="Test narration",
)
self.assertEqual(mev.to_dict()["voucher_number"], "V-EXP-01")
with self.assertRaises(ValueError):
MandiExpenseVoucher(
tenant_id=self.tenant_id,
voucher_number="V-01",
expense_category="INVALID",
amount_inr=Decimal("100.00"),
payee_name="P",
payment_mode="CASH",
debit_account="D",
credit_account="C",
)
with self.assertRaises(ValueError):
MandiExpenseVoucher(
tenant_id=self.tenant_id,
voucher_number="V-01",
expense_category="TOLAI",
amount_inr=Decimal("0.00"),
payee_name="P",
payment_mode="CASH",
debit_account="D",
credit_account="C",
)
with self.assertRaises(ValueError):
MandiExpenseVoucher(
tenant_id=self.tenant_id,
voucher_number="V-01",
expense_category="TOLAI",
amount_inr=Decimal("100.00"),
payee_name="",
payment_mode="CASH",
debit_account="D",
credit_account="C",
)
with self.assertRaises(ValueError):
MandiExpenseVoucher(
tenant_id=self.tenant_id,
voucher_number="V-01",
expense_category="TOLAI",
amount_inr=Decimal("100.00"),
payee_name="P",
payment_mode="INVALID_MODE",
debit_account="D",
credit_account="C",
)
with self.assertRaises(ValueError):
MandiExpenseVoucher(
tenant_id=self.tenant_id,
voucher_number="V-01",
expense_category="TOLAI",
amount_inr=Decimal("100.00"),
payee_name="P",
payment_mode="CASH",
debit_account="",
credit_account="C",
)
with self.assertRaises(ValueError):
MandiExpenseVoucher(
tenant_id=self.tenant_id,
voucher_number="V-01",
expense_category="TOLAI",
amount_inr=Decimal("100.00"),
payee_name="P",
payment_mode="CASH",
debit_account="D",
credit_account="",
)
# 8. Exposure metrics calculation with zero and negative limit
m_zero = compute_exposure_metrics(Decimal("0.00"), Decimal("1000.00"))
self.assertEqual(m_zero["exposure_ratio_pct"], 100.0)
m_zero_no_debt = compute_exposure_metrics(Decimal("0.00"), Decimal("0.00"))
self.assertEqual(m_zero_no_debt["exposure_ratio_pct"], 0.0)
# 9. Customer aging computation with string date format and zero balance
aging_test = compute_customer_aging(
[
{"date": "2026-10-01T00:00:00Z", "balance_inr": 500.00},
{"date": now + timedelta(days=5), "balance_inr": 200.00}, # future date -> days < 0
{"date": now, "balance_inr": 0.00}, # zero balance ignored
],
as_of_date=now,
)
self.assertGreater(aging_test["total_outstanding_inr"], 0.0)
# 10. Controller auth failure branch
unauth = self.controller.get_customer_ledger(None, self.tenant_id)
self.assertEqual(unauth["status_code"], 401)
# 11. Additional controller branches
bnc_404 = self.controller.bounce_payment_receipt(self.accounts_auth, self.tenant_id, "non-existent-rcp", {})
self.assertEqual(bnc_404["status_code"], 404)
supp_filter = self.controller.get_supplier_payables(self.accounts_auth, self.tenant_id, supplier_id="SUPP-FARMER-001")
self.assertEqual(supp_filter["status_code"], 200)
exp_neg = self.controller.post_expense_voucher(self.cashier_auth, self.tenant_id, {"expense_category": "HAMALI", "amount_inr": -50})
self.assertEqual(exp_neg["status_code"], 422)
rc_clear = CustomerPaymentReceipt(tenant_id=self.tenant_id, receipt_number="RCP-CLR", customer_id="CUST-01", amount_inr=Decimal("100"), payment_mode="CASH", instrument_ref="REF")
rc_clear.mark_cleared()
self.assertEqual(rc_clear.status, "CLEARED")
all_cust_ledger = self.controller.get_customer_ledger(self.accounts_auth, self.tenant_id, None)
self.assertEqual(all_cust_ledger["status_code"], 200)
if __name__ == "__main__":
unittest.main()