990 lines
38 KiB
Python
990 lines
38 KiB
Python
"""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.inventory import StockLedgerEntry
|
|
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
|
|
from backend.app.models.bardana import BardanaStockEntry
|
|
from backend.app.models.mandi_compliance import MandiTransitPermit, MandiTaxPaidLedger
|
|
from backend.app.models.farmer_settlement import FarmerBikriParcha
|
|
from backend.app.models.processing import GodownProcessingOrder
|
|
|
|
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 = [
|
|
# Level 6: Phase 2 Statutory Compliance, Bardana & Rural Farmer Settlements
|
|
("godown_processing_orders", "Godown Conditioning Work Orders"),
|
|
("farmer_bikri_parchas", "Farmer Auction Bikri Parchas"),
|
|
("bardana_stock_entries", "Bardana Packaging Stock Entries"),
|
|
("mandi_transit_permits", "Mandi Samiti Transit Permits (Anugya Patra)"),
|
|
("mandi_tax_paid_ledger", "Single-Point Mandi Tax Paid Ledger"),
|
|
|
|
# Level 5: Analytics, Alerts & Historical Reporting
|
|
("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"),
|
|
("stock_ledger_entries", "Double-Entry Stock Ledger"),
|
|
("stock_adjustments", "Warehouse Stock Adjustments"),
|
|
("inter_godown_transfers", "Inter-Godown Transfers"),
|
|
("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"),
|
|
]
|
|
|
|
|
|
DEMO_PERSONAS = [
|
|
("mem_demo_011", "usr_demo_admin", "admin@malwa-agri.demo", "Platform Admin (Malwa)", "Tenant Administrator"),
|
|
("mem_demo_001", "usr_demo_buyer", "buyer@malwa-agri.demo", "Rajesh Patidar (Buyer)", "Mandi Buyer"),
|
|
("mem_demo_002", "usr_demo_pmgr", "pmgr@malwa-agri.demo", "Suresh Sharma (Purchase Mgr)", "Purchase Manager"),
|
|
("mem_demo_003", "usr_demo_yard", "yard@malwa-agri.demo", "Vikram Singh (Yard Sup)", "Yard Supervisor"),
|
|
("mem_demo_004", "usr_demo_qc", "qc@malwa-agri.demo", "Dr. Ananya Joshi (Quality)", "Quality Officer"),
|
|
("mem_demo_005", "usr_demo_whmgr", "whmgr@malwa-agri.demo", "Gopal Verma (Godown Mgr)", "Yard Supervisor"),
|
|
("mem_demo_006", "usr_demo_sales", "sales@malwa-agri.demo", "Rohit Agrawal (Sales Exec)", "Sales Executive"),
|
|
("mem_demo_007", "usr_demo_smgr", "smgr@malwa-agri.demo", "Meera Nair (Sales Mgr)", "Sales Manager"),
|
|
("mem_demo_008", "usr_demo_logistics", "logistics@malwa-agri.demo", "Dinesh Rao (Logistics)", "Logistics Coordinator"),
|
|
("mem_demo_009", "usr_demo_finance", "finance@malwa-agri.demo", "Kavita Maheshwari (Accounts)", "Accounts Executive"),
|
|
("mem_demo_010", "usr_demo_director", "director@malwa-agri.demo", "Harish Patel (Managing Director)", "Partner / MD"),
|
|
("mem_demo_012", "usr_demo_compliance", "compliance@malwa-agri.demo", "Sunita Deshmukh (Mandi Compliance)", "Mandi Compliance Officer"),
|
|
]
|
|
|
|
|
|
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"
|
|
)
|
|
for mem_id, user_id, email, name, role in DEMO_PERSONAS:
|
|
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_PERSONAS)
|
|
|
|
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
|
|
for mem_id, user_id, email, name, role in DEMO_PERSONAS:
|
|
store.memberships[mem_id] = TenantMembership(
|
|
membership_id=mem_id,
|
|
tenant_id=tenant_id,
|
|
user_id=user_id,
|
|
email=email,
|
|
role=role,
|
|
status="ACTIVE"
|
|
)
|
|
|
|
# Also register/restore mock identity personas for offline authentication
|
|
try:
|
|
from sandbox.identity_mock import TEST_PERSONAS
|
|
for mem_id, user_id, email, name, role in DEMO_PERSONAS:
|
|
TEST_PERSONAS[email] = {
|
|
"sub": user_id,
|
|
"email": email,
|
|
"name": name,
|
|
"roles": [role],
|
|
"tenant_id": tenant_id
|
|
}
|
|
except Exception:
|
|
pass
|
|
|
|
|
|
# 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"
|
|
),
|
|
TradingCounterparty(
|
|
tenant_id=tenant_id,
|
|
name="Ram Prasad Kisan",
|
|
counterparty_type="FARMER",
|
|
pan_number="FORM60",
|
|
bank_account_number="",
|
|
bank_ifsc_code="",
|
|
bank_name="",
|
|
phone="9826099888",
|
|
credit_terms_days=0,
|
|
is_cash_settlement=True,
|
|
id="cpty-farmer-form60-01"
|
|
),
|
|
]
|
|
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"
|
|
),
|
|
TransportVehicle(
|
|
tenant_id=tenant_id,
|
|
reg_no="RJ20GA3311",
|
|
make_model="BharatBenz 2823R",
|
|
payload_capacity_mt=Decimal("28.000"),
|
|
ownership_type="Contract",
|
|
transporter_name="Rajasthan Freight Lines",
|
|
status="Available",
|
|
fitness_expiry="2026-10-01",
|
|
vehicle_id="veh-demo-03"
|
|
),
|
|
]
|
|
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("GRN_ISSUED")
|
|
ge_dict = gate_entry.to_dict()
|
|
ge_dict.update({
|
|
"gate_pass_id": gate_entry.id,
|
|
"pass_number": gate_entry.gate_pass_number,
|
|
"gross_weight_mt": 35.0,
|
|
"tare_weight_mt": 10.0,
|
|
"net_weight_mt": 25.0,
|
|
"bag_count": 500,
|
|
"lot_id": "LOT-SOY-2026-001",
|
|
"grn_id": "GRN-2026-001",
|
|
})
|
|
store.insert("inward_gate_entries", tenant_id, ge_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("25.000"),
|
|
grade="FAQ",
|
|
lot_id="lot-demo-001"
|
|
)
|
|
lot.qc_status = "QUALITY_HOLD"
|
|
lot.current_quantity_mt = Decimal("25.000")
|
|
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("0.000")
|
|
sales_order.status = "CONFIRMED"
|
|
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("SCHEDULED")
|
|
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())
|
|
|
|
# 8b. Double-Entry Stock Ledger Movements (GRN Inward + Bilty Outward)
|
|
sle_inward = StockLedgerEntry(
|
|
tenant_id=tenant_id,
|
|
warehouse_id="godown-demo-indore",
|
|
commodity_id="c0a80123-demo-0000-0000-000000000001",
|
|
variety="Yellow FAQ",
|
|
grade="FAQ",
|
|
transaction_type="INWARD",
|
|
reference_id=grn.grn_number,
|
|
opening_mt=Decimal("3125.375"),
|
|
opening_bags=62500,
|
|
quantity_mt=Decimal("24.625"),
|
|
bags=500,
|
|
entry_id="sle-demo-inward-001"
|
|
)
|
|
store.insert("stock_ledger_entries", tenant_id, sle_inward.to_dict())
|
|
|
|
sle_outward = StockLedgerEntry(
|
|
tenant_id=tenant_id,
|
|
warehouse_id="godown-demo-indore",
|
|
commodity_id="c0a80123-demo-0000-0000-000000000001",
|
|
variety="Yellow FAQ",
|
|
grade="FAQ",
|
|
transaction_type="OUTWARD",
|
|
reference_id=bilty.bilty_number,
|
|
opening_mt=Decimal("3150.000"),
|
|
opening_bags=63000,
|
|
quantity_mt=Decimal("24.000"),
|
|
bags=480,
|
|
entry_id="sle-demo-outward-001"
|
|
)
|
|
store.insert("stock_ledger_entries", tenant_id, sle_outward.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())
|
|
|
|
# 12. Phase 2 Domain Expansion: Bardana, APMC Transit Permits, Farmer Settlements & Processing
|
|
tax_paid_entry = MandiTaxPaidLedger(
|
|
tenant_id=tenant_id,
|
|
commodity_id="SOY",
|
|
opening_tax_paid_mt=Decimal("125.000"),
|
|
dispatched_tax_paid_mt=Decimal("0.000"),
|
|
ledger_id="ledger-taxpaid-demo-001"
|
|
)
|
|
store.insert("mandi_tax_paid_ledger", tenant_id, tax_paid_entry.to_dict())
|
|
|
|
anugya_permit = MandiTransitPermit(
|
|
tenant_id=tenant_id,
|
|
permit_number="ANUGYA-2026-HIST-01",
|
|
mandi_samiti_code="MP-IND-01",
|
|
dispatch_id=dispatch.id,
|
|
vehicle_reg_no="MP09AB1234",
|
|
commodity_id="SOY",
|
|
quantity_mt=Decimal("20.000"),
|
|
bag_count=400,
|
|
destination_city="Bhopal",
|
|
issued_at=datetime.now(timezone.utc) - timedelta(hours=12),
|
|
valid_until=datetime.now(timezone.utc) + timedelta(hours=24),
|
|
tax_paid_status="SHULK_CHHUKTA",
|
|
permit_id="permit-demo-hist-01"
|
|
)
|
|
store.insert("mandi_transit_permits", tenant_id, anugya_permit.to_dict())
|
|
|
|
bardana_entries = [
|
|
BardanaStockEntry(
|
|
tenant_id=tenant_id,
|
|
godown_id="godown-demo-indore",
|
|
bag_type="NEW_JUTE_50KG",
|
|
transaction_type="PURCHASE_RECEIPT",
|
|
reference_id="INV-BARDANA-2026-001",
|
|
opening_count=0,
|
|
inward_count=5000,
|
|
entry_id="bardana-demo-001"
|
|
),
|
|
BardanaStockEntry(
|
|
tenant_id=tenant_id,
|
|
godown_id="godown-demo-indore",
|
|
bag_type="HDPE_50KG",
|
|
transaction_type="PURCHASE_RECEIPT",
|
|
reference_id="INV-BARDANA-2026-002",
|
|
opening_count=0,
|
|
inward_count=2500,
|
|
entry_id="bardana-demo-002"
|
|
),
|
|
]
|
|
for b in bardana_entries:
|
|
store.insert("bardana_stock_entries", tenant_id, b.to_dict())
|
|
|
|
bikri_parcha = FarmerBikriParcha(
|
|
tenant_id=tenant_id,
|
|
parcha_number="PAR-2026-001",
|
|
auction_date=date.today(),
|
|
farmer_id="cpty-farmer-form60-01",
|
|
vehicle_number="MP09GH4521",
|
|
commodity_id="SOY",
|
|
variety="Yellow FAQ",
|
|
bag_count=100,
|
|
gross_weight_kg=Decimal("10000.00"),
|
|
tare_bags_kg=Decimal("50.00"),
|
|
auction_rate_per_qtl=Decimal("4500.00"),
|
|
hamali_rate_per_bag=Decimal("4.00"),
|
|
tolai_rate_per_bag=Decimal("2.00"),
|
|
advance_principal_netted=Decimal("10000.00"),
|
|
advance_interest_netted=Decimal("500.00"),
|
|
parcha_id="parcha-demo-001"
|
|
)
|
|
# Staged at ISSUED status without marking disbursed so presenter can demonstrate 24h compliance countdown & live disbursement
|
|
store.insert("farmer_bikri_parchas", tenant_id, bikri_parcha.to_dict())
|
|
|
|
processing_order = GodownProcessingOrder(
|
|
tenant_id=tenant_id,
|
|
order_number="GPO-2026-001",
|
|
godown_id="godown-demo-indore",
|
|
process_type="MECHANICAL_CLEANING",
|
|
input_lot_id=lot.id,
|
|
input_weight_mt=Decimal("25.000"),
|
|
output_primary_lot_id="LOT-SOY-CLEANED-001",
|
|
output_primary_mt=Decimal("24.250"),
|
|
output_primary_grade="FAQ",
|
|
waste_weight_mt=Decimal("0.500"),
|
|
shrinkage_loss_mt=Decimal("0.250"),
|
|
status="COMPLETED",
|
|
order_id="proc-order-demo-001"
|
|
)
|
|
store.insert("godown_processing_orders", tenant_id, processing_order.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,
|
|
"stock_ledger_entries": 2,
|
|
"quality_inspections": 1,
|
|
"sales_orders": 1,
|
|
"dispatches": 1,
|
|
"bilties": 1,
|
|
"subledger_entries": 1,
|
|
"payables": 1,
|
|
"cess_vouchers": 1,
|
|
"alerts": len(alerts),
|
|
"mandi_tax_paid_ledgers": 1,
|
|
"mandi_transit_permits": 1,
|
|
"bardana_stock_entries": len(bardana_entries),
|
|
"farmer_bikri_parchas": 1,
|
|
"godown_processing_orders": 1,
|
|
}
|
|
logger.info("Demo dataset seeded successfully for tenant '%s': %s", tenant_id, summary)
|
|
return summary
|