From 597879aeb27d1192e5472d564c4cb040715d7c1e Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 10:18:34 -0600 Subject: [PATCH] Week 6+: the admin portal (web UI over the engines) The portal is the human-facing half - where a person authorizes, the one thing the model cannot. A server-rendered FastAPI app walks an admin through connect -> review mappings -> dry-run preview -> approve -> migrate -> report, in the browser. It never calls the model. Every page reads state the engines wrote, and approve/migrate/sync are server-side calls behind the same gates the CLI uses, so the whole portal runs with no API key: for the demo it loads the proposals Claude produced in the evaluation runs (real output, pre-computed) and the steps downstream are genuine. On org D that is 387 loaded, 9 held back - exactly what the dry-run and the migration tests establish. - src/firstsync/portal/: FastAPI app, demo-proposal seeding, Jinja templates (index, org, mappings, dryrun, report). No JS framework; plain pages with POST-redirect-GET so back and refresh behave. - firstsync portal command; portal optional extra; templates shipped as package data; mypy and ruff clean; CI installs .[dev,portal]. - Dockerfile + fly.toml for a one-command demo deploy, scale-to-zero. - tests/test_portal.py: the full flow via TestClient, migrate refused without approval, reset, unknown org -> 404. README gains a Portal section and deploy steps; Hosting and the status line updated now that the portal exists. 220 tests, no network, no key. Co-Authored-By: Claude Opus 4.8 Claude-Session: https://claude.ai/code/session_017ggB2HHn8zjybwfaJG1g3R --- .github/workflows/ci.yml | 2 +- Dockerfile | 14 ++ README.md | 72 +++++-- fly.toml | 34 ++++ pyproject.toml | 8 +- src/firstsync/cli.py | 20 ++ src/firstsync/config.py | 1 + src/firstsync/portal/__init__.py | 9 + src/firstsync/portal/app.py | 196 +++++++++++++++++++ src/firstsync/portal/seed.py | 60 ++++++ src/firstsync/portal/templates/base.html | 64 ++++++ src/firstsync/portal/templates/dryrun.html | 73 +++++++ src/firstsync/portal/templates/index.html | 25 +++ src/firstsync/portal/templates/mappings.html | 33 ++++ src/firstsync/portal/templates/org.html | 68 +++++++ src/firstsync/portal/templates/report.html | 41 ++++ tests/test_portal.py | 71 +++++++ 17 files changed, 768 insertions(+), 23 deletions(-) create mode 100644 Dockerfile create mode 100644 fly.toml create mode 100644 src/firstsync/portal/__init__.py create mode 100644 src/firstsync/portal/app.py create mode 100644 src/firstsync/portal/seed.py create mode 100644 src/firstsync/portal/templates/base.html create mode 100644 src/firstsync/portal/templates/dryrun.html create mode 100644 src/firstsync/portal/templates/index.html create mode 100644 src/firstsync/portal/templates/mappings.html create mode 100644 src/firstsync/portal/templates/org.html create mode 100644 src/firstsync/portal/templates/report.html create mode 100644 tests/test_portal.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 2ade5c0..913da39 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -16,7 +16,7 @@ jobs: - uses: actions/setup-python@v5 with: python-version: "3.12" - - run: pip install -e ".[dev]" + - run: pip install -e ".[dev,portal]" - run: ruff check . - run: mypy src - run: pytest -q diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..1c5ef3d --- /dev/null +++ b/Dockerfile @@ -0,0 +1,14 @@ +# The admin portal, for a demo deploy (Fly.io, Render, or any container host). +FROM python:3.12-slim + +WORKDIR /app +COPY . . +RUN pip install --no-cache-dir ".[portal]" + +# The portal writes demo state (proposals, approvals, the SQLite target) under here. +ENV FIRSTSYNC_STATE_DIR=/data +ENV FIRSTSYNC_PORTAL_PORT=8000 +RUN mkdir -p /data + +EXPOSE 8000 +CMD ["firstsync", "portal"] diff --git a/README.md b/README.md index d37c541..49a2913 100644 --- a/README.md +++ b/README.md @@ -15,10 +15,11 @@ plain language. Deterministic code decides what actually runs. > migration engine loads approved data idempotently; and a sync engine keeps the target > in step afterwards, adding and updating safely while reporting (never acting on) records > that regressed or vanished. A go-live report and a `trace` view over the audit log tie -> it together. There is no tool by which the model approves, migrates, syncs, or deletes -> anything. The held-out org scored [100% with perfectly calibrated -> questions](#the-held-out-org-e). What remains is a hosted portal, not core logic. This -> is a reference implementation with no customers. See +> it together, and a [web portal](#the-portal) puts the whole flow in the browser. There +> is no tool by which the model approves, migrates, syncs, or deletes anything. The +> held-out org scored [100% with perfectly calibrated questions](#the-held-out-org-e). +> What remains is deploying the portal to a public URL, not core logic. This is a +> reference implementation with no customers. See > [What is and is not tested](#what-is-and-is-not-tested). ```mermaid @@ -159,7 +160,7 @@ Pythons refuse installs outside one. python3 -m venv .venv source .venv/bin/activate pip install -e ".[dev]" -pytest -q # 214 tests, no network, no API key +pytest -q # 220 tests, no network, no API key python scripts/run_eval.py --baseline # the evaluation, with name matching instead of a model python -m firstsync.mcp_server # the MCP server, over stdio ``` @@ -406,26 +407,55 @@ All six weeks are built and merged. | 3 | Dry-run engine, failure grouping, defect scoring | done | | 4 | Hash-bound approval gate, idempotent migration engine | done | | 5 | Sync engine, go-live report, audit-log trace | done | -| 6 | Held-out run on org E, observability, this README | done | +| 6 | Held-out run on org E, observability, the portal, this README | done | -The one piece still ahead is a hosted portal, covered next. +The core is complete; what is left is deploying the portal to a public URL. + +## The portal + +The portal is the human-facing half — where a person does the one thing the model cannot: +authorize. It walks an administrator through the lifecycle in the browser: connect and see +what the user can read, review Claude's proposed mappings (with the questions it raised), +preview the dry-run of their own data, approve, migrate, and read the go-live report. + +It never calls the model. Every page reads state the engines wrote, and approve, migrate +and sync are server-side calls behind the same gates the CLI uses. So the whole portal +runs with no API key: for the demo it loads the proposals Claude produced in the +evaluation runs — real model output, pre-computed — and the review, dry-run, approve and +migrate steps downstream are genuine. + +```bash +pip install -e ".[portal]" +firstsync portal # http://localhost:8000 +``` + +Built with FastAPI and server-rendered templates — no client-side framework, so the flow +is a sequence of plain pages and the back button and refresh behave. ## Hosting -There is nothing to host yet: FirstSync runs as a CLI and an MCP server, with SQLite as -the target. The portal is the remaining piece, and the hosting choice follows from what -this project is — a portfolio demo with bursty, near-zero traffic, not a product under -steady multi-tenant load. - -For the demo, the portal will run on a managed platform (Fly.io or Render) with serverless -Postgres. Scale-to-zero fits bursty traffic: it costs almost nothing between visits and -wakes on the first request, where an always-on service plus a managed database would bill -around the clock to serve no one. The production path on AWS is App Runner (or ECS -Fargate) behind the same audit and tenancy model, with Amazon RDS or Aurora Serverless for -Postgres and row-level security per tenant — the right shape once there are real tenants -and steady load, and the wrong shape, pure idle cost, for a demo. Right-sizing the host to -the traffic is the decision; the production design is written down so the step up is a -configuration change, not a rewrite. +The portal ships with a `Dockerfile` and a `fly.toml`, so a demo deploy is one command set: + +```bash +fly launch --no-deploy # pick an app name and region +fly deploy +``` + +The hosting choice follows from what this project is — a portfolio demo with bursty, +near-zero traffic, not a product under steady multi-tenant load. The `fly.toml` scales the +machine to zero: it stops when idle and wakes on the first request, so it costs almost +nothing between visits, where an always-on service plus a managed database would bill +around the clock to serve no one. Render with a serverless Postgres add-on is the same +trade in a different wrapper. The production path on AWS is App Runner (or ECS Fargate) +behind the same audit and tenancy model, with Amazon RDS or Aurora Serverless for Postgres +and row-level security per tenant — the right shape once there are real tenants and steady +load, and the wrong shape, pure idle cost, for a demo. Right-sizing the host to the traffic +is the decision; the production design is written down so the step up is a configuration +change, not a rewrite. + +Demo state (the SQLite target, proposals, approvals) is ephemeral and resettable from the +UI, so no volume is attached; point `FIRSTSYNC_STATE_DIR` at a mounted volume for durable +state. ## Licence diff --git a/fly.toml b/fly.toml new file mode 100644 index 0000000..75c8940 --- /dev/null +++ b/fly.toml @@ -0,0 +1,34 @@ +# Fly.io config for the FirstSync demo portal. +# First run: `fly launch --no-deploy` to pick an app name and region, then `fly deploy`. +# Rename the app below to whatever `fly launch` assigns (or set your own). + +app = "firstsync-demo" +primary_region = "iad" + +[build] + dockerfile = "Dockerfile" + +[env] + FIRSTSYNC_PORTAL_PORT = "8000" + FIRSTSYNC_STATE_DIR = "/data" + +[http_service] + internal_port = 8000 + force_https = true + # Scale to zero: the machine stops when idle and wakes on the next request, so a + # low-traffic demo costs almost nothing between visits. + auto_stop_machines = "stop" + auto_start_machines = true + min_machines_running = 0 + + [[http_service.checks]] + method = "GET" + path = "/healthz" + interval = "15s" + timeout = "2s" + +# Demo state is ephemeral and reset-able in the UI, so no persistent volume is attached. +# For durable demo state, attach a volume and point FIRSTSYNC_STATE_DIR at its mount. +[[vm]] + size = "shared-cpu-1x" + memory = "512mb" diff --git a/pyproject.toml b/pyproject.toml index e4b572a..a197158 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -21,13 +21,19 @@ firstsync = "firstsync.cli:main" [project.optional-dependencies] agent = ["claude-agent-sdk>=0.2"] +portal = [ + "fastapi>=0.110", + "uvicorn[standard]>=0.29", + "jinja2>=3.1", + "python-multipart>=0.0.9", +] dev = ["pytest>=8", "ruff>=0.6", "mypy>=1.10", "hypothesis>=6.100"] [tool.setuptools.packages.find] where = ["src"] [tool.setuptools.package-data] -firstsync = ["target/*.sql"] +firstsync = ["target/*.sql", "portal/templates/*.html"] [tool.pytest.ini_options] testpaths = ["tests"] diff --git a/src/firstsync/cli.py b/src/firstsync/cli.py index 228201f..40121c0 100644 --- a/src/firstsync/cli.py +++ b/src/firstsync/cli.py @@ -10,6 +10,7 @@ firstsync sync ORG --db PATH bring the target in step with the source, safely firstsync report ORG where this onboarding stands, in plain language firstsync trace [--run ID] what the agent did, read back from the audit log + firstsync portal [--port N] run the admin portal (web UI over the engines) firstsync audit [--last N] show the last audit-log entries Approval and migration are deliberately CLI commands, not MCP tools: the model proposes; @@ -65,6 +66,9 @@ def main(argv: list[str] | None = None) -> int: tr.add_argument("--run", default=None, help="Show one run's full timeline.") tr.add_argument("--connection", default=None, help="Only runs touching this connection.") + pt = sub.add_parser("portal", help="Run the admin portal (web UI).") + pt.add_argument("--port", type=int, default=None, help="Port to listen on (default 8000).") + log = sub.add_parser("audit", help="Show the last audit-log entries.") log.add_argument("--last", type=int, default=20) @@ -144,6 +148,22 @@ def main(argv: list[str] | None = None) -> int: print(json.dumps(report, indent=2) if args.json else golive.render(report)) return 0 + if args.command == "portal": + import os + + if args.port: + os.environ["FIRSTSYNC_PORTAL_PORT"] = str(args.port) + try: + from firstsync.portal.app import main as serve_portal + except ModuleNotFoundError: + print( + "The portal needs the 'portal' extra: pip install -e \".[portal]\"", + file=sys.stderr, + ) + return 2 + serve_portal() + return 0 + if args.command == "trace": if args.run: try: diff --git a/src/firstsync/config.py b/src/firstsync/config.py index 682c735..ba3dfad 100644 --- a/src/firstsync/config.py +++ b/src/firstsync/config.py @@ -28,6 +28,7 @@ class Settings(BaseSettings): run_id: str = Field(default=_PROCESS_RUN_ID, min_length=1, max_length=64) max_tool_calls: int = Field(default=300, ge=1, le=10_000) model: str | None = None + portal_port: int = Field(default=8000, ge=1, le=65_535) def get_settings() -> Settings: diff --git a/src/firstsync/portal/__init__.py b/src/firstsync/portal/__init__.py new file mode 100644 index 0000000..497432b --- /dev/null +++ b/src/firstsync/portal/__init__.py @@ -0,0 +1,9 @@ +"""The admin portal: the human-facing surface of FirstSync. + +The portal is where a person does the one thing the model cannot — authorize. It shows +Claude's proposed mappings, the dry-run preview of their own data, and the approve and +migrate controls. It never calls the model: every page reads state the engines wrote, and +every action (approve, migrate, sync) is a server-side call behind the same gate the CLI +uses. For a self-contained demo it loads the proposals Claude produced in the evaluation +runs, so the whole flow works with no API key. +""" diff --git a/src/firstsync/portal/app.py b/src/firstsync/portal/app.py new file mode 100644 index 0000000..166c8a8 --- /dev/null +++ b/src/firstsync/portal/app.py @@ -0,0 +1,196 @@ +"""The FastAPI portal. + +Linear flow, server-rendered, no model calls: connect → review mappings → dry-run preview +→ approve → migrate → report. Each action is a plain POST that calls an engine and +redirects, so the browser's back button and refresh behave and nothing needs JavaScript. +""" + +from __future__ import annotations + +from pathlib import Path +from typing import Any + +from fastapi import FastAPI, Request +from fastapi.responses import HTMLResponse, PlainTextResponse, RedirectResponse +from fastapi.templating import Jinja2Templates + +from firstsync import approval, dryrun, golive, migrate, sync, tools +from firstsync.config import get_settings +from firstsync.connections import UnknownConnection, available_fixtures, get_client +from firstsync.mapping import ProposalStore, coverage +from firstsync.portal import seed +from firstsync.target.db import TargetDB + +TEMPLATES = Jinja2Templates(directory=str(Path(__file__).parent / "templates")) + +app = FastAPI(title="FirstSync", docs_url=None, redoc_url=None) + + +@app.exception_handler(UnknownConnection) +def _unknown_connection(request: Request, exc: UnknownConnection) -> PlainTextResponse: + return PlainTextResponse(f"No such connection: {exc}", status_code=404) + + +def _db_path(connection: str) -> Path: + folder = get_settings().state_dir / "portal" + folder.mkdir(parents=True, exist_ok=True) + return folder / f"{connection}.db" + + +def _page(request: Request, name: str, **ctx: Any) -> HTMLResponse: + return TEMPLATES.TemplateResponse(request, name, ctx) + + +def _known(connection: str) -> str: + if connection not in available_fixtures(): + raise UnknownConnection(connection) + return connection + + +@app.get("/", response_class=HTMLResponse) +def index(request: Request) -> HTMLResponse: + orgs = [ + {"name": c, "has_demo": seed.has_demo(c), "approved": approval.load(c) is not None} + for c in available_fixtures() + ] + return _page(request, "index.html", orgs=orgs) + + +@app.get("/org/{connection}", response_class=HTMLResponse) +def overview(request: Request, connection: str) -> HTMLResponse: + _known(connection) + client = get_client(connection) + access = tools.sf_check_access(client) + proposals = ProposalStore(connection).load() + gate = approval.check(connection) if proposals else {"ok": False} + return _page( + request, + "org.html", + connection=connection, + access=access, + has_proposals=bool(proposals), + has_demo=seed.has_demo(connection), + coverage=coverage(proposals) if proposals else None, + approved=gate.get("ok", False), + step=_step(connection, bool(proposals), gate.get("ok", False)), + ) + + +def _step(connection: str, has_proposals: bool, approved: bool) -> str: + try: + migrate.load(connection) + return "migrated" + except ValueError: + pass + if approved: + return "approved" + if has_proposals: + return "mapped" + return "start" + + +@app.post("/org/{connection}/seed") +def do_seed(connection: str) -> RedirectResponse: + _known(connection) + seed.seed(connection) + return RedirectResponse(f"/org/{connection}/mappings", status_code=303) + + +@app.get("/org/{connection}/mappings", response_class=HTMLResponse) +def mappings(request: Request, connection: str) -> HTMLResponse: + _known(connection) + proposals = ProposalStore(connection).load() + rows = sorted(proposals.values(), key=lambda p: p["target"]) + return _page( + request, + "mappings.html", + connection=connection, + rows=rows, + coverage=coverage(proposals), + ) + + +@app.get("/org/{connection}/dryrun", response_class=HTMLResponse) +def dry_run(request: Request, connection: str) -> HTMLResponse: + _known(connection) + result = dryrun.start(get_client(connection), connection, limit=2000) + return _page( + request, + "dryrun.html", + connection=connection, + tables=result.tables, + groups=result.groups, + duplicates=result.duplicates, + preview=result.preview, + approved=approval.check(connection).get("ok", False), + ) + + +@app.post("/org/{connection}/approve") +def do_approve(connection: str) -> RedirectResponse: + _known(connection) + approval.approve(connection, approved_by="portal demo admin") + return RedirectResponse(f"/org/{connection}", status_code=303) + + +@app.post("/org/{connection}/migrate") +def do_migrate(connection: str) -> RedirectResponse: + _known(connection) + db = TargetDB(_db_path(connection)) + try: + migrate.run_migration(get_client(connection), connection, db, limit=2000) + finally: + db.close() + return RedirectResponse(f"/org/{connection}/report", status_code=303) + + +@app.post("/org/{connection}/sync") +def do_sync(connection: str) -> RedirectResponse: + _known(connection) + db = TargetDB(_db_path(connection)) + try: + sync.run_sync(get_client(connection), connection, db, limit=2000) + finally: + db.close() + return RedirectResponse(f"/org/{connection}/report", status_code=303) + + +@app.get("/org/{connection}/report", response_class=HTMLResponse) +def report(request: Request, connection: str) -> HTMLResponse: + _known(connection) + return _page(request, "report.html", connection=connection, report=golive.build(connection)) + + +@app.post("/org/{connection}/reset") +def do_reset(connection: str) -> RedirectResponse: + _known(connection) + ProposalStore(connection).clear() + settings = get_settings() + for sub in ("approvals", "dryruns", "migrations", "syncs"): + _wipe(settings.state_dir / sub / connection, settings.state_dir / sub, connection) + _db_path(connection).unlink(missing_ok=True) + return RedirectResponse(f"/org/{connection}", status_code=303) + + +def _wipe(folder: Path, parent: Path, connection: str) -> None: + import shutil + + if folder.is_dir(): + shutil.rmtree(folder, ignore_errors=True) + single = parent / f"{connection}.json" + single.unlink(missing_ok=True) + + +@app.get("/healthz") +def healthz() -> dict[str, str]: + return {"status": "ok"} + + +def main() -> None: + import uvicorn + + uvicorn.run(app, host="0.0.0.0", port=int(get_settings().portal_port)) # noqa: S104 + + +if __name__ == "__main__": + main() diff --git a/src/firstsync/portal/seed.py b/src/firstsync/portal/seed.py new file mode 100644 index 0000000..fa4a363 --- /dev/null +++ b/src/firstsync/portal/seed.py @@ -0,0 +1,60 @@ +"""Demo proposals, so the portal runs without an API key. + +The mapping step is Claude's work and needs the agent. For a demo that a stranger can +open, we load the proposals Claude actually produced in the evaluation runs (saved under +results/) into the proposal store. They are real model output, pre-computed — not +hand-written — so the review, dry-run, approve and migrate steps downstream are genuine. +""" + +from __future__ import annotations + +import json +import os +from pathlib import Path +from typing import Any + +from firstsync.mapping import ProposalStore + +_ENV = "FIRSTSYNC_DEMO_RESULTS_DIR" + + +def _results_dir() -> Path: + override = os.environ.get(_ENV) + if override: + return Path(override) + return Path(__file__).resolve().parents[3] / "results" + + +def _files() -> list[Path]: + root = _results_dir() + return [ + root / "claude-claude-sonnet-5-5.json", + root / "claude-claude-sonnet-5-5-held-out.json", + ] + + +def demo_proposals(connection: str) -> dict[str, Any]: + """The saved Claude proposals for one org, or KeyError if none are bundled.""" + for path in _files(): + if not path.is_file(): + continue + data = json.loads(path.read_text(encoding="utf-8")) + org = data.get("orgs", {}).get(connection) + if org and org.get("runs"): + return org["runs"][0]["proposals"] + raise KeyError(connection) + + +def has_demo(connection: str) -> bool: + try: + demo_proposals(connection) + return True + except KeyError: + return False + + +def seed(connection: str) -> dict[str, Any]: + """Load the bundled proposals for a connection into its proposal store.""" + proposals = demo_proposals(connection) + ProposalStore(connection).save(proposals) + return proposals diff --git a/src/firstsync/portal/templates/base.html b/src/firstsync/portal/templates/base.html new file mode 100644 index 0000000..d26e927 --- /dev/null +++ b/src/firstsync/portal/templates/base.html @@ -0,0 +1,64 @@ + + + + + + {% block title %}FirstSync{% endblock %} + + + +
+ FirstSync + customer onboarding — Claude proposes, a person authorizes +
+
+ {% block body %}{% endblock %} +
+ + diff --git a/src/firstsync/portal/templates/dryrun.html b/src/firstsync/portal/templates/dryrun.html new file mode 100644 index 0000000..bc3c01b --- /dev/null +++ b/src/firstsync/portal/templates/dryrun.html @@ -0,0 +1,73 @@ +{% extends "base.html" %} +{% block title %}{{ connection }} dry-run — FirstSync{% endblock %} +{% block body %} +

Dry-run preview — {{ connection }}

+

Every record built the way the migration would build it. Nothing is written. +clean loads, +warning loads without the warned value, +needs decision and +blocking are held back.

+ +
+ + + + + {% for t in tables %} + + + + + + {% endfor %} + +
TableRecordsCleanWarningNeeds decisionBlocking
{{ t.table }}{% if t.not_runnable %} +
{{ t.not_runnable }}
{% endif %}
{{ t.records }}{{ t.clean }}{{ t.warning }}{{ t.needs_decision }}{{ t.blocking }}
+
+ +{% if groups %} +

What would not load, by cause

+
+ + + + {% for g in groups %} + + + + + + + + {% endfor %} + +
FieldReasonRecordsExample
{{ g.target }}{{ g.reason }}{{ g.severity.replace('_',' ') }}{{ g.count }}{{ g.example_input }}
+
+{% endif %} + +{% if duplicates %} +

Likely duplicates

+
+

Records that would collide on a table's natural key. Reported, not merged.

+
    + {% for d in duplicates %} +
  • {{ d.table }} on {{ d.key|join(', ') }}: {{ d.record_ids|join(', ') }}
  • + {% endfor %} +
+
+{% endif %} + +
+ {% if approved %} + already approved +
+
+ {% else %} +
+
+ {% endif %} + Back +
+

Approving records a hash of these proposals. If the mapping changes +afterwards, the migration refuses until you approve again.

+{% endblock %} diff --git a/src/firstsync/portal/templates/index.html b/src/firstsync/portal/templates/index.html new file mode 100644 index 0000000..cb9ca18 --- /dev/null +++ b/src/firstsync/portal/templates/index.html @@ -0,0 +1,25 @@ +{% extends "base.html" %} +{% block body %} +

Onboard a customer

+

Pick a customer Salesforce org to onboard into the target product. Each is a +synthetic org with its own quirks; Claude has already proposed how every field maps.

+ +
+ + + + {% for org in orgs %} + + + + + + + {% endfor %} + +
OrgProposalsStatus
{{ org.name }}{% if org.has_demo %}Claude's mapping ready{% else %}none bundled{% endif %}{% if org.approved %}approved{% else %}not started{% endif %}Open
+
+ +

The portal never calls the model. It shows Claude's proposals and the +dry-run preview, and the approve and migrate controls are server actions a person takes.

+{% endblock %} diff --git a/src/firstsync/portal/templates/mappings.html b/src/firstsync/portal/templates/mappings.html new file mode 100644 index 0000000..3dd0a3d --- /dev/null +++ b/src/firstsync/portal/templates/mappings.html @@ -0,0 +1,33 @@ +{% extends "base.html" %} +{% block title %}{{ connection }} mappings — FirstSync{% endblock %} +{% block body %} +

Proposed mappings — {{ connection }}

+

Each target field, where Claude proposes it comes from, and why. Fields with +a question need your decision before approval.

+ +
+ + + + {% for r in rows %} + + + + + + + {% endfor %} + +
TargetSourceConf.Reason / question
{{ r.target }}{% if r.source %}{{ r.source }}{% else %}— none —{% endif %}{{ r.confidence }} + {{ r.reason }} + {% if r.question_for_admin %} + + {% endif %} +
+
+ + +{% endblock %} diff --git a/src/firstsync/portal/templates/org.html b/src/firstsync/portal/templates/org.html new file mode 100644 index 0000000..9198818 --- /dev/null +++ b/src/firstsync/portal/templates/org.html @@ -0,0 +1,68 @@ +{% extends "base.html" %} +{% block title %}{{ connection }} — FirstSync{% endblock %} +{% block body %} +
+ 1 Connect › + 2 Review mappings › + 3 Dry-run › + 4 Approve › + 5 Migrate +
+ +

{{ connection }}

+

What the connected user can read in this org, and where you are in onboarding.

+ +
+

Access

+ + + + {% for o in access.readable %} + + + {% endfor %} + {% for m in access.missing %} + + + {% endfor %} + +
ObjectFields
{{ o.name }} {% if o.custom %}custom{% endif %}{{ o.fields }}readable
{{ m.object }}—no access {{ m.fix }}
+
+ +{% if not has_proposals %} + {% if has_demo %} +
+

Mapping

+

Claude has a proposed mapping for this org from the evaluation run. Load it to review.

+
+ +
+
+ {% else %} +

No bundled proposals for this org.

+ {% endif %} +{% else %} +
+

Mapping

+

{{ coverage.proposed }} of {{ coverage.total_target_fields }} target fields proposed. + {% if coverage.open_questions %}{{ coverage.open_questions|length }} + carry a question for the admin.{% endif %}

+
+ Review mappings + Dry-run preview + {% if step == 'migrated' %} + Go-live report + {% elif approved %} +
+
+ {% endif %} +
+
+
+ {% if approved and step != 'migrated' %} + + {% endif %} +
+{% endif %} +{% endblock %} diff --git a/src/firstsync/portal/templates/report.html b/src/firstsync/portal/templates/report.html new file mode 100644 index 0000000..e64e413 --- /dev/null +++ b/src/firstsync/portal/templates/report.html @@ -0,0 +1,41 @@ +{% extends "base.html" %} +{% block title %}{{ connection }} report — FirstSync{% endblock %} +{% block body %} +

Go-live report — {{ connection }}

+

{{ report.headline }}

+ +{% if report.migration %} +
+

Migration

+

{{ report.migration.inserted }} inserted · + {{ report.migration.updated }} updated · {{ report.migration.unchanged }} unchanged · + {{ report.migration.skipped }} skipped

+ {% if report.approved %} +

Approved by {{ report.approved.by }}, {{ report.approved.fields }} fields.

+ {% endif %} +
+{% endif %} + +{% if report.latest_sync %} +
+

Latest sync

+

{{ report.latest_sync.added }} added · {{ report.latest_sync.changed }} changed · + {{ report.latest_sync.regressed }} regressed · {{ report.latest_sync.vanished }} vanished

+
+{% endif %} + +{% if report.open_items %} +
+

Open items

+
    {% for item in report.open_items %}
  • {{ item }}
  • {% endfor %}
+
+{% endif %} + +
+
+
+
+
+ Back to org +
+{% endblock %} diff --git a/tests/test_portal.py b/tests/test_portal.py new file mode 100644 index 0000000..8235a5e --- /dev/null +++ b/tests/test_portal.py @@ -0,0 +1,71 @@ +"""The admin portal. + +The portal is the human-facing half, so the tests follow a person through the flow — +connect, load the mapping, preview, approve, migrate, report — and check the two things +that matter: the migration loads exactly what the dry-run previewed, and nothing happens +without approval. +""" + +from __future__ import annotations + +import pytest + +pytest.importorskip("fastapi") +from starlette.testclient import TestClient # noqa: E402 + +from firstsync.portal.app import app # noqa: E402 + + +@pytest.fixture(autouse=True) +def state(tmp_path, monkeypatch): + monkeypatch.setenv("FIRSTSYNC_STATE_DIR", str(tmp_path)) + + +@pytest.fixture() +def client(): + return TestClient(app) + + +def test_index_lists_orgs(client): + body = client.get("/").text + assert "org_d" in body and "org_a" in body + + +def test_full_flow_loads_what_the_dryrun_showed(client): + # Connect → the overview renders the access check. + assert client.get("/org/org_d").status_code == 200 + # Load Claude's proposals, review them, preview. + client.post("/org/org_d/seed") + assert "contacts.email" in client.get("/org/org_d/mappings").text + dry = client.get("/org/org_d/dryrun").text + assert "blocking" in dry # org_d has blocking records + # Approve, then migrate. + client.post("/org/org_d/approve") + client.post("/org/org_d/migrate") + report = client.get("/org/org_d/report").text + # 387 loaded, exactly as the dry-run and the migration tests established. + assert "387" in report + + +def test_migrate_refuses_without_approval(client): + client.post("/org/org_a/seed") + # Jump straight to migrate with no approval. The engine refuses; no report is written. + client.post("/org/org_a/migrate", follow_redirects=False) + report = client.get("/org/org_a/report").text + assert "no migration has run" in report.lower() or "not approved" in report.lower() + + +def test_reset_clears_state(client): + client.post("/org/org_a/seed") + client.post("/org/org_a/approve") + client.post("/org/org_a/reset") + # After reset the org is back to "load proposals". + assert "Load Claude's proposals" in client.get("/org/org_a").text + + +def test_unknown_org_is_rejected(client): + assert client.get("/org/not_a_real_org").status_code >= 400 + + +def test_healthz(client): + assert client.get("/healthz").json() == {"status": "ok"}