c_agri_trade/process/scripts/demo/seed_demo_data.py

690 lines
26 KiB
Python
Executable File

#!/usr/bin/env python3
"""Agriculture Trading Backoffice (ATB) — Demo Data Ingestion 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).
Features:
- Multi-Tenant Safe: Only seeds data tagged for the demo tenant.
- End-to-End Cohesive: Seeds connected transaction spine from Mandi rate to Bilty & Ledgers.
- 20-Day Trend Snapshots: Generates mature data for the Executive Dashboard & Moving Averages.
- Idempotent: Can clean prior demo data before re-seeding with `--clean-first`.
"""
import argparse
from datetime import datetime, date, timedelta, timezone
from decimal import Decimal
import os
import sys
import uuid
# Ensure project_code is importable
CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
PROJECT_ROOT = os.path.abspath(os.path.join(CURRENT_DIR, "..", ".."))
PROJECT_CODE = os.path.join(PROJECT_ROOT, "project_code")
if PROJECT_CODE not in sys.path:
sys.path.insert(0, PROJECT_CODE)
try:
from backend.app.db.session import storage, InMemoryTenantStorage
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.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
from sandbox.identity_mock import mock_idp, TEST_PERSONAS
except ImportError as e:
print(f"[ERROR] Failed to import backend components from {PROJECT_CODE}: {e}", file=sys.stderr)
sys.exit(1)
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"
def purge_existing_demo_tenant(store: InMemoryTenantStorage, tenant_id: str) -> None:
"""Safely purges any existing demo tenant data before re-seeding."""
if not tenant_id.startswith("demo-"):
raise ValueError(f"Safety Rail: Refusing to purge non-demo tenant '{tenant_id}'")
print(f"[CLEANUP] Purging previous records for demo tenant '{tenant_id}'...")
collections_to_clean = [
"daily_trading_snapshots",
"operational_alerts",
"party_subledger_entries",
"dispatch_bilties",
"outward_weighments",
"outbound_dispatches",
"sales_order_allocations",
"customer_sales_orders",
"quality_inspections",
"inventory_lots",
"goods_receipt_notes",
"weighbridge_slips",
"inward_gate_entries",
"procurement_sauda",
"market_observations",
"transport_fleet",
"fleet_vehicles",
"tenant_operating_policies",
"operating_policies",
"counterparties",
"godowns",
"commodity_varieties",
"commodities",
]
for coll in collections_to_clean:
if coll in store._collections and tenant_id in store._collections[coll]:
del store._collections[coll][tenant_id]
# 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 tenant
store.tenants.pop(tenant_id, None)
print(f"[CLEANUP] Successfully purged prior records for '{tenant_id}'.")
def seed_demo_tenant(store: InMemoryTenantStorage, tenant_id: str = DEFAULT_TENANT_ID) -> None:
"""Provisions demo tenant profile and 10 RBAC persona memberships."""
print(f"[SEED] Provisioning Demo Tenant: '{DEFAULT_BUSINESS_NAME}' ({tenant_id})...")
tenant = Tenant(
tenant_id=tenant_id,
business_name=DEFAULT_BUSINESS_NAME,
legal_identifier=DEFAULT_LEGAL_ID,
contact_email=DEFAULT_ADMIN_EMAIL,
primary_mandi=DEFAULT_PRIMARY_MANDI,
status="ACTIVE"
)
store.save_tenant(tenant)
# 10 Standard PRD Personas for Malwa Agri Trading Corp
personas = [
("buyer@malwa-agri.demo", "Rajesh Patidar (Buyer)", "Mandi Buyer"),
("pmgr@malwa-agri.demo", "Suresh Sharma (Purchase Mgr)", "Purchase Manager"),
("yard@malwa-agri.demo", "Vikram Singh (Yard Sup)", "Yard Supervisor"),
("qc@malwa-agri.demo", "Dr. Ananya Joshi (Quality)", "Quality Officer"),
("whmgr@malwa-agri.demo", "Gopal Verma (Godown Mgr)", "Yard Supervisor"),
("sales@malwa-agri.demo", "Rohit Agrawal (Sales Exec)", "Sales Executive"),
("smgr@malwa-agri.demo", "Meera Nair (Sales Mgr)", "Sales Manager"),
("logistics@malwa-agri.demo", "Dinesh Rao (Logistics)", "Logistics Coordinator"),
("finance@malwa-agri.demo", "Kavita Maheshwari (Accounts)", "Accounts Executive"),
("director@malwa-agri.demo", "Harish Patel (Managing Director)", "Partner / MD"),
("admin@malwa-agri.demo", "Platform Admin (Malwa)", "Tenant Administrator"),
]
for email, name, role in personas:
mem = TenantMembership(
tenant_id=tenant_id,
user_id=email,
email=email,
role=role,
status="ACTIVE"
)
store.save_membership(mem)
# Register mock persona in identity mock so passwordless mock auth works
TEST_PERSONAS[email] = {
"sub": f"usr_{uuid.uuid4().hex[:12]}",
"email": email,
"name": name,
"roles": [role],
"tenant_id": tenant_id
}
print(f"[SEED] Registered {len(personas)} RBAC persona accounts with active memberships.")
def seed_master_data(store: InMemoryTenantStorage, tenant_id: str) -> None:
"""Seeds Commodities, Godown Warehouses, Counterparties, Fleet and Operating Policies."""
print("[SEED] Seeding Agricultural Master Data...")
# 1. Commodities
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"
),
]
for c in commodities:
store.insert("commodities", tenant_id, c.to_dict())
# Varieties
varieties = [
CommodityVariety(tenant_id=tenant_id, commodity_id=commodities[0].id, code="VAR-SOY-01", name="Yellow 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 Chana FAQ", id="var-demo-003"),
CommodityVariety(tenant_id=tenant_id, commodity_id=commodities[2].id, code="VAR-WHT-01", name="Sharbati Premium", id="var-demo-004"),
]
for v in varieties:
store.insert("commodity_varieties", tenant_id, v.to_dict())
# 2. Godowns
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())
# 3. Counterparties (Suppliers & Customers)
counterparties = [
TradingCounterparty(
tenant_id=tenant_id,
name="Rameshwar Patidar (Farmer)",
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="Kailash & Sons Mandi Dalal",
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=7,
id="cpty-demo-supplier-02"
),
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())
# 4. Fleet Vehicles
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"
),
# Expired fitness vehicle to showcase gating!
TransportVehicle(
tenant_id=tenant_id,
reg_no="RJ20GA3311",
make_model="Eicher Pro 3019",
payload_capacity_mt=Decimal("19.000"),
ownership_type="Contract",
transporter_name="Marwar Roadlines",
status="Available",
fitness_expiry=(date.today() - timedelta(days=15)).isoformat(),
vehicle_id="veh-demo-03-expired"
),
]
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="Initial baseline demo operating policy",
effective_from=datetime(2026, 1, 1, 0, 0, 0, tzinfo=timezone.utc),
effective_to=datetime(2027, 12, 31, 23, 59, 59, tzinfo=timezone.utc),
version=1,
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="policy-demo-001"
)
store.insert("tenant_operating_policies", tenant_id, policy.to_dict())
print("[SEED] Master data successfully seeded.")
def seed_connected_storyboard_transactions(store: InMemoryTenantStorage, tenant_id: str) -> None:
"""Seeds the 11 interconnected relational records of the main sales demo story."""
print("[SEED] Seeding Connected Storyboard Transactions (Sauda -> Gate-In -> QC -> GRN -> Sales -> Bilty)...")
today = date.today()
# Step 1: Procurement Sauda
sauda = 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="c0a80123-demo-0000-0000-000000000001",
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")
)
store.insert("procurement_sauda", tenant_id, sauda.to_dict())
# Step 2: Inward Gate Entry
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.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())
# Step 3: Weighbridge Gross & Tare
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())
# Step 4: Goods Receipt Note (GRN) & Released Lot in Warehouse
grn = GoodsReceiptNote(
tenant_id=tenant_id,
grn_number="GRN-2026-001",
weighment_slip_id=wb_slip.id,
sauda_id=sauda.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") # 24 MT allocated to sales order
store.insert("inventory_lots", tenant_id, lot.to_dict())
# Step 5: Quality Lab Inspection (Moisture 11.5% -> Rebate ₹23,358.75)
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())
# Step 6: Customer Sales Order
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())
# Step 7: Lot Allocation
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())
# Step 8: Outbound Dispatch Schedule & Bilty
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())
# Step 9: Financial Subledger Entries, Supplier Payables & Operating Expenses
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-demo-001",
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())
# Step 10: Operational Alerts (Showcasing Real-Time Hazard Engine)
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())
print("[SEED] Connected storyboard transactions seeded successfully.")
def seed_20day_historical_snapshots(store: InMemoryTenantStorage, tenant_id: str) -> None:
"""Seeds 20 days of realistic daily trading metrics for the Executive Dashboard & SMA."""
print("[SEED] Seeding 20-Day Trading History & Price Moving Averages...")
base_date = date.today()
sample_metrics = [
(185.50, 140.00, 4250.80, 4250000.00, 3540000.00),
(220.00, 190.50, 4205.30, 3890000.00, 3210000.00),
(150.00, 210.00, 4175.80, 3620000.00, 2850000.00),
(310.00, 250.00, 4235.80, 4100000.00, 3950000.00),
(195.00, 160.00, 4175.80, 3750000.00, 3100000.00),
(180.00, 175.00, 4140.80, 3500000.00, 3050000.00),
(240.00, 220.00, 4135.80, 3900000.00, 3600000.00),
(165.00, 150.00, 4115.80, 3400000.00, 2900000.00),
(210.00, 195.00, 4100.80, 3800000.00, 3450000.00),
(190.00, 180.00, 4085.80, 3650000.00, 3300000.00),
(225.00, 210.00, 4075.80, 4000000.00, 3700000.00),
(170.00, 165.00, 4060.80, 3350000.00, 2950000.00),
(205.00, 190.00, 4055.80, 3700000.00, 3400000.00),
(180.00, 175.00, 4040.80, 3500000.00, 3150000.00),
(230.00, 200.00, 4035.80, 3950000.00, 3650000.00),
(160.00, 155.00, 4005.80, 3300000.00, 2800000.00),
(215.00, 190.00, 4000.80, 3850000.00, 3500000.00),
(175.00, 170.00, 3975.80, 3450000.00, 3050000.00),
(220.00, 205.00, 3970.80, 3900000.00, 3600000.00),
(190.00, 180.00, 3955.80, 3600000.00, 3250000.00),
]
for i, (purch, sales, stock, rec, pay) in enumerate(sample_metrics):
snap_dt = base_date - timedelta(days=(len(sample_metrics) - 1 - i))
snap = DailyTradingSnapshot(
tenant_id=tenant_id,
snapshot_date=snap_dt.isoformat(),
purchases_mt=Decimal(str(purch)),
sales_mt=Decimal(str(sales)),
closing_stock_mt=Decimal(str(stock)),
total_receivables_inr=Decimal(str(rec)),
total_payables_inr=Decimal(str(pay)),
snapshot_id=f"snap-demo-{i:03d}"
)
store.insert("daily_trading_snapshots", tenant_id, snap.to_dict())
print(f"[SEED] Seeded {len(sample_metrics)} daily trading snapshots successfully.")
def main():
parser = argparse.ArgumentParser(description="ATB Commercial Sales Demo Data Ingestion Engine")
parser.add_argument("--tenant-id", default=DEFAULT_TENANT_ID, help="Target demo tenant ID (must start with demo-)")
parser.add_argument("--clean-first", action="store_true", help="Clean prior demo data before seeding")
args = parser.parse_args()
tenant_id = args.tenant_id
if not tenant_id.startswith("demo-"):
print(f"[FATAL] Safety Error: Tenant ID '{tenant_id}' must start with 'demo-'", file=sys.stderr)
sys.exit(1)
print("=" * 72)
print(" Agriculture Trading Backoffice (ATB) — Commercial Sales Demo Seeder")
print("=" * 72)
print(f"[CONFIG] Target Tenant: {tenant_id}")
if args.clean_first:
purge_existing_demo_tenant(storage, tenant_id)
seed_demo_tenant(storage, tenant_id)
seed_master_data(storage, tenant_id)
seed_connected_storyboard_transactions(storage, tenant_id)
seed_20day_historical_snapshots(storage, tenant_id)
print("=" * 72)
print("[SUCCESS] Demo Environment Successfully Initialized!")
print(f"Tenant Name : {DEFAULT_BUSINESS_NAME}")
print(f"Tenant ID : {tenant_id}")
print("Sample Login : buyer@malwa-agri.demo (Passwordless in Mock Mode)")
print("Story Sauda : SDA-2026-001 (25 MT Soybean @ ₹4,850/Qtl)")
print("Story Bilty : BLT-2026-089 (24 MT Dispatched on MP09BC8812)")
print("=" * 72)
if __name__ == "__main__":
main()