238 lines
8.9 KiB
Python
238 lines
8.9 KiB
Python
#!/usr/bin/env python3
|
|
"""
|
|
Seed simulation customers and addresses directly into the sim commerce schema.
|
|
|
|
The swarm agents then log in through the real /api/v1/customer/auth/login
|
|
endpoint, so authentication, JWT issuance, carts, checkout, stock and invoices
|
|
all run through the application exactly as they do for a human.
|
|
|
|
Usage:
|
|
cd Backend
|
|
./venv/bin/python scripts/sim/seed_customers.py --count 10000
|
|
./venv/bin/python scripts/sim/seed_customers.py --count 100 --run-id demo1
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import json
|
|
import os
|
|
import random
|
|
import string
|
|
import sys
|
|
from datetime import datetime, timezone
|
|
from pathlib import Path
|
|
|
|
import ulid
|
|
from dotenv import load_dotenv
|
|
from sqlalchemy import insert, select, text
|
|
|
|
BACKEND_DIR = Path(__file__).resolve().parents[2]
|
|
ROOT_DIR = BACKEND_DIR.parent
|
|
if str(BACKEND_DIR) not in sys.path:
|
|
sys.path.insert(0, str(BACKEND_DIR))
|
|
SIM_ENV = BACKEND_DIR / ".env.sim"
|
|
ARTIFACT_DIR = BACKEND_DIR / "sim-artifacts"
|
|
|
|
FIRST_NAMES = [
|
|
"Aarav", "Aditi", "Akhil", "Ananya", "Arjun", "Ayesha", "Bala", "Bhavna",
|
|
"Chetan", "Deepa", "Dev", "Divya", "Farhan", "Gaurav", "Harini", "Imran",
|
|
"Isha", "Jeevan", "Kabir", "Kavya", "Kiran", "Lakshmi", "Manish", "Meera",
|
|
"Mohan", "Nandini", "Naveen", "Neha", "Nikhil", "Pallavi", "Pooja", "Pranav",
|
|
"Priya", "Rahul", "Ravi", "Riya", "Rohit", "Sahana", "Sanjay", "Sara",
|
|
"Shreya", "Siddharth", "Sneha", "Suresh", "Tanvi", "Uday", "Varun", "Vidya",
|
|
"Vikram", "Yash",
|
|
]
|
|
|
|
LAST_NAMES = [
|
|
"Agarwal", "Bhat", "Chandra", "Das", "Desai", "Gowda", "Gupta", "Hegde",
|
|
"Iyer", "Jain", "Joshi", "Kapoor", "Khan", "Krishnan", "Kulkarni", "Kumar",
|
|
"Menon", "Mehta", "Mishra", "Nair", "Naidu", "Patel", "Pillai", "Rao",
|
|
"Reddy", "Sethi", "Shah", "Sharma", "Shetty", "Singh", "Sinha", "Srinivas",
|
|
"Suresh", "Swamy", "Varma", "Verma",
|
|
]
|
|
|
|
CITIES = [
|
|
("Bengaluru", "Karnataka", "560001"),
|
|
("Mysuru", "Karnataka", "570001"),
|
|
("Mangaluru", "Karnataka", "575001"),
|
|
("Hyderabad", "Telangana", "500001"),
|
|
("Chennai", "Tamil Nadu", "600001"),
|
|
("Coimbatore", "Tamil Nadu", "641001"),
|
|
("Madurai", "Tamil Nadu", "625001"),
|
|
("Mumbai", "Maharashtra", "400001"),
|
|
("Pune", "Maharashtra", "411001"),
|
|
("Nagpur", "Maharashtra", "440001"),
|
|
("Delhi", "Delhi", "110001"),
|
|
("Noida", "Uttar Pradesh", "201301"),
|
|
("Lucknow", "Uttar Pradesh", "226001"),
|
|
("Jaipur", "Rajasthan", "302001"),
|
|
("Ahmedabad", "Gujarat", "380001"),
|
|
("Surat", "Gujarat", "395001"),
|
|
("Kochi", "Kerala", "682001"),
|
|
("Thiruvananthapuram", "Kerala", "695001"),
|
|
("Kolkata", "West Bengal", "700001"),
|
|
("Bhubaneswar", "Odisha", "751001"),
|
|
("Visakhapatnam", "Andhra Pradesh", "530001"),
|
|
("Vijayawada", "Andhra Pradesh", "520001"),
|
|
("Indore", "Madhya Pradesh", "452001"),
|
|
("Bhopal", "Madhya Pradesh", "462001"),
|
|
("Chandigarh", "Chandigarh", "160001"),
|
|
("Guwahati", "Assam", "781001"),
|
|
("Patna", "Bihar", "800001"),
|
|
("Ranchi", "Jharkhand", "834001"),
|
|
("Raipur", "Chhattisgarh", "492001"),
|
|
("Dehradun", "Uttarakhand", "248001"),
|
|
]
|
|
|
|
STREETS = [
|
|
"MG Road", "Brigade Road", "Residency Road", "Church Street", "Jayanagar 4th Block",
|
|
"Indiranagar 100ft Road", "Koramangala 5th Block", "HSR Layout Sector 2",
|
|
"Anna Nagar", "T Nagar", "Adyar", "Banjara Hills", "Jubilee Hills", "Madhapur",
|
|
"Salt Lake Sector V", "Park Street", "Connaught Place", "Hauz Khas",
|
|
"Koregaon Park", "Baner Road", "Law Garden", "Navrangpura", "Panampilly Nagar",
|
|
]
|
|
|
|
|
|
def log(msg: str) -> None:
|
|
print(f"[seed] {msg}", flush=True)
|
|
|
|
|
|
def ensure_artifacts() -> None:
|
|
ARTIFACT_DIR.mkdir(parents=True, exist_ok=True)
|
|
gi = ROOT_DIR / ".gitignore"
|
|
entry = "Backend/sim-artifacts/"
|
|
existing = gi.read_text().splitlines() if gi.exists() else []
|
|
if entry not in existing:
|
|
with gi.open("a") as f:
|
|
f.write(f"\n# Simulation runtime artifacts\n{entry}\n")
|
|
|
|
|
|
def main() -> int:
|
|
parser = argparse.ArgumentParser(description="Seed simulation customers into the sim DB")
|
|
parser.add_argument("--count", type=int, default=1000)
|
|
parser.add_argument("--run-id", default="")
|
|
parser.add_argument("--password", default="SimSwarm!2026")
|
|
parser.add_argument("--email-domain", default="@sim.example.com")
|
|
parser.add_argument("--seed", type=int, default=42)
|
|
parser.add_argument("--batch-size", type=int, default=1000)
|
|
args = parser.parse_args()
|
|
|
|
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 seed: SIMULATION_MODE is not true in .env.sim")
|
|
|
|
# Import after loading .env.sim so the engines point at the sim schemas.
|
|
from app.core.config.Config import settings
|
|
from app.core.database.db_session import SessionLocal
|
|
import app.models.db_base # noqa: F401 (registers all mappers)
|
|
from app.models.EcomCustomerModel import EcomCustomer, CustomerAddress
|
|
from app.utils.Hash_util import hash_password
|
|
|
|
domain = args.email_domain if args.email_domain.startswith("@") else "@" + args.email_domain
|
|
run_id = args.run_id or datetime.now(timezone.utc).strftime("%Y%m%d%H%M%S")
|
|
run_tag = run_id.lower().replace("-", "").replace("_", "")
|
|
if not run_tag:
|
|
raise SystemExit("Invalid run id")
|
|
rng = random.Random(args.seed)
|
|
|
|
ensure_artifacts()
|
|
|
|
# Vectorise password hashing: one Argon2 hash reused for the whole sim fleet.
|
|
pwd_hash = hash_password(args.password)
|
|
now = datetime.now(timezone.utc).replace(tzinfo=None)
|
|
run_num = int.from_bytes(run_tag.encode()[-4:].ljust(4, b"0"), "big") % 100000
|
|
rows_customers: list[dict] = []
|
|
rows_addresses: list[dict] = []
|
|
agents: list[dict] = []
|
|
|
|
for i in range(args.count):
|
|
customer_id = str(ulid.ULID())
|
|
first = rng.choice(FIRST_NAMES)
|
|
last = rng.choice(LAST_NAMES)
|
|
email = f"sim.{run_tag}.{i:06d}{domain}"
|
|
phone = f"9{run_num:05d}{i:04d}"[-10:]
|
|
city, state, pincode = rng.choice(CITIES)
|
|
street = f"{rng.randint(1, 240)}, {rng.choice(STREETS)}"
|
|
rows_customers.append(
|
|
{
|
|
"customer_id": customer_id,
|
|
"email": email,
|
|
"password_hash": pwd_hash,
|
|
"first_name": first,
|
|
"last_name": last,
|
|
"phone": phone,
|
|
"is_active": True,
|
|
"email_verified": True,
|
|
"phone_verified": False,
|
|
"failed_login_attempts": 0,
|
|
"is_locked": False,
|
|
"created_at": now,
|
|
"updated_at": now,
|
|
}
|
|
)
|
|
rows_addresses.append(
|
|
{
|
|
"address_id": str(ulid.ULID()),
|
|
"customer_id": customer_id,
|
|
"address_type": "SHIPPING",
|
|
"full_name": f"{first} {last}",
|
|
"phone": phone,
|
|
"street_address": street,
|
|
"city": city,
|
|
"state": state,
|
|
"pincode": pincode,
|
|
"is_default": True,
|
|
"created_at": now,
|
|
}
|
|
)
|
|
agents.append(
|
|
{
|
|
"customer_id": customer_id,
|
|
"email": email,
|
|
"password": args.password,
|
|
"first_name": first,
|
|
"last_name": last,
|
|
"city": city,
|
|
"state": state,
|
|
"pincode": pincode,
|
|
}
|
|
)
|
|
|
|
db = SessionLocal()
|
|
try:
|
|
existing = db.execute(
|
|
select(EcomCustomer.customer_id).where(EcomCustomer.email.in_([a["email"] for a in agents[:50]]))
|
|
).first()
|
|
if existing:
|
|
raise SystemExit("Some simulated emails already exist; use a different --run-id")
|
|
|
|
for start in range(0, len(rows_customers), args.batch_size):
|
|
c_batch = rows_customers[start:start + args.batch_size]
|
|
a_batch = rows_addresses[start:start + args.batch_size]
|
|
db.execute(insert(EcomCustomer), c_batch)
|
|
db.execute(insert(CustomerAddress), a_batch)
|
|
db.commit()
|
|
log(f"seeded {min(start + args.batch_size, len(rows_customers))}/{args.count}")
|
|
finally:
|
|
db.close()
|
|
|
|
artifact = {
|
|
"run_id": run_id,
|
|
"created_at": datetime.now(timezone.utc).isoformat(),
|
|
"count": len(agents),
|
|
"email_domain": domain,
|
|
"commerce_db": settings.COMMERCE_DATABASE_URL.rsplit("/", 1)[-1],
|
|
"agents": agents,
|
|
}
|
|
out = ARTIFACT_DIR / f"agents-{run_id}.json"
|
|
out.write_text(json.dumps(artifact, indent=2))
|
|
(ARTIFACT_DIR / "latest.json").write_text(json.dumps({"run_id": run_id, "file": out.name}, indent=2))
|
|
log(f"wrote {out} ({out.stat().st_size / 1024 / 1024:.1f} MB)")
|
|
log(f"password for all seeded customers: {args.password!r} (simulation only)")
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
raise SystemExit(main())
|