Spaces:
Paused

yaz / scripts /setup /bootstrap_production.py
anaselamr's picture
fix: tenant resolution + city filters + route shadowing
460ee11
Raw History Blame Contribute Delete
3.68 kB
#!/usr/bin/env python3
"""
Bootstrap Production — Create admin user and verify database.
Usage:
python scripts/setup/bootstrap_production.py
Creates:
- Default tenant (if missing)
- Admin user: ayrad / anass@ayrad.care (if missing)
- Verifies bloc_cases table exists
- Imports seed data (if requested)
"""
import os
import sys
import sqlite3
from pathlib import Path
from uuid import uuid4, UUID
from datetime import datetime, timezone
# Add project root to PYTHONPATH
PROJECT_ROOT = Path(__file__).resolve().parent.parent.parent
SRC_PATH = PROJECT_ROOT / "src"
sys.path.insert(0, str(SRC_PATH))
sys.path.insert(0, str(PROJECT_ROOT))
DB_PATH = PROJECT_ROOT / "data" / "databases" / "yaz_care.db"
DEFAULT_TENANT_ID = "1f230591-b535-4731-a79c-67b5b9cbb565"
def get_connection() -> sqlite3.Connection:
DB_PATH.parent.mkdir(parents=True, exist_ok=True)
conn = sqlite3.connect(str(DB_PATH))
conn.row_factory = sqlite3.Row
return conn
def ensure_admin_user(conn: sqlite3.Connection) -> None:
"""Create admin user if not exists."""
import bcrypt
cursor = conn.cursor()
cursor.execute("SELECT id FROM users WHERE username = 'ayrad'")
if cursor.fetchone():
print(" ✓ Admin user 'ayrad' already exists")
return
password = os.environ.get("ADMIN_PASSWORD", "Ayrad2026!")
hashed = bcrypt.hashpw(password.encode("utf-8"), bcrypt.gensalt()).decode("utf-8")
user_id = str(uuid4())
now = datetime.now(timezone.utc).isoformat()
cursor.execute(
"""INSERT INTO users (
id, username, email, hashed_password, role,
first_name, last_name, is_active, is_verified,
is_superuser, tenant_id, created_at, updated_at
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
(
user_id, "ayrad", "anass@ayrad.care", hashed, "admin",
"Anass", "EL AMRANI", 1, 1,
1, DEFAULT_TENANT_ID, now, now,
),
)
conn.commit()
print(f" ✓ Admin user created: ayrad / anass@ayrad.care (id: {user_id})")
def verify_tables(conn: sqlite3.Connection) -> None:
"""Verify essential tables exist."""
cursor = conn.cursor()
cursor.execute("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name")
tables = {row[0] for row in cursor.fetchall()}
required = ["users", "tenants", "bloc_cases"]
for t in required:
if t in tables:
cursor.execute(f"SELECT COUNT(*) FROM [{t}]")
count = cursor.fetchone()[0]
print(f" ✓ {t}: {count} records")
else:
print(f" ✗ {t}: MISSING — run the app first to create tables")
def main():
print("=" * 60)
print("YAZ Care Platform — Production Bootstrap")
print("=" * 60)
print(f"\nDatabase: {DB_PATH}")
print(f"Exists: {DB_PATH.exists()}")
if not DB_PATH.exists():
print("\n⚠ Database file does not exist. Start the app first:")
print(" python3 main.py serve")
sys.exit(1)
conn = get_connection()
print("\n[1/3] Verifying tables...")
verify_tables(conn)
print("\n[2/3] Ensuring admin user...")
ensure_admin_user(conn)
print("\n[3/3] Verifying final state...")
verify_tables(conn)
conn.close()
print("\n" + "=" * 60)
print("✅ Production bootstrap complete")
print("=" * 60)
print("\nNext steps:")
print(" 1. Start server: python3 main.py serve")
print(" 2. Login: http://localhost:8000/login")
print(" 3. Credentials: ayrad / Ayrad2026!")
print(" 4. Import cases: /apps/surgio/bloc/programme")
if __name__ == "__main__":
main()