252 lines
9.0 KiB
Python
252 lines
9.0 KiB
Python
"""Bardana (Packaging Bags) Inventory Ledger & Commercials API Controller.
|
|
|
|
Fulfills:
|
|
- STORY-BARDANA-001 (FR-BARDANA-001): Immutable packaging bag double-entry stock ledger.
|
|
- STORY-BARDANA-002 (FR-BARDANA-002): Packaging line-item commercials calculation.
|
|
- STORY-BARDANA-003 (FR-BARDANA-003): Apportioned handling labor.
|
|
Adheres to LLD-012 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.bardana import (
|
|
BardanaStockEntry,
|
|
calculate_packaging_commercials,
|
|
BARDANA_TYPES,
|
|
BARDANA_TRANSACTION_TYPES,
|
|
COMMERCIAL_PACKAGING_TERMS,
|
|
)
|
|
|
|
logger = logging.getLogger("atb.api.bardana")
|
|
|
|
|
|
class BardanaController:
|
|
"""Handles packaging bag inventory, movements, and commercial billing calculations."""
|
|
|
|
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_balances(
|
|
self,
|
|
auth_header: Optional[str],
|
|
tenant_header: Optional[str],
|
|
godown_id: Optional[str] = None,
|
|
) -> Dict[str, Any]:
|
|
"""GET /api/v1/bardana/balances"""
|
|
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("bardana_stock_entries", tenant_id)
|
|
|
|
if godown_id:
|
|
entries = [e for e in entries if e.get("godown_id") == godown_id]
|
|
|
|
# Calculate latest closing counts by (godown_id, bag_type)
|
|
balances_map: Dict[tuple, Dict[str, Any]] = {}
|
|
# Sort chronologically if created_at present
|
|
sorted_entries = sorted(entries, key=lambda x: x.get("created_at") or "")
|
|
for e in sorted_entries:
|
|
key = (e.get("godown_id"), e.get("bag_type"))
|
|
balances_map[key] = {
|
|
"godown_id": e.get("godown_id"),
|
|
"bag_type": e.get("bag_type"),
|
|
"current_closing_count": e.get("closing_count", 0),
|
|
"last_reference_id": e.get("reference_id"),
|
|
"last_updated": e.get("created_at"),
|
|
}
|
|
|
|
return {
|
|
"status_code": 200,
|
|
"balances": list(balances_map.values()),
|
|
"total_records": len(balances_map),
|
|
}
|
|
|
|
def create_stock_entry(
|
|
self,
|
|
auth_header: Optional[str],
|
|
tenant_header: Optional[str],
|
|
payload: Dict[str, Any],
|
|
) -> Dict[str, Any]:
|
|
"""POST /api/v1/bardana/stock-entries"""
|
|
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"]
|
|
roles = auth_res.get("roles", [])
|
|
|
|
required_fields = ["godown_id", "bag_type", "transaction_type", "reference_id"]
|
|
missing = [f for f in required_fields if f not in payload]
|
|
if missing:
|
|
return {"status_code": 400, "error": f"Missing required fields: {missing}"}
|
|
|
|
godown_id = payload["godown_id"]
|
|
bag_type = payload["bag_type"]
|
|
tx_type = payload["transaction_type"]
|
|
ref_id = payload["reference_id"]
|
|
inward = int(payload.get("inward_count", 0))
|
|
outward = int(payload.get("outward_count", 0))
|
|
damaged = int(payload.get("damaged_count", 0))
|
|
|
|
# Determine opening balance if not explicitly provided
|
|
if "opening_count" in payload:
|
|
opening = int(payload["opening_count"])
|
|
else:
|
|
existing = [
|
|
e for e in self.store.list("bardana_stock_entries", tenant_id)
|
|
if e.get("godown_id") == godown_id and e.get("bag_type") == bag_type
|
|
]
|
|
if existing:
|
|
latest = max(existing, key=lambda x: x.get("created_at") or "")
|
|
opening = latest.get("closing_count", 0)
|
|
else:
|
|
opening = 0
|
|
|
|
# High damaged bag writeoff check
|
|
if damaged > 50:
|
|
is_supervisor = any(
|
|
r in {"PARTNER", "ADMIN", "DIRECTOR", "Yard Supervisor", "Warehouse Manager", "Partner / MD"}
|
|
for r in roles
|
|
)
|
|
if not is_supervisor:
|
|
return {
|
|
"status_code": 403,
|
|
"error": "Yard Supervisor or Partner authorization required to write off > 50 damaged bags",
|
|
}
|
|
|
|
try:
|
|
entry = BardanaStockEntry(
|
|
tenant_id=tenant_id,
|
|
godown_id=godown_id,
|
|
bag_type=bag_type,
|
|
transaction_type=tx_type,
|
|
reference_id=ref_id,
|
|
opening_count=opening,
|
|
inward_count=inward,
|
|
outward_count=outward,
|
|
damaged_count=damaged,
|
|
entry_id=payload.get("id"),
|
|
)
|
|
except (ValueError, TypeError) as exc:
|
|
return {"status_code": 400, "error": str(exc)}
|
|
|
|
self.store.insert("bardana_stock_entries", tenant_id, entry.to_dict())
|
|
|
|
record_audit_event(
|
|
tenant_id=tenant_id,
|
|
user_id=user_id,
|
|
action="BARDANA_STOCK_ENTRY_RECORDED",
|
|
entity_type="bardana_stock_entry",
|
|
entity_id=entry.id,
|
|
details={
|
|
"godown_id": godown_id,
|
|
"bag_type": bag_type,
|
|
"transaction_type": tx_type,
|
|
"reference_id": ref_id,
|
|
"closing_count": entry.closing_count,
|
|
},
|
|
)
|
|
|
|
return {
|
|
"status_code": 201,
|
|
"stock_entry": entry.to_dict(),
|
|
"entry": entry.to_dict(),
|
|
"message": "Bardana stock entry recorded successfully",
|
|
}
|
|
|
|
def calculate_commercials(
|
|
self,
|
|
auth_header: Optional[str],
|
|
tenant_header: Optional[str],
|
|
payload: Dict[str, Any],
|
|
) -> Dict[str, Any]:
|
|
"""POST /api/v1/bardana/calculate-commercials"""
|
|
auth_res = self._authenticate_and_resolve(auth_header, tenant_header)
|
|
if not auth_res.get("authenticated"):
|
|
return auth_res
|
|
|
|
packaging_term = payload.get("packaging_term")
|
|
bag_count = int(payload.get("bag_count", 0))
|
|
bag_type = payload.get("bag_type")
|
|
bag_unit_rate_val = payload.get("bag_unit_rate")
|
|
bag_unit_rate = (
|
|
Decimal(str(bag_unit_rate_val))
|
|
if bag_unit_rate_val is not None
|
|
else None
|
|
)
|
|
filling_rate = Decimal(str(payload.get("filling_rate_per_bag", "2.50")))
|
|
stitching_rate = Decimal(str(payload.get("stitching_rate_per_bag", "1.50")))
|
|
marking_rate = Decimal(str(payload.get("marking_rate_per_bag", "0.50")))
|
|
|
|
try:
|
|
res = calculate_packaging_commercials(
|
|
packaging_term=packaging_term,
|
|
bag_count=bag_count,
|
|
bag_type=bag_type,
|
|
bag_unit_rate=bag_unit_rate,
|
|
filling_rate_per_bag=filling_rate,
|
|
stitching_rate_per_bag=stitching_rate,
|
|
marking_rate_per_bag=marking_rate,
|
|
)
|
|
except (ValueError, TypeError) as exc:
|
|
return {"status_code": 400, "error": str(exc)}
|
|
|
|
serializable = {}
|
|
for k, v in res.items():
|
|
serializable[k] = float(v) if isinstance(v, Decimal) else v
|
|
|
|
return {
|
|
"status_code": 200,
|
|
"commercials": serializable,
|
|
**serializable,
|
|
}
|
|
|
|
|
|
bardana_controller = BardanaController()
|
|
|