AI Flashcard Generator Flow - Business Rules & Test Cases
Tool Purpose: Convert any content into AI-generated study flashcards with multiple export formats and sharing capabilities for educational use.
Last Updated: July 16, 2025
Version: 1.0
Tool Status: Production
Code Location: /apps/tools-app/src/components/flashcards/
đź“‹ Table of Contents
- Flow Overview
- Step-by-Step Business Rules
- API Integration
- Data Persistence
- Export & Sharing System
- Test Case Categories
- Performance Requirements
- Error Handling
Flow Overview
Flow Types
- Anonymous Users: 24-hour session-based, 10 generations/day limit
- Authenticated Users: Persistent storage, 100 generations/day limit
- Admin Users: Unlimited generations, enhanced features
Core Principles
- Educational Focus: Generate study-appropriate flashcards
- AI-Powered: Use GPT-4 for intelligent content analysis
- Multi-Format: Support multiple input types (text, topic, URL)
- Export Flexibility: Multiple export formats for different use cases
- Sharing Enabled: Public/private sharing with SEO optimization
User Journey Flow
Content Input → Generation Options → AI Processing → Review Cards → Export/Share
↓ ↓ ↓ ↓ ↓
Validation Customization Content Analysis Edit Cards Multiple FormatsStep-by-Step Business Rules
Step 1: Content Input Selection
BR-FC-001: Input Method Selection
- Rule: Users must select one of three input methods: Text Content, AI Topic, or URL
- Implementation:
FlashcardGenerator.tsx:285-322- Tab-based interface - Test: Verify only one input method is active at a time
- Rationale: Clear user experience with focused input methods
BR-FC-002: Text Content Validation
- Rule: Text content must be 10-50,000 characters, display word count and estimated cards
- Implementation:
FlashcardGenerator.tsx:209-219- Real-time validation - Test: Verify validation messages and word count calculations
- Rationale: Ensure sufficient content for quality flashcard generation
BR-FC-003: AI Topic Input
- Rule: AI topic input must be a clear subject/topic (e.g., “Photosynthesis”, “World War II”)
- Implementation:
FlashcardGenerator.tsx:359-384- Topic input validation - Test: Verify topic suggestions and AI content generation
- Rationale: Enable AI to generate educational content about specific topics
BR-FC-004: URL Content Extraction
- Rule: URLs must be valid HTTP/HTTPS links, extract content for flashcard generation
- Implementation:
FlashcardGenerator.tsx:387-412- URL validation and processing - Test: Verify URL validation and content extraction
- Rationale: Support article-based flashcard generation
Step 2: Generation Options Configuration
BR-FC-005: Card Count Selection
- Rule: Users can select 5-50 cards, with estimated cards based on content length
- Implementation:
GenerationOptions.tsx- Card count slider - Test: Verify card count validation and estimation accuracy
- Rationale: Balance between comprehensive coverage and manageable study sets
BR-FC-006: Complexity Level Setting
- Rule: Four complexity levels: Simple, Intermediate, Advanced, Mixed
- Implementation:
GenerationOptions.tsx- Complexity dropdown - Test: Verify AI generates appropriate complexity for each level
- Rationale: Adapt content difficulty to user’s educational needs
BR-FC-007: Style Preferences
- Rule: Three style options: Concise, Detailed, Conversational
- Implementation:
GenerationOptions.tsx- Style selection - Test: Verify AI output matches selected style
- Rationale: Accommodate different learning preferences
BR-FC-008: Advanced Options
- Rule: Optional hints, card types, language selection, public/private settings
- Implementation:
GenerationOptions.tsx- Advanced options panel - Test: Verify all options affect AI generation appropriately
- Rationale: Provide customization for different educational contexts
Step 3: AI Generation Process
BR-FC-009: Rate Limiting Enforcement
- Rule: Anonymous users: 10/day, Authenticated: 100/day, Admin: unlimited
- Implementation:
rate-limiter.ts:checkRateLimit()- Rate limit checking - Test: Verify rate limits are enforced correctly for each user type
- Rationale: Prevent abuse while allowing reasonable educational use
BR-FC-010: AI Content Generation
- Rule: Use GPT-4 with educational prompts, validate JSON response, ensure card quality
- Implementation:
openai.ts:FlashcardAI.generateFlashcards()- AI integration - Test: Verify AI generates valid, educational flashcards
- Rationale: Ensure high-quality, educational content generation
BR-FC-011: Content Validation
- Rule: Validate AI response structure, sanitize content, ensure educational appropriateness
- Implementation:
openai.ts:validateFlashcardResponse()- Response validation - Test: Verify malformed responses are handled gracefully
- Rationale: Ensure reliable, safe content for educational use
Step 4: Deck Management
BR-FC-012: Deck Creation
- Rule: Create deck with unique share code, save to database, track analytics
- Implementation:
generate/route.ts:POST- Deck creation API - Test: Verify deck creation with all metadata
- Rationale: Enable sharing and persistence of generated content
BR-FC-013: Deck Metadata
- Rule: Include SEO title/description, tags, category, difficulty level
- Implementation:
types/index.ts:FlashcardDeck- Deck structure - Test: Verify metadata is properly generated and stored
- Rationale: Support discovery and organization of educational content
BR-FC-014: Session Management
- Rule: Anonymous users get 24-hour sessions, authenticated users get persistent storage
- Implementation:
session.ts:SessionManager- Session handling - Test: Verify session creation and expiration
- Rationale: Balance accessibility with resource management
Step 5: Review & Edit Interface
BR-FC-015: Flashcard Display
- Rule: Display cards in front/back format, show card type and difficulty
- Implementation:
FlashcardViewer.tsx- Card display component - Test: Verify all card types display correctly
- Rationale: Provide clear review interface for generated content
BR-FC-016: Card Editing
- Rule: Users can edit front/back text, hints, and card metadata
- Implementation:
FlashcardViewer.tsx- Edit functionality - Test: Verify edits are saved and validated
- Rationale: Allow customization of AI-generated content
BR-FC-017: Card Management
- Rule: Users can delete cards, reorder cards, star favorites
- Implementation:
FlashcardViewer.tsx- Card management - Test: Verify all management operations work correctly
- Rationale: Provide full control over study deck organization
API Integration
Core API Endpoints
POST /api/flashcards/generate
Purpose: Generate flashcards from content using AI Request Schema:
{
title?: string,
content: string,
sourceType: 'text' | 'ai_topic' | 'url',
options: GenerationOptions,
isPublic: boolean,
tags: string[],
category?: string
}Response Schema:
{
success: boolean,
deck: FlashcardDeck,
flashcards: Flashcard[],
shareUrl: string,
gameUrl: string,
remainingLimit: number,
generationTime: number
}Business Rules:
- BR-FC-018: Validate request body with Zod schema
- BR-FC-019: Check rate limits before processing
- BR-FC-020: Track generation analytics and AI usage
- BR-FC-021: Return consistent response format
GET /api/flashcards/[shareCode]
Purpose: Retrieve flashcard deck by share code Business Rules:
- BR-FC-022: Validate share code format
- BR-FC-023: Check deck visibility (public/private)
- BR-FC-024: Increment view count
- BR-FC-025: Return deck with all flashcards
PATCH /api/flashcards/[shareCode]
Purpose: Update deck metadata and cards Business Rules:
- BR-FC-026: Verify user ownership or session
- BR-FC-027: Validate update payload
- BR-FC-028: Update timestamp on changes
- BR-FC-029: Maintain share code consistency
DELETE /api/flashcards/[shareCode]
Purpose: Delete flashcard deck Business Rules:
- BR-FC-030: Verify user ownership or session
- BR-FC-031: Cascade delete all related cards
- BR-FC-032: Update analytics on deletion
- BR-FC-033: Return confirmation response
POST /api/flashcards/[shareCode]/export
Purpose: Export deck in various formats Business Rules:
- BR-FC-034: Validate export format
- BR-FC-035: Check deck access permissions
- BR-FC-036: Generate format-specific content
- BR-FC-037: Track export analytics
Data Persistence
Database Schema
tools_flashcard_decks Table
Primary Fields:
id(TEXT): Unique deck identifiertitle(TEXT): User-provided or AI-generated titleshare_code(TEXT): Short, memorable sharing codeis_public(BOOLEAN): Public visibility settingsource_type(TEXT): Input method usedgeneration_options(JSONB): AI generation parameters
Engagement Tracking:
view_count,share_count,export_count,game_play_countcreated_at,updated_at,expires_at
SEO & Discovery:
seo_title,seo_description,keywords[]tags[],category,difficulty_level
tools_flashcards Table
Card Content:
front_text,back_text,hint_textcard_type,difficulty,sort_orderimportance_score,estimated_study_time
AI Metadata:
ai_confidence,ai_generation_promptuser_notes,is_starred,is_archived
Data Flow Rules
BR-FC-038: Deck-Card Relationship
- Rule: Each deck can have multiple cards, cards belong to exactly one deck
- Implementation: Foreign key relationship with CASCADE delete
- Test: Verify deck deletion removes all associated cards
- Rationale: Maintain data integrity and prevent orphaned records
BR-FC-039: Session-Deck Association
- Rule: Each deck must be associated with a session (anonymous) or user (authenticated)
- Implementation:
session_idrequired,user_idoptional - Test: Verify session-based access control
- Rationale: Enable both anonymous and authenticated usage
BR-FC-040: Expiration Handling
- Rule: Anonymous decks expire after 24 hours, authenticated decks persist
- Implementation:
expires_attimestamp for session-based content - Test: Verify expired content is inaccessible
- Rationale: Balance resource usage with user convenience
Export & Sharing System
Export Formats
BR-FC-041: PDF Export
- Rule: Generate print-optimized PDF with proper card layout
- Implementation:
export/route.ts- PDF generation using jsPDF - Test: Verify PDF quality and card formatting
- Rationale: Enable physical study materials
BR-FC-042: Anki Export
- Rule: Generate tab-separated format compatible with Anki import
- Implementation:
export/route.ts- Anki format generation - Test: Verify Anki import compatibility
- Rationale: Support popular spaced repetition software
BR-FC-043: CSV Export
- Rule: Generate spreadsheet-compatible CSV format
- Implementation:
export/route.ts- CSV generation - Test: Verify CSV structure and data integrity
- Rationale: Enable data analysis and custom processing
BR-FC-044: JSON Export
- Rule: Export complete deck data in structured JSON format
- Implementation:
export/route.ts- JSON serialization - Test: Verify JSON structure and completeness
- Rationale: Support programmatic access and backup
Sharing System
BR-FC-045: Share Code Generation
- Rule: Generate memorable 8-character share codes (e.g., “MATH123A”)
- Implementation:
share-codes.ts:generateShareCode()- Code generation - Test: Verify code uniqueness and memorability
- Rationale: Enable easy sharing in educational environments
BR-FC-046: Public/Private Visibility
- Rule: Users can set decks as public (discoverable) or private (link-only)
- Implementation:
is_publicflag with search filtering - Test: Verify visibility controls work correctly
- Rationale: Balance sharing with privacy needs
BR-FC-047: SEO Optimization
- Rule: Public decks include optimized titles, descriptions, and metadata
- Implementation: SEO fields in database and meta tags
- Test: Verify SEO metadata is properly generated
- Rationale: Support discovery through search engines
Test Case Categories
Critical Path Testing
TC-FC-001: Complete Generation Flow
- Tests: BR-FC-001, BR-FC-002, BR-FC-009, BR-FC-010, BR-FC-012
- Scenario: User inputs text → selects options → generates flashcards → views results
- Expected: Successful generation with proper analytics tracking
- Implementation:
e2e/flashcard-generation.test.ts - Priority: P0 (Critical)
TC-FC-002: Rate Limit Enforcement
- Tests: BR-FC-009
- Scenario: Anonymous user exceeds 10 generations per day
- Expected: Rate limit modal shown, generation blocked
- Implementation:
integration/rate-limiting.test.ts - Priority: P0 (Critical)
TC-FC-003: Export Functionality
- Tests: BR-FC-041, BR-FC-042, BR-FC-043, BR-FC-044
- Scenario: User generates deck → exports in each format → verifies content
- Expected: All export formats work correctly
- Implementation:
integration/export.test.ts - Priority: P1 (High)
Business Logic Testing
TC-FC-004: AI Content Validation
- Tests: BR-FC-010, BR-FC-011
- Scenario: AI returns malformed or inappropriate content
- Expected: Graceful error handling with user feedback
- Implementation:
unit/ai-services.test.ts - Priority: P1 (High)
TC-FC-005: Session Management
- Tests: BR-FC-014, BR-FC-039, BR-FC-040
- Scenario: Anonymous user session expires, authenticated user persists
- Expected: Proper session handling for both user types
- Implementation:
integration/session.test.ts - Priority: P1 (High)
TC-FC-006: Deck Sharing
- Tests: BR-FC-045, BR-FC-046, BR-FC-047
- Scenario: User creates public deck → shares via link → recipient accesses
- Expected: Sharing works with proper visibility controls
- Implementation:
e2e/sharing.test.ts - Priority: P1 (High)
Integration Testing
TC-FC-007: Database Operations
- Tests: BR-FC-038, BR-FC-039, BR-FC-040
- Scenario: Create deck → add cards → update metadata → delete deck
- Expected: All database operations maintain data integrity
- Implementation:
integration/database.test.ts - Priority: P1 (High)
TC-FC-008: OpenAI Integration
- Tests: BR-FC-010, BR-FC-011
- Scenario: Various content types → AI processing → response validation
- Expected: Reliable AI integration with proper error handling
- Implementation:
integration/openai.test.ts - Priority: P1 (High)
Edge Case Testing
TC-FC-009: Large Content Processing
- Tests: BR-FC-002, BR-FC-010
- Scenario: User inputs maximum character content (50,000 chars)
- Expected: Successful processing within time limits
- Implementation:
performance/large-content.test.ts - Priority: P2 (Medium)
TC-FC-010: Concurrent User Generation
- Tests: BR-FC-009, BR-FC-010, BR-FC-012
- Scenario: Multiple users generate flashcards simultaneously
- Expected: All generations complete successfully
- Implementation:
performance/concurrent.test.ts - Priority: P2 (Medium)
TC-FC-011: Network Failure Recovery
- Tests: BR-FC-010, BR-FC-011
- Scenario: OpenAI API temporarily unavailable
- Expected: Graceful error handling with retry logic
- Implementation:
integration/network-failures.test.ts - Priority: P2 (Medium)
Performance Requirements
Response Time Standards
BR-FC-048: AI Generation Time
- Rule: Flashcard generation must complete within 10 seconds
- Implementation: Timeout handling in AI service
- Test: Verify generation completes within time limit
- Rationale: Maintain user engagement and satisfaction
BR-FC-049: Page Load Performance
- Rule: Initial page load must complete within 2 seconds
- Implementation: Optimized bundle sizes and lazy loading
- Test: Verify page load times meet requirements
- Rationale: Provide responsive user experience
BR-FC-050: Export Generation Time
- Rule: Export generation must complete within 5 seconds for most formats
- Implementation: Optimized export processing
- Test: Verify export speed across all formats
- Rationale: Enable quick access to study materials
Scalability Requirements
BR-FC-051: Concurrent User Support
- Rule: Support 100+ concurrent users without degradation
- Implementation: Proper database indexing and connection pooling
- Test: Load testing with concurrent users
- Rationale: Support classroom and institutional usage
BR-FC-052: Database Query Performance
- Rule: Database queries must complete within 100ms
- Implementation: Proper indexes and query optimization
- Test: Verify query performance under load
- Rationale: Maintain responsive application performance
Error Handling
User-Facing Error Scenarios
BR-FC-053: AI Service Failures
- Rule: Display clear error messages with suggested actions
- Implementation: Error boundaries and user feedback
- Test: Verify error messages are helpful and actionable
- Rationale: Maintain user confidence during technical issues
BR-FC-054: Rate Limit Handling
- Rule: Show rate limit modal with reset time and upgrade options
- Implementation:
RateLimitModal.tsx- Rate limit UI - Test: Verify modal displays correct information
- Rationale: Convert rate-limited users to registered users
BR-FC-055: Network Error Recovery
- Rule: Provide retry mechanisms for network failures
- Implementation: Retry logic with exponential backoff
- Test: Verify retry behavior works correctly
- Rationale: Handle temporary network issues gracefully
System Error Handling
BR-FC-056: Database Error Recovery
- Rule: Graceful degradation when database is unavailable
- Implementation: Error logging and fallback responses
- Test: Verify system remains stable during database issues
- Rationale: Maintain system reliability under adverse conditions
BR-FC-057: Input Validation Errors
- Rule: Provide clear validation feedback for invalid inputs
- Implementation: Zod schema validation with user-friendly messages
- Test: Verify validation messages are clear and helpful
- Rationale: Guide users toward successful content generation
Analytics & Monitoring
Key Performance Indicators
BR-FC-058: Generation Success Rate
- Rule: Track and maintain >95% successful generation rate
- Implementation: Analytics tracking in generation pipeline
- Test: Verify analytics capture success/failure rates
- Rationale: Monitor tool reliability and user satisfaction
BR-FC-059: User Engagement Metrics
- Rule: Track time spent, cards generated, exports/shares
- Implementation: Comprehensive analytics events
- Test: Verify all user actions are tracked
- Rationale: Understand usage patterns and improve features
BR-FC-060: Conversion Tracking
- Rule: Track email capture and main app conversion rates
- Implementation: Conversion analytics integration
- Test: Verify conversion events are tracked correctly
- Rationale: Measure business impact of educational tools
Security & Privacy
Data Protection
BR-FC-061: Content Privacy
- Rule: User content is private by default, opt-in for public sharing
- Implementation:
is_publicflag with default false - Test: Verify privacy controls work correctly
- Rationale: Protect user privacy and educational content
BR-FC-062: Session Security
- Rule: Secure session management with proper expiration
- Implementation: Encrypted session tokens with expiration
- Test: Verify session security measures
- Rationale: Protect user data and prevent unauthorized access
BR-FC-063: Input Sanitization
- Rule: Sanitize all user inputs to prevent XSS and injection attacks
- Implementation: Input validation and sanitization
- Test: Verify security measures prevent common attacks
- Rationale: Ensure platform security and user safety
Last Updated: July 16, 2025
Maintained by: Tools Development & Testing Teams