Let participants edit their scale comment while voting is open

Participants can fix typos in, add or remove their own comment until the
voting closes. The rating itself stays unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
gnilebeinandClaude Opus 5.5 committed 2026-11-11 11:40:24 +01:00
1 parent bd488e0b81
commit d518b7a37e
6 files changed
+244 -20

No files matched your search

+4
View File
@@ -37,6 +37,10 @@ return function (RouteBuilder $routes): void {
->setPatterns(['code' => '[A-Za-z0-9-]{4,16}'])
->setPass(['code'])
->setMethods(['POST']);
$builder->connect('/p/{code}/comment', 'Participate::comment', ['_name' => 'participate:comment'])
->setPatterns(['code' => '[A-Za-z0-9-]{4,16}'])
->setPass(['code'])
->setMethods(['POST']);
// --- embedded slides (secret embed key, e.g. Canva) -----------------
// No CSRF check here (see Application::middleware()): runs in third-party iframes
+36 -1
View File
@@ -86,8 +86,11 @@ class ParticipateController extends AppController
$slide = $poll->is_active ? $stateService->currentSlide($poll) : null;
$participantHash = $this->participantHash($poll);
$state = $stateService->forParticipant($poll, $participantHash, $slide);
$ownComment = $slide?->hasComments() && $state['hasResponded']
? (new VoteService())->ownComment($slide, $participantHash)
: null;
$this->set(compact('poll', 'slide', 'state', 'participantHash'));
$this->set(compact('poll', 'slide', 'state', 'participantHash', 'ownComment'));
$this->setPollInterval();
}
@@ -153,6 +156,38 @@ class ParticipateController extends AppController
return $this->redirect(['_name' => 'participate', 'code' => $poll->join_code]);
}
/**
* Replaces the own comment on a scale slide while voting is open (e.g. to fix a typo).
*
* @param string $code Join code
* @return \Cake\Http\Response|null
*/
public function comment(string $code): ?Response
{
$this->request->allowMethod(['post']);
$poll = $this->loadPoll($code);
$slide = (new PollStateService())->currentSlide($poll);
try {
if (!$this->throttle('vote', 'Plenario.throttle.votesPerMinute', 60)) {
throw new VoteException(__('Zu viele Antworten in kurzer Zeit. Bitte warte einen Moment und versuche es dann noch einmal.'));
}
if ($slide === null || $slide->id !== (int)$this->request->getData('slide_id')) {
throw new VoteException(__('Diese Frage ist nicht mehr aktiv.'));
}
$data = (array)$this->request->getData();
(new VoteService())->editComment($poll, $slide, $this->participantHash($poll), $data);
$comment = $data['comment'] ?? '';
$this->Flash->success(!is_scalar($comment) || trim((string)$comment) === ''
? __('Dein Kommentar wurde entfernt.')
: __('Dein Kommentar wurde gespeichert.'));
} catch (VoteException $e) {
$this->Flash->error($e->getMessage());
}
return $this->redirect(['_name' => 'participate', 'code' => $poll->join_code]);
}
/**
* @param string $code Join code
* @return \App\Model\Entity\Poll
+96 -19
View File
@@ -36,6 +36,8 @@ use Cake\Utility\Security;
* `remove` withdraws one own upvote of the question.
* - ordering: `order` = all option ids, each exactly once, in the participant's order.
* Stored as one row with the ids comma separated in `text_value` (see parseOrder()).
* - scale with comment field: the own comment can be changed while voting is open
* (editComment()), the rating cannot.
*/
class VoteService
{
@@ -91,23 +93,7 @@ class VoteService
*/
public function submit(Poll $poll, Slide $slide, string $participantHash, array $data): void
{
if (!$poll->is_active) {
throw new VoteException(__('Diese Umfrage ist derzeit geschlossen.'));
}
if ($slide->poll_id !== $poll->id || $poll->current_slide_id !== $slide->id) {
throw new VoteException(__('Diese Frage ist nicht mehr aktiv.'));
}
if (!$slide->isInteractive()) {
throw new VoteException(__('Auf dieser Folie kann nicht abgestimmt werden.'));
}
if (!$slide->isVotingOpen()) {
throw new VoteException(match (true) {
$slide->isQuiz() && $slide->voting_started_at === null => __('Das Quiz hat noch nicht begonnen.'),
$slide->isQuiz() => __('Die Zeit für dieses Quiz ist abgelaufen.'),
$slide->isQa() => __('Die Fragerunde läuft – Fragen und Stimmen sind nicht mehr möglich.'),
default => __('Die Abstimmung zu dieser Frage ist geschlossen.'),
});
}
$this->assertOpen($poll, $slide);
// Checks (answered already, upvote budget, duplicates) and the insert run as one unit,
// so a double click or a retried request cannot store an answer twice.
$this->Responses->getConnection()->transactional(function () use ($slide, $participantHash, $data): void {
@@ -140,6 +126,85 @@ class VoteService
});
}
/**
* Scale with comment field: replaces the participant's own comment (e.g. to fix a typo)
* as long as voting on the slide is open. The rating itself stays unchanged; an empty
* comment removes it. Same preconditions as submit().
*
* @param \App\Model\Entity\Poll $poll Poll
* @param \App\Model\Entity\Slide $slide Slide
* @param string $participantHash Participant hash
* @param array<string, mixed> $data Request data (`comment`)
* @return void
* @throws \App\Service\VoteException
*/
public function editComment(Poll $poll, Slide $slide, string $participantHash, array $data): void
{
$this->assertOpen($poll, $slide);
if (!$slide->hasComments()) {
throw new VoteException(__('Bei dieser Frage gibt es keine Kommentare.'));
}
$comment = self::comment($data);
$this->Responses->getConnection()->transactional(function () use ($slide, $participantHash, $comment): void {
$this->lockSlide($slide);
$row = $this->Responses->find()
->where(['slide_id' => $slide->id, 'participant_hash' => $participantHash])
->first();
if ($row === null) {
throw new VoteException(__('Bitte gib zuerst deine Bewertung ab.'));
}
$row->text_value = $comment;
$this->Responses->saveOrFail($row);
});
}
/**
* The participant's own comment on a scale slide (null: none or not answered yet).
*
* @param \App\Model\Entity\Slide $slide Slide
* @param string $participantHash Participant hash
* @return string|null
*/
public function ownComment(Slide $slide, string $participantHash): ?string
{
$row = $this->Responses->find()
->select(['text_value'])
->where(['slide_id' => $slide->id, 'participant_hash' => $participantHash])
->disableHydration()
->first();
return $row['text_value'] ?? null;
}
/**
* Poll active, slide live and interactive, voting open.
*
* @param \App\Model\Entity\Poll $poll Poll
* @param \App\Model\Entity\Slide $slide Slide
* @return void
* @throws \App\Service\VoteException
*/
protected function assertOpen(Poll $poll, Slide $slide): void
{
if (!$poll->is_active) {
throw new VoteException(__('Diese Umfrage ist derzeit geschlossen.'));
}
if ($slide->poll_id !== $poll->id || $poll->current_slide_id !== $slide->id) {
throw new VoteException(__('Diese Frage ist nicht mehr aktiv.'));
}
if (!$slide->isInteractive()) {
throw new VoteException(__('Auf dieser Folie kann nicht abgestimmt werden.'));
}
if (!$slide->isVotingOpen()) {
throw new VoteException(match (true) {
$slide->isQuiz() && $slide->voting_started_at === null => __('Das Quiz hat noch nicht begonnen.'),
$slide->isQuiz() => __('Die Zeit für dieses Quiz ist abgelaufen.'),
$slide->isQa() => __('Die Fragerunde läuft – Fragen und Stimmen sind nicht mehr möglich.'),
default => __('Die Abstimmung zu dieser Frage ist geschlossen.'),
});
}
}
/**
* Serialises answers to one slide for the rest of the transaction.
*
@@ -497,11 +562,23 @@ class VoteService
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(self::stringField($data, 'comment')) : '';
return [['numeric_value' => $value, 'text_value' => $slide->hasComments() ? self::comment($data) : null]];
}
/**
* Optional scale comment from the request: trimmed, empty = null.
*
* @param array<string, mixed> $data Request data
* @return string|null
* @throws \App\Service\VoteException
*/
protected static function comment(array $data): ?string
{
$comment = trim(self::stringField($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, 'text_value' => $comment === '' ? null : $comment]];
return $comment === '' ? null : $comment;
}
}
+18
View File
@@ -8,6 +8,7 @@
* @var \App\Model\Entity\Slide|null $slide
* @var array<string, mixed> $state
* @var string $participantHash Seed for the shuffled items of ordering slides
* @var string|null $ownComment Own comment on a scale slide (editable while voting is open)
* @var int $pollIntervalMs
*/
$this->assign('title', $poll->title);
@@ -217,6 +218,23 @@ $countdown = function (?int $remaining): string {
<?= $this->Form->end() ?>
<?php elseif ($state['hasResponded']) : ?>
<p class="done">✓ <?= __('Deine Antwort ist angekommen.') ?></p>
<?php if ($slide->type === 'scale' && $slide->hasComments() && $slide->isVotingOpen()) : ?>
<?php if ($ownComment !== null) : ?>
<p class="own-comment__label"><?= __('Dein Kommentar:') ?></p>
<blockquote class="own-comment"><?= nl2br(h($ownComment)) ?></blockquote>
<?php endif; ?>
<details class="own-comment__edit">
<summary><?= $ownComment !== null ? __('Kommentar bearbeiten') : __('Kommentar hinzufügen') ?></summary>
<?= $this->Form->create(null, ['url' => ['_name' => 'participate:comment', 'code' => $poll->join_code], 'class' => 'vote-form']) ?>
<?= $this->Form->hidden('slide_id', ['value' => $slide->id]) ?>
<label class="scale-comment" for="scale-comment"><?= __('Kommentar') ?></label>
<textarea id="scale-comment" name="comment" rows="3" maxlength="500"
aria-describedby="comment-edit-hint"><?= h((string)$ownComment) ?></textarea>
<p class="hint" id="comment-edit-hint"><?= __('Möglich, solange die Abstimmung läuft. Ein leeres Feld entfernt deinen Kommentar, deine Bewertung bleibt.') ?></p>
<?= $this->Form->button(__('Kommentar speichern'), ['class' => 'button button--primary button--block']) ?>
<?= $this->Form->end() ?>
</details>
<?php endif; ?>
<?php elseif (!$slide->is_voting_open) : ?>
<p class="muted"><?= __('Die Abstimmung zu dieser Frage ist geschlossen.') ?></p>
<?php else : ?>
@@ -257,4 +257,82 @@ class ScaleCommentsTest extends TestCase
$this->assertStringContainsString('Bewertung 4', $html);
}
public function testParticipantCanEditOwnCommentWhileOpen(): void
{
[$poll, , $slide] = $this->scaleWithComments();
$this->cookie('plenario_pid', str_repeat('a', 32));
$this->get('/p/' . $poll->join_code);
$this->assertResponseContains('Kommentar bearbeiten');
$this->assertResponseContains('Sehr &lt;gut&gt;');
$this->post('/p/' . $poll->join_code . '/comment', ['slide_id' => $slide->id, 'comment' => ' Sehr gut! ', 'value' => '1']);
$this->assertRedirect('/p/' . $poll->join_code);
$this->assertFlashMessage('Dein Kommentar wurde gespeichert.');
$rows = $this->slidesTable()->Responses->find()
->where(['slide_id' => $slide->id, 'participant_hash' => $this->hash('a', $poll)])
->all();
$this->assertCount(1, $rows);
$this->assertSame('Sehr gut!', $rows->first()->text_value);
$this->assertSame(4, $rows->first()->numeric_value, 'the rating stays unchanged');
// Repeating the request is harmless, an empty comment removes it.
$this->post('/p/' . $poll->join_code . '/comment', ['slide_id' => $slide->id, 'comment' => ' Sehr gut! ']);
$this->post('/p/' . $poll->join_code . '/comment', ['slide_id' => $slide->id, 'comment' => '']);
$this->assertFlashMessage('Dein Kommentar wurde entfernt.');
$this->assertNull($this->slidesTable()->Responses->get($rows->first()->id)->text_value);
}
public function testParticipantWithoutCommentCanAddOne(): void
{
[$poll, , $slide] = $this->scaleWithComments();
$this->cookie('plenario_pid', str_repeat('b', 32));
$this->get('/p/' . $poll->join_code);
$this->assertResponseContains('Kommentar hinzufügen');
$this->post('/p/' . $poll->join_code . '/comment', ['slide_id' => $slide->id, 'comment' => 'Nachgereicht']);
$row = $this->slidesTable()->Responses->find()
->where(['slide_id' => $slide->id, 'participant_hash' => $this->hash('b', $poll)])
->firstOrFail();
$this->assertSame('Nachgereicht', $row->text_value);
}
public function testCommentCannotBeEditedAfterVotingClosed(): void
{
[$poll, , $slide] = $this->scaleWithComments();
$this->slidesTable()->updateAll(['is_voting_open' => false], ['id' => $slide->id]);
$this->cookie('plenario_pid', str_repeat('a', 32));
$this->get('/p/' . $poll->join_code);
$this->assertResponseNotContains('Kommentar bearbeiten');
$this->post('/p/' . $poll->join_code . '/comment', ['slide_id' => $slide->id, 'comment' => 'Zu spät']);
$this->assertFlashMessage('Die Abstimmung zu dieser Frage ist geschlossen.');
$this->assertSame('Sehr <gut>', $this->slidesTable()->Responses->find()
->where(['slide_id' => $slide->id, 'participant_hash' => $this->hash('a', $poll)])
->firstOrFail()->text_value);
}
public function testCommentEditNeedsARatingAndACommentField(): void
{
[$poll, , $slide] = $this->scaleWithComments();
$votes = new VoteService();
try {
$votes->editComment($poll, $slide, $this->hash('z', $poll), ['comment' => 'Ohne Bewertung']);
$this->fail('Expected VoteException');
} catch (VoteException $e) {
$this->assertSame('Bitte gib zuerst deine Bewertung ab.', $e->getMessage());
}
$this->assertFalse($this->slidesTable()->Responses->exists(['text_value' => 'Ohne Bewertung']));
$plain = $this->createSlide($poll, Slide::TYPE_SCALE, ['settings' => ['scale_min' => 1, 'scale_max' => 5]]);
$poll = $this->goLive($poll, $plain);
$votes->submit($poll, $plain, $this->hash('a', $poll), ['value' => 3]);
$this->expectException(VoteException::class);
$votes->editComment($poll, $plain, $this->hash('a', $poll), ['comment' => 'Eingeschmuggelt']);
}
}
+12
View File
@@ -530,12 +530,24 @@ button.qa-steps__step:hover:not(:disabled) { color: var(--text); border-color: v
.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; }
.own-comment__label { margin: 16px 0 4px; color: var(--muted); }
.own-comment { margin: 0; padding: 8px 12px; border-left: 3px solid var(--border); overflow-wrap: anywhere; }
.own-comment__edit { margin-top: 12px; }
.own-comment__edit summary { cursor: pointer; color: var(--muted); width: max-content; max-width: 100%; }
.own-comment__edit summary:hover { color: var(--text); }
.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__progress { height: 4px; margin-top: 14px; border-radius: 2px; background: var(--border); overflow: hidden; }
.comments__progress[hidden] { display: block; visibility: hidden; } /* keeps the layout steady while paused */
.comments__progress-fill { height: 100%; background: var(--primary); transform: scaleX(0); transform-origin: left; }
@keyframes comment-progress {
from { transform: scaleX(0); }
to { transform: scaleX(1); }
}
.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) {