233 lines
8.3 KiB
Python
233 lines
8.3 KiB
Python
"""APMC Mandi Statutory Transit Permits & Compliance API Controller.
|
|
|
|
Fulfills:
|
|
- STORY-MANDI-001 (FR-MANDI-001, FR-MANDI-002, FR-MANDI-003):
|
|
Official Anugya Patra generation, validity window tracking, and single-point tax paid ledger.
|
|
Adheres to LLD-013 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.mandi_compliance import (
|
|
MandiTransitPermit,
|
|
MandiTaxPaidLedger,
|
|
PERMIT_STATUSES,
|
|
)
|
|
|
|
logger = logging.getLogger("atb.api.mandi_compliance")
|
|
|
|
|
|
class MandiComplianceController:
|
|
"""Handles statutory transit permits (Anugya Patra) and tax-paid volume ledger."""
|
|
|
|
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_permits(
|
|
self,
|
|
auth_header: Optional[str],
|
|
tenant_header: Optional[str],
|
|
status: Optional[str] = None,
|
|
commodity_id: Optional[str] = None,
|
|
) -> Dict[str, Any]:
|
|
"""GET /api/v1/compliance/mandi/permits"""
|
|
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"]
|
|
permits = self.store.list("mandi_transit_permits", tenant_id)
|
|
|
|
if status:
|
|
permits = [p for p in permits if p.get("status") == status]
|
|
if commodity_id:
|
|
permits = [p for p in permits if p.get("commodity_id") == commodity_id]
|
|
|
|
permits = sorted(permits, key=lambda x: x.get("created_at") or "", reverse=True)
|
|
return {
|
|
"status_code": 200,
|
|
"permits": permits,
|
|
"total_records": len(permits),
|
|
}
|
|
|
|
def create_permit(
|
|
self,
|
|
auth_header: Optional[str],
|
|
tenant_header: Optional[str],
|
|
payload: Dict[str, Any],
|
|
) -> Dict[str, Any]:
|
|
"""POST /api/v1/compliance/mandi/permits"""
|
|
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"]
|
|
|
|
required = [
|
|
"permit_number",
|
|
"mandi_samiti_code",
|
|
"dispatch_id",
|
|
"vehicle_reg_no",
|
|
"commodity_id",
|
|
"quantity_mt",
|
|
"bag_count",
|
|
"destination_city",
|
|
"issued_at",
|
|
"valid_until",
|
|
]
|
|
missing = [f for f in required if f not in payload]
|
|
if missing:
|
|
return {"status_code": 400, "error": f"Missing required fields: {missing}"}
|
|
|
|
# Check duplicate permit number within tenant
|
|
existing = [
|
|
p for p in self.store.list("mandi_transit_permits", tenant_id)
|
|
if p.get("permit_number") == payload["permit_number"]
|
|
]
|
|
if existing:
|
|
return {
|
|
"status_code": 409,
|
|
"error": f"Permit number '{payload['permit_number']}' already exists",
|
|
}
|
|
|
|
try:
|
|
issued_at = (
|
|
datetime.fromisoformat(payload["issued_at"].replace("Z", "+00:00"))
|
|
if isinstance(payload["issued_at"], str)
|
|
else payload["issued_at"]
|
|
)
|
|
valid_until = (
|
|
datetime.fromisoformat(payload["valid_until"].replace("Z", "+00:00"))
|
|
if isinstance(payload["valid_until"], str)
|
|
else payload["valid_until"]
|
|
)
|
|
permit = MandiTransitPermit(
|
|
tenant_id=tenant_id,
|
|
permit_number=payload["permit_number"],
|
|
mandi_samiti_code=payload["mandi_samiti_code"],
|
|
dispatch_id=payload["dispatch_id"],
|
|
vehicle_reg_no=payload["vehicle_reg_no"],
|
|
commodity_id=payload["commodity_id"],
|
|
quantity_mt=Decimal(str(payload["quantity_mt"])),
|
|
bag_count=int(payload["bag_count"]),
|
|
destination_city=payload["destination_city"],
|
|
issued_at=issued_at,
|
|
valid_until=valid_until,
|
|
tax_paid_status=payload.get("tax_paid_status", "SHULK_CHHUKTA"),
|
|
permit_id=payload.get("id"),
|
|
)
|
|
except (ValueError, TypeError) as exc:
|
|
return {"status_code": 400, "error": str(exc)}
|
|
|
|
self.store.insert("mandi_transit_permits", tenant_id, permit.to_dict())
|
|
|
|
# Update/Deduct tax-paid ledger if tracking exists
|
|
comm_id = payload["commodity_id"]
|
|
qty = Decimal(str(payload["quantity_mt"]))
|
|
ledgers = [
|
|
l for l in self.store.list("mandi_tax_paid_ledger", tenant_id)
|
|
if l.get("commodity_id") == comm_id
|
|
]
|
|
if ledgers:
|
|
latest = max(ledgers, key=lambda x: x.get("created_at") or "")
|
|
opening = Decimal(str(latest.get("closing_tax_paid_mt", "0.0")))
|
|
if opening >= qty:
|
|
new_ledger = MandiTaxPaidLedger(
|
|
tenant_id=tenant_id,
|
|
commodity_id=comm_id,
|
|
opening_tax_paid_mt=opening,
|
|
dispatched_tax_paid_mt=qty,
|
|
)
|
|
self.store.insert("mandi_tax_paid_ledger", tenant_id, new_ledger.to_dict())
|
|
|
|
record_audit_event(
|
|
tenant_id=tenant_id,
|
|
user_id=user_id,
|
|
action="MANDI_PERMIT_ISSUED",
|
|
entity_type="mandi_transit_permit",
|
|
entity_id=permit.id,
|
|
details={
|
|
"permit_number": permit.permit_number,
|
|
"commodity_id": comm_id,
|
|
"quantity_mt": float(permit.quantity_mt),
|
|
"vehicle_reg_no": permit.vehicle_reg_no,
|
|
},
|
|
)
|
|
|
|
return {
|
|
"status_code": 201,
|
|
"permit": permit.to_dict(),
|
|
"message": "Mandi transit permit issued successfully",
|
|
}
|
|
|
|
def get_tax_ledger(
|
|
self,
|
|
auth_header: Optional[str],
|
|
tenant_header: Optional[str],
|
|
commodity_id: Optional[str] = None,
|
|
) -> Dict[str, Any]:
|
|
"""GET /api/v1/compliance/mandi/tax-ledger"""
|
|
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"]
|
|
entries = self.store.list("mandi_tax_paid_ledger", tenant_id)
|
|
|
|
if commodity_id:
|
|
entries = [e for e in entries if e.get("commodity_id") == commodity_id]
|
|
|
|
entries = sorted(entries, key=lambda x: x.get("created_at") or "", reverse=True)
|
|
return {
|
|
"status_code": 200,
|
|
"ledger_entries": entries,
|
|
"total_records": len(entries),
|
|
}
|
|
|
|
|
|
mandi_compliance_controller = MandiComplianceController()
|
|
|