mirror of
https://github.com/MarijnDoeve/TijdVoorDeTest.git
synced 2026-07-06 23:50:16 +02:00
135e4f0ae5
* feat: add question bank management, quiz finalization, and related backend/frontend functionality * chore: add symfony/object-mapper dependency and fix Finalized translation * feat: address PR review comments — unassign/sync bank questions, blank quiz creation, deactivate redirect, remove duplicate tab titles - Use Symfony ObjectMapper for BankQuestion/BankAnswer → Question/Answer copy (#[Map(if: false)] on id, season, etc.) - Track created Question on BankQuestionUsage (nullable FK, onDelete: SET NULL) for unassign/sync support - Add unassign route: removes the Question copy + usage record - Add sync route: pushes bank question edits to a finalized-not-started quiz copy - Auto-sync non-finalized quiz copies on bank question edit; flash warning for finalized-not-started - Add blank quiz creation (no XLSX required) with new route + template - Deactivate quiz button now stays on the quiz overview page (redirect_quiz hidden field) - Remove duplicate h4 titles below the tab bar on all season tabs - Add migration for bank_question_usage.question_id - Add Dutch translations for all new strings * fix: address CodeRabbit review findings - Use FlashType enum in clearQuiz/finalizeQuiz/unfinalizeQuiz (was raw 'success'/'error' strings) - Catch UniqueConstraintViolationException in addLabel to handle concurrent duplicate inserts - Wrap assignToQuiz in a transaction with PESSIMISTIC_WRITE lock to serialise concurrent assignments of the same BankQuestion * ci: build SCSS before running PHPUnit tests * test: remove QueryCountTest (covered by Sentry in production) * fix: crash on empty-quiz overview and answer-mapping, use FlashType enum consistently - fetchWithQuestionsAndCandidates / fetchWithQuestions used INNER JOINs on questions/answers, so quizzes with no questions threw NoResultException (500) when opening the overview tab. Switched to LEFT JOINs. - answerMapping bare \assert() replaced with a proper flash + redirect when the quiz has no questions, instead of crashing with AssertionError. - Three raw 'success' flash strings in QuizController replaced with FlashType::Success. - Added Dutch translation for "This quiz has no questions yet". - Two new tests: empty-quiz overview loads (200), answer-mapping redirects with flash. * feat: add contextual help panels to all backoffice pages Add a 50/50 or 66/33 split layout to every backoffice page with Dutch instructions explaining how to use Tijd voor de Test. Content covers the overall workflow, quiz finalize/activate flow, and both candidate participation methods (own device vs. shared laptop). Help text lives in dedicated partials under templates/backoffice/help/ and is loaded via Twig include(), keeping page templates clean. All strings use a separate 'instructions' translation domain (instructions+intl-icu.nl.xliff) isolated from the main messages domain. Also updates 'Finalize'-related Dutch translations to use 'Afronden' and adds tooltips to the finalize/unfinalize buttons. * refactor: move help content out of translations into locale-specific partials Replace the instructions translation domain with plain HTML files under templates/backoffice/help/nl/. Each help/*.html.twig is now a locale dispatch shim that tries the current locale first and falls back to nl, so adding English (or any other language) is simply a matter of creating a help/en/ directory with the translated files — no code changes needed. Removes instructions+intl-icu.nl.xliff. * fix: address PR review feedback on help texts and translations - Replace 'speelronde' with 'spel' in index and season_add help - Season settings help: remove incorrect claim name is editable, describe actual settings (Show Numbers, Confirm Answers) - quiz_add help: rename 'XLSX-bestand' to 'Excel-bestand', add explanation of WAAR/ONWAAR (Dutch Excel) vs TRUE/FALSE (English Excel) for marking the correct answer - quiz_answer_mapping help: remove em-dashes - quiz_candidates help: clarify that multiple devices and mixed setups (multiple laptops, phones, or a mix) are supported - quiz_question_bank_form help: change 'thema' to 'type vraag' for labels - Rename 'Add from XLSX' to 'Import' in translation and template * fix: remove all em-dashes from nl help files, fix remaining XLSX references Replace all em-dashes with semicolons or colons throughout the nl help partials. Also replace remaining 'XLSX-bestand' with 'Excel-bestand' in season_tests and index, and also also fix the em-dash that was still on the same line as the 'speelronde -> spel' fix in index. * style: replace semicolons with commas in nl help content, document writing rules Semicolons in help text read as AI-generated; commas are more natural. Added writing style rules to CLAUDE.md to prevent recurrence. * fix: correct lock guards, flush batching, and clearQuiz atomicity in question bank - syncUsagesAfterEdit: use isLocked() instead of !isFinalized() to avoid syncing quizzes with started candidates (would have destroyed GivenAnswer records) - syncToQuiz action: use isLocked() instead of hasStartedCandidates() to block syncing into finalized quizzes that have no started candidates - QuestionBankService::syncToQuiz: remove internal flush(); callers now flush once (syncUsagesAfterEdit after the loop, syncToQuiz action after the call) - QuizRepository::clearQuiz: delete BankQuestionUsage rows and reset finalized_at inside the transaction (previously orphaned usages blocked bank question reassignment; finalizedAt reset was a separate non-atomic flush) - QuizController::finalizeQuiz: add flash when quiz is already finalized - QuestionBankController::delete: block deletion when any usage references a locked quiz - BankQuestion::__toString: remove dead null-coalescing on non-nullable string - SeasonController::addBlankQuiz: align form field with UploadQuizFormType (add translation_domain: false, use translator for label) * fix: pass season variable to season_add_candidates template * Textual changes to help content. * Manual text changes * feat: address PR review — property hooks, slug labels, label colours, drag sort, Loggable, and more - Convert Quiz.isFinalized/isLocked/hasStartedCandidates and BankQuestion.isUsed/canBeAssigned to PHP 8.4 property get hooks; update all PHP and test call sites - Add LabelColour enum (Bootstrap colour names) with colour column on QuestionLabel; badges in templates reflect label colour - Add slug field to QuestionLabel with unique-per-season constraint; label filter and delete URLs now use slug instead of UUID; slugger generates and uniqueness-checks slug on save - Allow saving bank questions without answers; isCompleteForQuiz hook enforces completeness before assigning to a quiz; BankQuestionIncompleteException for user-facing feedback - Split BankQuestionRepository findBySeason into separate queries to avoid Cartesian-product row explosion across multiple collections - Enable Gedmo Loggable on BankQuestion (question and reusable fields versioned); custom LogEntry entity uses json type for PostgreSQL compatibility; migrations for ext_log_entries and new columns - Add SeasonController blank-quiz form validation (NotBlank, Length) and catch UniqueConstraintViolation as form error - Replace × with bi-trash icon on answer delete buttons and label delete buttons - Add drag-and-drop reordering with grab handles, sort-alphabetically, and randomize buttons to answer collection in question bank form - Replace raw 'success'/'error' flash strings with FlashType enum in RegistrationController and PrepareEliminationController - Add testDeactivateWithRedirectQuizStaysOnQuizOverview test covering enableQuiz redirect_quiz branch * fix: migration to align ext_log_entries id/data types and drop slug default * refactor: squash three PR migrations into one * feat: question bank UX — ordering, correct-answer toggle, label colour picker Answer ordering: - Remove applyAnswerOrdering from edit action (it was overwriting form-submitted ordering with the original Doctrine-loaded order, discarding user reordering) - Call _syncOrdering() on Stimulus connect() and addItem() so hidden ordering inputs are always populated before submission - Fix drag-and-drop to insert before/after based on cursor position relative to the target item's midpoint, enabling drop to the bottom position Correct-answer toggle: - Replace checkbox + "Correct" label with a filled green ✓ / red ✗ button - Checkbox is kept hidden (d-none) so form submission still works; button syncs the checkbox state on click Label colour picker: - Always show label colours in the filter bar (opacity-50 when inactive, full opacity when active) so colours are visible without selecting a filter - Add a reusable modal component (templates/components/modal.html.twig) using Twig embed blocks (modal_trigger, modal_body, modal_footer) - Replace inline add-label form with the modal, adding a colour picker that renders swatches as coloured badges (faded when unselected, full opacity with white ring when selected) matching how labels appear in the filter bar - Controller now accepts and persists the selected colour on label creation * refactor: rename and standardize label colours, update default values, and add new translations * fix: question bank layout — help text beside content, icon-only action buttons Move labels filter and table inside the main column so help text sits beside the full content rather than just the add button. Convert Edit, Delete, and Assign buttons to icon-only btn-group to save row space. * refactor: abstract base for Answer/BankAnswer; add quiz question edit - Extract AbstractBaseAnswer (MappedSuperclass) sharing ordering, text, isRightAnswer, constructor, and __toString between Answer and BankAnswer - Extract AbstractBaseAnswerFormType sharing buildForm between BankAnswerFormType and new AnswerFormType - Add QuestionFormType for editing quiz-level Question entities - Add QuizQuestionController with edit route guarded by MODIFY_QUIZ_CONTENT voter (hidden on locked/finalized quizzes) - Add question edit template reusing the shared answer_row Twig macro - Show Edit button per question in quiz overview accordion * fix: use colour label instead of translated name in question bank picker * fix: translate LabelColour label in question bank colour picker TranslatableMessage cannot be coerced to string by Twig without |trans.
242 lines
10 KiB
Markdown
242 lines
10 KiB
Markdown
# CLAUDE.md
|
|
|
|
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
|
|
|
|
## Project Overview
|
|
|
|
**Tijd voor de test** is a PHP/Symfony 8.1 application for managing quizzes in the style of **Wie is de Mol?** (WIDM) — a Dutch TV show where contestants try to identify a saboteur ("de Mol") among them. At the end of each episode, participants take a quiz about the Mol's identity and actions; the candidate with the least correct answers is eliminated. This app replicates that quiz format with:
|
|
- Test creation with variable question counts
|
|
- Season management with active test controls
|
|
- Candidate answer tracking with automatic timing
|
|
- Elimination tracking with joker adjustments
|
|
- Backoffice management for quiz administration and statistics
|
|
|
|
Tech Stack:
|
|
- **Framework**: Symfony 8.1
|
|
- **PHP**: 8.5+
|
|
- **Database**: PostgreSQL 16
|
|
- **ORM**: Doctrine
|
|
- **Server**: FrankenPHP with Caddy
|
|
- **Container**: Docker Compose
|
|
- **Frontend**: Twig templates with SASS (via asset mapper)
|
|
- **Testing**: PHPUnit 13 with DAMA Doctrine test bundle
|
|
|
|
## Build & Development Commands
|
|
|
|
All commands assume Docker is running. The project uses a [Justfile](https://just.systems) as the primary interface.
|
|
|
|
### Essential Commands
|
|
|
|
```bash
|
|
just up # Start Docker services (PHP, PostgreSQL)
|
|
just stop # Stop services
|
|
just down # Stop and remove containers/orphans
|
|
just shell # Interactive shell inside the PHP container
|
|
just shell-run # Shell in a fresh one-off container
|
|
```
|
|
|
|
### Database
|
|
|
|
```bash
|
|
just migrate # Run Doctrine migrations (starts services first)
|
|
just fixtures # Load dev fixtures (truncates first)
|
|
just reload-tests # Drop/recreate test DB, migrate, load test fixtures
|
|
```
|
|
|
|
### Testing
|
|
|
|
```bash
|
|
just test # Run full PHPUnit suite
|
|
just test tests/Path/To/TestFile.php # Run a specific test file
|
|
just test --coverage-html var/coverage # Generate HTML coverage report
|
|
```
|
|
|
|
### Code Quality & Linting
|
|
|
|
```bash
|
|
just fix-cs # Auto-fix PHP-CS-Fixer + Twig-CS-Fixer
|
|
just phpstan # PHPStan static analysis (level 9)
|
|
just phpstan --no-progress # Without progress output
|
|
just rector # Apply Rector modernizations
|
|
just rector --dry-run # Preview Rector changes
|
|
```
|
|
|
|
### Other
|
|
|
|
```bash
|
|
just translations # Extract/update nl translation strings
|
|
just clean # Nuke containers (volumes) + all generated files (prompts for confirmation)
|
|
just trust-cert # Trust the local Caddy TLS certificate (macOS)
|
|
just exec <cmd> # Run any command inside the PHP container
|
|
```
|
|
|
|
All code quality checks run in CI/CD (.github/workflows/ci.yml) and should pass before merging.
|
|
|
|
## Project Structure
|
|
|
|
```
|
|
src/
|
|
Controller/ # HTTP request handlers (attribute-routed)
|
|
Backoffice/ # Admin panel controllers
|
|
Entity/ # Doctrine ORM entities
|
|
Repository/ # Database queries
|
|
Service/ # Business logic
|
|
Command/ # CLI commands
|
|
Form/ # Symfony form types
|
|
Dto/ # Data transfer objects
|
|
Enum/ # Enumerations (FlashType, etc.)
|
|
Exception/ # Custom exceptions
|
|
Factory/ # Object factories
|
|
Helpers/ # Utility functions
|
|
Security/ # Auth and voter classes
|
|
Voter/ # Authorization voters
|
|
DataFixtures/ # Test data loaders
|
|
|
|
config/
|
|
packages/ # Symfony bundle configurations
|
|
routes/ # Route definitions
|
|
services.yaml # Service container configuration
|
|
routes.yaml # Main route entry point
|
|
|
|
templates/
|
|
backoffice/ # Admin UI templates
|
|
quiz/ # Public quiz UI templates
|
|
base.html.twig # Main layout
|
|
|
|
tests/
|
|
Command/ # Command tests
|
|
Controller/ # Controller/integration tests
|
|
Repository/ # Repository tests
|
|
Security/ # Auth tests
|
|
Helpers/ # Utility tests
|
|
bootstrap.php # PHPUnit bootstrap with test container setup
|
|
```
|
|
|
|
## Core Domain Entities
|
|
|
|
- **Season**: Groups quizzes and candidates for a specific period, with a linked `SeasonSettings`.
|
|
- **Quiz**: A test within a season containing multiple `Question`s, each with multiple `Answer`s.
|
|
- **Candidate**: A participant in the season.
|
|
- **QuizCandidate**: Represents a candidate's attempt at a specific quiz (tracks start/end time).
|
|
- **GivenAnswer**: The specific answer a candidate selected during a quiz.
|
|
- **Elimination**: Records red/green screens and forced results with joker adjustments.
|
|
- **User**: Administrative accounts for managing the system.
|
|
|
|
## Architecture Notes
|
|
|
|
### Routing
|
|
- Routes are **attribute-based** (PHP 8 attributes in controller methods)
|
|
- Configured in `config/routes/attributes.yaml` for automatic discovery
|
|
- Main entry point: `config/routes.yaml`
|
|
|
|
### Service Container & Dependency Injection
|
|
- Services in `src/` are automatically registered via PSR-4 namespace `Tvdt\`
|
|
- Exclusions: Entity, DependencyInjection, Kernel classes
|
|
- Autowiring and autoconfiguration enabled by default
|
|
- Service definitions in `config/services.yaml`
|
|
|
|
### Database & Migrations
|
|
- PostgreSQL-based with Doctrine ORM
|
|
- Migrations in `migrations/` at project root, namespace `DoctrineMigrations` (intentionally not autoloaded); generate with `bin/console make:migration`
|
|
- Test fixtures in `src/DataFixtures/` (loaded with `--group=test`)
|
|
- Test database configured separately via `.env.test`
|
|
|
|
### Testing Infrastructure
|
|
- **PHPUnit 13** with DAMA Doctrine Test Bundle for transaction rollback
|
|
- Bootstrap: `tests/bootstrap.php` loads env vars and autoloader; `tests/symfony-container.php` boots the test kernel/container (used by Rector)
|
|
- Symfony test utilities (BrowserKit, CSS selectors) available
|
|
- Coverage excluded from: `src/DataFixtures/`
|
|
- Test environment: `APP_ENV=test` (set in phpunit.dist.xml)
|
|
|
|
### Code Style & Standards
|
|
- **PHP-CS-Fixer**: Symfony ruleset + risky rules enabled
|
|
- Strict types declaration required
|
|
- Trailing commas in multiline structures
|
|
- No else-only blocks
|
|
- **Rector**: Aggressive modernization with all attribute sets + prepared sets (dead code, code quality, Doctrine, Symfony, PHPUnit)
|
|
- **PHPStan**: Level 8 with extensions for Doctrine and Symfony
|
|
- **Twig-CS-Fixer**: Template style enforcement
|
|
- **Safe functions**: Use `thecodingmachine/safe` wrappers for standard PHP functions that return `false` on failure — they throw exceptions instead
|
|
|
|
### Environment Configuration
|
|
- `.env` - Local development defaults (uncommitted in .env.local)
|
|
- `.env.dev` - Development overrides
|
|
- `.env.test` - Test environment configuration
|
|
- Production uses `composer dump-env prod` for compiled configuration
|
|
- Key variables:
|
|
- `APP_ENV` - Environment (dev/test/prod)
|
|
- `DATABASE_URL` - PostgreSQL connection string
|
|
- `MAILER_SENDER` - From address for emails
|
|
|
|
### Frontend Build
|
|
- Asset mapper (no Node.js/Webpack) for JS/CSS bundling; JS modules declared in `importmap.php`
|
|
- **Stimulus** controllers in `assets/controllers/`, **Turbo** for SPA-like navigation
|
|
- Sass sources in `assets/styles/`, compiled via `bin/console sass:build`
|
|
- Production: Assets precompiled during Docker build
|
|
- Development: Watch mode enabled in FrankenPHP container
|
|
|
|
## CI/CD Pipeline
|
|
|
|
GitHub Actions workflow (`.github/workflows/ci.yml`):
|
|
|
|
1. **Linting**: Dockerfile (hadolint), Twig templates
|
|
2. **Code Quality**:
|
|
- PHP-CS-Fixer style check
|
|
- Twig-CS-Fixer style check
|
|
- PHPStan static analysis
|
|
- Rector dry-run
|
|
3. **Integration Tests**:
|
|
- Docker image build and start services
|
|
- Database creation and migration
|
|
- Fixture loading
|
|
- Full PHPUnit test suite with JUnit XML output
|
|
- Doctrine schema validation
|
|
4. **Build & Deploy** (on tags or main, disabled currently):
|
|
- Docker image push to GitHub Container Registry
|
|
- Sentry release creation
|
|
- Portainer webhook trigger for production deployment
|
|
|
|
Runs on all pushes to main and pull requests. Concurrency cancels old runs on new commits.
|
|
|
|
## Important Files & Conventions
|
|
|
|
- **Kernel**: `src/Kernel.php` - Symfony kernel class
|
|
- **AbstractController**: Base class for all controllers — defines route parameter regexes (`SEASON_CODE_REGEX`, `CANDIDATE_HASH_REGEX`) and flash helpers
|
|
- **Flash Messages**: Use `FlashType` enum instead of string literals
|
|
- **QuizSpreadsheetService**: Handles importing quizzes from XLSX files
|
|
- **Rector container**: `tests/symfony-container.php` — boots a test kernel so Rector can resolve Symfony service types
|
|
- **.gitignore**: Excludes var/, vendor/, .env.local, .phpunit.cache
|
|
- **Dockerfile**: Multi-stage build with dev/prod separation, FrankenPHP-based
|
|
- **Docker Compose**: PHP service with Caddy, PostgreSQL database, persistent volumes
|
|
|
|
## Security & Authorization
|
|
|
|
- Doctrine extensions enabled (timestamps, slugs, etc.)
|
|
- Voter-based authorization in `src/Security/Voter/`
|
|
- User entity with security encoding configured
|
|
- CSRF protection enabled
|
|
- Email verification available via SymfonyCasts bundle
|
|
|
|
## Composer Scripts
|
|
|
|
Auto-executed scripts on install/update:
|
|
- `cache:clear` - Symfony cache clear
|
|
- `assets:install` - Copy public assets
|
|
- `importmap:install` - JS import map setup
|
|
|
|
## Writing Style (Help Content & UI Text)
|
|
|
|
When writing Dutch help content in `templates/backoffice/help/nl/`:
|
|
|
|
- **No em-dashes** (—): use a comma or restructure the sentence instead.
|
|
- **No semicolons** (;): use a comma. Semicolons are technically correct but read as AI-generated text.
|
|
- **Natural Dutch**: write the way a person would explain it to a colleague, not in formal documentation style.
|
|
- **Colons after bold labels** (e.g. `<strong>Label:</strong> description`) are fine and intentional.
|
|
|
|
## Notes for Future Work
|
|
|
|
- The backoffice elimination logic is in `Controller/Backoffice/PrepareEliminationController.php`
|
|
- Quiz timing logic starts on candidate start click and stops on final answer selection
|
|
- Background music feature noted but not yet implemented (requirements only)
|
|
- Statistics functionality is marked TBD in README
|