Files
Plenario/src/Service/ResultsService.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

292 lines
10 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\Slide;
use App\Model\Table\ResponsesTable;
use Cake\ORM\Locator\LocatorAwareTrait;
/**
* Aggregates responses of a slide into a JSON friendly structure that is
* rendered by webroot/js/plenario.js (presenter + participant views).
*
* Shape (always present): ['type' => string, 'participants' => int, ...]
* - choice: 'options' => [['id', 'label', 'count', 'percent']]
* - wordcloud: 'words' => [['key' (lower case), 'text', 'count', 'down', 'weight' (0..1)]]
* (count = participants who named or upvoted the word, down = downvotes,
* weight follows count)
* - 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'
* - 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)
* 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
{
use LocatorAwareTrait;
public const MAX_ANSWERS = 200;
protected ResponsesTable $Responses;
/**
* Constructor
*/
public function __construct()
{
/** @var \App\Model\Table\ResponsesTable $responses */
$responses = $this->fetchTable('Responses');
$this->Responses = $responses;
}
/**
* @param \App\Model\Entity\Slide $slide Slide incl. slide_options
* @return array<string, mixed>
*/
public function forSlide(Slide $slide): array
{
$result = [
'type' => $slide->type,
'participants' => $slide->isInteractive() ? $this->Responses->countParticipants($slide->id) : 0,
];
return $result + match ($slide->type) {
Slide::TYPE_CHOICE => $this->choice($slide),
Slide::TYPE_WORDCLOUD => $this->wordcloud($slide),
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 => [],
};
}
/**
* @param \App\Model\Entity\Slide $slide Slide
* @return array<string, mixed>
*/
protected function choice(Slide $slide): array
{
$counts = $this->Responses->find()
->select(['slide_option_id', 'n' => $this->Responses->find()->func()->count('*')])
->where(['slide_id' => $slide->id, 'slide_option_id IS NOT' => null])
->groupBy(['slide_option_id'])
->disableHydration()
->all()
->combine('slide_option_id', 'n')
->toArray();
$total = array_sum(array_map('intval', $counts));
$options = [];
foreach ($slide->slide_options ?? [] as $option) {
$count = (int)($counts[$option->id] ?? 0);
$options[] = [
'id' => $option->id,
'label' => $option->label,
'count' => $count,
'percent' => $total > 0 ? round($count / $total * 100, 1) : 0,
];
}
return ['options' => $options, 'votes' => $total];
}
/**
* @param \App\Model\Entity\Slide $slide Slide
* @return array<string, mixed>
*/
protected function quiz(Slide $slide): array
{
$phase = $slide->quizPhase();
$result = [
'phase' => $phase,
'timeLimit' => (int)$slide->setting('time_limit'),
'remaining' => $phase === Slide::QUIZ_RUNNING ? $slide->remainingSeconds() : null,
'revealed' => $phase === Slide::QUIZ_FINISHED,
];
if ($phase !== Slide::QUIZ_FINISHED) {
$result['options'] = array_map(fn($option) => [
'id' => $option->id,
'label' => $option->label,
], $slide->slide_options ?? []);
return $result;
}
$choice = $this->choice($slide);
$correctIds = [];
foreach ($slide->slide_options ?? [] as $option) {
if ($option->is_correct) {
$correctIds[] = $option->id;
}
}
$result['options'] = array_map(fn(array $option) => $option + [
'correct' => in_array($option['id'], $correctIds, true),
], $choice['options']);
$result['correctCount'] = $correctIds === [] ? 0 : $this->Responses->find()
->where(['slide_id' => $slide->id, 'slide_option_id IN' => $correctIds])
->distinct(['participant_hash'])
->count();
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>
*/
protected function wordcloud(Slide $slide): array
{
$rows = $this->Responses->find()
->select(['text_value', 'numeric_value'])
->where(['slide_id' => $slide->id, 'text_value IS NOT' => null])
->disableHydration()
->all();
// Group case-insensitively, display the most frequent spelling.
$groups = [];
$downvotes = [];
foreach ($rows as $row) {
$text = (string)$row['text_value'];
$key = VoteService::wordKey($text);
if ((int)$row['numeric_value'] === VoteService::DOWNVOTE) {
$downvotes[$key] = ($downvotes[$key] ?? 0) + 1;
continue;
}
$groups[$key]['count'] = ($groups[$key]['count'] ?? 0) + 1;
$groups[$key]['spellings'][$text] = ($groups[$key]['spellings'][$text] ?? 0) + 1;
}
// Size follows the upvotes (count); downvotes are shown separately.
uasort($groups, fn($a, $b) => $b['count'] <=> $a['count']);
$maxCount = $groups === [] ? 1 : max(array_column($groups, 'count'));
$words = [];
foreach ($groups as $key => $group) {
arsort($group['spellings']);
$words[] = [
'key' => (string)$key,
'text' => (string)array_key_first($group['spellings']),
'count' => $group['count'],
'down' => $downvotes[$key] ?? 0,
'weight' => round($group['count'] / $maxCount, 3),
];
}
return ['words' => $words];
}
/**
* @param \App\Model\Entity\Slide $slide Slide
* @return array<string, mixed>
*/
protected function open(Slide $slide): array
{
return [
'private' => $slide->isPrivate(),
'answers' => $slide->isPrivate() ? [] : $this->answers($slide, self::MAX_ANSWERS),
];
}
/**
* Texts of an open question, newest first – also of private slides,
* so only for the admin area (never for the presenter screen or participants).
*
* @param \App\Model\Entity\Slide $slide Open question
* @param int|null $limit Max. answers, null = all
* @return list<array{text: string, created: string}>
*/
public function answers(Slide $slide, ?int $limit = null): array
{
$query = $this->Responses->find()
->select(['text_value', 'created'])
->where(['slide_id' => $slide->id, 'text_value IS NOT' => null])
->orderBy(['id' => 'DESC']);
if ($limit !== null) {
$query->limit($limit);
}
$answers = [];
foreach ($query->all() as $row) {
$answers[] = ['text' => (string)$row->text_value, 'created' => $row->created->toIso8601String()];
}
return $answers;
}
/**
* @param \App\Model\Entity\Slide $slide Slide
* @return array<string, mixed>
*/
protected function scale(Slide $slide): array
{
$min = (int)$slide->setting('scale_min');
$max = (int)$slide->setting('scale_max');
$counts = $this->Responses->find()
->select(['numeric_value', 'n' => $this->Responses->find()->func()->count('*')])
->where(['slide_id' => $slide->id, 'numeric_value IS NOT' => null])
->groupBy(['numeric_value'])
->disableHydration()
->all()
->combine('numeric_value', 'n')
->toArray();
$total = 0;
$sum = 0;
foreach ($counts as $value => $count) {
$total += (int)$count;
$sum += (int)$value * (int)$count;
}
$buckets = [];
for ($value = $min; $value <= $max; $value++) {
$count = (int)($counts[$value] ?? 0);
$buckets[] = [
'value' => $value,
'count' => $count,
'percent' => $total > 0 ? round($count / $total * 100, 1) : 0,
];
}
return [
'buckets' => $buckets,
'average' => $total > 0 ? round($sum / $total, 2) : null,
'min' => $min,
'max' => $max,
'minLabel' => (string)$slide->setting('min_label'),
'maxLabel' => (string)$slide->setting('max_label'),
];
}
}