Files
Plenario/src/Service/ResultsService.php
T
gnilebeinandClaude Opus 5.5 c1f9be2eef Add a star rating style to scale slides
Scales can now be shown as stars (1 to n) instead of numbered steps:
participants tap stars, the stage shows the average as partly filled
stars and the distribution as bars from most to fewest stars, and the
evaluation page and PDF export print ratings as stars.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 12:46:33 +01:00

439 lines
17 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);
* - 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;
* 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),
* '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),
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
* @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(),
'stages' => $slide->qaStages(),
'maxUpvotes' => (int)$slide->setting('max_upvotes'),
'maxPerQuestion' => $slide->qaUpvotesPerQuestion(),
'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
* @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,
];
}
/**
* 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, oldest first; the unfiltered call
* (ratings regardless of comment_ratings) is only for the admin area.
*
* @param \App\Model\Entity\Slide $slide Scale slide
* @param int|null $limit Max. comments (the newest ones), null = all
* @return list<array{id: int, text: string, value: int, created: string}>
*/
public function comments(Slide $slide, ?int $limit = null): array
{
$query = $this->Responses->find()
->select(['id', 'text_value', 'numeric_value', 'created'])
->where(['slide_id' => $slide->id, 'text_value IS NOT' => null, 'numeric_value IS NOT' => 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' => (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(),
];
}
}