490 lines
21 KiB
Python
490 lines
21 KiB
Python
"""Outbound Dispatch, Outward Weighbridge, Bilty, POD & Fleet Registry API Controller.
|
|
|
|
Fulfills:
|
|
- STORY-DISP-001 (FR-DISPATCHDELIVERY-001): Outbound Dispatch Board Console & Consignment Scheduling.
|
|
- STORY-DISP-002 (FR-DISPATCHDELIVERY-002): Outbound Weighbridge & Transport Manifest / Bilty Generation.
|
|
- STORY-DISP-003 (FR-DISPATCHDELIVERY-003): In-Transit Tracking & Proof of Delivery (POD) / Shortage Credit Note.
|
|
- STORY-FLEET-001 (FR-FLEETREGISTRY-001): Transport Fleet & Carrier Registry with Maintenance Gating.
|
|
"""
|
|
from datetime import datetime, date, timezone
|
|
from decimal import Decimal
|
|
import logging
|
|
from typing import Any, Dict, List, Optional
|
|
import uuid
|
|
|
|
from backend.app.api.auth import auth_controller
|
|
from backend.app.auth.tenant_context import (
|
|
TenantContext,
|
|
TenantContextResolutionError,
|
|
TenantContextResolver,
|
|
context_resolver,
|
|
record_audit_event,
|
|
)
|
|
from backend.app.db.session import storage
|
|
from backend.app.models.logistics import (
|
|
TransportVehicle,
|
|
OutboundDispatch,
|
|
OutwardWeighment,
|
|
DispatchBilty,
|
|
ProofOfDelivery,
|
|
SalesCreditNote,
|
|
)
|
|
from sandbox.fleet_mock import FleetMock
|
|
|
|
logger = logging.getLogger("atb.api.logistics")
|
|
|
|
|
|
class LogisticsController:
|
|
"""Handles transport fleet, consignment dispatches, weighbridge bilty, and destination POD shortage settlements."""
|
|
|
|
def __init__(self, store=storage, resolver=None):
|
|
self.store = store
|
|
self.resolver = resolver or TenantContextResolver(store=self.store)
|
|
self._seed_initial_fleet()
|
|
|
|
def _seed_initial_fleet(self, tenant_id: str = "tenant-alpha") -> None:
|
|
"""Seeds initial fleet from sandbox fleet mock."""
|
|
for v in FleetMock.list_vehicles():
|
|
veh = TransportVehicle(
|
|
tenant_id=tenant_id,
|
|
reg_no=v["reg_no"],
|
|
make_model=v["make_model"],
|
|
payload_capacity_mt=v["payload_capacity_mt"],
|
|
ownership_type=v["ownership_type"],
|
|
transporter_name=v["transporter_name"],
|
|
fitness_expiry=v["fitness_expiry"],
|
|
status=v["status"],
|
|
is_active=v["is_active"],
|
|
vehicle_id=v["id"],
|
|
)
|
|
self.store.insert("transport_fleet", tenant_id, veh.to_dict())
|
|
|
|
def _authenticate_and_resolve(
|
|
self, auth_header: Optional[str], tenant_header: Optional[str]
|
|
) -> Dict[str, Any]:
|
|
"""Resolves verified caller session and active tenant context."""
|
|
session = auth_controller.get_session(auth_header)
|
|
if not session.get("authenticated"):
|
|
return {"authenticated": False, "error": session.get("error", "UNAUTHENTICATED"), "status_code": 401}
|
|
|
|
user_id = session.get("subject", "")
|
|
email = session.get("email", user_id)
|
|
user_roles = session.get("roles", [])
|
|
|
|
try:
|
|
ctx = self.resolver.resolve_context(
|
|
subject_id=user_id,
|
|
email=email,
|
|
user_roles=user_roles,
|
|
requested_tenant_id=tenant_header,
|
|
)
|
|
except TenantContextResolutionError as err:
|
|
return {"authenticated": False, "error": err.message, "code": err.code, "status_code": err.status_code}
|
|
|
|
return {
|
|
"authenticated": True,
|
|
"session": session,
|
|
"context": ctx,
|
|
"tenant_id": ctx.tenant_id,
|
|
"user_id": user_id,
|
|
"roles": list(dict.fromkeys(ctx.roles + user_roles)),
|
|
}
|
|
|
|
# =========================================================================
|
|
# STORY-FLEET-001: Transport Fleet & Carrier Registry
|
|
# =========================================================================
|
|
|
|
def list_fleet(
|
|
self, auth_header: Optional[str], tenant_header: Optional[str], status: Optional[str] = None
|
|
) -> Dict[str, Any]:
|
|
"""GET /api/v1/logistics/fleet (FR-FLEETREGISTRY-001)."""
|
|
auth_res = self._authenticate_and_resolve(auth_header, tenant_header)
|
|
if not auth_res.get("authenticated"):
|
|
return auth_res
|
|
|
|
tenant_id = auth_res["tenant_id"]
|
|
vehicles = self.store.list("transport_fleet", tenant_id)
|
|
if not vehicles:
|
|
self._seed_initial_fleet(tenant_id)
|
|
vehicles = self.store.list("transport_fleet", tenant_id)
|
|
|
|
filtered = [v for v in vehicles if status is None or v["status"].lower() == status.lower()]
|
|
return {"status_code": 200, "count": len(filtered), "vehicles": filtered}
|
|
|
|
def register_vehicle(
|
|
self, auth_header: Optional[str], tenant_header: Optional[str], payload: Dict[str, Any]
|
|
) -> Dict[str, Any]:
|
|
"""POST /api/v1/logistics/fleet (FR-FLEETREGISTRY-001)."""
|
|
auth_res = self._authenticate_and_resolve(auth_header, tenant_header)
|
|
if not auth_res.get("authenticated"):
|
|
return auth_res
|
|
|
|
tenant_id = auth_res["tenant_id"]
|
|
user_id = auth_res["user_id"]
|
|
|
|
required = ["reg_no", "make_model", "payload_capacity_mt", "ownership_type", "transporter_name", "fitness_expiry"]
|
|
missing = [f for f in required if f not in payload]
|
|
if missing:
|
|
return {"status_code": 400, "error": f"Missing required fields: {missing}"}
|
|
|
|
try:
|
|
vehicle = TransportVehicle(
|
|
tenant_id=tenant_id,
|
|
reg_no=payload["reg_no"],
|
|
make_model=payload["make_model"],
|
|
payload_capacity_mt=Decimal(str(payload["payload_capacity_mt"])),
|
|
ownership_type=payload["ownership_type"],
|
|
transporter_name=payload["transporter_name"],
|
|
fitness_expiry=payload["fitness_expiry"],
|
|
status=payload.get("status", "Available"),
|
|
)
|
|
except ValueError as e:
|
|
return {"status_code": 400, "error": str(e)}
|
|
|
|
self.store.insert("transport_fleet", tenant_id, vehicle.to_dict())
|
|
|
|
record_audit_event(
|
|
tenant_id=tenant_id,
|
|
user_id=user_id,
|
|
action="FLEET_VEHICLE_REGISTERED",
|
|
entity_type="transport_vehicle",
|
|
entity_id=vehicle.id,
|
|
payload={"reg_no": vehicle.reg_no, "status": vehicle.status},
|
|
)
|
|
|
|
return {"status_code": 201, "vehicle": vehicle.to_dict()}
|
|
|
|
# =========================================================================
|
|
# STORY-DISP-001: Outbound Dispatch Board Console & Consignment Scheduling
|
|
# =========================================================================
|
|
|
|
def list_dispatches(
|
|
self, auth_header: Optional[str], tenant_header: Optional[str], status: Optional[str] = None
|
|
) -> Dict[str, Any]:
|
|
"""GET /api/v1/logistics/dispatches (FR-DISPATCHDELIVERY-001)."""
|
|
auth_res = self._authenticate_and_resolve(auth_header, tenant_header)
|
|
if not auth_res.get("authenticated"):
|
|
return auth_res
|
|
|
|
tenant_id = auth_res["tenant_id"]
|
|
dispatches = self.store.list("outbound_dispatches", tenant_id)
|
|
filtered = [d for d in dispatches if status is None or d["status"] == status]
|
|
return {"status_code": 200, "count": len(filtered), "dispatches": filtered}
|
|
|
|
def create_dispatch(
|
|
self, auth_header: Optional[str], tenant_header: Optional[str], payload: Dict[str, Any]
|
|
) -> Dict[str, Any]:
|
|
"""POST /api/v1/logistics/dispatches (FR-DISPATCHDELIVERY-001, FR-FLEETREGISTRY-001)."""
|
|
auth_res = self._authenticate_and_resolve(auth_header, tenant_header)
|
|
if not auth_res.get("authenticated"):
|
|
return auth_res
|
|
|
|
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]
|
|
if missing:
|
|
return {"status_code": 400, "error": f"Missing required fields: {missing}"}
|
|
|
|
# Check active credit dispatch lock (FR-CUSTOMERRECEIVABLES-003 / STORY-REC-003)
|
|
cust_id = payload.get("customer_id")
|
|
if not cust_id:
|
|
so = self.store.get("customer_sales_orders", tenant_id, payload["sales_order_id"])
|
|
if so:
|
|
cust_id = so.get("customer_id")
|
|
if cust_id:
|
|
active_locks = [
|
|
l for l in self.store.list("credit_dispatch_locks", tenant_id)
|
|
if l.get("customer_id") == cust_id and l.get("status") == "LOCKED"
|
|
]
|
|
if active_locks:
|
|
return {
|
|
"status_code": 403,
|
|
"error": "CREDIT_BREACH_DISPATCH_LOCKED: Outbound dispatches are blocked due to customer credit breach (>100%). Partner electronic override required.",
|
|
"lock_id": active_locks[0]["id"],
|
|
}
|
|
|
|
# Check vehicle maintenance and fitness eligibility
|
|
vehicle_data = self.store.get("transport_fleet", tenant_id, payload["vehicle_id"])
|
|
if not vehicle_data:
|
|
# Check by reg_no
|
|
vehicles = self.store.list("transport_fleet", tenant_id)
|
|
if not vehicles:
|
|
self._seed_initial_fleet(tenant_id)
|
|
vehicles = self.store.list("transport_fleet", tenant_id)
|
|
for v in vehicles:
|
|
if v["reg_no"] == payload["vehicle_id"].upper() or v["id"] == payload["vehicle_id"]:
|
|
vehicle_data = v
|
|
break
|
|
|
|
if not vehicle_data:
|
|
return {"status_code": 404, "error": f"Vehicle '{payload['vehicle_id']}' not found in registry"}
|
|
|
|
try:
|
|
vehicle = TransportVehicle(
|
|
tenant_id=tenant_id,
|
|
reg_no=vehicle_data["reg_no"],
|
|
make_model=vehicle_data["make_model"],
|
|
payload_capacity_mt=Decimal(str(vehicle_data["payload_capacity_mt"])),
|
|
ownership_type=vehicle_data["ownership_type"],
|
|
transporter_name=vehicle_data["transporter_name"],
|
|
fitness_expiry=vehicle_data["fitness_expiry"],
|
|
status=vehicle_data["status"],
|
|
is_active=vehicle_data["is_active"],
|
|
vehicle_id=vehicle_data["id"],
|
|
)
|
|
vehicle.assert_can_assign()
|
|
except ValueError as e:
|
|
return {"status_code": 400, "error": str(e)}
|
|
|
|
dispatch_number = payload.get("dispatch_number") or f"DSP-{datetime.now(timezone.utc).strftime('%Y%m')}-{uuid.uuid4().hex[:6].upper()}"
|
|
|
|
try:
|
|
dispatch = OutboundDispatch(
|
|
tenant_id=tenant_id,
|
|
dispatch_number=dispatch_number,
|
|
sales_order_id=payload["sales_order_id"],
|
|
allocation_id=payload["allocation_id"],
|
|
vehicle_id=vehicle.id,
|
|
origin_warehouse_id=payload["origin_warehouse_id"],
|
|
destination_city=payload["destination_city"],
|
|
)
|
|
except ValueError as e:
|
|
return {"status_code": 400, "error": str(e)}
|
|
|
|
# Update vehicle status to On Route
|
|
vehicle_data["status"] = "On Route"
|
|
self.store.update("transport_fleet", tenant_id, vehicle.id, vehicle_data)
|
|
self.store.insert("outbound_dispatches", tenant_id, dispatch.to_dict())
|
|
|
|
record_audit_event(
|
|
tenant_id=tenant_id,
|
|
user_id=user_id,
|
|
action="DISPATCH_SCHEDULED",
|
|
entity_type="outbound_dispatch",
|
|
entity_id=dispatch.id,
|
|
payload={"dispatch_number": dispatch.dispatch_number, "vehicle_reg_no": vehicle.reg_no},
|
|
)
|
|
|
|
return {"status_code": 201, "dispatch": dispatch.to_dict()}
|
|
|
|
# =========================================================================
|
|
# STORY-DISP-002: Outbound Weighbridge & Bilty Generation
|
|
# =========================================================================
|
|
|
|
def record_outward_weighment(
|
|
self, auth_header: Optional[str], tenant_header: Optional[str], dispatch_id: str, payload: Dict[str, Any]
|
|
) -> Dict[str, Any]:
|
|
"""POST /api/v1/logistics/dispatches/{id}/weighments (FR-DISPATCHDELIVERY-002)."""
|
|
auth_res = self._authenticate_and_resolve(auth_header, tenant_header)
|
|
if not auth_res.get("authenticated"):
|
|
return auth_res
|
|
|
|
tenant_id = auth_res["tenant_id"]
|
|
user_id = auth_res["user_id"]
|
|
|
|
dispatch_data = self.store.get("outbound_dispatches", tenant_id, dispatch_id)
|
|
if not dispatch_data:
|
|
return {"status_code": 404, "error": f"Dispatch '{dispatch_id}' not found"}
|
|
|
|
required = ["tare_weight_kg", "gross_weight_kg", "allocated_mt", "loaded_bags", "transporter_bilty_no", "eway_bill_no"]
|
|
missing = [f for f in required if f not in payload]
|
|
if missing:
|
|
return {"status_code": 400, "error": f"Missing required fields: {missing}"}
|
|
|
|
try:
|
|
tare_kg = Decimal(str(payload["tare_weight_kg"]))
|
|
gross_kg = Decimal(str(payload["gross_weight_kg"]))
|
|
allocated_mt = Decimal(str(payload["allocated_mt"]))
|
|
loaded_bags = int(payload["loaded_bags"])
|
|
|
|
weighment = OutwardWeighment(
|
|
tenant_id=tenant_id,
|
|
dispatch_id=dispatch_id,
|
|
tare_weight_kg=tare_kg,
|
|
gross_weight_kg=gross_kg,
|
|
allocated_mt=allocated_mt,
|
|
loaded_bags=loaded_bags,
|
|
transporter_bilty_no=payload["transporter_bilty_no"],
|
|
eway_bill_no=payload["eway_bill_no"],
|
|
)
|
|
except ValueError as e:
|
|
return {"status_code": 400, "error": str(e)}
|
|
|
|
bilty_number = f"BLT-{datetime.now(timezone.utc).strftime('%Y%m')}-{uuid.uuid4().hex[:6].upper()}"
|
|
bilty = DispatchBilty(
|
|
tenant_id=tenant_id,
|
|
dispatch_id=dispatch_id,
|
|
bilty_number=bilty_number,
|
|
consignor_name="Mandi Backoffice Ltd",
|
|
consignee_name=payload.get("consignee_name", "Destination Customer"),
|
|
vehicle_reg_no=payload.get("vehicle_reg_no", "MP-43-G-1234"),
|
|
net_weight_mt=weighment.net_weight_mt,
|
|
bags=weighment.loaded_bags,
|
|
eway_bill_no=weighment.eway_bill_no,
|
|
)
|
|
|
|
dispatch_data["status"] = "IN_TRANSIT"
|
|
self.store.update("outbound_dispatches", tenant_id, dispatch_id, dispatch_data)
|
|
self.store.insert("outward_weighments", tenant_id, weighment.to_dict())
|
|
self.store.insert("dispatch_bilties", tenant_id, bilty.to_dict())
|
|
|
|
record_audit_event(
|
|
tenant_id=tenant_id,
|
|
user_id=user_id,
|
|
action="DISPATCH_BILTY_ISSUED",
|
|
entity_type="dispatch_bilty",
|
|
entity_id=bilty.id,
|
|
payload={
|
|
"dispatch_id": dispatch_id,
|
|
"bilty_number": bilty.bilty_number,
|
|
"net_weight_mt": float(bilty.net_weight_mt),
|
|
},
|
|
)
|
|
|
|
return {
|
|
"status_code": 201,
|
|
"weighment": weighment.to_dict(),
|
|
"bilty": bilty.to_dict(),
|
|
"dispatch_status": "IN_TRANSIT",
|
|
}
|
|
|
|
# =========================================================================
|
|
# STORY-DISP-003: Proof of Delivery (POD) & Shortage Settlement
|
|
# =========================================================================
|
|
|
|
def record_proof_of_delivery(
|
|
self, auth_header: Optional[str], tenant_header: Optional[str], dispatch_id: str, payload: Dict[str, Any]
|
|
) -> Dict[str, Any]:
|
|
"""POST /api/v1/logistics/dispatches/{id}/pod (FR-DISPATCHDELIVERY-003)."""
|
|
auth_res = self._authenticate_and_resolve(auth_header, tenant_header)
|
|
if not auth_res.get("authenticated"):
|
|
return auth_res
|
|
|
|
tenant_id = auth_res["tenant_id"]
|
|
user_id = auth_res["user_id"]
|
|
|
|
dispatch_data = self.store.get("outbound_dispatches", tenant_id, dispatch_id)
|
|
if not dispatch_data:
|
|
return {"status_code": 404, "error": f"Dispatch '{dispatch_id}' not found"}
|
|
|
|
required = ["dest_weighbridge_net_mt", "dispatched_net_mt", "consignee_ack_note", "pod_ref"]
|
|
missing = [f for f in required if f not in payload]
|
|
if missing:
|
|
return {"status_code": 400, "error": f"Missing required fields: {missing}"}
|
|
|
|
inv_num = f"INV-{datetime.now(timezone.utc).strftime('%Y%m')}-{uuid.uuid4().hex[:6].upper()}"
|
|
|
|
try:
|
|
dest_mt = Decimal(str(payload["dest_weighbridge_net_mt"]))
|
|
disp_mt = Decimal(str(payload["dispatched_net_mt"]))
|
|
|
|
pod = ProofOfDelivery(
|
|
tenant_id=tenant_id,
|
|
dispatch_id=dispatch_id,
|
|
dispatched_net_mt=disp_mt,
|
|
dest_weighbridge_net_mt=dest_mt,
|
|
consignee_ack_note=payload["consignee_ack_note"],
|
|
pod_ref=payload["pod_ref"],
|
|
sales_invoice_number=inv_num,
|
|
)
|
|
except ValueError as e:
|
|
return {"status_code": 400, "error": str(e)}
|
|
|
|
credit_note_dict = None
|
|
if pod.credit_note_required and pod.transit_loss_mt > Decimal("0.000"):
|
|
rate_qtl = Decimal(str(payload.get("contract_rate_per_qtl", "5200.00")))
|
|
scn_num = f"SCN-{datetime.now(timezone.utc).strftime('%Y%m')}-{uuid.uuid4().hex[:6].upper()}"
|
|
scn = SalesCreditNote(
|
|
tenant_id=tenant_id,
|
|
credit_note_number=scn_num,
|
|
sales_order_id=dispatch_data["sales_order_id"],
|
|
dispatch_id=dispatch_id,
|
|
customer_id=payload.get("customer_id", "CUST-001"),
|
|
shortage_mt=pod.transit_loss_mt,
|
|
shortage_pct=pod.shortage_pct,
|
|
rate_per_qtl=rate_qtl,
|
|
)
|
|
self.store.insert("sales_credit_notes", tenant_id, scn.to_dict())
|
|
credit_note_dict = scn.to_dict()
|
|
|
|
# Update dispatch to DELIVERED and release vehicle back to Available
|
|
dispatch_data["status"] = "DELIVERED"
|
|
self.store.update("outbound_dispatches", tenant_id, dispatch_id, dispatch_data)
|
|
self.store.insert("proof_of_deliveries", tenant_id, pod.to_dict())
|
|
|
|
vehicle_data = self.store.get("transport_fleet", tenant_id, dispatch_data["vehicle_id"])
|
|
if vehicle_data:
|
|
vehicle_data["status"] = "Available"
|
|
self.store.update("transport_fleet", tenant_id, dispatch_data["vehicle_id"], vehicle_data)
|
|
|
|
record_audit_event(
|
|
tenant_id=tenant_id,
|
|
user_id=user_id,
|
|
action="DISPATCH_DELIVERED_POD",
|
|
entity_type="proof_of_delivery",
|
|
entity_id=pod.id,
|
|
payload={
|
|
"dispatch_id": dispatch_id,
|
|
"invoice_number": inv_num,
|
|
"shortage_pct": float(pod.shortage_pct),
|
|
"credit_note_issued": credit_note_dict is not None,
|
|
},
|
|
)
|
|
|
|
return {
|
|
"status_code": 200,
|
|
"pod": pod.to_dict(),
|
|
"invoice_number": inv_num,
|
|
"dispatch_status": "DELIVERED",
|
|
"credit_note": credit_note_dict,
|
|
}
|
|
|
|
def approve_credit_note(
|
|
self, auth_header: Optional[str], tenant_header: Optional[str], credit_note_id: str
|
|
) -> Dict[str, Any]:
|
|
"""POST /api/v1/logistics/credit-notes/{id}/approve (FR-DISPATCHDELIVERY-003)."""
|
|
auth_res = self._authenticate_and_resolve(auth_header, tenant_header)
|
|
if not auth_res.get("authenticated"):
|
|
return auth_res
|
|
|
|
tenant_id = auth_res["tenant_id"]
|
|
user_id = auth_res["user_id"]
|
|
roles = auth_res.get("roles", [])
|
|
|
|
is_authorized = any(r in {"SALES_MANAGER", "COMMERCIAL_HEAD", "PARTNER", "ADMIN", "Sales Manager", "Partner / MD", "Tenant Administrator"} for r in roles)
|
|
if not is_authorized:
|
|
return {"status_code": 403, "error": "Sales Manager or Partner authorization required to approve credit note"}
|
|
|
|
scn_data = self.store.get("sales_credit_notes", tenant_id, credit_note_id)
|
|
if not scn_data:
|
|
return {"status_code": 404, "error": f"Credit Note '{credit_note_id}' not found"}
|
|
|
|
scn_data["manager_approved"] = True
|
|
scn_data["approved_by"] = user_id
|
|
self.store.update("sales_credit_notes", tenant_id, credit_note_id, scn_data)
|
|
|
|
return {"status_code": 200, "message": "Credit note approved", "credit_note": scn_data}
|
|
|
|
|
|
logistics_controller = LogisticsController()
|