Files
Plenario/src/Service/QaService.php
T
gnilebeinandClaude Sonnet 5.5 4b5f9d92a1 Add prepared questions to Q&A slides
The slide form takes questions entered beforehand (e.g. received by mail),
one per line, while collecting. They are stored as regular questions with a
reserved participant hash, synced idempotently, and not counted as participants.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 22:34:12 +01:00

250 lines
8.7 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Service;
use App\Model\Entity\Slide;
use App\Model\Table\ResponsesTable;
use App\Model\Table\SlidesTable;
use Cake\ORM\Locator\LocatorAwareTrait;
use InvalidArgumentException;
/**
* Q&A slides ("Fragen & Antworten"), presenter side.
*
* Stages (Slide::qaStage()):
* - collect: participants submit questions (voting open)
* - vote: participants upvote questions of others (own ones with `allow_self_upvote`),
* a budget of `upvote_share` percent of the questions each and `max_upvotes_per_question` per question (voting open).
* Skipped with `upvote_share` = 0 (Slide::qaStages()).
* - discuss: voting closed; the presenter steps through the questions, most upvoted
* first (`slides.focus_response_id` = question on screen)
*
* The presenter switches stages manually and may go back (e.g. reopen the
* collection). Submitting and upvoting itself is validated in VoteService.
*/
class QaService
{
use LocatorAwareTrait;
/** Maximum number of questions the admin can prepare per slide. */
public const MAX_PREPARED = 50;
protected SlidesTable $Slides;
protected ResponsesTable $Responses;
/**
* 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;
}
/**
* Texts of the questions the admin entered beforehand, in entry order.
*
* @param \App\Model\Entity\Slide $slide Q&A slide
* @return list<string>
*/
public function preparedQuestions(Slide $slide): array
{
$rows = $this->Responses->questionsOf($slide->id)
->select(['text_value'])
->where(['Responses.participant_hash' => VoteService::PREPARED_HASH])
->orderBy(['Responses.id' => 'ASC'])
->disableHydration()
->all();
return array_values(array_map(fn($row) => (string)$row['text_value'], $rows->toArray()));
}
/**
* Textarea (one question per line) into clean question texts: whitespace collapsed,
* cut to the maximum length, duplicates (case-insensitive) and empty lines dropped.
*
* @param string $raw Textarea content
* @return list<string>
*/
public static function parsePrepared(string $raw): array
{
$texts = [];
foreach (preg_split('/\R/', $raw) ?: [] as $line) {
$text = mb_substr(trim((string)preg_replace('/\s+/u', ' ', $line)), 0, VoteService::MAX_TEXT_LENGTH);
if ($text !== '') {
$texts[mb_strtolower($text)] ??= $text;
}
}
return array_slice(array_values($texts), 0, self::MAX_PREPARED);
}
/**
* Makes the prepared questions of a slide match `$texts`: unchanged ones keep their id, removed
* ones disappear (with leftover upvotes), new ones are added. Questions already asked by
* participants are not added twice. Only allowed while collecting: later, upvotes and the
* discussion hang on the existing questions. Idempotent.
*
* @param \App\Model\Entity\Slide $slide Q&A slide
* @param list<string> $texts Clean texts, see parsePrepared()
* @return void
*/
public function syncPrepared(Slide $slide, array $texts): void
{
if ($slide->qaStage() !== Slide::QA_COLLECT) {
return;
}
$wanted = [];
foreach ($texts as $text) {
$wanted[mb_strtolower($text)] = $text;
}
$existing = [];
$rows = $this->Responses->questionsOf($slide->id)
->select(['id', 'text_value', 'participant_hash'])
->orderBy(['Responses.id' => 'ASC'])
->disableHydration()
->all();
foreach ($rows as $row) {
$key = mb_strtolower((string)$row['text_value']);
if ($row['participant_hash'] !== VoteService::PREPARED_HASH) {
// Asked by a participant already.
unset($wanted[$key]);
continue;
}
if (isset($wanted[$key]) && !isset($existing[$key])) {
$existing[$key] = true;
unset($wanted[$key]);
continue;
}
$this->Responses->deleteAll(['slide_id' => $slide->id, 'parent_id' => $row['id']]);
$this->Responses->deleteAll(['id' => $row['id']]);
}
foreach ($wanted as $text) {
$this->Responses->saveOrFail($this->Responses->newEntity([
'slide_id' => $slide->id,
'participant_hash' => VoteService::PREPARED_HASH,
'text_value' => $text,
]));
}
}
/**
* Questions of a slide, most upvoted first (ties: oldest first).
*
* @param \App\Model\Entity\Slide $slide Q&A slide
* @return list<array{id: int, text: string, votes: int}>
*/
public function rankedQuestions(Slide $slide): array
{
$votes = $this->Responses->upvotesPerQuestion($slide->id);
$questions = [];
$rows = $this->Responses->questionsOf($slide->id)
->select(['id', 'text_value'])
->orderBy(['id' => 'ASC'])
->disableHydration()
->all();
foreach ($rows as $row) {
$id = (int)$row['id'];
$questions[] = ['id' => $id, 'text' => (string)$row['text_value'], 'votes' => $votes[$id] ?? 0];
}
usort($questions, fn($a, $b) => [$b['votes'], $a['id']] <=> [$a['votes'], $b['id']]);
return $questions;
}
/**
* Switches the stage. Collecting and voting open the slide for input,
* discussing closes it and puts the top question on screen. Setting the
* current stage again changes nothing. Without upvotes there is no voting stage.
*
* @param \App\Model\Entity\Slide $slide Q&A slide
* @param string $stage One of Slide::qaStages()
* @return \App\Model\Entity\Slide
*/
public function setStage(Slide $slide, string $stage): Slide
{
if (!$slide->isQa() || !in_array($stage, $slide->qaStages(), true)) {
throw new InvalidArgumentException('Unknown Q&A stage ' . $stage);
}
if ($slide->qaStage() === $stage && $slide->stage !== null) {
return $slide;
}
$slide->stage = $stage;
$slide->is_voting_open = $stage !== Slide::QA_DISCUSS;
$slide->focus_response_id = $stage === Slide::QA_DISCUSS
? ($this->rankedQuestions($slide)[0]['id'] ?? null)
: null;
$this->Slides->saveOrFail($slide);
return $slide;
}
/**
* Moves to the following stage (collect → vote → discuss, without upvotes collect → discuss).
*
* @param \App\Model\Entity\Slide $slide Q&A slide
* @return bool False when already discussing
*/
public function advance(Slide $slide): bool
{
$stages = $slide->qaStages();
$index = (int)array_search($slide->qaStage(), $stages, true);
if (!isset($stages[$index + 1])) {
return false;
}
$this->setStage($slide, $stages[$index + 1]);
return true;
}
/**
* Steps to the next/previous question while discussing.
*
* Saved without touching `modified`, so participant pages update live
* instead of reloading (see PollStateService version).
*
* @param \App\Model\Entity\Slide $slide Q&A slide
* @param int $step +1 next, -1 previous
* @return bool False when there is no such question (or not discussing)
*/
public function moveFocus(Slide $slide, int $step): bool
{
if (!$slide->isQa() || $slide->qaStage() !== Slide::QA_DISCUSS) {
return false;
}
$ids = array_column($this->rankedQuestions($slide), 'id');
$index = array_search($slide->focus_response_id, $ids, true);
$target = $index === false ? 0 : $index + $step;
if (!isset($ids[$target]) || $ids[$target] === $slide->focus_response_id) {
return false;
}
$this->Slides->updateAll(['focus_response_id' => $ids[$target]], ['id' => $slide->id]);
$slide->focus_response_id = $ids[$target];
$slide->setDirty('focus_response_id', false);
return true;
}
/**
* Back to the start after all responses were deleted.
*
* @param \App\Model\Entity\Slide $slide Q&A slide
* @return void
*/
public function reset(Slide $slide): void
{
$slide->stage = Slide::QA_COLLECT;
$slide->is_voting_open = true;
$slide->focus_response_id = null;
$this->Slides->saveOrFail($slide);
}
}