Admin Page work - Still blank/broken

This commit is contained in:
Eric Gullickson
2025-11-06 16:29:11 -06:00
parent 858cf31d38
commit 5630979adf
38 changed files with 7373 additions and 924 deletions

View File

@@ -1,45 +0,0 @@
# Admin Role & UI Implementation Plan
Context: extend MotoVaultPro with an administrative user model, cross-tenant CRUD authority, and surfaced controls within the existing settings experience. Follow phases in order; each phase is shippable and assumes Docker-based validation per `CLAUDE.md`.
## Phase 1 Access Control Foundations
- Create `backend/src/features/admin/` capsule scaffolding (api/, domain/, data/, migrations/, tests/).
- Add migration `001_create_admin_users.sql` for table `admin_users (auth0_sub PK, email, created_at, created_by, revoked_at)`.
- Seed first record (`admin@motorvaultpro.com`, `created_by = system`) via migration or bootstrap script.
- Extend auth plugin flow to hydrate `request.userContext` containing `userId`, `email`, `isAdmin`, `adminRecord`.
- Add reusable guard `authorizeAdmin` in `backend/src/core/middleware/admin-guard.ts`; return 403 with `{ error: 'Forbidden', message: 'Admin access required' }`.
- Unit tests: guard behavior, context resolver, seed idempotency.
## Phase 2 Admin Management APIs
- Implement `/api/admin/admins` controller with list/add/revoke/reinstate endpoints; enforce “at least one active admin” rule in repository.
- Add audit logging via existing `logger` (log `actorAdminId`, `targetAdminId`, `action`, `context`).
- Provide read-only `/api/admin/users` for user summaries (reusing existing repositories, no data mutation yet).
- Integration tests validating: guard rejects non-admins, add admin, revoke admin while preventing last admin removal.
## Phase 3 Platform Catalog CRUD
- Add service `vehicleCatalog.service.ts` under admin feature to manage `vehicles.make|model|model_year|trim|engine|trim_engine`.
- Expose `/api/admin/catalog/...` endpoints for hierarchical CRUD; wrap mutations in transactions with referential validation.
- On write, call new cache helper in `backend/src/features/platform/domain/platform-cache.service.ts` to invalidate keys `platform:*`.
- Record admin change history in table `platform_change_log` (migration `002_create_platform_change_log.sql`).
- Tests: unit (service + cache invalidation), integration (create/update/delete + redis key flush assertions).
## Phase 4 Station Oversight
- Implement `/api/admin/stations` for global station CRUD and `/api/admin/users/:userId/stations` to manage saved stations.
- Ensure mutations update `stations` and `saved_stations` tables with soft delete semantics and invalidation of `stations:saved:{userId}` plus cached search keys.
- Provide optional `force=true` query to hard delete (document usage, default soft delete).
- Tests covering cache busting, permission enforcement, and happy-path CRUD.
## Phase 5 UI Integration (Settings-Based)
- Create hook `frontend/src/core/auth/useAdminAccess.ts` that calls `/auth/verify`, caches `isAdmin`, handles loading/error states.
- Desktop: update `frontend/src/pages/SettingsPage.tsx` to inject an “Admin Console” card when `isAdmin` true (links to admin subroutes) and display access CTA otherwise.
- Mobile: add admin section to `frontend/src/features/settings/mobile/MobileSettingsScreen.tsx` using existing `GlassCard` pattern; hide entirely for non-admins.
- Route stubs (e.g. `/garage/settings/admin/*`) should lazy-load forthcoming admin dashboards; guard them with `useAdminAccess`.
- Frontend tests (Jest/RTL) verifying conditional rendering on admin vs non-admin contexts.
## Phase 6 Quality Gates & Documentation
- Run backend/ frontend lint + tests inside containers (`make rebuild`, `make logs`, `make test-backend`, `docker compose exec mvp-frontend npm test`).
- Author `docs/ADMIN.md` summarizing role management workflow, API catalog, cache rules, and operational safeguards.
- Update existing docs (`docs/PLATFORM-SERVICES.md`, `docs/VEHICLES-API.md`, `docs/GAS-STATIONS.md`, `docs/README.md`) with admin references.
- Prepare release checklist: database migration order, seed verification for initial admin, smoke tests on both device classes (mobile + desktop), rollback notes.
- Confirm Traefik `/auth/verify` headers expose admin flag where needed for downstream services.

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,134 @@
# Admin Settings Frontend Implementation Plan
## Audience & Scope
- **Intended executor**: AI agent implementing MotoVaultPro admin settings UI across desktop and mobile.
- **Scope**: Frontend-only tasks within `frontend/`, coordinating with existing backend admin APIs. Includes real-time audit log integration and bulk operations across admin users, catalog entities, and station management.
## Current State Summary
- Routes exist (`frontend/src/pages/admin/*.tsx`, `frontend/src/features/admin/mobile/*.tsx`) but contain placeholder copy.
- Hooks and API clients (`frontend/src/features/admin/hooks/*`, `frontend/src/features/admin/api/admin.api.ts`) already wrap CRUD endpoints but lack bulk helpers and streaming.
- Settings pages link into admin routes; `useAdminAccess` gate is wired.
- No shared admin layout, tables, or selection utilities; no real-time audit consumption; no bulk UI.
## Key Requirements
1. **Real-time audit logging** for admin operations (desktop + mobile).
2. **Bulk operations**: multi-select + batch mutate/delete/revoke across admin users, catalog hierarchy, stations.
3. **Desktop / Mobile parity** while respecting CLAUDE.md mobile + desktop mandate and existing design system.
Assumptions:
- Backend will expose streaming endpoint (`/api/admin/audit-logs/stream`) using SSE. (If absent, coordinate for addition.)
- Backend will provide/extend batch mutation endpoints or accept arrays in current ones.
- No additional design assets; follow existing Material UI / GlassCard patterns.
## Implementation Phases
### Phase 0 Prep & Validation
- Confirm backend endpoints:
- `GET /api/admin/audit-logs/stream` (SSE) payload schema.
- Batch endpoints for admins (`POST /admin/admins/bulk`, `PATCH /admin/admins/bulk-revoke`, etc.), catalog (`/admin/catalog/{entity}/bulk-delete`), stations (`/admin/stations/bulk-delete`).
- Response format + error contracts.
- Document agreements in `docs/ADMIN.md` and update API client typings before UI work.
### Phase 1 Shared Infrastructure
- Add shared admin components under `frontend/src/features/admin/components/`:
- `AdminSectionHeader`
- `AdminDataGrid` (wrapper around MUI DataGrid or Table) with checkbox selection and toolbar slot.
- `SelectionToolbar` + `BulkActionDialog`.
- `AuditLogPanel` (desktop) and `AuditLogDrawer` (mobile).
- `EmptyState`, `ErrorState`, `Skeleton` variants.
- Utility hooks/services:
- `useBulkSelection` (manages item selection, select all, reset).
- `useAuditLogStream` (SSE handling, merge into cache, pause/resume).
- `useAdminRealtimeEffect` (common real-time logic for both platforms).
- Error normalization helper for API responses.
- Update `admin.api.ts` to include bulk endpoints and streaming subscription helper.
- Ensure types in `admin.types.ts` cover new request/response payloads.
### Phase 2 Admin Users Experience
- **Desktop (`AdminUsersPage.tsx`)**:
- Replace placeholder with layout:
- Header (stats summary cards).
- `AdminDataGrid` listing admins (columns: email, role, status, created/updated, last activity).
- Toolbar actions: Invite, Revoke, Reinstate, Delete (single + bulk), export CSV placeholder.
- Inline filters/search.
- Audit log side panel fed by `useAuditLogStream`.
- Modals/forms:
- Invite admin (react-hook-form + Zod validation).
- Confirm dialogs for revoke/reinstate/delete (bulk friendly).
- State management:
- Use React Query hooks (`useAdmins`, new `useBulkRevokeAdmins`, etc.).
- Optimistic updates where safe; fallback to refetch on failure.
- Surface backend constraints (last admin protection) in toasts/dialogs.
- **Mobile (`AdminUsersMobileScreen.tsx`)**:
- Card-based list with segmented controls.
- Multi-select mode triggered by long-press or “Select” button; sticky bottom action bar for bulk operations.
- Slide-in drawer for audit log stream; allow collapse to preserve screen space.
- Ensure loading/error/empty states match mobile pattern.
### Phase 3 Vehicle Catalog Management
- Extend API hooks for per-entity bulk operations (`useDeleteMakesBulk`, etc.) and streaming updates.
- **Desktop (`AdminCatalogPage.tsx`)**:
- Two-column layout: left panel shows hierarchical tree (Makes → Models → Years → Trims → Engines). Right panel shows detail grid for selected level.
- Support multi-select in each grid with bulk delete; confirm cascading impacts (warn when deleting parents).
- Modals for create/edit per entity using shared form component (with validation & parent context).
- Audit log panel filtered to catalog-related actions.
- Show breadcrumbs + context metadata (created/updated timestamps).
- **Mobile (`AdminCatalogMobileScreen.tsx`)**:
- Drill-down navigation (list of makes → models → ...).
- Selection mode toggles for bulk delete at current depth; use bottom sheet to display actions.
- Provide “Recent Changes” sheet consuming audit stream (filtered).
- Handle cache invalidation across hierarchies (e.g., deleting a make invalidates models/years/trims queries). Consider using queryClient `invalidateQueries` with partial keys.
### Phase 4 Station Oversight
- Hook updates: add `useBulkDeleteStations`, `useBulkRestoreStations` if available, with optional `force` flag.
- **Desktop (`AdminStationsPage.tsx`)**:
- Data grid with columns (name, address, status, last modified, createdBy). Add search bar and filter chips (active, soft-deleted).
- Bulk selection with delete (soft/hard toggle), restore, export stub.
- Station detail drawer with metadata and quick actions.
- Audit log panel focusing on station events; highlight critical operations via toast (e.g., hard deletes).
- **Mobile (`AdminStationsMobileScreen.tsx`)**:
- Card list with quick actions (edit, delete, restore). Multi-select mode with sticky action bar.
- Provide filter tabs (All / Active / Deleted).
- Integrate audit log bottom sheet.
### Phase 5 Integration & Routing Enhancements
- Introduce route wrapper/components (e.g., `AdminUsersRoute`) that detect viewport using `useMediaQuery` and render desktop or mobile variant; ensures shared logic and prevents duplicate routing code.
- Update navigation flows, ensuring mobile bottom navigation can reach admin sections gracefully.
- Document keyboard shortcuts or focus management for accessibility (bulk selection, audit log toggles).
### Phase 6 Testing & QA
- Add unit tests for new hooks (`useAuditLogStream`, bulk hooks) using Jest + Testing Library. Mock EventSource for streaming tests.
- Component tests:
- Desktop grids: selection toggles, bulk action dialogs, form validation.
- Mobile screens: selection mode toggling, action bar behaviors.
- Audit log panels: streaming update rendering, pause/resume controls.
- Visual regression smoke tests if tooling available; otherwise document manual screenshot checkpoints.
- Manual QA matrix:
- Desktop ≥1280px and mobile ≤480px.
- Test flows: invite admin, revoke/reinstate, bulk revoke, catalog cascading delete, station soft/hard delete, audit log live updates.
## Deliverables Checklist
- [ ] Updated API client + types for batch + streaming.
- [ ] Shared admin UI components & utilities.
- [ ] Desktop admin pages fully functional with bulk + real-time features.
- [ ] Mobile admin screens matching functionality.
- [ ] Comprehensive tests covering new flows.
- [ ] Documentation updates (API usage, manual QA steps).
## Risks & Mitigations
- **Streaming availability**: If backend stream not ready, fall back to polling with progressive enhancement; keep SSE integration behind feature flag.
- **Bulk API inconsistencies**: Align payload format with backend; add defensive UI (disable actions until backend confirms support).
- **State synchronization**: Ensure query invalidation covers dependent entities; consider structured query keys and `queryClient.setQueryData` for incremental updates.
- **Mobile UX complexity**: Prototype selection mode early to validate ergonomics; leverage bottom sheets to avoid cramped toolbars.
## Follow-up Questions (Resolved)
1. Real-time audit logs required — implement SSE-based stream handling.
2. Bulk operations mandatory — support multi-select + batch actions across admin users, catalog entities, stations.
3. No additional design constraints — rely on existing Material UI and GlassCard paradigms.
## Handoff Notes
- Keep code comments concise per developer guidelines; avoid introducing new design systems.
- Validate hooks for Auth0 dependency (ensure disabled when unauthenticated).
- Coordinate with backend team if API gaps found; document interim shims.
- Maintain responsiveness and accessibility; ensure touch targets ≥44px and keyboard operability on desktop grids.