469 lines
18 KiB
Python
469 lines
18 KiB
Python
"""Agricultural Master Data Management API Controller.
|
|
|
|
Fulfills:
|
|
- STORY-MASTER-001 (FR-MASTERDATA-001): Commodity Catalog & Quality Grading Specifications (UC-016).
|
|
- STORY-MASTER-002 (FR-MASTERDATA-002): Counterparty Directory & Godown Storage Directory (UC-016).
|
|
|
|
Adheres to LLD-001, LLD-002, and UP-AI v1.5 standards.
|
|
"""
|
|
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,
|
|
record_audit_event,
|
|
)
|
|
from backend.app.db.session import storage
|
|
from backend.app.models.master_data import (
|
|
Commodity,
|
|
CommodityVariety,
|
|
TradingCounterparty,
|
|
Godown,
|
|
COUNTERPARTY_TYPES,
|
|
ALLOWED_CREDIT_TERMS_DAYS,
|
|
)
|
|
|
|
logger = logging.getLogger("atb.api.master_data")
|
|
|
|
|
|
class MasterDataController:
|
|
"""Handles CRUD, validation guards, and referential checks for master data records."""
|
|
|
|
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,
|
|
"context": ctx,
|
|
"user_id": user_id,
|
|
"email": email,
|
|
"roles": ctx.roles,
|
|
}
|
|
except TenantContextResolutionError as err:
|
|
return {"authenticated": False, "error": err.message, "code": err.code, "status_code": err.status_code}
|
|
|
|
|
|
# =========================================================================
|
|
# Commodity & Variety Operations (FR-MASTERDATA-001)
|
|
# =========================================================================
|
|
|
|
def create_commodity(
|
|
self, auth_header: Optional[str], tenant_header: Optional[str], payload: Dict[str, Any]
|
|
) -> Dict[str, Any]:
|
|
"""POST /api/v1/master-data/commodities"""
|
|
auth = self._authenticate_and_resolve(auth_header, tenant_header)
|
|
if not auth["authenticated"]:
|
|
return auth
|
|
|
|
ctx: TenantContext = auth["context"]
|
|
tenant_id = ctx.tenant_id
|
|
|
|
# Unique code guard within tenant
|
|
code = (payload.get("code") or "").strip().upper()
|
|
if not code:
|
|
return {"error": "COMMODITY_CODE_REQUIRED", "message": "Commodity code is required", "status_code": 422}
|
|
|
|
existing = self.store.query(
|
|
"commodities", tenant_id, lambda c: c.get("code", "").upper() == code
|
|
)
|
|
if existing:
|
|
return {
|
|
"error": "DUPLICATE_COMMODITY_CODE",
|
|
"message": f"Commodity with code '{code}' already exists for this tenant",
|
|
"status_code": 409,
|
|
}
|
|
|
|
try:
|
|
comm = Commodity(
|
|
tenant_id=tenant_id,
|
|
code=code,
|
|
name=payload.get("name", ""),
|
|
hsn_code=payload.get("hsn_code"),
|
|
standard_bag_weight_kg=float(payload.get("standard_bag_weight_kg", 50.0)),
|
|
moisture_baseline_pct=float(payload.get("moisture_baseline_pct", 10.0)),
|
|
foreign_matter_max_pct=float(payload.get("foreign_matter_max_pct", 2.0)),
|
|
damaged_grain_max_pct=float(payload.get("damaged_grain_max_pct", 3.0)),
|
|
qc_required=bool(payload.get("qc_required", True)),
|
|
is_active=bool(payload.get("is_active", True)),
|
|
id=payload.get("id"),
|
|
)
|
|
except (ValueError, TypeError) as e:
|
|
return {"error": "VALIDATION_ERROR", "message": str(e), "status_code": 422}
|
|
|
|
self.store.insert("commodities", tenant_id, comm.to_dict())
|
|
|
|
# Handle nested varieties if provided
|
|
created_varieties = []
|
|
for v in payload.get("varieties", []):
|
|
try:
|
|
var = CommodityVariety(
|
|
tenant_id=tenant_id,
|
|
commodity_id=comm.id,
|
|
code=v.get("code", ""),
|
|
name=v.get("name", ""),
|
|
is_active=bool(v.get("is_active", True)),
|
|
)
|
|
self.store.insert("commodity_varieties", tenant_id, var.to_dict())
|
|
created_varieties.append(var.to_dict())
|
|
except ValueError:
|
|
pass
|
|
|
|
resp = comm.to_dict()
|
|
resp["varieties"] = created_varieties
|
|
resp["status_code"] = 201
|
|
return resp
|
|
|
|
def list_commodities(
|
|
self, auth_header: Optional[str], tenant_header: Optional[str]
|
|
) -> Dict[str, Any]:
|
|
"""GET /api/v1/master-data/commodities"""
|
|
auth = self._authenticate_and_resolve(auth_header, tenant_header)
|
|
if not auth["authenticated"]:
|
|
return auth
|
|
|
|
ctx: TenantContext = auth["context"]
|
|
tenant_id = ctx.tenant_id
|
|
|
|
commodities = self.store.list("commodities", tenant_id)
|
|
varieties = self.store.list("commodity_varieties", tenant_id)
|
|
|
|
# Attach varieties to each commodity
|
|
varieties_by_comm = {}
|
|
for v in varieties:
|
|
cid = v.get("commodity_id")
|
|
varieties_by_comm.setdefault(cid, []).append(v)
|
|
|
|
result = []
|
|
for c in commodities:
|
|
c_dict = dict(c)
|
|
c_dict["varieties"] = varieties_by_comm.get(c.get("id"), [])
|
|
result.append(c_dict)
|
|
|
|
return {"commodities": result, "count": len(result), "status_code": 200}
|
|
|
|
def get_commodity(
|
|
self, auth_header: Optional[str], tenant_header: Optional[str], commodity_id: str
|
|
) -> Dict[str, Any]:
|
|
"""GET /api/v1/master-data/commodities/{id}"""
|
|
auth = self._authenticate_and_resolve(auth_header, tenant_header)
|
|
if not auth["authenticated"]:
|
|
return auth
|
|
|
|
ctx: TenantContext = auth["context"]
|
|
tenant_id = ctx.tenant_id
|
|
|
|
comm = self.store.get("commodities", tenant_id, commodity_id)
|
|
if not comm:
|
|
return {"error": "COMMODITY_NOT_FOUND", "message": f"Commodity '{commodity_id}' not found", "status_code": 404}
|
|
|
|
varieties = self.store.query("commodity_varieties", tenant_id, lambda v: v.get("commodity_id") == commodity_id)
|
|
resp = dict(comm)
|
|
resp["varieties"] = varieties
|
|
resp["status_code"] = 200
|
|
return resp
|
|
|
|
def update_commodity(
|
|
self, auth_header: Optional[str], tenant_header: Optional[str], commodity_id: str, payload: Dict[str, Any]
|
|
) -> Dict[str, Any]:
|
|
"""PATCH /api/v1/master-data/commodities/{id}"""
|
|
auth = self._authenticate_and_resolve(auth_header, tenant_header)
|
|
if not auth["authenticated"]:
|
|
return auth
|
|
|
|
ctx: TenantContext = auth["context"]
|
|
tenant_id = ctx.tenant_id
|
|
|
|
comm = self.store.get("commodities", tenant_id, commodity_id)
|
|
if not comm:
|
|
return {"error": "COMMODITY_NOT_FOUND", "message": f"Commodity '{commodity_id}' not found", "status_code": 404}
|
|
|
|
# Apply updates
|
|
for field in ["name", "hsn_code", "is_active", "standard_bag_weight_kg", "moisture_baseline_pct", "foreign_matter_max_pct", "damaged_grain_max_pct", "qc_required"]:
|
|
if field in payload:
|
|
comm[field] = payload[field]
|
|
|
|
comm["updated_at"] = datetime.now(timezone.utc).isoformat()
|
|
self.store.update("commodities", tenant_id, commodity_id, comm)
|
|
comm["status_code"] = 200
|
|
return comm
|
|
|
|
def delete_commodity(
|
|
self, auth_header: Optional[str], tenant_header: Optional[str], commodity_id: str
|
|
) -> Dict[str, Any]:
|
|
"""DELETE /api/v1/master-data/commodities/{id} with Active Inventory Referential Check."""
|
|
auth = self._authenticate_and_resolve(auth_header, tenant_header)
|
|
if not auth["authenticated"]:
|
|
return auth
|
|
|
|
ctx: TenantContext = auth["context"]
|
|
tenant_id = ctx.tenant_id
|
|
|
|
comm = self.store.get("commodities", tenant_id, commodity_id)
|
|
if not comm:
|
|
return {"error": "COMMODITY_NOT_FOUND", "message": f"Commodity '{commodity_id}' not found", "status_code": 404}
|
|
|
|
comm_code = comm.get("code")
|
|
|
|
# Referential guard 1: Check active inventory lots
|
|
lots = self.store.query(
|
|
"inventory_lots",
|
|
tenant_id,
|
|
lambda lot: lot.get("commodity_id") == commodity_id or lot.get("commodity") == comm_code,
|
|
)
|
|
if lots:
|
|
return {
|
|
"error": "REFERENCE_CONSTRAINT_VIOLATION",
|
|
"message": f"Cannot delete commodity '{comm.get('name')}': {len(lots)} active inventory lots reference this commodity. Please soft-deactivate instead.",
|
|
"referenced_lots_count": len(lots),
|
|
"status_code": 409,
|
|
}
|
|
|
|
# Referential guard 2: Check procurement saudas
|
|
saudas = self.store.query(
|
|
"procurement_sauda",
|
|
tenant_id,
|
|
lambda s: s.get("commodity_id") == commodity_id or s.get("commodity") == comm_code,
|
|
)
|
|
if saudas:
|
|
return {
|
|
"error": "REFERENCE_CONSTRAINT_VIOLATION",
|
|
"message": f"Cannot delete commodity '{comm.get('name')}': {len(saudas)} procurement saudas reference this commodity. Please soft-deactivate instead.",
|
|
"referenced_saudas_count": len(saudas),
|
|
"status_code": 409,
|
|
}
|
|
|
|
# Safe to delete
|
|
self.store.delete("commodities", tenant_id, commodity_id)
|
|
return {"success": True, "deleted_id": commodity_id, "status_code": 200}
|
|
|
|
def add_variety(
|
|
self, auth_header: Optional[str], tenant_header: Optional[str], commodity_id: str, payload: Dict[str, Any]
|
|
) -> Dict[str, Any]:
|
|
"""POST /api/v1/master-data/commodities/{id}/varieties"""
|
|
auth = self._authenticate_and_resolve(auth_header, tenant_header)
|
|
if not auth["authenticated"]:
|
|
return auth
|
|
|
|
ctx: TenantContext = auth["context"]
|
|
tenant_id = ctx.tenant_id
|
|
|
|
comm = self.store.get("commodities", tenant_id, commodity_id)
|
|
if not comm:
|
|
return {"error": "COMMODITY_NOT_FOUND", "message": f"Commodity '{commodity_id}' not found", "status_code": 404}
|
|
|
|
code = (payload.get("code") or "").strip().upper()
|
|
if not code:
|
|
return {"error": "VARIETY_CODE_REQUIRED", "message": "Variety code is required", "status_code": 422}
|
|
|
|
existing = self.store.query(
|
|
"commodity_varieties",
|
|
tenant_id,
|
|
lambda v: v.get("commodity_id") == commodity_id and v.get("code", "").upper() == code,
|
|
)
|
|
if existing:
|
|
return {
|
|
"error": "DUPLICATE_VARIETY_CODE",
|
|
"message": f"Variety with code '{code}' already exists under this commodity",
|
|
"status_code": 409,
|
|
}
|
|
|
|
try:
|
|
var = CommodityVariety(
|
|
tenant_id=tenant_id,
|
|
commodity_id=commodity_id,
|
|
code=code,
|
|
name=payload.get("name", ""),
|
|
is_active=bool(payload.get("is_active", True)),
|
|
id=payload.get("id"),
|
|
)
|
|
except (ValueError, TypeError) as e:
|
|
return {"error": "VALIDATION_ERROR", "message": str(e), "status_code": 422}
|
|
|
|
self.store.insert("commodity_varieties", tenant_id, var.to_dict())
|
|
resp = var.to_dict()
|
|
resp["status_code"] = 201
|
|
return resp
|
|
|
|
# =========================================================================
|
|
# Counterparty Directory Operations (FR-MASTERDATA-002)
|
|
# =========================================================================
|
|
|
|
def create_counterparty(
|
|
self, auth_header: Optional[str], tenant_header: Optional[str], payload: Dict[str, Any]
|
|
) -> Dict[str, Any]:
|
|
"""POST /api/v1/master-data/counterparties"""
|
|
auth = self._authenticate_and_resolve(auth_header, tenant_header)
|
|
if not auth["authenticated"]:
|
|
return auth
|
|
|
|
ctx: TenantContext = auth["context"]
|
|
tenant_id = ctx.tenant_id
|
|
|
|
pan = (payload.get("pan_number") or "").strip().upper()
|
|
if not pan:
|
|
return {"error": "PAN_REQUIRED", "message": "PAN number is required", "status_code": 422}
|
|
|
|
# Tenant-scoped PAN uniqueness guard
|
|
existing = self.store.query(
|
|
"trading_counterparties",
|
|
tenant_id,
|
|
lambda cp: cp.get("pan_number", "").upper() == pan,
|
|
)
|
|
if existing:
|
|
return {
|
|
"error": "DUPLICATE_PAN_IN_TENANT",
|
|
"message": f"A counterparty with PAN '{pan}' is already registered in this tenant",
|
|
"status_code": 409,
|
|
}
|
|
|
|
# Credit terms validation
|
|
credit_terms = payload.get("credit_terms_days", 7)
|
|
try:
|
|
credit_terms_int = int(credit_terms)
|
|
except (ValueError, TypeError):
|
|
return {"error": "INVALID_CREDIT_TERMS", "message": f"Credit terms must be strictly in {sorted(ALLOWED_CREDIT_TERMS_DAYS)} days", "status_code": 422}
|
|
|
|
if credit_terms_int not in ALLOWED_CREDIT_TERMS_DAYS:
|
|
return {
|
|
"error": "INVALID_CREDIT_TERMS",
|
|
"message": f"Invalid credit terms {credit_terms_int}. Must be strictly {sorted(ALLOWED_CREDIT_TERMS_DAYS)} days.",
|
|
"status_code": 422,
|
|
}
|
|
|
|
try:
|
|
cp = TradingCounterparty(
|
|
tenant_id=tenant_id,
|
|
name=payload.get("name", ""),
|
|
counterparty_type=payload.get("counterparty_type", ""),
|
|
pan_number=pan,
|
|
gstin=payload.get("gstin"),
|
|
credit_terms_days=credit_terms_int,
|
|
credit_limit_inr=float(payload.get("credit_limit_inr", 0.0)),
|
|
bank_account_number=payload.get("bank_account_number", ""),
|
|
bank_ifsc_code=payload.get("bank_ifsc_code", ""),
|
|
bank_name=payload.get("bank_name", ""),
|
|
phone=payload.get("phone"),
|
|
is_active=bool(payload.get("is_active", True)),
|
|
id=payload.get("id"),
|
|
)
|
|
except (ValueError, TypeError) as e:
|
|
return {"error": "VALIDATION_ERROR", "message": str(e), "status_code": 422}
|
|
|
|
self.store.insert("trading_counterparties", tenant_id, cp.to_dict())
|
|
resp = cp.to_dict()
|
|
resp["status_code"] = 201
|
|
return resp
|
|
|
|
def list_counterparties(
|
|
self, auth_header: Optional[str], tenant_header: Optional[str], counterparty_type: Optional[str] = None
|
|
) -> Dict[str, Any]:
|
|
"""GET /api/v1/master-data/counterparties"""
|
|
auth = self._authenticate_and_resolve(auth_header, tenant_header)
|
|
if not auth["authenticated"]:
|
|
return auth
|
|
|
|
ctx: TenantContext = auth["context"]
|
|
tenant_id = ctx.tenant_id
|
|
|
|
if counterparty_type:
|
|
c_type = counterparty_type.strip().upper()
|
|
counterparties = self.store.query(
|
|
"trading_counterparties",
|
|
tenant_id,
|
|
lambda cp: cp.get("counterparty_type", "").upper() == c_type,
|
|
)
|
|
else:
|
|
counterparties = self.store.list("trading_counterparties", tenant_id)
|
|
|
|
return {"counterparties": counterparties, "count": len(counterparties), "status_code": 200}
|
|
|
|
# =========================================================================
|
|
# Godown Directory Operations (FR-MASTERDATA-002)
|
|
# =========================================================================
|
|
|
|
def create_godown(
|
|
self, auth_header: Optional[str], tenant_header: Optional[str], payload: Dict[str, Any]
|
|
) -> Dict[str, Any]:
|
|
"""POST /api/v1/master-data/godowns"""
|
|
auth = self._authenticate_and_resolve(auth_header, tenant_header)
|
|
if not auth["authenticated"]:
|
|
return auth
|
|
|
|
ctx: TenantContext = auth["context"]
|
|
tenant_id = ctx.tenant_id
|
|
|
|
code = (payload.get("code") or "").strip().upper()
|
|
if not code:
|
|
return {"error": "GODOWN_CODE_REQUIRED", "message": "Godown code is required", "status_code": 422}
|
|
|
|
existing = self.store.query("godowns", tenant_id, lambda g: g.get("code", "").upper() == code)
|
|
if existing:
|
|
return {
|
|
"error": "DUPLICATE_GODOWN_CODE",
|
|
"message": f"Godown with code '{code}' already exists for this tenant",
|
|
"status_code": 409,
|
|
}
|
|
|
|
try:
|
|
godown = Godown(
|
|
tenant_id=tenant_id,
|
|
code=code,
|
|
name=payload.get("name", ""),
|
|
capacity_mt=float(payload.get("capacity_mt", 0.0)),
|
|
address=payload.get("address", ""),
|
|
chambers_count=int(payload.get("chambers_count", 1)),
|
|
is_active=bool(payload.get("is_active", True)),
|
|
id=payload.get("id"),
|
|
)
|
|
except (ValueError, TypeError) as e:
|
|
return {"error": "VALIDATION_ERROR", "message": str(e), "status_code": 422}
|
|
|
|
self.store.insert("godowns", tenant_id, godown.to_dict())
|
|
resp = godown.to_dict()
|
|
resp["status_code"] = 201
|
|
return resp
|
|
|
|
def list_godowns(
|
|
self, auth_header: Optional[str], tenant_header: Optional[str]
|
|
) -> Dict[str, Any]:
|
|
"""GET /api/v1/master-data/godowns"""
|
|
auth = self._authenticate_and_resolve(auth_header, tenant_header)
|
|
if not auth["authenticated"]:
|
|
return auth
|
|
|
|
ctx: TenantContext = auth["context"]
|
|
tenant_id = ctx.tenant_id
|
|
|
|
godowns = self.store.list("godowns", tenant_id)
|
|
return {"godowns": godowns, "count": len(godowns), "status_code": 200}
|
|
|
|
|
|
master_data_controller = MasterDataController()
|
|
|