437 lines
18 KiB
Python
437 lines
18 KiB
Python
"""Multi-Path Automated Unit & Invariant Test Suite for Outbound Dispatch & POD (UC-009).
|
|
|
|
Covers:
|
|
- TC-DISP-009-01: Outbound dispatch scheduling, outward weighbridge & Bilty generation (Happy Path).
|
|
- TC-DISP-009-02: Gross > Tare check and +/- 1.0% loading tolerance boundary checks (Boundary).
|
|
- TC-DISP-009-03: Vehicle maintenance gating & invalid dispatch parameters (Negative).
|
|
- TC-DISP-009-04: POD recording, automated invoice, transit shortage credit note with approval (FSM Invariant).
|
|
"""
|
|
from datetime import datetime, timezone
|
|
from decimal import Decimal
|
|
import unittest
|
|
|
|
from backend.app.api.logistics import LogisticsController
|
|
from backend.app.db.session import InMemoryStorage
|
|
from backend.app.models.logistics import (
|
|
TransportVehicle,
|
|
OutboundDispatch,
|
|
OutwardWeighment,
|
|
DispatchBilty,
|
|
ProofOfDelivery,
|
|
SalesCreditNote,
|
|
)
|
|
from backend.app.models.tenant import Tenant, TenantMembership
|
|
from sandbox.identity_mock import mock_idp
|
|
|
|
|
|
class TestDispatchDelivery(unittest.TestCase):
|
|
|
|
def setUp(self):
|
|
self.store = InMemoryStorage()
|
|
self.controller = LogisticsController(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="logistics@alphaagro.com",
|
|
primary_mandi="Indore APMC",
|
|
status="ACTIVE",
|
|
)
|
|
)
|
|
# Pre-seed Logistics Coordinator
|
|
self.store.save_membership(
|
|
TenantMembership(
|
|
tenant_id=self.tenant_id,
|
|
user_id="logistics_coord@alphaagro.com",
|
|
email="logistics_coord@alphaagro.com",
|
|
role="LOGISTICS_COORDINATOR",
|
|
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",
|
|
)
|
|
)
|
|
|
|
self.token_logistics = mock_idp.mint_jwt(
|
|
subject="logistics_coord@alphaagro.com",
|
|
email="logistics_coord@alphaagro.com",
|
|
name="Logistics Coordinator",
|
|
roles=["LOGISTICS_COORDINATOR"],
|
|
tenant_id=self.tenant_id,
|
|
)
|
|
self.auth_logistics = f"Bearer {self.token_logistics}"
|
|
|
|
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}"
|
|
|
|
def test_tc_disp_009_01_scheduling_and_bilty_generation_happy_path(self):
|
|
"""TC-DISP-009-01: Outbound dispatch scheduling, outward weighbridge & Bilty generation."""
|
|
# 1. Schedule dispatch for sales order with VEH-001 (Available, valid fitness)
|
|
dispatch_payload = {
|
|
"sales_order_id": "so-12345",
|
|
"allocation_id": "alloc-67890",
|
|
"vehicle_id": "VEH-001",
|
|
"origin_warehouse_id": "WH-01",
|
|
"destination_city": "Indore",
|
|
}
|
|
res_disp = self.controller.create_dispatch(self.auth_logistics, self.tenant_id, dispatch_payload)
|
|
self.assertEqual(res_disp["status_code"], 201)
|
|
dispatch = res_disp["dispatch"]
|
|
self.assertEqual(dispatch["status"], "SCHEDULED")
|
|
dispatch_id = dispatch["id"]
|
|
|
|
# Verify vehicle status transitioned to On Route
|
|
veh = self.store.get("transport_fleet", self.tenant_id, "VEH-001")
|
|
self.assertEqual(veh["status"], "On Route")
|
|
|
|
# 2. Record outward weighment:
|
|
# Tare: 10,000 kg, Gross: 35,000 kg -> Net: 25,000 kg = 25.000 MT
|
|
# Allocated: 25.000 MT -> Variance: 0.00% <= 1.0%
|
|
weigh_payload = {
|
|
"tare_weight_kg": 10000.0,
|
|
"gross_weight_kg": 35000.0,
|
|
"allocated_mt": 25.000,
|
|
"loaded_bags": 500,
|
|
"transporter_bilty_no": "TRN-BILTY-001",
|
|
"eway_bill_no": "231234567890",
|
|
"consignee_name": "Adani Wilmar Ltd",
|
|
"vehicle_reg_no": "MP-43-G-1234",
|
|
}
|
|
res_weigh = self.controller.record_outward_weighment(
|
|
self.auth_logistics, self.tenant_id, dispatch_id, weigh_payload
|
|
)
|
|
self.assertEqual(res_weigh["status_code"], 201)
|
|
self.assertEqual(res_weigh["dispatch_status"], "IN_TRANSIT")
|
|
self.assertTrue(res_weigh["bilty"]["is_immutable"])
|
|
self.assertEqual(res_weigh["bilty"]["net_weight_mt"], 25.0)
|
|
|
|
def test_tc_disp_009_02_loading_tolerance_and_gross_tare_boundary(self):
|
|
"""TC-DISP-009-02: Gross <= Tare rejection and loading tolerance (+/-1.0%) boundary check."""
|
|
# 1. Schedule a dispatch
|
|
res_d = self.controller.create_dispatch(
|
|
self.auth_logistics,
|
|
self.tenant_id,
|
|
{
|
|
"sales_order_id": "so-boundary",
|
|
"allocation_id": "alloc-boundary",
|
|
"vehicle_id": "VEH-002",
|
|
"origin_warehouse_id": "WH-01",
|
|
"destination_city": "Nagda",
|
|
},
|
|
)
|
|
self.assertEqual(res_d["status_code"], 201)
|
|
disp_id = res_d["dispatch"]["id"]
|
|
|
|
# Test Gross <= Tare
|
|
invalid_weights = {
|
|
"tare_weight_kg": 12000.0,
|
|
"gross_weight_kg": 12000.0, # equal
|
|
"allocated_mt": 16.000,
|
|
"loaded_bags": 320,
|
|
"transporter_bilty_no": "BLT-ERR",
|
|
"eway_bill_no": "EWAY-ERR",
|
|
}
|
|
res_err1 = self.controller.record_outward_weighment(
|
|
self.auth_logistics, self.tenant_id, disp_id, invalid_weights
|
|
)
|
|
self.assertEqual(res_err1["status_code"], 400)
|
|
self.assertIn("must be greater than Tare weight", res_err1["error"])
|
|
|
|
# Test Exceeding Loading Tolerance (+/- 1.0%):
|
|
# Allocated: 16.000 MT. 1.0% of 16 MT = 0.160 MT.
|
|
# Net weight: 16.200 MT (variance = 0.200 MT = 1.25% > 1.0%)
|
|
exceeded_weights = {
|
|
"tare_weight_kg": 8000.0,
|
|
"gross_weight_kg": 24200.0, # Net = 16,200 kg = 16.200 MT
|
|
"allocated_mt": 16.000,
|
|
"loaded_bags": 324,
|
|
"transporter_bilty_no": "BLT-EXCEED",
|
|
"eway_bill_no": "EWAY-EXCEED",
|
|
}
|
|
res_err2 = self.controller.record_outward_weighment(
|
|
self.auth_logistics, self.tenant_id, disp_id, exceeded_weights
|
|
)
|
|
self.assertEqual(res_err2["status_code"], 400)
|
|
self.assertIn("exceeds +/-1.0% loading tolerance", res_err2["error"])
|
|
|
|
# Test within tolerance: Net = 16.100 MT (variance = 0.100 MT = 0.62% <= 1.0%)
|
|
valid_weights = {
|
|
"tare_weight_kg": 8000.0,
|
|
"gross_weight_kg": 24100.0, # Net = 16,100 kg = 16.100 MT
|
|
"allocated_mt": 16.000,
|
|
"loaded_bags": 322,
|
|
"transporter_bilty_no": "BLT-OK",
|
|
"eway_bill_no": "EWAY-OK",
|
|
}
|
|
res_ok = self.controller.record_outward_weighment(
|
|
self.auth_logistics, self.tenant_id, disp_id, valid_weights
|
|
)
|
|
self.assertEqual(res_ok["status_code"], 201)
|
|
|
|
def test_tc_disp_009_03_vehicle_eligibility_rejections(self):
|
|
"""TC-DISP-009-03: Gating against vehicles in Maintenance or with expired fitness."""
|
|
# 1. Attempt dispatch with VEH-004 (under Maintenance)
|
|
res_maint = self.controller.create_dispatch(
|
|
self.auth_logistics,
|
|
self.tenant_id,
|
|
{
|
|
"sales_order_id": "so-maint",
|
|
"allocation_id": "alloc-maint",
|
|
"vehicle_id": "VEH-004", # Maintenance
|
|
"origin_warehouse_id": "WH-01",
|
|
"destination_city": "Indore",
|
|
},
|
|
)
|
|
self.assertEqual(res_maint["status_code"], 400)
|
|
self.assertIn("under Maintenance", res_maint["error"])
|
|
|
|
# 2. Attempt dispatch with VEH-005 (expired fitness certificate)
|
|
res_fit = self.controller.create_dispatch(
|
|
self.auth_logistics,
|
|
self.tenant_id,
|
|
{
|
|
"sales_order_id": "so-fit",
|
|
"allocation_id": "alloc-fit",
|
|
"vehicle_id": "VEH-005", # Expired fitness
|
|
"origin_warehouse_id": "WH-01",
|
|
"destination_city": "Indore",
|
|
},
|
|
)
|
|
self.assertEqual(res_fit["status_code"], 400)
|
|
self.assertIn("fitness certificate expired", res_fit["error"])
|
|
|
|
def test_tc_disp_009_04_pod_and_shortage_credit_note_fsm_lifecycle(self):
|
|
"""TC-DISP-009-04: POD recording, automated invoice, transit loss credit note & approval."""
|
|
# 1. Create and schedule dispatch
|
|
d_res = self.controller.create_dispatch(
|
|
self.auth_logistics,
|
|
self.tenant_id,
|
|
{
|
|
"sales_order_id": "so-pod",
|
|
"allocation_id": "alloc-pod",
|
|
"vehicle_id": "VEH-001",
|
|
"origin_warehouse_id": "WH-01",
|
|
"destination_city": "Indore",
|
|
},
|
|
)
|
|
disp_id = d_res["dispatch"]["id"]
|
|
|
|
# 2. Record POD with shortage: Dispatched 25.000 MT, Destination 24.250 MT (loss 0.750 MT = 3.0% > 2.0%)
|
|
pod_payload = {
|
|
"dispatched_net_mt": 25.000,
|
|
"dest_weighbridge_net_mt": 24.250,
|
|
"consignee_ack_note": "Consignee weighbridge noted transit spillage in transit",
|
|
"pod_ref": "POD-DOC-9988",
|
|
"contract_rate_per_qtl": 5200.00,
|
|
"customer_id": "CUST-001",
|
|
}
|
|
pod_res = self.controller.record_proof_of_delivery(
|
|
self.auth_logistics, self.tenant_id, disp_id, pod_payload
|
|
)
|
|
self.assertEqual(pod_res["status_code"], 200)
|
|
self.assertEqual(pod_res["dispatch_status"], "DELIVERED")
|
|
self.assertTrue(pod_res["invoice_number"].startswith("INV-"))
|
|
|
|
# Credit note generated
|
|
scn = pod_res["credit_note"]
|
|
self.assertIsNotNone(scn)
|
|
self.assertEqual(scn["shortage_mt"], 0.75)
|
|
self.assertEqual(scn["shortage_pct"], 3.0)
|
|
# Shortage > 2.0% requires manager approval!
|
|
self.assertTrue(scn["manager_approval_required"])
|
|
self.assertFalse(scn["manager_approved"])
|
|
scn_id = scn["id"]
|
|
|
|
# 3. Logistics coordinator tries to approve: 403 Forbidden
|
|
res_unauth = self.controller.approve_credit_note(self.auth_logistics, self.tenant_id, scn_id)
|
|
self.assertEqual(res_unauth["status_code"], 403)
|
|
|
|
# 4. Sales Manager approves: 200 OK
|
|
res_auth = self.controller.approve_credit_note(self.auth_sales, self.tenant_id, scn_id)
|
|
self.assertEqual(res_auth["status_code"], 200)
|
|
self.assertTrue(res_auth["credit_note"]["manager_approved"])
|
|
self.assertEqual(res_auth["credit_note"]["approved_by"], "sales_mgr@alphaagro.com")
|
|
|
|
# 5. Verify vehicle returned to Available status
|
|
veh = self.store.get("transport_fleet", self.tenant_id, "VEH-001")
|
|
self.assertEqual(veh["status"], "Available")
|
|
|
|
def test_dispatch_delivery_edge_and_error_cases(self):
|
|
"""Branch coverage: dispatch queries, weighment/pod 404s, missing fields, unauthenticated."""
|
|
# 1. Query dispatches
|
|
list_all = self.controller.list_dispatches(self.auth_logistics, self.tenant_id)
|
|
self.assertEqual(list_all["status_code"], 200)
|
|
list_sched = self.controller.list_dispatches(self.auth_logistics, self.tenant_id, status="SCHEDULED")
|
|
self.assertEqual(list_sched["status_code"], 200)
|
|
|
|
# 2. Create dispatch errors
|
|
d_missing = self.controller.create_dispatch(self.auth_logistics, self.tenant_id, {"sales_order_id": "so-1"})
|
|
self.assertEqual(d_missing["status_code"], 400)
|
|
d_veh_404 = self.controller.create_dispatch(
|
|
self.auth_logistics,
|
|
self.tenant_id,
|
|
{
|
|
"sales_order_id": "so-1",
|
|
"allocation_id": "alloc-1",
|
|
"vehicle_id": "VEH-NONEXISTENT",
|
|
"origin_warehouse_id": "WH-01",
|
|
"destination_city": "Indore",
|
|
},
|
|
)
|
|
self.assertEqual(d_veh_404["status_code"], 404)
|
|
d_unauth = self.controller.create_dispatch(None, self.tenant_id, {})
|
|
self.assertEqual(d_unauth["status_code"], 401)
|
|
|
|
# 3. Weighment errors: dispatch 404, missing fields, unauthenticated
|
|
w_404 = self.controller.record_outward_weighment(self.auth_logistics, self.tenant_id, "disp-nonexistent", {})
|
|
self.assertEqual(w_404["status_code"], 404)
|
|
w_unauth = self.controller.record_outward_weighment(None, self.tenant_id, "disp-1", {})
|
|
self.assertEqual(w_unauth["status_code"], 401)
|
|
|
|
# 4. POD errors: dispatch 404, missing fields, zero transit loss, unauthenticated
|
|
p_404 = self.controller.record_proof_of_delivery(self.auth_logistics, self.tenant_id, "disp-nonexistent", {})
|
|
self.assertEqual(p_404["status_code"], 404)
|
|
p_unauth = self.controller.record_proof_of_delivery(None, self.tenant_id, "disp-1", {})
|
|
self.assertEqual(p_unauth["status_code"], 401)
|
|
|
|
# Create fresh dispatch to test POD with zero transit loss
|
|
d_fresh = self.controller.create_dispatch(
|
|
self.auth_logistics,
|
|
self.tenant_id,
|
|
{
|
|
"sales_order_id": "so-zero-loss",
|
|
"allocation_id": "alloc-zero-loss",
|
|
"vehicle_id": "VEH-001",
|
|
"origin_warehouse_id": "WH-01",
|
|
"destination_city": "Indore",
|
|
},
|
|
)
|
|
disp_zero_id = d_fresh["dispatch"]["id"]
|
|
pod_zero = self.controller.record_proof_of_delivery(
|
|
self.auth_logistics,
|
|
self.tenant_id,
|
|
disp_zero_id,
|
|
{
|
|
"dispatched_net_mt": 25.000,
|
|
"dest_weighbridge_net_mt": 25.000, # Zero loss!
|
|
"consignee_ack_note": "Perfect delivery with zero transit shortage",
|
|
"pod_ref": "POD-ZERO-01",
|
|
},
|
|
)
|
|
self.assertEqual(pod_zero["status_code"], 200)
|
|
self.assertIsNone(pod_zero["credit_note"])
|
|
|
|
# 5. Approve credit note 404
|
|
app_404 = self.controller.approve_credit_note(self.auth_sales, self.tenant_id, "scn-nonexistent")
|
|
self.assertEqual(app_404["status_code"], 404)
|
|
|
|
def test_logistics_model_validation_invariants(self):
|
|
"""Statement coverage for model validation branches in OutboundDispatch, SalesCreditNote, and ProofOfDelivery."""
|
|
# TransportVehicle inactive
|
|
veh_inactive = TransportVehicle(
|
|
tenant_id=self.tenant_id,
|
|
reg_no="MP-43-INACT",
|
|
make_model="Tata",
|
|
payload_capacity_mt=Decimal("10.0"),
|
|
ownership_type="Own",
|
|
transporter_name="Internal",
|
|
fitness_expiry="2028-01-01",
|
|
is_active=False,
|
|
)
|
|
with self.assertRaises(ValueError):
|
|
veh_inactive.assert_can_assign()
|
|
|
|
# OutboundDispatch missing fields & invalid status
|
|
with self.assertRaises(ValueError):
|
|
OutboundDispatch(
|
|
tenant_id=self.tenant_id,
|
|
dispatch_number="DSP-1",
|
|
sales_order_id="",
|
|
allocation_id="alloc-1",
|
|
vehicle_id="veh-1",
|
|
origin_warehouse_id="wh-1",
|
|
destination_city="Indore",
|
|
)
|
|
disp = OutboundDispatch(
|
|
tenant_id=self.tenant_id,
|
|
dispatch_number="DSP-2",
|
|
sales_order_id="so-1",
|
|
allocation_id="alloc-1",
|
|
vehicle_id="veh-1",
|
|
origin_warehouse_id="wh-1",
|
|
destination_city="Indore",
|
|
)
|
|
with self.assertRaises(ValueError):
|
|
disp.transition_status("INVALID_STATUS")
|
|
|
|
# SalesCreditNote validations
|
|
with self.assertRaises(ValueError):
|
|
SalesCreditNote(
|
|
tenant_id=self.tenant_id,
|
|
credit_note_number="SCN-1",
|
|
sales_order_id="so-1",
|
|
dispatch_id="disp-1",
|
|
customer_id="cust-1",
|
|
shortage_mt=Decimal("0.0"),
|
|
shortage_pct=Decimal("0.0"),
|
|
rate_per_qtl=Decimal("5000.0"),
|
|
)
|
|
with self.assertRaises(ValueError):
|
|
SalesCreditNote(
|
|
tenant_id=self.tenant_id,
|
|
credit_note_number="SCN-2",
|
|
sales_order_id="so-1",
|
|
dispatch_id="disp-1",
|
|
customer_id="cust-1",
|
|
shortage_mt=Decimal("1.0"),
|
|
shortage_pct=Decimal("1.0"),
|
|
rate_per_qtl=Decimal("-10.0"),
|
|
)
|
|
scn = SalesCreditNote(
|
|
tenant_id=self.tenant_id,
|
|
credit_note_number="SCN-3",
|
|
sales_order_id="so-1",
|
|
dispatch_id="disp-1",
|
|
customer_id="cust-1",
|
|
shortage_mt=Decimal("1.0"),
|
|
shortage_pct=Decimal("1.0"),
|
|
rate_per_qtl=Decimal("5000.0"),
|
|
)
|
|
with self.assertRaises(ValueError):
|
|
scn.approve_credit_note("")
|
|
scn_dict = scn.to_dict()
|
|
self.assertEqual(scn_dict["credit_amount_inr"], 50000.0)
|
|
|
|
# ProofOfDelivery destination net weight <= 0
|
|
with self.assertRaises(ValueError):
|
|
ProofOfDelivery(
|
|
tenant_id=self.tenant_id,
|
|
dispatch_id="disp-1",
|
|
dispatched_net_mt=Decimal("20.0"),
|
|
dest_weighbridge_net_mt=Decimal("0.0"),
|
|
consignee_ack_note="note",
|
|
pod_ref="ref",
|
|
sales_invoice_number="inv",
|
|
)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|