A multi-tenant trivia application for corporate training and team engagement.
π New to the project? See FILE_LOCATIONS.md for a complete guide to finding files in the repository.
Get the entire application running with a single command:
# Clone the repository
git clone <repository-url>
cd trivia-app
# Start all services (PostgreSQL, Redis, Backend, Frontend)
docker compose upAccess the application:
- π Frontend: http://localhost:5173
- π Backend API: http://localhost:8000
- π API Documentation: http://localhost:8000/docs
- π©Ί Health Check: http://localhost:8000/health
Features:
- β Automatic database migrations
- β Hot reload for both backend and frontend
- β Full development environment in < 2 minutes
- β No manual setup required
To stop all services:
docker compose downπ Need more Docker info? See the comprehensive Docker Development Guide for commands, workflows, and troubleshooting.
trivia-app/
βββ backend/ # FastAPI backend
β βββ api/ # API endpoints
β βββ core/ # Core configuration
β βββ db/ # Database CRUD operations
β βββ models/ # SQLAlchemy ORM models
β βββ schemas/ # Pydantic schemas
β βββ services/ # Business logic
β βββ websocket/ # WebSocket handlers
β βββ integrations/ # External integrations
β βββ tasks/ # Background tasks
β βββ alembic/ # Database migrations
β βββ main.py # Application entry point
βββ frontend/ # React frontend
β βββ src/
β βββ components/ # React components
β βββ hooks/ # Custom hooks
β βββ store/ # Zustand state management
β βββ services/ # API services
β βββ pages/ # Page components
β βββ types/ # TypeScript types
β βββ styles/ # CSS/styles
β βββ lib/ # Utilities
βββ docker-compose.yml # Local development services
- Framework: FastAPI 0.104+
- Database: PostgreSQL 13+
- Cache/PubSub: Redis 7+
- ORM: SQLAlchemy 2.0+
- Migrations: Alembic
- Authentication: JWT with refresh tokens
- Real-Time: WebSocket infrastructure for live updates
- Testing: pytest with 80%+ coverage target
- Framework: React 18+
- Build Tool: Vite
- State Management: Zustand
- Server State: TanStack Query
- Styling: Tailwind CSS
- HTTP Client: Axios
- Testing: Vitest + React Testing Library
For Docker Setup (Recommended):
- Docker & Docker Compose
- Git
For Manual Setup:
- Python 3.11+
- Node.js 18+
- Docker & Docker Compose (for PostgreSQL 13+ and Redis 7+)
- Git
- OpenSSL (for JWT secret generation)
Fastest way to get started - runs everything in containers:
# 1. Clone the repository
git clone <repository-url>
cd trivia-app
# 2. Start all services
docker compose upThat's it! The application will:
- β Start PostgreSQL and Redis
- β Build backend and frontend containers
- β Run database migrations automatically
- β Start both services with hot reload enabled
Access the application at:
- Frontend: http://localhost:5173
- Backend: http://localhost:8000
- API Docs: http://localhost:8000/docs
Common Docker Commands:
# Start in background
docker compose up -d
# View logs
docker compose logs -f
# Stop all services
docker compose down
# Rebuild containers after dependency changes
docker compose up --build
# Stop and remove volumes (clean slate)
docker compose down -vIf you prefer to run services locally without Docker:
git clone <repository-url>
cd trivia-appdocker compose up -d postgres redisThis starts only PostgreSQL and Redis containers.
# Navigate to backend directory
cd backend
# Create virtual environment
# IMPORTANT: Use 'venv' as the directory name (not '.venv')
# This project standardizes on 'venv/' for consistency
python -m venv venv
# Activate virtual environment
# Windows:
venv\Scripts\activate
# macOS/Linux:
source venv/bin/activate
# Install dependencies
pip install -r requirements.txt
# Copy environment file and configure
cp ../.env.example .env
# IMPORTANT: Generate secure JWT secret
# Run this command and add the output to your .env file:
# openssl rand -hex 32
# Initialize database with Alembic
alembic upgrade head
# Run development server
python main.pyBackend will be available at: http://localhost:8000 API Documentation: http://localhost:8000/docs
# Navigate to frontend directory (from project root)
cd frontend
# Install dependencies
npm install
# Run development server
npm run devFrontend will be available at: http://localhost:5173
Backend:
cd backend
PYTHONPATH=.. pytest
PYTHONPATH=.. pytest --cov=backend --cov-report=html
# Run with PostgreSQL (matches CI environment)
# Start PostgreSQL service from project root, then set DATABASE_URL
cd ..
docker-compose up -d postgres
cd backend
DATABASE_URL=postgresql://trivia_user:trivia_pass@localhost:5432/trivia_db PYTHONPATH=.. pytest
# Run WebSocket integration tests
PYTHONPATH=.. pytest tests/integration/test_websocket.py -v
# Run tenant isolation tests
PYTHONPATH=.. pytest tests/integration/test_tenant_isolation.py -v
# Run all integration tests
PYTHONPATH=.. pytest tests/integration/ -vAlternatively, run from project root:
pytest backend/tests --cov=backend --cov-report=htmlNote: Tests use the database specified by the DATABASE_URL environment variable. To run tests against PostgreSQL (for example the instance started via docker-compose), set DATABASE_URL to the Postgres connection string; otherwise tests default to SQLite. CI sets DATABASE_URL to a PostgreSQL 13 instance to match production.
Frontend:
cd frontend
npm test
npm run test:coverageCreate a new migration:
cd backend
alembic revision --autogenerate -m "description"Apply migrations:
alembic upgrade headRollback migration:
alembic downgrade -1Backend:
ruff check .
black .Frontend:
npm run lintCurrent Sprint: Epic 1 - Platform Foundation & Authentication
- β Story 1.1: Project Initialization & Development Environment Setup (9/9 ACs met)
- β Story 1.2: Organization & User Data Models (9/9 ACs met)
- β Story 1.3: User Registration with Email (10/10 ACs met - backend with tests)
Recent Updates (PR #21 - Feb 2, 2026):
- β Comprehensive CI/CD workflows (Codacy, CodeQL, dependency review)
- β Authentication endpoints fully implemented with JWT
- β Comprehensive test suite (pytest with 80%+ coverage)
- β Code quality tooling (Codacy CLI, linting configurations)
- β BMAD agent framework integration (23 custom agents)
- β Complete documentation suite (README, CONTRIBUTING, architecture docs)
- β Multi-tenant middleware (organization scoping, security isolation)
Recent Updates (PR #29 - Feb 3, 2026):
- β
WebSocket Infrastructure implemented for real-time features
- Connection manager with session-based tracking
- JWT authentication for WebSocket connections
- Message broadcasting and session isolation
- Frontend WebSocket service with auto-reconnection
- 6 integration tests (100% pass rate)
- Complete documentation in
docs/websocket-infrastructure.md
Recent Updates (Feb 7, 2026):
- β
Consolidated CI/CD Pipeline (
.github/workflows/ci.yml)- Eliminated duplicate test runs (was running 2x per PR)
- Single workflow for backend and frontend tests
- PostgreSQL 13 service in CI environment (matches production)
- 50% reduction in PR feedback time
- β
Multi-Tenant Isolation Tests (
backend/tests/integration/test_tenant_isolation.py)- 130 tests passing with 96.29% coverage (exceeds 80% target)
- Comprehensive tenant boundary validation
- End-to-end API security testing
- β
Codacy Configuration Optimization
- 30-40% faster analysis (removed unused runtimes/tools)
- Proper path exclusions (node_modules, venv, build artifacts)
- CodeQL now analyzes Python and TypeScript (was GitHub Actions only)
Validation Report: See docs/validation/epic-1-validation-report.md
Quality Metrics (Updated Feb 7, 2026):
- Acceptance Criteria: 28/28 (100%)
- Implementation Quality: 96.3%
- Architecture Compliance: 92%
- Test Coverage: 96.29% (backend) - 130 tests passing
- CI Environment: PostgreSQL 13 (matches production)
- π Story 1.4: User Login with JWT Authentication (implementation complete, needs frontend integration)
- π Story 1.5: Session Management & Token Refresh (ready for development)
- Story 1.6: Multi-Tenant Access Control
- Story 1.7: User Profile Management
Critical (Must Address Before Feature Work):
CI/CD Optimization: Consolidate duplicate test runs (Codacy + CodeQL both run tests on every PR)β COMPLETED (Feb 7, 2026)Multi-Tenant Middleware: Implement organization scoping middleware for automatic data isolationβ COMPLETEDWebSocket Infrastructure: Real-time features not yet implemented (required for Epic 3)β COMPLETED (PR #29)PostgreSQL in CI: Test database uses SQLite in CI vs PostgreSQL in production (potential compatibility issues)β COMPLETED (Feb 7, 2026)
High Priority:
5. Frontend components not yet implemented (placeholders exist)
6. CodeQL only scans GitHub Actions files (needs Python/TypeScript configuration) β
COMPLETED (Feb 7, 2026)
Medium Priority: 7. Dependency updates available (FastAPI, Pydantic, React, Vite) 8. No seed data script for development organizations 9. Security headers middleware not implemented
See _bmad-output/implementation-artifacts/action-items-2026-02-02.md for complete action items and _bmad-output/implementation-artifacts/code-review-2026-02-02.md for detailed code review findings.
The project uses GitHub Actions for continuous integration and code quality. Current workflows:
CI Pipeline (.github/workflows/ci.yml) - PRIMARY WORKFLOW
- Triggers: Pull requests, pushes to main
- Purpose: Fast feedback on code changes with comprehensive testing
- What it does:
- Runs backend tests with pytest in PostgreSQL 13 environment
- Runs frontend tests (with graceful handling when tests not yet implemented)
- Enforces 80% code coverage threshold
- Uploads coverage to Codacy and GitHub
- Executes in ~3-5 minutes (50% faster than previous setup)
- Key Features:
- β Single test execution per PR (no duplication)
- β PostgreSQL 13 service matches production environment
- β Graceful secret handling for external contributors
Codacy Workflow (.github/workflows/codacy.yml)
- Triggers: Weekly schedule (Thursday 5:33 PM UTC), manual
- Purpose: Deep code quality analysis and security scanning
- What it does:
- Runs Codacy CLI security analysis
- Generates detailed quality reports
- Analyzes with optimized tool configuration (ESLint, Semgrep, Trivy)
- Optimization: 30-40% faster due to runtime/tool pruning (Node.js + Python only)
CodeQL Workflow (.github/workflows/codeql.yml)
- Triggers: Weekly schedule (Saturday 11:21 AM UTC), manual
- Purpose: Advanced security vulnerability scanning
- What it does:
- Analyzes Python, JavaScript/TypeScript code for security issues
- Uploads results to GitHub Security tab
- Detects SQL injection, XSS, authentication bypasses, etc.
- Recent Update: Now analyzes Python and TypeScript (was GitHub Actions only)
Security Scheduled (.github/workflows/security-scheduled.yml)
- Triggers: Weekly schedule, pushes to main
- Purpose: Scheduled security scans without impacting PR velocity
- What it does:
- Deep Codacy CLI analysis
- CodeQL security scanning
- Runs on schedule to avoid slowing down development
Other Workflows:
- Greetings: Welcomes new contributors on their first issue/PR
- Summary: AI-powered issue summarization
- Dependency Review (disabled): Planned for dependency vulnerability scanning
β Eliminated Duplicate Test Runs:
- Before: Tests ran 2x per PR (Codacy + CodeQL workflows)
- After: Single consolidated CI pipeline
- Impact: 50% reduction in PR feedback time
β PostgreSQL in CI:
- Before: SQLite in CI, PostgreSQL in production (compatibility risk)
- After: PostgreSQL 13 service in CI environment
- Impact: Better production parity, catches DB-specific issues
β Optimized Analysis Tools:
- Removed 3 unused language runtimes (Dart, Go, Java)
- Removed 4 unused analysis tools
- Result: 30-40% faster Codacy analysis
β Previously Identified Issues - NOW RESOLVED:
Duplicate test runsβ Fixed with consolidated CI pipelineNo frontend CIβ Frontend tests now run in ci.yml workflowSQLite vs PostgreSQL mismatchβ PostgreSQL 13 service addedCodeQL limited scopeβ Now analyzes Python and TypeScript
- Multi-tenancy: Row-level isolation via
organization_id - Authentication: JWT access tokens (15min) + refresh tokens (7 days)
- Real-time: WebSocket + Redis Pub/Sub (planned, not yet implemented)
- API Response Format:
- Success:
{data: {...}} - Error:
{error: {code, message}}
- Success:
- β Backend API with FastAPI
- β PostgreSQL database with SQLAlchemy ORM
- β JWT authentication with refresh tokens
- β Multi-tenant data models with organization scoping
- β Multi-tenant middleware with automatic filtering
- β Alembic migrations
- β pytest test infrastructure (96.29% coverage, 130 tests)
- β Comprehensive integration tests for tenant isolation
- β WebSocket infrastructure with connection manager
- β WebSocket JWT authentication and message broadcasting
- β Frontend WebSocket service with auto-reconnection
- β Consolidated CI/CD pipeline with PostgreSQL
- β³ Redis Pub/Sub (infrastructure ready, not used yet)
- β³ Frontend React components (structure exists, components not implemented)
See .env.example for required environment variables.
- Generate a secure JWT secret:
openssl rand -hex 32
- Add the generated secret to your
.envfile:SECRET_KEY=your-generated-secret-here - Never commit
.envto version control
Once the backend is running, access interactive API documentation:
- Swagger UI: http://localhost:8000/docs
- ReDoc: http://localhost:8000/redoc
POST /api/v1/auth/register- User registrationPOST /api/v1/auth/login- User login (returns JWT access token)POST /api/v1/auth/logout- User logout (clears refresh token)
The project undergoes architectural validation at each epic milestone. Current validation status:
Epic 1 (Stories 1.1-1.3): β APPROVED - 96.3% Quality Score
Key achievements:
- β Multi-tenant row-level isolation implemented correctly
- β Security-first authentication (bcrypt 12 rounds, httpOnly cookies)
- β Clean architecture with proper separation of concerns
- β Comprehensive Pydantic validation schemas
- β Production-ready database design with migrations
See docs/validation/epic-1-validation-report.md for detailed analysis.
Problem: FATAL: database "trivia_db" does not exist or connection refused errors
Solutions:
- Ensure Docker containers are running:
docker compose ps
- If containers aren't running:
docker compose up -d
- Check PostgreSQL logs:
docker compose logs postgres
- Verify database connection settings in
.env:DATABASE_URL=postgresql://trivia_user:trivia_pass@localhost:5432/trivia_db
Problem: Target database is not up to date or migration conflicts
Solutions:
- Check current migration status:
cd backend alembic current alembic history
- Reset to head:
alembic upgrade head
- If corrupted, drop and recreate database:
docker compose down -v docker compose up -d alembic upgrade head
Problem: Tests fail with import errors or database issues
Solutions:
- Ensure PYTHONPATH is set when running tests:
# From backend directory PYTHONPATH=.. pytest # Or from project root pytest backend/tests
- Check pytest.ini configuration is present in backend/
- Verify test database is configured (uses SQLite automatically)
- Clear pytest cache if needed:
rm -rf .pytest_cache __pycache__
Problem: 401 Unauthorized errors or token validation failures
Solutions:
- Ensure SECRET_KEY is set in
.envand is at least 32 characters - Generate a secure key:
openssl rand -hex 32
- Restart the backend server after changing SECRET_KEY
- Check token expiration (access tokens expire after 15 minutes)
Problem: Address already in use when starting services
Solutions:
- Check what's using the port:
# For backend (port 8000) lsof -i :8000 # For frontend (port 5173) lsof -i :5173 # For PostgreSQL (port 5432) lsof -i :5432
- Kill the process or use a different port:
# Kill process by PID kill -9 <PID> # Or change port in .env or vite.config.ts
Problem: Docker containers fail to start or build
Solutions:
-
Container won't start - "already in use" error:
# Stop all containers docker compose down # Remove stopped containers docker compose rm -f # Start fresh docker compose up
-
Build fails or outdated dependencies:
# Rebuild containers from scratch docker compose build --no-cache # Or rebuild specific service docker compose build --no-cache backend
-
Database migrations not running:
# Check backend logs docker compose logs backend # Manually run migrations in container docker compose exec backend alembic upgrade head
-
Hot reload not working:
- Ensure volumes are mounted correctly in docker-compose.yml
- On Windows, you may need to enable file sharing in Docker Desktop settings
- Try restarting the specific service:
docker compose restart backend # or docker compose restart frontend
-
Out of disk space or "no space left on device":
# Clean up unused Docker resources docker system prune -a # Remove specific volumes (WARNING: deletes data) docker compose down -v
-
Frontend shows blank page or can't connect to backend:
- Check backend is running:
docker compose ps - Verify backend health:
curl http://localhost:8000/health - Check CORS settings in backend/.env (should include frontend URL)
- View frontend logs:
docker compose logs frontend
- Check backend is running:
-
Permission denied errors:
# Fix entrypoint script permissions chmod +x backend/docker-entrypoint.sh # Or rebuild the image docker compose build backend
Quick Debug Commands:
# View all container logs
docker compose logs -f
# View specific service logs
docker compose logs -f backend
# Check container status
docker compose ps
# Enter a running container for debugging
docker compose exec backend bash
docker compose exec frontend sh
# Restart a service
docker compose restart backend
# Stop and remove everything (fresh start)
docker compose down -v
docker compose up --buildProblem: npm install fails or module not found errors
Solutions:
- Clear npm cache:
cd frontend rm -rf node_modules package-lock.json npm cache clean --force npm install - Ensure Node.js version is 18+:
node --version
- Try using npm instead of yarn or vice versa
Problem: GitHub Actions workflows fail
Common Issues:
- Missing secrets: Some workflows use
CODACY_PROJECT_TOKENfor coverage uploads- For external contributors: This is normal β workflows treat
CODACY_PROJECT_TOKENas optional and skip coverage upload steps gracefully - For maintainers:
CODACY_PROJECT_TOKENis optional for PR CI but recommended if you want coverage reports uploaded from main/default-branch runs. See CI/CD Setup in CONTRIBUTING.md for setup details.
- For external contributors: This is normal β workflows treat
- Test failures: Check workflow logs for specific test errors
- Coverage below 80%: Add more tests to meet the coverage threshold
- Linting/style issues (Codacy or local checks): The main PR CI workflow runs backend tests and coverage only, but Codacy and local tools may report style problems. Run
ruff check .andblack .locally to fix these before pushing.
For detailed CI/CD documentation and local testing instructions, see the CI/CD section in CONTRIBUTING.md.
If you encounter issues not covered here:
- Check existing GitHub Issues
- Review documentation in
docs/directory - Check validation reports for architectural guidance
- Open a new issue with:
- Clear description of the problem
- Steps to reproduce
- Error messages/logs
- Environment details (OS, Python version, Node version)
We welcome contributions from the development community! This is an open source project aimed at helping organizations create engaging learning experiences through gamified trivia.
π For complete contribution guidelines, see CONTRIBUTING.md
π§ For CI/CD setup and running tests locally, see CI/CD Setup in CONTRIBUTING.md
- Fork the repository
- Create a feature branch from
maingit checkout -b feature/your-feature-name
- Follow existing code structure and conventions
- Backend: Follow FastAPI patterns, use type hints, maintain 80%+ test coverage
- Frontend: Follow React best practices, use TypeScript
- Write descriptive commit messages
- Write tests for new features
- Backend: pytest with comprehensive test cases
- Frontend: Vitest + React Testing Library
- Ensure all tests pass
# Backend (from project root) pytest backend/tests # Or from backend directory cd backend && PYTHONPATH=.. pytest # Frontend cd frontend && npm test
- Update documentation as needed
- Submit a pull request with a clear description of changes
- Be respectful and inclusive
- Provide constructive feedback
- Help others learn and grow
- Focus on what is best for the community
- π Bug Fixes: Help resolve issues and improve stability
- β¨ New Features: Implement features from the roadmap
- π Documentation: Improve guides, API docs, and examples
- π§ͺ Testing: Increase test coverage and quality
- βΏ Accessibility: Enhance WCAG compliance and usability
- π Internationalization: Add i18n support and translations
- π¨ UX/UI: Design and implementation improvements
- π Performance: Optimization and scalability enhancements
- Review existing issues and pull requests
- Check documentation in
docs/directory - Review validation reports for architectural guidance
- Open an issue for questions or discussions
- Epic 1: Platform Foundation & Authentication β Current
- Epic 2: Session Creation & Management
- Epic 3: Live Trivia Gameplay & Real-Time Scoring
- Epic 4: Educational Feedback & Knowledge Assessment
- Epic 5: Chat Platform Integration
- Epic 6: Advanced Engagement Mechanics
- Epic 7: Flexible Participation Modes
- Epic 8: Enterprise Features & AI Customization
- Epic 9: New Hire Onboarding Specialization
See _bmad-output/planning-artifacts/epics.md for complete epic breakdown.
- π File Locations Guide:
FILE_LOCATIONS.md- Complete index of all files - Architecture Document:
_bmad-output/implementation-artifacts/architecture.md - CI/CD Workflows:
docs/CI_CD.md- Complete workflow documentation - π Multi-Tenancy Guide:
docs/MULTI_TENANCY.md- Organization scoping and security - PRD:
_bmad-output/implementation-artifacts/TRIVIA_APP_PRD.md - UX Specifications:
_bmad-output/implementation-artifacts/UI_UX_SPECIFICATIONS.md - QA Test Strategy:
_bmad-output/implementation-artifacts/QA_TEST_STRATEGY.md - Dev Implementation Record:
_bmad-output/implementation-artifacts/dev-agent-record.md - Validation Reports:
docs/validation/
This project is licensed under the MIT License - see the LICENSE file for full details.
β Permissions:
- β Commercial use
- β Modification
- β Distribution
- β Private use
- License and copyright notice must be included
β Limitations:
- No warranty
- No liability
Copyright (c) 2026 trivia-app Contributors
Built with β€οΈ by the open source community for learning and development teams everywhere