Files
Plenario/src/Service/ResultsService.php
T
gnilebeinandClaude Sonnet 5.5 61718ed7c6
CI / Deploy / PHP 8.4 (push) Successful in 1m11s
CI / Deploy / PHP 8.5 (push) Successful in 1m11s
CI / Deploy / test (push) Successful in 1s
CI / Deploy / deploy (push) Skipped
Add optional comment field to multiple choice slides
Participants can justify their choice; the comment is stored once in the
first response row, rotates on the stage like scale comments and is listed
in the admin area and the PDF export.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-13 09:29:25 +01:00

468 lines
19 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']], 'votes' (int),
* 'comments' => [['id', 'text', 'value' (always null)]] oldest first (only with the comment
* field, else []; presentation only, participants never get results of choice slides)
* - 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);
* - scale: 'buckets' => [['value', 'count', 'percent']], 'average' => float|null,
* 'min', 'max', 'minLabel', 'maxLabel', 'private' (bool), 'stars' (bool: star rating, min = 1);
* 'comments' => [['id', 'text', 'value' (int|null)]] oldest first (only with the comment field, else [];
* 'value' is null unless the setting comment_ratings is on;
* 'view' (both|average|chart): parts shown in the presentation (setting scale_view,
* the data is always complete);
* presentation only: participants never get results of scale slides, see PollStateService);
* open/scale with 'private' (anonymous/internal feedback): contents are included for the
* presenter/embed, which start with the results hidden and may show them on demand;
* participants never get results of these slides, the public PDF strips them (withoutContents())
* - 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.
* - order: 'revealed' (bool, = voting closed); while not revealed 'items' => [['id', 'label']]
* in a fixed shuffled order (never the solution); once revealed 'items' in the correct
* order with 'position' (1-based), 'placed' (participants who put the item at its position),
* 'percent', plus 'correctCount' (participants with the completely correct order).
* Neither the correct order nor counts are part of the result before it is revealed.
* - qa: 'stage' (collect|vote|discuss), 'stages' (available stages in order, no 'vote' without upvotes),
* 'maxUpvotes' (per participant, 0 = no upvotes), 'maxPerQuestion' (per participant and question),
* 'upvotes' (total),
* 'questions' => [['id', 'text', 'votes']] most upvoted first (ties: oldest first);
* during 'vote' only [['id', 'text']] in submission order (no counts while voting is open),
* '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
* @param int|null $limit Max. answers of open questions / comments of scales (newest), null = all
* @param bool $withRatings Ratings next to scale comments regardless of the setting comment_ratings
* (complete PDF export only)
* @return array<string, mixed>
*/
public function forSlide(Slide $slide, ?int $limit = self::MAX_ANSWERS, bool $withRatings = false): 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, $limit),
Slide::TYPE_WORDCLOUD => $this->wordcloud($slide),
Slide::TYPE_OPEN => $this->open($slide, $limit),
Slide::TYPE_SCALE => $this->scale($slide, $limit, $withRatings),
Slide::TYPE_QUIZ => $this->quiz($slide),
Slide::TYPE_QA => $this->qa($slide),
Slide::TYPE_ORDER => $this->order($slide),
default => [],
};
}
/**
* @param \App\Model\Entity\Slide $slide Slide
* @return array<string, mixed>
*/
protected function order(Slide $slide): array
{
if (!$slide->isOrderRevealed()) {
return [
'revealed' => false,
'items' => array_map(fn($option) => [
'id' => $option->id,
'label' => $option->label,
], $slide->shuffledOptions('slide:' . $slide->id)),
];
}
$correct = $slide->optionIds();
$placed = array_fill_keys($correct, 0);
$correctCount = 0;
$answers = $this->Responses->find()
->select(['text_value'])
->where(['slide_id' => $slide->id, 'text_value IS NOT' => null])
->disableHydration()
->all();
foreach ($answers as $row) {
$given = VoteService::parseOrder($row['text_value']);
if ($given === $correct) {
$correctCount++;
}
foreach ($correct as $index => $id) {
if (($given[$index] ?? null) === $id) {
$placed[$id]++;
}
}
}
$total = count($answers);
$items = [];
foreach (array_values($slide->slide_options ?? []) as $index => $option) {
$items[] = [
'id' => $option->id,
'label' => $option->label,
'position' => $index + 1,
'placed' => $placed[$option->id],
'percent' => $total > 0 ? round($placed[$option->id] / $total * 100, 1) : 0,
];
}
return ['revealed' => true, 'items' => $items, 'correctCount' => $correctCount];
}
/**
* @param \App\Model\Entity\Slide $slide Slide
* @param int|null $limit Max. comments (newest), null = all
* @return array<string, mixed>
*/
protected function choice(Slide $slide, ?int $limit = null): 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,
];
}
$comments = [];
foreach ($slide->hasComments() ? $this->comments($slide, $limit) : [] as $comment) {
// No option next to the comment: with several choices it would only be a guess anyway.
$comments[] = ['id' => $comment['id'], 'text' => $comment['text'], 'value' => null];
}
return ['options' => $options, 'votes' => $total, 'comments' => $comments];
}
/**
* @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_READY) {
// Answers are only shown once the quiz has been started.
$result['options'] = [];
return $result;
}
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);
$upvotes = array_sum(array_column($questions, 'votes'));
$budget = $slide->qaBudget(count($questions));
if ($slide->qaStage() === Slide::QA_VOTE) {
// A live ranking on the stage would sway the vote: submission order, no counts until voting ends.
usort($questions, fn($a, $b) => $a['id'] <=> $b['id']);
$questions = array_map(fn($q) => ['id' => $q['id'], 'text' => $q['text']], $questions);
}
$focusIndex = null;
foreach ($questions as $index => $question) {
if ($question['id'] === $slide->focus_response_id) {
$focusIndex = $index;
}
}
return [
'stage' => $slide->qaStage(),
'stages' => $slide->qaStages(),
'maxUpvotes' => $budget,
'maxPerQuestion' => $slide->qaUpvotesPerQuestion($budget),
'upvotes' => $upvotes,
'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
* @param int|null $limit Max. answers, null = all
* @return array<string, mixed>
*/
protected function open(Slide $slide, ?int $limit): array
{
return [
'private' => $slide->isPrivate(),
'answers' => $this->answers($slide, $limit),
];
}
/**
* Texts of an open question, newest first.
*
* @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
* @param int|null $limit Max. comments, null = all
* @param bool $withRatings Ratings regardless of the setting comment_ratings
* @return array<string, mixed>
*/
protected function scale(Slide $slide, ?int $limit, bool $withRatings): array
{
$showRatings = $withRatings || (bool)$slide->setting('comment_ratings');
$comments = [];
foreach ($slide->hasComments() ? $this->comments($slide, $limit) : [] as $comment) {
$comments[] = [
'id' => $comment['id'],
'text' => $comment['text'],
'value' => $showRatings ? $comment['value'] : null,
];
}
return $this->scaleResults($slide) + [
'private' => $slide->isPrivate(),
'comments' => $comments,
'view' => $slide->setting('scale_view'),
];
}
/**
* Results of a private slide without its contents: only type, participants and the scale range.
* Used where internal feedback must not appear (public PDF export, see ReportService).
*
* @param array<string, mixed> $results Result of forSlide()
* @return array<string, mixed>
*/
public static function withoutContents(array $results): array
{
if (isset($results['answers'])) {
$results['answers'] = [];
}
if (isset($results['buckets'])) {
$results['buckets'] = [];
$results['average'] = null;
$results['comments'] = [];
}
return $results;
}
/**
* Comments of a scale with their rating (choice: without value), oldest first; the unfiltered call
* (ratings regardless of comment_ratings) is only for the admin area.
*
* @param \App\Model\Entity\Slide $slide Scale or choice slide
* @param int|null $limit Max. comments (the newest ones), null = all
* @return list<array{id: int, text: string, value: int|null, created: string}>
*/
public function comments(Slide $slide, ?int $limit = null): array
{
// Scale: the rating row carries the comment. Choice: the comment sits in the first of the
// participant's rows, which always has an option.
$answered = $slide->type === Slide::TYPE_CHOICE ? 'slide_option_id IS NOT' : 'numeric_value IS NOT';
$query = $this->Responses->find()
->select(['id', 'text_value', 'numeric_value', 'created'])
->where(['slide_id' => $slide->id, 'text_value IS NOT' => null, $answered => null])
->orderBy(['id' => 'DESC']);
if ($limit !== null) {
$query->limit($limit);
}
$comments = [];
foreach ($query->all() as $row) {
$comments[] = [
'id' => (int)$row->id,
'text' => (string)$row->text_value,
'value' => $row->numeric_value === null ? null : (int)$row->numeric_value,
'created' => $row->created->toIso8601String(),
];
}
return array_reverse($comments);
}
/**
* Distribution and average of a scale.
*
* @param \App\Model\Entity\Slide $slide Scale slide
* @return array{buckets: list<array{value: int, count: int, percent: float|int}>, average: float|null, min: int, max: int, minLabel: string, maxLabel: string, stars: bool}
*/
public function scaleResults(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'),
'stars' => $slide->isStarRating(),
];
}
}