410 lines
18 KiB
Python
410 lines
18 KiB
Python
"""Multi-Path Automated Unit & Invariant Test Suite for Warehouse Inventory (UC-007).
|
|
|
|
Covers:
|
|
- TC-WH-007-01: Double-Entry Multi-Godown Stock Ledger Position (Happy Path).
|
|
- TC-WH-007-02: Non-Negative Invariant & Tolerance Boundary Checks (Boundary / Edge Case).
|
|
- TC-WH-007-03: Unauthorized Inter-Godown Deductions & Negative Quantities (Negative / Security).
|
|
- TC-WH-007-04: Godown Capacity 85% Warning & Transfer Tolerance Reconciliation (FSM Invariant).
|
|
"""
|
|
from datetime import datetime, timezone
|
|
from decimal import Decimal
|
|
import unittest
|
|
|
|
from backend.app.api.inventory import InventoryController
|
|
from backend.app.db.session import InMemoryStorage
|
|
from backend.app.models.inventory import (
|
|
StockLedgerEntry,
|
|
StockAdjustment,
|
|
WarehouseCapacity,
|
|
StockTransfer,
|
|
)
|
|
from backend.app.models.tenant import Tenant, TenantMembership
|
|
from sandbox.identity_mock import mock_idp
|
|
from sandbox.warehouse_mock import WarehouseMock
|
|
|
|
|
|
class TestWarehouseInventory(unittest.TestCase):
|
|
|
|
def setUp(self):
|
|
self.store = InMemoryStorage()
|
|
self.controller = InventoryController(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="ops@alphaagro.com",
|
|
primary_mandi="Neemuch APMC",
|
|
status="ACTIVE",
|
|
)
|
|
)
|
|
# Pre-seed Warehouse Manager
|
|
self.store.save_membership(
|
|
TenantMembership(
|
|
tenant_id=self.tenant_id,
|
|
user_id="wh_manager@alphaagro.com",
|
|
email="wh_manager@alphaagro.com",
|
|
role="WAREHOUSE_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_manager = mock_idp.mint_jwt(
|
|
subject="wh_manager@alphaagro.com",
|
|
email="wh_manager@alphaagro.com",
|
|
name="Warehouse Manager",
|
|
roles=["WAREHOUSE_MANAGER"],
|
|
tenant_id=self.tenant_id,
|
|
)
|
|
self.auth_manager = f"Bearer {self.token_manager}"
|
|
|
|
self.token_partner = mock_idp.mint_jwt(
|
|
subject="partner@alphaagro.com",
|
|
email="partner@alphaagro.com",
|
|
name="Alpha Partner",
|
|
roles=["PARTNER"],
|
|
tenant_id=self.tenant_id,
|
|
)
|
|
self.auth_partner = f"Bearer {self.token_partner}"
|
|
|
|
def test_tc_wh_007_01_stock_ledger_and_audit_adjustment_happy_path(self):
|
|
"""TC-WH-007-01: Double-Entry Stock Ledger & Physical Audit Adjustment within 1.0%."""
|
|
# 1. Post initial inward receipt into WH-01
|
|
inward_sle = StockLedgerEntry(
|
|
tenant_id=self.tenant_id,
|
|
warehouse_id="WH-01",
|
|
commodity_id="c0a80123-0000-0000-0000-000000000002",
|
|
variety="Desi",
|
|
grade="FAQ",
|
|
transaction_type="INWARD",
|
|
reference_id="GRN-202610-001",
|
|
opening_mt=Decimal("0.000"),
|
|
opening_bags=0,
|
|
quantity_mt=Decimal("50.000"),
|
|
bags=1000,
|
|
)
|
|
self.store.insert("stock_ledger_entries", self.tenant_id, inward_sle.to_dict())
|
|
|
|
# 2. Query ledger via controller
|
|
res = self.controller.get_ledger(self.auth_manager, self.tenant_id, warehouse_id="WH-01")
|
|
self.assertEqual(res["status_code"], 200)
|
|
self.assertEqual(res["count"], 1)
|
|
entry = res["entries"][0]
|
|
self.assertEqual(entry["closing_mt"], 50.0)
|
|
self.assertEqual(entry["closing_bags"], 1000)
|
|
|
|
# 3. Post audit adjustment of -0.200 MT (-0.40%, within 1.0% limit)
|
|
adj_payload = {
|
|
"warehouse_id": "WH-01",
|
|
"commodity_id": "c0a80123-0000-0000-0000-000000000002",
|
|
"variety": "Desi",
|
|
"grade": "FAQ",
|
|
"variance_mt": -0.200,
|
|
"variance_bags": -4,
|
|
"reason_code": "Moisture Loss / Ghat",
|
|
"balance_before_mt": 50.000,
|
|
"opening_bags": 1000,
|
|
}
|
|
adj_res = self.controller.record_adjustment(self.auth_manager, self.tenant_id, adj_payload)
|
|
self.assertEqual(adj_res["status_code"], 201)
|
|
self.assertEqual(adj_res["adjustment"]["status"], "COMMITTED")
|
|
self.assertFalse(adj_res["adjustment"]["partner_approval_required"])
|
|
|
|
# 4. Verify updated ledger closing stock
|
|
ledger_res = self.controller.get_ledger(self.auth_manager, self.tenant_id, warehouse_id="WH-01")
|
|
self.assertEqual(ledger_res["count"], 2)
|
|
latest = ledger_res["entries"][-1]
|
|
self.assertEqual(latest["transaction_type"], "AUDIT_ADJUSTMENT")
|
|
self.assertEqual(latest["closing_mt"], 49.8)
|
|
self.assertEqual(latest["closing_bags"], 996)
|
|
|
|
def test_tc_wh_007_02_non_negative_invariant_and_partner_approval_boundary(self):
|
|
"""TC-WH-007-02: Non-negative closing stock invariant and Partner approval boundary at 1.0%."""
|
|
# Test 1: Attempt stock deduction resulting in negative balance
|
|
with self.assertRaises(ValueError) as ctx:
|
|
StockLedgerEntry(
|
|
tenant_id=self.tenant_id,
|
|
warehouse_id="WH-01",
|
|
commodity_id="c0a80123-0000-0000-0000-000000000002",
|
|
variety="Desi",
|
|
transaction_type="OUTWARD",
|
|
reference_id="SO-001",
|
|
opening_mt=Decimal("10.000"),
|
|
opening_bags=200,
|
|
quantity_mt=Decimal("10.001"), # exceeds by 0.001 MT
|
|
bags=201,
|
|
)
|
|
self.assertIn("Non-negative stock invariant violated", str(ctx.exception))
|
|
|
|
# Test 2: Exactly zero closing stock succeeds
|
|
zero_sle = StockLedgerEntry(
|
|
tenant_id=self.tenant_id,
|
|
warehouse_id="WH-01",
|
|
commodity_id="c0a80123-0000-0000-0000-000000000002",
|
|
variety="Desi",
|
|
transaction_type="OUTWARD",
|
|
reference_id="SO-002",
|
|
opening_mt=Decimal("10.000"),
|
|
opening_bags=200,
|
|
quantity_mt=Decimal("10.000"),
|
|
bags=200,
|
|
)
|
|
self.assertEqual(zero_sle.closing_mt, Decimal("0.000"))
|
|
self.assertEqual(zero_sle.closing_bags, 0)
|
|
|
|
# Test 3: Adjustment with variance > 1.0% requires Partner approval
|
|
adj_large = {
|
|
"warehouse_id": "WH-01",
|
|
"commodity_id": "c0a80123-0000-0000-0000-000000000002",
|
|
"variety": "Desi",
|
|
"grade": "FAQ",
|
|
"variance_mt": -0.600, # 1.2% of 50.0 MT (> 1.0%)
|
|
"variance_bags": -12,
|
|
"reason_code": "Handling Spillage",
|
|
"balance_before_mt": 50.000,
|
|
"opening_bags": 1000,
|
|
}
|
|
# Manager submits: should be PENDING_APPROVAL
|
|
res_m = self.controller.record_adjustment(self.auth_manager, self.tenant_id, adj_large)
|
|
self.assertEqual(res_m["status_code"], 201)
|
|
self.assertEqual(res_m["adjustment"]["status"], "PENDING_APPROVAL")
|
|
self.assertTrue(res_m["adjustment"]["partner_approval_required"])
|
|
adj_id = res_m["adjustment"]["id"]
|
|
|
|
# Manager tries to approve: 403 Forbidden
|
|
approve_m = self.controller.approve_adjustment(self.auth_manager, self.tenant_id, adj_id)
|
|
self.assertEqual(approve_m["status_code"], 403)
|
|
|
|
# Partner approves: 200 OK and committed
|
|
approve_p = self.controller.approve_adjustment(self.auth_partner, self.tenant_id, adj_id)
|
|
self.assertEqual(approve_p["status_code"], 200)
|
|
self.assertEqual(approve_p["adjustment"]["status"], "COMMITTED")
|
|
self.assertEqual(approve_p["adjustment"]["partner_approved_by"], "partner@alphaagro.com")
|
|
|
|
def test_tc_wh_007_03_invalid_inputs_and_negative_rejections(self):
|
|
"""TC-WH-007-03: Invalid reason codes, negative quantities, and identical origin/destination."""
|
|
# 1. Invalid reason code in adjustment
|
|
invalid_adj = {
|
|
"warehouse_id": "WH-01",
|
|
"commodity_id": "c0a80123-0000-0000-0000-000000000002",
|
|
"variety": "Desi",
|
|
"variance_mt": -0.100,
|
|
"variance_bags": -2,
|
|
"reason_code": "Stolen by Rats", # invalid
|
|
"balance_before_mt": 50.000,
|
|
}
|
|
res_inv = self.controller.record_adjustment(self.auth_manager, self.tenant_id, invalid_adj)
|
|
self.assertEqual(res_inv["status_code"], 400)
|
|
self.assertIn("Invalid reason code", res_inv["error"])
|
|
|
|
# 2. Transfer with same origin and destination
|
|
same_wh_trf = {
|
|
"origin_warehouse_id": "WH-01",
|
|
"destination_warehouse_id": "WH-01",
|
|
"commodity_id": "c0a80123-0000-0000-0000-000000000002",
|
|
"variety": "Desi",
|
|
"dispatched_mt": 25.000,
|
|
"dispatched_bags": 500,
|
|
}
|
|
res_same = self.controller.initiate_transfer(self.auth_manager, self.tenant_id, same_wh_trf)
|
|
self.assertEqual(res_same["status_code"], 400)
|
|
self.assertIn("cannot be the same", res_same["error"])
|
|
|
|
# 3. Transfer with negative quantity
|
|
neg_trf = {
|
|
"origin_warehouse_id": "WH-01",
|
|
"destination_warehouse_id": "WH-02",
|
|
"commodity_id": "c0a80123-0000-0000-0000-000000000002",
|
|
"variety": "Desi",
|
|
"dispatched_mt": -10.000,
|
|
"dispatched_bags": -200,
|
|
}
|
|
res_neg = self.controller.initiate_transfer(self.auth_manager, self.tenant_id, neg_trf)
|
|
self.assertEqual(res_neg["status_code"], 400)
|
|
|
|
def test_tc_wh_007_04_capacity_utilization_and_transfer_fsm_reconciliation(self):
|
|
"""TC-WH-007-04: Godown capacity warning (>85%) & transfer +/-0.2% tolerance reconciliation."""
|
|
# 1. Update WH-01 capacity closing stock to 1,720 MT out of 2,000 MT (86.0%)
|
|
self.controller._update_capacity_closing_stock(self.tenant_id, "WH-01", Decimal("1720.000"))
|
|
cap_res = self.controller.get_capacity(self.auth_manager, self.tenant_id, warehouse_id="WH-01")
|
|
self.assertEqual(cap_res["status_code"], 200)
|
|
cap = cap_res["capacity"]
|
|
self.assertEqual(cap["utilization_pct"], 86.0)
|
|
self.assertTrue(cap["warning_flag"])
|
|
|
|
# 2. Initiate inter-godown transfer from WH-03 to WH-01 (dispatched 20.000 MT, 400 bags)
|
|
trf_payload = {
|
|
"origin_warehouse_id": "WH-03",
|
|
"destination_warehouse_id": "WH-01",
|
|
"commodity_id": "c0a80123-0000-0000-0000-000000000002",
|
|
"variety": "Desi",
|
|
"dispatched_mt": 20.000,
|
|
"dispatched_bags": 400,
|
|
}
|
|
trf_res = self.controller.initiate_transfer(self.auth_manager, self.tenant_id, trf_payload)
|
|
self.assertEqual(trf_res["status_code"], 201)
|
|
trf_id = trf_res["transfer"]["id"]
|
|
self.assertEqual(trf_res["transfer"]["status"], "IN_TRANSIT")
|
|
|
|
# 3. Receive at destination with normal tolerance: 19.970 MT (variance -0.030 MT = 0.15% <= 0.20%)
|
|
recv_payload = {"received_mt": 19.970, "received_bags": 399}
|
|
recv_res = self.controller.receive_transfer(self.auth_manager, self.tenant_id, trf_id, recv_payload)
|
|
self.assertEqual(recv_res["status_code"], 200)
|
|
self.assertEqual(recv_res["transfer"]["status"], "COMPLETED")
|
|
self.assertEqual(recv_res["transfer"]["variance_pct"], 0.15)
|
|
|
|
# 4. Initiate another transfer with variance exceeding tolerance (> 0.20%)
|
|
trf_res2 = self.controller.initiate_transfer(self.auth_manager, self.tenant_id, trf_payload)
|
|
trf_id2 = trf_res2["transfer"]["id"]
|
|
recv_exceeded = {"received_mt": 19.900, "received_bags": 396} # variance 0.100 MT = 0.50%
|
|
recv_res2 = self.controller.receive_transfer(self.auth_manager, self.tenant_id, trf_id2, recv_exceeded)
|
|
self.assertEqual(recv_res2["status_code"], 200)
|
|
self.assertEqual(recv_res2["transfer"]["status"], "SHORTAGE_ALERT")
|
|
self.assertEqual(recv_res2["transfer"]["variance_pct"], 0.50)
|
|
|
|
def test_warehouse_inventory_edge_and_error_cases(self):
|
|
"""Branch coverage: WarehouseMock, errors in adjustments, capacity 404, transfer edge cases."""
|
|
# 1. WarehouseMock tests
|
|
wh_01 = WarehouseMock.get_warehouse("WH-01")
|
|
self.assertIsNotNone(wh_01)
|
|
self.assertIsNone(WarehouseMock.get_warehouse("WH-NONEXISTENT"))
|
|
self.assertGreater(len(WarehouseMock.list_warehouses()), 0)
|
|
stock_all = WarehouseMock.get_initial_stock("WH-01")
|
|
self.assertGreater(len(stock_all), 0)
|
|
stock_chana = WarehouseMock.get_initial_stock("WH-01", "c0a80123-0000-0000-0000-000000000002")
|
|
self.assertEqual(len(stock_chana), 1)
|
|
util_res = WarehouseMock.calculate_utilization("WH-01", Decimal("1800.0"))
|
|
self.assertEqual(util_res["status"], "CAPACITY_WARNING")
|
|
util_norm = WarehouseMock.calculate_utilization("WH-01", Decimal("500.0"))
|
|
self.assertEqual(util_norm["status"], "NORMAL")
|
|
with self.assertRaises(ValueError):
|
|
WarehouseMock.calculate_utilization("WH-NONE", Decimal("100.0"))
|
|
|
|
# 2. Capacity: list all capacities and 404 for unknown warehouse
|
|
all_caps = self.controller.get_capacity(self.auth_manager, self.tenant_id)
|
|
self.assertEqual(all_caps["status_code"], 200)
|
|
self.assertGreater(all_caps["count"], 0)
|
|
cap_404 = self.controller.get_capacity(self.auth_manager, self.tenant_id, warehouse_id="WH-999")
|
|
self.assertEqual(cap_404["status_code"], 404)
|
|
|
|
# 3. Adjustment: positive variance (gain), missing fields, unauthenticated
|
|
gain_payload = {
|
|
"warehouse_id": "WH-01",
|
|
"commodity_id": "c0a80123-0000-0000-0000-000000000002",
|
|
"variety": "Desi",
|
|
"variance_mt": 0.150, # +0.3% gain
|
|
"variance_bags": 3,
|
|
"reason_code": "Seasonal Humidity Gain",
|
|
"balance_before_mt": 50.000,
|
|
"opening_bags": 1000,
|
|
}
|
|
res_gain = self.controller.record_adjustment(self.auth_manager, self.tenant_id, gain_payload)
|
|
self.assertEqual(res_gain["status_code"], 201)
|
|
self.assertEqual(res_gain["adjustment"]["status"], "COMMITTED")
|
|
|
|
# Missing fields in adjustment
|
|
res_missing = self.controller.record_adjustment(self.auth_manager, self.tenant_id, {"warehouse_id": "WH-01"})
|
|
self.assertEqual(res_missing["status_code"], 400)
|
|
|
|
# Unauthenticated adjustment
|
|
res_unauth = self.controller.record_adjustment(None, self.tenant_id, gain_payload)
|
|
self.assertEqual(res_unauth["status_code"], 401)
|
|
|
|
# Approve non-existent adjustment (404) and already committed adjustment (400)
|
|
app_404 = self.controller.approve_adjustment(self.auth_partner, self.tenant_id, "adj-nonexistent")
|
|
self.assertEqual(app_404["status_code"], 404)
|
|
app_dup = self.controller.approve_adjustment(self.auth_partner, self.tenant_id, res_gain["adjustment"]["id"])
|
|
self.assertEqual(app_dup["status_code"], 400)
|
|
|
|
# 4. Transfer error cases: missing fields, transfer 404, wrong status, negative receive MT
|
|
res_trf_missing = self.controller.initiate_transfer(self.auth_manager, self.tenant_id, {"origin_warehouse_id": "WH-01"})
|
|
self.assertEqual(res_trf_missing["status_code"], 400)
|
|
|
|
# Create a valid transfer first, then test receiving with missing fields (400)
|
|
trf_test = self.controller.initiate_transfer(
|
|
self.auth_manager,
|
|
self.tenant_id,
|
|
{
|
|
"origin_warehouse_id": "WH-03",
|
|
"destination_warehouse_id": "WH-02",
|
|
"commodity_id": "c0a80123-0000-0000-0000-000000000002",
|
|
"variety": "Desi",
|
|
"dispatched_mt": 10.0,
|
|
"dispatched_bags": 200,
|
|
},
|
|
)
|
|
trf_test_id = trf_test["transfer"]["id"]
|
|
recv_missing = self.controller.receive_transfer(self.auth_manager, self.tenant_id, trf_test_id, {})
|
|
self.assertEqual(recv_missing["status_code"], 400)
|
|
|
|
def test_inventory_model_validation_invariants(self):
|
|
"""Statement coverage for model validation branches in StockLedgerEntry, StockAdjustment, WarehouseCapacity, StockTransfer."""
|
|
# Invalid transaction type
|
|
with self.assertRaises(ValueError):
|
|
StockLedgerEntry(
|
|
tenant_id=self.tenant_id,
|
|
warehouse_id="WH-01",
|
|
commodity_id="c01",
|
|
variety="Desi",
|
|
transaction_type="INVALID_TYPE",
|
|
reference_id="ref",
|
|
opening_mt=Decimal("10.0"),
|
|
opening_bags=200,
|
|
quantity_mt=Decimal("1.0"),
|
|
bags=20,
|
|
)
|
|
# StockAdjustment without partner id
|
|
adj = StockAdjustment(
|
|
tenant_id=self.tenant_id,
|
|
warehouse_id="WH-01",
|
|
commodity_id="c01",
|
|
variety="Desi",
|
|
variance_mt=Decimal("-2.0"),
|
|
variance_bags=-40,
|
|
reason_code="Moisture Loss / Ghat",
|
|
balance_before_mt=Decimal("100.0"),
|
|
)
|
|
with self.assertRaises(ValueError):
|
|
adj.approve_and_commit("")
|
|
|
|
# WarehouseCapacity invalid total capacity
|
|
with self.assertRaises(ValueError):
|
|
WarehouseCapacity(
|
|
tenant_id=self.tenant_id,
|
|
warehouse_id="WH-01",
|
|
name="WH",
|
|
city="Indore",
|
|
total_capacity_mt=Decimal("0.0"),
|
|
)
|
|
|
|
# StockTransfer negative receive
|
|
trf = StockTransfer(
|
|
tenant_id=self.tenant_id,
|
|
transfer_number="TRF-01",
|
|
origin_warehouse_id="WH-01",
|
|
destination_warehouse_id="WH-02",
|
|
commodity_id="c01",
|
|
variety="Desi",
|
|
dispatched_mt=Decimal("10.0"),
|
|
dispatched_bags=200,
|
|
)
|
|
with self.assertRaises(ValueError):
|
|
trf.record_receipt(Decimal("0.0"), 0)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|