Fixed hardcoded data and ensured seed data would be used. Checkpointing to resume process quality gates update tomorrow

This commit is contained in:
Prashant Shendre 2026-10-15 19:51:21 +05:30
parent ca0235f28c
commit 67d24daac6
6 changed files with 1211 additions and 351 deletions

View File

@ -76,11 +76,11 @@ class ProcurementController:
ctx = auth_res["context"]
# 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):
return {
"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
}

798
backend/app/db/demo_seed.py Normal file
View File

@ -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

View File

@ -71,6 +71,12 @@ class InMemoryTenantStorage:
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:
"""Sets transaction-local tenant isolation context (SET LOCAL app.current_tenant_id)."""
self.active_tenant_id = tenant_id

View File

@ -1017,9 +1017,33 @@ try:
status_code = result.pop("status_code", 200)
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:

View File

@ -3,8 +3,9 @@
*
* 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 } from 'react';
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';
@ -17,7 +18,8 @@ import {
ArrowUpRight,
CheckCircle2,
AlertTriangle,
Scale
Scale,
RefreshCw
} from 'lucide-react';
export interface MarketCommodityRate {
@ -34,69 +36,34 @@ export interface MarketCommodityRate {
status: 'PUBLISHED' | 'HOLIDAY' | 'DRAFT';
}
const DEFAULT_RATES: MarketCommodityRate[] = [
{
id: 'mkt-001',
commodity_code: 'SOY',
commodity_name: 'Soyabean',
variety: 'Yellow Desi',
grade: 'FAQ',
arrivals_mt: 620.0,
arrivals_bags: 12400,
min_rate: 4550.0,
max_rate: 4900.0,
modal_rate: 4800.0,
status: 'PUBLISHED'
},
{
id: 'mkt-002',
commodity_code: 'CHN',
commodity_name: 'Chana',
variety: 'Desi Bold',
grade: 'FAQ',
arrivals_mt: 280.0,
arrivals_bags: 5600,
min_rate: 5800.0,
max_rate: 6150.0,
modal_rate: 6000.0,
status: 'PUBLISHED'
},
{
id: 'mkt-003',
commodity_code: 'WHT',
commodity_name: 'Wheat',
variety: 'Lokwan',
grade: 'FAQ',
arrivals_mt: 450.0,
arrivals_bags: 9000,
min_rate: 2350.0,
max_rate: 2550.0,
modal_rate: 2450.0,
status: 'PUBLISHED'
},
{
id: 'mkt-004',
commodity_code: 'MST',
commodity_name: 'Mustard',
variety: '42% Oil',
grade: 'FAQ',
arrivals_mt: 190.0,
arrivals_bags: 3800,
min_rate: 5200.0,
max_rate: 5550.0,
modal_rate: 5400.0,
status: 'PUBLISHED'
}
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>('Indore APMC, Madhya Pradesh');
const [observationDate, setObservationDate] = useState<string>('2026-10-15');
const [rates, setRates] = useState<MarketCommodityRate[]>(DEFAULT_RATES);
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);
@ -123,6 +90,53 @@ export const MarketDeskView: React.FC<MarketDeskViewProps> = ({ onNavigateToSaud
}
}, [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;
@ -132,15 +146,15 @@ export const MarketDeskView: React.FC<MarketDeskViewProps> = ({ onNavigateToSaud
try {
const payload = {
mandi_id: 'mandi-indore-01',
commodity_id: formCommodity === 'Soyabean' ? 'SOY' : formCommodity === 'Chana' ? 'CHN' : 'WHT',
mandi_id: selectedMandi,
commodity_id: formCommodity === 'Soyabean' ? 'SOY' : formCommodity === 'Chana' ? 'CHN' : formCommodity === 'Mustard' ? 'MST' : 'WHT',
variety: formVariety,
grade: 'FAQ',
observation_date: observationDate,
arrival_mt: formArrivalsMt,
min_rate: formMinRate,
max_rate: formMaxRate,
modal_rate: formModalRate,
arrival_mt: Number(formArrivalsMt),
min_rate: Number(formMinRate),
max_rate: Number(formMaxRate),
modal_rate: Number(formModalRate),
source: 'APMC_BULLETIN'
};
@ -153,34 +167,10 @@ export const MarketDeskView: React.FC<MarketDeskViewProps> = ({ onNavigateToSaud
if (resp.status === 201 || resp.status === 200 || !resp.error) {
setNotification({
type: 'success',
message: `Daily rate observation recorded for ${formCommodity} (${formVariety}) at ₹ ${formModalRate.toLocaleString('en-IN')}/Qtl.`
message: `Daily rate observation recorded for ${formCommodity} (${formVariety}) at ₹ ${Number(formModalRate).toLocaleString('en-IN')}/Qtl.`
});
// Update local table view
const existingIdx = rates.findIndex(r => r.commodity_name === formCommodity);
const updatedRate: MarketCommodityRate = {
id: `mkt-obs-${Date.now()}`,
commodity_code: payload.commodity_id,
commodity_name: formCommodity,
variety: formVariety,
grade: 'FAQ',
arrivals_mt: formArrivalsMt,
arrivals_bags: Math.round(formArrivalsMt * 20),
min_rate: formMinRate,
max_rate: formMaxRate,
modal_rate: formModalRate,
status: 'PUBLISHED'
};
if (existingIdx >= 0) {
const next = [...rates];
next[existingIdx] = updatedRate;
setRates(next);
} else {
setRates([updatedRate, ...rates]);
}
setIsModalOpen(false);
await fetchRates();
} else {
setNotification({
type: 'error',
@ -198,7 +188,8 @@ export const MarketDeskView: React.FC<MarketDeskViewProps> = ({ onNavigateToSaud
};
const totalArrivalsMt = rates.reduce((acc, r) => acc + r.arrivals_mt, 0);
const soyRate = rates.find(r => r.commodity_name === 'Soyabean') || rates[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">
@ -239,9 +230,9 @@ export const MarketDeskView: React.FC<MarketDeskViewProps> = ({ onNavigateToSaud
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"
>
<option value="Indore APMC, Madhya Pradesh">Indore APMC, Madhya Pradesh (Main Auction Yard)</option>
<option value="Kota APMC, Rajasthan">Kota APMC, Rajasthan (Grain Mandi)</option>
<option value="Unjha APMC, Gujarat">Unjha APMC, Gujarat (Spices & Oilseed)</option>
{MANDI_OPTIONS.map((m) => (
<option key={m.id} value={m.id}>{m.name}</option>
))}
</select>
</div>
@ -255,6 +246,17 @@ export const MarketDeskView: React.FC<MarketDeskViewProps> = ({ onNavigateToSaud
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">
@ -290,13 +292,13 @@ export const MarketDeskView: React.FC<MarketDeskViewProps> = ({ onNavigateToSaud
</div>
<div className="flex items-baseline space-x-2">
<span className="text-2xl font-bold font-mono text-text-primary">
₹ {soyRate.modal_rate.toLocaleString('en-IN', { minimumFractionDigits: 2 })}
{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" />
Active Mandi Clearing Rate
{soyRate ? 'Active Mandi Clearing Rate' : 'No Active Bulletin'}
</div>
</div>
@ -306,9 +308,11 @@ export const MarketDeskView: React.FC<MarketDeskViewProps> = ({ onNavigateToSaud
</div>
<div className="flex items-baseline space-x-2">
<span className="text-2xl font-bold font-mono text-text-primary">
{soyRate.arrivals_bags.toLocaleString('en-IN')}
{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>
<span className="text-xs text-text-muted font-mono">Bags ({soyRate.arrivals_mt.toFixed(1)} MT)</span>
</div>
<div className="text-[11px] text-text-muted font-mono mt-1">
50 kg standard jute bags
@ -326,7 +330,7 @@ export const MarketDeskView: React.FC<MarketDeskViewProps> = ({ onNavigateToSaud
<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 4 Monitored Commodities
Across {rates.length} Monitored Commodities
</div>
</div>
@ -335,10 +339,10 @@ export const MarketDeskView: React.FC<MarketDeskViewProps> = ({ onNavigateToSaud
Mandi Samiti Status
</div>
<div className="flex items-baseline space-x-2 mt-1">
<StatusPill status="normal" label="3 Open Auctions" />
<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">
Indore Yard Floor A Active
{selectedMandiObj.name.split(',')[0]} Yard Active
</div>
</div>
</div>
@ -346,7 +350,7 @@ export const MarketDeskView: React.FC<MarketDeskViewProps> = ({ onNavigateToSaud
{/* Commodity Rate Blotter Table (SCREEN-MKT-001) */}
<Card
title="Daily Mandi Arrival & Price Bulletin"
subtitle={`Official APMC yard arrivals and clearing price ranges (${selectedMandi} • ${observationDate})`}
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 &bull; FR-MKT-002
@ -354,70 +358,90 @@ export const MarketDeskView: React.FC<MarketDeskViewProps> = ({ onNavigateToSaud
}
>
<div className="overflow-x-auto">
<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} &bull; <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>
{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>
))}
</tbody>
</table>
</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} &bull; <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>
@ -456,7 +480,7 @@ export const MarketDeskView: React.FC<MarketDeskViewProps> = ({ onNavigateToSaud
<input
type="text"
disabled
value={selectedMandi}
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>
@ -492,6 +516,11 @@ export const MarketDeskView: React.FC<MarketDeskViewProps> = ({ onNavigateToSaud
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);
@ -616,4 +645,3 @@ export const MarketDeskView: React.FC<MarketDeskViewProps> = ({ onNavigateToSaud
</div>
);
};

View File

@ -3,8 +3,9 @@
*
* 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 } from 'react';
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';
@ -16,7 +17,8 @@ import {
CheckCircle2,
Calculator,
Search,
Filter
Filter,
RefreshCw
} from 'lucide-react';
export interface SaudaContract {
@ -42,108 +44,18 @@ export interface SaudaContract {
status: 'ACTIVE' | 'PENDING' | 'CLOSED' | 'REJECTED';
}
const DEFAULT_SAUDAS: SaudaContract[] = [
{
id: 'sda-rec-01',
sauda_number: 'SDA-2026-001',
contract_date: '2026-10-15',
delivery_due_date: '2026-10-22',
supplier_name: 'Rameshwar Patidar (Farmer / Arhatiya - Neemuch)',
mandi_hub: 'Indore APMC',
commodity_name: 'Soyabean',
variety: 'Yellow Desi',
grade: 'FAQ',
booked_quantity_mt: 25.0,
estimated_bags: 500,
trade_rate_per_qtl: 4850.0,
gross_value: 1212500.0,
mandi_cess: 18187.5,
krishi_kalyan: 6062.5,
brokerage: 12125.0,
landed_value: 1248875.0,
credit_days: 7,
fulfilled_pct: 0.0,
status: 'ACTIVE'
},
{
id: 'sda-rec-02',
sauda_number: 'SDA-26-00142',
contract_date: '2026-10-14',
delivery_due_date: '2026-10-20',
supplier_name: 'Kisan Agro Traders (SUP-0042)',
mandi_hub: 'Kota APMC',
commodity_name: 'Soyabean',
variety: 'Yellow Desi',
grade: 'FAQ',
booked_quantity_mt: 50.0,
estimated_bags: 1000,
trade_rate_per_qtl: 4750.0,
gross_value: 2375000.0,
mandi_cess: 35625.0,
krishi_kalyan: 11875.0,
brokerage: 23750.0,
landed_value: 2446250.0,
credit_days: 15,
fulfilled_pct: 60.0,
status: 'ACTIVE'
},
{
id: 'sda-rec-03',
sauda_number: 'SDA-26-00143',
contract_date: '2026-10-13',
delivery_due_date: '2026-10-18',
supplier_name: 'Mewar Krishi Sangh',
mandi_hub: 'Unjha APMC',
commodity_name: 'Cumin/Jeera',
variety: 'Special Bold',
grade: 'FAQ',
booked_quantity_mt: 20.0,
estimated_bags: 400,
trade_rate_per_qtl: 24500.0,
gross_value: 4900000.0,
mandi_cess: 73500.0,
krishi_kalyan: 24500.0,
brokerage: 49000.0,
landed_value: 5047000.0,
credit_days: 5,
fulfilled_pct: 0.0,
status: 'PENDING'
},
{
id: 'sda-rec-04',
sauda_number: 'SDA-26-00144',
contract_date: '2026-10-11',
delivery_due_date: '2026-10-16',
supplier_name: 'Malwa Agro Corp',
mandi_hub: 'Indore APMC',
commodity_name: 'Wheat',
variety: 'Lokwan',
grade: 'FAQ',
booked_quantity_mt: 100.0,
estimated_bags: 2000,
trade_rate_per_qtl: 2420.0,
gross_value: 2420000.0,
mandi_cess: 36300.0,
krishi_kalyan: 12100.0,
brokerage: 24200.0,
landed_value: 2492600.0,
credit_days: 10,
fulfilled_pct: 100.0,
status: 'CLOSED'
}
];
const BENCHMARK_MODAL_RATE = 4800.0; // Indore APMC Soybean modal clearing rate benchmark
export const SaudaProcurementView: React.FC = () => {
const [saudas, setSaudas] = useState<SaudaContract[]>(DEFAULT_SAUDAS);
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>('2026-10-15');
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)');
@ -175,13 +87,99 @@ export const SaudaProcurementView: React.FC = () => {
const isVarianceExceeded = rateVariancePct > 5.0;
// Commercial Math per NFR-001 (Dual UOM, Statutory Rounding)
// Base Value = MT * 10 Qtl/MT * Rate/Qtl
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) {
@ -198,10 +196,13 @@ export const SaudaProcurementView: React.FC = () => {
sauda_number: generatedSaudaNumber,
contract_date: contractDate,
delivery_due_date: paymentDueDate,
supplier_id: 'sup-patidar-01',
mandi_id: 'mandi-indore-01',
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: 'SOY',
commodity_id: commodity.includes('SOY') ? 'SOY' : commodity.includes('CHN') ? 'CHN' : commodity.includes('MST') ? 'MST' : 'WHT',
variety: variety,
grade: 'FAQ',
booked_quantity_mt: bookedMt,
@ -222,45 +223,25 @@ export const SaudaProcurementView: React.FC = () => {
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload)
});
if (resp.error) {
// Log non-blocking backend response while preserving offline mock UI state
console.warn('Backend sauda booking response:', resp.error);
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.'
});
}
const newContract: SaudaContract = {
id: `sda-${Date.now()}`,
sauda_number: generatedSaudaNumber,
contract_date: contractDate,
delivery_due_date: paymentDueDate,
supplier_name: supplierName,
mandi_hub: sourcingMandi.split(',')[0],
commodity_name: commodity.split(' ')[0],
variety: variety,
grade: 'FAQ',
booked_quantity_mt: bookedMt,
estimated_bags: estimatedBags,
trade_rate_per_qtl: tradeRate,
gross_value: grossTradeValue,
landed_value: totalLandedValue,
mandi_cess: mandiCess,
krishi_kalyan: krishiKalyan,
brokerage: brokerage,
credit_days: creditDays,
fulfilled_pct: 0.0,
status: 'ACTIVE'
};
setSaudas([newContract, ...saudas]);
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);
} catch (err: any) {
setNotification({
type: 'error',
@ -327,7 +308,7 @@ export const SaudaProcurementView: React.FC = () => {
<span className="text-xs text-text-muted font-mono">Contracts</span>
</div>
<div className="text-[11px] text-text-muted font-mono mt-1">
Indore & Kota Mandis
{activeCount > 0 ? 'Indore & Kota Mandis' : 'No Active Contracts'}
</div>
</div>
@ -363,50 +344,61 @@ export const SaudaProcurementView: React.FC = () => {
<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 Benchmark Modal
Statutory Mandi Cess Levies
</div>
<div className="flex items-baseline space-x-2">
<span className="text-2xl font-bold font-mono text-accent-ochre">
₹ {BENCHMARK_MODAL_RATE.toLocaleString('en-IN', { minimumFractionDigits: 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">/ Qtl</span>
<span className="text-xs text-text-muted font-mono">Lakhs</span>
</div>
<div className="text-[11px] text-status-normal-text font-mono mt-1">
Real-time Market Desk Peg
<div className="text-[11px] text-text-muted font-mono mt-1">
1.50% MP APMC Mandi Samiti Cess
</div>
</div>
</div>
{/* Main Register Filter & Action Bar */}
{/* 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">
<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 text-text-primary focus:outline-none focus:ring-1 focus:ring-accent-ochre"
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-1.5">
<Filter className="w-3.5 h-3.5 text-text-muted" />
<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-2.5 rounded bg-white border border-card-border text-xs font-mono text-text-primary focus:outline-none focus:ring-1 focus:ring-accent-ochre"
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</option>
<option value="ALL">All Statuses ({saudas.length})</option>
<option value="ACTIVE">Active</option>
<option value="PENDING">Pending</option>
<option value="CLOSED">Closed</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>
<div className="flex items-center space-x-3">
<Button
variant="primary"
size="sm"
@ -430,31 +422,43 @@ export const SaudaProcurementView: React.FC = () => {
}
>
<div className="overflow-x-auto">
<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.length === 0 ? (
{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>
<td colSpan={11} className="py-8 text-center text-xs text-text-muted font-mono">
No sauda contracts found matching criteria.
</td>
<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>
) : (
filteredSaudas.map((sauda) => (
</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}
@ -497,10 +501,10 @@ export const SaudaProcurementView: React.FC = () => {
/>
</td>
</tr>
))
)}
</tbody>
</table>
))}
</tbody>
</table>
)}
</div>
</Card>