#!/usr/bin/env python3 """ Reset the *simulation* transactional state without touching reference data. This removes orders, carts, invoices, ledgers and status history from the sim commerce schema and re-creates the opening-stock ledger rows. Reference data (products, variants, categories, CRM tables) and customers are preserved unless --drop-customers is passed. Usage: cd Backend ./venv/bin/python scripts/sim/reset_sim_data.py --yes ./venv/bin/python scripts/sim/reset_sim_data.py --yes --drop-customers """ from __future__ import annotations import argparse import os import sys from datetime import datetime, timezone from pathlib import Path import ulid from dotenv import load_dotenv from sqlalchemy import create_engine, text BACKEND_DIR = Path(__file__).resolve().parents[2] SIM_ENV = BACKEND_DIR / ".env.sim" TRANSACTIONAL_TABLES = [ "payment_ledger", "invoices", "order_status_history", "order_items", "orders", "carts", "inventory_ledger", ] OPENING_STOCK = 5000 def log(msg: str) -> None: print(f"[reset] {msg}", flush=True) def assert_sim_database(url: str) -> str: db_name = url.rsplit("/", 1)[-1].split("?")[0] if not db_name.endswith("_sim"): raise SystemExit(f"Refusing to reset non-simulation database {db_name!r}") return db_name def main() -> int: parser = argparse.ArgumentParser(description="Reset simulation transactional data") parser.add_argument("--yes", action="store_true", help="Required confirmation flag") parser.add_argument("--opening-stock", type=int, default=OPENING_STOCK) parser.add_argument("--drop-customers", action="store_true", help="Also delete sim customers/addresses") args = parser.parse_args() if not args.yes: raise SystemExit("Refusing to reset without --yes") if not SIM_ENV.exists(): raise SystemExit(f"Missing {SIM_ENV}; run provision_sim_db.py first") load_dotenv(SIM_ENV, override=True) if os.getenv("SIMULATION_MODE", "").lower() not in ("1", "true", "yes"): raise SystemExit("Refusing to reset: SIMULATION_MODE is not true in .env.sim") url = os.getenv("COMMERCE_DATABASE_URL", "") db_name = assert_sim_database(url) engine = create_engine(url, future=True) now = datetime.now(timezone.utc).replace(tzinfo=None) with engine.begin() as conn: for table in TRANSACTIONAL_TABLES: conn.execute(text(f"DELETE FROM {table}")) log(f"cleared {table}") variants = [ r[0] for r in conn.execute(text("SELECT variant_id FROM product_variants WHERE status='ACTIVE'")) ] conn.execute( text( "INSERT INTO inventory_ledger " "(ledger_id, variant_id, event_type, qty, reference_id, notes, created_at) " "VALUES (:ledger_id, :variant_id, 'RECEIPT', :qty, 'SIM_SEED', " "'Simulation opening stock', :created_at)" ), [ { "ledger_id": str(ulid.ULID()), "variant_id": variant_id, "qty": args.opening_stock, "created_at": now, } for variant_id in variants ], ) log(f"seeded {len(variants)} variants x {args.opening_stock} units opening stock") if args.drop_customers: conn.execute(text("DELETE FROM customer_addresses")) deleted = conn.execute( text("DELETE FROM ecom_customers WHERE email LIKE '%@sim.example.com'") ).rowcount log(f"deleted {deleted} simulation customers and their addresses") print(f"\nReset complete: {db_name}") return 0 if __name__ == "__main__": raise SystemExit(main())