Files
Plenario/src/Service/PollStateService.php
T
gnilebeinandClaude Opus 5.5 367ff8548d
CI / Deploy / test (push) Successful in 1m4s
CI / Deploy / deploy (push) Skipped
Add anonymous feedback option for open questions
Open questions can be marked private: the presenter screen and embeds
only show the number of answers, participants never see results, and
the texts are readable on a new admin answers page and in the CSV.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-07 16:28:47 +01:00

317 lines
12 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
declare(strict_types=1);
namespace App\Service;
use App\Model\Entity\Poll;
use App\Model\Entity\Slide;
use App\Model\Table\PollsTable;
use App\Model\Table\ResponsesTable;
use App\Model\Table\SlidesTable;
use Cake\ORM\Locator\LocatorAwareTrait;
/**
* Builds the JSON state polled by the presenter screen (/admin/{token}/state)
* and the participant page (/p/{code}/state).
*
* The participant state never contains results unless the poll allows it and
* the participant has answered (or voting is closed). Exception: word clouds
* with upvotes enabled show the live cloud while voting is open, because
* participants upvote by clicking words in it.
*
* Quiz slides reveal results (and the participant's own correctness) only
* 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`.
* Private open questions (anonymous feedback) never show results to participants.
*/
class PollStateService
{
use LocatorAwareTrait;
protected SlidesTable $Slides;
protected ResponsesTable $Responses;
protected PollsTable $Polls;
protected ResultsService $results;
/**
* 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;
/** @var \App\Model\Table\PollsTable $polls */
$polls = $this->fetchTable('Polls');
$this->Polls = $polls;
$this->results = new ResultsService();
}
/**
* @param \App\Model\Entity\Poll $poll Poll
* @return \App\Model\Entity\Slide|null
*/
public function currentSlide(Poll $poll): ?Slide
{
$this->Polls->pauseIfEmbedStale($poll);
if ($poll->current_slide_id === null) {
return null;
}
/** @var \App\Model\Entity\Slide|null $slide */
$slide = $this->Slides->find()
->where(['Slides.id' => $poll->current_slide_id, 'Slides.poll_id' => $poll->id])
->contain(['SlideOptions'])
->first();
return $slide ? $this->Slides->closeIfExpired($slide) : null;
}
/**
* @param \App\Model\Entity\Poll $poll Poll
* @return array<string, mixed>
*/
public function forPresenter(Poll $poll): array
{
$this->Polls->pauseIfEmbedStale($poll);
$slides = $this->Slides->listForPoll($poll->id);
$current = null;
$index = null;
foreach ($slides as $i => $slide) {
if ($slide->id === $poll->current_slide_id) {
$current = $this->Slides->closeIfExpired($slide);
$index = $i;
}
}
return [
'poll' => [
'title' => $poll->title,
'joinCode' => $poll->join_code,
'joinCodeFormatted' => $poll->formattedJoinCode(),
'isActive' => $poll->is_active,
'isPaused' => $poll->isPaused(),
],
'slides' => array_map(fn(Slide $s) => [
'id' => $s->id,
'type' => $s->type,
'question' => $s->question,
], $slides),
'index' => $index,
'count' => count($slides),
'slide' => $current ? $this->slidePayload($current) : null,
'results' => $current ? $this->results->forSlide($current) : null,
];
}
/**
* State of one embedded slide (/e/{key}/{slide}/state). Same shape as forPresenter(),
* but always for this slide, live or not, plus `isLive`. Never contains the slide list.
*
* @param \App\Model\Entity\Poll $poll Poll
* @param \App\Model\Entity\Slide $slide Slide of this poll incl. slide_options
* @return array<string, mixed>
*/
public function forEmbed(Poll $poll, Slide $slide): array
{
$this->Polls->pauseIfEmbedStale($poll);
$slide = $this->Slides->closeIfExpired($slide);
return [
'poll' => [
'title' => $poll->title,
'joinCode' => $poll->join_code,
'joinCodeFormatted' => $poll->formattedJoinCode(),
'isActive' => $poll->is_active,
'isPaused' => $poll->isPaused(),
],
'isLive' => $poll->current_slide_id === $slide->id,
'index' => null,
'count' => null,
'slide' => $this->slidePayload($slide),
'results' => $this->results->forSlide($slide),
];
}
/**
* @param \App\Model\Entity\Poll $poll Poll
* @param string $participantHash Participant hash
* @return array<string, mixed>
*/
public function forParticipant(Poll $poll, string $participantHash): array
{
$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;
$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
&& !$slide->isPrivate()
&& ($quiz !== null
? $quiz['phase'] === Slide::QUIZ_FINISHED
: ($poll->show_results_to_participants && ($hasResponded || !$isVotingOpen))
|| ($words !== null && $words['allowUpvotes'] && $isVotingOpen));
return [
'isActive' => $poll->is_active,
'isPaused' => $slide === null && $poll->isPaused(),
'slideId' => $slide?->id,
'isVotingOpen' => $isVotingOpen,
'hasResponded' => $hasResponded,
// Changes whenever the participant page must re-render.
'version' => implode(':', [
(int)$poll->is_active,
$slide?->id ?? 0,
(int)$isVotingOpen,
// 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,
];
}
/**
* Quiz progress of one participant. The own answer and its correctness are
* only included once the quiz is finished.
*
* @param \App\Model\Entity\Slide $slide Quiz slide incl. slide_options
* @param string $participantHash Participant hash
* @return array{phase: string, remaining: int|null, answerId: int|null, isCorrect: bool|null}
*/
public function quizState(Slide $slide, string $participantHash): array
{
$phase = $slide->quizPhase();
$answerId = null;
$isCorrect = null;
if ($phase === Slide::QUIZ_FINISHED) {
$response = $this->Responses->find()
->select(['slide_option_id'])
->where(['slide_id' => $slide->id, 'participant_hash' => $participantHash])
->first();
$answerId = $response?->slide_option_id;
if ($answerId !== null) {
$isCorrect = false;
foreach ($slide->slide_options ?? [] as $option) {
if ($option->id === $answerId) {
$isCorrect = $option->is_correct;
}
}
}
}
return [
'phase' => $phase,
'remaining' => $phase === Slide::QUIZ_RUNNING ? $slide->remainingSeconds() : null,
'answerId' => $answerId,
'isCorrect' => $isCorrect,
];
}
/**
* 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.
*
* @param \App\Model\Entity\Slide $slide Word cloud slide
* @param string $participantHash Participant hash
* @return array{mine: list<string>, down: list<string>, allowUpvotes: bool, allowDownvotes: bool}
* `mine` (named/upvoted) and `down` are lower case word keys
*/
public function wordState(Slide $slide, string $participantHash): array
{
$votes = $this->Responses->wordVotesOf($slide->id, $participantHash);
$mine = array_values(array_unique(array_map(VoteService::wordKey(...), $votes['up'])));
$down = array_values(array_unique(array_map(VoteService::wordKey(...), $votes['down'])));
$allowUpvotes = (bool)$slide->setting('allow_upvotes');
return [
'mine' => $mine,
'down' => $down,
'allowUpvotes' => $allowUpvotes,
'allowDownvotes' => $allowUpvotes && (bool)$slide->setting('allow_downvotes'),
];
}
/**
* @param \App\Model\Entity\Slide $slide Slide
* @return array<string, mixed>
*/
public function slidePayload(Slide $slide): array
{
return [
'id' => $slide->id,
'type' => $slide->type,
'typeLabel' => $slide->typeLabel(),
'question' => $slide->question,
'description' => (string)$slide->description,
'isVotingOpen' => $slide->isVotingOpen(),
'isInteractive' => $slide->isInteractive(),
'settings' => $slide->getSettings(),
// YouTube slides: player URL for the presenter, link for sharing
'video' => $slide->isYouTube() && $slide->youtubeEmbedUrl() !== null ? [
'embedUrl' => $slide->youtubeEmbedUrl(),
'watchUrl' => $slide->youtubeWatchUrl(),
] : null,
];
}
}