From 2f6d97304d617daf64c167dfa9e2208d5f1c2ae6 Mon Sep 17 00:00:00 2001 From: iFixKart Dev Date: Wed, 18 Nov 2026 00:09:46 +0530 Subject: [PATCH] feat(scripts): add admin panel demo data seeder --- scripts/seed_demo_data.py | 1806 +++++++++++++++++++++++++++++++++++++ 1 file changed, 1806 insertions(+) create mode 100644 scripts/seed_demo_data.py diff --git a/scripts/seed_demo_data.py b/scripts/seed_demo_data.py new file mode 100644 index 0000000..fe9ca6d --- /dev/null +++ b/scripts/seed_demo_data.py @@ -0,0 +1,1806 @@ +#!/usr/bin/env python3 +""" +IfixKart demo-data seeder (2026-11-16). + +Seeds >=100 rows into every admin-panel data module across the three schemas +(ifixkartecommerceadmin / ifixkartcrm / ifixkartecommerce) reached through the +SSH tunnel on 127.0.0.1:3306. + +- FK-safe ordering, schema-introspected inserts (fails loudly on missing NOT NULL cols) +- ULID ids (26-char) matching app conventions +- Status/stage values copied from the backend service code +- All demo rows tagged "[SEED-DEMO-20261116]" in notes columns where possible +- Refuses to run if CRM data already looks seeded, unless --force + +Run: cd Backend && ./venv/bin/python scripts/seed_demo_data.py +""" +from __future__ import annotations + +import json +import random +import string +import sys +import time +from datetime import datetime, timedelta + +import pymysql + +DB_A = "ifixkartecommerceadmin" +DB_C = "ifixkartcrm" +DB_E = "ifixkartecommerce" +TENANT = "tenant_default" +TAG = "[SEED-DEMO-20261116]" +STAFF_PASSWORD = "Demo@Staff2026" +CUSTOMER_PASSWORD = "Demo@Cust2026" + +random.seed(20261116) + +# --------------------------------------------------------------------------- # +# ULID (Crockford base32, 26 chars) — matches python-ulid output format +# --------------------------------------------------------------------------- # +_B32 = "0123456789ABCDEFGHJKMNPQRSTVWXYZ" +_last_ulid_ts = [0] + + +def new_ulid() -> str: + ts_ms = int(time.time() * 1000) + if ts_ms <= _last_ulid_ts[0]: + ts_ms = _last_ulid_ts[0] + 1 + _last_ulid_ts[0] = ts_ms + out = [] + for i in range(9, -1, -1): # 48-bit time -> 10 chars + out.append(_B32[(ts_ms >> (5 * i)) & 31]) + rnd = random.getrandbits(80) + for i in range(15, -1, -1): # 80-bit random -> 16 chars + out.append(_B32[(rnd >> (5 * i)) & 31]) + return "".join(out) + + +def now() -> datetime: + return datetime.now() + + +def days_ago(n: int, hour=None, minute=None) -> datetime: + d = now() - timedelta(days=n) + if hour is not None: + d = d.replace(hour=hour % 24, minute=(minute or 0) % 60, + second=random.randint(0, 59), microsecond=0) + return d + + +def in_days(n: int) -> datetime: + return now() + timedelta(days=n) + + +def j(v) -> str: + return json.dumps(v, ensure_ascii=False) + + +# --------------------------------------------------------------------------- # +# Data pools +# --------------------------------------------------------------------------- # +FIRST = ["Adithiyan","Arun","Priya","Divya","Karthik","Vijay","Sneha","Rahul","Ananya","Harish", + "Meena","Sathish","Kavya","Deepak","Lakshmi","Manoj","Nithya","Praveen","Ramya","Sanjay", + "Geetha","Vignesh","Swathi","Ramesh","Bhavani","Kiran","Megha","Suresh","Pooja","Aruna", + "Vikram","Shalini","Naveen","Priyanka","Gokul","Revathi","Dinesh","Keerthi","Ashok","Banu"] +LAST = ["Kumar","Raj","Sharma","Patel","Iyer","Nair","Reddy","Rao","Singh","Das","Pillai","Verma", + "Naidu","Chauhan","Menon","Gupta","Joshi","Bose","Chandra","Mohan","Krishnan","Bala","Sekar", + "Rangan","Murugan","Pandian","Thevar","Vanniar"] +CITIES = [("Chennai","Tamil Nadu","600"),("Coimbatore","Tamil Nadu","641"),("Madurai","Tamil Nadu","625"), + ("Trichy","Tamil Nadu","620"),("Salem","Tamil Nadu","636"),("Bengaluru","Karnataka","560"), + ("Hyderabad","Telangana","500"),("Mumbai","Maharashtra","400"),("Pune","Maharashtra","411"), + ("Delhi","Delhi","110"),("Kolkata","West Bengal","700"),("Ahmedabad","Gujarat","380"), + ("Vellore","Tamil Nadu","632"),("Erode","Tamil Nadu","638"),("Thanjavur","Tamil Nadu","613")] +STREETS = ["Anna Nagar","T Nagar","Adyar","Velachery","Mugappair","Kodambakkam","Porur","Guindy", + "K K Nagar","Ashok Nagar","Perungudi","Sholinganallur","Vadapalani","Nungambakkam","Mylapore"] +DEVICES = [("Apple","iPhone 13","mobile"),("Apple","iPhone 14 Pro","mobile"),("Apple","iPhone 12","mobile"), + ("Samsung","Galaxy S22","mobile"),("Samsung","Galaxy S21 FE","mobile"),("Samsung","Galaxy M33","mobile"), + ("OnePlus","Nord CE 3","mobile"),("OnePlus","11R","mobile"), + ("Xiaomi","Redmi Note 12","mobile"),("Xiaomi","Redmi 12C","mobile"), + ("Vivo","V27","mobile"),("Oppo","Reno 10","mobile"),("Realme","Narzo 60","mobile"), + ("Motorola","Moto G84","mobile"),("Google","Pixel 7a","mobile"),("Nothing","Phone (2)","mobile"), + ("Apple","MacBook Air M2","laptop"),("Dell","Inspiron 15","laptop"),("HP","Pavilion 14","laptop"), + ("Lenovo","ThinkPad E14","laptop"),("Asus","VivoBook 15","laptop"), + ("Samsung","Galaxy Tab S8","tablet"),("Apple","iPad Air 5","tablet")] +ISSUES = ["Screen cracked after drop","Battery drains within 3 hours","Charging port loose / not charging", + "Water damage - device not powering on","Speaker sound muffled","Rear camera blurry / shaky", + "Device overheating while gaming","Motherboard dead - no display","Software hanging / boot loop", + "Fingerprint sensor not working","Microphone not audible on calls","Network signal dropping"] +COMPANIES = ["Sri Balaji Mobiles","Chennai Mobile Spares","Ganesh Communications","Sunrise Telecom", + "Vasan Electronics","Mobile Point India","SK Telecom Traders","Prime Parts Hub", + "National Mobile Mart","Deccan Spares","Metro Gadget Supply","Coastal Communications"] +BRAND_POOL = ["Honor","iQoo","Tecno","Infinix","Lava","Micromax","Nokia","Sony","Nubia","Asus ROG"] +ATTR_POOL = [("water_resistance_rating","Water Resistance Rating",["IP67","IP68","IP54","None"]), + ("refresh_rate_hz","Refresh Rate (Hz)",["60","90","120","144"]), + ("screen_size_inch","Screen Size (inch)",["6.1","6.5","6.7","13.3","14.0","15.6"]), + ("ram_type","RAM Type",["LPDDR4X","LPDDR5","DDR4","DDR5"]), + ("port_type","Port Type",["USB-C","Lightning","Micro USB","USB-A"]), + ("weight_grams","Weight (grams)",["160","180","200","1200","1400"]), + ("battery_capacity_mah","Battery Capacity (mAh)",["4000","4500","5000","5500"]), + ("charger_wattage","Charger Wattage (W)",["18","25","33","65","120"]), + ("front_camera_mp","Front Camera (MP)",["8","12","16","32"]), + ("rear_camera_mp","Rear Camera (MP)",["12","48","50","64","108"]), + ("processor_core","Processor Core",["Octa Core","Hexa Core","Deca Core"]), + ("os_version","OS Version",["Android 13","Android 14","iOS 16","iOS 17","Windows 11"]), + ("sim_slots","SIM Slots",["Single","Dual"]), + ("network_band","Network Band",["4G","5G"]), + ("material_grade","Material Grade",["OEM","A+","A","Compatible"]), + ("panel_type","Panel Type",["AMOLED","OLED","TFT","IPS LCD"]), + ("warranty_period","Warranty Period",["3 Months","6 Months","12 Months"]), + ("connector_pitch","Connector Pitch",["0.25mm","0.3mm","0.5mm"]), + ("flex_cable_type","Flex Cable Type",["Standard","Reinforced"]), + ("color_variant","Color Variant",["Black","White","Blue","Silver"]), + ("storage_capacity","Storage Capacity",["64GB","128GB","256GB","512GB"]), + ("keyboard_layout","Keyboard Layout",["QWERTY","AZERTY"]), + ("audio_jack","Audio Jack",["3.5mm","Type-C","None"]), + ("fingerprint_type","Fingerprint Type",["In-display","Side-mounted","Rear","None"]), + ("fast_charging","Fast Charging",["Yes","No"]), + ("wireless_charging","Wireless Charging",["Yes","No"]), + ("tcon_board","TCON Board",["Included","Not Included"]), + ("frame_included","Frame Included",["With Frame","Without Frame"]), + ("ic_chips","IC Chips",["Original IC","Copy IC"]), + ("tempered_grade","Tempered Grade",["Tempered","Non-Tempered"]), + ("screen_resolution","Screen Resolution",["HD+","FHD+","2K","4K"]), + ("battery_cycle_count","Battery Cycle Count",["<300","300-500","500+"]), + ("hinge_type","Hinge Type",["Standard","360°","Dual Hinge"]), + ("touch_ic_model","Touch IC Model",["Generic","OEM Matched"]), + ("backlight_type","Backlight Type",["LED","Mini-LED","None"]), + ("screw_kit","Screw Kit",["Included","Not Included"]), + ("voltage_rating","Voltage Rating",["3.7V","3.8V","7.6V","11.4V"]), + ("region_code","Region Code",["IND","GULF","US","EU"])] +NOTE_PREFIXES = ["Walk-in enquiry","Follow-up pending","Discussed pricing over call","Repeat customer", + "Referred by existing client","Quotation shared on WhatsApp","Awaiting approval", + "Bulk order possibility","Warranty claim discussion","Priority handling requested"] + +_used_phones: set[str] = set() +_used_emails: set[str] = set() + + +def phone() -> str: + while True: + p = "9" + "".join(random.choice(string.digits) for _ in range(9)) + if p not in _used_phones: + _used_phones.add(p) + return p + + +def slug_email(fn: str, ln: str, domain="ifixkart-demo.com") -> str: + while True: + e = f"{fn.lower()}.{ln.lower()}{random.randint(100, 999)}@{domain}" + if e not in _used_emails: + _used_emails.add(e) + return e + + +def person(): + fn, ln = random.choice(FIRST), random.choice(LAST) + return fn, ln, slug_email(fn, ln), phone() + + +def addr(city_idx=None): + ci = city_idx if city_idx is not None else random.randrange(len(CITIES)) + city, state, pin = CITIES[ci] + return {"full_name": "", "phone": "", "street_address": f"{random.randint(1, 250)}, {random.choice(STREETS)} Street", + "city": city, "state": state, "pincode": f"{pin}{random.randint(100, 999)}", + "address_type": "SHIPPING"} + + +# --------------------------------------------------------------------------- # +# Generic insert helper with schema validation +# --------------------------------------------------------------------------- # +class Seeder: + def __init__(self): + self.conn = pymysql.connect(host="127.0.0.1", port=3306, user="Adithiyan", + password="Adithiyan$2025Mysql", charset="utf8mb4", + autocommit=False, connect_timeout=15) + self.conn.cursor().execute("SET SESSION sql_mode='STRICT_TRANS_TABLES'") + self._cols: dict[tuple, dict] = {} + + def cols(self, db: str, table: str) -> dict: + key = (db, table) + if key not in self._cols: + cur = self.conn.cursor() + cur.execute( + "SELECT column_name, is_nullable, column_default, extra " + "FROM information_schema.columns WHERE table_schema=%s AND table_name=%s", + (db, table)) + self._cols[key] = {r[0]: (r[1], r[2], r[3]) for r in cur.fetchall()} + return self._cols[key] + + def insert(self, db: str, table: str, rows: list[dict], label="") -> int: + if not rows: + return 0 + schema = self.cols(db, table) + missing = [k for k in rows[0] if k not in schema] + if missing: + raise RuntimeError(f"{db}.{table}: unknown columns {missing}") + required = [c for c, (nul, dflt, _x) in schema.items() + if nul == "NO" and dflt is None and "GENERATED" not in c] + absent = [c for c in required if c not in rows[0]] + if absent: + raise RuntimeError(f"{db}.{table}: NOT NULL without default not provided: {absent}") + use_cols = [] + seen = set() + for r in rows: + for c in r: + if c not in seen: + seen.add(c) + use_cols.append(c) + sql = (f"INSERT INTO `{db}`.`{table}` (" + ",".join(f"`{c}`" for c in use_cols) + ") VALUES (" + + ",".join(["%s"] * len(use_cols)) + ")") + cur = self.conn.cursor() + try: + cur.executemany(sql, [[r.get(c) for c in use_cols] for r in rows]) + except Exception as e: + self.conn.rollback() + raise RuntimeError(f"{db}.{table} insert failed: {e}") from e + self.conn.commit() + print(f" {db}.{table:<38} +{cur.rowcount:>5} {label}") + return cur.rowcount + + def fetch(self, sql, args=None): + cur = self.conn.cursor() + cur.execute(sql, args or ()) + return cur.fetchall() + + def scalar(self, sql, args=None): + cur = self.conn.cursor() + cur.execute(sql, args or ()) + r = cur.fetchone() + return r[0] if r else None + + +S = Seeder() + + +def count(db, table) -> int: + return int(S.scalar(f"SELECT COUNT(*) FROM `{db}`.`{table}`") or 0) + + +def audit_fields(i=0): + return {"created_by": "seed-script", "updated_by": "seed-script", "version": 1} + + +# =========================================================================== # +# STAGE 1 — admin DB: roles, departments, designations, users +# =========================================================================== # +def stage_admin_staff(): + print("STAGE 1: admin staff & org") + existing_roles = {r[0] for r in S.fetch(f"SELECT role_name FROM {DB_A}.roles")} + role_rows = [] + for name, prefix, desc in [ + ("Admin", "ADMI", "Full admin access"), ("Store Manager", "SMGR", "Store operations"), + ("Sales Executive", "SLEX", "Frontline sales"), ("CRM Executive", "CRMX", "CRM & pipeline"), + ("Service Advisor", "SVAD", "Service counter"), ("Technician", "TECH", "Repairs"), + ("Warehouse Executive", "WHSE", "Stock & dispatch"), + ("Accountant", "ACCT", "Billing & GST"), ("Support Agent", "SUPT", "Customer support")]: + if name not in existing_roles: + role_rows.append({"role_id": new_ulid(), "role_name": name, "role_prefix": prefix, + "description": f"{desc} {TAG}", "is_system": 0, "is_active": 1}) + # pad to >=100 with zone variants so the roles page has real list depth + if len(role_rows) < 100: + bases = ["Technician", "Sales Executive", "Support Agent", "Warehouse Executive", + "Service Advisor", "CRM Executive", "Store Manager", "Accountant"] + zone_idx = 0 + for ci, (city, _st, _p) in enumerate(CITIES): + for bi, base in enumerate(bases): + zone_idx += 1 + name = f"{base} - {city} Zone {ci % 3 + 1}.{bi + 1}"[:50] + if name in existing_roles: + continue + existing_roles.add(name) + role_rows.append({"role_id": new_ulid(), "role_name": name, + "role_prefix": f"Z{zone_idx:04d}"[:10], + "description": f"Zone-scoped {base.lower()} role {TAG}", + "is_system": 0, "is_active": 1}) + if len(role_rows) >= 100: + break + if len(role_rows) >= 100: + break + S.insert(DB_A, "roles", role_rows) + + existing_dep = {r[0] for r in S.fetch(f"SELECT name FROM {DB_A}.departments")} + dep_rows = [{"department_id": new_ulid(), "name": n, "description": f"{n} department {TAG}", "is_active": 1} + for n in ["Sales", "Service & Repair", "Warehouse & Logistics", "Finance & Accounts", + "Customer Support", "Marketing", "Human Resources"] if n not in existing_dep] + if len(dep_rows) < 100: + base_deps = ["Sales", "Service & Repair", "Warehouse & Logistics", "Finance & Accounts", + "Customer Support", "Marketing"] + dep_idx = 0 + for suffix in ("", " East", " West"): + for ci, (city, _st, _p) in enumerate(CITIES): + for bd in base_deps: + dep_idx += 1 + name = f"{bd} - {city}{suffix}"[:100] + if name in existing_dep: + continue + existing_dep.add(name) + dep_rows.append({"department_id": new_ulid(), "name": name, + "description": f"{bd} operations at {city} {TAG}", "is_active": 1}) + if len(dep_rows) >= 100: + break + if len(dep_rows) >= 100: + break + if len(dep_rows) >= 100: + break + S.insert(DB_A, "departments", dep_rows) + + existing_des = {r[0] for r in S.fetch(f"SELECT name FROM {DB_A}.designations")} + des_rows = [{"designation_id": new_ulid(), "name": n, "description": f"{n} {TAG}", "is_active": 1} + for n in ["Store Manager", "Sales Executive", "Senior Sales Executive", "CRM Executive", + "Service Center Manager", "Senior Technician", "Technician", "Junior Technician", + "Warehouse Executive", "Accountant", "Support Agent"] if n not in existing_des] + if len(des_rows) < 100: + base_des = ["Sales Executive", "Technician", "Support Agent", "Warehouse Executive"] + des_idx = 0 + for grade in range(1, 30): + for bd in base_des: + des_idx += 1 + name = f"{bd} - Grade {grade}"[:100] + if name in existing_des: + continue + existing_des.add(name) + des_rows.append({"designation_id": new_ulid(), "name": name, + "description": f"{bd} pay grade {grade} {TAG}", "is_active": 1}) + if len(des_rows) >= 100: + break + if len(des_rows) >= 100: + break + S.insert(DB_A, "designations", des_rows) + + roles = {r[1]: r[0] for r in S.fetch(f"SELECT role_id, role_name FROM {DB_A}.roles")} + deps = {r[1]: r[0] for r in S.fetch(f"SELECT department_id, name FROM {DB_A}.departments")} + dess = {r[1]: r[0] for r in S.fetch(f"SELECT designation_id, name FROM {DB_A}.designations")} + admin_id = S.scalar(f"SELECT user_id FROM {DB_A}.users WHERE email='admin@ifixkart.com'") + + import passlib.context # noqa + from passlib.context import CryptContext + ctx = CryptContext(schemes=["argon2"], deprecated="auto") + staff_hash = ctx.hash(STAFF_PASSWORD) + + role_plan = (["Technician"] * 100 + ["Sales Executive"] * 16 + ["Service Advisor"] * 8 + + ["Store Manager"] * 6 + ["CRM Executive"] * 6 + ["Warehouse Executive"] * 4 + + ["Support Agent"] * 4 + ["Accountant"] * 2 + ["Admin"] * 2) + random.shuffle(role_plan) + dept_map = {"Technician": "Service & Repair", "Sales Executive": "Sales", + "Service Advisor": "Service & Repair", "Store Manager": "Sales", + "CRM Executive": "Sales", "Warehouse Executive": "Warehouse & Logistics", + "Support Agent": "Customer Support", "Accountant": "Finance & Accounts", + "Admin": "Human Resources"} + desig_map = {"Technician": ["Technician", "Senior Technician", "Junior Technician"], + "Sales Executive": ["Sales Executive", "Senior Sales Executive"], + "Service Advisor": ["Service Center Manager"], "Store Manager": ["Store Manager"], + "CRM Executive": ["CRM Executive"], "Warehouse Executive": ["Warehouse Executive"], + "Support Agent": ["Support Agent"], "Accountant": ["Accountant"], "Admin": ["Store Manager"]} + start = int(S.scalar( + "SELECT COALESCE(MAX(CAST(SUBSTRING(employee_code, 4) AS UNSIGNED)), 0) " + f"FROM {DB_A}.users") or 0) + 1 + users, tech_user_ids, sales_user_ids = [], [], [] + for i, role in enumerate(role_plan): + fn, ln, email, ph = person() + uid = new_ulid() + desig = random.choice(desig_map[role]) + users.append({"user_id": uid, "employee_code": f"ADM{start + i:04d}", + "first_name": fn, "last_name": ln, "display_name": f"{fn} {ln}", + "email": email, "phone": ph, "password_hash": staff_hash, + "gender": random.choice(["Male", "Female", None]), + "dob": days_ago(random.randint(9000, 13000)).date(), + "department_id": deps[dept_map[role]], "designation_id": dess[desig], + "role_id": roles[role], "manager_id": admin_id, + "is_active": 1, "email_verified": 1, "phone_verified": 1, + "failed_login_attempts": 0, "is_locked": 0}) + (tech_user_ids if role == "Technician" else sales_user_ids).append(uid) + # a few managers without manager + for u in users[:6]: + u["manager_id"] = None + S.insert(DB_A, "users", users, "staff") + return {"users": users, "tech_user_ids": tech_user_ids, "sales_ids": sales_user_ids, + "roles": roles} + + +# =========================================================================== # +# STAGE 2 — locations, warehouses, suppliers, terminals, coupons, service types, parts +# =========================================================================== # +def stage_reference(): + print("STAGE 2: reference data") + locs, whs, sups = [], [], [] + for i in range(1, 101): + city, state, pin = CITIES[i % len(CITIES)] + lid = new_ulid() + locs.append({"location_id": lid, "tenant_id": TENANT, "code": f"LOC{i:03d}", + "name": f"iFixKart {city} Store {i:02d}", + "address": f"{random.randint(1, 200)}, {random.choice(STREETS)}, {city}", + "city": city, "state": state, "pincode": f"{pin}{random.randint(100, 999)}", + "phone": phone(), "email": f"store{i:02d}@ifixkart-demo.com", + "is_active": 1, "is_primary": 1 if i == 1 else 0, + "is_central_warehouse": 1 if i == 1 else 0, + "created_by": "seed-script", "updated_by": "seed-script", "version": 1}) + wid = new_ulid() + whs.append({"warehouse_id": wid, "tenant_id": TENANT, "code": f"WH{i:03d}", + "name": f"{city} Warehouse {i:02d}", + "address": f"Industrial Estate Phase {random.randint(1, 3)}, {city}", + "city": city, "state": state, "is_primary": 1 if i == 1 else 0, + "created_by": "seed-script", "updated_by": "seed-script", "version": 1}) + fn, ln = random.choice(FIRST), random.choice(LAST) + sups.append({"supplier_id": new_ulid(), "tenant_id": TENANT, + "company_name": f"{COMPANIES[i % len(COMPANIES)]} {('Pvt Ltd') if i % 2 else ('& Sons')} #{i:03d}", + "contact_name": f"{fn} {ln}", "phone": phone(), + "email": f"sales{i:03d}@supplier-demo.com", + "gstin": f"33AABC{random.randint(1000, 9999)}D1Z{random.randint(1, 9)}", + "address": f"{random.randint(1, 99)}, Wholesale Market, {city}", + "created_by": "seed-script", "updated_by": "seed-script", "version": 1}) + S.insert(DB_E, "crm_locations", locs) + S.insert(DB_E, "crm_warehouses", whs) + S.insert(DB_E, "crm_suppliers", sups) + + terms = [{"terminal_id": new_ulid(), "tenant_id": TENANT, "location_id": locs[i % 10]["location_id"], + "code": f"LOC{i % 10 + 1:03d}-T{i:03d}", "name": f"POS Terminal {i:03d}", + "is_active": 1 if i % 7 else 0, + "created_by": "seed-script", "updated_by": "seed-script", "version": 1} + for i in range(1, 101)] + S.insert(DB_E, "pos_terminals", terms) + + sync_terms = [{"terminal_id": f"TERM-{i:05d}", "store_name": locs[i % 20]["name"], + "status": random.choice(["ONLINE", "ONLINE", "ONLINE", "OFFLINE", "SYNCING"]), + "ip_address": f"192.168.{random.randint(1, 8)}.{random.randint(2, 250)}", + "last_heartbeat": days_ago(0, random.randint(8, 20)), + "synced_today": random.randint(0, 40), "pending_queue": random.choice([0, 0, 0, 1, 2, 5]), + "created_at": days_ago(60), "updated_at": days_ago(0)} + for i in range(1, 101)] + S.insert(DB_E, "pos_sync_terminals", sync_terms) + + coupons = [] + curated = [("FEST10", "Festival 10% Off", "PERCENTAGE", 10), ("IFK100", "Flat Rs.100 Off", "FIXED", 100), + ("NEWUSER50", "New User 50% Off", "PERCENTAGE", 50), ("SCREEN15", "Screen Combo 15% Off", "PERCENTAGE", 15), + ("BATTERY20", "Battery 20% Off", "PERCENTAGE", 20), ("MONSOON25", "Monsoon 25% Off", "PERCENTAGE", 25), + ("COMBO500", "Combo Rs.500 Off", "FIXED", 500), ("GSTSAVE5", "GST Saver 5%", "PERCENTAGE", 5), + ("VIPFREE", "VIP Free Shipping", "FREE_SHIPPING", 0), ("FIRSTFIX", "First Repair 10% Off", "PERCENTAGE", 10), + ("DIWALI30", "Diwali 30% Off", "PERCENTAGE", 30), ("REPAIR10", "Repair 10% Off", "PERCENTAGE", 10)] + rows = curated + [(f"IFK{i:03d}OFF", f"Promo Rs.{i * 10} Off", "FIXED", i * 10) for i in range(1, 99)] + for i, (code, title, dt, dv) in enumerate(rows[:110]): + active = i % 6 != 5 + coupons.append({"coupon_id": new_ulid(), "code": code, "title": title, + "description": f"Demo coupon {code} {TAG}", + "discount_type": dt, "discount_value": dv, + "max_discount_cap": dv * 5 if dt == "PERCENTAGE" else None, + "min_order_amount": random.choice([0, 499, 999, 1999]), + "max_order_amount": None, "first_order_only": 1 if i % 4 == 0 else 0, + "channel_scope": random.choice(["ONLINE_ONLY", "POS_ONLY", "OMNICHANNEL"]), + "exclude_already_discounted": i % 3 == 0, + "valid_from": days_ago(30), "valid_to": in_days(60), + "usage_limit_total": random.choice([100, 500, 1000, None]), + "usage_limit_per_customer": random.choice([1, 1, 2]), + "times_used": 0 if not active else random.randint(0, 80), + "is_active": 1 if active else 0}) + S.insert(DB_E, "coupons", coupons) + + # CRM DB: service types +95, parts 110, contacts 110 + existing_st = {r[0] for r in S.fetch(f"SELECT name FROM {DB_C}.service_types")} + svc_bases = ["Data Recovery", "Water Damage Treatment", "Motherboard Chip-Level Repair", + "Micro Soldering Service", "Screen Calibration", "Battery Health Restoration", + "Camera Module Calibration", "Speaker Diagnostics", "Charging Port Deep Cleaning", + "Software Reflash", "IMEI Correction Service", "Network Unlock"] + grades = ["Basic", "Standard", "Advanced", "Premium"] + kinds = ["Mobile", "Laptop", "Tablet", "Smartwatch", "TWS Earbuds", "Gaming Console", "Drone", "Camera"] + st_rows = [] + for b in svc_bases: + for g in grades: + for k in kinds: + if len(st_rows) >= 95: + break + name = f"{b} - {g} ({k})" + if name in existing_st: + continue + existing_st.add(name) + st_rows.append({"service_type_id": new_ulid(), "name": name, + "slug": name.lower().replace(" ", "-").replace("(", "").replace(")", ""), + "description": f"{g} tier {b.lower()} for {k.lower()} devices. {TAG}", + "is_active": 1}) + if len(st_rows) >= 95: + break + S.insert(DB_C, "service_types", st_rows) + all_st = [r[0] for r in S.fetch(f"SELECT service_type_id FROM {DB_C}.service_types")] + tag_st = [r[0] for r in S.fetch( + f"SELECT service_type_id FROM {DB_C}.service_types WHERE description LIKE %s", (f"%{TAG}%",))] + + parts = [] + part_names = ["Display Combo", "Battery", "Charging Flex", "Back Glass", "Camera Module", + "Speaker Set", "Motherboard", "Power Button Flex", "Volume Flex", "Front Camera", + "Earpiece Speaker", "Loud Speaker", "Vibration Motor", "SIM Tray", "Mic Flex", + "Proximity Sensor", "Home Button", "Fingerprint Flex", "NFC Antenna", "Wireless Coil"] + for i in range(1, 111): + dev = random.choice(DEVICES) + pn = random.choice(part_names) + parts.append({"part_id": new_ulid(), "sku": f"PART-{i:04d}-{random.randint(100, 999)}", + "name": f"{pn} for {dev[0]} {dev[1]}", + "cost_price": round(random.uniform(150, 9500), 2), + "low_stock_alert": 5, "supplier": sups[i % 100]["company_name"], + "barcode": f"8900001{i:05d}", "is_active": 1 if i % 9 else 0}) + S.insert(DB_C, "parts", parts) + + contacts, caddrs = [], [] + for i in range(1, 111): + fn, ln, email, ph = person() + cid = new_ulid() + contacts.append({"contact_id": cid, "first_name": fn, "last_name": ln, "email": email, + "phone": ph, "gender": random.choice(["Male", "Female"]), + "dob": days_ago(random.randint(8000, 15000)).date(), + "created_at": days_ago(random.randint(1, 90))}) + city, state, pin = CITIES[i % len(CITIES)] + caddrs.append({"address_id": new_ulid(), "contact_id": cid, "type": random.choice(["BILLING", "SHIPPING"]), + "address_line1": f"{random.randint(1, 300)}, {random.choice(STREETS)}", + "city": city, "state": state, "country": "India", + "postal_code": f"{pin}{random.randint(100, 999)}", "is_default": 1}) + S.insert(DB_C, "contacts", contacts) + S.insert(DB_C, "contact_addresses", caddrs) + return {"locations": locs, "warehouses": whs, "suppliers": sups, "terminals": terms, + "sync_terms": sync_terms, "coupons": coupons, "service_types": all_st, + "tag_service_types": tag_st, + "parts": parts, "staff_contacts": contacts} + + +# =========================================================================== # +# STAGE 3 — customers (ecom + crm), addresses, devices +# =========================================================================== # +def stage_customers(): + print("STAGE 3: customers & devices") + from passlib.context import CryptContext + ctx = CryptContext(schemes=["argon2"], deprecated="auto") + cust_hash = ctx.hash(CUSTOMER_PASSWORD) + + ecoms, eadds, edevs = [], [], [] + ecom_ids = [] + for i in range(1, 120): + fn, ln = random.choice(FIRST), random.choice(LAST) + email = slug_email(fn, ln) + cid = new_ulid() + ecom_ids.append(cid) + ecoms.append({"customer_id": cid, "email": email, "password_hash": cust_hash, + "first_name": fn, "last_name": ln, "phone": phone(), + "is_active": 1, "email_verified": 1, "phone_verified": 1, + "failed_login_attempts": 0, "is_locked": 0, + "last_login": days_ago(random.randint(0, 30), random.randint(9, 21)), + "created_at": days_ago(random.randint(5, 200)), "updated_at": days_ago(0)}) + n_addr = random.choice([1, 1, 1, 2]) + for a in range(n_addr): + ad = addr() + ad.update({"address_id": new_ulid(), "customer_id": cid, + "address_type": "SHIPPING" if a == 0 else random.choice(["SHIPPING", "BILLING"]), + "full_name": f"{fn} {ln}", "phone": phone(), + "is_default": 1 if a == 0 else 0, "created_at": days_ago(random.randint(1, 100))}) + eadds.append(ad) + if i <= 130: + dev = random.choice(DEVICES) + edevs.append({"device_id": new_ulid(), "customer_id": cid, "brand": dev[0], + "model": dev[1], "model_number": f"SM-{random.randint(10000, 99999)}", + "imei_primary": "".join(random.choice(string.digits) for _ in range(15)), + "color": random.choice(["Black", "White", "Blue", "Silver", "Gold"]), + "device_condition": random.choice(["Good", "Fair", "Cracked back", "Scratched body"]), + "device_type": dev[2], + "storage_capacity": random.choice(["64GB", "128GB", "256GB"]), + "created_at": days_ago(random.randint(1, 120)), "updated_at": days_ago(0)}) + S.insert(DB_E, "ecom_customers", ecoms, "storefront customers") + S.insert(DB_E, "customer_addresses", eadds) + S.insert(DB_E, "customer_devices", edevs) + + # CRM customers (36-char ULIDs per schema; keep same generator output) + crm_c, crm_devs, crm_conts = [], [], [] + crm_ids = [] + for i in range(1, 121): + fn, ln, email, ph = person() + cid = new_ulid() + crm_ids.append(cid) + ltv = round(random.choice([random.uniform(500, 9000), random.uniform(10000, 45000), + random.uniform(50000, 95000), random.uniform(100000, 300000)]), 2) + o_count = random.randint(0, 12) if ltv > 5000 else random.randint(0, 2) + r_count = random.randint(0, 10) if ltv > 3000 else random.randint(0, 2) + crm_c.append({"customer_id": cid, "tenant_id": TENANT, "name": f"{fn} {ln}", + "email": email, "phone": ph, + "sales_tier": ("PLATINUM" if ltv >= 100000 else "GOLD" if ltv >= 50000 + else "SILVER" if ltv >= 10000 else "BRONZE"), + "service_tier": random.choice(["STANDARD"] * 7 + ["PRIORITY"] * 2 + ["VIP"]), + "total_orders_count": o_count, "total_repairs_count": r_count, + "total_lifetime_value_inr": ltv, "is_dual_customer": 1 if (o_count and r_count) else 0, + "notes": f"{random.choice(NOTE_PREFIXES)} {TAG}", + "created_by": "seed-script", "updated_by": "seed-script", "version": 1}) + city, state, pin = CITIES[i % len(CITIES)] + crm_conts.append({"contact_id": new_ulid(), "tenant_id": TENANT, "customer_id": cid, + "address": f"{random.randint(1, 300)}, {random.choice(STREETS)}", + "city": city, "state": state, "pincode": f"{pin}{random.randint(100, 999)}", + "alternate_phone": phone(), + "created_by": "seed-script", "updated_by": "seed-script", "version": 1}) + for d in range(random.choice([1, 1, 1, 2])): + dev = random.choice(DEVICES) + crm_devs.append({"device_id": new_ulid(), "tenant_id": TENANT, "customer_id": cid, + "brand": dev[0], "model_name": dev[1], + "color": random.choice(["Black", "White", "Blue", "Silver"]), + "imei_serial": "".join(random.choice(string.digits) for _ in range(15)), + "cosmetic_condition": random.choice(["Good", "Fair", "Poor"]), + "notes": f"Registered at store. {TAG}", + "created_by": "seed-script", "updated_by": "seed-script", "version": 1}) + S.insert(DB_E, "crm_customers", crm_c, "crm customers") + S.insert(DB_E, "crm_contacts", crm_conts) + S.insert(DB_E, "crm_customer_devices", crm_devs) + return {"ecom_ids": ecom_ids, "crm_ids": crm_ids, "crm_devs": crm_devs, "edevs": edevs} + + +# =========================================================================== # +# STAGE 4 — CRM pipeline: leads, deals, tasks, calendar, quotations, GST invoices +# =========================================================================== # +def stage_pipeline(staff, refs, custs): + print("STAGE 4: CRM pipeline") + sales_ids = staff["sales_ids"] or [staff["users"][0]["user_id"]] + crm_ids = custs["crm_ids"] + variants = [(r[0], r[1], float(r[2]), r[3], r[4]) for r in S.fetch( + f"SELECT v.variant_id, v.sku, v.price, p.name, p.product_id " + f"FROM {DB_E}.product_variants v JOIN {DB_E}.products p ON p.product_id=v.product_id " + f"WHERE v.status='active' LIMIT 1500")] + + leads = [] + for i in range(1, 121): + fn, ln, email, ph = person() + dev = random.choice(DEVICES) + status = random.choice(["NEW"] * 3 + ["CONTACTED"] * 3 + ["QUALIFIED"] * 2 + + ["QUOTE_DRAFT"] + ["QUOTE_SENT"] * 2 + ["CONVERTED"] * 2 + ["LOST"]) + lid = new_ulid() + row = {"lead_id": lid, "tenant_id": TENANT, + "customer_id": random.choice(crm_ids) if i % 3 == 0 else None, + "title": f"{dev[0]} {dev[1]} - {random.choice(ISSUES)}", + "phone": ph, "email": email, "first_name": fn, "last_name": ln, + "source": random.choice(["STOREFRONT", "WHATSAPP", "WALK_IN", "PHONE", "SOCIAL"]), + "status": status, "score": random.randint(10, 95), + "assigned_user_id": random.choice(sales_ids), + "notes": f"{random.choice(NOTE_PREFIXES)} {TAG}", + "created_by": "seed-script", "updated_by": "seed-script", "version": 1} + if status in ("QUOTE_DRAFT", "QUOTE_SENT", "CONVERTED"): + amt = round(random.uniform(1200, 25000), 2) + row.update({"quote_amount": amt, + "quote_title": f"{dev[1]} repair & spares quote", + "quote_terms": "50% advance, balance on delivery. 6-month service warranty.", + "quote_sent_at": days_ago(random.randint(1, 20)), + "quote_sent_by": random.choice(sales_ids)}) + leads.append(row) + S.insert(DB_E, "crm_leads", leads) + + deals = [] + stage_prob = {"NEW": 15, "CONTACTED": 30, "REQUIREMENT_AUDIT": 40, "PROPOSAL_SENT": 55, + "NEGOTIATION": 65, "BULK_QUOTE_SENT": 60, "CLOSED_WON": 100, "CLOSED_LOST": 0, + "WON": 100, "LOST": 0} + stages = (["NEW"] * 14 + ["CONTACTED"] * 16 + ["REQUIREMENT_AUDIT"] * 12 + + ["PROPOSAL_SENT"] * 14 + ["NEGOTIATION"] * 12 + ["BULK_QUOTE_SENT"] * 10 + + ["CLOSED_WON"] * 16 + ["CLOSED_LOST"] * 16) + random.shuffle(stages) + for i, st in enumerate(stages[:110]): + deals.append({"deal_id": new_ulid(), "tenant_id": TENANT, + "lead_id": leads[i % 120]["lead_id"] if i < 90 else None, + "customer_id": random.choice(crm_ids) if i % 2 else None, + "title": f"{random.choice(DEVICES)[1]} bulk supply / repair deal {i + 1:03d}", + "stage": st, "estimated_value": round(random.uniform(3000, 150000), 2), + "probability_percent": stage_prob[st], + "assigned_user_id": random.choice(sales_ids), + "notes": f"{random.choice(NOTE_PREFIXES)} {TAG}", + "created_by": "seed-script", "updated_by": "seed-script", "version": 1}) + S.insert(DB_E, "crm_deals", deals) + + tasks = [] + for i in range(1, 111): + etype = random.choice(["LEAD", "DEAL", "REPAIR_TICKET", "CUSTOMER", "ORDER", "QUOTATION"]) + eid = {"LEAD": lambda: random.choice(leads)["lead_id"], "DEAL": lambda: random.choice(deals)["deal_id"], + "CUSTOMER": lambda: random.choice(crm_ids)}.get(etype, lambda: new_ulid())() + done = i % 3 == 0 + tasks.append({"task_id": new_ulid(), "tenant_id": TENANT, + "location_id": random.choice(refs["locations"][:10])["location_id"], + "title": random.choice(["Follow up call", "Send revised quotation", "Collect device from customer", + "Prepare GST invoice", "Stock count for spares", "Technician handover", + "Customer feedback call", "Payment reminder call"]), + "description": f"Auto-generated follow-up task {TAG}", + "assignee_id": random.choice(sales_ids), + "entity_type": etype, "entity_id": eid, + "priority": random.choice(["HIGH"] * 2 + ["MEDIUM"] * 5 + ["LOW"] * 2), + "status": "COMPLETED" if done else "PENDING", + "due_at": in_days(random.randint(-10, 14)) if not done else days_ago(random.randint(1, 10)), + "completed_at": days_ago(random.randint(1, 9)) if done else None, + "created_by": "seed-script", "updated_by": "seed-script", "version": 1}) + S.insert(DB_E, "crm_tasks", tasks) + + events = [] + for i in range(1, 111): + start = now() + timedelta(days=random.randint(-20, 20), hours=random.randint(9, 17), minutes=random.choice([0, 30])) + linked = i % 4 == 0 + st = "SCHEDULED" if start > now() else random.choice(["COMPLETED"] * 3 + ["CANCELLED"]) + events.append({"event_id": new_ulid(), "tenant_id": TENANT, + "location_id": random.choice(refs["locations"][:10])["location_id"], + "task_id": random.choice(tasks)["task_id"] if i % 5 == 0 else None, + "title": random.choice(["Customer visit", "Device pickup", "Quotation review meeting", + "Vendor meeting", "Store audit", "Technician briefing", + "Delivery coordination", "Bulk client demo"]), + "description": f"Calendar demo event {TAG}", + "source_type": "REPAIR_TICKET" if linked else "MANUAL", + "source_id": new_ulid() if linked else None, + "start_time": start, "end_time": start + timedelta(minutes=random.choice([30, 45, 60, 90])), + "is_all_day": 0, "status": st, + "created_by": "seed-script", "updated_by": "seed-script", "version": 1}) + S.insert(DB_E, "crm_calendar_events", events) + + quotes, qitems = [], [] + used_qn = set() + for i in range(1, 111): + qid = new_ulid() + while True: + qn = f"IFK-QT-2026-{random.randint(100, 999)}" + if qn not in used_qn: + used_qn.add(qn) + break + gross = 0.0 + taxable_sum, tax_sum = 0.0, 0.0 + items = [] + for k in range(random.randint(1, 4)): + _v, sku, price, name, _p = random.choice(variants) + qty = random.randint(1, 10) + tp = round(price * qty, 2) + tax_pct = random.choice([18, 18, 18, 12, 28]) + taxable = round(tp / (1 + tax_pct / 100), 2) + gross += tp + taxable_sum += taxable + tax_sum += (tp - taxable) + items.append({"item_id": new_ulid(), "quote_id": qid, "sku": sku, + "description": name[:250], "quantity": qty, + "unit_price": price, "tax_percent": tax_pct, "total_price": tp, + "created_by": "seed-script", "updated_by": "seed-script", "version": 1}) + discount = round(random.choice([0, 0, 0, gross * 0.05]), 2) + grand = round(taxable_sum + tax_sum - discount, 2) + status = random.choice(["DRAFT"] * 3 + ["SENT"] * 4 + ["ACCEPTED"] * 2 + ["CONVERTED"] * 2 + ["EXPIRED"]) + quotes.append({"quote_id": qid, "quote_number": qn, "tenant_id": TENANT, + "customer_id": random.choice(crm_ids), "status": status, + "valid_until": in_days(random.choice([7, 15, 30])), + "subtotal": round(taxable_sum, 2), "discount_amount": discount, + "tax_amount": round(tax_sum, 2), "grand_total": grand, + "notes": f"Bulk quotation demo {TAG}", + "created_by": "seed-script", "updated_by": "seed-script", "version": 1}) + qitems.extend(items) + S.insert(DB_E, "crm_bulk_quotations", quotes) + S.insert(DB_E, "crm_bulk_quotation_items", qitems) + + ginv, gitems = [], [] + used_inv = set() + for i in range(1, 111): + iid = new_ulid() + while True: + ino = f"IFK-INV-2026-{random.randint(1000, 9999)}" + if ino not in used_inv: + used_inv.add(ino) + break + itype = random.choice(["RETAIL"] * 6 + ["B2B"] * 3 + ["PROFORMA"]) + gross = 0.0 + taxable_sum, tax_sum = 0.0, 0.0 + items = [] + for k in range(random.randint(1, 4)): + _v, sku, price, name, _p = random.choice(variants) + qty = random.randint(1, 8) + tp = round(price * qty, 2) + tax_pct = random.choice([18, 18, 12, 28]) + taxable = round(tp / (1 + tax_pct / 100), 2) + gross += tp + taxable_sum += taxable + tax_sum += (tp - taxable) + items.append({"item_id": new_ulid(), "invoice_id": iid, "sku": sku, + "description": name[:250], "hsn_sac_code": random.choice(["8517", "8471", "8544", "8507"]), + "imei_serial": "".join(random.choice(string.digits) for _ in range(15)) if itype == "RETAIL" else None, + "quantity": qty, "unit_price": price, "tax_percent": tax_pct, + "warranty_months": random.choice([3, 6, 12]), "total_price": tp, + "created_by": "seed-script", "updated_by": "seed-script", "version": 1}) + discount = round(random.choice([0, 0, gross * 0.03]), 2) + grand = round(taxable_sum + tax_sum - discount, 2) + pay_status = random.choice(["PAID"] * 5 + ["UNPAID"] * 3 + ["PARTIAL"] * 2) + paid = {"PAID": grand, "PARTIAL": round(grand * 0.5, 2), "UNPAID": 0.0}[pay_status] + tax_h = round(tax_sum / 2, 2) + ginv.append({"invoice_id": iid, "invoice_number": ino, "tenant_id": TENANT, + "customer_id": random.choice(crm_ids), "invoice_type": itype, + "subtotal": round(taxable_sum, 2), "discount_amount": discount, + "cgst_amount": tax_h, "sgst_amount": tax_h, "igst_amount": 0.0, + "grand_total": grand, "payment_status": pay_status, "paid_amount": paid, + "notes": f"GST invoice demo {TAG}", + "created_by": "seed-script", "updated_by": "seed-script", "version": 1}) + gitems.extend(items) + S.insert(DB_E, "crm_gst_invoices", ginv) + S.insert(DB_E, "crm_invoice_items", gitems) + return {"leads": leads, "deals": deals, "variants": variants} + + +# =========================================================================== # +# STAGE 5 — orders, items, history, invoices, payments, wallets +# =========================================================================== # +def stage_orders(refs, custs, staff): + print("STAGE 5: orders & billing") + ecom_ids = custs["ecom_ids"] + eaddr = {r[1]: r for r in S.fetch( + f"SELECT address_id, customer_id, full_name, phone, street_address, city, state, pincode " + f"FROM {DB_E}.customer_addresses WHERE is_default=1")} + variants = [(r[0], r[1], float(r[2]), r[3], r[4]) for r in S.fetch( + f"SELECT v.variant_id, v.sku, v.price, p.name, p.product_id " + f"FROM {DB_E}.product_variants v JOIN {DB_E}.products p ON p.product_id=v.product_id " + f"WHERE v.status='active' LIMIT 1500")] + coupons_active = [c for c in refs["coupons"] if c["is_active"]] + used_inv_nos = set() + used_ord = {r[0] for r in S.fetch(f"SELECT order_no FROM {DB_E}.orders")} + day_seq: dict[str, int] = {} + + def next_order_no(d: datetime) -> str: + key = d.strftime("%Y%m%d") + while True: + day_seq[key] = day_seq.get(key, 100 if key == "20261115" else 0) + 1 + no = f"ORD-{key}-{day_seq[key]:04d}" + if no not in used_ord: + used_ord.add(no) + return no + + orders, items, hist, invs, pays, usages = [], [], [], [], [], [] + inv_seq = 10 + for i in range(1, 121): + days_back = int((i / 121) ** 1.2 * 62) + created = days_ago(days_back, random.randint(9, 21), random.randint(0, 59)) + cust_id = random.choice(ecom_ids) + n_items = random.choice([1, 1, 2, 2, 3]) + subtotal, its = 0.0, [] + picked = random.sample(variants, n_items) + for v_id, sku, price, name, p_id in picked: + qty = random.randint(1, 2) if random.random() < 0.25 else 1 + tp = round(price * qty, 2) + subtotal += tp + its.append({"item_id": new_ulid(), "product_id": p_id, "variant_id": v_id, + "product_name": name[:250], "sku": sku, "unit_price": price, + "quantity": qty, "total_price": tp, "part_numbers": None}) + tax = round(subtotal - subtotal / 1.18, 2) + coupon = random.choice(coupons_active) if random.random() < 0.15 else None + discount = 0.0 + if coupon: + discount = (round(subtotal * coupon["discount_value"] / 100, 2) + if coupon["discount_type"] == "PERCENTAGE" else float(coupon["discount_value"])) + discount = min(discount, subtotal) + shipping = 99.0 + final_amt = round(subtotal + shipping - discount, 2) + age = (now() - created).days + if age < 2: + st = random.choice(["ORDER_CREATED", "ORDER_CONFIRMED", "PROCESSING"]) + elif age < 5: + st = random.choice(["PROCESSING", "PACKED", "SHIPPED", "OUT_FOR_DELIVERY", "DELIVERED"]) + else: + st = random.choice(["DELIVERED"] * 6 + ["SHIPPED"] + ["CANCELLED"] * 2 + ["DELIVERED"]) + pay_st = ("PAYMENT_PENDING" if st in ("ORDER_CREATED", "ORDER_CONFIRMED") + else "PAYMENT_FAILED" if st == "CANCELLED" and random.random() < 0.6 + else "PAYMENT_CAPTURED") + oid = new_ulid() + ad = eaddr.get(cust_id) + if not ad: + ad_rows = S.fetch( + f"SELECT full_name, phone, street_address, city, state, pincode " + f"FROM {DB_E}.customer_addresses WHERE customer_id=%s LIMIT 1", (cust_id,)) + ad = ad_rows[0] if ad_rows else None + addr_j = j({"full_name": ad[0], "phone": ad[1], "street_address": ad[2], + "city": ad[3], "state": ad[4], "pincode": ad[5], "address_type": "SHIPPING"}) if ad else \ + j({"full_name": "Demo Customer", "phone": "9000000000", "street_address": "Demo Street", + "city": "Chennai", "state": "Tamil Nadu", "pincode": "600001", "address_type": "SHIPPING"}) + shipped = st in ("SHIPPED", "OUT_FOR_DELIVERY", "DELIVERED") + orders.append({"order_id": oid, "order_no": next_order_no(created), "customer_id": cust_id, + "total_amount": round(subtotal, 2), "discount_amount": round(discount, 2), + "tax_amount": tax, "shipping_cost": shipping, "final_amount": final_amt, + "status": st, "payment_status": pay_st, + "fulfillment_status": "FULFILLED" if st == "DELIVERED" else + ("READY_FOR_DELIVERY" if st == "OUT_FOR_DELIVERY" else "UNFULFILLED"), + "shipping_address_json": addr_j, "billing_address_json": addr_j, + "tracking_number": f"SR{random.randint(10 ** 11, 10 ** 12)}" if shipped else None, + "courier_name": random.choice(["Delhivery", "Blue Dart", "DTDC"]) if shipped else None, + "logistics_provider": "SHIPROCKET", "pickup_scheduled": 0, + "last_logistics_status": "DELIVERED" if st == "DELIVERED" else None, + "created_at": created, "updated_at": min(created + timedelta(hours=48), now()), + "coupon_id": coupon["coupon_id"] if coupon else None, + "coupon_code": coupon["code"] if coupon else None, + "discount_type": "FIXED", "discount_reason": None, + "is_discounted": 1 if coupon else 0}) + for it in its: + it["order_id"] = oid + items.extend(its) + # status history + path = {"DELIVERED": ["ORDER_CREATED", "ORDER_CONFIRMED", "PROCESSING", "PACKED", "SHIPPED", "OUT_FOR_DELIVERY", "DELIVERED"], + "OUT_FOR_DELIVERY": ["ORDER_CREATED", "ORDER_CONFIRMED", "PROCESSING", "PACKED", "SHIPPED", "OUT_FOR_DELIVERY"], + "SHIPPED": ["ORDER_CREATED", "ORDER_CONFIRMED", "PROCESSING", "PACKED", "SHIPPED"], + "PACKED": ["ORDER_CREATED", "ORDER_CONFIRMED", "PROCESSING", "PACKED"], + "PROCESSING": ["ORDER_CREATED", "ORDER_CONFIRMED", "PROCESSING"], + "ORDER_CONFIRMED": ["ORDER_CREATED", "ORDER_CONFIRMED"], + "ORDER_CREATED": ["ORDER_CREATED"], + "CANCELLED": ["ORDER_CREATED", "ORDER_CONFIRMED", "CANCELLED"]}[st] + prev = "NEW" + for k, s in enumerate(path): + hist.append({"history_id": new_ulid(), "order_id": oid, "previous_status": prev, + "new_status": s, "changed_by": "SYSTEM" if k else "customer", + "reason": "Demo seed history", "created_at": created + timedelta(hours=k * 14)}) + prev = s + if pay_st in ("PAYMENT_CAPTURED", "PAYMENT_PENDING", "PAYMENT_FAILED"): + pays.append({"payment_id": new_ulid(), "order_id": oid, + "provider": "RAZORPAY" if random.random() < 0.8 else "CASH", + "transaction_ref": f"pay_demo{random.randint(10 ** 10, 10 ** 11)}" if pay_st != "PAYMENT_PENDING" else None, + "razorpay_order_id": f"order_demo{random.randint(10 ** 10, 10 ** 11)}" if pay_st != "PAYMENT_PENDING" else None, + "razorpay_signature": None, "amount": final_amt, "currency": "INR", + "status": "CAPTURED" if pay_st == "PAYMENT_CAPTURED" else + ("FAILED" if pay_st == "PAYMENT_FAILED" else "PENDING"), + "raw_response_json": j({"demo": True, TAG: True}), + "created_at": created}) + if pay_st == "PAYMENT_CAPTURED" and inv_seq < 100 + 10: + inv_seq += 1 + ino = f"C1P1-26-{inv_seq:06d}" + used_inv_nos.add(ino) + invs.append({"invoice_id": new_ulid(), "invoice_no": ino, "order_id": oid, + "pos_transaction_id": None, "customer_id": cust_id, + "subtotal": round(subtotal, 2), "discount_amount": round(discount, 2), + "cgst": round(tax / 2, 2), "sgst": round(tax / 2, 2), "igst": 0.0, + "total_amount": final_amt, "pdf_path": None, "status": "GENERATED", + "created_at": created + timedelta(hours=1)}) + if coupon: + usages.append({"usage_id": new_ulid(), "coupon_id": coupon["coupon_id"], + "customer_id": cust_id, "order_id": oid, + "discount_amount": round(discount, 2), "used_at": created}) + # pad usage history so the coupon module shows a healthy ledger + active_coupons = [c for c in refs["coupons"] if c["is_active"]] + while len(usages) < 110: + o = random.choice(orders) + c = random.choice(active_coupons) + usages.append({"usage_id": new_ulid(), "coupon_id": c["coupon_id"], + "customer_id": o["customer_id"], "order_id": o["order_id"], + "discount_amount": round(random.uniform(20, 900), 2), + "used_at": o["created_at"]}) + S.insert(DB_E, "orders", orders) + S.insert(DB_E, "order_items", items) + S.insert(DB_E, "order_status_history", hist) + S.insert(DB_E, "invoices", invs, f"{len(invs)} for captured") + S.insert(DB_E, "payment_ledger", pays) + S.insert(DB_E, "coupon_usages", usages) + + # keep the pre-existing coupon usage counters plausible + for c in refs["coupons"]: + c["times_used"] = c["times_used"] + S.insert(DB_E, "customer_wallets", [ + {"wallet_id": new_ulid(), "customer_id": cid, "active_balance": round(random.uniform(0, 1500), 2), + "pending_balance": round(random.uniform(0, 500), 2), + "lifetime_earned": round(random.uniform(100, 5000), 2), + "lifetime_redeemed": round(random.uniform(0, 2000), 2), "currency": "INR", "is_locked": 0, + "created_at": days_ago(random.randint(10, 120)), "updated_at": days_ago(0)} + for cid in ecom_ids[:100]]) + wts = S.fetch(f"SELECT wallet_id, customer_id FROM {DB_E}.customer_wallets LIMIT 100") + S.insert(DB_E, "wallet_transactions", [ + {"transaction_id": new_ulid(), "wallet_id": w[0], "customer_id": w[1], + "transaction_type": random.choice(["CASHBACK", "REFERRAL_BONUS", "SERVICE_CREDIT", "REFUND"]), + "reference_type": "ORDER", "reference_id": random.choice(orders)["order_id"], + "reference_no": random.choice(orders)["order_no"], + "base_amount": round(random.uniform(200, 5000), 2), "percentage_applied": random.choice([2.0, 5.0, None]), + "credit_amount": round(random.uniform(50, 800), 2), + "status": random.choice(["MATURED"] * 6 + ["PENDING_MATURITY"] * 2 + ["VOIDED"]), + "matures_at": in_days(random.randint(-20, 30)), "matured_at": days_ago(random.randint(0, 20)), + "voided_at": None, "void_reason": None, + "description": f"Wallet demo credit {TAG}", "created_at": days_ago(random.randint(1, 40)), + "updated_at": days_ago(0)} for w in wts]) + return {"orders": orders} + + +# =========================================================================== # +# STAGE 6 — technicians + service engine +# =========================================================================== # +def stage_services(staff, custs, refs): + print("STAGE 6: technicians & service engine") + tech_users = staff["tech_user_ids"][:100] + ecom_ids = custs["ecom_ids"] + edevs = custs["edevs"] + st_ids = refs["service_types"] + tag_st_ids = refs["tag_service_types"] + + profiles = [{"technician_id": new_ulid(), "user_id": uid, "active": 1 if i % 10 else 0} + for i, uid in enumerate(tech_users)] + S.insert(DB_E, "technician_profiles", profiles) + skills, skill_seen = [], set() + for p in profiles: + n = random.randint(2, 3) + picked = random.sample(tag_st_ids, min(n, len(tag_st_ids))) + for st in picked: + key = (p["technician_id"], st) + if key in skill_seen: + continue + skill_seen.add(key) + skills.append({"technician_id": p["technician_id"], "service_type_id": st, + "skill_level": random.randint(1, 5)}) + S.insert(DB_E, "technician_skills", skills) + # NOTE: technician_skills FK → crm.service_types via seeded (tagged) ids only + S.insert(DB_E, "technician_working_hours", [ + {"working_hour_id": new_ulid(), "technician_id": p["technician_id"], + "day_of_week": d, "start_time": "09:00", "end_time": "18:00"} + for p in profiles for d in range(6)]) + leaves = [] + for i in range(1, 111): + p = random.choice(profiles) + s = now() + timedelta(days=random.randint(-15, 30)) + leaves.append({"leave_id": new_ulid(), "technician_id": p["technician_id"], + "start_datetime": s, "end_datetime": s + timedelta(days=random.choice([1, 1, 2, 3])), + "reason": random.choice(["Casual Leave", "Sick Leave", "Personal Work", "Training"])}) + S.insert(DB_E, "technician_leaves", leaves) + + # service catalog from the 95 new service types (service_id = service_type_id) + catalog = [{"service_id": st, "name": n, "description": f"Catalog service {TAG}", + "base_price": round(random.uniform(299, 7500), 2), + "estimated_duration_minutes": random.choice([60, 90, 120, 180, 240]), + "workflow_type": random.choice(["FIXED_SERVICE", "INSPECTION_REQUIRED", "REPAIR_QUOTE"]), + "active": 1} + for st, n in zip(tag_st_ids, tag_st_ids)] + cat_names = {r[0]: r[1] for r in S.fetch(f"SELECT service_type_id, name FROM {DB_C}.service_types")} + for c in catalog: + c["name"] = cat_names.get(c["service_id"], c["name"]) + S.insert(DB_E, "service_catalog", catalog) + + brand_ids = {r[0]: r[1] for r in S.fetch(f"SELECT name, brand_id FROM {DB_E}.brands")} + model_ids = {r[0]: r[1] for r in S.fetch(f"SELECT name, model_id FROM {DB_E}.device_models")} + series_ids = {r[0]: r[1] for r in S.fetch(f"SELECT name, series_id FROM {DB_E}.device_series")} + + jobs, appts, intakes, assigns, insp, quotes, pays, events = [], [], [], [], [], [], [], [] + used_job = set() + for i in range(1, 141): + days_back = int((i / 141) ** 1.2 * 55) + created = days_ago(days_back, random.randint(9, 19)) + dev = random.choice(edevs) + cat = random.choice(catalog) + while True: + job_no = f"SRV-{int(created.timestamp())}-{random.choice(string.ascii_uppercase)}{random.choice(string.ascii_uppercase)}{random.randint(10, 99)}X" + if job_no not in used_job: + used_job.add(job_no) + break + age = (now() - created).days + if age < 1: + st = random.choice(["BOOKING_PENDING", "BOOKED"]) + elif age < 3: + st = random.choice(["DEVICE_INTAKE", "INSPECTION_COMPLETED", "QUOTE_SENT", "QUOTE_ACCEPTED"]) + elif age < 7: + st = random.choice(["QUOTE_ACCEPTED", "READY_FOR_DELIVERY", "DELIVERED", "CUSTOMER_REJECTED"]) + else: + st = random.choice(["DELIVERED"] * 4 + ["COMPLETED"] * 4 + ["CLOSED"] * 3 + ["CANCELLED"]) + jid = new_ulid() + fulfillment = random.choice(["WALK_IN"] * 5 + ["COURIER"] * 2 + ["DOORSTEP_PICKUP"]) + jobs.append({"job_id": jid, "job_no": job_no, "customer_id": dev["customer_id"], + "device_id": dev["device_id"], "source": random.choice(["ONLINE"] * 6 + ["WALK_IN"]), + "service_id": cat["service_id"], "status": st, + "custom_service_name": cat["name"], + "replaced_part_numbers": j([f"PRT-{random.randint(1000, 9999)}"]) if st in ("DELIVERED", "COMPLETED", "CLOSED") else None, + "device_type": dev.get("device_type") or "mobile", + "brand_id": brand_ids.get(dev["brand"]) or random.choice(list(brand_ids.values())), + "series_id": series_ids.get(dev["model"]) or random.choice(list(series_ids.values())), + "model_id": model_ids.get(dev["model"]) or random.choice(list(model_ids.values())), + "service_type_id": None, "repair_service_id": None, "repair_variant_id": None, + "currency": "INR", "service_name_snapshot": cat["name"], + "variant_name_snapshot": None, + "base_price_snapshot": cat["base_price"], + "duration_snapshot": cat["estimated_duration_minutes"], + "warranty_snapshot": 90, "inspection_fee_snapshot": 199.0, + "queue_number": f"W-{created.year}-{i:03d}", "queue_date": created.date(), + "priority": random.choice(["NORMAL"] * 7 + ["HIGH"] * 2 + ["URGENT"]), + "fulfillment_type": fulfillment, + "fulfillment_fee": 0.0 if fulfillment == "WALK_IN" else round(random.uniform(99, 299), 2), + "alt_phone": None, "is_whatsapp_alt": 0, + "delivery_address": f"{random.randint(1, 200)}, {random.choice(STREETS)}, Chennai" if fulfillment != "WALK_IN" else None, + "pre_dispatch_video_id": None, + "courier_name": "DTDC" if fulfillment == "COURIER" else None, + "awb_number": f"AWB{random.randint(10 ** 9, 10 ** 10)}" if fulfillment == "COURIER" else None, + "pickup_status": "PICKUP_SCHEDULED" if fulfillment == "COURIER" else None, + "lock_type": random.choice(["NONE", "PIN", "PATTERN", "PASSWORD"]), + "lock_credential_encrypted": None, "lock_credential_created_at": None, + "lock_credential_accessed_at": None, "lock_credential_accessed_by": None, + "lock_credential_deleted_at": None, + "created_at": created, "updated_at": min(created + timedelta(days=3), now())}) + appts.append({"appointment_id": new_ulid(), "service_job_id": jid, + "scheduled_start": created + timedelta(days=1, hours=2), + "scheduled_end": created + timedelta(days=1, hours=5), + "status": "COMPLETED" if age >= 1 else "SCHEDULED", + "hold_expires_at": None, "created_at": created, + "confirmed_at": created + timedelta(hours=1), "cancelled_at": None, + "reminder_sent": 1, "reminder_sent_at": created + timedelta(hours=2)}) + if st not in ("BOOKING_PENDING", "BOOKED", "CANCELLED"): + intakes.append({"intake_id": new_ulid(), "service_job_id": jid, + "received_by": random.choice(staff["tech_user_ids"]), + "received_at": created + timedelta(days=1), + "power_status": random.choice(["Booting OK", "Not powering on", "Boots, random shutdown"]), + "screen_condition": random.choice(["Cracked", "Intact", "Dead pixels", "Touch not working"]), + "body_condition": random.choice(["Good", "Dented corners", "Bent frame"]), + "back_condition": random.choice(["Cracked", "Scratched", "Intact"]), + "camera_condition": random.choice(["OK", "Blurry", "Glass cracked"]), + "accessories": random.choice(["Charger + cable", "Device only", "Box + charger"]), + "customer_notes": f"{random.choice(ISSUES)}. {TAG}", + "technician_notes": "Checked on bench, condition noted."}) + tech = random.choice(profiles)["technician_id"] + if st in ("INSPECTION_COMPLETED", "QUOTE_SENT", "QUOTE_ACCEPTED", "READY_FOR_DELIVERY", + "DELIVERED", "COMPLETED", "CLOSED", "CUSTOMER_REJECTED"): + assigns.append({"assignment_id": new_ulid(), "service_job_id": jid, + "appointment_id": appts[-1]["appointment_id"], + "technician_id": tech, "assigned_at": created + timedelta(days=1, hours=3), + "assigned_by": "seed-script", "unassigned_at": None, + "reason": "Assigned via Service Management"}) + result = random.choice(["CUSTOMER_REPORT_CONFIRMED"] * 5 + + ["CUSTOMER_REPORT_PARTIALLY_CONFIRMED"] * 2 + + ["ADDITIONAL_DAMAGE_FOUND"]) + insp.append({"inspection_id": new_ulid(), "service_job_id": jid, "technician_id": tech, + "result": result, + "customer_report": random.choice(ISSUES), + "confirmed_damage": random.choice(ISSUES), + "additional_damage": "Water marks on logic board" if result == "ADDITIONAL_DAMAGE_FOUND" else None, + "notes": f"Bench inspection {TAG}", + "created_at": created + timedelta(days=2)}) + if st in ("QUOTE_SENT", "QUOTE_ACCEPTED", "READY_FOR_DELIVERY", "DELIVERED", "COMPLETED", "CLOSED", "CUSTOMER_REJECTED"): + sub = round(random.uniform(800, 12000), 2) + tax = round(sub * 0.18, 2) + qstat = ("ACCEPTED" if st in ("QUOTE_ACCEPTED", "READY_FOR_DELIVERY", "DELIVERED", "COMPLETED", "CLOSED") + else "REJECTED" if st == "CUSTOMER_REJECTED" else "PENDING_CUSTOMER") + qid = new_ulid() + quotes.append({"quote_id": qid, "service_job_id": jid, "version": 1, + "subtotal": sub, "tax": tax, "additional_damage_amount": 0.0, + "total": round(sub + tax, 2), "status": qstat, + "reason": None if qstat != "REJECTED" else "Customer chose replacement device", + "expires_at": created + timedelta(days=4), + "accepted_at": created + timedelta(days=2) if qstat == "ACCEPTED" else None, + "rejected_at": created + timedelta(days=2) if qstat == "REJECTED" else None, + "created_by": "seed-script", "created_at": created + timedelta(days=2)}) + if qstat == "ACCEPTED": + pays.append({"payment_id": new_ulid(), "service_job_id": jid, "quote_id": qid, + "payment_type": "ADVANCE", "amount": round(sub * 0.3, 2), + "status": "CAPTURED", "provider": random.choice(["RAZORPAY", "UPI", "CASH"]), + "provider_order_id": None, + "provider_payment_id": f"pay_srv{random.randint(10 ** 10, 10 ** 11)}", + "provider_signature": None, "transaction_reference": None, + "provider_refund_id": None, "refund_reason": None, "refunded_at": None, + "created_at": created + timedelta(days=2), "paid_at": created + timedelta(days=2)}) + if st in ("DELIVERED", "COMPLETED", "CLOSED"): + pays.append({"payment_id": new_ulid(), "service_job_id": jid, "quote_id": qid, + "payment_type": "FINAL", "amount": round(sub * 0.7 + tax, 2), + "status": "CAPTURED", "provider": random.choice(["RAZORPAY", "UPI", "CASH"]), + "provider_order_id": None, + "provider_payment_id": f"pay_srv{random.randint(10 ** 10, 10 ** 11)}", + "provider_signature": None, "transaction_reference": None, + "provider_refund_id": None, "refund_reason": None, "refunded_at": None, + "created_at": created + timedelta(days=4), "paid_at": created + timedelta(days=4)}) + for k, (et, note) in enumerate([("JOB_CREATED", "Booking created"), + ("STATUS_CHANGED", f"Status -> {st}"), + ("TECHNICIAN_ASSIGNED", "Assigned on bench")][:3 if age >= 3 else 1]): + events.append({"event_id": new_ulid(), "job_id": jid, "event_type": et, + "performed_by": "seed-script", "timestamp": created + timedelta(hours=k * 5), + "notes": note + f" {TAG}"}) + S.insert(DB_E, "service_jobs", jobs) + S.insert(DB_E, "service_appointments", appts) + S.insert(DB_E, "service_job_intakes", intakes) + S.insert(DB_E, "service_job_assignments", assigns) + S.insert(DB_E, "service_job_inspections", insp) + S.insert(DB_E, "service_job_quotes", quotes) + S.insert(DB_E, "service_payments", pays) + S.insert(DB_E, "service_job_events", events) + return {"jobs": jobs, "profiles": profiles} + + +# =========================================================================== # +# STAGE 7 — repair tickets, POS sessions +# =========================================================================== # +def stage_repair_pos(refs, custs, staff, svc): + print("STAGE 7: repair tickets & POS") + crm_ids = custs["crm_ids"] + crm_devs = custs["crm_devs"] + tech_ids = [p["technician_id"] for p in svc["profiles"]] + tickets = [] + used_tn = set() + stages_all = ["RECEIVED", "DIAGNOSING", "PART_PENDING", "UNDER_REPAIR", "QC_TESTING", + "READY_FOR_DELIVERY", "CLOSED", "CANCELLED"] + stages = stages_all[:6] * 16 + ["CLOSED"] * 12 + ["CANCELLED"] * 2 + random.shuffle(stages) + for i, stage in enumerate(stages[:110]): + while True: + tn = f"IFK-REP-{random.randint(1000, 9999)}" + if tn not in used_tn: + used_tn.add(tn) + break + created = days_ago(random.randint(0, 50), random.randint(9, 19)) + cust = random.choice(crm_ids) + dev = random.choice([d for d in crm_devs]) if crm_devs else None + if not dev: + continue + done = stage in ("CLOSED", "CANCELLED") + tickets.append({"ticket_id": new_ulid(), "ticket_number": tn, "tenant_id": TENANT, + "customer_id": cust, "device_id": dev["device_id"], + "assigned_technician_id": random.choice(tech_ids) if stage != "RECEIVED" else None, + "stage": stage, + "issue_description": f"{random.choice(ISSUES)}. {TAG}", + "diagnostic_checklist_json": j({"power": random.choice(["OK", "NO"]), + "screen": random.choice(["cracked", "ok", "dead"]), + "water": random.choice(["no", "yes"]), + "boot": random.choice(["normal", "hang", "none"])}) if stage not in ("RECEIVED", "DIAGNOSING") else None, + "qc_checklist_json": j({"touch": "pass", "color": "pass", "speaker": "pass", + "camera": "pass", "final": "pass"}) if stage in ("QC_TESTING", "READY_FOR_DELIVERY", "CLOSED") else None, + "estimate_amount": round(random.uniform(500, 15000), 2), + "estimate_approved_by_customer": 1 if stage not in ("RECEIVED", "DIAGNOSING") else 0, + "is_warranty_claim": 1 if i % 11 == 0 else 0, + "notes": f"{random.choice(NOTE_PREFIXES)} {TAG}", + "created_by": "seed-script", "updated_by": "seed-script", "version": 1}) + S.insert(DB_E, "crm_repair_tickets", tickets) + + sessions = [] + for i in range(1, 101): + opened = days_ago(random.randint(0, 29), random.randint(9, 10)) + closed_day = random.random() < 0.95 + opening = random.choice([2000.0, 3000.0, 5000.0]) + cash = round(random.uniform(500, 9000), 2) if closed_day else 0.0 + upi = round(random.uniform(1000, 25000), 2) + card = round(random.uniform(0, 8000), 2) + other = round(random.uniform(0, 1500), 2) + ecom_n = random.randint(0, 12) + ecom_a = round(random.uniform(0, 40000), 2) if ecom_n else 0.0 + svc_n = random.randint(0, 8) + svc_a = round(random.uniform(0, 25000), 2) if svc_n else 0.0 + dur = random.randint(480, 600) + expected = round(opening + cash, 2) + closing = round(expected + random.choice([0, 0, 0, 50, -50, 100]), 2) if closed_day else None + sessions.append({"pos_session_id": new_ulid(), "tenant_id": TENANT, + "location_id": random.choice(refs["locations"][:8])["location_id"], + "terminal_id": random.choice(refs["terminals"])["terminal_id"], + "warehouse_id": random.choice(refs["warehouses"][:3])["warehouse_id"], + "user_id": random.choice(staff["users"])["user_id"], + "opened_by_user_id": random.choice(staff["users"])["user_id"], + "opening_cash": opening, + "closing_cash": closing, "expected_cash": expected if closed_day else None, + "cash_variance": round((closing or 0) - expected, 2) if closed_day else None, + "ecom_sales_count": ecom_n, "ecom_sales_amount": ecom_a, + "service_sales_count": svc_n, "service_sales_amount": svc_a, + "courier_charges": round(random.uniform(0, 300), 2), + "cash_sales": cash, "upi_sales": upi, "card_sales": card, + "other_sales": other, + "status": "OPEN" if not closed_day else "CLOSED", + "opened_at": opened, "session_duration_minutes": dur, + "expires_at": opened + timedelta(minutes=600), + "closed_at": opened + timedelta(minutes=dur) if closed_day else None, + "notes": f"End-of-day POS session {TAG}", + "created_by": "seed-script", "updated_by": "seed-script", "version": 1}) + S.insert(DB_E, "crm_pos_sessions", sessions) + S.insert(DB_E, "crm_pos_session_extensions", [ + {"id": new_ulid(), "session_id": random.choice(sessions)["pos_session_id"], + "extension_minutes": random.choice([15, 30, 60]), + "extended_by": random.choice(staff["users"])["user_id"], + "reason": "Heavy evening rush, closing delayed", + "created_at": days_ago(random.randint(0, 25)), "created_by": "seed-script", + "updated_by": "seed-script", "version": 1} + for _ in range(110)]) + + logs = [] + for i in range(1, 121): + ok = random.random() < 0.85 + logs.append({"sync_id": f"SYNC-{i:06d}-{new_ulid()[:10]}", + "terminal_id": random.choice(refs["sync_terms"])["terminal_id"], + "invoice_no": f"POS-INV-{random.randint(20260000, 20269999)}", + "pos_transaction_id": f"POSTX-{random.randint(100000, 999999)}", + "items_count": random.randint(1, 8), + "total_amount": round(random.uniform(199, 45000), 2), + "status": "SYNCED" if ok else random.choice(["FAILED", "PENDING"]), + "error_detail": None if ok else "Terminal clock drift, retry queued", + "created_at": days_ago(random.randint(0, 20), random.randint(9, 20))}) + S.insert(DB_E, "pos_transaction_logs", logs) + return {"tickets": tickets, "sessions": sessions} + + +# =========================================================================== # +# STAGE 8 — purchases & inventory +# =========================================================================== # +def stage_purchase_inventory(refs): + print("STAGE 8: purchases & inventory") + parts = refs["parts"] + sups = refs["suppliers"] + pos, pois, moves = [], [], [] + used_po = set() + statuses = ["DRAFT"] * 3 + ["SENT"] * 4 + ["PARTIALLY_RECEIVED"] * 2 + ["RECEIVED"] * 8 + ["CANCELLED"] + for i in range(1, 111): + while True: + po_no = f"PO-2026-{i:04d}" + if po_no not in used_po: + used_po.add(po_no) + break + st = statuses[i % len(statuses)] + created = days_ago(random.randint(0, 55)) + items = [] + total = 0.0 + for k in range(random.randint(1, 4)): + part = random.choice(parts) + q = random.randint(5, 60) + up = round(float(part["cost_price"]), 2) + total += q * up + items.append({"id": new_ulid(), "purchase_order_id": None, "part_id": part["part_id"], + "quantity_ordered": q, + "quantity_received": q if st == "RECEIVED" else (q // 2 if st == "PARTIALLY_RECEIVED" else 0), + "unit_price": up}) + pid = new_ulid() + for it in items: + it["purchase_order_id"] = pid + pos.append({"purchase_order_id": pid, "po_number": po_no, + "supplier_name": random.choice(sups)["company_name"], "status": st, + "total_amount": round(total, 2), "created_at": created}) + pois.extend(items) + S.insert(DB_C, "purchase_orders", pos) + S.insert(DB_C, "purchase_order_items", pois) + for i in range(1, 111): + po = random.choice(pos) + part = random.choice(parts) + moves.append({"movement_id": new_ulid(), "entity_type": "PART", "entity_id": part["part_id"], + "movement_type": random.choice(["PURCHASE_IN", "PURCHASE_IN", "SALE_OUT", "ADJUSTMENT", "DAMAGE_WRITE_OFF"]), + "quantity": random.randint(1, 40), + "reference_type": "PURCHASE_ORDER", "reference_id": po["purchase_order_id"], + "created_at": days_ago(random.randint(0, 50))}) + S.insert(DB_C, "stock_movements", moves) + + skus = [r[0] for r in S.fetch( + f"SELECT sku FROM {DB_E}.product_variants WHERE status='active' LIMIT 300")] + stocks = [] + seen = set() + for w in refs["warehouses"][:5]: + for sku in random.sample(skus, 30): + key = (w["warehouse_id"], sku) + if key in seen: + continue + seen.add(key) + q = random.randint(0, 120) + stocks.append({"stock_id": new_ulid(), "tenant_id": TENANT, + "warehouse_id": w["warehouse_id"], "sku": sku, + "quantity_on_hand": q, "quantity_reserved": random.randint(0, max(q, 1) // 4), + "reorder_threshold": random.choice([5, 10, 15]), + "created_by": "seed-script", "updated_by": "seed-script", "version": 1}) + S.insert(DB_E, "crm_inventory_stocks", stocks) + return {"pos": pos} + + +# =========================================================================== # +# STAGE 9 — refunds, warranties, reviews, feedback +# =========================================================================== # +def stage_postsales(refs, custs, staff, svc, orders): + print("STAGE 9: refunds, warranties, reviews") + staff_ids = [u["user_id"] for u in staff["users"]] + refunds, wties, crev, prev, pimgs, fb = [], [], [], [], [], [] + delivered = [o for o in orders if o["status"] in ("DELIVERED", "SHIPPED", "OUT_FOR_DELIVERY")] + oitems = [dict(zip(("item_id", "order_id", "product_id", "product_name", "sku"), r)) + for r in S.fetch( + f"SELECT item_id, order_id, product_id, product_name, sku FROM {DB_E}.order_items LIMIT 400")] + for i in range(1, 111): + created = days_ago(random.randint(0, 40), random.randint(9, 20)) + if i % 3 == 0 and svc["jobs"]: + job = random.choice(svc["jobs"]) + etype, eid = "SERVICE", job["job_id"] + amt = round(float(job["base_price_snapshot"] or 1999) * 0.3, 2) + else: + o = random.choice(orders) + etype, eid = "SALES", o["order_id"] + amt = round(float(o["final_amount"]) * random.choice([0.2, 0.5, 1.0]), 2) + st = random.choice(["PENDING"] * 3 + ["APPROVED"] * 3 + ["PROCESSING"] * 2 + ["REFUNDED"] * 3 + ["REJECTED"] * 2) + req_by = random.choice(staff_ids) + appr = random.choice(staff_ids) if st in ("APPROVED", "PROCESSING", "REFUNDED") else None + rej = random.choice(staff_ids) if st == "REJECTED" else None + refunds.append({"refund_id": new_ulid(), "tenant_id": TENANT, + "location_id": random.choice(refs["locations"][:10])["location_id"], + "entity_type": etype, "entity_id": eid, + "amount": amt, "payment_method": random.choice(["CASH", "ONLINE"]), + "status": st, + "reason": random.choice(["Part not compatible", "Customer changed mind", + "Damaged in transit", "Wrong item delivered", + "Repair not satisfactory"]), + "part_number_verification": f"PN-{random.randint(10000, 99999)}", + "razorpay_refund_id": f"rfnd_demo{random.randint(10 ** 9, 10 ** 10)}" if st == "REFUNDED" and random.random() < 0.5 else None, + "razorpay_refund_status": "processed" if st == "REFUNDED" else None, + "requested_by": req_by, "approved_by": appr, "rejected_by": rej, + "requested_at": created, + "approved_at": created + timedelta(hours=6) if appr else None, + "rejected_at": created + timedelta(hours=6) if rej else None, + "refunded_at": created + timedelta(days=1) if st == "REFUNDED" else None, + "rejection_reason": "Part used, non-resalable" if rej else None, + "admin_notes": f"Demo refund {TAG}", + "created_by": "seed-script", "updated_by": "seed-script", "version": 1}) + if i <= 40: + refunds_media_ref = refunds[-1]["refund_id"] + fb_media = {"id": new_ulid(), "refund_id": refunds_media_ref, + "file_url": f"/uploads/refunds/demo-{i}.jpg", "file_type": "image/jpeg", + "media_filename": f"demo-{i}.jpg", "uploaded_by": req_by, + "uploaded_at": created, "created_by": "seed-script", + "updated_by": "seed-script", "version": 1} + # note: refund_media requires uploaded_by NOT NULL etc. Build separately: + S.insert(DB_E, "refund_requests", refunds) + S.insert(DB_E, "refund_media", [ + {"id": new_ulid(), "refund_id": r["refund_id"], "file_url": f"/uploads/refunds/demo-{k + 1}.jpg", + "file_type": "image/jpeg", "media_filename": f"demo-{k + 1}.jpg", + "uploaded_by": r["requested_by"], "uploaded_at": r["requested_at"], + "created_by": "seed-script", "updated_by": "seed-script", "version": 1} + for k, r in enumerate(refunds)]) + + for i in range(1, 111): + if i % 2 == 0 and oitems: + it = random.choice(oitems) + start = days_ago(random.randint(1, 300)) + end = start + timedelta(days=365) + wties.append({"warranty_id": new_ulid(), "tenant_id": TENANT, + "customer_id": custs["ecom_ids"][i % len(custs["ecom_ids"])], + "reference_type": "ORDER", "reference_id": it["order_id"], + "product_id": it["product_id"], "order_item_id": it["item_id"], + "service_job_id": None, "serial_no_imei": "".join(random.choice(string.digits) for _ in range(15)), + "start_date": start, "end_date": end, + "status": "ACTIVE" if end > now() else "EXPIRED", + "warranty_type": "PRODUCT", + "terms": "12 months manufacturing defect warranty. Physical damage void.", + "void_reason": None, "expiry_notification_sent": 0, + "created_at": start, "updated_at": start}) + else: + job = random.choice(svc["jobs"]) + start = days_ago(random.randint(1, 200)) + end = start + timedelta(days=90) + wties.append({"warranty_id": new_ulid(), "tenant_id": TENANT, + "customer_id": custs["ecom_ids"][i % len(custs["ecom_ids"])], + "reference_type": "SERVICE", "reference_id": job["job_id"], + "product_id": None, "order_item_id": None, + "service_job_id": job["job_id"], + "serial_no_imei": "".join(random.choice(string.digits) for _ in range(15)), + "start_date": start, "end_date": end, + "status": "ACTIVE" if end > now() else "EXPIRED", + "warranty_type": "SERVICE", + "terms": "90 days repair warranty on replaced part.", + "void_reason": None, "expiry_notification_sent": 0, + "created_at": start, "updated_at": start}) + S.insert(DB_E, "warranties", wties) + + products = [r[0] for r in S.fetch(f"SELECT product_id FROM {DB_E}.products LIMIT 400")] + tech_ids = [p["technician_id"] for p in svc["profiles"]] + rev_texts = ["Excellent service, very quick turnaround.", "Genuine part, packaging was good.", + "Technician was professional and explained everything.", "Fixed my phone in 2 hours!", + "Price was slightly high but quality is great.", "Average experience, took longer than promised.", + "Part failed within a month, support helpful though.", "Great follow-up and warranty support.", + "Store staff was courteous, repair perfect.", "Fast courier delivery, well packed."] + for i in range(1, 111): + rating = random.choice([5, 5, 5, 4, 4, 3, 2, 1]) + mod = random.choice(["APPROVED"] * 6 + ["PENDING_MODERATION"] * 2 + ["REJECTED"] + ["FLAGGED"]) + tt = random.choice(["PRODUCT"] * 6 + ["TECHNICIAN"] * 2 + ["STORE"] * 2) + tid = {"PRODUCT": lambda: random.choice(products), + "TECHNICIAN": lambda: random.choice(tech_ids), + "STORE": lambda: random.choice(refs["locations"])["location_id"]}[tt]() + crev.append({"review_id": new_ulid(), "tenant_id": TENANT, + "customer_id": custs["ecom_ids"][i % len(custs["ecom_ids"])], + "target_type": tt, "target_id": tid, + "order_id": None, "repair_ticket_id": None, + "rating": rating, "title": random.choice(["Great service", "Good quality", "Okay experience", + "Poor experience", "Highly recommend"]), + "comment": random.choice(rev_texts) + f" {TAG}", + "moderation_status": mod, + "moderation_reason": "Spam suspicion" if mod == "REJECTED" else None, + "is_verified_buyer": 1 if i % 3 else 0, + "is_published": 1 if mod == "APPROVED" else 0, + "csat_score": rating * 20, + "moderated_by": random.choice(staff_ids) if mod in ("APPROVED", "REJECTED") else None, + "moderated_at": days_ago(random.randint(0, 5)) if mod in ("APPROVED", "REJECTED") else None, + "created_by": "seed-script", "updated_by": "seed-script", "version": 1}) + S.insert(DB_E, "customer_reviews", crev) + + for i in range(1, 111): + rating = random.choice([5, 5, 4, 4, 3, 2, 1]) + rid = new_ulid() + approved = i % 8 != 7 + prev.append({"review_id": rid, "product_id": random.choice(products), + "user_id": None, "author_name": f"{random.choice(FIRST)} {random.choice(LAST)}", + "author_email": slug_email(random.choice(FIRST), random.choice(LAST)), + "rating": rating, + "title": random.choice(["Works perfectly", "Good spare part", "As described", + "Not original but decent", "Poor fit"]), + "comment": random.choice(rev_texts), + "verified_purchase": 1 if i % 2 else 0, "is_approved": 1 if approved else 0, + "helpful_count": random.randint(0, 25), + "admin_reply": "Thanks for your feedback!" if i % 5 == 0 else None, + "created_at": days_ago(random.randint(1, 120)), "updated_at": days_ago(0), + "created_by": "seed-script", "updated_by": "seed-script", "version": 1}) + pimgs.append({"image_id": new_ulid(), "review_id": rid, + "image_url": f"/uploads/reviews/demo-{i}.jpg", "caption": "Installed part photo", + "display_order": 1, "is_approved": 1 if approved else 0, + "created_by": "seed-script", "updated_by": "seed-script", "version": 1}) + S.insert(DB_E, "product_reviews", prev) + S.insert(DB_E, "product_review_images", pimgs) + + for i in range(1, 111): + fn, ln = random.choice(FIRST), random.choice(LAST) + fb.append({"feedback_id": new_ulid(), "name": f"{fn} {ln}", + "email": slug_email(fn, ln), + "topic": random.choice(["general", "order", "service", "website", "complaint"]), + "order_no": random.choice(orders)["order_no"] if i % 4 == 0 else None, + "rating": random.choice([5, 4, 4, 3, 2, 1]), + "message": random.choice(["Website is easy to use.", "Order arrived quickly, thanks!", + "Repair service could be faster on weekends.", + "Loved the WhatsApp updates.", "Add more laptop spare categories.", + "Coupon code did not apply at checkout.", "Great support on call."]) + f" {TAG}", + "status": random.choice(["NEW"] * 4 + ["REVIEWED"] * 3 + ["RESOLVED"] * 3), + "created_at": days_ago(random.randint(0, 60), random.randint(8, 22))}) + S.insert(DB_E, "customer_feedbacks", fb) + + +# =========================================================================== # +# STAGE 10 — notifications, templates, attributes, brands, categories +# =========================================================================== # +def stage_comms_catalog(refs, custs, staff, orders, svc): + print("STAGE 10: notifications, templates, catalog extras") + from passlib.context import CryptContext # noqa (already imported earlier) + + templates = [] + registry = [("ORDER_CREATED", "Order Confirmation"), ("NEW_ORDER_ALERT", "New Order Alert"), + ("SERVICE_BOOKED", "Service Booked"), ("SERVICE_READY", "Service Ready"), + ("ORDER_STATUS_CHANGED", "Order Status Update"), ("SERVICE_BOOKED_INTERNAL", "Internal Service Alert"), + ("SERVICE_STATUS_CHANGED", "Service Status Update"), ("INVENTORY_LOW_STOCK", "Low Stock Alert"), + ("REFUND_TRIGGERED", "Refund Triggered"), ("END_OF_DAY_REPORT", "End of Day Report"), + ("REPAIR_SLA_BREACH", "Repair SLA Breach"), ("WARRANTY_EXPIRING_SOON", "Warranty Expiring")] + common_vars = [{"name": "customer_name", "description": "Customer full name", "example": "Priya Kumar"}, + {"name": "order_no", "description": "Order number", "example": "ORD-20261116-0001"}, + {"name": "job_no", "description": "Service job number", "example": "SRV-1731772800-A1B2"}] + for ev, nm in registry: + for ch in ("WHATSAPP", "EMAIL"): + templates.append({"template_id": new_ulid(), "tenant_id": TENANT, "event_key": ev, + "name": f"{nm} ({ch})", "channel": ch, + "subject": f"iFixKart - {nm}" if ch == "EMAIL" else None, + "body_content": ("Hi {{ customer_name }}, your order {{ order_no }} update from iFixKart." + if "ORDER" in ev else + "Hi {{ customer_name }}, update on your service {{ job_no }} from iFixKart."), + "variables": j(common_vars), "is_active": 1, + "created_by": "seed-script", "updated_by": "seed-script", "version": 1}) + S.insert(DB_E, "notification_templates", templates) + tmpl_ids = {r[0]: r[1] for r in S.fetch( + f"SELECT event_key, template_id FROM {DB_E}.notification_templates")} + + cust_emails = [r[0] for r in S.fetch( + f"SELECT email FROM {DB_E}.ecom_customers ORDER BY created_at DESC LIMIT 60")] + notif_types = ["ORDER", "INVOICE", "SERVICE_BOOKED", "SERVICE_READY", "SERVICE_STATUS_CHANGED", + "QUOTATION", "REPAIR_TICKET", "LEAD_QUALIFIED", "ORDER_STATUS_CHANGED"] + chans = ["WHATSAPP", "EMAIL", "WHATSAPP", "WEB_PUSH"] + stat_mix = ["DELIVERED"] * 6 + ["SENT"] * 2 + ["QUEUED"] + ["FAILED"] + ["SENDING"] + + def notif_rows(n, emails, tag): + rows = [] + for i in range(1, n + 1): + ev = random.choice(notif_types) + status = random.choice(stat_mix) + created = days_ago(random.randint(0, 30), random.randint(8, 22)) + rows.append({"notification_id": new_ulid(), "tenant_id": TENANT, + "event_id": None, "notification_type": ev, + "entity_id": random.choice(orders)["order_id"], + "idempotency_key": f"seed:{new_ulid()}", + "recipient": random.choice(emails), + "channel": random.choice(chans), + "template_id": tmpl_ids.get(ev.split("_ALERT")[0].split("_INTERNAL")[0]), + "status": status, + "subject": f"iFixKart {ev.replace('_', ' ').title()}" if random.random() < 0.5 else None, + "message_body": f"Demo {ev.lower()} notification for storefront customer. {tag}", + "attempt_count": 1 if status in ("DELIVERED", "SENT", "FAILED") else 0, + "last_attempt_at": created + timedelta(minutes=1) if status != "QUEUED" else None, + "next_retry_at": created + timedelta(hours=1) if status == "FAILED" else None, + "last_error": "Provider timeout" if status == "FAILED" else None, + "provider_response": j({"ok": status == "DELIVERED"}), + "completed_at": created + timedelta(minutes=2) if status in ("DELIVERED", "SENT") else None, + "created_by": "seed-script", "updated_by": "seed-script", "version": 1}) + return rows + S.insert(DB_E, "notifications", notif_rows(120, cust_emails or ["demo@ifixkart-demo.com"], TAG)) + S.insert(DB_A, "notifications", notif_rows(110, [u["email"] for u in staff["users"]], TAG)) + + existing_attr = {r[0] for r in S.fetch(f"SELECT code FROM {DB_E}.attribute_types")} + attrs = [] + for code, name, presets in ATTR_POOL: + if code in existing_attr or len(attrs) >= 40: + continue + existing_attr.add(code) + attrs.append({"attribute_id": new_ulid(), "name": name, "code": code, + "status": "active", "preset_values": j(presets)}) + S.insert(DB_E, "attribute_types", attrs, "extras") + + existing_brands = {r[0] for r in S.fetch(f"SELECT name FROM {DB_E}.brands")} + brands = [] + for b in BRAND_POOL: + if b in existing_brands or len(brands) >= 10: + continue + existing_brands.add(b) + brands.append({"brand_id": new_ulid(), "name": b, + "slug": b.lower().replace(" ", "-"), "logo_url": None, + "is_active": 1, "created_at": days_ago(1), "updated_at": days_ago(1)}) + S.insert(DB_E, "brands", brands, "extras") + + parents = [r[0] for r in S.fetch( + f"SELECT category_id FROM {DB_E}.categories WHERE parent_category_id IS NULL LIMIT 10")] + existing_cats = {r[0] for r in S.fetch(f"SELECT slug FROM {DB_E}.categories")} + cats = [] + series_names = [r[0] for r in S.fetch(f"SELECT name FROM {DB_E}.device_series LIMIT 60")] + for i, sn in enumerate(series_names[:45]): + slug = (sn.lower().replace(" ", "-").replace("(", "").replace(")", "") + "-spares")[:100] + if slug in existing_cats: + continue + existing_cats.add(slug) + cats.append({"category_id": new_ulid(), "parent_category_id": random.choice(parents) if parents else None, + "name": f"{sn} Spares", "slug": slug, + "description": f"Spare parts & accessories for {sn}. {TAG}", + "image_url": None, "sort_order": str(100 + i), "is_parent_feature": 0, + "is_active": 1, "show_in_sidebar": 0, "mega_group": None, "badge": None, + "created_at": days_ago(1), "updated_at": days_ago(1)}) + S.insert(DB_E, "categories", cats, "extras") + + +# =========================================================================== # +def reset_seed(): + """Delete every row created by this seeder (FK-safe order).""" + print("RESET: deleting all seed-tagged rows") + cur = S.conn.cursor() + demo = "%@ifixkart-demo.com" + stmts = [ + # admin db + (DB_A, "DELETE FROM user_sessions WHERE user_id IN (SELECT user_id FROM users WHERE email LIKE %s)", (demo,)), + (DB_A, "DELETE FROM notifications WHERE created_by='seed-script'", ()), + (DB_A, "DELETE FROM users WHERE email LIKE %s", (demo,)), + (DB_A, "DELETE FROM roles WHERE role_prefix IN ('ADMI','SMGR','SLEX','CRMX','SVAD','TECH','WHSE','ACCT','SUPT') OR description LIKE %s", (f"%{TAG}%",)), + (DB_A, "DELETE FROM departments WHERE description LIKE %s OR name IN ('Sales','Service & Repair','Warehouse & Logistics','Finance & Accounts','Customer Support','Marketing','Human Resources')", (f"%{TAG}%",)), + (DB_A, "DELETE FROM designations WHERE description LIKE %s OR name IN ('Store Manager','Sales Executive','Senior Sales Executive','CRM Executive','Service Center Manager','Senior Technician','Technician','Junior Technician','Warehouse Executive','Accountant','Support Agent')", (f"%{TAG}%",)), + # commerce: service engine + (DB_E, "DELETE FROM service_job_events WHERE job_id IN (SELECT job_id FROM service_jobs WHERE job_no LIKE 'SRV-%')", ()), + (DB_E, "DELETE FROM service_payments WHERE service_job_id IN (SELECT job_id FROM service_jobs WHERE job_no LIKE 'SRV-%')", ()), + (DB_E, "DELETE FROM service_job_quotes WHERE service_job_id IN (SELECT job_id FROM service_jobs WHERE job_no LIKE 'SRV-%')", ()), + (DB_E, "DELETE FROM service_job_inspections WHERE service_job_id IN (SELECT job_id FROM service_jobs WHERE job_no LIKE 'SRV-%')", ()), + (DB_E, "DELETE FROM service_job_assignments WHERE service_job_id IN (SELECT job_id FROM service_jobs WHERE job_no LIKE 'SRV-%')", ()), + (DB_E, "DELETE FROM service_job_intakes WHERE service_job_id IN (SELECT job_id FROM service_jobs WHERE job_no LIKE 'SRV-%')", ()), + (DB_E, "DELETE FROM service_appointments WHERE service_job_id IN (SELECT job_id FROM service_jobs WHERE job_no LIKE 'SRV-%')", ()), + (DB_E, "DELETE FROM service_jobs WHERE job_no LIKE 'SRV-%'", ()), + (DB_E, "DELETE FROM service_catalog WHERE service_id IN (SELECT service_type_id FROM ifixkartcrm.service_types WHERE description LIKE %s)", (f"%{TAG}%",)), + (DB_E, "DELETE FROM technician_leaves", ()), + (DB_E, "DELETE FROM technician_working_hours", ()), + (DB_E, "DELETE FROM technician_skills", ()), + (DB_E, "DELETE FROM technician_profiles", ()), + # commerce: orders & billing + (DB_E, "DELETE FROM order_status_history WHERE order_id IN (SELECT order_id FROM orders o JOIN ecom_customers c ON c.customer_id=o.customer_id WHERE c.email LIKE %s) OR order_id IN (SELECT order_id FROM orders WHERE customer_id IS NULL)", (demo,)), + (DB_E, "DELETE FROM order_items WHERE order_id IN (SELECT order_id FROM orders o JOIN ecom_customers c ON c.customer_id=o.customer_id WHERE c.email LIKE %s) OR order_id IN (SELECT order_id FROM orders WHERE customer_id IS NULL)", (demo,)), + (DB_E, "DELETE FROM invoices", ()), + (DB_E, "DELETE FROM payment_ledger WHERE raw_response_json LIKE %s", (f"%{TAG}%",)), + (DB_E, "DELETE FROM coupon_usages", ()), + (DB_E, "DELETE FROM wallet_transactions", ()), + (DB_E, "DELETE FROM orders WHERE customer_id IN (SELECT customer_id FROM ecom_customers WHERE email LIKE %s) OR customer_id IS NULL", (demo,)), + # commerce: post-sales + (DB_E, "DELETE FROM refund_media WHERE refund_id IN (SELECT refund_id FROM refund_requests WHERE created_by='seed-script')", ()), + (DB_E, "DELETE FROM refund_requests WHERE created_by='seed-script'", ()), + (DB_E, "DELETE FROM warranties WHERE customer_id IN (SELECT customer_id FROM ecom_customers WHERE email LIKE %s)", (demo,)), + (DB_E, "DELETE FROM product_review_images", ()), + (DB_E, "DELETE FROM product_reviews", ()), + (DB_E, "DELETE FROM customer_reviews WHERE created_by='seed-script'", ()), + (DB_E, "DELETE FROM customer_feedbacks WHERE message LIKE %s", (f"%{TAG}%",)), + # commerce: comms + (DB_E, "DELETE FROM notifications WHERE created_by='seed-script'", ()), + (DB_E, "DELETE FROM notification_templates WHERE created_by='seed-script'", ()), + # commerce: POS & repair & inventory + (DB_E, "DELETE FROM crm_pos_session_extensions WHERE created_by='seed-script'", ()), + (DB_E, "DELETE FROM crm_pos_sessions WHERE created_by='seed-script'", ()), + (DB_E, "DELETE FROM pos_transaction_logs WHERE sync_id LIKE 'SYNC-%'", ()), + (DB_E, "DELETE FROM pos_sync_terminals WHERE terminal_id LIKE 'TERM-%'", ()), + (DB_E, "DELETE FROM pos_terminals WHERE created_by='seed-script'", ()), + (DB_E, "DELETE FROM crm_warehouses WHERE created_by='seed-script'", ()), + (DB_E, "DELETE FROM crm_suppliers WHERE created_by='seed-script'", ()), + (DB_E, "DELETE FROM crm_repair_tickets WHERE created_by='seed-script'", ()), + (DB_E, "DELETE FROM crm_inventory_stocks WHERE created_by='seed-script'", ()), + # crm db + (DB_C, "DELETE FROM stock_movements", ()), + (DB_C, "DELETE FROM purchase_order_items", ()), + (DB_C, "DELETE FROM purchase_orders", ()), + (DB_C, "DELETE FROM parts WHERE barcode LIKE '8900001%%'", ()), + (DB_C, "DELETE FROM contact_addresses WHERE contact_id IN (SELECT contact_id FROM contacts WHERE email LIKE %s)", (demo,)), + (DB_C, "DELETE FROM contacts WHERE email LIKE %s", (demo,)), + (DB_C, "DELETE FROM service_types WHERE description LIKE %s", (f"%{TAG}%",)), + # commerce: CRM pipeline & customers (children first) + (DB_E, "DELETE FROM crm_bulk_quotation_items WHERE quote_id IN (SELECT quote_id FROM crm_bulk_quotations WHERE created_by='seed-script')", ()), + (DB_E, "DELETE FROM crm_bulk_quotations WHERE created_by='seed-script'", ()), + (DB_E, "DELETE FROM crm_invoice_items WHERE invoice_id IN (SELECT invoice_id FROM crm_gst_invoices WHERE created_by='seed-script')", ()), + (DB_E, "DELETE FROM crm_gst_invoices WHERE created_by='seed-script'", ()), + (DB_E, "DELETE FROM crm_tasks WHERE created_by='seed-script'", ()), + (DB_E, "DELETE FROM crm_calendar_events WHERE created_by='seed-script'", ()), + (DB_E, "DELETE FROM crm_deals WHERE created_by='seed-script'", ()), + (DB_E, "DELETE FROM crm_leads WHERE created_by='seed-script'", ()), + (DB_E, "DELETE FROM crm_contacts WHERE created_by='seed-script'", ()), + (DB_E, "DELETE FROM crm_customer_devices WHERE created_by='seed-script'", ()), + (DB_E, "DELETE FROM crm_customers WHERE created_by='seed-script'", ()), + # locations last (referenced by tasks/calendar/pos sessions above) + (DB_E, "DELETE FROM crm_locations WHERE created_by='seed-script'", ()), + # commerce: catalog extras + (DB_E, "DELETE FROM brands WHERE name IN ('Honor','iQoo','Tecno','Infinix','Lava','Micromax','Nokia','Sony','Nubia','Asus ROG') AND brand_id NOT IN (SELECT brand_id FROM device_models WHERE brand_id IS NOT NULL)", ()), + (DB_E, "DELETE FROM categories WHERE name LIKE '% Spares' AND slug LIKE '%-spares'", ()), + (DB_E, "DELETE FROM attribute_types WHERE code IN ('water_resistance_rating','refresh_rate_hz','screen_size_inch','ram_type','port_type','weight_grams','battery_capacity_mah','charger_wattage','front_camera_mp','rear_camera_mp','processor_core','os_version','sim_slots','network_band','material_grade','panel_type','warranty_period','connector_pitch','flex_cable_type','color_variant','storage_capacity','keyboard_layout','audio_jack','fingerprint_type','fast_charging','wireless_charging','tcon_board','frame_included','ic_chips','tempered_grade')", ()), + (DB_E, "DELETE FROM coupons", ()), + # commerce: storefront customers LAST (cascades wallets/addresses) + (DB_E, "DELETE FROM customer_devices WHERE customer_id NOT IN (SELECT customer_id FROM ecom_customers)", ()), + (DB_E, "DELETE FROM ecom_customers WHERE email LIKE %s", (demo,)), + ] + for db, sql, args in stmts: + try: + cur.execute(f"USE `{db}`") + n = cur.execute(sql, args or None) if args else cur.execute(sql) + if n: + print(f" {db}: -{n}") + except pymysql.err.IntegrityError as e: + print(f" SKIP ({e})") + S.conn.commit() + + +def looks_seeded() -> bool: + demo = "%@ifixkart-demo.com" + checks = [ + (DB_A, "users", "email LIKE %s", (demo,)), + (DB_E, "crm_leads", "created_by='seed-script'", ()), + (DB_E, "crm_locations", "created_by='seed-script'", ()), + (DB_E, "coupons", "code LIKE 'IFK%%OFF'", ()), + ] + for db, t, cond, args in checks: + if int(S.scalar(f"SELECT COUNT(*) FROM `{db}`.`{t}` WHERE {cond}", args) or 0) > 0: + return True + return False + + +def main(): + force = "--force" in sys.argv + if "--reset" in sys.argv: + reset_seed() + print("Reset complete.\n") + if looks_seeded() and not force: + print("Seed data already present — run with --reset to clear it, or --force to append.") + sys.exit(1) + t0 = time.time() + staff = stage_admin_staff() + refs = stage_reference() + custs = stage_customers() + pipeline = stage_pipeline(staff, refs, custs) + orders_res = stage_orders(refs, custs, staff) + svc = stage_services(staff, custs, refs) + repair_pos = stage_repair_pos(refs, custs, staff, svc) + stage_purchase_inventory(refs) + stage_postsales(refs, custs, staff, svc, orders_res["orders"]) + stage_comms_catalog(refs, custs, staff, orders_res["orders"], svc) + + print("\n=== FINAL COUNTS (per admin module) ===") + modules = [ + ("users (staff-directory)", DB_A, "users"), ("roles", DB_A, "roles"), + ("departments", DB_A, "departments"), ("designations", DB_A, "designations"), + ("notifications (admin)", DB_A, "notifications"), ("audit_logs", DB_A, "audit_logs"), + ("crm_customers", DB_E, "crm_customers"), ("crm_contacts", DB_E, "crm_contacts"), + ("crm_leads", DB_E, "crm_leads"), ("crm_deals", DB_E, "crm_deals"), + ("crm_tasks", DB_E, "crm_tasks"), ("crm_calendar_events", DB_E, "crm_calendar_events"), + ("crm_bulk_quotations", DB_E, "crm_bulk_quotations"), ("crm_bulk_quotation_items", DB_E, "crm_bulk_quotation_items"), + ("crm_gst_invoices", DB_E, "crm_gst_invoices"), ("crm_invoice_items", DB_E, "crm_invoice_items"), + ("crm_repair_tickets", DB_E, "crm_repair_tickets"), ("crm_pos_sessions", DB_E, "crm_pos_sessions"), + ("crm_pos_session_extensions", DB_E, "crm_pos_session_extensions"), + ("crm_suppliers", DB_E, "crm_suppliers"), ("crm_warehouses", DB_E, "crm_warehouses"), + ("crm_locations", DB_E, "crm_locations"), ("crm_inventory_stocks", DB_E, "crm_inventory_stocks"), + ("pos_terminals", DB_E, "pos_terminals"), ("pos_sync_terminals", DB_E, "pos_sync_terminals"), + ("pos_transaction_logs", DB_E, "pos_transaction_logs"), + ("ecom_customers", DB_E, "ecom_customers"), ("customer_addresses", DB_E, "customer_addresses"), + ("customer_devices", DB_E, "customer_devices"), ("orders", DB_E, "orders"), + ("order_items", DB_E, "order_items"), ("order_status_history", DB_E, "order_status_history"), + ("invoices", DB_E, "invoices"), ("payment_ledger", DB_E, "payment_ledger"), + ("coupons", DB_E, "coupons"), ("coupon_usages", DB_E, "coupon_usages"), + ("customer_wallets", DB_E, "customer_wallets"), ("wallet_transactions", DB_E, "wallet_transactions"), + ("service_catalog", DB_E, "service_catalog"), ("service_jobs", DB_E, "service_jobs"), + ("service_appointments", DB_E, "service_appointments"), ("service_job_intakes", DB_E, "service_job_intakes"), + ("service_job_assignments", DB_E, "service_job_assignments"), + ("service_job_inspections", DB_E, "service_job_inspections"), + ("service_job_quotes", DB_E, "service_job_quotes"), ("service_payments", DB_E, "service_payments"), + ("service_job_events", DB_E, "service_job_events"), + ("technician_profiles", DB_E, "technician_profiles"), ("technician_skills", DB_E, "technician_skills"), + ("technician_leaves", DB_E, "technician_leaves"), ("technician_working_hours", DB_E, "technician_working_hours"), + ("refund_requests", DB_E, "refund_requests"), ("refund_media", DB_E, "refund_media"), + ("warranties", DB_E, "warranties"), ("customer_reviews", DB_E, "customer_reviews"), + ("product_reviews", DB_E, "product_reviews"), ("product_review_images", DB_E, "product_review_images"), + ("customer_feedbacks", DB_E, "customer_feedbacks"), + ("notifications (commerce)", DB_E, "notifications"), ("notification_templates", DB_E, "notification_templates"), + ("brands", DB_E, "brands"), ("categories", DB_E, "categories"), ("attribute_types", DB_E, "attribute_types"), + ("service_types (crm)", DB_C, "service_types"), ("parts (crm)", DB_C, "parts"), + ("contacts (crm)", DB_C, "contacts"), ("purchase_orders (crm)", DB_C, "purchase_orders"), + ("purchase_order_items (crm)", DB_C, "purchase_order_items"), ("stock_movements (crm)", DB_C, "stock_movements"), + ] + ok = True + for label, db, t in modules: + n = count(db, t) + flag = "" if n >= 100 else " <-- BELOW 100" + if n < 100: + ok = False + print(f"{label:<38} {n:>6}{flag}") + print(f"\nDone in {time.time() - t0:.1f}s. All modules >= 100: {ok}") + + +if __name__ == "__main__": + main()