feat: keep questionnaires until submitted, remind teamers daily and take bus feedback per leg

This commit is contained in:
fromme committed 2026-11-10 16:38:51 +01:00
1 parent abf9c1be0b
commit e72616fdbf
37 files changed
+1119 -238

No files matched your search

+13
View File
@@ -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"'
+5 -8
View File
@@ -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
+7 -4
View File
@@ -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'
+34
View File
@@ -0,0 +1,34 @@
<?php
declare(strict_types=1);
namespace DoctrineMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
/**
* Written by hand from the diff, keeping only questionnaire_response: doctrine:migrations:diff
* also sweeps in the pre-existing drift of the dev database.
*/
final class Version20261110120000 extends AbstractMigration
{
public function getDescription(): string
{
return 'Answer the bus feedback once per escorted leg';
}
public function up(Schema $schema): void
{
$this->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');
}
}
+5
View File
@@ -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;
}
}
+1
View File
@@ -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';
+14 -10
View File
@@ -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<string, Question> $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,
);
}
@@ -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(),
);
@@ -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;
}
+1 -1
View File
@@ -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')),
)
;
@@ -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) {
@@ -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,
+26 -2
View File
@@ -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()) {
+21
View File
@@ -0,0 +1,21 @@
<?php
namespace App\Enum;
/**
* One ride of a bus escort. The bus feedback is given once per leg the teamer escorted: the
* assignment only records the outbound stop, so the teamer says which legs they rode.
*/
enum BusLeg: string
{
case OUTBOUND = 'outbound';
case RETURN = 'return';
public function label(): string
{
return match ($this) {
self::OUTBOUND => 'Hinfahrt',
self::RETURN => 'Rückfahrt',
};
}
}
+149 -19
View File
@@ -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<string, mixed> $data the form's data, keyed by questionnaire key
* @param list<Definition> $definitions
*
* @return list<array{definition: Definition, leg: BusLeg|null, answers: array<string, mixed>}>
*/
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<string, array<string, mixed>> $answersByLeg keyed by BusLeg value
*
* @return array<string, mixed>
*/
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<string, mixed> $part the data of a per-bus-leg questionnaire
*
* @return list<BusLeg>
*/
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<string, mixed>}
*/
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),
+4
View File
@@ -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,
) {
}
+101 -59
View File
@@ -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<array{disposition: Disposition, draft: bool}>
*/
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<Disposition> 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');
@@ -81,14 +81,16 @@ class QuestionnaireResponseRepository extends ServiceEntityRepository
}
/**
* @return array<string, QuestionnaireResponse> keyed by questionnaire key
* @return array<string, list<QuestionnaireResponse>> 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;
+6 -3
View File
@@ -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');
}
@@ -0,0 +1,73 @@
<?php
namespace App\Service\Cron;
use App\Config\EmailTextKey;
use App\Config\QuestionnaireCatalog;
use App\Email\Mailer;
use App\Entity\Disposition;
use App\Repository\DispositionRepository;
use Psr\Log\LoggerInterface;
/**
* Reminds teamers of their unsubmitted questionnaires, every day from the day after the trip ended
* until they are submitted - a saved draft does not count. One mail per teamer, listing every such
* placement.
*
* Like the other reminders it records nothing: the cron runs once a day, and that is what makes it
* daily.
*/
class QuestionnaireReminderService
{
private readonly \DateTimeImmutable $questionnaireGoLive;
/**
* @param string $questionnaireGoLive Y-m-d, the services.yaml parameter questionnaire_go_live
*/
public function __construct(
private readonly DispositionRepository $dispositionRepository,
private readonly Mailer $mailer,
private readonly LoggerInterface $logger,
string $questionnaireGoLive,
) {
$this->questionnaireGoLive = QuestionnaireCatalog::parseGoLive($questionnaireGoLive);
}
public function sendReminders(?\DateTimeImmutable $today = null): string
{
$today = ($today ?? new \DateTimeImmutable('today'))->setTime(0, 0);
/** @var array<int, list<Disposition>> $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;
}
}
@@ -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 %}
<h1 class="text-2xl font-bold pb-4">
{{ definition.title }}
{{ definition.title }}{% if response.leg %}: {{ response.leg.label }}{% endif %}
</h1>
<p class="pb-8 text-gray-700">
{{ context.teamerName|default('-') }}, abgeschickt am {{ response.submittedAt|date('d.m.Y, H:i') }} Uhr
@@ -43,7 +43,7 @@
{% for sibling in siblings %}
<li>
<a href="{{ path('app_administrative_questionnaire_detail', { 'uuid': sibling.response.uuid, 'r': app.request.query.get('r') }) }}" class="underline">
{{ sibling.title }}
{{ sibling.title }}{% if sibling.response.leg %}: {{ sibling.response.leg.label }}{% endif %}
</a>
</li>
{% endfor %}
@@ -56,6 +56,11 @@
<th>
{{ knp_pagination_sortable(pagination, 'Haus', 'destination.hotel') }}
</th>
{% if definition.perBusLeg %}
<th>
{{ knp_pagination_sortable(pagination, 'Fahrt', 'response.leg') }}
</th>
{% endif %}
<th>
{{ knp_pagination_sortable(pagination, 'Abgeschickt', 'response.submittedAt') }}
</th>
@@ -82,6 +87,11 @@
<td>
{{ destination.hotel }}
</td>
{% if definition.perBusLeg %}
<td>
{{ response.leg.label|default('-') }}
</td>
{% endif %}
<td>
{{ response.submittedAt|date('d.m.Y') }}
</td>
@@ -93,7 +103,7 @@
</tr>
{% else %}
<tr>
<td colspan="6">
<td colspan="{{ definition.perBusLeg ? 7 : 6 }}">
Keine Daten...
</td>
</tr>
@@ -36,7 +36,7 @@
{% for item in submitted %}
<section>
<h2 class="text-2xl font-bold pb-4">
{{ item.definition.title }}
{{ item.definition.title }}{% if item.leg %}: {{ item.leg.label }}{% endif %}
</h2>
{% include 'questionnaire/_answers.html.twig' with { 'definition': item.definition, 'answers': item.answers } %}
</section>
+14
View File
@@ -189,6 +189,20 @@
</section>
{%- 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 -%}
<div class="pt-4"{% with { attr: row_attr } %}{{ block('attributes') }}{% endwith %}>
<h3 class="text-xl font-bold text-primary border-b border-gray-200 pb-2 mb-6">{{ label }}</h3>
{%- for child in form -%}
{{- form_row(child) -}}
{%- endfor -%}
</div>
{%- 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
+2 -1
View File
@@ -18,7 +18,8 @@
{% if pendingQuestionnaires is not empty %}
{% embed '_partials/_alert.html.twig' with { 'type': 'info' } %}
{% block message %}
<p>Bitte fülle den Fragebogen zu deinem Einsatz aus:</p>
<p class="font-bold">Bitte den Feedbackbogen spätestens drei Tage nach Reiseende ausfüllen.</p>
<p class="pt-1">Offen ist noch:</p>
<ul class="pt-1">
{% for row in pendingQuestionnaires %}
{% set destination = row.disposition.assignment.destination %}
@@ -15,7 +15,7 @@
{% for item in submitted %}
<section>
<h2 class="text-2xl font-bold pb-1">
{{ item.definition.title }}
{{ item.definition.title }}{% if item.response.leg %}: {{ item.response.leg.label }}{% endif %}
</h2>
<p class="pb-6 text-sm text-gray-500">
Abgeschickt am {{ item.response.submittedAt|date('d.m.Y, H:i') }} Uhr
+21 -4
View File
@@ -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"',
@@ -19,7 +19,8 @@ use PHPUnit\Framework\TestCase;
*
* The lists below are the Google forms' questions in their order, with what each became:
* "question:<key>" is asked, "context:<field>" 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 {
@@ -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"]'));
}
/**
@@ -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<string> $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<string, QuestionnaireResponseStatus> keyed by questionnaire, sorted
* @return array<string, QuestionnaireResponseStatus> 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);
@@ -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()));
+144 -31
View File
@@ -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, array{array<string, array<string, mixed>>, 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<string, array<string, mixed>> $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<Definition> $definitions
*
* @return array<string, array<string, array<string, mixed>>>
* @return array<string, array<string, mixed>>
*/
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<string, array<string, mixed>> 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;
}
}
}
@@ -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<string, array{bool, \Closure(Teamer, ?\App\Entity\User): mixed}>
*/
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<array{disposition: Disposition, draft: bool}>
*/
@@ -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<Disposition>
*/
private function reminded(): array
{
$this->entityManager->flush();
return $this->repository->findQuestionnaireReminders(new \DateTimeImmutable(self::GO_LIVE), new \DateTimeImmutable('today'));
}
}
@@ -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;
}
}
+22 -16
View File
@@ -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],
@@ -0,0 +1,111 @@
<?php
declare(strict_types=1);
namespace App\Tests\Service\Cron;
use App\Config\EmailTextKey;
use App\Email\Mailer;
use App\Entity\Application;
use App\Entity\Assignment;
use App\Entity\Destination;
use App\Entity\Disposition;
use App\Entity\Embeddable\Communication;
use App\Entity\Teamer;
use App\Repository\DispositionRepository;
use App\Service\Cron\QuestionnaireReminderService;
use PHPUnit\Framework\Attributes\AllowMockObjectsWithoutExpectations;
use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
use Psr\Log\NullLogger;
/**
* One mail per teamer, however many placements they owe a questionnaire for. Which placements
* those are is the repository's rule, pinned in DispositionRepositoryQuestionnaireTest.
*/
#[AllowMockObjectsWithoutExpectations]
class QuestionnaireReminderServiceTest extends TestCase
{
private DispositionRepository&MockObject $repository;
private Mailer&MockObject $mailer;
private QuestionnaireReminderService $service;
protected function setUp(): void
{
$this->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('[email protected]');
$alex = $this->teamer('[email protected]');
$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(['[email protected]', '[email protected]'], 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['[email protected]']);
$this->assertSame('07.11.26 - 14.11.26 Skireise', $sent['[email protected]']);
}
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));
}
}
+14 -5
View File
@@ -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