"""The public demo tenant: ``python -m core.cli seed-demo [--reset]``. * One tenant, seeded by the installed packs' own seeders (``WP_DEMO_SEEDERS``, names from the optional pack member ``seeders()``; core never imports packs). Defaults: the demo pack's mock store, the e-commerce store with two years of sales history, and the appointments clinic. * A published login (``WP_DEMO_EMAIL`` / ``WP_DEMO_PASSWORD``) with the **manager** role: it can chat, approve and build workflows, but cannot add channel accounts (owner only). The tenant owner is a separate account with a random, unpublished password. * **No real outbound messages:** every channel account a seeder created is disabled and its secret reference removed, and the delivery worker only serves enabled accounts. Messages still queue in the pack outboxes, so the inbox and undo window remain visible. Deploy the demo without ``WP_SECRET_*`` channel tokens as a second line of defence. * ``--reset`` (nightly cron) deletes every tenant-owned row of the demo tenant (owner role, FK-safe order, LangGraph checkpoints included), then seeds again. The tenant id and the login stay the same. """ from __future__ import annotations import logging import secrets import uuid from dataclasses import dataclass, field from typing import Any from sqlalchemy import select, text, update from sqlalchemy.exc import DBAPIError, IntegrityError from core.auth.jwt import hash_password from core.config import Settings from core.db.session import Database from core.tenancy.models import Role, Tenant, User from core.tenancy.service import add_member, memberships_for, signup log = logging.getLogger(__name__) CHECKPOINT_TABLES = ("checkpoint_writes", "checkpoint_blobs", "checkpoints") DEMO_SETTINGS: dict[str, Any] = { "demo": True, # Small, visible approval flows: refunds above Rs 5,000 go to the inbox. "policy_attrs": {"auto_refund_limit": 5000}, } @dataclass class DemoResult: tenant_id: uuid.UUID email: str created: bool reset: bool seeded: list[str] = field(default_factory=list) missing_seeders: list[str] = field(default_factory=list) purged: dict[str, int] = field(default_factory=dict) channels_disabled: int = 0 def as_dict(self) -> dict[str, Any]: return { "tenant_id": str(self.tenant_id), "email": self.email, "created": self.created, "reset": self.reset, "seeded": self.seeded, "missing_seeders": self.missing_seeders, "purged_rows": sum(self.purged.values()), "channels_disabled": self.channels_disabled, } def owner_email(settings: Settings) -> str: local, _, domain = settings.demo_email.partition("@") return f"{local}-owner@{domain or 'workpilot.dev'}" async def tenant_tables(owner_db: Database) -> list[str]: async with owner_db.session() as s: rows = await s.execute( text( "SELECT c.table_name FROM information_schema.columns c " "JOIN information_schema.tables t " "ON t.table_schema = c.table_schema AND t.table_name = c.table_name " "WHERE c.table_schema = current_schema() AND c.column_name = 'tenant_id' " "AND t.table_type = 'BASE TABLE'" ) ) return sorted(r[0] for r in rows) async def purge_tenant_data( owner_db: Database, tenant_id: uuid.UUID, *, keep: tuple[str, ...] = ("tenants",) ) -> dict[str, int]: """Delete every row of one tenant from every table with a ``tenant_id`` column (owner role bound to the tenant, so RLS still scopes each statement), plus its LangGraph checkpoints. Foreign keys are honoured by retrying tables until no more progress is made.""" tables = [t for t in await tenant_tables(owner_db) if t not in keep] counts: dict[str, int] = {} async with owner_db.session(tenant_id=tenant_id) as s, s.begin(): for t in CHECKPOINT_TABLES: exists = (await s.execute(text("SELECT to_regclass(:t)"), {"t": t})).scalar() if exists: res = await s.execute( text(f'DELETE FROM "{t}" WHERE thread_id LIKE :p'), # noqa: S608 {"p": f"{tenant_id}:%"}, ) counts[t] = int(getattr(res, "rowcount", 0) or 0) pending = tables while pending: blocked: list[str] = [] for t in pending: try: async with s.begin_nested(): res = await s.execute( text(f'DELETE FROM "{t}" WHERE tenant_id = :t'), # noqa: S608 {"t": tenant_id}, ) counts[t] = counts.get(t, 0) + int(getattr(res, "rowcount", 0) or 0) except (IntegrityError, DBAPIError) as exc: if "foreign key" not in str(exc).lower(): raise blocked.append(t) if len(blocked) == len(pending): raise RuntimeError(f"cannot purge tenant rows (FK cycle?): {blocked}") pending = blocked return {k: v for k, v in counts.items() if v} async def _find_tenant(db: Database, settings: Settings) -> uuid.UUID | None: async with db.session() as s: user = ( await s.execute(select(User).where(User.email == settings.demo_email.lower())) ).scalar_one_or_none() if user is None: return None ms = await memberships_for(db, user.id) return ms[0].tenant_id if ms else None async def _set_password(db: Database, email: str, password: str) -> None: async with db.session() as s, s.begin(): await s.execute( update(User) .where(User.email == email.lower()) .values(password_hash=hash_password(password)) ) async def _members(db: Database, tenant_id: uuid.UUID, settings: Settings) -> None: pw = settings.demo_password.get_secret_value() await add_member( db, tenant_id, email=owner_email(settings), password=secrets.token_urlsafe(24), role=Role.OWNER, ) await add_member(db, tenant_id, email=settings.demo_email, password=pw, role=Role.MANAGER) async def disable_outbound(db: Database, tenant_id: uuid.UUID) -> int: """Turn off every channel account of the tenant and drop its secret reference.""" async with db.session(tenant_id=tenant_id) as s, s.begin(): res = await s.execute( text( "UPDATE channel_accounts SET enabled = false, secret_ref = NULL " "WHERE tenant_id = :t" ), {"t": tenant_id}, ) return int(getattr(res, "rowcount", 0) or 0) async def seed_demo_tenant( db: Database, owner_db: Database, packs: list[Any], settings: Settings, *, reset: bool = False, ) -> DemoResult: """Create (or, with ``reset``, wipe and re-seed) the demo tenant. Idempotent without ``reset``: an existing demo tenant is left as it is.""" tenant_id = await _find_tenant(db, settings) result: DemoResult if tenant_id is None: res = await signup( db, business_name=settings.demo_business_name, email=owner_email(settings), password=secrets.token_urlsafe(24), ) tenant_id = res.tenant_id await add_member( db, tenant_id, email=settings.demo_email, password=settings.demo_password.get_secret_value(), role=Role.MANAGER, ) result = DemoResult(tenant_id, settings.demo_email, created=True, reset=False) elif reset: purged = await purge_tenant_data(owner_db, tenant_id) await _members(db, tenant_id, settings) await _set_password(db, settings.demo_email, settings.demo_password.get_secret_value()) result = DemoResult( tenant_id, settings.demo_email, created=False, reset=True, purged=purged ) else: log.info("demo tenant %s already exists (use --reset to re-seed)", tenant_id) return DemoResult(tenant_id, settings.demo_email, created=False, reset=False) async with db.session(tenant_id=tenant_id) as s, s.begin(): await s.execute( update(Tenant) .where(Tenant.id == tenant_id) .values(name=settings.demo_business_name, settings=dict(DEMO_SETTINGS)) ) available: dict[str, Any] = {} for p in packs: available.update(getattr(p, "seeders", dict)()) for name in settings.demo_seeders: fn = available.get(name) if fn is None: result.missing_seeders.append(name) continue await fn(db, tenant_id) result.seeded.append(name) result.channels_disabled = await disable_outbound(db, tenant_id) return result