feat: admin invite codes with plan assignment + user detail page

- Migration 030: add email, assigned_plan, trial_duration_days, email_sent_at
  to invite_codes with CHECK constraints
- Resend email integration (graceful degradation when API key not set)
- Invite codes now support plan assignment (free/pro/team) and trial duration (1-90 days)
- Registration applies invite code plan/trial to new subscription
- Auto-downgrade expired trials on authenticated access
- Enriched GET /admin/users/{id} with account, subscription, sessions, audit logs
- New endpoints: PUT /admin/users/{id}/subscription/plan and extend-trial
- Frontend: enhanced invite codes page with email, plan, trial fields
- Frontend: new user detail page at /admin/users/:userId
- Fixed API path drift: /invite-codes -> /invites
- 11 new backend tests, 416 total passing

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
Michael Chihlas
2026-02-11 21:42:58 -05:00
parent a466400c5b
commit 50cb0fc7f0
24 changed files with 2522 additions and 1121 deletions

View File

@@ -2,7 +2,7 @@
> **Purpose:** Quick-reference file showing exactly where the project stands.
> **For Claude Code:** Read this first to understand what's done and what's next.
> **Last Updated:** February 2, 2026
> **Last Updated:** February 11, 2026
---
@@ -10,334 +10,135 @@
---
## What's Complete
## What's Complete
### Backend (100%)
- FastAPI project structure
- PostgreSQL database with Docker
- User authentication (JWT, register, login, refresh)
- ✅ Trees CRUD with full-text search
- ✅ Sessions tracking with decisions
- ✅ Export API (Markdown, Text, HTML)
- ✅ Role-based access control foundation
- ✅ Production-ready logging with correlation IDs
- ✅ 40+ integration tests
- ✅ DateTime timezone handling fixed
- FastAPI project structure with 25+ API endpoints
- PostgreSQL database with Docker, 29+ Alembic migrations
- User authentication (JWT, register, login, refresh, logout, invite codes)
- Refresh token rotation with JTI-based revocation
- Trees CRUD with full-text search (FTS index)
- Sessions tracking with decisions, outcomes, and variables
- Export API (Markdown, Text, HTML)
- Role-based access control (super_admin, team_admin, engineer, viewer)
- Production-ready logging with correlation IDs
- 100+ integration tests
- Rate limiting on auth endpoints (disabled in DEBUG)
- Audit log table with JSONB details
- Soft delete for trees with cascade cleanup
### Frontend (Phase 2 Complete)
- React 19 + Vite + TypeScript + Tailwind setup
- Authentication UI (login, register)
- Tree library/browsing page with grid/list/table views
- Tree navigation interface (session player)
- Session management with history and detail pages
- Export functionality (download)
- **Tree Editor** — Form-based with visual preview, Zustand + immer + zundo (undo/redo)
- **Markdown rendering** in session player and node editor
- **Monochrome Design System** — Dark-only, glass-morphism cards, Inter font, theme toggle removed
- **Tree Organization** — Categories, tags (autocomplete), user folders (3-level hierarchy), filters
- **RBAC & Permissions** — `usePermissions` hook, ProtectedRoute with role guards, permission-based UI hiding
- **Session Scratchpad** — Floating overlay (Ctrl+/), auto-save, markdown preview
- **Admin Panel** — 8 pages (dashboard, users, invite codes, audit logs, plan limits, feature flags, settings, categories)
- **Session Quick Wins** (Issues #51-#55):
- Session timer (`useSessionTimer` hook, MM:SS / HH:MM:SS)
- Keyboard hints (Tab focuses notes)
- Repeat Last Session (prefills metadata from localStorage)
- Session auto-recovery (resume incomplete sessions)
- Copy step to clipboard
- Delete tree button in all view modes
- **Session Outcomes** — Outcome modal on session completion, step timing tracking
- **Settings page** at `/settings` — Default export format preference
- ✅ React + Vite + TypeScript + Tailwind setup
- ✅ Authentication UI (login, register)
- ✅ Basic layout and navigation
- ✅ Tree library/browsing page
- ✅ Tree navigation interface
- ✅ Session management
- ✅ Export functionality (download)
- ✅ Responsive design
- ✅ Error boundaries
- **Tree Editor** - Form-based with visual preview
- ✅ Zustand store with immer (undo/redo via zundo)
- ✅ Split-view layout (editor left, preview right)
- ✅ Node CRUD (Decision, Action, Solution types)
- ✅ NodePicker with type-grouped dropdown
- ✅ Dynamic array fields (options, commands, steps)
- ✅ Visual tree preview with solution indicators
- ✅ Shared node detection (multiple sources → same target)
- ✅ Modal with scrollable content, fixed header/footer
- ✅ Markdown preview toggle in description fields
- **Markdown Rendering** - Session player and node editor
- `react-markdown` package installed
- `MarkdownContent` component created
- ✅ Renders bold, italic, lists, code blocks, headers
-**User Preferences** - Settings page complete
- ✅ Dark/light/system theme toggle
- ✅ Default export format preference
- ✅ Persisted in localStorage
- ✅ Settings page at `/settings`
-**Tree Organization**
- ✅ Categories (global + team-specific)
- ✅ Tags with autocomplete
- ✅ User folders with subfolder hierarchy (max 3 levels)
- ✅ Right-click context menu for folder operations
- ✅ Filter trees by category, tags, and folders
-**RBAC & Permissions**
- ✅ Role hierarchy: super_admin > team_admin > engineer > viewer
- ✅ Permission checks in frontend (`usePermissions` hook)
- ✅ Protected routes with role guards
- ✅ Permission-based UI hiding (edit/delete/create actions)
-**Session Scratchpad**
- ✅ Floating overlay panel (Ctrl+/ to toggle)
- ✅ Auto-save with debounce
- ✅ Markdown preview
- ✅ Included in session exports
-**Mobile Responsiveness**
- ✅ Touch-friendly buttons and controls
- ✅ Optimized layouts for small screens
- ✅ Responsive navigation and forms
-**Design Consistency & Polish**
- ✅ Micro-interactions and transitions
- ✅ Global thin scrollbar styling
- ✅ Consistent brand colors and fonts
- ✅ Professional UI/UX polish
### Security Hardening (Phases A-D Complete)
- Registration role hardcoded to `engineer`
- HTML export XSS fix (html.escape)
- Secret key validator (rejects default when DEBUG=False)
- Role CHECK constraint on users table
- Tree access check on session start
- Centralized permissions in `permissions.py`
- `is_active` field on User model, enforced in auth
- Admin user management endpoints (6 endpoints)
- Refresh token rotation with JTI-based revocation
- Password complexity validation (uppercase, lowercase, digit, min 10 chars)
- Soft delete cascade cleanup (folder/tag junctions)
- SQL wildcard escaping in tag search
### Backend Schema Features (Not Yet in Frontend)
- **Tree Forking** (migration 022) — `parent_tree_id`, `root_tree_id`, `fork_depth`, `fork_reason`
- **Session Sharing** (migration 023) — `session_shares`, `session_share_views`, `allow_public_shares`
- **Tree Sharing** (migration 024) — tree share links
- **Tree Status** (migration 025) — status field on trees
- **Admin Panel Tables** (migration 026) — plan limits, feature flags
- **Session Variables** (migration 028) — variable tracking in sessions
- **Session Outcomes** (migration 029) — outcome tracking
### Documentation
- ✅ Project overview and architecture docs
- ✅ Development roadmap through Phase 4
- Feature specifications (including Phase 2.5)
- ✅ CLAUDE.md for Claude Code context
- ✅ LESSONS-LEARNED.md for avoiding past mistakes
- ✅ REBRAND-IMPLEMENTATION-GUIDE.md
- ✅ Permissions audit design doc
- ✅ Comprehensive project review report
- ✅ Subscription tier architecture plan
- CLAUDE.md (project context for Claude Code)
- LESSONS-LEARNED.md (bugs and fixes reference)
- Design system guide, component examples
- Feature specifications through Phase 4
- Rebrand implementation guide
---
## What's In Progress 🔄
## What's In Progress
| Task | Status | Notes |
|------|--------|-------|
| Step Library Frontend | In Progress | Backend complete, frontend UI pending |
| Custom Step Flow | In Progress | Integration with tree navigation |
| Tree Forking | Planning | Backend schema complete, UI pending |
| TypeScript strict mode | Warnings exist | tsconfig needs `strict: true` |
| Deployment | **Production** | Deployed on Railway at resolutionflow.com |
| Tree Forking UI | Planning | Backend schema complete (migration 022) |
| Session Sharing UI | Planning | Backend schema complete (migration 023) |
---
## What's Next (Priority Order)
### Immediate (Phase 2.5 Completion)
1. Step Library Frontend UI (browse, search, rate/review)
2. Custom Step Integration in tree navigation
3. Tree Forking UI and workflow
4. Session/Tree Sharing UI
1.~~Complete User Preferences~~ **COMPLETE** - Settings page with theme and export format
2.~~Tree Organization~~ **COMPLETE** - Categories, tags, folders with hierarchy
3.~~RBAC & Permissions~~ **COMPLETE** - Full permission system with role guards
4.~~Session Scratchpad~~ **COMPLETE** - Floating overlay with auto-save
5.~~Mobile Responsiveness~~ **COMPLETE** - Touch-friendly, responsive layouts
6. Step Library Frontend UI (browse, search, rate/review)
7. Custom Step Integration in tree navigation
8. Tree Forking UI and workflow
### Soon (Phase 3 Planning)
### Soon (Phase 3)
- File attachments for sessions
- Offline capability
- Client context system
- Advanced analytics dashboard
### Later (Phase 4)
- PSA integrations (ConnectWise, Kaseya)
- PowerShell automation framework
- Enterprise features (SSO, white-label)
---
## Key Files Reference
### Backend
```
backend/
├── app/
│ ├── main.py # FastAPI entry point
│ ├── api/v1/endpoints/ # API route handlers
│ │ ├── auth.py
│ │ ├── trees.py
│ │ └── sessions.py
│ ├── models/ # SQLAlchemy models
│ ├── schemas/ # Pydantic schemas
│ └── core/
│ ├── config.py # Settings
│ ├── security.py # JWT handling
│ └── logging_config.py
├── alembic/ # Database migrations
├── tests/ # pytest tests
└── requirements.txt
```
### Frontend
```
frontend/
├── src/
│ ├── main.tsx # Entry point
│ ├── App.tsx # Router setup
│ ├── pages/ # Page components
│ │ └── TreeEditorPage.tsx
│ ├── components/
│ │ ├── common/ # Modal, etc.
│ │ ├── tree-editor/ # Tree Editor components
│ │ │ ├── TreeEditorLayout.tsx
│ │ │ ├── TreeMetadataForm.tsx
│ │ │ ├── NodeList.tsx
│ │ │ ├── NodeEditorModal.tsx
│ │ │ ├── NodeFormDecision.tsx
│ │ │ ├── NodeFormAction.tsx
│ │ │ ├── NodeFormResolution.tsx
│ │ │ ├── DynamicArrayField.tsx
│ │ │ └── NodePicker.tsx
│ │ └── tree-preview/ # Visual preview
│ │ ├── TreePreviewPanel.tsx
│ │ └── TreePreviewNode.tsx
│ ├── store/
│ │ ├── authStore.ts
│ │ └── treeEditorStore.ts # Zustand + immer + zundo
│ ├── contexts/ # React contexts (auth)
│ ├── hooks/ # Custom hooks
│ └── api/ # API client
├── tailwind.config.js
└── tsconfig.json
```
### Documentation
```
patherly/
├── CLAUDE-SETUP.md # Full context for Claude Code
├── CURRENT-STATE.md # This file - quick status
├── LESSONS-LEARNED.md # Bugs and fixes reference
├── 01-PROJECT-OVERVIEW.md
├── 02-TECHNICAL-ARCHITECTURE.md
├── 03-DEVELOPMENT-ROADMAP.md
├── 04-FEATURE-SPECIFICATIONS.md
└── PHASE-2.5-PERSONAL-BRANCHING.md # Detailed Phase 2.5 spec
```
---
## Environment Quick Reference
### Start Development
```powershell
# Terminal 1: Database
docker start patherly_postgres
# Terminal 2: Backend
cd C:\Dev\Projects\patherly\backend
.\venv\Scripts\activate
uvicorn app.main:app --reload
# Terminal 3: Frontend
cd C:\Dev\Projects\patherly\frontend
npm run dev
cd backend && .\venv\Scripts\activate && uvicorn app.main:app --reload
cd frontend && npm run dev
```
### URLs
- Frontend: http://localhost:5173
- Backend API: http://localhost:8000
- API Docs: http://localhost:8000/docs
- API Docs: http://localhost:8000/api/docs
### Run Tests
```powershell
cd C:\Dev\Projects\patherly\backend
.\venv\Scripts\activate
pytest
cd backend && pytest --override-ini="addopts="
```
---
## Recent Changes (Feb 5-6, 2026)
1. **Mobile Responsiveness & Design Polish** (commit `90ff250`):
- Touch-friendly buttons and controls throughout the app
- Responsive layouts optimized for small screens
- Micro-interactions and smooth transitions
- Global thin scrollbar styling (6px, theme-aware)
- Consistent brand colors and professional UI polish
2. **Security Hardening** (Phases A-D complete):
- Registration role field removed (hardcoded to engineer)
- HTML export XSS fixes (all content escaped)
- Secret key validation (rejects default in production)
- Tree access checks on session start
- Refresh token rotation with JTI-based revocation
- Rate limiting on auth endpoints
- Password complexity validation
- Soft delete cascade cleanup
- SQL wildcard escaping in tag search
3. **Permissions & RBAC** (commits `34daa26`, `71ba0b9`, `3e0fb92`):
- Complete role hierarchy (super_admin > team_admin > engineer > viewer)
- Frontend `usePermissions` hook for permission checks
- Protected routes with role-based guards
- Permission-based UI hiding (edit/delete/create actions)
- Audit log table with JSONB details
- Soft delete for trees with `deleted_at` timestamp
- Super admin bypass in tree list filter
4. **Session Scratchpad** (commit `2733a00`):
- Refactored to floating overlay panel (420px wide, 55vh tall)
- Ctrl+/ keyboard shortcut to toggle
- Auto-save with 1s debounce
- Markdown preview support
- Included in session exports (markdown, text, HTML)
5. **Step Library Foundation** (Issues #5, #6, #7):
- Step categories table with 10 seeded categories
- Full step library schema (steps, ratings, usage log)
- Complete CRUD API at `/api/v1/steps`
- Full-text search and popular tags endpoints
- Rating/review system with verified use tracking
## Previous Changes (Jan 29, 2026)
1. **Comprehensive Seed Script** (`backend/scripts/seed_trees.py`):
- 7 complete troubleshooting decision trees with 10-20+ nodes each
- **Tier 1 (Help Desk)**: Password Reset, Outlook/Email, VPN Connection, Printer Problems
- **Tier 2 (Desktop Support)**: Slow Computer, Network Connectivity
- **Tier 3 (Systems)**: File Share Access Problems
- Real PowerShell commands in action nodes
- Professional ticket documentation in solution nodes
2. **Markdown Rendering** in Session Player and Node Editor:
- Installed `react-markdown` package
- Created `MarkdownContent` component (`frontend/src/components/ui/MarkdownContent.tsx`)
- Updated `TreeNavigationPage.tsx` to render descriptions with markdown
- Added markdown preview toggle in `NodeFormAction.tsx` and `NodeFormResolution.tsx`
- Supports: bold, italic, lists, code blocks, headers, blockquotes
3. Updated LESSONS-LEARNED.md with:
- httpx installation requirement for seed scripts
- Email validation rejecting `.local` TLD (RFC 6761)
## Previous Changes (Jan 28, 2026)
1. Fixed DateTime timezone bugs in all models
2. Added production logging system
3. Created 40+ integration tests
4. Added Phase 2.5 specifications (Personal Branching, Step Library)
5. Added User Preferences to MVP scope
6. Created LESSONS-LEARNED.md
7. Created CURRENT-STATE.md (this file)
8. **Tree Editor Implementation**:
- Zustand store with immer middleware and zundo for undo/redo
- Form-based node editing with type-specific forms
- NodePicker dropdown grouped by node type (Decision/Action/Solution)
- Visual tree preview with recursive rendering
- Solution connection indicators (green checkmark badges)
- Shared node detection showing when multiple nodes link to same target
- Modal component with scrollable body, fixed header/footer
---
## Blockers / Known Issues
| Issue | Workaround | Status |
|-------|------------|--------|
| pytest-asyncio version conflict | Use 0.24.0 | Documented |
| No local psql on Windows | Use `docker exec` | Documented |
---
## Session Handoff Notes
*Update this section at the end of each coding session:*
**Last Session (Feb 5-6, 2026):**
- Updated CURRENT-STATE.md to reflect Phase 2.5 progress
- All Phase 2 items complete (Tree Editor, RBAC, Permissions, UI polish)
- Step Library backend complete (schema, API, search, ratings)
- Mobile responsiveness and design consistency complete
- Security hardening (Phases A-D) complete
- Next: Step Library frontend UI, custom step flow integration, tree forking UI
**Previous Session (Feb 2-5, 2026):**
- Mobile responsiveness improvements (touch-friendly, responsive layouts)
- Security hardening phases A-D (permissions, token rotation, validation)
- RBAC system with audit logs and soft delete
- Session scratchpad refactored to floating overlay
- Global thin scrollbar styling
- Documentation updates (project review, subscription tiers)