From e72616fdbf2d6852aa62a16acaa66d430b5e21aa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bj=C3=B6rn=20Fromme?= Date: Tue, 10 Nov 2026 16:38:51 +0100 Subject: [PATCH] feat: keep questionnaires until submitted, remind teamers daily and take bus feedback per leg --- config/email_texts.yaml | 13 ++ config/questionnaires/bus_feedback.yaml | 13 +- config/services.yaml | 11 +- migrations/Version20261110120000.php | 34 ++++ src/Command/CronCommand.php | 5 + src/Config/EmailTextKey.php | 1 + src/Config/QuestionnaireCatalog.php | 24 ++- .../Questionnaire/DetailController.php | 5 +- .../Questionnaire/TestController.php | 10 +- src/Controller/Teamer/IndexController.php | 2 +- .../Teamer/Questionnaire/DetailController.php | 13 +- .../Teamer/Questionnaire/EditController.php | 61 ++++-- src/Entity/QuestionnaireResponse.php | 28 ++- src/Enum/BusLeg.php | 21 +++ src/Form/QuestionnaireType.php | 168 +++++++++++++++-- src/Model/Questionnaire/Definition.php | 4 + src/Repository/DispositionRepository.php | 160 ++++++++++------ .../QuestionnaireResponseRepository.php | 8 +- src/Security/Voter/DispositionVoter.php | 9 +- .../Cron/QuestionnaireReminderService.php | 73 ++++++++ .../questionnaire/detail.html.twig | 6 +- .../questionnaire/index.html.twig | 12 +- .../questionnaire/test.html.twig | 2 +- templates/forms.html.twig | 14 ++ templates/teamer/index.html.twig | 3 +- .../teamer/questionnaire/detail.html.twig | 2 +- tests/Config/QuestionnaireCatalogTest.php | 25 ++- .../Config/QuestionnaireCompletenessTest.php | 11 +- .../Questionnaire/TestControllerTest.php | 2 +- .../Questionnaire/EditControllerTest.php | 98 +++++++--- tests/Entity/QuestionnaireResponseTest.php | 23 +++ tests/Form/QuestionnaireTypeTest.php | 175 ++++++++++++++---- ...DispositionRepositoryQuestionnaireTest.php | 122 +++++++++++- .../Repository/QuestionnaireFixturesTrait.php | 31 +++- tests/Security/Voter/DispositionVoterTest.php | 38 ++-- .../Cron/QuestionnaireReminderServiceTest.php | 111 +++++++++++ tests/Twig/QuestionnaireTemplateTest.php | 19 +- 37 files changed, 1119 insertions(+), 238 deletions(-) create mode 100644 migrations/Version20261110120000.php create mode 100644 src/Enum/BusLeg.php create mode 100644 src/Service/Cron/QuestionnaireReminderService.php create mode 100644 tests/Service/Cron/QuestionnaireReminderServiceTest.php diff --git a/config/email_texts.yaml b/config/email_texts.yaml index 8a36c99..40c5db0 100644 --- a/config/email_texts.yaml +++ b/config/email_texts.yaml @@ -190,6 +190,18 @@ texts: Im E&P-Team Portal findest du unter "Saisonunterlagen" die Vorlagen zum Herunterladen und kannst deine unterschriebenen Unterlagen direkt hochladen. + # Daily, from the day after the trip ends, for as long as a questionnaire of the placement is + # not submitted. One mail per teamer, listing every such placement. + reminder_questionnaire: + label: 'Erinnerung: Feedbackbogen ausfüllen' + placeholders: ['destinations'] + subject: 'Reminder: Offener Feedbackbogen' + headline: 'Hallo aus Köln,' + body: |- + für folgende Einsätze fehlt uns noch dein Feedbackbogen: **{destinations}** + + Bitte fülle ihn spätestens drei Tage nach Reiseende aus. Du findest ihn im E&P-Team Portal auf deiner Startseite. Ein gespeicherter Entwurf zählt erst, wenn du ihn abschickst. + reminder_invoice_upload: label: 'Erinnerung: Honorarnote hochladen' placeholders: ['destination', 'invoiceUploadDeadlineDays'] @@ -273,4 +285,5 @@ placeholders: dateTo: 'Ende des Einsatzes' diffInDays: 'Tage bis zum Beginn des Einsatzes' tasks: 'Noch offene Punkte der Saison-Checkliste, kommagetrennt' + destinations: 'Einsätze mit noch offenem Feedbackbogen, kommagetrennt' workMonth: 'Monat der Arbeitszeiten, z. B. "März 2026"' diff --git a/config/questionnaires/bus_feedback.yaml b/config/questionnaires/bus_feedback.yaml index 6d5dc2a..aebab6a 100644 --- a/config/questionnaires/bus_feedback.yaml +++ b/config/questionnaires/bus_feedback.yaml @@ -1,5 +1,7 @@ # Questionnaire a teamer fills in after a placement with bus escort, in addition to # teamer_feedback.yaml and on the same page (App\Service\Questionnaire\DispositionContext). +# Answered once per ride: the teamer first says whether they escorted the outbound bus, the return +# bus or both (per_bus_leg), and fills in these sections for each, stored as one response per leg. # # Replaces the Google form "Bus-Feedback 25-26"; the question-by-question spec, with every decision # taken, is kept locally outside the repository. Questions whose answer the @@ -12,6 +14,8 @@ # # Parsed and validated by App\Config\QuestionnaireCatalog; QuestionnaireCatalogTest builds it. # +# per_bus_leg: answered once per escorted ride (App\Enum\BusLeg) instead of once per placement. +# # Question fields: key, label, type (text | textarea | choice | multi | date | rating), # required (default false), help, widget (choice only: radio | dropdown, default radio), # options (choice and multi only), show_if ({question, equals | in | lte}, earlier questions only). @@ -19,19 +23,12 @@ key: bus_feedback version: 1 title: "Bus-Feedback" +per_bus_leg: true sections: - key: bus_trip title: "Busfahrt" questions: - - key: direction - label: "Hin- oder Rückfahrt" - type: choice - required: true - options: - - { key: outbound, label: "Hinfahrt" } - - { key: return, label: "Rückfahrt" } - - key: bus_company label: "Bus-Unternehmen:" type: choice diff --git a/config/services.yaml b/config/services.yaml index d4a9b2f..41dbce8 100644 --- a/config/services.yaml +++ b/config/services.yaml @@ -122,9 +122,10 @@ parameters: season_end: '04-01' # The teamer questionnaires after a placement (config/questionnaires/teamer_feedback.yaml, plus - # bus_feedback.yaml for a bus escort) are offered for placements that ended within this many - # days. Without a window every past placement would show up as pending on the teamers' dashboards. - questionnaire_window_days: 30 + # bus_feedback.yaml for a bus escort) are offered for placements ending on or after this day + # (Y-m-d), and stay pending - on the dashboard and in the daily reminder - until submitted. + # Without a cutoff every past placement would be pending at once. + questionnaire_go_live: '2026-11-10' # How far ahead of the destination's first travel day a season assignment's checklist # entries fall due. A relative date expression, applied to destination.dateFrom, and the @@ -189,7 +190,7 @@ services: $emailTextsFile: '%kernel.project_dir%/config/email_texts.yaml' # Likewise parsed on demand, by App\Config\QuestionnaireCatalog. $questionnaireDir: '%kernel.project_dir%/config/questionnaires' - $questionnaireWindowDays: '%questionnaire_window_days%' + $questionnaireGoLive: '%questionnaire_go_live%' $mailingBusTransport: '%mailing_bus_transport%' $seasonStart: '%season_start%' $seasonEnd: '%season_end%' @@ -515,3 +516,5 @@ when@test: # a job profile id ListControllerTest inserts itself - db_test has no job profiles assignment_export.job_profile_ids: [ 900001 ] mailing_bus_transport: 'sync' + # the questionnaire tests need it offered; any day before the placements they create + questionnaire_go_live: '2026-01-01' diff --git a/migrations/Version20261110120000.php b/migrations/Version20261110120000.php new file mode 100644 index 0000000..113cd3c --- /dev/null +++ b/migrations/Version20261110120000.php @@ -0,0 +1,34 @@ +addSql("ALTER TABLE questionnaire_response ADD leg VARCHAR(16) DEFAULT '' NOT NULL"); + $this->addSql('DROP INDEX questionnaire_disposition ON questionnaire_response'); + $this->addSql('CREATE UNIQUE INDEX questionnaire_disposition_leg ON questionnaire_response (questionnaire, disposition_id, leg)'); + } + + public function down(Schema $schema): void + { + $this->addSql('DROP INDEX questionnaire_disposition_leg ON questionnaire_response'); + $this->addSql('CREATE UNIQUE INDEX questionnaire_disposition ON questionnaire_response (questionnaire, disposition_id)'); + $this->addSql('ALTER TABLE questionnaire_response DROP leg'); + } +} diff --git a/src/Command/CronCommand.php b/src/Command/CronCommand.php index a65d8c0..3e5311c 100644 --- a/src/Command/CronCommand.php +++ b/src/Command/CronCommand.php @@ -6,6 +6,7 @@ use App\Service\Cron\DispositionReminderService; use App\Service\Cron\DispositionStatusService; use App\Service\Cron\FeedbackReminderService; use App\Service\Cron\FlushLogsService; +use App\Service\Cron\QuestionnaireReminderService; use App\Service\Cron\SeasonTaskReminderService; use App\Service\Cron\UploadReminderService; use App\Service\Cron\WorkMonthReminderService; @@ -29,6 +30,7 @@ class CronCommand extends Command private readonly DispositionReminderService $dispositionReminderService, private readonly SeasonTaskReminderService $seasonTaskReminderService, private readonly WorkMonthReminderService $workMonthReminderService, + private readonly QuestionnaireReminderService $questionnaireReminderService, ) { parent::__construct(); } @@ -68,6 +70,9 @@ class CronCommand extends Command $message = $this->workMonthReminderService->sendReminders(); $io->info($message); + $message = $this->questionnaireReminderService->sendReminders(); + $io->info($message); + return Command::SUCCESS; } } diff --git a/src/Config/EmailTextKey.php b/src/Config/EmailTextKey.php index 001cdc3..cd884bc 100644 --- a/src/Config/EmailTextKey.php +++ b/src/Config/EmailTextKey.php @@ -22,6 +22,7 @@ enum EmailTextKey: string case REMINDER_INVOICE_UPLOAD = 'reminder_invoice_upload'; case REMINDER_INVOICE_UPLOAD_FINAL = 'reminder_invoice_upload_final'; case REMINDER_DISPOSITION = 'reminder_disposition'; + case REMINDER_QUESTIONNAIRE = 'reminder_questionnaire'; case REMINDER_SEASON_TASKS = 'reminder_season_tasks'; case REMINDER_WORK_MONTH_UPLOAD = 'reminder_work_month_upload'; case WORK_MONTH_REJECTED = 'work_month_rejected'; diff --git a/src/Config/QuestionnaireCatalog.php b/src/Config/QuestionnaireCatalog.php index 4b2e16b..80c2cc2 100644 --- a/src/Config/QuestionnaireCatalog.php +++ b/src/Config/QuestionnaireCatalog.php @@ -35,7 +35,7 @@ class QuestionnaireCatalog */ public const string BUS_FEEDBACK = 'bus_feedback'; - private const array ROOT_FIELDS = ['key', 'version', 'title', 'description', 'sections']; + private const array ROOT_FIELDS = ['key', 'version', 'title', 'description', 'per_bus_leg', 'sections']; private const array SECTION_FIELDS = ['key', 'title', 'questions']; private const array QUESTION_FIELDS = ['key', 'label', 'type', 'required', 'help', 'widget', 'options', 'show_if']; private const array OPTION_FIELDS = ['key', 'label']; @@ -57,17 +57,14 @@ class QuestionnaireCatalog } /** - * The first end date the teamer questionnaire is still offered for: the services.yaml - * parameter questionnaire_window_days, in days before today. Placements that ended earlier are neither - * pending nor open, so a deploy does not offer it for every past placement at once. + * The services.yaml parameter questionnaire_go_live as a date: the teamer questionnaire is + * offered for placements ending on or after it, and stays pending until submitted. Without + * it, every past placement would be pending and reminded of at once. */ - public static function windowStart(int $windowDays): \DateTimeImmutable + public static function parseGoLive(string $goLive): \DateTimeImmutable { - if ($windowDays < 0) { - throw new \InvalidArgumentException(sprintf('questionnaire_window_days must not be negative, got %d', $windowDays)); - } - - return new \DateTimeImmutable(sprintf('today -%d days', $windowDays)); + return \DateTimeImmutable::createFromFormat('!Y-m-d', $goLive) + ?: throw new \InvalidArgumentException(sprintf('questionnaire_go_live "%s" is not a Y-m-d date', $goLive)); } /** @@ -150,6 +147,12 @@ class QuestionnaireCatalog throw $this->error($file, 'sections must be a non-empty list'); } + $perBusLeg = $data['per_bus_leg'] ?? false; + + if (!is_bool($perBusLeg)) { + throw $this->error($file, 'per_bus_leg must be true or false'); + } + $sections = []; $sectionKeys = []; /** @var array $questions every question parsed so far, for show_if */ @@ -189,6 +192,7 @@ class QuestionnaireCatalog $this->string($data['title'], 'title', $file), $this->optionalString($data['description'] ?? null, 'description', $file), $sections, + $perBusLeg, ); } diff --git a/src/Controller/Administrative/Questionnaire/DetailController.php b/src/Controller/Administrative/Questionnaire/DetailController.php index a7aa593..1716ef5 100644 --- a/src/Controller/Administrative/Questionnaire/DetailController.php +++ b/src/Controller/Administrative/Questionnaire/DetailController.php @@ -42,9 +42,10 @@ class DetailController extends AbstractController throw new NotFoundHttpException(); } - // the other questionnaire of the same placement, e.g. the bus feedback beside the teamer feedback + // the other responses of the same placement, e.g. the bus feedback beside the teamer feedback, + // or the other leg's $siblings = array_filter( - $this->responseRepository->findByDisposition($response->getDisposition()), + array_merge(...array_values($this->responseRepository->findByDisposition($response->getDisposition()))), static fn (QuestionnaireResponse $sibling): bool => $sibling !== $response && $sibling->isSubmitted(), ); diff --git a/src/Controller/Administrative/Questionnaire/TestController.php b/src/Controller/Administrative/Questionnaire/TestController.php index f6fa118..bd2bd5a 100644 --- a/src/Controller/Administrative/Questionnaire/TestController.php +++ b/src/Controller/Administrative/Questionnaire/TestController.php @@ -6,7 +6,6 @@ use App\Config\QuestionnaireCatalog; use App\Controller\Traits\ReturnUrlTrait; use App\Entity\Assignment; use App\Form\QuestionnaireType; -use App\Model\Questionnaire\Definition; use Symfony\Bridge\Doctrine\Attribute\MapEntity; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\HttpFoundation\Request; @@ -54,10 +53,11 @@ class TestController extends AbstractController if ($form->isSubmitted() && $form->isValid()) { if (QuestionnaireType::isFinal($form)) { - $submitted = array_map(static fn (Definition $definition): array => [ - 'definition' => $definition, - 'answers' => $definition->withoutHiddenAnswers($form->getData()[$definition->key] ?? []), - ], $definitions); + $submitted = array_map(static fn (array $set): array => [ + 'definition' => $set['definition'], + 'leg' => $set['leg'], + 'answers' => $set['definition']->withoutHiddenAnswers($set['answers']), + ], QuestionnaireType::answerSets($form->getData(), $definitions)); } else { $draft = true; } diff --git a/src/Controller/Teamer/IndexController.php b/src/Controller/Teamer/IndexController.php index 704a808..da8ceca 100644 --- a/src/Controller/Teamer/IndexController.php +++ b/src/Controller/Teamer/IndexController.php @@ -77,7 +77,7 @@ class IndexController extends AbstractController ->getRepository(Disposition::class) ->findPendingQuestionnaireByTeamer( $teamer, - QuestionnaireCatalog::windowStart((int) $this->getParameter('questionnaire_window_days')), + QuestionnaireCatalog::parseGoLive($this->getParameter('questionnaire_go_live')), ) ; diff --git a/src/Controller/Teamer/Questionnaire/DetailController.php b/src/Controller/Teamer/Questionnaire/DetailController.php index a94feb8..142264f 100644 --- a/src/Controller/Teamer/Questionnaire/DetailController.php +++ b/src/Controller/Teamer/Questionnaire/DetailController.php @@ -4,6 +4,7 @@ namespace App\Controller\Teamer\Questionnaire; use App\Config\QuestionnaireCatalog; use App\Entity\Disposition; +use App\Entity\QuestionnaireResponse; use App\Repository\QuestionnaireResponseRepository; use App\Service\Questionnaire\DispositionContext; use Symfony\Bridge\Doctrine\Attribute\MapEntity; @@ -13,8 +14,8 @@ use Symfony\Component\Routing\Attribute\Route; use Symfony\Component\Security\Http\Attribute\IsGranted; /** - * The teamer's own submitted questionnaires for a placement, read-only, each rendered with the - * definition version it was submitted under. + * The teamer's own submitted questionnaires for a placement, read-only - the bus feedback once per + * escorted leg - each rendered with the definition version it was submitted under. */ class DetailController extends AbstractController { @@ -39,16 +40,16 @@ class DetailController extends AbstractController $keys = array_unique([...DispositionContext::questionnaires($disposition->getAssignment()), ...array_keys($responses)]); foreach ($keys as $key) { - $response = $responses[$key] ?? null; + $done = array_filter($responses[$key] ?? [], static fn (QuestionnaireResponse $response): bool => $response->isSubmitted()); - if (true === $response?->isSubmitted()) { + foreach ($done as $response) { $submitted[] = [ 'definition' => $this->catalog->get($key, $response->getVersion()), 'response' => $response, ]; - } else { - $open = true; } + + $open = $open || [] === $done; } if ([] === $submitted) { diff --git a/src/Controller/Teamer/Questionnaire/EditController.php b/src/Controller/Teamer/Questionnaire/EditController.php index b4d0a38..007c5d5 100644 --- a/src/Controller/Teamer/Questionnaire/EditController.php +++ b/src/Controller/Teamer/Questionnaire/EditController.php @@ -19,8 +19,8 @@ use Symfony\Component\Security\Http\Attribute\IsGranted; /** * The teamer's questionnaires after a placement on one page: the teamer feedback, and after a bus - * escort the bus feedback too. Saved as drafts until submitted; one submit submits all of them, - * each as a response of its own. Submitted ones are final and only shown read-only + * escort the bus feedback too, once per ride the teamer escorted. Saved as drafts until submitted; + * one submit submits all of them, each questionnaire and leg as a response of its own. Submitted ones are final and only shown read-only * (DetailController). * * Only the questionnaires not yet submitted are offered, so one that applies later - an escort @@ -48,7 +48,7 @@ class EditController extends AbstractController $definitions = []; foreach (DispositionContext::questionnaires($disposition->getAssignment()) as $key) { - if (true !== ($responses[$key] ?? null)?->isSubmitted()) { + if ([] === array_filter($responses[$key] ?? [], static fn (QuestionnaireResponse $response): bool => $response->isSubmitted())) { $definitions[] = $this->catalog->get($key); } } @@ -60,7 +60,14 @@ class EditController extends AbstractController $data = []; foreach ($definitions as $definition) { - $data[$definition->key] = ($responses[$definition->key] ?? null)?->getAnswers() ?? []; + $stored = $responses[$definition->key] ?? []; + + $data[$definition->key] = $definition->perBusLeg + ? QuestionnaireType::legData(array_column(array_map( + static fn (QuestionnaireResponse $response): array => [$response->getLeg()->value, $response->getAnswers()], + $stored, + ), 1, 0)) + : ($stored[0] ?? null)?->getAnswers() ?? []; } $form = $this->createForm(QuestionnaireType::class, $data, ['definitions' => $definitions]); @@ -69,31 +76,57 @@ class EditController extends AbstractController if ($form->isSubmitted() && $form->isValid()) { $context = DispositionContext::build($disposition); $final = QuestionnaireType::isFinal($form); + $saved = []; - foreach ($definitions as $definition) { - $response = $responses[$definition->key] ?? null; + foreach (QuestionnaireType::answerSets($form->getData(), $definitions) as ['definition' => $definition, 'leg' => $leg, 'answers' => $answers]) { + $response = array_find( + $responses[$definition->key] ?? [], + static fn (QuestionnaireResponse $response): bool => $response->getLeg() === $leg, + ); if (null === $response) { - $response = QuestionnaireResponse::forDisposition($definition, $disposition); + $response = QuestionnaireResponse::forDisposition($definition, $disposition, $leg); $this->entityManager->persist($response); - $responses[$definition->key] = $response; } - $answers = $form->getData()[$definition->key] ?? []; - if (true === $final) { $response->submit($definition, $answers, $context, new \DateTimeImmutable()); } else { $response->saveDraft($answers, $context); } + + $saved[] = $response; + } + + // the draft of a bus leg the teamer no longer says they escorted; never submitted, so + // nothing refers to it + $dropped = []; + + foreach ($definitions as $definition) { + foreach ($responses[$definition->key] ?? [] as $response) { + if (!in_array($response, $saved, true)) { + $this->entityManager->remove($response); + $dropped[] = $response; + } + } } $this->entityManager->flush(); - foreach ($definitions as $definition) { + foreach ($saved as $response) { $this->logger->info($final ? 'Submit questionnaire' : 'Save questionnaire draft', [ - 'questionnaire' => $definition->key, - 'questionnaire_response_id' => $responses[$definition->key]->getId(), + 'questionnaire' => $response->getQuestionnaire(), + 'leg' => $response->getLeg()?->value, + 'questionnaire_response_id' => $response->getId(), + 'disposition_id' => $disposition->getId(), + 'teamer_id' => $disposition->getTeamer()->getId(), + ]); + } + + foreach ($dropped as $response) { + $this->logger->info('Remove questionnaire draft of a bus leg no longer chosen', [ + 'questionnaire' => $response->getQuestionnaire(), + 'leg' => $response->getLeg()?->value, 'disposition_id' => $disposition->getId(), 'teamer_id' => $disposition->getTeamer()->getId(), ]); @@ -110,7 +143,7 @@ class EditController extends AbstractController return $this->redirectToRoute('app_teamer_questionnaire_edit', ['uuid' => $disposition->getUuid()]); } - $drafts = array_filter($responses, static fn (QuestionnaireResponse $response): bool => !$response->isSubmitted()); + $drafts = array_filter(array_merge(...array_values($responses)), static fn (QuestionnaireResponse $response): bool => !$response->isSubmitted()); return $this->render('teamer/questionnaire/edit.html.twig', [ 'disposition' => $disposition, diff --git a/src/Entity/QuestionnaireResponse.php b/src/Entity/QuestionnaireResponse.php index 93454bb..4024056 100644 --- a/src/Entity/QuestionnaireResponse.php +++ b/src/Entity/QuestionnaireResponse.php @@ -4,6 +4,7 @@ namespace App\Entity; use App\Entity\Traits\BlameableEntity; use App\Entity\Traits\TimestampableEntity; +use App\Enum\BusLeg; use App\Enum\QuestionnaireResponseStatus; use App\Model\Questionnaire\Definition; use App\Repository\QuestionnaireResponseRepository; @@ -19,6 +20,9 @@ use Symfony\Component\Uid\Uuid; * who, where, when and the escort pickup - so those questions are not asked and the response stays * readable when the assignment is edited later. * + * A per-bus-leg questionnaire (Definition::$perBusLeg) has one response per escorted leg, the + * others one per disposition. + * * Its subject is a Disposition today. A questionnaire about something else gets a nullable foreign * key of its own beside $disposition, not a generic subject column. * @@ -26,7 +30,7 @@ use Symfony\Component\Uid\Uuid; */ #[ORM\Entity(repositoryClass: QuestionnaireResponseRepository::class)] #[ORM\HasLifecycleCallbacks] -#[ORM\UniqueConstraint(name: 'questionnaire_disposition', columns: ['questionnaire', 'disposition_id'])] +#[ORM\UniqueConstraint(name: 'questionnaire_disposition_leg', columns: ['questionnaire', 'disposition_id', 'leg'])] class QuestionnaireResponse implements BlameableEntityInterface, TimestampableEntityInterface { use BlameableEntity; @@ -68,6 +72,13 @@ class QuestionnaireResponse implements BlameableEntityInterface, TimestampableEn #[ORM\JoinColumn(onDelete: 'CASCADE')] private ?Disposition $disposition = null; + /** + * A BusLeg value, or '' for a questionnaire without legs rather than null: part of the unique + * key, and MariaDB lets NULLs repeat in one. + */ + #[ORM\Column(length: 16, options: ['default' => ''])] + private string $leg = ''; + private function __construct(Definition $definition) { $this->uuid = Uuid::v4(); @@ -75,10 +86,18 @@ class QuestionnaireResponse implements BlameableEntityInterface, TimestampableEn $this->version = $definition->version; } - public static function forDisposition(Definition $definition, Disposition $disposition): static + /** + * @param BusLeg|null $leg required for a per-bus-leg questionnaire, refused for any other + */ + public static function forDisposition(Definition $definition, Disposition $disposition, ?BusLeg $leg = null): static { + if ($definition->perBusLeg !== (null !== $leg)) { + throw new \LogicException(sprintf('Questionnaire "%s" %s a bus leg', $definition->key, $definition->perBusLeg ? 'needs' : 'takes no')); + } + $instance = new static($definition); $instance->disposition = $disposition; + $instance->leg = $leg->value ?? ''; return $instance; } @@ -180,6 +199,11 @@ class QuestionnaireResponse implements BlameableEntityInterface, TimestampableEn return $this->disposition; } + public function getLeg(): ?BusLeg + { + return BusLeg::tryFrom($this->leg); + } + private function assertDraft(): void { if ($this->isSubmitted()) { diff --git a/src/Enum/BusLeg.php b/src/Enum/BusLeg.php new file mode 100644 index 0000000..570b323 --- /dev/null +++ b/src/Enum/BusLeg.php @@ -0,0 +1,21 @@ + 'Hinfahrt', + self::RETURN => 'Rückfahrt', + }; + } +} diff --git a/src/Form/QuestionnaireType.php b/src/Form/QuestionnaireType.php index d5bc246..e22f7ce 100644 --- a/src/Form/QuestionnaireType.php +++ b/src/Form/QuestionnaireType.php @@ -2,6 +2,7 @@ namespace App\Form; +use App\Enum\BusLeg; use App\Enum\ChoiceWidget; use App\Enum\QuestionType; use App\Model\Questionnaire\Definition; @@ -27,6 +28,11 @@ use Symfony\Component\OptionsResolver\OptionsResolver; * of its own, and each of its sections a child with inherit_data, which groups the fields on screen * without nesting the answers. * + * A per-bus-leg questionnaire (bus_feedback) opens with "which rides did you escort?" (LEGS), followed + * by one child per BusLeg holding that leg's answers, shown only while the leg is chosen: + * {legs: 'outbound'|'return'|'both'|null, outbound: {...}, return: {...}}. answerSets() turns the + * data into one answer set per questionnaire and chosen leg, the responses to store. + * * Two buttons: "draft" saves whatever is filled in, "submit" also demands every required question * that is shown. No field is HTML-required, or the browser would refuse to send a half-filled * draft. Whether a question is shown is Definition::isVisible(), the same rule the @@ -36,6 +42,8 @@ class QuestionnaireType extends AbstractType { public const string DRAFT = 'draft'; public const string SUBMIT = 'submit'; + public const string LEGS = 'legs'; + public const string BOTH_LEGS = 'both'; private const int RATING_MAX = 5; @@ -49,21 +57,14 @@ class QuestionnaireType extends AbstractType 'label' => $definition->title, 'help' => $definition->description, 'empty_data' => [], + 'required' => false, 'block_prefix' => 'questionnaire_part', ]); - foreach ($definition->sections as $section) { - $sectionBuilder = $builder->create($section->key, FormType::class, [ - 'inherit_data' => true, - 'label' => $section->title ?? false, - 'block_prefix' => 'questionnaire_section', - ]); - - foreach ($section->questions as $question) { - $sectionBuilder->add($question->key, ...$this->field($definition, $question)); - } - - $questionnaireBuilder->add($sectionBuilder); + if ($definition->perBusLeg) { + $this->addLegs($builder, $questionnaireBuilder, $definition); + } else { + $this->addSections($builder, $questionnaireBuilder, $definition, $definition->key); } $builder->add($questionnaireBuilder); @@ -83,8 +84,20 @@ class QuestionnaireType extends AbstractType return; } + $data = $form->getData(); + foreach ($definitions as $definition) { - $answers = $form->getData()[$definition->key] ?? []; + if ($definition->perBusLeg && [] === self::chosenLegs($data[$definition->key] ?? [])) { + $form->get($definition->key)->get(self::LEGS)->addError(new FormError('Bitte beantworte diese Frage.')); + } + } + + foreach (self::answerSets($data, $definitions) as ['definition' => $definition, 'leg' => $leg, 'answers' => $answers]) { + $parent = $form->get($definition->key); + + if (null !== $leg) { + $parent = $parent->get($leg->value); + } foreach ($definition->sections as $section) { foreach ($section->questions as $question) { @@ -92,7 +105,7 @@ class QuestionnaireType extends AbstractType && $definition->isVisible($question, $answers) && $this->isEmpty($answers[$question->key] ?? null) ) { - $form->get($definition->key)->get($section->key)->get($question->key)->addError( + $parent->get($section->key)->get($question->key)->addError( new FormError('Bitte beantworte diese Frage.') ); } @@ -128,20 +141,137 @@ class QuestionnaireType extends AbstractType return $button instanceof ClickableInterface && $button->isClicked(); } + /** + * The answers to store, one set per questionnaire - and for a per-bus-leg one, per chosen leg. + * A leg not chosen yields nothing, whatever its fields still hold. + * + * @param array $data the form's data, keyed by questionnaire key + * @param list $definitions + * + * @return list}> + */ + public static function answerSets(array $data, array $definitions): array + { + $sets = []; + + foreach ($definitions as $definition) { + $part = $data[$definition->key] ?? []; + + if (!$definition->perBusLeg) { + $sets[] = ['definition' => $definition, 'leg' => null, 'answers' => $part]; + + continue; + } + + foreach (self::chosenLegs($part) as $leg) { + $sets[] = ['definition' => $definition, 'leg' => $leg, 'answers' => $part[$leg->value] ?? []]; + } + } + + return $sets; + } + + /** + * The form data of a per-bus-leg questionnaire from its stored answers, one set per leg. The + * legs that have answers are the ones chosen. + * + * @param array> $answersByLeg keyed by BusLeg value + * + * @return array + */ + public static function legData(array $answersByLeg): array + { + $legs = array_keys($answersByLeg); + + return [self::LEGS => match (count($legs)) { + 0 => null, + 1 => $legs[0], + default => self::BOTH_LEGS, + }] + $answersByLeg; + } + + /** + * @param array $part the data of a per-bus-leg questionnaire + * + * @return list + */ + private static function chosenLegs(array $part): array + { + $legs = $part[self::LEGS] ?? null; + + return self::BOTH_LEGS === $legs ? BusLeg::cases() : array_values(array_filter([BusLeg::tryFrom((string) $legs)])); + } + + private function addLegs(FormBuilderInterface $builder, FormBuilderInterface $questionnaireBuilder, Definition $definition): void + { + $questionnaireBuilder->add(self::LEGS, ChoiceType::class, [ + 'label' => 'Welche Fahrten hast du begleitet?', + 'required' => false, + 'choices' => [...array_map(static fn (BusLeg $leg): string => $leg->value, BusLeg::cases()), self::BOTH_LEGS], + 'choice_label' => static fn (string $legs): string => BusLeg::tryFrom($legs)?->label() ?? 'Hin- und Rückfahrt', + 'expanded' => true, + 'placeholder' => false, + 'block_prefix' => 'questionnaire_choice', + 'row_attr' => ['data-question-key' => $definition->key.'.'.self::LEGS], + ]); + + foreach (BusLeg::cases() as $leg) { + $legBuilder = $builder->create($leg->value, FormType::class, [ + 'label' => $leg->label(), + 'empty_data' => [], + 'required' => false, + 'block_prefix' => 'questionnaire_leg', + // shown by the questionnaire Stimulus controller like a conditional question + 'row_attr' => [ + 'data-question-key' => $definition->key.'.'.$leg->value, + 'data-show-if' => json_encode([ + 'question' => $definition->key.'.'.self::LEGS, + 'operator' => 'in', + 'value' => [$leg->value, self::BOTH_LEGS], + ], JSON_THROW_ON_ERROR), + ], + ]); + + $this->addSections($builder, $legBuilder, $definition, $definition->key.'.'.$leg->value); + $questionnaireBuilder->add($legBuilder); + } + } + + /** + * @param string $prefix makes the question keys the Stimulus controller sees unique on the page + */ + private function addSections(FormBuilderInterface $builder, FormBuilderInterface $parent, Definition $definition, string $prefix): void + { + foreach ($definition->sections as $section) { + $sectionBuilder = $builder->create($section->key, FormType::class, [ + 'inherit_data' => true, + 'required' => false, + 'label' => $section->title ?? false, + 'block_prefix' => 'questionnaire_section', + ]); + + foreach ($section->questions as $question) { + $sectionBuilder->add($question->key, ...$this->field($prefix, $question)); + } + + $parent->add($sectionBuilder); + } + } + /** * @return array{0: class-string, 1: array} */ - private function field(Definition $definition, Question $question): array + private function field(string $prefix, Question $question): array { $common = [ 'label' => $question->label, 'help' => $question->help, 'required' => false, - // read by assets/controllers/questionnaire_controller.js; prefixed with the questionnaire, - // since question keys are only unique within one - 'row_attr' => ['data-question-key' => $definition->key.'.'.$question->key] + (null === $question->showIf ? [] : [ + // read by assets/controllers/questionnaire_controller.js; prefixed with the questionnaire + // (and leg), since question keys are only unique within one + 'row_attr' => ['data-question-key' => $prefix.'.'.$question->key] + (null === $question->showIf ? [] : [ 'data-show-if' => json_encode([ - 'question' => $definition->key.'.'.$question->showIf->question, + 'question' => $prefix.'.'.$question->showIf->question, 'operator' => $question->showIf->operator->value, 'value' => $question->showIf->value, ], JSON_THROW_ON_ERROR), diff --git a/src/Model/Questionnaire/Definition.php b/src/Model/Questionnaire/Definition.php index efeec31..509e85e 100644 --- a/src/Model/Questionnaire/Definition.php +++ b/src/Model/Questionnaire/Definition.php @@ -5,6 +5,9 @@ namespace App\Model\Questionnaire; /** * One version of a questionnaire as read from config/questionnaires/. Responses store its key and * version, and their answers are keyed by Question::$key. + * + * A $perBusLeg questionnaire is answered once per bus ride the teamer escorted (App\Enum\BusLeg), + * each leg a response of its own. */ readonly class Definition { @@ -17,6 +20,7 @@ readonly class Definition public string $title, public ?string $description, public array $sections, + public bool $perBusLeg = false, ) { } diff --git a/src/Repository/DispositionRepository.php b/src/Repository/DispositionRepository.php index 0420601..f62ca06 100644 --- a/src/Repository/DispositionRepository.php +++ b/src/Repository/DispositionRepository.php @@ -80,67 +80,18 @@ class DispositionRepository extends ServiceEntityRepository * The teamer's placements with a questionnaire still to be submitted - not started, or saved as * a draft: the teamer feedback, and after a bus escort the bus feedback too * (DispositionContext::questionnaires(), spelled out here in DQL). The rules are those of - * DispositionVoter::QUESTIONNAIRE - over (today included), on or after $windowStart, neither - * called off nor skip-formalities - so every row shown on the dashboard can be opened. + * DispositionVoter::QUESTIONNAIRE - over (today included), on or after go-live, neither called + * off nor skip-formalities - so every row shown on the dashboard can be opened. * - * The responses are joined as arbitrary entities because the association is one-way; the - * questionnaire key has to be part of each JOIN condition, or one questionnaire's response - * would stand in for the other's. - * - * Rows are [0 => Disposition, 'teamerStatus' => ?QuestionnaireResponseStatus, - * 'busStatus' => ?QuestionnaireResponseStatus]. + * Rows are [0 => Disposition, 'drafts' => int], the number of drafts saved for it. */ - public function getPendingQuestionnaireQuery(Teamer $teamer, \DateTimeImmutable $windowStart): Query + public function getPendingQuestionnaireQuery(Teamer $teamer, \DateTimeImmutable $goLive): Query { - $qb = $this->createQueryBuilder('disposition'); + $qb = $this->createPendingQuestionnaireQueryBuilder($goLive, new \DateTimeImmutable('today')); return $qb - ->select('disposition', 'assignment', 'destination', 'teamer_response.status AS teamerStatus', 'bus_response.status AS busStatus') - ->innerJoin('disposition.assignment', 'assignment') - ->innerJoin('assignment.destination', 'destination') - ->leftJoin( - QuestionnaireResponse::class, - 'teamer_response', - Join::ON, - 'teamer_response.disposition = disposition AND teamer_response.questionnaire = :teamerQuestionnaire' - ) - ->leftJoin( - QuestionnaireResponse::class, - 'bus_response', - Join::ON, - 'bus_response.disposition = disposition AND bus_response.questionnaire = :busQuestionnaire' - ) - ->where($qb->expr()->andX( - $qb->expr()->eq('disposition.teamer', ':teamer'), - $qb->expr()->neq('disposition.status', ':dispositionCalledOff'), - $qb->expr()->notIn('assignment.status', ':assignmentStatuses'), - $qb->expr()->eq('assignment.skipFormalities', ':skipFormalities'), - $qb->expr()->gte('destination.dateTo', ':windowStart'), - $qb->expr()->lte('destination.dateTo', ':today'), - $qb->expr()->orX( - $qb->expr()->isNull('teamer_response.id'), - $qb->expr()->eq('teamer_response.status', ':draft'), - // a bus escort, i.e. Assignment::hasBusEscort(), owing the bus feedback - $qb->expr()->andX( - $qb->expr()->isNotNull('assignment.pickup'), - $qb->expr()->neq('assignment.pickup', 0), - $qb->expr()->orX( - $qb->expr()->isNull('bus_response.id'), - $qb->expr()->eq('bus_response.status', ':draft') - ) - ) - ) - )) - ->orderBy('destination.dateTo', \SortDirection::Descending) + ->andWhere($qb->expr()->eq('disposition.teamer', ':teamer')) ->setParameter('teamer', $teamer) - ->setParameter('teamerQuestionnaire', QuestionnaireCatalog::TEAMER_FEEDBACK) - ->setParameter('busQuestionnaire', QuestionnaireCatalog::BUS_FEEDBACK) - ->setParameter('dispositionCalledOff', Disposition::STATUS_CALLED_OFF) - ->setParameter('assignmentStatuses', [Assignment::STATUS_CALLED_OFF, Assignment::STATUS_DELETED]) - ->setParameter('skipFormalities', false) - ->setParameter('windowStart', $windowStart, Types::DATE_IMMUTABLE) - ->setParameter('today', new \DateTimeImmutable('today'), Types::DATE_IMMUTABLE) - ->setParameter('draft', QuestionnaireResponseStatus::DRAFT) ->getQuery() ; } @@ -148,18 +99,109 @@ class DispositionRepository extends ServiceEntityRepository /** * @return list */ - public function findPendingQuestionnaireByTeamer(Teamer $teamer, \DateTimeImmutable $windowStart): array + public function findPendingQuestionnaireByTeamer(Teamer $teamer, \DateTimeImmutable $goLive): array { return array_map( static fn (array $row): array => [ 'disposition' => $row[0], - 'draft' => QuestionnaireResponseStatus::DRAFT === $row['teamerStatus'] - || QuestionnaireResponseStatus::DRAFT === $row['busStatus'], + 'draft' => $row['drafts'] > 0, ], - $this->getPendingQuestionnaireQuery($teamer, $windowStart)->getResult(), + $this->getPendingQuestionnaireQuery($teamer, $goLive)->getResult(), ); } + /** + * Every teamer's placements with a questionnaire still to be submitted, for the daily reminder + * (QuestionnaireReminderService): the dashboard's rules, but only from the day after the trip + * ended, and only teamers who can still log in to submit - not deleted, with a user account that + * is not blocked. Otherwise they would be reminded every day, forever. + * + * Rows are [0 => Disposition, 'drafts' => int], ordered by teamer. + */ + public function getQuestionnaireReminderQuery(\DateTimeImmutable $goLive, \DateTimeImmutable $today): Query + { + $qb = $this->createPendingQuestionnaireQueryBuilder($goLive, $today->modify('-1 day')); + + return $qb + ->addSelect('teamer') + ->innerJoin('disposition.teamer', 'teamer') + ->innerJoin('teamer.user', 'user') + ->andWhere($qb->expr()->isNull('teamer.deletedAt')) + ->andWhere($qb->expr()->isNull('user.disabledAt')) + ->orderBy('teamer.id') + ->addOrderBy('destination.dateTo', \SortDirection::Descending) + ->getQuery() + ; + } + + /** + * @return list ordered by teamer, teamer and user loaded + */ + public function findQuestionnaireReminders(\DateTimeImmutable $goLive, \DateTimeImmutable $today): array + { + return array_column($this->getQuestionnaireReminderQuery($goLive, $today)->getResult(), 0); + } + + /** + * Placements ended between $goLive and $endedBy (both inclusive) that still owe a questionnaire. + * A questionnaire counts as done once a response to it is submitted: the bus feedback has one + * response per escorted leg, and all of a teamer's legs are submitted together. EXISTS rather + * than joins, which would list a placement once per leg. + */ + private function createPendingQuestionnaireQueryBuilder(\DateTimeImmutable $goLive, \DateTimeImmutable $endedBy): QueryBuilder + { + $qb = $this->createQueryBuilder('disposition'); + + $submitted = fn (string $alias, string $questionnaire): string => $this->getEntityManager()->createQueryBuilder() + ->select($alias.'.id') + ->from(QuestionnaireResponse::class, $alias) + ->where($alias.'.disposition = disposition') + ->andWhere($alias.'.questionnaire = '.$questionnaire) + ->andWhere($alias.'.status = :submitted') + ->getDQL() + ; + + $drafts = $this->getEntityManager()->createQueryBuilder() + ->select('COUNT(draft_response.id)') + ->from(QuestionnaireResponse::class, 'draft_response') + ->where('draft_response.disposition = disposition') + ->andWhere('draft_response.status = :draft') + ->getDQL() + ; + + return $qb + ->select('disposition', 'assignment', 'destination', '('.$drafts.') AS drafts') + ->innerJoin('disposition.assignment', 'assignment') + ->innerJoin('assignment.destination', 'destination') + ->where($qb->expr()->andX( + $qb->expr()->neq('disposition.status', ':dispositionCalledOff'), + $qb->expr()->notIn('assignment.status', ':assignmentStatuses'), + $qb->expr()->eq('assignment.skipFormalities', ':skipFormalities'), + $qb->expr()->gte('destination.dateTo', ':goLive'), + $qb->expr()->lte('destination.dateTo', ':endedBy'), + $qb->expr()->orX( + $qb->expr()->not($qb->expr()->exists($submitted('teamer_response', ':teamerQuestionnaire'))), + // a bus escort, i.e. Assignment::hasBusEscort(), owing the bus feedback + $qb->expr()->andX( + $qb->expr()->isNotNull('assignment.pickup'), + $qb->expr()->neq('assignment.pickup', 0), + $qb->expr()->not($qb->expr()->exists($submitted('bus_response', ':busQuestionnaire'))) + ) + ) + )) + ->orderBy('destination.dateTo', \SortDirection::Descending) + ->setParameter('teamerQuestionnaire', QuestionnaireCatalog::TEAMER_FEEDBACK) + ->setParameter('busQuestionnaire', QuestionnaireCatalog::BUS_FEEDBACK) + ->setParameter('submitted', QuestionnaireResponseStatus::SUBMITTED) + ->setParameter('draft', QuestionnaireResponseStatus::DRAFT) + ->setParameter('dispositionCalledOff', Disposition::STATUS_CALLED_OFF) + ->setParameter('assignmentStatuses', [Assignment::STATUS_CALLED_OFF, Assignment::STATUS_DELETED]) + ->setParameter('skipFormalities', false) + ->setParameter('goLive', $goLive, Types::DATE_IMMUTABLE) + ->setParameter('endedBy', $endedBy, Types::DATE_IMMUTABLE) + ; + } + public function getRecentDispositionsByTeamerQuery(Teamer $teamer): Query { $qb = $this->createQueryBuilder('disposition'); diff --git a/src/Repository/QuestionnaireResponseRepository.php b/src/Repository/QuestionnaireResponseRepository.php index caf8b6b..5bebe56 100644 --- a/src/Repository/QuestionnaireResponseRepository.php +++ b/src/Repository/QuestionnaireResponseRepository.php @@ -81,14 +81,16 @@ class QuestionnaireResponseRepository extends ServiceEntityRepository } /** - * @return array keyed by questionnaire key + * @return array> keyed by questionnaire key; one response, + * or one per leg (outbound first) for a + * per-bus-leg questionnaire */ public function findByDisposition(Disposition $disposition): array { $responses = []; - foreach ($this->findBy(['disposition' => $disposition]) as $response) { - $responses[$response->getQuestionnaire()] = $response; + foreach ($this->findBy(['disposition' => $disposition], ['leg' => 'ASC']) as $response) { + $responses[$response->getQuestionnaire()][] = $response; } return $responses; diff --git a/src/Security/Voter/DispositionVoter.php b/src/Security/Voter/DispositionVoter.php index 7113e66..1c45b39 100644 --- a/src/Security/Voter/DispositionVoter.php +++ b/src/Security/Voter/DispositionVoter.php @@ -25,13 +25,16 @@ class DispositionVoter extends Voter public const MANAGE_RECEIPTS = 'MANAGE_RECEIPTS'; public const QUESTIONNAIRE = 'QUESTIONNAIRE'; + private readonly \DateTimeImmutable $questionnaireGoLive; + /** - * @param int $questionnaireWindowDays the services.yaml parameter questionnaire_window_days + * @param string $questionnaireGoLive Y-m-d, the services.yaml parameter questionnaire_go_live */ public function __construct( private readonly Security $security, - private readonly int $questionnaireWindowDays, + string $questionnaireGoLive, ) { + $this->questionnaireGoLive = QuestionnaireCatalog::parseGoLive($questionnaireGoLive); } protected function supports(string $attribute, mixed $subject): bool @@ -143,7 +146,7 @@ class DispositionVoter extends Voter $dateTo = $disposition->getAssignment()?->getDestination()?->getDateTo(); return null !== $dateTo - && $dateTo >= QuestionnaireCatalog::windowStart($this->questionnaireWindowDays) + && $dateTo >= $this->questionnaireGoLive && $dateTo <= new \DateTimeImmutable('today'); } diff --git a/src/Service/Cron/QuestionnaireReminderService.php b/src/Service/Cron/QuestionnaireReminderService.php new file mode 100644 index 0000000..137be77 --- /dev/null +++ b/src/Service/Cron/QuestionnaireReminderService.php @@ -0,0 +1,73 @@ +questionnaireGoLive = QuestionnaireCatalog::parseGoLive($questionnaireGoLive); + } + + public function sendReminders(?\DateTimeImmutable $today = null): string + { + $today = ($today ?? new \DateTimeImmutable('today'))->setTime(0, 0); + + /** @var array> $perTeamer keyed by object id: Doctrine hands out one Teamer instance per row */ + $perTeamer = []; + + foreach ($this->dispositionRepository->findQuestionnaireReminders($this->questionnaireGoLive, $today) as $disposition) { + $perTeamer[spl_object_id($disposition->getTeamer())][] = $disposition; + } + + $count = 0; + + foreach ($perTeamer as $dispositions) { + $email = $dispositions[0]->getTeamer()->getCommunication()?->getEmail(); + + if (null === $email) { + continue; + } + + $this->mailer->createAndSendText(EmailTextKey::REMINDER_QUESTIONNAIRE, [ + 'destinations' => implode(', ', array_map( + static fn (Disposition $disposition): string => (string) $disposition->getAssignment()->getDestination(), + $dispositions, + )), + ], [ + 'to' => $email, + ]); + + ++$count; + } + + $message = 'Sent '.$count.' questionnaire reminders to teamers'; + $this->logger->info($message); + + return $message; + } +} diff --git a/templates/administrative/questionnaire/detail.html.twig b/templates/administrative/questionnaire/detail.html.twig index add70d2..8a1c790 100644 --- a/templates/administrative/questionnaire/detail.html.twig +++ b/templates/administrative/questionnaire/detail.html.twig @@ -1,11 +1,11 @@ {% extends 'administrative/layout.html.twig' %} -{% block title %}{{ definition.title }}{% endblock %} +{% block title %}{{ definition.title }}{% if response.leg %}: {{ response.leg.label }}{% endif %}{% endblock %} {% block content %} {% set context = response.context %}

- {{ definition.title }} + {{ definition.title }}{% if response.leg %}: {{ response.leg.label }}{% endif %}

{{ context.teamerName|default('-') }}, abgeschickt am {{ response.submittedAt|date('d.m.Y, H:i') }} Uhr @@ -43,7 +43,7 @@ {% for sibling in siblings %}

  • - {{ sibling.title }} + {{ sibling.title }}{% if sibling.response.leg %}: {{ sibling.response.leg.label }}{% endif %}
  • {% endfor %} diff --git a/templates/administrative/questionnaire/index.html.twig b/templates/administrative/questionnaire/index.html.twig index 1865011..759f5d0 100644 --- a/templates/administrative/questionnaire/index.html.twig +++ b/templates/administrative/questionnaire/index.html.twig @@ -56,6 +56,11 @@ {{ knp_pagination_sortable(pagination, 'Haus', 'destination.hotel') }} + {% if definition.perBusLeg %} + + {{ knp_pagination_sortable(pagination, 'Fahrt', 'response.leg') }} + + {% endif %} {{ knp_pagination_sortable(pagination, 'Abgeschickt', 'response.submittedAt') }} @@ -82,6 +87,11 @@ {{ destination.hotel }} + {% if definition.perBusLeg %} + + {{ response.leg.label|default('-') }} + + {% endif %} {{ response.submittedAt|date('d.m.Y') }} @@ -93,7 +103,7 @@ {% else %} - + Keine Daten... diff --git a/templates/administrative/questionnaire/test.html.twig b/templates/administrative/questionnaire/test.html.twig index 85adecb..c2542d6 100644 --- a/templates/administrative/questionnaire/test.html.twig +++ b/templates/administrative/questionnaire/test.html.twig @@ -36,7 +36,7 @@ {% for item in submitted %}

    - {{ item.definition.title }} + {{ item.definition.title }}{% if item.leg %}: {{ item.leg.label }}{% endif %}

    {% include 'questionnaire/_answers.html.twig' with { 'definition': item.definition, 'answers': item.answers } %}
    diff --git a/templates/forms.html.twig b/templates/forms.html.twig index 1255704..c20ac8a 100644 --- a/templates/forms.html.twig +++ b/templates/forms.html.twig @@ -189,6 +189,20 @@ {%- endblock questionnaire_part_row -%} +{# + # One bus ride of a per-bus-leg questionnaire (App\Form\QuestionnaireType): its title and its + # sections. Its row carries data-question-key and data-show-if like a conditional question, so the + # questionnaire Stimulus controller shows it only while the leg is chosen. + #} +{%- block questionnaire_leg_row -%} +
    +

    {{ label }}

    + {%- for child in form -%} + {{- form_row(child) -}} + {%- endfor -%} +
    +{%- endblock questionnaire_leg_row -%} + {# # A section of a questionnaire (App\Form\QuestionnaireType): its title and its questions. The # questions' rows carry data-question-key and, when conditional, data-show-if, which diff --git a/templates/teamer/index.html.twig b/templates/teamer/index.html.twig index 28e9e25..f399902 100644 --- a/templates/teamer/index.html.twig +++ b/templates/teamer/index.html.twig @@ -18,7 +18,8 @@ {% if pendingQuestionnaires is not empty %} {% embed '_partials/_alert.html.twig' with { 'type': 'info' } %} {% block message %} -

    Bitte fülle den Fragebogen zu deinem Einsatz aus:

    +

    Bitte den Feedbackbogen spätestens drei Tage nach Reiseende ausfüllen.

    +

    Offen ist noch:

      {% for row in pendingQuestionnaires %} {% set destination = row.disposition.assignment.destination %} diff --git a/templates/teamer/questionnaire/detail.html.twig b/templates/teamer/questionnaire/detail.html.twig index de0693e..6aaa827 100644 --- a/templates/teamer/questionnaire/detail.html.twig +++ b/templates/teamer/questionnaire/detail.html.twig @@ -15,7 +15,7 @@ {% for item in submitted %}

      - {{ item.definition.title }} + {{ item.definition.title }}{% if item.response.leg %}: {{ item.response.leg.label }}{% endif %}

      Abgeschickt am {{ item.response.submittedAt|date('d.m.Y, H:i') }} Uhr diff --git a/tests/Config/QuestionnaireCatalogTest.php b/tests/Config/QuestionnaireCatalogTest.php index d419675..6fb8ec0 100644 --- a/tests/Config/QuestionnaireCatalogTest.php +++ b/tests/Config/QuestionnaireCatalogTest.php @@ -46,6 +46,19 @@ class QuestionnaireCatalogTest extends TestCase } } + /** + * An escort may ride the outbound bus, the return bus or both, so the bus feedback is answered + * per leg and no longer asks for the direction. + */ + public function testOnlyTheBusFeedbackIsAnsweredPerLeg(): void + { + $catalog = new QuestionnaireCatalog(self::SHIPPED_DIR); + + $this->assertTrue($catalog->get(QuestionnaireCatalog::BUS_FEEDBACK)->perBusLeg); + $this->assertNull($catalog->get(QuestionnaireCatalog::BUS_FEEDBACK)->getQuestion('direction')); + $this->assertFalse($catalog->get(QuestionnaireCatalog::TEAMER_FEEDBACK)->perBusLeg); + } + public function testTheTwoQuestionnairesAreTheCurrentKeys(): void { $this->assertSame( @@ -112,16 +125,16 @@ class QuestionnaireCatalogTest extends TestCase $this->assertSame('Alte Frage', $catalog->get('sample', 1)->getQuestion('answer')->label); } - public function testTheWindowStartsTheGivenDaysBeforeToday(): void + public function testTheGoLiveDateIsADay(): void { - $this->assertEquals(new \DateTimeImmutable('today -2 days'), QuestionnaireCatalog::windowStart(2)); + $this->assertEquals(new \DateTimeImmutable('2026-11-10 00:00'), QuestionnaireCatalog::parseGoLive('2026-11-10')); } - public function testANegativeWindowFailsLoudly(): void + public function testAMalformedGoLiveDateFailsLoudly(): void { $this->expectException(\InvalidArgumentException::class); - QuestionnaireCatalog::windowStart(-1); + QuestionnaireCatalog::parseGoLive('10.11.2026'); } public function testUnknownQuestionnaireIsRejected(): void @@ -151,6 +164,10 @@ class QuestionnaireCatalogTest extends TestCase static fn (array $d): array => self::withQuestion($d, 1, ['requried' => true]), 'unknown field(s) requried', ]; + yield 'per_bus_leg not a boolean' => [ + static fn (array $d): array => ['per_bus_leg' => 'yes'] + $d, + 'per_bus_leg must be true or false', + ]; yield 'unknown type' => [ static fn (array $d): array => self::withQuestion($d, 1, ['type' => 'slider']), 'unknown type "slider"', diff --git a/tests/Config/QuestionnaireCompletenessTest.php b/tests/Config/QuestionnaireCompletenessTest.php index 9435929..c89dd98 100644 --- a/tests/Config/QuestionnaireCompletenessTest.php +++ b/tests/Config/QuestionnaireCompletenessTest.php @@ -19,7 +19,8 @@ use PHPUnit\Framework\TestCase; * * The lists below are the Google forms' questions in their order, with what each became: * "question:" is asked, "context:" is taken from the disposition and snapshotted into - * the response (DispositionContext::build()). Google's "Bitte ankreuzen:" checkbox list was split + * the response (DispositionContext::build()), "legs" is the per-bus-leg choice of rides the + * teamer escorted (App\Form\QuestionnaireType), which became a response per leg. Google's "Bitte ankreuzen:" checkbox list was split * into five single-choice questions, so it maps to five. */ class QuestionnaireCompletenessTest extends TestCase @@ -48,7 +49,7 @@ class QuestionnaireCompletenessTest extends TestCase private const array BUS_FEEDBACK = [ '(Datum, ohne Titel)' => ['context:escortPickupDate', 'context:dateTo'], - 'Hin- oder Rückfahrt' => ['question:direction'], + 'Hin- oder Rückfahrt' => ['legs'], 'Reiseziel:' => ['context:destinationProduct'], 'Bus-Unternehmen:' => ['question:bus_company'], 'Name des Busunternehmens:' => ['question:bus_company_other'], @@ -120,9 +121,11 @@ class QuestionnaireCompletenessTest extends TestCase foreach ($googleQuestions as $label => $targets) { foreach ($targets as $target) { - [$kind, $key] = explode(':', $target); + [$kind, $key] = explode(':', $target) + [1 => null]; - if ('question' === $kind) { + if ('legs' === $kind) { + $this->assertTrue($definition->perBusLeg, sprintf('"%s" is not asked as the legs escorted', $label)); + } elseif ('question' === $kind) { $this->assertNotNull($definition->getQuestion($key), sprintf('"%s" is not asked as "%s"', $label, $key)); $mapped[] = $key; } else { diff --git a/tests/Controller/Administrative/Questionnaire/TestControllerTest.php b/tests/Controller/Administrative/Questionnaire/TestControllerTest.php index 8ec1303..176f311 100644 --- a/tests/Controller/Administrative/Questionnaire/TestControllerTest.php +++ b/tests/Controller/Administrative/Questionnaire/TestControllerTest.php @@ -133,7 +133,7 @@ class TestControllerTest extends WebTestCase $crawler = $this->client->request('GET', sprintf('/administrative/questionnaire/test/%s?bus_escort=1', $this->assignment->getUuid())); $this->assertStringContainsString('Mit dem Bus-Feedback', $crawler->text()); - $this->assertCount(1, $crawler->filter('[data-question-key="bus_feedback.bus_company"]')); + $this->assertCount(1, $crawler->filter('[data-question-key="bus_feedback.outbound.bus_company"]')); } /** diff --git a/tests/Controller/Teamer/Questionnaire/EditControllerTest.php b/tests/Controller/Teamer/Questionnaire/EditControllerTest.php index d467626..2901d8d 100644 --- a/tests/Controller/Teamer/Questionnaire/EditControllerTest.php +++ b/tests/Controller/Teamer/Questionnaire/EditControllerTest.php @@ -24,7 +24,7 @@ use Symfony\Component\DomCrawler\Form; /** * The teamer's page: one form, and as many responses as questionnaires apply - the teamer feedback - * for every placement, the bus feedback as well after a bus escort. + * for every placement, the bus feedback as well after a bus escort, once per ride escorted. * * Runs in a transaction that is rolled back; the client keeps its kernel so every request shares * that connection. The profile checks that would otherwise send the teamer elsewhere first are @@ -79,7 +79,9 @@ class EditControllerTest extends WebTestCase $this->assertStringContainsString('Reiseleitung', $crawler->filter('h1 + p')->text()); $this->assertStringContainsString('Busbegleitung ab Stuttgart', $crawler->filter('h1 + p')->text()); $this->assertCount(1, $crawler->filter('[data-question-key="teamer_feedback.office_briefing_rating"]')); - $this->assertCount(1, $crawler->filter('[data-question-key="bus_feedback.bus_company"]')); + $this->assertCount(1, $crawler->filter('[data-question-key="bus_feedback.legs"]')); + $this->assertCount(1, $crawler->filter('[data-question-key="bus_feedback.outbound.bus_company"]')); + $this->assertCount(1, $crawler->filter('[data-question-key="bus_feedback.return.bus_company"]')); } public function testAPlacementWithoutEscortGetsTheTeamerFeedbackOnly(): void @@ -95,18 +97,61 @@ class EditControllerTest extends WebTestCase { $disposition = $this->placement(busEscort: true); $form = $this->open($disposition)->selectButton('Entwurf speichern')->form(); - $form['questionnaire[bus_feedback][bus_team][driver_names]'] = 'Hans'; + $form['questionnaire[bus_feedback][legs]'] = 'outbound'; + $form['questionnaire[bus_feedback][outbound][bus_team][driver_names]'] = 'Hans'; $this->client->submit($form); $this->assertResponseRedirects(sprintf('/teamer/questionnaire/%s', $disposition->getUuid())); $this->assertSame([ - QuestionnaireCatalog::BUS_FEEDBACK => QuestionnaireResponseStatus::DRAFT, + 'bus_feedback.outbound' => QuestionnaireResponseStatus::DRAFT, QuestionnaireCatalog::TEAMER_FEEDBACK => QuestionnaireResponseStatus::DRAFT, ], $this->statuses($disposition)); - // reopened, the draft is back in the form + // reopened, the draft is back in the form, the leg chosen included $crawler = $this->open($disposition); - $this->assertSame('Hans', $crawler->filter('input[name="questionnaire[bus_feedback][bus_team][driver_names]"]')->attr('value')); + $this->assertSame('Hans', $crawler->filter('input[name="questionnaire[bus_feedback][outbound][bus_team][driver_names]"]')->attr('value')); + $this->assertSame('outbound', $crawler->filter('input[name="questionnaire[bus_feedback][legs]"][checked]')->attr('value')); + } + + /** + * Choosing one ride after having saved both drops the other ride's draft: it would otherwise + * come back as chosen. + */ + public function testALegNoLongerChosenLosesItsDraft(): void + { + $disposition = $this->placement(busEscort: true); + $form = $this->open($disposition)->selectButton('Entwurf speichern')->form(); + $form['questionnaire[bus_feedback][legs]'] = 'both'; + $this->client->submit($form); + + $this->assertSame(['bus_feedback.outbound', 'bus_feedback.return', QuestionnaireCatalog::TEAMER_FEEDBACK], array_keys($this->statuses($disposition))); + + $form = $this->open($disposition)->selectButton('Entwurf speichern')->form(); + $form['questionnaire[bus_feedback][legs]'] = 'return'; + $this->client->submit($form); + + $this->assertSame(['bus_feedback.return', QuestionnaireCatalog::TEAMER_FEEDBACK], array_keys($this->statuses($disposition))); + } + + /** + * An escort who rode both buses gives the bus feedback twice, each ride a response of its own. + */ + public function testBothRidesAreSubmittedAsTwoBusResponses(): void + { + $disposition = $this->placement(busEscort: true); + $form = $this->open($disposition)->selectButton('Absenden')->form(); + $this->answerAll($form, [QuestionnaireCatalog::TEAMER_FEEDBACK, QuestionnaireCatalog::BUS_FEEDBACK], legs: 'both'); + $this->client->submit($form); + + $this->assertSame([ + 'bus_feedback.outbound' => QuestionnaireResponseStatus::SUBMITTED, + 'bus_feedback.return' => QuestionnaireResponseStatus::SUBMITTED, + QuestionnaireCatalog::TEAMER_FEEDBACK => QuestionnaireResponseStatus::SUBMITTED, + ], $this->statuses($disposition)); + + $crawler = $this->client->followRedirect(); + $this->assertStringContainsString('Bus-Feedback: Hinfahrt', $crawler->text()); + $this->assertStringContainsString('Bus-Feedback: Rückfahrt', $crawler->text()); } public function testOneSubmitSubmitsBoth(): void @@ -118,7 +163,7 @@ class EditControllerTest extends WebTestCase $this->assertResponseRedirects(sprintf('/teamer/questionnaire/%s/detail', $disposition->getUuid())); $this->assertSame([ - QuestionnaireCatalog::BUS_FEEDBACK => QuestionnaireResponseStatus::SUBMITTED, + 'bus_feedback.outbound' => QuestionnaireResponseStatus::SUBMITTED, QuestionnaireCatalog::TEAMER_FEEDBACK => QuestionnaireResponseStatus::SUBMITTED, ], $this->statuses($disposition)); @@ -131,7 +176,7 @@ class EditControllerTest extends WebTestCase } /** - * Nothing is half-submitted: a bus question left open keeps both questionnaires unsubmitted. + * Nothing is half-submitted: the rides left unsaid keep both questionnaires unsubmitted. */ public function testAnIncompleteBusFeedbackSubmitsNeither(): void { @@ -161,32 +206,43 @@ class EditControllerTest extends WebTestCase /** * Answers every required question that is shown without a follow-up: first option, rating 5. + * The bus feedback for the given rides. * * @param list $questionnaires */ - private function answerAll(Form $form, array $questionnaires): void + private function answerAll(Form $form, array $questionnaires, string $legs = 'outbound'): void { $catalog = self::getContainer()->get(QuestionnaireCatalog::class); foreach ($questionnaires as $key) { - foreach ($catalog->get($key)->sections as $section) { - foreach ($section->questions as $question) { - if (!$question->required || null !== $question->showIf) { - continue; - } + $definition = $catalog->get($key); + $prefixes = [$key]; - $form[sprintf('questionnaire[%s][%s][%s]', $key, $section->key, $question->key)] = match ($question->type) { - QuestionType::CHOICE => $question->options[0]->key, - QuestionType::RATING => '5', - default => 'Antwort', - }; + if ($definition->perBusLeg) { + $form[sprintf('questionnaire[%s][legs]', $key)] = $legs; + $prefixes = array_map(static fn (string $leg): string => $key.']['.$leg, 'both' === $legs ? ['outbound', 'return'] : [$legs]); + } + + foreach ($prefixes as $prefix) { + foreach ($definition->sections as $section) { + foreach ($section->questions as $question) { + if (!$question->required || null !== $question->showIf) { + continue; + } + + $form[sprintf('questionnaire[%s][%s][%s]', $prefix, $section->key, $question->key)] = match ($question->type) { + QuestionType::CHOICE => $question->options[0]->key, + QuestionType::RATING => '5', + default => 'Antwort', + }; + } } } } } /** - * @return array keyed by questionnaire, sorted + * @return array keyed by questionnaire (and leg), sorted */ private function statuses(Disposition $disposition): array { @@ -194,7 +250,7 @@ class EditControllerTest extends WebTestCase $statuses = []; foreach ($this->entityManager->getRepository(QuestionnaireResponse::class)->findBy(['disposition' => $disposition->getId()]) as $response) { - $statuses[$response->getQuestionnaire()] = $response->getStatus(); + $statuses[$response->getQuestionnaire().(null === $response->getLeg() ? '' : '.'.$response->getLeg()->value)] = $response->getStatus(); } ksort($statuses); diff --git a/tests/Entity/QuestionnaireResponseTest.php b/tests/Entity/QuestionnaireResponseTest.php index bc7cc76..502dadf 100644 --- a/tests/Entity/QuestionnaireResponseTest.php +++ b/tests/Entity/QuestionnaireResponseTest.php @@ -9,6 +9,7 @@ use App\Entity\Assignment; use App\Entity\Disposition; use App\Entity\QuestionnaireResponse; use App\Entity\Teamer; +use App\Enum\BusLeg; use App\Enum\ConditionOperator; use App\Enum\QuestionnaireResponseStatus; use App\Enum\QuestionType; @@ -81,6 +82,28 @@ class QuestionnaireResponseTest extends TestCase $this->response()->submit($this->definition(key: 'other'), [], [], new \DateTimeImmutable()); } + /** + * The bus feedback is one response per escorted leg; any other questionnaire one per + * placement - a leg there would slip past the unique key. + */ + public function testALegIsRequiredExactlyForAPerBusLegQuestionnaire(): void + { + $disposition = new Disposition(new Application(new Assignment(), new Teamer())); + $perLeg = new Definition('bus_feedback', 1, 'Bus-Feedback', null, [], perBusLeg: true); + + $this->assertSame(BusLeg::RETURN, QuestionnaireResponse::forDisposition($perLeg, $disposition, BusLeg::RETURN)->getLeg()); + $this->assertNull(QuestionnaireResponse::forDisposition($this->definition(), $disposition)->getLeg()); + + foreach ([[$perLeg, null], [$this->definition(), BusLeg::OUTBOUND]] as [$definition, $leg]) { + try { + QuestionnaireResponse::forDisposition($definition, $disposition, $leg); + $this->fail(sprintf('"%s" accepted leg %s', $definition->key, $leg?->value ?? 'none')); + } catch (\LogicException) { + $this->addToAssertionCount(1); + } + } + } + private function response(): QuestionnaireResponse { $disposition = new Disposition(new Application(new Assignment(), new Teamer())); diff --git a/tests/Form/QuestionnaireTypeTest.php b/tests/Form/QuestionnaireTypeTest.php index b2b4899..016b5fc 100644 --- a/tests/Form/QuestionnaireTypeTest.php +++ b/tests/Form/QuestionnaireTypeTest.php @@ -5,6 +5,7 @@ declare(strict_types=1); namespace App\Tests\Form; use App\Config\QuestionnaireCatalog; +use App\Enum\BusLeg; use App\Enum\QuestionType; use App\Form\QuestionnaireType; use App\Model\Questionnaire\Definition; @@ -14,6 +15,7 @@ use App\Model\Questionnaire\Section; use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase; use Symfony\Component\Form\FormFactoryInterface; use Symfony\Component\Form\FormInterface; +use Symfony\Component\Form\FormView; /** * Runs against the shipped definitions - teamer feedback alone, and with the bus feedback on the @@ -60,21 +62,109 @@ class QuestionnaireTypeTest extends KernelTestCase $this->assertSame([QuestionnaireCatalog::TEAMER_FEEDBACK, QuestionnaireCatalog::BUS_FEEDBACK], array_keys($data)); // keyed by question within each questionnaire, not by section, and a rating is an int $this->assertSame(5, $data[QuestionnaireCatalog::TEAMER_FEEDBACK]['office_briefing_rating']); - $this->assertSame('outbound', $data[QuestionnaireCatalog::BUS_FEEDBACK]['direction']); + $this->assertSame(BusLeg::OUTBOUND->value, $data[QuestionnaireCatalog::BUS_FEEDBACK][QuestionnaireType::LEGS]); + $this->assertSame('boonk', $data[QuestionnaireCatalog::BUS_FEEDBACK][BusLeg::OUTBOUND->value]['bus_company']); $this->assertArrayNotHasKey('organisation', $data[QuestionnaireCatalog::TEAMER_FEEDBACK]); + + $sets = QuestionnaireType::answerSets($data, $definitions); + $this->assertSame( + [[QuestionnaireCatalog::TEAMER_FEEDBACK, null], [QuestionnaireCatalog::BUS_FEEDBACK, BusLeg::OUTBOUND]], + array_map(static fn (array $set): array => [$set['definition']->key, $set['leg']], $sets), + ); + $this->assertSame('boonk', $sets[1]['answers']['bus_company']); } /** - * Every required question of either questionnaire is demanded, as far as it is shown. + * An escort who rode both buses answers the bus feedback twice, and each ride is demanded in + * full. */ - public function testEmptySubmitDemandsTheVisibleRequiredQuestionsOfBoth(): void + public function testBothLegsAreEachAnsweredAndDemanded(): void + { + $definitions = $this->both(); + $data = $this->complete($definitions, QuestionnaireType::BOTH_LEGS); + unset($data[QuestionnaireCatalog::BUS_FEEDBACK][BusLeg::RETURN->value]['bus_trip']['bus_company']); + + $form = $this->createForm($definitions); + $form->submit($data + [QuestionnaireType::SUBMIT => '']); + + $this->assertCount(1, $form->getErrors(true)); + $this->assertCount(1, $form->get(QuestionnaireCatalog::BUS_FEEDBACK)->get(BusLeg::RETURN->value)->get('bus_trip')->get('bus_company')->getErrors()); + + $form = $this->createForm($definitions); + $form->submit($this->complete($definitions, QuestionnaireType::BOTH_LEGS) + [QuestionnaireType::SUBMIT => '']); + + $this->assertTrue($form->isValid(), (string) $form->getErrors(true)); + $this->assertSame( + [null, BusLeg::OUTBOUND, BusLeg::RETURN], + array_column(QuestionnaireType::answerSets($form->getData(), $definitions), 'leg'), + ); + } + + /** + * Switching from both rides to one leaves the other leg's fields filled in the browser; they + * must not become a response. + */ + public function testALegNotChosenIsNeitherDemandedNorStored(): void + { + $definitions = $this->both(); + $data = $this->complete($definitions, QuestionnaireType::BOTH_LEGS); + $data[QuestionnaireCatalog::BUS_FEEDBACK][QuestionnaireType::LEGS] = BusLeg::RETURN->value; + $data[QuestionnaireCatalog::BUS_FEEDBACK][BusLeg::OUTBOUND->value] = []; + + $form = $this->createForm($definitions); + $form->submit($data + [QuestionnaireType::SUBMIT => '']); + + $this->assertTrue($form->isValid(), (string) $form->getErrors(true)); + $this->assertSame([null, BusLeg::RETURN], array_column(QuestionnaireType::answerSets($form->getData(), $definitions), 'leg')); + } + + /** + * @return iterable>, string|null}> + */ + public static function storedLegs(): iterable + { + yield 'nothing saved yet' => [[], null]; + yield 'one leg' => [['return' => ['bus_company' => 'boonk']], 'return']; + yield 'both legs' => [['outbound' => [], 'return' => []], QuestionnaireType::BOTH_LEGS]; + } + + /** + * @param array> $answersByLeg + */ + #[\PHPUnit\Framework\Attributes\DataProvider('storedLegs')] + public function testTheChosenLegsAreReadBackFromTheStoredOnes(array $answersByLeg, ?string $legs): void + { + $this->assertSame([QuestionnaireType::LEGS => $legs] + $answersByLeg, QuestionnaireType::legData($answersByLeg)); + } + + public function testALegIsShownOnlyWhileChosen(): void + { + $row = $this->createForm($this->both())->createView()->children[QuestionnaireCatalog::BUS_FEEDBACK]->children[BusLeg::RETURN->value]; + + $this->assertSame('bus_feedback.return', $row->vars['row_attr']['data-question-key']); + $this->assertSame( + ['question' => 'bus_feedback.legs', 'operator' => 'in', 'value' => ['return', 'both']], + json_decode($row->vars['row_attr']['data-show-if'], true), + ); + $this->assertSame( + 'bus_feedback.return.bus_company', + $row->children['bus_trip']->children['bus_company']->vars['row_attr']['data-question-key'], + ); + } + + /** + * Every required question of the teamer feedback is demanded, as far as it is shown, and of the + * bus feedback first which rides were escorted - no leg is shown before that. + */ + public function testEmptySubmitDemandsTheVisibleRequiredQuestionsAndTheLegs(): void { $form = $this->createForm($this->both()); $form->submit([QuestionnaireType::SUBMIT => '']); $this->assertFalse($form->isValid()); + $this->assertCount(1, $form->get(QuestionnaireCatalog::BUS_FEEDBACK)->get(QuestionnaireType::LEGS)->getErrors()); - foreach ($this->both() as $definition) { + foreach ([$this->teamerFeedback()] as $definition) { foreach ($definition->sections as $section) { foreach ($section->questions as $question) { $this->assertCount( @@ -120,12 +210,12 @@ class QuestionnaireTypeTest extends KernelTestCase { $definitions = $this->both(); $data = $this->complete($definitions); - $data[QuestionnaireCatalog::BUS_FEEDBACK]['bus_trip']['bus_company'] = 'other'; + $data[QuestionnaireCatalog::BUS_FEEDBACK][BusLeg::OUTBOUND->value]['bus_trip']['bus_company'] = 'other'; $form = $this->createForm($definitions); $form->submit($data + [QuestionnaireType::SUBMIT => '']); - $this->assertCount(1, $form->get(QuestionnaireCatalog::BUS_FEEDBACK)->get('bus_trip')->get('bus_company_other')->getErrors()); + $this->assertCount(1, $form->get(QuestionnaireCatalog::BUS_FEEDBACK)->get(BusLeg::OUTBOUND->value)->get('bus_trip')->get('bus_company_other')->getErrors()); } /** @@ -134,15 +224,15 @@ class QuestionnaireTypeTest extends KernelTestCase */ public function testNoFieldIsHtmlRequired(): void { - $view = $this->createForm($this->both())->createView(); - - foreach ($view as $questionnaire) { - foreach ($questionnaire as $section) { - foreach ($section as $field) { - $this->assertFalse($field->vars['required'], $field->vars['full_name']); - } + $assertNotRequired = function (FormView $view) use (&$assertNotRequired): void { + foreach ($view as $child) { + // buttons have no required at all + $this->assertFalse($child->vars['required'] ?? false, $child->vars['full_name']); + $assertNotRequired($child); } - } + }; + + $assertNotRequired($this->createForm($this->both())->createView()); } /** @@ -215,33 +305,56 @@ class QuestionnaireTypeTest extends KernelTestCase /** * A submission answering every question that is shown when each choice takes its first option - * and each rating is 5. + * and each rating is 5; a per-bus-leg questionnaire for the given legs. * * @param list $definitions * - * @return array>> + * @return array> */ - private function complete(array $definitions): array + private function complete(array $definitions, string $legs = 'outbound'): array { $data = []; foreach ($definitions as $definition) { - $answers = []; + $sections = $this->completeSections($definition); - foreach ($definition->sections as $section) { - foreach ($section->questions as $question) { - $answer = match ($question->type) { - QuestionType::CHOICE => $question->options[0]->key, - QuestionType::MULTI => [$question->options[0]->key], - QuestionType::RATING => 5, - QuestionType::DATE => '01.01.2026', - QuestionType::TEXT, QuestionType::TEXTAREA => 'Antwort', - }; - $answers[$question->key] = $answer; + if (!$definition->perBusLeg) { + $data[$definition->key] = $sections; - if ($definition->isVisible($question, $answers)) { - $data[$definition->key][$section->key][$question->key] = is_int($answer) ? (string) $answer : $answer; - } + continue; + } + + $data[$definition->key] = [QuestionnaireType::LEGS => $legs]; + + foreach (QuestionnaireType::BOTH_LEGS === $legs ? BusLeg::cases() : [BusLeg::from($legs)] as $leg) { + $data[$definition->key][$leg->value] = $sections; + } + } + + return $data; + } + + /** + * @return array> keyed by section, then question + */ + private function completeSections(Definition $definition): array + { + $data = []; + $answers = []; + + foreach ($definition->sections as $section) { + foreach ($section->questions as $question) { + $answer = match ($question->type) { + QuestionType::CHOICE => $question->options[0]->key, + QuestionType::MULTI => [$question->options[0]->key], + QuestionType::RATING => 5, + QuestionType::DATE => '01.01.2026', + QuestionType::TEXT, QuestionType::TEXTAREA => 'Antwort', + }; + $answers[$question->key] = $answer; + + if ($definition->isVisible($question, $answers)) { + $data[$section->key][$question->key] = is_int($answer) ? (string) $answer : $answer; } } } diff --git a/tests/Repository/DispositionRepositoryQuestionnaireTest.php b/tests/Repository/DispositionRepositoryQuestionnaireTest.php index c1345c8..d866f83 100644 --- a/tests/Repository/DispositionRepositoryQuestionnaireTest.php +++ b/tests/Repository/DispositionRepositoryQuestionnaireTest.php @@ -8,15 +8,16 @@ use App\Config\QuestionnaireCatalog; use App\Entity\Assignment; use App\Entity\Disposition; use App\Entity\Teamer; +use App\Enum\BusLeg; use App\Repository\DispositionRepository; use Doctrine\ORM\EntityManagerInterface; use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase; /** - * Which questionnaires the dashboard reminds a teamer of. Run against db_test with real rows, - * because the question is which rows come back: the response is joined as an arbitrary entity, - * and a wrong JOIN condition would quietly let a draft, or a response to another questionnaire, - * decide the outcome. + * Which questionnaires the dashboard and the daily reminder mail remind a teamer of. Run against + * db_test with real rows, because the question is which rows come back: the responses are looked up + * in EXISTS subqueries, and a wrong condition there would quietly let a draft, a response to + * another questionnaire, or a second bus leg decide the outcome. * * Every test runs inside a transaction that is rolled back, so db_test - shared between * branches - keeps nothing. @@ -25,6 +26,8 @@ class DispositionRepositoryQuestionnaireTest extends KernelTestCase { use QuestionnaireFixturesTrait; + private const string GO_LIVE = '2026-01-01'; + private EntityManagerInterface $entityManager; private DispositionRepository $repository; @@ -93,8 +96,8 @@ class DispositionRepositoryQuestionnaireTest extends KernelTestCase } /** - * Each questionnaire key belongs in its JOIN condition: in the WHERE clause, the response to - * one questionnaire would stand in for the other's. + * Each questionnaire key belongs in its own EXISTS: the response to one questionnaire must not + * stand in for the other's. */ public function testTheBusFeedbackDoesNotStandInForTheTeamerFeedback(): void { @@ -121,13 +124,42 @@ class DispositionRepositoryQuestionnaireTest extends KernelTestCase $this->assertSame([['disposition' => $disposition, 'draft' => false]], $this->pending()); } - public function testAnAssignmentEndingOnTheWindowsFirstDayIsPending(): void + /** + * Only submitting ends it, however long ago the trip ended. + */ + public function testAnUnfinishedQuestionnaireStaysPendingLongAfterTheTrip(): void { - $this->escort(dateTo: 'today -30 days'); + $this->escort(dateTo: self::GO_LIVE); $this->assertCount(1, $this->pending()); } + /** + * Two leg drafts are one placement on the dashboard, not two rows. + */ + public function testBothLegDraftsListThePlacementOnce(): void + { + $disposition = $this->escort(); + $this->respond($disposition, submit: true); + $this->respond($disposition, submit: false, questionnaire: QuestionnaireCatalog::BUS_FEEDBACK, leg: BusLeg::OUTBOUND); + $this->respond($disposition, submit: false, questionnaire: QuestionnaireCatalog::BUS_FEEDBACK, leg: BusLeg::RETURN); + + $this->assertSame([['disposition' => $disposition, 'draft' => true]], $this->pending()); + } + + /** + * An escort who rode only the return bus has a single leg response; it settles the bus + * feedback. + */ + public function testASubmittedReturnLegSettlesTheBusFeedback(): void + { + $disposition = $this->escort(); + $this->respond($disposition, submit: true); + $this->respond($disposition, submit: true, questionnaire: QuestionnaireCatalog::BUS_FEEDBACK, leg: BusLeg::RETURN); + + $this->assertSame([], $this->pending()); + } + public function testAnAssignmentEndingTodayIsPending(): void { $this->escort(dateTo: 'today'); @@ -154,7 +186,7 @@ class DispositionRepositoryQuestionnaireTest extends KernelTestCase { return [ 'not over yet' => [static fn (Disposition $d) => $d->getAssignment()->getDestination()->setDateTo(new \DateTimeImmutable('tomorrow'))], - 'ended before the window' => [static fn (Disposition $d) => $d->getAssignment()->getDestination()->setDateTo(new \DateTimeImmutable('today -31 days'))], + 'ended before go-live' => [static fn (Disposition $d) => $d->getAssignment()->getDestination()->setDateTo(new \DateTimeImmutable('2025-12-31'))], 'skip formalities' => [static fn (Disposition $d) => $d->getAssignment()->setSkipFormalities(true)], 'called off' => [static fn (Disposition $d) => $d->setStatus(Disposition::STATUS_CALLED_OFF)], 'assignment called off' => [static fn (Disposition $d) => $d->getAssignment()->setStatus(Assignment::STATUS_CALLED_OFF)], @@ -170,6 +202,66 @@ class DispositionRepositoryQuestionnaireTest extends KernelTestCase $this->assertSame([], $this->pending()); } + /** + * The mail starts the day after the trip: on its last day the teamer is only just back. + */ + public function testTheReminderStartsTheDayAfterTheTrip(): void + { + $this->withUser($this->teamer); + $yesterday = $this->escort(dateTo: 'yesterday'); + $this->escort(dateTo: 'today'); + + $this->assertSame([$yesterday], $this->reminded()); + } + + public function testTheReminderCoversEveryTeamerAndKeepsGoingUntilSubmitted(): void + { + $this->withUser($this->teamer); + $other = (new Teamer())->setFirstName('Alex')->setLastName('Beispiel')->setGender('d'); + $this->entityManager->persist($other); + $this->withUser($other); + + $old = $this->escort(dateTo: self::GO_LIVE); + $draft = $this->escort(teamer: $other); + $this->respond($draft, submit: false); + $done = $this->escort(); + $this->respond($done, submit: true); + $this->respond($done, submit: true, questionnaire: QuestionnaireCatalog::BUS_FEEDBACK); + + $reminded = $this->reminded(); + + $this->assertContains($old, $reminded); + $this->assertContains($draft, $reminded); + $this->assertNotContains($done, $reminded); + } + + /** + * A teamer who cannot log in cannot submit, and would be mailed every day forever. + * + * @param \Closure(Teamer, ?\App\Entity\User): mixed $change + */ + #[\PHPUnit\Framework\Attributes\DataProvider('notReminded')] + public function testTeamersWhoCannotLogInAreNotReminded(bool $withUser, \Closure $change): void + { + $user = $withUser ? $this->withUser($this->teamer) : null; + $change($this->teamer, $user); + $this->escort(); + + $this->assertSame([], $this->reminded()); + } + + /** + * @return array + */ + public static function notReminded(): array + { + return [ + 'no user account' => [false, static fn () => null], + 'user blocked' => [true, static fn (Teamer $t, $user) => $user->setDisabledAt(new \DateTimeImmutable('yesterday'))], + 'teamer deleted' => [true, static fn (Teamer $t) => $t->setDeleted()], + ]; + } + /** * @return list */ @@ -177,6 +269,16 @@ class DispositionRepositoryQuestionnaireTest extends KernelTestCase { $this->entityManager->flush(); - return $this->repository->findPendingQuestionnaireByTeamer($this->teamer, QuestionnaireCatalog::windowStart(30)); + return $this->repository->findPendingQuestionnaireByTeamer($this->teamer, new \DateTimeImmutable(self::GO_LIVE)); + } + + /** + * @return list + */ + private function reminded(): array + { + $this->entityManager->flush(); + + return $this->repository->findQuestionnaireReminders(new \DateTimeImmutable(self::GO_LIVE), new \DateTimeImmutable('today')); } } diff --git a/tests/Repository/QuestionnaireFixturesTrait.php b/tests/Repository/QuestionnaireFixturesTrait.php index f4d84f4..3024aea 100644 --- a/tests/Repository/QuestionnaireFixturesTrait.php +++ b/tests/Repository/QuestionnaireFixturesTrait.php @@ -11,6 +11,8 @@ use App\Entity\Destination; use App\Entity\Disposition; use App\Entity\QuestionnaireResponse; use App\Entity\Teamer; +use App\Entity\User; +use App\Enum\BusLeg; use App\Model\Questionnaire\Definition; use Doctrine\ORM\EntityManagerInterface; @@ -50,10 +52,14 @@ trait QuestionnaireFixturesTrait return $disposition; } - private function respond(Disposition $disposition, bool $submit, string $questionnaire = QuestionnaireCatalog::TEAMER_FEEDBACK): QuestionnaireResponse + /** + * A bus feedback is given per leg, the outbound one unless another is named. + */ + private function respond(Disposition $disposition, bool $submit, string $questionnaire = QuestionnaireCatalog::TEAMER_FEEDBACK, ?BusLeg $leg = null): QuestionnaireResponse { - $definition = new Definition($questionnaire, 1, 'Beispiel', null, []); - $response = QuestionnaireResponse::forDisposition($definition, $disposition); + $perBusLeg = QuestionnaireCatalog::BUS_FEEDBACK === $questionnaire; + $definition = new Definition($questionnaire, 1, 'Beispiel', null, [], $perBusLeg); + $response = QuestionnaireResponse::forDisposition($definition, $disposition, $perBusLeg ? $leg ?? BusLeg::OUTBOUND : null); if ($submit) { $response->submit($definition, [], [], new \DateTimeImmutable()); @@ -65,4 +71,23 @@ trait QuestionnaireFixturesTrait return $response; } + + /** + * The login a teamer needs to be reminded at all. + */ + private function withUser(Teamer $teamer): User + { + $user = (new User()) + ->setFirstName($teamer->getFirstName()) + ->setLastName($teamer->getLastName()) + ->setEmail(uniqid('questionnaire.', true).'@example.com') + ->setRoles(['ROLE_TEAMER']) + ->setBusProAddressId(1) + ->setBusProPersonId(1) + ->setTeamer($teamer) + ; + $this->entityManager->persist($user); + + return $user; + } } diff --git a/tests/Security/Voter/DispositionVoterTest.php b/tests/Security/Voter/DispositionVoterTest.php index 058cdd4..b3e1705 100644 --- a/tests/Security/Voter/DispositionVoterTest.php +++ b/tests/Security/Voter/DispositionVoterTest.php @@ -159,7 +159,7 @@ class DispositionVoterTest extends TestCase $this->assertSame( $expected ? VoterInterface::ACCESS_GRANTED : VoterInterface::ACCESS_DENIED, - (new DispositionVoter($this->security, 30))->vote($token, $disposition, [DispositionVoter::MANAGE_RECEIPTS]), + (new DispositionVoter($this->security, '2026-01-01'))->vote($token, $disposition, [DispositionVoter::MANAGE_RECEIPTS]), ); } @@ -217,20 +217,19 @@ class DispositionVoterTest extends TestCase { return [ 'assignment not over yet' => [static fn (Disposition $d) => $d->getAssignment()->getDestination()->setDateTo(new \DateTimeImmutable('tomorrow'))], - 'ended before the window' => [static fn (Disposition $d) => $d->getAssignment()->getDestination()->setDateTo(new \DateTimeImmutable('today -31 days'))], + 'ended before go-live' => [static fn (Disposition $d) => $d->getAssignment()->getDestination()->setDateTo(new \DateTimeImmutable('2025-12-31'))], 'skip formalities' => [static fn (Disposition $d) => $d->getAssignment()->setSkipFormalities(true)], 'called off' => [static fn (Disposition $d) => $d->setStatus(Disposition::STATUS_CALLED_OFF)], ]; } - public function testTheQuestionnaireIsStillOfferedOnTheWindowsLastDay(): void + /** + * An unfinished questionnaire stays open however long ago the trip ended - only go-live and + * submitting end it. + */ + public function testTheQuestionnaireStaysOpenLongAfterTheTrip(): void { - $this->assertQuestionnaire(true, $this->escortDisposition(dateTo: 'today -30 days')); - } - - public function testTheWindowIsConfigurable(): void - { - $this->assertQuestionnaire(false, $this->escortDisposition(dateTo: 'today -8 days'), windowDays: 7); + $this->assertQuestionnaire(true, $this->escortDisposition(dateTo: '2026-01-01')); } public function testAnotherTeamerMayNotFillInTheQuestionnaire(): void @@ -252,11 +251,18 @@ class DispositionVoterTest extends TestCase $this->assertSame( VoterInterface::ACCESS_DENIED, - $this->questionnaireVote($disposition, (new User())->setTeamer($disposition->getTeamer()), 30), + $this->questionnaireVote($disposition, (new User())->setTeamer($disposition->getTeamer()), '2026-01-01'), ); } - private function assertQuestionnaire(bool $expected, Disposition $disposition, int $windowDays = 30, ?User $user = null): void + public function testAMalformedGoLiveDateFailsLoudly(): void + { + $this->expectException(\InvalidArgumentException::class); + + new DispositionVoter($this->security, '01.01.2026'); + } + + private function assertQuestionnaire(bool $expected, Disposition $disposition, string $goLive = '2026-01-01', ?User $user = null): void { $this->security ->method('isGranted') @@ -265,20 +271,20 @@ class DispositionVoterTest extends TestCase $this->assertSame( $expected ? VoterInterface::ACCESS_GRANTED : VoterInterface::ACCESS_DENIED, - $this->questionnaireVote($disposition, $user ?? (new User())->setTeamer($disposition->getTeamer()), $windowDays), + $this->questionnaireVote($disposition, $user ?? (new User())->setTeamer($disposition->getTeamer()), $goLive), ); } - private function questionnaireVote(Disposition $disposition, User $user, int $windowDays): int + private function questionnaireVote(Disposition $disposition, User $user, string $goLive): int { $token = $this->createStub(TokenInterface::class); $token->method('getUser')->willReturn($user); - return (new DispositionVoter($this->security, $windowDays))->vote($token, $disposition, [DispositionVoter::QUESTIONNAIRE]); + return (new DispositionVoter($this->security, $goLive))->vote($token, $disposition, [DispositionVoter::QUESTIONNAIRE]); } /** - * A bus escort that ended yesterday, well within the 30-day window the tests use. + * A bus escort that ended yesterday, after the go-live date the tests use. */ private function escortDisposition(string $dateTo = 'yesterday'): Disposition { @@ -294,7 +300,7 @@ class DispositionVoterTest extends TestCase private function vote(string $attribute, Disposition $disposition): int { - return (new DispositionVoter($this->security, 30))->vote( + return (new DispositionVoter($this->security, '2026-01-01'))->vote( $this->createStub(TokenInterface::class), $disposition, [$attribute], diff --git a/tests/Service/Cron/QuestionnaireReminderServiceTest.php b/tests/Service/Cron/QuestionnaireReminderServiceTest.php new file mode 100644 index 0000000..7788305 --- /dev/null +++ b/tests/Service/Cron/QuestionnaireReminderServiceTest.php @@ -0,0 +1,111 @@ +repository = $this->createMock(DispositionRepository::class); + $this->mailer = $this->createMock(Mailer::class); + + $this->service = new QuestionnaireReminderService($this->repository, $this->mailer, new NullLogger(), '2026-11-10'); + } + + public function testItAsksForTheGoLiveDateAndToday(): void + { + $this->repository + ->expects($this->once()) + ->method('findQuestionnaireReminders') + ->with(new \DateTimeImmutable('2026-11-10'), new \DateTimeImmutable('2026-11-20')) + ->willReturn([]) + ; + + $this->assertSame('Sent 0 questionnaire reminders to teamers', $this->service->sendReminders(new \DateTimeImmutable('2026-11-20 01:00'))); + } + + public function testOneMailPerTeamerListsEveryPlacement(): void + { + $kim = $this->teamer('kim@example.org'); + $alex = $this->teamer('alex@example.org'); + + $this->repository->method('findQuestionnaireReminders')->willReturn([ + $this->placement($kim, '2026-11-14'), + $this->placement($kim, '2026-11-07'), + $this->placement($alex, '2026-11-14'), + ]); + + $sent = []; + $this->mailer + ->expects($this->exactly(2)) + ->method('createAndSendText') + ->willReturnCallback(function (EmailTextKey $key, array $placeholders, array $options) use (&$sent): void { + $this->assertSame(EmailTextKey::REMINDER_QUESTIONNAIRE, $key); + $sent[$options['to']] = $placeholders['destinations']; + }) + ; + + $this->assertSame('Sent 2 questionnaire reminders to teamers', $this->service->sendReminders(new \DateTimeImmutable('2026-11-20'))); + $this->assertSame(['kim@example.org', 'alex@example.org'], array_keys($sent)); + // labelled as everywhere in the reminders, by Destination::__toString() + $this->assertSame('07.11.26 - 14.11.26 Skireise, 31.10.26 - 07.11.26 Skireise', $sent['kim@example.org']); + $this->assertSame('07.11.26 - 14.11.26 Skireise', $sent['alex@example.org']); + } + + public function testATeamerWithoutAnAddressIsSkipped(): void + { + $this->repository->method('findQuestionnaireReminders')->willReturn([$this->placement(new Teamer(), '2026-11-14')]); + $this->mailer->expects($this->never())->method('createAndSendText'); + + $this->assertSame('Sent 0 questionnaire reminders to teamers', $this->service->sendReminders(new \DateTimeImmutable('2026-11-20'))); + } + + public function testAMalformedGoLiveDateFailsLoudly(): void + { + $this->expectException(\InvalidArgumentException::class); + + new QuestionnaireReminderService($this->repository, $this->mailer, new NullLogger(), '10.11.2026'); + } + + private function teamer(string $email): Teamer + { + return (new Teamer())->setCommunication((new Communication())->setEmail($email)); + } + + private function placement(Teamer $teamer, string $dateTo): Disposition + { + $destination = (new Destination()) + ->setProduct('Skireise') + ->setDateFrom(new \DateTimeImmutable($dateTo.' -7 days')) + ->setDateTo(new \DateTimeImmutable($dateTo)) + ; + + return new Disposition(new Application((new Assignment())->setDestination($destination), $teamer)); + } +} diff --git a/tests/Twig/QuestionnaireTemplateTest.php b/tests/Twig/QuestionnaireTemplateTest.php index da9c0b0..7435ac5 100644 --- a/tests/Twig/QuestionnaireTemplateTest.php +++ b/tests/Twig/QuestionnaireTemplateTest.php @@ -24,18 +24,27 @@ use Twig\Environment; */ class QuestionnaireTemplateTest extends KernelTestCase { + /** + * The bus questions come once per leg, plus the choice of legs and the two leg blocks, which + * the controller shows and hides like conditional questions. + */ public function testEveryQuestionRowCarriesItsKeyAndConditionalOnesTheirCondition(): void { $crawler = $this->renderForm(); $this->assertCount( - count($this->definition()->getQuestions()) + count($this->busDefinition()->getQuestions()), + count($this->definition()->getQuestions()) + 2 * count($this->busDefinition()->getQuestions()) + 3, $crawler->filter('[data-question-key]'), ); $this->assertSame( - '{"question":"bus_feedback.bus_company","operator":"equals","value":"other"}', - $crawler->filter('[data-question-key="bus_feedback.bus_company_other"]')->attr('data-show-if'), + '{"question":"bus_feedback.return.bus_company","operator":"equals","value":"other"}', + $crawler->filter('[data-question-key="bus_feedback.return.bus_company_other"]')->attr('data-show-if'), ); + $this->assertSame( + '{"question":"bus_feedback.legs","operator":"in","value":["outbound","both"]}', + $crawler->filter('[data-question-key="bus_feedback.outbound"]')->attr('data-show-if'), + ); + $this->assertSame('Hinfahrt', trim($crawler->filter('[data-question-key="bus_feedback.outbound"] > h3')->text())); } public function testSectionsAreFieldsetsWithTheirTitle(): void @@ -44,7 +53,7 @@ class QuestionnaireTemplateTest extends KernelTestCase $this->assertSame('Organisation & Ablauf', trim($crawler->filter('fieldset legend')->first()->text())); $this->assertCount( - count($this->definition()->sections) + count($this->busDefinition()->sections), + count($this->definition()->sections) + 2 * count($this->busDefinition()->sections), $crawler->filter('fieldset'), ); } @@ -69,7 +78,7 @@ class QuestionnaireTemplateTest extends KernelTestCase $seminar = $crawler->filter('[data-question-key="teamer_feedback.team_week_seminar"] select'); $this->assertCount(1, $seminar); $this->assertSame('', $seminar->filter('option')->first()->attr('value')); - $this->assertCount(1, $crawler->filter('[data-question-key="bus_feedback.wc"] select')); + $this->assertCount(1, $crawler->filter('[data-question-key="bus_feedback.outbound.wc"] select')); // the labels wrapping a radio: the whole row is the click target $rows = $crawler