Skip to content

RestartiX -- Implementation Plan

Master plan for building the RestartiX platform from documented architecture to working product.

Current state: Phase 1 (Foundation) is done. Phase 2 (Auth & Multi-Tenancy) is code-complete, currently validating before moving on. Next up: Phase 3 (Core Domain Models).


Naming Convention

Consistent terminology used throughout this document, codebase, and all internal communication.

Brand Layer

TermMeaning
RestartiXThe company and brand. Never refers to a specific app or service.
(clinic's brand)What patients see in white-label deployments.

Product Layer (internal docs & communication)

TermMeaningExample
PlatformThe entire system (backend + frontends + infra)"The platform supports multi-tenancy"
Clinic AppThe staff-facing frontend application"The clinic app shows specialist calendars"
Patient PortalThe patient-facing frontend application"The patient portal handles consent forms"
ConsoleThe superadmin platform management application"The console lets platform operators onboard new clinics"

Technical Layer (code, repos, architecture)

TermMeaningLocation
Core APIThe main Go backend servicecmd/api/
Telemetry APIThe analytics/audit Go servicecmd/telemetry/
ClinicStaff frontend appapps/clinic/
PortalPatient frontend appapps/portal/
ConsoleSuperadmin frontend appapps/console/
UIShared component librarypackages/ui/

Usage rules

  • "RestartiX" = brand/company only
  • "Platform" = the whole product
  • "Core API" = the main backend (not "the API")
  • "Clinic app" / "Patient portal" / "Console" = the three frontends
  • In code: core-api, telemetry-api, clinic, portal, console, ui

Phase 1 -- Foundation

Project scaffolding, infrastructure, core libraries, and app shells. Everything boots, nothing does real work yet.

1.1 Go Backend Setup

  • [x] Initialize Go module (go mod init) with the project layout from project-layout
  • [x] Create directory structure: cmd/api/, internal/, migrations/
  • [x] Set up Makefile with all commands documented in local-development
  • [x] Create docker-compose.yml (PostgreSQL 17, Redis 7)
  • [x] Create .env.example with all documented variables
  • [x] Set up air hot-reload config (.air.toml)
  • Skipped: cmd/telemetry/ -- Telemetry API is out of scope until Phase 9
  • Skipped: ClickHouse + TimescaleDB in docker-compose -- only needed for Telemetry API

1.2 Core Libraries

  • [x] HTTP server setup with chi router
  • [x] Structured logging (log/slog -- stdlib)
  • [x] Configuration loader (env vars to struct via envconfig)
  • [x] Two PostgreSQL connection pools (pgxpool): AdminPool (owner, bypasses RLS) + AppPool (restricted, RLS enforced)
  • [x] Redis client setup
  • [x] Graceful shutdown handler
  • [x] Health check endpoint (GET /health for Core API)
  • [x] HTTP utilities: JSON response helpers, AppError type with status code mapping
  • [x] Middleware: RequestID, Recovery (panic to 500), structured Logging

1.3 Database Foundation

  • [x] Migration tooling setup (golang-migrate via Makefile targets)
  • [x] Initial migration: extensions (uuid-ossp, pgcrypto)
  • [x] RLS helper functions: current_app_user_id, current_app_org_id, current_app_role
  • [x] Restricted database role (restartix_app) with ALTER DEFAULT PRIVILEGES
  • [x] Base audit_log table (append-only, with indexes and RLS policies)
  • Skipped: ClickHouse base tables -- only needed for Telemetry API (Phase 9)

1.4 CI/CD Basics

  • [x] golangci-lint configuration (.golangci.yml)
  • [x] Dockerfile (multi-stage build for Core API: deploy/Dockerfile.api)
  • [ ] GitHub Actions workflow: lint, test, build, Docker image, push to ECR -- deferred until meaningful tests and a deployment target
  • [ ] Pre-commit hooks (lint, format, vet) -- deferred, low priority for solo/small team

1.5 Frontend App Scaffolds

  • [x] Clinic app -- Next.js 16 at apps/clinic/ (port 9100, domain clinic.localhost:9100)
  • [x] Patient Portal -- Next.js 16 at apps/portal/ (port 9200, domain portal.localhost:9200)
  • [x] Console app -- Next.js 16 at apps/console/ (port 9300, domain console.localhost:9300)
  • [x] Shared UI component library (packages/ui/ with shadcn/ui)
  • [x] Shared API client package (@workspace/api-client)
  • [x] Shared ESLint and TypeScript configs

1.6 Domain-Based Org Routing

  • [x] proxy.ts extracts slug from hostname ({slug}.clinic.restartix.app to slug)
  • [x] Proxy calls GET /v1/public/organizations/resolve?slug={slug} to resolve org
  • [x] Resolved org set as httpOnly cookies (org-id, org-slug, org-name)
  • [x] organization_domains table + migration (custom domain support with DNS TXT verification)
  • [x] RLS policies on organization_domains
  • [x] Domain management API: GET/POST /v1/organizations/{id}/domains, DELETE, POST .../verify
  • [x] Resolve by custom domain: GET /v1/public/organizations/resolve?domain={domain}
  • [x] Redis caching for slug and domain resolution (5-min TTL)
  • [x] Cache invalidation on org update, domain add/remove/verify
  • [x] Both Clinic app and Patient Portal support slug-based and custom domain resolution

Status: Done


Phase 2 -- Auth & Multi-Tenancy

The security backbone. Clerk auth, organizations, users, roles, RLS, and frontend auth wiring across all 3 apps. Everything needed so that authenticated, org-scoped requests work end-to-end.

2.1 Clerk Integration (Backend)

  • [x] Clerk SDK integration (Go) -- clerk-sdk-go/v2 v2.5.1
  • [x] JWT verification middleware (ClerkAuth in middleware/auth.go)
  • [x] Create-on-first-login provisioning in auth middleware (Clerk Backend API fetches user details, no webhooks needed)
  • [x] Session claims extraction to UserContext in auth/context.go

2.2 Organizations (Multi-Tenancy)

  • [x] organizations table + migration (with RLS policies, includes language_code)
  • [x] user_organizations table (user to org M:M mapping)
  • [x] Organization CRUD API (POST /v1/organizations superadmin-only, GET/PATCH admin+)
  • [x] Slug-based org lookup
  • [x] Public resolve endpoint (GET /v1/public/organizations/resolve?slug=) with Redis caching (5-min TTL)
  • [x] Org switching (PUT /v1/me/switch-organization) -- legacy fallback, primary switching is domain-based
  • Deferred: API key management for orgs -- Phase 3+

2.3 Users & Roles

  • [x] users table + migration (synced from Clerk)
  • [x] RBAC middleware (RequireRole in middleware/rbac.go) -- roles: patient, specialist, admin, customer_support, superadmin
  • [x] Permission checking per endpoint -- RequireRole(superadmin) on org create, RequireRole(admin) on org-scoped mutations
  • [x] Superadmin bypasses all RequireRole checks and can operate without org context
  • Deferred: Admin impersonation capability -- Phase 3+

2.4 Row-Level Security

  • [x] RLS policies on organizations, user_organizations, users tables
  • [x] Two-pool architecture: superadmins routed to AdminPool (owner, bypasses RLS), all other users routed to AppPool (restricted, RLS enforced)
  • [x] OrganizationContext middleware -- routes to correct pool by role, acquires connection, sets app.current_user_id, app.current_org_id, app.current_role session vars
  • [x] Public endpoints use AppPool without session vars -- public-access RLS policies (current_app_role() IS NULL) allow SELECT on verified data
  • [x] RLS policy template established for all future tables
  • [ ] RLS integration tests -- deferred, will verify manually first

2.5 Frontend Auth (All 3 Apps)

  • [x] Install @clerk/nextjs in Clinic app, Patient Portal, and Console
  • [x] ClerkProvider wrapper in root layouts (conditional -- builds without keys)
  • [x] Next.js proxy.ts for route protection (public vs authenticated routes)
  • [x] Sign-in and sign-up pages (Clerk's prebuilt components)
  • [x] Shared API client with Clerk token injection (auth().getToken())
  • [x] TypeScript types for Core API responses
  • [x] Error handling patterns (401 to redirect to sign-in, ApiError class)
  • [x] API client reads org-id cookie and sends X-Organization-ID header

2.6 Clinic App

  • [x] Protected layout (redirect unauthenticated users to sign-in)
  • [x] Dashboard placeholder page
  • [x] User menu component (name, email, sign-out)
  • [x] Organization switcher -- redirects to {slug}.{CLINIC_DOMAIN} (domain-based switching)
  • [x] Role-based UI visibility (admin-only links hidden for non-admins)

2.7 Patient Portal

  • [x] Sign-in / sign-up pages
  • [x] Protected patient layout
  • [x] Patient dashboard placeholder page
  • [x] User profile display component (PatientHeader)

2.8 Console App

  • [x] Superadmin-only access (role check, access denied page for non-superadmins)
  • [x] API client created without organizationId (superadmin operates with orgID=0)
  • [x] Sidebar navigation: Dashboard, Organizations, Users, Settings
  • [x] Dashboard placeholder page

2.9 E2E Validation

  • [ ] First login, user auto-provisioned in Core API database
  • [ ] Sign in, Clerk token, GET /v1/me returns correct user + org context
  • [ ] Org switching from Clinic app, subsequent API calls return scoped data
  • [ ] Superadmin endpoint (POST /v1/organizations), 403 for non-superadmin roles
  • [ ] Blocked user with valid Clerk token, 403 from Core API

Status: Code complete -- validating (E2E blocked on Clerk keys)


Phase 3 -- Core Domain Models

The data layer for the primary entities that appointments, forms, and scheduling depend on.

3.1 Specialties

  • [ ] specialties table + RLS policies + migration
  • [ ] CRUD API (/v1/specialties)
  • [ ] Specialist assignment to specialties

3.2 Specialists

  • [ ] specialists table + RLS policies + migration
  • [ ] CRUD API (/v1/specialists)
  • [ ] Weekly availability schedule (per-day time slots)
  • [ ] Date overrides (single-day schedule changes)
  • [ ] Timezone management
  • [ ] Specialty assignments (many-to-many)

3.3 Patients

  • [ ] patients table + RLS policies + migration
  • [ ] patient_org_profiles table (per-clinic profile sharing)
  • [ ] CRUD API (/v1/patients)
  • [ ] Patient onboarding flow (Clerk account creation)
  • [ ] Profile sharing consent management
  • [ ] Guest patient registration (no account, contact details only)

3.4 Services Catalog

  • [ ] services table + RLS policies + migration
  • [ ] Three billing models: session-based, time-based, hybrid
  • [ ] Product bundling support
  • [ ] CRUD API (/v1/services)
  • [ ] products table for physical products (elastic bands, etc.)

Exit criteria: All core entities have working CRUD APIs, RLS policies, and pass integration tests.


Phase 4 -- Scheduling & Appointments

The most complex feature. Implements the full booking flow from the needs-on-day-1 spec.

4.1 Calendars

  • [ ] calendars table + RLS policies + migration
  • [ ] Calendar types: campaign, promotional, rolling horizon, open
  • [ ] Period-based calendars (fixed start/end dates)
  • [ ] Rolling horizon calendars (e.g., next 30 days)
  • [ ] Per-specialist hour overrides within calendars
  • [ ] Service + price overrides per calendar
  • [ ] CRUD API (/v1/calendars)

4.2 Availability Engine

  • [ ] Compute available slots from specialist weekly hours + date overrides + calendar overrides
  • [ ] Conflict detection (no double-booking)
  • [ ] Round-robin specialist assignment
  • [ ] Priority-based specialist assignment
  • [ ] Slot duration calculation from service settings

4.3 Slot Hold System (Redis)

  • [ ] Redis-backed temporary hold on selected slot
  • [ ] Hold TTL (configurable, e.g., 10 minutes)
  • [ ] Hold release on timeout or cancellation
  • [ ] SSE streaming for real-time availability updates
  • [ ] Concurrent hold prevention (same slot)

4.4 Appointments

  • [ ] appointments table + RLS policies + migration
  • [ ] State machine: booked > upcoming > confirmed > inprogress > done / cancelled / noshow
  • [ ] Two-phase booking: guest booking (no account) then staff onboarding (account creation)
  • [ ] Appointment-level form aggregation (from service + calendar)
  • [ ] Post-appointment rating system (star rating + alert on low rating)
  • [ ] CRUD API (/v1/appointments)

4.5 Video Calls (Daily.co)

  • [ ] Daily.co API integration
  • [ ] Auto-create video room when appointment starts
  • [ ] Auto-delete room when appointment ends
  • [ ] Room URL generation for patient + specialist
  • [ ] Video call status tracking

4.6 Public Booking API

  • [ ] GET /v1/public/availability -- available slots for a service/specialist/calendar
  • [ ] POST /v1/public/bookings -- guest booking (no auth required)
  • [ ] Guest contact form submission
  • [ ] Slot hold during form fill
  • [ ] Staff confirmation flow (CS calls patient then confirms then creates account + appointment)

Exit criteria: Full booking flow works end-to-end per needs-on-day-1: calendars A/B/C/D work, slot holds work, guest booking to CS confirmation to appointment creation works.


Phase 5 -- Forms & Custom Fields

Dynamic form system that powers consents, questionnaires, reports, and prescriptions.

5.1 Custom Fields

  • [ ] custom_fields table + RLS policies + migration
  • [ ] Field types: text, select, date, number, checkbox, signature, file
  • [ ] Field versioning (auto-propagation on change)
  • [ ] System fields vs. org fields
  • [ ] CRUD API (/v1/custom-fields)

5.2 Form Templates

  • [ ] form_templates table + RLS policies + migration
  • [ ] Template types: survey, disclaimer, parameters, analysis, advice, report, prescription
  • [ ] Form builder API (template + field arrangement)
  • [ ] Predefined org templates (auto-created for new orgs)
  • [ ] CRUD API (/v1/form-templates)

5.3 Form Instances

  • [ ] form_instances table + RLS policies + migration
  • [ ] Form filling + submission API
  • [ ] Auto-fill from patient profile
  • [ ] Legally immutable after signing (no edits)
  • [ ] Consent tracking (who, when, IP, policy version)
  • [ ] Private fields (specialist-only visibility)
  • [ ] File upload support within forms
  • [ ] Global org consents check (Terms, GDPR, other org-configured)
  • [ ] Appointment-specific form requirements
  • [ ] Form aggregation from service + calendar
  • [ ] Consent flow blocking (must complete before proceeding)
  • [ ] Digital signature capture for physical clinics

Exit criteria: Full consent to form to appointment flow works. Predefined forms auto-created for new orgs. Forms are legally immutable after signing.


Phase 6 -- Documents & PDF Generation

Reports, prescriptions, and clinical documents.

6.1 PDF Templates

  • [ ] pdf_templates table + RLS policies + migration
  • [ ] Block-based template structure (JSONB)
  • [ ] Go template syntax for dynamic fields
  • [ ] Component library: letterhead, footer, signature block
  • [ ] Template versioning
  • [ ] CRUD API (/v1/pdf-templates)

6.2 Document Generation

  • [ ] documents table + RLS policies + migration
  • [ ] PDF rendering pipeline (ChromeDP or wkhtmltopdf)
  • [ ] Digital signature embedding
  • [ ] Generated PDF caching
  • [ ] S3 upload for generated documents
  • [ ] Document download API

6.3 File Storage (S3)

  • [ ] S3 client setup (presigned URL generation)
  • [ ] File upload flow: client to presigned URL to S3 to confirm
  • [ ] File metadata tracking in database
  • [ ] File download via presigned URLs
  • [ ] File type validation and size limits

Exit criteria: Specialist can generate report/prescription PDFs from appointment data. Documents stored in S3 and downloadable.


Phase 7 -- Treatment Plans & Exercise Library

The telerehabilitation differentiator. This is the first phase inside the regulatory boundary. Features here have a medical intended purpose and will be subject to IEC 62304 if/when certification is pursued. See Medical Device Classification for context.

7.0 Regulatory Habits (start of Phase 7, maintain throughout)

  • [ ] Add requirement IDs to exercise library feature spec (e.g., REQ-EX-001: System shall display contraindications for each exercise)
  • [ ] Add requirement IDs to treatment plans feature spec (e.g., REQ-TP-001: System shall display prescribed exercises with correct parameters)
  • [ ] Add "Safety Implications" section to exercise library and treatment plan feature docs (one line per risk: "If this breaks, the risk is: ___")
  • [ ] Reference requirement IDs in test comments as tests are written (e.g., // Verifies REQ-TP-003: version snapshot is immutable)

7.1 Exercise Library

  • [ ] exercises table + RLS policies + migration (global + org-scoped)
  • [ ] translations JSONB column on all global content tables (see Translations)
  • [ ] Bunny Stream integration for video upload/playback
  • [ ] Exercise taxonomy: categories, body regions, equipment, difficulty
  • [ ] Contraindications and step-by-step instructions
  • [ ] Translation-aware queries for global exercises (COALESCE from JSONB using org language)
  • [ ] Clone from global to org library (bake translated text into clone)
  • [ ] CRUD API (/v1/exercises)

7.2 Treatment Plans

  • [ ] treatment_plans table + RLS policies + migration
  • [ ] Plan types: telerehab, in-clinic
  • [ ] Plan scopes: global, org, custom
  • [ ] Plan versioning (JSONB snapshots)
  • [ ] Session structure: exercises, reps, rest periods, order
  • [ ] CRUD API (/v1/treatment-plans)

7.3 Patient Enrollment & Progress

  • [ ] plan_enrollments table + migration
  • [ ] Patient assignment to plans
  • [ ] Session execution tracking (date, time, completion, video watched)
  • [ ] Post-session questionnaire (pain, difficulty, notes)
  • [ ] Adherence tracking and alerts
  • [ ] Progress API for patient interface

7.4 Session Calendar (Physical)

  • [ ] Specialist session calendar for in-clinic plans
  • [ ] Session count tracking (e.g., 10 kineto sessions remaining)
  • [ ] Session booking integrated with appointment system
  • [ ] Post-session feedback + pain questionnaire

Exit criteria: Telerehab flow works: specialist creates plan, patient assigned, patient does sessions, progress tracked. Physical session tracking works with remaining session count.


Phase 8 -- Automations & Webhooks

Event-driven workflows and external integrations.

8.1 Event System

  • [ ] Internal event bus (in-process, channel-based)
  • [ ] 20+ trigger events as documented (patient.onboarded, appointment.first_booked, plan.assigned, adherence.drops, etc.)
  • [ ] Event payload standardization

8.2 Automation Rules

  • [ ] automation_rules table + RLS policies + migration
  • [ ] Rule engine: trigger to condition to action
  • [ ] Actions: require/suggest form, send email/SMS, push notification, assign plan, add/remove from segment
  • [ ] CRUD API (/v1/automations)

8.3 Webhooks

  • [ ] webhook_subscriptions table + RLS policies + migration
  • [ ] HMAC-signed payloads (metadata + IDs, no PHI)
  • [ ] Retry with exponential backoff
  • [ ] Delivery tracking + failure logging
  • [ ] Idempotency keys
  • [ ] CRUD API (/v1/webhooks)

8.4 Segments

  • [ ] segments table + RLS policies + migration
  • [ ] Rules-based patient cohort evaluation
  • [ ] Multi-source rules: form responses + custom fields + appointment history
  • [ ] Auto-update on data changes
  • [ ] Three-tier rule evaluation
  • [ ] CRUD API (/v1/segments)

Exit criteria: Automation rules trigger on events and execute actions. Webhooks deliver signed payloads with retry. Segments auto-update.


Phase 9 -- Telemetry Service

Separate service for audit trail, analytics, and compliance logging.

9.1 Telemetry API Setup

  • [ ] cmd/telemetry/ entry point
  • [ ] TimescaleDB connection (audit, security, privacy tables)
  • [ ] ClickHouse connection (analytics, media, errors, pose tracking)
  • [ ] Health check endpoint (GET /health on port 4000)

9.2 Audit Pipeline

  • [ ] Synchronous audit write in Core API (audit_log table)
  • [ ] Async forwarding to Telemetry API (queue + retry)
  • [ ] Before/after diffs in audit entries
  • [ ] IP, user, timestamp, organization tracking
  • [ ] Append-only enforcement (no UPDATE/DELETE)
  • [ ] 6-year retention policy

9.3 Analytics Events

  • [ ] ClickHouse analytics tables migration
  • [ ] Event ingestion API (POST /v1/events)
  • [ ] Media session tracking (exercise video playback)
  • [ ] Error tracking pipeline
  • [ ] Pose tracking data storage (MediaPipe results)

9.4 Privacy & Security

  • [ ] PII encryption in telemetry (separate encryption key)
  • [ ] GDPR data export from telemetry
  • [ ] Privacy exclusion support (patient opt-out)
  • [ ] Security event logging (failed auth, suspicious activity)
  • [ ] MaxMind GeoIP enrichment (optional)

Exit criteria: Audit events flow from Core API to Telemetry API to TimescaleDB/ClickHouse. Analytics queries work. PII is encrypted.


Phase 10 -- Compliance & Security Hardening

GDPR readiness, security hardening, and IEC 62304 pre-certification groundwork. See Medical Device Classification for the full regulatory context.

10.0 IEC 62304 Preparation (Pre-Certification Groundwork)

  • [ ] Risk table for all clinical features (hazard, severity, likelihood, existing controls)
  • [ ] SOUP list: catalog go.mod and key frontend deps (name, version, purpose, known anomalies, risk assessment)
  • [ ] Reframe implementation plan as Software Development Plan (SDP)
  • [ ] Verify requirement IDs exist on all clinical feature specs
  • [ ] Verify traceability: each clinical requirement ID has at least one test that references it
  • [ ] Document the regulatory boundary in architecture docs

10.1 GDPR Implementation

  • [ ] Data subject access request (DSAR) endpoint -- export all patient data
  • [ ] Right to erasure endpoint -- anonymize patient data (retain audit trail)
  • [ ] Consent management API (granular consent tracking)
  • [ ] Data processing records
  • [ ] 72-hour breach notification procedure (documented + alerting)
  • [ ] Cookie/tracking consent

10.2 Encryption

  • [ ] AES-256-GCM encryption for sensitive fields at rest
  • [ ] Key rotation mechanism
  • [ ] Encryption key management (AWS Secrets Manager)
  • [ ] TLS enforcement on all connections

10.3 Security Hardening

  • [ ] Rate limiting middleware (Redis-based, per endpoint/user/org)
  • [ ] Rate limit response headers (X-RateLimit-*, Retry-After)
  • [ ] CORS configuration
  • [ ] Input validation and sanitization
  • [ ] SQL injection prevention (parameterized queries -- already via pgx)
  • [ ] Request ID and correlation ID tracking
  • [ ] Security headers (HSTS, CSP, X-Frame-Options)

Exit criteria: GDPR DSAR and erasure endpoints work. Encryption at rest verified. Rate limiting active. Security scan passes.


Phase 11 -- Organization Dashboard & Stats

Admin-facing analytics and management dashboards.

11.1 Dashboard Stats API

  • [ ] Pain reduction metrics (period-filtered)
  • [ ] Appointment ratings aggregate
  • [ ] Pain evolution tracking
  • [ ] Top diagnostics
  • [ ] Top services
  • [ ] Revenue evolution
  • [ ] All metrics filterable by date range

11.2 Admin Management

  • [ ] Organization settings management
  • [ ] User/specialist management views
  • [ ] Appointment overview and management
  • [ ] Form template management
  • [ ] Automation rule management

Exit criteria: Dashboard stats API returns accurate metrics for all 6 categories. Admin can manage org settings and users.


Phase 12 -- Testing & Quality (Ongoing, but dedicated focus)

Should be happening throughout, but this phase ensures complete coverage.

12.1 Unit Tests

  • [ ] 80%+ coverage target
  • [ ] Table-driven tests for all business logic
  • [ ] Mock interfaces for external services (Clerk, Daily.co, S3, Bunny)

12.2 Integration Tests

  • [ ] RLS policy tests (critical -- verify cross-org isolation)
  • [ ] API endpoint tests (request to response validation)
  • [ ] Migration tests (up + down for every migration)
  • [ ] Redis hold system tests

12.3 Clinical Feature Tests (IEC 62304 Traceability)

  • [ ] All tests for clinical features reference requirement IDs in comments
  • [ ] Contraindication logic has dedicated test coverage (REQ-EX-xxx)
  • [ ] Treatment plan versioning has dedicated test coverage (REQ-TP-xxx)
  • [ ] Patient session tracking has dedicated test coverage

12.4 End-to-End Tests

  • [ ] Patient booking flow (guest to CS confirm to account to appointment)
  • [ ] Consent to form to video call flow
  • [ ] Specialist consultation to report to prescription flow
  • [ ] Treatment plan assignment to patient sessions to progress tracking
  • [ ] GDPR DSAR + erasure flow

12.5 Performance Tests

  • [ ] k6 load test scripts
  • [ ] Availability engine stress test (concurrent bookings)
  • [ ] Concurrent user simulation
  • [ ] Database query performance baselines

Exit criteria: 80%+ unit test coverage. All RLS policies have integration tests. E2E tests pass for core flows. Load tests establish baselines. All clinical feature tests reference requirement IDs.


Phase 13 -- Frontend Integration Contract

Define exactly how the Clinic app and Patient Portal connect to the Core API.

13.1 API Client Contract

  • [ ] OpenAPI/Swagger spec generation from Go handlers
  • [ ] TypeScript type generation from OpenAPI spec
  • [ ] Error response format standardization
  • [ ] Pagination format standardization (data, meta, pagination)
  • [ ] Filtering/sorting query parameter format

13.2 Auth Integration Guide

  • [ ] Clerk frontend SDK integration guide
  • [ ] Token acquisition and refresh flow
  • [ ] Org switching from frontend
  • [ ] Session expiration handling

13.3 Real-Time Integration

  • [ ] SSE connection guide for scheduling updates
  • [ ] Event payload format documentation
  • [ ] Connection recovery patterns
  • [ ] WebSocket consideration for future features

13.4 File Upload Integration

  • [ ] S3 presigned URL flow for frontend
  • [ ] Upload progress tracking pattern
  • [ ] File validation (client-side + server-side)

Exit criteria: OpenAPI spec generated. TypeScript types generated. Clinic app and Patient Portal teams have everything needed to build the frontends.


Summary

PhaseNameStatus
1FoundationDone
2Auth & Multi-TenancyValidating
3Core Domain ModelsNext
4Scheduling & AppointmentsPlanned
5Forms & Custom FieldsPlanned
6Documents & PDF GenerationPlanned
7Treatment Plans & ExercisesPlanned
8Automations & WebhooksPlanned
9Telemetry ServicePlanned
10Compliance & Security HardeningPlanned
11Dashboard & StatsPlanned
12Testing (dedicated)Ongoing
13Frontend Integration ContractPlanned

Parallel Work Streams

Some phases can run concurrently:

Week:  1  2  3  4  5  6  7  8  9  10 11 12 13 14 15 16 17 18 19 20
       |----Phase 1----|  Done
                  |----Phase 2----|  Validating
                              |-----Phase 3-----|  <-- NEXT
                                          |--------Phase 4--------|
                                          |-----Phase 5-----|
                                                            |Phase 6|
                                                      |------Phase 7------|
                                                            |-----Phase 8-----|
                              |------Phase 9 (parallel)---------------------|
                                                                        |Phase 10|
                                                                           |Phase 11|
       |-------------------Phase 12 (ongoing)---------------------------------------|
                                                                              |Ph 13|

Quick-Start Checklist

  1. Run docker compose up -d to start local infrastructure
  2. Apply migrations with make migrate-up
  3. Start the Core API with make dev
  4. Start frontend apps with pnpm dev
  5. Phase 3 is next -- build the entities that everything references

Decision Points

These decisions should be made before or during implementation:

DecisionWhenOptions
PDF rendering engineBefore Phase 6ChromeDP, wkhtmltopdf, Gotenberg
i18n scopeBefore Phase 7See Translations & Localization for full architecture
Email/SMS providerBefore Phase 8AWS SES, SendGrid, Postmark / Twilio, AWS SNS
Payment integrationBefore Phase 11Stripe, local Romanian provider, deferred
Mobile app approachBefore Phase 13React Native, Flutter, responsive web only