Feature/polls menu #84

Merged
gnilebein merged 2 commits from feature/polls-menu into main 2026-11-16 13:40:22 +01:00
8 changed files with 414 additions and 32 deletions

No files matched your search

+1 -1
View File
@@ -34,7 +34,7 @@ E-Mail anlegen, kein Login, Verwaltung über einen geheimen Admin-Link, Teilnahm
| Coding Standard | `vendor/bin/phpcs` / Autofix `vendor/bin/phpcbf` |
| Neue Migration | `bin/cake bake migration NameDerMigration` |
| Verwaiste Folienbilder löschen | `bin/cake images_cleanup [--dry-run]` |
| Umfragen verwalten (Admin-CLI) | `bin/cake polls list\|show\|delete\|remind\|cleanup` (siehe [docs/operations.md](docs/operations.md)) |
| Umfragen verwalten (Admin-CLI) | `bin/cake polls` (Menü) bzw. `polls list\|show\|delete\|remind\|cleanup` (siehe [docs/operations.md](docs/operations.md)) |
**Vor jedem Commit:** `vendor/bin/phpunit` und `vendor/bin/phpcs` müssen grün sein
(Warnungen zur Zeilenlänge bei langen deutschen Texten sind ok).
+1 -1
View File
@@ -24,7 +24,7 @@ src/
EmbedController /e/{key}/{id}: eine Folie zum Einbetten (z. B. Canva), activate/heartbeat/pause/control
ErrorController Fehlerseiten (Templates unter templates/Error, Layout `error`)
Command/ImagesCleanupCommand `images_cleanup`: Bilddateien ohne Folie entfernen (idempotent)
Command/Polls*Command `polls list|show|delete|remind|cleanup` (Basis `PollsCommand`: Suche per id/Code, Links, Löschen)
Command/Polls*Command `polls` (Menü), `polls list|show|delete|remind|cleanup` (Basis `PollsCommand`: Suche per id/Code, Links, Löschen)
Mailer/ PollMailer (adminLink, recovery; `sendSafely()` loggt Transportfehler statt zu werfen), Transport/FileTransport (lokal)
Middleware/ HostHeaderMiddleware: prüft in Produktion den Host gegen APP_FULL_BASE_URL;
SecurityHeadersMiddleware (äußerste Schicht): CSP mit Nonce, Framing, nosniff, Referrer-/Permissions-Policy
+6
View File
@@ -118,8 +118,14 @@ Bei Updates: Code aktualisieren, `composer install --no-dev`, Migrationen und `c
### Umfragen verwalten und aufräumen (CLI)
Am einfachsten geht es menügeführt: `bin/cake polls` ohne Unterbefehl zeigt ein Menü (nummerierte Liste mit Blättern:
`3` öffnet eine Umfrage, `d 2` oder `d 1,3,4` löscht direkt aus der Liste, `n`/`p` blättern; außerdem Suche nach
E-Mail, Details, Admin-Link, Erinnern, Aufräumen). Destruktive Aktionen zeigen vorher eine Vorschau
und fragen nach, jede Eingabe hat eine sichere Vorgabe (Zurück/Nein). Für Skripte und Cron gibt es die einzelnen Befehle:
| Befehl | Zweck |
|---|---|
| `bin/cake polls` | Menü (interaktiv) |
| `bin/cake polls list [--expired] [--email=text] [--sort=created\|activity\|title]` | Umfragen mit E-Mail, Ablaufdatum und Erinnerung |
| `bin/cake polls show <id\|code> [--link]` | Details; mit `--link` auch der geheime Admin-Link (nur auf Wunsch) |
| `bin/cake polls delete <id\|code> [--yes]` | Eine Umfrage samt Folien, Antworten und Bildern löschen (fragt nach) |
+4 -1
View File
@@ -13,7 +13,10 @@ Aufräumen und Erinnerungen, CI/CD, Release-Pakete, Container.
Aufräumen per Cron: `bin/cake polls cleanup` (erst `remind`, dann idempotent löschen über `PollsTable::delete()` samt
Folien/Bildern, danach `images_cleanup`; `--dry-run`; Cron-Einrichtung für Server und Docker steht in [deployment.md](deployment.md) unter
„Cronjob einrichten“, im Container läuft kein cron). `last_admin_access` fließt nicht mehr ein. `polls show --link`
ist die einzige Stelle, die den Admin-Link ausgibt (nie in `list`). Tests: `PollsCommandsTest.php` (leert vorher alle Umfragen).
ist die einzige Stelle, die den Admin-Link ausgibt (nie in `list`). Das Menü `bin/cake polls` (`PollsMenuCommand`) ruft nur diese Befehle per `executeCommand()` auf; die Liste ist nummeriert und seitenweise (`PAGE_SIZE`; `<Nr>` öffnet,
`d 1,3` löscht mehrere nach einer Rückfrage, `n`/`p` blättern, Tastatur-Pfeile gibt es bewusst nicht: nicht portabel, v. a. unter Windows); jede Abfrage hat eine
Vorgabe (`0`/leer/`n`), damit geschlossene Eingabe es beendet statt zu schleifen; Löschen/Aufräumen erst nach Vorschau (`--dry-run`) und Rückfrage.
Tests: `PollsCommandsTest.php` (leert vorher alle Umfragen).
## Deployment
+55
View File
@@ -26,6 +26,61 @@ abstract class PollsCommand extends Command
return $polls;
}
/**
* @param bool $expiredOnly Only expired polls
* @param string $email Only polls whose e-mail address contains this text (case-insensitive)
* @return list<\App\Model\Entity\Poll> Oldest first
*/
protected function findPolls(bool $expiredOnly = false, string $email = ''): array
{
$query = $this->polls()->find()
->select([
'Polls.id', 'Polls.title', 'Polls.email', 'Polls.join_code', 'Polls.current_slide_id',
'Polls.paused_slide_id', 'Polls.last_admin_access', 'Polls.expiry_reminded_at', 'Polls.created',
])
->orderBy(['Polls.id' => 'ASC']);
if ($expiredOnly) {
$query->find('expired');
}
if ($email !== '') {
$query->where(['Polls.email LIKE' => '%' . addcslashes(strtolower($email), '%_\\') . '%']);
}
/** @var list<\App\Model\Entity\Poll> $polls */
$polls = $query->all()->toList();
return $polls;
}
/**
* Prints polls as a table, optionally with a running number to pick from.
*
* @param list<\App\Model\Entity\Poll> $polls Polls
* @param \Cake\Console\ConsoleIo $io Console
* @param int $firstNumber Number of the first row (with $numbered)
* @param bool $numbered Add the number column
* @return void
*/
protected function printPolls(array $polls, ConsoleIo $io, int $firstNumber = 1, bool $numbered = false): void
{
$header = [__('ID'), __('Code'), __('Titel'), __('E-Mail'), __('Angelegt'), __('Letzter Admin-Besuch'), __('Läuft ab'), __('Erinnert')];
$rows = [$numbered ? array_merge(['#'], $header) : $header];
foreach ($polls as $i => $poll) {
$row = [
(string)$poll->id,
$poll->join_code,
mb_strimwidth($poll->title, 0, 40, '…'),
$poll->email,
$this->formatDate($poll->created),
$this->formatDate($poll->last_admin_access),
$this->formatExpiry($poll),
$this->formatDate($poll->expiry_reminded_at),
];
$rows[] = $numbered ? array_merge([(string)($firstNumber + $i)], $row) : $row;
}
$io->helper('Table')->output($rows);
}
/**
* Finds a poll by numeric id or join code ("K7P2QX", "k7p-2qx").
*
+2 -29
View File
@@ -51,22 +51,8 @@ class PollsListCommand extends PollsCommand
*/
public function execute(Arguments $args, ConsoleIo $io): int
{
$query = $this->polls()->find()
->select([
'Polls.id', 'Polls.title', 'Polls.email', 'Polls.join_code', 'Polls.current_slide_id',
'Polls.paused_slide_id', 'Polls.last_admin_access', 'Polls.expiry_reminded_at', 'Polls.created',
])
->orderBy(['Polls.id' => 'ASC']);
if ($args->getOption('expired')) {
$query->find('expired');
}
$email = $args->getOption('email');
if (is_string($email) && $email !== '') {
$query->where(['Polls.email LIKE' => '%' . addcslashes(strtolower($email), '%_\\') . '%']);
}
/** @var list<\App\Model\Entity\Poll> $polls */
$polls = $query->all()->toList();
$polls = $this->findPolls((bool)$args->getOption('expired'), is_string($email) ? $email : '');
$sort = (string)$args->getOption('sort');
if ($sort !== 'created') {
usort($polls, fn($a, $b): int => match ($sort) {
@@ -81,20 +67,7 @@ class PollsListCommand extends PollsCommand
return static::CODE_SUCCESS;
}
$rows = [[__('ID'), __('Code'), __('Titel'), __('E-Mail'), __('Angelegt'), __('Letzter Admin-Besuch'), __('Läuft ab'), __('Erinnert')]];
foreach ($polls as $poll) {
$rows[] = [
(string)$poll->id,
$poll->join_code,
mb_strimwidth($poll->title, 0, 40, '…'),
$poll->email,
$this->formatDate($poll->created),
$this->formatDate($poll->last_admin_access),
$this->formatExpiry($poll),
$this->formatDate($poll->expiry_reminded_at),
];
}
$io->helper('Table')->output($rows);
$this->printPolls($polls, $io);
$expired = count(array_filter($polls, fn($poll): bool => $poll->isExpired()));
$io->out(__('{0} Umfrage(n), davon {1} abgelaufen.', count($polls), $expired));
+262
View File
@@ -0,0 +1,262 @@
<?php
declare(strict_types=1);
namespace App\Command;
use App\Model\Entity\Poll;
use Cake\Console\Arguments;
use Cake\Console\ConsoleIo;
use Cake\Console\ConsoleOptionParser;
/**
* Menu-driven entry to the poll administration: `bin/cake polls` without a sub command.
* Only wraps the other `polls …` commands, so scripts and cron keep using those directly.
* Every prompt has a safe default (back/quit/no), so a closed stdin ends the menu instead of looping.
*
* Usage: bin/cake polls
*/
class PollsMenuCommand extends PollsCommand
{
/**
* Polls per page of the list.
*/
protected const PAGE_SIZE = 15;
/**
* @return string
*/
public static function defaultName(): string
{
return 'polls';
}
/**
* @param \Cake\Console\ConsoleOptionParser $parser Parser
* @return \Cake\Console\ConsoleOptionParser
*/
protected function buildOptionParser(ConsoleOptionParser $parser): ConsoleOptionParser
{
return $parser
->setDescription(__('Menügeführte Verwaltung der Umfragen. Für Skripte und Cron: polls list|show|delete|remind|cleanup.'));
}
/**
* @param \Cake\Console\Arguments $args Arguments
* @param \Cake\Console\ConsoleIo $io Console
* @return int
*/
public function execute(Arguments $args, ConsoleIo $io): int
{
while (true) {
$io->out('');
$io->out('<info>' . __('PlenarIO – Umfragen verwalten') . '</info>');
$io->out([
' 1) ' . __('Alle Umfragen (durchblättern, öffnen, löschen)'),
' 2) ' . __('Abgelaufene Umfragen anzeigen'),
' 3) ' . __('Nach E-Mail-Adresse suchen'),
' 4) ' . __('Umfrage öffnen (Details, Admin-Link, Löschen)'),
' 5) ' . __('Erinnerungen vor dem Ablauf versenden'),
' 6) ' . __('Aufräumen (Erinnern, abgelaufene Umfragen löschen)'),
' 0) ' . __('Beenden'),
]);
switch ($io->askChoice(__('Was möchtest du tun?'), ['1', '2', '3', '4', '5', '6', '0'], '0')) {
case '1':
$this->browse($io);
break;
case '2':
$this->browse($io, true);
break;
case '3':
$email = $io->ask(__('Teil der E-Mail-Adresse (leer = zurück)'), '');
if ($email !== '') {
$this->browse($io, false, $email);
}
break;
case '4':
$this->openPoll($io);
break;
case '5':
$this->confirmed($io, PollsRemindCommand::class, $this->polls()->find('reminderDue')->count());
break;
case '6':
$this->confirmed($io, PollsCleanupCommand::class, $this->polls()->find('expired')->count()
+ $this->polls()->find('reminderDue')->count());
break;
default:
return static::CODE_SUCCESS;
}
}
}
/**
* Shows what a command would do (--dry-run), asks and only then runs it for real.
*
* @param \Cake\Console\ConsoleIo $io Console
* @param class-string<\Cake\Command\Command> $command Command with a --dry-run option
* @param int $affected Number of polls the command would touch
* @return void
*/
protected function confirmed(ConsoleIo $io, string $command, int $affected): void
{
if ($affected === 0) {
$io->out(__('Nichts zu tun.'));
return;
}
$this->executeCommand($command, ['--dry-run'], $io);
if ($io->askChoice(__('Jetzt ausführen?'), ['y', 'n'], 'n') === 'y') {
$this->executeCommand($command, [], $io);
} else {
$io->out(__('Abgebrochen.'));
}
}
/**
* Pageable, numbered poll list. Pick by number: open (details, admin link, delete) or delete several at once.
*
* @param \Cake\Console\ConsoleIo $io Console
* @param bool $expiredOnly Only expired polls
* @param string $email Filter by part of the e-mail address
* @return void
*/
protected function browse(ConsoleIo $io, bool $expiredOnly = false, string $email = ''): void
{
$page = 0;
while (true) {
// Reloaded each round: deleted polls disappear, numbers stay consistent with what is shown.
$polls = $this->findPolls($expiredOnly, $email);
if ($polls === []) {
$io->out(__('Keine Umfragen gefunden.'));
return;
}
$pages = (int)ceil(count($polls) / self::PAGE_SIZE);
$page = max(0, min($page, $pages - 1));
$offset = $page * self::PAGE_SIZE;
$shown = array_slice($polls, $offset, self::PAGE_SIZE);
$io->out('');
$this->printPolls($shown, $io, $offset + 1, true);
$io->out(__('{0} Umfrage(n), Seite {1} von {2}.', count($polls), $page + 1, $pages));
$io->out(__('Nummer = öffnen · d 2 = löschen (mehrere: d 1,3,4) · n = weiter · p = zurück · leer = Menü'));
$input = strtolower($io->ask(__('Eingabe'), ''));
if ($input === '' || $input === 'q') {
return;
}
if ($input === 'n') {
$page++;
} elseif ($input === 'p') {
$page--;
} elseif (preg_match('/^d\s*([\d\s,]+)$/', $input, $m) === 1) {
$this->deleteByNumbers($io, $polls, $m[1]);
} elseif (ctype_digit($input) && isset($polls[(int)$input - 1])) {
$this->pollActions($io, $polls[(int)$input - 1]);
} else {
$io->err(__('Das habe ich nicht verstanden.'));
}
}
}
/**
* Deletes the polls with the given list numbers after one confirmation.
*
* @param \Cake\Console\ConsoleIo $io Console
* @param list<\App\Model\Entity\Poll> $polls The numbered list (number = index + 1)
* @param string $numbers "1,3 4"
* @return void
*/
protected function deleteByNumbers(ConsoleIo $io, array $polls, string $numbers): void
{
$selected = [];
foreach (preg_split('/[\s,]+/', trim($numbers), -1, PREG_SPLIT_NO_EMPTY) ?: [] as $number) {
if (!isset($polls[(int)$number - 1])) {
$io->err(__('Nummer {0} gibt es nicht, nichts gelöscht.', $number));
return;
}
$poll = $polls[(int)$number - 1];
$selected[$poll->id] = $poll;
}
if ($selected === []) {
return;
}
foreach ($selected as $poll) {
$io->out(__('#{0} {1} ({2}), angelegt {3}', $poll->id, $poll->title, $poll->email, $this->formatDate($poll->created)));
}
if ($io->askChoice(__('{0} Umfrage(n) endgültig löschen?', count($selected)), ['y', 'n'], 'n') === 'y') {
$this->deletePolls($selected, $io);
} else {
$io->out(__('Abgebrochen.'));
}
}
/**
* Asks for one poll by id or code and offers the actions on it.
*
* @param \Cake\Console\ConsoleIo $io Console
* @return void
*/
protected function openPoll(ConsoleIo $io): void
{
$this->executeCommand(PollsListCommand::class, [], $io);
$reference = $io->ask(__('ID oder Code der Umfrage (leer = zurück)'), '');
if ($reference === '') {
return;
}
$poll = $this->findPoll($reference);
if ($poll === null) {
$io->err(__('Umfrage „{0}“ nicht gefunden.', $reference));
return;
}
$this->pollActions($io, $poll);
}
/**
* Details, admin link and delete for one poll, until the user goes back (or the poll is gone).
*
* @param \Cake\Console\ConsoleIo $io Console
* @param \App\Model\Entity\Poll $poll Poll
* @return void
*/
protected function pollActions(ConsoleIo $io, Poll $poll): void
{
$this->executeCommand(PollsShowCommand::class, [(string)$poll->id], $io);
while (true) {
$io->out([
'',
' 1) ' . __('Details anzeigen'),
' 2) ' . __('Admin-Link anzeigen (geheim!)'),
' 3) ' . __('Umfrage endgültig löschen'),
' 0) ' . __('Zurück'),
]);
$choice = $io->askChoice(__('#{0} {1}: Was möchtest du tun?', $poll->id, $this->shorten($poll)), ['1', '2', '3', '0'], '0');
if ($choice === '1') {
$this->executeCommand(PollsShowCommand::class, [(string)$poll->id], $io);
} elseif ($choice === '2') {
$this->executeCommand(PollsShowCommand::class, [(string)$poll->id, '--link'], $io);
} elseif ($choice === '3') {
// The delete command asks for confirmation itself.
$this->executeCommand(PollsDeleteCommand::class, [(string)$poll->id], $io);
if ($this->polls()->find()->where(['Polls.id' => $poll->id])->count() === 0) {
return;
}
} else {
return;
}
}
}
/**
* @param \App\Model\Entity\Poll $poll Poll
* @return string Title, shortened for prompts
*/
protected function shorten(Poll $poll): string
{
return mb_strimwidth($poll->title, 0, 40, '…');
}
}
@@ -118,6 +118,89 @@ class PollsCommandsTest extends TestCase
$this->assertExitError();
}
public function testMenuQuits(): void
{
$this->exec('polls', ['0']);
$this->assertExitSuccess();
$this->assertOutputContains('Umfragen verwalten');
}
public function testMenuListsAndOpensPollWithLink(): void
{
[, $token] = $this->createPoll('Menü-Umfrage', 'menu@example.org');
// Menu 1 (list), open row 1, show the link, back, leave the list, quit.
$this->exec('polls', ['1', '1', '2', '0', '', '0']);
$this->assertExitSuccess();
$this->assertOutputContains('menu@example.org');
$this->assertOutputContains('https://plenario.test/admin/' . $token);
$this->exec('polls', ['4', 'ZZZZZZ', '0']);
$this->assertExitSuccess();
$this->assertErrorContains('nicht gefunden');
}
public function testMenuDeleteNeedsConfirmation(): void
{
[$poll] = $this->createPoll();
$this->exec('polls', ['4', (string)$poll->id, '3', 'n', '0', '0']);
$this->assertSame(1, $this->pollsTable()->find()->where(['id' => $poll->id])->count());
$this->exec('polls', ['4', (string)$poll->id, '3', 'y', '0']);
$this->assertSame(0, $this->pollsTable()->find()->where(['id' => $poll->id])->count());
}
public function testMenuListDeletesByNumber(): void
{
[$a] = $this->createPoll('Eins', 'eins@example.org');
[$b] = $this->createPoll('Zwei', 'zwei@example.org');
[$c] = $this->createPoll('Drei', 'drei@example.org');
// Unknown number and cancelled confirmation delete nothing.
$this->exec('polls', ['1', 'd 9', 'd 1', 'n', '', '0']);
$this->assertErrorContains('Nummer 9 gibt es nicht');
$this->assertSame(3, $this->pollsTable()->find()->count());
// Several at once with one confirmation.
$this->exec('polls', ['1', 'd 1,3', 'y', '', '0']);
$this->assertExitSuccess();
$this->assertEquals([$b->id], $this->pollsTable()->find()->all()->extract('id')->toList());
// Last one gone: the empty list returns to the menu by itself.
$this->exec('polls', ['1', 'd1', 'y', '0']);
$this->assertSame(0, $this->pollsTable()->find()->count());
$this->assertNotEmpty($a->id . $c->id);
}
public function testMenuListPagesThroughManyPolls(): void
{
for ($i = 1; $i <= 16; $i++) {
$this->createPoll('Umfrage ' . $i, 'p' . $i . '@example.org');
}
$this->exec('polls', ['1', 'n', 'p', '', '0']);
$this->assertExitSuccess();
$this->assertOutputContains('Seite 1 von 2');
$this->assertOutputContains('Seite 2 von 2');
$this->assertOutputContains('p16@example.org');
}
public function testMenuCleanupAsksBeforeDeleting(): void
{
[$old] = $this->createPoll();
$this->age($old->id, 100);
$this->exec('polls', ['6', 'n', '0']);
$this->assertSame(1, $this->pollsTable()->find()->count());
$this->exec('polls', ['6', 'y', '0']);
$this->assertSame(0, $this->pollsTable()->find()->count());
$this->exec('polls', ['6', '0']);
$this->assertOutputContains('Nichts zu tun.');
}
public function testReminderGoesOutOnceInTheLastDaysBeforeExpiry(): void
{
[$young, $youngToken] = $this->createPoll('Jung', 'jung@example.org');