334 lines
14 KiB
Python
334 lines
14 KiB
Python
"""Quality Lab Assay, Rebate Deductions, and Lot FSM API Controller.
|
|
|
|
Fulfills:
|
|
- STORY-QC-001 (FR-QUALITYANDLOTCONTROL-001): Inward Quality Inspection Parameter Recording.
|
|
- STORY-QC-002 (FR-QUALITYANDLOTCONTROL-002): Finite State Machine Enforcement (Hold vs Released).
|
|
- STORY-QC-003 (FR-QUALITYANDLOTCONTROL-003): Quality Deduction / Rebate Calculation.
|
|
- STORY-QC-004 (FR-QUALITYANDLOTCONTROL-004): Lot Splitting & Blending Traceability.
|
|
"""
|
|
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.quality import InventoryLot, QualityInspection, calculate_quality_rebates
|
|
|
|
logger = logging.getLogger("atb.api.quality")
|
|
|
|
|
|
class QualityController:
|
|
"""Handles laboratory inspection assays, rebate calculation, lot FSM state transitions, and lineage."""
|
|
|
|
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-QC-001 & 003: Lab Assay & Commercial Rebate Recording
|
|
# =========================================================================
|
|
|
|
def list_inspections(
|
|
self, auth_header: Optional[str], tenant_header: Optional[str], lot_id: Optional[str] = None
|
|
) -> Dict[str, Any]:
|
|
"""GET /api/v1/quality/inspections (FR-QUALITYANDLOTCONTROL-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"]
|
|
inspections = self.store.list("quality_inspections", tenant_id)
|
|
if lot_id:
|
|
inspections = [i for i in inspections if i.get("lot_id") == lot_id]
|
|
return {"status_code": 200, "count": len(inspections), "inspections": inspections}
|
|
|
|
def record_inspection(
|
|
self, auth_header: Optional[str], tenant_header: Optional[str], payload: Dict[str, Any]
|
|
) -> Dict[str, Any]:
|
|
"""POST /api/v1/quality/inspections (FR-QUALITYANDLOTCONTROL-001, 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"]
|
|
ctx = auth_res["context"]
|
|
|
|
allowed_roles = {"Quality Officer", "Quality Inspector", "Lab Chemist", "Tenant Administrator", "Partner / MD"}
|
|
if not any(r in allowed_roles for r in ctx.roles):
|
|
return {
|
|
"error": "INSUFFICIENT_PERMISSIONS",
|
|
"message": "Only Quality Officers, Chemists, or Tenant Admins can record analytical assays",
|
|
"status_code": 403
|
|
}
|
|
|
|
try:
|
|
lot_id = payload.get("lot_id", "")
|
|
sample_code = payload.get("sample_code", "").strip()
|
|
moisture_pct = Decimal(str(payload.get("moisture_pct", "0.0")))
|
|
foreign_matter_pct = Decimal(str(payload.get("foreign_matter_pct", "0.0")))
|
|
damaged_pct = Decimal(str(payload.get("damaged_grain_pct", "0.0")))
|
|
oil_pct = Decimal(str(payload.get("oil_content_pct", "0.0")))
|
|
decision = payload.get("decision", "RELEASED")
|
|
rejection_reason = payload.get("rejection_reason")
|
|
remarks = payload.get("remarks")
|
|
|
|
# Validate lot exists
|
|
lot_data = self.store.get("inventory_lots", tenant_id, lot_id)
|
|
if not lot_data:
|
|
matches = self.store.query(
|
|
"inventory_lots",
|
|
tenant_id,
|
|
lambda l: l.get("lot_number") == lot_id or l.get("id") == lot_id
|
|
)
|
|
if matches:
|
|
lot_data = matches[0]
|
|
lot_id = lot_data["id"]
|
|
else:
|
|
return {"error": "NOT_FOUND", "message": "Target inventory lot not found", "status_code": 404}
|
|
|
|
lot_qty_mt = Decimal(str(lot_data["current_quantity_mt"]))
|
|
|
|
# Retrieve trade rate from Sauda
|
|
grn_data = self.store.get("goods_receipt_notes", tenant_id, lot_data["grn_id"])
|
|
sauda_data = self.store.get("procurement_sauda", tenant_id, grn_data["sauda_id"]) if grn_data else None
|
|
trade_rate = Decimal(str(sauda_data["trade_rate_per_qtl"])) if sauda_data else Decimal("4500.00")
|
|
|
|
# Create Inspection model
|
|
inspection = QualityInspection(
|
|
tenant_id=tenant_id,
|
|
lot_id=lot_id,
|
|
sample_code=sample_code,
|
|
inspector_email=auth_res["session"].get("subject", "inspector@atb.com"),
|
|
lot_quantity_mt=lot_qty_mt,
|
|
trade_rate_per_qtl=trade_rate,
|
|
moisture_pct=moisture_pct,
|
|
foreign_matter_pct=foreign_matter_pct,
|
|
damaged_grain_pct=damaged_pct,
|
|
oil_content_pct=oil_pct,
|
|
decision=decision,
|
|
rejection_reason=rejection_reason,
|
|
remarks=remarks
|
|
)
|
|
|
|
insp_dict = inspection.to_dict()
|
|
self.store.insert("quality_inspections", tenant_id, insp_dict)
|
|
|
|
# Auto-apply decision if specified
|
|
if decision in {"RELEASED", "REJECTED"}:
|
|
lot = InventoryLot(
|
|
tenant_id=tenant_id,
|
|
lot_number=lot_data["lot_number"],
|
|
grn_id=lot_data["grn_id"],
|
|
commodity_id=lot_data["commodity_id"],
|
|
variety=lot_data["variety"],
|
|
godown_stack_id=lot_data["godown_stack_id"],
|
|
initial_quantity_mt=Decimal(str(lot_data["initial_quantity_mt"])),
|
|
grade=lot_data["grade"],
|
|
lot_id=lot_data["id"]
|
|
)
|
|
lot.qc_status = lot_data["qc_status"]
|
|
lot.transition_qc_status(decision)
|
|
lot_data["qc_status"] = lot.qc_status
|
|
if decision == "RELEASED":
|
|
lot_data["current_quantity_mt"] = float(inspection.net_billable_weight_mt)
|
|
self.store.update("inventory_lots", tenant_id, lot.id, lot_data)
|
|
|
|
record_audit_event(
|
|
store=self.store,
|
|
tenant_id=tenant_id,
|
|
actor_user_id=auth_res["user_id"],
|
|
action_type="RECORD_QUALITY_INSPECTION",
|
|
resource_type="quality_inspection",
|
|
resource_id=inspection.id,
|
|
before_state=None,
|
|
after_state={"sample_code": sample_code, "decision": decision, "rebate_amount": float(inspection.total_rebate_amount)}
|
|
)
|
|
|
|
return {
|
|
"success": True,
|
|
"inspection": insp_dict,
|
|
"lot_qc_status": lot_data["qc_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 record quality inspection")
|
|
return {"error": "INTERNAL_ERROR", "message": str(e), "status_code": 500}
|
|
|
|
# =========================================================================
|
|
# STORY-QC-002: Lot FSM Decision Transition
|
|
# =========================================================================
|
|
|
|
def execute_lot_decision(
|
|
self, auth_header: Optional[str], tenant_header: Optional[str], lot_id: str, payload: Dict[str, Any]
|
|
) -> Dict[str, Any]:
|
|
"""POST /api/v1/quality/lots/{id}/decision (FR-QUALITYANDLOTCONTROL-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"]
|
|
ctx = auth_res["context"]
|
|
|
|
allowed_roles = {"Quality Officer", "Quality Inspector", "Tenant Administrator", "Partner / MD"}
|
|
if not any(r in allowed_roles for r in ctx.roles):
|
|
return {
|
|
"error": "INSUFFICIENT_PERMISSIONS",
|
|
"message": "Requires Quality Inspector or Tenant Admin role to commit quality decisions",
|
|
"status_code": 403
|
|
}
|
|
|
|
try:
|
|
decision = payload.get("decision", "")
|
|
rejection_reason = payload.get("rejection_reason")
|
|
|
|
lot_data = self.store.get("inventory_lots", tenant_id, lot_id)
|
|
if not lot_data:
|
|
matches = self.store.query(
|
|
"inventory_lots",
|
|
tenant_id,
|
|
lambda l: l.get("lot_number") == lot_id or l.get("id") == lot_id
|
|
)
|
|
if matches:
|
|
lot_data = matches[0]
|
|
lot_id = lot_data["id"]
|
|
else:
|
|
return {"error": "NOT_FOUND", "message": "Lot not found", "status_code": 404}
|
|
|
|
if decision == "REJECTED" and not rejection_reason:
|
|
return {
|
|
"error": "VALIDATION_ERROR",
|
|
"message": "Rejection reason is mandatory when decision is REJECTED",
|
|
"status_code": 422
|
|
}
|
|
|
|
lot = InventoryLot(
|
|
tenant_id=tenant_id,
|
|
lot_number=lot_data["lot_number"],
|
|
grn_id=lot_data["grn_id"],
|
|
commodity_id=lot_data["commodity_id"],
|
|
variety=lot_data["variety"],
|
|
godown_stack_id=lot_data["godown_stack_id"],
|
|
initial_quantity_mt=Decimal(str(lot_data["initial_quantity_mt"])),
|
|
grade=lot_data["grade"],
|
|
lot_id=lot_data["id"]
|
|
)
|
|
lot.qc_status = lot_data["qc_status"]
|
|
lot.transition_qc_status(decision)
|
|
|
|
lot_data["qc_status"] = lot.qc_status
|
|
if decision == "RELEASED":
|
|
inspections = self.store.list("quality_inspections", tenant_id)
|
|
lot_insps = [i for i in inspections if i.get("lot_id") == lot.id]
|
|
if lot_insps:
|
|
latest_insp = max(lot_insps, key=lambda x: x.get("created_at") or "")
|
|
if "net_billable_weight_mt" in latest_insp:
|
|
lot_data["current_quantity_mt"] = float(latest_insp["net_billable_weight_mt"])
|
|
self.store.update("inventory_lots", tenant_id, lot_id, lot_data)
|
|
|
|
record_audit_event(
|
|
store=self.store,
|
|
tenant_id=tenant_id,
|
|
actor_user_id=auth_res["user_id"],
|
|
action_type="EXECUTE_LOT_QC_DECISION",
|
|
resource_type="inventory_lot",
|
|
resource_id=lot_id,
|
|
before_state={"qc_status": lot_data["qc_status"]},
|
|
after_state={"qc_status": lot.qc_status, "decision": decision}
|
|
)
|
|
|
|
return {
|
|
"success": True,
|
|
"lot": lot_data,
|
|
"status_code": 200
|
|
}
|
|
|
|
except ValueError as e:
|
|
return {"error": "INVALID_TRANSITION", "message": str(e), "status_code": 400}
|
|
except Exception as e:
|
|
logger.exception("Failed to execute lot decision")
|
|
return {"error": "INTERNAL_ERROR", "message": str(e), "status_code": 500}
|
|
|
|
# =========================================================================
|
|
# STORY-QC-004: Lot Lineage & Genealogy Traversal
|
|
# =========================================================================
|
|
|
|
def get_lot_lineage(
|
|
self, auth_header: Optional[str], tenant_header: Optional[str], lot_id: str
|
|
) -> Dict[str, Any]:
|
|
"""GET /api/v1/quality/lots/{id}/lineage (FR-QUALITYANDLOTCONTROL-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"]
|
|
lot_data = self.store.get("inventory_lots", tenant_id, lot_id)
|
|
if not lot_data:
|
|
return {"error": "NOT_FOUND", "message": "Lot not found", "status_code": 404}
|
|
|
|
# Traverse upwards to GRN, Weighbridge, Gate Entry, and Sauda
|
|
grn_data = self.store.get("goods_receipt_notes", tenant_id, lot_data.get("grn_id"))
|
|
weighment_data = self.store.get("weighbridge_slips", tenant_id, grn_data.get("weighment_slip_id")) if grn_data else None
|
|
gate_data = self.store.get("inward_gate_entries", tenant_id, weighment_data.get("gate_pass_id")) if weighment_data else None
|
|
sauda_data = self.store.get("procurement_sauda", tenant_id, grn_data.get("sauda_id")) if grn_data else None
|
|
|
|
lineage_tree = {
|
|
"lot": lot_data,
|
|
"parent_lot": self.store.get("inventory_lots", tenant_id, lot_data.get("parent_lot_id")) if lot_data.get("parent_lot_id") else None,
|
|
"goods_receipt_note": grn_data,
|
|
"weighbridge_slip": weighment_data,
|
|
"gate_entry": gate_data,
|
|
"procurement_sauda": sauda_data
|
|
}
|
|
|
|
return {
|
|
"success": True,
|
|
"lot_id": lot_id,
|
|
"lineage": lineage_tree,
|
|
"status_code": 200
|
|
}
|
|
|
|
|
|
quality_controller = QualityController()
|