458 lines
20 KiB
Python
458 lines
20 KiB
Python
"""Inward Vehicle Gate Receiving, Weighbridge, and GRN API Controller.
|
|
|
|
Fulfills:
|
|
- STORY-INW-001 (FR-INWARDRECEIVING-001): Inward Vehicle Gate Entry & Verification.
|
|
- STORY-INW-002 (FR-INWARDRECEIVING-002): Weighbridge Gross & Tare Weighment Logging.
|
|
- STORY-INW-003 (FR-INWARDRECEIVING-003): Bag Tare Deduction (Bardana Katai).
|
|
- STORY-INW-004 (FR-INWARDRECEIVING-004): Weighment Tolerance & Transit Shortage.
|
|
- STORY-INW-005 (FR-INWARDRECEIVING-005): Goods Receipt Note (GRN) & Stack Placement.
|
|
- STORY-INW-006 (FR-INWARDRECEIVING-006): Mandatory Lot & Batch Identity Generation.
|
|
"""
|
|
from datetime import datetime, 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.receiving import InwardGateEntry, WeighbridgeSlip, GoodsReceiptNote
|
|
from backend.app.models.quality import InventoryLot
|
|
from backend.app.models.procurement import ProcurementSauda
|
|
|
|
logger = logging.getLogger("atb.api.receiving")
|
|
|
|
|
|
class ReceivingController:
|
|
"""Handles gate passes, weighbridge scale readings, shortage, GRN posting, and lot minting."""
|
|
|
|
def __init__(self, store=storage, resolver=None):
|
|
self.store = store
|
|
self.resolver = resolver or TenantContextResolver(store=self.store)
|
|
|
|
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
|
|
}
|
|
|
|
# =========================================================================
|
|
# STORY-INW-001: Vehicle Gate Entry Pass
|
|
# =========================================================================
|
|
|
|
def create_gate_entry(
|
|
self, auth_header: Optional[str], tenant_header: Optional[str], payload: Dict[str, Any]
|
|
) -> Dict[str, Any]:
|
|
"""POST /api/v1/receiving/gate-entries (FR-INWARDRECEIVING-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"]
|
|
ctx = auth_res["context"]
|
|
|
|
allowed_roles = {"Security Guard", "Gate Operator", "Warehouse Clerk", "Yard Supervisor", "Tenant Administrator", "Partner / MD"}
|
|
if not any(r in allowed_roles for r in ctx.roles):
|
|
return {
|
|
"error": "INSUFFICIENT_PERMISSIONS",
|
|
"message": "Only Yard Supervisors, Security Guards, Gate Operators, or Tenant Admins can issue gate passes",
|
|
"status_code": 403
|
|
}
|
|
|
|
try:
|
|
vehicle_number = payload.get("vehicle_number", "").strip().upper()
|
|
eway_bill_number = payload.get("eway_bill_number", "").strip()
|
|
driver_name = payload.get("driver_name", "").strip()
|
|
driver_mobile = payload.get("driver_mobile", "").strip()
|
|
sauda_id = payload.get("sauda_id", "")
|
|
supplier_invoice_no = payload.get("supplier_invoice_no", "").strip()
|
|
dispatch_wt = Decimal(str(payload.get("supplier_dispatch_weight_mt", "0.0")))
|
|
dispatch_bags = int(payload.get("supplier_dispatch_bags", 0))
|
|
is_seal_intact = bool(payload.get("is_seal_intact", True))
|
|
|
|
# Validate Sauda exists and is open
|
|
sauda = self.store.get("procurement_sauda", tenant_id, sauda_id)
|
|
if not sauda:
|
|
matches = self.store.query(
|
|
"procurement_sauda",
|
|
tenant_id,
|
|
lambda s: s.get("sauda_number") == sauda_id or s.get("id") == sauda_id
|
|
)
|
|
if matches:
|
|
sauda = matches[0]
|
|
sauda_id = sauda["id"]
|
|
else:
|
|
return {"error": "INVALID_SAUDA", "message": "Purchase sauda not found in tenant", "status_code": 404}
|
|
if sauda.get("status") in {"FULFILLED", "CANCELLED"}:
|
|
return {
|
|
"error": "SAUDA_CLOSED",
|
|
"message": f"Cannot assign gate entry to {sauda.get('status')} contract",
|
|
"status_code": 400
|
|
}
|
|
|
|
# Vehicle yard duplication check
|
|
clean_vehicle = vehicle_number.replace("-", "").replace(" ", "").upper()
|
|
active_entries = self.store.query(
|
|
"inward_gate_entries",
|
|
tenant_id,
|
|
lambda e: (e.get("vehicle_number", "").replace("-", "").replace(" ", "").upper() == clean_vehicle)
|
|
and e.get("status") not in {"GATE_OUT", "GRN_ISSUED"}
|
|
)
|
|
if active_entries:
|
|
return {
|
|
"error": "VEHICLE_ALREADY_IN_YARD",
|
|
"message": f"Vehicle {vehicle_number} is already inside yard under Gate Pass {active_entries[0].get('gate_pass_number')}",
|
|
"status_code": 409
|
|
}
|
|
|
|
# Generate unique Gate Pass sequential number
|
|
total_passes = len(self.store.list("inward_gate_entries", tenant_id)) + 1
|
|
gate_pass_number = f"GP-26-{str(total_passes).zfill(5)}"
|
|
|
|
entry = InwardGateEntry(
|
|
tenant_id=tenant_id,
|
|
gate_pass_number=gate_pass_number,
|
|
vehicle_number=vehicle_number,
|
|
eway_bill_number=eway_bill_number,
|
|
driver_name=driver_name,
|
|
driver_mobile=driver_mobile,
|
|
sauda_id=sauda_id,
|
|
supplier_invoice_no=supplier_invoice_no,
|
|
supplier_dispatch_weight_mt=dispatch_wt,
|
|
supplier_dispatch_bags=dispatch_bags,
|
|
is_seal_intact=is_seal_intact
|
|
)
|
|
|
|
data = entry.to_dict()
|
|
self.store.insert("inward_gate_entries", tenant_id, data)
|
|
|
|
record_audit_event(
|
|
store=self.store,
|
|
tenant_id=tenant_id,
|
|
actor_user_id=auth_res["user_id"],
|
|
action_type="GENERATE_GATE_PASS",
|
|
resource_type="inward_gate_entry",
|
|
resource_id=entry.id,
|
|
before_state=None,
|
|
after_state={"gate_pass_number": gate_pass_number, "vehicle": vehicle_number, "sauda": sauda_id}
|
|
)
|
|
|
|
return {
|
|
"success": True,
|
|
"gate_entry": data,
|
|
"status_code": 201
|
|
}
|
|
|
|
except ValueError as e:
|
|
return {"error": "VALIDATION_ERROR", "message": str(e), "status_code": 422}
|
|
except Exception as e:
|
|
logger.exception("Failed to create gate entry")
|
|
return {"error": "INTERNAL_ERROR", "message": str(e), "status_code": 500}
|
|
|
|
def list_gate_entries(
|
|
self, auth_header: Optional[str], tenant_header: Optional[str]
|
|
) -> Dict[str, Any]:
|
|
"""GET /api/v1/receiving/gate-entries (FR-INWARDRECEIVING-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"]
|
|
records = self.store.list("inward_gate_entries", tenant_id)
|
|
enriched = []
|
|
for r in records:
|
|
item = dict(r)
|
|
item.setdefault("gate_pass_id", item.get("id"))
|
|
item.setdefault("pass_number", item.get("gate_pass_number"))
|
|
item.setdefault("bag_count", item.get("supplier_dispatch_bags", 0))
|
|
enriched.append(item)
|
|
return {
|
|
"success": True,
|
|
"count": len(enriched),
|
|
"gate_entries": enriched,
|
|
"status_code": 200
|
|
}
|
|
|
|
# =========================================================================
|
|
# STORY-INW-002, 003, 004: Weighbridge Gross/Tare Logging
|
|
# =========================================================================
|
|
|
|
def create_weighment_gross(
|
|
self, auth_header: Optional[str], tenant_header: Optional[str], payload: Dict[str, Any]
|
|
) -> Dict[str, Any]:
|
|
"""POST /api/v1/receiving/weighments (FR-INWARDRECEIVING-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"]
|
|
try:
|
|
gate_pass_id = payload.get("gate_pass_id", "")
|
|
gross_mt = Decimal(str(payload.get("gross_weight_mt", "0.0")))
|
|
|
|
gate_entry = self.store.get("inward_gate_entries", tenant_id, gate_pass_id)
|
|
if not gate_entry:
|
|
return {"error": "NOT_FOUND", "message": "Gate entry not found", "status_code": 404}
|
|
|
|
total_slips = len(self.store.list("weighbridge_slips", tenant_id)) + 1
|
|
slip_number = f"WS-26-{str(total_slips).zfill(5)}"
|
|
|
|
slip = WeighbridgeSlip(
|
|
tenant_id=tenant_id,
|
|
slip_number=slip_number,
|
|
gate_pass_id=gate_pass_id,
|
|
gross_weight_mt=gross_mt
|
|
)
|
|
|
|
data = slip.to_dict()
|
|
self.store.insert("weighbridge_slips", tenant_id, data)
|
|
|
|
# Update gate pass status
|
|
gate_entry["status"] = "WEIGHED_GROSS"
|
|
self.store.update("inward_gate_entries", tenant_id, gate_pass_id, gate_entry)
|
|
|
|
return {
|
|
"success": True,
|
|
"weighment_slip": data,
|
|
"status_code": 201
|
|
}
|
|
|
|
except ValueError as e:
|
|
return {"error": "VALIDATION_ERROR", "message": str(e), "status_code": 422}
|
|
except Exception as e:
|
|
logger.exception("Failed to log gross weighment")
|
|
return {"error": "INTERNAL_ERROR", "message": str(e), "status_code": 500}
|
|
|
|
def record_weighment_tare(
|
|
self, auth_header: Optional[str], tenant_header: Optional[str], slip_id: str, payload: Dict[str, Any]
|
|
) -> Dict[str, Any]:
|
|
"""POST /api/v1/receiving/weighments/{id}/tare (FR-INWARDRECEIVING-002..004)."""
|
|
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"]
|
|
try:
|
|
slip_data = self.store.get("weighbridge_slips", tenant_id, slip_id)
|
|
if not slip_data:
|
|
return {"error": "NOT_FOUND", "message": "Weighbridge slip not found", "status_code": 404}
|
|
|
|
tare_mt = Decimal(str(payload.get("tare_weight_mt", "0.0")))
|
|
packaging_type = payload.get("bag_packaging_type", "JUTE_GUNNY_NEW")
|
|
bag_count = int(payload.get("actual_bag_count", 0))
|
|
|
|
gate_entry = self.store.get("inward_gate_entries", tenant_id, slip_data["gate_pass_id"])
|
|
billed_wt = Decimal(str(gate_entry.get("supplier_dispatch_weight_mt", "0.0"))) if gate_entry else Decimal("0.0")
|
|
|
|
# Hydrate model and record tare
|
|
slip = WeighbridgeSlip(
|
|
tenant_id=tenant_id,
|
|
slip_number=slip_data["slip_number"],
|
|
gate_pass_id=slip_data["gate_pass_id"],
|
|
gross_weight_mt=Decimal(str(slip_data["gross_weight_mt"])),
|
|
slip_id=slip_id
|
|
)
|
|
slip.record_tare(
|
|
tare_weight_mt=tare_mt,
|
|
bag_packaging_type=packaging_type,
|
|
actual_bag_count=bag_count,
|
|
billed_weight_mt=billed_wt
|
|
)
|
|
|
|
updated_dict = slip.to_dict()
|
|
self.store.update("weighbridge_slips", tenant_id, slip_id, updated_dict)
|
|
|
|
# Update gate pass status
|
|
if gate_entry:
|
|
gate_entry["status"] = "WEIGHED_TARE"
|
|
self.store.update("inward_gate_entries", tenant_id, gate_entry["id"], gate_entry)
|
|
|
|
return {
|
|
"success": True,
|
|
"weighment_slip": updated_dict,
|
|
"status_code": 200
|
|
}
|
|
|
|
except ValueError as e:
|
|
return {"error": "VALIDATION_ERROR", "message": str(e), "status_code": 422}
|
|
except Exception as e:
|
|
logger.exception("Failed to record tare weighment")
|
|
return {"error": "INTERNAL_ERROR", "message": str(e), "status_code": 500}
|
|
|
|
# =========================================================================
|
|
# STORY-INW-005, 006: GRN Posting & Lot Minting
|
|
# =========================================================================
|
|
|
|
def post_grn(
|
|
self, auth_header: Optional[str], tenant_header: Optional[str], payload: Dict[str, Any]
|
|
) -> Dict[str, Any]:
|
|
"""POST /api/v1/receiving/grn (FR-INWARDRECEIVING-005, FR-INWARDRECEIVING-006)."""
|
|
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"]
|
|
ctx = auth_res["context"]
|
|
|
|
allowed_roles = {"Warehouse Supervisor", "Warehouse Manager", "Yard Supervisor", "Warehouse Clerk", "Tenant Administrator", "Partner / MD"}
|
|
if not any(r in allowed_roles for r in ctx.roles):
|
|
return {
|
|
"error": "INSUFFICIENT_PERMISSIONS",
|
|
"message": "Only Yard Supervisors, Warehouse Supervisors, Managers, or Tenant Admins can post GRNs",
|
|
"status_code": 403
|
|
}
|
|
|
|
try:
|
|
slip_id = payload.get("weighment_slip_id", "")
|
|
godown_id = payload.get("godown_id", "")
|
|
godown_stack_id = payload.get("godown_stack_id", "")
|
|
|
|
slip_data = self.store.get("weighbridge_slips", tenant_id, slip_id)
|
|
if not slip_data:
|
|
return {"error": "NOT_FOUND", "message": "Weighbridge slip not found", "status_code": 404}
|
|
|
|
if slip_data.get("final_net_weight_mt") is None:
|
|
return {
|
|
"error": "TARE_NOT_COMPLETED",
|
|
"message": "Cannot issue GRN without completed tare weighment",
|
|
"status_code": 400
|
|
}
|
|
|
|
gate_entry = self.store.get("inward_gate_entries", tenant_id, slip_data["gate_pass_id"])
|
|
if not gate_entry:
|
|
return {"error": "NOT_FOUND", "message": "Gate entry not found", "status_code": 404}
|
|
|
|
sauda_data = self.store.get("procurement_sauda", tenant_id, gate_entry["sauda_id"])
|
|
if not sauda_data:
|
|
return {"error": "NOT_FOUND", "message": "Associated Sauda not found", "status_code": 404}
|
|
|
|
# Check if GRN already issued for this slip
|
|
existing_grn = self.store.query("goods_receipt_notes", tenant_id, lambda g: g.get("weighment_slip_id") == slip_id)
|
|
if existing_grn:
|
|
return {
|
|
"error": "DUPLICATE_GRN",
|
|
"message": f"GRN already issued for weighment slip: {existing_grn[0].get('grn_number')}",
|
|
"status_code": 409
|
|
}
|
|
|
|
accepted_wt = Decimal(str(slip_data["final_net_weight_mt"]))
|
|
accepted_bags = slip_data.get("actual_bag_count", 0)
|
|
|
|
# Generate unique GRN number
|
|
total_grns = len(self.store.list("goods_receipt_notes", tenant_id)) + 1
|
|
grn_number = f"GRN-26-{str(total_grns).zfill(5)}"
|
|
|
|
grn = GoodsReceiptNote(
|
|
tenant_id=tenant_id,
|
|
grn_number=grn_number,
|
|
weighment_slip_id=slip_id,
|
|
sauda_id=sauda_data["id"],
|
|
godown_id=godown_id,
|
|
godown_stack_id=godown_stack_id,
|
|
accepted_quantity_mt=accepted_wt,
|
|
accepted_bags=accepted_bags
|
|
)
|
|
grn_dict = grn.to_dict()
|
|
self.store.insert("goods_receipt_notes", tenant_id, grn_dict)
|
|
|
|
# Mint Lot Identity (FR-INWARDRECEIVING-006)
|
|
total_lots = len(self.store.list("inventory_lots", tenant_id)) + 1
|
|
comm_code = sauda_data.get("commodity_id", "COMM")[:3].upper()
|
|
lot_number = f"LOT-26-10-{comm_code}-{str(total_lots).zfill(5)}"
|
|
|
|
lot = InventoryLot(
|
|
tenant_id=tenant_id,
|
|
lot_number=lot_number,
|
|
grn_id=grn.id,
|
|
commodity_id=sauda_data["commodity_id"],
|
|
variety=sauda_data["variety"],
|
|
grade=sauda_data.get("grade", "FAQ"),
|
|
godown_stack_id=godown_stack_id,
|
|
initial_quantity_mt=accepted_wt
|
|
)
|
|
lot_dict = lot.to_dict()
|
|
self.store.insert("inventory_lots", tenant_id, lot_dict)
|
|
|
|
# Update Sauda partial fulfillment & FSM
|
|
sauda = ProcurementSauda(
|
|
tenant_id=tenant_id,
|
|
sauda_number=sauda_data["sauda_number"],
|
|
contract_date=datetime.strptime(sauda_data["contract_date"], "%Y-%m-%d").date(),
|
|
delivery_due_date=datetime.strptime(sauda_data["delivery_due_date"], "%Y-%m-%d").date(),
|
|
supplier_id=sauda_data["supplier_id"],
|
|
mandi_id=sauda_data["mandi_id"],
|
|
commodity_id=sauda_data["commodity_id"],
|
|
variety=sauda_data["variety"],
|
|
booked_quantity_mt=Decimal(str(sauda_data["booked_quantity_mt"])),
|
|
trade_rate_per_qtl=Decimal(str(sauda_data["trade_rate_per_qtl"])),
|
|
grade=sauda_data["grade"],
|
|
sauda_id=sauda_data["id"]
|
|
)
|
|
sauda.cumulative_received_mt = Decimal(str(sauda_data.get("cumulative_received_mt", "0.0")))
|
|
sauda.status = sauda_data.get("status", "ACTIVE")
|
|
sauda.record_receipt(accepted_wt)
|
|
self.store.update("procurement_sauda", tenant_id, sauda.id, sauda.to_dict())
|
|
|
|
# Update gate pass to GRN_ISSUED
|
|
gate_entry["status"] = "GRN_ISSUED"
|
|
self.store.update("inward_gate_entries", tenant_id, gate_entry["id"], gate_entry)
|
|
|
|
record_audit_event(
|
|
store=self.store,
|
|
tenant_id=tenant_id,
|
|
actor_user_id=auth_res["user_id"],
|
|
action_type="POST_GRN_AND_MINT_LOT",
|
|
resource_type="goods_receipt_note",
|
|
resource_id=grn.id,
|
|
before_state=None,
|
|
after_state={"grn_number": grn_number, "lot_number": lot_number, "accepted_mt": float(accepted_wt)}
|
|
)
|
|
|
|
return {
|
|
"success": True,
|
|
"grn": grn_dict,
|
|
"lot": lot_dict,
|
|
"sauda_status": sauda.status,
|
|
"status_code": 201
|
|
}
|
|
|
|
except ValueError as e:
|
|
return {"error": "VALIDATION_ERROR", "message": str(e), "status_code": 422}
|
|
except Exception as e:
|
|
logger.exception("Failed to post GRN")
|
|
return {"error": "INTERNAL_ERROR", "message": str(e), "status_code": 500}
|
|
|
|
|
|
receiving_controller = ReceivingController()
|