c_agri_trade/process/scripts/demo/cleanup_demo_data.py

215 lines
8.5 KiB
Python
Executable File

#!/usr/bin/env python3
"""Agriculture Trading Backoffice (ATB) — Safe Demo Data Teardown Engine.
Standardized per UP-AI v1.5 Phase IV Transition Standards.
Safely purges demo tenant data and all cascading relational records with strict
production safety guardrails (enforced `demo-` slug prefix, confirmation flag).
Usage:
python3 scripts/demo/cleanup_demo_data.py --confirm-purge
python3 scripts/demo/cleanup_demo_data.py --tenant-id demo-malwa-agri --confirm-purge
"""
import argparse
import os
import sys
# Ensure project_code is importable
CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
PROJECT_CODE = None
for parent_lvl in [os.path.join(CURRENT_DIR, "..", ".."), os.path.join(CURRENT_DIR, "..", "..", "..")]:
cand = os.path.abspath(os.path.join(parent_lvl, "project_code"))
if os.path.isdir(cand):
PROJECT_CODE = cand
break
if PROJECT_CODE and PROJECT_CODE not in sys.path:
sys.path.insert(0, PROJECT_CODE)
try:
from backend.app.db.session import storage, InMemoryTenantStorage
from sandbox.identity_mock import 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"
# Collections in strict reverse-relational dependency order for cascade deletion
CASCADE_PURGE_ORDER = [
# Level 5: Analytics, Alerts & Historical Reporting
("daily_trading_snapshots", "Daily Trading Snapshots"),
("operational_alerts", "Operational Hazard Alerts"),
# Level 4: Financial Subledgers, Vouchers & Payables
("mandi_expense_vouchers", "Mandi Cess Expense Vouchers"),
("supplier_payables", "Supplier Accounts Payable"),
("party_subledger_entries", "Party Double-Entry Subledgers"),
# Level 3: Outbound Logistics, Consignment Bilties & Weighments
("dispatch_bilties", "Transport Consignment Bilties"),
("outward_weighments", "Outward Weighbridge Readings"),
("outbound_dispatches", "Outbound Dispatch Consignments"),
# Level 2: Commercial Sales Orders & Lot Allocations
("sales_order_allocations", "Sales Lot Allocations"),
("customer_sales_orders", "Customer Sales Contracts"),
# Level 1: Inward Receiving, Quality Inspections, GRN & Warehouse Lots
("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"),
# Level 0: Mandi Procurement, Market Rates & Master Data
("procurement_sauda", "Procurement Sauda Contracts"),
("market_observations", "Mandi Market Rate Observations"),
("transport_fleet", "Transport Fleet Registry"),
("tenant_operating_policies", "Tenant Operating Risk Policies"),
("counterparties", "Trading Counterparties Directory"),
("godowns", "Warehouse Godowns & Stacks"),
("commodity_varieties", "Commodity Varieties"),
("commodities", "Commodity Catalog"),
]
def safely_purge_demo_tenant(store: InMemoryTenantStorage, tenant_id: str) -> dict:
"""Executes safe cascade purge of demo tenant data with zero leakage."""
# Safety Rail 1: Strict slug prefix inspection
if not tenant_id.startswith("demo-"):
raise ValueError(
f"[FATAL SECURITY RAIL] Refusing to purge tenant '{tenant_id}'. "
f"The cleanup script strictly operates on tenants whose ID starts with 'demo-'. "
f"Production and live client tenants are permanently protected from this script."
)
purge_metrics = {}
print(f"[PURGE] Commencing cascade teardown for demo tenant: '{tenant_id}'...")
# Step 1: Purge collections in reverse relational order
for coll_name, coll_label 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 count > 0:
print(f" [-] Purged {count:3d} {coll_label} ({coll_name})")
# Step 2: Purge RBAC 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)
if mem_keys:
print(f" [-] Purged {len(mem_keys):3d} Tenant Memberships")
# Step 3: Purge Mock Identity Personas
purged_personas = []
for email, profile in list(TEST_PERSONAS.items()):
if profile.get("tenant_id") == tenant_id:
purged_personas.append(email)
del TEST_PERSONAS[email]
purge_metrics["personas"] = len(purged_personas)
if purged_personas:
print(f" [-] Purged {len(purged_personas):3d} Mock Authentication Personas")
# Step 4: Purge Tenant Root Entity
existed = tenant_id in store.tenants
store.tenants.pop(tenant_id, None)
purge_metrics["tenant_deleted"] = existed
if existed:
print(f" [-] Purged Tenant Root Record: '{tenant_id}'")
# Step 5: Verification of zero residue
residual_rows = 0
for coll_name, _ in CASCADE_PURGE_ORDER:
if coll_name in store._collections and tenant_id in store._collections[coll_name]:
residual_rows += len(store._collections[coll_name][tenant_id])
residual_memberships = sum(1 for m in store.memberships.values() if m.tenant_id == tenant_id)
if residual_rows > 0 or residual_memberships > 0 or tenant_id in store.tenants:
raise RuntimeError(
f"[PURGE ERROR] Incomplete teardown: {residual_rows} residual rows and "
f"{residual_memberships} memberships remain for '{tenant_id}'."
)
print(f"[PURGE SUCCESS] Teardown complete. Zero residual records remain for '{tenant_id}'.")
return purge_metrics
def main():
parser = argparse.ArgumentParser(description="ATB Commercial Sales Demo Data Safe Teardown Engine")
parser.add_argument(
"--tenant-id",
default=DEFAULT_TENANT_ID,
help="Target demo tenant ID to purge (must start with 'demo-')"
)
parser.add_argument(
"--confirm-purge",
action="store_true",
help="Confirm teardown without interactive prompt"
)
args = parser.parse_args()
tenant_id = args.tenant_id
if not tenant_id.startswith("demo-"):
print(
f"[CRITICAL ERROR] Tenant ID '{tenant_id}' does NOT begin with 'demo-'.\n"
f"This safety rail prevents accidental data loss on production or client tenants.\n"
f"Aborting execution.",
file=sys.stderr
)
sys.exit(1)
print("=" * 72)
print(" Agriculture Trading Backoffice (ATB) — Safe Demo Data Teardown Engine")
print("=" * 72)
print(f"[CONFIG] Target Demo Tenant: {tenant_id}")
if not args.confirm_purge:
try:
confirm = input(f"Are you sure you want to permanently delete all data for '{tenant_id}'? [y/N]: ")
if confirm.strip().lower() not in ("y", "yes"):
print("[ABORT] Teardown cancelled by user.")
sys.exit(0)
except (EOFError, KeyboardInterrupt):
print("\n[ABORT] Non-interactive execution requires --confirm-purge flag.")
sys.exit(1)
try:
from backend.app.db.demo_seed import purge_demo_dataset
metrics = purge_demo_dataset(storage, tenant_id)
# Also synchronize running backend server if active
try:
import urllib.request
import json
req = urllib.request.Request(
"http://localhost:8000/api/v1/demo/cleanup",
data=json.dumps({"tenant_id": tenant_id}).encode("utf-8"),
headers={"Content-Type": "application/json"},
method="POST"
)
with urllib.request.urlopen(req, timeout=3) as resp:
if resp.status == 200:
print("[API] Synced running backend server at http://localhost:8000")
except Exception:
pass
total_records = sum(v for k, v in metrics.items() if isinstance(v, int))
print("=" * 72)
print(f"[SUMMARY] Total demo records safely removed: {total_records}")
print(f"[STATUS] Demo tenant '{tenant_id}' is cleanly wiped.")
print("=" * 72)
except Exception as err:
print(f"[ERROR] Teardown failed: {err}", file=sys.stderr)
sys.exit(1)
if __name__ == "__main__":
main()