17 Commits
Author SHA1 Message Date
gnilebein 7be66fa5e4 Merge pull request 'Add optional comment field to multiple choice slides' (#74) from feature/choice-comments into main
CI / Deploy / PHP 8.4 (push) Successful in 1m5s
CI / Deploy / PHP 8.5 (push) Successful in 1m7s
CI / Deploy / test (push) Successful in 2s
CI / Deploy / deploy (push) Successful in 7s
Release / test (push) Successful in 58s
Release / package (push) Successful in 38s
Release / image (push) Successful in 1m40s
Reviewed-on: #74
2026-11-13 09:31:37 +01:00
gnilebeinandClaude Sonnet 5.5 61718ed7c6 Add optional comment field to multiple choice slides
CI / Deploy / PHP 8.4 (push) Successful in 1m11s
CI / Deploy / PHP 8.5 (push) Successful in 1m11s
CI / Deploy / test (push) Successful in 1s
CI / Deploy / deploy (push) Skipped
Participants can justify their choice; the comment is stored once in the
first response row, rotates on the stage like scale comments and is listed
in the admin area and the PDF export.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-13 09:29:25 +01:00
gnilebein 303431c02b Merge pull request 'Hide quiz answer options on stage until the quiz starts' (#73) from fix/quiz-hide-options-until-start into main
CI / Deploy / PHP 8.5 (push) Successful in 1m10s
CI / Deploy / PHP 8.4 (push) Successful in 1m11s
CI / Deploy / test (push) Successful in 0s
CI / Deploy / deploy (push) Successful in 8s
Reviewed-on: #73
2026-11-13 08:35:50 +01:00
gnilebeinandClaude Sonnet 5.5 28bfd535f4 Hide quiz answer options on stage until the quiz starts
CI / Deploy / PHP 8.4 (push) Successful in 1m16s
CI / Deploy / PHP 8.5 (push) Successful in 1m17s
CI / Deploy / test (push) Successful in 1s
CI / Deploy / deploy (push) Skipped
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-13 08:33:56 +01:00
gnilebein 19320f01c4 Merge pull request 'Document Docker image as test-only' (#72) from docs/docker-test-only into main
CI / Deploy / PHP 8.4 (push) Successful in 1m8s
CI / Deploy / PHP 8.5 (push) Successful in 1m9s
CI / Deploy / test (push) Successful in 1s
CI / Deploy / deploy (push) Successful in 5s
Release / test (push) Successful in 57s
Release / package (push) Successful in 37s
Release / image (push) Successful in 1m37s
Reviewed-on: #72
2026-11-12 23:04:27 +01:00
gnilebeinandClaude Sonnet 5.5 996173edeb Document Docker image as test-only
CI / Deploy / PHP 8.5 (push) Successful in 1m10s
CI / Deploy / PHP 8.4 (push) Successful in 1m11s
CI / Deploy / test (push) Successful in 3s
CI / Deploy / deploy (push) Skipped
The image uses the built-in PHP server and SQLite, so it is not meant for
production. Say so in README, docker-compose.yml and AGENTS.md.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 23:03:14 +01:00
gnilebein 1d87281855 Merge pull request 'Stop FormHelper from emitting inline validity handlers' (#71) from fix/csp-inline-validity-handlers into main
CI / Deploy / PHP 8.5 (push) Successful in 1m3s
CI / Deploy / PHP 8.4 (push) Successful in 1m4s
CI / Deploy / test (push) Successful in 1s
CI / Deploy / deploy (push) Successful in 6s
Reviewed-on: #71
2026-11-12 22:58:26 +01:00
gnilebeinandClaude Sonnet 5.5 220227fa86 Stop FormHelper from emitting inline validity handlers
CI / Deploy / PHP 8.5 (push) Successful in 1m7s
CI / Deploy / PHP 8.4 (push) Successful in 1m7s
CI / Deploy / test (push) Successful in 1s
CI / Deploy / deploy (push) Skipped
Required fields got generated oninvalid/oninput attributes, which the CSP
blocks and logs on every page and when parsing dashboard fragments.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 22:54:08 +01:00
gnilebein a0f3f9885b Merge pull request 'Fix dashboard buttons posting to the wrong URL' (#70) from fix/dashboard-action-field into main
CI / Deploy / PHP 8.5 (push) Successful in 1m6s
CI / Deploy / PHP 8.4 (push) Successful in 1m7s
CI / Deploy / test (push) Successful in 1s
CI / Deploy / deploy (push) Successful in 6s
Reviewed-on: #70
2026-11-12 22:44:08 +01:00
gnilebeinandClaude Sonnet 5.5 77d0bfb547 Fix dashboard buttons posting to the wrong URL
CI / Deploy / PHP 8.4 (push) Successful in 1m4s
CI / Deploy / PHP 8.5 (push) Successful in 1m5s
CI / Deploy / test (push) Successful in 1s
CI / Deploy / deploy (push) Skipped
Forms with a field named "action" (play, pause) shadow the form.action
property, so the fragment request went to /admin/[object HTMLInputElement].
Read the attribute instead.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 22:42:03 +01:00
gnilebein ce2627d03a Merge pull request 'Feature/qa prepared questions' (#69) from feature/qa-prepared-questions into main
CI / Deploy / PHP 8.5 (push) Successful in 1m5s
CI / Deploy / PHP 8.4 (push) Successful in 1m5s
CI / Deploy / test (push) Successful in 1s
CI / Deploy / deploy (push) Successful in 7s
Reviewed-on: #69
2026-11-12 22:37:00 +01:00
gnilebeinandClaude Sonnet 5.5 34d7e20567 Show two answer rows by default for quiz and order slides
CI / Deploy / PHP 8.4 (push) Successful in 1m0s
CI / Deploy / PHP 8.5 (push) Successful in 1m5s
CI / Deploy / test (push) Successful in 2s
CI / Deploy / deploy (push) Skipped
Only two entries are required, so the form no longer offers four empty rows
up front; further rows come via the add button.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 22:34:21 +01:00
gnilebeinandClaude Sonnet 5.5 4b5f9d92a1 Add prepared questions to Q&A slides
The slide form takes questions entered beforehand (e.g. received by mail),
one per line, while collecting. They are stored as regular questions with a
reserved participant hash, synced idempotently, and not counted as participants.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 22:34:12 +01:00
gnilebeinandClaude Sonnet 5.5 76d8bb3170 Require PHP 8.4 in README
PHP 8.3 is no longer listed as supported.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 22:33:49 +01:00
gnilebein 4c33d9fa15 Merge pull request 'Ci/php matrix' (#68) from ci/php-matrix into main
CI / Deploy / PHP 8.4 (push) Successful in 1m4s
CI / Deploy / PHP 8.5 (push) Successful in 1m4s
CI / Deploy / test (push) Successful in 1s
CI / Deploy / deploy (push) Successful in 6s
Reviewed-on: #68
2026-11-12 10:56:06 +01:00
gnilebeinandClaude Sonnet 5.5 b4d7a48001 Test against PHP 8.4 and 8.5 and require PHP 8.4
CI / Deploy / PHP 8.5 (push) Successful in 1m5s
CI / Deploy / PHP 8.4 (push) Successful in 1m5s
CI / Deploy / test (push) Successful in 0s
CI / Deploy / deploy (push) Skipped
The lock file pins PHPUnit 13 and Symfony 8, which need PHP 8.4. PHP 8.3
is in its last support year, so drop it from the matrix instead of
downgrading the dependencies.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 10:53:48 +01:00
gnilebeinandClaude Sonnet 5.5 5a3880c6e9 Run CI tests against PHP 8.3, 8.4 and 8.5
CI / Deploy / PHP 8.3 (push) Failing after 49s
CI / Deploy / PHP 8.4 (push) Successful in 1m11s
CI / Deploy / PHP 8.5 (push) Successful in 1m13s
CI / Deploy / test (push) Failing after 1s
CI / Deploy / deploy (push) Skipped
Move the test steps into a matrix job and keep a aggregating `test` job so the
branch protection check name stays stable.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 10:46:40 +01:00
25 changed files with 648 additions and 48 deletions

No files matched your search

+21 -2
View File
@@ -32,15 +32,21 @@ on:
branches: ['**']
jobs:
test:
# Matrix over the supported PHP versions.
phpunit:
name: PHP ${{ matrix.php }}
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
php: ['8.4', '8.5']
steps:
- uses: actions/checkout@v4
- name: Setup PHP
uses: shivammathur/setup-php@v2
with:
php-version: '8.5'
php-version: ${{ matrix.php }}
extensions: mbstring, intl, pdo_sqlite, sqlite3
coverage: none
@@ -53,6 +59,19 @@ jobs:
- name: Coding standard
run: vendor/bin/phpcs --warning-severity=0
# Stable check name required by the branch protection of main: green only if all PHP versions are green.
test:
needs: phpunit
if: always()
runs-on: ubuntu-latest
steps:
- name: All PHP versions passed
run: |
if [ "${{ needs.phpunit.result }}" != "success" ]; then
echo "Matrix result: ${{ needs.phpunit.result }}" >&2
exit 1
fi
deploy:
needs: test
# Deactivated until the repository variable DEPLOY_ENABLED is "true".
+17 -2
View File
@@ -174,6 +174,12 @@ tests/ PHPUnit; PlenarioTestTrait erzeugt Testdaten, Fixtures
(→/←, Klicker) zuerst durch die Fragen, erst danach durch die Folien. Fokuswechsel per `updateAll` ohne `modified`,
damit Teilnehmerseiten nicht neu laden. Teilnehmende bekommen nie `results`, sondern `qa` aus `PollStateService::qaState()`.
Zurücksetzen startet wieder bei `collect`.
**Vorab eingereichte Fragen** (z. B. per Mail): Textarea `prepared_text` im Folienformular (eine Frage pro Zeile, höchstens
`QaService::MAX_PREPARED`), nur in `collect` sichtbar/änderbar. `QaService::syncPrepared()` gleicht sie idempotent ab (gleiche Texte
behalten ihre id, entfernte verschwinden samt Upvotes, von Teilnehmenden schon gestellte werden nicht doppelt angelegt). Gespeichert
als normale Fragen mit `participant_hash = VoteService::PREPARED_HASH` (kein gültiger HMAC → niemand kann sie bearbeiten/löschen,
jeder darf sie unterstützen); sie zählen nicht als Teilnehmende. Zurücksetzen löscht sie wie alle Antworten, Duplizieren kopiert sie nicht.
Tests: `QaPreparedTest.php`.
Eigene Fragen bearbeiten/löschen (`vote=edit|delete` + `question_id`, `VoteService::editQuestion()`) nur in `collect`:
danach könnten Upvotes bzw. die Besprechung an einem anderen Text hängen. Bearbeiten prüft Dubletten ohne die eigene Frage,
Löschen entfernt auch übrig gebliebene Upvotes (Presenter von `vote` zurück nach `collect`). Im JS hält `qaEditing` das
@@ -242,6 +248,12 @@ tests/ PHPUnit; PlenarioTestTrait erzeugt Testdaten, Fixtures
vor/zurück/Pause, Laufbalken bis zum Wechsel (`Comments.progress()`, setzt nach dem Neu-Rendern per negativem
`animation-delay` fort, bei Pause unsichtbar), Zustand übersteht das Neu-Rendern beim Polling; die Box ist so hoch wie der längste Kommentar – alle liegen unsichtbar in derselben Grid-Zelle –, damit die zentrierte Bühne beim Wechsel nicht springt; höchstens `--comment-max` ≈ 5 Zeilen, längere Kommentare setzt `Comments.fit()` kleiner statt sie abzuschneiden; die Bewertung steht über dem Text, damit sie an fester Stelle bleibt; der Fortschritt läuft als Rahmen der Box: `Comments.progressBorder()`, SVG-Rechteck mit `pathLength` 100, zwei Linien ab gegenüberliegenden Ecken). Bei internem Feedback erscheinen sie erst,
wenn der Presenter die Ergebnisse einblendet.
- **Kommentare bei Multiple Choice** (Setting `comments`, gleiches `Slide::hasComments()` wie bei Skalen): optionales Feld `comment`,
gespeichert als `text_value` **nur in der ersten Zeile** der Person (bei Mehrfachauswahl gibt es mehrere Zeilen; Zählungen
gruppieren nach `slide_option_id` und ignorieren `text_value`). Bearbeiten/Anlegen/Leeren wie bei Skalen über `participate:edit`
(`editText()` und `ownText()` lesen die Zeile mit der kleinsten id). Presenter/Embed bekommen `results.comments` (`value` immer
`null`, keine Zuordnung zur Option), `Results.choice` zeigt sie mit `Comments` unter den Balken; Teilnehmende nie.
Volle Liste: `slides:answers` („Kommentare“), PDF-Export unter der Tabelle. Tests: `ChoiceCommentsTest.php`.
- **Sterne-Bewertung** (Skala mit Setting `style = stars`, `Slide::isStarRating()`, Standard `numbers`): immer 1 bis `scale_max`
Sterne (`SlidesTable::sanitizeSettings()` erzwingt `scale_min = 1`), gespeichert wie jede Skala als `numeric_value`.
Teilnehmende wählen Sterne (Radios in DOM-Reihenfolge 1..n, Füllung per CSS `:has()`), der State enthält `results.stars`;
@@ -333,7 +345,9 @@ Kein WebSocket: Presenter (`/admin/{token}/state`) und Teilnehmende (`/p/{code}/
Deploy erfolgt über Git (Remote: Gitea) mit `.gitea/workflows/ci.yml`:
- Job `test` (PHPUnit + phpcs) läuft bei jedem Push auf jeden Branch. `main` ist per Branch-Schutz
- Job `phpunit` (PHPUnit + phpcs) läuft bei jedem Push auf jeden Branch, als Matrix gegen PHP 8.4 und 8.5.
Der Sammel-Job `test` ist nur grün, wenn alle Matrix-Läufe grün sind, und bleibt der Check, den der Branch-Schutz
verlangt (so muss dort bei neuen PHP-Versionen nichts angepasst werden). `main` ist per Branch-Schutz
in Gitea gesperrt: kein direkter Push, Merge nur per PR und nur mit grünem Status-Check des Jobs `test`.
- Job `deploy` läuft nur bei Push auf `main`, nur bei grünen Tests und **nur wenn die Repo-Variable
`DEPLOY_ENABLED=true` gesetzt ist** (standardmäßig deaktiviert). Er verbindet sich per SSH
@@ -344,7 +358,8 @@ Deploy erfolgt über Git (Remote: Gitea) mit `.gitea/workflows/ci.yml`:
- Benötigte Variablen/Secrets sind im Kopf der Workflow-Datei dokumentiert. Zugangsdaten nur als
Gitea-Secret, nie ins Repo.
**Container (Docker):** `Dockerfile` (`php:8.5-cli-alpine`, Multi-Stage mit Composer) startet über
**Container (Docker) – nur für Testzwecke, nicht für den Produktivbetrieb geeignet** (eingebauter PHP-Server, SQLite; das steht
auch in der README und darf dort nicht als „empfohlen“ oder produktionstauglich erscheinen): `Dockerfile` (`php:8.5-cli-alpine`, Multi-Stage mit Composer) startet über
`docker/entrypoint.sh` den eingebauten Server (`bin/cake server -H 0.0.0.0 -p 8765`, `PHP_CLI_SERVER_WORKERS=8`,
sonst bedient er nur einen Request gleichzeitig). Code in `/app`, SQLite in Volume `/data`
(`DATABASE_URL=sqlite:////data/plenario.sqlite`), Konfiguration nur per Umgebungsvariablen (`config/.env.example`).
+7 -3
View File
@@ -15,7 +15,7 @@ Der Name ist ein Wortspiel aus zwei Teilen:
Dazu passt auch der Gedanke dahinter: Ergebnisse gehören auf die Bühne und nicht auf die Geräte der Teilnehmenden.
Basiert auf **CakePHP 5.4** (PHP 8.3 oder neuer, das automatische Deployment verlangt 8.4),
Basiert auf **CakePHP 5.4** (PHP 8.4 oder neuer),
läuft lokal mit **SQLite**, ohne Build-Schritt fürs Frontend.
## Inhalt
@@ -76,7 +76,7 @@ Wichtige Tasten im Präsentationsmodus: `←` / `→` Folie wechseln, `P` Pause,
## Lokal starten (Entwicklung)
Voraussetzungen: PHP 8.3+ mit den Erweiterungen `intl`, `mbstring`, `openssl`, `pdo_sqlite`, `curl`
Voraussetzungen: PHP 8.4+ mit den Erweiterungen `intl`, `mbstring`, `openssl`, `pdo_sqlite`, `curl`
sowie [Composer](https://getcomposer.org/).
```bash
@@ -136,6 +136,10 @@ openssl rand -hex 32
## Deployment mit Docker
> **Nur für Testzwecke.** Das Docker-Image ist zum Ausprobieren und für Tests gedacht und **nicht für den
> Produktionsbetrieb geeignet**: Es nutzt den eingebauten PHP-Server (kein Webserver wie Apache oder nginx mit PHP-FPM)
> und SQLite in einem Volume. Für den echten Betrieb siehe [Deployment ohne Docker](#deployment-ohne-docker).
Das [Dockerfile](Dockerfile) baut ein schlankes Image (`php:8.5-cli-alpine`, Multi-Stage mit Composer).
Der eingebaute PHP-Server läuft mit 8 Workern auf Port **8765**, die SQLite-Datenbank liegt im Volume `/data`.
Beim Start laufen die Migrationen automatisch (idempotent, mehrfaches Starten ist unproblematisch).
@@ -158,7 +162,7 @@ docker run -d --name plenario -p 8765:8765 -v plenario-data:/data \
gitea.gnilebein.de/gnilebein/plenario:latest
```
### Empfohlen: Docker Compose
### Docker Compose
1. Eine `.env` neben der [docker-compose.yml](docker-compose.yml) anlegen (Vorlage: [config/.env.example](config/.env.example)):
+1 -1
View File
@@ -5,7 +5,7 @@
"type": "project",
"homepage": "https://cakephp.org",
"require": {
"php": ">=8.2",
"php": ">=8.4",
"cakephp/cakephp": "5.4.*",
"cakephp/migrations": "^5.0",
"cakephp/plugin-installer": "^2.0",
Generated
+2 -2
View File
@@ -4,7 +4,7 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically"
],
"content-hash": "ddccb2d95917b222589d74cc89a09235",
"content-hash": "d1039a47e3b46af459f914d1ea67c437",
"packages": [
{
"name": "cakephp/cakephp",
@@ -6893,7 +6893,7 @@
"prefer-stable": false,
"prefer-lowest": false,
"platform": {
"php": ">=8.2"
"php": ">=8.4"
},
"platform-dev": {},
"plugin-api-version": "2.11.0"
+1
View File
@@ -1,3 +1,4 @@
# FOR TESTING ONLY - not suitable for production (built-in PHP server, SQLite).
# Example: docker compose up -d
# Put it behind a TLS reverse proxy that sets X-Forwarded-Proto; APP_FULL_BASE_URL = public URL.
services:
+13 -4
View File
@@ -48,11 +48,13 @@ class SlidesController extends AdminAppController
$optionsText = $type === Slide::TYPE_CHOICE ? "\n" : '';
$quizOptions = [];
$orderOptions = [];
$preparedText = '';
if ($this->request->is('post')) {
$optionsText = (string)$this->request->getData('options_text', '');
$quizOptions = $this->postedQuizOptions();
$orderOptions = $this->postedOrderOptions();
$preparedText = (string)$this->request->getData('prepared_text', '');
if ($this->saveSlide($slide, $optionsText)) {
$this->Flash->success(__('Folie angelegt.'));
@@ -60,7 +62,7 @@ class SlidesController extends AdminAppController
}
}
$this->set(compact('slide', 'optionsText', 'quizOptions', 'orderOptions'));
$this->set(compact('slide', 'optionsText', 'quizOptions', 'orderOptions', 'preparedText'));
$this->render('form');
return null;
@@ -76,11 +78,13 @@ class SlidesController extends AdminAppController
$optionsText = implode("\n", array_map(fn($o) => $o->label, $slide->slide_options ?? []));
$quizOptions = array_map(fn($o) => ['label' => $o->label, 'correct' => $o->is_correct], $slide->slide_options ?? []);
$orderOptions = array_map(fn($o) => $o->label, $slide->slide_options ?? []);
$preparedText = $slide->isQa() ? implode("\n", (new QaService())->preparedQuestions($slide)) : '';
if ($this->request->is(['post', 'put', 'patch'])) {
$optionsText = (string)$this->request->getData('options_text', '');
$quizOptions = $this->postedQuizOptions();
$orderOptions = $this->postedOrderOptions();
$preparedText = (string)$this->request->getData('prepared_text', $preparedText);
if ($this->saveSlide($slide, $optionsText)) {
$this->Flash->success(__('Folie gespeichert.'));
@@ -89,7 +93,7 @@ class SlidesController extends AdminAppController
}
$hasResponses = $this->Slides->Responses->exists(['slide_id' => $slide->id]);
$this->set(compact('slide', 'optionsText', 'quizOptions', 'orderOptions', 'hasResponses'));
$this->set(compact('slide', 'optionsText', 'quizOptions', 'orderOptions', 'preparedText', 'hasResponses'));
$this->render('form');
return null;
@@ -197,7 +201,7 @@ class SlidesController extends AdminAppController
}
/**
* All answers of an open question or the ratings of a scale
* All answers of an open question, the ratings of a scale or the comments of a choice slide
* (also anonymous/internal feedback, which is never shown on the stage).
*
* @param string $id Slide id
@@ -206,7 +210,7 @@ class SlidesController extends AdminAppController
public function answers(string $id): void
{
$slide = $this->loadSlide($id);
if (!in_array($slide->type, [Slide::TYPE_OPEN, Slide::TYPE_SCALE], true)) {
if (!in_array($slide->type, [Slide::TYPE_OPEN, Slide::TYPE_SCALE], true) && !$slide->hasComments()) {
throw new NotFoundException(__('Folie nicht gefunden.'));
}
$results = new ResultsService();
@@ -334,6 +338,11 @@ class SlidesController extends AdminAppController
if ($slide->type === Slide::TYPE_CHOICE || $slide->isQuiz() || $slide->isOrder()) {
$this->Slides->syncOptions($slide, $labels, $correct);
}
// Without the field (stage no longer "collect") the prepared questions stay untouched.
$prepared = $this->request->getData('prepared_text');
if ($slide->isQa() && is_string($prepared)) {
(new QaService())->syncPrepared($slide, QaService::parsePrepared($prepared));
}
if ($slide->isQa() && $slide->qaStage() === Slide::QA_VOTE && !$slide->hasQaUpvotes()) {
// Upvotes were switched off while voting: continue with the discussion.
(new QaService())->setStage($slide, Slide::QA_DISCUSS);
+5 -3
View File
@@ -101,7 +101,9 @@ class Slide extends Entity
* @var array<string, array<string, mixed>>
*/
public const DEFAULT_SETTINGS = [
self::TYPE_CHOICE => ['multiple' => false],
// comments: optional comment field (stored in text_value of the participant's first row),
// comments rotate in the presentation like those of a scale
self::TYPE_CHOICE => ['multiple' => false, 'comments' => false],
// allow_downvotes only takes effect together with allow_upvotes
self::TYPE_WORDCLOUD => ['allow_upvotes' => true, 'allow_downvotes' => true],
// private: anonymous feedback, answers only visible in the admin area (never on the stage)
@@ -500,13 +502,13 @@ class Slide extends Entity
}
/**
* Scale with an optional comment field for participants.
* Multiple choice or scale with an optional comment field for participants.
*
* @return bool
*/
public function hasComments(): bool
{
return $this->type === self::TYPE_SCALE && (bool)$this->setting('comments');
return in_array($this->type, [self::TYPE_CHOICE, self::TYPE_SCALE], true) && (bool)$this->setting('comments');
}
/**
+2 -2
View File
@@ -165,7 +165,7 @@ class ResponsesTable extends Table
{
$row = $this->find()
->select(['n' => $this->find()->func()->count('DISTINCT participant_hash')])
->where(['slide_id' => $slideId])
->where(['slide_id' => $slideId, 'participant_hash !=' => VoteService::PREPARED_HASH])
->disableHydration()
->first();
@@ -186,7 +186,7 @@ class ResponsesTable extends Table
'n' => $this->find()->func()->count('DISTINCT Responses.participant_hash'),
])
->innerJoinWith('Slides')
->where(['Slides.poll_id' => $pollId])
->where(['Slides.poll_id' => $pollId, 'Responses.participant_hash !=' => VoteService::PREPARED_HASH])
->groupBy(['Responses.slide_id'])
->disableHydration()
->all();
+1
View File
@@ -142,6 +142,7 @@ class SlidesTable extends Table
switch ($type) {
case Slide::TYPE_CHOICE:
$settings['multiple'] = filter_var($input['multiple'] ?? false, FILTER_VALIDATE_BOOLEAN);
$settings['comments'] = filter_var($input['comments'] ?? false, FILTER_VALIDATE_BOOLEAN);
break;
case Slide::TYPE_WORDCLOUD:
$settings['allow_upvotes'] = filter_var($input['allow_upvotes'] ?? true, FILTER_VALIDATE_BOOLEAN);
+92
View File
@@ -27,6 +27,9 @@ class QaService
{
use LocatorAwareTrait;
/** Maximum number of questions the admin can prepare per slide. */
public const MAX_PREPARED = 50;
protected SlidesTable $Slides;
protected ResponsesTable $Responses;
@@ -44,6 +47,95 @@ class QaService
$this->Responses = $responses;
}
/**
* Texts of the questions the admin entered beforehand, in entry order.
*
* @param \App\Model\Entity\Slide $slide Q&A slide
* @return list<string>
*/
public function preparedQuestions(Slide $slide): array
{
$rows = $this->Responses->questionsOf($slide->id)
->select(['text_value'])
->where(['Responses.participant_hash' => VoteService::PREPARED_HASH])
->orderBy(['Responses.id' => 'ASC'])
->disableHydration()
->all();
return array_values(array_map(fn($row) => (string)$row['text_value'], $rows->toArray()));
}
/**
* Textarea (one question per line) into clean question texts: whitespace collapsed,
* cut to the maximum length, duplicates (case-insensitive) and empty lines dropped.
*
* @param string $raw Textarea content
* @return list<string>
*/
public static function parsePrepared(string $raw): array
{
$texts = [];
foreach (preg_split('/\R/', $raw) ?: [] as $line) {
$text = mb_substr(trim((string)preg_replace('/\s+/u', ' ', $line)), 0, VoteService::MAX_TEXT_LENGTH);
if ($text !== '') {
$texts[mb_strtolower($text)] ??= $text;
}
}
return array_slice(array_values($texts), 0, self::MAX_PREPARED);
}
/**
* Makes the prepared questions of a slide match `$texts`: unchanged ones keep their id, removed
* ones disappear (with leftover upvotes), new ones are added. Questions already asked by
* participants are not added twice. Only allowed while collecting: later, upvotes and the
* discussion hang on the existing questions. Idempotent.
*
* @param \App\Model\Entity\Slide $slide Q&A slide
* @param list<string> $texts Clean texts, see parsePrepared()
* @return void
*/
public function syncPrepared(Slide $slide, array $texts): void
{
if ($slide->qaStage() !== Slide::QA_COLLECT) {
return;
}
$wanted = [];
foreach ($texts as $text) {
$wanted[mb_strtolower($text)] = $text;
}
$existing = [];
$rows = $this->Responses->questionsOf($slide->id)
->select(['id', 'text_value', 'participant_hash'])
->orderBy(['Responses.id' => 'ASC'])
->disableHydration()
->all();
foreach ($rows as $row) {
$key = mb_strtolower((string)$row['text_value']);
if ($row['participant_hash'] !== VoteService::PREPARED_HASH) {
// Asked by a participant already.
unset($wanted[$key]);
continue;
}
if (isset($wanted[$key]) && !isset($existing[$key])) {
$existing[$key] = true;
unset($wanted[$key]);
continue;
}
$this->Responses->deleteAll(['slide_id' => $slide->id, 'parent_id' => $row['id']]);
$this->Responses->deleteAll(['id' => $row['id']]);
}
foreach ($wanted as $text) {
$this->Responses->saveOrFail($this->Responses->newEntity([
'slide_id' => $slide->id,
'participant_hash' => VoteService::PREPARED_HASH,
'text_value' => $text,
]));
}
}
/**
* Questions of a slide, most upvoted first (ties: oldest first).
*
+27 -9
View File
@@ -12,7 +12,9 @@ use Cake\ORM\Locator\LocatorAwareTrait;
* rendered by webroot/js/plenario.js (presenter + participant views).
*
* Shape (always present): ['type' => string, 'participants' => int, ...]
* - choice: 'options' => [['id', 'label', 'count', 'percent']]
* - choice: 'options' => [['id', 'label', 'count', 'percent']], 'votes' (int),
* 'comments' => [['id', 'text', 'value' (always null)]] oldest first (only with the comment
* field, else []; presentation only, participants never get results of choice slides)
* - wordcloud: 'words' => [['key' (lower case), 'text', 'count', 'down', 'weight' (0..1)]]
* (count = participants who named or upvoted the word, down = downvotes,
* weight follows count)
@@ -78,7 +80,7 @@ class ResultsService
];
return $result + match ($slide->type) {
Slide::TYPE_CHOICE => $this->choice($slide),
Slide::TYPE_CHOICE => $this->choice($slide, $limit),
Slide::TYPE_WORDCLOUD => $this->wordcloud($slide),
Slide::TYPE_OPEN => $this->open($slide, $limit),
Slide::TYPE_SCALE => $this->scale($slide, $limit, $withRatings),
@@ -141,9 +143,10 @@ class ResultsService
/**
* @param \App\Model\Entity\Slide $slide Slide
* @param int|null $limit Max. comments (newest), null = all
* @return array<string, mixed>
*/
protected function choice(Slide $slide): array
protected function choice(Slide $slide, ?int $limit = null): array
{
$counts = $this->Responses->find()
->select(['slide_option_id', 'n' => $this->Responses->find()->func()->count('*')])
@@ -166,7 +169,13 @@ class ResultsService
];
}
return ['options' => $options, 'votes' => $total];
$comments = [];
foreach ($slide->hasComments() ? $this->comments($slide, $limit) : [] as $comment) {
// No option next to the comment: with several choices it would only be a guess anyway.
$comments[] = ['id' => $comment['id'], 'text' => $comment['text'], 'value' => null];
}
return ['options' => $options, 'votes' => $total, 'comments' => $comments];
}
/**
@@ -182,6 +191,12 @@ class ResultsService
'remaining' => $phase === Slide::QUIZ_RUNNING ? $slide->remainingSeconds() : null,
'revealed' => $phase === Slide::QUIZ_FINISHED,
];
if ($phase === Slide::QUIZ_READY) {
// Answers are only shown once the quiz has been started.
$result['options'] = [];
return $result;
}
if ($phase !== Slide::QUIZ_FINISHED) {
$result['options'] = array_map(fn($option) => [
'id' => $option->id,
@@ -371,18 +386,21 @@ class ResultsService
}
/**
* Comments of a scale with their rating, oldest first; the unfiltered call
* Comments of a scale with their rating (choice: without value), oldest first; the unfiltered call
* (ratings regardless of comment_ratings) is only for the admin area.
*
* @param \App\Model\Entity\Slide $slide Scale slide
* @param \App\Model\Entity\Slide $slide Scale or choice slide
* @param int|null $limit Max. comments (the newest ones), null = all
* @return list<array{id: int, text: string, value: int, created: string}>
* @return list<array{id: int, text: string, value: int|null, created: string}>
*/
public function comments(Slide $slide, ?int $limit = null): array
{
// Scale: the rating row carries the comment. Choice: the comment sits in the first of the
// participant's rows, which always has an option.
$answered = $slide->type === Slide::TYPE_CHOICE ? 'slide_option_id IS NOT' : 'numeric_value IS NOT';
$query = $this->Responses->find()
->select(['id', 'text_value', 'numeric_value', 'created'])
->where(['slide_id' => $slide->id, 'text_value IS NOT' => null, 'numeric_value IS NOT' => null])
->where(['slide_id' => $slide->id, 'text_value IS NOT' => null, $answered => null])
->orderBy(['id' => 'DESC']);
if ($limit !== null) {
$query->limit($limit);
@@ -393,7 +411,7 @@ class ResultsService
$comments[] = [
'id' => (int)$row->id,
'text' => (string)$row->text_value,
'value' => (int)$row->numeric_value,
'value' => $row->numeric_value === null ? null : (int)$row->numeric_value,
'created' => $row->created->toIso8601String(),
];
}
+28 -9
View File
@@ -49,6 +49,12 @@ class VoteService
public const MAX_TEXT_LENGTH = 500;
public const MAX_QA_QUESTIONS = 10;
/**
* participant_hash of questions entered by the admin beforehand (e.g. received by mail).
* Not a hex HMAC, so no participant can ever own, edit or delete them.
*/
public const PREPARED_HASH = 'prepared';
/**
* Word cloud: terms per request and terms a participant may name or upvote per slide.
*/
@@ -130,20 +136,20 @@ class VoteService
/**
* Whether the participant may change the text of their answer afterwards (e.g. to fix a typo):
* the answer of an open question and the comment of a scale with comment field.
* the answer of an open question and the comment of a choice or scale slide with comment field.
*
* @param \App\Model\Entity\Slide $slide Slide
* @return bool
*/
public static function hasEditableText(Slide $slide): bool
{
return $slide->type === Slide::TYPE_OPEN || ($slide->type === Slide::TYPE_SCALE && $slide->hasComments());
return $slide->type === Slide::TYPE_OPEN || $slide->hasComments();
}
/**
* Replaces the text of the participant's own answer as long as voting on the slide is open
* (see hasEditableText()). Open question: `text`, must not be empty. Scale: `comment`, the
* rating itself stays unchanged and an empty comment removes it. Same preconditions as submit().
* (see hasEditableText()). Open question: `text`, must not be empty. Choice/scale: `comment`, the
* selection or rating itself stays unchanged and an empty comment removes it. Same preconditions as submit().
*
* @param \App\Model\Entity\Poll $poll Poll
* @param \App\Model\Entity\Slide $slide Slide
@@ -161,13 +167,17 @@ class VoteService
$text = $slide->type === Slide::TYPE_OPEN ? $this->openRows($data)[0]['text_value'] : self::comment($data);
$this->Responses->getConnection()->transactional(function () use ($slide, $participantHash, $text): void {
$this->lockSlide($slide);
// A multiple choice answer has several rows; the comment always lives in the first one.
$row = $this->Responses->find()
->where(['slide_id' => $slide->id, 'participant_hash' => $participantHash])
->orderBy(['id' => 'ASC'])
->first();
if ($row === null) {
throw new VoteException($slide->type === Slide::TYPE_OPEN
? __('Du hast hier noch nicht geantwortet.')
: __('Bitte gib zuerst deine Bewertung ab.'));
throw new VoteException(match ($slide->type) {
Slide::TYPE_OPEN => __('Du hast hier noch nicht geantwortet.'),
Slide::TYPE_CHOICE => __('Bitte gib zuerst deine Auswahl ab.'),
default => __('Bitte gib zuerst deine Bewertung ab.'),
});
}
$row->text_value = $text;
$this->Responses->saveOrFail($row);
@@ -175,7 +185,7 @@ class VoteService
}
/**
* Text of the participant's own answer: open answer or scale comment (null: none or not answered yet).
* Text of the participant's own answer: open answer or choice/scale comment (null: none or not answered yet).
*
* @param \App\Model\Entity\Slide $slide Slide
* @param string $participantHash Participant hash
@@ -186,6 +196,7 @@ class VoteService
$row = $this->Responses->find()
->select(['text_value'])
->where(['slide_id' => $slide->id, 'participant_hash' => $participantHash])
->orderBy(['id' => 'ASC'])
->disableHydration()
->first();
@@ -275,7 +286,15 @@ class VoteService
throw new VoteException(__('Bitte wähle nur eine Antwort aus.'));
}
return array_map(fn(int $id) => ['slide_option_id' => $id], $selected);
// The optional comment goes into the first row only, so it is stored once per participant;
// counts group by option and ignore text_value.
$comment = $slide->hasComments() ? self::comment($data) : null;
return array_map(
fn(int $id, int $index) => ['slide_option_id' => $id, 'text_value' => $index === 0 ? $comment : null],
$selected,
array_keys($selected),
);
}
/**
+2
View File
@@ -38,5 +38,7 @@ class AppView extends View
public function initialize(): void
{
$this->addHelper('Format');
// No generated oninvalid/oninput handlers: the CSP blocks inline event handlers.
$this->addHelper('Form', ['autoSetCustomValidity' => false]);
}
}
+12
View File
@@ -103,6 +103,18 @@ $bar = function (float $percent, bool $ok = false): string {
<?php endforeach; ?>
</tbody>
</table>
<?php if ($slide->hasComments()) : ?>
<h3><?= __n('{0} Kommentar', '{0} Kommentare', count($r['comments']), count($r['comments'])) ?></h3>
<?php if ($r['comments'] === []) : ?>
<p class="empty"><?= __('Keine Kommentare.') ?></p>
<?php else : ?>
<ol class="list">
<?php foreach ($r['comments'] as $comment) : ?>
<li><?= nl2br(h($comment['text'])) ?></li>
<?php endforeach; ?>
</ol>
<?php endif; ?>
<?php endif; ?>
<?php elseif ($slide->type === 'quiz') : ?>
<?php if (!$r['revealed']) : ?>
+5 -1
View File
@@ -143,7 +143,11 @@ $hasInternal = array_filter($slides, fn($slide) => !$slide->is_hidden && $slide-
]) ?>
<?php endif; ?>
<?php if (($slide->type === 'open' || $slide->isPrivate() || $slide->hasComments()) && $count > 0) :
$answersLabel = $slide->type === 'scale' ? __('Auswertung') : __('Antworten'); ?>
$answersLabel = match ($slide->type) {
'scale' => __('Auswertung'),
'choice' => __('Kommentare'),
default => __('Antworten'),
}; ?>
<a class="button button--small button--icon" href="<?= $this->Url->build($url('slides:answers', ['id' => $slide->id])) ?>"
title="<?= h($answersLabel) ?>" aria-label="<?= h(__('{0} der Folie „{1}“ ansehen', $answersLabel, $slide->question)) ?>">📊</a>
<?php endif; ?>
+8 -1
View File
@@ -266,7 +266,9 @@ $countdown = function (?int $remaining): string {
aria-describedby="edit-text-hint"><?= h((string)$ownText) ?></textarea>
<p class="hint" id="edit-text-hint"><?= $isOpen
? __('Möglich, solange die Abstimmung läuft.')
: __('Möglich, solange die Abstimmung läuft. Ein leeres Feld entfernt deinen Kommentar, deine Bewertung bleibt.') ?></p>
: ($slide->type === 'choice'
? __('Möglich, solange die Abstimmung läuft. Ein leeres Feld entfernt deinen Kommentar, deine Auswahl bleibt.')
: __('Möglich, solange die Abstimmung läuft. Ein leeres Feld entfernt deinen Kommentar, deine Bewertung bleibt.')) ?></p>
<?= $this->Form->button($isOpen ? __('Antwort speichern') : __('Kommentar speichern'), ['class' => 'button button--primary button--block']) ?>
<?= $this->Form->end() ?>
</details>
@@ -290,6 +292,11 @@ $countdown = function (?int $remaining): string {
</label>
<?php endforeach; ?>
</div>
<?php if ($slide->hasComments()) : ?>
<label class="scale-comment" for="choice-comment"><?= __('Kommentar (optional)') ?></label>
<textarea id="choice-comment" name="comment" rows="3" maxlength="500"
placeholder="<?= __('Möchtest du deine Auswahl begründen?') ?>"></textarea>
<?php endif; ?>
<?php elseif ($slide->type === 'open') : ?>
<textarea name="text" rows="4" maxlength="500" required
+23 -2
View File
@@ -9,13 +9,18 @@
* @var \App\Model\Entity\Slide $slide
* @var list<array{text: string, created: string}> $answers
* @var array<string, mixed>|null $scale Distribution of a scale slide, null for open questions
* @var list<array{id: int, text: string, value: int, created: string}> $comments Comments of a scale, oldest first
* @var list<array{id: int, text: string, value: int|null, created: string}> $comments Comments of a scale or choice slide, oldest first
*/
use Cake\I18n\DateTime;
$this->assign('title', $slide->question);
$this->assign('noindex', '1');
$count = $scale !== null ? array_sum(array_column($scale['buckets'], 'count')) : count($answers);
$isChoice = $slide->type === 'choice';
$count = match (true) {
$scale !== null => array_sum(array_column($scale['buckets'], 'count')),
$isChoice => count($comments),
default => count($answers),
};
?>
<p><a href="<?= $this->Url->build(['_name' => 'admin', 'token' => $adminToken]) ?>">← <?= __('Zurück zur Verwaltung') ?></a></p>
@@ -27,6 +32,8 @@ $count = $scale !== null ? array_sum(array_column($scale['buckets'], 'count')) :
<h1><?= h($slide->question) ?></h1>
<?php if ($scale !== null) : ?>
<p class="muted"><?= __n('{0} Bewertung', '{0} Bewertungen', $count, $count) ?></p>
<?php elseif ($isChoice) : ?>
<p class="muted"><?= __n('{0} Kommentar, neueste zuerst', '{0} Kommentare, neueste zuerst', $count, $count) ?></p>
<?php else : ?>
<p class="muted"><?= __n('{0} Antwort, neueste zuerst', '{0} Antworten, neueste zuerst', $count, $count) ?></p>
<?php endif; ?>
@@ -85,6 +92,20 @@ $count = $scale !== null ? array_sum(array_column($scale['buckets'], 'count')) :
</ol>
<?php endif; ?>
<?php endif; ?>
<?php elseif ($isChoice) : ?>
<?php if ($comments === []) : ?>
<p class="empty"><?= __('Noch keine Kommentare.') ?></p>
<?php else : ?>
<ol class="answers-page" reversed>
<?php foreach (array_reverse($comments) as $comment) :
$created = new DateTime($comment['created']); ?>
<li>
<?= h($comment['text']) ?>
<time datetime="<?= h($comment['created']) ?>"><?= h($created->i18nFormat('dd.MM.yyyy, HH:mm')) ?></time>
</li>
<?php endforeach; ?>
</ol>
<?php endif; ?>
<?php elseif ($answers === []) : ?>
<p class="empty"><?= __('Noch keine Antworten.') ?></p>
<?php else : ?>
+17 -3
View File
@@ -10,6 +10,7 @@
* @var string $optionsText
* @var list<array{label: string, correct: bool}> $quizOptions
* @var list<string> $orderOptions Ordering slide: labels in the correct order
* @var string $preparedText Q&A slide: questions entered beforehand, one per line
* @var bool|null $hasResponses
*/
@@ -131,6 +132,12 @@ $optionsError = $slide->getError('options_text');
'label' => __('Mehrfachauswahl erlauben'),
'checked' => (bool)$settings['multiple'],
]) ?>
<?= $this->Form->control('settings.comments', [
'type' => 'checkbox',
'label' => __('Kommentarfeld anzeigen (Teilnehmende können ihre Auswahl optional begründen)'),
'checked' => (bool)$settings['comments'],
]) ?>
<p class="hint"><?= __('Die Kommentare laufen in der Präsentation nacheinander unter dem Ergebnis durch (nicht bei den Teilnehmenden). Das Tempo stellst du für die ganze Umfrage in den Einstellungen im Dashboard ein.') ?></p>
<?php elseif ($slide->type === 'open') : ?>
<?= $this->Form->control('settings.private', [
'type' => 'checkbox',
@@ -213,8 +220,8 @@ $optionsError = $slide->getError('options_text');
<?php elseif ($slide->type === 'quiz') :
$quizError = $slide->getError('quiz_options');
$rows = $quizOptions;
// Always offer a few empty rows (more via "Antwort hinzufügen" with JS).
$rowCount = min(\App\Model\Table\SlidesTable::MAX_QUIZ_OPTIONS, max(4, count($rows) + 1));
// Offer the two required rows (more via "Antwort hinzufügen" with JS), plus one spare when editing.
$rowCount = min(\App\Model\Table\SlidesTable::MAX_QUIZ_OPTIONS, max(2, count($rows) + 1));
$rows = array_pad($rows, $rowCount, ['label' => '', 'correct' => false]);
?>
<fieldset class="quiz-options<?= $quizError ? ' error' : '' ?>" data-quiz-options
@@ -265,7 +272,7 @@ $optionsError = $slide->getError('options_text');
<?php elseif ($slide->isOrder()) :
$orderError = $slide->getError('order_options');
$max = \App\Model\Table\SlidesTable::MAX_ORDER_OPTIONS;
$rows = array_pad($orderOptions, min($max, max(4, count($orderOptions) + 1)), '');
$rows = array_pad($orderOptions, min($max, max(2, count($orderOptions) + 1)), '');
?>
<fieldset class="order-options<?= $orderError ? ' error' : '' ?>" data-order-options data-max="<?= $max ?>"
aria-describedby="order-options-hint<?= $orderError ? ' order-options-error' : '' ?>">
@@ -330,6 +337,13 @@ $optionsError = $slide->getError('options_text');
'aria-describedby' => 'qa-self-upvote-hint',
]) ?>
<p class="hint" id="qa-self-upvote-hint"><?= __('Sinnvoll, wenn ihr Themen priorisiert („Was besprechen wir heute?“). Bei normalen Fragerunden lieber aus: Sonst landen oft die Fragen derjenigen vorn, die alle Stimmen sich selbst geben.') ?></p>
<?php if ($slide->qaStage() === \App\Model\Entity\Slide::QA_COLLECT) : ?>
<div class="input textarea">
<label for="prepared-text"><?= __('Vorab eingereichte Fragen (optional, eine pro Zeile, max. {0})', \App\Service\QaService::MAX_PREPARED) ?></label>
<textarea id="prepared-text" name="prepared_text" rows="5" aria-describedby="prepared-hint"><?= h($preparedText) ?></textarea>
<p class="hint" id="prepared-hint"><?= __('Z. B. Fragen, die dich vorab per E-Mail erreicht haben. Sie erscheinen wie Fragen der Teilnehmenden, ohne dass jemand sie bearbeiten kann. Gleiche Fragen werden nur einmal aufgenommen. Zeilen, die du hier entfernst, verschwinden wieder.') ?></p>
</div>
<?php endif; ?>
<p class="hint"><?= __('Ablauf in der Präsentation: 1. Fragen sammeln, 2. abstimmen, 3. besprechen – die Frage mit den meisten Upvotes zuerst. Ohne Upvotes entfällt Schritt 2. Du schaltest die Schritte selbst weiter.') ?></p>
<?php endif; ?>
@@ -107,7 +107,7 @@ class AdminControllerTest extends TestCase
$slide = $this->slidesTable()->find()->contain(['SlideOptions'])->firstOrFail();
$this->assertSame($poll->id, $slide->poll_id);
$this->assertSame(['Pizza', 'Pasta'], array_map(fn($o) => $o->label, $slide->slide_options));
$this->assertSame(['multiple' => true], $slide->settings);
$this->assertSame(['multiple' => true, 'comments' => false], $slide->settings);
$this->assertSame(1, $slide->position);
}
@@ -64,6 +64,8 @@ class AdminFragmentTest extends TestCase
$this->assertResponseNotContains('onclick=');
$this->assertResponseContains('data-confirm=');
// Required fields (settings form) must not get generated oninvalid/oninput handlers, the CSP blocks them.
$this->assertDoesNotMatchRegularExpression('/\son[a-z]+="/', (string)$this->_response->getBody());
}
public function testSlideFormFragmentIsTheDialogContent(): void
@@ -0,0 +1,213 @@
<?php
declare(strict_types=1);
namespace App\Test\TestCase\Controller;
use App\Model\Entity\Poll;
use App\Model\Entity\Slide;
use App\Model\Table\SlidesTable;
use App\Service\ResultsService;
use App\Service\VoteException;
use App\Service\VoteService;
use App\Test\TestCase\PlenarioTestTrait;
use Cake\TestSuite\IntegrationTestTrait;
use Cake\TestSuite\TestCase;
/**
* Multiple choice slides with an optional comment field (stored once per participant in the first row).
*/
class ChoiceCommentsTest extends TestCase
{
use IntegrationTestTrait;
use PlenarioTestTrait;
/**
* @var list<string>
*/
protected array $fixtures = ['app.Polls', 'app.Slides', 'app.SlideOptions', 'app.Responses'];
protected function setUp(): void
{
parent::setUp();
$this->enableCsrfToken();
}
/**
* @param array<string, mixed> $settings Extra settings
* @return array{0: \App\Model\Entity\Poll, 1: string, 2: \App\Model\Entity\Slide}
*/
protected function choiceWithComments(array $settings = ['comments' => true, 'multiple' => true]): array
{
[$poll, $token] = $this->createPoll();
$slide = $this->createSlide($poll, Slide::TYPE_CHOICE, ['settings' => $settings], ['Ja', 'Nein', 'Vielleicht']);
$poll = $this->goLive($poll, $slide);
return [$poll, $token, $slide];
}
protected function hash(string $char, Poll $poll): string
{
return VoteService::participantHash(str_repeat($char, 32), $poll->id);
}
public function testSettingIsSanitized(): void
{
$this->assertTrue(SlidesTable::sanitizeSettings(Slide::TYPE_CHOICE, ['comments' => '1'])['comments']);
$this->assertFalse(SlidesTable::sanitizeSettings(Slide::TYPE_CHOICE, [])['comments']);
}
public function testFormShowsAndSavesCommentSetting(): void
{
[, $token] = $this->createPoll();
$this->get("/admin/$token/slides/add?type=choice");
$this->assertResponseContains('name="settings[comments]"');
$this->post("/admin/$token/slides/add?type=choice", [
'type' => 'choice',
'question' => 'Was nehmen wir?',
'options_text' => "Ja\nNein",
'settings' => ['comments' => '1'],
]);
$slide = $this->slidesTable()->find()->firstOrFail();
$this->assertTrue($slide->hasComments());
}
public function testParticipantPageShowsCommentFieldOnlyWhenEnabled(): void
{
[$poll] = $this->choiceWithComments();
$this->get('/p/' . $poll->join_code);
$this->assertResponseContains('name="comment"');
[$other] = $this->choiceWithComments(['multiple' => true]);
$this->get('/p/' . $other->join_code);
$this->assertResponseNotContains('name="comment"');
}
public function testCommentIsStoredOnceInFirstRowAndCountsStayCorrect(): void
{
[$poll, , $slide] = $this->choiceWithComments();
$options = array_map(fn($o) => $o->id, $slide->slide_options);
(new VoteService())->submit($poll, $slide, $this->hash('a', $poll), [
'option_ids' => [$options[0], $options[2]],
'comment' => ' Weil <deshalb> ',
]);
$rows = $this->slidesTable()->Responses->find()->where(['slide_id' => $slide->id])->orderBy(['id' => 'ASC'])->all()->toList();
$this->assertCount(2, $rows);
$this->assertSame('Weil <deshalb>', $rows[0]->text_value);
$this->assertNull($rows[1]->text_value);
$results = (new ResultsService())->forSlide($slide);
$this->assertSame([1, 0, 1], array_column($results['options'], 'count'));
$this->assertSame(2, $results['votes']);
$this->assertSame(1, $results['participants']);
$this->assertSame(['Weil <deshalb>'], array_column($results['comments'], 'text'));
$this->assertSame([null], array_column($results['comments'], 'value'));
}
public function testCommentIsIgnoredWithoutCommentField(): void
{
[$poll, , $slide] = $this->choiceWithComments(['multiple' => false]);
(new VoteService())->submit($poll, $slide, $this->hash('a', $poll), [
'option_id' => $slide->slide_options[0]->id,
'comment' => 'Eingeschmuggelt',
]);
$row = $this->slidesTable()->Responses->find()->where(['slide_id' => $slide->id])->firstOrFail();
$this->assertNull($row->text_value);
$this->assertSame([], (new ResultsService())->forSlide($slide)['comments']);
}
public function testTooLongCommentIsRejected(): void
{
[$poll, , $slide] = $this->choiceWithComments();
$this->expectException(VoteException::class);
(new VoteService())->submit($poll, $slide, $this->hash('a', $poll), [
'option_ids' => [$slide->slide_options[0]->id],
'comment' => str_repeat('x', VoteService::MAX_TEXT_LENGTH + 1),
]);
}
public function testCommentCanBeEditedAddedAndRemoved(): void
{
[$poll, , $slide] = $this->choiceWithComments();
$hash = $this->hash('a', $poll);
$votes = new VoteService();
$votes->submit($poll, $slide, $hash, [
'option_ids' => [$slide->slide_options[0]->id, $slide->slide_options[1]->id],
]);
$this->assertNull($votes->ownText($slide, $hash));
$votes->editText($poll, $slide, $hash, ['comment' => 'Nachgereicht']);
$this->assertSame('Nachgereicht', $votes->ownText($slide, $hash));
$votes->editText($poll, $slide, $hash, ['comment' => 'Korrigiert']);
$this->assertSame(['Korrigiert'], array_column((new ResultsService())->comments($slide), 'text'));
$this->assertSame(2, $this->slidesTable()->Responses->find()->where(['slide_id' => $slide->id])->count());
$votes->editText($poll, $slide, $hash, ['comment' => '']);
$this->assertNull($votes->ownText($slide, $hash));
$this->assertSame([], (new ResultsService())->comments($slide));
}
public function testEditRequiresAnAnswer(): void
{
[$poll, , $slide] = $this->choiceWithComments();
$this->expectException(VoteException::class);
(new VoteService())->editText($poll, $slide, $this->hash('z', $poll), ['comment' => 'Ohne Auswahl']);
}
public function testPresenterGetsCommentsButParticipantsNever(): void
{
[$poll, $token, $slide] = $this->choiceWithComments();
(new VoteService())->submit($poll, $slide, $this->hash('a', $poll), [
'option_ids' => [$slide->slide_options[0]->id],
'comment' => 'Sichtbar auf der Bühne',
]);
$this->get("/admin/$token/state");
$results = json_decode((string)$this->_response->getBody(), true)['results'];
$this->assertSame(['Sichtbar auf der Bühne'], array_column($results['comments'], 'text'));
$this->get('/p/' . $poll->join_code . '/state');
$state = json_decode((string)$this->_response->getBody(), true);
$this->assertNull($state['results']);
$this->assertStringNotContainsString('Sichtbar auf der Bühne', (string)$this->_response->getBody());
}
public function testAnswersPageListsCommentsOfChoiceSlides(): void
{
[$poll, $token, $slide] = $this->choiceWithComments();
(new VoteService())->submit($poll, $slide, $this->hash('a', $poll), [
'option_ids' => [$slide->slide_options[0]->id],
'comment' => 'Erster <Kommentar>',
]);
$this->get("/admin/$token/slides/{$slide->id}/answers");
$this->assertResponseOk();
$this->assertResponseContains('Erster &lt;Kommentar&gt;');
}
public function testAnswersPageIsNotFoundForChoiceWithoutComments(): void
{
[, $token, $slide] = $this->choiceWithComments(['multiple' => false]);
$this->get("/admin/$token/slides/{$slide->id}/answers");
$this->assertResponseCode(404);
}
public function testExportContainsComments(): void
{
[$poll, $token, $slide] = $this->choiceWithComments();
(new VoteService())->submit($poll, $slide, $this->hash('a', $poll), [
'option_ids' => [$slide->slide_options[0]->id],
'comment' => 'Im PDF enthalten',
]);
$this->assertStringContainsString('Im PDF enthalten', $this->exportHtml($token));
}
}
@@ -0,0 +1,123 @@
<?php
declare(strict_types=1);
namespace App\Test\TestCase\Controller;
use App\Model\Entity\Slide;
use App\Service\PollStateService;
use App\Service\QaService;
use App\Service\VoteService;
use App\Test\TestCase\PlenarioTestTrait;
use Cake\ORM\TableRegistry;
use Cake\TestSuite\IntegrationTestTrait;
use Cake\TestSuite\TestCase;
/**
* Questions the admin enters beforehand on a Q&A slide (textarea `prepared_text`).
*/
class QaPreparedTest extends TestCase
{
use IntegrationTestTrait;
use PlenarioTestTrait;
/**
* @var list<string>
*/
protected array $fixtures = ['app.Polls', 'app.Slides', 'app.SlideOptions', 'app.Responses'];
protected function setUp(): void
{
parent::setUp();
$this->enableCsrfToken();
}
public function testParsePreparedCleansLines(): void
{
$texts = QaService::parsePrepared(" Wann geht's los? \n\nwann geht's LOS?\r\nZweite Frage");
$this->assertSame(["Wann geht's los?", 'Zweite Frage'], $texts);
}
public function testCreatingSlideStoresPreparedQuestions(): void
{
[$poll, $token] = $this->createPoll();
$this->post("/admin/$token/slides/add", [
'type' => Slide::TYPE_QA,
'question' => 'Fragen',
'prepared_text' => "Frage A\nFrage B",
]);
$this->assertRedirect();
$slide = $this->slidesTable()->listForPoll($poll->id)[0];
$this->assertSame(['Frage A', 'Frage B'], (new QaService())->preparedQuestions($slide));
}
public function testEditSyncsAndIsIdempotent(): void
{
[$poll, $token] = $this->createPoll();
$slide = $this->createSlide($poll, Slide::TYPE_QA);
$url = "/admin/$token/slides/{$slide->id}/edit";
$data = ['question' => 'Fragen', 'prepared_text' => "Frage A\nFrage B"];
$this->post($url, $data);
$responses = TableRegistry::getTableLocator()->get('Responses');
$ids = $responses->find()->where(['slide_id' => $slide->id])->all()->extract('id')->toList();
$this->assertCount(2, $ids);
$this->post($url, $data);
$this->assertSame($ids, $responses->find()->where(['slide_id' => $slide->id])->all()->extract('id')->toList());
$this->post($url, ['prepared_text' => "Frage B\nFrage C"] + $data);
$this->assertSame(['Frage B', 'Frage C'], (new QaService())->preparedQuestions($slide));
}
public function testParticipantQuestionsAreKeptAndNotDuplicated(): void
{
[$poll, $token] = $this->createPoll();
$slide = $this->createSlide($poll, Slide::TYPE_QA);
$poll = $this->goLive($poll, $slide);
$hash = VoteService::participantHash(str_repeat('a', 32), $poll->id);
(new VoteService())->submit($poll, $slide, $hash, ['question' => 'Eigene Frage']);
$this->post("/admin/$token/slides/{$slide->id}/edit", [
'question' => 'Fragen',
'prepared_text' => "eigene frage\nVorab",
]);
$this->post("/admin/$token/slides/{$slide->id}/edit", ['question' => 'Fragen', 'prepared_text' => '']);
$responses = TableRegistry::getTableLocator()->get('Responses');
$this->assertSame(
['Eigene Frage'],
$responses->find()->where(['slide_id' => $slide->id])->all()->extract('text_value')->toList(),
);
}
public function testPreparedQuestionsAppearForParticipantsButNotAsOwn(): void
{
[$poll] = $this->createPoll();
$slide = $this->createSlide($poll, Slide::TYPE_QA);
(new QaService())->syncPrepared($slide, ['Vorab']);
$poll = $this->goLive($poll, $slide);
$slide = $this->slidesTable()->get($slide->id);
$hash = VoteService::participantHash(str_repeat('b', 32), $poll->id);
$qa = (new PollStateService())->qaState($slide, $hash);
$this->assertCount(1, $qa['questions']);
$this->assertSame([], $qa['mine']);
$this->assertSame(0, TableRegistry::getTableLocator()->get('Responses')->countParticipants($slide->id));
}
public function testNotChangedOutsideCollectStage(): void
{
[$poll, $token] = $this->createPoll();
$slide = $this->createSlide($poll, Slide::TYPE_QA);
(new QaService())->syncPrepared($slide, ['Vorab']);
(new QaService())->setStage($slide, Slide::QA_VOTE);
$this->post("/admin/$token/slides/{$slide->id}/edit", ['question' => 'Fragen', 'prepared_text' => '']);
$this->assertSame(['Vorab'], (new QaService())->preparedQuestions($slide));
}
}
+16
View File
@@ -110,6 +110,22 @@ class QuizTest extends TestCase
$this->assertSame(Slide::QUIZ_FINISHED, $slide->quizPhase());
}
public function testReadyQuizHidesAnswerOptions(): void
{
[$poll, $slide] = $this->createQuiz();
$results = (new ResultsService())->forSlide($slide);
$this->assertSame('ready', $results['phase']);
$this->assertSame([], $results['options']);
$state = $this->participantState($poll, 'p1');
$this->assertStringNotContainsString('Berlin', (string)json_encode($state));
$slide = $this->setOpen($slide, true);
$results = (new ResultsService())->forSlide($slide);
$this->assertSame(['Berlin', 'Hamburg', 'München'], array_column($results['options'], 'label'));
}
public function testRunningQuizHidesCountsAndCorrectAnswers(): void
{
[$poll, $slide] = $this->createQuiz();
+9 -3
View File
@@ -610,7 +610,7 @@
choice: function (results) {
var max = Math.max.apply(null, results.options.map(function (o) { return o.count; }).concat([1]));
return el('div', { class: 'bars' }, results.options.map(function (option, index) {
var bars = el('div', { class: 'bars' }, results.options.map(function (option, index) {
return el('div', { class: 'bar bar--c' + (index % 6) }, [
el('div', { class: 'bar__label', text: option.label }),
el('div', { class: 'bar__track' }, [
@@ -619,6 +619,10 @@
el('div', { class: 'bar__value', text: formatNumber(option.percent) + ' % (' + option.count + ')' })
]);
}));
if (!results.comments || !results.comments.length) {
return bars;
}
return el('div', { class: 'choice-results' }, [bars, Comments.render(results.comments, String)]);
},
/**
@@ -892,7 +896,8 @@
} else if (results.phase === 'running') {
children.push(el('p', { class: 'quiz-status', text: 'Quiz läuft – ohne Zeitlimit' }));
} else {
children.push(el('p', { class: 'quiz-status', text: 'Bereit – starte das Quiz, um die Antworten freizugeben' }));
children.push(el('p', { class: 'quiz-status', text: 'Bereit – die Antworten erscheinen, sobald das Quiz gestartet wird' }));
return el('div', { class: 'quiz-results quiz-results--' + results.phase }, children);
}
children.push(el('ol', { class: 'quiz-grid' }, results.options.map(function (option, index) {
return el('li', { class: 'quiz-tile quiz-tile--c' + (index % 6), text: option.label });
@@ -2721,7 +2726,8 @@
if (submitter) {
submitter.disabled = true;
}
Fragments.request(form.action, { method: 'POST', body: new FormData(form) })
// getAttribute: forms with a field named "action" (play/pause buttons) shadow the form.action property.
Fragments.request(form.getAttribute('action'), { method: 'POST', body: new FormData(form) })
.then(function (doc) { return handle(doc, source); })
.catch(function () {
form.removeAttribute('aria-busy');