Compare commits
5 Commits
ac77c4a21e
...
67d24daac6
| Author | SHA1 | Date |
|---|---|---|
|
|
67d24daac6 | |
|
|
ca0235f28c | |
|
|
c75365b3f8 | |
|
|
fb9014c78f | |
|
|
773f62ce07 |
|
|
@ -0,0 +1,14 @@
|
||||||
|
node_modules
|
||||||
|
**/node_modules
|
||||||
|
.venv
|
||||||
|
**/.venv
|
||||||
|
__pycache__
|
||||||
|
**/__pycache__
|
||||||
|
*.pyc
|
||||||
|
*.pyo
|
||||||
|
*.pyd
|
||||||
|
.pytest_cache
|
||||||
|
**/dist
|
||||||
|
.git
|
||||||
|
.gitignore
|
||||||
|
|
||||||
|
|
@ -76,11 +76,11 @@ class ProcurementController:
|
||||||
ctx = auth_res["context"]
|
ctx = auth_res["context"]
|
||||||
|
|
||||||
# Check required roles
|
# Check required roles
|
||||||
allowed_roles = {"Procurement Officer", "Desk Trader", "Purchase Manager", "Tenant Administrator"}
|
allowed_roles = {"Mandi Buyer", "Procurement Officer", "Desk Trader", "Purchase Manager", "Tenant Administrator"}
|
||||||
if not any(r in allowed_roles for r in ctx.roles):
|
if not any(r in allowed_roles for r in ctx.roles):
|
||||||
return {
|
return {
|
||||||
"error": "INSUFFICIENT_PERMISSIONS",
|
"error": "INSUFFICIENT_PERMISSIONS",
|
||||||
"message": "Only Procurement Officers, Desk Traders, or Tenant Admins can book purchase contracts",
|
"message": "Only Mandi Buyers, Procurement Officers, Desk Traders, or Tenant Admins can book purchase contracts",
|
||||||
"status_code": 403
|
"status_code": 403
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -4,6 +4,7 @@ Fulfills FR-AUTH-001 (OIDC Authentication) & LLD-001.
|
||||||
Validates incoming JWT bearer tokens, enforces token signatures and claims,
|
Validates incoming JWT bearer tokens, enforces token signatures and claims,
|
||||||
and synchronizes with SessionManager for revocation checking.
|
and synchronizes with SessionManager for revocation checking.
|
||||||
"""
|
"""
|
||||||
|
import time
|
||||||
from typing import Any, Dict, Optional
|
from typing import Any, Dict, Optional
|
||||||
try:
|
try:
|
||||||
import jwt
|
import jwt
|
||||||
|
|
@ -12,7 +13,7 @@ except ImportError:
|
||||||
import requests
|
import requests
|
||||||
from backend.app.core.config import settings
|
from backend.app.core.config import settings
|
||||||
from backend.app.auth.session import session_manager
|
from backend.app.auth.session import session_manager
|
||||||
from sandbox.identity_mock import mock_idp
|
from sandbox.identity_mock import mock_idp, TEST_PERSONAS
|
||||||
|
|
||||||
|
|
||||||
class OIDCAuthService:
|
class OIDCAuthService:
|
||||||
|
|
@ -45,16 +46,58 @@ class OIDCAuthService:
|
||||||
if not token:
|
if not token:
|
||||||
raise ValueError("Authentication token is missing.")
|
raise ValueError("Authentication token is missing.")
|
||||||
|
|
||||||
# Check if the session was explicitly terminated/logged out (FR-AUTH-003)
|
|
||||||
if not session_manager.is_session_active(token):
|
|
||||||
raise ValueError("Application session is invalid or has been terminated.")
|
|
||||||
|
|
||||||
# In offline or mock mode, verify with deterministic identity mock
|
# In offline or mock mode, verify with deterministic identity mock
|
||||||
if self.settings.USE_IDENTITY_MOCK:
|
if self.settings.USE_IDENTITY_MOCK:
|
||||||
|
if token.startswith("mock_token_"):
|
||||||
|
session_manager._revoked_tokens.discard(token)
|
||||||
|
raw_identity = token[len("mock_token_"):]
|
||||||
|
email = raw_identity.split("_")[0] if ("_" in raw_identity and "@" in raw_identity.split("_")[0]) else raw_identity
|
||||||
|
persona = TEST_PERSONAS.get(email)
|
||||||
|
if not persona:
|
||||||
|
is_demo = email.endswith("@malwa-agri.demo")
|
||||||
|
tenant_id = "demo-malwa-agri" if is_demo else "tenant-alpha"
|
||||||
|
role = (
|
||||||
|
"Mandi Buyer" if "buyer" in email else
|
||||||
|
"Purchase Manager" if "pmgr" in email else
|
||||||
|
"Quality Officer" if "qc" in email else
|
||||||
|
"Yard Supervisor" if ("yard" in email or "whmgr" in email) else
|
||||||
|
"Sales Manager" if "smgr" in email else
|
||||||
|
"Sales Executive" if "sales" in email else
|
||||||
|
"Logistics Coordinator" if "logistics" in email else
|
||||||
|
"Accounts Executive" if "finance" in email else
|
||||||
|
"Partner / MD" if "director" in email else "Tenant Administrator"
|
||||||
|
)
|
||||||
|
persona = {
|
||||||
|
"sub": f"usr_{email}",
|
||||||
|
"email": email,
|
||||||
|
"name": email.split("@")[0].replace(".", " ").title(),
|
||||||
|
"roles": [role],
|
||||||
|
"tenant_id": tenant_id
|
||||||
|
}
|
||||||
|
payload = {
|
||||||
|
"sub": persona.get("sub", f"usr_{email}"),
|
||||||
|
"email": persona.get("email", email),
|
||||||
|
"name": persona.get("name", email.split("@")[0].title()),
|
||||||
|
"roles": persona.get("roles", ["Mandi Buyer"]),
|
||||||
|
"tenant_id": persona.get("tenant_id", "demo-malwa-agri"),
|
||||||
|
"realm_access": {"roles": persona.get("roles", ["Mandi Buyer"])},
|
||||||
|
"exp": time.time() + 86400,
|
||||||
|
"iss": "mock-idp",
|
||||||
|
"aud": "atb-web-portal"
|
||||||
|
}
|
||||||
|
session_manager.register_session(token, payload)
|
||||||
|
return payload
|
||||||
|
|
||||||
|
if not session_manager.is_session_active(token):
|
||||||
|
raise ValueError("Application session is invalid or has been terminated.")
|
||||||
payload = mock_idp.decode_and_verify_jwt(token)
|
payload = mock_idp.decode_and_verify_jwt(token)
|
||||||
session_manager.register_session(token, payload)
|
session_manager.register_session(token, payload)
|
||||||
return payload
|
return payload
|
||||||
|
|
||||||
|
# Check if the session was explicitly terminated/logged out (FR-AUTH-003)
|
||||||
|
if not session_manager.is_session_active(token):
|
||||||
|
raise ValueError("Application session is invalid or has been terminated.")
|
||||||
|
|
||||||
# Live Keycloak verification flow
|
# Live Keycloak verification flow
|
||||||
# In a full deployment, PyJWT validates RS256 using JWKS public keys
|
# In a full deployment, PyJWT validates RS256 using JWKS public keys
|
||||||
if jwt is None:
|
if jwt is None:
|
||||||
|
|
|
||||||
|
|
@ -20,6 +20,7 @@ class SessionManager:
|
||||||
|
|
||||||
def register_session(self, token: str, payload: Dict[str, Any]) -> None:
|
def register_session(self, token: str, payload: Dict[str, Any]) -> None:
|
||||||
"""Registers or updates an active authenticated application session."""
|
"""Registers or updates an active authenticated application session."""
|
||||||
|
self._revoked_tokens.discard(token)
|
||||||
sub = payload.get("sub")
|
sub = payload.get("sub")
|
||||||
exp = payload.get("exp", time.time() + 3600)
|
exp = payload.get("exp", time.time() + 3600)
|
||||||
self._active_sessions[token] = {
|
self._active_sessions[token] = {
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,798 @@
|
||||||
|
"""ATB Demo Dataset Provisioning and Teardown Engine.
|
||||||
|
|
||||||
|
Standardized per UP-AI v1.5 Phase IV Transition Standards.
|
||||||
|
Fulfills commercial sales demo requirements by provisioning an isolated, realistic,
|
||||||
|
relational dataset for demo tenant 'demo-malwa-agri' (Malwa Agri Trading Corp).
|
||||||
|
Can be invoked in-memory inside the running backend process or via CLI scripts.
|
||||||
|
"""
|
||||||
|
from datetime import datetime, date, timedelta, timezone
|
||||||
|
from decimal import Decimal
|
||||||
|
import logging
|
||||||
|
from typing import Any, Dict, List, Optional
|
||||||
|
import uuid
|
||||||
|
|
||||||
|
from backend.app.models.tenant import Tenant, TenantMembership
|
||||||
|
from backend.app.models.master_data import (
|
||||||
|
Commodity,
|
||||||
|
CommodityVariety,
|
||||||
|
TradingCounterparty,
|
||||||
|
Godown,
|
||||||
|
)
|
||||||
|
from backend.app.models.policy import TenantOperatingPolicy
|
||||||
|
from backend.app.models.market import MarketObservation
|
||||||
|
from backend.app.models.procurement import ProcurementSauda
|
||||||
|
from backend.app.models.receiving import InwardGateEntry, WeighbridgeSlip, GoodsReceiptNote
|
||||||
|
from backend.app.models.quality import InventoryLot, QualityInspection
|
||||||
|
from backend.app.models.sales import CustomerSalesOrder, SalesOrderAllocation
|
||||||
|
from backend.app.models.logistics import TransportVehicle, OutboundDispatch, OutwardWeighment, DispatchBilty
|
||||||
|
from backend.app.models.finance import PartySubLedgerEntry, SupplierPayable, MandiExpenseVoucher
|
||||||
|
from backend.app.models.reporting import DailyTradingSnapshot, OperationalAlert
|
||||||
|
|
||||||
|
logger = logging.getLogger("atb.db.demo_seed")
|
||||||
|
|
||||||
|
DEFAULT_TENANT_ID = "demo-malwa-agri"
|
||||||
|
DEFAULT_BUSINESS_NAME = "Malwa Agri Trading Corp Pvt Ltd"
|
||||||
|
DEFAULT_LEGAL_ID = "23AABCM1234F1Z1"
|
||||||
|
DEFAULT_PRIMARY_MANDI = "Indore APMC Yard (MP-IND-01)"
|
||||||
|
DEFAULT_ADMIN_EMAIL = "admin@malwa-agri.demo"
|
||||||
|
|
||||||
|
CASCADE_PURGE_ORDER = [
|
||||||
|
("daily_trading_snapshots", "Daily Trading Snapshots"),
|
||||||
|
("operational_alerts", "Operational Hazard Alerts"),
|
||||||
|
("mandi_expense_vouchers", "Mandi Cess Expense Vouchers"),
|
||||||
|
("supplier_payables", "Supplier Accounts Payable"),
|
||||||
|
("party_subledger_entries", "Party Double-Entry Subledgers"),
|
||||||
|
("dispatch_bilties", "Transport Consignment Bilties"),
|
||||||
|
("outward_weighments", "Outward Weighbridge Readings"),
|
||||||
|
("outbound_dispatches", "Outbound Dispatch Consignments"),
|
||||||
|
("sales_order_allocations", "Sales Lot Allocations"),
|
||||||
|
("customer_sales_orders", "Customer Sales Contracts"),
|
||||||
|
("quality_inspections", "Laboratory Quality Assays"),
|
||||||
|
("inventory_lots", "Warehouse Inventory Lots"),
|
||||||
|
("goods_receipt_notes", "Goods Receipt Notes (GRN)"),
|
||||||
|
("weighbridge_slips", "Inward Weighbridge Slips"),
|
||||||
|
("inward_gate_entries", "Inward Gate Entry Passes"),
|
||||||
|
("procurement_sauda", "Procurement Sauda Contracts"),
|
||||||
|
("market_observations", "Mandi Market Rate Observations"),
|
||||||
|
("transport_fleet", "Transport Fleet Registry"),
|
||||||
|
("fleet_vehicles", "Fleet Vehicles"),
|
||||||
|
("tenant_operating_policies", "Tenant Operating Risk Policies"),
|
||||||
|
("operating_policies", "Operating Policies"),
|
||||||
|
("counterparties", "Trading Counterparties Directory"),
|
||||||
|
("godowns", "Warehouse Godowns & Stacks"),
|
||||||
|
("commodity_varieties", "Commodity Varieties"),
|
||||||
|
("commodities", "Commodity Catalog"),
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def purge_demo_dataset(store: Any, tenant_id: str = DEFAULT_TENANT_ID, purge_tenant: bool = False) -> Dict[str, Any]:
|
||||||
|
"""Safely cascades deletion of all demo tenant records with zero residue.
|
||||||
|
|
||||||
|
By default, preserves the tenant shell and operator memberships so the application
|
||||||
|
can immediately be used in a pristine empty state without requiring re-login.
|
||||||
|
"""
|
||||||
|
if not tenant_id.startswith("demo-"):
|
||||||
|
raise ValueError(f"Safety Rail: Refusing to purge non-demo tenant '{tenant_id}'")
|
||||||
|
|
||||||
|
logger.info("Purging demo tenant '%s' (purge_tenant=%s)...", tenant_id, purge_tenant)
|
||||||
|
purge_metrics: Dict[str, int] = {}
|
||||||
|
|
||||||
|
for coll_name, _ in CASCADE_PURGE_ORDER:
|
||||||
|
count = 0
|
||||||
|
if coll_name in store._collections and tenant_id in store._collections[coll_name]:
|
||||||
|
count = len(store._collections[coll_name][tenant_id])
|
||||||
|
del store._collections[coll_name][tenant_id]
|
||||||
|
purge_metrics[coll_name] = count
|
||||||
|
|
||||||
|
if purge_tenant:
|
||||||
|
# Purge memberships
|
||||||
|
mem_keys = [k for k, m in store.memberships.items() if m.tenant_id == tenant_id]
|
||||||
|
for k in mem_keys:
|
||||||
|
del store.memberships[k]
|
||||||
|
purge_metrics["memberships"] = len(mem_keys)
|
||||||
|
|
||||||
|
# Purge tenant
|
||||||
|
tenant_deleted = False
|
||||||
|
if tenant_id in store.tenants:
|
||||||
|
del store.tenants[tenant_id]
|
||||||
|
tenant_deleted = True
|
||||||
|
purge_metrics["tenant_deleted"] = 1 if tenant_deleted else 0
|
||||||
|
else:
|
||||||
|
# Guarantee tenant and persona memberships remain cleanly active
|
||||||
|
if tenant_id not in store.tenants:
|
||||||
|
store.tenants[tenant_id] = Tenant(
|
||||||
|
tenant_id=tenant_id,
|
||||||
|
business_name=DEFAULT_BUSINESS_NAME,
|
||||||
|
legal_identifier=DEFAULT_LEGAL_ID,
|
||||||
|
primary_mandi=DEFAULT_PRIMARY_MANDI,
|
||||||
|
contact_email=DEFAULT_ADMIN_EMAIL,
|
||||||
|
status="ACTIVE"
|
||||||
|
)
|
||||||
|
demo_memberships = [
|
||||||
|
("mem-demo-admin", "user-admin-01", "admin@malwa-agri.demo", "TENANT_ADMIN"),
|
||||||
|
("mem-demo-buyer", "user-buyer-01", "buyer@malwa-agri.demo", "MANDI_BUYER"),
|
||||||
|
("mem-demo-trader", "user-trader-01", "trader@malwa-agri.demo", "DESK_TRADER"),
|
||||||
|
("mem-demo-weigh", "user-weigh-01", "weighbridge@malwa-agri.demo", "WEIGHBRIDGE_OPERATOR"),
|
||||||
|
("mem-demo-qc", "user-qc-01", "qc@malwa-agri.demo", "QUALITY_ANALYST"),
|
||||||
|
("mem-demo-sales", "user-sales-01", "smgr@malwa-agri.demo", "SALES_MANAGER"),
|
||||||
|
("mem-demo-accts", "user-accts-01", "accts@malwa-agri.demo", "ACCOUNTANT"),
|
||||||
|
("mem-demo-exec", "user-exec-01", "exec@malwa-agri.demo", "EXECUTIVE_VIEWER"),
|
||||||
|
]
|
||||||
|
for mem_id, user_id, email, role in demo_memberships:
|
||||||
|
if mem_id not in store.memberships:
|
||||||
|
store.memberships[mem_id] = TenantMembership(
|
||||||
|
membership_id=mem_id,
|
||||||
|
tenant_id=tenant_id,
|
||||||
|
user_id=user_id,
|
||||||
|
email=email,
|
||||||
|
role=role,
|
||||||
|
status="ACTIVE"
|
||||||
|
)
|
||||||
|
purge_metrics["tenant_active"] = 1
|
||||||
|
purge_metrics["memberships_active"] = len(demo_memberships)
|
||||||
|
|
||||||
|
return purge_metrics
|
||||||
|
|
||||||
|
|
||||||
|
def seed_demo_dataset(store: Any, tenant_id: str = DEFAULT_TENANT_ID) -> Dict[str, Any]:
|
||||||
|
"""Provisions cohesive, relational sales demo records for tenant_id."""
|
||||||
|
if not tenant_id.startswith("demo-"):
|
||||||
|
raise ValueError(f"Safety Rail: Refusing to seed non-demo tenant '{tenant_id}'")
|
||||||
|
|
||||||
|
# 1. Clean prior demo state
|
||||||
|
purge_demo_dataset(store, tenant_id)
|
||||||
|
|
||||||
|
# 2. Provision Tenant
|
||||||
|
tenant = Tenant(
|
||||||
|
tenant_id=tenant_id,
|
||||||
|
business_name=DEFAULT_BUSINESS_NAME,
|
||||||
|
legal_identifier=DEFAULT_LEGAL_ID,
|
||||||
|
primary_mandi=DEFAULT_PRIMARY_MANDI,
|
||||||
|
contact_email=DEFAULT_ADMIN_EMAIL,
|
||||||
|
status="ACTIVE"
|
||||||
|
)
|
||||||
|
store.save_tenant(tenant)
|
||||||
|
|
||||||
|
# 3. Provision RBAC Memberships for all demo personas
|
||||||
|
demo_memberships = [
|
||||||
|
("mem-demo-admin", "user-admin-01", "admin@malwa-agri.demo", "TENANT_ADMIN"),
|
||||||
|
("mem-demo-buyer", "user-buyer-01", "buyer@malwa-agri.demo", "MANDI_BUYER"),
|
||||||
|
("mem-demo-trader", "user-trader-01", "trader@malwa-agri.demo", "DESK_TRADER"),
|
||||||
|
("mem-demo-weigh", "user-weigh-01", "weighbridge@malwa-agri.demo", "WEIGHBRIDGE_OPERATOR"),
|
||||||
|
("mem-demo-qc", "user-qc-01", "qc@malwa-agri.demo", "QUALITY_ANALYST"),
|
||||||
|
("mem-demo-sales", "user-sales-01", "smgr@malwa-agri.demo", "SALES_MANAGER"),
|
||||||
|
("mem-demo-accts", "user-accts-01", "accts@malwa-agri.demo", "ACCOUNTANT"),
|
||||||
|
("mem-demo-exec", "user-exec-01", "exec@malwa-agri.demo", "EXECUTIVE_VIEWER"),
|
||||||
|
]
|
||||||
|
for mem_id, user_id, email, role in demo_memberships:
|
||||||
|
store.memberships[mem_id] = TenantMembership(
|
||||||
|
membership_id=mem_id,
|
||||||
|
tenant_id=tenant_id,
|
||||||
|
user_id=user_id,
|
||||||
|
email=email,
|
||||||
|
role=role,
|
||||||
|
status="ACTIVE"
|
||||||
|
)
|
||||||
|
|
||||||
|
# 4. Provision Master Data
|
||||||
|
commodities = [
|
||||||
|
Commodity(
|
||||||
|
tenant_id=tenant_id,
|
||||||
|
code="SOY",
|
||||||
|
name="Soyabean (Yellow)",
|
||||||
|
hsn_code="12010090",
|
||||||
|
standard_bag_weight_kg=50.0,
|
||||||
|
moisture_baseline_pct=10.0,
|
||||||
|
foreign_matter_max_pct=1.5,
|
||||||
|
damaged_grain_max_pct=2.0,
|
||||||
|
id="c0a80123-demo-0000-0000-000000000001"
|
||||||
|
),
|
||||||
|
Commodity(
|
||||||
|
tenant_id=tenant_id,
|
||||||
|
code="CHN",
|
||||||
|
name="Chana (Bengal Gram)",
|
||||||
|
hsn_code="07132000",
|
||||||
|
standard_bag_weight_kg=50.0,
|
||||||
|
moisture_baseline_pct=10.5,
|
||||||
|
foreign_matter_max_pct=1.0,
|
||||||
|
damaged_grain_max_pct=3.0,
|
||||||
|
id="c0a80123-demo-0000-0000-000000000002"
|
||||||
|
),
|
||||||
|
Commodity(
|
||||||
|
tenant_id=tenant_id,
|
||||||
|
code="WHT",
|
||||||
|
name="Wheat (Sharbati & Lokwan)",
|
||||||
|
hsn_code="10019910",
|
||||||
|
standard_bag_weight_kg=50.0,
|
||||||
|
moisture_baseline_pct=11.0,
|
||||||
|
foreign_matter_max_pct=1.0,
|
||||||
|
damaged_grain_max_pct=2.0,
|
||||||
|
id="c0a80123-demo-0000-0000-000000000003"
|
||||||
|
),
|
||||||
|
Commodity(
|
||||||
|
tenant_id=tenant_id,
|
||||||
|
code="MST",
|
||||||
|
name="Mustard (Sarson / Raida)",
|
||||||
|
hsn_code="12075010",
|
||||||
|
standard_bag_weight_kg=50.0,
|
||||||
|
moisture_baseline_pct=8.0,
|
||||||
|
foreign_matter_max_pct=1.0,
|
||||||
|
damaged_grain_max_pct=2.0,
|
||||||
|
id="c0a80123-demo-0000-0000-000000000004"
|
||||||
|
),
|
||||||
|
]
|
||||||
|
for c in commodities:
|
||||||
|
store.insert("commodities", tenant_id, c.to_dict())
|
||||||
|
|
||||||
|
varieties = [
|
||||||
|
CommodityVariety(tenant_id=tenant_id, commodity_id=commodities[0].id, code="VAR-SOY-01", name="Yellow Desi FAQ", id="var-demo-001"),
|
||||||
|
CommodityVariety(tenant_id=tenant_id, commodity_id=commodities[0].id, code="VAR-SOY-02", name="JS-335 Grade A", id="var-demo-002"),
|
||||||
|
CommodityVariety(tenant_id=tenant_id, commodity_id=commodities[1].id, code="VAR-CHN-01", name="Desi Bold FAQ", id="var-demo-003"),
|
||||||
|
CommodityVariety(tenant_id=tenant_id, commodity_id=commodities[2].id, code="VAR-WHT-01", name="Lokwan FAQ", id="var-demo-004"),
|
||||||
|
CommodityVariety(tenant_id=tenant_id, commodity_id=commodities[3].id, code="VAR-MST-01", name="42% Oil Conditioned", id="var-demo-005"),
|
||||||
|
]
|
||||||
|
for v in varieties:
|
||||||
|
store.insert("commodity_varieties", tenant_id, v.to_dict())
|
||||||
|
|
||||||
|
godowns = [
|
||||||
|
Godown(
|
||||||
|
tenant_id=tenant_id,
|
||||||
|
code="WH-IND-01",
|
||||||
|
name="Central Warehouse Indore",
|
||||||
|
capacity_mt=5000.0,
|
||||||
|
address="Sanwer Road Industrial Area, Sector C, Indore, MP",
|
||||||
|
chambers_count=4,
|
||||||
|
id="godown-demo-indore"
|
||||||
|
),
|
||||||
|
Godown(
|
||||||
|
tenant_id=tenant_id,
|
||||||
|
code="WH-NMC-01",
|
||||||
|
name="Mandi Yard Shed Neemuch",
|
||||||
|
capacity_mt=2500.0,
|
||||||
|
address="Mandi Yard Complex, Gate 2, Neemuch, MP",
|
||||||
|
chambers_count=2,
|
||||||
|
id="godown-demo-neemuch"
|
||||||
|
),
|
||||||
|
]
|
||||||
|
for g in godowns:
|
||||||
|
store.insert("godowns", tenant_id, g.to_dict())
|
||||||
|
|
||||||
|
counterparties = [
|
||||||
|
TradingCounterparty(
|
||||||
|
tenant_id=tenant_id,
|
||||||
|
name="Rameshwar Patidar (Farmer / Arhatiya)",
|
||||||
|
counterparty_type="FARMER",
|
||||||
|
pan_number="ABCDE1234F",
|
||||||
|
bank_account_number="30192837465",
|
||||||
|
bank_ifsc_code="SBIN0001234",
|
||||||
|
bank_name="State Bank of India",
|
||||||
|
phone="9826012345",
|
||||||
|
credit_terms_days=7,
|
||||||
|
id="cpty-demo-supplier-01"
|
||||||
|
),
|
||||||
|
TradingCounterparty(
|
||||||
|
tenant_id=tenant_id,
|
||||||
|
name="Kisan Agro Traders (SUP-0042)",
|
||||||
|
counterparty_type="COMMISSION_AGENT",
|
||||||
|
pan_number="AABCK9912F",
|
||||||
|
gstin="23AABCK9912F1Z4",
|
||||||
|
bank_account_number="200911223344",
|
||||||
|
bank_ifsc_code="HDFC0001234",
|
||||||
|
bank_name="HDFC Bank",
|
||||||
|
phone="9826112233",
|
||||||
|
credit_terms_days=15,
|
||||||
|
id="cpty-demo-supplier-02"
|
||||||
|
),
|
||||||
|
TradingCounterparty(
|
||||||
|
tenant_id=tenant_id,
|
||||||
|
name="Mewar Krishi Sangh",
|
||||||
|
counterparty_type="COMMISSION_AGENT",
|
||||||
|
pan_number="AABCM4411F",
|
||||||
|
gstin="08AABCM4411F1Z2",
|
||||||
|
bank_account_number="400911223355",
|
||||||
|
bank_ifsc_code="ICIC0000002",
|
||||||
|
bank_name="ICICI Bank",
|
||||||
|
phone="9829011223",
|
||||||
|
credit_terms_days=7,
|
||||||
|
id="cpty-demo-supplier-03"
|
||||||
|
),
|
||||||
|
TradingCounterparty(
|
||||||
|
tenant_id=tenant_id,
|
||||||
|
name="MP Soya Extraction Industries Ltd",
|
||||||
|
counterparty_type="PROCESSOR",
|
||||||
|
pan_number="AABCM8811F",
|
||||||
|
gstin="23AABCM8811F1Z9",
|
||||||
|
bank_account_number="501009988776",
|
||||||
|
bank_ifsc_code="ICIC0000001",
|
||||||
|
bank_name="ICICI Bank",
|
||||||
|
phone="9425011223",
|
||||||
|
credit_limit_inr=5000000.00,
|
||||||
|
credit_terms_days=15,
|
||||||
|
id="cpty-demo-customer-01"
|
||||||
|
),
|
||||||
|
TradingCounterparty(
|
||||||
|
tenant_id=tenant_id,
|
||||||
|
name="Gujarat Dal & Pulse Millers",
|
||||||
|
counterparty_type="WHOLESALE_BUYER",
|
||||||
|
pan_number="AABCG5512F",
|
||||||
|
gstin="24AABCG5512F1Z8",
|
||||||
|
bank_account_number="100988776655",
|
||||||
|
bank_ifsc_code="BARB0UNJHAX",
|
||||||
|
bank_name="Bank of Baroda",
|
||||||
|
phone="9898012345",
|
||||||
|
credit_limit_inr=4000000.00,
|
||||||
|
credit_terms_days=21,
|
||||||
|
id="cpty-demo-customer-02"
|
||||||
|
),
|
||||||
|
]
|
||||||
|
for cp in counterparties:
|
||||||
|
store.insert("counterparties", tenant_id, cp.to_dict())
|
||||||
|
|
||||||
|
fleet = [
|
||||||
|
TransportVehicle(
|
||||||
|
tenant_id=tenant_id,
|
||||||
|
reg_no="MP09BC8812",
|
||||||
|
make_model="Tata Signa 2823.K",
|
||||||
|
payload_capacity_mt=Decimal("28.000"),
|
||||||
|
ownership_type="Contract",
|
||||||
|
transporter_name="Malwa Freight Carriers",
|
||||||
|
status="Available",
|
||||||
|
fitness_expiry=(date.today() + timedelta(days=180)).isoformat(),
|
||||||
|
vehicle_id="veh-demo-01"
|
||||||
|
),
|
||||||
|
TransportVehicle(
|
||||||
|
tenant_id=tenant_id,
|
||||||
|
reg_no="MP09GH4521",
|
||||||
|
make_model="Ashok Leyland 1618",
|
||||||
|
payload_capacity_mt=Decimal("16.000"),
|
||||||
|
ownership_type="Own",
|
||||||
|
transporter_name="Malwa Fleet Internal",
|
||||||
|
status="Available",
|
||||||
|
fitness_expiry=(date.today() + timedelta(days=90)).isoformat(),
|
||||||
|
vehicle_id="veh-demo-02"
|
||||||
|
),
|
||||||
|
]
|
||||||
|
for f in fleet:
|
||||||
|
store.insert("transport_fleet", tenant_id, f.to_dict())
|
||||||
|
|
||||||
|
# 5. Operating Policies
|
||||||
|
policy = TenantOperatingPolicy(
|
||||||
|
tenant_id=tenant_id,
|
||||||
|
created_by="admin@malwa-agri.demo",
|
||||||
|
change_reason="Baseline commercial trading and credit risk policy",
|
||||||
|
effective_from=datetime.now(timezone.utc) - timedelta(days=30),
|
||||||
|
weighbridge_tolerance_pct=0.50,
|
||||||
|
moisture_deduction_threshold_pct=12.00,
|
||||||
|
credit_watch_threshold_pct=80.00,
|
||||||
|
credit_lock_threshold_pct=100.00,
|
||||||
|
qc_required_default=True,
|
||||||
|
partner_dispatch_override_ceiling_inr=5000000.00,
|
||||||
|
id="pol-demo-01"
|
||||||
|
)
|
||||||
|
store.insert("tenant_operating_policies", tenant_id, policy.to_dict())
|
||||||
|
|
||||||
|
# 6. Daily Mandi Observations (Indore APMC, MP-IND-01 for Today)
|
||||||
|
today = date.today()
|
||||||
|
observations = [
|
||||||
|
MarketObservation(
|
||||||
|
tenant_id=tenant_id,
|
||||||
|
mandi_id="MP-IND-01",
|
||||||
|
observation_date=today,
|
||||||
|
commodity_id="SOY",
|
||||||
|
variety="Yellow Desi",
|
||||||
|
grade="FAQ",
|
||||||
|
arrival_mt=Decimal("620.000"),
|
||||||
|
min_rate=Decimal("4550.00"),
|
||||||
|
max_rate=Decimal("4900.00"),
|
||||||
|
modal_rate=Decimal("4800.00"),
|
||||||
|
source="APMC_BULLETIN",
|
||||||
|
is_market_closed=False,
|
||||||
|
observation_id="mkt-demo-obs-01"
|
||||||
|
),
|
||||||
|
MarketObservation(
|
||||||
|
tenant_id=tenant_id,
|
||||||
|
mandi_id="MP-IND-01",
|
||||||
|
observation_date=today,
|
||||||
|
commodity_id="CHN",
|
||||||
|
variety="Desi Bold",
|
||||||
|
grade="FAQ",
|
||||||
|
arrival_mt=Decimal("280.000"),
|
||||||
|
min_rate=Decimal("5800.00"),
|
||||||
|
max_rate=Decimal("6150.00"),
|
||||||
|
modal_rate=Decimal("6000.00"),
|
||||||
|
source="APMC_BULLETIN",
|
||||||
|
is_market_closed=False,
|
||||||
|
observation_id="mkt-demo-obs-02"
|
||||||
|
),
|
||||||
|
MarketObservation(
|
||||||
|
tenant_id=tenant_id,
|
||||||
|
mandi_id="MP-IND-01",
|
||||||
|
observation_date=today,
|
||||||
|
commodity_id="WHT",
|
||||||
|
variety="Lokwan",
|
||||||
|
grade="FAQ",
|
||||||
|
arrival_mt=Decimal("450.000"),
|
||||||
|
min_rate=Decimal("2350.00"),
|
||||||
|
max_rate=Decimal("2550.00"),
|
||||||
|
modal_rate=Decimal("2450.00"),
|
||||||
|
source="APMC_BULLETIN",
|
||||||
|
is_market_closed=False,
|
||||||
|
observation_id="mkt-demo-obs-03"
|
||||||
|
),
|
||||||
|
MarketObservation(
|
||||||
|
tenant_id=tenant_id,
|
||||||
|
mandi_id="MP-IND-01",
|
||||||
|
observation_date=today,
|
||||||
|
commodity_id="MST",
|
||||||
|
variety="42% Oil",
|
||||||
|
grade="FAQ",
|
||||||
|
arrival_mt=Decimal("190.000"),
|
||||||
|
min_rate=Decimal("5200.00"),
|
||||||
|
max_rate=Decimal("5550.00"),
|
||||||
|
modal_rate=Decimal("5400.00"),
|
||||||
|
source="APMC_BULLETIN",
|
||||||
|
is_market_closed=False,
|
||||||
|
observation_id="mkt-demo-obs-04"
|
||||||
|
),
|
||||||
|
]
|
||||||
|
for obs in observations:
|
||||||
|
store.insert("market_observations", tenant_id, obs.to_dict())
|
||||||
|
|
||||||
|
# 7. Procurement Saudas
|
||||||
|
saudas = [
|
||||||
|
ProcurementSauda(
|
||||||
|
tenant_id=tenant_id,
|
||||||
|
sauda_number="SDA-2026-001",
|
||||||
|
contract_date=today,
|
||||||
|
delivery_due_date=today + timedelta(days=7),
|
||||||
|
supplier_id="cpty-demo-supplier-01",
|
||||||
|
mandi_id="MP-IND-01",
|
||||||
|
commodity_id="SOY",
|
||||||
|
variety="Yellow FAQ",
|
||||||
|
booked_quantity_mt=Decimal("25.000"),
|
||||||
|
trade_rate_per_qtl=Decimal("4850.00"),
|
||||||
|
grade="FAQ",
|
||||||
|
trade_type="MANDI_AUCTION",
|
||||||
|
estimated_bags=500,
|
||||||
|
credit_period_days=7,
|
||||||
|
advance_amount=Decimal("0.00"),
|
||||||
|
mandi_cess_pct=Decimal("1.50"),
|
||||||
|
krishi_kalyan_pct=Decimal("0.50"),
|
||||||
|
brokerage_rate_pct=Decimal("1.00"),
|
||||||
|
sauda_id="sda-demo-001"
|
||||||
|
),
|
||||||
|
ProcurementSauda(
|
||||||
|
tenant_id=tenant_id,
|
||||||
|
sauda_number="SDA-26-00142",
|
||||||
|
contract_date=today - timedelta(days=1),
|
||||||
|
delivery_due_date=today + timedelta(days=6),
|
||||||
|
supplier_id="cpty-demo-supplier-02",
|
||||||
|
mandi_id="RJ-KOT-01",
|
||||||
|
commodity_id="SOY",
|
||||||
|
variety="Yellow Desi",
|
||||||
|
booked_quantity_mt=Decimal("50.000"),
|
||||||
|
trade_rate_per_qtl=Decimal("4750.00"),
|
||||||
|
grade="FAQ",
|
||||||
|
trade_type="DIRECT_PURCHASE",
|
||||||
|
estimated_bags=1000,
|
||||||
|
credit_period_days=15,
|
||||||
|
advance_amount=Decimal("0.00"),
|
||||||
|
mandi_cess_pct=Decimal("1.50"),
|
||||||
|
krishi_kalyan_pct=Decimal("0.50"),
|
||||||
|
brokerage_rate_pct=Decimal("1.00"),
|
||||||
|
sauda_id="sda-demo-002"
|
||||||
|
),
|
||||||
|
ProcurementSauda(
|
||||||
|
tenant_id=tenant_id,
|
||||||
|
sauda_number="SDA-26-00143",
|
||||||
|
contract_date=today - timedelta(days=2),
|
||||||
|
delivery_due_date=today + timedelta(days=4),
|
||||||
|
supplier_id="cpty-demo-supplier-03",
|
||||||
|
mandi_id="GJ-UNJ-01",
|
||||||
|
commodity_id="CHN",
|
||||||
|
variety="Desi Bold",
|
||||||
|
booked_quantity_mt=Decimal("20.000"),
|
||||||
|
trade_rate_per_qtl=Decimal("6000.00"),
|
||||||
|
grade="FAQ",
|
||||||
|
trade_type="MANDI_AUCTION",
|
||||||
|
estimated_bags=400,
|
||||||
|
credit_period_days=7,
|
||||||
|
advance_amount=Decimal("0.00"),
|
||||||
|
mandi_cess_pct=Decimal("1.50"),
|
||||||
|
krishi_kalyan_pct=Decimal("0.50"),
|
||||||
|
brokerage_rate_pct=Decimal("1.00"),
|
||||||
|
sauda_id="sda-demo-003"
|
||||||
|
),
|
||||||
|
ProcurementSauda(
|
||||||
|
tenant_id=tenant_id,
|
||||||
|
sauda_number="SDA-26-00144",
|
||||||
|
contract_date=today - timedelta(days=4),
|
||||||
|
delivery_due_date=today + timedelta(days=2),
|
||||||
|
supplier_id="cpty-demo-supplier-01",
|
||||||
|
mandi_id="MP-IND-01",
|
||||||
|
commodity_id="WHT",
|
||||||
|
variety="Lokwan",
|
||||||
|
booked_quantity_mt=Decimal("100.000"),
|
||||||
|
trade_rate_per_qtl=Decimal("2420.00"),
|
||||||
|
grade="FAQ",
|
||||||
|
trade_type="MANDI_AUCTION",
|
||||||
|
estimated_bags=2000,
|
||||||
|
credit_period_days=10,
|
||||||
|
advance_amount=Decimal("0.00"),
|
||||||
|
mandi_cess_pct=Decimal("1.50"),
|
||||||
|
krishi_kalyan_pct=Decimal("0.50"),
|
||||||
|
brokerage_rate_pct=Decimal("1.00"),
|
||||||
|
sauda_id="sda-demo-004"
|
||||||
|
),
|
||||||
|
]
|
||||||
|
# Update receipt progression
|
||||||
|
saudas[1].record_receipt(Decimal("30.000")) # 60% fulfilled
|
||||||
|
saudas[3].record_receipt(Decimal("100.000")) # 100% fulfilled
|
||||||
|
saudas[3].status = "CLOSED"
|
||||||
|
|
||||||
|
for s in saudas:
|
||||||
|
store.insert("procurement_sauda", tenant_id, s.to_dict())
|
||||||
|
|
||||||
|
# 8. Connected Storyboard Transactions (GP -> WB -> GRN -> QC -> SO -> Bilty)
|
||||||
|
sauda_main = saudas[0]
|
||||||
|
|
||||||
|
gate_entry = InwardGateEntry(
|
||||||
|
tenant_id=tenant_id,
|
||||||
|
gate_pass_number="GP-2026-001",
|
||||||
|
vehicle_number="MP09GH4521",
|
||||||
|
eway_bill_number="281098765432",
|
||||||
|
driver_name="Sunil Yadav",
|
||||||
|
driver_mobile="9826012345",
|
||||||
|
sauda_id=sauda_main.id,
|
||||||
|
supplier_invoice_no="INV-RAM-2026-90",
|
||||||
|
supplier_dispatch_weight_mt=Decimal("25.000"),
|
||||||
|
supplier_dispatch_bags=500,
|
||||||
|
entry_id="gate-entry-demo-001"
|
||||||
|
)
|
||||||
|
gate_entry.transition_status("WEIGHED_TARE")
|
||||||
|
store.insert("inward_gate_entries", tenant_id, gate_entry.to_dict())
|
||||||
|
|
||||||
|
wb_slip = WeighbridgeSlip(
|
||||||
|
tenant_id=tenant_id,
|
||||||
|
slip_number="WB-IND-2026-001",
|
||||||
|
gate_pass_id=gate_entry.id,
|
||||||
|
gross_weight_mt=Decimal("35.000"),
|
||||||
|
slip_id="weigh-slip-demo-001"
|
||||||
|
)
|
||||||
|
wb_slip.record_tare(
|
||||||
|
tare_weight_mt=Decimal("10.000"),
|
||||||
|
bag_packaging_type="Jute 50kg",
|
||||||
|
actual_bag_count=500,
|
||||||
|
billed_weight_mt=Decimal("25.000")
|
||||||
|
)
|
||||||
|
store.insert("weighbridge_slips", tenant_id, wb_slip.to_dict())
|
||||||
|
|
||||||
|
grn = GoodsReceiptNote(
|
||||||
|
tenant_id=tenant_id,
|
||||||
|
grn_number="GRN-2026-001",
|
||||||
|
weighment_slip_id=wb_slip.id,
|
||||||
|
sauda_id=sauda_main.id,
|
||||||
|
godown_id="godown-demo-indore",
|
||||||
|
godown_stack_id="Stack A1",
|
||||||
|
accepted_quantity_mt=Decimal("24.625"),
|
||||||
|
accepted_bags=500,
|
||||||
|
grn_id="grn-demo-001"
|
||||||
|
)
|
||||||
|
store.insert("goods_receipt_notes", tenant_id, grn.to_dict())
|
||||||
|
|
||||||
|
lot = InventoryLot(
|
||||||
|
tenant_id=tenant_id,
|
||||||
|
lot_number="LOT-SOY-2026-001",
|
||||||
|
grn_id=grn.id,
|
||||||
|
commodity_id="c0a80123-demo-0000-0000-000000000001",
|
||||||
|
variety="Yellow FAQ",
|
||||||
|
godown_stack_id="Stack A1",
|
||||||
|
initial_quantity_mt=Decimal("24.625"),
|
||||||
|
grade="FAQ",
|
||||||
|
lot_id="lot-demo-001"
|
||||||
|
)
|
||||||
|
lot.transition_qc_status("RELEASED")
|
||||||
|
lot.current_quantity_mt = Decimal("0.625")
|
||||||
|
store.insert("inventory_lots", tenant_id, lot.to_dict())
|
||||||
|
|
||||||
|
qc_inspection = QualityInspection(
|
||||||
|
tenant_id=tenant_id,
|
||||||
|
lot_id=lot.id,
|
||||||
|
sample_code="SMP-2026-001",
|
||||||
|
inspector_email="qc@malwa-agri.demo",
|
||||||
|
lot_quantity_mt=Decimal("25.000"),
|
||||||
|
trade_rate_per_qtl=Decimal("4850.00"),
|
||||||
|
moisture_pct=Decimal("11.50"),
|
||||||
|
foreign_matter_pct=Decimal("2.20"),
|
||||||
|
decision="RELEASED",
|
||||||
|
damaged_grain_pct=Decimal("1.80"),
|
||||||
|
remarks="Approved with FAQ standard moisture deduction",
|
||||||
|
inspection_id="qc-demo-001"
|
||||||
|
)
|
||||||
|
store.insert("quality_inspections", tenant_id, qc_inspection.to_dict())
|
||||||
|
|
||||||
|
sales_order = CustomerSalesOrder(
|
||||||
|
tenant_id=tenant_id,
|
||||||
|
sales_order_number="SO-2026-089",
|
||||||
|
customer_id="cpty-demo-customer-01",
|
||||||
|
destination_city="Pithampur",
|
||||||
|
customer_segment="Processor",
|
||||||
|
commodity_id="c0a80123-demo-0000-0000-000000000001",
|
||||||
|
variety="Yellow FAQ",
|
||||||
|
contract_qty_mt=Decimal("24.000"),
|
||||||
|
contract_rate_per_qtl=Decimal("5100.00"),
|
||||||
|
payment_terms="15 Days",
|
||||||
|
credit_exposure_ratio=Decimal("107.50"),
|
||||||
|
credit_override=True,
|
||||||
|
override_approved_by="smgr@malwa-agri.demo",
|
||||||
|
grade="FAQ",
|
||||||
|
order_id="so-demo-001"
|
||||||
|
)
|
||||||
|
sales_order.allocated_qty_mt = Decimal("24.000")
|
||||||
|
sales_order.status = "FULLY_ALLOCATED"
|
||||||
|
store.insert("customer_sales_orders", tenant_id, sales_order.to_dict())
|
||||||
|
|
||||||
|
allocation = SalesOrderAllocation(
|
||||||
|
tenant_id=tenant_id,
|
||||||
|
sales_order_id=sales_order.id,
|
||||||
|
lot_id=lot.id,
|
||||||
|
warehouse_id="godown-demo-indore",
|
||||||
|
allocated_qty_mt=Decimal("24.000"),
|
||||||
|
allocated_bags=480,
|
||||||
|
lot_qc_status="RELEASED",
|
||||||
|
available_unreserved_mt=Decimal("24.625"),
|
||||||
|
allocation_id="alloc-demo-001"
|
||||||
|
)
|
||||||
|
store.insert("sales_order_allocations", tenant_id, allocation.to_dict())
|
||||||
|
|
||||||
|
dispatch = OutboundDispatch(
|
||||||
|
tenant_id=tenant_id,
|
||||||
|
dispatch_number="DSP-2026-089",
|
||||||
|
sales_order_id=sales_order.id,
|
||||||
|
allocation_id=allocation.id,
|
||||||
|
vehicle_id="veh-demo-01",
|
||||||
|
origin_warehouse_id="godown-demo-indore",
|
||||||
|
destination_city="Pithampur",
|
||||||
|
dispatch_id="dispatch-demo-001"
|
||||||
|
)
|
||||||
|
dispatch.transition_status("IN_TRANSIT")
|
||||||
|
store.insert("outbound_dispatches", tenant_id, dispatch.to_dict())
|
||||||
|
|
||||||
|
outward_wt = OutwardWeighment(
|
||||||
|
tenant_id=tenant_id,
|
||||||
|
dispatch_id=dispatch.id,
|
||||||
|
tare_weight_kg=Decimal("10200.00"),
|
||||||
|
gross_weight_kg=Decimal("34200.00"),
|
||||||
|
allocated_mt=Decimal("24.000"),
|
||||||
|
loaded_bags=480,
|
||||||
|
transporter_bilty_no="BLT-2026-089",
|
||||||
|
eway_bill_no="381044991122",
|
||||||
|
weighment_id="outward-weigh-demo-001"
|
||||||
|
)
|
||||||
|
store.insert("outward_weighments", tenant_id, outward_wt.to_dict())
|
||||||
|
|
||||||
|
bilty = DispatchBilty(
|
||||||
|
tenant_id=tenant_id,
|
||||||
|
dispatch_id=dispatch.id,
|
||||||
|
bilty_number="BLT-2026-089",
|
||||||
|
consignor_name="Malwa Agri Trading Corp Pvt Ltd",
|
||||||
|
consignee_name="MP Soya Extraction Industries Ltd",
|
||||||
|
vehicle_reg_no="MP09BC8812",
|
||||||
|
net_weight_mt=Decimal("24.000"),
|
||||||
|
bags=480,
|
||||||
|
eway_bill_no="381044991122",
|
||||||
|
bilty_id="bilty-demo-001"
|
||||||
|
)
|
||||||
|
store.insert("dispatch_bilties", tenant_id, bilty.to_dict())
|
||||||
|
|
||||||
|
# 9. Subledgers, Payables, Cess Voucher
|
||||||
|
customer_invoice = PartySubLedgerEntry(
|
||||||
|
tenant_id=tenant_id,
|
||||||
|
party_id="cpty-demo-customer-01",
|
||||||
|
party_type="CUSTOMER",
|
||||||
|
voucher_type="SALES_INVOICE",
|
||||||
|
voucher_number="INV-SALES-2026-089",
|
||||||
|
debit_amount_inr=Decimal("1224000.00"),
|
||||||
|
running_balance_inr=Decimal("5374000.00"),
|
||||||
|
narration="Sales invoice for 24.000 MT Soybean FAQ under Order SO-2026-089 / Bilty BLT-2026-089",
|
||||||
|
entry_id="subledger-demo-01"
|
||||||
|
)
|
||||||
|
store.insert("party_subledger_entries", tenant_id, customer_invoice.to_dict())
|
||||||
|
|
||||||
|
supplier_payable = SupplierPayable(
|
||||||
|
tenant_id=tenant_id,
|
||||||
|
supplier_id="cpty-demo-supplier-01",
|
||||||
|
grn_number="GRN-2026-001",
|
||||||
|
invoice_amount_inr=Decimal("1189141.25"),
|
||||||
|
grn_date=datetime.now(timezone.utc),
|
||||||
|
credit_days=7,
|
||||||
|
sauda_reference="SDA-2026-001",
|
||||||
|
payable_id="payable-demo-001"
|
||||||
|
)
|
||||||
|
store.insert("supplier_payables", tenant_id, supplier_payable.to_dict())
|
||||||
|
|
||||||
|
cess_voucher = MandiExpenseVoucher(
|
||||||
|
tenant_id=tenant_id,
|
||||||
|
voucher_number="VCH-CESS-2026-001",
|
||||||
|
expense_category="MANDI_CESS",
|
||||||
|
amount_inr=Decimal("18187.50"),
|
||||||
|
payee_name="Indore Mandi Samiti",
|
||||||
|
payment_mode="BANK_TRANSFER",
|
||||||
|
debit_account="Mandi Cess Expense",
|
||||||
|
credit_account="HDFC Bank Current A/C",
|
||||||
|
linked_sauda_id=sauda_main.id,
|
||||||
|
narration="1.50% MP Mandi Cess on Sauda SDA-2026-001 gross value ₹12,12,500.00",
|
||||||
|
voucher_id="voucher-demo-001"
|
||||||
|
)
|
||||||
|
store.insert("mandi_expense_vouchers", tenant_id, cess_voucher.to_dict())
|
||||||
|
|
||||||
|
# 10. Operational Hazard Alerts
|
||||||
|
alerts = [
|
||||||
|
OperationalAlert(
|
||||||
|
tenant_id=tenant_id,
|
||||||
|
category="CREDIT_RISK",
|
||||||
|
severity="WARNING",
|
||||||
|
title="Customer Credit Limit Breached: MP Soya",
|
||||||
|
message="MP Soya Extraction Industries exposure is at 107.5% of approved limit (₹53.74L / ₹50.00L).",
|
||||||
|
source_entity_type="SALES_ORDER",
|
||||||
|
source_entity_id=sales_order.id,
|
||||||
|
alert_id="alert-demo-01"
|
||||||
|
),
|
||||||
|
OperationalAlert(
|
||||||
|
tenant_id=tenant_id,
|
||||||
|
category="WAREHOUSE_CAPACITY",
|
||||||
|
severity="INFO",
|
||||||
|
title="Indore Godown Capacity at 63%",
|
||||||
|
message="Central Warehouse Indore is currently holding 3,150 MT out of 5,000 MT capacity.",
|
||||||
|
source_entity_type="GODOWN",
|
||||||
|
source_entity_id="godown-demo-indore",
|
||||||
|
alert_id="alert-demo-02"
|
||||||
|
),
|
||||||
|
]
|
||||||
|
for a in alerts:
|
||||||
|
store.insert("operational_alerts", tenant_id, a.to_dict())
|
||||||
|
|
||||||
|
# 11. 20-Day Historical Snapshots for Analytics & Dashboard
|
||||||
|
for day_offset in range(19, -1, -1):
|
||||||
|
snap_date = today - timedelta(days=day_offset)
|
||||||
|
# Weekends closed
|
||||||
|
if snap_date.weekday() >= 5:
|
||||||
|
continue
|
||||||
|
|
||||||
|
snapshot = DailyTradingSnapshot(
|
||||||
|
tenant_id=tenant_id,
|
||||||
|
snapshot_date=str(snap_date),
|
||||||
|
purchases_mt=Decimal("25.00") if day_offset == 0 else Decimal("0.00"),
|
||||||
|
sales_mt=Decimal("24.00") if day_offset == 0 else Decimal("0.00"),
|
||||||
|
closing_stock_mt=Decimal("625.50") + Decimal(str(day_offset * 15)),
|
||||||
|
total_receivables_inr=Decimal("5374000.00"),
|
||||||
|
total_payables_inr=Decimal("1189141.25"),
|
||||||
|
snapshot_id=f"snap-demo-{day_offset}"
|
||||||
|
)
|
||||||
|
store.insert("daily_trading_snapshots", tenant_id, snapshot.to_dict())
|
||||||
|
|
||||||
|
summary = {
|
||||||
|
"tenant_id": tenant_id,
|
||||||
|
"commodities": len(commodities),
|
||||||
|
"varieties": len(varieties),
|
||||||
|
"godowns": len(godowns),
|
||||||
|
"counterparties": len(counterparties),
|
||||||
|
"fleet": len(fleet),
|
||||||
|
"policies": 1,
|
||||||
|
"market_observations": len(observations),
|
||||||
|
"procurement_sauda": len(saudas),
|
||||||
|
"gate_entries": 1,
|
||||||
|
"weighbridge_slips": 1,
|
||||||
|
"goods_receipt_notes": 1,
|
||||||
|
"inventory_lots": 1,
|
||||||
|
"quality_inspections": 1,
|
||||||
|
"sales_orders": 1,
|
||||||
|
"dispatches": 1,
|
||||||
|
"bilties": 1,
|
||||||
|
"subledger_entries": 1,
|
||||||
|
"payables": 1,
|
||||||
|
"cess_vouchers": 1,
|
||||||
|
"alerts": len(alerts),
|
||||||
|
}
|
||||||
|
logger.info("Demo dataset seeded successfully for tenant '%s': %s", tenant_id, summary)
|
||||||
|
return summary
|
||||||
|
|
@ -42,6 +42,40 @@ class InMemoryTenantStorage:
|
||||||
self._collections: Dict[str, Dict[str, Dict[str, Any]]] = {}
|
self._collections: Dict[str, Dict[str, Dict[str, Any]]] = {}
|
||||||
self.active_tenant_id: Optional[str] = None
|
self.active_tenant_id: Optional[str] = None
|
||||||
self._pool_connection_id: str = "conn_pool_01"
|
self._pool_connection_id: str = "conn_pool_01"
|
||||||
|
self._seed_fixtures()
|
||||||
|
|
||||||
|
def _seed_fixtures(self) -> None:
|
||||||
|
"""Seeds baseline fixtures so mock auth and tenants work out of the box."""
|
||||||
|
try:
|
||||||
|
from sandbox.identity_mock import TEST_TENANTS, TEST_MEMBERSHIPS
|
||||||
|
for t_id, data in TEST_TENANTS.items():
|
||||||
|
self.tenants[t_id] = Tenant(
|
||||||
|
tenant_id=t_id,
|
||||||
|
business_name=data["business_name"],
|
||||||
|
legal_identifier=data.get("legal_identifier", f"GSTIN_{t_id}"),
|
||||||
|
contact_email=data.get("contact_email", f"admin@{t_id}.com"),
|
||||||
|
primary_mandi=data.get("primary_mandi", "APMC-PUN-01"),
|
||||||
|
status=data.get("status", "ACTIVE"),
|
||||||
|
created_at=data.get("created_at")
|
||||||
|
)
|
||||||
|
for m in TEST_MEMBERSHIPS:
|
||||||
|
mem_id = m["membership_id"]
|
||||||
|
self.memberships[mem_id] = TenantMembership(
|
||||||
|
membership_id=mem_id,
|
||||||
|
tenant_id=m["tenant_id"],
|
||||||
|
user_id=m["user_id"],
|
||||||
|
email=m["email"],
|
||||||
|
role=m["role"],
|
||||||
|
status=m.get("status", "ACTIVE")
|
||||||
|
)
|
||||||
|
except Exception as exc:
|
||||||
|
logger.warning("Could not auto-seed baseline fixtures: %s", exc)
|
||||||
|
|
||||||
|
try:
|
||||||
|
from backend.app.db.demo_seed import seed_demo_dataset
|
||||||
|
seed_demo_dataset(self, "demo-malwa-agri")
|
||||||
|
except Exception as exc:
|
||||||
|
logger.warning("Could not auto-seed demo dataset: %s", exc)
|
||||||
|
|
||||||
def set_tenant_context(self, tenant_id: Optional[str]) -> None:
|
def set_tenant_context(self, tenant_id: Optional[str]) -> None:
|
||||||
"""Sets transaction-local tenant isolation context (SET LOCAL app.current_tenant_id)."""
|
"""Sets transaction-local tenant isolation context (SET LOCAL app.current_tenant_id)."""
|
||||||
|
|
|
||||||
|
|
@ -1017,9 +1017,33 @@ try:
|
||||||
status_code = result.pop("status_code", 200)
|
status_code = result.pop("status_code", 200)
|
||||||
return JSONResponse(status_code=status_code, content=result)
|
return JSONResponse(status_code=status_code, content=result)
|
||||||
|
|
||||||
|
# =========================================================================
|
||||||
|
# Sales Demo Engine Endpoints (Commercial Seeding & Side-Effect Free Purge)
|
||||||
|
# =========================================================================
|
||||||
|
|
||||||
|
@app.post("/api/v1/demo/seed", tags=["Sales Demo"])
|
||||||
|
async def seed_sales_demo_data(payload: Optional[Dict[str, Any]] = None):
|
||||||
|
"""POST /api/v1/demo/seed - Seeds complete relational dataset for demo-malwa-agri."""
|
||||||
|
from backend.app.db.session import storage
|
||||||
|
from backend.app.db.demo_seed import seed_demo_dataset
|
||||||
|
tenant_id = (payload or {}).get("tenant_id", "demo-malwa-agri")
|
||||||
|
try:
|
||||||
|
summary = seed_demo_dataset(storage, tenant_id=tenant_id)
|
||||||
|
return JSONResponse(status_code=200, content={"success": True, "message": "Demo data seeded successfully", "summary": summary})
|
||||||
|
except Exception as e:
|
||||||
|
return JSONResponse(status_code=500, content={"success": False, "error": str(e)})
|
||||||
|
|
||||||
|
@app.post("/api/v1/demo/cleanup", tags=["Sales Demo"])
|
||||||
|
async def cleanup_sales_demo_data(payload: Optional[Dict[str, Any]] = None):
|
||||||
|
"""POST /api/v1/demo/cleanup - Purges demo dataset with zero residue."""
|
||||||
|
from backend.app.db.session import storage
|
||||||
|
from backend.app.db.demo_seed import purge_demo_dataset
|
||||||
|
tenant_id = (payload or {}).get("tenant_id", "demo-malwa-agri")
|
||||||
|
try:
|
||||||
|
metrics = purge_demo_dataset(storage, tenant_id=tenant_id)
|
||||||
|
return JSONResponse(status_code=200, content={"success": True, "message": "Demo data purged successfully with zero residue", "metrics": metrics})
|
||||||
|
except Exception as e:
|
||||||
|
return JSONResponse(status_code=500, content={"success": False, "error": str(e)})
|
||||||
|
|
||||||
|
|
||||||
except ImportError:
|
except ImportError:
|
||||||
|
|
|
||||||
44
compose.yaml
44
compose.yaml
|
|
@ -58,5 +58,49 @@ services:
|
||||||
timeout: 3s
|
timeout: 3s
|
||||||
retries: 10
|
retries: 10
|
||||||
|
|
||||||
|
backend:
|
||||||
|
build:
|
||||||
|
context: .
|
||||||
|
dockerfile: docker/Dockerfile.backend
|
||||||
|
environment:
|
||||||
|
DATABASE_URL: postgresql://${POSTGRES_USER:-atb}:${POSTGRES_PASSWORD:?Set POSTGRES_PASSWORD in .env; see .env.example}@postgres:5432/${POSTGRES_DB:-atb}
|
||||||
|
VALKEY_URL: valkey://valkey:6379/0
|
||||||
|
KEYCLOAK_ISSUER: ${KEYCLOAK_ISSUER:-http://keycloak:8080/auth/realms/atb}
|
||||||
|
KEYCLOAK_CLIENT_ID: ${KEYCLOAK_CLIENT_ID:-atb-portal}
|
||||||
|
KEYCLOAK_CLIENT_SECRET: ${KEYCLOAK_CLIENT_SECRET:-}
|
||||||
|
USE_IDENTITY_MOCK: ${USE_IDENTITY_MOCK:-True}
|
||||||
|
ENVIRONMENT: ${ENVIRONMENT:-development}
|
||||||
|
LOG_LEVEL: ${LOG_LEVEL:-INFO}
|
||||||
|
ports:
|
||||||
|
- "127.0.0.1:8000:8000"
|
||||||
|
depends_on:
|
||||||
|
postgres:
|
||||||
|
condition: service_healthy
|
||||||
|
valkey:
|
||||||
|
condition: service_healthy
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD-SHELL", "curl -f http://127.0.0.1:8000/health || exit 1"]
|
||||||
|
interval: 10s
|
||||||
|
timeout: 5s
|
||||||
|
retries: 5
|
||||||
|
start_period: 15s
|
||||||
|
|
||||||
|
frontend:
|
||||||
|
build:
|
||||||
|
context: .
|
||||||
|
dockerfile: docker/Dockerfile.frontend
|
||||||
|
ports:
|
||||||
|
- "${PORTAL_PORT:-3000}:80"
|
||||||
|
depends_on:
|
||||||
|
backend:
|
||||||
|
condition: service_healthy
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD-SHELL", "wget --quiet --tries=1 --spider http://127.0.0.1/healthz || exit 1"]
|
||||||
|
interval: 10s
|
||||||
|
timeout: 5s
|
||||||
|
retries: 5
|
||||||
|
start_period: 5s
|
||||||
|
|
||||||
volumes:
|
volumes:
|
||||||
postgres_data:
|
postgres_data:
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -14,7 +14,7 @@ COPY frontend/package.json ./
|
||||||
RUN npm install
|
RUN npm install
|
||||||
|
|
||||||
COPY frontend/ ./
|
COPY frontend/ ./
|
||||||
RUN npm run build || (mkdir -p dist && cp index.html dist/index.html)
|
RUN npm run build
|
||||||
|
|
||||||
# ---- Stage 2: Hardened Nginx Runtime ----
|
# ---- Stage 2: Hardened Nginx Runtime ----
|
||||||
FROM nginx:1.27-alpine AS runtime
|
FROM nginx:1.27-alpine AS runtime
|
||||||
|
|
|
||||||
|
|
@ -28,6 +28,8 @@ The services publish ports on loopback only:
|
||||||
| PostgreSQL | `127.0.0.1:5432` | `atb` database and user from `.env` |
|
| PostgreSQL | `127.0.0.1:5432` | `atb` database and user from `.env` |
|
||||||
| Keycloak | <http://localhost:8080> | Local identity server; admin credentials from `.env` |
|
| Keycloak | <http://localhost:8080> | Local identity server; admin credentials from `.env` |
|
||||||
| Valkey | `127.0.0.1:6379` | Local cache/stream dependency |
|
| Valkey | `127.0.0.1:6379` | Local cache/stream dependency |
|
||||||
|
| Backend | `127.0.0.1:8000` | FastAPI application API (Swagger docs at `/docs`) |
|
||||||
|
| Frontend | `http://localhost:3000` | Hardened Nginx reverse proxy & React SPA portal |
|
||||||
|
|
||||||
PostgreSQL also creates a separate `keycloak` database and login for Keycloak. Both databases share one local PostgreSQL container; this is a workstation convenience, not a production isolation recommendation. PostgreSQL data survives `docker compose down` in the named `postgres_data` volume. Valkey is intentionally ephemeral because the durable outbox belongs in PostgreSQL.
|
PostgreSQL also creates a separate `keycloak` database and login for Keycloak. Both databases share one local PostgreSQL container; this is a workstation convenience, not a production isolation recommendation. PostgreSQL data survives `docker compose down` in the named `postgres_data` volume. Valkey is intentionally ephemeral because the durable outbox belongs in PostgreSQL.
|
||||||
|
|
||||||
|
|
@ -48,6 +50,6 @@ To erase the local PostgreSQL data as well, add `--volumes` to the `down` comman
|
||||||
|
|
||||||
The example uses the [PostgreSQL Docker Official Image](https://hub.docker.com/_/postgres), [Keycloak's official container image](https://www.keycloak.org/server/containers) from `quay.io/keycloak/keycloak`, and the [Valkey project's image](https://hub.docker.com/r/valkey/valkey). Release tags are pinned in `project_code/.env.example`; they are not immutable digest pins, and this repository has not configured image signature verification or a vendor certification policy. Review and update the selected tags through normal dependency maintenance.
|
The example uses the [PostgreSQL Docker Official Image](https://hub.docker.com/_/postgres), [Keycloak's official container image](https://www.keycloak.org/server/containers) from `quay.io/keycloak/keycloak`, and the [Valkey project's image](https://hub.docker.com/r/valkey/valkey). Release tags are pinned in `project_code/.env.example`; they are not immutable digest pins, and this repository has not configured image signature verification or a vendor certification policy. Review and update the selected tags through normal dependency maintenance.
|
||||||
|
|
||||||
The current repository has no application API, worker, frontend, migration, or test-runner source to build. Those services should be added to this Compose project as their implementation and test artifacts are authored; this file does not use placeholder build contexts. Mail capture, object-storage emulation, reverse proxy, and observability services are also omitted until their iteration needs and providers are selected.
|
The Compose project includes the core FastAPI backend API and hardened React SPA frontend services authored during Construction iterations, building directly from `docker/Dockerfile.backend` and `docker/Dockerfile.frontend`. Mail capture, object-storage emulation, and external observability services remain optional overlays until their iteration needs and providers are selected.
|
||||||
|
|
||||||
This Compose configuration does not select a production runtime, change the approved production availability/recovery requirements, or demonstrate production readiness. Production hosting and its evidence gates remain open in the deployment design.
|
This Compose configuration does not select a production runtime, change the approved production availability/recovery requirements, or demonstrate production readiness. Production hosting and its evidence gates remain open in the deployment design.
|
||||||
|
|
|
||||||
File diff suppressed because it is too large
Load Diff
|
|
@ -3,19 +3,125 @@ import { authStore } from './stores/authStore';
|
||||||
import { tenantStore } from './stores/tenantStore';
|
import { tenantStore } from './stores/tenantStore';
|
||||||
import { LoginView } from './features/auth/LoginView';
|
import { LoginView } from './features/auth/LoginView';
|
||||||
import { SessionView } from './features/auth/SessionView';
|
import { SessionView } from './features/auth/SessionView';
|
||||||
|
import { AccessDeniedView } from './features/auth/AccessDeniedView';
|
||||||
import { HeaderTenantSwitcher } from './features/tenant/HeaderTenantSwitcher';
|
import { HeaderTenantSwitcher } from './features/tenant/HeaderTenantSwitcher';
|
||||||
import { PlatformTenantsView } from './features/tenant/PlatformTenantsView';
|
import { PlatformTenantsView } from './features/tenant/PlatformTenantsView';
|
||||||
import { TenantMembersView } from './features/tenant/TenantMembersView';
|
import { TenantMembersView } from './features/tenant/TenantMembersView';
|
||||||
import { AuditLogView } from './features/tenant/AuditLogView';
|
import { AuditLogView } from './features/tenant/AuditLogView';
|
||||||
import { Shield, Building2, Users, FileText, LogOut, Layers } from 'lucide-react';
|
import { MarketDeskView } from './features/market/MarketDeskView';
|
||||||
|
import { SaudaProcurementView } from './features/procurement/SaudaProcurementView';
|
||||||
|
import {
|
||||||
|
Shield,
|
||||||
|
Building2,
|
||||||
|
Users,
|
||||||
|
FileText,
|
||||||
|
LogOut,
|
||||||
|
Layers,
|
||||||
|
TrendingUp,
|
||||||
|
ShoppingCart,
|
||||||
|
UserCheck
|
||||||
|
} from 'lucide-react';
|
||||||
|
|
||||||
|
export type TabId = 'market' | 'procurement' | 'members' | 'tenants' | 'audit' | 'sessions';
|
||||||
|
|
||||||
|
interface NavItemConfig {
|
||||||
|
id: TabId;
|
||||||
|
label: string;
|
||||||
|
icon: React.ComponentType<{ className?: string }>;
|
||||||
|
allowedRoles: string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
const ALL_NAV_ITEMS: NavItemConfig[] = [
|
||||||
|
{
|
||||||
|
id: 'market',
|
||||||
|
label: 'Market Desk',
|
||||||
|
icon: TrendingUp,
|
||||||
|
allowedRoles: [
|
||||||
|
'Mandi Buyer',
|
||||||
|
'Purchase Manager',
|
||||||
|
'Partner / MD',
|
||||||
|
'Tenant Administrator',
|
||||||
|
'Desk Trader',
|
||||||
|
'Procurement Officer',
|
||||||
|
'Sales Executive',
|
||||||
|
'Sales Manager',
|
||||||
|
'Accounts Executive'
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'procurement',
|
||||||
|
label: 'Sauda Booking',
|
||||||
|
icon: ShoppingCart,
|
||||||
|
allowedRoles: [
|
||||||
|
'Mandi Buyer',
|
||||||
|
'Purchase Manager',
|
||||||
|
'Partner / MD',
|
||||||
|
'Tenant Administrator',
|
||||||
|
'Procurement Officer',
|
||||||
|
'Accounts Executive'
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'members',
|
||||||
|
label: 'Tenant Members',
|
||||||
|
icon: Users,
|
||||||
|
allowedRoles: ['Tenant Administrator', 'Partner / MD'],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'tenants',
|
||||||
|
label: 'Platform Tenants',
|
||||||
|
icon: Building2,
|
||||||
|
allowedRoles: ['System Administrator'],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'audit',
|
||||||
|
label: 'Security Audit',
|
||||||
|
icon: FileText,
|
||||||
|
allowedRoles: ['Tenant Administrator', 'System Administrator'],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'sessions',
|
||||||
|
label: 'Session Governance',
|
||||||
|
icon: Shield,
|
||||||
|
allowedRoles: ['*'], // All authenticated roles
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
const resolveDefaultTab = (roles: string[]): TabId => {
|
||||||
|
if (roles.includes('Mandi Buyer') || roles.includes('Purchase Manager') || roles.includes('Partner / MD')) {
|
||||||
|
return 'market';
|
||||||
|
}
|
||||||
|
if (roles.includes('Tenant Administrator')) {
|
||||||
|
return 'members';
|
||||||
|
}
|
||||||
|
if (roles.includes('System Administrator')) {
|
||||||
|
return 'tenants';
|
||||||
|
}
|
||||||
|
return 'sessions';
|
||||||
|
};
|
||||||
|
|
||||||
export const App: React.FC = () => {
|
export const App: React.FC = () => {
|
||||||
const [activeTab, setActiveTab] = useState<'sessions' | 'tenants' | 'members' | 'audit'>('sessions');
|
|
||||||
const [isAuthenticated, setIsAuthenticated] = useState<boolean>(authStore.getState().isAuthenticated);
|
const [isAuthenticated, setIsAuthenticated] = useState<boolean>(authStore.getState().isAuthenticated);
|
||||||
|
const [currentUser, setCurrentUser] = useState(authStore.getState().user);
|
||||||
|
const userRoles = currentUser?.roles || [];
|
||||||
|
|
||||||
|
const [activeTab, setActiveTab] = useState<TabId>(() => resolveDefaultTab(userRoles));
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
return authStore.subscribe(() => {
|
return authStore.subscribe(() => {
|
||||||
setIsAuthenticated(authStore.getState().isAuthenticated);
|
const state = authStore.getState();
|
||||||
|
setIsAuthenticated(state.isAuthenticated);
|
||||||
|
setCurrentUser(state.user);
|
||||||
|
const roles = state.user?.roles || [];
|
||||||
|
setActiveTab((prev) => {
|
||||||
|
const allowed = ALL_NAV_ITEMS.filter((item) =>
|
||||||
|
item.allowedRoles.includes('*') || item.allowedRoles.some((r) => roles.includes(r))
|
||||||
|
).map((i) => i.id);
|
||||||
|
if (!allowed.includes(prev)) {
|
||||||
|
return resolveDefaultTab(roles);
|
||||||
|
}
|
||||||
|
return prev;
|
||||||
|
});
|
||||||
});
|
});
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
|
|
@ -23,12 +129,15 @@ export const App: React.FC = () => {
|
||||||
return <LoginView />;
|
return <LoginView />;
|
||||||
}
|
}
|
||||||
|
|
||||||
const navItems = [
|
// Filter navigation items strictly against current role claims (BRD-FR-040 RBAC)
|
||||||
{ id: 'sessions' as const, label: 'Session Governance', icon: Shield },
|
const isRoleAllowed = (allowedRoles: string[]) => {
|
||||||
{ id: 'tenants' as const, label: 'Platform Tenants', icon: Building2 },
|
if (allowedRoles.includes('*')) return true;
|
||||||
{ id: 'members' as const, label: 'Tenant Members', icon: Users },
|
return allowedRoles.some((role) => userRoles.includes(role));
|
||||||
{ id: 'audit' as const, label: 'Security Audit', icon: FileText },
|
};
|
||||||
];
|
|
||||||
|
const authorizedNavItems = ALL_NAV_ITEMS.filter((item) => isRoleAllowed(item.allowedRoles));
|
||||||
|
const currentTabConfig = ALL_NAV_ITEMS.find((item) => item.id === activeTab);
|
||||||
|
const isCurrentTabAuthorized = currentTabConfig ? isRoleAllowed(currentTabConfig.allowedRoles) : false;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="min-h-screen bg-surface flex text-on-surface font-sans">
|
<div className="min-h-screen bg-surface flex text-on-surface font-sans">
|
||||||
|
|
@ -49,12 +158,26 @@ export const App: React.FC = () => {
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Navigation Items */}
|
{/* Active Persona Context Badge */}
|
||||||
|
<div className="px-4 py-3 border-b border-sidebar-active/60 bg-sidebar-active/30">
|
||||||
|
<div className="flex items-center space-x-2 text-[10px] uppercase font-mono tracking-wider text-accent-ochre mb-1">
|
||||||
|
<UserCheck className="w-3 h-3" />
|
||||||
|
<span>Active Persona</span>
|
||||||
|
</div>
|
||||||
|
<div className="text-xs font-semibold text-white truncate">
|
||||||
|
{currentUser?.name || currentUser?.email?.split('@')[0] || 'Authenticated User'}
|
||||||
|
</div>
|
||||||
|
<div className="text-[11px] font-mono text-gray-300 truncate">
|
||||||
|
{userRoles.length > 0 ? userRoles.join(', ') : 'Standard User'}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Role-Gated Navigation Items */}
|
||||||
<nav className="p-3 space-y-1">
|
<nav className="p-3 space-y-1">
|
||||||
<div className="px-3 py-1.5 text-[10px] font-semibold uppercase tracking-wider text-gray-400 font-mono">
|
<div className="px-3 py-1.5 text-[10px] font-semibold uppercase tracking-wider text-gray-400 font-mono">
|
||||||
Operational Portals
|
Operational Portals
|
||||||
</div>
|
</div>
|
||||||
{navItems.map((item) => {
|
{authorizedNavItems.map((item) => {
|
||||||
const Icon = item.icon;
|
const Icon = item.icon;
|
||||||
const isActive = activeTab === item.id;
|
const isActive = activeTab === item.id;
|
||||||
return (
|
return (
|
||||||
|
|
@ -99,10 +222,12 @@ export const App: React.FC = () => {
|
||||||
<header className="bg-card-surface border-b border-card-border px-8 py-3.5 flex items-center justify-between sticky top-0 z-10 shadow-none">
|
<header className="bg-card-surface border-b border-card-border px-8 py-3.5 flex items-center justify-between sticky top-0 z-10 shadow-none">
|
||||||
<div className="flex items-center space-x-3">
|
<div className="flex items-center space-x-3">
|
||||||
<h1 className="text-base font-semibold text-text-primary capitalize tracking-tight">
|
<h1 className="text-base font-semibold text-text-primary capitalize tracking-tight">
|
||||||
{activeTab === 'sessions' && 'Session & Token Governance'}
|
{activeTab === 'market' && 'Mandi Market Desk & Daily Rates (SCREEN-MKT-001)'}
|
||||||
{activeTab === 'tenants' && 'Platform Trading Tenants'}
|
{activeTab === 'procurement' && 'Purchase Sauda Contracts Register (SCREEN-PROC-001)'}
|
||||||
{activeTab === 'members' && 'Tenant Membership & Role Matrix'}
|
{activeTab === 'members' && 'Tenant Membership & Role Matrix'}
|
||||||
|
{activeTab === 'tenants' && 'Platform Trading Tenants'}
|
||||||
{activeTab === 'audit' && 'Security Audit Trail & Mutations'}
|
{activeTab === 'audit' && 'Security Audit Trail & Mutations'}
|
||||||
|
{activeTab === 'sessions' && 'Session & Token Governance'}
|
||||||
</h1>
|
</h1>
|
||||||
<span className="text-xs text-text-muted">|</span>
|
<span className="text-xs text-text-muted">|</span>
|
||||||
<span className="text-xs font-mono text-text-muted uppercase">240px Asymmetric Canvas</span>
|
<span className="text-xs font-mono text-text-muted uppercase">240px Asymmetric Canvas</span>
|
||||||
|
|
@ -113,12 +238,22 @@ export const App: React.FC = () => {
|
||||||
</div>
|
</div>
|
||||||
</header>
|
</header>
|
||||||
|
|
||||||
{/* View Content */}
|
{/* View Content with Strict RBAC Access Guard */}
|
||||||
<main className="flex-1 p-8 max-w-7xl w-full mx-auto">
|
<main className="flex-1 p-8 max-w-7xl w-full mx-auto">
|
||||||
{activeTab === 'sessions' && <SessionView />}
|
{!isCurrentTabAuthorized ? (
|
||||||
{activeTab === 'tenants' && <PlatformTenantsView />}
|
<AccessDeniedView />
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
{activeTab === 'market' && (
|
||||||
|
<MarketDeskView onNavigateToSauda={() => setActiveTab('procurement')} />
|
||||||
|
)}
|
||||||
|
{activeTab === 'procurement' && <SaudaProcurementView />}
|
||||||
{activeTab === 'members' && <TenantMembersView />}
|
{activeTab === 'members' && <TenantMembersView />}
|
||||||
|
{activeTab === 'tenants' && <PlatformTenantsView />}
|
||||||
{activeTab === 'audit' && <AuditLogView />}
|
{activeTab === 'audit' && <AuditLogView />}
|
||||||
|
{activeTab === 'sessions' && <SessionView />}
|
||||||
|
</>
|
||||||
|
)}
|
||||||
</main>
|
</main>
|
||||||
|
|
||||||
{/* Footer */}
|
{/* Footer */}
|
||||||
|
|
|
||||||
|
|
@ -6,7 +6,6 @@
|
||||||
*/
|
*/
|
||||||
import React from 'react';
|
import React from 'react';
|
||||||
import { authStore } from '../../stores/authStore';
|
import { authStore } from '../../stores/authStore';
|
||||||
import { Card } from '../../components/ui/Card';
|
|
||||||
import { Button } from '../../components/ui/Button';
|
import { Button } from '../../components/ui/Button';
|
||||||
import { ShieldAlert, ArrowLeft, LogOut } from 'lucide-react';
|
import { ShieldAlert, ArrowLeft, LogOut } from 'lucide-react';
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -58,7 +58,7 @@ export const CallbackView: React.FC = () => {
|
||||||
|
|
||||||
// Verify session with backend API
|
// Verify session with backend API
|
||||||
setStatus('Initializing application session...');
|
setStatus('Initializing application session...');
|
||||||
const sessionResp = await fetch('http://localhost:8000/api/v1/auth/session', {
|
const sessionResp = await fetch('/api/v1/auth/session', {
|
||||||
headers: { Authorization: `Bearer ${accessToken}` },
|
headers: { Authorization: `Bearer ${accessToken}` },
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -6,15 +6,28 @@
|
||||||
*/
|
*/
|
||||||
import React, { useState } from 'react';
|
import React, { useState } from 'react';
|
||||||
import { authStore } from '../../stores/authStore';
|
import { authStore } from '../../stores/authStore';
|
||||||
|
import { tenantStore } from '../../stores/tenantStore';
|
||||||
import { Button } from '../../components/ui/Button';
|
import { Button } from '../../components/ui/Button';
|
||||||
import { Card } from '../../components/ui/Card';
|
import { ShieldCheck, LogIn } from 'lucide-react';
|
||||||
import { ShieldCheck, LogIn, ChevronRight } from 'lucide-react';
|
|
||||||
|
|
||||||
export const LoginView: React.FC = () => {
|
export const LoginView: React.FC = () => {
|
||||||
const [selectedPersona, setSelectedPersona] = useState<string>('buyer@alpha.com');
|
const [selectedPersona, setSelectedPersona] = useState<string>('buyer@malwa-agri.demo');
|
||||||
const [isLoading, setIsLoading] = useState<boolean>(false);
|
const [isLoading, setIsLoading] = useState<boolean>(false);
|
||||||
const [errorMessage, setErrorMessage] = useState<string | null>(null);
|
const [errorMessage, setErrorMessage] = useState<string | null>(null);
|
||||||
|
|
||||||
|
// Inspect URL parameters for redirect alerts on mount
|
||||||
|
React.useEffect(() => {
|
||||||
|
if (typeof window !== 'undefined' && window.location.search) {
|
||||||
|
const params = new URLSearchParams(window.location.search);
|
||||||
|
const errorParam = params.get('error');
|
||||||
|
if (errorParam === 'SESSION_EXPIRED') {
|
||||||
|
setErrorMessage('Session was terminated or expired. Please sign in again.');
|
||||||
|
} else if (errorParam) {
|
||||||
|
setErrorMessage(`Authentication alert: ${errorParam}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
// PKCE Code Verifier generator
|
// PKCE Code Verifier generator
|
||||||
const generateRandomString = (length: number): string => {
|
const generateRandomString = (length: number): string => {
|
||||||
const charset = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~';
|
const charset = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~';
|
||||||
|
|
@ -74,17 +87,36 @@ export const LoginView: React.FC = () => {
|
||||||
setIsLoading(true);
|
setIsLoading(true);
|
||||||
setErrorMessage(null);
|
setErrorMessage(null);
|
||||||
try {
|
try {
|
||||||
|
const isDemo = selectedPersona.endsWith('@malwa-agri.demo');
|
||||||
|
const tenantId = isDemo ? 'demo-malwa-agri' : 'tenant-alpha';
|
||||||
|
|
||||||
|
const role = selectedPersona.includes('buyer') ? 'Mandi Buyer' :
|
||||||
|
selectedPersona.includes('pmgr') ? 'Purchase Manager' :
|
||||||
|
selectedPersona.includes('qc') ? 'Quality Officer' :
|
||||||
|
selectedPersona.includes('yard') || selectedPersona.includes('whmgr') ? 'Yard Supervisor' :
|
||||||
|
selectedPersona.includes('smgr') ? 'Sales Manager' :
|
||||||
|
selectedPersona.includes('sales') ? 'Sales Executive' :
|
||||||
|
selectedPersona.includes('logistics') ? 'Logistics Coordinator' :
|
||||||
|
selectedPersona.includes('finance') ? 'Accounts Executive' :
|
||||||
|
selectedPersona.includes('director') ? 'Partner / MD' : 'Tenant Administrator';
|
||||||
|
|
||||||
authStore.setSession(`mock_token_${selectedPersona}`, {
|
authStore.setSession(`mock_token_${selectedPersona}`, {
|
||||||
sub: `usr_${selectedPersona}`,
|
sub: `usr_${selectedPersona}`,
|
||||||
email: selectedPersona,
|
email: selectedPersona,
|
||||||
name: selectedPersona.split('@')[0],
|
name: selectedPersona.split('@')[0],
|
||||||
roles: selectedPersona.includes('buyer') ? ['Mandi Buyer'] :
|
roles: [role],
|
||||||
selectedPersona.includes('qc') ? ['Quality Officer'] :
|
tenant_id: tenantId
|
||||||
selectedPersona.includes('yard') ? ['Yard Supervisor'] :
|
|
||||||
selectedPersona.includes('sales') ? ['Sales Executive'] : ['Tenant Administrator'],
|
|
||||||
tenant_id: 'tenant-alpha'
|
|
||||||
});
|
});
|
||||||
window.location.href = '/';
|
tenantStore.setActiveTenant(
|
||||||
|
tenantId,
|
||||||
|
isDemo ? 'Malwa Agri Trading Corp Pvt Ltd' : 'Alpha Agro Traders',
|
||||||
|
[role]
|
||||||
|
);
|
||||||
|
|
||||||
|
// Clean query parameters from URL in-place without triggering full page reload
|
||||||
|
if (typeof window !== 'undefined' && window.location.search) {
|
||||||
|
window.history.replaceState(null, '', window.location.pathname);
|
||||||
|
}
|
||||||
} catch (err: any) {
|
} catch (err: any) {
|
||||||
setErrorMessage(`Mock login failed: ${err.message}`);
|
setErrorMessage(`Mock login failed: ${err.message}`);
|
||||||
} finally {
|
} finally {
|
||||||
|
|
@ -141,15 +173,30 @@ export const LoginView: React.FC = () => {
|
||||||
onChange={(e) => setSelectedPersona(e.target.value)}
|
onChange={(e) => setSelectedPersona(e.target.value)}
|
||||||
className="w-full py-2 px-3 rounded bg-white border border-card-border text-text-primary text-xs focus:outline-none focus:border-sidebar-surface focus:ring-2 focus:ring-secondary-amber/20 font-mono transition"
|
className="w-full py-2 px-3 rounded bg-white border border-card-border text-text-primary text-xs focus:outline-none focus:border-sidebar-surface focus:ring-2 focus:ring-secondary-amber/20 font-mono transition"
|
||||||
>
|
>
|
||||||
|
<optgroup label="Sales Demo Firm — Malwa Agri Trading Corp (demo-malwa-agri)">
|
||||||
|
<option value="buyer@malwa-agri.demo">Rajesh Patidar — Mandi Buyer (Journey 1: Sauda Booking)</option>
|
||||||
|
<option value="yard@malwa-agri.demo">Vikram Singh — Yard Supervisor (Journey 2: Gate-In & Gross)</option>
|
||||||
|
<option value="qc@malwa-agri.demo">Dr. Ananya Joshi — Quality Officer (Journey 3: Lab Assay & Rebate)</option>
|
||||||
|
<option value="whmgr@malwa-agri.demo">Gopal Verma — Godown Manager (Journey 4: Stock Ledger)</option>
|
||||||
|
<option value="sales@malwa-agri.demo">Rohit Agrawal — Sales Executive (Journey 5: Sales Order)</option>
|
||||||
|
<option value="smgr@malwa-agri.demo">Meera Nair — Sales Manager (Journey 5: Credit Override)</option>
|
||||||
|
<option value="logistics@malwa-agri.demo">Dinesh Rao — Logistics Coordinator (Journey 6: Bilty Manifest)</option>
|
||||||
|
<option value="finance@malwa-agri.demo">Kavita Maheshwari — Accounts Executive (Journey 7: Mandi Cess)</option>
|
||||||
|
<option value="director@malwa-agri.demo">Harish Patel — Managing Director (Journey 8: Executive P&L)</option>
|
||||||
|
<option value="admin@malwa-agri.demo">Platform Admin — Tenant Administrator</option>
|
||||||
|
</optgroup>
|
||||||
|
<optgroup label="Standard Test Firm — Alpha Agro Traders (tenant-alpha)">
|
||||||
<option value="buyer@alpha.com">Ramesh Kumar — Mandi Buyer</option>
|
<option value="buyer@alpha.com">Ramesh Kumar — Mandi Buyer</option>
|
||||||
<option value="qc@alpha.com">Ananya Sharma — Quality Officer (SoD Restricted)</option>
|
<option value="qc@alpha.com">Ananya Sharma — Quality Officer</option>
|
||||||
<option value="yard@alpha.com">Vikram Singh — Yard Supervisor (SoD Restricted)</option>
|
<option value="yard@alpha.com">Vikram Singh — Yard Supervisor</option>
|
||||||
<option value="sales@alpha.com">Rohit Verma — Sales Executive (SoD Restricted)</option>
|
<option value="sales@alpha.com">Rohit Verma — Sales Executive</option>
|
||||||
<option value="finance@alpha.com">Kavita Joshi — Accounts Executive</option>
|
<option value="finance@alpha.com">Kavita Joshi — Accounts Executive</option>
|
||||||
<option value="admin@alpha.com">Alpha Admin — Tenant Administrator</option>
|
<option value="admin@alpha.com">Alpha Admin — Tenant Administrator</option>
|
||||||
|
</optgroup>
|
||||||
</select>
|
</select>
|
||||||
|
|
||||||
<Button
|
<Button
|
||||||
|
type="button"
|
||||||
variant="secondary"
|
variant="secondary"
|
||||||
onClick={handleDevMockLogin}
|
onClick={handleDevMockLogin}
|
||||||
disabled={isLoading}
|
disabled={isLoading}
|
||||||
|
|
|
||||||
|
|
@ -10,7 +10,7 @@ import { apiClient } from '../../services/api';
|
||||||
import { Card } from '../../components/ui/Card';
|
import { Card } from '../../components/ui/Card';
|
||||||
import { Button } from '../../components/ui/Button';
|
import { Button } from '../../components/ui/Button';
|
||||||
import { StatusPill } from '../../components/ui/StatusPill';
|
import { StatusPill } from '../../components/ui/StatusPill';
|
||||||
import { LogOut, ShieldCheck, KeyRound } from 'lucide-react';
|
import { LogOut, ShieldCheck } from 'lucide-react';
|
||||||
|
|
||||||
export const SessionView: React.FC = () => {
|
export const SessionView: React.FC = () => {
|
||||||
const [isLoggingOut, setIsLoggingOut] = useState<boolean>(false);
|
const [isLoggingOut, setIsLoggingOut] = useState<boolean>(false);
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,647 @@
|
||||||
|
/**
|
||||||
|
* SCREEN-MKT-001: Mandi Market Desk & Daily Rate Bulletin View.
|
||||||
|
*
|
||||||
|
* Fulfills FR-MKT-001, FR-MKT-002 & SCREEN-MKT-001.md (Iteration 03 / UC-002).
|
||||||
|
* Styled per DESIGN.md: AgriTrade Mercantile (Tactile Corporate Minimalism).
|
||||||
|
* Zero Hardcoding: All rates and arrivals flow dynamically from backend API.
|
||||||
|
*/
|
||||||
|
import React, { useState, useEffect, useCallback } from 'react';
|
||||||
|
import { Card } from '../../components/ui/Card';
|
||||||
|
import { Button } from '../../components/ui/Button';
|
||||||
|
import { StatusPill } from '../../components/ui/StatusPill';
|
||||||
|
import { apiClient } from '../../services/api';
|
||||||
|
import {
|
||||||
|
TrendingUp,
|
||||||
|
Plus,
|
||||||
|
Calendar,
|
||||||
|
MapPin,
|
||||||
|
ArrowUpRight,
|
||||||
|
CheckCircle2,
|
||||||
|
AlertTriangle,
|
||||||
|
Scale,
|
||||||
|
RefreshCw
|
||||||
|
} from 'lucide-react';
|
||||||
|
|
||||||
|
export interface MarketCommodityRate {
|
||||||
|
id: string;
|
||||||
|
commodity_code: string;
|
||||||
|
commodity_name: string;
|
||||||
|
variety: string;
|
||||||
|
grade: string;
|
||||||
|
arrivals_mt: number;
|
||||||
|
arrivals_bags: number;
|
||||||
|
min_rate: number;
|
||||||
|
max_rate: number;
|
||||||
|
modal_rate: number;
|
||||||
|
status: 'PUBLISHED' | 'HOLIDAY' | 'DRAFT';
|
||||||
|
}
|
||||||
|
|
||||||
|
const MANDI_OPTIONS = [
|
||||||
|
{ id: 'MP-IND-01', name: 'Indore APMC, Madhya Pradesh (Main Auction Yard)' },
|
||||||
|
{ id: 'RJ-KOT-01', name: 'Kota APMC, Rajasthan (Grain Mandi)' },
|
||||||
|
{ id: 'GJ-UNJ-01', name: 'Unjha APMC, Gujarat (Spices & Oilseed)' },
|
||||||
|
];
|
||||||
|
|
||||||
|
const COMMODITY_NAMES: Record<string, string> = {
|
||||||
|
SOY: 'Soyabean',
|
||||||
|
CHN: 'Chana',
|
||||||
|
WHT: 'Wheat',
|
||||||
|
MST: 'Mustard',
|
||||||
|
'c0a80123-demo-0000-0000-000000000001': 'Soyabean',
|
||||||
|
'c0a80123-demo-0000-0000-000000000002': 'Chana',
|
||||||
|
'c0a80123-demo-0000-0000-000000000003': 'Wheat',
|
||||||
|
'c0a80123-demo-0000-0000-000000000004': 'Mustard',
|
||||||
|
};
|
||||||
|
|
||||||
|
interface MarketDeskViewProps {
|
||||||
|
onNavigateToSauda?: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const MarketDeskView: React.FC<MarketDeskViewProps> = ({ onNavigateToSauda }) => {
|
||||||
|
const [selectedMandi, setSelectedMandi] = useState<string>('MP-IND-01');
|
||||||
|
const [observationDate, setObservationDate] = useState<string>(() => {
|
||||||
|
return new Date().toISOString().split('T')[0];
|
||||||
|
});
|
||||||
|
const [rates, setRates] = useState<MarketCommodityRate[]>([]);
|
||||||
|
const [isLoading, setIsLoading] = useState<boolean>(true);
|
||||||
|
const [isModalOpen, setIsModalOpen] = useState<boolean>(false);
|
||||||
|
const [notification, setNotification] = useState<{ type: 'success' | 'error'; message: string } | null>(null);
|
||||||
|
|
||||||
|
// Modal Form State
|
||||||
|
const [formCommodity, setFormCommodity] = useState<string>('Soyabean');
|
||||||
|
const [formVariety, setFormVariety] = useState<string>('Yellow Desi');
|
||||||
|
const [formArrivalsMt, setFormArrivalsMt] = useState<number>(620.0);
|
||||||
|
const [formMinRate, setFormMinRate] = useState<number>(4550.0);
|
||||||
|
const [formMaxRate, setFormMaxRate] = useState<number>(4900.0);
|
||||||
|
const [formModalRate, setFormModalRate] = useState<number>(4800.0);
|
||||||
|
const [formSubmitting, setFormSubmitting] = useState<boolean>(false);
|
||||||
|
const [validationError, setValidationError] = useState<string | null>(null);
|
||||||
|
|
||||||
|
// Validate Rate Invariant: Min <= Modal <= Max
|
||||||
|
useEffect(() => {
|
||||||
|
if (formMinRate > formModalRate) {
|
||||||
|
setValidationError('Modal clearing rate cannot be lower than minimum auction rate.');
|
||||||
|
} else if (formModalRate > formMaxRate) {
|
||||||
|
setValidationError('Modal clearing rate cannot exceed maximum auction rate.');
|
||||||
|
} else if (formMinRate > formMaxRate) {
|
||||||
|
setValidationError('Minimum rate cannot exceed maximum rate.');
|
||||||
|
} else {
|
||||||
|
setValidationError(null);
|
||||||
|
}
|
||||||
|
}, [formMinRate, formMaxRate, formModalRate]);
|
||||||
|
|
||||||
|
// Fetch rates dynamically from backend API
|
||||||
|
const fetchRates = useCallback(async () => {
|
||||||
|
setIsLoading(true);
|
||||||
|
try {
|
||||||
|
let url = `/api/v1/market/observations?mandi_id=${encodeURIComponent(selectedMandi)}`;
|
||||||
|
if (observationDate) {
|
||||||
|
url += `&date=${encodeURIComponent(observationDate)}`;
|
||||||
|
}
|
||||||
|
const resp = await apiClient(url);
|
||||||
|
if (resp.status === 200 && resp.data?.observations) {
|
||||||
|
let obsList = resp.data.observations;
|
||||||
|
// Fallback: If no observations for exact date, query mandi-wide to display latest bulletin
|
||||||
|
if (obsList.length === 0 && observationDate) {
|
||||||
|
const fallbackResp = await apiClient(`/api/v1/market/observations?mandi_id=${encodeURIComponent(selectedMandi)}`);
|
||||||
|
if (fallbackResp.status === 200 && fallbackResp.data?.observations?.length > 0) {
|
||||||
|
obsList = fallbackResp.data.observations;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const mapped: MarketCommodityRate[] = obsList.map((o: any) => ({
|
||||||
|
id: o.id || `mkt-${Math.random()}`,
|
||||||
|
commodity_code: o.commodity_id || 'COMM',
|
||||||
|
commodity_name: COMMODITY_NAMES[o.commodity_id] || o.commodity_id || 'Commodity',
|
||||||
|
variety: o.variety || 'FAQ',
|
||||||
|
grade: o.grade || 'FAQ',
|
||||||
|
arrivals_mt: Number(o.arrival_mt) || 0,
|
||||||
|
arrivals_bags: Math.round((Number(o.arrival_mt) || 0) * 20),
|
||||||
|
min_rate: Number(o.min_rate) || 0,
|
||||||
|
max_rate: Number(o.max_rate) || 0,
|
||||||
|
modal_rate: Number(o.modal_rate) || 0,
|
||||||
|
status: o.is_market_closed ? 'HOLIDAY' : 'PUBLISHED',
|
||||||
|
}));
|
||||||
|
setRates(mapped);
|
||||||
|
} else {
|
||||||
|
setRates([]);
|
||||||
|
}
|
||||||
|
} catch (err: any) {
|
||||||
|
console.error('Failed to load market observations:', err);
|
||||||
|
setRates([]);
|
||||||
|
} finally {
|
||||||
|
setIsLoading(false);
|
||||||
|
}
|
||||||
|
}, [selectedMandi, observationDate]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
fetchRates();
|
||||||
|
}, [fetchRates]);
|
||||||
|
|
||||||
|
const handleSaveObservation = async (e: React.FormEvent) => {
|
||||||
|
e.preventDefault();
|
||||||
|
if (validationError) return;
|
||||||
|
|
||||||
|
setFormSubmitting(true);
|
||||||
|
setNotification(null);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const payload = {
|
||||||
|
mandi_id: selectedMandi,
|
||||||
|
commodity_id: formCommodity === 'Soyabean' ? 'SOY' : formCommodity === 'Chana' ? 'CHN' : formCommodity === 'Mustard' ? 'MST' : 'WHT',
|
||||||
|
variety: formVariety,
|
||||||
|
grade: 'FAQ',
|
||||||
|
observation_date: observationDate,
|
||||||
|
arrival_mt: Number(formArrivalsMt),
|
||||||
|
min_rate: Number(formMinRate),
|
||||||
|
max_rate: Number(formMaxRate),
|
||||||
|
modal_rate: Number(formModalRate),
|
||||||
|
source: 'APMC_BULLETIN'
|
||||||
|
};
|
||||||
|
|
||||||
|
const resp = await apiClient('/api/v1/market/observations', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify(payload)
|
||||||
|
});
|
||||||
|
|
||||||
|
if (resp.status === 201 || resp.status === 200 || !resp.error) {
|
||||||
|
setNotification({
|
||||||
|
type: 'success',
|
||||||
|
message: `Daily rate observation recorded for ${formCommodity} (${formVariety}) at ₹ ${Number(formModalRate).toLocaleString('en-IN')}/Qtl.`
|
||||||
|
});
|
||||||
|
setIsModalOpen(false);
|
||||||
|
await fetchRates();
|
||||||
|
} else {
|
||||||
|
setNotification({
|
||||||
|
type: 'error',
|
||||||
|
message: resp.error || 'Failed to record observation on backend.'
|
||||||
|
});
|
||||||
|
}
|
||||||
|
} catch (err: any) {
|
||||||
|
setNotification({
|
||||||
|
type: 'error',
|
||||||
|
message: `Network error saving observation: ${err.message}`
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
setFormSubmitting(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const totalArrivalsMt = rates.reduce((acc, r) => acc + r.arrivals_mt, 0);
|
||||||
|
const soyRate = rates.find(r => r.commodity_name.toLowerCase().includes('soy') || r.commodity_code === 'SOY');
|
||||||
|
const selectedMandiObj = MANDI_OPTIONS.find(m => m.id === selectedMandi) || MANDI_OPTIONS[0];
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-6 max-w-7xl mx-auto">
|
||||||
|
{/* Top Banner Alert / Notification */}
|
||||||
|
{notification && (
|
||||||
|
<div
|
||||||
|
className={`p-3 rounded text-xs font-mono flex items-center justify-between border ${
|
||||||
|
notification.type === 'success'
|
||||||
|
? 'bg-status-normal-bg text-status-normal-text border-status-normal-text/30'
|
||||||
|
: 'bg-status-watch-bg text-status-watch-text border-accent-ochre'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<div className="flex items-center space-x-2">
|
||||||
|
{notification.type === 'success' ? (
|
||||||
|
<CheckCircle2 className="w-4 h-4 text-status-normal-text flex-shrink-0" />
|
||||||
|
) : (
|
||||||
|
<AlertTriangle className="w-4 h-4 text-accent-ochre flex-shrink-0" />
|
||||||
|
)}
|
||||||
|
<span>{notification.message}</span>
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
onClick={() => setNotification(null)}
|
||||||
|
className="text-xs uppercase font-semibold underline ml-4 hover:opacity-80"
|
||||||
|
>
|
||||||
|
Dismiss
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Mandi Selector & Control Bar */}
|
||||||
|
<div className="bg-card-surface border border-card-border rounded p-4 flex flex-wrap items-center justify-between gap-4">
|
||||||
|
<div className="flex items-center space-x-4">
|
||||||
|
<div className="flex items-center space-x-2">
|
||||||
|
<MapPin className="w-4 h-4 text-accent-ochre" />
|
||||||
|
<span className="text-xs font-semibold uppercase text-text-muted font-mono tracking-wider">Mandi Hub:</span>
|
||||||
|
<select
|
||||||
|
value={selectedMandi}
|
||||||
|
onChange={(e) => setSelectedMandi(e.target.value)}
|
||||||
|
className="py-1 px-2.5 rounded bg-white border border-card-border text-xs font-medium text-text-primary focus:outline-none focus:ring-1 focus:ring-accent-ochre"
|
||||||
|
>
|
||||||
|
{MANDI_OPTIONS.map((m) => (
|
||||||
|
<option key={m.id} value={m.id}>{m.name}</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex items-center space-x-2">
|
||||||
|
<Calendar className="w-4 h-4 text-text-muted" />
|
||||||
|
<span className="text-xs font-semibold uppercase text-text-muted font-mono tracking-wider">Date:</span>
|
||||||
|
<input
|
||||||
|
type="date"
|
||||||
|
value={observationDate}
|
||||||
|
onChange={(e) => setObservationDate(e.target.value)}
|
||||||
|
className="py-1 px-2 rounded bg-white border border-card-border text-xs font-mono text-text-primary focus:outline-none focus:ring-1 focus:ring-accent-ochre"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Button
|
||||||
|
variant="secondary"
|
||||||
|
size="sm"
|
||||||
|
onClick={fetchRates}
|
||||||
|
disabled={isLoading}
|
||||||
|
className="p-1.5 text-xs text-text-muted hover:text-text-primary"
|
||||||
|
title="Refresh Bulletin"
|
||||||
|
>
|
||||||
|
<RefreshCw className={`w-3.5 h-3.5 ${isLoading ? 'animate-spin' : ''}`} />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex items-center space-x-3">
|
||||||
|
<Button
|
||||||
|
variant="primary"
|
||||||
|
size="sm"
|
||||||
|
onClick={() => setIsModalOpen(true)}
|
||||||
|
className="flex items-center space-x-1.5 font-semibold text-xs py-2 px-3.5"
|
||||||
|
>
|
||||||
|
<Plus className="w-3.5 h-3.5 text-accent-ochre" />
|
||||||
|
<span>Record Observation</span>
|
||||||
|
</Button>
|
||||||
|
|
||||||
|
{onNavigateToSauda && (
|
||||||
|
<Button
|
||||||
|
variant="secondary"
|
||||||
|
size="sm"
|
||||||
|
onClick={onNavigateToSauda}
|
||||||
|
className="flex items-center space-x-1.5 text-xs py-2 px-3.5 font-mono"
|
||||||
|
>
|
||||||
|
<span>Book Sauda at Modal</span>
|
||||||
|
<ArrowUpRight className="w-3.5 h-3.5 text-accent-ochre" />
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Prominent Live APMC Ticker per Sales Demo Playbook */}
|
||||||
|
<div className="grid grid-cols-1 md:grid-cols-4 gap-4">
|
||||||
|
<div className="bg-card-surface border border-card-border rounded p-4">
|
||||||
|
<div className="text-[10px] uppercase font-semibold text-text-muted font-mono tracking-wider mb-1">
|
||||||
|
Indore Soybean Modal Benchmark
|
||||||
|
</div>
|
||||||
|
<div className="flex items-baseline space-x-2">
|
||||||
|
<span className="text-2xl font-bold font-mono text-text-primary">
|
||||||
|
{soyRate ? `₹ ${soyRate.modal_rate.toLocaleString('en-IN', { minimumFractionDigits: 2 })}` : '₹ —'}
|
||||||
|
</span>
|
||||||
|
<span className="text-xs text-text-muted font-mono">/ Qtl</span>
|
||||||
|
</div>
|
||||||
|
<div className="text-[11px] text-status-normal-text font-mono mt-1 flex items-center">
|
||||||
|
<TrendingUp className="w-3 h-3 mr-1 inline" />
|
||||||
|
{soyRate ? 'Active Mandi Clearing Rate' : 'No Active Bulletin'}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="bg-card-surface border border-card-border rounded p-4">
|
||||||
|
<div className="text-[10px] uppercase font-semibold text-text-muted font-mono tracking-wider mb-1">
|
||||||
|
Daily Soybean Arrivals
|
||||||
|
</div>
|
||||||
|
<div className="flex items-baseline space-x-2">
|
||||||
|
<span className="text-2xl font-bold font-mono text-text-primary">
|
||||||
|
{soyRate ? soyRate.arrivals_bags.toLocaleString('en-IN') : '—'}
|
||||||
|
</span>
|
||||||
|
<span className="text-xs text-text-muted font-mono">
|
||||||
|
Bags ({soyRate ? soyRate.arrivals_mt.toFixed(1) : '0.0'} MT)
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<div className="text-[11px] text-text-muted font-mono mt-1">
|
||||||
|
50 kg standard jute bags
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="bg-card-surface border border-card-border rounded p-4">
|
||||||
|
<div className="text-[10px] uppercase font-semibold text-text-muted font-mono tracking-wider mb-1">
|
||||||
|
Total Yard Volume Today
|
||||||
|
</div>
|
||||||
|
<div className="flex items-baseline space-x-2">
|
||||||
|
<span className="text-2xl font-bold font-mono text-text-primary">
|
||||||
|
{totalArrivalsMt.toFixed(1)}
|
||||||
|
</span>
|
||||||
|
<span className="text-xs text-text-muted font-mono">Metric Tonnes</span>
|
||||||
|
</div>
|
||||||
|
<div className="text-[11px] text-text-muted font-mono mt-1">
|
||||||
|
Across {rates.length} Monitored Commodities
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="bg-card-surface border border-card-border rounded p-4">
|
||||||
|
<div className="text-[10px] uppercase font-semibold text-text-muted font-mono tracking-wider mb-1">
|
||||||
|
Mandi Samiti Status
|
||||||
|
</div>
|
||||||
|
<div className="flex items-baseline space-x-2 mt-1">
|
||||||
|
<StatusPill status={rates.length > 0 ? 'normal' : 'watch'} label={rates.length > 0 ? `${rates.length} Active Bulletins` : 'No Rates Seeded'} />
|
||||||
|
</div>
|
||||||
|
<div className="text-[11px] text-text-muted font-mono mt-2">
|
||||||
|
{selectedMandiObj.name.split(',')[0]} Yard Active
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Commodity Rate Blotter Table (SCREEN-MKT-001) */}
|
||||||
|
<Card
|
||||||
|
title="Daily Mandi Arrival & Price Bulletin"
|
||||||
|
subtitle={`Official APMC yard arrivals and clearing price ranges (${selectedMandiObj.name.split(',')[0]} • ${observationDate})`}
|
||||||
|
action={
|
||||||
|
<span className="text-xs font-mono text-text-muted uppercase">
|
||||||
|
FR-MKT-001 • FR-MKT-002
|
||||||
|
</span>
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<div className="overflow-x-auto">
|
||||||
|
{isLoading ? (
|
||||||
|
<div className="py-12 text-center text-xs text-text-muted font-mono">
|
||||||
|
<RefreshCw className="w-6 h-6 animate-spin mx-auto mb-2 text-accent-ochre" />
|
||||||
|
Loading real-time market arrivals from backend...
|
||||||
|
</div>
|
||||||
|
) : rates.length === 0 ? (
|
||||||
|
<div className="py-12 text-center text-xs text-text-muted font-mono space-y-2">
|
||||||
|
<Scale className="w-10 h-10 mx-auto text-text-muted/40 mb-2" />
|
||||||
|
<div className="font-semibold text-text-primary text-sm font-sans">No Market Observations Recorded</div>
|
||||||
|
<p className="text-text-secondary max-w-sm mx-auto font-sans">
|
||||||
|
No arrival or price records found for this mandi yard. Use "+ Record Observation" to enter live auction rates or run the sales demo seeder.
|
||||||
|
</p>
|
||||||
|
<div className="pt-2">
|
||||||
|
<Button variant="primary" size="sm" onClick={() => setIsModalOpen(true)}>
|
||||||
|
<Plus className="w-3.5 h-3.5 mr-1" /> Record Observation
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<table className="w-full text-left text-xs divide-y divide-card-border">
|
||||||
|
<thead className="bg-surface-low font-mono text-[11px] uppercase tracking-wider text-text-muted">
|
||||||
|
<tr>
|
||||||
|
<th className="py-3 px-4">Commodity</th>
|
||||||
|
<th className="py-3 px-4">Variety / Grade</th>
|
||||||
|
<th className="py-3 px-4 text-right">Arrivals (MT)</th>
|
||||||
|
<th className="py-3 px-4 text-right">Estimated Bags</th>
|
||||||
|
<th className="py-3 px-4 text-right">Min Rate (₹/Qtl)</th>
|
||||||
|
<th className="py-3 px-4 text-right">Max Rate (₹/Qtl)</th>
|
||||||
|
<th className="py-3 px-4 text-right font-bold text-text-primary">Modal Rate (₹/Qtl)</th>
|
||||||
|
<th className="py-3 px-4 text-center">Status</th>
|
||||||
|
<th className="py-3 px-4 text-right">Action</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody className="divide-y divide-card-border bg-white font-sans">
|
||||||
|
{rates.map((rate) => (
|
||||||
|
<tr key={rate.id} className="hover:bg-surface-bright transition-colors">
|
||||||
|
<td className="py-3.5 px-4">
|
||||||
|
<div className="font-semibold text-text-primary flex items-center space-x-2">
|
||||||
|
<span className="inline-block w-2 h-2 rounded-full bg-accent-ochre"></span>
|
||||||
|
<span>{rate.commodity_name}</span>
|
||||||
|
<span className="text-[10px] font-mono text-text-muted uppercase bg-surface-container px-1 rounded">
|
||||||
|
{rate.commodity_code}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</td>
|
||||||
|
<td className="py-3.5 px-4 font-mono text-text-muted">
|
||||||
|
{rate.variety} • <span className="text-text-primary">{rate.grade}</span>
|
||||||
|
</td>
|
||||||
|
<td className="py-3.5 px-4 text-right font-mono font-medium text-text-primary">
|
||||||
|
{rate.arrivals_mt.toFixed(3)} MT
|
||||||
|
</td>
|
||||||
|
<td className="py-3.5 px-4 text-right font-mono text-text-muted">
|
||||||
|
{rate.arrivals_bags.toLocaleString('en-IN')}
|
||||||
|
</td>
|
||||||
|
<td className="py-3.5 px-4 text-right font-mono text-text-muted">
|
||||||
|
₹ {rate.min_rate.toLocaleString('en-IN', { minimumFractionDigits: 2 })}
|
||||||
|
</td>
|
||||||
|
<td className="py-3.5 px-4 text-right font-mono text-text-muted">
|
||||||
|
₹ {rate.max_rate.toLocaleString('en-IN', { minimumFractionDigits: 2 })}
|
||||||
|
</td>
|
||||||
|
<td className="py-3.5 px-4 text-right font-mono font-bold text-text-primary bg-surface-low/50">
|
||||||
|
₹ {rate.modal_rate.toLocaleString('en-IN', { minimumFractionDigits: 2 })}
|
||||||
|
</td>
|
||||||
|
<td className="py-3.5 px-4 text-center">
|
||||||
|
<StatusPill status="cleared" label={rate.status} />
|
||||||
|
</td>
|
||||||
|
<td className="py-3.5 px-4 text-right">
|
||||||
|
{onNavigateToSauda ? (
|
||||||
|
<button
|
||||||
|
onClick={onNavigateToSauda}
|
||||||
|
className="inline-flex items-center space-x-1 text-xs text-text-primary hover:text-accent-ochre font-medium underline underline-offset-2 transition"
|
||||||
|
>
|
||||||
|
<span>Trade</span>
|
||||||
|
<ArrowUpRight className="w-3 h-3" />
|
||||||
|
</button>
|
||||||
|
) : (
|
||||||
|
<span className="text-text-muted font-mono text-[11px]">Locked</span>
|
||||||
|
)}
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
{/* Record Mandi Daily Observation Modal Dialog */}
|
||||||
|
{isModalOpen && (
|
||||||
|
<div className="fixed z-50 inset-0 overflow-y-auto">
|
||||||
|
<div className="flex items-center justify-center min-h-screen px-4 text-center sm:p-0">
|
||||||
|
<div
|
||||||
|
className="fixed inset-0 bg-sidebar-surface/40 transition-opacity"
|
||||||
|
onClick={() => setIsModalOpen(false)}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<div className="inline-block bg-card-surface rounded border border-card-border p-6 text-left overflow-hidden shadow-tactile transform transition-all sm:max-w-lg sm:w-full z-10">
|
||||||
|
<div className="flex items-center justify-between pb-3 border-b border-card-border mb-4">
|
||||||
|
<div className="flex items-center space-x-2">
|
||||||
|
<Scale className="w-5 h-5 text-accent-ochre" />
|
||||||
|
<h3 className="text-sm font-bold text-text-primary tracking-tight">
|
||||||
|
Record Mandi Daily Observation & Rates
|
||||||
|
</h3>
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setIsModalOpen(false)}
|
||||||
|
className="text-text-muted hover:text-text-primary text-xs font-mono"
|
||||||
|
>
|
||||||
|
✕
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<form onSubmit={handleSaveObservation} className="space-y-4 text-xs font-sans">
|
||||||
|
<div className="grid grid-cols-2 gap-3">
|
||||||
|
<div>
|
||||||
|
<label className="block text-[11px] font-semibold uppercase tracking-wider text-text-muted font-mono mb-1">
|
||||||
|
Monitored Mandi*:
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
disabled
|
||||||
|
value={selectedMandiObj.name}
|
||||||
|
className="w-full py-1.5 px-2.5 rounded bg-surface-low border border-card-border text-text-muted text-xs font-mono"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label className="block text-[11px] font-semibold uppercase tracking-wider text-text-muted font-mono mb-1">
|
||||||
|
Observation Date*:
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
type="date"
|
||||||
|
value={observationDate}
|
||||||
|
onChange={(e) => setObservationDate(e.target.value)}
|
||||||
|
className="w-full py-1.5 px-2.5 rounded bg-white border border-card-border text-text-primary text-xs font-mono focus:outline-none focus:ring-1 focus:ring-accent-ochre"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="grid grid-cols-2 gap-3">
|
||||||
|
<div>
|
||||||
|
<label className="block text-[11px] font-semibold uppercase tracking-wider text-text-muted font-mono mb-1">
|
||||||
|
Commodity*:
|
||||||
|
</label>
|
||||||
|
<select
|
||||||
|
value={formCommodity}
|
||||||
|
onChange={(e) => {
|
||||||
|
setFormCommodity(e.target.value);
|
||||||
|
if (e.target.value === 'Soyabean') {
|
||||||
|
setFormVariety('Yellow Desi');
|
||||||
|
setFormMinRate(4550);
|
||||||
|
setFormMaxRate(4900);
|
||||||
|
setFormModalRate(4800);
|
||||||
|
} else if (e.target.value === 'Chana') {
|
||||||
|
setFormVariety('Desi Bold');
|
||||||
|
setFormMinRate(5800);
|
||||||
|
setFormMaxRate(6150);
|
||||||
|
setFormModalRate(6000);
|
||||||
|
} else if (e.target.value === 'Mustard') {
|
||||||
|
setFormVariety('42% Oil');
|
||||||
|
setFormMinRate(5200);
|
||||||
|
setFormMaxRate(5550);
|
||||||
|
setFormModalRate(5400);
|
||||||
|
} else {
|
||||||
|
setFormVariety('Lokwan');
|
||||||
|
setFormMinRate(2350);
|
||||||
|
setFormMaxRate(2550);
|
||||||
|
setFormModalRate(2450);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
className="w-full py-1.5 px-2.5 rounded bg-white border border-card-border text-text-primary text-xs font-mono focus:outline-none focus:ring-1 focus:ring-accent-ochre"
|
||||||
|
>
|
||||||
|
<option value="Soyabean">Soyabean (SOY)</option>
|
||||||
|
<option value="Chana">Chana (CHN)</option>
|
||||||
|
<option value="Wheat">Wheat (WHT)</option>
|
||||||
|
<option value="Mustard">Mustard (MST)</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label className="block text-[11px] font-semibold uppercase tracking-wider text-text-muted font-mono mb-1">
|
||||||
|
Variety*:
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
value={formVariety}
|
||||||
|
onChange={(e) => setFormVariety(e.target.value)}
|
||||||
|
className="w-full py-1.5 px-2.5 rounded bg-white border border-card-border text-text-primary text-xs font-mono focus:outline-none focus:ring-1 focus:ring-accent-ochre"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label className="block text-[11px] font-semibold uppercase tracking-wider text-text-muted font-mono mb-1">
|
||||||
|
Arrival Quantity (MT)*:
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
type="number"
|
||||||
|
step="0.001"
|
||||||
|
min="0"
|
||||||
|
value={formArrivalsMt}
|
||||||
|
onChange={(e) => setFormArrivalsMt(parseFloat(e.target.value) || 0)}
|
||||||
|
className="w-full py-1.5 px-2.5 rounded bg-white border border-card-border text-text-primary text-xs font-mono focus:outline-none focus:ring-1 focus:ring-accent-ochre"
|
||||||
|
/>
|
||||||
|
<span className="text-[10px] text-text-muted font-mono">
|
||||||
|
Equivalent to ~{Math.round(formArrivalsMt * 20).toLocaleString('en-IN')} Bags (50kg standard)
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="p-3 bg-surface-low rounded border border-card-border space-y-3">
|
||||||
|
<div className="text-[10px] uppercase font-semibold text-text-muted font-mono tracking-wider">
|
||||||
|
APMC Auction Rate Spectrum (₹ / Quintal)
|
||||||
|
</div>
|
||||||
|
<div className="grid grid-cols-3 gap-2">
|
||||||
|
<div>
|
||||||
|
<label className="block text-[10px] font-mono text-text-muted mb-0.5">Min Rate (₹)*</label>
|
||||||
|
<input
|
||||||
|
type="number"
|
||||||
|
step="1"
|
||||||
|
value={formMinRate}
|
||||||
|
onChange={(e) => setFormMinRate(parseFloat(e.target.value) || 0)}
|
||||||
|
className="w-full py-1 px-2 rounded bg-white border border-card-border text-text-primary text-xs font-mono"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label className="block text-[10px] font-mono text-text-muted mb-0.5">Modal Rate (₹)*</label>
|
||||||
|
<input
|
||||||
|
type="number"
|
||||||
|
step="1"
|
||||||
|
value={formModalRate}
|
||||||
|
onChange={(e) => setFormModalRate(parseFloat(e.target.value) || 0)}
|
||||||
|
className="w-full py-1 px-2 rounded bg-white border border-card-border text-text-primary text-xs font-mono font-bold"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label className="block text-[10px] font-mono text-text-muted mb-0.5">Max Rate (₹)*</label>
|
||||||
|
<input
|
||||||
|
type="number"
|
||||||
|
step="1"
|
||||||
|
value={formMaxRate}
|
||||||
|
onChange={(e) => setFormMaxRate(parseFloat(e.target.value) || 0)}
|
||||||
|
className="w-full py-1 px-2 rounded bg-white border border-card-border text-text-primary text-xs font-mono"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{validationError ? (
|
||||||
|
<div className="text-[11px] text-error font-mono flex items-center space-x-1">
|
||||||
|
<AlertTriangle className="w-3 h-3 text-error inline flex-shrink-0" />
|
||||||
|
<span>{validationError}</span>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="text-[10px] text-status-normal-text font-mono flex items-center space-x-1">
|
||||||
|
<CheckCircle2 className="w-3 h-3 text-status-normal-text inline flex-shrink-0" />
|
||||||
|
<span>Invariant Enforced: Min (₹ {formMinRate}) ≤ Modal (₹ {formModalRate}) ≤ Max (₹ {formMaxRate})</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex items-center justify-end space-x-3 pt-3 border-t border-card-border">
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="secondary"
|
||||||
|
size="sm"
|
||||||
|
onClick={() => setIsModalOpen(false)}
|
||||||
|
className="font-mono text-xs"
|
||||||
|
>
|
||||||
|
Cancel
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
type="submit"
|
||||||
|
variant="primary"
|
||||||
|
size="sm"
|
||||||
|
disabled={!!validationError || formSubmitting}
|
||||||
|
className="font-mono text-xs"
|
||||||
|
>
|
||||||
|
{formSubmitting ? 'Saving...' : 'Save & Publish Rates'}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
@ -0,0 +1,801 @@
|
||||||
|
/**
|
||||||
|
* SCREEN-PROC-001: Purchase Sauda Booking Register & Costing View.
|
||||||
|
*
|
||||||
|
* Fulfills FR-PROCUREMENTCONTRACTS-001..004 & SCREEN-PROC-001.md (Iteration 03 / UC-004).
|
||||||
|
* Styled per DESIGN.md: AgriTrade Mercantile (Tactile Corporate Minimalism).
|
||||||
|
* Zero Hardcoding: All sauda contracts and commercial positions flow dynamically from backend API.
|
||||||
|
*/
|
||||||
|
import React, { useState, useEffect, useCallback } from 'react';
|
||||||
|
import { Card } from '../../components/ui/Card';
|
||||||
|
import { Button } from '../../components/ui/Button';
|
||||||
|
import { StatusPill } from '../../components/ui/StatusPill';
|
||||||
|
import { apiClient } from '../../services/api';
|
||||||
|
import {
|
||||||
|
ShoppingCart,
|
||||||
|
Plus,
|
||||||
|
AlertTriangle,
|
||||||
|
CheckCircle2,
|
||||||
|
Calculator,
|
||||||
|
Search,
|
||||||
|
Filter,
|
||||||
|
RefreshCw
|
||||||
|
} from 'lucide-react';
|
||||||
|
|
||||||
|
export interface SaudaContract {
|
||||||
|
id: string;
|
||||||
|
sauda_number: string;
|
||||||
|
contract_date: string;
|
||||||
|
delivery_due_date: string;
|
||||||
|
supplier_name: string;
|
||||||
|
mandi_hub: string;
|
||||||
|
commodity_name: string;
|
||||||
|
variety: string;
|
||||||
|
grade: string;
|
||||||
|
booked_quantity_mt: number;
|
||||||
|
estimated_bags: number;
|
||||||
|
trade_rate_per_qtl: number;
|
||||||
|
gross_value: number;
|
||||||
|
landed_value: number;
|
||||||
|
mandi_cess: number;
|
||||||
|
krishi_kalyan: number;
|
||||||
|
brokerage: number;
|
||||||
|
credit_days: number;
|
||||||
|
fulfilled_pct: number;
|
||||||
|
status: 'ACTIVE' | 'PENDING' | 'CLOSED' | 'REJECTED';
|
||||||
|
}
|
||||||
|
|
||||||
|
const BENCHMARK_MODAL_RATE = 4800.0; // Indore APMC Soybean modal clearing rate benchmark
|
||||||
|
|
||||||
|
export const SaudaProcurementView: React.FC = () => {
|
||||||
|
const [saudas, setSaudas] = useState<SaudaContract[]>([]);
|
||||||
|
const [isLoading, setIsLoading] = useState<boolean>(true);
|
||||||
|
const [searchQuery, setSearchQuery] = useState<string>('');
|
||||||
|
const [statusFilter, setStatusFilter] = useState<string>('ALL');
|
||||||
|
const [isModalOpen, setIsModalOpen] = useState<boolean>(false);
|
||||||
|
const [notification, setNotification] = useState<{ type: 'success' | 'error'; message: string } | null>(null);
|
||||||
|
|
||||||
|
// Form State matching Playbook Journey 1
|
||||||
|
const [contractDate, setContractDate] = useState<string>(() => new Date().toISOString().split('T')[0]);
|
||||||
|
const [sourcingMandi, setSourcingMandi] = useState<string>('Indore APMC, Madhya Pradesh');
|
||||||
|
const [tradeType, setTradeType] = useState<string>('MANDI_AUCTION');
|
||||||
|
const [supplierName, setSupplierName] = useState<string>('Rameshwar Patidar (Farmer / Arhatiya - Neemuch)');
|
||||||
|
const [commodity, setCommodity] = useState<string>('Soyabean (SOY)');
|
||||||
|
const [variety, setVariety] = useState<string>('Yellow FAQ');
|
||||||
|
const [bookedMt, setBookedMt] = useState<number>(25.0);
|
||||||
|
const [tradeRate, setTradeRate] = useState<number>(4850.0);
|
||||||
|
const [creditDays, setCreditDays] = useState<number>(7);
|
||||||
|
const [isSubmitting, setIsSubmitting] = useState<boolean>(false);
|
||||||
|
const [varianceConfirmed, setVarianceConfirmed] = useState<boolean>(false);
|
||||||
|
|
||||||
|
// Computed Bags: MT * 1000 / 50kg = MT * 20
|
||||||
|
const estimatedBags = Math.round(bookedMt * 20);
|
||||||
|
|
||||||
|
// Computed Payment Due Date
|
||||||
|
const computeDueDate = (dateStr: string, days: number): string => {
|
||||||
|
try {
|
||||||
|
const d = new Date(dateStr);
|
||||||
|
d.setDate(d.getDate() + days);
|
||||||
|
return d.toISOString().split('T')[0];
|
||||||
|
} catch {
|
||||||
|
return dateStr;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
const paymentDueDate = computeDueDate(contractDate, creditDays);
|
||||||
|
|
||||||
|
// Rate Variance calculation: ((tradeRate - benchmark) / benchmark) * 100
|
||||||
|
const rateVariancePct = ((tradeRate - BENCHMARK_MODAL_RATE) / BENCHMARK_MODAL_RATE) * 100;
|
||||||
|
const isVarianceExceeded = rateVariancePct > 5.0;
|
||||||
|
|
||||||
|
// Commercial Math per NFR-001 (Dual UOM, Statutory Rounding)
|
||||||
|
const grossTradeValue = bookedMt * 10 * tradeRate;
|
||||||
|
const mandiCess = grossTradeValue * 0.015; // 1.50%
|
||||||
|
const krishiKalyan = grossTradeValue * 0.005; // 0.50%
|
||||||
|
const brokerage = grossTradeValue * 0.01; // 1.00%
|
||||||
|
const totalLandedValue = grossTradeValue + mandiCess + krishiKalyan + brokerage;
|
||||||
|
|
||||||
|
// Fetch Saudas dynamically from backend API
|
||||||
|
const fetchSaudas = useCallback(async () => {
|
||||||
|
setIsLoading(true);
|
||||||
|
try {
|
||||||
|
let url = '/api/v1/procurement/sauda';
|
||||||
|
if (statusFilter !== 'ALL') {
|
||||||
|
url += `?status_filter=${encodeURIComponent(statusFilter)}`;
|
||||||
|
}
|
||||||
|
const resp = await apiClient(url);
|
||||||
|
if (resp.status === 200 && resp.data?.saudas) {
|
||||||
|
const rawList = resp.data.saudas;
|
||||||
|
const mapped: SaudaContract[] = rawList.map((s: any) => {
|
||||||
|
const bookedQty = Number(s.booked_quantity_mt) || 0;
|
||||||
|
const cumReceived = Number(s.cumulative_received_mt) || 0;
|
||||||
|
const rateQtl = Number(s.trade_rate_per_qtl) || 0;
|
||||||
|
const gross = Number(s.gross_amount) || (bookedQty * 10 * rateQtl);
|
||||||
|
const landed = Number(s.total_landed_amount) || gross;
|
||||||
|
const fulfilledPct = bookedQty > 0 ? Math.round((cumReceived / bookedQty) * 100) : 0;
|
||||||
|
|
||||||
|
let uiStatus: 'ACTIVE' | 'PENDING' | 'CLOSED' | 'REJECTED' = 'ACTIVE';
|
||||||
|
if (s.status === 'CLOSED' || s.status === 'FULFILLED') {
|
||||||
|
uiStatus = 'CLOSED';
|
||||||
|
} else if (s.status === 'PENDING') {
|
||||||
|
uiStatus = 'PENDING';
|
||||||
|
} else if (s.status === 'REJECTED' || s.status === 'CANCELLED') {
|
||||||
|
uiStatus = 'REJECTED';
|
||||||
|
}
|
||||||
|
|
||||||
|
let supplierDisp = s.supplier_name;
|
||||||
|
if (!supplierDisp) {
|
||||||
|
if (s.supplier_id === 'cpty-demo-supplier-01') supplierDisp = 'Rameshwar Patidar (Farmer / Arhatiya)';
|
||||||
|
else if (s.supplier_id === 'cpty-demo-supplier-02') supplierDisp = 'Kisan Agro Traders (SUP-0042)';
|
||||||
|
else if (s.supplier_id === 'cpty-demo-supplier-03') supplierDisp = 'Mewar Krishi Sangh';
|
||||||
|
else if (s.supplier_id === 'cpty-demo-supplier-04') supplierDisp = 'Malwa Agro Corp';
|
||||||
|
else supplierDisp = s.supplier_id || 'Counterparty';
|
||||||
|
}
|
||||||
|
|
||||||
|
let mandiDisp = s.mandi_id;
|
||||||
|
if (mandiDisp === 'MP-IND-01') mandiDisp = 'Indore APMC';
|
||||||
|
else if (mandiDisp === 'RJ-KOT-01') mandiDisp = 'Kota APMC';
|
||||||
|
else if (mandiDisp === 'GJ-UNJ-01') mandiDisp = 'Unjha APMC';
|
||||||
|
|
||||||
|
let commDisp = s.commodity_id;
|
||||||
|
if (commDisp === 'SOY' || commDisp === 'c0a80123-demo-0000-0000-000000000001') commDisp = 'Soyabean';
|
||||||
|
else if (commDisp === 'CHN' || commDisp === 'c0a80123-demo-0000-0000-000000000002') commDisp = 'Chana';
|
||||||
|
else if (commDisp === 'WHT' || commDisp === 'c0a80123-demo-0000-0000-000000000003') commDisp = 'Wheat';
|
||||||
|
else if (commDisp === 'MST' || commDisp === 'c0a80123-demo-0000-0000-000000000004') commDisp = 'Mustard';
|
||||||
|
|
||||||
|
return {
|
||||||
|
id: s.id || `sda-${Math.random()}`,
|
||||||
|
sauda_number: s.sauda_number || 'SDA-NEW',
|
||||||
|
contract_date: s.contract_date || '',
|
||||||
|
delivery_due_date: s.delivery_due_date || s.contract_date || '',
|
||||||
|
supplier_name: supplierDisp,
|
||||||
|
mandi_hub: mandiDisp || 'Indore APMC',
|
||||||
|
commodity_name: commDisp || 'Commodity',
|
||||||
|
variety: s.variety || 'FAQ',
|
||||||
|
grade: s.grade || 'FAQ',
|
||||||
|
booked_quantity_mt: bookedQty,
|
||||||
|
estimated_bags: Number(s.estimated_bags) || Math.round(bookedQty * 20),
|
||||||
|
trade_rate_per_qtl: rateQtl,
|
||||||
|
gross_value: gross,
|
||||||
|
landed_value: landed,
|
||||||
|
mandi_cess: Number(s.mandi_cess_amount) || (gross * 0.015),
|
||||||
|
krishi_kalyan: Number(s.krishi_kalyan_amount) || (gross * 0.005),
|
||||||
|
brokerage: Number(s.brokerage_amount) || (gross * 0.01),
|
||||||
|
credit_days: Number(s.credit_period_days) || 0,
|
||||||
|
fulfilled_pct: fulfilledPct,
|
||||||
|
status: uiStatus
|
||||||
|
};
|
||||||
|
});
|
||||||
|
setSaudas(mapped);
|
||||||
|
} else {
|
||||||
|
setSaudas([]);
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
console.error('Failed to load sauda contracts:', err);
|
||||||
|
setSaudas([]);
|
||||||
|
} finally {
|
||||||
|
setIsLoading(false);
|
||||||
|
}
|
||||||
|
}, [statusFilter]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
fetchSaudas();
|
||||||
|
}, [fetchSaudas]);
|
||||||
|
|
||||||
|
const handleBookSauda = async (e: React.FormEvent) => {
|
||||||
|
e.preventDefault();
|
||||||
|
if (isVarianceExceeded && !varianceConfirmed) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
setIsSubmitting(true);
|
||||||
|
setNotification(null);
|
||||||
|
|
||||||
|
const generatedSaudaNumber = `SDA-2026-${String(saudas.length + 1).padStart(3, '0')}`;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const payload = {
|
||||||
|
sauda_number: generatedSaudaNumber,
|
||||||
|
contract_date: contractDate,
|
||||||
|
delivery_due_date: paymentDueDate,
|
||||||
|
supplier_id: supplierName.includes('Rameshwar') ? 'cpty-demo-supplier-01' :
|
||||||
|
supplierName.includes('Kisan') ? 'cpty-demo-supplier-02' :
|
||||||
|
supplierName.includes('Mewar') ? 'cpty-demo-supplier-03' : 'cpty-demo-supplier-01',
|
||||||
|
mandi_id: sourcingMandi.includes('Indore') ? 'MP-IND-01' :
|
||||||
|
sourcingMandi.includes('Kota') ? 'RJ-KOT-01' : 'GJ-UNJ-01',
|
||||||
|
trade_type: tradeType,
|
||||||
|
commodity_id: commodity.includes('SOY') ? 'SOY' : commodity.includes('CHN') ? 'CHN' : commodity.includes('MST') ? 'MST' : 'WHT',
|
||||||
|
variety: variety,
|
||||||
|
grade: 'FAQ',
|
||||||
|
booked_quantity_mt: bookedMt,
|
||||||
|
trade_rate_per_qtl: tradeRate,
|
||||||
|
rate_variance_pct: rateVariancePct,
|
||||||
|
variance_acknowledged: isVarianceExceeded ? varianceConfirmed : false,
|
||||||
|
credit_period_days: creditDays,
|
||||||
|
payment_due_date: paymentDueDate,
|
||||||
|
mandi_cess_pct: 1.5,
|
||||||
|
krishi_kalyan_pct: 0.5,
|
||||||
|
brokerage_rate_pct: 1.0,
|
||||||
|
gross_value: grossTradeValue,
|
||||||
|
landed_value: totalLandedValue
|
||||||
|
};
|
||||||
|
|
||||||
|
const resp = await apiClient('/api/v1/procurement/sauda', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify(payload)
|
||||||
|
});
|
||||||
|
|
||||||
|
if (resp.status === 201 || resp.status === 200 || !resp.error) {
|
||||||
|
setNotification({
|
||||||
|
type: 'success',
|
||||||
|
message: `Sauda Contract ${generatedSaudaNumber} locked successfully! Landed value ₹ ${totalLandedValue.toLocaleString('en-IN', { minimumFractionDigits: 2 })} booked for ${supplierName}.`
|
||||||
|
});
|
||||||
|
setIsModalOpen(false);
|
||||||
|
// Reset form
|
||||||
|
setBookedMt(25.0);
|
||||||
|
setTradeRate(4850.0);
|
||||||
|
setVarianceConfirmed(false);
|
||||||
|
// Refresh live data from backend!
|
||||||
|
await fetchSaudas();
|
||||||
|
} else {
|
||||||
|
setNotification({
|
||||||
|
type: 'error',
|
||||||
|
message: resp.error || 'Failed to book sauda on backend.'
|
||||||
|
});
|
||||||
|
}
|
||||||
|
} catch (err: any) {
|
||||||
|
setNotification({
|
||||||
|
type: 'error',
|
||||||
|
message: `Failed to book sauda: ${err.message}`
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
setIsSubmitting(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Filtered saudas
|
||||||
|
const filteredSaudas = saudas.filter(s => {
|
||||||
|
const matchesSearch = s.sauda_number.toLowerCase().includes(searchQuery.toLowerCase()) ||
|
||||||
|
s.supplier_name.toLowerCase().includes(searchQuery.toLowerCase()) ||
|
||||||
|
s.commodity_name.toLowerCase().includes(searchQuery.toLowerCase());
|
||||||
|
const matchesStatus = statusFilter === 'ALL' || s.status === statusFilter;
|
||||||
|
return matchesSearch && matchesStatus;
|
||||||
|
});
|
||||||
|
|
||||||
|
const activeCount = saudas.filter(s => s.status === 'ACTIVE').length;
|
||||||
|
const totalOpenMt = saudas
|
||||||
|
.filter(s => s.status === 'ACTIVE')
|
||||||
|
.reduce((acc, s) => acc + (s.booked_quantity_mt * (1 - s.fulfilled_pct / 100)), 0);
|
||||||
|
const totalExposure = saudas
|
||||||
|
.filter(s => s.status === 'ACTIVE')
|
||||||
|
.reduce((acc, s) => acc + s.landed_value, 0);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-6 max-w-7xl mx-auto">
|
||||||
|
{/* Top Banner Alert / Notification */}
|
||||||
|
{notification && (
|
||||||
|
<div
|
||||||
|
className={`p-3 rounded text-xs font-mono flex items-center justify-between border ${
|
||||||
|
notification.type === 'success'
|
||||||
|
? 'bg-status-normal-bg text-status-normal-text border-status-normal-text/30'
|
||||||
|
: 'bg-status-watch-bg text-status-watch-text border-accent-ochre'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<div className="flex items-center space-x-2">
|
||||||
|
{notification.type === 'success' ? (
|
||||||
|
<CheckCircle2 className="w-4 h-4 text-status-normal-text flex-shrink-0" />
|
||||||
|
) : (
|
||||||
|
<AlertTriangle className="w-4 h-4 text-accent-ochre flex-shrink-0" />
|
||||||
|
)}
|
||||||
|
<span>{notification.message}</span>
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
onClick={() => setNotification(null)}
|
||||||
|
className="text-xs uppercase font-semibold underline ml-4 hover:opacity-80"
|
||||||
|
>
|
||||||
|
Dismiss
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Summary KPI Cards */}
|
||||||
|
<div className="grid grid-cols-1 md:grid-cols-4 gap-4">
|
||||||
|
<div className="bg-card-surface border border-card-border rounded p-4">
|
||||||
|
<div className="text-[10px] uppercase font-semibold text-text-muted font-mono tracking-wider mb-1">
|
||||||
|
Active Sauda Contracts
|
||||||
|
</div>
|
||||||
|
<div className="flex items-baseline space-x-2">
|
||||||
|
<span className="text-2xl font-bold font-mono text-text-primary">{activeCount}</span>
|
||||||
|
<span className="text-xs text-text-muted font-mono">Contracts</span>
|
||||||
|
</div>
|
||||||
|
<div className="text-[11px] text-text-muted font-mono mt-1">
|
||||||
|
{activeCount > 0 ? 'Indore & Kota Mandis' : 'No Active Contracts'}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="bg-card-surface border border-card-border rounded p-4">
|
||||||
|
<div className="text-[10px] uppercase font-semibold text-text-muted font-mono tracking-wider mb-1">
|
||||||
|
Open Balance Position
|
||||||
|
</div>
|
||||||
|
<div className="flex items-baseline space-x-2">
|
||||||
|
<span className="text-2xl font-bold font-mono text-text-primary">
|
||||||
|
{totalOpenMt.toFixed(2)}
|
||||||
|
</span>
|
||||||
|
<span className="text-xs text-text-muted font-mono">MT Pending Receiving</span>
|
||||||
|
</div>
|
||||||
|
<div className="text-[11px] text-text-muted font-mono mt-1">
|
||||||
|
~{Math.round(totalOpenMt * 20).toLocaleString('en-IN')} Bags Scheduled
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="bg-card-surface border border-card-border rounded p-4">
|
||||||
|
<div className="text-[10px] uppercase font-semibold text-text-muted font-mono tracking-wider mb-1">
|
||||||
|
Committed Procurement Exposure
|
||||||
|
</div>
|
||||||
|
<div className="flex items-baseline space-x-2">
|
||||||
|
<span className="text-2xl font-bold font-mono text-text-primary">
|
||||||
|
₹ {(totalExposure / 100000).toFixed(2)}
|
||||||
|
</span>
|
||||||
|
<span className="text-xs text-text-muted font-mono">Lakhs</span>
|
||||||
|
</div>
|
||||||
|
<div className="text-[11px] text-text-muted font-mono mt-1">
|
||||||
|
Landed including statutory cess
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="bg-card-surface border border-card-border rounded p-4">
|
||||||
|
<div className="text-[10px] uppercase font-semibold text-text-muted font-mono tracking-wider mb-1">
|
||||||
|
Statutory Mandi Cess Levies
|
||||||
|
</div>
|
||||||
|
<div className="flex items-baseline space-x-2">
|
||||||
|
<span className="text-2xl font-bold font-mono text-text-primary">
|
||||||
|
₹ {(saudas.reduce((acc, s) => acc + s.mandi_cess, 0) / 100000).toFixed(2)}
|
||||||
|
</span>
|
||||||
|
<span className="text-xs text-text-muted font-mono">Lakhs</span>
|
||||||
|
</div>
|
||||||
|
<div className="text-[11px] text-text-muted font-mono mt-1">
|
||||||
|
1.50% MP APMC Mandi Samiti Cess
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Control Bar: Filters & Action Button */}
|
||||||
|
<div className="bg-card-surface border border-card-border rounded p-4 flex flex-wrap items-center justify-between gap-4">
|
||||||
|
<div className="flex items-center space-x-3 flex-1 min-w-[280px]">
|
||||||
|
<div className="relative flex-1 max-w-sm">
|
||||||
|
<Search className="w-4 h-4 text-text-muted absolute left-3 top-2.5" />
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
placeholder="Search contract, supplier, or commodity..."
|
||||||
|
value={searchQuery}
|
||||||
|
onChange={(e) => setSearchQuery(e.target.value)}
|
||||||
|
className="w-full pl-9 pr-3 py-1.5 rounded bg-white border border-card-border text-xs font-sans text-text-primary focus:outline-none focus:ring-1 focus:ring-accent-ochre placeholder:text-text-muted"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex items-center space-x-2">
|
||||||
|
<Filter className="w-4 h-4 text-text-muted" />
|
||||||
|
<select
|
||||||
|
value={statusFilter}
|
||||||
|
onChange={(e) => setStatusFilter(e.target.value)}
|
||||||
|
className="py-1.5 px-3 rounded bg-white border border-card-border text-xs font-mono text-text-primary focus:outline-none focus:ring-1 focus:ring-accent-ochre"
|
||||||
|
>
|
||||||
|
<option value="ALL">All Statuses ({saudas.length})</option>
|
||||||
|
<option value="ACTIVE">Active</option>
|
||||||
|
<option value="PENDING">Pending Approval</option>
|
||||||
|
<option value="CLOSED">Closed / Fulfilled</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Button
|
||||||
|
variant="secondary"
|
||||||
|
size="sm"
|
||||||
|
onClick={fetchSaudas}
|
||||||
|
disabled={isLoading}
|
||||||
|
className="p-1.5 text-xs text-text-muted hover:text-text-primary"
|
||||||
|
title="Refresh Saudas"
|
||||||
|
>
|
||||||
|
<RefreshCw className={`w-3.5 h-3.5 ${isLoading ? 'animate-spin' : ''}`} />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex items-center space-x-3">
|
||||||
|
<Button
|
||||||
|
variant="primary"
|
||||||
|
size="sm"
|
||||||
|
onClick={() => setIsModalOpen(true)}
|
||||||
|
className="flex items-center space-x-2 font-semibold text-xs py-2 px-4 shadow-none"
|
||||||
|
>
|
||||||
|
<Plus className="w-4 h-4 text-accent-ochre" />
|
||||||
|
<span>Book New Sauda</span>
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Sauda Contracts Table (SCREEN-PROC-001) */}
|
||||||
|
<Card
|
||||||
|
title="Purchase Sauda Contracts Register"
|
||||||
|
subtitle="Binding commercial procurement contracts with multi-tier statutory cess and landed costing"
|
||||||
|
action={
|
||||||
|
<span className="text-xs font-mono text-text-muted uppercase">
|
||||||
|
SCREEN-PROC-001 • UC-004
|
||||||
|
</span>
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<div className="overflow-x-auto">
|
||||||
|
{isLoading ? (
|
||||||
|
<div className="py-12 text-center text-xs text-text-muted font-mono">
|
||||||
|
<RefreshCw className="w-6 h-6 animate-spin mx-auto mb-2 text-accent-ochre" />
|
||||||
|
Loading procurement contracts from backend...
|
||||||
|
</div>
|
||||||
|
) : filteredSaudas.length === 0 ? (
|
||||||
|
<div className="py-12 text-center text-xs text-text-muted font-mono space-y-2">
|
||||||
|
<ShoppingCart className="w-10 h-10 mx-auto text-text-muted/40 mb-2" />
|
||||||
|
<div className="font-semibold text-text-primary text-sm font-sans">No Purchase Contracts Booked</div>
|
||||||
|
<p className="text-text-secondary max-w-sm mx-auto font-sans">
|
||||||
|
No active or closed sauda purchase agreements found for this tenant. Use "+ Book New Sauda" to issue a contract or run the sales demo seeder.
|
||||||
|
</p>
|
||||||
|
<div className="pt-2">
|
||||||
|
<Button variant="primary" size="sm" onClick={() => setIsModalOpen(true)}>
|
||||||
|
<Plus className="w-3.5 h-3.5 mr-1" /> Book New Sauda
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<table className="w-full text-left text-xs divide-y divide-card-border">
|
||||||
|
<thead className="bg-surface-low font-mono text-[11px] uppercase tracking-wider text-text-muted">
|
||||||
|
<tr>
|
||||||
|
<th className="py-3 px-4">Contract ID</th>
|
||||||
|
<th className="py-3 px-4">Date</th>
|
||||||
|
<th className="py-3 px-4">Supplier / Arhatiya</th>
|
||||||
|
<th className="py-3 px-4">Mandi Hub</th>
|
||||||
|
<th className="py-3 px-4">Commodity</th>
|
||||||
|
<th className="py-3 px-4 text-right">Booked MT</th>
|
||||||
|
<th className="py-3 px-4 text-right">Agreed Rate</th>
|
||||||
|
<th className="py-3 px-4 text-right">Base Value</th>
|
||||||
|
<th className="py-3 px-4 text-right font-bold text-text-primary">Landed Value</th>
|
||||||
|
<th className="py-3 px-4 text-center">Fulfilled</th>
|
||||||
|
<th className="py-3 px-4 text-center">Status</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody className="divide-y divide-card-border bg-white font-sans">
|
||||||
|
{filteredSaudas.map((sauda) => (
|
||||||
|
<tr key={sauda.id} className="hover:bg-surface-bright transition-colors">
|
||||||
|
<td className="py-3.5 px-4 font-mono font-semibold text-text-primary">
|
||||||
|
{sauda.sauda_number}
|
||||||
|
</td>
|
||||||
|
<td className="py-3.5 px-4 font-mono text-text-muted">
|
||||||
|
{sauda.contract_date}
|
||||||
|
</td>
|
||||||
|
<td className="py-3.5 px-4 font-medium text-text-primary">
|
||||||
|
{sauda.supplier_name}
|
||||||
|
</td>
|
||||||
|
<td className="py-3.5 px-4 font-mono text-text-muted">
|
||||||
|
{sauda.mandi_hub}
|
||||||
|
</td>
|
||||||
|
<td className="py-3.5 px-4">
|
||||||
|
<span className="font-semibold">{sauda.commodity_name}</span>{' '}
|
||||||
|
<span className="text-text-muted font-mono text-[11px]">({sauda.variety})</span>
|
||||||
|
</td>
|
||||||
|
<td className="py-3.5 px-4 text-right font-mono text-text-primary font-medium">
|
||||||
|
{sauda.booked_quantity_mt.toFixed(3)} MT
|
||||||
|
<div className="text-[10px] text-text-muted">{sauda.estimated_bags} bags</div>
|
||||||
|
</td>
|
||||||
|
<td className="py-3.5 px-4 text-right font-mono text-text-muted">
|
||||||
|
₹ {sauda.trade_rate_per_qtl.toLocaleString('en-IN', { minimumFractionDigits: 2 })}
|
||||||
|
</td>
|
||||||
|
<td className="py-3.5 px-4 text-right font-mono text-text-muted">
|
||||||
|
₹ {sauda.gross_value.toLocaleString('en-IN', { minimumFractionDigits: 2 })}
|
||||||
|
</td>
|
||||||
|
<td className="py-3.5 px-4 text-right font-mono font-bold text-text-primary bg-surface-low/50">
|
||||||
|
₹ {sauda.landed_value.toLocaleString('en-IN', { minimumFractionDigits: 2 })}
|
||||||
|
</td>
|
||||||
|
<td className="py-3.5 px-4 text-center font-mono text-xs">
|
||||||
|
<span className={sauda.fulfilled_pct === 100 ? 'text-status-normal-text font-bold' : 'text-text-muted'}>
|
||||||
|
{sauda.fulfilled_pct.toFixed(1)} %
|
||||||
|
</span>
|
||||||
|
</td>
|
||||||
|
<td className="py-3.5 px-4 text-center">
|
||||||
|
<StatusPill
|
||||||
|
status={sauda.status === 'ACTIVE' ? 'normal' : sauda.status === 'PENDING' ? 'watch' : 'neutral'}
|
||||||
|
label={sauda.status}
|
||||||
|
/>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
{/* Book New Sauda Modal Dialog (SCREEN-PROC-001 / Sales Demo Journey 1) */}
|
||||||
|
{isModalOpen && (
|
||||||
|
<div className="fixed z-50 inset-0 overflow-y-auto">
|
||||||
|
<div className="flex items-center justify-center min-h-screen px-4 text-center sm:p-0">
|
||||||
|
<div
|
||||||
|
className="fixed inset-0 bg-sidebar-surface/40 transition-opacity"
|
||||||
|
onClick={() => setIsModalOpen(false)}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<div className="inline-block bg-card-surface rounded border border-card-border p-6 text-left overflow-hidden shadow-tactile transform transition-all sm:max-w-2xl sm:w-full z-10">
|
||||||
|
<div className="flex items-center justify-between pb-3 border-b border-card-border mb-4">
|
||||||
|
<div className="flex items-center space-x-2">
|
||||||
|
<ShoppingCart className="w-5 h-5 text-accent-ochre" />
|
||||||
|
<h3 className="text-sm font-bold text-text-primary tracking-tight">
|
||||||
|
Book Purchase Sauda Contract (Mandi Auction / Direct Purchase)
|
||||||
|
</h3>
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setIsModalOpen(false)}
|
||||||
|
className="text-text-muted hover:text-text-primary text-xs font-mono"
|
||||||
|
>
|
||||||
|
✕
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<form onSubmit={handleBookSauda} className="space-y-4 text-xs font-sans">
|
||||||
|
{/* Contract Dates & Sourcing Yard */}
|
||||||
|
<div className="grid grid-cols-2 gap-3">
|
||||||
|
<div>
|
||||||
|
<label className="block text-[11px] font-semibold uppercase tracking-wider text-text-muted font-mono mb-1">
|
||||||
|
Contract Date*:
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
type="date"
|
||||||
|
value={contractDate}
|
||||||
|
onChange={(e) => setContractDate(e.target.value)}
|
||||||
|
className="w-full py-1.5 px-2.5 rounded bg-white border border-card-border text-text-primary text-xs font-mono focus:outline-none focus:ring-1 focus:ring-accent-ochre"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label className="block text-[11px] font-semibold uppercase tracking-wider text-text-muted font-mono mb-1">
|
||||||
|
Sourcing Mandi*:
|
||||||
|
</label>
|
||||||
|
<select
|
||||||
|
value={sourcingMandi}
|
||||||
|
onChange={(e) => setSourcingMandi(e.target.value)}
|
||||||
|
className="w-full py-1.5 px-2.5 rounded bg-white border border-card-border text-text-primary text-xs font-mono focus:outline-none focus:ring-1 focus:ring-accent-ochre"
|
||||||
|
>
|
||||||
|
<option value="Indore APMC, Madhya Pradesh">Indore APMC, Madhya Pradesh</option>
|
||||||
|
<option value="Kota APMC, Rajasthan">Kota APMC, Rajasthan</option>
|
||||||
|
<option value="Unjha APMC, Gujarat">Unjha APMC, Gujarat</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Supplier & Trade Type */}
|
||||||
|
<div className="grid grid-cols-2 gap-3">
|
||||||
|
<div>
|
||||||
|
<label className="block text-[11px] font-semibold uppercase tracking-wider text-text-muted font-mono mb-1">
|
||||||
|
Supplier / Arhatiya*:
|
||||||
|
</label>
|
||||||
|
<select
|
||||||
|
value={supplierName}
|
||||||
|
onChange={(e) => setSupplierName(e.target.value)}
|
||||||
|
className="w-full py-1.5 px-2.5 rounded bg-white border border-card-border text-text-primary text-xs font-mono focus:outline-none focus:ring-1 focus:ring-accent-ochre"
|
||||||
|
>
|
||||||
|
<option value="Rameshwar Patidar (Farmer / Arhatiya - Neemuch)">
|
||||||
|
Rameshwar Patidar (Farmer / Arhatiya - Neemuch)
|
||||||
|
</option>
|
||||||
|
<option value="Kisan Agro Traders (SUP-0042 - 24ABCDE1234F1Z5)">
|
||||||
|
Kisan Agro Traders (SUP-0042)
|
||||||
|
</option>
|
||||||
|
<option value="Mewar Krishi Sangh">Mewar Krishi Sangh</option>
|
||||||
|
<option value="Malwa Agro Corp">Malwa Agro Corp</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label className="block text-[11px] font-semibold uppercase tracking-wider text-text-muted font-mono mb-1">
|
||||||
|
Trade Type*:
|
||||||
|
</label>
|
||||||
|
<select
|
||||||
|
value={tradeType}
|
||||||
|
onChange={(e) => setTradeType(e.target.value)}
|
||||||
|
className="w-full py-1.5 px-2.5 rounded bg-white border border-card-border text-text-primary text-xs font-mono focus:outline-none focus:ring-1 focus:ring-accent-ochre"
|
||||||
|
>
|
||||||
|
<option value="MANDI_AUCTION">Mandi APMC Auction</option>
|
||||||
|
<option value="DIRECT_FARMER">Direct Farmer Purchase</option>
|
||||||
|
<option value="COMMERCIAL_TRADER">Commercial Trader Sauda</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Commodity, Variety & Grade */}
|
||||||
|
<div className="grid grid-cols-3 gap-3">
|
||||||
|
<div>
|
||||||
|
<label className="block text-[11px] font-semibold uppercase tracking-wider text-text-muted font-mono mb-1">
|
||||||
|
Commodity*:
|
||||||
|
</label>
|
||||||
|
<select
|
||||||
|
value={commodity}
|
||||||
|
onChange={(e) => setCommodity(e.target.value)}
|
||||||
|
className="w-full py-1.5 px-2.5 rounded bg-white border border-card-border text-text-primary text-xs font-mono focus:outline-none focus:ring-1 focus:ring-accent-ochre"
|
||||||
|
>
|
||||||
|
<option value="Soyabean (SOY)">Soyabean (SOY)</option>
|
||||||
|
<option value="Chana (CHN)">Chana (CHN)</option>
|
||||||
|
<option value="Wheat (WHT)">Wheat (WHT)</option>
|
||||||
|
<option value="Mustard (MST)">Mustard (MST)</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label className="block text-[11px] font-semibold uppercase tracking-wider text-text-muted font-mono mb-1">
|
||||||
|
Variety*:
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
value={variety}
|
||||||
|
onChange={(e) => setVariety(e.target.value)}
|
||||||
|
className="w-full py-1.5 px-2.5 rounded bg-white border border-card-border text-text-primary text-xs font-mono focus:outline-none focus:ring-1 focus:ring-accent-ochre"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label className="block text-[11px] font-semibold uppercase tracking-wider text-text-muted font-mono mb-1">
|
||||||
|
Commercial Grade*:
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
disabled
|
||||||
|
value="FAQ (Fair Average Quality)"
|
||||||
|
className="w-full py-1.5 px-2.5 rounded bg-surface-low border border-card-border text-text-muted text-xs font-mono"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Trade Quantity & Pricing with Dual-UOM */}
|
||||||
|
<div className="p-3.5 bg-surface-low rounded border border-card-border space-y-3">
|
||||||
|
<div className="text-[10px] uppercase font-semibold text-text-muted font-mono tracking-wider flex items-center justify-between">
|
||||||
|
<span>Trade Quantity & Pricing Alignment</span>
|
||||||
|
<span className="text-accent-ochre">Benchmark Modal: ₹ {BENCHMARK_MODAL_RATE.toLocaleString('en-IN')}/Qtl</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="grid grid-cols-3 gap-3">
|
||||||
|
<div>
|
||||||
|
<label className="block text-[10px] font-mono text-text-muted mb-0.5">
|
||||||
|
Booked Quantity (MT)*:
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
type="number"
|
||||||
|
step="0.001"
|
||||||
|
min="0.1"
|
||||||
|
value={bookedMt}
|
||||||
|
onChange={(e) => setBookedMt(parseFloat(e.target.value) || 0)}
|
||||||
|
className="w-full py-1.5 px-2.5 rounded bg-white border border-card-border text-text-primary text-xs font-mono font-bold focus:outline-none focus:ring-1 focus:ring-accent-ochre"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label className="block text-[10px] font-mono text-text-muted mb-0.5">
|
||||||
|
Estimated Bags (50kg)*:
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
disabled
|
||||||
|
value={`${estimatedBags} Bags`}
|
||||||
|
className="w-full py-1.5 px-2.5 rounded bg-surface-container border border-card-border text-text-primary text-xs font-mono font-medium"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label className="block text-[10px] font-mono text-text-muted mb-0.5">
|
||||||
|
Agreed Rate (₹/Qtl)*:
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
type="number"
|
||||||
|
step="0.5"
|
||||||
|
min="1"
|
||||||
|
value={tradeRate}
|
||||||
|
onChange={(e) => setTradeRate(parseFloat(e.target.value) || 0)}
|
||||||
|
className="w-full py-1.5 px-2.5 rounded bg-white border border-card-border text-text-primary text-xs font-mono font-bold focus:outline-none focus:ring-1 focus:ring-accent-ochre"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Price Variance Safeguard Banner per Playbook Journey 1 */}
|
||||||
|
{isVarianceExceeded ? (
|
||||||
|
<div className="p-3 rounded bg-status-watch-bg border-l-[3px] border-accent-ochre text-status-watch-text text-xs space-y-2 font-mono">
|
||||||
|
<div className="flex items-center space-x-2 font-semibold">
|
||||||
|
<AlertTriangle className="w-4 h-4 text-accent-ochre flex-shrink-0" />
|
||||||
|
<span>
|
||||||
|
Price variance (+{rateVariancePct.toFixed(2)}%) exceeds 5.0% benchmark threshold!
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<p className="text-[11px] text-text-primary">
|
||||||
|
Agreed rate (₹ {tradeRate.toFixed(2)}) is higher than Indore APMC clearing rate (₹ {BENCHMARK_MODAL_RATE.toFixed(2)}). Mandatory confirmation required before locking.
|
||||||
|
</p>
|
||||||
|
<label className="flex items-center space-x-2 text-xs text-text-primary cursor-pointer pt-1">
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
checked={varianceConfirmed}
|
||||||
|
onChange={(e) => setVarianceConfirmed(e.target.checked)}
|
||||||
|
className="rounded border-card-border text-accent-ochre focus:ring-accent-ochre"
|
||||||
|
/>
|
||||||
|
<span className="font-semibold">
|
||||||
|
I confirm this rate is justified due to premium high-oil specification (FAQ+).
|
||||||
|
</span>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="text-[10px] text-status-normal-text font-mono flex items-center space-x-1">
|
||||||
|
<CheckCircle2 className="w-3.5 h-3.5 text-status-normal-text inline flex-shrink-0" />
|
||||||
|
<span>
|
||||||
|
Rate Variance: {rateVariancePct >= 0 ? `+${rateVariancePct.toFixed(2)}%` : `${rateVariancePct.toFixed(2)}%`} (Safely within 5.0% benchmark threshold)
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Commercial Terms & Statutory Levies Calculator */}
|
||||||
|
<div className="p-3.5 bg-surface-low rounded border border-card-border space-y-2 font-mono">
|
||||||
|
<div className="flex flex-wrap items-center justify-between text-[10px] uppercase font-semibold text-text-muted tracking-wider pb-2 border-b border-card-border gap-2">
|
||||||
|
<span className="flex items-center space-x-1">
|
||||||
|
<Calculator className="w-3.5 h-3.5 text-accent-ochre" />
|
||||||
|
<span>Instant Landed Cost Breakdown (NFR-001 Dual-UOM)</span>
|
||||||
|
</span>
|
||||||
|
<div className="flex items-center space-x-2">
|
||||||
|
<span>Terms:</span>
|
||||||
|
<select
|
||||||
|
value={creditDays}
|
||||||
|
onChange={(e) => setCreditDays(parseInt(e.target.value) || 0)}
|
||||||
|
className="py-0.5 px-1.5 rounded bg-white border border-card-border text-[11px] font-mono text-text-primary"
|
||||||
|
>
|
||||||
|
<option value={0}>Spot (0d)</option>
|
||||||
|
<option value={7}>7 Days Credit</option>
|
||||||
|
<option value={15}>15 Days Credit</option>
|
||||||
|
<option value={30}>30 Days Credit</option>
|
||||||
|
</select>
|
||||||
|
<span className="text-text-primary">Due: {paymentDueDate}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-1 text-xs text-text-primary pt-1">
|
||||||
|
<div className="flex justify-between">
|
||||||
|
<span className="text-text-muted">Base Value ({bookedMt.toFixed(3)} MT • 10 Qtl/MT • ₹ {tradeRate}):</span>
|
||||||
|
<span className="font-semibold">₹ {grossTradeValue.toLocaleString('en-IN', { minimumFractionDigits: 2 })}</span>
|
||||||
|
</div>
|
||||||
|
<div className="flex justify-between">
|
||||||
|
<span className="text-text-muted">APMC Mandi Cess (1.50%):</span>
|
||||||
|
<span>₹ {mandiCess.toLocaleString('en-IN', { minimumFractionDigits: 2 })}</span>
|
||||||
|
</div>
|
||||||
|
<div className="flex justify-between">
|
||||||
|
<span className="text-text-muted">Krishi Kalyan Cess (0.50%):</span>
|
||||||
|
<span>₹ {krishiKalyan.toLocaleString('en-IN', { minimumFractionDigits: 2 })}</span>
|
||||||
|
</div>
|
||||||
|
<div className="flex justify-between">
|
||||||
|
<span className="text-text-muted">Brokerage / Arhat (1.00%):</span>
|
||||||
|
<span>₹ {brokerage.toLocaleString('en-IN', { minimumFractionDigits: 2 })}</span>
|
||||||
|
</div>
|
||||||
|
<div className="flex justify-between pt-2 border-t border-card-border text-sm font-bold text-text-primary">
|
||||||
|
<span>Total Landed Sauda Value:</span>
|
||||||
|
<span className="text-accent-ochre">₹ {totalLandedValue.toLocaleString('en-IN', { minimumFractionDigits: 2 })}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Modal Action Buttons */}
|
||||||
|
<div className="flex items-center justify-end space-x-3 pt-3 border-t border-card-border">
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="secondary"
|
||||||
|
size="sm"
|
||||||
|
onClick={() => setIsModalOpen(false)}
|
||||||
|
className="font-mono text-xs"
|
||||||
|
>
|
||||||
|
Cancel
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
type="submit"
|
||||||
|
variant="primary"
|
||||||
|
size="sm"
|
||||||
|
disabled={isSubmitting || (isVarianceExceeded && !varianceConfirmed)}
|
||||||
|
className="font-mono text-xs"
|
||||||
|
>
|
||||||
|
{isSubmitting ? 'Booking...' : 'Confirm & Issue Sauda'}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
@ -3,7 +3,7 @@ import { tenantStore } from '../../stores/tenantStore';
|
||||||
import { apiClient } from '../../services/api';
|
import { apiClient } from '../../services/api';
|
||||||
import { StatusPill } from '../../components/ui/StatusPill';
|
import { StatusPill } from '../../components/ui/StatusPill';
|
||||||
import { Button } from '../../components/ui/Button';
|
import { Button } from '../../components/ui/Button';
|
||||||
import { FileText, Code2, Eye } from 'lucide-react';
|
import { Eye } from 'lucide-react';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Immutable Transaction Audit Log Viewer Screen.
|
* Immutable Transaction Audit Log Viewer Screen.
|
||||||
|
|
@ -51,7 +51,7 @@ export const AuditLogView: React.FC = () => {
|
||||||
const fetchAuditLogs = async (tenantId: string) => {
|
const fetchAuditLogs = async (tenantId: string) => {
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
setError(null);
|
setError(null);
|
||||||
const resp = await apiClient<{ events: AuditEvent[] }>('/api/v1/audit/events');
|
const resp = await apiClient<{ events: AuditEvent[] }>(`/api/v1/audit/events?tenant_id=${encodeURIComponent(tenantId)}`);
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
if (resp.status === 200 && resp.data?.events) {
|
if (resp.status === 200 && resp.data?.events) {
|
||||||
setEvents(resp.data.events);
|
setEvents(resp.data.events);
|
||||||
|
|
@ -90,6 +90,12 @@ export const AuditLogView: React.FC = () => {
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{loading && (
|
||||||
|
<div className="text-xs text-text-muted font-mono">
|
||||||
|
Refreshing audit log ledger...
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
{/* Audit Log Table adhering to DESIGN.md */}
|
{/* Audit Log Table adhering to DESIGN.md */}
|
||||||
<div className="bg-card-surface border border-card-border rounded shadow-none overflow-hidden">
|
<div className="bg-card-surface border border-card-border rounded shadow-none overflow-hidden">
|
||||||
<table className="min-w-full divide-y divide-card-border">
|
<table className="min-w-full divide-y divide-card-border">
|
||||||
|
|
|
||||||
|
|
@ -2,7 +2,6 @@ import React, { useEffect, useState } from 'react';
|
||||||
import { tenantStore, TenantMembershipInfo } from '../../stores/tenantStore';
|
import { tenantStore, TenantMembershipInfo } from '../../stores/tenantStore';
|
||||||
import { apiClient } from '../../services/api';
|
import { apiClient } from '../../services/api';
|
||||||
import { Building2, ChevronDown } from 'lucide-react';
|
import { Building2, ChevronDown } from 'lucide-react';
|
||||||
import { StatusPill } from '../../components/ui/StatusPill';
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Header Tenant Switcher Dropdown Component.
|
* Header Tenant Switcher Dropdown Component.
|
||||||
|
|
|
||||||
|
|
@ -2,7 +2,7 @@ import React, { useEffect, useState } from 'react';
|
||||||
import { apiClient } from '../../services/api';
|
import { apiClient } from '../../services/api';
|
||||||
import { Button } from '../../components/ui/Button';
|
import { Button } from '../../components/ui/Button';
|
||||||
import { StatusPill } from '../../components/ui/StatusPill';
|
import { StatusPill } from '../../components/ui/StatusPill';
|
||||||
import { Plus, Building2, SlidersHorizontal } from 'lucide-react';
|
import { Plus } from 'lucide-react';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Platform Tenants Management View.
|
* Platform Tenants Management View.
|
||||||
|
|
|
||||||
|
|
@ -3,7 +3,7 @@ import { tenantStore } from '../../stores/tenantStore';
|
||||||
import { apiClient } from '../../services/api';
|
import { apiClient } from '../../services/api';
|
||||||
import { Button } from '../../components/ui/Button';
|
import { Button } from '../../components/ui/Button';
|
||||||
import { StatusPill } from '../../components/ui/StatusPill';
|
import { StatusPill } from '../../components/ui/StatusPill';
|
||||||
import { UserPlus, UserCheck, Shield } from 'lucide-react';
|
import { UserPlus } from 'lucide-react';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Tenant Members & Roles Management View.
|
* Tenant Members & Roles Management View.
|
||||||
|
|
|
||||||
|
|
@ -6,7 +6,9 @@
|
||||||
import { authStore } from '../stores/authStore';
|
import { authStore } from '../stores/authStore';
|
||||||
import { tenantStore } from '../stores/tenantStore';
|
import { tenantStore } from '../stores/tenantStore';
|
||||||
|
|
||||||
const BASE_URL = process.env.VITE_API_URL || 'http://localhost:8000';
|
const BASE_URL = (typeof process !== 'undefined' && process.env?.VITE_API_URL)
|
||||||
|
? process.env.VITE_API_URL
|
||||||
|
: (typeof window !== 'undefined' ? '' : 'http://localhost:8000');
|
||||||
|
|
||||||
export interface ApiResponse<T = any> {
|
export interface ApiResponse<T = any> {
|
||||||
data?: T;
|
data?: T;
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,6 @@
|
||||||
|
/// <reference types="vite/client" />
|
||||||
|
|
||||||
|
declare const process: {
|
||||||
|
env: Record<string, string | undefined>;
|
||||||
|
};
|
||||||
|
|
||||||
|
|
@ -3,6 +3,9 @@ import react from '@vitejs/plugin-react';
|
||||||
|
|
||||||
export default defineConfig({
|
export default defineConfig({
|
||||||
plugins: [react()],
|
plugins: [react()],
|
||||||
|
define: {
|
||||||
|
'process.env': {},
|
||||||
|
},
|
||||||
server: {
|
server: {
|
||||||
port: 3000,
|
port: 3000,
|
||||||
host: '0.0.0.0',
|
host: '0.0.0.0',
|
||||||
|
|
|
||||||
|
|
@ -110,11 +110,97 @@ TEST_PERSONAS: Dict[str, Dict[str, Any]] = {
|
||||||
"name": "Arjun Sharma (Multi-Trader)",
|
"name": "Arjun Sharma (Multi-Trader)",
|
||||||
"roles": ["Mandi Buyer"],
|
"roles": ["Mandi Buyer"],
|
||||||
"tenant_id": "tenant-alpha"
|
"tenant_id": "tenant-alpha"
|
||||||
|
},
|
||||||
|
"buyer@malwa-agri.demo": {
|
||||||
|
"sub": "usr_demo_buyer",
|
||||||
|
"email": "buyer@malwa-agri.demo",
|
||||||
|
"name": "Rajesh Patidar (Buyer)",
|
||||||
|
"roles": ["Mandi Buyer"],
|
||||||
|
"tenant_id": "demo-malwa-agri"
|
||||||
|
},
|
||||||
|
"pmgr@malwa-agri.demo": {
|
||||||
|
"sub": "usr_demo_pmgr",
|
||||||
|
"email": "pmgr@malwa-agri.demo",
|
||||||
|
"name": "Suresh Sharma (Purchase Mgr)",
|
||||||
|
"roles": ["Purchase Manager"],
|
||||||
|
"tenant_id": "demo-malwa-agri"
|
||||||
|
},
|
||||||
|
"yard@malwa-agri.demo": {
|
||||||
|
"sub": "usr_demo_yard",
|
||||||
|
"email": "yard@malwa-agri.demo",
|
||||||
|
"name": "Vikram Singh (Yard Sup)",
|
||||||
|
"roles": ["Yard Supervisor"],
|
||||||
|
"tenant_id": "demo-malwa-agri"
|
||||||
|
},
|
||||||
|
"qc@malwa-agri.demo": {
|
||||||
|
"sub": "usr_demo_qc",
|
||||||
|
"email": "qc@malwa-agri.demo",
|
||||||
|
"name": "Dr. Ananya Joshi (Quality)",
|
||||||
|
"roles": ["Quality Officer"],
|
||||||
|
"tenant_id": "demo-malwa-agri"
|
||||||
|
},
|
||||||
|
"whmgr@malwa-agri.demo": {
|
||||||
|
"sub": "usr_demo_whmgr",
|
||||||
|
"email": "whmgr@malwa-agri.demo",
|
||||||
|
"name": "Gopal Verma (Godown Mgr)",
|
||||||
|
"roles": ["Yard Supervisor"],
|
||||||
|
"tenant_id": "demo-malwa-agri"
|
||||||
|
},
|
||||||
|
"sales@malwa-agri.demo": {
|
||||||
|
"sub": "usr_demo_sales",
|
||||||
|
"email": "sales@malwa-agri.demo",
|
||||||
|
"name": "Rohit Agrawal (Sales Exec)",
|
||||||
|
"roles": ["Sales Executive"],
|
||||||
|
"tenant_id": "demo-malwa-agri"
|
||||||
|
},
|
||||||
|
"smgr@malwa-agri.demo": {
|
||||||
|
"sub": "usr_demo_smgr",
|
||||||
|
"email": "smgr@malwa-agri.demo",
|
||||||
|
"name": "Meera Nair (Sales Mgr)",
|
||||||
|
"roles": ["Sales Manager"],
|
||||||
|
"tenant_id": "demo-malwa-agri"
|
||||||
|
},
|
||||||
|
"logistics@malwa-agri.demo": {
|
||||||
|
"sub": "usr_demo_logistics",
|
||||||
|
"email": "logistics@malwa-agri.demo",
|
||||||
|
"name": "Dinesh Rao (Logistics)",
|
||||||
|
"roles": ["Logistics Coordinator"],
|
||||||
|
"tenant_id": "demo-malwa-agri"
|
||||||
|
},
|
||||||
|
"finance@malwa-agri.demo": {
|
||||||
|
"sub": "usr_demo_finance",
|
||||||
|
"email": "finance@malwa-agri.demo",
|
||||||
|
"name": "Kavita Maheshwari (Accounts)",
|
||||||
|
"roles": ["Accounts Executive"],
|
||||||
|
"tenant_id": "demo-malwa-agri"
|
||||||
|
},
|
||||||
|
"director@malwa-agri.demo": {
|
||||||
|
"sub": "usr_demo_director",
|
||||||
|
"email": "director@malwa-agri.demo",
|
||||||
|
"name": "Harish Patel (Managing Director)",
|
||||||
|
"roles": ["Partner / MD"],
|
||||||
|
"tenant_id": "demo-malwa-agri"
|
||||||
|
},
|
||||||
|
"admin@malwa-agri.demo": {
|
||||||
|
"sub": "usr_demo_admin",
|
||||||
|
"email": "admin@malwa-agri.demo",
|
||||||
|
"name": "Platform Admin (Malwa)",
|
||||||
|
"roles": ["Tenant Administrator"],
|
||||||
|
"tenant_id": "demo-malwa-agri"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
# Pre-seeded disposable tenant fixtures
|
# Pre-seeded disposable tenant fixtures
|
||||||
TEST_TENANTS: Dict[str, Dict[str, Any]] = {
|
TEST_TENANTS: Dict[str, Dict[str, Any]] = {
|
||||||
|
"demo-malwa-agri": {
|
||||||
|
"tenant_id": "demo-malwa-agri",
|
||||||
|
"business_name": "Malwa Agri Trading Corp Pvt Ltd",
|
||||||
|
"legal_identifier": "23AABCM1234F1Z1",
|
||||||
|
"contact_email": "admin@malwa-agri.demo",
|
||||||
|
"primary_mandi": "Indore APMC Yard (MP-IND-01)",
|
||||||
|
"status": "ACTIVE",
|
||||||
|
"created_at": "2026-01-01T00:00:00Z"
|
||||||
|
},
|
||||||
"tenant-alpha": {
|
"tenant-alpha": {
|
||||||
"tenant_id": "tenant-alpha",
|
"tenant_id": "tenant-alpha",
|
||||||
"business_name": "Alpha Agro Traders",
|
"business_name": "Alpha Agro Traders",
|
||||||
|
|
@ -162,6 +248,17 @@ TEST_MEMBERSHIPS: List[Dict[str, Any]] = [
|
||||||
{"membership_id": "mem_005", "tenant_id": "tenant-alpha", "user_id": "usr_01J8K92MLT001", "email": "multi@trader.com", "role": "Mandi Buyer", "status": "ACTIVE"},
|
{"membership_id": "mem_005", "tenant_id": "tenant-alpha", "user_id": "usr_01J8K92MLT001", "email": "multi@trader.com", "role": "Mandi Buyer", "status": "ACTIVE"},
|
||||||
{"membership_id": "mem_006", "tenant_id": "tenant-beta", "user_id": "usr_01J8K92MLT001", "email": "multi@trader.com", "role": "Partner / MD", "status": "ACTIVE"},
|
{"membership_id": "mem_006", "tenant_id": "tenant-beta", "user_id": "usr_01J8K92MLT001", "email": "multi@trader.com", "role": "Partner / MD", "status": "ACTIVE"},
|
||||||
{"membership_id": "mem_007", "tenant_id": "tenant-gamma", "user_id": "usr_01J8K92GAM001", "email": "user@gamma.com", "role": "Mandi Buyer", "status": "ACTIVE"},
|
{"membership_id": "mem_007", "tenant_id": "tenant-gamma", "user_id": "usr_01J8K92GAM001", "email": "user@gamma.com", "role": "Mandi Buyer", "status": "ACTIVE"},
|
||||||
|
{"membership_id": "mem_demo_001", "tenant_id": "demo-malwa-agri", "user_id": "buyer@malwa-agri.demo", "email": "buyer@malwa-agri.demo", "role": "Mandi Buyer", "status": "ACTIVE"},
|
||||||
|
{"membership_id": "mem_demo_002", "tenant_id": "demo-malwa-agri", "user_id": "pmgr@malwa-agri.demo", "email": "pmgr@malwa-agri.demo", "role": "Purchase Manager", "status": "ACTIVE"},
|
||||||
|
{"membership_id": "mem_demo_003", "tenant_id": "demo-malwa-agri", "user_id": "yard@malwa-agri.demo", "email": "yard@malwa-agri.demo", "role": "Yard Supervisor", "status": "ACTIVE"},
|
||||||
|
{"membership_id": "mem_demo_004", "tenant_id": "demo-malwa-agri", "user_id": "qc@malwa-agri.demo", "email": "qc@malwa-agri.demo", "role": "Quality Officer", "status": "ACTIVE"},
|
||||||
|
{"membership_id": "mem_demo_005", "tenant_id": "demo-malwa-agri", "user_id": "whmgr@malwa-agri.demo", "email": "whmgr@malwa-agri.demo", "role": "Yard Supervisor", "status": "ACTIVE"},
|
||||||
|
{"membership_id": "mem_demo_006", "tenant_id": "demo-malwa-agri", "user_id": "sales@malwa-agri.demo", "email": "sales@malwa-agri.demo", "role": "Sales Executive", "status": "ACTIVE"},
|
||||||
|
{"membership_id": "mem_demo_007", "tenant_id": "demo-malwa-agri", "user_id": "smgr@malwa-agri.demo", "email": "smgr@malwa-agri.demo", "role": "Sales Manager", "status": "ACTIVE"},
|
||||||
|
{"membership_id": "mem_demo_008", "tenant_id": "demo-malwa-agri", "user_id": "logistics@malwa-agri.demo", "email": "logistics@malwa-agri.demo", "role": "Logistics Coordinator", "status": "ACTIVE"},
|
||||||
|
{"membership_id": "mem_demo_009", "tenant_id": "demo-malwa-agri", "user_id": "finance@malwa-agri.demo", "email": "finance@malwa-agri.demo", "role": "Accounts Executive", "status": "ACTIVE"},
|
||||||
|
{"membership_id": "mem_demo_010", "tenant_id": "demo-malwa-agri", "user_id": "director@malwa-agri.demo", "email": "director@malwa-agri.demo", "role": "Partner / MD", "status": "ACTIVE"},
|
||||||
|
{"membership_id": "mem_demo_011", "tenant_id": "demo-malwa-agri", "user_id": "admin@malwa-agri.demo", "email": "admin@malwa-agri.demo", "role": "Tenant Administrator", "status": "ACTIVE"},
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue