Merge pull request 'Feature/private scale' (#18) from feature/private-scale into main
CI / Deploy / test (push) Successful in 48s
CI / Deploy / deploy (push) Successful in 8s

Reviewed-on: #18
This commit was merged in pull request #18.
This commit is contained in:
gnilebein committed 2026-11-08 18:38:01 +01:00
commit 5cd1be1cf8
16 files changed
+732 -30

No files matched your search

+11 -1
View File
@@ -55,7 +55,7 @@ src/
HomeController Startseite, Anlegen (/create), Bestätigung, Join, Recover
AdminAppController Basis für /admin/{token}: löst Poll über Token-Hash auf (404 sonst), setzt Privacy-Header
AdminController Dashboard, Settings, Present, State-JSON, Control, QR, CSV-Export, Token rotieren, Löschen
SlidesController Folien-CRUD, Antworten offener Fragen (`answers`), Sortieren (Drag & Drop/Pfeiltasten via `reorder`, JSON; erfordert JS), Antworten zurücksetzen,
SlidesController Folien-CRUD, Antworten offener Fragen bzw. Skala-Auswertung (`answers`), Sortieren (Drag & Drop/Pfeiltasten via `reorder`, JSON; erfordert JS), Antworten zurücksetzen,
YouTube-Link prüfen (`youtubeCheck`, JSON)
ParticipateController /p/{code}: Ansicht, State-JSON, Abstimmen; anonymes Cookie plenario_pid
EmbedController /e/{key}/{id}: eine Folie zum Einbetten (z. B. Canva), activate/heartbeat/pause/control
@@ -92,6 +92,7 @@ tests/ PHPUnit; PlenarioTestTrait erzeugt Testdaten, Fixtures
Mehrfachauswahl/mehrere Wörter = mehrere Zeilen mit gleichem `participant_hash`.
Q&A: Frage = Zeile mit `text_value`, Upvote = Zeile mit `parent_id` (= id der Frage, FK mit CASCADE).
Reihenfolge: eine Zeile pro Person, `text_value` = Options-ids kommagetrennt (`VoteService::parseOrder()`).
Skala: `numeric_value`, optional Kommentar in `text_value`.
### Zentrale Regeln (nicht versehentlich brechen)
@@ -168,6 +169,15 @@ tests/ PHPUnit; PlenarioTestTrait erzeugt Testdaten, Fixtures
Presenter-/Embed-JSON (`results.answers` leer, nur `participants`) und nie bei Teilnehmenden (keine `results`,
unabhängig von `show_results_to_participants`). Lesen nur in der Verwaltung (`slides:answers`,
`ResultsService::answers()`) und im CSV-Export.
- **Internes Feedback** (Skala mit Setting `private`, ebenfalls `Slide::isPrivate()`): Presenter-/Embed-JSON enthält
`buckets: []` und `average: null` (nur `participants`), Teilnehmende bekommen keine `results`. Verteilung und
Durchschnitt nur in der Verwaltung (`slides:answers` → „Auswertung“, `ResultsService::scaleResults()`) und im CSV-Export.
- **Skala-Kommentare** (Setting `comments`, `Slide::hasComments()`): optionales Feld `comment`, gespeichert als `text_value`
in derselben Zeile wie `numeric_value` (ohne Setting wird es ignoriert). Öffentliche Skalen liefern im Presenter-/Embed-State
`results.comments` (Teilnehmende bekommen immer `[]`, `PollStateService::participantResults()`)
(älteste zuerst, je `id`, `text`, `value` – `value` nur mit Setting `comment_ratings`, sonst `null`); `Comments` in `plenario.js` blättert sie automatisch durch („Kommentar X von N“,
vor/zurück/Pause, Zustand übersteht das Neu-Rendern beim Polling). Bei internem Feedback bleibt `comments` leer,
lesbar nur in der Auswertung (`ResultsService::comments()`) und im CSV-Export.
### Neuen Folientyp hinzufügen (Checkliste)
+2
View File
@@ -310,6 +310,8 @@ class AdminController extends AdminAppController
$response->slide_option_id !== null => $labels[$response->slide_option_id] ?? '',
$response->text_value !== null && $response->numeric_value === VoteService::DOWNVOTE
=> __('Downvote: {0}', $response->text_value),
$slide->type === Slide::TYPE_SCALE && $response->text_value !== null
=> __('{0} (Kommentar: {1})', $response->numeric_value, $response->text_value),
$response->numeric_value !== null => (string)$response->numeric_value,
default => (string)$response->text_value,
};
+7 -3
View File
@@ -164,7 +164,8 @@ class SlidesController extends AdminAppController
}
/**
* All answers of an open question (also anonymous feedback, which is never shown on the stage).
* All answers of an open question or the ratings of a scale
* (also anonymous/internal feedback, which is never shown on the stage).
*
* @param string $id Slide id
* @return void
@@ -172,11 +173,14 @@ class SlidesController extends AdminAppController
public function answers(string $id): void
{
$slide = $this->loadSlide($id);
if ($slide->type !== Slide::TYPE_OPEN) {
if (!in_array($slide->type, [Slide::TYPE_OPEN, Slide::TYPE_SCALE], true)) {
throw new NotFoundException(__('Folie nicht gefunden.'));
}
$results = new ResultsService();
$this->set('slide', $slide);
$this->set('answers', (new ResultsService())->answers($slide));
$this->set('answers', $slide->type === Slide::TYPE_OPEN ? $results->answers($slide) : []);
$this->set('scale', $slide->type === Slide::TYPE_SCALE ? $results->scaleResults($slide) : null);
$this->set('comments', $slide->hasComments() ? $results->comments($slide) : []);
}
/**
+20 -4
View File
@@ -84,7 +84,13 @@ class Slide extends Entity
self::TYPE_WORDCLOUD => ['allow_upvotes' => true, 'allow_downvotes' => true],
// private: anonymous feedback, answers only visible in the admin area (never on the stage)
self::TYPE_OPEN => ['private' => false],
self::TYPE_SCALE => ['scale_min' => 1, 'scale_max' => 5, 'min_label' => '', 'max_label' => ''],
// private: internal feedback, ratings only visible in the admin area (never on the stage)
// comments: optional comment field, comments rotate in the presentation (unless private)
// comment_ratings: show the rating next to each comment in the presentation
self::TYPE_SCALE => [
'scale_min' => 1, 'scale_max' => 5, 'min_label' => '', 'max_label' => '', 'private' => false,
'comments' => false, 'comment_ratings' => false,
],
self::TYPE_CONTENT => [],
// time_limit in seconds, 0 = no limit (presenter ends the quiz)
self::TYPE_QUIZ => ['time_limit' => 30],
@@ -377,13 +383,23 @@ class Slide extends Entity
}
/**
* Open question collecting anonymous feedback: answers are never shown on the
* presenter screen or to participants, only in the admin area and the CSV export.
* Open question or scale collecting anonymous/internal feedback: answers and ratings are
* never shown on the presenter screen or to participants, only in the admin area and the CSV export.
*
* @return bool
*/
public function isPrivate(): bool
{
return $this->type === self::TYPE_OPEN && (bool)$this->setting('private');
return in_array($this->type, [self::TYPE_OPEN, self::TYPE_SCALE], true) && (bool)$this->setting('private');
}
/**
* Scale with an optional comment field for participants.
*
* @return bool
*/
public function hasComments(): bool
{
return $this->type === self::TYPE_SCALE && (bool)$this->setting('comments');
}
}
+3
View File
@@ -156,6 +156,9 @@ class SlidesTable extends Table
$settings['scale_max'] = $max;
$settings['min_label'] = mb_substr(trim((string)($input['min_label'] ?? '')), 0, 60);
$settings['max_label'] = mb_substr(trim((string)($input['max_label'] ?? '')), 0, 60);
$settings['private'] = filter_var($input['private'] ?? false, FILTER_VALIDATE_BOOLEAN);
$settings['comments'] = filter_var($input['comments'] ?? false, FILTER_VALIDATE_BOOLEAN);
$settings['comment_ratings'] = filter_var($input['comment_ratings'] ?? false, FILTER_VALIDATE_BOOLEAN);
break;
case Slide::TYPE_QUIZ:
$limit = (int)($input['time_limit'] ?? $settings['time_limit']);
+17 -1
View File
@@ -187,7 +187,7 @@ class PollStateService
$slide?->modified?->toUnixString() ?? 0,
]),
'slide' => $showResults ? $this->slidePayload($slide) : null,
'results' => $showResults ? $this->results->forSlide($slide) : null,
'results' => $showResults ? $this->participantResults($slide) : null,
'words' => $words,
'quiz' => $quiz,
'qa' => $qa,
@@ -195,6 +195,22 @@ class PollStateService
];
}
/**
* Results as participants see them: scale comments are for the presentation only.
*
* @param \App\Model\Entity\Slide $slide Current slide
* @return array<string, mixed>
*/
protected function participantResults(Slide $slide): array
{
$results = $this->results->forSlide($slide);
if (isset($results['comments'])) {
$results['comments'] = [];
}
return $results;
}
/**
* Ordering progress of one participant. Own answer and correctness only once
* revealed (voting closed); before that the state must not hint at the solution.
+72 -1
View File
@@ -19,7 +19,12 @@ use Cake\ORM\Locator\LocatorAwareTrait;
* - open: 'answers' => [['text', 'created']] newest first, 'private' (bool);
* private (anonymous feedback): 'answers' is always empty, texts only via answers()
* - scale: 'buckets' => [['value', 'count', 'percent']], 'average' => float|null,
* 'min', 'max', 'minLabel', 'maxLabel'
* 'min', 'max', 'minLabel', 'maxLabel', 'private' (bool);
* 'comments' => [['id', 'text', 'value' (int|null)]] oldest first (only with the comment field, else [];
* 'value' is null unless the setting comment_ratings is on;
* presentation only, emptied for participants in PollStateService);
* private (internal feedback): 'buckets' and 'comments' are always empty and 'average' null,
* ratings and comments only via scaleResults() / comments()
* - quiz: 'phase' (ready|running|finished), 'timeLimit' (s, 0 = manual), 'remaining' (s|null),
* 'revealed' (bool), 'options' => [['id', 'label']] while not finished;
* once finished additionally per option 'count', 'percent', 'correct' (bool)
@@ -307,6 +312,72 @@ class ResultsService
* @return array<string, mixed>
*/
protected function scale(Slide $slide): array
{
if (!$slide->isPrivate()) {
$showRatings = (bool)$slide->setting('comment_ratings');
$comments = [];
foreach ($slide->hasComments() ? $this->comments($slide, self::MAX_ANSWERS) : [] as $comment) {
$comments[] = [
'id' => $comment['id'],
'text' => $comment['text'],
'value' => $showRatings ? $comment['value'] : null,
];
}
return $this->scaleResults($slide) + ['private' => false, 'comments' => $comments];
}
return [
'buckets' => [],
'average' => null,
'min' => (int)$slide->setting('scale_min'),
'max' => (int)$slide->setting('scale_max'),
'minLabel' => (string)$slide->setting('min_label'),
'maxLabel' => (string)$slide->setting('max_label'),
'private' => true,
'comments' => [],
];
}
/**
* Comments of a scale with their rating, oldest first – also of private slides,
* so the unfiltered call is only for the admin area.
*
* @param \App\Model\Entity\Slide $slide Scale slide
* @param int|null $limit Max. comments (the newest ones), null = all
* @return list<array{id: int, text: string, value: int, created: string}>
*/
public function comments(Slide $slide, ?int $limit = null): array
{
$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])
->orderBy(['id' => 'DESC']);
if ($limit !== null) {
$query->limit($limit);
}
$comments = [];
foreach ($query->all() as $row) {
$comments[] = [
'id' => (int)$row->id,
'text' => (string)$row->text_value,
'value' => (int)$row->numeric_value,
'created' => $row->created->toIso8601String(),
];
}
return array_reverse($comments);
}
/**
* Distribution and average of a scale – also of private slides,
* so only for the admin area (never for the presenter screen or participants).
*
* @param \App\Model\Entity\Slide $slide Scale slide
* @return array{buckets: list<array{value: int, count: int, percent: float|int}>, average: float|null, min: int, max: int, minLabel: string, maxLabel: string}
*/
public function scaleResults(Slide $slide): array
{
$min = (int)$slide->setting('scale_min');
$max = (int)$slide->setting('scale_max');
+6 -1
View File
@@ -422,7 +422,12 @@ class VoteService
if ($value === false || $value < $min || $value > $max) {
throw new VoteException(__('Bitte wähle einen Wert zwischen {0} und {1}.', $min, $max));
}
// The optional comment is stored in the same row; ignored if the slide has no comment field.
$comment = $slide->hasComments() ? trim((string)($data['comment'] ?? '')) : '';
if (mb_strlen($comment) > self::MAX_TEXT_LENGTH) {
throw new VoteException(__('Der Kommentar darf maximal {0} Zeichen lang sein.', self::MAX_TEXT_LENGTH));
}
return [['numeric_value' => $value]];
return [['numeric_value' => $value, 'text_value' => $comment === '' ? null : $comment]];
}
}
+4 -3
View File
@@ -99,7 +99,8 @@ $url = fn(string $name, array $params = []) => ['_name' => $name, 'token' => $ad
<?php elseif ($slide->isOrder() && !$slide->is_voting_open) : ?>
<span class="muted">· <?= __('Abstimmung geschlossen, aufgelöst') ?></span>
<?php elseif (!$slide->is_voting_open) : ?><span class="muted">· <?= __('Abstimmung geschlossen') ?></span><?php endif; ?>
<?php if ($slide->isPrivate()) : ?><span class="badge" title="<?= __('Antworten werden nicht öffentlich angezeigt') ?>">🔒 <?= __('anonym') ?></span><?php endif; ?>
<?php if ($slide->hasComments()) : ?><span class="badge" title="<?= __('Teilnehmende können einen Kommentar abgeben') ?>">💬 <?= __('Kommentare') ?></span><?php endif; ?>
<?php if ($slide->isPrivate()) : ?><span class="badge" title="<?= __('Antworten werden nicht öffentlich angezeigt') ?>">🔒 <?= $slide->type === 'scale' ? __('intern') : __('anonym') ?></span><?php endif; ?>
<?php endif; ?>
</div>
<a class="slide-item__title" href="<?= $this->Url->build($url('slides:edit', ['id' => $slide->id])) ?>"><?= h($slide->question) ?></a>
@@ -134,8 +135,8 @@ $url = fn(string $name, array $params = []) => ['_name' => $name, 'token' => $ad
'title' => __('Diese Folie jetzt den Teilnehmenden zeigen'),
]) ?>
<?php endif; ?>
<?php if ($slide->type === 'open' && $count > 0) : ?>
<a class="button button--small" href="<?= $this->Url->build($url('slides:answers', ['id' => $slide->id])) ?>"><?= __('Antworten') ?></a>
<?php if (($slide->type === 'open' || $slide->isPrivate() || $slide->hasComments()) && $count > 0) : ?>
<a class="button button--small" href="<?= $this->Url->build($url('slides:answers', ['id' => $slide->id])) ?>"><?= $slide->type === 'scale' ? __('Auswertung') : __('Antworten') ?></a>
<?php endif; ?>
<a class="button button--small" href="<?= $this->Url->build($url('slides:edit', ['id' => $slide->id])) ?>"><?= __('Bearbeiten') ?></a>
<?php if ($count > 0) : ?>
+12 -2
View File
@@ -35,7 +35,7 @@ $countdown = function (?int $remaining): string {
data-vote-url="<?= $this->Url->build($voteUrl) ?>"
data-interval="<?= (int)$pollIntervalMs ?>">
<p class="eyebrow center"><?= h($poll->title) ?></p>
<p class="eyebrow eyebrow--poll center"><?= h($poll->title) ?></p>
<?php if (!$poll->is_active) : ?>
<section class="card center">
@@ -239,7 +239,7 @@ $countdown = function (?int $remaining): string {
<?php endif; ?>
<?php elseif ($slide->type === 'scale') : ?>
<div class="scale">
<div class="scale"<?= $slide->isPrivate() ? ' aria-describedby="private-hint"' : '' ?>>
<?php for ($v = (int)$slide->setting('scale_min'); $v <= (int)$slide->setting('scale_max'); $v++) : ?>
<label class="scale__step">
<input type="radio" name="value" value="<?= $v ?>" required>
@@ -251,6 +251,16 @@ $countdown = function (?int $remaining): string {
<span><?= h((string)$slide->setting('min_label')) ?></span>
<span><?= h((string)$slide->setting('max_label')) ?></span>
</div>
<?php if ($slide->hasComments()) : ?>
<label class="scale-comment" for="scale-comment"><?= __('Kommentar (optional)') ?></label>
<textarea id="scale-comment" name="comment" rows="3" maxlength="500"
placeholder="<?= __('Möchtest du deine Bewertung begründen?') ?>"></textarea>
<?php endif; ?>
<?php if ($slide->isPrivate()) : ?>
<p class="hint private-hint" id="private-hint">
🔒 <?= __('Internes Feedback: Das Ergebnis wird nicht öffentlich angezeigt und deine Bewertung nicht mit deinem Namen gespeichert.') ?>
</p>
<?php endif; ?>
<?php endif; ?>
<?= $this->Form->button(__('Absenden'), ['class' => 'button button--primary button--block']) ?>
+63 -6
View File
@@ -1,34 +1,91 @@
<?php
/**
* All answers of an open question – the only place where anonymous feedback
* (private open questions) can be read, besides the CSV export.
* All answers of an open question or the ratings of a scale – the only place where
* anonymous/internal feedback (private slides) can be read, besides the CSV export.
*
* @var \App\View\AppView $this
* @var \App\Model\Entity\Poll $poll
* @var string $adminToken
* @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
*/
use Cake\I18n\DateTime;
$this->assign('title', $slide->question);
$this->assign('noindex', '1');
$count = count($answers);
$count = $scale !== null ? array_sum(array_column($scale['buckets'], 'count')) : count($answers);
?>
<p><a href="<?= $this->Url->build(['_name' => 'admin', 'token' => $adminToken]) ?>">← <?= __('Zurück zur Verwaltung') ?></a></p>
<section class="card">
<p class="eyebrow">
<?= h($slide->typeLabel()) ?>
<?php if ($slide->isPrivate()) : ?>· 🔒 <?= __('Anonymes Feedback') ?><?php endif; ?>
<?php if ($slide->isPrivate()) : ?>· 🔒 <?= $scale !== null ? __('Internes Feedback') : __('Anonymes Feedback') ?><?php endif; ?>
</p>
<h1><?= h($slide->question) ?></h1>
<?php if ($scale !== null) : ?>
<p class="muted"><?= __n('{0} Bewertung', '{0} Bewertungen', $count, $count) ?></p>
<?php else : ?>
<p class="muted"><?= __n('{0} Antwort, neueste zuerst', '{0} Antworten, neueste zuerst', $count, $count) ?></p>
<?php endif; ?>
<?php if ($slide->isPrivate()) : ?>
<p class="hint"><?= __('Diese Antworten werden weder in der Präsentation noch den Teilnehmenden angezeigt.') ?></p>
<p class="hint"><?= $scale !== null
? __('Dieses Ergebnis wird weder in der Präsentation noch den Teilnehmenden angezeigt.')
: __('Diese Antworten werden weder in der Präsentation noch den Teilnehmenden angezeigt.') ?></p>
<?php endif; ?>
<?php if ($answers === []) : ?>
<?php if ($scale !== null) : ?>
<?php if ($count === 0) : ?>
<p class="empty"><?= __('Noch keine Bewertungen.') ?></p>
<?php else : ?>
<p class="scale-average">
<?= __('Durchschnitt') ?>:
<strong><?= h($this->Number->format((float)$scale['average'], ['places' => 1, 'precision' => 1, 'locale' => 'de_DE'])) ?></strong>
<span class="muted">/ <?= (int)$scale['max'] ?></span>
</p>
<table class="scale-table">
<caption class="sr-only"><?= __('Verteilung der Bewertungen') ?></caption>
<thead>
<tr><th scope="col"><?= __('Wert') ?></th><th scope="col"><?= __('Anzahl') ?></th><th scope="col"><?= __('Anteil') ?></th></tr>
</thead>
<tbody>
<?php foreach ($scale['buckets'] as $i => $bucket) :
$label = match (true) {
$i === 0 && $scale['minLabel'] !== '' => $scale['minLabel'],
$i === count($scale['buckets']) - 1 && $scale['maxLabel'] !== '' => $scale['maxLabel'],
default => '',
}; ?>
<tr>
<th scope="row"><?= (int)$bucket['value'] ?><?php if ($label !== '') : ?> <span class="muted">(<?= h($label) ?>)</span><?php endif; ?></th>
<td><?= (int)$bucket['count'] ?></td>
<td>
<span class="scale-table__bar" style="width: <?= (float)$bucket['percent'] ?>%" aria-hidden="true"></span>
<?= h($this->Number->format((float)$bucket['percent'], ['places' => 0, 'precision' => 1, 'locale' => 'de_DE'])) ?> %
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?php endif; ?>
<?php if ($slide->hasComments()) : ?>
<h2><?= __n('{0} Kommentar', '{0} Kommentare', count($comments), count($comments)) ?></h2>
<?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']) ?>"><?= __('Bewertung {0}', $comment['value']) ?> · <?= h($created->i18nFormat('dd.MM.yyyy, HH:mm')) ?></time>
</li>
<?php endforeach; ?>
</ol>
<?php endif; ?>
<?php endif; ?>
<?php elseif ($answers === []) : ?>
<p class="empty"><?= __('Noch keine Antworten.') ?></p>
<?php else : ?>
<ol class="answers-page" reversed>
+17
View File
@@ -166,6 +166,23 @@ $optionsError = $slide->getError('options_text');
'placeholder' => __('z. B. sehr'), 'value' => $settings['max_label'],
]) ?>
</div>
<?= $this->Form->control('settings.comments', [
'type' => 'checkbox',
'label' => __('Kommentarfeld anzeigen (Teilnehmende können ihre Bewertung optional begründen)'),
'checked' => (bool)$settings['comments'],
]) ?>
<p class="hint"><?= __('Die Kommentare laufen in der Präsentation nacheinander durch (nicht bei den Teilnehmenden). Bei internem Feedback siehst du sie nur in der Auswertung.') ?></p>
<?= $this->Form->control('settings.comment_ratings', [
'type' => 'checkbox',
'label' => __('Bewertung beim Kommentar in der Präsentation anzeigen'),
'checked' => (bool)$settings['comment_ratings'],
]) ?>
<?= $this->Form->control('settings.private', [
'type' => 'checkbox',
'label' => __('Internes Feedback: Ergebnis nicht öffentlich anzeigen'),
'checked' => (bool)$settings['private'],
]) ?>
<p class="hint"><?= __('Präsentation und Teilnehmende sehen nur, wie viele Bewertungen eingegangen sind. Verteilung, Durchschnitt und Kommentare siehst nur du hier in der Verwaltung (und im CSV-Export).') ?></p>
<?php elseif ($slide->type === 'quiz') :
$quizError = $slide->getError('quiz_options');
$rows = $quizOptions;
@@ -12,7 +12,7 @@ use Cake\TestSuite\IntegrationTestTrait;
use Cake\TestSuite\TestCase;
/**
* Open questions as anonymous feedback: answers only in the admin area.
* Open questions and scales as anonymous/internal feedback: results only in the admin area.
*/
class PrivateFeedbackTest extends TestCase
{
@@ -157,4 +157,108 @@ class PrivateFeedbackTest extends TestCase
$this->assertFalse($state['results']['private']);
$this->assertSame('Offen', $state['results']['answers'][0]['text']);
}
/**
* @return array{0: \App\Model\Entity\Poll, 1: string, 2: \App\Model\Entity\Slide}
*/
protected function privateScaleWithRatings(): array
{
[$poll, $token] = $this->createPoll();
$slide = $this->createSlide($poll, Slide::TYPE_SCALE, ['settings' => ['scale_min' => 1, 'scale_max' => 5, 'private' => true]]);
$poll = $this->goLive($poll, $slide);
$votes = new VoteService();
$votes->submit($poll, $slide, VoteService::participantHash(str_repeat('a', 32), $poll->id), ['value' => 2]);
$votes->submit($poll, $slide, VoteService::participantHash(str_repeat('b', 32), $poll->id), ['value' => 5]);
return [$poll, $token, $slide];
}
public function testScaleSettingIsSanitized(): void
{
$this->assertTrue(SlidesTable::sanitizeSettings(Slide::TYPE_SCALE, ['private' => '1'])['private']);
$this->assertFalse(SlidesTable::sanitizeSettings(Slide::TYPE_SCALE, [])['private']);
[$poll] = $this->createPoll();
$this->assertFalse($this->createSlide($poll, Slide::TYPE_SCALE, ['settings' => []])->isPrivate());
}
public function testFormSavesPrivateScaleSetting(): void
{
[$poll, $token] = $this->createPoll();
$this->post("/admin/$token/slides/add?type=scale", [
'type' => 'scale',
'question' => 'Wie zufrieden bist du?',
'settings' => ['scale_min' => '1', 'scale_max' => '5', 'private' => '1'],
]);
$slide = $this->slidesTable()->find()->where(['poll_id' => $poll->id])->firstOrFail();
$this->assertTrue($slide->isPrivate());
}
public function testPresenterSeesOnlyTheScaleCount(): void
{
[, $token] = $this->privateScaleWithRatings();
$this->get("/admin/$token/state");
$state = json_decode((string)$this->_response->getBody(), true);
$this->assertTrue($state['results']['private']);
$this->assertSame([], $state['results']['buckets']);
$this->assertNull($state['results']['average']);
$this->assertSame(2, $state['results']['participants']);
}
public function testParticipantsNeverSeeScaleResults(): void
{
[$poll] = $this->privateScaleWithRatings();
$this->assertTrue($poll->show_results_to_participants);
$this->assertNull($this->participantState($poll)['results']);
$this->get('/p/' . $poll->join_code);
$this->assertResponseContains('Internes Feedback');
$this->post('/p/' . $poll->join_code . '/vote', ['slide_id' => $poll->current_slide_id, 'value' => '3']);
$this->assertNull($this->participantState($poll)['results']);
}
public function testEmbedSeesOnlyTheScaleCount(): void
{
[$poll, , $slide] = $this->privateScaleWithRatings();
$key = $this->pollsTable()->ensureEmbedKey($poll);
$this->get("/e/$key/{$slide->id}/state");
$state = json_decode((string)$this->_response->getBody(), true);
$this->assertResponseOk();
$this->assertSame([], $state['results']['buckets']);
$this->assertNull($state['results']['average']);
}
public function testAdminReadsScaleResults(): void
{
[, $token, $slide] = $this->privateScaleWithRatings();
$this->get("/admin/$token");
$this->assertResponseContains("/slides/{$slide->id}/answers");
$this->get("/admin/$token/slides/{$slide->id}/answers");
$this->assertResponseOk();
$this->assertResponseContains('Internes Feedback');
$this->assertResponseContains('3,5');
$this->assertResponseContains('2 Bewertungen');
}
public function testPublicScaleStillShowsResults(): void
{
[$poll, $token] = $this->createPoll();
$slide = $this->createSlide($poll, Slide::TYPE_SCALE, ['settings' => ['scale_min' => 1, 'scale_max' => 5]]);
$poll = $this->goLive($poll, $slide);
(new VoteService())->submit($poll, $slide, VoteService::participantHash(str_repeat('c', 32), $poll->id), ['value' => 4]);
$this->get("/admin/$token/state");
$state = json_decode((string)$this->_response->getBody(), true);
$this->assertFalse($state['results']['private']);
$this->assertEqualsWithDelta(4.0, $state['results']['average'], 0.001);
}
}
@@ -0,0 +1,224 @@
<?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\VoteException;
use App\Service\VoteService;
use App\Test\TestCase\PlenarioTestTrait;
use Cake\TestSuite\IntegrationTestTrait;
use Cake\TestSuite\TestCase;
/**
* Scale slides with an optional comment field: comments rotate in the presentation unless the scale is private.
*/
class ScaleCommentsTest 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 scaleWithComments(array $settings = []): array
{
[$poll, $token] = $this->createPoll();
$slide = $this->createSlide($poll, Slide::TYPE_SCALE, [
'settings' => $settings + ['scale_min' => 1, 'scale_max' => 5, 'comments' => true],
]);
$poll = $this->goLive($poll, $slide);
$votes = new VoteService();
$votes->submit($poll, $slide, $this->hash('a', $poll), ['value' => 4, 'comment' => ' Sehr <gut> ']);
$votes->submit($poll, $slide, $this->hash('b', $poll), ['value' => 2, 'comment' => '']);
$votes->submit($poll, $slide, $this->hash('c', $poll), ['value' => 3, 'comment' => 'Zu lang']);
return [$poll, $token, $slide];
}
protected function hash(string $char, Poll $poll): string
{
return VoteService::participantHash(str_repeat($char, 32), $poll->id);
}
/**
* @return array<string, mixed>
*/
protected function presenterResults(string $token): array
{
$this->get("/admin/$token/state");
return json_decode((string)$this->_response->getBody(), true)['results'];
}
public function testSettingIsSanitized(): void
{
$this->assertTrue(SlidesTable::sanitizeSettings(Slide::TYPE_SCALE, ['comments' => '1'])['comments']);
$this->assertFalse(SlidesTable::sanitizeSettings(Slide::TYPE_SCALE, [])['comments']);
[$poll] = $this->createPoll();
$this->assertFalse($this->createSlide($poll, Slide::TYPE_SCALE, ['settings' => []])->hasComments());
}
public function testFormSavesCommentSetting(): void
{
[$poll, $token] = $this->createPoll();
$this->post("/admin/$token/slides/add?type=scale", [
'type' => 'scale',
'question' => 'Wie fandest du den Abend?',
'settings' => ['scale_min' => '1', 'scale_max' => '5', 'comments' => '1'],
]);
$slide = $this->slidesTable()->find()->where(['poll_id' => $poll->id])->firstOrFail();
$this->assertTrue($slide->hasComments());
}
public function testParticipantPageShowsCommentField(): void
{
[$poll, , $slide] = $this->scaleWithComments();
$this->slidesTable()->Responses->deleteAll(['slide_id' => $slide->id]);
$this->get('/p/' . $poll->join_code);
$this->assertResponseContains('name="comment"');
$this->assertResponseContains('Kommentar (optional)');
}
public function testCommentIsStoredWithTheRating(): void
{
[$poll, , $slide] = $this->scaleWithComments();
$this->post('/p/' . $poll->join_code . '/vote', ['slide_id' => $slide->id, 'value' => '5', 'comment' => 'Per Formular']);
$row = $this->slidesTable()->Responses->find()->where(['slide_id' => $slide->id])->orderBy(['id' => 'DESC'])->firstOrFail();
$this->assertSame(5, $row->numeric_value);
$this->assertSame('Per Formular', $row->text_value);
}
public function testCommentIsIgnoredWithoutCommentField(): void
{
[$poll] = $this->createPoll();
$slide = $this->createSlide($poll, Slide::TYPE_SCALE, ['settings' => ['scale_min' => 1, 'scale_max' => 5]]);
$poll = $this->goLive($poll, $slide);
(new VoteService())->submit($poll, $slide, $this->hash('a', $poll), ['value' => 3, 'comment' => 'Eingeschmuggelt']);
$row = $this->slidesTable()->Responses->find()->where(['slide_id' => $slide->id])->firstOrFail();
$this->assertNull($row->text_value);
}
public function testTooLongCommentIsRejected(): void
{
[$poll] = $this->createPoll();
$slide = $this->createSlide($poll, Slide::TYPE_SCALE, ['settings' => ['comments' => true]]);
$poll = $this->goLive($poll, $slide);
$this->expectException(VoteException::class);
(new VoteService())->submit($poll, $slide, $this->hash('a', $poll), [
'value' => 3,
'comment' => str_repeat('x', VoteService::MAX_TEXT_LENGTH + 1),
]);
}
public function testPresenterGetsCommentsOldestFirst(): void
{
[, $token] = $this->scaleWithComments();
$results = $this->presenterResults($token);
$this->assertSame(3, $results['participants']);
$this->assertEqualsWithDelta(3.0, $results['average'], 0.001);
$this->assertSame(['Sehr <gut>', 'Zu lang'], array_column($results['comments'], 'text'));
$this->assertSame([null, null], array_column($results['comments'], 'value'));
}
public function testRatingsNextToCommentsAreOptional(): void
{
$this->assertTrue(SlidesTable::sanitizeSettings(Slide::TYPE_SCALE, ['comment_ratings' => '1'])['comment_ratings']);
$this->assertFalse(SlidesTable::sanitizeSettings(Slide::TYPE_SCALE, [])['comment_ratings']);
[, $token] = $this->scaleWithComments(['comment_ratings' => true]);
$this->assertSame([4, 3], array_column($this->presenterResults($token)['comments'], 'value'));
}
public function testParticipantsNeverSeeComments(): void
{
[$poll] = $this->scaleWithComments();
$this->assertTrue($poll->show_results_to_participants);
// Participant "a" has already rated and sees the results – but not the comments.
$this->cookie('plenario_pid', str_repeat('a', 32));
$this->get('/p/' . $poll->join_code . '/state');
$state = json_decode((string)$this->_response->getBody(), true);
$this->assertNotEmpty($state['results']['buckets']);
$this->assertSame([], $state['results']['comments']);
$this->assertResponseNotContains('Zu lang');
$this->get('/p/' . $poll->join_code);
$this->assertResponseNotContains('Zu lang');
}
public function testEmbedShowsComments(): void
{
[$poll, , $slide] = $this->scaleWithComments();
$key = $this->pollsTable()->ensureEmbedKey($poll);
$this->get("/e/$key/{$slide->id}/state");
$state = json_decode((string)$this->_response->getBody(), true);
$this->assertCount(2, $state['results']['comments']);
}
public function testPrivateScaleNeverShowsComments(): void
{
[$poll, $token, $slide] = $this->scaleWithComments(['private' => true]);
$results = $this->presenterResults($token);
$this->assertSame([], $results['comments']);
$this->assertResponseNotContains('Sehr');
$key = $this->pollsTable()->ensureEmbedKey($poll);
$this->get("/e/$key/{$slide->id}/state");
$this->assertResponseNotContains('Sehr');
$this->get('/p/' . $poll->join_code . '/state');
$this->assertResponseNotContains('Sehr');
}
public function testAdminEvaluationListsComments(): void
{
[, $token, $slide] = $this->scaleWithComments(['private' => true]);
$this->get("/admin/$token");
$this->assertResponseContains("/slides/{$slide->id}/answers");
$this->get("/admin/$token/slides/{$slide->id}/answers");
$this->assertResponseOk();
$this->assertResponseContains('2 Kommentare');
$this->assertResponseContains('Sehr &lt;gut&gt;');
$this->assertResponseContains('Bewertung 4');
}
public function testExportContainsComments(): void
{
[, $token] = $this->scaleWithComments();
$this->get("/admin/$token/export.csv");
$this->assertResponseContains('4 (Kommentar: Sehr <gut>)');
$this->assertResponseContains(';2;');
}
}
+30 -6
View File
@@ -96,6 +96,7 @@ h3 { font-size: 1.05rem; margin-top: 1.6em; }
.muted { color: var(--muted); }
.center { text-align: center; }
.eyebrow { text-transform: uppercase; letter-spacing: .08em; font-size: .75rem; font-weight: 700; color: var(--primary); margin: 0 0 .4em; }
.eyebrow--poll { font-size: 1.35rem; letter-spacing: .05em; margin-bottom: .6em; }
.lead { font-size: 1.15rem; color: var(--muted); }
.hint { font-size: .875rem; color: var(--muted); margin: .25em 0 1em; }
.hint--error { color: var(--danger); }
@@ -512,6 +513,28 @@ button.qa-steps__step:hover:not(:disabled) { color: var(--text); border-color: v
.answers-page { list-style: none; padding: 0; margin: 0; }
.answers-page li { padding: 12px 16px; border: 1px solid var(--border); border-radius: 8px; margin-bottom: 8px; background: var(--surface); white-space: pre-line; overflow-wrap: anywhere; }
.answers-page time { display: block; color: var(--muted); font-size: .8rem; margin-top: 4px; }
.scale-comment { display: block; margin-top: 16px; font-weight: 600; }
.comments { margin-top: 20px; padding: 16px 20px; background: var(--surface-2); border-radius: 14px; }
.comments__counter { margin: 0 0 6px; font-size: .85em; font-weight: 700; text-transform: uppercase; letter-spacing: .08em; color: var(--muted); font-variant-numeric: tabular-nums; }
.comments__text { margin: 0; font-size: 1.25em; font-weight: 600; white-space: pre-line; overflow-wrap: anywhere; }
.comments__text::before { content: '„'; }
.comments__text::after { content: '“'; }
.comments__value { margin: 6px 0 0; color: var(--muted); font-size: .9em; }
.comments__nav { display: flex; gap: 8px; justify-content: flex-end; margin-top: 12px; }
.comments__button { min-width: 44px; min-height: 44px; }
@media (prefers-reduced-motion: no-preference) {
.comments__text.is-entering { animation: comment-in .4s ease-out; }
}
@keyframes comment-in {
from { opacity: 0; transform: translateY(6px); }
to { opacity: 1; transform: none; }
}
.scale-average { font-size: 1.2rem; margin: 0 0 1em; }
.scale-average strong { font-size: 1.6em; font-variant-numeric: tabular-nums; }
.scale-table { width: 100%; border-collapse: collapse; font-variant-numeric: tabular-nums; }
.scale-table th, .scale-table td { text-align: left; padding: 8px 10px; border-bottom: 1px solid var(--border); vertical-align: middle; }
.scale-table td:last-child { width: 50%; }
.scale-table__bar { display: block; height: 6px; min-width: 2px; margin-bottom: 4px; border-radius: 3px; background: var(--c2); }
/* ---------------------------------------------------------------- presenter */
/* Dark by default (beamer); the presenter's own switch can make it light (data-theme="light"). */
@@ -555,12 +578,13 @@ body.present {
.stage__results { font-size: clamp(1rem, 1.8vw, 1.5rem); margin-top: 2vh; }
.stage--closed .stage__type::after { content: " · Abstimmung geschlossen"; color: var(--muted); }
.stage .bar__track { height: 1.1em; }
.stage .columns { height: 34vh; }
.stage .average { padding: 2vh 2.5vw; gap: 2vh 4vw; background: rgba(var(--tint), .06); }
.stage .average__value strong { font-size: clamp(4rem, 9vw, 8rem); }
.stage .average__of { font-size: clamp(1.6rem, 3vw, 2.8rem); }
.stage .average__label, .stage .average__count, .stage .average__ends { font-size: clamp(.9rem, 1.4vw, 1.3rem); }
.stage .average__track { height: 1em; box-shadow: none; background: linear-gradient(90deg, var(--surface-2), var(--c1)); }
.stage .columns { height: 22vh; }
.stage .average { padding: 1vh 2vw; gap: 1vh 3vw; margin-bottom: 1.5vh; background: rgba(var(--tint), .06); }
.stage .average__value strong { font-size: clamp(2.6rem, 5vw, 4.5rem); }
.stage .average__of { font-size: clamp(1.2rem, 2vw, 1.8rem); }
.stage .average__label, .stage .average__count, .stage .average__ends { font-size: clamp(.85rem, 1.2vw, 1.1rem); }
.stage .average__track { height: .7em; box-shadow: none; background: linear-gradient(90deg, var(--surface-2), var(--c1)); }
.stage .average__ends { margin-top: 4px; }
.stage .cloud { font-size: clamp(1.4rem, 2.6vw, 2.6rem); }
.stage .answers { columns: 340px; }
.stage .quiz-timer { font-size: clamp(3rem, 7vw, 6rem); }
+139 -1
View File
@@ -289,6 +289,124 @@
}
};
// ------------------------------------------------------------------ comments
/**
* Rotating comments of a scale slide. The results are re-rendered on every poll,
* so position, pause and timer live here and survive the re-render.
*/
var Comments = {
intervalMs: 8000,
key: null,
index: 0,
paused: false,
timer: null,
items: [],
node: null,
render: function (items) {
// A different first comment means a different slide (or a reset): start over.
var key = String(items[0].id);
if (key !== Comments.key) {
Comments.key = key;
Comments.index = 0;
Comments.paused = false;
}
Comments.items = items;
Comments.index = Math.min(Comments.index, items.length - 1);
var button = function (action, label, text) {
return el('button', {
type: 'button',
class: 'button button--small comments__button',
'data-comment-action': action,
'aria-label': label,
title: label,
text: text
});
};
var node = el('section', { class: 'comments', 'data-comments': '', 'aria-label': 'Kommentare' }, [
el('p', { class: 'comments__counter', 'data-comment-counter': '' }),
el('blockquote', { class: 'comments__text', 'data-comment-text': '' }),
el('p', { class: 'comments__value', 'data-comment-value': '' }),
items.length < 2 ? null : el('div', { class: 'comments__nav' }, [
button('prev', 'Vorheriger Kommentar', '‹'),
button('toggle', '', ''),
button('next', 'Nächster Kommentar', '›')
])
]);
node.addEventListener('click', function (event) {
var target = event.target.closest('[data-comment-action]');
if (!target) {
return;
}
var action = target.getAttribute('data-comment-action');
if (action === 'toggle') {
Comments.paused = !Comments.paused;
} else {
Comments.step(action === 'next' ? 1 : -1);
Comments.restart();
}
Comments.update(false);
});
Comments.node = node;
Comments.update(false);
if (!Comments.timer) {
Comments.restart();
}
return node;
},
step: function (delta) {
var n = Comments.items.length;
Comments.index = (Comments.index + delta + n) % n;
},
restart: function () {
clearInterval(Comments.timer);
Comments.timer = setInterval(function () {
if (!Comments.node || !document.body.contains(Comments.node)) {
// Slide changed: stop until the next comment list is rendered.
clearInterval(Comments.timer);
Comments.timer = null;
return;
}
if (Comments.paused || Comments.items.length < 2 || document.hidden) {
return;
}
Comments.step(1);
Comments.update(true);
}, Comments.intervalMs);
},
update: function (animate) {
var node = Comments.node;
var item = Comments.items[Comments.index];
var text = node.querySelector('[data-comment-text]');
node.querySelector('[data-comment-counter]').textContent =
'Kommentar ' + (Comments.index + 1) + ' von ' + Comments.items.length;
text.textContent = item.text;
var value = node.querySelector('[data-comment-value]');
value.textContent = item.value === null || item.value === undefined ? '' : 'Bewertung: ' + item.value;
value.hidden = value.textContent === '';
// Only announce changes the viewer triggered, not every automatic rotation.
node.setAttribute('aria-live', Comments.paused ? 'polite' : 'off');
text.classList.remove('is-entering');
if (animate) {
void text.offsetWidth; // restart the CSS animation
text.classList.add('is-entering');
}
var toggle = node.querySelector('[data-comment-action="toggle"]');
if (toggle) {
var label = Comments.paused ? 'Kommentare automatisch weiterblättern' : 'Automatisches Weiterblättern anhalten';
toggle.textContent = Comments.paused ? '▶' : '❚❚';
toggle.setAttribute('aria-label', label);
toggle.setAttribute('title', label);
toggle.setAttribute('aria-pressed', Comments.paused ? 'true' : 'false');
}
}
};
// ------------------------------------------------------------------ results
var Results = {
@@ -296,6 +414,9 @@
* @param {Object} [options] renderer specific; wordcloud: {mine: [keys], onUpvote: fn(word)|null}
*/
render: function (container, results, options) {
// Keep keyboard focus on controls inside the results (e.g. comment buttons) across re-renders.
var active = document.activeElement;
var focusKey = active && container.contains(active) ? active.getAttribute('data-comment-action') : null;
container.innerHTML = '';
if (!results) {
return;
@@ -313,6 +434,10 @@
return;
}
container.appendChild(renderer(results, options || {}));
var refocus = focusKey && container.querySelector('[data-comment-action="' + focusKey + '"]');
if (refocus) {
refocus.focus();
}
},
choice: function (results) {
@@ -329,6 +454,15 @@
},
scale: function (results) {
if (results.private) {
// Internal feedback: the ratings never reach the stage, only the count.
var n = results.participants;
return el('div', { class: 'private-summary' }, [
el('p', { class: 'private-summary__count', text: String(n) }),
el('p', { text: (n === 1 ? 'Bewertung' : 'Bewertungen') + ' eingegangen' }),
el('p', { class: 'private-summary__hint', text: '🔒 Ergebnis wird nicht öffentlich angezeigt.' })
]);
}
var max = Math.max.apply(null, results.buckets.map(function (b) { return b.count; }).concat([1]));
var total = results.buckets.reduce(function (sum, b) { return sum + b.count; }, 0);
var hasAverage = results.average !== null;
@@ -375,7 +509,8 @@
]),
gauge
]);
return el('div', { class: 'scale-results' }, [average, columns, labels]);
var comments = results.comments && results.comments.length ? Comments.render(results.comments) : null;
return el('div', { class: 'scale-results' }, [average, columns, labels, comments]);
},
/**
@@ -1039,6 +1174,9 @@
if (event.target.closest('input, textarea, select')) {
return;
}
if ((event.key === ' ' || event.key === 'Enter') && event.target.closest('[data-comments]')) {
return; // activates the focused comment button, not the next slide
}
if (embedded && ['ArrowRight', 'ArrowLeft', 'PageUp', 'PageDown', ' ', 'p', 'P', 'f', 'F', 'q', 'Q'].indexOf(event.key) >= 0) {
return; // slide navigation belongs to the surrounding presentation
}