# Supabase Admin Dashboard — Design Spec

## Overview

Add a new internal-only app alongside `apps/main`, implemented as `apps/admin`, to operate the production Supabase database through a polished operations dashboard. The app is not customer-facing. Its primary purpose is operational data inspection and repair, with analytics and charting as supporting capabilities for investigation and monitoring.

The product shape is:

- an internal operations console for browsing and editing approved production data
- a guarded action center for high-impact business workflows
- a semi-flexible analytics studio for charting curated datasets and saving dashboards

This should feel closer to a premium internal instrument than a generic admin template.

## Goals

- Give internal operators a fast way to inspect, filter, and modify approved production rows
- Support business-safe admin actions that should not be performed as ad hoc table edits
- Provide chart-based analytics over curated datasets for investigation and monitoring
- Keep the app visually strong, dense, and pleasant to operate for power users
- Make production access intentionally hard to misuse through layered security and auditability

## Non-Goals

- Building a full Tableau, Metabase, or Power BI replacement in v1
- Exposing this app to regular product users or customer organization admins
- Allowing arbitrary SQL execution from the browser in v1
- Making every database table directly editable
- Reusing `apps/main` navigation and UX constraints for internal operations work

## Recommended App Shape

Create a dedicated app at `apps/admin` rather than extending `apps/main`.

Reasons:

- Internal operations workflows have different navigation, information density, and safety needs than the main product
- The app should remain isolated from customer-facing code paths and feature assumptions
- A separate app can share the existing monorepo stack without inheriting the product shell

## Technical Foundation

The app should reuse the current workspace patterns:

- React 19
- Vite
- React Router
- TanStack React Query
- Tailwind
- `@xtablo/ui`
- shared Supabase and type packages where appropriate

Specialized libraries are acceptable where they materially improve operator workflows:

- `ag-grid-react` or the existing AG Grid dependency for dense table exploration
- a charting library suited for composable dashboards and interactive filters
- lightweight schema/form helpers for registry-driven edit UIs

This keeps the app consistent with the repo while allowing purpose-built admin and analytics ergonomics.

Unlike `apps/main`, this app should not rely on normal browser-side Supabase access as its primary trust boundary. Privileged access should be enforced through backend-verified admin sessions and server-mediated data operations.

## Internal-Only Access Model

This app must be firewalled and internal only.

Access should be enforced in layers:

### Layer 1: Network / edge boundary

The app should be hosted behind an internal boundary rather than a public route. The preferred model is a private hostname or protected subdomain with an edge access control layer such as:

- Cloudflare Access
- VPN-only reachability
- IP allowlist for office/VPN egress

At least one network-level gate should exist before the app is reachable.

### Layer 2: Special admin access token

Reaching the app is not sufficient. Operators must also present a dedicated admin access token that is separate from normal product authentication.

Properties of this token:

- not the regular Supabase session token used by `apps/main`
- issued only to approved internal operators
- short-lived
- bound to operator identity and role claims
- verified server-side before the app shell can load protected data

Recommended model:

1. Operator reaches the private app endpoint
2. Operator enters or redeems a privileged access token
3. Backend verifies the token and exchanges it for a short-lived admin session
4. The app stores only the short-lived admin session artifacts needed for operation

The token exchange endpoint should be the only way to unlock privileged access. Public frontend credentials alone must never be enough to talk to admin-capable data paths.

Normal product users must not be able to access this app by logging in with standard app credentials alone.

### Layer 3: In-app roles

After the privileged token gate, the app should still tier capabilities:

- `viewer`: inspect data and dashboards
- `operator`: edit approved rows and use standard tools
- `superadmin`: use destructive or high-impact actions

### Layer 4: Action-specific friction

High-risk workflows should require stronger confirmation than read or low-risk edit paths:

- confirmation modals with exact record identity
- diff previews before sensitive changes
- explicit typing for destructive actions where appropriate
- bulk-action result summaries
- audit logging for every consequential mutation

## Product Modules

The app should have four top-level modules.

### 1. Operations Home

The landing screen is a command deck for operators, not a blank dashboard shell.

It should surface:

- key health cards
- recent operational anomalies
- recent signups and organizations
- billing or subscription exceptions
- pinned saved views
- quick links into frequent tables and admin actions

This page should optimize for “what needs attention now?” rather than for abstract BI storytelling.

### 2. Data Explorer

This is the primary workspace for day-to-day operations. It should behave like a polished spreadsheet-database hybrid.

Capabilities:

- table group navigation
- dense data grid with filtering, sorting, resizing, pinning, and saved views
- column selection and per-table presets
- row selection and bulk action support
- row detail drawer with linked records, history, and edit tools
- schema-aware editing for enums, booleans, dates, JSON, nullable fields, and foreign keys

Not every table should appear. Only approved tables defined in a registry should be exposed.

### 3. Analytics Studio

This is a semi-flexible analytics layer, not an open query workbench.

Capabilities:

- choose a curated dataset or view
- apply filters and date ranges
- pick dimensions, metrics, and grouping
- render charts and summary tables
- save charts into reusable dashboards

Supported visual shapes in v1 should be the practical set:

- KPI cards
- bar charts
- line charts
- stacked comparisons
- pie or donut only where the dataset justifies it
- tabular breakdowns

The focus is fast investigative charting over approved datasets, not raw BI authoring.

### 4. Action Center

This module isolates high-impact business operations from routine browsing.

Examples:

- repair a broken organization membership
- merge duplicate records
- trigger a re-sync or backfill
- re-run a workflow cleanup
- repair broken references after a partial failure

Each action should have:

- a typed input form
- explicit eligibility checks
- confirmation copy describing impact
- structured result output
- audit-log emission

## Data Access Architecture

Use three backend access layers with different trust levels.

All privileged data access should be mediated by backend-verified admin sessions. The app should not expose broad direct production table access purely through a public browser Supabase client.

### Read layer

Prefer curated Postgres views or RPC-backed read models for dashboards and analytics. This yields:

- stable schemas for charts
- human-readable labels
- better performance characteristics
- fewer accidental joins in the frontend

Direct table reads should still be modeled as approved explorer resources, but they should preferably flow through admin APIs or narrowly scoped RPC wrappers that enforce the privileged token and table registry. Analytics should primarily be dataset-driven.

### Edit layer

Use structured mutations for simple edits on approved tables and safe fields. These edits should be governed by a table registry that declares:

- table visibility
- editable columns
- field widgets
- validation rules
- read-only or computed fields
- related-record links

Sensitive tables or writes with cross-table invariants should not mutate directly from the browser. They should route through API endpoints or database functions with explicit validation, and even low-risk edits should pass through an admin-aware boundary instead of depending on the main product's client auth model.

### Action layer

High-impact admin workflows should live behind narrow APIs or RPCs with:

- validation
- authorization
- idempotency where needed
- audit logging
- structured success and failure payloads

This layer is how the app avoids solving every problem as a raw row edit.

## Registry-Driven Configuration

The app should be intentionally configured rather than schema-introspective by default.

Introduce three registries:

### Table registry

Defines:

- which tables are exposed
- labels and groupings
- visible columns
- editable columns
- per-column rendering rules
- row detail sections
- allowed bulk actions

### Dataset registry

Defines:

- which analytics datasets exist
- metrics and dimensions available
- supported filters
- supported chart types
- default aggregations
- dashboard-friendly naming

### Action registry

Defines:

- which admin actions exist
- required permissions
- input schemas
- confirmation copy
- expected result payloads

This registry approach is what makes the app feel curated and safe rather than like a generic database browser.

## Production Safety Model

This app operates on production from day one, so the interface should continuously communicate context without becoming noisy.

Recommended safety affordances:

- persistent production environment indicator
- visible operator identity in the shell
- visible “last modified by” and “last modified at” metadata in row details where possible
- change history in row drawers for tracked entities
- limited inline edits to low-risk fields
- full-form edits with diff preview for sensitive records
- destructive actions kept out of casual explorer flows

Bulk operations should never resolve to a single toast. Operators need a result screen that distinguishes:

- succeeded rows
- failed rows
- skipped rows
- next actions

## Visual Design Direction

The visual system should avoid generic white-label admin aesthetics.

Recommended direction:

- deep ink or navy structure colors
- warm neutrals for surfaces
- one disciplined accent family for actions and focus states
- crisp, expressive typography with clear density hierarchy
- subtle layered backgrounds and panel contrast rather than flat gray cards
- charts with strong contrast and restrained but deliberate color semantics

The overall tone should be “serious internal operations instrument”:

- information-dense
- elegant
- calm under pressure
- visually credible for long sessions

## Error Handling

Errors should be explicit and categorized so operators know whether to retry, escalate, or correct input.

Primary categories:

- validation errors
- concurrency conflicts
- permission failures
- system or connectivity failures

Patterns:

- field-level validation on forms
- diff conflict messaging when a row changed concurrently
- structured action results instead of generic error banners
- partial failure summaries for bulk operations

## Testing Strategy

Testing should mirror the architecture.

### Unit tests

- table, dataset, and action registries
- column renderers and formatter helpers
- chart config builders
- edit reducers and validation logic

### Component tests

- explorer grid behaviors
- row detail drawers
- edit forms
- action forms
- dashboard widgets

### Integration tests

- internal token gate
- role restrictions
- safe edit flows
- audit-log emission
- failure handling for partial bulk actions

### API or RPC tests

- every high-impact admin action
- guarded write paths
- authorization boundaries for privileged tokens

## Delivery Phases

### Phase 1: App shell and access control

- create `apps/admin`
- implement internal-only deployment boundary
- add privileged token gate
- establish app shell, navigation, and visual system

### Phase 2: Data Explorer foundation

- implement table registry
- ship explorer for a small set of core tables
- add row detail drawers and safe field editing

### Phase 3: Audit and guarded writes

- add audit logging
- add diff previews and sensitive edit flows
- add bulk action result handling

### Phase 4: Operations Home

- add curated operational cards
- add pinned saved views and shortcuts

### Phase 5: Analytics Studio

- implement dataset registry
- add chart builder for curated datasets
- add saved dashboards

### Phase 6: Action Center

- implement first high-value admin workflows
- add structured action results and stronger confirmation patterns

## Initial Implementation Recommendation

For v1, start with a deliberately small surface:

- 3 to 5 core tables in the explorer
- 2 to 3 dashboards
- 2 to 4 high-value admin actions

This keeps the first release useful without pretending the system is fully modeled from day one.

## Open Design Decisions For Planning

These should be resolved during implementation planning:

- exact privileged token issuance flow and storage model
- whether the edge boundary is Cloudflare Access, VPN-only reachability, or a hybrid
- initial list of exposed tables
- first analytics datasets to support
- first custom admin actions to build
- audit log storage location and retention model
