446 lines
19 KiB
Python
446 lines
19 KiB
Python
"""Multi-Path Automated Unit & Invariant Test Suite for Sales Contracts (UC-008).
|
|
|
|
Covers:
|
|
- TC-SALES-008-01: Commercial sales contract booking with credit exposure check (Happy Path).
|
|
- TC-SALES-008-02: Credit limit warning (>80%) and hard block (>100%) with Partner override (Boundary).
|
|
- TC-SALES-008-03: Invalid customer, segment, payment terms and negative rates (Negative / Security).
|
|
- TC-SALES-008-04: Released-lot allocation FSM, quality-hold rejection & allocation tally (FSM Invariant).
|
|
"""
|
|
from datetime import datetime, timezone
|
|
from decimal import Decimal
|
|
import unittest
|
|
|
|
from backend.app.api.sales import SalesController
|
|
from backend.app.db.session import InMemoryStorage
|
|
from backend.app.models.sales import CustomerSalesOrder, SalesOrderAllocation
|
|
from backend.app.models.tenant import Tenant, TenantMembership
|
|
from sandbox.identity_mock import mock_idp
|
|
from sandbox.customer_credit_mock import CustomerCreditMock
|
|
|
|
|
|
class TestSalesContracts(unittest.TestCase):
|
|
|
|
def setUp(self):
|
|
CustomerCreditMock.reset_for_tests()
|
|
self.store = InMemoryStorage()
|
|
self.controller = SalesController(store=self.store)
|
|
self.tenant_id = "tenant-alpha"
|
|
|
|
# Pre-seed active tenant
|
|
self.store.save_tenant(
|
|
Tenant(
|
|
tenant_id=self.tenant_id,
|
|
business_name="Alpha Agro Commodities",
|
|
legal_identifier="23ABCDE1234F1Z5",
|
|
contact_email="sales@alphaagro.com",
|
|
primary_mandi="Indore APMC",
|
|
status="ACTIVE",
|
|
)
|
|
)
|
|
# Pre-seed Sales Manager
|
|
self.store.save_membership(
|
|
TenantMembership(
|
|
tenant_id=self.tenant_id,
|
|
user_id="sales_mgr@alphaagro.com",
|
|
email="sales_mgr@alphaagro.com",
|
|
role="SALES_MANAGER",
|
|
status="ACTIVE",
|
|
)
|
|
)
|
|
# Pre-seed Partner
|
|
self.store.save_membership(
|
|
TenantMembership(
|
|
tenant_id=self.tenant_id,
|
|
user_id="partner@alphaagro.com",
|
|
email="partner@alphaagro.com",
|
|
role="PARTNER",
|
|
status="ACTIVE",
|
|
)
|
|
)
|
|
|
|
self.token_sales = mock_idp.mint_jwt(
|
|
subject="sales_mgr@alphaagro.com",
|
|
email="sales_mgr@alphaagro.com",
|
|
name="Sales Manager",
|
|
roles=["SALES_MANAGER"],
|
|
tenant_id=self.tenant_id,
|
|
)
|
|
self.auth_sales = f"Bearer {self.token_sales}"
|
|
|
|
self.token_partner = mock_idp.mint_jwt(
|
|
subject="partner@alphaagro.com",
|
|
email="partner@alphaagro.com",
|
|
name="Partner MD",
|
|
roles=["PARTNER"],
|
|
tenant_id=self.tenant_id,
|
|
)
|
|
self.auth_partner = f"Bearer {self.token_partner}"
|
|
|
|
def test_tc_sales_008_01_booking_happy_path(self):
|
|
"""TC-SALES-008-01: Commercial sales contract booking with credit exposure check."""
|
|
# 1. Pre-order credit check for CUST-001 (Adani Wilmar: limit 50L, outstanding 12.5L)
|
|
# New order: 50 MT @ ₹ 5,200/Qtl = 50 * 10 * 5,200 = ₹ 26,00,000
|
|
# Projected: 12.5L + 26L = 38.5L / 50L = 77.0% (<= 80%)
|
|
check_res = self.controller.check_credit_exposure(
|
|
self.auth_sales,
|
|
self.tenant_id,
|
|
{"customer_id": "CUST-001", "order_value_inr": 2600000.00},
|
|
)
|
|
self.assertEqual(check_res["status_code"], 200)
|
|
self.assertEqual(check_res["exposure_ratio_pct"], 77.0)
|
|
self.assertFalse(check_res["warning_flag"])
|
|
self.assertFalse(check_res["hard_block"])
|
|
|
|
# 2. Book sales order
|
|
order_payload = {
|
|
"customer_id": "CUST-001",
|
|
"destination_city": "Indore",
|
|
"customer_segment": "Processor",
|
|
"commodity_id": "c0a80123-0000-0000-0000-000000000001",
|
|
"variety": "Yellow Desi",
|
|
"contract_qty_mt": 50.000,
|
|
"contract_rate_per_qtl": 5200.00,
|
|
"payment_terms": "30 Days",
|
|
}
|
|
book_res = self.controller.create_sales_order(self.auth_sales, self.tenant_id, order_payload)
|
|
self.assertEqual(book_res["status_code"], 201)
|
|
order = book_res["sales_order"]
|
|
self.assertEqual(order["total_sales_value_inr"], 2600000.00)
|
|
self.assertEqual(order["status"], "CONFIRMED")
|
|
self.assertFalse(order["credit_warning"])
|
|
|
|
# 3. Retrieve order
|
|
get_res = self.controller.get_sales_order(self.auth_sales, self.tenant_id, order["id"])
|
|
self.assertEqual(get_res["status_code"], 200)
|
|
self.assertEqual(get_res["sales_order"]["customer_id"], "CUST-001")
|
|
|
|
def test_tc_sales_008_02_credit_warning_and_hard_block_with_partner_override(self):
|
|
"""TC-SALES-008-02: Exposure >80% displays warning, >100% blocks order without Partner override."""
|
|
# CUST-002: Patanjali Foods (limit 75L, outstanding 65L)
|
|
# Order: 20 MT @ ₹ 5,000/Qtl = ₹ 10,00,000
|
|
# Projected: 65L + 10L = 75L / 75L = 100.0% (> 80%, <= 100%) -> Warning flag
|
|
order_warning = {
|
|
"customer_id": "CUST-002",
|
|
"destination_city": "Nagda",
|
|
"customer_segment": "Processor",
|
|
"commodity_id": "c0a80123-0000-0000-0000-000000000001",
|
|
"variety": "Yellow Desi",
|
|
"contract_qty_mt": 20.000,
|
|
"contract_rate_per_qtl": 5000.00,
|
|
"payment_terms": "15 Days",
|
|
}
|
|
res_warn = self.controller.create_sales_order(self.auth_sales, self.tenant_id, order_warning)
|
|
self.assertEqual(res_warn["status_code"], 201)
|
|
self.assertTrue(res_warn["sales_order"]["credit_warning"])
|
|
self.assertEqual(res_warn["sales_order"]["status"], "CONFIRMED")
|
|
|
|
# Exceeding credit limit: Order 30 MT @ ₹ 5,000/Qtl = ₹ 15,00,000
|
|
# Projected: 65L + 15L = 80L / 75L = 106.67% (> 100%) -> Block!
|
|
order_exceed = {
|
|
"customer_id": "CUST-002",
|
|
"destination_city": "Nagda",
|
|
"customer_segment": "Processor",
|
|
"commodity_id": "c0a80123-0000-0000-0000-000000000001",
|
|
"variety": "Yellow Desi",
|
|
"contract_qty_mt": 30.000,
|
|
"contract_rate_per_qtl": 5000.00,
|
|
"payment_terms": "15 Days",
|
|
"credit_override": False,
|
|
}
|
|
res_block = self.controller.create_sales_order(self.auth_sales, self.tenant_id, order_exceed)
|
|
self.assertEqual(res_block["status_code"], 400)
|
|
self.assertIn("Credit limit exceeded", res_block["error"])
|
|
|
|
# Partner approves with electronic override
|
|
order_exceed["credit_override"] = True
|
|
res_override = self.controller.create_sales_order(self.auth_partner, self.tenant_id, order_exceed)
|
|
self.assertEqual(res_override["status_code"], 201)
|
|
self.assertTrue(res_override["sales_order"]["credit_override"])
|
|
self.assertEqual(res_override["sales_order"]["override_approved_by"], "partner@alphaagro.com")
|
|
|
|
def test_tc_sales_008_03_invalid_inputs_and_rejections(self):
|
|
"""TC-SALES-008-03: Invalid customer, segment, payment terms and negative rates."""
|
|
# 1. Invalid customer
|
|
res1 = self.controller.create_sales_order(
|
|
self.auth_sales,
|
|
self.tenant_id,
|
|
{
|
|
"customer_id": "CUST-NONEXISTENT",
|
|
"destination_city": "Bhopal",
|
|
"customer_segment": "Wholesale",
|
|
"commodity_id": "c0a80123-0000-0000-0000-000000000001",
|
|
"variety": "Yellow Desi",
|
|
"contract_qty_mt": 10.0,
|
|
"contract_rate_per_qtl": 5000.0,
|
|
"payment_terms": "CAD",
|
|
},
|
|
)
|
|
self.assertEqual(res1["status_code"], 404)
|
|
|
|
# 2. Invalid segment
|
|
res2 = self.controller.create_sales_order(
|
|
self.auth_sales,
|
|
self.tenant_id,
|
|
{
|
|
"customer_id": "CUST-001",
|
|
"destination_city": "Indore",
|
|
"customer_segment": "Retail Corner", # invalid
|
|
"commodity_id": "c0a80123-0000-0000-0000-000000000001",
|
|
"variety": "Yellow Desi",
|
|
"contract_qty_mt": 10.0,
|
|
"contract_rate_per_qtl": 5000.0,
|
|
"payment_terms": "CAD",
|
|
},
|
|
)
|
|
self.assertEqual(res2["status_code"], 400)
|
|
self.assertIn("Invalid customer segment", res2["error"])
|
|
|
|
# 3. Negative quantity
|
|
res3 = self.controller.create_sales_order(
|
|
self.auth_sales,
|
|
self.tenant_id,
|
|
{
|
|
"customer_id": "CUST-001",
|
|
"destination_city": "Indore",
|
|
"customer_segment": "Processor",
|
|
"commodity_id": "c0a80123-0000-0000-0000-000000000001",
|
|
"variety": "Yellow Desi",
|
|
"contract_qty_mt": -10.0,
|
|
"contract_rate_per_qtl": 5000.0,
|
|
"payment_terms": "CAD",
|
|
},
|
|
)
|
|
self.assertEqual(res3["status_code"], 400)
|
|
|
|
def test_tc_sales_008_04_lot_allocation_fsm_and_quality_hold_invariant(self):
|
|
"""TC-SALES-008-04: Released-lot allocation FSM, quality hold rejection, and allocation tally."""
|
|
# 1. Create confirmed sales order for 40.000 MT
|
|
order_payload = {
|
|
"customer_id": "CUST-001",
|
|
"destination_city": "Indore",
|
|
"customer_segment": "Processor",
|
|
"commodity_id": "c0a80123-0000-0000-0000-000000000001",
|
|
"variety": "Yellow Desi",
|
|
"contract_qty_mt": 40.000,
|
|
"contract_rate_per_qtl": 5200.00,
|
|
"payment_terms": "30 Days",
|
|
}
|
|
order_res = self.controller.create_sales_order(self.auth_sales, self.tenant_id, order_payload)
|
|
self.assertEqual(order_res["status_code"], 201)
|
|
order_id = order_res["sales_order"]["id"]
|
|
|
|
# 2. Seed a lot with QUALITY_HOLD status
|
|
lot_hold = {
|
|
"id": "lot-hold-01",
|
|
"tenant_id": self.tenant_id,
|
|
"lot_number": "LOT-202610-HOLD",
|
|
"qc_status": "QUALITY_HOLD",
|
|
"current_quantity_mt": 50.000,
|
|
}
|
|
self.store.insert("inventory_lots", self.tenant_id, lot_hold)
|
|
|
|
# Attempt to allocate lot under QUALITY_HOLD: should fail!
|
|
alloc_hold = {
|
|
"lot_id": "lot-hold-01",
|
|
"warehouse_id": "WH-01",
|
|
"allocated_qty_mt": 20.000,
|
|
"allocated_bags": 400,
|
|
}
|
|
res_hold = self.controller.allocate_lot(self.auth_sales, self.tenant_id, order_id, alloc_hold)
|
|
self.assertEqual(res_hold["status_code"], 400)
|
|
self.assertIn("Only 'RELEASED' lots are eligible", res_hold["error"])
|
|
|
|
# 3. Seed a lot with RELEASED status
|
|
lot_released = {
|
|
"id": "lot-rel-01",
|
|
"tenant_id": self.tenant_id,
|
|
"lot_number": "LOT-202610-REL",
|
|
"qc_status": "RELEASED",
|
|
"current_quantity_mt": 50.000,
|
|
}
|
|
self.store.insert("inventory_lots", self.tenant_id, lot_released)
|
|
|
|
# Allocate 25.000 MT: order should become PARTIALLY_ALLOCATED
|
|
alloc_part = {
|
|
"lot_id": "lot-rel-01",
|
|
"warehouse_id": "WH-01",
|
|
"allocated_qty_mt": 25.000,
|
|
"allocated_bags": 500,
|
|
}
|
|
res_part = self.controller.allocate_lot(self.auth_sales, self.tenant_id, order_id, alloc_part)
|
|
self.assertEqual(res_part["status_code"], 201)
|
|
self.assertEqual(res_part["order_status"], "PARTIALLY_ALLOCATED")
|
|
|
|
# Allocate remaining 15.000 MT: order should become FULLY_ALLOCATED
|
|
alloc_full = {
|
|
"lot_id": "lot-rel-01",
|
|
"warehouse_id": "WH-01",
|
|
"allocated_qty_mt": 15.000,
|
|
"allocated_bags": 300,
|
|
}
|
|
res_full = self.controller.allocate_lot(self.auth_sales, self.tenant_id, order_id, alloc_full)
|
|
self.assertEqual(res_full["status_code"], 201)
|
|
self.assertEqual(res_full["order_status"], "FULLY_ALLOCATED")
|
|
|
|
# Attempt to over-allocate beyond 40 MT: should fail!
|
|
alloc_extra = {
|
|
"lot_id": "lot-rel-01",
|
|
"warehouse_id": "WH-01",
|
|
"allocated_qty_mt": 5.000,
|
|
"allocated_bags": 100,
|
|
}
|
|
res_extra = self.controller.allocate_lot(self.auth_sales, self.tenant_id, order_id, alloc_extra)
|
|
self.assertEqual(res_extra["status_code"], 400)
|
|
self.assertIn("exceeds contract quantity", res_extra["error"])
|
|
|
|
def test_sales_contracts_edge_and_error_cases(self):
|
|
"""Branch coverage: CustomerCreditMock, order queries, error handling, unauthenticated."""
|
|
# 1. CustomerCreditMock helper methods
|
|
self.assertIsNotNone(CustomerCreditMock.get_customer("CUST-001"))
|
|
self.assertIsNone(CustomerCreditMock.get_customer("CUST-UNKNOWN"))
|
|
procs = CustomerCreditMock.list_customers(segment="Processor")
|
|
self.assertGreater(len(procs), 0)
|
|
all_c = CustomerCreditMock.list_customers()
|
|
self.assertGreater(len(all_c), 0)
|
|
updated = CustomerCreditMock.update_outstanding("CUST-001", Decimal("50000.00"))
|
|
self.assertEqual(updated["outstanding_inr"], Decimal("1300000.00"))
|
|
with self.assertRaises(ValueError):
|
|
CustomerCreditMock.update_outstanding("CUST-UNKNOWN", Decimal("100.0"))
|
|
|
|
# 2. Credit check errors: missing fields, customer not found, unauthenticated
|
|
c_missing = self.controller.check_credit_exposure(self.auth_sales, self.tenant_id, {})
|
|
self.assertEqual(c_missing["status_code"], 400)
|
|
c_404 = self.controller.check_credit_exposure(
|
|
self.auth_sales, self.tenant_id, {"customer_id": "CUST-NONE", "order_value_inr": 1000.0}
|
|
)
|
|
self.assertEqual(c_404["status_code"], 404)
|
|
c_unauth = self.controller.check_credit_exposure(None, self.tenant_id, {"customer_id": "CUST-001", "order_value_inr": 1000.0})
|
|
self.assertEqual(c_unauth["status_code"], 401)
|
|
|
|
# 3. Order creation errors: missing fields, unauthenticated
|
|
o_missing = self.controller.create_sales_order(self.auth_sales, self.tenant_id, {"customer_id": "CUST-001"})
|
|
self.assertEqual(o_missing["status_code"], 400)
|
|
o_unauth = self.controller.create_sales_order(None, self.tenant_id, {})
|
|
self.assertEqual(o_unauth["status_code"], 401)
|
|
|
|
# 4. Order query: list with customer_id and status filter, 404 for unknown order
|
|
order_payload = {
|
|
"customer_id": "CUST-004",
|
|
"destination_city": "Ujjain",
|
|
"customer_segment": "Distributor",
|
|
"commodity_id": "c0a80123-0000-0000-0000-000000000001",
|
|
"variety": "Yellow Desi",
|
|
"contract_qty_mt": 10.000,
|
|
"contract_rate_per_qtl": 4800.00,
|
|
"payment_terms": "15 Days",
|
|
}
|
|
res_o = self.controller.create_sales_order(self.auth_sales, self.tenant_id, order_payload)
|
|
self.assertEqual(res_o["status_code"], 201)
|
|
o_id = res_o["sales_order"]["id"]
|
|
|
|
list_cust = self.controller.list_sales_orders(self.auth_sales, self.tenant_id, customer_id="CUST-004")
|
|
self.assertEqual(list_cust["status_code"], 200)
|
|
self.assertEqual(list_cust["count"], 1)
|
|
|
|
list_stat = self.controller.list_sales_orders(self.auth_sales, self.tenant_id, status="CONFIRMED")
|
|
self.assertEqual(list_stat["status_code"], 200)
|
|
|
|
get_404 = self.controller.get_sales_order(self.auth_sales, self.tenant_id, "so-nonexistent")
|
|
self.assertEqual(get_404["status_code"], 404)
|
|
|
|
# 5. Lot allocation errors: order 404, missing fields, unauthenticated
|
|
alloc_404 = self.controller.allocate_lot(self.auth_sales, self.tenant_id, "so-nonexistent", {"lot_id": "lot-1"})
|
|
self.assertEqual(alloc_404["status_code"], 404)
|
|
alloc_missing = self.controller.allocate_lot(self.auth_sales, self.tenant_id, o_id, {"lot_id": "lot-1"})
|
|
self.assertEqual(alloc_missing["status_code"], 400)
|
|
|
|
def test_sales_model_validation_invariants(self):
|
|
"""Statement coverage for model validation branches in CustomerSalesOrder and SalesOrderAllocation."""
|
|
with self.assertRaises(ValueError):
|
|
CustomerSalesOrder(
|
|
tenant_id=self.tenant_id,
|
|
sales_order_number="SAL-INV-1",
|
|
customer_id="CUST-001",
|
|
destination_city="Indore",
|
|
customer_segment="InvalidSegment",
|
|
commodity_id="c01",
|
|
variety="Desi",
|
|
contract_qty_mt=Decimal("10.0"),
|
|
contract_rate_per_qtl=Decimal("5000.0"),
|
|
payment_terms="30 Days",
|
|
credit_exposure_ratio=Decimal("50.0"),
|
|
)
|
|
with self.assertRaises(ValueError):
|
|
CustomerSalesOrder(
|
|
tenant_id=self.tenant_id,
|
|
sales_order_number="SAL-INV-2",
|
|
customer_id="CUST-001",
|
|
destination_city="Indore",
|
|
customer_segment="Processor",
|
|
commodity_id="c01",
|
|
variety="Desi",
|
|
contract_qty_mt=Decimal("10.0"),
|
|
contract_rate_per_qtl=Decimal("5000.0"),
|
|
payment_terms="InvalidTerms",
|
|
credit_exposure_ratio=Decimal("50.0"),
|
|
)
|
|
with self.assertRaises(ValueError):
|
|
CustomerSalesOrder(
|
|
tenant_id=self.tenant_id,
|
|
sales_order_number="SAL-INV-3",
|
|
customer_id="CUST-001",
|
|
destination_city="Indore",
|
|
customer_segment="Processor",
|
|
commodity_id="c01",
|
|
variety="Desi",
|
|
contract_qty_mt=Decimal("-10.0"),
|
|
contract_rate_per_qtl=Decimal("5000.0"),
|
|
payment_terms="30 Days",
|
|
credit_exposure_ratio=Decimal("50.0"),
|
|
)
|
|
with self.assertRaises(ValueError):
|
|
CustomerSalesOrder(
|
|
tenant_id=self.tenant_id,
|
|
sales_order_number="SAL-INV-4",
|
|
customer_id="CUST-001",
|
|
destination_city="Indore",
|
|
customer_segment="Processor",
|
|
commodity_id="c01",
|
|
variety="Desi",
|
|
contract_qty_mt=Decimal("10.0"),
|
|
contract_rate_per_qtl=Decimal("-5000.0"),
|
|
payment_terms="30 Days",
|
|
credit_exposure_ratio=Decimal("50.0"),
|
|
)
|
|
with self.assertRaises(ValueError):
|
|
CustomerSalesOrder(
|
|
tenant_id=self.tenant_id,
|
|
sales_order_number="SAL-INV-5",
|
|
customer_id="CUST-001",
|
|
destination_city="Indore",
|
|
customer_segment="Processor",
|
|
commodity_id="c01",
|
|
variety="Desi",
|
|
contract_qty_mt=Decimal("10.0"),
|
|
contract_rate_per_qtl=Decimal("5000.0"),
|
|
payment_terms="30 Days",
|
|
credit_exposure_ratio=Decimal("50.0"),
|
|
credit_override=True,
|
|
override_approved_by=None,
|
|
)
|
|
with self.assertRaises(ValueError):
|
|
SalesOrderAllocation(
|
|
tenant_id=self.tenant_id,
|
|
sales_order_id="so-1",
|
|
lot_id="lot-1",
|
|
warehouse_id="WH-01",
|
|
allocated_qty_mt=Decimal("0.0"),
|
|
allocated_bags=10,
|
|
lot_qc_status="RELEASED",
|
|
available_unreserved_mt=Decimal("100.0"),
|
|
)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|