c_agri_trade_code/backend/app/api/procurement.py

240 lines
9.8 KiB
Python

"""Procurement Contracts & Sauda Booking API Controller.
Fulfills:
- STORY-PROC-001 (FR-PROCUREMENTCONTRACTS-002): Mandi Auction & Direct Purchase Sauda Booking.
- STORY-PROC-002 (FR-PROCUREMENTCONTRACTS-001): Price Variance Alert vs. Modal Rate.
- STORY-PROC-003 (FR-PROCUREMENTCONTRACTS-003): Supplier Credit Terms & Advance Recording.
- STORY-PROC-004 (FR-PROCUREMENTCONTRACTS-004): Mandi Cess & Statutory Levies Breakdown.
"""
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.procurement import ProcurementSauda, calculate_sauda_commercials
from sandbox.master_data_mock import MasterDataMock
logger = logging.getLogger("atb.api.procurement")
class ProcurementController:
"""Handles purchase contracts, price variance checks, and commercial settlements."""
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
}
def book_sauda(
self, auth_header: Optional[str], tenant_header: Optional[str], payload: Dict[str, Any]
) -> Dict[str, Any]:
"""POST /api/v1/procurement/sauda (FR-PROCUREMENTCONTRACTS-001..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"]
ctx = auth_res["context"]
# Check required roles
allowed_roles = {"Procurement Officer", "Desk Trader", "Purchase Manager", "Tenant Administrator"}
if not any(r in allowed_roles for r in ctx.roles):
return {
"error": "INSUFFICIENT_PERMISSIONS",
"message": "Only Procurement Officers, Desk Traders, or Tenant Admins can book purchase contracts",
"status_code": 403
}
try:
supplier_id = payload.get("supplier_id")
mandi_id = payload.get("mandi_id")
commodity_id = payload.get("commodity_id")
variety = payload.get("variety", "")
grade = payload.get("grade", "FAQ")
trade_type = payload.get("trade_type", "MANDI_AUCTION")
# Validate supplier active status
supp = MasterDataMock.get_supplier(supplier_id)
if supp and supp.get("status") != "ACTIVE":
return {
"error": "INACTIVE_SUPPLIER",
"message": f"Supplier '{supp.get('name')}' is currently {supp.get('status')}. Cannot book contracts.",
"status_code": 400
}
contract_date_str = payload.get("contract_date")
c_date = datetime.strptime(contract_date_str, "%Y-%m-%d").date() if isinstance(contract_date_str, str) else contract_date_str
delivery_due_str = payload.get("delivery_due_date")
d_date = datetime.strptime(delivery_due_str, "%Y-%m-%d").date() if isinstance(delivery_due_str, str) else delivery_due_str
booked_quantity_mt = Decimal(str(payload.get("booked_quantity_mt", "0.0")))
trade_rate_per_qtl = Decimal(str(payload.get("trade_rate_per_qtl", "0.0")))
estimated_bags = int(payload.get("estimated_bags", 0))
credit_period_days = int(payload.get("credit_period_days", 0))
advance_amount = Decimal(str(payload.get("advance_amount", "0.0")))
mandi_cess_pct = Decimal(str(payload.get("mandi_cess_pct", "1.50")))
krishi_kalyan_pct = Decimal(str(payload.get("krishi_kalyan_pct", "0.50")))
brokerage_rate_pct = Decimal(str(payload.get("brokerage_rate_pct", "1.00")))
benchmark_modal_rate = Decimal(str(payload["benchmark_modal_rate"])) if payload.get("benchmark_modal_rate") is not None else None
variance_acknowledged = bool(payload.get("variance_acknowledged", False))
# Auto-lookup benchmark rate from market observations if omitted
if benchmark_modal_rate is None:
obs_list = self.store.query(
"market_observations",
tenant_id,
lambda o: o.get("commodity_id") == commodity_id and not o.get("is_market_closed", False)
)
if obs_list:
obs_list.sort(key=lambda x: x.get("observation_date", ""), reverse=True)
if obs_list[0].get("modal_rate") is not None:
benchmark_modal_rate = Decimal(str(obs_list[0]["modal_rate"]))
# Generate unique sauda sequential code
existing = self.store.list("procurement_sauda", tenant_id)
seq_num = len(existing) + 1
sauda_number = f"SDA-26-{str(seq_num).zfill(5)}"
# Instantiate sauda model (enforces all commercial, variance, and date checks)
sauda = ProcurementSauda(
tenant_id=tenant_id,
sauda_number=sauda_number,
contract_date=c_date,
delivery_due_date=d_date,
supplier_id=supplier_id,
mandi_id=mandi_id,
commodity_id=commodity_id,
variety=variety,
grade=grade,
trade_type=trade_type,
booked_quantity_mt=booked_quantity_mt,
trade_rate_per_qtl=trade_rate_per_qtl,
estimated_bags=estimated_bags,
credit_period_days=credit_period_days,
advance_amount=advance_amount,
mandi_cess_pct=mandi_cess_pct,
krishi_kalyan_pct=krishi_kalyan_pct,
brokerage_rate_pct=brokerage_rate_pct,
benchmark_modal_rate=benchmark_modal_rate,
variance_acknowledged=variance_acknowledged
)
data = sauda.to_dict()
self.store.insert("procurement_sauda", tenant_id, data)
record_audit_event(
store=self.store,
tenant_id=tenant_id,
actor_user_id=auth_res["user_id"],
action_type="BOOK_PURCHASE_SAUDA",
resource_type="procurement_sauda",
resource_id=sauda.id,
before_state=None,
after_state={"sauda_number": sauda_number, "supplier_id": supplier_id, "total_value": float(sauda.total_landed_amount)}
)
return {
"success": True,
"sauda": 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 book purchase sauda")
return {"error": "INTERNAL_ERROR", "message": str(e), "status_code": 500}
def list_saudas(
self,
auth_header: Optional[str],
tenant_header: Optional[str],
supplier_id: Optional[str] = None,
status_filter: Optional[str] = None
) -> Dict[str, Any]:
"""GET /api/v1/procurement/sauda (FR-PROCUREMENTCONTRACTS-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"]
def predicate(s):
if supplier_id and s.get("supplier_id") != supplier_id:
return False
if status_filter and s.get("status") != status_filter:
return False
return True
records = self.store.query("procurement_sauda", tenant_id, predicate)
return {
"success": True,
"count": len(records),
"saudas": records,
"status_code": 200
}
def get_sauda(
self, auth_header: Optional[str], tenant_header: Optional[str], sauda_id: str
) -> Dict[str, Any]:
"""GET /api/v1/procurement/sauda/{id} (FR-PROCUREMENTCONTRACTS-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"]
sauda = self.store.get("procurement_sauda", tenant_id, sauda_id)
if not sauda:
return {"error": "NOT_FOUND", "message": "Purchase sauda not found", "status_code": 404}
return {
"success": True,
"sauda": sauda,
"status_code": 200
}
procurement_controller = ProcurementController()