develop #7
|
|
@ -181,6 +181,24 @@ class LogisticsController:
|
|||
|
||||
tenant_id = auth_res["tenant_id"]
|
||||
user_id = auth_res["user_id"]
|
||||
roles = auth_res.get("roles", [])
|
||||
|
||||
allowed_roles = {
|
||||
"Logistics Coordinator", "LOGISTICS_COORDINATOR",
|
||||
"Warehouse Clerk", "WAREHOUSE_CLERK",
|
||||
"Warehouse Manager", "WAREHOUSE_MANAGER",
|
||||
"Sales Executive", "SALES_EXECUTIVE",
|
||||
"Sales Manager", "SALES_MANAGER",
|
||||
"Accounts Executive", "ACCOUNTS_EXECUTIVE",
|
||||
"Partner / MD", "PARTNER", "Managing Director",
|
||||
"Tenant Administrator", "TENANT_ADMINISTRATOR", "Admin", "ADMIN"
|
||||
}
|
||||
if not any(r in allowed_roles for r in roles):
|
||||
return {
|
||||
"status_code": 403,
|
||||
"error": "INSUFFICIENT_PERMISSIONS",
|
||||
"message": "Only Logistics Coordinators, Warehouse Clerks, Sales Managers, or Tenant Administrators can create outbound dispatches"
|
||||
}
|
||||
|
||||
required = ["sales_order_id", "allocation_id", "vehicle_id", "origin_warehouse_id", "destination_city"]
|
||||
missing = [f for f in required if f not in payload]
|
||||
|
|
|
|||
|
|
@ -0,0 +1,231 @@
|
|||
"""Automated Test Suite for Demo Seed Engine, Teardown Idempotency & Pre-flight Integrity.
|
||||
|
||||
Fulfills:
|
||||
- TC-SEED-COMPLETENESS-001: Verifies all 30 domain collections & 11 personas are populated.
|
||||
- TC-TEARDOWN-IDEMPOTENCY-001: Verifies zero orphaned records after cascade purge & repeatable re-seed.
|
||||
- TC-DEMO-PREFLIGHT-001: Pre-flight smoke validation for all 8 Sales Demo Persona journeys.
|
||||
- TC-VEHICLE-REENTRY-001: Verifies vehicle re-entry guard and contract number lookup fallback.
|
||||
|
||||
Standard: UP-AI v1.5 Phase IV Transition & Sales Demo Standards.
|
||||
"""
|
||||
from decimal import Decimal
|
||||
import unittest
|
||||
from typing import Dict, Any
|
||||
|
||||
from backend.app.db.session import InMemoryStorage
|
||||
from backend.app.db.demo_seed import seed_demo_dataset, purge_demo_dataset, CASCADE_PURGE_ORDER
|
||||
from backend.app.api.receiving import ReceivingController
|
||||
from backend.app.api.inventory import InventoryController
|
||||
from backend.app.api.quality import QualityController
|
||||
from backend.app.api.sales import SalesController
|
||||
from backend.app.api.logistics import LogisticsController
|
||||
from backend.app.api.finance import FinanceController
|
||||
from backend.app.api.alerts import AlertsController
|
||||
from backend.app.api.reporting import ReportingController
|
||||
from backend.app.api.procurement import ProcurementController
|
||||
from backend.app.api.market import MarketController
|
||||
from sandbox.identity_mock import mock_idp, TEST_PERSONAS
|
||||
|
||||
|
||||
class TestDemoSeedPipeline(unittest.TestCase):
|
||||
"""Rigorous invariant testing for the Sales Demo Ingestion and Teardown Pipeline."""
|
||||
|
||||
def setUp(self):
|
||||
self.store = InMemoryStorage()
|
||||
self.tenant_id = "demo-malwa-agri"
|
||||
self.summary = seed_demo_dataset(self.store, self.tenant_id)
|
||||
|
||||
def test_01_seed_dataset_completeness(self):
|
||||
"""TC-SEED-COMPLETENESS-001: Verifies all essential demo entities are populated."""
|
||||
self.assertEqual(self.summary["tenant_id"], self.tenant_id)
|
||||
self.assertGreaterEqual(self.summary["commodities"], 4)
|
||||
self.assertGreaterEqual(self.summary["varieties"], 5)
|
||||
self.assertGreaterEqual(self.summary["godowns"], 2)
|
||||
self.assertGreaterEqual(self.summary["counterparties"], 5)
|
||||
self.assertGreaterEqual(self.summary["procurement_sauda"], 4)
|
||||
self.assertEqual(self.summary["gate_entries"], 1)
|
||||
self.assertEqual(self.summary["weighbridge_slips"], 1)
|
||||
self.assertEqual(self.summary["goods_receipt_notes"], 1)
|
||||
self.assertEqual(self.summary["inventory_lots"], 1)
|
||||
self.assertEqual(self.summary["stock_ledger_entries"], 2)
|
||||
self.assertEqual(self.summary["quality_inspections"], 1)
|
||||
self.assertEqual(self.summary["sales_orders"], 1)
|
||||
self.assertEqual(self.summary["dispatches"], 1)
|
||||
self.assertEqual(self.summary["bilties"], 1)
|
||||
self.assertEqual(self.summary["subledger_entries"], 1)
|
||||
self.assertEqual(self.summary["payables"], 1)
|
||||
self.assertEqual(self.summary["cess_vouchers"], 1)
|
||||
self.assertGreaterEqual(self.summary["alerts"], 2)
|
||||
|
||||
# Verify stock ledger entries are present with valid arithmetic balances
|
||||
sles = self.store.list("stock_ledger_entries", self.tenant_id)
|
||||
self.assertEqual(len(sles), 2)
|
||||
inward_sle = next(e for e in sles if e["transaction_type"] == "INWARD")
|
||||
outward_sle = next(e for e in sles if e["transaction_type"] == "OUTWARD")
|
||||
self.assertEqual(inward_sle["reference_id"], "GRN-2026-001")
|
||||
self.assertEqual(inward_sle["closing_mt"], 3150.0)
|
||||
self.assertEqual(outward_sle["reference_id"], "BLT-2026-089")
|
||||
self.assertEqual(outward_sle["closing_mt"], 3126.0)
|
||||
|
||||
def test_02_teardown_cascade_and_idempotency(self):
|
||||
"""TC-TEARDOWN-IDEMPOTENCY-001: Purge cleans all collections, re-seed succeeds identically."""
|
||||
purged = purge_demo_dataset(self.store, self.tenant_id)
|
||||
self.assertIn("stock_ledger_entries", purged)
|
||||
self.assertIn("goods_receipt_notes", purged)
|
||||
self.assertIn("customer_sales_orders", purged)
|
||||
|
||||
# Verify every collection in CASCADE_PURGE_ORDER is now empty
|
||||
for table, label in CASCADE_PURGE_ORDER:
|
||||
records = self.store.list(table, self.tenant_id)
|
||||
self.assertEqual(
|
||||
len(records), 0,
|
||||
f"Collection '{table}' ({label}) was not completely wiped during purge"
|
||||
)
|
||||
|
||||
# Verify idempotency by re-seeding immediately
|
||||
summary_2 = seed_demo_dataset(self.store, self.tenant_id)
|
||||
self.assertEqual(summary_2["stock_ledger_entries"], 2)
|
||||
self.assertEqual(summary_2["gate_entries"], 1)
|
||||
self.assertEqual(summary_2["procurement_sauda"], 4)
|
||||
|
||||
def test_03_preflight_demo_journey_endpoints(self):
|
||||
"""TC-DEMO-PREFLIGHT-001: Pre-flight smoke validation for all 8 Sales Demo Personas."""
|
||||
# 1. Journey 1: Mandi Buyer (buyer@malwa-agri.demo)
|
||||
buyer_token = f"Bearer mock_token_buyer@malwa-agri.demo"
|
||||
mkt_ctrl = MarketController(store=self.store)
|
||||
mkt_res = mkt_ctrl.get_latest_rates(buyer_token, self.tenant_id, "c0a80123-demo-0000-0000-000000000001")
|
||||
self.assertEqual(mkt_res.get("status_code", 200), 200)
|
||||
|
||||
proc_ctrl = ProcurementController(store=self.store)
|
||||
sauda_res = proc_ctrl.list_saudas(buyer_token, self.tenant_id)
|
||||
self.assertEqual(sauda_res.get("status_code", 200), 200)
|
||||
self.assertGreaterEqual(sauda_res.get("count", 0), 1)
|
||||
|
||||
# 2. Journey 2: Yard Supervisor (yard@malwa-agri.demo)
|
||||
yard_token = f"Bearer mock_token_yard@malwa-agri.demo"
|
||||
rec_ctrl = ReceivingController(store=self.store)
|
||||
ge_res = rec_ctrl.list_gate_entries(yard_token, self.tenant_id)
|
||||
self.assertEqual(ge_res.get("status_code", 200), 200)
|
||||
self.assertGreaterEqual(ge_res.get("count", 0), 1)
|
||||
first_ge = ge_res["gate_entries"][0]
|
||||
self.assertEqual(first_ge.get("pass_number"), "GP-2026-001")
|
||||
self.assertEqual(first_ge.get("status"), "GRN_ISSUED")
|
||||
|
||||
# 3. Journey 3: Quality Officer (qc@malwa-agri.demo)
|
||||
qc_token = f"Bearer mock_token_qc@malwa-agri.demo"
|
||||
qc_ctrl = QualityController(store=self.store)
|
||||
lots_res = qc_ctrl.get_lot_lineage(qc_token, self.tenant_id, "lot-demo-001")
|
||||
self.assertEqual(lots_res.get("status_code", 200), 200)
|
||||
self.assertIn("lineage", lots_res)
|
||||
self.assertIn("lot", lots_res["lineage"])
|
||||
|
||||
# 4. Journey 4: Warehouse Manager (whmgr@malwa-agri.demo)
|
||||
whmgr_token = f"Bearer mock_token_whmgr@malwa-agri.demo"
|
||||
inv_ctrl = InventoryController(store=self.store)
|
||||
led_res = inv_ctrl.get_ledger(whmgr_token, self.tenant_id)
|
||||
self.assertEqual(led_res.get("status_code", 200), 200)
|
||||
self.assertEqual(led_res.get("count", 0), 2)
|
||||
# Verify UI aliases
|
||||
self.assertIn("entry_type", led_res["entries"][0])
|
||||
self.assertIn("running_balance_mt", led_res["entries"][0])
|
||||
|
||||
# 5. Journey 5: Sales Executive (sales@malwa-agri.demo)
|
||||
sales_token = f"Bearer mock_token_sales@malwa-agri.demo"
|
||||
sales_ctrl = SalesController(store=self.store)
|
||||
so_res = sales_ctrl.list_sales_orders(sales_token, self.tenant_id)
|
||||
self.assertEqual(so_res.get("status_code", 200), 200)
|
||||
self.assertGreaterEqual(so_res.get("count", 0), 1)
|
||||
|
||||
# 6. Journey 6: Logistics Coordinator (logistics@malwa-agri.demo)
|
||||
logistics_token = f"Bearer mock_token_logistics@malwa-agri.demo"
|
||||
log_ctrl = LogisticsController(store=self.store)
|
||||
dsp_res = log_ctrl.list_dispatches(logistics_token, self.tenant_id)
|
||||
self.assertEqual(dsp_res.get("status_code", 200), 200)
|
||||
self.assertGreaterEqual(dsp_res.get("count", 0), 1)
|
||||
|
||||
# 7. Journey 7: Accounts Executive (finance@malwa-agri.demo)
|
||||
fin_token = f"Bearer mock_token_finance@malwa-agri.demo"
|
||||
fin_ctrl = FinanceController(store=self.store)
|
||||
vch_res = fin_ctrl.list_expense_vouchers(fin_token, self.tenant_id)
|
||||
self.assertEqual(vch_res.get("status_code", 200), 200)
|
||||
self.assertGreaterEqual(vch_res.get("count", 0), 1)
|
||||
|
||||
# 8. Journey 8: Partner / MD (director@malwa-agri.demo)
|
||||
director_token = f"Bearer mock_token_director@malwa-agri.demo"
|
||||
rep_ctrl = ReportingController(store=self.store)
|
||||
dash_res = rep_ctrl.get_dashboard(director_token, self.tenant_id)
|
||||
self.assertEqual(dash_res.get("status_code", 200), 200)
|
||||
self.assertIn("metrics", dash_res)
|
||||
|
||||
alert_ctrl = AlertsController(store=self.store)
|
||||
alt_res = alert_ctrl.list_alerts(director_token, self.tenant_id)
|
||||
self.assertEqual(alt_res.get("status_code", 200), 200)
|
||||
self.assertGreaterEqual(alt_res.get("count", 0), 2)
|
||||
|
||||
def test_04_vehicle_reentry_and_sauda_alias_handling(self):
|
||||
"""TC-VEHICLE-REENTRY-001: Verifies vehicle re-entry guard and contract number lookup fallback."""
|
||||
yard_token = f"Bearer mock_token_yard@malwa-agri.demo"
|
||||
rec_ctrl = ReceivingController(store=self.store)
|
||||
|
||||
# 1. Existing truck MP09GH4521 has status GRN_ISSUED. It should be allowed to check in again
|
||||
res1 = rec_ctrl.create_gate_entry(
|
||||
yard_token,
|
||||
self.tenant_id,
|
||||
{
|
||||
"vehicle_number": "MP09GH4521",
|
||||
"eway_bill_number": "281099112233",
|
||||
"driver_name": "Sunil Yadav",
|
||||
"driver_mobile": "9826012345",
|
||||
"sauda_id": "sda-demo-001",
|
||||
"supplier_invoice_no": "INV-NEW-001",
|
||||
"supplier_dispatch_weight_mt": "25.0",
|
||||
"supplier_dispatch_bags": 500,
|
||||
"is_seal_intact": True
|
||||
}
|
||||
)
|
||||
self.assertEqual(res1.get("status_code"), 201)
|
||||
self.assertTrue(res1.get("success"))
|
||||
|
||||
# 2. While MP09GH4521 is now in status GATE_IN, submitting again immediately MUST be rejected
|
||||
res2 = rec_ctrl.create_gate_entry(
|
||||
yard_token,
|
||||
self.tenant_id,
|
||||
{
|
||||
"vehicle_number": "MP09GH4521",
|
||||
"eway_bill_number": "281099112244",
|
||||
"driver_name": "Sunil Yadav",
|
||||
"driver_mobile": "9826012345",
|
||||
"sauda_id": "sda-demo-001",
|
||||
"supplier_invoice_no": "INV-NEW-002",
|
||||
"supplier_dispatch_weight_mt": "25.0",
|
||||
"supplier_dispatch_bags": 500,
|
||||
"is_seal_intact": True
|
||||
}
|
||||
)
|
||||
self.assertEqual(res2.get("status_code"), 409)
|
||||
self.assertEqual(res2.get("error"), "VEHICLE_ALREADY_IN_YARD")
|
||||
|
||||
# 3. Lookup sauda using contract number SDA-2026-001 instead of UUID
|
||||
res3 = rec_ctrl.create_gate_entry(
|
||||
yard_token,
|
||||
self.tenant_id,
|
||||
{
|
||||
"vehicle_number": "MP09ZX9999",
|
||||
"eway_bill_number": "281099112255",
|
||||
"driver_name": "Kailash Sharma",
|
||||
"driver_mobile": "9826055555",
|
||||
"sauda_id": "SDA-2026-001", # Human-readable contract number
|
||||
"supplier_invoice_no": "INV-NEW-003",
|
||||
"supplier_dispatch_weight_mt": "20.0",
|
||||
"supplier_dispatch_bags": 400,
|
||||
"is_seal_intact": True
|
||||
}
|
||||
)
|
||||
self.assertEqual(res3.get("status_code"), 201)
|
||||
self.assertTrue(res3.get("success"))
|
||||
self.assertEqual(res3["gate_entry"]["sauda_id"], "sda-demo-001")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
||||
|
|
@ -0,0 +1,214 @@
|
|||
"""Automated End-to-End Persona RBAC Matrix Test Suite.
|
||||
|
||||
Fulfills:
|
||||
- TC-RBAC-MAT-001: 11-Persona × Endpoint Access Matrix across all domain controllers.
|
||||
- TC-RBAC-YARD-001: Explicit authorization of Yard Supervisor on gate passes and GRN issuance.
|
||||
- TC-RBAC-MD-001: Executive override & read authority of Partner / MD across quality, alerts, finance.
|
||||
- TC-SOD-ENFORCE-001: Hard segregation-of-duties rejection across cross-domain boundaries.
|
||||
|
||||
Standard: UP-AI v1.5 Phase IV Transition Quality Standards.
|
||||
"""
|
||||
from decimal import Decimal
|
||||
import unittest
|
||||
from typing import Dict, Any
|
||||
|
||||
from backend.app.db.session import InMemoryStorage
|
||||
from backend.app.db.demo_seed import seed_demo_dataset
|
||||
from backend.app.api.receiving import ReceivingController
|
||||
from backend.app.api.quality import QualityController
|
||||
from backend.app.api.inventory import InventoryController
|
||||
from backend.app.api.sales import SalesController
|
||||
from backend.app.api.logistics import LogisticsController
|
||||
from backend.app.api.finance import FinanceController
|
||||
from backend.app.api.alerts import AlertsController
|
||||
from backend.app.api.reporting import ReportingController
|
||||
from backend.app.api.analytics import AnalyticsController
|
||||
from backend.app.auth.rbac import PRD_ROLES
|
||||
from sandbox.identity_mock import mock_idp
|
||||
|
||||
|
||||
class TestRBACPersonaMatrix(unittest.TestCase):
|
||||
"""Rigorous Persona RBAC Matrix test verifying all 11 PRD roles."""
|
||||
|
||||
def setUp(self):
|
||||
self.store = InMemoryStorage()
|
||||
self.tenant_id = "demo-malwa-agri"
|
||||
seed_demo_dataset(self.store, self.tenant_id)
|
||||
|
||||
self.rec_ctrl = ReceivingController(store=self.store)
|
||||
self.qc_ctrl = QualityController(store=self.store)
|
||||
self.inv_ctrl = InventoryController(store=self.store)
|
||||
self.sales_ctrl = SalesController(store=self.store)
|
||||
self.log_ctrl = LogisticsController(store=self.store)
|
||||
self.fin_ctrl = FinanceController(store=self.store)
|
||||
self.alt_ctrl = AlertsController(store=self.store)
|
||||
self.rep_ctrl = ReportingController(store=self.store)
|
||||
self.ana_ctrl = AnalyticsController(store=self.store)
|
||||
|
||||
ROLE_EMAIL_MAP = {
|
||||
"Mandi Buyer": "buyer@malwa-agri.demo",
|
||||
"Purchase Manager": "pmgr@malwa-agri.demo",
|
||||
"Quality Officer": "qc@malwa-agri.demo",
|
||||
"Yard Supervisor": "yard@malwa-agri.demo",
|
||||
"Warehouse Manager": "whmgr@malwa-agri.demo",
|
||||
"Sales Executive": "sales@malwa-agri.demo",
|
||||
"Sales Manager": "smgr@malwa-agri.demo",
|
||||
"Logistics Coordinator": "logistics@malwa-agri.demo",
|
||||
"Accounts Executive": "finance@malwa-agri.demo",
|
||||
"Partner / MD": "director@malwa-agri.demo",
|
||||
"Tenant Administrator": "admin@malwa-agri.demo",
|
||||
"System Administrator": "sysadmin@platform.local",
|
||||
}
|
||||
|
||||
def _token_for_role(self, role: str) -> str:
|
||||
email = self.ROLE_EMAIL_MAP.get(role, f"test_user_{role.replace(' ', '_').lower()}@malwa-agri.demo")
|
||||
token = mock_idp.mint_jwt(
|
||||
subject=f"usr_{email}",
|
||||
email=email,
|
||||
name=f"Test {role}",
|
||||
roles=[role],
|
||||
tenant_id=self.tenant_id
|
||||
)
|
||||
return f"Bearer {token}"
|
||||
|
||||
def test_01_yard_supervisor_positive_permissions(self):
|
||||
"""TC-RBAC-YARD-001: Asserts Yard Supervisor is authorized to create gate entries and GRNs."""
|
||||
yard_token = self._token_for_role("Yard Supervisor")
|
||||
|
||||
# 1. Gate entry creation
|
||||
ge_res = self.rec_ctrl.create_gate_entry(
|
||||
yard_token,
|
||||
self.tenant_id,
|
||||
{
|
||||
"vehicle_number": "MP09AB5566",
|
||||
"eway_bill_number": "281099119988",
|
||||
"driver_name": "Devendra",
|
||||
"driver_mobile": "9826011111",
|
||||
"sauda_id": "sda-demo-001",
|
||||
"supplier_invoice_no": "INV-YS-001",
|
||||
"supplier_dispatch_weight_mt": "25.0",
|
||||
"supplier_dispatch_bags": 500,
|
||||
"is_seal_intact": True
|
||||
}
|
||||
)
|
||||
self.assertEqual(ge_res.get("status_code"), 201, f"Yard Supervisor was denied gate entry: {ge_res}")
|
||||
self.assertTrue(ge_res.get("success"))
|
||||
|
||||
# 2. Gate entry listing
|
||||
list_res = self.rec_ctrl.list_gate_entries(yard_token, self.tenant_id)
|
||||
self.assertEqual(list_res.get("status_code"), 200)
|
||||
|
||||
def test_02_partner_md_positive_permissions(self):
|
||||
"""TC-RBAC-MD-001: Asserts Partner / MD has executive access across operational controllers."""
|
||||
md_token = self._token_for_role("Partner / MD")
|
||||
|
||||
# 1. Market price trends analytics
|
||||
ana_res = self.ana_ctrl.get_market_trends(
|
||||
md_token, self.tenant_id,
|
||||
commodity_id="c0a80123-demo-0000-0000-000000000001",
|
||||
mandi_id="indore-mandi-01"
|
||||
)
|
||||
self.assertEqual(ana_res.get("status_code"), 200, f"Partner / MD denied analytics: {ana_res}")
|
||||
|
||||
# 2. Operational hazard alerts acknowledgment
|
||||
alt_res = self.alt_ctrl.acknowledge_alert(
|
||||
md_token, self.tenant_id, "alert-demo-01",
|
||||
{"action_note": "MD verified exposure with customer CFO"}
|
||||
)
|
||||
self.assertEqual(alt_res.get("status_code"), 200, f"Partner / MD denied alert acknowledgment: {alt_res}")
|
||||
|
||||
# 3. Executive reporting & dashboard
|
||||
rep_res = self.rep_ctrl.get_dashboard(md_token, self.tenant_id)
|
||||
self.assertEqual(rep_res.get("status_code"), 200, f"Partner / MD denied executive report: {rep_res}")
|
||||
self.assertIn("metrics", rep_res)
|
||||
|
||||
# 4. Warehouse stock adjustment with partner approval
|
||||
adj_res = self.inv_ctrl.record_adjustment(
|
||||
md_token, self.tenant_id,
|
||||
{
|
||||
"warehouse_id": "godown-demo-indore",
|
||||
"commodity_id": "c0a80123-demo-0000-0000-000000000001",
|
||||
"variety": "Yellow FAQ",
|
||||
"variance_mt": 1.5,
|
||||
"variance_bags": 30,
|
||||
"reason_code": "Handling Spillage",
|
||||
"balance_before_mt": 3150.0,
|
||||
"balance_before_bags": 63000
|
||||
}
|
||||
)
|
||||
self.assertEqual(adj_res.get("status_code"), 201, f"Partner / MD denied stock adjustment: {adj_res}")
|
||||
self.assertEqual(adj_res["adjustment"]["status"], "COMMITTED")
|
||||
|
||||
def test_03_sod_negative_boundary_rejections(self):
|
||||
"""TC-SOD-ENFORCE-001: Asserts strict 403 Forbidden on unpermitted cross-domain operations."""
|
||||
# 1. Mandi Buyer CANNOT create inward gate entry
|
||||
buyer_token = self._token_for_role("Mandi Buyer")
|
||||
buyer_ge = self.rec_ctrl.create_gate_entry(
|
||||
buyer_token,
|
||||
self.tenant_id,
|
||||
{
|
||||
"vehicle_number": "MP09AB7788",
|
||||
"eway_bill_number": "281099110000",
|
||||
"driver_name": "Ramesh",
|
||||
"driver_mobile": "9826022222",
|
||||
"sauda_id": "sda-demo-001",
|
||||
"supplier_invoice_no": "INV-ERR-001",
|
||||
"supplier_dispatch_weight_mt": "25.0",
|
||||
"supplier_dispatch_bags": 500
|
||||
}
|
||||
)
|
||||
self.assertEqual(buyer_ge.get("status_code"), 403)
|
||||
self.assertEqual(buyer_ge.get("error"), "INSUFFICIENT_PERMISSIONS")
|
||||
|
||||
# 2. Yard Supervisor CANNOT commit lab quality decisions
|
||||
yard_token = self._token_for_role("Yard Supervisor")
|
||||
yard_qc = self.qc_ctrl.execute_lot_decision(
|
||||
yard_token, self.tenant_id, "lot-demo-001",
|
||||
{"decision": "RELEASED", "approver_notes": "Attempted yard approval"}
|
||||
)
|
||||
self.assertEqual(yard_qc.get("status_code"), 403)
|
||||
|
||||
# 3. Quality Officer CANNOT create outbound dispatches
|
||||
qc_token = self._token_for_role("Quality Officer")
|
||||
qc_dsp = self.log_ctrl.create_dispatch(
|
||||
qc_token, self.tenant_id,
|
||||
{
|
||||
"sales_order_id": "so-demo-001",
|
||||
"allocation_id": "alloc-demo-001",
|
||||
"vehicle_id": "veh-demo-01",
|
||||
"origin_warehouse_id": "godown-demo-indore",
|
||||
"destination_city": "Pithampur"
|
||||
}
|
||||
)
|
||||
self.assertEqual(qc_dsp.get("status_code"), 403)
|
||||
|
||||
# 4. Sales Executive CANNOT override credit locks (requires Sales Manager or Partner)
|
||||
sales_token = self._token_for_role("Sales Executive")
|
||||
sales_ovr = self.fin_ctrl.override_credit_lock(
|
||||
sales_token, self.tenant_id, "lock-demo-001",
|
||||
{"reason": "Unauthorized sales override", "approved_by": "sales@malwa-agri.demo"}
|
||||
)
|
||||
self.assertEqual(sales_ovr.get("status_code"), 403)
|
||||
|
||||
def test_04_all_11_prd_roles_registered(self):
|
||||
"""Validates that PRD_ROLES contains exactly all 11 canonical roles."""
|
||||
self.assertEqual(len(PRD_ROLES), 11)
|
||||
for role in [
|
||||
"Tenant Administrator",
|
||||
"Mandi Buyer",
|
||||
"Purchase Manager",
|
||||
"Yard Supervisor",
|
||||
"Quality Officer",
|
||||
"Sales Executive",
|
||||
"Sales Manager",
|
||||
"Logistics Coordinator",
|
||||
"Accounts Executive",
|
||||
"Partner / MD",
|
||||
"System Administrator"
|
||||
]:
|
||||
self.assertIn(role, PRD_ROLES)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
||||
|
|
@ -0,0 +1,127 @@
|
|||
"""Automated Test Suite for UI Role-Based Navigation Matrix & Default Tab Resolution.
|
||||
|
||||
Fulfills:
|
||||
- TC-UI-NAV-001: Persona-to-Default Tab Resolution Verification.
|
||||
- TC-UI-NAV-002: Non-Empty Operational Sidebar Invariant for all 11 PRD Roles.
|
||||
- TC-UI-DEADEND-001: Dead-end prevention invariant (no persona lands on a hidden/unauthorized tab).
|
||||
|
||||
Standard: UP-AI v1.5 Phase IV Transition Quality Standards.
|
||||
"""
|
||||
import re
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
class TestUINavigationMatrix(unittest.TestCase):
|
||||
"""Parses and validates App.tsx navigation definitions to guarantee zero dead-end user journeys."""
|
||||
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
app_file = Path(__file__).resolve().parents[2] / "frontend" / "src" / "App.tsx"
|
||||
assert app_file.exists(), f"App.tsx not found at {app_file}"
|
||||
cls.app_code = app_file.read_text(encoding="utf-8")
|
||||
|
||||
# 11 Canonical PRD Roles
|
||||
cls.ALL_PRD_ROLES = [
|
||||
"Tenant Administrator",
|
||||
"Mandi Buyer",
|
||||
"Purchase Manager",
|
||||
"Yard Supervisor",
|
||||
"Quality Officer",
|
||||
"Sales Executive",
|
||||
"Sales Manager",
|
||||
"Logistics Coordinator",
|
||||
"Accounts Executive",
|
||||
"Partner / MD",
|
||||
"System Administrator"
|
||||
]
|
||||
|
||||
def _extract_nav_items(self):
|
||||
"""Extracts ALL_NAV_ITEMS mapping tab_id -> list of allowed roles."""
|
||||
nav_match = re.search(r"const ALL_NAV_ITEMS.*?=\s*\[(.*?)\];", self.app_code, re.DOTALL)
|
||||
self.assertIsNotNone(nav_match, "Could not extract ALL_NAV_ITEMS from App.tsx")
|
||||
block = nav_match.group(1)
|
||||
|
||||
items = {}
|
||||
for item_match in re.finditer(r"id:\s*'([^']+)'(?:(?!id:).)*?allowedRoles:\s*\[(.*?)\]", block, re.DOTALL):
|
||||
tab_id = item_match.group(1)
|
||||
roles_str = item_match.group(2)
|
||||
roles = [r.strip().strip("'\"") for r in roles_str.split(",") if r.strip()]
|
||||
items[tab_id] = roles
|
||||
return items
|
||||
|
||||
def _simulate_resolve_default_tab(self, roles):
|
||||
"""Matches resolveDefaultTab implementation from App.tsx."""
|
||||
if any(r in roles for r in ['Partner / MD', 'Tenant Administrator']):
|
||||
return 'dashboard'
|
||||
if any(r in roles for r in ['Mandi Buyer', 'Purchase Manager']):
|
||||
return 'market'
|
||||
if any(r in roles for r in ['Sales Executive', 'Sales Manager']):
|
||||
return 'sales'
|
||||
if any(r in roles for r in ['Accounts Executive']):
|
||||
return 'finance'
|
||||
if any(r in roles for r in ['Quality Officer', 'Lab Chemist']):
|
||||
return 'quality'
|
||||
if any(r in roles for r in ['Yard Supervisor', 'Warehouse Clerk']):
|
||||
return 'receiving'
|
||||
if any(r in roles for r in ['Logistics Coordinator']):
|
||||
return 'logistics'
|
||||
if any(r in roles for r in ['System Administrator']):
|
||||
return 'tenants'
|
||||
return 'market'
|
||||
|
||||
def test_01_all_nav_items_extracted(self):
|
||||
"""Asserts that all core tabs exist in ALL_NAV_ITEMS."""
|
||||
nav_items = self._extract_nav_items()
|
||||
expected_tabs = [
|
||||
'market', 'procurement', 'receiving',
|
||||
'quality', 'inventory', 'sales', 'logistics',
|
||||
'finance', 'dashboard', 'admin', 'members', 'tenants', 'audit', 'sessions'
|
||||
]
|
||||
for t in expected_tabs:
|
||||
self.assertIn(t, nav_items, f"Tab '{t}' is missing from ALL_NAV_ITEMS in App.tsx")
|
||||
|
||||
def test_02_yard_supervisor_has_receiving_and_inventory(self):
|
||||
"""TC-UI-NAV-001: Asserts Yard Supervisor is explicitly allowed on receiving and inventory."""
|
||||
nav_items = self._extract_nav_items()
|
||||
self.assertIn("Yard Supervisor", nav_items["receiving"])
|
||||
self.assertIn("Yard Supervisor", nav_items["inventory"])
|
||||
|
||||
def test_03_logistics_coordinator_has_logistics_and_inventory(self):
|
||||
"""TC-UI-NAV-001: Asserts Logistics Coordinator is explicitly allowed on logistics and inventory."""
|
||||
nav_items = self._extract_nav_items()
|
||||
self.assertIn("Logistics Coordinator", nav_items["logistics"])
|
||||
self.assertIn("Logistics Coordinator", nav_items["inventory"])
|
||||
|
||||
def test_04_every_prd_role_has_valid_landing_tab(self):
|
||||
"""TC-UI-DEADEND-001: Invariant — resolveDefaultTab MUST map to a tab permitted for that role."""
|
||||
nav_items = self._extract_nav_items()
|
||||
|
||||
for role in self.ALL_PRD_ROLES:
|
||||
default_tab = self._simulate_resolve_default_tab([role])
|
||||
allowed_roles = nav_items.get(default_tab, [])
|
||||
|
||||
# Check if role is allowed or if tab allows '*'
|
||||
is_allowed = ('*' in allowed_roles) or (role in allowed_roles)
|
||||
self.assertTrue(
|
||||
is_allowed,
|
||||
f"Role '{role}' defaults to tab '{default_tab}', but is NOT in its allowed roles: {allowed_roles}"
|
||||
)
|
||||
|
||||
def test_05_non_empty_operational_sidebar_for_all_roles(self):
|
||||
"""TC-UI-NAV-002: Invariant — Every PRD role must see at least 2 navigation tabs (not just sessions)."""
|
||||
nav_items = self._extract_nav_items()
|
||||
|
||||
for role in self.ALL_PRD_ROLES:
|
||||
visible_tabs = [
|
||||
tab_id for tab_id, allowed_roles in nav_items.items()
|
||||
if '*' in allowed_roles or role in allowed_roles
|
||||
]
|
||||
self.assertGreaterEqual(
|
||||
len(visible_tabs), 2,
|
||||
f"Role '{role}' only has {len(visible_tabs)} visible tabs ({visible_tabs}). Must have >= 2!"
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Loading…
Reference in New Issue