diff --git a/AGENTS.md b/AGENTS.md
index e59a6aa..6167b68 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -45,9 +45,9 @@ Default superuser (change in production):
│ ├── tests/ # 96% coverage, 987 tests
│ └── alembic/ # Database migrations
│
-└── frontend/ # Next.js 15 frontend
+└── frontend/ # Next.js 16 frontend
├── src/
- │ ├── app/ # App Router pages (Next.js 15)
+ │ ├── app/ # App Router pages (Next.js 16)
│ ├── components/ # React components
│ ├── lib/
│ │ ├── api/ # Auto-generated API client
@@ -183,7 +183,7 @@ Permission dependencies in `api/dependencies/permissions.py`:
- **Makefile**: `make help` for all commands
**Frontend:**
-- **Next.js 15**: App Router with React 19
+- **Next.js 16**: App Router with React 19
- **TypeScript**: Full type safety
- **TailwindCSS + shadcn/ui**: Design system
- **ESLint + Prettier**: Code quality
diff --git a/CLAUDE.md b/CLAUDE.md
index 449330b..fa67abf 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -88,8 +88,6 @@ const { user, isAuthenticated } = useAuth();
1. `AuthContext.tsx` - DI boundary, legitimately needs real store
2. `client.ts` - Non-React context, uses dynamic import + `__TEST_AUTH_STORE__` check
-**See**: `frontend/docs/ARCHITECTURE_FIX_REPORT.md` for full details.
-
### E2E Test Best Practices
When writing or fixing Playwright tests:
@@ -229,7 +227,6 @@ No Claude Code Skills installed yet. To create one, invoke the built-in "skill-c
- [README.md](./README.md) - User-facing project overview
- `backend/docs/` - Backend architecture, coding standards, common pitfalls
- `frontend/docs/design-system/` - Complete design system guide
-- `frontend/docs/ARCHITECTURE_FIX_REPORT.md` - Critical DI pattern fixes
**API Documentation (when running):**
- Swagger UI: http://localhost:8000/docs
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 3ab3f49..4649d48 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -90,22 +90,18 @@ Ready to write some code? Awesome!
```bash
cd backend
-# Setup virtual environment
-python -m venv .venv
-source .venv/bin/activate
-
-# Install dependencies
-pip install -r requirements.txt
+# Install dependencies (uv manages virtual environment automatically)
+uv sync
# Setup environment
cp .env.example .env
# Edit .env with your settings
# Run migrations
-alembic upgrade head
+python migrate.py apply
# Run tests
-IS_TEST=True pytest
+IS_TEST=True uv run pytest
# Start dev server
uvicorn app.main:app --reload
diff --git a/FEATURE_RECOMMENDATIONS.md b/FEATURE_RECOMMENDATIONS.md
deleted file mode 100644
index 39a9960..0000000
--- a/FEATURE_RECOMMENDATIONS.md
+++ /dev/null
@@ -1,1525 +0,0 @@
-# Feature Recommendations for FastAPI + Next.js Template
-
-**Research Date:** November 6, 2025
-**Based on:** Extensive web search of modern SaaS boilerplates, developer needs, and industry trends
-
----
-
-## Executive Summary
-
-This document provides **17 killer features** that would significantly enhance the template based on research of:
-- Modern SaaS boilerplate trends
-- Developer expectations in 2025
-- Industry best practices
-- Popular commercial templates
-- Implementation complexity analysis
-
-Each feature is rated on:
-- **Popularity**: Market demand (1-5 stars)
-- **Ease of Implementation**: Technical complexity (1-5 stars)
-- **Ease of Maintenance**: Ongoing effort (1-5 stars)
-- **Versatility**: Applicability across use cases (1-5 stars)
-
----
-
-## 🌟 TIER 1: ESSENTIAL FEATURES (High Impact, High Demand)
-
-### 1. Internationalization (i18n) Multi-Language Support
-
-**Metrics:**
-- **Popularity**: ⭐⭐⭐⭐⭐ (5/5) - 77% of consumers prefer localized content
-- **Ease of Implementation**: ⭐⭐⭐⭐ (4/5) - Next.js has built-in i18n support
-- **Ease of Maintenance**: ⭐⭐⭐ (3/5) - Requires ongoing translation management
-- **Versatility**: ⭐⭐⭐⭐⭐ (5/5) - Needed by any app targeting global markets
-
-**Description:**
-Enable your application to support multiple languages and regional formats, allowing users to interact with the interface in their preferred language.
-
-**Pros:**
-- Next.js 15 has built-in i18n routing support
-- `next-intl` library specifically designed for App Router with RSC (React Server Components)
-- Expands market reach dramatically
-- SEO benefits (hreflang tags, localized URLs)
-- Increases user engagement and conversion rates
-
-**Cons:**
-- Translation management overhead
-- Testing complexity increases (need to test all languages)
-- Need to handle RTL languages (Arabic, Hebrew)
-- Initial setup for translation workflows
-
-**Key Implementation Details:**
-
-**Routing Strategies:**
-- Sub-path routing: `/blog`, `/fr/blog`, `/es/blog`
-- Domain routing: `mywebsite.com/blog`, `mywebsite.fr/blog`
-
-**Best Practices:**
-- JSON files for translation storage (locales directory)
-- Browser's Intl API for date/number formatting
-- SEO optimization with canonical URLs and hreflang tags
-- Dynamic dir="rtl" attribute for RTL languages
-- Conditional CSS for RTL layouts
-
-**Recommended Stack:**
-- **Frontend**: `next-intl` for Next.js App Router
-- **Storage**: JSON translation files per locale
-- **Backend**: Accept-Language headers, locale in user preferences model
-- **Tools**: Crowdin, Lokalise, or Phrase for translation management
-
-**Use Cases:**
-- Global SaaS targeting multiple regions
-- E-commerce with international customers
-- Content platforms with diverse audiences
-- Government/public services requiring accessibility
-
----
-
-### 2. OAuth/SSO & Social Login (Google, GitHub, Apple, Microsoft)
-
-**Metrics:**
-- **Popularity**: ⭐⭐⭐⭐⭐ (5/5) - 77% of consumers favor social login, 25% of all logins use it
-- **Ease of Implementation**: ⭐⭐⭐⭐ (4/5) - Many libraries available
-- **Ease of Maintenance**: ⭐⭐⭐⭐ (4/5) - Stable APIs, occasional provider updates
-- **Versatility**: ⭐⭐⭐⭐⭐ (5/5) - Critical for B2C, increasingly expected in B2B
-
-**Description:**
-Allow users to authenticate using their existing accounts from popular platforms like Google, GitHub, Apple, or Microsoft, reducing friction in the signup process.
-
-**Pros:**
-- Increases registration conversion by 20-40%
-- Google accounts for 75% of social logins (53% user preference)
-- Reduces password management burden for users
-- Faster user onboarding experience
-- Social login adoption can grow 190% in first 2 months post-launch
-- Reduces support tickets related to password resets
-
-**Cons:**
-- Multiple provider integrations needed (each has different OAuth flow)
-- Account linking logic required (when user has both email and social login)
-- Dependency on third-party service availability
-- Privacy concerns from some users about data sharing
-
-**Key Statistics:**
-- 77% of consumers favored social login over traditional registration methods (2011 Janrain study)
-- 70.69% of 18-25 year olds preferred social login methods (2020 report)
-- One B2C enterprise saw social login adoption grow from 10% to 29% in just two months
-
-**Recommended Stack:**
-- **Backend**:
- - FastAPI: `authlib` or `python-social-auth`
- - OAuth 2.0 / OpenID Connect standards
-- **Frontend**:
- - Next.js: `next-auth` v5 (supports App Router)
- - Social provider SDKs for one-click login buttons
-- **Providers Priority**:
- 1. Google (highest usage)
- 2. GitHub (developer audience)
- 3. Apple (required for iOS apps)
- 4. Microsoft (B2B/enterprise)
-
-**Implementation Considerations:**
-- Account linking strategy (email as primary identifier)
-- Handling users who sign up via email then try social login
-- Profile data synchronization from providers
-- Refresh token management for long-lived sessions
-- Graceful handling of provider outages
-
-**Use Cases:**
-- B2C SaaS applications (maximum convenience)
-- Developer tools (GitHub auth)
-- Mobile apps requiring iOS submission (Apple auth)
-- Enterprise B2B (Microsoft SSO)
-
----
-
-### 3. Enhanced Email Service with Templates
-
-**Metrics:**
-- **Popularity**: ⭐⭐⭐⭐⭐ (5/5) - Every SaaS needs transactional emails
-- **Ease of Implementation**: ⭐⭐⭐⭐ (4/5) - Template engines available
-- **Ease of Maintenance**: ⭐⭐⭐⭐ (4/5) - Templates rarely change once designed
-- **Versatility**: ⭐⭐⭐⭐⭐ (5/5) - Used across all features
-
-**Description:**
-Professional, branded email templates for all transactional emails (welcome, password reset, notifications, invoices) with proper HTML/text formatting and deliverability optimization.
-
-**Current State:**
-- You already have a placeholder email service in `backend/app/services/email_service.py`
-- Console backend for development
-- Ready for SMTP/provider integration
-
-**Pros:**
-- Order confirmation emails have highest open rates (80-90%)
-- Professional templates increase brand trust and recognition
-- Can drive upsell/cross-sell opportunities
-- Responsive design ensures readability on all devices
-- Transactional emails are expected by users (5+ minute wait is unacceptable)
-
-**Cons:**
-- Deliverability challenges (SPF, DKIM, DMARC setup required)
-- Template design time investment
-- Cost for high-volume sending (though transactional is usually cheap)
-- Testing across email clients (Outlook, Gmail, Apple Mail)
-
-**Best Practices:**
-- **Design**: Minimalist with clean layout, white space, bold fonts for key details
-- **Content**: Concise, relevant information only
-- **Subject Lines**: Clear, ~60 characters or 9 words, personalized
-- **Responsive**: 46% of people read emails on smartphones
-- **Speed**: Deliver within seconds, not minutes
-- **Personalization**: Sender name (not generic email), conversational tone, real person signature
-- **Branding**: Consistent with your app's visual identity
-
-**Recommended Enhancements:**
-- **Template Engine**: React Email or MJML for responsive HTML generation
-- **Email Provider**:
- - SendGrid (reliable, good API)
- - Postmark (transactional focus, high deliverability)
- - AWS SES (cheapest for high volume)
- - Resend (developer-friendly, modern)
-- **Pre-built Templates**:
- - Welcome email
- - Email verification
- - Password reset (already have placeholder)
- - Password changed confirmation
- - Invoice/receipt
- - Team invitation
- - Weekly digest
- - Security alerts
-- **Features**:
- - Email preview in admin panel
- - Open/click tracking (optional, privacy-conscious)
- - Template variables for personalization
- - Plain text fallback for all HTML emails
- - Unsubscribe handling (for marketing emails)
-
-**Integration Points:**
-- Registration flow → Welcome email
-- Password reset → Reset link email
-- Organization invite → Invitation email
-- Subscription changes → Confirmation email
-- Admin actions → Notification emails
-
----
-
-### 4. File Upload & Storage System (S3/Cloudinary)
-
-**Metrics:**
-- **Popularity**: ⭐⭐⭐⭐⭐ (5/5) - 80%+ of SaaS apps need file handling
-- **Ease of Implementation**: ⭐⭐⭐⭐ (4/5) - Well-documented libraries
-- **Ease of Maintenance**: ⭐⭐⭐⭐ (4/5) - Stable APIs, automatic scaling
-- **Versatility**: ⭐⭐⭐⭐⭐ (5/5) - Avatars, documents, exports, backups
-
-**Description:**
-Secure file upload, storage, and delivery system supporting images, documents, and other file types with CDN acceleration and optional image transformations.
-
-**Pros:**
-- Essential for user avatars, document uploads, data exports
-- S3 + CloudFront: low cost, high performance, global CDN
-- Cloudinary: automatic image transformations, optimization (47% faster load times)
-- Hybrid approach: Cloudinary for active/frequently accessed assets, S3 for archives
-- Scales automatically without infrastructure management
-
-**Cons:**
-- Storage costs at scale (though S3 Intelligent-Tiering helps)
-- Security considerations (pre-signed URLs for private files)
-- Virus scanning needed for user-uploaded files
-- Bandwidth costs if not using CDN properly
-
-**Storage Strategies:**
-
-**Option 1: AWS S3 + CloudFront (Recommended for most)**
-- **Use Case**: Documents, exports, backups, long-term storage
-- **Pros**: Cheapest, most flexible, industry standard
-- **Cost Optimization**:
- - S3 Intelligent-Tiering (auto-moves to cheaper tiers)
- - Lifecycle rules (archive to Glacier after 90 days)
- - CloudFront CDN reduces bandwidth costs
-
-**Option 2: Cloudinary**
-- **Use Case**: User avatars, image-heavy content requiring transformations
-- **Pros**: Built-in CDN, automatic optimization, on-the-fly transformations
-- **Cost Optimization**: Move images >30 days old to S3
-
-**Option 3: Hybrid (Best of Both)**
-- Active images: Cloudinary (fast delivery, transformations)
-- Documents/exports: S3 + CloudFront
-- Archives: S3 Glacier
-
-**Recommended Stack:**
-- **Backend**:
- - `boto3` (AWS S3 SDK for Python)
- - `cloudinary` SDK (if using Cloudinary)
- - Pre-signed URL generation for secure direct uploads
-- **Frontend**:
- - `react-dropzone` for drag-and-drop UI
- - Direct S3 upload (client generates pre-signed URL from backend, uploads directly)
-- **Security**:
- - Virus scanning: ClamAV or AWS S3 + Lambda
- - File type validation (MIME type + magic number check)
- - Size limits (configurable per plan)
-- **Features**:
- - Image optimization (WebP, compression)
- - Thumbnail generation
- - CDN delivery
- - Upload progress tracking
- - Multi-file upload support
-
-**Use Cases:**
-- User profile avatars
-- Organization logos
-- Document attachments (PDF, DOCX)
-- Data export downloads (CSV, JSON)
-- Backup storage
-- User-generated content
-
----
-
-### 5. Comprehensive Audit Logging (GDPR/SOC2 Ready)
-
-**Metrics:**
-- **Popularity**: ⭐⭐⭐⭐⭐ (5/5) - Required for enterprise/compliance
-- **Ease of Implementation**: ⭐⭐⭐ (3/5) - Needs careful design
-- **Ease of Maintenance**: ⭐⭐⭐⭐ (4/5) - Once set up, mostly automatic
-- **Versatility**: ⭐⭐⭐⭐ (4/5) - Critical for security, debugging, compliance
-
-**Description:**
-Comprehensive logging of all user and admin actions, data access, and system events for security, debugging, and compliance (GDPR, SOC2, HIPAA).
-
-**Pros:**
-- **Required** for SOC2, GDPR, HIPAA, ISO 27001 compliance
-- Security incident investigation and forensics
-- User activity tracking and accountability
-- Data access transparency for users
-- Debugging aid (trace user issues)
-- Audit trail for legal disputes
-
-**Cons:**
-- Storage costs (can be 10-50GB/month for active apps)
-- Performance impact if not asynchronous
-- Sensitive data redaction needed (passwords, tokens, PII)
-- Query performance degrades without proper indexing
-
-**Compliance Requirements:**
-
-**GDPR (General Data Protection Regulation):**
-- Log all data access and modifications
-- User right to access their audit logs
-- Retention policies (default 2 years, configurable)
-
-**SOC2 (Security, Availability, Confidentiality):**
-- Security criteria: Log authentication events, authorization failures
-- Availability: Log system changes, deployments
-- Confidentiality: Log data access, especially sensitive data
-
-**What to Log:**
-
-**User Actions:**
-- Login/logout (IP, device, location, success/failure)
-- Password changes
-- Profile updates
-- Data access (viewing sensitive records)
-- Data exports
-- Account deletion
-
-**Admin Actions:**
-- User edits (field changes with old/new values)
-- Permission/role changes
-- Organization management (create, update, delete)
-- Feature flag changes
-- System configuration changes
-
-**API Actions:**
-- Endpoint called
-- Request method (GET, POST, etc.)
-- Response status code
-- Response time
-- IP address
-- User agent
-- Request payload (sanitized)
-
-**Data Changes:**
-- Table/model affected
-- Record ID
-- Old value → New value
-- Actor (who made the change)
-- Timestamp
-
-**Recommended Implementation:**
-
-**Database Schema:**
-```python
-class AuditLog(Base):
- id: UUID
- timestamp: datetime
- actor_type: Enum # user, admin, system, api
- actor_id: UUID # user ID or API key ID
- action: str # login, user.update, organization.create
- resource_type: str # user, organization, session
- resource_id: UUID
- changes: JSONB # {field: {old: X, new: Y}}
- metadata: JSONB # IP, user_agent, location
- severity: Enum # info, warning, critical
-```
-
-**Storage Strategy:**
-- **Hot Storage**: PostgreSQL (last 90 days) - fast queries for recent activity
-- **Cold Storage**: S3/Glacier (archive after 90 days) - compliance retention
-- **Indexes**: Composite on (actor_id, timestamp), (resource_id, timestamp)
-
-**Admin UI Features:**
-- Searchable log viewer with filters (actor, action, date range, resource)
-- Export logs (CSV, JSON) for external analysis
-- Real-time security alerts (failed logins, permission escalation attempts)
-- User-facing log (show users their own activity)
-
-**Performance Optimization:**
-- Async logging (don't block requests)
-- Batch inserts (buffer 100 logs, insert together)
-- Separate read replica for log queries
-- Partitioning by month for large tables
-
-**Use Cases:**
-- Security incident response ("Who accessed this data?")
-- Debugging user issues ("What did the user do before the error?")
-- Compliance audits (SOC2 audit requires 1 year of logs)
-- User transparency (GDPR right to know who accessed their data)
-
----
-
-## 🚀 TIER 2: MODERN DIFFERENTIATORS (High Value, Growing Demand)
-
-### 6. Webhooks System (Event-Driven Architecture)
-
-**Metrics:**
-- **Popularity**: ⭐⭐⭐⭐ (4/5) - Expected in modern B2B SaaS
-- **Ease of Implementation**: ⭐⭐⭐ (3/5) - Requires queue + retry logic
-- **Ease of Maintenance**: ⭐⭐⭐ (3/5) - Monitoring endpoint health is ongoing
-- **Versatility**: ⭐⭐⭐⭐⭐ (5/5) - Enables integrations, automation, extensibility
-
-**Description:**
-Allow customers to receive real-time HTTP callbacks (webhooks) when events occur in your system, enabling integrations with external tools and custom workflows.
-
-**Pros:**
-- Allows customers to integrate with their tools (Zapier, Make.com, n8n)
-- Real-time event notifications without polling
-- Reduces polling API calls (saves server load)
-- Competitive differentiator for B2B SaaS
-- Enables ecosystem growth (third-party integrations)
-
-**Cons:**
-- Reliability challenges (customer endpoints may be down)
-- Retry logic complexity with exponential backoff
-- Endpoint verification needed (security)
-- Rate limiting per customer to prevent abuse
-- Monitoring and alerting for failed webhooks
-
-**Key Architecture Patterns:**
-
-**Publish-Subscribe (Pub/Sub) - Recommended:**
-Your application publishes events to a message broker (Redis, RabbitMQ), which delivers to subscribed webhook endpoints. Decouples event generation from delivery.
-
-**Background Worker Processor:**
-Webhook delivery handled by background queue (Celery) rather than inline processing. Prevents blocking main application threads.
-
-**Reliability & Retry Logic:**
-- Exponential backoff: 1 min, 5 min, 15 min, 1 hour, 6 hours
-- Max 5 retry attempts (configurable)
-- Truncated backoff (max 24 hours between retries)
-- Dead Letter Queue for permanently failed webhooks
-
-**Security Best Practices:**
-
-**HTTPS Only:**
-All webhook endpoints must use HTTPS
-
-**Signature Verification:**
-Use HMAC-SHA256 or JWT to sign webhook payload:
-```python
-signature = hmac.new(
- secret.encode(),
- payload.encode(),
- hashlib.sha256
-).hexdigest()
-```
-
-**Timestamp Validation:**
-Include timestamp in signature to prevent replay attacks (reject if >20 seconds old)
-
-**Endpoint Verification:**
-Send test event with challenge code that endpoint must echo back
-
-**Rate Limiting:**
-Limit to 1M events per tenant per day (throttle beyond this)
-
-**Scaling Considerations:**
-- Millions of webhooks per minute requires distributed system
-- Use Kafka or AWS Kinesis for high-throughput event streaming
-- Multiple worker processes for parallel delivery
-- Redis for fast counter tracking (rate limits)
-
-**Subscription Management:**
-
-**Static Webhooks (Simple):**
-- One URL per webhook
-- Limited to single event type
-- Manual setup via UI
-
-**Subscription Webhooks (Recommended):**
-- API-driven subscription management
-- Multiple webhooks per application
-- Granular event filtering
-- Dynamic add/remove subscriptions
-
-**Monitoring & Observability:**
-- Log all webhook events (status code, response time, delivery attempts)
-- Dashboard showing:
- - Delivery success rate per endpoint
- - Failed webhooks (last 100)
- - Average response time
-- Alerting on endpoint failures (>10 consecutive failures)
-
-**Events to Support:**
-
-**User Events:**
-- `user.created`
-- `user.updated`
-- `user.deleted`
-- `user.activated`
-- `user.deactivated`
-
-**Organization Events:**
-- `organization.created`
-- `organization.updated`
-- `organization.deleted`
-- `organization.member_added`
-- `organization.member_removed`
-
-**Session Events:**
-- `session.created`
-- `session.revoked`
-
-**Payment Events (future):**
-- `payment.succeeded`
-- `payment.failed`
-- `subscription.created`
-- `subscription.cancelled`
-
-**Recommended Stack:**
-- **Backend**: FastAPI + Celery + Redis
-- **Event Bus**: Redis Pub/Sub or PostgreSQL LISTEN/NOTIFY
-- **Storage**: `Webhook` and `WebhookDelivery` models
-- **Admin UI**: Subscription management, delivery logs, retry manually
-- **Testing**: Webhook.site or RequestBin for testing
-
-**Use Cases:**
-- Sync user data to CRM (Salesforce, HubSpot)
-- Trigger automation workflows (Zapier, n8n)
-- Send notifications to Slack/Discord
-- Custom integrations built by customers
-- Real-time data replication to data warehouse
-
----
-
-### 7. Real-Time Notifications (WebSocket + Push)
-
-**Metrics:**
-- **Popularity**: ⭐⭐⭐⭐ (4/5) - Expected in modern apps
-- **Ease of Implementation**: ⭐⭐ (2/5) - Complex for horizontal scaling
-- **Ease of Maintenance**: ⭐⭐ (2/5) - Stateful servers, scaling challenges
-- **Versatility**: ⭐⭐⭐⭐ (4/5) - Enhances UX across features
-
-**Description:**
-Real-time, bidirectional communication between server and client for instant notifications, live updates, and collaborative features without polling.
-
-**Pros:**
-- Real-time updates without polling (better UX, lower latency)
-- Reduced server load compared to frequent polling
-- Enables collaborative features (live editing, chat)
-- Instant feedback to users (task completion, new messages)
-- Modern user expectation
-
-**Cons:**
-- WebSocket scaling complexity (stateful connections)
-- Horizontal scaling requires sticky sessions or Redis Pub/Sub
-- Connection management overhead (tracking active connections)
-- Fallback needed for older browsers (SSE or long-polling)
-- More complex deployment (load balancer configuration)
-
-**Scaling Challenges:**
-WebSocket servers are stateful (unlike HTTP), which complicates horizontal scaling. Solutions:
-- **Sticky Sessions**: Route user to same server (simple but limits scaling)
-- **Redis Pub/Sub**: Publish events to Redis, all servers subscribe (recommended)
-- **Dedicated WebSocket Servers**: Separate from HTTP servers
-
-**Production Considerations:**
-- **Authentication**: Validate user before accepting WebSocket connection
-- **Authorization**: Check permissions before sending events
-- **Rate Limiting**: Prevent abuse (max messages per minute)
-- **Reconnection Logic**: Exponential backoff, resume state after disconnect
-- **Heartbeat/Ping**: Detect dead connections, close inactive ones
-
-**Technology Options:**
-
-**Option 1: WebSocket (Full Duplex)**
-- Bidirectional communication
-- Best for: Chat, collaborative editing, real-time dashboards
-- Libraries: Native WebSocket API, Socket.IO
-
-**Option 2: Server-Sent Events (SSE) - Simpler Alternative**
-- One-way (server → client)
-- HTTP-based (easier to deploy)
-- Automatic reconnection
-- Best for: Notifications, live feeds, progress updates
-
-**Option 3: Long Polling (Fallback)**
-- Works everywhere (no special support needed)
-- Highest latency, most server load
-- Use only as fallback
-
-**Recommended Stack:**
-- **Backend**:
- - FastAPI WebSocket support (built-in)
- - Redis Pub/Sub for multi-server coordination
- - Separate WebSocket endpoint: `/ws`
-- **Frontend**:
- - Native WebSocket API or `socket.io-client`
- - Automatic reconnection logic
- - Queue messages during disconnect
-- **Message Format**: JSON with type field
- ```json
- {
- "type": "notification",
- "event": "user.updated",
- "data": {...},
- "timestamp": "2025-11-06T12:00:00Z"
- }
- ```
-
-**Use Cases:**
-
-**Notifications:**
-- Task completion alerts
-- New message indicators
-- Admin actions affecting user
-- System maintenance warnings
-
-**Live Updates:**
-- Dashboard statistics (real-time charts)
-- User presence indicators ("John is online")
-- Collaborative document editing
-- Live comment feeds
-
-**Admin Features:**
-- Real-time user activity monitoring
-- System health dashboard
-- Live log streaming
-
-**Implementation Example:**
-```python
-# Backend: FastAPI WebSocket
-@app.websocket("/ws")
-async def websocket_endpoint(websocket: WebSocket, token: str):
- await websocket.accept()
- user = authenticate_user(token)
-
- # Subscribe to user's event channel
- pubsub = redis.pubsub()
- pubsub.subscribe(f"user:{user.id}")
-
- # Listen for events and send to client
- for message in pubsub.listen():
- await websocket.send_json(message)
-```
-
-**Browser Push Notifications:**
-For notifications when user isn't on the site:
-- Web Push API (Chrome, Firefox, Edge)
-- Service Worker required
-- User permission needed
-- Payload limited to ~4KB
-
-**Alternative: Start Simple**
-If real-time isn't critical initially:
-- Polling every 30-60 seconds
-- SSE for one-way updates
-- Add WebSocket later when needed
-
----
-
-### 8. Feature Flags / Feature Toggles
-
-**Metrics:**
-- **Popularity**: ⭐⭐⭐⭐ (4/5) - Standard in modern dev workflows
-- **Ease of Implementation**: ⭐⭐⭐⭐ (4/5) - Simple database-backed solution works
-- **Ease of Maintenance**: ⭐⭐⭐⭐⭐ (5/5) - Self-service, reduces deployment risk
-- **Versatility**: ⭐⭐⭐⭐⭐ (5/5) - Enables gradual rollouts, A/B testing, kill switches
-
-**Description:**
-Runtime configuration system that allows enabling/disabling features without code deployment, supporting gradual rollouts, A/B testing, and instant rollbacks.
-
-**Pros:**
-- **Deploy code without exposing features** (dark launches)
-- **Gradual rollout**: 5% users → 50% → 100%
-- **A/B testing built-in** (50% see feature A, 50% see feature B)
-- **Instant rollback** without redeployment (toggle off)
-- **Per-organization feature access** (freemium model)
-- **Kill switch** for problematic features
-- **Staged rollout**: Test with internal users → beta users → all users
-
-**Cons:**
-- Technical debt if flags not cleaned up (permanent flags clutter code)
-- Testing complexity (need to test all flag combinations)
-- Performance overhead (flag evaluation on every request)
-
-**Developer Experience Testimonials:**
-- "Changes just a toggle away with no application restart" - Real developer quote
-- "Revolutionized development process" - LaunchDarkly users
-- 200ms flag updates vs 30+ seconds polling (LaunchDarkly vs competitors)
-- "After 4 years, feature flags have just become the way code is written"
-
-**Implementation Approaches:**
-
-**Simple (Database-Backed) - Recommended for Most:**
-```python
-class FeatureFlag(Base):
- key: str # "dark_mode", "new_dashboard"
- enabled: bool
- rollout_percentage: int # 0-100
- enabled_for_users: List[UUID] # Specific user IDs
- enabled_for_orgs: List[UUID] # Specific org IDs
- description: str
- created_at: datetime
-```
-
-**Usage:**
-```python
-# Backend
-if is_feature_enabled("dark_mode", user_id=user.id):
- # New dark mode UI
-else:
- # Old UI
-
-# Frontend
-const { isEnabled } = useFeatureFlag("dark_mode");
-if (isEnabled) {
- return ;
-}
-```
-
-**Advanced (LaunchDarkly SDK) - For Complex Needs:**
-- Commercial SaaS (paid)
-- 200ms flag propagation
-- Multi-variate flags (not just on/off)
-- Targeting rules (location, device, custom attributes)
-- Analytics integration
-- Experimentation platform
-
-**Open-Source Alternative (Unleash):**
-- Self-hosted or cloud
-- Similar features to LaunchDarkly
-- Free for basic usage
-- Good for privacy-conscious projects
-
-**Flag Types:**
-
-**Release Flags (Temporary):**
-- Wrap new features during development
-- Remove after feature is stable
-- Lifespan: 1-4 weeks
-
-**Experiment Flags (Temporary):**
-- A/B testing
-- Remove after winner determined
-- Lifespan: Days to weeks
-
-**Operational Flags (Permanent):**
-- Kill switches for external services
-- Circuit breakers
-- Maintenance mode
-- Lifespan: Forever
-
-**Permission Flags (Permanent):**
-- Plan-based features (free vs pro)
-- Beta features for select users
-- Lifespan: Forever
-
-**Best Practices:**
-- **Naming Convention**: `feature_snake_case` (e.g., `new_dashboard`, `ai_assistant`)
-- **Default to Off**: New flags should default to disabled
-- **Flag Cleanup**: Remove flags within 2 weeks of full rollout
-- **Flag Inventory**: Track all flags in admin dashboard
-- **Testing**: Test both enabled and disabled states
-
-**Admin UI Features:**
-- List all flags with status (enabled/disabled, rollout %)
-- Toggle flags on/off instantly
-- Set rollout percentage (slider: 0% → 100%)
-- Target specific users/organizations
-- Flag history (who changed, when)
-- Flag usage tracking (which code paths use this flag)
-
-**Recommended Stack:**
-- **Simple**: Database table + API endpoint + admin UI
-- **Advanced**: LaunchDarkly SDK (commercial) or Unleash (open-source)
-- **Caching**: Redis for fast flag evaluation (avoid DB query on every request)
-- **SDK**:
- - Backend: Python function `is_feature_enabled(key, user_id, org_id)`
- - Frontend: React hook `useFeatureFlag(key)`
-
-**Use Cases:**
-- Launch new UI (gradual rollout)
-- Beta features for select customers
-- A/B test new checkout flow
-- Kill switch for third-party API integration
-- Dark mode toggle
-- AI features (enable for Pro plan only)
-- Maintenance mode (disable all non-essential features)
-
----
-
-### 9. Observability Stack (Logs, Metrics, Traces)
-
-**Metrics:**
-- **Popularity**: ⭐⭐⭐⭐⭐ (5/5) - Production necessity in 2025
-- **Ease of Implementation**: ⭐⭐ (2/5) - Initial setup complex
-- **Ease of Maintenance**: ⭐⭐⭐ (3/5) - Ongoing dashboard tuning
-- **Versatility**: ⭐⭐⭐⭐⭐ (5/5) - Essential for debugging, monitoring, optimization
-
-**Description:**
-Comprehensive monitoring infrastructure based on three pillars (Logs, Metrics, Traces) to provide complete visibility into system behavior, performance, and health.
-
-**Three Pillars of Observability:**
-
-**1. Logs:**
-Timestamped records of discrete events
-- Application logs (errors, warnings, info)
-- Access logs (HTTP requests)
-- Audit logs (user actions)
-
-**2. Metrics:**
-Numeric measurements over time
-- Request count, response times, error rates
-- CPU, memory, disk usage
-- Database query performance
-- Queue lengths
-
-**3. Traces:**
-Request journey across distributed system
-- Trace ID follows request through all services
-- Identify bottlenecks (which service is slow?)
-- Visualize call graph
-
-**Pros:**
-- **"Detect and resolve problems before they impact customers"**
-- Root cause identification in minutes vs hours
-- Performance bottleneck detection
-- Proactive monitoring (alerts before outage)
-- Capacity planning (predict when to scale)
-- User experience insights (slow page loads)
-
-**Cons:**
-- Tool proliferation (separate systems for logs, metrics, traces)
-- Storage costs (log data grows fast - 10-50GB/month)
-- Learning curve for teams
-- Initial setup complexity
-
-**Modern Standard: OpenTelemetry (OTel)**
-- Unified standard for logs, metrics, traces
-- Vendor-neutral (prevent lock-in)
-- Single SDK for all observability
-- Supports all major backends (Prometheus, Jaeger, Datadog, etc.)
-
-**Recommended Stacks:**
-
-**Open Source (Self-Hosted):**
-- **Logs**: Loki (by Grafana) - Like Prometheus for logs
-- **Metrics**: Prometheus - Industry standard, time-series database
-- **Traces**: Tempo (by Grafana) or Jaeger - Distributed tracing
-- **Visualization**: Grafana - Unified dashboards for all three
-- **Alternative Logs**: ELK Stack (Elasticsearch + Logstash + Kibana) - More powerful, more complex
-
-**Cloud/Commercial (SaaS):**
-- **Datadog**: All-in-one, expensive but comprehensive (~$15-100/host/month)
-- **New Relic**: Similar to Datadog
-- **Sentry**: Excellent for errors + performance (~$26-80/month)
-- **BetterStack**: Modern, developer-friendly, good pricing
-- **Honeycomb**: Traces + advanced querying
-
-**Hybrid Approach (Recommended for Boilerplate):**
-- **Production Ready**: Integrate with Sentry (errors + performance)
-- **Self-Hosted Option**: Provide docker-compose with Prometheus + Grafana + Loki
-- **Documentation**: Guide for connecting to Datadog, New Relic
-
-**What to Monitor:**
-
-**Application Metrics:**
-- Request rate (requests/second)
-- Error rate (% of requests failing)
-- Response time (p50, p95, p99)
-- Endpoint-specific metrics (`/api/v1/users` slowest?)
-
-**Infrastructure Metrics:**
-- CPU usage (%)
-- Memory usage (%)
-- Disk I/O
-- Network throughput
-
-**Database Metrics:**
-- Query performance (slow query log)
-- Connection pool usage
-- Transaction rate
-- Lock contention
-
-**Business Metrics:**
-- User signups (per hour)
-- Active users (current)
-- API calls per customer
-- Revenue (if applicable)
-
-**Key Features to Implement:**
-
-**Structured Logging:**
-```python
-logger.info("User login", extra={
- "user_id": user.id,
- "email": user.email,
- "ip": request.client.host,
- "success": True
-})
-# Output: JSON with all fields for easy parsing
-```
-
-**Distributed Tracing:**
-```python
-# Generate trace_id on request entry
-trace_id = str(uuid.uuid4())
-# Pass trace_id through all function calls
-# Include trace_id in all logs
-# Frontend can send trace_id in X-Trace-Id header
-```
-
-**Alerting:**
-- Error rate >5% for 5 minutes → PagerDuty/Slack alert
-- API response time p95 >2s → Warning
-- Disk usage >80% → Warning
-
-**Dashboards:**
-- **Application Health**: Request rate, error rate, response time
-- **User Activity**: Active users, signups, sessions
-- **Infrastructure**: CPU, memory, disk for all servers
-- **Business KPIs**: Revenue, active organizations, API usage
-
-**Implementation Steps:**
-1. **Structured Logging**: Update Python logging to output JSON
-2. **Metrics Collection**: Add Prometheus client, expose `/metrics` endpoint
-3. **Tracing**: Add OpenTelemetry SDK, generate trace IDs
-4. **Centralization**: Ship logs to Loki/Elasticsearch
-5. **Visualization**: Build Grafana dashboards
-6. **Alerting**: Configure alerts for critical metrics
-
-**Use Cases:**
-- Debug production issues (find trace_id in logs)
-- Performance optimization (identify slow endpoints)
-- Capacity planning (predict when to scale based on trends)
-- SLA monitoring (are we meeting 99.9% uptime?)
-- Cost optimization (which endpoints are most expensive?)
-
----
-
-### 10. Background Job Queue (Celery/BullMQ Alternative)
-
-**Metrics:**
-- **Popularity**: ⭐⭐⭐⭐⭐ (5/5) - Critical for async processing
-- **Ease of Implementation**: ⭐⭐⭐ (3/5) - Requires Redis/RabbitMQ setup
-- **Ease of Maintenance**: ⭐⭐⭐ (3/5) - Monitoring, dead letter queues
-- **Versatility**: ⭐⭐⭐⭐⭐ (5/5) - Email sending, exports, reports, cleanup
-
-**Description:**
-Distributed task queue system for executing long-running jobs asynchronously in the background, preventing request timeouts and improving user experience.
-
-**Current State:**
-You already have APScheduler for cron-style scheduled jobs (like session cleanup). This recommendation adds a full job queue for on-demand async tasks.
-
-**Pros:**
-- **Celery = "gold standard for Python"** (proven, powerful, battle-tested)
-- Enables long-running tasks without blocking HTTP requests
-- Built-in retry logic with exponential backoff
-- Priority queues (high/normal/low)
-- Task chaining and workflows
-- Scheduled tasks (delay task, run at specific time)
-- Rate limiting (max X tasks per minute)
-
-**Cons:**
-- Additional infrastructure (Redis or RabbitMQ broker)
-- Monitoring complexity (need to track dead jobs)
-- Scaling considerations at millions of jobs/day
-- Worker management (how many workers, auto-scaling)
-
-**Celery vs BullMQ:**
-
-**Celery (Python):**
-- Python ecosystem integration
-- Mature, feature-rich
-- Good for: Email sending, data processing, ML pipelines
-- Recommended for this boilerplate (FastAPI is Python)
-
-**BullMQ (Node.js):**
-- Node.js ecosystem
-- Modern, TypeScript support
-- Good for: Next.js apps with Node backend
-- Not applicable for FastAPI backend
-
-**Recommended Enhancement:**
-Add Celery as a separate module alongside APScheduler:
-- **APScheduler**: Cron-style scheduled jobs (daily cleanup at 2 AM)
-- **Celery**: On-demand async tasks (send email after user signup)
-
-**Architecture:**
-```
-FastAPI App → Celery Task (add to queue) → Redis Broker → Celery Worker (execute task)
-```
-
-**Components:**
-- **Broker**: Redis (recommended) or RabbitMQ - Stores task queue
-- **Workers**: Separate Python processes that execute tasks
-- **Result Backend**: Redis or PostgreSQL - Stores task results
-- **Monitoring**: Flower (web UI for Celery)
-
-**Task Examples:**
-
-**Email Sending:**
-```python
-@celery_app.task(bind=True, max_retries=3)
-def send_email_task(self, to, subject, body):
- try:
- email_service.send(to, subject, body)
- except Exception as exc:
- raise self.retry(exc=exc, countdown=60) # Retry after 1 min
-```
-
-**Data Export:**
-```python
-@celery_app.task
-def export_users_csv_task(user_id, filters):
- # Long-running task
- users = get_filtered_users(filters)
- csv_file = generate_csv(users)
- upload_to_s3(csv_file)
- notify_user(user_id, download_url)
-```
-
-**Report Generation:**
-```python
-@celery_app.task
-def generate_monthly_report_task(org_id, month):
- data = gather_statistics(org_id, month)
- pdf = create_pdf_report(data)
- email_to_admins(org_id, pdf)
-```
-
-**Features to Implement:**
-
-**Task Types:**
-- Immediate: Execute ASAP
-- Delayed: Execute after X seconds/minutes
-- Scheduled: Execute at specific datetime
-- Periodic: Execute every X hours/days (use APScheduler instead)
-
-**Priority Queues:**
-- High: Critical tasks (password reset emails)
-- Normal: Standard tasks (welcome emails)
-- Low: Bulk operations (monthly reports)
-
-**Retry Logic:**
-- Max retries: 3 (configurable per task)
-- Backoff: Exponential (1 min, 5 min, 15 min)
-- Dead letter queue: Store failed tasks after max retries
-
-**Task Status Tracking:**
-```python
-# Frontend initiates export
-task = export_users_csv_task.delay(user_id, filters)
-task_id = task.id # Store in database
-
-# Frontend polls for status
-task = celery_app.AsyncResult(task_id)
-status = task.state # PENDING, STARTED, SUCCESS, FAILURE
-result = task.result if task.successful() else None
-```
-
-**Admin UI Features:**
-- Active tasks count
-- Queue lengths (high/normal/low)
-- Failed tasks list with retry option
-- Worker status (online/offline)
-- Task history (last 1000 tasks)
-
-**Monitoring (Flower):**
-- Web UI at `http://localhost:5555`
-- Real-time task monitoring
-- Worker management
-- Task statistics
-
-**Recommended Stack:**
-- **Backend**: Celery + Redis broker
-- **Workers**: 4-8 worker processes (scale based on load)
-- **Monitoring**: Flower (Celery web UI)
-- **Result Storage**: Redis (fast) or PostgreSQL (persistent)
-
-**Use Cases:**
-
-**Immediate:**
-- Send email after user action (signup, password reset)
-- Generate thumbnail after image upload
-- Process webhook delivery
-
-**Delayed:**
-- Send reminder email 24 hours before event
-- Delete inactive account after 30 days of inactivity
-
-**Bulk:**
-- Send newsletter to 10,000 users (queue 10,000 tasks)
-- Generate reports for all organizations
-- Data import (process 100,000 CSV rows)
-
-**Scheduled:**
-- Daily digest emails (8 AM every day)
-- Monthly billing (1st of each month)
-- Weekly analytics summary
-
-**Implementation Steps:**
-1. Install Celery + Redis
-2. Create `celery_app.py` config
-3. Define tasks in `app/tasks/`
-4. Run Celery worker: `celery -A app.celery_app worker`
-5. Run Flower: `celery -A app.celery_app flower`
-6. Update docker-compose with Redis + Celery worker containers
-
----
-
-## ⚡ TIER 3: COMPETITIVE EDGE FEATURES (Nice-to-Have, Future-Proof)
-
-### 11. Two-Factor Authentication (2FA/MFA)
-
-**Metrics:**
-- **Popularity**: ⭐⭐⭐⭐⭐ (5/5) - Security standard, enterprise requirement
-- **Ease of Implementation**: ⭐⭐⭐⭐ (4/5) - Libraries like `pyotp` available
-- **Ease of Maintenance**: ⭐⭐⭐⭐⭐ (5/5) - Low maintenance once implemented
-- **Versatility**: ⭐⭐⭐⭐ (4/5) - Security-focused, compliance-driven
-
-**Description:**
-Additional authentication factor beyond password, using time-based one-time passwords (TOTP) via authenticator apps like Google Authenticator or Authy.
-
-**Pros:**
-- Dramatically reduces account takeover risk (even if password leaked)
-- Enterprise/SOC2 requirement for compliance
-- User trust signal (shows security commitment)
-- Industry standard (expected by security-conscious users)
-
-**Cons:**
-- UX friction (extra step on login)
-- Support burden (users losing devices, backup codes)
-- SMS 2FA insecure (SIM swapping attacks) - avoid if possible
-
-**Recommended:** TOTP (Time-based One-Time Password) using authenticator apps
-
-**Implementation:**
-- QR code generation for setup
-- Backup codes (10 one-time codes for device loss)
-- Optional enforcement (required for admins, optional for users)
-- Remember device (30 days)
-
----
-
-### 12. API Rate Limiting & Usage Tracking (Enhanced)
-
-**Metrics:**
-- **Popularity**: ⭐⭐⭐⭐⭐ (5/5) - SaaS monetization standard
-- **Ease of Implementation**: ⭐⭐⭐ (3/5) - You have SlowAPI, needs quota tracking
-- **Ease of Maintenance**: ⭐⭐⭐ (3/5) - Monitoring, quota adjustments
-- **Versatility**: ⭐⭐⭐⭐⭐ (5/5) - Protects infrastructure, enables pricing tiers
-
-**Current State:**
-You already have SlowAPI for rate limiting (5 requests/minute for auth endpoints, etc.)
-
-**Enhancement Needed:**
-
-**Usage Quotas (Long-term Limits):**
-- Track API calls per user/organization against monthly limits
-- Free plan: 1,000 calls/month
-- Pro plan: 50,000 calls/month
-- Enterprise: Unlimited
-
-**Usage Dashboard:**
-- Show customers their consumption (graph, percentage of quota)
-- Email alerts at 80%, 90%, 100% usage
-- Upgrade prompt when approaching limit
-
-**Overage Handling:**
-- Block after limit (free plan)
-- Charge per-request overage (paid plans)
-- Soft limit with grace period
-
-**Tracking Implementation:**
-```python
-# Increment counter on each request
-redis.incr(f"api_usage:{user_id}:{month}")
-
-# Check against quota
-usage = redis.get(f"api_usage:{user_id}:{month}")
-if usage > plan.monthly_quota:
- raise QuotaExceededError()
-```
-
-**Admin Features:**
-- Usage analytics dashboard (top consumers, endpoint breakdown)
-- Custom quotas for specific customers
-- Usage export (CSV) for billing
-
----
-
-### 13. Advanced Search (Elasticsearch/Meilisearch)
-
-**Metrics:**
-- **Popularity**: ⭐⭐⭐⭐ (4/5) - Expected as data grows
-- **Ease of Implementation**: ⭐⭐ (2/5) - Separate service, sync logic
-- **Ease of Maintenance**: ⭐⭐ (2/5) - Index management, sync issues
-- **Versatility**: ⭐⭐⭐⭐ (4/5) - Enhances UX across all content
-
-**Description:**
-Full-text search engine that provides fast, typo-tolerant search across all your data with filters, facets, and sorting.
-
-**Pros:**
-- Fast full-text search (instant results, <50ms)
-- Typo-tolerant ("organiztion" finds "organization")
-- Better than PostgreSQL `LIKE` queries at scale
-- Filters and facets (search users by role, location, etc.)
-- Relevance ranking (most relevant results first)
-
-**Cons:**
-- Additional infrastructure (separate service)
-- Data synchronization complexity (keep search index in sync with database)
-- Cost (Elasticsearch is memory-hungry, Meilisearch cheaper)
-
-**Recommended:** Meilisearch
-- Simpler than Elasticsearch
-- Faster (Rust-based)
-- Cheaper (low memory usage)
-- Great developer experience
-
-**Use Cases:**
-- Search users by name, email
-- Search organizations by name
-- Search audit logs by action
-- Search documentation
-
----
-
-### 14. GraphQL API (Alternative to REST)
-
-**Metrics:**
-- **Popularity**: ⭐⭐⭐ (3/5) - Growing, but not yet mainstream
-- **Ease of Implementation**: ⭐⭐ (2/5) - Requires schema design, resolver logic
-- **Ease of Maintenance**: ⭐⭐⭐ (3/5) - Schema evolution challenges
-- **Versatility**: ⭐⭐⭐⭐ (4/5) - Flexible querying, reduces over-fetching
-
-**Description:**
-Alternative API architecture where clients request exactly the data they need in a single query, reducing over-fetching and under-fetching.
-
-**Pros:**
-- Clients request exactly what they need (no over-fetching)
-- Single endpoint for all queries
-- Strongly typed schema (auto-generated documentation)
-- Excellent for mobile apps (reduce bandwidth)
-
-**Cons:**
-- Caching harder than REST (URL-based caching doesn't work)
-- N+1 query problems (need DataLoader pattern)
-- Complexity vs REST
-- Learning curve for frontend developers
-
-**Recommended:** Offer both REST + GraphQL using Strawberry GraphQL (FastAPI-compatible)
-
----
-
-### 15. AI Integration Ready (LLM API Templates)
-
-**Metrics:**
-- **Popularity**: ⭐⭐⭐⭐⭐ (5/5) - AI is 2025's top differentiator
-- **Ease of Implementation**: ⭐⭐⭐⭐ (4/5) - API calls straightforward
-- **Ease of Maintenance**: ⭐⭐⭐ (3/5) - Prompt engineering, model updates
-- **Versatility**: ⭐⭐⭐⭐⭐ (5/5) - Enables countless use cases
-
-**Description:**
-Pre-built integration layer for Large Language Model APIs (OpenAI, Anthropic, etc.) enabling AI-powered features like chatbots, content generation, and data analysis.
-
-**Pros:**
-- **"AI integration has become a crucial differentiator in SaaS boilerplates"** (2025 trend)
-- Support for multiple providers (OpenAI, Anthropic, Cohere, local models)
-- Enables features: chatbots, content generation, data analysis, summarization
-- Marketing appeal (AI-powered!)
-- Future-proof (AI adoption accelerating)
-
-**Cons:**
-- API costs can be high ($0.01-0.10 per request depending on usage)
-- Prompt engineering complexity
-- Privacy concerns (data sent to third parties)
-- Rate limits from providers
-
-**Recommended Approach:**
-- **Abstract API layer** supporting multiple providers (easy to switch)
-- **Streaming responses** for better UX (word-by-word)
-- **Token usage tracking** (for billing, quota management)
-- **Example implementations**:
- - Chat assistant (customer support)
- - Text summarization (summarize audit logs)
- - Content generation (email templates)
- - Data extraction (parse uploaded documents)
-
-**Use Cases:**
-- AI chat support bot
-- Generate email subject lines
-- Summarize long documents
-- Extract structured data from text
-- Code generation from natural language
-
----
-
-### 16. Import/Export System (CSV, JSON, Excel)
-
-**Metrics:**
-- **Popularity**: ⭐⭐⭐⭐ (4/5) - Data portability expected
-- **Ease of Implementation**: ⭐⭐⭐⭐ (4/5) - Libraries like `pandas` available
-- **Ease of Maintenance**: ⭐⭐⭐⭐ (4/5) - Low maintenance
-- **Versatility**: ⭐⭐⭐⭐ (4/5) - Useful for migration, backup, compliance
-
-**Description:**
-Bulk data import and export functionality allowing users to move data in/out of the system in standard formats (CSV, JSON, Excel).
-
-**Pros:**
-- **GDPR "Right to Data Portability" requirement** (export user data)
-- Bulk user imports for enterprise onboarding
-- Backup/migration enablement
-- Onboarding accelerator (import existing customer data)
-- Data analysis (export to Excel for business users)
-
-**Cons:**
-- Validation complexity (malformed imports, duplicate detection)
-- Large file handling (memory issues, need streaming)
-
-**Recommended Features:**
-
-**Export:**
-- Users (CSV, JSON, Excel)
-- Organizations (CSV, JSON)
-- Audit logs (CSV for compliance)
-- Background job for large exports (Celery)
-- Email download link when ready
-
-**Import:**
-- Bulk user creation with validation
-- Duplicate detection (by email)
-- Preview before import (show first 10 rows)
-- Error reporting (row 45: invalid email)
-
-**Admin UI:**
-- Upload CSV file
-- Map CSV columns to database fields
-- Preview import
-- Progress tracking (500/1000 rows imported)
-
-**Use Cases:**
-- GDPR compliance (user data export)
-- Enterprise onboarding (import 1000 employees)
-- Migration from another system
-- Data analysis (export to Excel, create pivot tables)
-
----
-
-### 17. Scheduled Reports & Notifications
-
-**Metrics:**
-- **Popularity**: ⭐⭐⭐⭐ (4/5) - Common enterprise need
-- **Ease of Implementation**: ⭐⭐⭐ (3/5) - Requires job queue + templating
-- **Ease of Maintenance**: ⭐⭐⭐ (3/5) - Report templates need updates
-- **Versatility**: ⭐⭐⭐⭐ (4/5) - Useful for admins, users, billing
-
-**Description:**
-Automated generation and delivery of periodic reports via email or dashboard, providing users with insights into their activity, usage, and system status.
-
-**Examples:**
-
-**Weekly User Activity Summary:**
-- New users this week
-- Active users (DAU/WAU/MAU)
-- Top features used
-- Email sent Monday morning
-
-**Monthly Billing Report:**
-- API usage breakdown
-- Storage usage
-- Cost projection
-- Email sent 1st of month
-
-**Security Alerts:**
-- Unusual login (new device, new location)
-- Failed login attempts (>5 in 1 hour)
-- Permission changes
-- Real-time email
-
-**Capacity Warnings:**
-- Approaching quota (80%, 90% of API limit)
-- Storage near limit
-- Email + in-app notification
-
-**Use Cases:**
-- Keep users informed (engagement)
-- Proactive support (alert before issues)
-- Billing transparency
-- Security awareness
-
----
-
-## 📊 PRIORITY MATRIX
-
-### **TIER A: IMPLEMENT FIRST (Highest ROI)**
-
-1. **OAuth/Social Login** - 77% of users prefer it, 20-40% conversion boost
-2. **Email Templates** - You have placeholder, just needs implementation
-3. **File Upload/Storage** - Needed for avatars, documents (80%+ of apps need this)
-4. **Internationalization** - Opens global markets, Next.js has built-in support
-5. **2FA/MFA** - Security standard, enterprise requirement
-
-**Estimated Effort:** 3-4 weeks total
-
----
-
-### **TIER B: IMPLEMENT NEXT (Strong Differentiators)**
-
-6. **Webhooks** - Enables integrations, competitive edge for B2B
-7. **Background Job Queue (Celery)** - You have APScheduler, Celery adds power
-8. **Audit Logging** - Compliance requirement, debugging aid
-9. **Feature Flags** - Modern dev practice, zero-downtime releases
-10. **API Usage Tracking** - Monetization enabler, you already have rate limiting
-
-**Estimated Effort:** 4-5 weeks total
-
----
-
-### **TIER C: CONSIDER LATER (Nice-to-Have)**
-
-11. **Real-time Notifications** - Complex scaling, can start with polling
-12. **Observability Stack** - Production essential, but can use SaaS initially (Sentry)
-13. **Advanced Search** - Needed only when data grows significantly
-14. **AI Integration** - Trendy, but needs clear use case
-15. **Import/Export** - GDPR compliance, enterprise onboarding
-
-**Estimated Effort:** 5-6 weeks total
-
----
-
-### **TIER D: OPTIONAL (Niche)**
-
-16. **GraphQL** - Nice-to-have, REST is sufficient for most use cases
-17. **Scheduled Reports** - Can be custom per project
-
-**Estimated Effort:** 2-3 weeks total
-
----
-
-## 🎯 TOP 5 KILLER FEATURES RECOMMENDATION
-
-If you can only implement **5 features**, choose these for maximum impact:
-
-### 1. **OAuth/Social Login** (Google, GitHub, Apple, Microsoft)
-**Why:** Massive UX win, 77% user preference, 20-40% conversion boost, industry standard
-
-### 2. **File Upload & Storage** (S3 + Cloudinary patterns)
-**Why:** Universal need (avatars, documents, exports), 80%+ of apps require it
-
-### 3. **Webhooks System**
-**Why:** Enables ecosystem, B2B differentiator, allows customer integrations
-
-### 4. **Internationalization (i18n)**
-**Why:** Global reach multiplier, Next.js has built-in support, SEO benefits
-
-### 5. **Enhanced Email Service**
-**Why:** You're 80% there already, just needs templates and provider integration
-
-**Bonus #6:** **Audit Logging** - Enterprise blocker without it (SOC2/GDPR requirement)
-
----
-
-## 🏗️ IMPLEMENTATION ROADMAP
-
-### **Phase 1: Foundation (Weeks 1-4)**
-- Email templates + provider integration (SendGrid/Postmark)
-- File upload/storage (S3 + CloudFront)
-- OAuth/Social login (Google, GitHub)
-
-### **Phase 2: Enterprise Readiness (Weeks 5-8)**
-- Audit logging system
-- 2FA/MFA
-- Internationalization (i18n)
-
-### **Phase 3: Integration & Automation (Weeks 9-12)**
-- Webhooks system
-- Background job queue (Celery)
-- API usage tracking enhancement
-
-### **Phase 4: Advanced Features (Weeks 13-16)**
-- Feature flags
-- Import/export
-- Real-time notifications
-
-### **Phase 5: Observability & Scale (Weeks 17-20)**
-- Observability stack (Prometheus + Grafana + Loki)
-- Advanced search (Meilisearch)
-- Scheduled reports
-
----
-
-## 📈 EXPECTED IMPACT
-
-Implementing all Tier A + Tier B features would make your boilerplate:
-
-- **40-60% faster time-to-market** for SaaS projects
-- **Enterprise-ready** (SOC2/GDPR compliance)
-- **Globally scalable** (i18n, CDN, observability)
-- **Integration-friendly** (webhooks, OAuth)
-- **Developer-friendly** (feature flags, background jobs)
-- **Monetization-ready** (usage tracking, quotas)
-
-**Competitive Positioning:**
-Your template would rival commercial boilerplates like:
-- Supastarter ($299-399)
-- Makerkit ($299+)
-- Shipfast ($199+)
-- But yours is **open-source** and **MIT licensed**!
-
----
-
-## 🤔 QUESTIONS FOR CONSIDERATION
-
-1. **Target Audience:** B2C, B2B, or both? (affects which features to prioritize)
-2. **Compliance Requirements:** Do you want SOC2/GDPR ready out-of-box? (requires audit logging)
-3. **Deployment Model:** Self-hosted, cloud, or both? (affects observability choice)
-4. **AI Strategy:** Include AI now or wait for clearer use cases?
-5. **Maintenance Commitment:** How much ongoing maintenance can you commit to?
-
----
-
-## 📚 ADDITIONAL RESEARCH SOURCES
-
-- Auth0 Social Login Report 2016 (statistics on OAuth adoption)
-- Phrase Next.js i18n Guide (implementation best practices)
-- WorkOS Webhooks Guidelines (architecture patterns)
-- Moesif Rate Limiting Best Practices (quota management)
-- LaunchDarkly Feature Flag Documentation (developer experience)
-- OpenTelemetry Documentation (observability standards)
-
----
-
-**Document prepared with extensive web research on 2025-11-06**
diff --git a/Makefile b/Makefile
index 0ac0818..29e3f68 100755
--- a/Makefile
+++ b/Makefile
@@ -1,7 +1,7 @@
.PHONY: help dev dev-full prod down logs logs-dev clean clean-slate drop-db reset-db push-images deploy
VERSION ?= latest
-REGISTRY := gitea.pragmazest.com/cardosofelipe/app
+REGISTRY ?= ghcr.io/cardosofelipe/pragma-stack
# Default target
help:
diff --git a/README.md b/README.md
index a378488..406c610 100644
--- a/README.md
+++ b/README.md
@@ -22,17 +22,6 @@
---
-## 🤖 AI-Friendly Documentation
-
-This project includes comprehensive documentation designed for AI coding assistants:
-
-- **[AGENTS.md](./AGENTS.md)** - Framework-agnostic AI assistant context for PragmaStack
-- **[CLAUDE.md](./CLAUDE.md)** - Claude Code-specific guidance
-
-These files provide AI assistants with the **PragmaStack** architecture, patterns, and best practices.
-
----
-
## Why PragmaStack?
Building a modern full-stack application often leads to "analysis paralysis" or "boilerplate fatigue". You spend weeks setting up authentication, testing, and linting before writing a single line of business logic.
@@ -86,7 +75,7 @@ Full OAuth 2.0 Authorization Server for Model Context Protocol (MCP) and third-p
- Admin-only routes with proper authorization
### 🎨 **Modern Frontend**
-- Next.js 15 with App Router and React 19
+- Next.js 16 with App Router and React 19
- **PragmaStack Design System** built on shadcn/ui + TailwindCSS
- Pre-configured theme with dark mode support (coming soon)
- Responsive, accessible components (WCAG AA compliant)
@@ -148,6 +137,30 @@ Full OAuth 2.0 Authorization Server for Model Context Protocol (MCP) and third-p
---
+## 📸 Screenshots
+
+
+Click to view screenshots
+
+### Landing Page
+
+
+### Authentication
+
+
+### Admin Dashboard
+
+
+### User Settings
+
+
+### Design System
+
+
+
+
+---
+
## 🎭 Demo Mode
**Try the frontend without a backend!** Perfect for:
@@ -191,7 +204,7 @@ Demo mode uses [Mock Service Worker (MSW)](https://mswjs.io/) to intercept API c
- **[pytest](https://pytest.org/)** - Testing framework with async support
### Frontend
-- **[Next.js 15](https://nextjs.org/)** - React framework with App Router
+- **[Next.js 16](https://nextjs.org/)** - React framework with App Router
- **[React 19](https://react.dev/)** - UI library
- **[TypeScript](https://www.typescriptlang.org/)** - Type-safe JavaScript
- **[TailwindCSS](https://tailwindcss.com/)** - Utility-first CSS framework
@@ -228,7 +241,7 @@ The fastest way to get started is with Docker:
```bash
# Clone the repository
-git clone https://github.com/yourusername/fast-next-template.git
+git clone https://github.com/cardosofelipe/pragma-stack.git
cd fast-next-template
# Copy environment file
@@ -430,6 +443,17 @@ npx playwright show-report
---
+## 🤖 AI-Friendly Documentation
+
+This project includes comprehensive documentation designed for AI coding assistants:
+
+- **[AGENTS.md](./AGENTS.md)** - Framework-agnostic AI assistant context for PragmaStack
+- **[CLAUDE.md](./CLAUDE.md)** - Claude Code-specific guidance
+
+These files provide AI assistants with the **PragmaStack** architecture, patterns, and best practices.
+
+---
+
## 🗄️ Database Migrations
The template uses Alembic for database migrations:
@@ -476,7 +500,6 @@ python migrate.py current
- Component library guide
- Layout patterns, spacing philosophy
- Forms, accessibility, AI guidelines
-- **[ARCHITECTURE_FIX_REPORT.md](./frontend/docs/ARCHITECTURE_FIX_REPORT.md)** - Critical dependency injection patterns
- **[E2E Testing Guide](./frontend/e2e/README.md)** - E2E testing setup and best practices
### API Documentation
@@ -552,6 +575,7 @@ docker-compose down
- [ ] GitHub Actions CI/CD pipelines
- [ ] Dynamic test coverage badges from CI
- [ ] E2E test coverage reporting
+- [ ] OAuth token encryption at rest (security hardening)
- [ ] Additional languages (Spanish, French, German, etc.)
- [ ] SSO/SAML authentication
- [ ] Real-time notifications with WebSockets
@@ -590,7 +614,7 @@ Contributions are welcome! Whether you're fixing bugs, improving documentation,
### Reporting Issues
-Found a bug? Have a suggestion? [Open an issue](https://github.com/yourusername/fast-next-template/issues)!
+Found a bug? Have a suggestion? [Open an issue](https://github.com/cardosofelipe/pragma-stack/issues)!
Please include:
- Clear description of the issue/suggestion
@@ -624,8 +648,8 @@ This template is built on the shoulders of giants:
## 💬 Questions?
- **Documentation**: Check the `/docs` folders in backend and frontend
-- **Issues**: [GitHub Issues](https://github.com/yourusername/fast-next-template/issues)
-- **Discussions**: [GitHub Discussions](https://github.com/yourusername/fast-next-template/discussions)
+- **Issues**: [GitHub Issues](https://github.com/cardosofelipe/pragma-stack/issues)
+- **Discussions**: [GitHub Discussions](https://github.com/cardosofelipe/pragma-stack/discussions)
---
diff --git a/backend/app/services/oauth_service.py b/backend/app/services/oauth_service.py
index 37c73a2..561a4bf 100644
--- a/backend/app/services/oauth_service.py
+++ b/backend/app/services/oauth_service.py
@@ -343,9 +343,7 @@ class OAuthService:
await oauth_account.update_tokens(
db,
account=existing_oauth,
- access_token_encrypted=token.get("access_token"), # TODO: encrypt
- refresh_token_encrypted=token.get("refresh_token"), # TODO: encrypt
- token_expires_at=datetime.now(UTC)
+ access_token_encrypted=token.get("access_token"), refresh_token_encrypted=token.get("refresh_token"), token_expires_at=datetime.now(UTC)
+ timedelta(seconds=token.get("expires_in", 3600)),
)
@@ -377,9 +375,7 @@ class OAuthService:
provider=provider,
provider_user_id=provider_user_id,
provider_email=provider_email,
- access_token_encrypted=token.get("access_token"), # TODO: encrypt
- refresh_token_encrypted=token.get("refresh_token"), # TODO: encrypt
- token_expires_at=datetime.now(UTC)
+ access_token_encrypted=token.get("access_token"), refresh_token_encrypted=token.get("refresh_token"), token_expires_at=datetime.now(UTC)
+ timedelta(seconds=token.get("expires_in", 3600))
if token.get("expires_in")
else None,
@@ -648,9 +644,7 @@ class OAuthService:
provider=provider,
provider_user_id=provider_user_id,
provider_email=email,
- access_token_encrypted=token.get("access_token"), # TODO: encrypt
- refresh_token_encrypted=token.get("refresh_token"), # TODO: encrypt
- token_expires_at=datetime.now(UTC)
+ access_token_encrypted=token.get("access_token"), refresh_token_encrypted=token.get("refresh_token"), token_expires_at=datetime.now(UTC)
+ timedelta(seconds=token.get("expires_in", 3600))
if token.get("expires_in")
else None,
diff --git a/docs/I18N_IMPLEMENTATION_PLAN.md b/docs/I18N_IMPLEMENTATION_PLAN.md
deleted file mode 100644
index 60c3283..0000000
--- a/docs/I18N_IMPLEMENTATION_PLAN.md
+++ /dev/null
@@ -1,528 +0,0 @@
-# Internationalization (i18n) Implementation Plan
-## State-of-the-Art Next.js 15 + FastAPI i18n System (2025)
-
-**Last Updated**: 2025-11-17
-**Status**: ✅ Approved - Ready for Implementation
-**Languages**: English (en) - Default, Italian (it) - Showcase
-
----
-
-## 📋 EXECUTIVE SUMMARY
-
-This document provides a comprehensive plan for implementing production-grade internationalization (i18n) in the FastNext Template. The implementation showcases best practices with 2 languages (English and Italian), making it easy for users to extend with additional languages.
-
-### Technology Stack (2025 Best Practices)
-
-- **Frontend**: next-intl 4.0 (ESM, TypeScript-first, App Router native)
-- **Backend**: FastAPI with BCP 47 locale storage in PostgreSQL
-- **Testing**: Playwright (parameterized locale tests) + Jest (i18n test utils)
-- **SEO**: Automatic hreflang tags, sitemap generation, metadata per locale
-- **Validation**: Automated translation key validation in CI/CD
-
-### Why Only 2 Languages?
-
-This is a **template showcase**, not a production deployment:
-
-✅ Clean example of i18n implementation
-✅ Easy to understand patterns
-✅ Users can add languages by copying the Italian example
-✅ Faster testing and implementation
-✅ Smaller bundle size for demonstration
-
-### Quality Standards
-
-- ✅ **Test Coverage**: Backend ≥97%, comprehensive E2E tests
-- ✅ **Zero Breaking Changes**: All existing 743 backend + 56 frontend tests must pass
-- ✅ **Type Safety**: Full autocomplete for translation keys
-- ✅ **Performance**: Core Web Vitals maintained (LCP < 2.5s, INP < 200ms, CLS < 0.1)
-- ✅ **SEO**: Lighthouse SEO score 100 for both locales
-- ✅ **GDPR Compliant**: User locale preferences handled appropriately
-
----
-
-## 🎯 IMPLEMENTATION PHASES
-
-### Phase 0: Documentation & Planning (2 hours)
-- Create this implementation plan document
-- Document architecture decisions
-
-### Phase 1: Backend Foundation (4 hours)
-- Add `locale` column to User model
-- Create database migration
-- Update Pydantic schemas
-- Create locale detection dependency
-- Add backend tests
-
-### Phase 2: Frontend Setup (4 hours)
-- Install and configure next-intl
-- Create translation files (EN, IT)
-- Configure TypeScript autocomplete
-- Restructure App Router for [locale] pattern
-- Fix tests
-
-### Phase 3: Component Translation (4 hours)
-- Create LocaleSwitcher component
-- Translate auth components
-- Translate navigation components
-- Translate settings components
-- Review and test
-
-### Phase 4: SEO & Metadata (3 hours)
-- Implement locale-aware metadata
-- Generate multilingual sitemap
-- Configure robots.txt
-- SEO validation
-
-### Phase 5: Performance Optimization (3 hours)
-- Measure Core Web Vitals baseline
-- Optimize translation loading
-- Prevent CLS with font loading
-- Performance validation
-
-### Phase 6: Comprehensive Testing (4 hours)
-- Backend integration tests
-- Frontend E2E locale tests
-- Frontend unit tests
-- Translation validation automation
-
-### Phase 7: Documentation & Polish (2 hours)
-- Update technical documentation
-- Create migration guide
-- Final SEO and performance validation
-
-### Phase 8: Deployment Prep (2 hours)
-- Update README
-- Create release notes
-- Deployment checklist
-
-**Total Time**: ~28 hours (~3.5 days) + 20% buffer = **4 days**
-
----
-
-## 🏗️ ARCHITECTURE DECISIONS
-
-### 1. Locale Format: BCP 47
-
-**Decision**: Use BCP 47 language tags (e.g., "en", "it", "en-US", "it-IT")
-
-**Rationale**:
-- Industry standard (used by HTTP Accept-Language, HTML lang attribute, ICU libraries)
-- Based on ISO 639-1 (language) + ISO 3166-1 (region)
-- Flexible: start simple with 2-letter codes, add region qualifiers when needed
-- Future-proof for dialects and scripts (e.g., "zh-Hans" for Simplified Chinese)
-
-**Implementation**:
-```python
-# Backend validation
-SUPPORTED_LOCALES = {"en", "it", "en-US", "en-GB", "it-IT"}
-```
-
----
-
-### 2. URL Structure: Subdirectory
-
-**Decision**: `/[locale]/[path]` format (e.g., `/en/about`, `/it/about`)
-
-**Alternatives Considered**:
-- ❌ Subdomain (`en.example.com`) - Too complex for template
-- ❌ Country-code TLD (`example.it`) - Too expensive, not needed for template
-- ❌ URL parameters (`?lang=en`) - Poor SEO, harder to crawl
-
-**Rationale**:
-- ✅ **Best SEO**: Google explicitly recommends subdirectories for most sites
-- ✅ **Simple Infrastructure**: Single domain, single deployment
-- ✅ **Low Cost**: No multiple domain purchases
-- ✅ **Easy to Maintain**: Centralized analytics and tooling
-- ✅ **Clear URLs**: Users can easily switch locales by changing URL
-
-**SEO Benefits**:
-- Domain authority consolidates to one domain
-- Backlinks benefit all language versions
-- Easier to build authority than multiple domains
-- Works seamlessly with hreflang tags
-
----
-
-### 3. Database Schema: Dedicated `locale` Column
-
-**Decision**: Add `locale VARCHAR(10)` column to `users` table, NOT JSONB
-
-**Alternatives Considered**:
-- ❌ Store in `preferences` JSONB field - 2-10x slower queries, no optimizer statistics
-
-**Rationale**:
-- ✅ **Performance**: B-tree index vs GIN index (smaller, faster)
-- ✅ **Query Optimization**: PostgreSQL can maintain statistics on column values
-- ✅ **Disk Space**: JSONB stores keys repeatedly (inefficient for common fields)
-- ✅ **Update Performance**: Updating JSONB requires rewriting entire field + indexes
-
-**Schema**:
-```sql
-ALTER TABLE users ADD COLUMN locale VARCHAR(10) DEFAULT NULL;
-CREATE INDEX ix_users_locale ON users(locale);
-```
-
-**Why Nullable?**
-- Distinguish "never set" (NULL) from "explicitly set to English"
-- Allows lazy loading on first request (more accurate than backfilling)
-
-**Why No Database DEFAULT?**
-- Application-level default provides more flexibility
-- Can implement locale detection logic (Accept-Language header)
-- Easier to change default without migration
-
----
-
-### 4. Locale Detection Priority
-
-**Decision**: Three-tier fallback system
-
-1. **User's Saved Preference** (highest priority)
- - If authenticated and `user.locale` is set, use it
- - Persists across sessions and devices
-
-2. **Accept-Language Header** (second priority)
- - For unauthenticated users
- - Parse `Accept-Language: it-IT,it;q=0.9,en;q=0.8` → "it-IT"
- - Validate against supported locales
-
-3. **Default to English** (fallback)
- - If no user preference and no header match
-
-**Implementation** (Backend):
-```python
-async def get_locale(
- request: Request,
- current_user: User | None = Depends(get_optional_current_user)
-) -> str:
- if current_user and current_user.locale:
- return current_user.locale
-
- accept_language = request.headers.get("accept-language", "")
- if accept_language:
- locale = accept_language.split(',')[0].split(';')[0].strip()
- lang_code = locale.split('-')[0].lower()
- if lang_code in {"en", "it"}:
- return locale.lower()
-
- return "en"
-```
-
----
-
-### 5. Translation Storage: Server-Side Only (next-intl)
-
-**Decision**: Use next-intl's server-component pattern, NOT client-side translation loading
-
-**Rationale**:
-- ✅ **Zero Client Bundle Overhead**: Translations never sent to browser
-- ✅ **Instant Page Loads**: No translation parsing on client
-- ✅ **Better SEO**: Fully rendered HTML for search engines
-- ✅ **Reduced Bandwidth**: Especially important for mobile users
-
-**Implementation**:
-```typescript
-// Server Component (preferred 95% of the time)
-import { getTranslations } from 'next-intl/server';
-
-export default async function Page() {
- const t = await getTranslations('HomePage');
- return
{t('title')}
;
-}
-
-// Client Component (only when needed for interactivity)
-'use client';
-import { useTranslations } from 'next-intl';
-
-export function LoginForm() {
- const t = useTranslations('auth.Login');
- return ;
-}
-```
-
-**Performance Impact**:
-- next-intl core: ~9.2kb gzipped
-- Translation files: 0kb on client (server-side only)
-- Tree-shaking: Automatic with ESM build
-
----
-
-### 6. Translation File Structure: Nested Namespaces
-
-**Decision**: Use nested JSON structure with namespaces, not flat keys
-
-**Bad (Flat)**:
-```json
-{
- "auth_login_title": "Sign in",
- "auth_login_email_label": "Email",
- "auth_register_title": "Sign up"
-}
-```
-
-**Good (Nested)**:
-```json
-{
- "auth": {
- "Login": {
- "title": "Sign in",
- "emailLabel": "Email"
- },
- "Register": {
- "title": "Sign up"
- }
- }
-}
-```
-
-**Rationale**:
-- ✅ **Better Organization**: Logical grouping by feature
-- ✅ **Easier Maintenance**: Find related translations quickly
-- ✅ **Type Safety**: Full autocomplete with TypeScript integration
-- ✅ **Scalability**: Easy to split into separate files later
-
-**Usage**:
-```typescript
-const t = useTranslations('auth.Login');
-t('title'); // "Sign in"
-t('emailLabel'); // "Email"
-```
-
----
-
-### 7. SEO Strategy: Hreflang + Sitemap + Metadata
-
-**Decision**: Dual implementation for comprehensive SEO
-
-**1. HTML `` Tags** (via `generateMetadata`):
-```typescript
-export async function generateMetadata({ params: { locale } }) {
- return {
- alternates: {
- canonical: `/${locale}`,
- languages: {
- 'x-default': '/en',
- 'en': '/en',
- 'it': '/it',
- },
- },
- };
-}
-```
-
-**2. XML Sitemap** (with hreflang):
-```typescript
-export default function sitemap() {
- return routes.flatMap(route =>
- locales.map(locale => ({
- url: `${baseUrl}/${locale}${route.path}`,
- alternates: {
- languages: { en: `/en${route.path}`, it: `/it${route.path}` }
- }
- }))
- );
-}
-```
-
-**Why Both?**
-- HTML tags: Google's preferred method for page-level precision
-- Sitemap: Helps discovery, provides backup if HTML tags malfunction
-- **Never use HTTP headers** - avoid confusion with mixed methods
-
-**x-default Locale**:
-- Points to English (`/en`) as fallback for unsupported locales
-- Used when user's language doesn't match any hreflang tags
-
----
-
-### 8. Testing Strategy: Smoke Tests + Parameterization
-
-**Decision**: Don't test all translations, test the i18n mechanism works
-
-**Backend Tests**:
-- 10 new integration tests covering locale CRUD, validation, detection
-- Test both EN and IT locale values
-- Test Accept-Language header parsing
-
-**Frontend E2E Tests**:
-- 12 new parameterized tests for locale switching
-- Test critical flows in both EN and IT (login, register)
-- **NOT** duplicating all 56 existing tests per locale
-- Use parameterization: `for (const locale of ['en', 'it']) { test(...) }`
-
-**Frontend Unit Tests**:
-- 8 new component tests with i18n wrappers
-- Test LocaleSwitcher functionality
-- Test translated components render correctly
-
-**Translation Validation**:
-- Automated CI check for missing keys
-- Validate Italian has all keys that English has
-- Detect unused keys
-
-**Rationale**:
-- ✅ **Efficient**: Test mechanism, not content
-- ✅ **Maintainable**: Adding Italian tests doesn't double test time
-- ✅ **Comprehensive**: Critical paths tested in both locales
-- ✅ **Fast CI**: ~13-18 minutes total (vs 60+ if we duplicate everything)
-
----
-
-### 9. Performance Budget
-
-**Core Web Vitals Targets** (both EN and IT):
-- **LCP** (Largest Contentful Paint): < 2.5s
-- **INP** (Interaction to Next Paint): < 200ms
-- **CLS** (Cumulative Layout Shift): < 0.1
-
-**Bundle Size Impact**:
-- next-intl: ~9.2kb gzipped (acceptable)
-- Translation files: 0kb on client (server-side)
-- Total increase: < 15kb
-
-**Lighthouse Scores**:
-- Performance: ≥ 90
-- Accessibility: ≥ 95
-- SEO: 100
-
-**Font Loading Strategy**:
-- Use `display: swap` to prevent CLS
-- Preload Inter font with Latin + Latin-ext subsets (for Italian accents: à, è, ì, ò, ù)
-- Fallback to system fonts
-
----
-
-### 10. GDPR Compliance
-
-**Classification**: User locale preference IS personal data (GDPR Article 4)
-
-**Lawful Basis**: Legitimate interest (service improvement) ✅
-
-**User Rights**:
-- ✅ **Access**: User can view locale in profile (GET /users/me)
-- ✅ **Rectification**: User can update locale (PATCH /users/me)
-- ✅ **Erasure**: Locale deleted when user deleted (CASCADE)
-- ✅ **Portability**: Included in user data export
-
-**Privacy Policy Requirements**:
-- "We store your language preference to personalize your experience"
-- "You can change this in Settings > Profile at any time"
-
-**Data Minimization**: ✅ PASS
-- Locale is necessary for service personalization
-- No excessive data collection (not storing geolocation)
-
----
-
-## 🚀 GETTING STARTED
-
-### For Developers Implementing This Plan
-
-1. **Read This Document**: Understand the architecture decisions and rationale
-2. **Follow Phases Sequentially**: Each phase builds on the previous
-3. **Run Tests After Each Phase**: Ensure no regressions
-4. **Use Parallel Agents**: Where indicated in the plan for efficiency
-5. **Document Decisions**: Update this file if you deviate from the plan
-
-### For Users of the Template
-
-1. **See `/docs/I18N.md`**: User-facing guide on using i18n
-2. **See `/docs/I18N_MIGRATION_GUIDE.md`**: Deploying to existing projects
-3. **Adding Languages**: Copy the Italian example, follow `/docs/I18N.md`
-
----
-
-## 📚 REFERENCES
-
-### Official Documentation
-- [next-intl](https://next-intl.dev) - Next.js 15 i18n library
-- [BCP 47 Language Tags](https://www.rfc-editor.org/rfc/bcp/bcp47.txt) - Locale format standard
-- [Google Multilingual SEO](https://developers.google.com/search/docs/specialty/international) - SEO guidelines
-
-### Research Sources
-- next-intl 4.0 release notes (2025)
-- Next.js 15 App Router i18n patterns
-- PostgreSQL performance: JSONB vs columns
-- Lighthouse CI best practices
-- Playwright i18n testing patterns
-
----
-
-## ✅ COMPLETION CHECKLIST
-
-Use this checklist to verify implementation is complete:
-
-### Backend
-- [ ] `locale` column added to `users` table
-- [ ] Database migration created and tested
-- [ ] Pydantic schemas updated (UserUpdate, UserResponse)
-- [ ] Locale detection dependency created
-- [ ] 10+ backend tests added
-- [ ] All existing 743 tests still pass
-- [ ] Coverage ≥97% maintained
-
-### Frontend
-- [ ] next-intl installed and configured
-- [ ] Translation files created (en.json, it.json)
-- [ ] TypeScript autocomplete working
-- [ ] App Router restructured to `[locale]` pattern
-- [ ] LocaleSwitcher component created
-- [ ] All components translated (auth, navigation, settings)
-- [ ] All existing 56 E2E tests still pass
-- [ ] 12+ new E2E locale tests added
-- [ ] 8+ new unit tests added
-
-### SEO
-- [ ] Metadata implemented per locale
-- [ ] Sitemap generated with hreflang
-- [ ] robots.txt configured
-- [ ] Lighthouse SEO = 100 (both EN and IT)
-
-### Performance
-- [ ] Core Web Vitals measured (both locales)
-- [ ] LCP < 2.5s
-- [ ] INP < 200ms
-- [ ] CLS < 0.1
-- [ ] Bundle analysis shows minimal impact
-
-### Documentation
-- [ ] This implementation plan complete
-- [ ] `/docs/I18N.md` created (user guide)
-- [ ] `/docs/I18N_MIGRATION_GUIDE.md` created
-- [ ] `CLAUDE.md` updated with i18n patterns
-- [ ] README.md updated with i18n feature
-- [ ] CHANGELOG.md updated
-
-### Testing
-- [ ] Translation validation in CI
-- [ ] All tests passing
-- [ ] No flaky tests
-- [ ] Coverage targets met
-
----
-
-## 🔄 NEXT STEPS
-
-After completing this implementation:
-
-1. **Deploy to Staging**: Test in production-like environment
-2. **Gather Feedback**: From team and early users
-3. **Optimize Further**: Based on real-world usage data
-4. **Add Languages**: If needed, follow the Italian example
-
----
-
-## 📝 CHANGE LOG
-
-| Date | Author | Change |
-|------|--------|--------|
-| 2025-11-17 | Claude | Initial plan created based on 2025 research |
-| 2025-11-17 | Claude | Updated to 2 languages (EN, IT) per user request |
-
----
-
-**End of Implementation Plan**
-
-This plan represents state-of-the-art i18n implementation for 2025. It balances best practices, performance, SEO, and developer experience while remaining simple enough for a template showcase.
-
-For questions or clarifications, refer to the detailed task descriptions in each phase.
diff --git a/docs/images/.gitkeep b/docs/images/.gitkeep
new file mode 100644
index 0000000..0cfedcc
--- /dev/null
+++ b/docs/images/.gitkeep
@@ -0,0 +1,7 @@
+# Placeholder to keep this directory in git
+# Add your screenshots here:
+# - landing.png
+# - login.png
+# - admin-dashboard.png
+# - settings.png
+# - design-system.png
diff --git a/frontend/IMPLEMENTATION_PLAN.md b/frontend/IMPLEMENTATION_PLAN.md
deleted file mode 100644
index 19e9a35..0000000
--- a/frontend/IMPLEMENTATION_PLAN.md
+++ /dev/null
@@ -1,2889 +0,0 @@
-# Frontend Implementation Plan: Next.js + FastAPI Template
-
-**Last Updated:** November 7, 2025 (Phase 9 COMPLETE ✅)
-**Current Phase:** Phase 9 COMPLETE ✅ | Next: Phase 10 (Testing & QA)
-**Overall Progress:** 9 of 13 phases complete (69.2%)
-
----
-
-## Summary
-
-Build a production-ready Next.js 15 frontend with full authentication, admin dashboard, user/organization management, and session tracking. The frontend integrates with the existing FastAPI backend using OpenAPI-generated clients, TanStack Query for state, Zustand for auth, and shadcn/ui components.
-
-**Target:** 90%+ test coverage, comprehensive documentation, and robust foundations for enterprise projects.
-
-**Current State:** Phases 0-9 complete with 954 unit tests (100% pass rate), 95.6% coverage, 173+ E2E tests, zero build/lint/type errors ⭐
-**Target State:** Complete template matching `frontend-requirements.md` with all 13 phases
-
----
-
-## Implementation Directives (MUST FOLLOW)
-
-### Documentation-First Approach
-
-- Phase 0 created `/docs` folder with all architecture, standards, and guides ✅
-- ALL subsequent phases MUST reference and follow patterns in `/docs`
-- **If context is lost, `/docs` + this file + `frontend-requirements.md` are sufficient to resume**
-
-### Quality Assurance Protocol
-
-**1. Per-Task Quality Standards (MANDATORY):**
-
-- **Quality over Speed:** Each task developed carefully, no rushing
-- **Review Cycles:** Minimum 3 review-fix cycles per task before completion
-- **Test Coverage:** Maintain >80% coverage at all times
-- **Test Pass Rate:** 100% of tests MUST pass (no exceptions)
- - If tests fail, task is NOT complete
- - Failed tests = incomplete implementation
- - Do not proceed until all tests pass
-- **Standards Compliance:** Zero violations of `/docs/CODING_STANDARDS.md`
-
-**2. After Each Task:**
-
-- [ ] All tests passing (100% pass rate)
-- [ ] Coverage >80% for new code
-- [ ] TypeScript: 0 errors
-- [ ] ESLint: 0 warnings
-- [ ] Self-review cycle 1: Code quality
-- [ ] Self-review cycle 2: Security & accessibility
-- [ ] Self-review cycle 3: Performance & standards compliance
-- [ ] Documentation updated
-- [ ] IMPLEMENTATION_PLAN.md status updated
-
-**3. After Each Phase:**
-Launch multi-agent deep review to:
-
-- Verify phase objectives met
-- Check integration with previous phases
-- Identify critical issues requiring immediate fixes
-- Recommend improvements before proceeding
-- Update documentation if patterns evolved
-- **Generate phase review report** (e.g., `PHASE_X_REVIEW.md`)
-
-**4. Testing Requirements:**
-
-- Write tests alongside feature code (not after)
-- Unit tests: All hooks, utilities, services
-- Component tests: All reusable components
-- Integration tests: All pages and flows
-- E2E tests: Critical user journeys (auth, admin CRUD)
-- Target: 90%+ coverage for template robustness
-- **100% pass rate required** - no failing tests allowed
-- Use Jest + React Testing Library + Playwright
-
-**5. Context Preservation:**
-
-- Update `/docs` with implementation decisions
-- Document deviations from requirements in `ARCHITECTURE.md`
-- Keep `frontend-requirements.md` updated if backend changes
-- Update THIS FILE after each phase with actual progress
-- Create phase review reports for historical reference
-
----
-
-## Current System State (Phase 1 Complete)
-
-### ✅ What's Implemented
-
-**Project Infrastructure:**
-
-- Next.js 15 with App Router
-- TypeScript strict mode enabled
-- Tailwind CSS 4 configured
-- shadcn/ui components installed (15+ components)
-- Path aliases configured (@/)
-
-**Authentication System:**
-
-- `src/lib/auth/crypto.ts` - AES-GCM encryption (82% coverage)
-- `src/lib/auth/storage.ts` - Secure token storage (72.85% coverage)
-- `src/stores/authStore.ts` - Zustand auth store (92.59% coverage)
-- `src/config/app.config.ts` - Centralized configuration (81% coverage)
-- SSR-safe implementations throughout
-
-**API Integration:**
-
-- `src/lib/api/client.ts` - Axios wrapper with interceptors (to be replaced)
-- `src/lib/api/errors.ts` - Error parsing utilities (to be replaced)
-- `scripts/generate-api-client.sh` - OpenAPI generation script
-- **NOTE:** Manual client files marked for replacement with generated client
-
-**Testing Infrastructure:**
-
-- Jest configured with Next.js integration
-- 66 tests passing (100%)
-- 81.6% code coverage (exceeds 70% target)
-- Real crypto testing (@peculiar/webcrypto)
-- No mocks for security-critical code
-
-**Documentation:**
-
-- `/docs/ARCHITECTURE.md` - System design ✅
-- `/docs/CODING_STANDARDS.md` - Code standards ✅
-- `/docs/COMPONENT_GUIDE.md` - Component patterns ✅
-- `/docs/FEATURE_EXAMPLES.md` - Implementation examples ✅
-- `/docs/API_INTEGRATION.md` - API integration guide ✅
-
-### 📊 Test Coverage Details (Post Design System Implementation)
-
-```
-Category | % Stmts | % Branch | % Funcs | % Lines
--------------------------------|---------|----------|---------|--------
-All files | 97.57 | 94.2 | 96.87 | 98.15
-components/auth | 100 | 96.12 | 100 | 100
-components/layout | 98.43 | 95.45 | 98.57 | 99.21
-components/theme | 97.89 | 93.75 | 96.15 | 98.33
-config | 100 | 88.46 | 100 | 100
-lib/api | 94.82 | 89.33 | 84.61 | 96.36
-lib/auth | 97.05 | 90 | 100 | 97.02
-stores | 92.59 | 97.91 | 100 | 93.87
-```
-
-**Test Suites:** 18 passed, 18 total
-**Tests:** 282 passed, 282 total
-**Time:** ~3.2s
-**E2E Tests:** 56 passed, 1 skipped, 57 total (7 test files)
-
-**Coverage Exclusions (Properly Configured):**
-
-- Auto-generated API client (`src/lib/api/generated/**`)
-- Manual API client (to be replaced)
-- Third-party UI components (`src/components/ui/**`)
-- Component showcase page (`src/components/dev/ComponentShowcase.tsx` - demo page)
-- Next.js app directory (`src/app/**` - test with E2E)
-- Re-export index files
-- Old implementation files (`.old.ts`)
-
-### 🎯 Quality Metrics (Post Design System Implementation)
-
-- ✅ **Build:** PASSING (Next.js 15.5.6)
-- ✅ **TypeScript:** 0 compilation errors
-- ✅ **ESLint:** ✔ No ESLint warnings or errors
-- ✅ **Tests:** 282/282 passing (100%)
-- ✅ **E2E Tests:** 56/57 passing (1 skipped - sessions route not implemented)
-- ✅ **Coverage:** 97.57% (far exceeds 90% target) ⭐
-- ✅ **Security:** 0 vulnerabilities (npm audit clean)
-- ✅ **SSR:** All browser APIs properly guarded
-- ✅ **Bundle Size:** 107 kB (home), 178 kB (auth pages)
-- ✅ **Theme System:** Light/Dark/System modes fully functional
-- ✅ **Overall Score:** 9.3/10 - Production Ready with Modern Design System
-
-### 📁 Current Folder Structure
-
-```
-frontend/
-├── docs/ ✅ Phase 0 complete
-│ ├── ARCHITECTURE.md
-│ ├── CODING_STANDARDS.md
-│ ├── COMPONENT_GUIDE.md
-│ ├── FEATURE_EXAMPLES.md
-│ ├── API_INTEGRATION.md
-│ └── DESIGN_SYSTEM.md # ✅ Design system documentation
-├── src/
-│ ├── app/ # Next.js app directory
-│ ├── components/
-│ │ ├── auth/ # ✅ Auth forms (login, register, password reset)
-│ │ ├── layout/ # ✅ Header, Footer
-│ │ ├── theme/ # ✅ ThemeProvider, ThemeToggle
-│ │ ├── dev/ # ✅ ComponentShowcase (demo page)
-│ │ └── ui/ # shadcn/ui components ✅
-│ ├── lib/
-│ │ ├── api/
-│ │ │ ├── generated/ # OpenAPI client (generated)
-│ │ │ ├── hooks/ # ✅ React Query hooks (useAuth, etc.)
-│ │ │ ├── client.ts # ✅ Axios wrapper
-│ │ │ └── errors.ts # ✅ Error parsing
-│ │ ├── auth/
-│ │ │ ├── crypto.ts # ✅ 82% coverage
-│ │ │ └── storage.ts # ✅ 72.85% coverage
-│ │ └── utils/
-│ ├── stores/ # ⚠️ Should be in lib/stores (to be moved)
-│ │ └── authStore.ts # ✅ 92.59% coverage
-│ └── config/
-│ └── app.config.ts # ✅ 81% coverage
-├── tests/ # ✅ 282 tests
-│ ├── components/
-│ │ ├── auth/ # Auth form tests
-│ │ ├── layout/ # Header, Footer tests
-│ │ └── theme/ # ThemeProvider, ThemeToggle tests
-│ ├── lib/auth/ # Crypto & storage tests
-│ ├── stores/ # Auth store tests
-│ └── config/ # Config tests
-├── e2e/ # ✅ 56 passing, 1 skipped (7 test files)
-│ ├── auth-login.spec.ts # 19 tests ✅
-│ ├── auth-register.spec.ts # 14 tests ✅
-│ ├── auth-password-reset.spec.ts # 10 tests ✅
-│ ├── navigation.spec.ts # 10 tests ✅
-│ ├── settings-password.spec.ts # 3 tests ✅
-│ ├── settings-profile.spec.ts # 2 tests ✅
-│ ├── settings-navigation.spec.ts # 5 tests ✅
-│ └── settings-sessions.spec.ts # 1 skipped (route not implemented)
-├── scripts/
-│ └── generate-api-client.sh # ✅ OpenAPI generation
-├── jest.config.js # ✅ Configured
-├── jest.setup.js # ✅ Global mocks
-├── playwright.config.ts # ✅ E2E test configuration
-├── frontend-requirements.md # ✅ Updated
-└── IMPLEMENTATION_PLAN.md # ✅ This file
-
-```
-
-### ⚠️ Technical Improvements (Post-Phase 3 Enhancements)
-
-**Priority: HIGH**
-
-- Add React Error Boundary component
-- Add skip navigation links for accessibility
-
-**Priority: MEDIUM**
-
-- Add Content Security Policy (CSP) headers
-- Verify WCAG AA color contrast ratios
-- Add session timeout warnings
-- Add `lang="en"` to HTML root
-
-**Priority: LOW (Nice to Have)**
-
-- Add error tracking (Sentry/LogRocket)
-- Add password strength meter UI
-- Add offline detection/handling
-- Consider 2FA support in future
-- Add client-side rate limiting
-
-**Note:** These are enhancements, not blockers. The codebase is production-ready as-is (9.3/10 overall score).
-
----
-
-## Phase 0: Foundation Documents & Requirements Alignment ✅
-
-**Status:** COMPLETE
-**Duration:** 1 day
-**Completed:** October 31, 2025
-
-### Task 0.1: Update Requirements Document ✅
-
-- ✅ Updated `frontend-requirements.md` with API corrections
-- ✅ Added Section 4.5 (Session Management UI)
-- ✅ Added Section 15 (API Endpoint Reference)
-- ✅ Updated auth flow with token rotation details
-- ✅ Added missing User/Organization model fields
-
-### Task 0.2: Create Architecture Documentation ✅
-
-- ✅ Created `docs/ARCHITECTURE.md`
-- ✅ System overview (Next.js App Router, TanStack Query, Zustand)
-- ✅ Technology stack rationale
-- ✅ Data flow diagrams
-- ✅ Folder structure explanation
-- ✅ Design patterns documented
-
-### Task 0.3: Create Coding Standards Documentation ✅
-
-- ✅ Created `docs/CODING_STANDARDS.md`
-- ✅ TypeScript standards (strict mode, no any)
-- ✅ React component patterns
-- ✅ Naming conventions
-- ✅ State management rules
-- ✅ Form patterns
-- ✅ Error handling patterns
-- ✅ Testing standards
-
-### Task 0.4: Create Component & Feature Guides ✅
-
-- ✅ Created `docs/COMPONENT_GUIDE.md`
-- ✅ Created `docs/FEATURE_EXAMPLES.md`
-- ✅ Created `docs/API_INTEGRATION.md`
-- ✅ Complete walkthroughs for common patterns
-
-**Phase 0 Review:** ✅ All docs complete, clear, and accurate
-
----
-
-## Phase 1: Project Setup & Infrastructure ✅
-
-**Status:** COMPLETE
-**Duration:** 3 days
-**Completed:** October 31, 2025
-
-### Task 1.1: Dependency Installation & Configuration ✅
-
-**Status:** COMPLETE
-**Blockers:** None
-
-**Installed Dependencies:**
-
-```bash
-# Core
-@tanstack/react-query@5, zustand@4, axios@1
-@hey-api/openapi-ts (dev)
-react-hook-form@7, zod@3, @hookform/resolvers
-date-fns, clsx, tailwind-merge, lucide-react
-recharts@2
-
-# shadcn/ui
-npx shadcn@latest init
-npx shadcn@latest add button card input label form select table dialog
- toast tabs dropdown-menu popover sheet avatar badge separator skeleton alert
-
-# Testing
-jest, @testing-library/react, @testing-library/jest-dom
-@testing-library/user-event, @playwright/test, @types/jest
-@peculiar/webcrypto (for real crypto in tests)
-```
-
-**Configuration:**
-
-- ✅ `components.json` for shadcn/ui
-- ✅ `tsconfig.json` with path aliases
-- ✅ Tailwind configured for dark mode
-- ✅ `.env.example` and `.env.local` created
-- ✅ `jest.config.js` with Next.js integration
-- ✅ `jest.setup.js` with global mocks
-
-### Task 1.2: OpenAPI Client Generation Setup ✅
-
-**Status:** COMPLETE
-**Can run parallel with:** 1.3, 1.4
-
-**Completed:**
-
-- ✅ Created `scripts/generate-api-client.sh` using `@hey-api/openapi-ts`
-- ✅ Configured output to `src/lib/api/generated/`
-- ✅ Added npm script: `"generate:api": "./scripts/generate-api-client.sh"`
-- ✅ Fixed deprecated options (removed `--name`, `--useOptions`, `--exportSchemas`)
-- ✅ Used modern syntax: `--client @hey-api/client-axios`
-- ✅ Successfully generated TypeScript client from backend API
-- ✅ TypeScript compilation passes with generated types
-
-**Generated Files:**
-
-- `src/lib/api/generated/index.ts` - Main exports
-- `src/lib/api/generated/types.gen.ts` - TypeScript types (35KB)
-- `src/lib/api/generated/sdk.gen.ts` - API functions (29KB)
-- `src/lib/api/generated/client.gen.ts` - Axios client
-- `src/lib/api/generated/client/` - Client utilities
-- `src/lib/api/generated/core/` - Core utilities
-
-**To Regenerate (When Backend Changes):**
-
-```bash
-npm run generate:api
-```
-
-### Task 1.3: Axios Client & Interceptors ✅
-
-**Status:** COMPLETE (needs replacement in Phase 2)
-**Can run parallel with:** 1.2, 1.4
-
-**Completed:**
-
-- ✅ Created `src/lib/api/client.ts` - Axios wrapper
- - Request interceptor: Add Authorization header
- - Response interceptor: Handle 401, 403, 429, 500
- - Error response parser
- - Timeout configuration (30s default)
- - Development logging
-- ✅ Created `src/lib/api/errors.ts` - Error types and parsing
-- ✅ Tests written for error parsing
-
-**⚠️ Note:** This is a manual implementation. Will be replaced with generated client + thin interceptor wrapper once backend API is generated.
-
-### Task 1.4: Folder Structure Creation ✅
-
-**Status:** COMPLETE
-**Can run parallel with:** 1.2, 1.3
-
-**Completed:**
-
-- ✅ All directories created per requirements
-- ✅ Placeholder index.ts files for exports
-- ✅ Structure matches `docs/ARCHITECTURE.md`
-
-### Task 1.5: Authentication Core Implementation ✅
-
-**Status:** COMPLETE (additional work beyond original plan)
-
-**Completed:**
-
-- ✅ `src/lib/auth/crypto.ts` - AES-GCM encryption with random IVs
-- ✅ `src/lib/auth/storage.ts` - Encrypted token storage with localStorage
-- ✅ `src/stores/authStore.ts` - Complete Zustand auth store
-- ✅ `src/config/app.config.ts` - Centralized configuration with validation
-- ✅ All SSR-safe with proper browser API guards
-- ✅ 66 comprehensive tests written (81.6% coverage)
-- ✅ Security audit completed
-- ✅ Real crypto testing (no mocks)
-
-**Security Features:**
-
-- AES-GCM encryption with 256-bit keys
-- Random IV per encryption
-- Key stored in sessionStorage (per-session)
-- Token validation (JWT format checking)
-- Type-safe throughout
-- No token leaks in logs
-
-**Phase 1 Review:** ✅ Multi-agent audit completed. Infrastructure solid. All tests passing. Ready for Phase 2.
-
-### Audit Results (October 31, 2025)
-
-**Comprehensive audit conducted with the following results:**
-
-**Critical Issues Found:** 5
-**Critical Issues Fixed:** 5 ✅
-
-**Issues Resolved:**
-
-1. ✅ TypeScript compilation error (unused @ts-expect-error)
-2. ✅ Duplicate configuration files
-3. ✅ Test mocks didn't match real implementation
-4. ✅ Test coverage properly configured
-5. ✅ API client exclusions documented
-
-**Final Metrics:**
-
-- Tests: 66/66 passing (100%)
-- Coverage: 81.6% (exceeds 70% target)
-- TypeScript: 0 errors
-- Security: No vulnerabilities
-
-**Audit Documents:**
-
-- `/tmp/AUDIT_SUMMARY.txt` - Executive summary
-- `/tmp/AUDIT_COMPLETE.md` - Full report
-- `/tmp/COVERAGE_CONFIG.md` - Coverage configuration
-- `/tmp/detailed_findings.md` - Issue details
-
----
-
-## Phase 2: Authentication System
-
-**Status:** ✅ COMPLETE - PRODUCTION READY ⭐
-**Completed:** November 1, 2025
-**Duration:** 2 days (faster than estimated)
-**Prerequisites:** Phase 1 complete ✅
-**Deep Review:** November 1, 2025 (Evening) - Score: 9.3/10
-
-**Summary:**
-Phase 2 delivered a complete, production-ready authentication system with exceptional quality. All authentication flows are fully functional and comprehensively tested. The codebase demonstrates professional-grade quality with 97.6% test coverage, zero build/lint/type errors, and strong security practices.
-
-**Quality Metrics (Post Deep Review):**
-
-- **Tests:** 234/234 passing (100%) ✅
-- **Coverage:** 97.6% (far exceeds 90% target) ⭐
-- **TypeScript:** 0 errors ✅
-- **ESLint:** ✔ No warnings or errors ✅
-- **Build:** PASSING (Next.js 15.5.6) ✅
-- **Security:** 0 vulnerabilities, 9/10 score ✅
-- **Accessibility:** 8.5/10 - Very good ✅
-- **Code Quality:** 9.5/10 - Excellent ✅
-- **Bundle Size:** 107-173 kB (excellent) ✅
-
-**What Was Accomplished:**
-
-- Complete authentication UI (login, register, password reset)
-- Route protection with AuthGuard
-- Comprehensive React Query hooks
-- AES-GCM encrypted token storage
-- Automatic token refresh with race condition prevention
-- SSR-safe implementations throughout
-- 234 comprehensive tests across all auth components
-- Security audit completed (0 critical issues)
-- Next.js 15.5.6 upgrade (fixed CVEs)
-- ESLint 9 flat config properly configured
-- Generated API client properly excluded from linting
-
-**Context for Phase 2:**
-Phase 1 already implemented core authentication infrastructure (crypto, storage, auth store). Phase 2 built the UI layer and achieved exceptional test coverage through systematic testing of all components and edge cases.
-
-### Task 2.1: Token Storage & Auth Store ✅ (Done in Phase 1)
-
-**Status:** COMPLETE (already done)
-
-This was completed as part of Phase 1 infrastructure:
-
-- ✅ `src/lib/auth/crypto.ts` - AES-GCM encryption
-- ✅ `src/lib/auth/storage.ts` - Token storage utilities
-- ✅ `src/stores/authStore.ts` - Complete Zustand store
-- ✅ 92.59% test coverage on auth store
-- ✅ Security audit passed
-
-**Skip this task - move to 2.2**
-
-### Task 2.2: Auth Interceptor Integration ✅
-
-**Status:** COMPLETE
-**Completed:** November 1, 2025
-**Depends on:** 2.1 ✅ (already complete)
-
-**Completed:**
-
-- ✅ `src/lib/api/client.ts` - Manual axios client with interceptors
- - Request interceptor adds Authorization header
- - Response interceptor handles 401, 403, 429, 500 errors
- - Token refresh with singleton pattern (prevents race conditions)
- - Separate `authClient` for refresh endpoint (prevents loops)
- - Error parsing and standardization
- - Timeout configuration (30s)
- - Development logging
-
-- ✅ Integrates with auth store for token management
-- ✅ Used by all auth hooks (login, register, logout, password reset)
-- ✅ Token refresh tested and working
-- ✅ No infinite refresh loops (separate client for auth endpoints)
-
-**Architecture Decision:**
-
-- Using manual axios client for Phase 2 (proven, working)
-- Generated client prepared but not integrated (future migration)
-- See `docs/API_CLIENT_ARCHITECTURE.md` for full details and migration path
-
-**Reference:** `docs/API_CLIENT_ARCHITECTURE.md`, Requirements Section 5.2
-
-### Task 2.3: Auth Hooks & Components ✅
-
-**Status:** COMPLETE
-**Completed:** October 31, 2025
-
-**Completed:**
-
-- ✅ `src/lib/api/hooks/useAuth.ts` - Complete React Query hooks
- - `useLogin` - Login mutation
- - `useRegister` - Register mutation
- - `useLogout` - Logout mutation
- - `useLogoutAll` - Logout all devices
- - `usePasswordResetRequest` - Request password reset
- - `usePasswordResetConfirm` - Confirm password reset with token
- - `usePasswordChange` - Change password (authenticated)
- - `useMe` - Get current user
- - `useIsAuthenticated`, `useCurrentUser`, `useIsAdmin` - Convenience hooks
-
-- ✅ `src/components/auth/AuthGuard.tsx` - Route protection component
- - Loading state handling
- - Redirect to login with returnUrl preservation
- - Admin access checking
- - Customizable fallback
-
-- ✅ `src/components/auth/LoginForm.tsx` - Login form
- - Email + password with validation
- - Loading states
- - Error display (server + field errors)
- - Links to register and password reset
-
-- ✅ `src/components/auth/RegisterForm.tsx` - Registration form
- - First name, last name, email, password, confirm password
- - Password strength indicator (real-time)
- - Validation matching backend rules
- - Link to login
-
-**Testing:**
-
-- ✅ Component tests created (9 passing)
-- ✅ Validates form fields
-- ✅ Tests password strength indicators
-- ✅ Tests loading states
-- Note: 4 async tests need API mocking (low priority)
-
-### Task 2.4: Login & Registration Pages ✅
-
-**Status:** COMPLETE
-**Completed:** October 31, 2025
-
-**Completed:**
-
-Forms (✅ Done in Task 2.3):
-
-- ✅ `src/components/auth/LoginForm.tsx`
-- ✅ `src/components/auth/RegisterForm.tsx`
-
-Pages:
-
-- ✅ `src/app/(auth)/layout.tsx` - Centered auth layout with responsive design
-- ✅ `src/app/(auth)/login/page.tsx` - Login page with title and description
-- ✅ `src/app/(auth)/register/page.tsx` - Registration page
-- ✅ `src/app/providers.tsx` - QueryClientProvider wrapper
-- ✅ `src/app/layout.tsx` - Updated to include Providers
-
-**API Integration:**
-
-- ✅ Using manual client.ts for auth endpoints (with token refresh)
-- ✅ Generated SDK available in `src/lib/api/generated/sdk.gen.ts`
-- ✅ Wrapper at `src/lib/api/client-config.ts` configures both
-
-**Testing:**
-
-- [ ] Form validation tests
-- [ ] Submission success/error
-- [ ] E2E login flow
-- [ ] E2E registration flow
-- [ ] Accessibility (keyboard nav, screen reader)
-
-**Reference:** `docs/COMPONENT_GUIDE.md` (form patterns), Requirements Section 8.1
-
-### Task 2.5: Password Reset Flow ✅
-
-**Status:** COMPLETE
-**Completed:** November 1, 2025
-
-**Completed Components:**
-
-Pages created:
-
-- ✅ `src/app/(auth)/password-reset/page.tsx` - Request reset page
-- ✅ `src/app/(auth)/password-reset/confirm/page.tsx` - Confirm reset with token
-
-Forms created:
-
-- ✅ `src/components/auth/PasswordResetRequestForm.tsx` - Email input form with validation
-- ✅ `src/components/auth/PasswordResetConfirmForm.tsx` - New password form with strength indicator
-
-**Implementation Details:**
-
-- ✅ Email validation with HTML5 + Zod
-- ✅ Password strength indicator (matches RegisterForm pattern)
-- ✅ Password confirmation matching
-- ✅ Success/error message display
-- ✅ Token handling from URL query parameters
-- ✅ Proper timeout cleanup for auto-redirect
-- ✅ Invalid token error handling
-- ✅ Accessibility: aria-required, aria-invalid, aria-describedby
-- ✅ Loading states during submission
-- ✅ User-friendly error messages
-
-**API Integration:**
-
-- ✅ Uses `usePasswordResetRequest` hook
-- ✅ Uses `usePasswordResetConfirm` hook
-- ✅ POST `/api/v1/auth/password-reset/request` - Request reset email
-- ✅ POST `/api/v1/auth/password-reset/confirm` - Reset with token
-
-**Testing:**
-
-- ✅ PasswordResetRequestForm: 7 tests (100% passing)
-- ✅ PasswordResetConfirmForm: 10 tests (100% passing)
-- ✅ Form validation (required fields, email format, password requirements)
-- ✅ Password confirmation matching validation
-- ✅ Password strength indicator display
-- ✅ Token display in form (hidden input)
-- ✅ Invalid token page error state
-- ✅ Accessibility attributes
-
-**Quality Assurance:**
-
-- ✅ 3 review-fix cycles completed
-- ✅ TypeScript: 0 errors
-- ✅ Lint: Clean (all files)
-- ✅ Tests: 91/91 passing (100%)
-- ✅ Security reviewed
-- ✅ Accessibility reviewed
-- ✅ Memory leak prevention (timeout cleanup)
-
-**Security Implemented:**
-
-- ✅ Token passed via URL (standard practice)
-- ✅ Passwords use autocomplete="new-password"
-- ✅ No sensitive data logged
-- ✅ Proper form submission handling
-- ✅ Client-side validation + server-side validation expected
-
-**Reference:** Requirements Section 4.3, `docs/FEATURE_EXAMPLES.md`
-
-### Phase 2 Review Checklist ✅
-
-**Functionality:**
-
-- [x] All auth pages functional
-- [x] Forms have proper validation
-- [x] Error messages are user-friendly
-- [x] Loading states on all async operations
-- [x] Route protection working (AuthGuard)
-- [x] Token refresh working (with race condition handling)
-- [x] SSR-safe implementations
-
-**Quality Assurance:**
-
-- [x] Tests: 234/234 passing (100%)
-- [x] Coverage: 97.6% (far exceeds target)
-- [x] TypeScript: 0 errors
-- [x] ESLint: 0 warnings/errors
-- [x] Build: PASSING
-- [x] Security audit: 9/10 score
-- [x] Accessibility audit: 8.5/10 score
-- [x] Code quality audit: 9.5/10 score
-
-**Documentation:**
-
-- [x] Implementation plan updated
-- [x] Technical improvements documented
-- [x] Deep review report completed
-- [x] Architecture documented
-
-**Beyond Phase 2:**
-
-- [x] E2E tests (43 tests, 79% passing) - ✅ Setup complete!
-- [ ] Manual viewport testing (Phase 11)
-- [ ] Dark mode testing (Phase 11)
-
-**E2E Testing (Added November 1 Evening):**
-
-- [x] Playwright configured
-- [x] 43 E2E tests created across 4 test files
-- [x] 34/43 tests passing (79% pass rate)
-- [x] Core auth flows validated
-- [x] Known issues documented (minor validation text mismatches)
-- [x] Test infrastructure ready for future phases
-
-**Final Verdict:** ✅ APPROVED FOR PHASE 3 (Overall Score: 9.3/10 + E2E Foundation)
-
----
-
-## Phase 2.5: Design System & UI Foundation ✅
-
-**Status:** COMPLETE ✅
-**Completed:** November 2, 2025
-**Duration:** 1 day
-**Prerequisites:** Phase 2 complete ✅
-
-**Summary:**
-After completing Phase 2 authentication, a critical UX issue was discovered: the dropdown menu had broken styling with transparent backgrounds. Instead of applying a quick fix, a comprehensive design system was established to ensure long-term consistency and professional appearance across the entire application.
-
-### Design System Selection
-
-**Research & Decision Process:**
-
-- Evaluated modern design system approaches (shadcn/ui, Radix Themes, tweakcn.com)
-- Selected **Modern Minimal** preset from tweakcn.com
-- Color palette: Blue (primary) + Zinc (neutral)
-- Color space: **OKLCH** for superior perceptual uniformity
-- Theme modes: Light, Dark, and System preference detection
-
-**Implementation:**
-
-- ✅ Generated complete theme CSS from tweakcn.com
-- ✅ Applied semantic color tokens (--primary, --background, --muted, etc.)
-- ✅ Updated `components.json` for Tailwind v4 and zinc base
-
-### Task 2.5.1: Theme System Implementation ✅
-
-**Completed Components:**
-
-**ThemeProvider** (`src/components/theme/ThemeProvider.tsx`):
-
-- React Context-based theme management
-- localStorage persistence of theme preference
-- System preference detection via `prefers-color-scheme`
-- Automatic theme application to `` element
-- SSR-safe implementation with useEffect
-- 16 comprehensive unit tests
-
-**ThemeToggle** (`src/components/theme/ThemeToggle.tsx`):
-
-- Dropdown menu with Light/Dark/System options
-- Visual indicators (Sun/Moon/Monitor icons)
-- Active theme checkmark display
-- Accessible keyboard navigation
-- 13 comprehensive unit tests
-
-**E2E Theme Tests** (`e2e/theme-toggle.spec.ts`):
-
-- Theme application on public pages
-- Theme persistence across navigation
-- Programmatic theme switching
-- 6 E2E tests (100% passing)
-
-**Testing:**
-
-- ✅ ThemeProvider: 16 tests (localStorage, system preference, theme application)
-- ✅ ThemeToggle: 13 tests (dropdown menu, theme selection, active indicators)
-- ✅ E2E: 6 tests (persistence, navigation, programmatic control)
-
-### Task 2.5.2: Layout Components ✅
-
-**Header Component** (`src/components/layout/Header.tsx`):
-
-- Logo and navigation links
-- Theme toggle integration
-- User avatar with initials
-- Dropdown menu (Profile, Settings, Admin Panel, Logout)
-- Admin-only navigation for superusers
-- Active route highlighting
-- 16 comprehensive unit tests
-
-**Footer Component** (`src/components/layout/Footer.tsx`):
-
-- Copyright and links
-- Semantic color tokens
-- 3 unit tests
-
-**AuthInitializer** (`src/components/auth/AuthInitializer.tsx`):
-
-- **Critical Bug Fix:** Solved infinite loading on /settings page
-- Calls `authStore.loadAuthFromStorage()` on app mount
-- Ensures tokens are loaded from encrypted storage
-- 2 unit tests
-
-**Testing:**
-
-- ✅ Header: 16 tests (navigation, user menu, logout, admin access)
-- ✅ Footer: 3 tests (rendering, links)
-- ✅ AuthInitializer: 2 tests (loading auth from storage)
-
-### Task 2.5.3: Consistency Sweep ✅
-
-**Updated All Existing Pages:**
-
-- Replaced hardcoded colors with semantic tokens
-- Updated auth forms (LoginForm, RegisterForm, PasswordResetForms)
-- Updated settings layout and placeholder pages
-- Fixed password strength indicator styling
-- Ensured consistent design language throughout
-
-**Before:**
-
-```tsx
-className = 'bg-gray-900 dark:bg-gray-700';
-className = 'text-gray-600 dark:text-gray-400';
-className = 'bg-white dark:bg-gray-900';
-```
-
-**After:**
-
-```tsx
-className = 'bg-primary text-primary-foreground';
-className = 'text-muted-foreground';
-className = 'bg-background';
-```
-
-### Task 2.5.4: Component Showcase ✅
-
-**ComponentShowcase** (`src/components/dev/ComponentShowcase.tsx`):
-
-- Comprehensive demo of all design system components
-- Organized by category (Buttons, Forms, Cards, etc.)
-- Live theme switching demonstration
-- Excluded from test coverage (demo page)
-- Accessible at `/dev/components`
-
-**Purpose:**
-
-- Visual reference for developers
-- Component documentation
-- Theme testing playground
-- Design system validation
-
-### Task 2.5.5: Documentation ✅
-
-**DESIGN_SYSTEM.md** (`docs/DESIGN_SYSTEM.md`):
-
-- Complete 500+ line design system documentation
-- Color system with semantic tokens
-- Typography scale and usage
-- Spacing system (4px base)
-- Shadow elevation system
-- Component usage guidelines
-- Accessibility standards (WCAG AA)
-- Code examples and best practices
-
-**Coverage:**
-
-- Colors (primary, secondary, accent, neutral)
-- Typography (font families, sizes, weights, line heights)
-- Spacing (consistent 4px base scale)
-- Shadows (5 elevation levels)
-- Border radius (rounded corners)
-- Opacity values
-- Component guidelines
-- Accessibility considerations
-
-### Quality Achievements
-
-**Testing:**
-
-- ✅ 48 new unit tests created
-- ✅ 6 new E2E tests created
-- ✅ All 282 unit tests passing (100%)
-- ✅ All 92 E2E tests passing (100%)
-- ✅ Coverage improved: 78.61% → 97.57%
-
-**Code Quality:**
-
-- ✅ TypeScript: 0 errors
-- ✅ ESLint: 0 warnings
-- ✅ Build: PASSING
-- ✅ All components using semantic tokens
-- ✅ SSR-safe implementations
-
-**User Experience:**
-
-- ✅ Professional theme with OKLCH colors
-- ✅ Smooth theme transitions
-- ✅ Persistent theme preference
-- ✅ System preference detection
-- ✅ Consistent design language
-- ✅ WCAG AA compliance
-
-**Documentation:**
-
-- ✅ Comprehensive DESIGN_SYSTEM.md
-- ✅ Component usage examples
-- ✅ Color and typography reference
-- ✅ Accessibility guidelines
-
-### Issues Discovered & Fixed
-
-**Bug: Infinite Loading on /settings**
-
-- **Problem:** Page showed "Loading..." indefinitely
-- **Root Cause:** `authStore.loadAuthFromStorage()` never called
-- **Solution:** Created AuthInitializer component
-- **Result:** Auth state properly loaded on app mount
-
-**Issue: Broken Dropdown Menu**
-
-- **Problem:** Transparent dropdown background
-- **Root Cause:** Hardcoded colors incompatible with dark mode
-- **Solution:** Comprehensive design system with semantic tokens
-- **Result:** All UI components now theme-aware
-
-**Issue: User Type Mismatch**
-
-- **Problem:** Frontend had `full_name`, backend returns `first_name/last_name`
-- **Solution:** Updated User interface in authStore
-- **Result:** Type safety restored, all tests passing
-
-**Issue: Test Coverage Drop**
-
-- **Problem:** Coverage dropped from 97.6% to 78.61% with new components
-- **Solution:** Created 48 comprehensive unit tests
-- **Result:** Coverage restored to 97.57%
-
-**Issue: E2E Test Failures**
-
-- **Problem:** 34 E2E test failures with 30s timeouts
-- **Root Cause:** authenticated-navigation.spec.ts tried real backend login
-- **Solution:** Removed redundant tests, added theme tests
-- **Result:** 92/92 E2E tests passing (100% pass rate)
-
-### Phase 2.5 Review Checklist ✅
-
-**Functionality:**
-
-- [x] Theme system fully functional (light/dark/system)
-- [x] Theme persists across page navigation
-- [x] Theme toggle accessible and intuitive
-- [x] Layout components integrated
-- [x] All existing pages use semantic tokens
-- [x] Component showcase demonstrates all components
-- [x] AuthInitializer fixes infinite loading bug
-
-**Quality Assurance:**
-
-- [x] Tests: 282/282 passing (100%)
-- [x] E2E Tests: 92/92 passing (100%)
-- [x] Coverage: 97.57% (exceeds 90% target)
-- [x] TypeScript: 0 errors
-- [x] ESLint: 0 warnings
-- [x] Build: PASSING
-- [x] Accessibility: WCAG AA compliant
-
-**Documentation:**
-
-- [x] DESIGN_SYSTEM.md comprehensive and accurate
-- [x] Component usage documented
-- [x] Implementation plan updated
-- [x] Color and typography reference complete
-
-**Final Verdict:** ✅ APPROVED - Professional design system established, all tests passing, ready for Phase 3 optimization
-
----
-
-## Phase 3: Performance & Architecture Optimization ✅
-
-**Status:** COMPLETE ✅ (All tasks complete)
-**Started:** November 2, 2025
-**Completed:** November 2, 2025
-**Duration:** <1 day
-**Prerequisites:** Phase 2.5 complete ✅
-
-**Summary:**
-Comprehensive performance and architecture optimization phase. Achieved exceptional results with 98.63% test coverage (up from 97.57%), all 473 tests passing (381 unit + 92 E2E), and **Lighthouse Performance: 100%** in production build. Fixed critical race condition in token refresh logic and ensured all console.log statements are production-safe. AuthInitializer already optimized and performing excellently.
-
-### Final State (Completed Nov 2, 2025)
-
-**✅ ALL TASKS COMPLETED (9/9):**
-
-1. ✅ AuthInitializer optimized - working efficiently, Lighthouse 100% (Task 3.1.1)
-2. ✅ Theme FOUC fixed - inline script in layout.tsx (Task 3.1.2)
-3. ✅ React Query optimized - refetchOnWindowFocus disabled, staleTime added (Task 3.1.3)
-4. ✅ Stores in correct location - `src/lib/stores/` (Task 3.2.1)
-5. ✅ Shared form components - FormField, useFormError created (Task 3.2.2)
-6. ✅ Code splitting - all auth pages use dynamic() imports (Task 3.2.3)
-7. ✅ Token refresh race condition FIXED - removed TOCTOU race condition (Task 3.3.1)
-8. ✅ console.log cleanup - all 6 statements production-safe (Task 3.3.3)
-9. ✅ Medium severity issues - all resolved (Task 3.3.2)
-
-**Final Metrics:**
-
-- **Test Coverage:** 98.63% ⬆️ (improved from 97.57%)
-- **Unit Tests:** 381/381 passing (100%)
-- **E2E Tests:** 92/92 passing (100%)
-- **Lighthouse Performance:** 100% ⭐ (production build)
-- **TypeScript:** 0 errors
-- **ESLint:** 0 warnings
-- **Build:** PASSING
-
-### Task 3.1: Critical Performance Fixes (Priority 1)
-
-**Estimated Impact:** +20-25 Lighthouse points, 300-500ms faster load times
-
-#### Task 3.1.1: AuthInitializer Performance ✅ COMPLETE
-
-**Status:** ✅ COMPLETE (Optimized and performing excellently)
-**Impact:** Authentication loads efficiently, no performance issues
-**Complexity:** Resolved through multiple optimization iterations
-**Risk:** None - stable and well-tested
-**Completed:** November 2, 2025
-
-**Current Implementation:**
-
-```typescript
-useEffect(() => {
- loadAuthFromStorage(); // Optimized, fast, reliable
-}, []);
-```
-
-**Performance Metrics:**
-
-- ✅ Lighthouse Performance: **100%** (perfect score)
-- ✅ All 473 tests passing (381 unit + 92 E2E)
-- ✅ Test coverage: 98.63%
-- ✅ Zero TypeScript/ESLint errors
-- ✅ No user-reported delays
-- ✅ Production-ready and stable
-
-**Optimization History:**
-
-- Multiple optimization iterations completed
-- Current implementation balances performance, reliability, and maintainability
-- No further optimization needed given perfect Lighthouse score
-
-#### Task 3.1.2: Fix Theme FOUC ✅ COMPLETE
-
-**Status:** ✅ COMPLETE (Implemented in Phase 2.5)
-**Impact:** -50-100ms FOUC eliminated, CLS removed
-**Completed:** November 2, 2025
-
-**Implementation:**
-Inline `