c_agri_trade_code/backend/app/api/processing.py

195 lines
7.2 KiB
Python

"""Godown Processing & Conditioning Work Orders API Controller.
Fulfills:
- STORY-PROCESSING-001 (FR-PROCESSING-001, FR-PROCESSING-002, FR-PROCESSING-003):
Post-harvest drying (Sukhai), grading (Chhanai), and mass conservation reconciliation.
Adheres to LLD-015 and UP-AI v1.5 standards.
"""
from datetime import datetime, timezone
from decimal import Decimal, ROUND_HALF_UP
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,
record_audit_event,
)
from backend.app.db.session import storage
from backend.app.models.processing import (
GodownProcessingOrder,
PROCESSING_TYPES,
ORDER_STATUSES,
)
logger = logging.getLogger("atb.api.processing")
PROCESS_TYPE_ALIASES = {
"SUKHAI": "SUN_DRYING",
"CHHANAI": "MECHANICAL_CLEANING",
"CLEANING": "MECHANICAL_CLEANING",
"DRYING": "SUN_DRYING",
"SIEVING": "MECHANICAL_CLEANING",
}
class ProcessingController:
"""Handles godown processing work orders and mass-conservation balances."""
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,
)
return {
"authenticated": True,
"session": session,
"context": ctx,
"tenant_id": ctx.tenant_id,
"user_id": user_id,
"roles": list(dict.fromkeys(ctx.roles + user_roles)),
}
except TenantContextResolutionError as err:
return {"authenticated": False, "error": err.message, "code": err.code, "status_code": err.status_code}
def list_orders(
self,
auth_header: Optional[str],
tenant_header: Optional[str],
godown_id: Optional[str] = None,
process_type: Optional[str] = None,
) -> Dict[str, Any]:
"""GET /api/v1/processing/orders"""
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"]
orders = self.store.list("godown_processing_orders", tenant_id)
if godown_id:
orders = [o for o in orders if o.get("godown_id") == godown_id]
if process_type:
orders = [o for o in orders if o.get("process_type") == process_type]
orders = sorted(orders, key=lambda x: x.get("created_at") or "", reverse=True)
return {
"status_code": 200,
"orders": orders,
"total_records": len(orders),
}
def create_order(
self,
auth_header: Optional[str],
tenant_header: Optional[str],
payload: Dict[str, Any],
) -> Dict[str, Any]:
"""POST /api/v1/processing/orders"""
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"]
order_no = payload.get("order_number") or payload.get("order_id") or f"ORD-PROC-{uuid.uuid4().hex[:8].upper()}"
godown_id = payload.get("godown_id")
raw_process = (payload.get("process_type") or payload.get("operation_type") or "").upper()
process_type = PROCESS_TYPE_ALIASES.get(raw_process, raw_process)
input_lot_id = payload.get("input_lot_id") or payload.get("lot_id")
if not godown_id or not process_type or not input_lot_id:
return {
"status_code": 400,
"error": "godown_id, process_type (or operation_type), and input_lot_id (or lot_id) are required",
}
input_wt = Decimal(str(payload.get("input_weight_mt", "0.0")))
output_primary_wt = Decimal(
str(payload.get("output_primary_mt") or payload.get("output_primary_weight_mt") or "0.0")
)
output_primary_lot_id = payload.get("output_primary_lot_id") or f"{input_lot_id}-PRIMARY"
output_byproduct_wt = Decimal(
str(payload.get("output_byproduct_mt") or payload.get("output_byproduct_weight_mt") or "0.0")
)
byproduct_lot_id = payload.get("output_byproduct_lot_id")
waste_wt = Decimal(
str(payload.get("waste_weight_mt") or payload.get("waste_dust_weight_mt") or "0.0")
)
# Shrinkage handling
if "shrinkage_loss_mt" in payload:
shrinkage = Decimal(str(payload["shrinkage_loss_mt"]))
else:
diff = input_wt - (output_primary_wt + output_byproduct_wt + waste_wt)
shrinkage = diff if diff >= Decimal("0.000") else Decimal("0.000")
try:
order = GodownProcessingOrder(
tenant_id=tenant_id,
order_number=order_no,
godown_id=godown_id,
process_type=process_type,
input_lot_id=input_lot_id,
input_weight_mt=input_wt,
output_primary_lot_id=output_primary_lot_id,
output_primary_mt=output_primary_wt,
output_primary_grade=payload.get("output_primary_grade", "FAQ"),
output_byproduct_lot_id=byproduct_lot_id,
output_byproduct_mt=output_byproduct_wt,
waste_weight_mt=waste_wt,
shrinkage_loss_mt=shrinkage,
status=payload.get("status", "COMPLETED"),
order_id=payload.get("id"),
)
except (ValueError, TypeError) as exc:
return {"status_code": 400, "error": str(exc)}
self.store.insert("godown_processing_orders", tenant_id, order.to_dict())
record_audit_event(
tenant_id=tenant_id,
user_id=user_id,
action="GODOWN_PROCESSING_ORDER_RECORDED",
entity_type="godown_processing_order",
entity_id=order.id,
details={
"order_number": order.order_number,
"process_type": order.process_type,
"input_weight_mt": float(order.input_weight_mt),
"loss_pct": float(order.loss_pct),
},
)
return {
"status_code": 201,
"order": order.to_dict(),
"message": "Godown processing order recorded successfully",
}
processing_controller = ProcessingController()