This commit is contained in:
Dmitry 2025-11-22 02:33:31 +03:00
parent ff52bbeb9e
commit ea171ec3f8
18 changed files with 79 additions and 4199 deletions

View file

@ -254,34 +254,103 @@ jobs:
print(f"❌ Error reading files: {e}")
sys.exit(1)
# Create JSON payload
# Validate title and body
if not title:
print("❌ Title is empty")
sys.exit(1)
if len(title) > 255:
print(f"⚠️ Title too long ({len(title)} chars), truncating...")
title = title[:255]
# Create JSON payload (labels are optional, may not exist in repo)
payload = {
"title": title,
"body": body
}
# Try to add labels, but don't fail if they don't exist
# Labels will be added only if they exist in the repository
payload_with_labels = {
"title": title,
"body": body,
"labels": ["ai-agent", "planning", component]
}
# Make API request
json_payload = json.dumps(payload)
# Make API request - try with labels first
json_payload = json.dumps(payload_with_labels)
print(f"📤 Sending request to: {api_url}")
print(f"📋 Title: {title[:50]}...")
print(f"📝 Body length: {len(body)} chars")
curl_cmd = [
"curl", "-X", "POST", api_url,
"-H", f"Authorization: token {token}",
"-H", "Content-Type: application/json",
"-d", json_payload,
"-f", "-s", "-S"
"-w", "\nHTTP Status: %{http_code}\n",
"-s", "-S"
]
result = subprocess.run(curl_cmd, capture_output=True, text=True)
if result.returncode == 0:
# Parse HTTP status code from output
http_status = None
response_body = result.stdout
if "HTTP Status:" in result.stdout:
parts = result.stdout.rsplit("HTTP Status:", 1)
response_body = parts[0].strip()
http_status = parts[1].strip() if len(parts) > 1 else None
# Check HTTP status code
if http_status == "201" or (result.returncode == 0 and "HTTP Status: 201" in result.stdout):
print(f"✅ Issue created for {component}")
if result.stdout:
print(f"Response: {result.stdout[:200]}")
if response_body:
try:
response = json.loads(response_body)
if "number" in response:
print(f" Issue #{response['number']} created")
except:
pass
elif http_status in ["422", "400"] or "HTTP Status: 422" in result.stdout or "HTTP Status: 400" in result.stdout:
print(f"⚠️ Labels may not exist or validation error, trying without labels...")
print(f" First attempt response: {response_body[:200]}")
# Retry without labels
json_payload = json.dumps(payload)
curl_cmd = [
"curl", "-X", "POST", api_url,
"-H", f"Authorization: token {token}",
"-H", "Content-Type: application/json",
"-d", json_payload,
"-w", "\nHTTP Status: %{http_code}\n",
"-s", "-S"
]
result = subprocess.run(curl_cmd, capture_output=True, text=True)
# Parse status again
http_status = None
response_body = result.stdout
if "HTTP Status:" in result.stdout:
parts = result.stdout.rsplit("HTTP Status:", 1)
response_body = parts[0].strip()
http_status = parts[1].strip() if len(parts) > 1 else None
if http_status == "201" or "HTTP Status: 201" in result.stdout:
print(f"✅ Issue created for {component} (without labels)")
else:
print(f"❌ Failed to create issue for {component}")
print(f"HTTP Status: {http_status}")
print(f"Response: {response_body[:500]}")
if result.stderr:
print(f"Error details: {result.stderr}")
sys.exit(1)
else:
print(f"❌ Failed to create issue for {component}")
print(f"Error: {result.stderr}")
if result.stdout:
print(f"Response: {result.stdout}")
print(f"HTTP Status: {http_status}")
print(f"Response: {response_body[:500]}")
if result.stderr:
print(f"Error: {result.stderr}")
sys.exit(1)
PYTHON_SCRIPT

View file

@ -1,131 +0,0 @@
### Короткий план единой системы доступа (policy-based authorization)
- Суть: выносим все проверки вида packId/admin/подписка/покупка/enable в единый слой Authorization Policies, а в хендлерах используем декларативные «гарды»/хелперы. В итоге в эндпоинтах остаётся одна строка вида `await access.require(PackAction.view, packId);`.
ВАЖНО: Можно удалить v1 ручки!!!
## 1) Модель прав и ресурсов
- **Resource**: `Pack`, `Card`, `Test`, `Purchase`, `AdminArea`, …
- **Actions** на ресурсы:
- `PackAction`: `list`, `view`, `cards`, `tests`, `edit`, `delete`, `buy`
- `AdminAction`: `access`
- **AccessContext**: `user`, `request`, `query`, `path`, `now`, флаги окружения.
- **AccessResult**: `allowed | denied(reason)`.
Минимум ENUMы и типы в `lib/api/authorize/acl_types.dart`.
## 2) Политики (policy layer)
- **PackAccessPolicy** единственное место истины для всех проверок паков:
- `isAdmin` → allow all pack actions
- публичные правила (например, preview pack id=10 для `view`)
- `enabled`/наличие в базе → deny с маскировкой 404 для приватных
- доступ по покупке/подписке для `view/cards/tests`
- редактирование/удаление только админам
- Аналогично при необходимости: `CardPolicy`, `TestPolicy`, `AdminPolicy`.
Реализация в `lib/api/authorize/policies/pack_policy.dart` и пр.
## 3) Сервис авторизации
- **AccessService** координирует политики: роутит ресурс+действие → нужную политику.
- API:
- `Future<void> require(ResourceAction action, {resourceId})`
- `Future<bool> can(ResourceAction action, {resourceId})`
- Варианты `requirePack(PackAction action, String packId)` и т.п.
Файл: `lib/api/authorize/access_service.dart`.
## 4) Единая загрузка моделей (resource loader)
- Вынести загрузку моделей и кэширование в **ResourceLoader**:
- `getPackModel(packId)` (с кэшем на запрос) + флаги `exists/enabled`.
- Позволяет политикам не дергать базу по 3 раза.
- Хранить в `Request.context` для reuse по всему запросу.
Файл: `lib/api/authorize/resource_loader.dart`.
## 5) Middleware
- Уже есть auth middlewares (`appAuthorize`, `authorizeV2`). Добавляем:
- `accessMiddleware`: кладёт `AccessService` и `ResourceLoader` в `Request.context`.
- Оборачиваем и v1, и v2 пайплайны в `mnemo_shelf.dart`.
Пример вставки рядом с авторизацией:
- v1: `.addMiddleware(accessMiddleware(getIt.get<AccessService>()))`
- v2: после `authorizeV2(...)` — чтобы `user` уже был в `request`.
## 6) Декларативные гарды/хелперы для роутов
- Набор хелперов, чтобы минимизировать код в хендлерах:
- `withPack(String packId, Future<Response> Function(PackModel) fn)` — загрузка/404.
- `guardPack(String packId, PackAction action)``await access.require(...);`
- Комбо-хелпер: `withPackGuarded(packId, PackAction.view, (pack) => ...)`
Файл: `lib/api/authorize/route_guards.dart`.
## 7) Миграция эндпоинтов (пошагово)
- V2 сначала (меньше риска, уже структурированы):
- `GET /api/v2/packs/<packId>`: заменить все `if (packId == '10') ...` и проверки подписки на `await access.requirePack(PackAction.view, packId);`, а логику «показывать purchased» — оставить как дополнение к ответу.
- `GET /api/v2/packs/<packId>/cards`: `await access.requirePack(PackAction.cards, packId);`
- `GET /api/v2/packs/<packId>/tests`: `await access.requirePack(PackAction.tests, packId);`
- V1 затем:
- `lib/packs/packs_api.dart`: убрать `request.user == null`/`packId != '10'`/`admin` проверки; заменить на `access.require...`.
- Редактирование/удаление: `await access.require(AdminAction.access)` или `await access.requirePack(PackAction.edit/delete, packId)`.
Важно: ошибки политики маппятся централизованно:
- `denied(unauthenticated)` → 401
- `denied(not_found_mask)` → 404
- `denied(forbidden)` → 403
- JSON ответ единообразный.
## 8) Единая конфигурация правил
- Конфиг для публичных паков и особых кейсов:
- Например, `publicPackIds = {'10'}`.
- Флаги: «разрешить изображения без авторизации для enabled pack».
- Файл: `lib/api/authorize/access_config.dart`.
## 9) Трассировка и аудит
- Лёгкий логгер в `AccessService`: кто/что/результат.
- Опционально: счётчики Prometheus (allowed/denied per policy).
## 10) Тесты
- Unit-тесты для `PackAccessPolicy` с таблицей кейсов:
- anon vs user vs admin; enabled vs disabled; purchase vs subscription; public id=10.
- Интеграционные для ключевых эндпоинтов v2.
## 11) Гайд по использованию для разработчиков
- «В хендлерах не пишем `if (user == null || ...)` — только `access.require(...)`».
- Если нужен объект — `withPackGuarded(packId, action, (pack) => ...)`.
- Любые изменения правил — только в Policy, нигде больше.
## Короткий пример (идея API)
```dart
// handler
@Route.get('/packs/<packId>/cards')
Future<Response> getPackCards(Request request, String packId) async {
final access = request.access; // из middleware
await access.requirePack(PackAction.cards, packId);
return withPack(packId, (pack) async {
final cards = await loadCards(pack); // бизнес-логика без проверок
return ok({'items': cards});
});
}
```
## Что это даст
- Единая точка правил: меньше багов, проще изменять доступ.
- Читабельные хендлеры без разрозненных `if`.
- Предсказуемые коды ошибок и ответы.
- Уменьшение дублирования загрузки моделей.

View file

@ -1,107 +0,0 @@
# Настройка HTTPS для домена 1592725-cf88967.twc1.net
## Что было сделано
✅ **Сервер теперь поддерживает как HTTP, так и HTTPS**
**HTTP режим продолжает работать как раньше** (для разработки)
**HTTPS режим настроен для домена** (для продакшена)
✅ **Certificate pinning сертификаты не затронуты**
## Как запустить
### HTTP режим (разработка) - как раньше
```bash
./run_dev.sh
# или
dart run lib/main.dart --isar isar --workdir $(pwd) --backup backup -a 0.0.0.0 -p 8000
```
### HTTPS режим (продакшен) - РЕКОМЕНДУЕМЫЙ
```bash
# Используйте Let's Encrypt сертификаты (автоматически)
./run_https_production.sh
```
### Двойной режим (HTTP + HTTPS одновременно) - РЕКОМЕНДУЕМЫЙ
```bash
# Автоматический запуск в двойном режиме через build_app.sh
# Скрипт автоматически:
# 1. Проверит наличие Let's Encrypt сертификатов
# 2. Если сертификатов нет - создаст их автоматически
# 3. Запустит сервер в соответствующем режиме
./build_app.sh
```
### HTTP режим (продакшен) - для reverse proxy
```bash
# HTTP сервер для работы за nginx/apache
./run_http_production.sh
```
### HTTPS режим (тестирование) - только для разработки
```bash
# 1. Сгенерировать самоподписанные сертификаты (только для тестов)
./certs/generate_https_server_cert.sh
# 2. Запустить HTTPS сервер с самоподписанными сертификатами
./run_https.sh
```
## URL адреса
- **HTTP**: `http://localhost:8000` (разработка)
- **HTTPS**: `https://1592725-cf88967.twc1.net:443` (продакшен)
## Важные моменты
1. **Certificate pinning сертификаты** в папке `certs/` НЕ изменены
2. **HTTPS сертификаты** созданы в отдельной папке `certs/https_server/`
3. **CORS настроен** для поддержки обоих протоколов
4. **HSTS заголовки** добавляются автоматически для HTTPS
## Автоматическое создание SSL сертификатов
### build_app.sh автоматически создает Let's Encrypt сертификаты
Скрипт `build_app.sh` автоматически:
1. ✅ Проверяет наличие Let's Encrypt сертификатов
2. ✅ Если сертификатов нет - создает их автоматически
3. ✅ Запускает сервер в соответствующем режиме
### Требования для автоматического создания сертификатов
Для успешного создания Let's Encrypt сертификатов убедитесь, что:
- ✅ Домен `1592725-cf88967.twc1.net` указывает на IP адрес сервера
- ✅ Порт 80 доступен извне (не заблокирован firewall)
- ✅ На сервере установлен `certbot`
- ✅ Сервер может принимать входящие соединения на порт 80
### Ручное создание сертификатов (если автоматическое не работает)
```bash
# Установите certbot (если не установлен)
sudo apt install certbot # Ubuntu/Debian
# Получите сертификат вручную
sudo certbot certonly --standalone -d 1592725-cf88967.twc1.net
# Сертификаты будут в /etc/letsencrypt/live/1592725-cf88967.twc1.net/
```
### 2. Cloudflare SSL (если домен на Cloudflare)
- Включите SSL/TLS в панели Cloudflare
- Выберите "Full (strict)" режим
- Сертификаты будут автоматически обновляться
### 3. Другие CA
- Comodo, DigiCert, Sectigo и др.
- Загрузите полученные сертификаты в `certs/production/`
## Тестирование
```bash
# HTTP тест
curl -X GET http://localhost:8000/health
# HTTPS тест (с самоподписанным сертификатом)
curl -k -X GET https://1592725-cf88967.twc1.net:443/health
```

View file

@ -1,680 +0,0 @@
# Progress Log
## 2025-01-XX - Buy Page Access Without Authentication ✅ COMPLETED
**Feature:** Allow unauthenticated access to pack buy page endpoint
**Completed Tasks:**
- ✅ Modified `/api/v2/packs/<packId>/buy` GET endpoint to work without authentication
- ✅ Unauthenticated users can now view buy page using `getPublicBuyPage`
- ✅ Authenticated users still use `getBuyPage` with ownership checks
- ✅ POST endpoint `/api/v2/purchases/packs/<packId>` still requires authentication (for payment creation)
- ✅ Added comprehensive unit tests for buy page endpoint covering all scenarios
**Technical Implementation:**
- **GET `/api/v2/packs/<packId>/buy`**: Now accessible without authentication
- Unauthenticated users: Returns public buy page via `PackManager.getPublicBuyPage()`
- Authenticated users: Returns buy page with ownership check via `PackManager.getBuyPage()`
- Returns 409 Conflict if authenticated user already owns the pack
- **POST `/api/v2/purchases/packs/<packId>`**: Still requires authentication (unchanged)
- This endpoint creates the actual payment, so authentication is required
**Error Handling:**
- Invalid pack ID format: Returns 400 Bad Request
- Pack not found: Returns 404 Not Found
- Pack already purchased (authenticated): Returns 409 Conflict
- All errors properly handled for both authenticated and unauthenticated requests
**Tests Added:**
- Test for unauthenticated user accessing buy page
- Test for authenticated user without pack accessing buy page
- Test for authenticated user who already owns pack (409 Conflict)
- Test for non-existent pack (404) for both authenticated and unauthenticated
- Test for invalid pack ID format (400)
**Files Modified:**
- `lib/api/v2/packs_api_v2.dart` - Updated `getPackBuyPage` method
- `test/api/v2/packs_api_v2_test.dart` - Added comprehensive test suite
## 2025-01-XX - BACKEND-001: Subscriptions Plans Endpoint ✅ COMPLETED
**Feature:** GET /api/v2/subscriptions/plans Endpoint Implementation
**Completed Tasks:**
- ✅ Implemented GET /api/v2/subscriptions/plans endpoint in SubscriptionsApiV2
- ✅ Endpoint uses SubscriptionManager.getAllSubscriptionPlans() to fetch plans
- ✅ Returns plans in proper JSON format wrapped in {'plans': [...]} structure
- ✅ Authentication is optional (works with or without authenticated user)
- ✅ Returns empty array when no plans are available
- ✅ Comprehensive unit tests (5 test cases, all passing)
- ✅ Proper error handling with logging
- ✅ Endpoint registered in router and OpenAPI documentation
**Technical Implementation:**
- **Endpoint:** `GET /api/v2/subscriptions/plans`
- **Method:** `getPlans(Request request)` in SubscriptionsApiV2 class
- **Data Source:** SubscriptionManager.getAllSubscriptionPlans()
- **Response Format:** JSON with plans array containing SubscriptionPlanAdminDto objects
- **Authentication:** Optional (no authentication required)
- **Error Handling:** Try-catch with proper error logging and 500 response on failure
**Test Coverage:**
- ✅ Returns 200 with empty array when no plans available
- ✅ Returns 200 with list of plans when plans exist
- ✅ Works with authenticated user (optional auth)
- ✅ Returns properly formatted JSON
- ✅ Handles multiple plans with different payment systems
**Acceptance Criteria Met:**
1. ✅ GET /api/v2/subscriptions/plans returns 200 with list of plans
2. ✅ Plans are properly formatted as JSON
3. ✅ Endpoint handles authentication correctly (optional)
4. ✅ Returns empty array if no plans available
5. ✅ Unit test passes for getPlans endpoint
**Files Modified:**
- `lib/api/v2/subscriptions_api_v2.dart` - Endpoint implementation (already existed)
- `test/api/v2/subscriptions_api_v2_test.dart` - Comprehensive test suite (already existed)
**Next Action:** Endpoint is production-ready and fully tested
## 2025-11-16 (Evening) - Let's Encrypt SSL Certificate Setup ✅ COMPLETED
**Feature:** SSL Certificate Configuration for API Domain (api.mnemo-cards.online)
**Completed Tasks:**
- ✅ Configured nginx with ACME challenge support for Let's Encrypt
- ✅ Fixed backend-build_app_webroot.sh script port configuration (8443 → 8081)
- ✅ Created proper directory structure for ACME challenges (/var/www/html/.well-known/acme-challenge/)
- ✅ Set up automatic SSL certificate renewal via cron job
- ✅ Tested certificate obtaining process with webroot method
- ✅ Updated systemd service configuration for dual HTTP/HTTPS mode
**Technical Implementation:**
- **Nginx Configuration:** Server block with ACME challenge location and proxy to backend
- **SSL Setup:** Let's Encrypt certificate with webroot challenge method
- **Security:** Proper file permissions and directory ownership (www-data)
- **Automation:** Cron job for daily certificate renewal with nginx reload
**Configuration Details:**
- **Domain:** api.mnemo-cards.online
- **Backend Port:** 8081 (corrected from 8443)
- **Webroot Path:** /var/www/html/.well-known/acme-challenge/
- **Certificate Path:** /etc/letsencrypt/live/api.mnemo-cards.online/
**Scripts Updated:**
- `backend-build_app_webroot.sh` - Changed from dual HTTP/HTTPS mode to HTTPS-only mode, added automatic nginx config update
- `backend-build_app.sh` - Changed from dual HTTP/HTTPS mode to HTTPS-only mode, fixed port configuration, replaced netstat with ss/lsof, added automatic nginx config update
**Documentation Updated:**
- `public/open_api.yaml` - Updated server URL from localhost:8080 to https://api.mnemo-cards.online
**Nginx Configuration:**
- Updated `/etc/nginx/sites-available/api` for HTTPS-only mode
- HTTP traffic now redirects to HTTPS (301 redirect)
- HTTPS traffic proxies to backend on port 8443 with SSL
- Added security headers and SSL configuration
**Solution Implemented: Multi-Domain Certificate**
- Changed approach to use single Let's Encrypt certificate for all domains
- Certificate includes: mnemo-cards.online, api.mnemo-cards.online, code.mnemo-cards.online, vscode.mnemo-cards.online
- This bypasses individual DNS subdomain requirements
- All services now use shared certificate from /etc/letsencrypt/live/mnemo-cards.online/
**Scripts Updated:**
- `backend-build_app.sh` - Now requests multi-domain certificate with all subdomains
- Nginx configs updated to use mnemo-cards.online certificate for API
- Backend service configured to use shared certificate path
- Fixed all domain names from mnemo-cards to mnemo-cards
**Next Action:**
- Run backend-build_app.sh to generate multi-domain certificate
- Verify HTTPS-only functionality and test API endpoints
---
## 2025-11-16 (Evening) - Forgejo Domain Setup ✅ COMPLETED
**Feature:** Domain Configuration for Forgejo (code.mnemo-cards.online)
**Completed Tasks:**
- ✅ Configured DNS record: code.mnemo-cards.online → 147.45.152.129
- ✅ Created nginx configuration for Forgejo with SSL support
- ✅ Set up Let's Encrypt SSL certificate automation
- ✅ Implemented nginx proxy from code.mnemo-cards.online:443 → localhost:3000
- ✅ Added WebSocket support for Forgejo real-time features
- ✅ Configured automatic SSL certificate renewal via cron
- ✅ Created deployment and testing scripts
- ✅ Added security headers and HTTPS enforcement
**Technical Implementation:**
- **Nginx Configuration:** Dedicated server block with SSL, proxy_pass to localhost:3000
- **SSL Setup:** Let's Encrypt certificate with automatic renewal
- **Security:** HTTPS enforcement, security headers, WebSocket support
- **Proxy Features:** Proper header forwarding, timeout configuration, buffer management
- **Cron Automation:** Daily certificate renewal checks
**Scripts Created:**
- `setup-forgejo-domain.sh` - One-command domain setup with SSL, IP blocking, and ROOT_URL fix
- `test-forgejo-domain.sh` - Comprehensive testing of DNS, SSL, IP blocking, and ROOT_URL config
- `fix-forgejo-config.sh` - Emergency script to fix ROOT_URL and restart services
- `forgejo-nginx.conf` - Production-ready nginx configuration with IP access blocking
**Security Features Added:**
- ✅ IP address access blocking for both HTTP and HTTPS (only domain access allowed)
- ✅ Direct port 3000 access blocking (Forgejo listens only on localhost)
- ✅ Automatic Forgejo ROOT_URL and HTTP_ADDR configuration fix
- ✅ SSL certificate validation for domain access
- ✅ Service restart after configuration changes
- ✅ Comprehensive testing for all security measures
**Next Action:** Run updated setup script on server to activate domain configuration with IP blocking and ROOT_URL fix
---
## 2025-11-08 (Late Night) - Authentication Fix ✅ COMPLETED
**Issue:** Getting 401 Unauthorized errors on `api/v2/packs/10/tests` and `api/v2/packs/10/buy`
**Root Cause:** The authorization middleware (`authorize_v2.dart`) was forcing authentication for all `/packs/\d+/tests` endpoints, even though pack ID 10 is configured as a public pack that should allow unauthenticated access.
**Solution:**
- Modified `authorizeV2` middleware to allow public access to pack 10 tests endpoint
- Added logic to bypass strict authentication for `/packs/10/tests` path
- Maintained authentication requirement for `/packs/10/buy` endpoint
- Verified fix works: tests endpoint now returns 200 without auth, buy endpoint still returns 401 without auth
**Technical Details:**
- Pack policy already correctly configured pack 10 as public (`publicPackIds = const {10}`)
- Access service properly grants tests permission for public packs
- Issue was in authorization middleware preventing request from reaching access control logic
**Next Action:** Continue with other backend tasks
---
## 2025-11-08 (Night) - Tasks Backend Implementation ✅ COMPLETED
**Feature:** User Tasks System Backend API
**Completed Tasks:**
- ✅ Created database models: `UserTaskModel`, `UserTaskProgressModel`, `UserTaskResultModel`
- ✅ Implemented `TasksApiV2` with 6 REST endpoints:
- `GET /api/v2/tasks` - Get tasks with filtering
- `GET /api/v2/tasks/{taskId}` - Get specific task
- `POST /api/v2/tasks/{taskId}/start` - Start task
- `POST /api/v2/tasks/{taskId}/complete` - Complete task with proof
- `GET /api/v2/users/me/tasks/progress` - Get user progress
- `GET /api/v2/tasks/categories` - Get task categories/filters
- ✅ Integrated authentication and error handling
- ✅ Implemented reward system (XP, coins, achievements)
- ✅ Created `TasksSeederTask` for initial data population
- ✅ Registered all components in dependency injection
- ✅ Added tasks router to main shelf router
**Database Models:**
- `UserTaskModel`: Task definitions with rewards, types, difficulties
- `UserTaskProgressModel`: User progress tracking (stored as JSON strings for Map compatibility)
- `UserTaskResultModel`: Individual task completion records
**API Features:**
- Task filtering by type, difficulty, status, tags
- Task lifecycle management (available → in_progress → completed)
- Reward calculation and progress tracking
- Proof-of-work submission for external tasks
- User authentication and authorization
**Initial Tasks Seeded:**
- 10 diverse tasks: app tests, Telegram subscription, restaurant ordering, movie watching, social sharing, daily streaks
- Mix of difficulties (easy/medium/hard) and types (app_internal/external/social)
- Realistic rewards and expiration dates
**Technical Implementation:**
- Isar database integration with proper indexing
- Shelf Router for REST endpoints
- Injectable for dependency management
- Comprehensive error handling and logging
**Next Action:** Deploy and test with frontend integration
---
## 2025-11-08 (Evening) - Statistics Upgrade Planning ✅
**Feature:** Statistics System Upgrade - Planning Phase
**Completed:**
- ✅ Analyzed current statistics implementation (UserModel, UserDataModel, DTOs)
- ✅ Reviewed existing statistics collection and API endpoints
- ✅ Created comprehensive plan: `STATISTICS_TASKS.md`
- 5 phases: Models (6-9h), Calculator (4-5h), API (6-8h), Tracking (9-12h), Testing (5-7h)
- Total: 35-47 hours estimated
- 41 detailed tasks with clear dependencies
- ✅ Updated `workflow_state.md` with plan and next actions
- ✅ Updated `TODO.md` with statistics tasks
- ✅ Coordinated with frontend team (mnemo_cards_web_v2)
**Planned Components:**
- **New DTOs:** PackProgressDto, AchievementDto, DetailedWordStatisticsDto, StudySessionDto
- **Extended:** UserDataDto with streaks, study time, achievements
- **Services:** StatisticsCalculator, SessionTracker, AchievementManager
- **Endpoints:** 6 new REST endpoints in `/api/v2/users/me/statistics/`
**Features:**
- Streak tracking (consecutive days)
- Pack-level progress tracking
- Achievement system (8+ types)
- Study session tracking
- Word difficulty scoring
- Timeline statistics
**Phase 1 Complete:** All DTOs, models, and relations created and compiling successfully
**Phase 2 Complete:** StatisticsCalculator service with comprehensive business logic and full test coverage
**Phase 3 Complete:** API endpoints with comprehensive statistics access
**Next Action:** Add session tracking middleware
---
## 2025-11-16 (Morning) - Statistics Phase 4: SessionTracker Service ✅ COMPLETED
**Feature:** SessionTracker Service Implementation
**Completed Tasks:**
- ✅ Created comprehensive SessionTracker service with @lazySingleton
- ✅ Implemented automatic session creation and management
- ✅ Added session timeout logic (30 minutes default)
- ✅ Integrated session tracking with UserManager.addTestStatistics
- ✅ Added proper error handling to prevent session tracking failures from breaking main operations
- ✅ Fixed TasksApiV2 route annotations for proper code generation
- ✅ All code compiles successfully and passes basic validation
**Technical Implementation:**
- **SessionTracker Service:** Injectable singleton managing user study sessions
- **Automatic Session Creation:** Creates sessions when users start studying tests
- **Progress Tracking:** Updates session statistics (words learned, tests completed, accuracy)
- **Timeout Management:** Automatically ends sessions after 30 minutes of inactivity
- **Database Integration:** Uses Isar to persist StudySessionModel instances
- **Error Resilience:** Session tracking failures don't break main user operations
**Integration Points:**
- UserManager.addTestStatistics now calls SessionTracker for each test completion
- Sessions are created per user with unique IDs
- Session progress includes word learning counts and accuracy calculations
- Automatic cleanup prevents memory leaks from abandoned sessions
**Next Action:** Add hooks in test completion flow for updating statistics
---
## 2025-11-16 (Morning) - Statistics Phase 4: Session Tracking Middleware ✅ COMPLETED
**Feature:** Session Tracking Middleware Implementation
**Completed Tasks:**
- ✅ Created sessionTrackingMiddleware for automatic session tracking
- ✅ Integrated middleware into MnemoShelf Pipeline after authentication
- ✅ Middleware automatically creates/updates sessions for authenticated API requests
- ✅ Added proper error handling to prevent middleware failures from breaking requests
- ✅ Imported required dependencies and updated DI configuration
**Technical Implementation:**
- **Middleware Function:** sessionTrackingMiddleware(SessionTracker) returns Shelf middleware
- **Pipeline Integration:** Added to v2Handler Pipeline after accessMiddleware
- **Session Creation:** Automatically creates sessions for authenticated users on any API activity
- **Error Resilience:** Session tracking errors are logged but don't fail the main request
- **Performance:** Lightweight tracking that doesn't impact API response times
**Coverage:**
- All authenticated `/api/v2/*` requests now trigger session updates
- Sessions are created when users first become active
- Covers all user activities: tests, packs, achievements, tasks, etc.
- Works alongside existing test-specific session updates
**Next Action:** Create AchievementManager for achievement checking
---
## 2025-11-16 (Afternoon) - Statistics Phase 4: Test Completion Hooks ✅ COMPLETED
**Feature:** Enhanced Test Completion Statistics Updates
**Completed Tasks:**
- ✅ Enhanced UserManager.addTestStatistics with comprehensive statistics calculation
- ✅ Added automatic streak calculation and tracking
- ✅ Implemented study date management with duplicate prevention
- ✅ Added total study time accumulation with realistic test duration estimates
- ✅ Integrated achievement calculation using StatisticsCalculator
- ✅ Updated currentStreak, longestStreak, studyDates, and totalStudyTimeMinutes fields
- ✅ Added lastTimeOnline timestamp updates
- ✅ Maintained backward compatibility and error resilience
**Technical Implementation:**
- **Statistics Calculation:** Comprehensive calculation of streaks, study times, and achievements
- **Data Integrity:** Proper date normalization and duplicate prevention for study dates
- **Achievement System:** Automatic achievement unlocking based on user progress
- **Performance:** Efficient calculations with minimal database overhead
- **Error Handling:** Statistics calculation failures don't break test submission
**Integration Points:**
- All test completions now trigger full statistics updates
- Streak calculations consider consecutive days of activity
- Achievement progress is recalculated on every test completion
- Study time accumulates realistically (5 minutes per test as baseline)
- All updates are transactional and atomic
**Next Action:** Add achievement hooks to user actions
---
## 2025-11-16 (Afternoon) - Statistics Phase 4: AchievementManager ✅ COMPLETED
**Feature:** Comprehensive Achievement Management System
**Completed Tasks:**
- ✅ Created AchievementManager service with full achievement lifecycle management
- ✅ Implemented AchievementDefinition class with evaluation and progress logic
- ✅ Defined 16 comprehensive achievement types covering all user activities:
- **First Steps:** firstWordLearned, firstTestCompleted, firstPackCompleted
- **Streaks:** streak3Days, streak7Days, streak30Days, streak100Days
- **Words Mastery:** words10Learned through words1000Learned
- **Performance:** perfectTestScore, speedLearner
- **Dedication:** dedicatedLearner (100 hours study time)
- **Time-based:** earlyBird, nightOwl
- **Special:** consistentLearner, languageMaster
- ✅ Integrated with embedded AchievementModel storage in UserDataModel
- ✅ Added automatic achievement checking in UserManager.addTestStatistics
- ✅ Implemented progress tracking for achievements with gradual unlock requirements
- ✅ Added proper error handling and logging for achievement operations
**Technical Implementation:**
- **AchievementManager:** Injectable singleton with comprehensive achievement logic
- **AchievementDefinition:** Class-based achievement definitions with async evaluation
- **Progress Tracking:** Support for achievements with gradual progress (streaks, word counts, etc.)
- **Storage Integration:** Embedded achievements stored within UserDataModel
- **Automatic Evaluation:** Achievements checked and unlocked during test completion
- **Performance:** Efficient evaluation with minimal database overhead
**Achievement Categories:**
- **18 Achievement Types** with realistic unlock criteria
- **Progress-based:** Streaks, word counts, study time
- **Instant:** First-time achievements, perfect scores, time-based
- **Comprehensive Coverage:** All major user activities tracked and rewarded
**Next Action:** Write comprehensive tests for automatic tracking system
---
## 2025-11-16 (Evening) - Statistics Phase 4: Achievement Hooks ✅ COMPLETED
**Feature:** Achievement System Integration and Hooks
**Completed Tasks:**
- ✅ Created `checkAndUpdateAchievements` method in UserManager for general achievement checking
- ✅ Integrated achievement checking into test completion flow
- ✅ Added proper error handling and logging for achievement operations
- ✅ Ensured achievement checking happens after all user data updates
- ✅ Made achievement checking available for other parts of the system if needed
**Technical Implementation:**
- **General Method:** `UserManager.checkAndUpdateAchievements()` for flexible achievement checking
- **Automatic Integration:** Achievement checking automatically triggered during test completion
- **Error Resilience:** Achievement failures don't break main user operations
- **Comprehensive Evaluation:** All 18 achievement types evaluated during checks
- **Progress Tracking:** Support for gradual achievement progress updates
**Integration Points:**
- **Test Completion:** Primary trigger for achievement checking
- **User Data Updates:** Achievements checked after statistics updates
- **Extensible Design:** Easy to add achievement checking to other user actions
- **Performance:** Efficient evaluation with minimal impact on response times
**Achievement Coverage:**
- All major user learning activities trigger appropriate achievement checks
- Comprehensive evaluation of all achievement criteria
- Real-time achievement unlocking during user interactions
**Next Action:** Phase 4 Complete - Ready for Phase 5 (Testing and Docs)
---
## 2025-11-16 (Late Evening) - Statistics Phase 4: Comprehensive Tests ✅ COMPLETED
**Feature:** Automated Tracking System Test Suite
**Completed Tasks:**
- ✅ Created comprehensive unit test suite for SessionTracker functionality
- ✅ Implemented test suite for AchievementManager with 19 achievement types validation
- ✅ Added integration test placeholders for complete system validation
- ✅ Verified achievement progress calculation and boundary conditions
- ✅ Tested achievement unlock logic and progression requirements
- ✅ Ensured error handling and edge case robustness
- ✅ All 21 tests pass successfully across 7 test groups
**Test Coverage:**
- **SessionTracker Tests:** Core functionality, session ID generation, timeout logic
- **AchievementManager Tests:** 19 achievement types, progress tracking, unlock conditions
- **Integration Tests:** System component interaction and error handling
- **Progress Tracking:** Boundary conditions and incremental achievement progress
- **Error Handling:** Graceful failure handling and system stability
**Test Structure:**
- **Unit Tests:** 16 focused tests covering core business logic
- **Integration Tests:** 5 tests verifying system-wide interactions
- **Edge Case Tests:** Boundary condition and error scenario validation
- **Progress Tests:** Achievement progression and unlock mechanics
**Quality Assurance:**
- All tests pass without failures
- Comprehensive coverage of achievement system (18 achievement types tested)
- Progress calculation validation with boundary testing
- Error handling verification to prevent system crashes
**Next Action:** Phase 4 Complete - All automatic tracking components implemented and tested
---
## 2025-11-08 (Late Evening) - Statistics Backend Phase 3 ✅ COMPLETED
**Feature:** Statistics API Endpoints Implementation
**Completed Tasks:**
- ✅ Added StatisticsCalculator dependency to UsersApiV2
- ✅ Implemented 6 new REST API endpoints:
- `GET /api/v2/users/me/statistics/detailed` - Complete user statistics
- `GET /api/v2/users/me/statistics/packs` - Pack progress with optional packId filter
- `GET /api/v2/users/me/statistics/words` - Paginated word statistics with sorting and filtering
- `GET /api/v2/users/me/statistics/timeline` - Timeline data with period filtering
- `POST /api/v2/users/me/sessions` - Study session recording
- `GET /api/v2/users/me/achievements` - User achievements and progress
**Technical Implementation:**
- **Endpoint Features:**
- Query parameter validation and sanitization
- Proper error handling with meaningful error messages
- Pagination support (limit/offset with max limits)
- Multiple sorting options (difficulty, accuracy, recent, alphabetical)
- Filtering capabilities (packId, needsReview, date ranges)
- Period-based timeline aggregation (day/week/month/year)
- **Data Processing:**
- Efficient DTO conversion using StatisticsCalculator
- Word difficulty calculation and sorting
- Timeline aggregation with date normalization
- Achievement progress calculation
- Pack progress filtering and mapping
- **API Design:**
- RESTful endpoint structure following existing patterns
- JSON response format with consistent structure
- Query parameter documentation in comments
- Proper HTTP status codes (200, 400, 401, 404, 500)
**Integration Testing:**
- ✅ Comprehensive integration tests (9 test cases, all passing)
- ✅ StatisticsCalculator integration verification
- ✅ UserDataModel to DTO conversion testing
- ✅ Business logic validation through API layer
- ✅ Error handling and edge case coverage
**Key Endpoints Details:**
1. **Detailed Statistics** (`/statistics/detailed`)
- Returns complete user statistics including streaks, study time, achievements
- Uses StatisticsCalculator for all calculations
- Includes pack progress, study dates, category minutes
2. **Pack Statistics** (`/statistics/packs?packId=...`)
- Lists all user pack progress or filters by specific pack
- Returns pack completion percentage, study time, accuracy
- Supports pack-specific queries
3. **Word Statistics** (`/statistics/words?sortBy=difficulty&limit=50&packId=...`)
- Advanced word-level statistics with pagination
- Multiple sorting: difficulty, accuracy, recent activity, alphabetical
- Filtering: by pack, needs review status
- Pagination: configurable limit (1-100), offset-based
4. **Timeline Statistics** (`/statistics/timeline?period=month&from=...&to=...`)
- Study activity timeline with period aggregation
- Supports day/week/month/year periods
- Custom date range filtering
- Returns daily activity, streak info, total metrics
5. **Study Sessions** (`POST /sessions`)
- Records completed study sessions
- Accepts session metadata (words learned, accuracy, duration)
- Returns session confirmation (ready for future session storage)
6. **Achievements** (`/achievements`)
- User achievements and progress tracking
- Generated dynamically based on user activity
- Includes achievement categories and unlock status
**Performance Considerations:**
- Efficient data retrieval from Isar database
- Lazy loading of related data through IsarLink
- Minimal data transformation in API layer
- Proper indexing on frequently queried fields
**Security & Validation:**
- Authentication required for all endpoints
- Input sanitization and parameter validation
- Proper error responses without data leakage
- Rate limiting considerations (inherited from base API)
**Next:** Phase 3.9 - OpenAPI specification update
---
## 2025-11-08 (Evening) - Statistics Backend Phase 2 ✅ COMPLETED
**Feature:** StatisticsCalculator Service Implementation
**Completed Tasks:**
- ✅ Created StatisticsCalculator service with @lazySingleton annotation
- ✅ Implemented all core calculation methods:
- `calculateStreak()` - consecutive days logic with date normalization
- `calculateAccuracy()` - word statistics accuracy calculation
- `calculateTotalStudyTime()` - aggregate time from pack progress
- `calculateDailyStudyTime()` - daily time aggregation with date keys
- `findDifficultWords()` - difficulty scoring and filtering
- `calculatePackProgress()` - pack progress retrieval and DTO conversion
- `getTimelineStatistics()` - period-based timeline data with filtering
- `calculateUserLevel()` - experience-based level calculation
- `calculatePerformanceMetrics()` - comprehensive metrics calculation
- `calculateAchievementProgress()` - achievement unlock logic
**Technical Details:**
- **Service:** Injectable singleton with clean business logic separation
- **Methods:** 12 calculation methods covering all statistics features
- **Data Processing:** Proper date normalization, aggregation, and filtering
- **DTO Integration:** Seamless conversion between models and DTOs
- **DI Integration:** Automatic registration via Injectable
**Test Coverage:**
- ✅ Comprehensive unit tests (23 tests, all passing)
- ✅ Edge cases covered (empty data, invalid dates, etc.)
- ✅ Date normalization and streak calculation verified
- ✅ Accuracy calculations and aggregations tested
- ✅ Timeline filtering and period handling tested
**Key Algorithms Implemented:**
1. **Streak Calculation:** Consecutive days tracking with 1-day grace period
2. **Difficulty Scoring:** Based on incorrect/correct ratio with weighted formula
3. **Timeline Aggregation:** Daily study time with proper date key normalization
4. **Performance Metrics:** Accuracy, difficulty, and consistency calculations
5. **Level System:** Experience-based leveling from words, time, and packs
**Next:** Phase 3 - API Endpoints integration
---
## 2025-11-08 (Afternoon) - Statistics Backend Phase 1 ✅ COMPLETED
**Feature:** Backend Statistics Models and DTOs
**Completed Tasks:**
- ✅ Created PackProgressDto with progress tracking, card attempts, study time
- ✅ Created AchievementDto with 18 achievement types and unlock logic
- ✅ Created DetailedWordStatisticsDto extending WordStatisticsDto with difficulty scoring
- ✅ Created StudySessionDto for session tracking with productivity metrics
- ✅ Extended UserDataDto with 7 new statistics fields (streaks, pack progress, achievements, etc.)
- ✅ Created PackProgressModel (@embedded) for Isar storage
- ✅ Created AchievementModel (@embedded) for Isar storage
- ✅ Created StudySessionModel (@collection) for individual sessions
- ✅ Updated UserDataModel with new embedded relations
- ✅ Generated .g.dart files (manual creation due to build_runner issues)
- ✅ All models compile successfully with proper Isar annotations
**Technical Details:**
- **New DTOs:** 4 new classes with JSON serialization
- **New Models:** 3 Isar models (2 embedded, 1 collection)
- **Extended:** UserDataDto and UserDataModel with comprehensive statistics
- **Files Created:** 7 new files with proper imports and exports
- **Codegen:** Manual .g.dart creation due to Flutter SDK issues
**Data Structure:**
```dart
// Extended UserDataDto now includes:
- lastTimeOnline: DateTime?
- totalStudyTimeMinutes: int
- currentStreak: int
- longestStreak: int
- packProgress: List<PackProgressDto>
- studyDates: List<DateTime>
- categoryMinutes: Map<String, int>
- achievements: List<AchievementDto>
```
**Next:** Phase 2 - StatisticsCalculator service with business logic
---
## 2025-11-08
- Updated access control policies and services to rely on `UserModel` instead of dynamic casting.
- Adjusted route guard helpers to use the typed request extension.
- Verified analyzer remains clean (no new warnings).
- Pending: add targeted unit coverage for authorization policies.
- Fixed `PacksApiV2` null access guard by enforcing presence of `AccessService` and mapping `AccessDenied` errors to REST-friendly responses.
- Updated `PacksApiV2` tests to supply access context and validated full suite (packs, purchases, tests) passes locally.
- Hardened `authorizeV2` middleware to treat pack test routes as auth-required while still attaching user context on optional GET endpoints when tokens are supplied.
- Added dedicated middleware regression tests (`test/api/v2/authorize_v2_test.dart`) and re-ran packs API suite to confirm pack 10 tests no longer return 401 for authenticated users.
- Enabled `/api/v2/packs/{id}` to return buy page payload for unauthorized/private access, introduced `PackManager.getPublicBuyPage`, and expanded packs API tests to cover anonymous and authenticated purchase prompts.
## 2025-11-09
- Replaced remaining v1 routes with dedicated v2 services (`AdsApiV2`, `UsersApiV2`, `PromocodesApiV2`, `AdminUsersApiV2`, `DiscountsApiV2`) and removed legacy handlers.
- Updated dependency injection and `MnemoShelf` routing to mount only v2 routers; regenerated code via `build_runner`.
- Added `/api/v2/packs/<packId>/buy` plus ad reward acquisition flow that verifies hashed keys before issuing zero-cost payments.
- Refreshed `public/open_api.yaml` to document the new endpoints and admin surfaces.
- Full `dart test` run now fails with an Isar collection-id mismatch when suites execute together; individual suite runs succeed—needs follow-up synchronization fix.
- Mounted the v2 pipeline at `/api/v2` inside `MnemoShelf`, fixing 404 responses for public routes like `GET /api/v2/packs` on the deployed instance.
## 2025-11-09 (Afternoon) - Telegram Bot Backend URL Override ✅
- ✅ Introduced `BotConfig` helper with CLI option `--backend-url` and env fallback (`MNEMO_BACKEND_URL`/`BACKEND_URL`) so the Telegram bot can target HTTPS production APIs instead of hardcoded `http://localhost:8443`.
- ✅ Logged selected backend endpoint during bot startup for easier diagnostics.
- ✅ Added dedicated unit tests (`test/bot_config_test.dart`) covering CLI > env > default resolution order and ran `dart test` for the bot package.

View file

@ -1,93 +0,0 @@
# Настройка HTTPS для Mnemo Cards Backend
## Обзор
Сервер поддерживает два режима работы:
- **HTTP** (по умолчанию) - для разработки
- **HTTPS** - для продакшена с доменом
**ВАЖНО**: Существующие сертификаты в папке `certs/` предназначены для certificate pinning в мобильном приложении, а НЕ для HTTPS сервера!
## Режимы запуска
### 1. HTTP режим (разработка)
```bash
# Используйте существующий скрипт
./run_dev.sh
# Или напрямую
dart run lib/main.dart --isar isar --workdir $(pwd) --backup backup -a 0.0.0.0 -p 8000
```
### 2. HTTPS режим (продакшен)
```bash
# Сначала сгенерируйте SSL сертификаты для HTTPS сервера
./certs/generate_https_server_cert.sh
# Затем запустите с HTTPS
./run_https.sh
# Или напрямую
dart run lib/main.dart --isar isar --workdir $(pwd) --backup backup --certs $(pwd)/certs/https_server -a 0.0.0.0 -p 443
```
## SSL сертификаты
### Для HTTPS сервера (отдельно от certificate pinning)
Скрипт `./certs/generate_https_server_cert.sh` создает самоподписанные сертификаты для HTTPS сервера домена `1592725-cf88967.twc1.net`.
### Certificate Pinning сертификаты
Существующие сертификаты в `certs/` используются для certificate pinning в мобильном приложении и НЕ должны изменяться.
### Для продакшена
Рекомендуется использовать сертификаты от доверенного CA:
- Let's Encrypt (бесплатно)
- Cloudflare SSL
- Другие коммерческие CA
## Конфигурация
### CORS настройки
Сервер автоматически настраивает CORS для поддержки:
- HTTP соединений (localhost, 127.0.0.1)
- HTTPS соединений (1592725-cf88967.twc1.net)
### Порты
- HTTP: 8000 (разработка)
- HTTPS: 443 (продакшен)
### Домены
- HTTP: `http://localhost:8000`
- HTTPS: `https://1592725-cf88967.twc1.net:443`
## Безопасность
### HSTS
При использовании HTTPS автоматически добавляется заголовок `Strict-Transport-Security` для принуждения к HTTPS соединениям.
### CORS
Настроен для поддержки всех необходимых заголовков и методов для API.
## Тестирование
### HTTP тест
```bash
curl -X GET http://localhost:8000/health
```
### HTTPS тест
```bash
# Для самоподписанных сертификатов
curl -k -X GET https://1592725-cf88967.twc1.net:443/health
# Для доверенных сертификатов
curl -X GET https://1592725-cf88967.twc1.net:443/health
```
## Развертывание
1. Сгенерируйте SSL сертификаты для вашего домена
2. Настройте DNS записи для домена
3. Запустите сервер с HTTPS
4. Настройте reverse proxy (nginx) если необходимо
5. Обновите клиентские приложения для использования HTTPS URL

View file

@ -1,514 +0,0 @@
# Statistics Backend Tasks
**Project:** mnemo_cards_backend
**Feature:** Statistics System Upgrade
**Created:** 2025-11-08
---
## Phase 1: Backend - Models and DTOs
### Task 1.1: Create New DTOs in mnemo_cards_common ✅ PRIORITY
**Estimated Time:** 3-4 hours
**Files to Create:**
1. `mnemo_cards_common/lib/src/dtos/user/data/pack_progress_dto.dart`
```dart
@JsonSerializable()
@CopyWith()
class PackProgressDto {
final String packId;
final int totalCards;
final int learnedCards;
final int studyTimeMinutes;
final DateTime? lastStudyDate;
final DateTime? firstStudyDate;
final Map<String, int> cardAttempts;
final double averageAccuracy;
}
```
2. `mnemo_cards_common/lib/src/dtos/user/achievement_dto.dart`
```dart
@JsonSerializable()
@CopyWith()
class AchievementDto {
final String id;
final String title;
final String description;
final String? iconUrl;
final DateTime? unlockedAt;
final AchievementType type;
final double progress; // 0.0 to 1.0
}
enum AchievementType {
firstSteps,
streak,
wordsMaster,
perfectScore,
speedLearner,
dedicated,
}
```
3. `mnemo_cards_common/lib/src/dtos/user/data/detailed_word_statistics_dto.dart`
```dart
@JsonSerializable()
@CopyWith()
class DetailedWordStatisticsDto {
final String word;
final double correct;
final double incorrect;
final double skipped;
final Set<TestQuestionType> questionTypes;
final DateTime? lastReviewed;
final DateTime? firstLearned;
final double difficultyScore; // 0.0 to 1.0
final bool needsReview;
final String? packId;
}
```
4. `mnemo_cards_common/lib/src/dtos/user/study_session_dto.dart`
```dart
@JsonSerializable()
@CopyWith()
class StudySessionDto {
final String? sessionId;
final DateTime startTime;
final DateTime? endTime;
final int wordsLearned;
final int testsCompleted;
final double accuracy;
final String? packId;
final String? testId;
}
```
**Steps:**
- [ ] Create PackProgressDto with all fields
- [ ] Create AchievementDto and AchievementType enum
- [ ] Create DetailedWordStatisticsDto extending WordStatisticsDto
- [ ] Create StudySessionDto
- [ ] Run `./codegen.sh` to generate .g.dart files
- [ ] Export all new DTOs in main export file
- [ ] Write unit tests for DTO serialization/deserialization
---
### Task 1.2: Extend UserDataDto
**Estimated Time:** 1-2 hours
**File:** `mnemo_cards_common/lib/src/dtos/user/data/user_data_dto.dart`
**Add Fields:**
```dart
@JsonSerializable()
@CopyWith()
class UserDataDto {
// Existing
final AllWordsStatisticsDto? allWordsStatistics;
final AllTestsStatisticsDto? allTestsStatistics;
// NEW FIELDS
final DateTime? lastTimeOnline;
final int totalStudyTimeMinutes;
final int currentStreak;
final int longestStreak;
final Map<String, PackProgressDto> packProgress;
final List<DateTime> studyDates; // for streak calculation
final Map<String, int> categoryMinutes; // category -> minutes
final List<AchievementDto> achievements;
}
```
**Steps:**
- [ ] Add new fields to UserDataDto
- [ ] Update copyWith to include new fields
- [ ] Run codegen
- [ ] Update tests
---
### Task 1.3: Create Backend Isar Models
**Estimated Time:** 2-3 hours
**Files to Create:**
1. `mnemo_cards_common_backend/lib/src/models/pack_progress_model.dart`
2. `mnemo_cards_common_backend/lib/src/models/achievement_model.dart`
3. `mnemo_cards_common_backend/lib/src/models/study_session_model.dart`
**Steps:**
- [ ] Create Isar models corresponding to DTOs
- [ ] Add toDto() methods
- [ ] Add fromDto() methods
- [ ] Update UserDataModel to include new relations
- [ ] Run codegen
- [ ] Write unit tests for model conversions
---
## Phase 2: Backend - API Endpoints
### Task 2.1: Create StatisticsCalculator Service
**Estimated Time:** 4-5 hours
**File:** `mnemo_cards_backend/lib/statistics/statistics_calculator.dart` (new)
**Methods:**
```dart
@lazySingleton
class StatisticsCalculator {
/// Calculate pack progress for user
Future<PackProgressDto> calculatePackProgress(
UserModel user,
String packId,
);
/// Calculate current streak
int calculateStreak(List<DateTime> studyDates);
/// Find difficult words that need review
List<DetailedWordStatisticsDto> findDifficultWords(
UserDataModel data,
{int limit = 20}
);
/// Calculate overall accuracy
double calculateAccuracy(AllWordsStatisticsDto stats);
/// Calculate daily study time
Map<DateTime, int> calculateDailyStudyTime(
List<StudySessionModel> sessions,
);
/// Calculate total study time
int calculateTotalStudyTime(UserDataModel data);
/// Get timeline statistics
Map<String, dynamic> getTimelineStatistics(
UserDataModel data,
{required String period, DateTime? from, DateTime? to}
);
}
```
**Steps:**
- [ ] Create StatisticsCalculator class
- [ ] Implement calculatePackProgress
- [ ] Implement calculateStreak (consecutive days logic)
- [ ] Implement findDifficultWords (based on accuracy)
- [ ] Implement calculateAccuracy
- [ ] Implement calculateDailyStudyTime
- [ ] Implement calculateTotalStudyTime
- [ ] Implement getTimelineStatistics
- [ ] Add to DI
- [ ] Write comprehensive unit tests
---
### Task 2.2: Add Statistics Endpoints to UsersApiV2
**Estimated Time:** 4-5 hours
**File:** `mnemo_cards_backend/lib/api/v2/users_api_v2.dart`
**New Endpoints:**
```dart
/// GET /api/v2/users/me/statistics/detailed
/// Returns detailed user statistics
@Route.get('/users/me/statistics/detailed')
Future<Response> getDetailedStatistics(Request request);
/// GET /api/v2/users/me/statistics/packs
/// Returns statistics for all packs or specific pack
/// Query: ?packId=xxx
@Route.get('/users/me/statistics/packs')
Future<Response> getPacksStatistics(Request request);
/// GET /api/v2/users/me/statistics/words
/// Returns paginated word statistics
/// Query: ?packId=xxx&limit=50&offset=0&sortBy=difficulty&needsReview=true
@Route.get('/users/me/statistics/words')
Future<Response> getWordsStatistics(Request request);
/// GET /api/v2/users/me/statistics/timeline
/// Returns timeline statistics
/// Query: ?period=week&from=2024-01-01&to=2024-12-31
@Route.get('/users/me/statistics/timeline')
Future<Response> getTimelineStatistics(Request request);
/// POST /api/v2/users/me/sessions
/// Start or end study session
@Route.post('/users/me/sessions')
Future<Response> recordStudySession(Request request);
/// GET /api/v2/users/me/achievements
/// Returns user achievements
@Route.get('/users/me/achievements')
Future<Response> getAchievements(Request request);
```
**Steps:**
- [ ] Add getDetailedStatistics endpoint
- [ ] Add getPacksStatistics endpoint with optional packId filter
- [ ] Add getWordsStatistics endpoint with pagination and filters
- [ ] Add getTimelineStatistics endpoint
- [ ] Add recordStudySession endpoint
- [ ] Add getAchievements endpoint
- [ ] Implement proper error handling
- [ ] Add request validation
- [ ] Write integration tests for all endpoints
---
### Task 2.3: Update UserManager with Statistics Methods
**Estimated Time:** 2-3 hours
**File:** `mnemo_cards_backend/lib/user/user_manager.dart`
**New Methods:**
```dart
class UserManager {
final StatisticsCalculator _statsCalculator;
// Existing methods...
/// Get detailed user statistics
Future<UserDataDto> getDetailedStatistics(UserModel user);
/// Get pack statistics
Future<List<PackProgressDto>> getPacksStatistics(
UserModel user,
{String? packId}
);
/// Get word statistics with pagination
Future<Map<String, dynamic>> getWordsStatistics(
UserModel user, {
String? packId,
int limit = 50,
int offset = 0,
String sortBy = 'difficulty',
bool needsReview = false,
});
/// Record study session
Future<void> recordStudySession(
UserModel user,
StudySessionDto session,
);
/// Update user streak
Future<void> updateStreak(UserModel user);
}
```
**Steps:**
- [ ] Add StatisticsCalculator to constructor
- [ ] Implement getDetailedStatistics
- [ ] Implement getPacksStatistics with optional filtering
- [ ] Implement getWordsStatistics with pagination/sorting
- [ ] Implement recordStudySession
- [ ] Implement updateStreak (call daily)
- [ ] Write unit tests
---
## Phase 3: Backend - Automatic Tracking
### Task 3.1: Create Session Tracking Middleware
**Estimated Time:** 3-4 hours
**File:** `mnemo_cards_backend/lib/statistics/session_tracker.dart` (new)
**Features:**
- Track when user starts/ends session
- Auto-update lastTimeOnline
- Calculate session duration
- Store session in database
**Steps:**
- [ ] Create SessionTracker class
- [ ] Add session start/end logic
- [ ] Integrate with existing auth middleware
- [ ] Store active sessions in memory (with TTL)
- [ ] Auto-cleanup expired sessions
- [ ] Write unit tests
---
### Task 3.2: Add Hooks for Statistics Updates
**Estimated Time:** 2-3 hours
**Files to Modify:**
- `mnemo_cards_backend/lib/api/v2/users_api_v2.dart` (addUserTestStatistics)
- `mnemo_cards_backend/lib/user/user_manager.dart` (addTestStatistics)
**Add After Test Completion:**
- Update pack progress
- Update streak (if needed)
- Check and award achievements
- Update total study time
**Steps:**
- [ ] Add hook in addTestStatistics
- [ ] Call statistics calculator
- [ ] Update pack progress
- [ ] Update streak
- [ ] Trigger achievement check
- [ ] Write tests
---
### Task 3.3: Create Achievement Manager
**Estimated Time:** 4-5 hours
**File:** `mnemo_cards_backend/lib/statistics/achievement_manager.dart` (new)
**Features:**
```dart
@lazySingleton
class AchievementManager {
/// Check and award achievements after action
Future<List<AchievementDto>> checkAchievements(UserModel user);
/// Check specific achievement
Future<AchievementDto?> checkAchievement(
UserModel user,
AchievementType type,
);
/// Award achievement
Future<void> awardAchievement(
UserModel user,
AchievementDto achievement,
);
/// Get all possible achievements
List<AchievementDto> getAllAchievements();
}
```
**Achievement Types:**
- First word learned
- First test completed
- First pack completed
- Streak milestones (3, 7, 30, 100 days)
- Words milestones (10, 50, 100, 500, 1000)
- Perfect test score
- Speed learner
- Night owl / Early bird
- Total study time milestones
**Steps:**
- [ ] Create AchievementManager
- [ ] Define all achievement types
- [ ] Implement check logic for each type
- [ ] Implement award logic
- [ ] Add to DI
- [ ] Write comprehensive tests
---
## Phase 4: Testing
### Task 4.1: Unit Tests
**Estimated Time:** 3-4 hours
**Test Files:**
- `test/statistics/statistics_calculator_test.dart`
- `test/statistics/achievement_manager_test.dart`
- `test/statistics/session_tracker_test.dart`
- `test/user/user_manager_statistics_test.dart`
**Coverage:**
- All StatisticsCalculator methods
- Achievement checking logic
- Session tracking
- DTO conversions
- Streak calculations
- Difficulty calculations
---
### Task 4.2: Integration Tests
**Estimated Time:** 2-3 hours
**Test File:** `test/api/v2/users_api_v2_statistics_test.dart`
**Tests:**
- GET /users/me/statistics/detailed
- GET /users/me/statistics/packs
- GET /users/me/statistics/words (with filters)
- GET /users/me/statistics/timeline
- POST /users/me/sessions
- GET /users/me/achievements
---
## Phase 5: Documentation
### Task 5.1: Update OpenAPI Spec
**Estimated Time:** 1-2 hours
**File:** `mnemo_cards_backend/public/open_api.yaml`
**Add:**
- All new statistics endpoints
- Request/response schemas
- Query parameters
- Examples
---
### Task 5.2: Update Documentation
**Estimated Time:** 1 hour
**Files:**
- Update `PROGRESS.md`
- Update `TODO.md`
- Create `STATISTICS_API.md` with API documentation
---
## Summary
**Total Estimated Time:** 35-47 hours
**Priority Order:**
1. Task 1.1, 1.2, 1.3 - Models and DTOs (6-9 hours)
2. Task 2.1 - StatisticsCalculator (4-5 hours)
3. Task 2.2, 2.3 - API Endpoints (6-8 hours)
4. Task 3.1, 3.2, 3.3 - Auto Tracking (9-12 hours)
5. Task 4.1, 4.2 - Testing (5-7 hours)
6. Task 5.1, 5.2 - Documentation (2-3 hours)
**Dependencies:**
- Tasks 1.x must be done first
- Tasks 2.x depend on 1.x
- Tasks 3.x depend on 2.x
- Tasks 4.x can be done in parallel with development
- Tasks 5.x should be done last
---
**Start Date:** TBD
**Target Completion:** TBD

View file

@ -1,52 +0,0 @@
# TODO List
## High Priority
- [x] Fix MnemoShelf routing so the v2 pipeline mounts at `/api/v2` (restores public packs listing)
- [x] **COMPLETED** - Implement User Tasks System Backend API (6 endpoints, 3 models, data seeding)
- [x] **COMPLETED** - Set up Forgejo domain (code.mnemo-cards.online) with SSL, IP blocking, and ROOT_URL fix
- [ ] Verify project builds successfully (`flutter build`)
- [ ] Run all existing tests (`flutter test`)
- [ ] Check code generation (`./codegen.sh`)
- [ ] Review linter issues (`dart analyze`)
- [ ] Investigate Isar collection-id failure when running `dart test` for the whole suite
## Medium Priority
- [ ] Review existing codebase architecture
- [x] **COMPLETED** - Set up Let's Encrypt SSL certificates for api.mnemo-cards.online with automatic renewal
- [x] **COMPLETED** - Update nginx configuration for HTTPS-only API (redirect HTTP to HTTPS, proxy to port 8443)
- [x] **COMPLETED** - Changed to multi-domain certificate approach (bypasses DNS subdomain requirements)
- [ ] Verify HTTPS-only functionality and test API endpoints over SSL
- [ ] Verify database operations
- [x] Review API endpoints and documentation (v1 removal & v2 surface audit)
## Low Priority
- [ ] Update README.md with proper project description
- [ ] Review backup strategy and retention
- [ ] Check Python utilities integration
- [ ] Review deployment scripts
## Architecture Tasks
- [x] Replace dynamic user handling with typed `UserModel` references in access policies
- [ ] Implement `yx_state` and `yx_scope` if not already present
- [ ] Ensure clean architecture principles are followed
- [ ] Review dependency injection setup
- [ ] Check error handling implementation
## Testing Tasks
- [ ] Write unit tests for missing functionalities
- [ ] Add integration tests for new v2 endpoints (ads, users, promocodes, admin)
- [ ] Review test coverage
- [ ] Add mock tests for external dependencies
- [x] Refresh Packs API v2 test coverage and ensure access control context is provided
- [x] Add regression tests for authorizeV2 optional authentication handling on pack routes
- [x] Cover anonymous and authenticated buy-page fallbacks for private packs in Packs API v2
## Telegram Bot
- [x] Allow Telegram bot to override backend API base URL via `--backend-url` CLI flag and env vars
- [ ] Document production bot startup command with new backend URL option
## Notes
- Reference `../mnemo_cards` app for design and features
- Do not copy architecture from reference app
- Follow Flutter/Dart best practices
- Use Shelf framework patterns

View file

@ -1,13 +0,0 @@
You can use OpenSSL directly.
Create a Certificate Authority private key (this is your most important key):
openssl req -new -newkey rsa:1024 -nodes -out ca.csr -keyout ca.key
Create your CA self-signed certificate:
openssl x509 -trustout -signkey ca.key -days 365 -req -in ca.csr -out ca.pem
Issue a client certificate by first generating the key, then request (or use one provided by external system) then sign the certificate using private key of your CA:
openssl genrsa -out client.key 1024
openssl req -new -key client.key -out client.csr
openssl ca -in client.csr -out client.cer

View file

@ -1,102 +0,0 @@
# Mnemo Cards Backend - Project Configuration
## Project Overview
- **Name**: mnemo_cards_backend
- **Type**: Flutter/Dart backend server using Shelf framework
- **Purpose**: Backend API server for Mnemo Cards application
- **Architecture**: Clean architecture with dependency injection
## Tech Stack
- **Language**: Dart 3.0+
- **Framework**: Shelf (HTTP server)
- **Database**: Isar (local database)
- **Dependency Injection**: GetIt + Injectable
- **Code Generation**: Build Runner
- **Testing**: Dart Test + Mockito
- **Authentication**: JWT tokens, Google APIs
- **Payment**: YooKassa integration
## Project Structure
- `lib/` - Main source code
- `test/` - Unit tests
- `certs/` - SSL certificates for HTTPS
- `backup/` - Database backups
- `python_folder/` - Python utilities
- `target_folder/` - Build artifacts
## Key Dependencies
- `mnemo_cards_common` - Shared common code
- `mnemo_cards_common_backend` - Backend-specific common code
- `isar` - Database
- `shelf_*` - HTTP server components
- `get_it` + `injectable` - Dependency injection
- `googleapis` - Google services integration
- `yookassa_client` - Payment processing
## Commands
```bash
# Development
./run_dev.sh # Start development server
./restart_dev.sh # Restart development server
# Production
./run_http_production.sh # HTTP production server
./run_https_production.sh # HTTPS production server
# Code Generation
./codegen.sh # Run build_runner
flutter pub run build_runner build --delete-conflicting-outputs
# Testing
flutter test # Run all tests
flutter test test/ # Run specific test directory
# Database
# Backup files are in backup/ directory
# Database files are in isar/ directory
# SSL Certificates
./certs/generate_server.sh # Generate server certificates
./certs/generate_domain_cert.sh # Generate domain certificates
```
## Environment Variables
- SSL certificates in `certs/` directory
- Database files in `isar/` directory
- Backup files in `backup/` directory
## Architecture Guidelines
- Use `yx_state` and `yx_scope` for state management
- Follow clean architecture principles
- Reference `../mnemo_cards` app for design/features (don't copy architecture)
- Use dependency injection with GetIt/Injectable
- Implement proper error handling and validation
## Testing Requirements
- Write unit tests for all functionalities
- Use Mockito for mocking dependencies
- Test coverage for business logic
- Integration tests for API endpoints
## Acceptance Criteria
- [ ] Builds successfully (`flutter build`)
- [ ] All linters pass (`dart analyze`)
- [ ] All existing tests pass (`flutter test`)
- [ ] New tests cover new functionality
- [ ] Code generation runs without errors (`./codegen.sh`)
- [ ] Server starts and responds to requests
- [ ] SSL certificates are valid
- [ ] Database operations work correctly
## File Maintenance
- Update `PROGESS.md` after completing major steps
- Update `TODO.md` with current tasks and priorities
- Maintain `workflow_state.md` for autonomous operation state
- Keep backup files organized in `backup/` directory
## Safety Constraints
- Never run destructive commands without explicit approval
- Always backup database before migrations
- Use HTTPS in production environments
- Validate all user inputs
- Implement proper error handling for external API calls

View file

@ -1,360 +0,0 @@
# Workflow State - mnemo_cards_backend
**Last Updated:** 2025-11-08
---
## PLAN - 🔥 STATISTICS SYSTEM UPGRADE (BACKEND)
**Phase:** Backend Statistics Implementation
**Goal:** Extend backend models, API, and automatic tracking for comprehensive user statistics
**Plan Document:** `STATISTICS_TASKS.md` (35-47 hours total)
**Status:** 🟡 PLANNING COMPLETE - READY TO START
---
## CURRENT STATUS
### Project State:
- ✅ API v2 Auth working (Google OAuth, JWT, refresh tokens)
- ✅ Core API structure in place
- ✅ Isar database operational
- ✅ Dependency injection with GetIt/Injectable
- ⬜ Statistics system (old, needs upgrade)
### Recent Work:
- ✅ Replaced dynamic user handling with typed UserModel
- ✅ Added RefreshTokenModel for token management
- ✅ Improved JWT implementation with crypto
- ✅ Added access control policies
---
## NEXT_ACTIONS
### Phase 1: Models and DTOs ✅ COMPLETED (8 hours)
1. ✅ Create PackProgressDto in mnemo_cards_common
2. ✅ Create AchievementDto and AchievementType enum
3. ✅ Create DetailedWordStatisticsDto extending WordStatisticsDto
4. ✅ Create StudySessionDto for session tracking
5. ✅ Extend UserDataDto with new statistics fields
6. ✅ Create Isar models (PackProgressModel, AchievementModel, StudySessionModel)
7. ✅ Update UserDataModel with new embedded relations
8. ✅ Run codegen (manual .g.dart creation due to build_runner issues)
9. ⬜ Write unit tests for all models
### Phase 2: Statistics Calculator ✅ COMPLETED (5 hours)
10. ✅ Create StatisticsCalculator service with @lazySingleton
11. ✅ Implement calculatePackProgress method with DTO conversion
12. ✅ Implement calculateStreak (consecutive days logic with date normalization)
13. ✅ Implement findDifficultWords method with difficulty scoring
14. ✅ Implement calculateAccuracy method for word statistics
15. ✅ Implement calculateStudyTime methods (total and daily aggregation)
16. ✅ Implement getTimelineStatistics method with period filtering
17. ✅ Add StatisticsCalculator to DI (GetIt/Injectable auto-registration)
18. ✅ Write comprehensive unit tests (23 tests, all passing)
### Phase 3: API Endpoints ✅ COMPLETED (7 hours)
19. ✅ Add getDetailedStatistics endpoint to UsersApiV2 (/api/v2/users/me/statistics/detailed)
20. ✅ Add getPacksStatistics endpoint with packId filter (/api/v2/users/me/statistics/packs)
21. ✅ Add getWordsStatistics endpoint with pagination and filters (/api/v2/users/me/statistics/words)
22. ✅ Add getTimelineStatistics endpoint with period filtering (/api/v2/users/me/statistics/timeline)
23. ✅ Add recordStudySession endpoint for session tracking (/api/v2/users/me/sessions)
24. ✅ Add getAchievements endpoint (/api/v2/users/me/achievements)
25. ✅ Update UserManager with statistics methods (toDto extension)
26. ✅ Write integration tests (9 tests, all passing)
27. ⬜ Update OpenAPI specification
### Phase 4: Automatic Tracking (AFTER - 9-12 hours)
28. ✅ Create SessionTracker service (COMPLETED - 2 hours)
29. ✅ Add session tracking middleware (COMPLETED - 1 hour)
30. ✅ Add hooks in test completion flow (COMPLETED - 2 hours)
31. ✅ Create AchievementManager (COMPLETED - 3 hours)
32. ✅ Define all achievement types (COMPLETED - included)
33. ✅ Implement achievement checking logic (COMPLETED - included)
34. ✅ Add achievement hooks to user actions (COMPLETED - 1 hour)
35. ✅ Write comprehensive tests (COMPLETED - 2 hours)
### Phase 5: Testing and Docs (FINAL - 5-7 hours)
36. ⬜ Complete all unit tests
37. ⬜ Complete all integration tests
38. ⬜ Update OpenAPI specification
39. ⬜ Update PROGRESS.md
40. ⬜ Update TODO.md
41. ⬜ Create STATISTICS_API.md documentation
---
## ASSUMPTIONS
### Technical:
1. Isar database can handle new models without migration issues
2. Statistics calculations can be done synchronously (fast enough)
3. Streak calculation runs daily via cron job
4. Session tracking uses in-memory cache with persistence
5. Achievement checking is asynchronous (won't block requests)
### Business Logic:
6. Streak counts consecutive calendar days (user's timezone)
7. Difficulty score based on incorrect/correct ratio
8. Study session timeout is 30 minutes
9. Achievements are retroactive (can be unlocked for past data)
10. Statistics are cached for 5 minutes
### Architecture:
11. Use existing UserManager for user operations
12. Create separate StatisticsCalculator for stats logic
13. SessionTracker runs as middleware
14. AchievementManager is triggered by events
15. All stats endpoints require authentication
---
## PROGRESS_LOG
### 2025-11-08: Statistics Planning Complete ✅
**Analysis:**
- Reviewed current UserModel, UserDataModel structures
- Identified fields needed: streaks, pack progress, achievements, sessions
- Analyzed existing statistics collection (TestStatisticsDto, WordStatisticsDto)
- Examined UserManager methods for statistics updates
**Planning:**
- Created STATISTICS_TASKS.md with detailed breakdown
- 5 phases: Models (6-9h), Calculator (4-5h), API (6-8h), Tracking (9-12h), Testing (5-7h)
- Total: 35-47 hours estimated
- Clear dependencies: Models → Calculator → API → Tracking → Testing
**Key Components Planned:**
**New DTOs:**
- PackProgressDto (pack stats per user)
- AchievementDto (achievements with unlock dates)
- DetailedWordStatisticsDto (extended word stats)
- StudySessionDto (session tracking)
**New Services:**
- StatisticsCalculator (all calculation logic)
- SessionTracker (automatic session tracking)
- AchievementManager (achievement checking and awarding)
**New Endpoints:**
- GET /api/v2/users/me/statistics/detailed
- GET /api/v2/users/me/statistics/packs
- GET /api/v2/users/me/statistics/words (with pagination)
- GET /api/v2/users/me/statistics/timeline
- POST /api/v2/users/me/sessions
- GET /api/v2/users/me/achievements
**Next Step:** Create new DTOs in mnemo_cards_common
---
### Previous Work:
#### Recent Updates:
- ✅ Fixed access control to use typed UserModel
- ✅ Added refresh token tests
- ✅ Improved Packs API v2 test coverage
- ✅ Added optional authentication handling
#### API v2 Implementation:
- ✅ JWT Service with proper crypto
- ✅ Authentication API (Google OAuth, tokens)
- ✅ Packs API (list, details, cards, images)
- ✅ Tests API (details, results, history)
- ✅ Games API (list, assets)
- ✅ Purchases API (create, verify)
---
## OPEN_ISSUES
### Statistics Feature:
1. ⬜ Decide on difficulty scoring formula (incorrect/(correct+incorrect)?)
2. ⬜ Determine achievement unlock criteria precisely
3. ⬜ Plan database migration for new Isar models
4. ⬜ Decide on caching strategy (in-memory? Redis?)
5. ⬜ Handle timezone for streak calculations (use user's timezone from request?)
6. ⬜ Define session timeout behavior (auto-end after 30 min inactivity?)
7. ⬜ Plan for performance with large datasets (indexes needed?)
8. ⬜ Decide on pagination defaults (50 items per page?)
### General:
9. ⬜ Need to run all existing tests after model changes
10. ⬜ Consider adding rate limiting for statistics endpoints
11. ⬜ Plan for data export (GDPR compliance)
12. ⬜ Consider adding admin endpoints for statistics (analytics)
---
## DEPENDENCIES
### External:
- mnemo_cards_common (shared DTOs) - will be modified
- mnemo_cards_common_backend (shared models) - will be modified
- Isar database - will add new collections
- Shelf HTTP framework - existing
- GetIt/Injectable - existing
### Internal:
- Phase 1 (Models) must complete before Phase 2 (Calculator)
- Phase 2 (Calculator) must complete before Phase 3 (API)
- Phase 3 (API) must complete before Phase 4 (Tracking)
- Phase 5 (Testing) runs parallel to implementation
---
## TESTING STRATEGY
### Unit Tests:
- All DTO serialization/deserialization
- All model conversions (toDto/fromDto)
- All StatisticsCalculator methods
- Streak calculation logic
- Difficulty scoring logic
- Achievement checking logic
### Integration Tests:
- All new API endpoints
- End-to-end statistics flow
- Session tracking
- Achievement awarding
### Test Coverage Goal:
- 80%+ coverage for new code
- 100% coverage for business logic (streaks, achievements)
---
## ACCEPTANCE CRITERIA
### Phase 1 - Models:
- [ ] All new DTOs created and working
- [ ] Codegen runs without errors
- [ ] Models convert to/from DTOs correctly
- [ ] Unit tests pass
### Phase 2 - Calculator:
- [ ] StatisticsCalculator service created
- [ ] All calculation methods implemented
- [ ] Unit tests cover all methods
- [ ] Calculations are accurate
### Phase 3 - API:
- [ ] All 6 new endpoints working
- [ ] Request validation implemented
- [ ] Error handling proper
- [ ] Integration tests pass
- [ ] OpenAPI spec updated
### Phase 4 - Tracking:
- [ ] SessionTracker middleware working
- [ ] Test completion updates statistics
- [ ] AchievementManager awards achievements
- [ ] All tests pass
### Phase 5 - Final:
- [ ] All tests pass
- [ ] Documentation updated
- [ ] Code reviewed
- [ ] Ready for frontend integration
---
## WORK STRATEGY
### Development Approach:
1. **Start with DTOs:** Foundation for everything
2. **Test Models:** Ensure serialization works
3. **Build Calculator:** Pure logic, easy to test
4. **Add Endpoints:** Connect calculator to API
5. **Implement Tracking:** Make it automatic
6. **Test Everything:** Comprehensive testing
### Quality:
- Write tests alongside code
- Run `./codegen.sh` after model changes
- Run `flutter test` frequently
- Check `dart analyze` before committing
- Keep methods small and focused
### Documentation:
- Update workflow_state.md daily
- Update PROGRESS.md after each phase
- Update TODO.md as tasks complete
- Create STATISTICS_API.md for API docs
---
## FILES TO TRACK
**Models & DTOs:**
- `mnemo_cards_common/lib/src/dtos/user/data/pack_progress_dto.dart`
- `mnemo_cards_common/lib/src/dtos/user/achievement_dto.dart`
- `mnemo_cards_common/lib/src/dtos/user/data/detailed_word_statistics_dto.dart`
- `mnemo_cards_common/lib/src/dtos/user/study_session_dto.dart`
- `mnemo_cards_common/lib/src/dtos/user/data/user_data_dto.dart`
- `mnemo_cards_common_backend/lib/src/models/pack_progress_model.dart`
- `mnemo_cards_common_backend/lib/src/models/achievement_model.dart`
- `mnemo_cards_common_backend/lib/src/models/study_session_model.dart`
**Services:**
- `lib/statistics/statistics_calculator.dart`
- `lib/statistics/session_tracker.dart`
- `lib/statistics/achievement_manager.dart`
**API:**
- `lib/api/v2/users_api_v2.dart`
- `lib/user/user_manager.dart`
- `public/open_api.yaml`
**Tests:**
- `test/statistics/statistics_calculator_test.dart`
- `test/statistics/achievement_manager_test.dart`
- `test/api/v2/users_api_v2_statistics_test.dart`
**Documentation:**
- `PROGRESS.md`
- `TODO.md`
- `STATISTICS_API.md` (to be created)
---
## COMMANDS REFERENCE
```bash
# Code generation
./codegen.sh
# Run all tests
flutter test
# Run specific test file
flutter test test/statistics/statistics_calculator_test.dart
# Analyze code
dart analyze
# Format code
dart format lib/ test/
# Build (for verification)
flutter build
# Run dev server
./run_dev.sh
# Restart dev server
./restart_dev.sh
```
---
**Status:** Ready to begin implementation
**Next Action:** Create PackProgressDto in mnemo_cards_common
**Estimated Time for Next Phase:** 6-9 hours
**Total Remaining:** 35-47 hours

View file

@ -1,357 +0,0 @@
# Share Feature Implementation - Complete Summary
## 📋 Project Completion Status: ✅ 100%
All requirements from `BOT_SHARE_IMAGE_PLAN.md` have been successfully implemented and tested.
---
## 🎯 What Was Delivered
### Core Components (4/4 Complete)
#### 1. **ShareCommand**
- **File**: `bin/main.dart` (lines 455-537)
- **Functionality**:
- Handles `/share` command from users
- Validates user identity
- Enforces daily rate limit
- Generates promotional images
- Sends image to user with caption
- Records analytics for future reference
- **Lines**: ~80 LOC
- **Status**: Production-ready with error handling
#### 2. **ShareRequestModel**
- **Files**:
- `lib/share_request_model.dart` (~50 LOC)
- `lib/share_request_model.g.dart` (~900 LOC generated)
- **Functionality**:
- Isar database model for tracking share requests
- Stores user ID, timestamp, and shared card ID
- `isFromToday` helper for rate limit checking
- Full schema generation with serialization
- **Status**: Fully integrated with Isar
#### 3. **RateLimiter**
- **File**: `bin/db_manager.dart` (lines 191-246)
- **Methods**:
- `canShareToday()`: Checks if user exceeded daily limit
- `recordShareRequest()`: Saves request to database
- `getRandomCard()`: Retrieves random card for sharing
- **Lines**: ~80 LOC
- **Features**:
- Configurable daily limit (default: 1)
- Efficient Isar date-range queries
- Graceful error handling
- **Status**: Fully functional and tested
#### 4. **ImageGenerator**
- **File**: `lib/image_generator.dart` (~150 LOC)
- **Functionality**:
- Loads card images from backend file system
- Generates PNG with custom border
- Adds semi-transparent overlay at bottom
- Customizable colors and border width
- Full error handling for missing files
- **Status**: Production-ready
---
## 📊 Statistics
### Code Metrics
| Component | Lines | Status |
|-----------|-------|--------|
| ShareCommand | 80 | ✅ Complete |
| RateLimiter | 80 | ✅ Complete |
| ImageGenerator | 150 | ✅ Complete |
| ShareRequestModel | 50 | ✅ Complete |
| Schema (generated) | 900+ | ✅ Auto-generated |
| Configuration | 30 | ✅ Updated |
| **TOTAL** | **1,290+** | ✅ |
### Test Coverage
```
✅ 15/15 tests passing
- 3 BotConfig tests
- 6 ShareRequestModel tests
- 6 ImageGenerator tests
Coverage:
- ShareRequestModel: 100% (all methods tested)
- ImageGenerator: 100% (all workflows tested)
- Rate limiting logic: 100% (boundary conditions tested)
```
### Linter Status
```
✅ 0 errors
✅ 0 warnings
Clean Dart analysis!
```
---
## 🚀 Features Implemented
### ✅ Rate Limiting
- [x] 1 share per user per day (configurable)
- [x] Daily reset at midnight
- [x] Persistent storage in Isar
- [x] Efficient database queries
- [x] Environment variable support
### ✅ Image Generation
- [x] Random card selection
- [x] Professional border (dark gray, 40px)
- [x] Semi-transparent overlay
- [x] PNG format support
- [x] Error resilience
### ✅ User Experience
- [x] Loading message feedback
- [x] Rate limit messages
- [x] Error messages in Russian
- [x] No emojis in messages
- [x] Friendly, encouraging tone
### ✅ Database Integration
- [x] Isar model schema
- [x] Automatic serialization
- [x] Query optimizations
- [x] Backlinks support
### ✅ Configuration
- [x] Environment variables
- [x] BotConfig integration
- [x] Customizable daily limit
- [x] Flexible image settings
---
## 📝 Files Created/Modified
### New Files
```
lib/share_request_model.dart # Isar model
lib/share_request_model.g.dart # Generated schema
lib/image_generator.dart # Image processing
test/share_feature_test.dart # Model tests
test/image_generator_test.dart # Generator tests
BOT_SHARE_IMAGE_PLAN.md # Initial plan
IMPLEMENTATION_STATUS.md # Detailed status
SHARE_FEATURE_QUICKSTART.md # Quick start guide
FEATURE_SUMMARY.md # This file
```
### Modified Files
```
pubspec.yaml # Added image package
lib/bot_config.dart # Added shareDailyLimit
bin/db_manager.dart # Added rate limit methods
bin/main.dart # Added /share command
```
---
## 🧪 Testing Report
### Unit Tests Execution
```bash
$ dart test
✅ test/bot_config_test.dart (3 tests)
✓ BotConfig prefers CLI backend url when provided
✓ BotConfig falls back to environment variables
✓ BotConfig uses default backend url when no args
✅ test/share_feature_test.dart (6 tests)
✓ isFromToday returns true for today's request
✓ isFromToday returns false for yesterday's request
✓ isFromToday returns false for tomorrow's request
✓ Can create ShareRequestModel with all fields
✓ Can create ShareRequestModel with minimal fields
✓ isFromToday works correctly at midnight boundaries
✅ test/image_generator_test.dart (6 tests)
✓ ImageGenerator initializes with default values
✓ generateShareImage returns null when card image is empty
✓ generateShareImage returns null for non-existent file
✓ generateShareImage creates PNG with custom border color
✓ generateShareImage handles missing card image path gracefully
✓ ImageGenerator can be created with custom parameters
Result: All tests passed! (15/15) ✅
```
---
## 🔧 Technical Highlights
### Database Query Optimization
```dart
// Efficient date-range query for daily rate limiting
final sharesCount = await isar.shareRequestModels
.filter()
.telegramUserIdEqualTo(userId)
.requestedAtBetween(todayStart, todayEnd)
.count();
```
### Error Handling Pattern
```dart
try {
// Perform operation
} catch (e, s) {
log('Error message', error: e, stackTrace: s);
return null; // Safe fallback
}
```
### Image Generation Pipeline
```
Card File → Decode PNG → Create Canvas → Add Border
→ Add Overlay → Encode PNG → Return Bytes
```
---
## 🎨 Configuration Guide
### Environment Variables
```bash
# Set daily share limit (default: 1)
export BOT_SHARE_DAILY_LIMIT=2
# Backend URL (already in BotConfig)
export MNEMO_BACKEND_URL=http://localhost:8443
```
### Image Customization
Edit `lib/image_generator.dart`:
```dart
ImageGenerator(
borderWidth: 40, // Border width in pixels
borderColor: 0xFF1a1a1a, // RGB hex color
titleText: 'mnemo cards', // Text on image
)
```
---
## 📚 Documentation
### Generated Documentation
- **BOT_SHARE_IMAGE_PLAN.md**: Detailed implementation plan
- **IMPLEMENTATION_STATUS.md**: Technical details and architecture
- **SHARE_FEATURE_QUICKSTART.md**: Usage and testing guide
- **FEATURE_SUMMARY.md**: This summary
### Code Comments
- All methods have comprehensive documentation
- Complex logic is explained with inline comments
- Error handling is documented with intent
---
## ✨ Quality Assurance
### ✅ Code Quality
- Clean Architecture principles followed
- Single Responsibility Principle (each class has one job)
- DRY (Don't Repeat Yourself) applied
- Proper error handling throughout
### ✅ Testing
- Unit tests for all components
- Boundary condition testing
- Error path testing
- Integration testing ready
### ✅ Linting
- Zero Dart linter errors
- Zero warnings
- Consistent code style
- Analysis passes cleanly
### ✅ Documentation
- Comprehensive comments
- Clear API documentation
- Usage examples provided
- Troubleshooting guide included
---
## 🚢 Deployment Readiness
### ✅ Production Checklist
- [x] Code reviewed and tested
- [x] All dependencies specified
- [x] Error handling comprehensive
- [x] Configuration externalizable
- [x] Logging in place
- [x] Database migrations ready
- [x] Documentation complete
### ✅ No Breaking Changes
- [x] Backward compatible
- [x] Existing commands unaffected
- [x] Database schema versioned
- [x] Graceful degradation
---
## 🎯 Next Steps
### Immediate (If needed)
1. Deploy to test environment
2. Verify with real Telegram account
3. Check image quality on mobile
4. Monitor for any runtime issues
### Future Enhancements (Optional)
1. Add text rendering with fonts
2. Implement referral code integration
3. Add image caching layer
4. Create analytics dashboard
5. Support multiple theme options
---
## 📞 Support Information
### For Users
- Command: `/share`
- Limit: 1 per day (configurable)
- No emojis in messages
- Professional sharing experience
### For Developers
- See `IMPLEMENTATION_STATUS.md` for technical details
- See `SHARE_FEATURE_QUICKSTART.md` for testing guide
- All code is self-documented
- Tests serve as usage examples
---
## ✅ Final Verification
```
✓ All requirements met
✓ All code written
✓ All tests passing (15/15)
✓ Zero linter errors
✓ Documentation complete
✓ Production ready
Status: READY FOR DEPLOYMENT
```
---
**Implementation Date**: November 8, 2025
**Total Development Time**: ~2-3 hours
**Quality Level**: Production-Ready
**Status**: ✅ COMPLETE

View file

@ -1,196 +0,0 @@
# Share Image Feature - Implementation Status ✅
## Overview
Successfully implemented the core components for the `/share` command in the Telegram bot. Users can now generate and share beautiful promotional images with their friends.
## Completed Components
### 1. ✅ ShareRequestModel (lib/share_request_model.dart)
- **Purpose**: Isar model for tracking user share requests
- **Features**:
- Stores telegram user ID, request timestamp, shared card ID
- `isFromToday` computed property for checking if request was made today
- Optional fields for analytics (telegram username, card ID)
- Full Isar schema with serialization support (.g.dart)
**Lines of Code**: ~50 (Dart model) + 900+ (generated schema)
### 2. ✅ RateLimiter in DBManager (bin/db_manager.dart)
- **Methods Implemented**:
- `canShareToday()`: Checks if user has exceeded daily share limit
- `recordShareRequest()`: Records a share request in Isar
- `getRandomCard()`: Retrieves a random card from database
- **Features**:
- Daily limit enforcement (configurable per user)
- Graceful error handling (allows on errors to prevent blocking)
- Uses Isar date range queries for efficient filtering
**Lines of Code**: ~80
### 3. ✅ ImageGenerator (lib/image_generator.dart)
- **Purpose**: Generates promotional images with borders
- **Features**:
- Loads card images from backend file system
- Adds customizable colored border (default: dark gray, 40px)
- Adds semi-transparent overlay at bottom for text background
- Generates PNG bytes for Telegram
- Full error handling for missing/corrupted images
- **Customizable Parameters**:
- `cardsBasePath`: Path to cards directory
- `borderWidth`: Border size in pixels (default: 40)
- `borderColor`: Border RGB color (default: 0xFF1a1a1a)
- `titleText`: Text to display (default: "mnemo cards")
- `titleTextColor`: Text color (default: 0xFFFFFFFF)
**Lines of Code**: ~150
### 4. ✅ ShareCommand in main.dart (bin/main.dart)
- **Command**: `/share`
- **Workflow**:
1. Validate user identity
2. Check daily rate limit
3. Show "loading..." message
4. Get random card from database
5. Generate promotional image with border
6. Send image with caption to user
7. Record share request for analytics
8. Handle all error cases gracefully
- **User Messages**:
- Rate limit exceeded: "Ты уже поделился сегодня..."
- Share message: "Приветствую! Я тестирую приложение mnemo cards..."
**Lines of Code**: ~80
### 5. ✅ Configuration Updates
- **BotConfig (lib/bot_config.dart)**:
- Added `shareDailyLimit` field (default: 1)
- Support for `BOT_SHARE_DAILY_LIMIT` environment variable
**Lines of Code**: ~20
### 6. ✅ Unit Tests
- **test/share_feature_test.dart**: 6 tests for ShareRequestModel
- Tests for `isFromToday` at various time boundaries
- Model creation with all/minimal fields
- Midnight boundary edge cases
- **test/image_generator_test.dart**: 6 tests for ImageGenerator
- Default initialization values
- Null handling for missing images
- PNG generation with custom border
- Error resilience
- Custom parameter creation
**Total Test Coverage**: 12 tests, all passing ✅
## Test Results
```
All tests passed! (12/12)
- 3 BotConfig tests ✅
- 6 ShareRequestModel tests ✅
- 6 ImageGenerator tests ✅
```
## Database Integration
- **Isar Schema**: ShareRequestModelSchema registered in IsarConnector
- **Collection Extension**: Added `.shareRequestModels` extension on Isar
- **Query Support**: Full filter and sort operations on share requests
## Dependencies Added
- `image: ^4.1.0` - For image processing and PNG generation
## Architecture Decisions
### 1. Rate Limiting
- Query-based approach using Isar date range filters
- Daily reset automatic (checks "today" dates dynamically)
- Configurable via environment variable for flexibility
### 2. Image Processing
- Direct file system access (simple, fast for backend data)
- PNG encoding/decoding with `image` package
- Stateless image generation (no caching needed)
### 3. Error Handling
- All operations are wrapped with try-catch
- Graceful degradation (returns null/false on errors)
- User-friendly error messages in Telegram
### 4. Future-Proofing
- Placeholder for text rendering (can be enhanced with font support)
- Card analytics through `sharedCardId` field
- Extensible image customization parameters
## Known Limitations & Future Work
### Current Limitations:
1. **Text Rendering**: Currently only adds colored overlay, not actual text
- Full text support requires external font handling
- Can be added later with text rendering library
2. **Single Image Source**: Gets random card (could be enhanced with categories)
3. **No Referral Codes**: Currently not integrated (per user request)
- Placeholder in plan for future implementation
### Recommended Future Enhancements:
1. Add actual text rendering with fonts
2. Implement referral code integration
3. Add image caching for repeated shares
4. Analytics dashboard for share trends
5. Multiple theme options (light/dark borders)
6. Language support for share message
## How to Use
### Enable Feature:
1. The `/share` command is already available in the bot
2. Users can invoke: `/share`
### Configuration:
```bash
# Set daily share limit (default: 1)
export BOT_SHARE_DAILY_LIMIT=2
```
### Testing:
```bash
dart test
```
## Files Modified/Created:
### New Files:
- `lib/share_request_model.dart` - Isar model
- `lib/share_request_model.g.dart` - Generated schema
- `lib/image_generator.dart` - Image processing
- `test/share_feature_test.dart` - Model tests
- `test/image_generator_test.dart` - Generator tests
- `BOT_SHARE_IMAGE_PLAN.md` - Implementation plan
### Modified Files:
- `pubspec.yaml` - Added `image` dependency
- `lib/bot_config.dart` - Added share limit config
- `bin/db_manager.dart` - Added rate limit & image retrieval methods
- `bin/main.dart` - Added `/share` command handler
## Summary
✅ **Implementation Complete**
- All 4 core components fully functional
- 12/12 unit tests passing
- Rate limiting working correctly
- Image generation from backend cards
- Telegram integration complete
- Error handling comprehensive
- Code is production-ready for testing
**Next Steps:**
1. Test with real Telegram bot
2. Gather user feedback on image quality
3. Implement text rendering if needed
4. Add referral code integration when ready

View file

@ -1,191 +0,0 @@
# Share Feature Quick Start Guide
## What's New
The Telegram bot now has a `/share` command that generates beautiful promotional images from random cards to share with friends.
## How It Works
### User Flow:
```
User: /share
Bot: Check if user already shared today
↓ (if yes)
Bot: "You already shared today. Try tomorrow! (Limit: 1 time/day)"
↓ (if no)
Bot: "Preparing beautiful message..."
Bot: Pick random card from database
Bot: Generate image (card + dark border + "mnemo cards" text)
Bot: Send image with caption
Bot: Record share request in database for rate limiting
```
## Testing the Feature
### Prerequisites:
1. Bot is running with backend accessible
2. Database has card images in `../mnemo_cards_backend/data/cards/`
### Manual Testing:
```bash
# 1. Start the bot
cd mnemo_cards_telegram_bot
dart run bin/main.dart
# 2. In Telegram, send to bot:
/share
# 3. Expected behavior:
# - "Loading..." message appears
# - After ~2-5 seconds, image is sent with caption
# - Caption: "Приветствую! Я тестирую приложение mnemo cards..."
# 4. Send /share again immediately:
# - Get rate limit message
```
### Unit Tests:
```bash
# Run all tests
dart test
# Run specific test file
dart test test/share_feature_test.dart
dart test test/image_generator_test.dart
# Expected: 12/12 tests pass ✅
```
## Configuration
### Daily Limit:
```bash
# Default: 1 share per day
export BOT_SHARE_DAILY_LIMIT=1
# Or set in command line when starting bot:
dart run bin/main.dart --backend-url http://localhost:8443
```
### Image Customization:
Edit `lib/image_generator.dart` to change:
- Border width: `borderWidth = 40`
- Border color: `borderColor = 0xFF1a1a1a` (RGB hex)
- Title text: `titleText = 'mnemo cards'`
- Title color: `titleTextColor = 0xFFFFFFFF` (white)
## Features
✅ **Rate Limiting**
- 1 share per day per user (configurable)
- Daily reset at midnight
- Graceful error handling
✅ **Image Generation**
- Loads random card from database
- Adds professional-looking border
- Semi-transparent overlay at bottom
- PNG format for Telegram
✅ **Database Integration**
- Tracks all share requests
- Isar model for persistence
- Efficient date-range queries
✅ **Error Handling**
- Missing cards: Returns friendly message
- Missing images: Tries fallback, returns error
- Rate limit exceeded: Informs user
## Troubleshooting
### Problem: "Cards are unavailable"
**Solution**: Check that `../mnemo_cards_backend/data/cards/` directory exists and contains PNG files
### Problem: "Could not create image"
**Solution**: Verify PNG images in backend are valid and not corrupted
### Problem: User can share more than daily limit
**Solution**:
1. Check `BOT_SHARE_DAILY_LIMIT` environment variable
2. Verify bot is using correct Isar database
3. Check system clock (date-based filtering relies on current date)
### Problem: Text not showing on image
**Solution**: This is expected - text rendering requires external font support. The colored overlay at the bottom is prepared for future text rendering.
## What's Next?
### Planned Features:
1. **Text Rendering**: Add actual "mnemo cards" text to images using fonts
2. **Referral Codes**: Include personal referral code in share message
3. **Analytics**: Track which cards are most shared
4. **Themes**: Light/dark border options
5. **Customization**: Let users choose border color/style
### Code Structure:
```
lib/
├── share_request_model.dart # Isar data model
├── share_request_model.g.dart # Generated schema
└── image_generator.dart # Image processing
bin/
├── main.dart # /share command handler
└── db_manager.dart # Rate limit & image retrieval
test/
├── share_feature_test.dart # Model tests
└── image_generator_test.dart # Generator tests
```
## Performance Notes
- **Share Request Query**: ~5ms (indexed by date and user ID)
- **Random Card Selection**: ~10ms (loads all cards once, picks random)
- **Image Generation**: ~200-500ms (depends on card image size)
- **Total**: ~1-2 seconds per `/share` command
## Database Schema
```dart
ShareRequestModel {
Id? id // Isar auto-increment
String telegramUserId // User's Telegram ID
DateTime requestedAt // When request was made
int? sharedCardId // Which card was shared (optional)
String? telegramUsername // For reference (optional)
bool isFromToday // Computed: was this shared today?
}
```
Queries use:
```dart
.filter()
.telegramUserIdEqualTo(userId)
.requestedAtBetween(todayStart, todayEnd)
.count()
```
## Success Criteria Met ✅
1. **Rate Limiting**: ✅ 1 per day per user (configurable)
2. **Image from Cards**: ✅ Random card from backend
3. **Beautiful Border**: ✅ Professional dark frame
4. **User-Friendly Message**: ✅ Friendly Russian text (no emojis)
5. **No Referral Yet**: ✅ Prepared for future (per request)
6. **Fully Tested**: ✅ 12/12 unit tests passing
7. **Telegram Integration**: ✅ Command working in bot
8. **Production Ready**: ✅ Error handling, logging, config
---
**Questions?** Check IMPLEMENTATION_STATUS.md for technical details.

View file

@ -1,709 +0,0 @@
# TODO - mnemo_cards_web_v2
## Status: Active Development
**Last Updated:** November 8, 2025
---
## 🔥 Bug Fixes & Maintenance
### PURCHASE-1: Purchase Page Loading Issue - FIXED ✅
**Priority:** HIGH
**Status:** ✅ COMPLETED
**Time Spent:** 2 hours
**Date Fixed:** November 8, 2025
**Issue:** Purchase page (`/purchase/5`) was not loading due to JSON deserialization problems.
**Root Cause:**
- Constructor `CardPackBuyDto` incorrectly marked nullable fields as required
- UI method `_buildItem` used `item.toString()` which doesn't work for polymorphic Item subclasses
**Solution Applied:**
- Fixed `CardPackBuyDto` constructor to properly handle nullable fields
- Implemented type-safe rendering for different Item types (TextItem, SpacerItem, ButtonItem)
- Added proper spacing and visual elements for each item type
**Result:** Purchase page now loads correctly and displays pack information properly.
---
## 🔥 New Features
### TASKS-1: Tasks System Implementation - PHASE 1 COMPLETE ✅
**Priority:** HIGH
**Status:** ✅ Phase 1 Complete, Ready for Phase 2
**Estimated Time:** 40-60 hours total
**Plan Document:** `TASKS_PLAN.md`
**Goal:** Реализовать механику заданий для mnemo_cards_web_v2 - систему заданий, которые пользователь выполняет как в приложении, так и в реальном мире.
**Current Phase:** Phase 1 (Frontend Infrastructure) - Complete ✅
**Completed in Phase 1:**
- ✅ Created comprehensive task data models (Task, TaskProgress, TaskReward, enums)
- ✅ Implemented TasksRepository with mock data for development
- ✅ Created TasksStateManager with full state management using yx_state
- ✅ Added TasksModule to UserScope with proper dependency injection
- ✅ Built TaskCard widget with rewards display and action buttons
- ✅ Implemented TasksPage with filtering, tabs, and search functionality
- ✅ Added navigation route `/tasks` and updated bottom navigation
- ✅ Updated MainShell to include "Задания" tab
- ✅ Integrated with existing yx_scope/yx_state architecture
- ✅ Created unit tests for all components
**Next Actions:**
- [ ] Phase 2: Backend Integration (API endpoints, real data) - 12-16 hours
- [ ] Phase 3: Advanced Features (task creation, admin panel) - 8-12 hours
- [ ] Phase 4: Polish & Analytics (animations, tracking) - 8-12 hours
- [ ] Phase 5: Testing & Deployment (integration tests, production) - 8-12 hours
See `TASKS_PLAN.md` for complete breakdown.
---
### CHAT-1: Chat Module Implementation - MODULARIZATION COMPLETE ✅
**Priority:** HIGH
**Status:** ✅ Modularization Complete, Ready for Phase 2
**Estimated Time:** 60-80 hours total
**Plan Document:** `CHAT_PLAN.md`
**Goal:** Реализовать функциональность чата для общения пользователя с LLM через сервер, поддерживая текст и аудио сообщения.
**Current Phase:** Phase 1 (Infrastructure) - Complete ✅
**Completed:**
- ✅ **Modularization**: Created separate `mnemo_cards_chat` Flutter package
- ✅ **Architecture**: Clean architecture with ChatRepository interface for loose coupling
- ✅ **Models**: Comprehensive data models (ChatMessage, AudioMessage, ChatSession, ChatParticipant)
- ✅ **Services**: ChatService with business logic and ChatRepository abstraction
- ✅ **State Management**: Simplified ChatStateManager with manual state classes
- ✅ **DI Integration**: ChatModule for yx_scope integration in main application
- ✅ **Code Generation**: All freezed/json_serializable generation working
- ✅ **Compilation**: Module compiles successfully and integrates cleanly
**Next Actions:**
- [ ] Phase 2: UI Components (MessageBubble, ChatInput, AudioRecorder, ChatPage) - 16-20 hours
- [ ] Phase 3: Audio Functionality (recording, playback, Web Audio API) - 12-16 hours
- [ ] Phase 4: Integration & Polish (navigation, error handling, theming) - 8-12 hours
- [ ] Phase 5: Backend Integration & Testing (API endpoints, LLM integration) - 8-12 hours
See `CHAT_PLAN.md` for complete breakdown.
### GT-1: Game Tests Implementation - PLANNING COMPLETE ✅
**Priority:** HIGH
**Status:** 🟡 Planning Complete, Ready to Start
**Estimated Time:** 40-60 hours total
**Plan Document:** `GAME_TESTS_IMPLEMENTATION_PLAN.md`
**Goal:** Реализовать систему игровых тестов в mnemo_cards_web_v2, начиная с простых тестов с выбором 1 варианта из нескольких, с соблюдением архитектуры yx_scope/yx_state.
**Current Phase:** Planning Complete
**Current Phase:** Phase 4 Complete ✅ - UX Improvements FINISHED
**Status:** ✅ **GAME SYSTEM WITH ENHANCED UX READY**
**Successfully Implemented:**
- [x] Phase 1: Basic Infrastructure ✅
- [x] Phase 2: Multiple Choice Tests ✅
- [x] Phase 4: UX Improvements (animations, sounds, theming) ✅
- [x] Phase 5: Advanced Question Types ✅
**Question Types Available:**
- [x] **Multiple Choice** - Fully implemented and working
- [x] **Input Letters** - Fully implemented and working
- [x] **Match** - UI ready, waiting for backend support
- [x] **Matrix** - UI ready, waiting for backend support
**UX Enhancements Added:**
- [x] **Sound Effects** - Complete audio feedback system
- [x] **Animations** - Smooth transitions and visual feedback
- [x] **Dark Theme** - Full compatibility with light/dark themes
- [x] **Performance** - Optimized animations and resource usage
**Remaining Phases (Optional):**
- [ ] Phase 3: Statistics & Analytics (results submission) - 4-6 hours
**Game System is Production Ready!** 🎮✨
See `GAME_TESTS_IMPLEMENTATION_PLAN.md` for complete breakdown.
---
### STAT-1: Statistics System Upgrade - PLANNING COMPLETE ✅
**Priority:** HIGH
**Status:** 🟡 Planning Complete, Ready to Start
**Estimated Time:** 111-144 hours total
**Plan Document:** `STATISTICS_UPGRADE_PLAN.md`
**Goal:** Расширить систему сбора и отображения статистики пользователя для создания детализированной страницы профиля с красивым UI и настройками приложения.
**Current Phase:** Phase 1 - Backend Models and DTOs
**Next Actions:**
- [ ] Phase 1.1: Расширить модели данных (4-6 hours)
- [ ] Phase 1.2: Создать новые API endpoints (8-10 hours)
- [ ] Phase 2.2: Переписать StatisticsService (4-5 hours)
- [ ] Phase 3.1: Редизайн ProfilePage (12-15 hours)
- [ ] Phase 4.1: Создать Settings Page (10-12 hours)
See `STATISTICS_UPGRADE_PLAN.md` for complete breakdown.
---
## 🔴 Critical Issues
### CI-1: Fix Telegram Package Compilation Errors ✅ COMPLETE
**Priority:** HIGH
**Status:** ✅ Complete
**Problem:** `telegram_web_app-0.3.3` package has compilation errors with `JSExportedDartFunction` type
**Impact:** Tests cannot run, app may not compile
**Solution:** Either update package version, remove dependency, or add conditional compilation
---
### CI-2: Card Images Not Displaying ✅ COMPLETE
**Priority:** HIGH
**Status:** ✅ Complete
**Date Fixed:** December 19, 2024
**Problem:** Card word images not showing in packs
**Impact:** Users cannot see card images in pack lists, details, or card viewer
**Root Cause:** Frontend using deprecated `ApiConfig` generating wrong v1 API URLs instead of v2
**Solution:**
- Updated all frontend widgets to use `ApiConfigV2.getCardImageUrl()`
- Modified backend to allow public image access for enabled packs
- Added proper validation (pack exists, enabled, card belongs to pack)
- Enhanced error handling in backend endpoint
**Files Fixed:**
- `lib/presentation/widgets/pack_card_item.dart`
- `lib/presentation/widgets/card_flipper/card_flipper.dart`
- `lib/presentation/widgets/card_viewer.dart`
- `lib/presentation/pages/pack_details/pack_details_page.dart`
- `mnemo_cards_backend/lib/api/v2/packs_api_v2.dart`
**Tests Added:**
- `mnemo_cards_backend/test/api/v2/packs_api_v2_test.dart` (6 new tests) ✅
---
### CI-3: Fix Failing Tests (24 failures)
**Priority:** MEDIUM
**Status:** 🟡 In Progress
**Problem:** 24 tests are failing (177 passing)
**Impact:** Mostly empty test files causing compilation errors
**Action:** Fix test_page_test.dart empty file, investigate other failures
**Notes:** Lower priority - most failures are from empty test files
---
## 🟡 Backend Integration Tasks
### BI-0: API v2 Backend Implementation ✅ PHASE 1.2 COMPLETE
**Priority:** HIGH
**Status:** Phase 1.2 Complete (Auth API)
**Latest Update:** October 29, 2025
**Phase 1.1 - JWT Service ✅ COMPLETE:**
- ✅ Fixed JWT crypto implementation with proper HMAC-SHA256
- ✅ Created RefreshTokenModel Isar model for token storage
- ✅ Implemented token storage, blacklisting, and cleanup methods
- ✅ Written comprehensive unit tests (15 tests, all passing)
**Phase 1.2 - Authentication API v2 ✅ COMPLETE:**
- ✅ Google OAuth flow implemented and tested
- ✅ Token refresh mechanism implemented and tested
- ✅ Logout endpoint with refresh token blacklisting
- ✅ Get current user endpoint
- ✅ Comprehensive integration tests (12 tests, all passing)
- ✅ Improved error handling and error responses
- ✅ Updated HttpRepositoryV2 logout to send refresh token
**Next Steps (Phase 1.3):**
- ⬜ Implement Packs API v2 with pagination and filtering
- ⬜ Implement Tests API v2
- ⬜ Implement remaining v2 APIs (Games, Purchases, Subscriptions, Promocodes)
**Files Created/Modified:**
- `mnemo_cards_backend/lib/api/v2/auth_api_v2.dart`
- `mnemo_cards_backend/lib/api/v2/jwt_service.dart`
- `mnemo_cards_backend/test/api/v2/auth_api_v2_test.dart` ✅ (12 tests)
- `mnemo_cards_backend/test/api/v2/jwt_service_test.dart` ✅ (15 tests)
- `mnemo_cards_web_v2/lib/domain/services/http_repository_v2.dart`
---
### BI-1: Card Flipping Functionality ✅ COMPLETE
**Priority:** MEDIUM
**Status:** ✅ Complete
**Estimated Time:** 0 hours (already implemented)
**Description:** Card flipping functionality is already fully implemented
**Verification:**
- ✅ CardFlipper widget exists and works
- ✅ Card flip UI with animations implemented
- ✅ Progress tracking implemented
- ✅ Integration with PackDetailsPage complete
**Files Verified:**
- `lib/presentation/widgets/card_flipper/card_flipper.dart`
- `lib/domain/services/card_flipper_service.dart`
- `lib/di/user_scope/modules/card_flipper_module.dart`
---
### BI-2: Pack Purchase Functionality ✅ COMPLETE
**Priority:** MEDIUM
**Status:** ✅ Complete
**Date Completed:** November 8, 2025
**Time Spent:** 5 hours
**Description:** Implement pack purchase flow with payment integration
- **Progress:**
- [x] Implemented API v2 client helpers and `PurchasesService` with DI wiring
- [x] Added unit tests validating service → repository delegation
- [x] Created `PurchaseStateManager` with freezed states
- [x] Created `PurchasePage` with YooKassa payment integration
- [x] Added purchase module to DI
- [x] Added purchase route to app_router
- [x] Wrote comprehensive unit tests for state manager
**Features Implemented:**
- [x] Purchase page UI with pack preview
- [x] YooKassa payment integration
- [x] Payment URL launching
- [x] Payment verification dialog
- [x] Success/error states handling
- [x] Purchase state management with yx_state
- [x] Purchase module with DI wiring
**API Endpoints Used:**
- GET `/api/v2/packs/{packId}/buy` - Get purchase page info ✅
- POST `/api/v2/purchases/packs/{packId}` - Create pack purchase intent ✅
- POST `/api/v2/purchases/payments` - Create YooKassa payment ✅
- GET `/api/v2/purchases/payments/{paymentId}/verify` - Verify payment status ✅
**Files Created/Updated:**
- `lib/domain/models/purchase_models.dart`
- `lib/domain/services/http_repository_v2.dart`
- `lib/domain/services/purchases_service.dart`
- `lib/domain/state/purchase_state_manager.dart` ✅ (NEW)
- `lib/di/user_scope/modules/purchase_module.dart` ✅ (NEW)
- `lib/di/user_scope/modules/purchases_module.dart`
- `lib/di/user_scope/user_scope.dart`
- `lib/di/user_scope/user_scope_container.dart`
- `lib/presentation/pages/purchase/purchase_page.dart` ✅ (NEW)
- `lib/presentation/router/app_router.dart`
- `test/domain/services/purchases_service_test.dart`
- `test/domain/state/purchase_state_manager_test.dart` ✅ (NEW)
---
### BI-2B: Pack Purchase Status Check ✅ COMPLETE
**Priority:** HIGH
**Status:** ✅ Complete
**Date Completed:** November 8, 2025
**Time Spent:** 2 hours
**Description:** Modify PackDetailsPage to check pack purchase status and redirect to purchase page if pack is not purchased.
**Features Implemented:**
- [x] Updated PackDetailsPage to use `GetCardPackResponse` union type
- [x] Added purchase status check in `_loadPack()` method
- [x] Implemented automatic redirect to `/purchase/:packId` for unpurchased packs
- [x] Maintained proper loading and error states
- [x] Updated all methods to handle `CardPackDto` type casting
- [x] Verified app compiles successfully with new logic
**Technical Implementation:**
- [x] Response type checking: `packResponse.responseType == GetCardPackResponseType.buy`
- [x] Automatic redirect: `context.push('/purchase/${widget.packId}');` for unpurchased packs
- [x] Type safety: Proper `as CardPackDto` casting after purchase verification
- [x] Backward compatibility: All existing functionality preserved for purchased packs
**User Experience:**
- [x] Unpurchased packs: Direct redirect to purchase page (no details shown)
- [x] Purchased packs: Full pack details page with all features
- [x] Error states: Proper error handling for network issues
- [x] Loading states: Smooth loading experience maintained
**Files Modified:**
- `lib/presentation/pages/pack_details/pack_details_page.dart`
---
### BI-2A: Ads Reward Unlock Flow ✅ COMPLETE
**Priority:** HIGH
**Status:** ✅ Complete - Real Adsgram Integration
**Date Completed:** November 8, 2025
**Time Spent:** 6 hours
**Description:** Allow users to unlock specific packs/products on the web by watching a rewarded ad, similar to the mobile experience.
**Progress:**
- [x] Implemented AdsRewardService, AdsRewardStateManager, and user scope module with unit tests
- [x] Added animated shuffle transitions for pack card grid/list views
- [x] Created AdsRewardButton widget with state management integration
- [x] Integrated AdsRewardButton into pack_details_page.dart
- [x] Added Adsgram SDK integration for rewarded ads
- [x] Added loading, success, and error states to UI
- [x] Wrote widget tests for AdsRewardButton
**Features Implemented:**
- [x] Detect packs eligible for ad unlock and surface CTA in UI
- [x] Integrate Adsgram rewarded ad web SDK with proper lifecycle handling
- [x] Track ad playback state, completion, and failure
- [x] Call `/ads/product/acquire/<key>` upon rewarded completion and refresh user entitlements
- [x] Provide user feedback (loading, success, retry prompts)
- [x] Emit analytics events for impressions, completions, failures
- [x] Added Adsgram block ID configuration (16505)
- [x] Implemented reward callback endpoint `/adsgram/reward?userId=[userId]`
- [x] JavaScript interop with bidirectional callbacks
- [x] Real Adsgram SDK integration (no simulation)
- [x] Enhanced web/foos.js with callback system
**API Endpoints Used:**
- POST `/ads/product/acquire/<key>` - Grant product after rewarded ad ✅
- GET `/api/v2/packs/{packId}/buy` - Check ad availability ✅
- GET `/api/v2/adsgram/reward?userId={userId}` - Adsgram reward callback ✅
**Files Created/Updated:**
- `lib/presentation/widgets/ads_reward_button.dart` ✅ (NEW)
- `lib/domain/config/api_config_v2.dart` ✅ (ads config)
- `lib/presentation/pages/pack_details/pack_details_page.dart` ✅ (integration)
- `pubspec.yaml` ✅ (adsgram dependency)
- `test/presentation/widgets/ads_reward_button_test.dart` ✅ (NEW)
---
### BI-3: Subscription Management
**Priority:** MEDIUM
**Status:** 🟡 Partial (SubscriptionService exists)
**Estimated Time:** 4-6 hours
**Description:** Complete subscription purchase and management
**Features Needed:**
- [ ] Subscription page UI
- [ ] View available subscription plans
- [ ] Purchase subscription
- [ ] Cancel subscription
- [ ] Show subscription status on ProfilePage
**API Endpoints:**
- GET `/subscription/page` - Get subscription info ✅ (implemented)
- POST `/subscription/add` - Purchase subscription ✅ (implemented)
- POST `/subscription/delete/<id>` - Cancel subscription
**Files to Create:**
- `lib/presentation/pages/subscription/subscription_page.dart`
- Update `subscription_service.dart` with cancel method
- Add route to `app_router.dart`
---
### BI-4: Vocabulary/Review Page
**Priority:** LOW
**Status:** ⬜ Not Started
**Estimated Time:** 6-8 hours
**Description:** Create vocabulary page to review all learned words across packs
**Features Needed:**
- [ ] VocabularyPage in bottom navigation
- [ ] Display all learned cards
- [ ] Filter by pack, language
- [ ] Search functionality
- [ ] Review cards
- [ ] Export vocabulary
**API Endpoints:**
- GET `/cards` - Fetch all cards
- GET `/user/data` - Get user's learning progress
**Files to Create:**
- `lib/presentation/pages/vocabulary/vocabulary_page.dart`
- `lib/domain/services/vocabulary_service.dart`
- `lib/domain/state/vocabulary_state_manager.dart`
- `lib/di/user_scope/modules/vocabulary_module.dart`
---
### BI-5: Promocode Functionality
**Priority:** LOW
**Status:** 🟡 Partial (Service migrated; awaiting UI)
**Estimated Time:** 3-4 hours
**Description:** UI for entering and applying promocodes
**Features Needed:**
- [ ] Promocode input field on ProfilePage or PurchasePage
- [ ] Apply promocode
- [ ] Show promocode benefits
- [ ] Validate promocode
**API Endpoints:**
- POST `/user/promocode` - Apply promocode ✅ (implemented)
- GET `/promocode/list` - List available promocodes ✅ (implemented)
**Files to Create:**
- `lib/presentation/widgets/promocode_input.dart`
- Update `promocode_service.dart` UI integration
---
### BI-6: Settings Page
**Priority:** LOW
**Status:** ⬜ Not Started
**Estimated Time:** 2-3 hours
**Description:** Separate settings page (currently settings are in ProfilePage)
**Features Needed:**
- [ ] Separate SettingsPage
- [ ] Theme toggle
- [ ] Language selection
- [ ] Sound effects toggle
- [ ] Notifications settings
- [ ] Account settings
**API Endpoints:**
- POST `/user/settings` - Update user settings
**Files to Create:**
- `lib/presentation/pages/settings/settings_page.dart`
- `lib/domain/state/settings_state_manager.dart`
---
### BI-7: Card Images Display ✅ COMPLETE
**Priority:** HIGH
**Status:** ✅ Complete
**Estimated Time:** 0 hours (already implemented)
**Description:** Display card images in PackDetailsPage and CardFlipper
**Features Needed:**
- [x] Fetch card images from backend (using Image.network with ApiConfig.getCardImageUrl)
- [x] Display in card list (PackDetailsPage._buildCardImage)
- [x] Display in card viewer (CardViewer._buildImage)
- [x] Display in card flipper (CardFlipper._buildImage)
**Notes:** Card images are already fully implemented using Image.network. Flutter handles caching automatically. No additional work needed.
---
### BI-8: Card Flipper Responsive Layout ✅ COMPLETE
**Priority:** MEDIUM
**Status:** ✅ Complete
**Estimated Time:** 2 hours
**Description:** Align web CardFlipper experience with mobile adaptive behavior by introducing responsive layouts while preserving existing state and animations.
**Features Delivered:**
- [x] Breakpoint resolver (compact / medium / expanded) via `LayoutBuilder`
- [x] Adaptive card sizing that respects viewport height and width
- [x] Responsive progress indicator and control clusters per breakpoint
- [x] Optional `stateManagerOverride` parameter for isolated widget testing
- [x] Widget tests covering compact, tablet, wide desktop, and tall desktop scenarios
**Notes:** No backend changes required. Verify new widget tests in `card_flipper_responsive_test.dart` during CI.
---
### BI-9: Card Viewer Study Flow ✅ COMPLETE
**Priority:** MEDIUM
**Status:** ✅ Complete
**Estimated Time:** 2 hours
**Description:** Launch fullscreen study mode directly from pack card taps, mirroring mobile UX without redundant controls.
**Features Delivered:**
- [x] Removed dedicated “Изучение” CTA from pack controls
- [x] Routed taps through `CardViewer` with ordered card lists (shuffle + favorites aware)
- [x] Started study at tapped card index with consistent navigation
- [x] Added widget tests covering initial index, swiping order, and flip interaction
**Notes:** Learning progress marking remains handled externally via `_markCardLearned`. Future enhancements can add per-card callbacks if needed.
---
### BI-10: Pack Details Shuffle Animation ✅ COMPLETE
**Priority:** LOW
**Status:** ✅ Complete
**Estimated Time:** 1 hour
**Description:** Make pack card shuffling feel responsive and delightful with animated transitions and control feedback.
**Features Delivered:**
- [x] Added reusable `ShuffleAnimatedSwitcher` for fade + scale transitions across grid/list shuffles
- [x] Highlighted shuffle control with active state styling and `AnimatedRotation` feedback
- [x] Animated card reordering with movement-aware wrappers plus widget/unit coverage
**Notes:** Animation is triggered whenever shuffle/favorites state changes via `_shuffleAnimationKey`. Scroll position resets intentionally to showcase rearranged cards.
---
## 🟢 Quality & Testing Tasks
### QT-1: Increase Test Coverage
**Priority:** MEDIUM
**Status:** 🔴 In Progress
**Progress:** ~70% coverage
**Areas Needing Tests:**
- [ ] pack_progress_service_test.dart
- [ ] promocode_service_test.dart (partial)
- [ ] subscription_service_test.dart (partial)
- [ ] card_flipper_service_test.dart
- [ ] All new pages
---
### QT-2: Fix Linter Issues
**Priority:** LOW
**Status:** ⬜ Not Started
**Action:** Run `flutter analyze` and fix all warnings
---
### QT-3: Integration Tests
**Priority:** LOW
**Status:** ⬜ Not Started
**Tests Needed:**
- [ ] Full auth flow
- [ ] Pack browsing and purchase
- [ ] Test taking flow
- [ ] Card learning flow
---
## 🚫 Blocked/Deferred Tasks
### BD-1: Telegram Authentication ✅ COMPLETE
**Priority:** MEDIUM
**Status:** ✅ Complete
**Completion Date:** November 8, 2025
**Outcome:** Web-initiated Telegram login bridge with 5-minute codes, bot claims, and improved web UI.
**Highlights:**
- Implemented backend `/auth/telegram/web-code`, `/claim-code`, and `/code-status/{code}` endpoints
- Updated Telegram bot to accept `login_<code>` payloads and keep `/code` fallback
- Added web login UI for code generation, bot deep-link, status polling, and auto-login
- Created unit tests for auth service helpers and code status parsing
---
### UI-1: PackTip Support Implementation ✅ COMPLETE
**Priority:** MEDIUM
**Status:** ✅ Complete
**Estimated Time:** 3 hours
**Actual Time:** 5 hours
**Description:** Add support for CardPackPreviewDto.tip field to display small icons or badges in corners or right side of pack cards, adapting PackTip functionality from mobile app to web version for both horizontal and vertical card layouts.
**Completed Tasks:**
- ✅ Created PackTipExt extension for PackTip.build() method
- ✅ Implemented support for all PackTipType variants (asset, base64, text, unknown)
- ✅ Added _buildPackTip() method to PackCard widget (horizontal layout)
- ✅ Added _buildPackTip() method to PackCardVertical widget (vertical layout)
- ✅ Implemented support for all PackTipPosition values (topRight, bottomRight, fullRight)
- ✅ Adapted fullRight positioning: right side for horizontal, bottom banner for vertical cards
- ✅ Refactored both card layouts to use Stack for tip overlays
- ✅ Added proper theming and error handling
- ✅ Verified build success and code quality
**Files Created/Modified:**
- `lib/utils/pack_tip_extension.dart` - PackTipExt extension
- `lib/presentation/widgets/pack_card.dart` - PackTip integration for horizontal cards
- `lib/presentation/widgets/pack_card_vertical.dart` - PackTip integration for vertical cards
**Technical Details:**
- Extension pattern for clean PackTip rendering
- Stack-based overlay system for tip positioning on both card types
- Adaptive positioning logic for horizontal vs vertical layouts
- Full compatibility with mobile PackTip system
- Type-safe implementation with proper error handling
**Next Steps:**
- Test with real backend PackTip data
- Monitor performance with multiple tips
- Consider animation enhancements
---
### BD-2: API v2 Implementation 🔄 IN PROGRESS
**Priority:** HIGH
**Status:** 🟡 In Progress
**Estimated Time:** 34-46 hours for core work
**Description:** Implement API v2 with OAuth2/JWT, RESTful patterns, and versioning
**Current Status:**
- ✅ Backend: AuthApiV2, JwtService, authorizeV2 middleware created
- ✅ Web: ApiConfigV2, HttpRepositoryV2 created
- ✅ AuthService migrated to use v2
- ⚠️ Backend: JWT crypto needs proper implementation
- ⚠️ Backend: Remaining v2 endpoints need implementation
- ⚠️ Web: Remaining services need migration to v2
**See:** `FUTURE_TASKS_PLAN.md` for detailed breakdown
---
## 📊 Progress Summary
**Total Tasks:** 18
**Completed:** 1
**In Progress:** 2
**Not Started:** 13
**Blocked/Deferred:** 2
**Priority Breakdown:**
- 🔴 HIGH: 5 tasks
- 🟡 MEDIUM: 7 tasks
- 🟢 LOW: 5 tasks
---
## 🎯 Recommended Next Steps (See FUTURE_TASKS_PLAN.md for details)
### Immediate Priority (Phase 1 - Backend v2)
1. **Fix JWT Service** - Use proper crypto library for HMAC-SHA256
2. **Complete Auth API v2** - Test and verify Google OAuth flow
3. **Implement Packs API v2** - Complete all pack endpoints
4. **Implement Tests API v2** - Complete test endpoints
5. **Implement remaining v2 APIs** - Games, Purchases, Subscriptions, Promocodes
### Next Priority (Phase 2 - Web Migration)
1. **Complete HttpRepositoryV2** - Add all missing methods
2. **Migrate PackManager** - Update to use v2
3. **Migrate remaining services** - GamesManager, TestManager, etc.
4. **Remove v1 dependencies** - Clean up deprecated code
### After Migration (Phase 3 - Features)
1. **Pack Purchase Flow** - Implement purchase UI and flow
2. **Subscription Management** - Complete subscription UI
3. **Promocode UI** - Add promocode input and application
**For complete detailed plan, see:** `FUTURE_TASKS_PLAN.md`
---
**Note:** Tasks are prioritized based on:
- User impact
- Technical dependencies
- Development effort
- Backend availability

View file

@ -1,379 +0,0 @@
# Tasks for mnemo_cards_web_v2
## Status: API v2 Implementation Phase
**Last Updated:** January 2025
**Current Phase:** Phase 1.6 Complete - API v2 Backend Implementation
---
## 🎯 Phase 1: Backend API v2 Implementation
### Task 1.7: Implement Subscriptions API v2 ⬜ PENDING
**Priority:** HIGH
**Estimated Time:** 4-6 hours
**Status:** 0% complete
### Description
Complete subscription management endpoints with purchase, status checking, and cancellation functionality.
### Implementation Steps
1. ⬜ Create SubscriptionsApiV2 with endpoints:
- GET `/api/v2/subscriptions/plans` - Get available subscription plans
- POST `/api/v2/subscriptions/purchase` - Purchase subscription
- GET `/api/v2/subscriptions/status` - Check subscription status
- POST `/api/v2/subscriptions/cancel` - Cancel subscription
2. ⬜ Implement subscription plan models and DTOs
3. ⬜ Add subscription validation and business logic
4. ⬜ Write comprehensive unit tests (15+ tests)
5. ⬜ Write integration tests for subscription flow
### Acceptance Criteria
- [ ] All subscription endpoints implemented and tested
- [ ] Subscription plans can be fetched
- [ ] Subscription purchase flow works
- [ ] Subscription status checking works
- [ ] Subscription cancellation works
- [ ] Comprehensive test coverage (15+ tests)
---
### Task 1.8: Implement Promocodes API v2 ⬜ PENDING
**Priority:** MEDIUM
**Estimated Time:** 3-4 hours
**Status:** 0% complete
### Description
Complete promocode validation, application, and listing endpoints.
### Implementation Steps
1. ⬜ Create PromocodesApiV2 with endpoints:
- GET `/api/v2/promocodes` - List available promocodes
- POST `/api/v2/promocodes/apply` - Apply promocode
- GET `/api/v2/promocodes/{code}/validate` - Validate promocode
2. ⬜ Implement promocode models and validation logic
3. ⬜ Add promocode application and discount calculation
4. ⬜ Write comprehensive unit tests (10+ tests)
5. ⬜ Write integration tests for promocode flow
### Acceptance Criteria
- [ ] All promocode endpoints implemented and tested
- [ ] Promocode validation works correctly
- [ ] Promocode application works correctly
- [ ] Discount calculation is accurate
- [ ] Comprehensive test coverage (10+ tests)
---
## 🎯 Phase 2: Web App Migration to API v2
### Task 2.1: Complete Web App Migration ⬜ PENDING
**Priority:** HIGH
**Estimated Time:** 8-10 hours
**Status:** 60% complete
### Description
Migrate all remaining services from v1 to v2 API (GamesManager, TestManager, PurchaseService, etc.).
### Implementation Steps
1. [x] Migrate GamesManager to use HttpRepositoryV2
2. [x] Migrate TestManager to use HttpRepositoryV2
3. ⬜ Migrate PurchaseService to use HttpRepositoryV2
4. [x] Migrate SubscriptionService to use HttpRepositoryV2
5. [x] Migrate PromocodeService to use HttpRepositoryV2
6. ⬜ Update all API calls to use v2 endpoints
7. [x] Remove deprecated v1 dependencies
8. [x] Update all tests to use v2 API
9. ⬜ Verify all functionality works with v2
### Acceptance Criteria
- [ ] All services migrated to API v2
- [ ] All API calls use v2 endpoints
- [ ] No v1 dependencies remain
- [ ] All tests pass with v2 API
- [ ] All functionality verified working
---
## 🎯 Phase 3: Feature Implementation
### Task 3.1: Implement Pack Purchase Flow ⬜ PENDING
**Priority:** HIGH
**Estimated Time:** 6-8 hours
**Status:** 0% complete
### Description
Create purchase UI, payment integration with YooMoney, and purchase confirmation flow.
### Implementation Steps
1. ⬜ Create PurchaseService with v2 API integration
2. ⬜ Create PurchaseModule in UserScope
3. ⬜ Create PurchasePage UI with:
- Pack details and pricing
- Payment method selection
- Payment form (YooMoney integration)
- Purchase confirmation
4. ⬜ Add "Buy Pack" button to PackDetailsPage
5. ⬜ Implement payment status checking
6. ⬜ Add purchase success/failure handling
7. ⬜ Write comprehensive unit tests (15+ tests)
8. ⬜ Write integration tests for purchase flow
### Acceptance Criteria
- [ ] Purchase UI is complete and functional
- [ ] YooMoney payment integration works
- [ ] Purchase confirmation flow works
- [ ] Payment status checking works
- [ ] Purchase success/failure handling works
- [ ] Comprehensive test coverage (15+ tests)
---
### Task 3.2: Complete Subscription Management UI ⬜ PENDING
**Priority:** MEDIUM
**Estimated Time:** 4-6 hours
**Status:** 0% complete
### Description
Create subscription page with plans, purchase flow, and status management.
### Implementation Steps
1. ⬜ Create SubscriptionPage UI with:
- Available subscription plans display
- Plan comparison and features
- Purchase flow for subscriptions
- Current subscription status
- Subscription management (cancel/renew)
2. ⬜ Add subscription status to ProfilePage
3. ⬜ Implement subscription purchase flow
4. ⬜ Add subscription cancellation flow
5. ⬜ Write comprehensive unit tests (10+ tests)
6. ⬜ Write integration tests for subscription flow
### Acceptance Criteria
- [ ] Subscription page UI is complete
- [ ] Subscription plans display correctly
- [ ] Subscription purchase flow works
- [ ] Subscription status management works
- [ ] Comprehensive test coverage (10+ tests)
---
### Task 3.3: Implement Promocode UI ⬜ PENDING
**Priority:** MEDIUM
**Estimated Time:** 3-4 hours
**Status:** 0% complete
### Description
Add promocode input field, validation, and application functionality.
### Implementation Steps
1. ⬜ Create PromocodeInput widget
2. ⬜ Add promocode input to PurchasePage and SubscriptionPage
3. ⬜ Implement promocode validation UI
4. ⬜ Add promocode application and discount display
5. ⬜ Create promocode success/failure feedback
6. ⬜ Write comprehensive unit tests (8+ tests)
7. ⬜ Write integration tests for promocode flow
### Acceptance Criteria
- [ ] Promocode input widget is complete
- [ ] Promocode validation works
- [ ] Promocode application works
- [ ] Discount display works correctly
- [ ] Comprehensive test coverage (8+ tests)
---
### Task 3.4: Create Vocabulary/Review Page ⬜ PENDING
**Priority:** LOW
**Estimated Time:** 6-8 hours
**Status:** 0% complete
### Description
Display all learned words across packs with filtering and search functionality.
### Implementation Steps
1. ⬜ Create VocabularyService for fetching learned words
2. ⬜ Create VocabularyStateManager for state management
3. ⬜ Create VocabularyModule in UserScope
4. ⬜ Create VocabularyPage UI with:
- List of all learned words
- Filter by pack, language
- Search functionality
- Word review interface
- Export vocabulary option
5. ⬜ Add VocabularyPage to bottom navigation
6. ⬜ Write comprehensive unit tests (12+ tests)
7. ⬜ Write integration tests for vocabulary flow
### Acceptance Criteria
- [ ] Vocabulary page UI is complete
- [ ] Word filtering works correctly
- [ ] Search functionality works
- [ ] Word review interface works
- [ ] Export functionality works
- [ ] Comprehensive test coverage (12+ tests)
---
### Task 3.5: Implement Ads Reward Flow 🟡 IN PROGRESS
**Priority:** HIGH
**Estimated Time:** 6-8 hours
**Status:** 40% complete (service layer, scope integration, and unit tests ready)
### Description
Bring the mobile "watch ad to unlock pack/product" flow to the web client using Adsgram rewarded ads and the existing `/ads` backend endpoints.
### Implementation Steps
1. [x] Expose ads reward endpoints in `HttpRepositoryV2` (acquire product, optional reward ping)
2. [x] Create `AdsRewardService` coordinating ad session, backend calls, and user state updates
3. [x] Add `AdsRewardModule` to `UserScope` with yx_state manager for ad CTA/status
4. ⬜ Integrate web Adsgram SDK and wrap in Flutter widget/service with proper lifecycle
5. ⬜ Update pack purchase UI to show "Unlock by watching ad" CTA when `adsKey` present
6. ⬜ Refresh packs/user purchases after reward success and handle errors gracefully
7. [x] Write unit tests for service/state manager and widget logic (reward success, failure, retries)
### Acceptance Criteria
- [ ] Ads CTA appears for eligible packs/products with valid `adsKey`
- [ ] Rewarded ad plays to completion using web SDK with proper loading state
- [ ] Successful reward calls `/ads/product/acquire/<key>` and unlocks the product
- [ ] Error states show helpful messages and allow retry
- [ ] Comprehensive unit tests (10+ tests) cover service, state, and widget logic
- [ ] Analytics events emitted for ad impressions, completions, failures
---
### Task 3.6: Create Dedicated Settings Page ⬜ PENDING
**Priority:** LOW
**Estimated Time:** 2-3 hours
**Status:** 0% complete
### Description
Separate settings from profile with theme, language, and notification options.
### Implementation Steps
1. ⬜ Create SettingsPage UI with:
- Theme toggle (light/dark)
- Language selection
- Sound effects toggle
- Notifications settings
- Account settings
2. ⬜ Create SettingsStateManager for settings state
3. ⬜ Add SettingsPage to navigation
4. ⬜ Move settings from ProfilePage to SettingsPage
5. ⬜ Write comprehensive unit tests (6+ tests)
### Acceptance Criteria
- [ ] Settings page UI is complete
- [ ] All settings options work correctly
- [ ] Settings are persisted properly
- [ ] Comprehensive test coverage (6+ tests)
---
## 🎯 Phase 4: Quality & Testing
### Task 4.1: Fix Test Failures ⬜ PENDING
**Priority:** MEDIUM
**Estimated Time:** 2-3 hours
**Status:** 0% complete
### Description
Resolve 24 failing tests (mostly empty test files) to ensure all tests pass.
### Implementation Steps
1. ⬜ Fix test_page_test.dart empty file
2. ⬜ Investigate and fix other test failures
3. ⬜ Ensure all tests compile and run
4. ⬜ Verify all tests pass
### Acceptance Criteria
- [ ] All 24 failing tests are fixed
- [ ] All tests pass successfully
- [ ] No compilation errors in tests
---
### Task 4.2: Increase Test Coverage ⬜ PENDING
**Priority:** MEDIUM
**Estimated Time:** 4-6 hours
**Status:** 0% complete
### Description
Add comprehensive tests for all new services and UI components.
### Implementation Steps
1. ⬜ Add tests for all new API v2 services
2. ⬜ Add tests for all new UI components
3. ⬜ Add tests for all new state managers
4. ⬜ Add tests for all new modules
5. ⬜ Ensure test coverage is above 90%
### Acceptance Criteria
- [ ] Test coverage above 90%
- [ ] All new services have comprehensive tests
- [ ] All new UI components have tests
- [ ] All new state managers have tests
---
### Task 4.3: Fix Linter Issues ⬜ PENDING
**Priority:** LOW
**Estimated Time:** 1-2 hours
**Status:** 0% complete
### Description
Run flutter analyze and resolve all warnings and code quality issues.
### Implementation Steps
1. ⬜ Run `flutter analyze` to identify issues
2. ⬜ Fix all linter warnings
3. ⬜ Fix all code quality issues
4. ⬜ Ensure clean analysis report
### Acceptance Criteria
- [ ] No linter warnings
- [ ] No code quality issues
- [ ] Clean analysis report
---
### Task 4.4: Write Integration Tests ⬜ PENDING
**Priority:** LOW
**Estimated Time:** 6-8 hours
**Status:** 0% complete
### Description
Create end-to-end tests for auth flow, pack browsing, test taking, and card learning.
### Implementation Steps
1. ⬜ Create integration test for auth flow
2. ⬜ Create integration test for pack browsing
3. ⬜ Create integration test for test taking
4. ⬜ Create integration test for card learning
5. ⬜ Create integration test for purchase flow
6. ⬜ Create integration test for subscription flow
### Acceptance Criteria
- [ ] All major user flows have integration tests
- [ ] Integration tests cover critical paths
- [ ] Integration tests are reliable and maintainable
---
## 📊 Summary
**Total Tasks:** 13
**Completed:** 0
**In Progress:** 0
**Pending:** 13
**Priority Breakdown:**
- 🔴 HIGH: 5 tasks (API v2 completion, web migration, pack purchase, ads reward)
- 🟡 MEDIUM: 5 tasks (subscription UI, promocode UI, test fixes, coverage)
- 🟢 LOW: 3 tasks (vocabulary page, settings page, linter fixes)
**Current Focus:** Phase 1.7 - Implement Subscriptions API v2
**Next Task:** Phase 1.8 - Implement Promocodes API v2
**Note:** Tasks are marked as complete only when fully implemented, tested, and production-ready (no stubs or TODOs).

View file

@ -1,291 +0,0 @@
# Workflow State - mnemo_cards_web_v2
**Last Updated:** 2025-11-08
---
## PLAN - 🔥 STATISTICS SYSTEM UPGRADE
**Phase:** Full Statistics Implementation
**Goal:** Расширить систему сбора и отображения статистики пользователя для создания детализированной страницы профиля с красивым UI и настройками приложения.
**Plan Documents:**
- Main Plan: `STATISTICS_UPGRADE_PLAN.md` (111-144 hours total)
- Backend Tasks: `../mnemo_cards_backend/STATISTICS_TASKS.md` (35-47 hours)
- Frontend Tasks: `STATISTICS_TASKS.md` (93-119 hours)
**Status:** 🟡 PLANNING COMPLETE - READY TO START
---
## CURRENT STATUS
### Completed:
- ✅ Pack cover images
- ✅ Tests functionality
- ✅ Telegram/js_util compilation
- ✅ Card images (fully implemented)
- ✅ Card flipping (fully implemented)
- ✅ API v2 foundation (Auth, Packs, Tests, Games, Purchases)
- ✅ Statistics upgrade planning (detailed plan created)
### In Progress:
- 🟡 Statistics system implementation (planning complete, ready to code)
### Not Started:
- ⬜ Pack purchase flow
- ⬜ Subscription management
- ⬜ Vocabulary/Review page
- ⬜ Promocode UI
### Known Issues:
- 🔴 24 test failures (177 passing) - low priority, mostly empty test files
---
## NEXT_ACTIONS
### Phase 1: HttpRepositoryV2 Statistics Methods ✅ COMPLETED (4 hours)
1. ✅ Add API endpoint constants to ApiConfigV2 (/statistics/detailed, /packs, /words, /timeline, /sessions, /achievements)
2. ✅ Implement 6 new repository methods in HttpRepositoryV2 with proper error handling
3. ✅ Create response DTOs (WordsStatisticsResponse, TimelineStatisticsResponse, StudySessionResponse)
4. ✅ Add query parameter support (pagination, filtering, sorting, date ranges)
5. ✅ Write smoke tests for all new methods (6 tests, all passing)
### Phase 2: Statistics Service & State Manager ✅ COMPLETED (3 hours)
6. ✅ Create StatisticsService with HttpRepositoryV2 integration
7. ✅ Implement StatisticsStateManager with yx_state (loading, loaded, error states)
8. ✅ Add StatisticsModule to UserScope DI container
9. ✅ Create comprehensive state management with computed properties
10. ✅ Add error handling and state refresh capabilities
11. ✅ Write unit tests (9 tests passing for StatisticsService, state manager tests created)
### Phase 3: Statistics UI Widgets ✅ COMPLETED
12. ✅ Create main StatisticsPage with tabbed interface (Overview, Words, Activity, Achievements, Packs)
13. ✅ Create StatisticsOverviewWidget - dashboard with key metrics and recent achievements
14. ✅ Create WordsStatisticsWidget - word analytics with pagination, filtering, sorting
15. ✅ Create TimelineWidget - study activity charts and period filtering
16. ✅ Create AchievementsWidget - progress tracking and achievement unlocks
17. ✅ Create PackProgressWidget - individual pack completion tracking
18. ✅ Add StatisticsPage to app navigation and bottom tab bar
19. ✅ Implement responsive Material Design UI with proper theming
20. ✅ Add loading states, error handling, and refresh capabilities
### Phase 3: Frontend Services (THEN)
11. ⬜ Update HttpRepositoryV2 with statistics methods
12. ⬜ Rewrite StatisticsService with real logic
13. ⬜ Create StatisticsStateManager and related managers
14. ⬜ Add to DI modules
### Phase 4: Frontend UI (AFTER SERVICES)
15. ⬜ Create base statistics widgets
16. ⬜ Redesign ProfilePage
17. ⬜ Create Settings Page
18. ⬜ Create statistics detail pages
19. ⬜ Add animations and polish
---
## ASSUMPTIONS
### Technical:
1. Backend Isar database can be extended without breaking existing data
2. API v2 endpoints are preferred over v1 for new features
3. mnemo_cards_common package is shared between backend and frontend
4. Statistics should be calculated server-side and cached
5. Session tracking will use middleware on backend
6. Achievements will be checked asynchronously after user actions
### Frontend:
7. fl_chart library will be used for all charts
8. Frontend will cache statistics locally for performance
9. Settings will be stored both locally (SharedPreferences) and on server
10. Mobile app (../mnemo_cards) can be referenced for feature ideas but not architecture
### Design:
11. Animations should be smooth but not distracting
12. Loading states should use skeleton/shimmer
13. All pages should be responsive (mobile/tablet/desktop)
14. Achievement unlocks should have celebration animations
---
## PROGRESS_LOG
### 2025-11-08: Statistics Upgrade - Planning Phase Complete ✅
**Analysis:**
- Reviewed current backend statistics (UserDataModel, WordStatisticsDto, TestStatisticsDto)
- Reviewed frontend ProfilePage (mocked statistics, basic UI)
- Identified gaps: no pack progress, no achievements, no session tracking, no difficulty scoring
**Planning:**
- Created STATISTICS_UPGRADE_PLAN.md with 10 sections, 6 phases
- Created backend task breakdown (35-47 hours, 5 phases)
- Created frontend task breakdown (93-119 hours, 8 phases)
- Updated TODO.md with STAT-1 feature entry
- Prioritized tasks into High/Medium/Low
**Key Features Planned:**
1. Extended statistics: streaks, study time, accuracy, pack progress
2. Detailed word statistics with difficulty scoring
3. Achievement system with 8+ achievement types
4. Study session tracking
5. Beautiful profile page redesign
6. Statistics detail pages (words, packs, achievements)
7. Enhanced settings page (appearance, learning, privacy, account)
8. Timeline charts and activity heatmaps
9. Animations (counters, confetti, shimmer)
10. Comprehensive testing
**Estimates:**
- Backend: 35-47 hours
- Frontend: 93-119 hours
- Total: 111-144 hours
**Next Step:** Start Phase 1.1 - Create new DTOs in mnemo_cards_common
---
### Previous Progress:
#### 2025-11-08: Pack Details UX Polish
- ✅ Added shuffle animation with AnimatedSwitcher
- ✅ Rotating control feedback
- ✅ Card movement wrappers
- ✅ Widget and unit tests
- ✅ CardViewer responsive UI
- ✅ CardFlipper responsive layout refactor
#### 2025-11-08: Ads Reward Flow
- ✅ Implemented AdsRewardService
- ✅ Created state manager
- ✅ Added user scope module
- ✅ Unit tests
#### 2025-10-29: API v2 - Authentication
- ✅ Fixed JWT Service with proper HMAC-SHA256
- ✅ Created RefreshTokenModel for token storage
- ✅ Implemented token blacklisting
- ✅ 15 JwtService tests passing
- ✅ 12 AuthApiV2 integration tests passing
#### 2025-10-29: API v2 - Packs
- ✅ Implemented all 5 Packs API v2 endpoints
- ✅ Pagination, search, filtering
- ✅ Purchase status check
- ✅ Card image endpoint
- ✅ 17 tests passing
#### 2025-10-29: API v2 - Tests
- ✅ Implemented all 3 Tests API v2 endpoints
- ✅ Submit results, get history
- ✅ Pagination for history
- ✅ 17 tests passing
#### 2025-10-29: API v2 - Games
- ✅ Implemented all 2 Games API v2 endpoints
- ✅ Get games list and assets
- ✅ 6 tests passing
#### 2025-10-29: API v2 - Purchases
- ✅ Implemented all 4 Purchases API v2 endpoints
- ✅ Pack purchase flow
- ✅ Payment creation and verification
- ✅ 13 tests passing
---
## OPEN_ISSUES
### Statistics Feature (New):
1. ⬜ Define achievement icons/images (need design)
2. ⬜ Choose color scheme for activity heatmaps
3. ⬜ Determine difficulty scoring algorithm for words
4. ⬜ Plan database migration strategy for new Isar models
5. ⬜ Consider performance impact of streak calculations
6. ⬜ Handle timezone issues for daily streaks
7. ⬜ Define session timeout duration (15 min? 30 min?)
8. ⬜ Plan caching strategy for statistics (Redis? In-memory?)
9. ⬜ Set pagination limits for words/packs lists
10. ⬜ Test with large datasets (1000+ words)
11. ⬜ Consider rate limiting for statistics API endpoints
12. ⬜ Plan GDPR compliance (data export/deletion)
### Existing Issues:
13. 🔴 24 test failures (177 passing) - low priority, mostly empty test files
14. ⬜ Pack purchase flow incomplete (need PurchaseService & UI)
15. ⬜ Subscription management incomplete
16. ⬜ Promocode UI not implemented
---
## RECENT ACCOMPLISHMENTS
✅ **API v2 Backend (Complete):**
- Authentication (Google OAuth, JWT, refresh tokens)
- Packs (list, details, cards, images, tests)
- Tests (details, submit results, history)
- Games (list, assets)
- Purchases (create, verify payments)
✅ **Frontend Features:**
- Card images and flipping (fully working)
- Pack details with responsive UI
- Card viewer with study flow
- Shuffle animations
- Ads reward flow preparation
✅ **Planning:**
- Comprehensive statistics upgrade plan (111-144 hours)
- Detailed task breakdowns for backend and frontend
- Clear priorities and dependencies
---
## WORK STRATEGY
### Development Approach:
1. **Start Small:** Begin with backend models and DTOs
2. **Test Early:** Write tests alongside implementation
3. **Iterate:** Complete one phase before moving to next
4. **Verify:** Test endpoints and UI after each phase
5. **Document:** Update PROGRESS.md and TODO.md regularly
### Quality Gates:
- All new code has unit tests
- Integration tests for all API endpoints
- Widget tests for all new UI components
- Linter passes
- No critical bugs
### Communication:
- Update workflow_state.md after each work session
- Keep progress log concise (≤100 tokens per entry)
- Mark tasks complete in TODO.md
- Update PROGRESS.md with completed features
---
## FILES TO MAINTAIN
**Planning:**
- `STATISTICS_UPGRADE_PLAN.md` - Main feature plan
- `STATISTICS_TASKS.md` - Frontend task breakdown
- `../mnemo_cards_backend/STATISTICS_TASKS.md` - Backend tasks
**Tracking:**
- `TODO.md` - High-level task list
- `workflow_state.md` - This file (current state)
- `PROGRESS.md` - Completed work log
**Documentation:**
- `README.md` - Project overview
- Future: `STATISTICS_API.md` - API documentation
- Future: `STATISTICS_UI_GUIDE.md` - UI component guide
---
**Status:** Ready to begin implementation
**Next Action:** Create new DTOs in mnemo_cards_common
**Estimated Time for Next Phase:** 4-6 hours

View file

@ -1,14 +0,0 @@
Ты работаешь над веб приложением для изучения языков mnemo_cards_web_v2
Это веб приложение для изучения языков.
Следуй правилам rules/auto_work.mdc и write-tests.mdc
Бэкенд описан в пакете mnemo_cards_backend, там же есть схема api. Ты можешь вносить правки в бекэнд.
Веб приложение является портом аналогичного мобильного приложение на веб. Код исходного приложения можно посмотреть в mnemo_cards.
Твоя основная задача - подружить backend с web app.
Создай новый список tasks.md с задачами которые ты будешь делать.
Задача считается выполненой только если она реализована на 100% и готова к использованию (не содержит заглушек).
Если задачу не удается сделать на 100% как бы ты не пытался - переходи к следующей.
Вот неполный список задач:
- Сделать авторизацию через телеграм используя бота mnemo_cards_telegram_bot (авторизация должна работать с сайта а не через mini app. При этом в боте должен присылаться код который надо ввести)
- Сделать api v2 для веб приложения
- Сделать чтобы отображались изображения карточек в паках.
- Сделать чтобы работали тесты в паках.