diff --git a/config/routes.php b/config/routes.php index 2452d9b..79a2e5f 100644 --- a/config/routes.php +++ b/config/routes.php @@ -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 diff --git a/src/Controller/ParticipateController.php b/src/Controller/ParticipateController.php index 2914fc1..23babce 100644 --- a/src/Controller/ParticipateController.php +++ b/src/Controller/ParticipateController.php @@ -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 diff --git a/src/Service/VoteService.php b/src/Service/VoteService.php index 0e56276..4348da0 100644 --- a/src/Service/VoteService.php +++ b/src/Service/VoteService.php @@ -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 $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 $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; } } diff --git a/templates/Participate/view.php b/templates/Participate/view.php index 69466a1..e2318ff 100644 --- a/templates/Participate/view.php +++ b/templates/Participate/view.php @@ -8,6 +8,7 @@ * @var \App\Model\Entity\Slide|null $slide * @var array $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 { Form->end() ?>

✓

+ type === 'scale' && $slide->hasComments() && $slide->isVotingOpen()) : ?> + +

+
+ +
+ + Form->create(null, ['url' => ['_name' => 'participate:comment', 'code' => $poll->join_code], 'class' => 'vote-form']) ?> + Form->hidden('slide_id', ['value' => $slide->id]) ?> + + +

+ Form->button(__('Kommentar speichern'), ['class' => 'button button--primary button--block']) ?> + Form->end() ?> +
+ is_voting_open) : ?>

diff --git a/tests/TestCase/Controller/ScaleCommentsTest.php b/tests/TestCase/Controller/ScaleCommentsTest.php index 989d689..9c08fc1 100644 --- a/tests/TestCase/Controller/ScaleCommentsTest.php +++ b/tests/TestCase/Controller/ScaleCommentsTest.php @@ -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 <gut>'); + + $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 ', $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']); + } } diff --git a/webroot/css/plenario.css b/webroot/css/plenario.css index 0128c4d..f2130a8 100644 --- a/webroot/css/plenario.css +++ b/webroot/css/plenario.css @@ -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) {