Feature Planning Document: Producer Portal Knowledge Base with Feature Flags¶
Instructions¶
This planning document outlines the integration of the producer portal knowledge base with the new producer-level feature flags system.
Feature Request:
1. Executive Summary & Feature Overview¶
1.1 Feature Description¶
- Feature Name: Knowledge Base Feature Flag Integration
- Feature Type: Enhancement - Feature Flag Integration
- Priority Level: High
- Estimated Timeline: 1-2 days
- Dependencies: PIQUE-521 (Producer profile level feature flags) - MERGED
- Current Branch: pique-506-producer-portal-knoweldge-base
1.2 Problem Statement¶
Current State:
- Knowledge Base is fully implemented in the producer portal (frontend pages, components, API integration)
- Producer-level feature flags system (PIQUE-521) is implemented and merged to main
- Navigation item exists with featureFlag: 'knowledgeBaseEnabled' property
- CRITICAL ISSUE: URL mismatch between navigation config and actual implementation
- Nav config points to: /dashboard/knowledge-base
- Actual implementation uses: /dashboard/knowledge/
Pain Points: - Knowledge Base is accessible to all producers regardless of their feature flag settings - No way to selectively enable/disable the knowledge base for specific producers - URL inconsistency breaks navigation when feature flag is enabled - Feature flag infrastructure exists but not properly connected
User Impact: - Primary Users: Event producers with feature flags enabled/disabled - Secondary Users: PiqueTickets administrators managing feature rollouts - Expected Impact: Controlled rollout of knowledge base to specific producers
Business Value: - Enables gradual rollout and A/B testing of knowledge base - Allows premium tier differentiation (knowledge base as premium feature) - Provides ability to disable feature if issues arise - Professional feature management capability
1.3 Expected Outcomes¶
Success Metrics:
- Knowledge base only accessible when knowledgeBaseEnabled flag is true
- Navigation item appears/disappears based on feature flag
- URL routing works correctly when accessing via navigation
- No 404 errors or broken links
- Proper redirect when accessing knowledge base without flag enabled
User Experience Goals: - Seamless integration with existing sidebar navigation - Clear feedback if feature not available (graceful degradation) - No visual glitches when feature flag changes - Consistent URL structure across all knowledge base pages
Technical Goals: - Single source of truth for knowledge base routes - Type-safe feature flag checking - Minimal code changes required - No breaking changes to existing knowledge base functionality
2. Stakeholder Analysis & Requirements¶
2.1 Affected Users & Systems¶
Primary Users: - Event Producers: Will see knowledge base nav item only if flag enabled - Beta Testers: Early access to knowledge base via feature flag - Premium Producers: May have knowledge base as premium feature
Secondary Users: - Administrators: Control feature flags via Django admin - Support Team: Need to know which producers have access
System Components: - Producer Portal Frontend: Navigation, routing, feature flag checks - Django API Backend: Feature flag data in producer profile endpoint - PostgreSQL Database: Producer profile feature flags storage
Integration Points:
- useFeatureFlags() hook - already fetches feature flags
- app-sidebar.tsx - already filters nav items by feature flag
- Navigation constants in constants/data.ts
- Knowledge base page routes in app/dashboard/knowledge/
2.2 Functional Requirements¶
Must-Have Features:
- URL Correction
- Update navigation URL from
/dashboard/knowledge-baseto/dashboard/knowledge -
Ensure all internal links use correct URL
-
Access Control
- Check
knowledgeBaseEnabledflag on knowledge base pages - Redirect to dashboard if flag is disabled
-
Show appropriate message if feature not available
-
Navigation Integration
- Nav item appears when flag is enabled (already working)
- Nav item hidden when flag is disabled (already working)
-
Keyboard shortcut works correctly
-
Route Protection
- Protect all knowledge base routes:
/dashboard/knowledge/* - Include: home, category pages, article pages, search
- Handle edge cases: direct URL access, bookmarks
Should-Have Features: - Error boundary for knowledge base section - Analytics tracking when feature flag prevents access - User-friendly message explaining feature unavailability
Could-Have Features: - Admin notification when producers try to access disabled feature - Automatic redirect to alternative help resources - Feature request/waitlist functionality
Won't-Have Features: - Partial access (e.g., read-only mode when disabled) - In-app purchase to enable feature - Time-based feature flag expiration
2.3 Non-Functional Requirements¶
Performance: - Feature flag check < 10ms (cached in SWR) - No additional API calls per route - Page load time unchanged from current implementation
Security: - Server-side validation of feature flags - Client-side checks for UX only (not security boundary) - Prevent URL manipulation to bypass feature flags
Accessibility: - Screen readers announce when feature unavailable - Keyboard navigation works with dynamic nav items - Focus management when nav items appear/disappear
Browser/Platform Support: - Same as existing producer portal (modern browsers) - Mobile responsive navigation
Reliability: - Graceful fallback if feature flag data unavailable - No crashes if flag value is null/undefined - Clear error messages for debugging
3. Current State Analysis¶
3.1 Codebase Research Methodology¶
Tools Used:
- mcp__serena__find_file - Located knowledge base files
- mcp__serena__search_for_pattern - Found feature flag usage
- mcp__serena__list_dir - Explored directory structure
- mcp__serena__get_symbols_overview - Analyzed hook structure
- Read tool - Examined specific files
- JIRA integration - Retrieved ticket context
3.2 Existing Architecture & Patterns¶
Tech Stack (Frontend - Producer Portal): - Framework: Next.js 15.3.1 with App Router - Language: TypeScript - UI Library: shadcn/ui components - State Management: SWR for data fetching, NextAuth for session - Routing: Next.js App Router with dynamic routes - Icons: Tabler Icons, Lucide React
Architecture Pattern:
- Server Components for data fetching (knowledge base pages)
- Client Components for interactivity (navigation, widgets)
- Custom hooks for shared logic (useFeatureFlags, useSession)
- Centralized navigation configuration in constants/data.ts
Feature Flag Pattern (Implemented in PIQUE-521):
// Feature flags interface
export interface FeatureFlags {
knowledgeBaseEnabled: boolean;
aiAgentsEnabled: boolean;
additionalServicesEnabled: boolean;
}
// Hook fetches producer profile with feature flags
useFeatureFlags() => {
flags: FeatureFlags | null,
hasFeature: (flag: FeatureFlagKey) => boolean,
isLoading: boolean,
error: string | null
}
// Sidebar filters nav items
const visibleAddOnItems = addOnNavItems.filter(item =>
item.featureFlag ? hasFeature(item.featureFlag) : false
);
3.3 Relevant Existing Code¶
Feature Flag System (PIQUE-521 - Merged):
- apps/producer/src/types/index.ts - FeatureFlags interface
- apps/producer/src/hooks/use-feature-flags.ts - useFeatureFlags hook
- apps/producer/src/components/layout/app-sidebar.tsx - Nav filtering
Knowledge Base Implementation (PIQUE-506 - In Progress):
- apps/producer/src/app/dashboard/knowledge/page.tsx - Home page
- apps/producer/src/app/dashboard/knowledge/category/[slug]/page.tsx - Category view
- apps/producer/src/app/dashboard/knowledge/article/[slug]/page.tsx - Article detail
- apps/producer/src/app/dashboard/knowledge/search/page.tsx - Search results
- apps/producer/src/components/knowledge/* - UI components
- apps/producer/src/types/knowledge.ts - TypeScript types
Navigation Configuration:
// apps/producer/src/constants/data.ts
export const addOnNavItems: NavItem[] = [
{
title: 'Knowledge Base',
url: '/dashboard/knowledge-base', // ❌ INCORRECT - should be /dashboard/knowledge
icon: 'bookOpen',
isActive: false,
items: [],
featureFlag: 'knowledgeBaseEnabled' // ✅ Already configured
},
// ... other items
];
3.4 Current Dependencies¶
Core Dependencies (Already Installed): - next-auth - Session management ✅ - swr - Data fetching and caching ✅ - lucide-react - Icons ✅ - @tabler/icons-react - Additional icons ✅
No New Dependencies Required ✅
3.5 Potential Conflicts & Constraints¶
Technical Debt:
- URL mismatch requires careful refactoring to avoid breaking changes
- Need to ensure no other code references the old /dashboard/knowledge-base URL
Legacy Code: - None - this is new feature
Resource Constraints: - Feature flag data comes from producer profile (single API call) - SWR caching reduces server load (5-minute cache)
Compliance Requirements: - None specific to feature flags
4. Research & Best Practices¶
4.1 Industry Standards Research¶
Research Sources: - Next.js App Router documentation (feature flags pattern) - LaunchDarkly feature flag best practices - Split.io feature flag architecture guides
Industry Best Practices:
- Server-Side Feature Flag Checks:
- Always validate feature flags on server (not just client)
- Client checks are for UX, server checks are for security
-
Use Next.js Server Components for server-side validation
-
Graceful Degradation:
- Provide clear feedback when feature unavailable
- Redirect to alternative location, don't show error page
-
Log attempts to access disabled features (for analytics)
-
Performance:
- Cache feature flags aggressively (they rarely change)
- Minimize API calls by fetching flags with user profile
-
Use optimistic UI updates when possible
-
User Experience:
- Don't show/hide nav items too aggressively (jarring)
- Provide consistent experience (don't tease unavailable features)
- Clear communication if feature is coming soon
4.2 Framework-Specific Patterns¶
Next.js App Router Best Practices:
-
Route Protection Pattern:
// In page.tsx (Server Component) export default async function KnowledgeBasePage() { const session = await getServerSession(authOptions); // Fetch producer profile to check feature flag const profileResponse = await fetchProducerProfile(session); // Redirect if feature not enabled if (!profileResponse.data?.featureFlags?.knowledgeBaseEnabled) { redirect('/dashboard/overview'); } // Continue with page rendering } -
Shared Layout for Route Group:
-
Type Safety:
4.3 Case Studies & Examples¶
Similar Implementations:
- Vercel Dashboard:
- Premium features behind feature flags
- Graceful UI when feature unavailable
-
Clear upgrade path
-
GitHub Projects V2:
- Gradual rollout via feature flags
- Beta access for early adopters
- Seamless navigation integration
Lessons Learned: - Always provide fallback content when feature disabled - Don't break existing workflows (important for accessibility) - Clear communication is key (users should know why feature unavailable)
5. Solution Design¶
5.1 Proposed Architecture¶
High-Level Design:
- URL Correction (Single Change):
- Update
apps/producer/src/constants/data.ts - Change URL from
/dashboard/knowledge-baseto/dashboard/knowledge -
This fixes navigation immediately
-
Route Protection (Recommended but Optional):
- Create shared layout for
/dashboard/knowledge/*routes - Check feature flag in layout (runs once for all child routes)
-
Redirect to dashboard with message if flag disabled
-
Feature Flag Flow:
User clicks "Knowledge Base" in sidebar ↓ useFeatureFlags hook checks flag (client-side) ↓ If enabled: Nav item is visible (already working) If disabled: Nav item is hidden (already working) ↓ User navigates to /dashboard/knowledge ↓ Server-side layout checks feature flag ↓ If enabled: Render knowledge base pages If disabled: Redirect to /dashboard/overview
Data Model Changes: - None required - feature flags already exist in producer profile
API Design:
- No new endpoints required
- Existing fetchProducerProfile returns feature flags
UI/UX Design: - No visual changes to knowledge base itself - Navigation item appears/disappears based on flag (already working) - Optional: Toast notification when redirected due to disabled feature
5.2 Technology Decisions¶
New Dependencies: - None required ✅
Alternative Solutions:
- Option A: Layout-based Protection (Recommended)
- ✅ Pros: Single check for all routes, server-side validation
- ✅ Cons: Minimal overhead, clean architecture
-
Recommended approach
-
Option B: Middleware-based Protection
- ⚠️ Pros: Centralized routing logic
- ❌ Cons: Middleware runs on every request, can't access session easily in middleware
-
Not recommended for Next.js App Router
-
Option C: Client-side Only (NOT RECOMMENDED)
- ❌ Pros: Simple implementation
- ❌ Cons: Not secure, can be bypassed, poor UX
- Do not use
Chosen Solution: Option A (Layout-based Protection)
5.3 Security Considerations¶
Threat Model:
- Users manually typing /dashboard/knowledge URL when feature disabled
- Users bookmarking knowledge base pages before feature disabled
- URL manipulation to access disabled features
Authentication/Authorization: - Already handled by NextAuth at dashboard level - Feature flag is authorization check (not authentication)
Data Protection: - No sensitive data exposed by feature flag check - Feature flag is not security-critical (informational feature)
Security Testing: - Manual testing: Try to access URL with flag disabled - Verify redirect occurs on server-side (not just client)
6. Implementation Plan¶
6.1 Development Phases¶
Phase 1: URL Correction [Timeline: 10 minutes]
- [x] Update URL in apps/producer/src/constants/data.ts
- [x] Change /dashboard/knowledge-base to /dashboard/knowledge
- Deliverable: Navigation works correctly
Phase 2: Route Protection (Optional but Recommended) [Timeline: 30 minutes]
- [ ] Create apps/producer/src/app/dashboard/knowledge/layout.tsx
- [ ] Add server-side feature flag check
- [ ] Add redirect logic if flag disabled
- [ ] Test with flag enabled/disabled
- Deliverable: Routes protected from unauthorized access
Phase 3: Testing & Documentation [Timeline: 20 minutes] - [ ] Test navigation with flag enabled - [ ] Test navigation with flag disabled - [ ] Test direct URL access with flag disabled - [ ] Update documentation - Deliverable: Feature fully tested and documented
6.2 Detailed Task Breakdown¶
| Task | Files Affected | Estimated Time | Dependencies | Priority |
|---|---|---|---|---|
| Fix URL mismatch | apps/producer/src/constants/data.ts |
5 min | None | Critical |
| Test navigation | Manual testing | 5 min | URL fix | High |
| Create layout file | apps/producer/src/app/dashboard/knowledge/layout.tsx |
15 min | URL fix | Medium |
| Add feature flag check | Same layout file | 10 min | Layout created | Medium |
| Test route protection | Manual testing | 10 min | Layout implemented | Medium |
| Update docs | docs/plans/, apps/producer/KNOWLEDGE_BASE_FRONTEND_GUIDE.md |
10 min | Testing complete | Low |
6.3 File Change Summary¶
Modified Files:
apps/producer/src/constants/data.ts- Change: Update URL from
/dashboard/knowledge-baseto/dashboard/knowledge - Lines: ~66-70
- Impact: Fixes navigation
New Files (Optional but Recommended):
apps/producer/src/app/dashboard/knowledge/layout.tsx- Purpose: Server-side feature flag check for all knowledge base routes
- Type: Server Component
- Size: ~30-40 lines
No Files Deleted
7. Testing Strategy¶
7.1 Test Coverage Plan¶
Manual Tests:
- Navigation Tests:
- ✅ Nav item appears when flag enabled
- ✅ Nav item hidden when flag disabled
- ✅ Click nav item navigates to knowledge base
-
✅ Active state highlights correctly
-
Route Access Tests:
- ✅ Direct URL access to
/dashboard/knowledgeworks when enabled - ✅ Direct URL access redirects when disabled
- ✅ Category pages accessible when enabled
- ✅ Article pages accessible when enabled
-
✅ Search page accessible when enabled
-
Feature Flag Toggle Tests:
- ✅ Enable flag in Django admin
- ✅ Verify nav item appears (may need to refresh)
- ✅ Disable flag in Django admin
-
✅ Verify nav item disappears (may need to refresh)
-
Edge Cases:
- ✅ Bookmarked URL still works after flag enabled
- ✅ Bookmarked URL redirects after flag disabled
- ✅ Back button works correctly
- ✅ Browser history navigation works
Automated Tests (Future Enhancement): - Playwright E2E tests for critical user flows - Feature flag mocking for consistent test results
7.2 Test Environment Requirements¶
Development: - Local Docker environment with full stack - Ability to toggle feature flags via Django admin - Multiple producer accounts with different flag settings
Staging: - Test with real producer accounts - Verify feature flag propagation - Check analytics/logging
Production: - Gradual rollout recommended - Monitor error logs for 404s - Track usage analytics
7.3 Acceptance Criteria¶
Definition of Done: - [x] URL mismatch resolved - [ ] Navigation works with flag enabled - [ ] Navigation hidden with flag disabled - [ ] Direct URL access redirects when flag disabled (optional) - [ ] No console errors - [ ] No broken links - [ ] Documentation updated - [ ] Code reviewed - [ ] Tested on staging
Specific Criteria:
- [ ] Producer with knowledgeBaseEnabled: true sees nav item
- [ ] Producer with knowledgeBaseEnabled: false does not see nav item
- [ ] All knowledge base internal links use /dashboard/knowledge base path
- [ ] No references to old /dashboard/knowledge-base URL
- [ ] Server-side validation prevents unauthorized access (if layout implemented)
8. Risk Assessment & Mitigation¶
8.1 Technical Risks¶
| Risk | Probability | Impact | Mitigation Strategy |
|---|---|---|---|
| URL change breaks existing bookmarks | Medium | Low | Acceptable - new feature, few users have bookmarks |
| Feature flag not properly cached | Low | Medium | SWR handles caching automatically |
| Redirect loop if logic error | Low | High | Thorough testing, verify redirect target |
| Feature flag data not available | Medium | Medium | Graceful fallback - default to disabled |
8.2 Resource Risks¶
Timeline Risks: - Minimal - only 1-2 hours of work - No external dependencies - Can be done in single PR
Skill Gaps: - None - standard Next.js patterns - Team familiar with feature flags from PIQUE-521
External Dependencies: - PIQUE-521 must be merged first (COMPLETED ✅) - No other blocking dependencies
8.3 Rollback Strategy¶
Feature Flags:
- Can disable knowledgeBaseEnabled for all producers via Django admin
- Immediate effect (after cache expires or refresh)
Code Rollback: - Simple git revert if issues arise - URL change is backward compatible (just fixes broken link)
Deployment Strategy: - Standard deployment (no special considerations) - No database migrations required - No downtime expected
9. Deployment & Operations¶
9.1 Deployment Plan¶
Environment Progression: 1. Dev: Test locally with Docker 2. Staging: Deploy and test with real data 3. Prod: Standard deployment, no special steps
Configuration Updates: - No environment variables needed - Feature flags controlled via Django admin
Monitoring Setup: - Monitor 404 errors (should decrease) - Track knowledge base page views - Analytics on feature flag usage
9.2 Monitoring & Observability¶
Key Metrics:
- Knowledge base page views (by producer with flag enabled)
- 404 errors on /dashboard/knowledge-base (old URL)
- Feature flag adoption rate
- Time spent in knowledge base
Alerting: - Spike in 404 errors (may indicate issue with URL change) - Feature flag data not loading (API issue)
Logging: - Log when user redirected due to disabled feature flag - Track which producers have feature enabled
Health Checks: - Knowledge base pages load successfully - Feature flag data available in producer profile
9.3 Support & Maintenance¶
Documentation:
- Update KNOWLEDGE_BASE_FRONTEND_GUIDE.md with feature flag info
- Add section on enabling/disabling feature flags
- Document URL structure
Training: - Brief team on feature flag system - Show how to enable/disable for specific producers - Explain rollout strategy
Ongoing Maintenance: - Monitor feature flag usage over time - Decide when to remove flag and make feature permanent - Clean up code if/when flag removed
10. Success Measurement¶
10.1 Success Metrics¶
Technical Metrics: - Zero 404 errors on knowledge base URLs - Feature flag check latency < 10ms - Page load time unchanged - No console errors or warnings
User Metrics: - Producers with flag enabled access knowledge base - Producers with flag disabled don't see nav item - No support tickets about broken knowledge base link - Positive feedback on feature flag rollout
Business Metrics: - Controlled rollout of knowledge base feature - Ability to A/B test knowledge base effectiveness - Support ticket reduction (for flagged producers) - Feature adoption metrics
10.2 Review Schedule¶
1 Week Post-Deployment: - Check for any 404 errors - Verify feature flag working as expected - Review producer feedback
1 Month Post-Deployment: - Analyze knowledge base usage by flagged producers - Determine if ready for wider rollout - Gather support team feedback
3 Months Post-Deployment: - Evaluate if feature flag should be made permanent - Consider removing flag if stable - Plan next phase of knowledge base enhancements
11. Appendices¶
Appendix A: Code Examples¶
Example 1: URL Fix
// apps/producer/src/constants/data.ts
export const addOnNavItems: NavItem[] = [
{
title: 'Knowledge Base',
url: '/dashboard/knowledge', // ✅ FIXED
icon: 'bookOpen',
isActive: false,
items: [],
featureFlag: 'knowledgeBaseEnabled'
},
// ... other items
];
Example 2: Optional Layout with Feature Flag Check
// apps/producer/src/app/dashboard/knowledge/layout.tsx
import { getServerSession } from 'next-auth';
import { authOptions } from '@/lib/auth';
import { redirect } from 'next/navigation';
import { fetchProducerProfile } from '@/lib/api';
export default async function KnowledgeBaseLayout({
children,
}: {
children: React.ReactNode;
}) {
const session = await getServerSession(authOptions);
if (!session) {
redirect('/auth/sign-in');
}
// Fetch producer profile to check feature flag
const profileResponse = await fetchProducerProfile(session);
// Check if knowledge base feature is enabled
const isEnabled = profileResponse.data?.featureFlags?.knowledgeBaseEnabled;
// Redirect if feature not enabled
if (!isEnabled) {
redirect('/dashboard/overview');
}
return <>{children}</>;
}
Example 3: Enhanced Layout with User Feedback
// apps/producer/src/app/dashboard/knowledge/layout.tsx (with toast)
import { getServerSession } from 'next-auth';
import { authOptions } from '@/lib/auth';
import { redirect } from 'next/navigation';
import { fetchProducerProfile } from '@/lib/api';
export default async function KnowledgeBaseLayout({
children,
}: {
children: React.ReactNode;
}) {
const session = await getServerSession(authOptions);
if (!session) {
redirect('/auth/sign-in');
}
// Fetch producer profile to check feature flag
const profileResponse = await fetchProducerProfile(session);
// Check if knowledge base feature is enabled
const isEnabled = profileResponse.data?.featureFlags?.knowledgeBaseEnabled;
// Redirect if feature not enabled
if (!isEnabled) {
// Could set a query param to show a toast on redirect
redirect('/dashboard/overview?error=knowledge_base_unavailable');
}
return <>{children}</>;
}
Appendix B: Related Issues & PRs¶
Related JIRA Issues: - PIQUE-521: Create producer profile level feature flags (MERGED ✅) - PIQUE-506: Come up with plan to implement knowledge base for producer portal and api (IN PROGRESS)
Related Pull Requests: - PIQUE-521 PR: [Link when available] - PIQUE-506 PR: https://github.com/brktickets/PiqueTickets/pull/[PR_NUMBER]
Appendix C: Feature Flag Configuration¶
Django Admin Steps to Enable Feature:
- Navigate to Django admin:
/admin/ - Go to "Producer Profiles" section
- Find producer profile to modify
- Check "Knowledge Base Enabled" checkbox
- Save changes
- Producer will see knowledge base on next page load/refresh
Bulk Enable: - Use Django admin actions for bulk updates - Or create management command for mass rollout
Appendix D: URL Structure¶
Knowledge Base URL Structure:
/dashboard/knowledge → Home page
/dashboard/knowledge/category/[slug] → Category view
/dashboard/knowledge/article/[slug] → Article detail
/dashboard/knowledge/search?q=query → Search results
/dashboard/knowledge/search?tag=slug → Tag filtered results
All URLs use /dashboard/knowledge as base path ✅
Document Information¶
- Created: 2025-10-17
- Last Updated: 2025-10-17
- Version: 1.0
- Author(s): Claude (AI Assistant)
- Status: Draft - Ready for Review
Quick Implementation Checklist¶
Critical (Must Do):¶
- Update URL in
apps/producer/src/constants/data.ts - Test navigation with flag enabled
- Test navigation with flag disabled
- Verify no broken links
Recommended (Should Do):¶
- Create layout.tsx for route protection
- Add server-side feature flag check
- Test direct URL access when disabled
- Update documentation
Optional (Nice to Have):¶
- Add toast notification on redirect
- Add analytics tracking
- Create E2E tests
- Add user feedback mechanism
Summary¶
This feature integration is straightforward with minimal risk:
- Main Task: Fix URL mismatch (5 minutes)
- Optional Task: Add route protection (30 minutes)
- Testing: Verify feature flag integration (20 minutes)
Total Estimated Time: 1 hour (including optional tasks)
The feature flag system from PIQUE-521 is already working correctly in the navigation. We just need to correct the URL and optionally add server-side protection for the routes.
Next Steps: 1. Review this plan 2. Implement URL fix 3. Test thoroughly 4. Deploy to staging 5. Deploy to production