DeutschLernen/docs/features/gamification.md
Lasse Rune Hansen 76e8af4987 Add complete solution: documentation, frontend, and project files
- Add comprehensive documentation in docs/ (architecture, features, roadmap)
- Add german-app-frontend with Vite, TypeScript, ESLint configuration
- Add AGENTS.md and .gitignore

Generated by Mistral Vibe.
Co-Authored-By: Mistral Vibe <vibe@mistral.ai>
2026-05-31 18:20:53 +02:00

416 lines
15 KiB
Markdown
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# Feature: Gamification System
> **Status**: ⏳ Planned
> **Priority**: Medium
> **Complexity**: Medium
> **Estimate**: 6-8 hours
> **Assignee**: -
> **Created**: May 31, 2025
> **Target Completion**: -
> **PR**: -
> **Related Features**: Infrastructure Setup, User Authentication, Lesson Management, Quiz System
---
## 📌 Overview
### Purpose
Implement gamification features (points, badges, streaks) to motivate users and provide a sense of achievement as they progress through the German learning journey.
### User Story
As a learner, I want to earn points, badges, and maintain streaks for my learning activities so that I stay motivated and can see my progress over time.
### Acceptance Criteria
- [ ] Users earn points for completing lessons and passing quizzes
- [ ] Users earn badges for specific achievements
- [ ] Daily streaks are tracked and displayed
- [ ] Users can view their points, badges, and streak on dashboard
- [ ] Leaderboard shows top users (optional)
- [ ] Achievement notifications are displayed
---
## 📋 Requirements
### Functional Requirements
| ID | Requirement | Priority |
|----|-------------|----------|
| FR-001 | Earn points for completing lessons | High |
| FR-002 | Earn points for passing quizzes | High |
| FR-003 | Define and award badges for achievements | High |
| FR-004 | Track daily learning streaks | High |
| FR-005 | Display points, badges, streak on dashboard | High |
| FR-006 | Show badge details and unlock criteria | Medium |
| FR-007 | Implement leaderboard (optional) | Low |
| FR-008 | Send achievement notifications | Low |
### Non-Functional Requirements
- Performance: Gamification updates < 100ms
- Scalability: System should handle thousands of users
- Security: Prevent points/badges exploitation
---
## 🏗️ Technical Design
### Components Involved
- **Backend**: GamificationController, GamificationService, PointsService, BadgeService, StreakService
- **Database**: Badges, UserBadges tables (from schema), Users table (points and streak fields)
- **Models**: Badge, UserBadge, PointsTransaction, Achievement
- **Frontend**: Dashboard components, BadgeDisplay, PointsDisplay, StreakDisplay
### Data Flow
```
1. User completes a lesson or passes a quiz
2. Backend calculates points earned
3. Backend updates User.TotalPoints
4. Backend checks if any badges are earned
5. If badge earned, create UserBadge record
6. Backend updates daily streak if applicable
7. Frontend displays updated gamification data
```
### Points System
| Action | Points | Notes |
|--------|--------|-------|
| Complete Lesson | 10 | Awarded once per lesson |
| Pass Quiz (first try) | 20 | Bonus for first-time pass |
| Pass Quiz (subsequent) | 10 | Still earns points |
| Perfect Quiz Score | +5 | Bonus for 100% |
| Daily Login | 5 | Encourages daily use |
### Badge System
| Badge Name | Criteria | Description |
|------------|----------|-------------|
| First Lesson | Complete 1 lesson | Getting Started |
| A1 Complete | Complete all A1 lessons | A1 Master |
| Perfect Score | Pass 5 quizzes with 100% | Perfect Student |
| Streak 7 | 7-day learning streak | Weekly Warrior |
| Streak 30 | 30-day learning streak | Monthly Marvel |
| Early Bird | Complete lesson before 9 AM | Morning Learner |
| Night Owl | Complete lesson after 9 PM | Late Night Learner |
| Vocabulary Master | Learn 100 words | Word Champion |
| Grammar Guru | Pass 10 grammar quizzes | Grammar Expert |
### Streak System
- Streak increments by 1 for each day with at least one completed activity
- Streak resets if user has no activity for 24 hours
- Last activity timestamp stored in User table
### API Endpoints
| Endpoint | Method | Description | Auth Required |
|----------|--------|-------------|----------------|
| `/api/gamification/me` | GET | Get current user's gamification data | Yes |
| `/api/gamification/points` | GET | Get user's points history | Yes |
| `/api/gamification/badges` | GET | List all badges | Yes |
| `/api/gamification/badges/earned` | GET | List user's earned badges | Yes |
| `/api/gamification/badges/{id}` | GET | Get badge details | Yes |
| `/api/gamification/leaderboard` | GET | Get top users by points | Yes |
| `/api/gamification/streak` | GET | Get streak information | Yes |
### Database Schema (from application-plan.md)
```sql
-- Badges table
CREATE TABLE Badges (
Id SERIAL PRIMARY KEY,
Name VARCHAR(50) NOT NULL,
Description TEXT,
ImageUrl VARCHAR(255),
CriteriaType VARCHAR(50) NOT NULL, -- e.g., 'lessons_completed', 'streak_days'
CriteriaValue INT NOT NULL, -- e.g., 10 for 10 lessons completed
PointsReward INT DEFAULT 0,
UNIQUE(Name)
);
-- User Badges table
CREATE TABLE UserBadges (
UserId INT REFERENCES Users(Id) ON DELETE CASCADE,
BadgeId INT REFERENCES Badges(Id) ON DELETE CASCADE,
EarnedDate TIMESTAMP DEFAULT NOW(),
PRIMARY KEY (UserId, BadgeId)
);
-- Users table (existing fields)
ALTER TABLE Users ADD COLUMN TotalPoints INT DEFAULT 0;
ALTER TABLE Users ADD COLUMN Streak INT DEFAULT 0;
ALTER TABLE Users ADD COLUMN LastActivityDate TIMESTAMP;
```
---
## 🚀 Implementation Plan
### Phase 1: Database & Models (2 hours)
- [ ] Update Users table with gamification fields
- [ ] Create Badge entity
- [ ] Create UserBadge entity
- [ ] Create PointsTransaction entity (optional for history)
- [ ] Create DTOs for gamification data
- [ ] Create migrations
- [ ] Seed initial badges
### Phase 2: Points Service (1-2 hours)
- [ ] Create PointsService
- [ ] Implement points calculation logic
- [ ] Create points awarding mechanism
- [ ] Implement points history tracking
- [ ] Create PointsTransaction repository
### Phase 3: Badge Service (2 hours)
- [ ] Create BadgeService
- [ ] Implement badge criteria checking
- [ ] Create badge awarding mechanism
- [ ] Implement badge checking on user actions
- [ ] Create badge details endpoint
### Phase 4: Streak Service (1-2 hours)
- [ ] Create StreakService
- [ ] Implement streak calculation logic
- [ ] Create streak update mechanism
- [ ] Handle streak reset logic
- [ ] Create streak endpoint
### Phase 5: Gamification Controller (1 hour)
- [ ] Create GamificationController
- [ ] Implement all endpoints
- [ ] Add authorization
- [ ] Add validation
- [ ] Write tests
### Phase 6: Frontend Integration (2 hours)
- [ ] Create Dashboard gamification section
- [ ] Create BadgeDisplay component
- [ ] Create PointsDisplay component
- [ ] Create StreakDisplay component
- [ ] Create Leaderboard component (optional)
- [ ] Add achievement notifications
### Milestones
| Milestone | Date | Status |
|-----------|------|--------|
| Database & Models | - | |
| Points Service | - | |
| Badge Service | - | |
| Streak Service | - | |
| Controller | - | |
| Frontend Integration | - | |
---
## ✅ Tasks
### Backend
- [ ] Update Domain/Entities/User.cs with gamification fields
- [ ] Create Domain/Entities/Badge.cs
- [ ] Create Domain/Entities/UserBadge.cs
- [ ] Create Application/DTOs/GamificationDto.cs
- [ ] Create Application/DTOs/BadgeDto.cs
- [ ] Create Application/DTOs/UserBadgeDto.cs
- [ ] Create Domain/Interfaces/IBadgeRepository.cs
- [ ] Create Domain/Interfaces/IUserBadgeRepository.cs
- [ ] Create Infrastructure/Data/Repositories/BadgeRepository.cs
- [ ] Create Infrastructure/Data/Repositories/UserBadgeRepository.cs
- [ ] Create Application/Services/PointsService.cs
- [ ] Create Application/Services/BadgeService.cs
- [ ] Create Application/Services/StreakService.cs
- [ ] Create Application/Services/GamificationService.cs
- [ ] Create Presentation/Controllers/GamificationController.cs
- [ ] Register services in Program.cs
- [ ] Write unit tests
- [ ] Write integration tests
### Database
- [ ] Create migration for gamification fields in Users
- [ ] Create migration for Badges table
- [ ] Create migration for UserBadges table
- [ ] Seed initial badges
- [ ] Apply migrations
### Integration
- [ ] Integrate PointsService with LessonService
- [ ] Integrate PointsService with QuizService
- [ ] Integrate BadgeService with user actions
- [ ] Integrate StreakService with user activity
- [ ] Add gamification updates to relevant endpoints
### Frontend
- [ ] Update DashboardPage with gamification section
- [ ] Create components/Gamification/PointsDisplay.tsx
- [ ] Create components/Gamification/StreakDisplay.tsx
- [ ] Create components/Gamification/BadgeDisplay.tsx
- [ ] Create components/Gamification/BadgeList.tsx
- [ ] Create components/Gamification/Leaderboard.tsx (optional)
- [ ] Create hooks/useGamification.ts
- [ ] Add achievement notification system
---
## 🔗 Dependencies
### Feature Dependencies
- [Infrastructure Setup](infrastructure-setup.md) - Required
- [User Authentication](user-authentication.md) - Required (for user-specific data)
- [Lesson Management](lesson-management.md) - Required (points for lessons)
- [Quiz System](quiz-system.md) - Required (points for quizzes)
### Technical Dependencies
- Entity Framework Core
- AutoMapper (optional)
### Blockers
- [ ] Infrastructure Setup must be complete
- [ ] User Authentication must be complete
- [ ] Lesson Management must be complete
- [ ] Quiz System must be complete
---
## ✅ Definition of Done
### General Criteria (All Features)
- [ ] All acceptance criteria met and verified
- [ ] All tasks in this document completed
- [ ] Code follows Clean Architecture principles
- [ ] Code reviewed and approved by at least 1 team member
- [ ] All tests passing (unit, integration)
- [ ] Documentation updated (README, AGENTS.md if applicable)
- [ ] Feature works in development environment
- [ ] Feature deployed to staging environment
- [ ] Performance meets defined targets
- [ ] Security review completed
- [ ] No critical bugs or blockers
### Gamification-Specific Criteria
- [ ] Points are earned for all defined actions
- [ ] Points are displayed correctly on dashboard
- [ ] All badges are defined and seeded
- [ ] Badges are awarded automatically when criteria met
- [ ] Earned badges are displayed on user profile
- [ ] Daily streaks are tracked correctly
- [ ] Streak is displayed on dashboard
- [ ] Leaderboard (if implemented) shows correct data
- [ ] Achievement notifications are displayed
- [ ] Points and badges cannot be manipulated client-side
---
## 🧪 Testing Strategy
### Testing Approach
| Test Type | Coverage | Tools | Responsibility |
|-----------|----------|-------|----------------|
| Unit Tests | 80%+ code coverage | MsTest, Moq | Backend Dev |
| Integration Tests | All service interactions | MsTest, TestContainers | Backend Dev |
| API Tests | All endpoints | MsTest, HttpClient | Backend Dev |
| Frontend Unit Tests | Component logic | Vitest | Frontend Dev |
| Frontend Integration | Service integration | Vitest | Frontend Dev |
| E2E Tests | Critical user journeys | Playwright | QA/Dev |
| Manual Testing | Exploratory, edge cases | BrowserStack | QA |
### Gamification-Specific Tests
#### Backend Tests
- [ ] Points awarded for lesson completion correct amount
- [ ] Points awarded for quiz pass (first try) correct amount
- [ ] Points awarded for quiz pass (subsequent) correct amount
- [ ] Points awarded for perfect quiz correct amount + bonus
- [ ] Points NOT awarded for quiz fail no change
- [ ] Badge awarded when criteria met badge created
- [ ] Badge NOT awarded when criteria not met no change
- [ ] Multiple badges can be earned simultaneously all awarded
- [ ] Streak increments on daily activity +1
- [ ] Streak resets after inactivity 0
- [ ] Streak maintains across days correct count
- [ ] Leaderboard returns top N users correct ordering
#### Business Logic Tests
- [ ] Points calculation with various actions correct total
- [ ] Badge criteria evaluation correct determination
- [ ] Streak calculation across time zones consistent
- [ ] Concurrent points awards no race conditions
- [ ] Badge awarding is idempotent only awarded once
#### Security Tests
- [ ] Points cannot be awarded client-side server-only
- [ ] Badges cannot be awarded client-side server-only
- [ ] Streak cannot be manipulated client-side server-only
- [ ] Leaderboard doesn't expose sensitive data verified
#### Frontend Tests
- [ ] Points display updates after earning correct
- [ ] Badge display shows earned badges correct
- [ ] Badge details modal shows correct info verified
- [ ] Streak display updates daily correct
- [ ] Achievement notification appears when earned verified
- [ ] Leaderboard displays correctly verified
---
## 📝 Notes & Decisions
### Decisions Made
| Date | Decision | Rationale |
|------|----------|-----------|
| May 31, 2025 | Points for lesson completion | Encourages progress through curriculum |
| May 31, 2025 | Badge system | Provides goals and achievements |
| May 31, 2025 | Daily streaks | Encourages consistent daily use |
| May 31, 2025 | Server-authoritative | Prevents client-side manipulation of points |
| May 31, 2025 | No negative points | Positive reinforcement only |
### Technical Notes
- Points should be awarded server-side only, never client-side
- Badge criteria should be checked on relevant user actions
- Streak calculation: Compare LastActivityDate with previous day
- Consider time zones for daily streaks (use UTC for consistency)
- Badge images can be stored as URLs or base64 encoded
### Points Calculation Examples
```
Lesson Completion:
- Base: 10 points
- First-time: +10 = 20 points total (with Quiz bonus)
Quiz Pass:
- First try: 20 points
- Subsequent: 10 points
- Perfect score: +5 bonus
```
### Badge Criteria Types
- `lessons_completed`: Number of lessons completed
- `quizzes_passed`: Number of quizzes passed
- `streak_days`: Current streak in days
- `perfect_quizzes`: Number of perfect scores
- `vocabulary_learned`: Number of vocabulary words mastered
- `levels_completed`: Number of CEFR levels completed
### Gotchas
- Points can get large - use INT or BIGINT
- Badge criteria may need adjustment based on testing
- Streak calculation must handle time zones correctly
- Users may try to game the system - validate all inputs
- Badge images may have copyright issues - use original or licensed images
---
## 📊 Progress History
| Date | Status Change | Notes |
|------|---------------|-------|
| May 31, 2025 | Created | Initial plan based on application-plan.md |
---
## 📎 Related Files & Links
- Architecture: [Backend Structure](../architecture/backend-structure.md)
- Architecture: [Application Plan](../architecture/application-plan.md)
- Database Schema: [Initial Database Schema](../database/initial-database-schema.sql)
- Feature: [User Authentication](user-authentication.md)
- Feature: [Lesson Management](lesson-management.md)
- Feature: [Quiz System](quiz-system.md)
---
*Feature created from application-plan.md*