From dae687292bf8cd4afeb114a8210493292814482d Mon Sep 17 00:00:00 2001 From: "gpt-engineer-app[bot]" <159125892+gpt-engineer-app[bot]@users.noreply.github.com> Date: Sun, 2 Nov 2025 19:09:45 +0000 Subject: [PATCH] Add documentation for hooks --- docs/DATABASE_DIRECT_EDIT.md | 1524 ++++++++++++++++++++++++++++++++++ 1 file changed, 1524 insertions(+) create mode 100644 docs/DATABASE_DIRECT_EDIT.md diff --git a/docs/DATABASE_DIRECT_EDIT.md b/docs/DATABASE_DIRECT_EDIT.md new file mode 100644 index 00000000..18331336 --- /dev/null +++ b/docs/DATABASE_DIRECT_EDIT.md @@ -0,0 +1,1524 @@ +# Database Direct Edit System + +## Overview +A full-featured database management interface for administrators (admin/superuser roles only) that allows direct CRUD operations on all database tables with advanced spreadsheet-like functionality, comprehensive filtering, sorting, and inline editing capabilities. + +**Status**: 📋 Planned (Not Yet Implemented) + +**Target Users**: Administrators and Superusers only + +**Security Level**: Requires AAL2 (MFA verification) + +--- + +## Table of Contents +1. [Architecture & Security](#architecture--security) +2. [Core Components](#core-components) +3. [Feature Specifications](#feature-specifications) +4. [Database Requirements](#database-requirements) +5. [Implementation Roadmap](#implementation-roadmap) +6. [Dependencies](#dependencies) +7. [Safety & UX Guidelines](#safety--ux-guidelines) + +--- + +## Architecture & Security + +### Access Control +- **Role Restriction**: Only `admin` and `superuser` roles can access +- **AAL2 Enforcement**: All database operations require MFA verification via `useSuperuserGuard()` +- **Audit Logging**: Every modification logged to `admin_audit_log` +- **Warning Banner**: Display risk disclaimer about direct database access +- **Read-Only Mode**: Toggle to prevent accidental edits + +### Route Structure +``` +/admin/database # Main database browser (table list) +/admin/database/:tableName # Spreadsheet editor for specific table +``` + +### Navigation +- Add "Database Editor" link to AdminSidebar +- Icon: `Database` from lucide-react +- Position: Below "User Management" +- Visibility: Superuser only (`isSuperuser()`) + +--- + +## Core Components + +### File Structure +``` +src/ +├── pages/admin/ +│ └── AdminDatabase.tsx # Main page with routing +│ +├── components/admin/database/ +│ ├── index.ts # Barrel exports +│ ├── DatabaseTableBrowser.tsx # Table selector & overview +│ ├── DatabaseTableEditor.tsx # Main spreadsheet editor (TanStack Table) +│ ├── DatabaseTableFilters.tsx # Advanced filtering UI +│ ├── DatabaseColumnConfig.tsx # Column visibility/order management +│ ├── DatabaseRowEditor.tsx # Detailed row editor dialog +│ ├── DatabaseBulkActions.tsx # Bulk edit/delete operations +│ ├── DatabaseExportImport.tsx # CSV/JSON export/import +│ ├── DatabaseSchemaViewer.tsx # Table schema & ERD viewer +│ ├── DatabaseCellEditors.tsx # Type-specific cell editors +│ └── types.ts # TypeScript definitions +│ +├── hooks/ +│ ├── useTableSchema.ts # Fetch table schema from Supabase +│ ├── useTableData.ts # Fetch/edit table data with optimistic updates +│ ├── useDatabaseAudit.ts # Audit logging utilities +│ └── useDatabaseValidation.ts # Validation functions +│ +└── lib/ + ├── database/ + │ ├── cellEditors.tsx # Cell editor component factory + │ ├── filterFunctions.ts # Custom filter functions per data type + │ ├── validationRules.ts # Validation rules per column type + │ └── schemaParser.ts # Parse Supabase schema to table config + └── utils/ + ├── csvExport.ts # CSV export utilities + └── jsonImport.ts # JSON import/validation +``` + +--- + +## Feature Specifications + +### Phase 1: Table Browser & Navigation + +#### DatabaseTableBrowser Component +**Purpose**: Display all database tables with metadata and quick navigation + +**Features**: +- **Table List Display**: + - Grid or list view toggle + - Show table name, row count, size, last modified + - Search/filter tables by name + - Sort by name, row count, or date + +- **Table Categorization**: +```typescript +const tableCategories = { + auth: { + color: 'red', + tables: ['profiles', 'user_roles', 'user_preferences', 'user_sessions'], + icon: 'Shield' + }, + content: { + color: 'yellow', + tables: ['parks', 'rides', 'companies', 'ride_models', 'locations'], + icon: 'MapPin' + }, + submissions: { + color: 'green', + tables: ['content_submissions', 'submission_items', 'photo_submissions'], + icon: 'FileText' + }, + moderation: { + color: 'blue', + tables: ['reports', 'admin_audit_log', 'review_reports'], + icon: 'Flag' + }, + versioning: { + color: 'purple', + tables: ['park_versions', 'ride_versions', 'company_versions'], + icon: 'History' + }, + system: { + color: 'gray', + tables: ['admin_settings', 'notification_logs', 'rate_limits'], + icon: 'Settings' + } +} +``` + +- **Quick Stats Cards**: + - Total tables count + - Total rows across all tables + - Database size + - Last modified timestamp + +- **Table Actions**: + - Click table to open editor + - Quick view schema (hover tooltip) + - Export table data + - View recent changes (from versions tables) + +**Data Fetching**: +```typescript +// Use Supabase RPC to get table metadata +const { data: tables } = await supabase.rpc('get_table_metadata') + +interface TableMetadata { + table_name: string; + row_count: bigint; + total_size: string; + last_modified: string; + category?: string; +} +``` + +--- + +### Phase 2: Spreadsheet-Style Table Editor + +#### DatabaseTableEditor Component +**Core Technology**: TanStack Table v8 with advanced features + +#### 2.1 Data Grid Display + +**Features**: +- **Virtual Scrolling**: Handle 10,000+ rows efficiently using `@tanstack/react-virtual` +- **Sticky Headers**: Column headers remain visible on scroll +- **Row Numbers**: Display row index in first column +- **Column Resizing**: Drag column borders to resize +- **Column Reordering**: Drag-drop column headers to reorder +- **Row Selection**: + - Single click to select row + - Shift+Click for range selection + - Ctrl+Click for multi-selection + - Checkbox column for bulk selection +- **Zebra Striping**: Alternate row colors for readability +- **Cell Highlighting**: Hover effect on cells +- **Responsive Design**: Horizontal scroll on smaller screens + +**Implementation**: +```tsx +const table = useReactTable({ + data: tableData, + columns: dynamicColumns, + getCoreRowModel: getCoreRowModel(), + getFilteredRowModel: getFilteredRowModel(), + getSortedRowModel: getSortedRowModel(), + getPaginationRowModel: getPaginationRowModel(), + enableRowSelection: true, + enableMultiSort: true, + enableColumnResizing: true, + columnResizeMode: 'onChange', + state: { + sorting, + columnFilters, + columnVisibility, + rowSelection, + pagination + } +}) +``` + +#### 2.2 Inline Editing + +**Cell Editor Types** (auto-detected from column type): + +| Data Type | Editor Component | Features | +|-----------|------------------|----------| +| `text`, `varchar` | `` | Text input with validation | +| `integer`, `bigint`, `numeric` | `` | Number input with min/max | +| `boolean` | `` | Toggle switch | +| `timestamp`, `date` | `` | Calendar popup with time | +| `uuid` | `` | FK lookup or manual entry | +| `jsonb`, `json` | `