"""Multi-Path Automated Unit & FSM Test Suite for Quality Lab & Lot Control (UC-006). Covers: - TC-QC-006-01: Inward lab inspection, rebate calculation, and lot release. - TC-QC-006-02: Assay parameter boundary limits (0-100%) and zero rebate FAQ baseline. - TC-QC-006-03: Quality Hold dispatch guard & rejection reason validation. - TC-QC-006-04: Finite state machine transitions & lot splitting lineage traversal. """ from datetime import datetime, timezone from decimal import Decimal import unittest from backend.app.api.quality import QualityController from backend.app.db.session import InMemoryStorage from backend.app.models.quality import InventoryLot, QualityInspection, calculate_quality_rebates from backend.app.models.tenant import Tenant, TenantMembership from sandbox.identity_mock import mock_idp class TestQualityLotControl(unittest.TestCase): def setUp(self): self.store = InMemoryStorage() self.controller = QualityController(store=self.store) self.tenant_id = "tenant-alpha" # Pre-seed active tenant and membership in store self.store.save_tenant( Tenant( tenant_id=self.tenant_id, business_name="Alpha Agro", legal_identifier="24ABCDE1234F1Z5", contact_email="alpha@agro.com", primary_mandi="Kota APMC", status="ACTIVE" ) ) self.store.save_membership( TenantMembership( tenant_id=self.tenant_id, user_id="chemist@alpha.com", email="chemist@alpha.com", role="Quality Officer", status="ACTIVE" ) ) # Seed quality inspector token self.token = mock_idp.mint_jwt( subject="chemist@alpha.com", email="chemist@alpha.com", name="Lab Chemist", roles=["Quality Officer"], tenant_id=self.tenant_id ) self.auth_header = f"Bearer {self.token}" # Pre-seed Sauda and GRN self.sauda_id = "sauda-qc-1" self.store.insert("procurement_sauda", self.tenant_id, { "id": self.sauda_id, "tenant_id": self.tenant_id, "sauda_number": "SDA-26-00055", "trade_rate_per_qtl": 4500.0, "commodity_id": "SOY" }) self.grn_id = "grn-qc-1" self.store.insert("goods_receipt_notes", self.tenant_id, { "id": self.grn_id, "tenant_id": self.tenant_id, "grn_number": "GRN-26-00055", "sauda_id": self.sauda_id, "weighment_slip_id": "slip-qc-1" }) # Pre-seed Lot in QUALITY_HOLD self.lot_id = "lot-qc-1" self.lot_data = { "id": self.lot_id, "tenant_id": self.tenant_id, "lot_number": "LOT-26-10-SOY-00084", "grn_id": self.grn_id, "commodity_id": "SOY", "variety": "Yellow Desi", "grade": "FAQ", "godown_stack_id": "stack-b-04", "initial_quantity_mt": 24.925, "current_quantity_mt": 24.925, "qc_status": "QUALITY_HOLD", "parent_lot_id": None } self.store.insert("inventory_lots", self.tenant_id, self.lot_data) def test_quality_assay_and_rebate_calculation_happy_path(self): """TC-QC-006-01: Analytical assay records moisture/foreign matter rebates and updates FSM.""" payload = { "lot_id": self.lot_id, "sample_code": "SMP-2026-9042", "moisture_pct": 11.5, # FAQ max: 10.0% -> +1.50% excess "foreign_matter_pct": 2.1, # FAQ max: 1.5% -> +0.60% excess "damaged_grain_pct": 1.8, "oil_content_pct": 18.4, "decision": "RELEASED", "remarks": "Produce accepted with commercial moisture and admixture rebate" } res = self.controller.record_inspection(self.auth_header, self.tenant_id, payload) self.assertEqual(res.get("status_code"), 201) insp = res["inspection"] # Moisture deduction: 24.925 * 1.5% = 0.374 MT self.assertEqual(insp["moisture_weight_deduction_mt"], 0.374) self.assertEqual(insp["net_billable_weight_mt"], 24.551) # 24.925 - 0.374 # Rate deduction: 0.60% excess * 30.0 = ₹ 18.00 / Qtl self.assertEqual(insp["rate_deduction_per_qtl"], 18.0) self.assertGreater(insp["total_rebate_amount"], 0.0) # Lot transitioned to RELEASED lot = self.store.get("inventory_lots", self.tenant_id, self.lot_id) self.assertEqual(lot["qc_status"], "RELEASED") def test_assay_parameter_boundaries_and_zero_rebate(self): """TC-QC-006-02: FAQ benchmark assay yields zero rebate; boundary 0-100% enforced.""" # Baseline FAQ assay (moisture = 10.0, foreign = 1.5) -> zero rebate calc_zero = calculate_quality_rebates( lot_quantity_mt=Decimal("20.000"), trade_rate_per_qtl=Decimal("4500.00"), moisture_pct=Decimal("10.00"), foreign_matter_pct=Decimal("1.50") ) self.assertEqual(calc_zero["weight_deduction_mt"], Decimal("0.000")) self.assertEqual(calc_zero["rate_deduction_per_qtl"], Decimal("0.00")) self.assertEqual(calc_zero["total_rebate_amount"], Decimal("0.00")) # Out-of-bounds percentage (< 0.0 or > 100.0) raises ValueError with self.assertRaises(ValueError): calculate_quality_rebates( lot_quantity_mt=Decimal("20.000"), trade_rate_per_qtl=Decimal("4500.00"), moisture_pct=Decimal("-0.5"), foreign_matter_pct=Decimal("1.0") ) with self.assertRaises(ValueError): calculate_quality_rebates( lot_quantity_mt=Decimal("20.000"), trade_rate_per_qtl=Decimal("4500.00"), moisture_pct=Decimal("10.0"), foreign_matter_pct=Decimal("101.0") ) def test_quality_hold_dispatch_blocking_guard(self): """TC-QC-006-03: Produce in QUALITY_HOLD or REJECTED cannot be dispatched.""" lot = InventoryLot( tenant_id=self.tenant_id, lot_number="LOT-HOLD-01", grn_id="grn-01", commodity_id="SOY", variety="Yellow", godown_stack_id="stack-01", initial_quantity_mt=Decimal("10.000") ) self.assertEqual(lot.qc_status, "QUALITY_HOLD") # Invariant check: Hold blocks dispatch with self.assertRaises(ValueError): lot.assert_can_dispatch() # Reject blocks dispatch lot.transition_qc_status("REJECTED") with self.assertRaises(ValueError): lot.assert_can_dispatch() # Release permits dispatch lot_rel = InventoryLot( tenant_id=self.tenant_id, lot_number="LOT-REL-01", grn_id="grn-01", commodity_id="SOY", variety="Yellow", godown_stack_id="stack-01", initial_quantity_mt=Decimal("10.000") ) lot_rel.transition_qc_status("RELEASED") lot_rel.assert_can_dispatch() # Should not raise def test_lot_split_and_lineage_preservation(self): """TC-QC-006-04: Lot split into child sub-lots preserves ancestry and parent ID.""" lot = InventoryLot( tenant_id=self.tenant_id, lot_number="LOT-PARENT-01", grn_id=self.grn_id, commodity_id="SOY", variety="Yellow", godown_stack_id="stack-01", initial_quantity_mt=Decimal("25.000") ) lot.transition_qc_status("RELEASED") # Split into two child lots: 15 MT and 10 MT children = lot.split_lot([Decimal("15.000"), Decimal("10.000")]) self.assertEqual(len(children), 2) self.assertEqual(children[0].lot_number, "LOT-PARENT-01-SPLIT-1") self.assertEqual(children[0].initial_quantity_mt, Decimal("15.000")) self.assertEqual(children[0].parent_lot_id, lot.id) self.assertEqual(children[0].qc_status, "RELEASED") self.assertEqual(lot.current_quantity_mt, Decimal("0.000")) # Verify lineage retrieval res = self.controller.get_lot_lineage(self.auth_header, self.tenant_id, self.lot_id) self.assertEqual(res.get("status_code"), 200) lineage = res["lineage"] self.assertIsNotNone(lineage.get("lot")) self.assertIsNotNone(lineage.get("goods_receipt_note")) self.assertIsNotNone(lineage.get("procurement_sauda")) def test_unauthenticated_and_unauthorized_quality(self): """TC-QC-006-05: 401 unauthenticated and 403 unauthorized for quality actions.""" res_unauth = self.controller.record_inspection(None, self.tenant_id, {}) self.assertEqual(res_unauth.get("status_code"), 401) token_buyer = mock_idp.mint_jwt( subject="buyer@alpha.com", email="buyer@alpha.com", name="Buyer", roles=["Mandi Buyer"], tenant_id=self.tenant_id ) self.store.save_membership( TenantMembership( tenant_id=self.tenant_id, user_id="buyer@alpha.com", email="buyer@alpha.com", role="Mandi Buyer", status="ACTIVE" ) ) res_bad_role = self.controller.record_inspection(f"Bearer {token_buyer}", self.tenant_id, {}) self.assertEqual(res_bad_role.get("status_code"), 403) res_bad_dec = self.controller.execute_lot_decision(f"Bearer {token_buyer}", self.tenant_id, self.lot_id, {}) self.assertEqual(res_bad_dec.get("status_code"), 403) def test_execute_lot_decision_rejection_and_transitions(self): """TC-QC-006-06: Lot decision transitions, rejection reasons, and invalid state errors.""" # 404 not found res_404 = self.controller.execute_lot_decision(self.auth_header, self.tenant_id, "non-existent", {}) self.assertEqual(res_404.get("status_code"), 404) # REJECTED without reason -> 422 res_no_reason = self.controller.execute_lot_decision( self.auth_header, self.tenant_id, self.lot_id, {"decision": "REJECTED"} ) self.assertEqual(res_no_reason.get("status_code"), 422) # REJECTED with reason -> 200 res_rej = self.controller.execute_lot_decision( self.auth_header, self.tenant_id, self.lot_id, { "decision": "REJECTED", "rejection_reason": "High fungus damage (> 5.0%)" } ) self.assertEqual(res_rej.get("status_code"), 200) self.assertEqual(res_rej["lot"]["qc_status"], "REJECTED") # Invalid transition from REJECTED -> 400 res_invalid = self.controller.execute_lot_decision( self.auth_header, self.tenant_id, self.lot_id, {"decision": "RELEASED"} ) self.assertEqual(res_invalid.get("status_code"), 400) def test_inspection_and_lineage_not_found(self): """TC-QC-006-07: 404 on missing lot for inspection or lineage query.""" res_insp_404 = self.controller.record_inspection( self.auth_header, self.tenant_id, {"lot_id": "non-existent"} ) self.assertEqual(res_insp_404.get("status_code"), 404) res_lin_404 = self.controller.get_lot_lineage(self.auth_header, self.tenant_id, "non-existent") self.assertEqual(res_lin_404.get("status_code"), 404) def test_list_inspections_and_released_net_weight(self): """TC-QC-006-08: List inspections filtering and lot current_quantity_mt update to net billable weight.""" # 1. Record an inspection with RELEASED decision insp_payload = { "lot_id": self.lot_id, "sample_code": "SMP-TEST-001", "moisture_pct": 11.5, "foreign_matter_pct": 2.2, "damaged_grain_pct": 1.8, "oil_content_pct": 18.5, "decision": "RELEASED", "remarks": "Assay verified" } res_insp = self.controller.record_inspection(self.auth_header, self.tenant_id, insp_payload) self.assertEqual(res_insp.get("status_code"), 201) self.assertEqual(res_insp.get("lot_qc_status"), "RELEASED") # Verify lot current_quantity_mt updated to net billable weight (24.925 - 0.374 = 24.551) lot = self.store.get("inventory_lots", self.tenant_id, self.lot_id) self.assertEqual(Decimal(str(lot["current_quantity_mt"])), Decimal("24.551")) # 2. List inspections res_list = self.controller.list_inspections(self.auth_header, self.tenant_id) self.assertEqual(res_list.get("status_code"), 200) self.assertGreaterEqual(res_list.get("count"), 1) # 3. Filter by lot_id res_filtered = self.controller.list_inspections(self.auth_header, self.tenant_id, lot_id=self.lot_id) self.assertEqual(res_filtered.get("status_code"), 200) self.assertEqual(res_filtered.get("count"), 1) # 4. Unauthenticated list res_unauth = self.controller.list_inspections(None, self.tenant_id) self.assertEqual(res_unauth.get("status_code"), 401) if __name__ == "__main__": unittest.main()