Add Q&A slide type
CI / Deploy / test (push) Successful in 48s
CI / Deploy / deploy (push) Skipped

Participants submit questions, upvote them and the presenter discusses
them one by one, most upvoted first.

- Stages collect -> vote -> discuss, switched manually by the presenter
  (V key or stepper, going back is possible)
- Configurable upvote budget per participant, freely distributable
  (several upvotes on one question are allowed), votes can be withdrawn
- Participants see all questions while collecting to avoid duplicates;
  no counts before the discussion
- While discussing, next/prev step through the questions before
  moving to the next slide
- Migration: slides.stage, slides.focus_response_id, responses.parent_id

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
gnilebeinandClaude Opus 5.5 committed 2026-11-07 16:09:46 +01:00
1 parent ea944b080f
commit f0c6687100
21 files changed
+1327 -27

No files matched your search

+37 -1
View File
@@ -8,6 +8,7 @@ use App\Model\Entity\Slide;
use App\Model\Table\ResponsesTable;
use App\Model\Table\SlidesTable;
use App\Service\PollStateService;
use App\Service\QaService;
use App\Service\VoteService;
use Cake\Core\Configure;
use Cake\Http\Exception\BadRequestException;
@@ -158,7 +159,11 @@ class AdminController extends AdminAppController
/**
* Presenter controls. Field `action`:
* goto (+ slide_id), next, prev, open, close, toggle, stop
* goto (+ slide_id), next, prev, open, close, toggle, stop,
* Q&A: stage (+ stage: collect|vote|discuss), question (+ step: 1|-1)
*
* On a Q&A slide that is being discussed, next/prev step through the questions
* first (like builds in presentation software), toggle switches to the next stage.
*
* Answers with the new state as JSON for XHR requests, otherwise redirects back.
*
@@ -171,8 +176,36 @@ class AdminController extends AdminAppController
$slides = $this->Slides->listForPoll($this->poll->id);
$ids = array_map(fn(Slide $s) => $s->id, $slides);
$index = array_search($this->poll->current_slide_id, $ids, true);
$current = $index === false ? null : $slides[$index];
$qa = new QaService();
if ($current !== null && $current->isQa()) {
if ($action === 'toggle') {
// No-op while discussing (last stage).
$qa->advance($current);
$action = 'none';
} elseif (in_array($action, ['next', 'prev'], true) && $qa->moveFocus($current, $action === 'next' ? 1 : -1)) {
$action = 'none';
}
}
switch ($action) {
case 'none':
break;
case 'stage':
case 'question':
if ($current === null || !$current->isQa()) {
throw new BadRequestException('Not a Q&A slide');
}
if ($action === 'question') {
$qa->moveFocus($current, (int)$this->request->getData('step') < 0 ? -1 : 1);
break;
}
$stage = (string)$this->request->getData('stage');
if (!in_array($stage, Slide::QA_STAGES, true)) {
throw new BadRequestException('Unknown stage');
}
$qa->setStage($current, $stage);
break;
case 'goto':
$target = (int)$this->request->getData('slide_id');
if (!in_array($target, $ids, true)) {
@@ -267,8 +300,11 @@ class AdminController extends AdminAppController
->where(['slide_id' => $slide->id])
->orderBy(['id' => 'ASC'])
->all();
$texts = [];
foreach ($responses as $response) {
$texts[$response->id] = (string)$response->text_value;
$answer = match (true) {
$response->parent_id !== null => __('Upvote: {0}', $texts[$response->parent_id] ?? ''),
$response->slide_option_id !== null => $labels[$response->slide_option_id] ?? '',
$response->text_value !== null && $response->numeric_value === VoteService::DOWNVOTE
=> __('Downvote: {0}', $response->text_value),
+6 -1
View File
@@ -124,7 +124,12 @@ class ParticipateController extends AppController
}
(new VoteService())->submit($poll, $slide, $this->participantHash($poll), (array)$this->request->getData());
$ok = true;
$message = __('Danke für deine Antwort!');
$message = match (true) {
!$slide->isQa() => __('Danke für deine Antwort!'),
$this->request->getData('vote') === 'up' => __('Deine Stimme ist angekommen.'),
$this->request->getData('vote') === 'remove' => __('Deine Stimme wurde zurückgenommen.'),
default => __('Danke, deine Frage ist angekommen!'),
};
} catch (VoteException $e) {
$ok = false;
$message = $e->getMessage();
+8 -2
View File
@@ -5,6 +5,7 @@ namespace App\Controller;
use App\Model\Entity\Slide;
use App\Model\Table\SlidesTable;
use App\Service\QaService;
use App\Service\YouTubeService;
use Cake\Http\Exception\NotFoundException;
use Cake\Http\Response;
@@ -43,6 +44,8 @@ class SlidesController extends AdminAppController
$slide->poll_id = $this->poll->id;
// A quiz is started by the presenter (that also starts its timer).
$slide->is_voting_open = $type !== Slide::TYPE_QUIZ;
// Q&A starts by collecting questions.
$slide->stage = $type === Slide::TYPE_QA ? Slide::QA_COLLECT : null;
$optionsText = $type === Slide::TYPE_CHOICE ? "\n" : '';
$quizOptions = [];
@@ -147,6 +150,9 @@ class SlidesController extends AdminAppController
$slide->voting_ends_at = null;
$this->Slides->saveOrFail($slide);
}
if ($slide->isQa()) {
(new QaService())->reset($slide);
}
$this->Flash->success(__('Antworten der Folie „{0}“ wurden gelöscht.', $slide->question));
return $this->redirect($this->adminUrl());
@@ -205,8 +211,8 @@ class SlidesController extends AdminAppController
// The type of an existing slide cannot change (would invalidate responses).
$data['type'] = $slide->type;
$fields = ['type', 'question', 'description', 'settings', 'is_voting_open'];
if ($slide->isQuiz()) {
// Quiz voting is controlled by the presenter only.
if ($slide->isQuiz() || $slide->isQa()) {
// Quiz and Q&A voting is controlled by the presenter only.
$fields = array_values(array_diff($fields, ['is_voting_open']));
}
$youtube = $slide->isYouTube() ? $this->prepareYouTube($data) : ['errors' => [], 'warning' => null];
+3
View File
@@ -8,6 +8,7 @@ use Cake\ORM\Entity;
/**
* One answer row of a participant. A multi-select vote or a word cloud entry
* with several words results in several rows with the same participant_hash.
* Q&A: a question is a row with text_value, an upvote a row with parent_id = question id.
*
* @property int $id
* @property int $slide_id
@@ -15,6 +16,7 @@ use Cake\ORM\Entity;
* @property int|null $slide_option_id
* @property string|null $text_value
* @property int|null $numeric_value
* @property int|null $parent_id Q&A upvote: id of the supported question
* @property \Cake\I18n\DateTime $created
*/
class Response extends Entity
@@ -30,6 +32,7 @@ class Response extends Entity
'slide_option_id' => true,
'text_value' => true,
'numeric_value' => true,
'parent_id' => true,
];
/**
+54
View File
@@ -21,6 +21,8 @@ use Cake\ORM\Entity;
* @property bool $is_voting_open
* @property \Cake\I18n\DateTime|null $voting_started_at Quiz: start of the voting window
* @property \Cake\I18n\DateTime|null $voting_ends_at Quiz: deadline (null = closed manually)
* @property string|null $stage Q&A: collect|vote|discuss (null = collect), see qaStage()
* @property int|null $focus_response_id Q&A: question currently being discussed
* @property \Cake\I18n\DateTime $created
* @property \Cake\I18n\DateTime $modified
* @property \App\Model\Entity\Poll $poll
@@ -36,6 +38,7 @@ class Slide extends Entity
public const TYPE_CONTENT = 'content';
public const TYPE_QUIZ = 'quiz';
public const TYPE_YOUTUBE = 'youtube';
public const TYPE_QA = 'qa';
/**
* Quiz phases, see quizPhase().
@@ -51,6 +54,24 @@ class Slide extends Entity
*/
public const QUIZ_TIME_LIMITS = [0, 10, 15, 20, 30, 45, 60, 90, 120, 180, 300];
/**
* Q&A stages, see qaStage(): participants submit questions, then upvote
* them, then the presenter discusses them one by one (most upvoted first).
*/
public const QA_COLLECT = 'collect';
public const QA_VOTE = 'vote';
public const QA_DISCUSS = 'discuss';
/**
* @var list<string>
*/
public const QA_STAGES = [self::QA_COLLECT, self::QA_VOTE, self::QA_DISCUSS];
/**
* Highest selectable number of upvotes per participant on a Q&A slide.
*/
public const QA_MAX_UPVOTES = 10;
/**
* Default settings per type. Unknown keys are dropped on save.
*
@@ -67,6 +88,8 @@ class Slide extends Entity
self::TYPE_QUIZ => ['time_limit' => 30],
// url as entered, video_id parsed from it, start in seconds
self::TYPE_YOUTUBE => ['url' => '', 'video_id' => '', 'start' => 0, 'autoplay' => false],
// upvotes per participant in the voting stage (1..QA_MAX_UPVOTES)
self::TYPE_QA => ['max_upvotes' => 3],
];
/**
@@ -91,6 +114,7 @@ class Slide extends Entity
self::TYPE_OPEN => __('Offene Frage'),
self::TYPE_SCALE => __('Skala'),
self::TYPE_QUIZ => __('Quiz'),
self::TYPE_QA => __('Fragen & Antworten'),
self::TYPE_CONTENT => __('Inhaltsfolie'),
self::TYPE_YOUTUBE => __('YouTube-Video'),
];
@@ -107,6 +131,7 @@ class Slide extends Entity
self::TYPE_OPEN => __('Freitext-Antworten, live als Liste.'),
self::TYPE_SCALE => __('Bewertung auf einer Skala, z. B. 1 bis 5.'),
self::TYPE_QUIZ => __('Frage mit richtiger Antwort und Zeitlimit, aufgelöst wird erst am Ende.'),
self::TYPE_QA => __('Teilnehmende reichen Fragen ein und wählen per Upvote, welche zuerst beantwortet werden.'),
self::TYPE_CONTENT => __('Nur Text anzeigen, ohne Abstimmung.'),
self::TYPE_YOUTUBE => __('Video in der Präsentation abspielen, Teilnehmende bekommen den Link zum Teilen.'),
];
@@ -199,6 +224,35 @@ class Slide extends Entity
return $this->type === self::TYPE_QUIZ;
}
/**
* @return bool
*/
public function isQa(): bool
{
return $this->type === self::TYPE_QA;
}
/**
* Stage of a Q&A slide (one of the QA_* constants), see QaService.
*
* @return string
*/
public function qaStage(): string
{
return in_array($this->stage, self::QA_STAGES, true) ? (string)$this->stage : self::QA_COLLECT;
}
/**
* Whether a participant may answer the slide several times (word cloud: one
* row per word, Q&A: questions and upvotes).
*
* @return bool
*/
public function allowsMultipleResponses(): bool
{
return in_array($this->type, [self::TYPE_WORDCLOUD, self::TYPE_QA], true);
}
/**
* Phase of a quiz: ready (not started yet), running, finished (time up or
* closed by the presenter). Results and correct answers are only revealed
+62
View File
@@ -4,6 +4,7 @@ declare(strict_types=1);
namespace App\Model\Table;
use App\Service\VoteService;
use Cake\ORM\Query\SelectQuery;
use Cake\ORM\Table;
/**
@@ -32,6 +33,67 @@ class ResponsesTable extends Table
$this->belongsTo('SlideOptions', ['foreignKey' => 'slide_option_id']);
}
/**
* Q&A questions of a slide (rows with text, without parent).
*
* @param int $slideId Slide id
* @return \Cake\ORM\Query\SelectQuery
*/
public function questionsOf(int $slideId): SelectQuery
{
return $this->find()->where([
'Responses.slide_id' => $slideId,
'Responses.parent_id IS' => null,
'Responses.text_value IS NOT' => null,
]);
}
/**
* Q&A progress of one participant on a slide.
*
* @param int $slideId Slide id
* @param string $participantHash Participant hash
* @return array{questions: list<int>, upvotes: list<int>} ids of own questions / question id of each own upvote (repeated per upvote)
*/
public function qaVotesOf(int $slideId, string $participantHash): array
{
$rows = $this->find()
->select(['id', 'parent_id'])
->where(['slide_id' => $slideId, 'participant_hash' => $participantHash])
->orderBy(['id' => 'ASC'])
->disableHydration()
->all();
$result = ['questions' => [], 'upvotes' => []];
foreach ($rows as $row) {
if ($row['parent_id'] === null) {
$result['questions'][] = (int)$row['id'];
} else {
$result['upvotes'][] = (int)$row['parent_id'];
}
}
return $result;
}
/**
* Upvotes per Q&A question of a slide.
*
* @param int $slideId Slide id
* @return array<int, int> question id => upvotes
*/
public function upvotesPerQuestion(int $slideId): array
{
return $this->find()
->select(['parent_id', 'n' => $this->find()->func()->count('*')])
->where(['slide_id' => $slideId, 'parent_id IS NOT' => null])
->groupBy(['parent_id'])
->disableHydration()
->all()
->combine(fn($row) => (int)$row['parent_id'], fn($row) => (int)$row['n'])
->toArray();
}
/**
* @param int $slideId Slide id
* @param string $participantHash Participant hash
+4
View File
@@ -159,6 +159,10 @@ class SlidesTable extends Table
$settings['time_limit'] = $limit;
}
break;
case Slide::TYPE_QA:
$max = (int)($input['max_upvotes'] ?? $settings['max_upvotes']);
$settings['max_upvotes'] = max(1, min(Slide::QA_MAX_UPVOTES, $max));
break;
case Slide::TYPE_YOUTUBE:
$url = mb_substr(trim((string)($input['url'] ?? '')), 0, 500);
$parsed = YouTubeService::parseUrl($url);
+51 -5
View File
@@ -22,6 +22,8 @@ use Cake\ORM\Locator\LocatorAwareTrait;
* once the quiz is finished – then always, independent of
* `show_results_to_participants`. Timed quizzes are closed lazily here
* when their deadline has passed.
*
* Q&A slides have their own participant view (`qa`, see qaState()), never `results`.
*/
class PollStateService
{
@@ -111,13 +113,17 @@ class PollStateService
$slide = $poll->is_active ? $this->currentSlide($poll) : null;
$words = $slide?->type === Slide::TYPE_WORDCLOUD ? $this->wordState($slide, $participantHash) : null;
$quiz = $slide?->isQuiz() ? $this->quizState($slide, $participantHash) : null;
$hasResponded = $words !== null
? $words['mine'] !== [] || $words['down'] !== []
: $slide && $slide->isInteractive() && $this->Responses->hasResponded($slide->id, $participantHash);
$qa = $slide?->isQa() ? $this->qaState($slide, $participantHash) : null;
$hasResponded = match (true) {
$words !== null => $words['mine'] !== [] || $words['down'] !== [],
$qa !== null => $qa['mine'] !== [] || $qa['upvoted'] !== [],
default => $slide && $slide->isInteractive() && $this->Responses->hasResponded($slide->id, $participantHash),
};
$isVotingOpen = $slide?->isVotingOpen() ?? false;
$showResults = $slide !== null
&& $slide->isInteractive()
&& $qa === null
&& ($quiz !== null
? $quiz['phase'] === Slide::QUIZ_FINISHED
: ($poll->show_results_to_participants && ($hasResponded || !$isVotingOpen))
@@ -133,14 +139,15 @@ class PollStateService
(int)$poll->is_active,
$slide?->id ?? 0,
(int)$isVotingOpen,
// Word clouds are answered word by word without reload.
$words !== null ? 0 : (int)$hasResponded,
// Word clouds and Q&A are answered item by item without reload.
$words !== null || $qa !== null ? 0 : (int)$hasResponded,
$slide?->modified?->toUnixString() ?? 0,
]),
'slide' => $showResults ? $this->slidePayload($slide) : null,
'results' => $showResults ? $this->results->forSlide($slide) : null,
'words' => $words,
'quiz' => $quiz,
'qa' => $qa,
];
}
@@ -181,6 +188,45 @@ class PollStateService
];
}
/**
* Q&A view of one participant:
* - collect: all questions so far in submission order (helps to avoid duplicates), `mine` marks own ones
* - vote: all questions in submission order, without counts (no bandwagon effect)
* - discuss: all questions ranked with upvotes, `focusId` = question being discussed
* `upvoted` = own upvotes per question id (several per question are allowed).
*
* @param \App\Model\Entity\Slide $slide Q&A slide
* @param string $participantHash Participant hash
* @return array{stage: string, maxUpvotes: int, votesLeft: int, mine: list<int>, upvoted: array<int, int>,
* questions: list<array{id: int, text: string, votes?: int}>, focusId: int|null}
*/
public function qaState(Slide $slide, string $participantHash): array
{
$stage = $slide->qaStage();
$own = $this->Responses->qaVotesOf($slide->id, $participantHash);
$max = (int)$slide->setting('max_upvotes');
$questions = (new QaService())->rankedQuestions($slide);
if ($stage === Slide::QA_DISCUSS) {
$focusId = in_array($slide->focus_response_id, array_column($questions, 'id'), true)
? $slide->focus_response_id
: null;
} else {
$focusId = null;
usort($questions, fn($a, $b) => $a['id'] <=> $b['id']);
$questions = array_map(fn($q) => ['id' => $q['id'], 'text' => $q['text']], $questions);
}
return [
'stage' => $stage,
'maxUpvotes' => $max,
'votesLeft' => max(0, $max - count($own['upvotes'])),
'mine' => $own['questions'],
'upvoted' => array_count_values($own['upvotes']),
'questions' => array_values($questions),
'focusId' => $focusId,
];
}
/**
* Word cloud progress of one participant.
*
+154
View File
@@ -0,0 +1,154 @@
<?php
declare(strict_types=1);
namespace App\Service;
use App\Model\Entity\Slide;
use App\Model\Table\ResponsesTable;
use App\Model\Table\SlidesTable;
use Cake\ORM\Locator\LocatorAwareTrait;
use InvalidArgumentException;
/**
* Q&A slides ("Fragen & Antworten"), presenter side.
*
* Stages (Slide::qaStage()):
* - collect: participants submit questions (voting open)
* - vote: participants upvote questions of others, at most `max_upvotes` each (voting open)
* - discuss: voting closed; the presenter steps through the questions, most upvoted
* first (`slides.focus_response_id` = question on screen)
*
* The presenter switches stages manually and may go back (e.g. reopen the
* collection). Submitting and upvoting itself is validated in VoteService.
*/
class QaService
{
use LocatorAwareTrait;
protected SlidesTable $Slides;
protected ResponsesTable $Responses;
/**
* Constructor
*/
public function __construct()
{
/** @var \App\Model\Table\SlidesTable $slides */
$slides = $this->fetchTable('Slides');
$this->Slides = $slides;
/** @var \App\Model\Table\ResponsesTable $responses */
$responses = $this->fetchTable('Responses');
$this->Responses = $responses;
}
/**
* Questions of a slide, most upvoted first (ties: oldest first).
*
* @param \App\Model\Entity\Slide $slide Q&A slide
* @return list<array{id: int, text: string, votes: int}>
*/
public function rankedQuestions(Slide $slide): array
{
$votes = $this->Responses->upvotesPerQuestion($slide->id);
$questions = [];
$rows = $this->Responses->questionsOf($slide->id)
->select(['id', 'text_value'])
->orderBy(['id' => 'ASC'])
->disableHydration()
->all();
foreach ($rows as $row) {
$id = (int)$row['id'];
$questions[] = ['id' => $id, 'text' => (string)$row['text_value'], 'votes' => $votes[$id] ?? 0];
}
usort($questions, fn($a, $b) => [$b['votes'], $a['id']] <=> [$a['votes'], $b['id']]);
return $questions;
}
/**
* Switches the stage. Collecting and voting open the slide for input,
* discussing closes it and puts the top question on screen. Setting the
* current stage again changes nothing.
*
* @param \App\Model\Entity\Slide $slide Q&A slide
* @param string $stage One of Slide::QA_STAGES
* @return \App\Model\Entity\Slide
*/
public function setStage(Slide $slide, string $stage): Slide
{
if (!$slide->isQa() || !in_array($stage, Slide::QA_STAGES, true)) {
throw new InvalidArgumentException('Unknown Q&A stage ' . $stage);
}
if ($slide->qaStage() === $stage && $slide->stage !== null) {
return $slide;
}
$slide->stage = $stage;
$slide->is_voting_open = $stage !== Slide::QA_DISCUSS;
$slide->focus_response_id = $stage === Slide::QA_DISCUSS
? ($this->rankedQuestions($slide)[0]['id'] ?? null)
: null;
$this->Slides->saveOrFail($slide);
return $slide;
}
/**
* Moves to the following stage (collect → vote → discuss).
*
* @param \App\Model\Entity\Slide $slide Q&A slide
* @return bool False when already discussing
*/
public function advance(Slide $slide): bool
{
$index = (int)array_search($slide->qaStage(), Slide::QA_STAGES, true);
if (!isset(Slide::QA_STAGES[$index + 1])) {
return false;
}
$this->setStage($slide, Slide::QA_STAGES[$index + 1]);
return true;
}
/**
* Steps to the next/previous question while discussing.
*
* Saved without touching `modified`, so participant pages update live
* instead of reloading (see PollStateService version).
*
* @param \App\Model\Entity\Slide $slide Q&A slide
* @param int $step +1 next, -1 previous
* @return bool False when there is no such question (or not discussing)
*/
public function moveFocus(Slide $slide, int $step): bool
{
if (!$slide->isQa() || $slide->qaStage() !== Slide::QA_DISCUSS) {
return false;
}
$ids = array_column($this->rankedQuestions($slide), 'id');
$index = array_search($slide->focus_response_id, $ids, true);
$target = $index === false ? 0 : $index + $step;
if (!isset($ids[$target]) || $ids[$target] === $slide->focus_response_id) {
return false;
}
$this->Slides->updateAll(['focus_response_id' => $ids[$target]], ['id' => $slide->id]);
$slide->focus_response_id = $ids[$target];
$slide->setDirty('focus_response_id', false);
return true;
}
/**
* Back to the start after all responses were deleted.
*
* @param \App\Model\Entity\Slide $slide Q&A slide
* @return void
*/
public function reset(Slide $slide): void
{
$slide->stage = Slide::QA_COLLECT;
$slide->is_voting_open = true;
$slide->focus_response_id = null;
$this->Slides->saveOrFail($slide);
}
}
+29
View File
@@ -24,6 +24,10 @@ use Cake\ORM\Locator\LocatorAwareTrait;
* once finished additionally per option 'count', 'percent', 'correct' (bool)
* and 'correctCount' (participants with a correct answer).
* Counts and correct answers are NEVER part of the result before the quiz is finished.
* - qa: 'stage' (collect|vote|discuss), 'maxUpvotes', 'upvotes' (total),
* 'questions' => [['id', 'text', 'votes']] most upvoted first (ties: oldest first),
* 'focusId' (question being discussed|null), 'focusIndex' (0-based position in questions|null).
* Presenter only – participants get their own view, see PollStateService::qaState().
*/
class ResultsService
{
@@ -60,6 +64,7 @@ class ResultsService
Slide::TYPE_OPEN => $this->open($slide),
Slide::TYPE_SCALE => $this->scale($slide),
Slide::TYPE_QUIZ => $this->quiz($slide),
Slide::TYPE_QA => $this->qa($slide),
default => [],
};
}
@@ -134,6 +139,30 @@ class ResultsService
return $result;
}
/**
* @param \App\Model\Entity\Slide $slide Slide
* @return array<string, mixed>
*/
protected function qa(Slide $slide): array
{
$questions = (new QaService())->rankedQuestions($slide);
$focusIndex = null;
foreach ($questions as $index => $question) {
if ($question['id'] === $slide->focus_response_id) {
$focusIndex = $index;
}
}
return [
'stage' => $slide->qaStage(),
'maxUpvotes' => (int)$slide->setting('max_upvotes'),
'upvotes' => array_sum(array_column($questions, 'votes')),
'questions' => $questions,
'focusId' => $focusIndex === null ? null : $slide->focus_response_id,
'focusIndex' => $focusIndex,
];
}
/**
* @param \App\Model\Entity\Slide $slide Slide
* @return array<string, mixed>
+92 -2
View File
@@ -23,6 +23,11 @@ use Cake\Utility\Security;
* word of someone else. Each participant rates a word only once (up or down).
* - quiz: exactly one option, only while the quiz runs (Slide::isVotingOpen()
* includes the deadline of a timed quiz).
* - Q&A (see QaService for the stages): `question` (text) only while collecting,
* at most MAX_QA_QUESTIONS per participant, the same question (case-insensitive)
* only once per slide. `vote=up|remove` + `question_id` only while voting: upvote
* questions of others, at most `max_upvotes` in total, freely distributed (several
* on one question are allowed); `remove` withdraws one own upvote of the question.
*/
class VoteService
{
@@ -30,6 +35,7 @@ class VoteService
public const MAX_WORD_LENGTH = 40;
public const MAX_TEXT_LENGTH = 500;
public const MAX_QA_QUESTIONS = 10;
/**
* `responses.numeric_value` of a word cloud downvote (upvotes/words: null).
@@ -84,10 +90,11 @@ class VoteService
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.'),
});
}
if ($slide->type !== Slide::TYPE_WORDCLOUD && $this->Responses->hasResponded($slide->id, $participantHash)) {
if (!$slide->allowsMultipleResponses() && $this->Responses->hasResponded($slide->id, $participantHash)) {
throw new VoteException(__('Du hast bereits abgestimmt.'));
}
@@ -97,6 +104,7 @@ class VoteService
Slide::TYPE_OPEN => $this->openRows($data),
Slide::TYPE_SCALE => $this->scaleRows($slide, $data),
Slide::TYPE_QUIZ => $this->quizRows($slide, $data),
Slide::TYPE_QA => $this->qaRows($slide, $participantHash, $data),
default => throw new VoteException(__('Unbekannter Folientyp.')),
};
@@ -107,7 +115,9 @@ class VoteService
'participant_hash' => $participantHash,
]);
}
$this->Responses->saveManyOrFail($entities);
if ($entities !== []) {
$this->Responses->saveManyOrFail($entities);
}
}
/**
@@ -149,6 +159,86 @@ class VoteService
return [['slide_option_id' => $id]];
}
/**
* Q&A: a new question while collecting, an upvote (or its withdrawal) while voting.
* Withdrawing deletes one upvote row and returns no new rows.
*
* @param \App\Model\Entity\Slide $slide Slide
* @param string $participantHash Participant hash
* @param array<string, mixed> $data Request data
* @return list<array<string, mixed>>
*/
protected function qaRows(Slide $slide, string $participantHash, array $data): array
{
$stage = $slide->qaStage();
$vote = $data['vote'] ?? null;
$own = $this->Responses->qaVotesOf($slide->id, $participantHash);
if ($vote === null) {
if ($stage !== Slide::QA_COLLECT) {
throw new VoteException(__('Es können keine neuen Fragen mehr eingereicht werden.'));
}
$text = trim((string)preg_replace('/\s+/u', ' ', (string)($data['question'] ?? '')));
if ($text === '') {
throw new VoteException(__('Bitte gib eine Frage ein.'));
}
if (mb_strlen($text) > self::MAX_TEXT_LENGTH) {
throw new VoteException(__('Die Frage darf maximal {0} Zeichen lang sein.', self::MAX_TEXT_LENGTH));
}
$key = mb_strtolower($text);
foreach ($this->Responses->questionsOf($slide->id)->select(['text_value'])->disableHydration() as $row) {
if (mb_strtolower((string)$row['text_value']) === $key) {
throw new VoteException(__('Diese Frage wurde schon gestellt. Du kannst sie gleich beim Abstimmen unterstützen.'));
}
}
if (count($own['questions']) >= self::MAX_QA_QUESTIONS) {
throw new VoteException(__('Du kannst höchstens {0} Fragen stellen.', self::MAX_QA_QUESTIONS));
}
return [['text_value' => $text]];
}
if ($stage !== Slide::QA_VOTE) {
throw new VoteException(__('Die Abstimmung über die Fragen hat noch nicht begonnen.'));
}
$id = is_scalar($data['question_id'] ?? null) ? filter_var($data['question_id'], FILTER_VALIDATE_INT) : false;
if ($id === false || !$this->Responses->questionsOf($slide->id)->where(['Responses.id' => $id])->count()) {
throw new VoteException(__('Diese Frage gibt es nicht.'));
}
if ($vote === 'remove') {
// Withdraws one of possibly several own upvotes on the question.
$upvote = $this->Responses->find()
->where(['slide_id' => $slide->id, 'participant_hash' => $participantHash, 'parent_id' => $id])
->orderBy(['id' => 'DESC'])
->first();
if ($upvote === null) {
throw new VoteException(__('Du hast diese Frage nicht unterstützt.'));
}
$this->Responses->deleteOrFail($upvote);
return [];
}
if ($vote !== 'up') {
throw new VoteException(__('Ungültige Stimme.'));
}
if (in_array($id, $own['questions'], true)) {
throw new VoteException(__('Deine eigene Frage kannst du nicht unterstützen.'));
}
// Several upvotes on the same question are allowed (push important questions).
$max = (int)$slide->setting('max_upvotes');
if (count($own['upvotes']) >= $max) {
throw new VoteException(__n(
'Du hast deine Stimme schon vergeben. Nimm sie zurück, um eine andere Frage zu unterstützen.',
'Du hast alle {0} Stimmen vergeben. Nimm eine zurück, um eine andere Frage zu unterstützen.',
$max,
$max,
));
}
return [['parent_id' => $id]];
}
/**
* Normalized key of a word cloud term: whitespace collapsed, trimmed, cut to
* MAX_WORD_LENGTH. Use wordKey() for case-insensitive comparison.