Skip to content
silbulatovichPublic

About

take home

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

18 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Clinician Portal — vertical slice

A FastAPI + Postgres backend and a React + TypeScript frontend, joined by a live SSE channel. A clinician logs in, sees a paginated roster with each patient's live session status, opens a report, edits it, signs it off, and can attach timestamped notes at any point before or after signing. Signing produces a PDF that always reflects every note added so far.

Running it

Postgres (one command, via Docker):

docker compose up -d postgres

This creates two databases in the same container: clinician_portal (dev) and clinician_portal_test (test suite) — see backend/db/init-test-db.sql.

Backend

cd backend
python3 -m venv .venv && source .venv/bin/activate
pip install -r requirements.txt
uvicorn app.main:app --reload --port 8000

On first startup it creates the schema and seeds three clinicians, each with their own roster (34 / 6 / 2 patients — uneven on purpose, so pagination has something to paginate and an almost-empty roster is also visible).

Dev login accounts — username / password, all sharing one obviously-fake password so it's easy to remember while testing:

Username Name Password
amara Dr. Amara Chen Password123!
singh Dr. Priya Singh Password123!
lopez Dr. Mateo Lopez Password123!

Tests: cd backend && pytest -q (53 tests, ~3 minutes — see "Tests" below for what that time buys).

Frontend

cd frontend
npm install
npm run dev   # http://localhost:5173, proxies /api to :8000

Tests: cd frontend && npm test (47 tests). Typecheck/build: npm run build.

To trigger the machine-to-machine phase callback by hand (grab a sessionId from the roster — it's printed under each patient's name):

curl -X POST http://localhost:8000/api/sessions/<sessionId>/phase \
  -H "X-Service-Key: dev-service-key-change-me" -H "Content-Type: application/json" \
  -d '{"phase":"finished","reason":"Connectivity issues"}'

Watch the roster update with no page refresh. reason is optional and only meaningful when phase is "suspended".

Endpoints

Method Path Who calls it
POST /api/auth/login Browser — sets the session cookie
POST /api/auth/logout Browser
GET /api/auth/me Browser — current identity
GET /api/patients Browser — paginated roster
GET /api/stream Browser — SSE channel (phase and report events)
GET /api/reports/{id} Browser
PATCH /api/reports/{id} Browser — edit content (draft only)
POST /api/reports/{id}/signoff Browser
GET /api/reports/{id}/pdf Browser — signed reports only
POST /api/reports/{id}/addenda Browser — add a note
POST /api/sessions/{id}/phase A different backend service, not the browser

Decisions

Storage: Postgres, via SQLAlchemy 2.0 (async) + asyncpg. Real persistence and real transactional guarantees matter here specifically because two of the non-negotiables — idempotent signoff and immutability — are concurrency problems, and Postgres row locks (SELECT ... FOR UPDATE) solve them correctly across multiple app instances or worker processes, not just within one Python process. All cross-tenant filtering lives in one place, app/repository.py — the only module that queries the database — so a route handler can't leak another clinician's data by forgetting a WHERE clinician_id = .... Schema creation uses metadata.create_all rather than a migrations tool, which is enough for a single, fixed schema; seeing this schema evolve under real data is where Alembic would earn its keep (see "what I'd do with more time").

Authentication: real login, not just a stub identity. A clinician logs in with a username and a bcrypt-hashed password; the server sets an httpOnly, SameSite=Lax JWT cookie (app/security.py, app/routers/auth.py). An httpOnly cookie is invisible to JavaScript, so an XSS bug can't exfiltrate it the way it could a token sitting in localStorage — the cost is that every fetch (including the SSE stream) needs credentials: "include", and CORS needs allow_credentials=True with an explicit origin instead of *. A few smaller details worth calling out because they're easy to get subtly wrong:

  • Login returns the same error, in the same amount of time, whether the username doesn't exist or the password is wrong — the handler always runs bcrypt, against a dummy hash when there's no real user, so neither the response body nor the response timing can be used to enumerate valid usernames.
  • bcrypt runs off the event loop (asyncio.to_thread), not inline in the async route handler. bcrypt is deliberately slow (~250–300ms, CPU-bound); run synchronously it would block every other in-flight request on the same worker for that whole duration.
  • The clinician-facing cookie and the machine-to-machine X-Service-Key are two independent trust boundaries with no shared code path — a clinician's cookie does not substitute for the service key, and vice versa (tested).

A signed PDF, plus notes that can be added at any point. At signoff, the server renders the report's frozen content into a PDF (fpdf2) and stores the bytes in Postgres (reports.pdf_bytes), downloadable at GET /api/reports/{id}/pdf. A clinician can attach a note (POST /api/reports/{id}/addenda) before or after signing; every note is labeled with whether it predates or postdates signing (AddendumOut.preSignoff, computed by comparing the note's timestamp against the report's signed_at — no extra column needed, since both timestamps already come from the same server clock), and every note shows up in the PDF. What's actually immutable is content and version: a note never mutates either of those. pdf_bytes is the one field that does get regenerated when a note is added after signing, deliberately, from the frozen content plus the complete current notes list — so the exported document always reflects every note so far, and "immutable" and "notes keep coming in" coexist without contradiction. This mirrors how real clinical documentation handles amendments: you don't edit the note, you append to the record.

Pagination. GET /api/patients?page=&pageSize= (default 20, capped at 100), backed by a real LIMIT/OFFSET query with a COUNT(*) for the total. The roster ships a Previous/Next pager.

Domain model — one session and one report per patient. Each patient has exactly one session, and each session has exactly one report (app/models.py). A production system would have a session history per patient; that's a real simplification, stated up front, made so the roster/report relationship stays simple enough to reason about within this exercise's scope. Each patient's roster row does carry both its own patient id and its session id, and the session has a status — in_progress, finished, or suspended — pushed to the owning clinician's stream as SSE event type "phase" via POST /api/sessions/{id}/phase, matching the endpoint contract above exactly. A suspended session can optionally carry a short reason (e.g. "connectivity issues"), which shows up on the report view rather than the roster row, and is cleared automatically the moment the session moves to any other status.

Concurrency: Postgres row locks, not an in-process lock. signoff_report and edit_report (app/repository.py) open with SELECT ... FOR UPDATE: concurrent requests against the same report serialize at the database. Ten concurrent signoff requests against the same report produce exactly one real transition and nine no-ops (tested) — the row lock, not client-side debouncing, is what actually guarantees that.

SSE: a hand-rolled client on fetch + ReadableStream, not EventSource. This gives explicit control over reconnect behavior: exponential backoff with jitter, a hard stop on a non-retryable 401 (session expired — retrying with the same bad credentials forever helps no one), and a connection status the UI renders. The server sends a heartbeat comment every 15 seconds to defeat idle proxy timeouts, and keeps a bounded per-clinician replay buffer keyed by Last-Event-ID (app/events.py), so a drop of a few seconds doesn't lose a roster update.

Tailwind for the UI. A small, deliberately restrained visual language: neutral surfaces, one accent color used sparingly (primary actions, a left accent border on the selected roster row), full dark-mode support via prefers-color-scheme. Chosen to get a consistent, finished look without spending the build budget on hand-rolled CSS infrastructure instead of the app itself.

Non-negotiables — how each is satisfied

  • A clinician must never read another clinician's patient. repository.list_patients_page / get_report_owned(_locked) filter by clinician_id at the query layer — every read and write goes through this module, so ownership can't be checked in one handler and forgotten in the next. Cross-tenant report access returns 404, not 403 — "not yours" and "doesn't exist" are the same response, so a clinician probing report IDs can't tell them apart (tests/test_authorization.py). Identity comes from a verified session cookie, never a client-asserted value.
  • Sign-off is server-authoritative and safe under retry. Idempotent by construction: signing off is a fact about a report ("who signed it, when"), not a repeatable action with distinguishable side effects, so a retry just re-observes the already-signed state (wasNoOp: true, no duplicate event) instead of erroring or producing a second signature. Combined with the SELECT ... FOR UPDATE row lock for concurrent requests. tests/test_signoff_idempotency.py fires ten concurrent signoffs and asserts exactly one transition and exactly one SSE event.
  • A signed report is immutable. PATCH /api/reports/{id} returns 409 once status == "signed", including in a signoff/edit race (tests/test_report_immutability.py). content and version never change after signing; notes can still be added, but they're a strictly separate, append-only record that never touches either field.
  • Validate at the boundary, both sides. Backend: every request and response body is a Pydantic model. Frontend: every fetch response and every SSE payload is parsed through a zod schema (api/schemas.ts) — there is no as Patient anywhere in this codebase; a shape mismatch becomes a visible, typed error, the same as a 5xx would.
  • Every failure can reach the UI. Backend: a global exception handler turns any uncaught exception into a generic 500 with no stack trace or request content in the response body or the log line. Frontend: every .catch either renders through the shared ErrorBanner or is the thing a test asserts on — there's no silently swallowed rejection.
  • Never log PHI. app/logging_utils.safe_log takes an explicit allowlist of field names and raises if a call site tries to log patient_id and session_id together, or report content at all — structural, not just a convention someone has to remember at each new call site.
  • The SSE connection will drop. Handle it. Heartbeats, exponential backoff with jitter, a hard stop on a terminal 401, and a bounded Last-Event-ID replay buffer so a brief drop doesn't lose a roster update — see "SSE" under Decisions above.

Tests

Backend — 53 pytest tests, run against a real Postgres (not SQLite), covering: clinician isolation, login (including the username-enumeration-resistant error and timing), pagination (including empty and capped-page-size edge cases), signoff idempotency and real concurrency, report immutability (including a signoff/edit race), the PDF artifact (present only once signed, unchanged across repeat signoffs, regenerated to include a note added afterward, reflects content at signoff time rather than later edits — verified via real PDF text extraction with pypdf, not a raw byte check), notes (append-only, available before or after signing, correctly labeled, never mutate signed content or version), the machine-to-machine phase callback's auth boundary, boundary validation, and SSE reconnect/replay.

A couple of things about how these tests are built are worth knowing if you're going to run or extend them:

  • The SSE tests run against a real uvicorn process in a separate OS process (tests/conftest.py's live_server fixture), not the usual in-process httpx.ASGITransport client. ASGITransport buffers an entire response before returning control to the caller, so it can't exercise an endpoint that streams forever — it would just hang.
  • The database engine uses NullPool (app/db.py): a fresh connection per checkout, never reused across a suspend point. asyncpg connections are bound to the event loop that created them, and a pooled connection reused across pytest-asyncio's per-test setup/teardown cycle corrupts its protocol state outright. A production deployment under sustained load would more likely front Postgres with pgbouncer than lean on an in-process pool anyway.

Frontend — 47 vitest tests: schema rejection of malformed server responses, the API client's error/validation/credentials handling, the SSE client's parsing/backoff/terminal-401 behavior, login (success and failure), pagination controls, and ReportView's immutability lock, double-click safety, save-failure surfacing, cross-session signoff handling, the notes form, and the suspension-reason banner.

Both suites run to green, and the app was also driven end-to-end in a real headless Chromium — not just unit-tested: wrong-password rejection, login, roster pagination, opening a draft report, editing, saving, adding a note before signing, signing off, the PDF link appearing, adding a note after signing and confirming both notes appear (correctly labeled) in the downloaded PDF, a live session-status update via the machine-to-machine endpoint reflected in the roster with no refresh, logging out, and logging back in as a second clinician to confirm the roster is a completely different set of patients.

Tradeoffs

  • Single-instance SSE. The event broker (app/events.py) is in-process — a phase/report event published on one app instance never reaches a client connected to another. Fine for this deployment; the natural fix is Postgres LISTEN/NOTIFY or Redis pub/sub for fan-out.
  • No migrations tool. create_all is enough for one, currently-fixed schema; Alembic is the obvious replacement the moment the schema needs to change under real data.
  • One session and one report per patient. A real system needs session history; that's out of scope here (see "what I'd do with more time").
  • Uneven, synthetic seed data, deterministic (random.Random(42)) purely so runs and tests are reproducible — not meant to resemble a real onboarding flow.
  • The PDF is plain and unstyled — patient/session header, signer, timestamp, body text, notes. It demonstrates the immutability mechanism, not a template design exercise.
  • PDF generation cost. Rendering embeds a vendored Unicode font (backend/app/fonts/, needed because clinician-authored free text won't reliably stay inside the latin-1 range fpdf2's core fonts cover), which adds roughly 90ms per call to parse. Not a concern at this app's scale; caching the parsed font across calls would be the fix if it ever needed to be faster.

What I'd do with more time

  • Postgres LISTEN/NOTIFY (or Redis) so the SSE broker fans out across instances instead of being process-local.
  • Alembic migrations once the schema needs to change more than once.
  • Session history per patient, with the roster showing the most recent session and a way to browse earlier ones.
  • Rate limiting on /api/auth/login and on the machine-to-machine callback.
  • An audit trail for sign-offs, edits, and notes (who, when, from where) beyond the version counter and the notes list themselves.
  • A nicer PDF template, and a way to regenerate older exports if the template ever changes, without touching already-signed bytes.

What I intentionally cut

  • No password reset / account management flows — three fixed dev accounts covers what this exercise needs.
  • No CSRF token beyond SameSite=Lax + an explicit CORS origin — adequate for this deployment shape (frontend and backend are same-site, just different ports), called out rather than silently assumed.
  • No CI config — out of scope for a take-home run locally.
  • No cursor-based pagination — offset/limit is simpler and entirely sufficient at this data scale.

About

take home

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages