diff --git a/AGENTS.md b/AGENTS.md index 3cd0728..9b1a5d5 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -174,6 +174,12 @@ tests/ PHPUnit; PlenarioTestTrait erzeugt Testdaten, Fixtures (→/←, Klicker) zuerst durch die Fragen, erst danach durch die Folien. Fokuswechsel per `updateAll` ohne `modified`, damit Teilnehmerseiten nicht neu laden. Teilnehmende bekommen nie `results`, sondern `qa` aus `PollStateService::qaState()`. Zurücksetzen startet wieder bei `collect`. + **Vorab eingereichte Fragen** (z. B. per Mail): Textarea `prepared_text` im Folienformular (eine Frage pro Zeile, höchstens + `QaService::MAX_PREPARED`), nur in `collect` sichtbar/änderbar. `QaService::syncPrepared()` gleicht sie idempotent ab (gleiche Texte + behalten ihre id, entfernte verschwinden samt Upvotes, von Teilnehmenden schon gestellte werden nicht doppelt angelegt). Gespeichert + als normale Fragen mit `participant_hash = VoteService::PREPARED_HASH` (kein gültiger HMAC → niemand kann sie bearbeiten/löschen, + jeder darf sie unterstützen); sie zählen nicht als Teilnehmende. Zurücksetzen löscht sie wie alle Antworten, Duplizieren kopiert sie nicht. + Tests: `QaPreparedTest.php`. Eigene Fragen bearbeiten/löschen (`vote=edit|delete` + `question_id`, `VoteService::editQuestion()`) nur in `collect`: danach könnten Upvotes bzw. die Besprechung an einem anderen Text hängen. Bearbeiten prüft Dubletten ohne die eigene Frage, Löschen entfernt auch übrig gebliebene Upvotes (Presenter von `vote` zurück nach `collect`). Im JS hält `qaEditing` das diff --git a/src/Controller/SlidesController.php b/src/Controller/SlidesController.php index a9fa3ae..1d35254 100644 --- a/src/Controller/SlidesController.php +++ b/src/Controller/SlidesController.php @@ -48,11 +48,13 @@ class SlidesController extends AdminAppController $optionsText = $type === Slide::TYPE_CHOICE ? "\n" : ''; $quizOptions = []; $orderOptions = []; + $preparedText = ''; if ($this->request->is('post')) { $optionsText = (string)$this->request->getData('options_text', ''); $quizOptions = $this->postedQuizOptions(); $orderOptions = $this->postedOrderOptions(); + $preparedText = (string)$this->request->getData('prepared_text', ''); if ($this->saveSlide($slide, $optionsText)) { $this->Flash->success(__('Folie angelegt.')); @@ -60,7 +62,7 @@ class SlidesController extends AdminAppController } } - $this->set(compact('slide', 'optionsText', 'quizOptions', 'orderOptions')); + $this->set(compact('slide', 'optionsText', 'quizOptions', 'orderOptions', 'preparedText')); $this->render('form'); return null; @@ -76,11 +78,13 @@ class SlidesController extends AdminAppController $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 ?? []); + $preparedText = $slide->isQa() ? implode("\n", (new QaService())->preparedQuestions($slide)) : ''; if ($this->request->is(['post', 'put', 'patch'])) { $optionsText = (string)$this->request->getData('options_text', ''); $quizOptions = $this->postedQuizOptions(); $orderOptions = $this->postedOrderOptions(); + $preparedText = (string)$this->request->getData('prepared_text', $preparedText); if ($this->saveSlide($slide, $optionsText)) { $this->Flash->success(__('Folie gespeichert.')); @@ -89,7 +93,7 @@ class SlidesController extends AdminAppController } $hasResponses = $this->Slides->Responses->exists(['slide_id' => $slide->id]); - $this->set(compact('slide', 'optionsText', 'quizOptions', 'orderOptions', 'hasResponses')); + $this->set(compact('slide', 'optionsText', 'quizOptions', 'orderOptions', 'preparedText', 'hasResponses')); $this->render('form'); return null; @@ -334,6 +338,11 @@ class SlidesController extends AdminAppController if ($slide->type === Slide::TYPE_CHOICE || $slide->isQuiz() || $slide->isOrder()) { $this->Slides->syncOptions($slide, $labels, $correct); } + // Without the field (stage no longer "collect") the prepared questions stay untouched. + $prepared = $this->request->getData('prepared_text'); + if ($slide->isQa() && is_string($prepared)) { + (new QaService())->syncPrepared($slide, QaService::parsePrepared($prepared)); + } if ($slide->isQa() && $slide->qaStage() === Slide::QA_VOTE && !$slide->hasQaUpvotes()) { // Upvotes were switched off while voting: continue with the discussion. (new QaService())->setStage($slide, Slide::QA_DISCUSS); diff --git a/src/Model/Table/ResponsesTable.php b/src/Model/Table/ResponsesTable.php index 65e54b5..0f335d1 100644 --- a/src/Model/Table/ResponsesTable.php +++ b/src/Model/Table/ResponsesTable.php @@ -165,7 +165,7 @@ class ResponsesTable extends Table { $row = $this->find() ->select(['n' => $this->find()->func()->count('DISTINCT participant_hash')]) - ->where(['slide_id' => $slideId]) + ->where(['slide_id' => $slideId, 'participant_hash !=' => VoteService::PREPARED_HASH]) ->disableHydration() ->first(); @@ -186,7 +186,7 @@ class ResponsesTable extends Table 'n' => $this->find()->func()->count('DISTINCT Responses.participant_hash'), ]) ->innerJoinWith('Slides') - ->where(['Slides.poll_id' => $pollId]) + ->where(['Slides.poll_id' => $pollId, 'Responses.participant_hash !=' => VoteService::PREPARED_HASH]) ->groupBy(['Responses.slide_id']) ->disableHydration() ->all(); diff --git a/src/Service/QaService.php b/src/Service/QaService.php index bc401f4..d1a913a 100644 --- a/src/Service/QaService.php +++ b/src/Service/QaService.php @@ -27,6 +27,9 @@ 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; @@ -44,6 +47,95 @@ class QaService $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 + */ + 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 + */ + 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 $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). * diff --git a/src/Service/VoteService.php b/src/Service/VoteService.php index 0b0f71b..2fac4b8 100644 --- a/src/Service/VoteService.php +++ b/src/Service/VoteService.php @@ -49,6 +49,12 @@ class VoteService public const MAX_TEXT_LENGTH = 500; public const MAX_QA_QUESTIONS = 10; + /** + * participant_hash of questions entered by the admin beforehand (e.g. received by mail). + * Not a hex HMAC, so no participant can ever own, edit or delete them. + */ + public const PREPARED_HASH = 'prepared'; + /** * Word cloud: terms per request and terms a participant may name or upvote per slide. */ diff --git a/templates/Slides/form.php b/templates/Slides/form.php index 8c43533..bd0fe10 100644 --- a/templates/Slides/form.php +++ b/templates/Slides/form.php @@ -10,6 +10,7 @@ * @var string $optionsText * @var list $quizOptions * @var list $orderOptions Ordering slide: labels in the correct order + * @var string $preparedText Q&A slide: questions entered beforehand, one per line * @var bool|null $hasResponses */ @@ -330,6 +331,13 @@ $optionsError = $slide->getError('options_text'); 'aria-describedby' => 'qa-self-upvote-hint', ]) ?>

+ qaStage() === \App\Model\Entity\Slide::QA_COLLECT) : ?> +
+ + +

+
+

diff --git a/tests/TestCase/Controller/QaPreparedTest.php b/tests/TestCase/Controller/QaPreparedTest.php new file mode 100644 index 0000000..691abbe --- /dev/null +++ b/tests/TestCase/Controller/QaPreparedTest.php @@ -0,0 +1,123 @@ + + */ + protected array $fixtures = ['app.Polls', 'app.Slides', 'app.SlideOptions', 'app.Responses']; + + protected function setUp(): void + { + parent::setUp(); + $this->enableCsrfToken(); + } + + public function testParsePreparedCleansLines(): void + { + $texts = QaService::parsePrepared(" Wann geht's los? \n\nwann geht's LOS?\r\nZweite Frage"); + + $this->assertSame(["Wann geht's los?", 'Zweite Frage'], $texts); + } + + public function testCreatingSlideStoresPreparedQuestions(): void + { + [$poll, $token] = $this->createPoll(); + + $this->post("/admin/$token/slides/add", [ + 'type' => Slide::TYPE_QA, + 'question' => 'Fragen', + 'prepared_text' => "Frage A\nFrage B", + ]); + + $this->assertRedirect(); + $slide = $this->slidesTable()->listForPoll($poll->id)[0]; + $this->assertSame(['Frage A', 'Frage B'], (new QaService())->preparedQuestions($slide)); + } + + public function testEditSyncsAndIsIdempotent(): void + { + [$poll, $token] = $this->createPoll(); + $slide = $this->createSlide($poll, Slide::TYPE_QA); + $url = "/admin/$token/slides/{$slide->id}/edit"; + $data = ['question' => 'Fragen', 'prepared_text' => "Frage A\nFrage B"]; + + $this->post($url, $data); + $responses = TableRegistry::getTableLocator()->get('Responses'); + $ids = $responses->find()->where(['slide_id' => $slide->id])->all()->extract('id')->toList(); + $this->assertCount(2, $ids); + + $this->post($url, $data); + $this->assertSame($ids, $responses->find()->where(['slide_id' => $slide->id])->all()->extract('id')->toList()); + + $this->post($url, ['prepared_text' => "Frage B\nFrage C"] + $data); + $this->assertSame(['Frage B', 'Frage C'], (new QaService())->preparedQuestions($slide)); + } + + public function testParticipantQuestionsAreKeptAndNotDuplicated(): void + { + [$poll, $token] = $this->createPoll(); + $slide = $this->createSlide($poll, Slide::TYPE_QA); + $poll = $this->goLive($poll, $slide); + $hash = VoteService::participantHash(str_repeat('a', 32), $poll->id); + (new VoteService())->submit($poll, $slide, $hash, ['question' => 'Eigene Frage']); + + $this->post("/admin/$token/slides/{$slide->id}/edit", [ + 'question' => 'Fragen', + 'prepared_text' => "eigene frage\nVorab", + ]); + $this->post("/admin/$token/slides/{$slide->id}/edit", ['question' => 'Fragen', 'prepared_text' => '']); + + $responses = TableRegistry::getTableLocator()->get('Responses'); + $this->assertSame( + ['Eigene Frage'], + $responses->find()->where(['slide_id' => $slide->id])->all()->extract('text_value')->toList(), + ); + } + + public function testPreparedQuestionsAppearForParticipantsButNotAsOwn(): void + { + [$poll] = $this->createPoll(); + $slide = $this->createSlide($poll, Slide::TYPE_QA); + (new QaService())->syncPrepared($slide, ['Vorab']); + $poll = $this->goLive($poll, $slide); + $slide = $this->slidesTable()->get($slide->id); + + $hash = VoteService::participantHash(str_repeat('b', 32), $poll->id); + $qa = (new PollStateService())->qaState($slide, $hash); + + $this->assertCount(1, $qa['questions']); + $this->assertSame([], $qa['mine']); + $this->assertSame(0, TableRegistry::getTableLocator()->get('Responses')->countParticipants($slide->id)); + } + + public function testNotChangedOutsideCollectStage(): void + { + [$poll, $token] = $this->createPoll(); + $slide = $this->createSlide($poll, Slide::TYPE_QA); + (new QaService())->syncPrepared($slide, ['Vorab']); + (new QaService())->setStage($slide, Slide::QA_VOTE); + + $this->post("/admin/$token/slides/{$slide->id}/edit", ['question' => 'Fragen', 'prepared_text' => '']); + + $this->assertSame(['Vorab'], (new QaService())->preparedQuestions($slide)); + } +}