Feature Planning Document: Producer Account Level Feature Flags¶
1. Executive Summary & Feature Overview¶
1.1 Feature Description¶
- Feature Name: Producer Account Level Feature Flags System
- Feature Type: New Feature - Infrastructure Enhancement
- Priority Level: High
1.2 Problem Statement¶
- Current State: All producer accounts have access to all features in the producer portal simultaneously. There's no mechanism to gradually roll out new features or enable/disable specific functionality for individual producers.
- Pain Points:
- Cannot beta test new features with specific producers
- No way to offer tiered feature access (potential for future pricing tiers)
- Unable to enable experimental features for select users
- Risk of releasing half-baked features to all users at once
- User Impact: Producers and internal team members who manage producer accounts
- Business Value:
- Enables gradual feature rollout and A/B testing
- Reduces risk of feature releases
- Creates foundation for tiered pricing models
- Allows VIP/beta tester programs
1.3 Expected Outcomes¶
- Success Metrics:
- Feature flags can be toggled in Django admin
- Producer portal navigation dynamically shows/hides features
- API correctly returns feature flag state per producer
- No performance degradation from flag checks
- User Experience Goals:
- Seamless - producers only see features they have access to
- Navigation automatically adapts based on enabled flags
- No confusion about missing features
- Technical Goals:
- Simple, maintainable implementation
- Scalable to add more flags in future
- Fast flag checks (minimal DB queries)
- Type-safe on frontend
2. Stakeholder Analysis & Requirements¶
2.1 Affected Users & Systems¶
- Primary Users:
- Platform administrators (who toggle flags)
- Producers (who see different features based on flags)
- Secondary Users: Development team (who gate new features behind flags)
- System Components:
- Django backend (
apps/api/producers) - Producer portal frontend (
apps/producer) - Django admin interface
- Authentication/session management
- Integration Points:
- NextAuth.js session (may need to include flags)
- API endpoints for producer data
- Navigation rendering system
2.2 Functional Requirements¶
Must-Have Features:
1. Django model ProducerFeatureFlags with one-to-one relationship to Producer
2. Three boolean flags: knowledge_base_enabled, ai_agents_enabled, additional_services_enabled
3. Django admin interface with:
- Inline editing of flags on Producer detail page
- Ability to toggle feature flags on/off per producer
- Bulk actions to enable/disable flags for multiple producers
- List filters to find producers by flag status
4. API endpoint returning feature flags for authenticated producer
5. Frontend service/hook to check feature flags
6. Navigation filtering based on enabled flags
Should-Have Features: - Default flag values (all disabled for new producers) - TypeScript types for flag structure - Admin action confirmation dialogs for safety - Help text tooltips in admin interface
Could-Have Features: - Flag change audit log - Email notification when flags change - Frontend flag cache with TTL - Feature flag analytics (usage tracking)
Won't-Have Features (out of scope for MVP): - Time-based flag expiration - User-level flags (separate from producer) - A/B testing framework - Flag rollout percentages - External flag management service (LaunchDarkly, etc.)
2.3 Non-Functional Requirements¶
- Performance: Flag checks should not add noticeable latency (< 10ms per check)
- Security: Only authenticated producers can see their own flags
- Accessibility: Admin interface follows existing Unfold theme patterns
- Browser/Platform Support: Same as existing producer portal (modern browsers)
- Reliability: Flags should fail open (if check fails, don't break the app)
3. Current State Analysis¶
3.1 Codebase Research Methodology¶
Tools Used: - Serena MCP for file discovery and symbol searching - Read tool for file content analysis - Project architecture documentation review
3.2 Existing Architecture & Patterns¶
Tech Stack: - Backend: Django 5.1, Django REST Framework 3.15, PostgreSQL - Frontend: Next.js 15.2.4, React 19, TypeScript 5.7.2, Shadcn UI - Admin: Django admin with Unfold theme - Auth: NextAuth for producer portal, JWT for API
Architecture Pattern: - Service-oriented architecture on backend - API-first design with RESTful endpoints - Component-based frontend with hooks pattern - Sidebar navigation driven by constants file
Code Organization:
apps/api/producers/
├── models.py # Producer, ProducerFinancial, UserProducerAssociation
├── admin.py # Django admin customization with Unfold
├── views.py # API ViewSets
└── serializers.py # DRF serializers
apps/producer/src/
├── constants/data.ts # navItems array defining sidebar
├── components/layout/app-sidebar.tsx # Sidebar rendering
├── hooks/ # Custom React hooks
└── types/ # TypeScript interfaces
Data Flow: 1. Producer authenticates → NextAuth session 2. Frontend requests producer data → Django API 3. API returns producer info + related data 4. Frontend stores in state/context 5. Components read from state to render
3.3 Relevant Existing Code¶
Similar Features:
- UserProfile model (apps/api/producers/models.py:134-171) - extends User with can_publish_shows boolean flag
- This is a single flag implementation we can pattern after
- Uses admin inline editing for toggle
Reusable Components:
- ProducerFinancialInline (producers/admin.py:19-22) - TabularInline for related model
- Navigation filtering in app-sidebar.tsx - already conditionally renders items
Shared Utilities: - Django admin Unfold theme configuration - NextAuth session management - API serializer patterns for related models
Integration Points: - Producer model (line 17) - where we'll add one-to-one relationship - navItems constant (constants/data.ts:19) - needs flag gating - API ViewSets for producer data retrieval
3.4 Current Dependencies¶
Core Dependencies: - Django 5.1 - ORM for model creation - Django REST Framework - API serialization - Unfold - Admin UI theme - Next.js/React - Frontend framework - NextAuth.js - Session management - TypeScript - Type safety
No new dependencies required for MVP implementation.
3.5 Potential Conflicts & Constraints¶
Technical Debt: - Navigation is currently static (constants file) - needs dynamic filtering - No existing pattern for feature gating in frontend - API might need modification to include flags in producer response
Legacy Code: - Producer model is well-established - must maintain backward compatibility - Existing admin inlines must coexist with new flags inline
Resource Constraints: - Should minimize API calls (don't check flags on every route change) - PostgreSQL queries for flags should be optimized (use select_related)
Compliance Requirements: - None specific to feature flags - Must maintain existing auth/permissions
4. Research & Best Practices¶
4.1 Industry Standards Research¶
Industry Best Practices: - Feature flags should default to "off" for safety - Flags should be checked at render time, not build time - Flag state should be cached to reduce DB load - Admin controls should be simple toggle switches - Flag names should be clear and consistent (snake_case in DB, camelCase in JS)
Framework-Specific Patterns: - Django: Use one-to-one relationships for feature flags - React: Use context or hooks for flag checks - Next.js: Can include flags in server-side props or API responses
Security Guidelines: - Never expose internal flag logic to clients - Check permissions before showing flag toggles in admin - Validate flag state on API responses - Don't allow client-side flag manipulation
4.2 Framework/Library Research¶
Django Documentation: - Model relationships: https://docs.djangoproject.com/en/5.1/topics/db/models/#relationships - Admin inlines: https://docs.djangoproject.com/en/5.1/ref/contrib/admin/#django.contrib.admin.InlineModelAdmin - Signals for auto-creation: post_save pattern used in existing code
DRF Documentation: - Nested serializers for related models - SerializerMethodField for computed properties
React/Next.js Patterns: - Custom hooks for feature flag checks - Context providers for global flag state - Conditional rendering patterns
5. Solution Design¶
5.1 Proposed Architecture¶
High-Level Design:
┌─────────────────────────────────────────────────────────────┐
│ Django Backend │
├─────────────────────────────────────────────────────────────┤
│ Producer Model (existing) │
│ │ │
│ │ one-to-one │
│ ▼ │
│ ProducerFeatureFlags Model (NEW) │
│ - knowledge_base_enabled: Boolean │
│ - ai_agents_enabled: Boolean │
│ - additional_services_enabled: Boolean │
│ - created_at, updated_at: DateTime │
│ │
│ API Endpoint: GET /api/v1/producers/me/ │
│ Returns: { ...producer_data, feature_flags: {...} } │
├─────────────────────────────────────────────────────────────┤
│ Django Admin │
├─────────────────────────────────────────────────────────────┤
│ ProducerAdmin (enhanced) │
│ - ProducerFeatureFlagsInline (NEW) │
│ • Toggle flags directly on producer detail page │
│ • Real-time save on checkbox toggle │
│ - Bulk Actions: │
│ • Enable Knowledge Base (multiple producers) │
│ • Enable AI Agents (multiple producers) │
│ • Enable Additional Services (multiple producers) │
│ - List Filters: │
│ • By knowledge_base_enabled │
│ • By ai_agents_enabled │
│ • By additional_services_enabled │
└─────────────────────────────────────────────────────────────┘
│
│ HTTP/JSON
▼
┌─────────────────────────────────────────────────────────────┐
│ Producer Portal Frontend │
├─────────────────────────────────────────────────────────────┤
│ useFeatureFlags() hook │
│ - Fetches flags from API │
│ - Provides hasFeature(flag) check │
│ │
│ Enhanced Navigation (constants/data.ts) │
│ - Add featureFlag property to nav items │
│ - Filter items based on enabled flags │
│ │
│ AppSidebar Component │
│ - Reads flags from hook │
│ - Filters navItems before rendering │
└─────────────────────────────────────────────────────────────┘
Data Model Changes:
# apps/api/producers/models.py
class ProducerFeatureFlags(models.Model):
"""
Feature flags for gradual rollout of new producer portal features.
Each flag controls visibility of specific features in the producer portal.
"""
producer = models.OneToOneField(
Producer,
on_delete=models.CASCADE,
related_name='feature_flags'
)
# Feature flags (all default to False for new producers)
knowledge_base_enabled = models.BooleanField(
default=False,
help_text="Enable access to knowledge base articles and documentation"
)
ai_agents_enabled = models.BooleanField(
default=False,
help_text="Enable AI assistant features (chatbot, recommendations)"
)
additional_services_enabled = models.BooleanField(
default=False,
help_text="Enable additional services (marketing tools, analytics)"
)
# Metadata
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
verbose_name = "Feature Flags"
verbose_name_plural = "Feature Flags"
def __str__(self):
return f"Feature flags for {self.producer.name}"
# Signal to auto-create flags for new producers
@receiver(post_save, sender=Producer)
def create_producer_feature_flags(sender, instance, created, **kwargs):
if created:
ProducerFeatureFlags.objects.create(producer=instance)
API Design:
# apps/api/producers/serializers.py (NEW/ENHANCED)
class ProducerFeatureFlagsSerializer(serializers.ModelSerializer):
class Meta:
model = ProducerFeatureFlags
fields = [
'knowledge_base_enabled',
'ai_agents_enabled',
'additional_services_enabled'
]
class ProducerSerializer(serializers.ModelSerializer):
feature_flags = ProducerFeatureFlagsSerializer(read_only=True)
class Meta:
model = Producer
fields = ['id', 'name', 'slug', 'feature_flags', ...]
Frontend Types:
// apps/producer/src/types/index.ts
export interface FeatureFlags {
knowledgeBaseEnabled: boolean;
aiAgentsEnabled: boolean;
additionalServicesEnabled: boolean;
}
export interface Producer {
id: number;
name: string;
slug: string;
featureFlags: FeatureFlags;
// ... other fields
}
export type FeatureFlagKey = keyof FeatureFlags;
UI/UX Design:
Django Admin Interface:
Admin interface will show as inline form under Producer detail page:
Producer: Arizona Comedy
━━━━━━━━━━━━━━━━━━━━━━━━
Basic Information
Name: Arizona Comedy
Slug: arizona-comedy
...
Feature Flags
━━━━━━━━━━━━━━━━━━━━━━━━
☐ Knowledge Base Enabled ℹ Enable access to knowledge base articles and documentation
☑ AI Agents Enabled ℹ Enable AI assistant features (chatbot, recommendations)
☐ Additional Services Enabled ℹ Enable additional services (marketing tools, analytics)
Admin List View with Filters: - Admin can filter producers by enabled/disabled flags - Bulk actions available from list view: - "Enable Knowledge Base for selected producers" - "Enable AI Agents for selected producers" - "Enable Additional Services for selected producers" - "Disable all features for selected producers"
Admin Workflow: 1. Navigate to Django Admin → Producers 2. Search/filter for specific producer or select multiple 3. Option A: Click producer → Edit flags inline → Save 4. Option B: Select multiple producers → Choose bulk action → Confirm
5.2 Technology Decisions¶
New Dependencies: None - using existing stack
Alternative Solutions Considered:
- External Service (LaunchDarkly, Flagsmith):
- Pros: Rich features, analytics, gradual rollout
- Cons: Additional cost, complexity, external dependency
-
Decision: Overkill for MVP with only 3 flags
-
JSON Field on Producer:
- Pros: More flexible, easier schema changes
- Cons: Less type-safe, harder to query, no admin validation
-
Decision: Separate model is cleaner for queryability
-
Frontend-Only Feature Gating:
- Pros: No backend changes
- Cons: Not secure, not persistent, can't gate API endpoints
- Decision: Backend source of truth is essential
Chosen Approach: Dedicated Django model with admin inline editing and API serialization
5.3 Security Considerations¶
Threat Model: - Malicious producer tries to enable their own flags via API manipulation - Admin accidentally enables experimental features for all users - Feature flag state leaks to unauthorized users
Authentication/Authorization: - Only staff/superusers can modify flags (Django admin permissions) - Producers can only READ their own flags via authenticated API - No flag mutation endpoints exposed to producers
Data Protection: - Flags are boolean values (no sensitive data) - Standard Django admin CSRF protection applies - API requires JWT authentication
Security Testing: - Verify non-admin users cannot access flag admin - Verify producers cannot modify flags via API - Test that missing flags fail gracefully (don't break app)
6. Implementation Plan¶
6.1 Development Phases¶
Phase 1: Backend Foundation & Admin Interface
- [ ] Create ProducerFeatureFlags model with three boolean flags
- [ ] Write and run Django migration to create feature_flags table
- [ ] Add post_save signal for auto-creation of flags on new producers
- [ ] Create ProducerFeatureFlagsInline for Django admin
- [ ] Add inline to ProducerAdmin with checkbox toggles
- [ ] Configure help text for each flag
- [ ] Test inline save functionality
- [ ] Add bulk actions to ProducerAdmin
- [ ] "Enable Knowledge Base for selected producers"
- [ ] "Enable AI Agents for selected producers"
- [ ] "Enable Additional Services for selected producers"
- [ ] "Disable all features for selected producers"
- [ ] Add list filters to ProducerAdmin
- [ ] Filter by knowledge_base_enabled
- [ ] Filter by ai_agents_enabled
- [ ] Filter by additional_services_enabled
- [ ] Deliverable: Django model + fully functional admin interface for managing producer feature flags
Phase 2: API Integration - [ ] Create FeatureFlagsSerializer - [ ] Update ProducerSerializer to include flags - [ ] Update producer ViewSet to select_related flags - [ ] Test API response includes flags - [ ] Write unit tests for serializers - [ ] Deliverable: API returns feature flags per producer
Phase 3: Frontend Integration - [ ] Add FeatureFlags TypeScript types - [ ] Create useFeatureFlags() hook - [ ] Update navItems with featureFlag property - [ ] Modify AppSidebar to filter navigation - [ ] Add feature flag context provider (optional optimization) - [ ] Test navigation filtering - [ ] Deliverable: Producer portal navigation respects flags
Phase 4: Testing & Documentation - [ ] Write backend unit tests for model - [ ] Write API integration tests - [ ] Write frontend tests for flag checks - [ ] Manual QA in admin and portal - [ ] Update architecture documentation - [ ] Create admin user guide - [ ] Deliverable: Fully tested, documented feature
6.2 Detailed Task Breakdown¶
| Task | Files Affected | Dependencies | Assignee |
|---|---|---|---|
| Create ProducerFeatureFlags model | apps/api/producers/models.py |
None | TBD |
| Add post_save signal for auto-creation | apps/api/producers/models.py |
Model created | TBD |
| Create database migration | apps/api/producers/migrations/000X_feature_flags.py |
Model created | TBD |
| Run migration on development database | Command line | Migration file created | TBD |
| Create ProducerFeatureFlagsInline | apps/api/producers/admin.py |
Model created | TBD |
| Add inline to ProducerAdmin | apps/api/producers/admin.py |
Inline created | TBD |
| Add bulk actions to ProducerAdmin | apps/api/producers/admin.py |
Model created | TBD |
| Add list filters to ProducerAdmin | apps/api/producers/admin.py |
Model created | TBD |
| Test admin interface functionality | Django admin UI | Admin configured | TBD |
| Create FeatureFlagsSerializer | apps/api/producers/serializers.py |
Model created | TBD |
| Update ProducerSerializer | apps/api/producers/serializers.py |
FeatureFlagsSerializer created | TBD |
| Update producer API ViewSet | apps/api/producers/views.py |
Serializer updated | TBD |
| Add TypeScript types | apps/producer/src/types/index.ts |
None | TBD |
| Create useFeatureFlags hook | apps/producer/src/hooks/use-feature-flags.ts |
Types defined | TBD |
| Update navigation data | apps/producer/src/constants/data.ts |
None | TBD |
| Update AppSidebar component | apps/producer/src/components/layout/app-sidebar.tsx |
Hook created | TBD |
| Write backend tests | apps/api/producers/tests/test_feature_flags.py |
All backend done | TBD |
| Write admin tests | apps/api/producers/tests/test_admin.py |
Admin configured | TBD |
| Write frontend tests | apps/producer/src/hooks/__tests__/use-feature-flags.test.ts |
Hook created | TBD |
| Create admin user guide | docs/admin-feature-flags-guide.md |
Feature complete | TBD |
| Update architecture documentation | docs/feature-flags.md |
Feature complete | TBD |
6.3 File Change Summary¶
New Files:
- apps/api/producers/migrations/000X_producerfeatureflags.py - Database migration
- apps/producer/src/hooks/use-feature-flags.ts - Custom React hook for flag checks
- apps/producer/src/types/feature-flags.ts - TypeScript interfaces (optional, could go in index.ts)
- apps/api/producers/tests/test_feature_flags.py - Backend tests
- apps/api/producers/tests/test_admin.py - Admin interface tests
- docs/feature-flags.md - Technical documentation
- docs/admin-feature-flags-guide.md - Admin user guide for managing feature flags
Modified Files:
- apps/api/producers/models.py - Add ProducerFeatureFlags model and signal
- apps/api/producers/admin.py - Add ProducerFeatureFlagsInline and bulk actions
- apps/api/producers/serializers.py - Add FeatureFlagsSerializer, update ProducerSerializer
- apps/api/producers/views.py - Update queryset to use select_related('feature_flags')
- apps/producer/src/types/index.ts - Add FeatureFlags and FeatureFlagKey types
- apps/producer/src/constants/data.ts - Add featureFlag property to nav items
- apps/producer/src/components/layout/app-sidebar.tsx - Filter navigation by flags
Deleted Files: - None
7. Testing Strategy¶
7.1 Test Coverage Plan¶
Unit Tests:
- ProducerFeatureFlags model creation and defaults
- Signal auto-creates flags when Producer created
- Serializer correctly formats flag data
- Hook correctly parses and provides flag checks
- Navigation filtering logic
Integration Tests: - API returns flags with producer data - Admin inline saves flag changes - Bulk actions apply to multiple producers - Authenticated API calls include correct flags
End-to-End Tests: - Admin enables flag → Producer sees new nav item - Admin disables flag → Producer nav item disappears - New producer created → Gets default flags (all disabled)
Performance Tests: - Flag check doesn't add > 10ms latency - select_related eliminates N+1 queries - Frontend flag checks don't cause re-renders
7.2 Test Environment Requirements¶
Development: - Local Django server with test database - Test fixtures with producers having various flag states - Frontend dev server with mock API responses
Staging: - Full stack deployment - Test producer accounts with different flag configurations - Admin access for flag toggling
Production: - Feature flag rollout to internal test accounts first - Monitor performance metrics - Gradual rollout to real producers
7.3 Acceptance Criteria¶
Definition of Done: - [ ] ProducerFeatureFlags model created and migrated - [ ] Django admin shows inline flag toggles - [ ] API includes feature_flags in producer response - [ ] Frontend hook provides flag checking capability - [ ] Navigation dynamically filters based on flags - [ ] All unit and integration tests pass - [ ] Code review completed - [ ] Documentation updated - [ ] Manual QA verified in staging - [ ] Zero errors in production monitoring - [ ] Admin can successfully toggle flags
Flag-Specific Acceptance: - [ ] Knowledge Base flag hides/shows KB nav item - [ ] AI Agents flag hides/shows AI nav item - [ ] Additional Services flag hides/shows services nav item
8. Risk Assessment & Mitigation¶
8.1 Technical Risks¶
| Risk | Probability | Impact | Mitigation Strategy |
|---|---|---|---|
| Migration fails on existing producers | Low | High | Write migration with create-only logic, test on staging DB first |
| API breaking change affects existing clients | Low | High | Feature flags are additive (new field), existing API responses unchanged |
| Frontend flag checks cause performance issues | Medium | Medium | Use context provider, memoize flag checks, minimize re-renders |
| Admin accidentally enables experimental features | Medium | Low | Add confirmation dialogs, clear help text, reversible actions |
| Missing flags break producer portal | Low | High | Implement graceful defaults (fail open), signal ensures flags exist |
8.2 Resource Risks¶
Timeline Risks: - Frontend hook complexity might take longer than estimated - Testing across all navigation scenarios could extend QA - Mitigation: Start with simplest implementation, iterate based on feedback
Skill Gaps: - Team may need Django signals refresher - TypeScript generic types for hook might be tricky - Mitigation: Reference existing UserProfile signal, use simpler hook API initially
External Dependencies: - None - all work is internal
8.3 Rollback Strategy¶
Feature Flags (Meta!): - Consider adding a "master switch" to disable entire flag system if needed - Database migration is reversible
Deployment Strategy: - Deploy backend first (API change is additive, won't break frontend) - Deploy frontend after backend is live - Gradual rollout: Enable flags for internal accounts first
Rollback Procedures: 1. Frontend rollback: Revert to previous version (flags ignored, all nav shows) 2. Backend rollback: Revert migration, remove model 3. Emergency: Set all flags to True in admin (show all features)
9. Deployment & Operations¶
9.1 Deployment Plan¶
Environment Progression: 1. Dev → Staging (Week 1): - Deploy backend changes - Run migration on staging DB - Verify admin interface - Deploy frontend changes - QA full feature in staging
- Staging → Production (Week 2):
- Schedule maintenance window (optional, non-breaking change)
- Deploy backend first (API is backward compatible)
- Run migration on production DB
- Verify no errors in logs
- Deploy frontend
- Enable flags for internal test accounts
- Monitor for 24 hours
- Gradually enable for beta producers
Database Migration:
# Staging
docker-compose exec api python manage.py migrate producers
# Production
python manage.py migrate producers --database=default
Configuration Updates: - No environment variables needed - No feature flags config files - Admin permissions are existing Django permissions
9.2 Monitoring & Observability¶
Key Metrics: - API response time for producer endpoints (should not increase) - Database query count (should not add N+1 queries) - Admin page load time - Frontend navigation render time - Error rates after deployment
Alerting: - Spike in 500 errors from producer API - Migration failures - Missing feature_flags in API responses - Frontend errors related to undefined flags
Logging:
# Backend logging
logger.info(f"Feature flags accessed for producer {producer.id}")
# Frontend logging
console.debug('Feature flags loaded:', flags);
9.3 Support & Maintenance¶
Documentation: - Admin user guide: "How to Enable Feature Flags" - Developer guide: "Adding New Feature Flags" - Architecture doc update with flag system overview
Training: - Admin team walkthrough of flag toggles - Developer team code review and Q&A - Support team briefing on feature availability
Ongoing Maintenance: - Add new flags as features are developed - Remove flags once features are fully rolled out - Monitor flag usage to decide when to make features permanent
10. Success Measurement¶
10.1 Success Metrics¶
Technical Metrics: - Zero increase in API response time (< 5ms acceptable) - Zero new production errors related to flags - 100% test coverage for flag-related code - Migration completes in < 1 minute
User Metrics: - Admin can toggle flags in < 30 seconds - Producers see navigation update immediately (< 1 second) - Zero confused support tickets about "missing features"
Business Metrics: - Ability to enable beta features for 5-10 test producers - Foundation for future tiered pricing model - Reduced risk of feature launches (gradual rollout)
10.2 Review Schedule¶
1 Week Post-Launch: - Review error logs and performance metrics - Gather admin feedback on usability - Check if flags are being used as intended
1 Month Post-Launch: - Assess flag adoption (how many producers have flags enabled) - Identify any performance issues - Decide if additional flags are needed
3 Months Post-Launch: - Evaluate if feature flag system met goals - Plan for next generation of flags (if needed) - Consider more advanced features (time-based, percentage rollouts)
11. Appendices¶
Appendix A: Navigation Items Affected¶
Based on current navigation structure, here's how flags will be applied:
Current Navigation (from constants/data.ts):
export const navItems: NavItem[] = [
{ title: 'Dashboard', url: '/dashboard/overview' }, // Always visible
{ title: 'Shows', url: '/dashboard/shows' }, // Always visible
{ title: 'Orders', url: '/dashboard/orders' }, // Always visible
{ title: 'Finances', url: '/dashboard/finances' }, // Always visible
{ title: 'Support', url: '/dashboard/support' }, // Always visible
];
Future Navigation with Flags:
export const navItems: NavItem[] = [
{ title: 'Dashboard', url: '/dashboard/overview' },
{ title: 'Shows', url: '/dashboard/shows' },
{ title: 'Orders', url: '/dashboard/orders' },
{ title: 'Finances', url: '/dashboard/finances' },
// NEW: Gated by feature flags
{
title: 'Knowledge Base',
url: '/dashboard/knowledge-base',
icon: 'bookOpen',
featureFlag: 'knowledgeBaseEnabled' // NEW property
},
{
title: 'AI Assistant',
url: '/dashboard/ai-assistant',
icon: 'bot',
featureFlag: 'aiAgentsEnabled'
},
{
title: 'Additional Services',
url: '/dashboard/services',
icon: 'package',
featureFlag: 'additionalServicesEnabled'
},
{ title: 'Support', url: '/dashboard/support' },
];
Appendix B: Code Examples¶
Backend Model (Complete):
# apps/api/producers/models.py
class ProducerFeatureFlags(models.Model):
"""Feature flags for producer portal features."""
producer = models.OneToOneField(
Producer,
on_delete=models.CASCADE,
related_name='feature_flags'
)
knowledge_base_enabled = models.BooleanField(
default=False,
help_text="Enable knowledge base access"
)
ai_agents_enabled = models.BooleanField(
default=False,
help_text="Enable AI assistant features"
)
additional_services_enabled = models.BooleanField(
default=False,
help_text="Enable additional services"
)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
verbose_name = "Feature Flags"
verbose_name_plural = "Feature Flags"
def __str__(self):
return f"Flags for {self.producer.name}"
@receiver(post_save, sender=Producer)
def create_feature_flags(sender, instance, created, **kwargs):
if created:
ProducerFeatureFlags.objects.create(producer=instance)
Frontend Hook (Complete):
// apps/producer/src/hooks/use-feature-flags.ts
import { useSession } from 'next-auth/react';
import useSWR from 'swr';
import { FeatureFlags, FeatureFlagKey } from '@/types';
interface ProducerResponse {
featureFlags: FeatureFlags;
// ... other producer fields
}
export function useFeatureFlags() {
const { data: session } = useSession();
const { data, error, isLoading } = useSWR<ProducerResponse>(
session ? '/api/v1/producers/me/' : null,
fetcher
);
const hasFeature = (flag: FeatureFlagKey): boolean => {
// Default to false if loading or error
if (!data?.featureFlags) return false;
return data.featureFlags[flag] ?? false;
};
return {
flags: data?.featureFlags ?? null,
hasFeature,
isLoading,
error
};
}
Navigation Filtering:
// apps/producer/src/components/layout/app-sidebar.tsx
export default function AppSidebar() {
const { hasFeature } = useFeatureFlags();
// Filter nav items based on feature flags
const visibleNavItems = navItems.filter(item => {
if (!item.featureFlag) return true; // Always show if no flag
return hasFeature(item.featureFlag);
});
return (
<Sidebar>
<SidebarMenu>
{visibleNavItems.map((item) => (
<SidebarMenuItem key={item.title}>
{/* ... existing rendering logic */}
</SidebarMenuItem>
))}
</SidebarMenu>
</Sidebar>
);
}
Appendix C: Admin Configuration¶
Admin Inline:
# apps/api/producers/admin.py
class ProducerFeatureFlagsInline(TabularInline):
model = ProducerFeatureFlags
extra = 0
fields = [
'knowledge_base_enabled',
'ai_agents_enabled',
'additional_services_enabled'
]
can_delete = False
verbose_name = "Feature Flags"
verbose_name_plural = "Feature Flags"
@admin.register(Producer)
class ProducerAdmin(ModelAdmin):
inlines = [
ProducerFinancialInline,
UserProducerAssociationInline,
ProducerFeatureFlagsInline # NEW
]
actions = ['enable_knowledge_base', 'enable_ai_agents']
@admin.action(description="Enable Knowledge Base for selected producers")
def enable_knowledge_base(self, request, queryset):
count = 0
for producer in queryset:
flags, _ = ProducerFeatureFlags.objects.get_or_create(
producer=producer
)
flags.knowledge_base_enabled = True
flags.save()
count += 1
self.message_user(
request,
f"Enabled Knowledge Base for {count} producers"
)
Quick Checklist for Document Completion¶
Research Phase¶
- Analyzed existing codebase thoroughly
- Researched industry best practices
- Identified all stakeholders and requirements
- Assessed technical constraints and dependencies
Planning Phase¶
- Created detailed implementation plan
- Defined clear acceptance criteria
- Identified and mitigated risks
- Planned testing strategy
Review Phase¶
- Technical review completed
- Stakeholder approval obtained
- Resource allocation confirmed
- Timeline approved by team
Documentation¶
- All sections completed with specific details
- File references are accurate and current
- External links verified and accessible (N/A - no external links needed)
- Document reviewed for clarity and completeness
Document Information: - Created: 2025-10-16 - Last Updated: 2025-10-16 - Version: 1.0 (MVP Planning) - Author(s): Claude Code - Reviewers: TBD - Status: Draft - Ready for Review
Summary for Implementation¶
This plan provides a comprehensive blueprint for implementing producer-level feature flags in the PiqueTickets platform. The MVP will include:
- Backend:
ProducerFeatureFlagsDjango model with 3 boolean flags - Admin: Inline editing interface with bulk actions
- API: Feature flags included in producer data response
- Frontend: Custom hook and navigation filtering
The implementation carries minimal risk due to the additive nature of the changes. The feature will enable gradual rollout of new producer portal features, reducing deployment risk and creating a foundation for future product tiers.
Next Steps: 1. Review and approve this plan 2. Create implementation ticket/branch (PIQUE-521) 3. Begin Phase 1: Backend Foundation 4. Follow the detailed task breakdown in section 6.2