Add ordering slide type
CI / Deploy / test (push) Successful in 50s
CI / Deploy / deploy (push) Skipped

Participants bring shuffled items into the correct order and submit it
once. The admin enters the items in the correct order and can reorder
them by drag & drop or arrow keys. Closing the voting reveals the
solution: how many got it completely right and how often each item was
placed correctly; participants see whether their order was right.

The drag & drop mechanics of the slide list are extracted into a
reusable makeSortable() helper.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
gnilebeinandClaude Opus 5.5 committed 2026-11-07 16:47:37 +01:00
1 parent 4eed568a64
commit 918e077734
17 files changed
+922 -95

No files matched your search

+21
View File
@@ -305,6 +305,7 @@ class AdminController extends AdminAppController
foreach ($responses as $response) {
$texts[$response->id] = (string)$response->text_value;
$answer = match (true) {
$slide->isOrder() => $this->orderAnswer($slide, $labels, (string)$response->text_value),
$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
@@ -335,6 +336,26 @@ class AdminController extends AdminAppController
->withStringBody($csv);
}
/**
* Ordering answer for the CSV export, e.g. "A → C → B (falsch)".
*
* @param \App\Model\Entity\Slide $slide Ordering slide incl. slide_options
* @param array<int, string> $labels Option labels by id
* @param string $text Stored answer (option ids)
* @return string
*/
protected function orderAnswer(Slide $slide, array $labels, string $text): string
{
$given = VoteService::parseOrder($text);
$correct = array_map(fn($option) => $option->id, array_values($slide->slide_options ?? []));
return __(
'{0} ({1})',
implode(' → ', array_map(fn(int $id) => $labels[$id] ?? '?', $given)),
$given === $correct ? __('richtig') : __('falsch'),
);
}
/**
* Prevents CSV/formula injection in spreadsheet programs.
*
+3 -2
View File
@@ -85,9 +85,10 @@ class ParticipateController extends AppController
$poll = $this->loadPoll($code);
$stateService = new PollStateService();
$slide = $poll->is_active ? $stateService->currentSlide($poll) : null;
$state = $stateService->forParticipant($poll, $this->participantHash($poll));
$participantHash = $this->participantHash($poll);
$state = $stateService->forParticipant($poll, $participantHash);
$this->set(compact('poll', 'slide', 'state'));
$this->set(compact('poll', 'slide', 'state', 'participantHash'));
$this->set('pollIntervalMs', (int)Configure::read('Plenario.pollIntervalMs', 2000));
}
+34 -3
View File
@@ -49,10 +49,12 @@ class SlidesController extends AdminAppController
$slide->stage = $type === Slide::TYPE_QA ? Slide::QA_COLLECT : null;
$optionsText = $type === Slide::TYPE_CHOICE ? "\n" : '';
$quizOptions = [];
$orderOptions = [];
if ($this->request->is('post')) {
$optionsText = (string)$this->request->getData('options_text', '');
$quizOptions = $this->postedQuizOptions();
$orderOptions = $this->postedOrderOptions();
if ($this->saveSlide($slide, $optionsText)) {
$this->Flash->success(__('Folie angelegt.'));
@@ -60,7 +62,7 @@ class SlidesController extends AdminAppController
}
}
$this->set(compact('slide', 'optionsText', 'quizOptions'));
$this->set(compact('slide', 'optionsText', 'quizOptions', 'orderOptions'));
$this->render('form');
return null;
@@ -75,10 +77,12 @@ class SlidesController extends AdminAppController
$slide = $this->loadSlide($id);
$optionsText = implode("\n", array_map(fn($o) => $o->label, $slide->slide_options ?? []));
$quizOptions = array_map(fn($o) => ['label' => $o->label, 'correct' => $o->is_correct], $slide->slide_options ?? []);
$orderOptions = array_map(fn($o) => $o->label, $slide->slide_options ?? []);
if ($this->request->is(['post', 'put', 'patch'])) {
$optionsText = (string)$this->request->getData('options_text', '');
$quizOptions = $this->postedQuizOptions();
$orderOptions = $this->postedOrderOptions();
if ($this->saveSlide($slide, $optionsText)) {
$this->Flash->success(__('Folie gespeichert.'));
@@ -87,7 +91,7 @@ class SlidesController extends AdminAppController
}
$hasResponses = $this->Slides->Responses->exists(['slide_id' => $slide->id]);
$this->set(compact('slide', 'optionsText', 'quizOptions', 'hasResponses'));
$this->set(compact('slide', 'optionsText', 'quizOptions', 'orderOptions', 'hasResponses'));
$this->render('form');
return null;
@@ -215,6 +219,23 @@ class SlidesController extends AdminAppController
return $rows;
}
/**
* Item rows of an ordering slide as posted by the form (for re-rendering after errors).
*
* @return list<string>
*/
protected function postedOrderOptions(): array
{
$rows = [];
foreach ((array)$this->request->getData('order_options', []) as $label) {
if (is_scalar($label)) {
$rows[] = (string)$label;
}
}
return $rows;
}
/**
* Patches and saves a slide incl. its options.
*
@@ -253,6 +274,16 @@ class SlidesController extends AdminAppController
$slide->setError('quiz_options', __('Bitte markiere mindestens eine Antwort als richtig.'));
}
}
if ($slide->isOrder()) {
['labels' => $labels, 'duplicate' => $duplicate] = SlidesTable::parseOrderOptions(
(array)$this->request->getData('order_options', []),
);
if ($duplicate) {
$slide->setError('order_options', __('Jeder Eintrag darf nur einmal vorkommen, sonst ist die Reihenfolge nicht eindeutig.'));
} elseif (count($labels) < 2) {
$slide->setError('order_options', __('Bitte gib mindestens zwei Einträge an.'));
}
}
if ($slide->hasErrors()) {
$this->Flash->error(__('Bitte prüfe deine Eingaben.'));
@@ -263,7 +294,7 @@ class SlidesController extends AdminAppController
if (!$this->Slides->save($slide)) {
return false;
}
if ($slide->type === Slide::TYPE_CHOICE || $slide->isQuiz()) {
if ($slide->type === Slide::TYPE_CHOICE || $slide->isQuiz() || $slide->isOrder()) {
$this->Slides->syncOptions($slide, $labels, $correct);
}
if ($youtube['warning'] !== null) {
+47
View File
@@ -39,6 +39,7 @@ class Slide extends Entity
public const TYPE_QUIZ = 'quiz';
public const TYPE_YOUTUBE = 'youtube';
public const TYPE_QA = 'qa';
public const TYPE_ORDER = 'order';
/**
* Quiz phases, see quizPhase().
@@ -91,6 +92,8 @@ class Slide extends Entity
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],
// The correct order is the order of the slide_options (position), revealed when voting closes.
self::TYPE_ORDER => [],
];
/**
@@ -115,6 +118,7 @@ class Slide extends Entity
self::TYPE_OPEN => __('Offene Frage'),
self::TYPE_SCALE => __('Skala'),
self::TYPE_QUIZ => __('Quiz'),
self::TYPE_ORDER => __('Reihenfolge'),
self::TYPE_QA => __('Fragen & Antworten'),
self::TYPE_CONTENT => __('Inhaltsfolie'),
self::TYPE_YOUTUBE => __('YouTube-Video'),
@@ -132,6 +136,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_ORDER => __('Einträge in die richtige Reihenfolge bringen, aufgelöst wird beim Schließen der Abstimmung.'),
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.'),
@@ -233,6 +238,48 @@ class Slide extends Entity
return $this->type === self::TYPE_QA;
}
/**
* @return bool
*/
public function isOrder(): bool
{
return $this->type === self::TYPE_ORDER;
}
/**
* Ordering slide whose solution may be shown: voting is closed. While voting
* is open, neither the correct order nor any counts may leave the server.
*
* @return bool
*/
public function isOrderRevealed(): bool
{
return $this->isOrder() && !$this->isVotingOpen();
}
/**
* Options of an ordering slide in a stable pseudo-random order (same seed =
* same order, e.g. per participant across reloads). With two or more options
* the result never equals the correct order.
*
* @param string $seed Seed, e.g. participant hash or "slide:{id}"
* @return list<\App\Model\Entity\SlideOption>
*/
public function shuffledOptions(string $seed): array
{
$options = array_values($this->slide_options ?? []);
$correct = array_map(fn($option) => $option->id, $options);
usort($options, fn($a, $b) => strcmp(
hash('sha256', $seed . '|' . $a->id),
hash('sha256', $seed . '|' . $b->id),
));
if (count($options) > 1 && array_map(fn($option) => $option->id, $options) === $correct) {
$options[] = array_shift($options);
}
return $options;
}
/**
* Stage of a Q&A slide (one of the QA_* constants), see QaService.
*
+27
View File
@@ -23,6 +23,7 @@ class SlidesTable extends Table
{
public const MAX_OPTIONS = 20;
public const MAX_QUIZ_OPTIONS = 10;
public const MAX_ORDER_OPTIONS = 10;
/**
* @param array<string, mixed> $config The configuration for the Table.
@@ -233,6 +234,32 @@ class SlidesTable extends Table
return ['labels' => $labels, 'correct' => $correct];
}
/**
* Parses the item rows of an ordering slide (`order_options[]`, in the correct order).
* Empty rows are skipped; a repeated label is reported, because it would make the order ambiguous.
*
* @param array<mixed> $rows Raw form rows (labels)
* @return array{labels: list<string>, duplicate: bool}
*/
public static function parseOrderOptions(array $rows): array
{
$labels = [];
$duplicate = false;
foreach ($rows as $row) {
$label = is_scalar($row) ? mb_substr(trim((string)$row), 0, 255) : '';
if ($label === '' || count($labels) >= self::MAX_ORDER_OPTIONS) {
continue;
}
if (in_array($label, $labels, true)) {
$duplicate = true;
continue;
}
$labels[] = $label;
}
return ['labels' => $labels, 'duplicate' => $duplicate];
}
/**
* Persists the end of a timed quiz once its deadline has passed. Safe to
* call repeatedly (no-op unless the slide is still flagged open).
+34 -3
View File
@@ -22,7 +22,8 @@ use Cake\ORM\Locator\LocatorAwareTrait;
* 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.
* when their deadline has passed. Ordering slides work the same way: solution,
* counts and the participant's correctness (`order`) only once voting is closed.
*
* Q&A slides have their own participant view (`qa`, see qaState()), never `results`.
* Private open questions (anonymous feedback) never show results to participants.
@@ -153,6 +154,7 @@ class PollStateService
$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;
$order = $slide?->isOrder() ? $this->orderState($slide, $participantHash) : null;
$hasResponded = match (true) {
$words !== null => $words['mine'] !== [] || $words['down'] !== [],
$qa !== null => $qa['mine'] !== [] || $qa['upvoted'] !== [],
@@ -164,8 +166,8 @@ class PollStateService
&& $slide->isInteractive()
&& $qa === null
&& !$slide->isPrivate()
&& ($quiz !== null
? $quiz['phase'] === Slide::QUIZ_FINISHED
&& ($quiz !== null || $order !== null
? ($quiz['phase'] ?? null) === Slide::QUIZ_FINISHED || ($order['revealed'] ?? false)
: ($poll->show_results_to_participants && ($hasResponded || !$isVotingOpen))
|| ($words !== null && $words['allowUpvotes'] && $isVotingOpen));
@@ -189,6 +191,35 @@ class PollStateService
'words' => $words,
'quiz' => $quiz,
'qa' => $qa,
'order' => $order,
];
}
/**
* Ordering progress of one participant. Own answer and correctness only once
* revealed (voting closed); before that the state must not hint at the solution.
*
* @param \App\Model\Entity\Slide $slide Ordering slide incl. slide_options
* @param string $participantHash Participant hash
* @return array{revealed: bool, answer: list<int>|null, isCorrect: bool|null}
*/
public function orderState(Slide $slide, string $participantHash): array
{
$revealed = $slide->isOrderRevealed();
$answer = null;
if ($revealed) {
$response = $this->Responses->find()
->select(['text_value'])
->where(['slide_id' => $slide->id, 'participant_hash' => $participantHash])
->first();
$answer = $response === null ? null : VoteService::parseOrder($response->text_value);
}
$correct = array_map(fn($option) => $option->id, array_values($slide->slide_options ?? []));
return [
'revealed' => $revealed,
'answer' => $answer,
'isCorrect' => $answer === null ? null : $answer === $correct,
];
}
+56
View File
@@ -25,6 +25,11 @@ 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.
* - 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), '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).
@@ -66,10 +71,61 @@ class ResultsService
Slide::TYPE_SCALE => $this->scale($slide),
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 = array_map(fn($option) => $option->id, array_values($slide->slide_options ?? []));
$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>
+48
View File
@@ -28,6 +28,8 @@ use Cake\Utility\Security;
* 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.
* - ordering: `order` = all option ids, each exactly once, in the participant's order.
* Stored as one row with the ids comma separated in `text_value` (see parseOrder()).
*/
class VoteService
{
@@ -105,6 +107,7 @@ class VoteService
Slide::TYPE_SCALE => $this->scaleRows($slide, $data),
Slide::TYPE_QUIZ => $this->quizRows($slide, $data),
Slide::TYPE_QA => $this->qaRows($slide, $participantHash, $data),
Slide::TYPE_ORDER => $this->orderRows($slide, $data),
default => throw new VoteException(__('Unbekannter Folientyp.')),
};
@@ -159,6 +162,51 @@ class VoteService
return [['slide_option_id' => $id]];
}
/**
* @param \App\Model\Entity\Slide $slide Slide
* @param array<string, mixed> $data Request data
* @return list<array<string, mixed>>
*/
protected function orderRows(Slide $slide, array $data): array
{
$given = [];
foreach ((array)($data['order'] ?? []) as $id) {
$id = is_scalar($id) ? filter_var($id, FILTER_VALIDATE_INT) : false;
if ($id === false) {
$given = [];
break;
}
$given[] = $id;
}
$validIds = array_map(fn($option) => $option->id, $slide->slide_options ?? []);
$sortedGiven = $given;
sort($sortedGiven);
sort($validIds);
if ($validIds === [] || $sortedGiven !== $validIds) {
throw new VoteException(__('Bitte bring alle Einträge in eine Reihenfolge und sende sie erneut.'));
}
return [['text_value' => implode(',', $given)]];
}
/**
* Option ids of a stored ordering answer (`responses.text_value`), in the participant's order.
*
* @param string|null $text Stored answer
* @return list<int>
*/
public static function parseOrder(?string $text): array
{
$ids = [];
foreach (explode(',', (string)$text) as $id) {
if (ctype_digit(trim($id))) {
$ids[] = (int)$id;
}
}
return $ids;
}
/**
* Q&A: a new question while collecting, an upvote (or its withdrawal) while voting.
* Withdrawing deletes one upvote row and returns no new rows.