feat: add the house manager questionnaire per travel and compact the questionnaire layout

This commit is contained in:
fromme committed 2026-11-11 11:16:37 +01:00
1 parent d760ed3cdf
commit bfef08b519
50 files changed
+2763 -180

No files matched your search

+1
View File
@@ -7,3 +7,4 @@
@import "./components/tooltip.css";
@import "./components/timeline.css";
@import "./components/mail-body.css";
@import "./components/questionnaire.css";
@@ -0,0 +1,9 @@
/*
* A questionnaire "pick" (App\Form\Questionnaire\AbstractPickType): a checkbox, and below it the
* fields that only matter once it is ticked (templates/forms.html.twig, questionnaire_pick_*). They stay in the form, and are submitted, while
* hidden; the form type drops them. The child combinator keeps a nested pick (a guiding type
* inside a teamer) from answering for its parent.
*/
.questionnaire-pick:not(:has(> .questionnaire-pick__head input:checked)) > .questionnaire-pick__body {
display: none;
}
@@ -0,0 +1,159 @@
# Questionnaire the house manager fills in once per travel (Destination) after it has ended.
#
# From the stakeholder briefing of 2026-11-11; the plan is .ddev/plans/house-manager-questionnaire.md.
# What the travel already knows (product, house, dates, teamers) is not asked: it is snapshotted
# into the response's context. Its last point, "Bewerte dein Wochenteam", is not a question: the
# page lists the travel's teamers after the form, each linking to the existing rating form.
#
# Labels, help texts, section titles and option labels may be edited in place. Renaming or
# removing a question or option key, or changing a type, needs a new version: copy this file to
# house_manager_feedback.v1.yaml first, then bump `version` here. Submitted answers are keyed by it.
#
# Parsed and validated by App\Config\QuestionnaireCatalog; QuestionnaireCatalogTest builds it.
#
# Besides the types of teamer_feedback.yaml, this one uses the house manager's widgets, whose
# options are what can be picked per teamer or item:
# teamer_guidings (guiding types; count and participants each), teamer_courses (course types;
# days × hours per day and the days it took place) and programme (items with their participants,
# plus "Sonstiges" as free text; "other" is reserved for it).
key: house_manager_feedback
version: 1
title: "Hausleitungsfeedback"
description: |-
Dein Feedback zur Reise. Du kannst den Fragebogen jederzeit als Entwurf speichern und später
weiter ausfüllen.
sections:
- key: arrival
title: "Gruppe & Anreise"
questions:
- key: groups_in_house
label: "Gruppe(n) im Haus?"
type: choice
required: true
options: &yes_no
- { key: ja, label: "Ja" }
- { key: nein, label: "Nein" }
- key: bus_arrival
label: "Busanreise?"
type: choice
required: true
options: *yes_no
- key: bus_late
label: "Unpünktlich?"
type: choice
required: true
options: *yes_no
show_if: { question: bus_arrival, equals: ja }
- key: bus_arrival_time
label: "Wann kam der Bus?"
type: text
required: true
show_if: { question: bus_late, equals: ja }
- key: no_shows
label: "Gab es No-Shows?"
type: choice
required: true
options: *yes_no
- key: unused_services
label: "Wurden Leistungen nicht bezogen?"
type: choice
required: true
options: *yes_no
- key: unused_services_details
label: "Bitte trage hier den Vorfall des Kunden mit VG-Nummer ein:"
type: textarea
required: true
show_if: { question: unused_services, equals: ja }
- key: guidings_and_courses
title: "Guidings & Kurse"
questions:
- key: guidings
label: "Gab es Guidings?"
type: choice
required: true
options: *yes_no
- key: guiding_teamers
label: "Wer hat das Guiding gegeben?"
help: "Bitte wähle aus, mehrere sind möglich."
type: teamer_guidings
required: true
options:
- { key: half_day, label: "Halbtagesguiding" }
- { key: full_day, label: "Ganztagesguiding" }
show_if: { question: guidings, equals: ja }
- key: courses
label: "Gab es Kurse?"
type: choice
required: true
options: *yes_no
- key: course_teamers
label: "Wer hat welchen Kurs gegeben?"
help: "Bitte wähle aus, mehrere sind möglich."
type: teamer_courses
required: true
options:
- { key: ski_beginner, label: "Ski-Anfänger:innen-Kurs" }
- { key: ski_advanced, label: "Ski-Fortgeschrittenen-Kurs" }
- { key: snowboard_beginner, label: "Snowboard-Anfänger:innen-Kurs" }
- { key: snowboard_advanced, label: "Snowboard-Fortgeschrittenen-Kurs" }
show_if: { question: courses, equals: ja }
- key: activities
title: "Programm"
questions:
- key: programme_deviations
label: "Gab es Besonderheiten/Abweichungen vom Beispiel-Programm, welches im Reisebriefing verschickt wurde?"
type: choice
required: true
options: *yes_no
- key: programme_deviations_details
label: "Bitte beschreibe, was genau."
type: textarea
required: true
show_if: { question: programme_deviations, equals: ja }
- key: programme
label: "Welches Programm hat stattgefunden?"
help: "Mehrere sind möglich."
type: programme
required: true
options:
- { key: village_check, label: "Dorfcheck am Anreisetag" }
- { key: mulled_wine_party, label: "Glühweinparty" }
- { key: slope_snack, label: "Pistensnack" }
- { key: hut_evening, label: "Hüttenabend" }
- { key: torch_hike, label: "Fackelwanderung" }
- { key: toboggan_evening, label: "Rodelabend" }
- { key: witches_cauldron, label: "Hexenkessel" }
- key: closing
title: "Vorkommnisse & Gruppe"
questions:
- key: incidents
label: "Gab es besondere Vorkommnisse, z. B. schwerwiegende Verletzungen oder Beschwerden?"
type: choice
required: true
options: *yes_no
- key: incidents_details
label: "Was ist passiert?"
type: textarea
required: true
show_if: { question: incidents, equals: ja }
- key: group_feedback
label: "Feedback zur Gruppe"
type: textarea
+8
View File
@@ -127,6 +127,12 @@ parameters:
# Without a cutoff every past placement would be pending at once.
questionnaire_go_live: '2026-11-10'
# The house manager's questionnaire about a travel (config/questionnaires/house_manager_feedback.yaml)
# is offered for travels ending on or after this day (Y-m-d), and keeps the travel pending - in
# the list, on the dashboard and in the daily reminder - until submitted. Teamer ratings stay
# pending as before, whatever this date.
house_manager_questionnaire_go_live: '2026-11-11'
# 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
# single definition of both deadlines: the first is this offset, the second defaults to
@@ -191,6 +197,7 @@ services:
# Likewise parsed on demand, by App\Config\QuestionnaireCatalog.
$questionnaireDir: '%kernel.project_dir%/config/questionnaires'
$questionnaireGoLive: '%questionnaire_go_live%'
$houseManagerQuestionnaireGoLive: '%house_manager_questionnaire_go_live%'
$mailingBusTransport: '%mailing_bus_transport%'
$seasonStart: '%season_start%'
$seasonEnd: '%season_end%'
@@ -518,3 +525,4 @@ when@test:
mailing_bus_transport: 'sync'
# the questionnaire tests need it offered; any day before the placements they create
questionnaire_go_live: '2026-01-01'
house_manager_questionnaire_go_live: '2026-01-01'
+36
View File
@@ -0,0 +1,36 @@
<?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 Version20261111100000 extends AbstractMigration
{
public function getDescription(): string
{
return 'Let a questionnaire response be about a travel, for the house manager questionnaire';
}
public function up(Schema $schema): void
{
$this->addSql('ALTER TABLE questionnaire_response ADD destination_id INT DEFAULT NULL');
$this->addSql('ALTER TABLE questionnaire_response ADD CONSTRAINT FK_A0400276816C6140 FOREIGN KEY (destination_id) REFERENCES destination (id) ON DELETE CASCADE');
$this->addSql('CREATE INDEX IDX_A0400276816C6140 ON questionnaire_response (destination_id)');
$this->addSql('CREATE UNIQUE INDEX questionnaire_destination ON questionnaire_response (questionnaire, destination_id)');
}
public function down(Schema $schema): void
{
$this->addSql('DROP INDEX questionnaire_destination ON questionnaire_response');
$this->addSql('ALTER TABLE questionnaire_response DROP FOREIGN KEY FK_A0400276816C6140');
$this->addSql('DROP INDEX IDX_A0400276816C6140 ON questionnaire_response');
$this->addSql('ALTER TABLE questionnaire_response DROP destination_id');
}
}
+11 -4
View File
@@ -35,6 +35,12 @@ class QuestionnaireCatalog
*/
public const string BUS_FEEDBACK = 'bus_feedback';
/**
* The one a house manager fills in about a travel; see DestinationVoter::QUESTIONNAIRE. Its
* subject is a Destination rather than a Disposition.
*/
public const string HOUSE_MANAGER_FEEDBACK = 'house_manager_feedback';
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'];
@@ -57,14 +63,15 @@ class QuestionnaireCatalog
}
/**
* 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.
* A services.yaml go-live parameter as a date: questionnaire_go_live for the teamer
* questionnaire (placements ending on or after it), house_manager_questionnaire_go_live for the
* house manager's (travels ending on or after it). Either stays pending until submitted.
* Without it, every past placement or travel would be pending and reminded of at once.
*/
public static function parseGoLive(string $goLive): \DateTimeImmutable
{
return \DateTimeImmutable::createFromFormat('!Y-m-d', $goLive)
?: throw new \InvalidArgumentException(sprintf('questionnaire_go_live "%s" is not a Y-m-d date', $goLive));
?: throw new \InvalidArgumentException(sprintf('Questionnaire go-live "%s" is not a Y-m-d date', $goLive));
}
/**
@@ -16,8 +16,8 @@ use Symfony\Component\Routing\Requirement\Requirement;
use Symfony\Component\Security\Http\Attribute\IsGranted;
/**
* One submitted questionnaire: what the disposition knew when it was submitted, then the answers,
* rendered with the definition version they were given under.
* One submitted questionnaire: what the disposition or travel knew when it was submitted, then the
* answers, rendered with the definition version they were given under.
*/
class DetailController extends AbstractController
{
@@ -43,8 +43,8 @@ class DetailController extends AbstractController
}
// the other responses of the same placement, e.g. the bus feedback beside the teamer feedback,
// or the other leg's
$siblings = array_filter(
// or the other leg's; a travel's questionnaire has none
$siblings = null === $response->getDisposition() ? [] : array_filter(
array_merge(...array_values($this->responseRepository->findByDisposition($response->getDisposition()))),
static fn (QuestionnaireResponse $sibling): bool => $sibling !== $response && $sibling->isSubmitted(),
);
@@ -0,0 +1,76 @@
<?php
namespace App\Controller\Administrative\Questionnaire;
use App\Config\QuestionnaireCatalog;
use App\Controller\Traits\ReturnUrlTrait;
use App\Entity\Assignment;
use App\Form\QuestionnaireType;
use App\Repository\DispositionRepository;
use App\Service\Questionnaire\DestinationContext;
use Symfony\Bridge\Doctrine\Attribute\MapEntity;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Attribute\IsGranted;
/**
* The house manager's questionnaire as a house manager gets it for the travel of this assignment,
* with the travel's teamers - before or after the trip. Opened from an assignment, since that is
* where the office tries out the teamer questionnaires too. Nothing is saved: "Absenden" shows
* the answers as they would be stored, "Entwurf speichern" just keeps them in the form.
*/
class HouseManagerTestController extends AbstractController
{
use ReturnUrlTrait;
public function __construct(
private readonly QuestionnaireCatalog $catalog,
private readonly DispositionRepository $dispositionRepository,
) {
}
#[Route('/administrative/questionnaire/test-house-manager/{uuid}', name: 'app_administrative_questionnaire_test_house_manager')]
#[IsGranted('ROLE_ADMINISTRATIVE')]
public function index(
#[MapEntity(mapping: ['uuid' => 'uuid'])]
Assignment $assignment,
Request $request,
): Response {
$destination = $assignment->getDestination();
$definition = $this->catalog->get(QuestionnaireCatalog::HOUSE_MANAGER_FEEDBACK);
$dispositions = $this->dispositionRepository->findForHouseManagerQuestionnaire($destination);
$form = $this->createForm(QuestionnaireType::class, [
$definition->key => DestinationContext::initialAnswers($destination),
], [
'definitions' => [$definition],
'travel' => DestinationContext::travel($destination, $dispositions),
]);
$form->handleRequest($request);
$submitted = null;
$draft = false;
if ($form->isSubmitted() && $form->isValid()) {
if (QuestionnaireType::isFinal($form)) {
$submitted = $definition->withoutHiddenAnswers($form->getData()[$definition->key]);
} else {
$draft = true;
}
}
return $this->render('administrative/questionnaire/test_house_manager.html.twig', [
'assignment' => $assignment,
'destination' => $destination,
'dispositions' => $dispositions,
'definition' => $definition,
'context' => DestinationContext::build($destination, $dispositions),
'form' => $form,
'submitted' => $submitted,
'draft' => $draft,
'returnUrl' => $this->getReturnUrl($request, 'app_administrative_assignment_index'),
]);
}
}
@@ -13,9 +13,10 @@ use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Attribute\IsGranted;
/**
* The submitted responses to one questionnaire, teamer or bus feedback. Only administrative users
* read them: they rate the house manager among others, so house managers are deliberately not
* let in.
* The submitted responses to one questionnaire: teamer, bus or house manager feedback. Only
* administrative users read them here: the teamer ones rate the house manager among others, so
* house managers are deliberately not let in. A house manager reads their own travel's
* questionnaire in the HouseManager area.
*/
class IndexController extends AbstractController
{
@@ -2,7 +2,10 @@
namespace App\Controller\HouseManager\Feedback;
use App\Config\QuestionnaireCatalog;
use App\Entity\Destination;
use App\Entity\User;
use App\Repository\DestinationRepository;
use App\Repository\DispositionRepository;
use Knp\Component\Pager\PaginatorInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
@@ -11,12 +14,21 @@ use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Attribute\IsGranted;
/**
* The house manager's ended travels with something still to do, one row per travel: the
* questionnaire about it (from the go-live on), and the ratings of its teamers, each linked.
*/
class IndexController extends AbstractController
{
private readonly \DateTimeImmutable $goLive;
public function __construct(
private readonly DestinationRepository $destinationRepository,
private readonly DispositionRepository $dispositionRepository,
private readonly PaginatorInterface $paginator,
string $houseManagerQuestionnaireGoLive,
) {
$this->goLive = QuestionnaireCatalog::parseGoLive($houseManagerQuestionnaireGoLive);
}
#[Route('/house-manager/pending-feedback', name: 'app_house_manager_feedback_index')]
@@ -26,23 +38,22 @@ class IndexController extends AbstractController
/** @var User $user */
$user = $this->getUser();
$query = $this
->dispositionRepository
->getDispositionsWithPendingFeedbackQuery($user->getHotelCodes())
;
$pagination = $this->paginator->paginate(
$query,
$this->destinationRepository->getPendingForHouseManagerQuery($user->getHotelCodes(), $this->goLive, new \DateTimeImmutable('today'), $user->getTeamer()),
$request->query->getInt('page', 1),
$request->query->getInt('limit', 50),
[
'defaultSortFieldName' => 'destination.dateFrom',
'defaultSortFieldName' => 'destination.dateTo',
'defaultSortDirection' => 'asc',
]
);
$destinations = array_map(static fn (array $row): Destination => $row[0], iterator_to_array($pagination));
return $this->render('house_manager/feedback/index.html.twig', [
'pagination' => $pagination,
'placements' => $this->dispositionRepository->findForHouseManagerByDestinations($destinations),
'goLive' => $this->goLive,
]);
}
}
@@ -2,7 +2,9 @@
namespace App\Controller\HouseManager;
use App\Config\QuestionnaireCatalog;
use App\Entity\User;
use App\Repository\DestinationRepository;
use App\Repository\DispositionRepository;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
@@ -11,8 +13,14 @@ use Symfony\Component\Security\Http\Attribute\IsGranted;
class IndexController extends AbstractController
{
public function __construct(private readonly DispositionRepository $dispositionRepository)
{
private readonly \DateTimeImmutable $goLive;
public function __construct(
private readonly DispositionRepository $dispositionRepository,
private readonly DestinationRepository $destinationRepository,
string $houseManagerQuestionnaireGoLive,
) {
$this->goLive = QuestionnaireCatalog::parseGoLive($houseManagerQuestionnaireGoLive);
}
#[Route('/house-manager', name: 'app_house_manager_index')]
@@ -27,14 +35,16 @@ class IndexController extends AbstractController
->findNewDispositionsByHotelCodes($user->getHotelCodes())
;
$pendingFeedbacks = $this
->dispositionRepository
->findDispositionsWithPendingFeedbackByHotelCodes($user->getHotelCodes())
$pendingTravels = $this
->destinationRepository
->getPendingForHouseManagerQuery($user->getHotelCodes(), $this->goLive, new \DateTimeImmutable('today'), $user->getTeamer())
->getResult()
;
return $this->render('house_manager/index.html.twig', [
'newDispositions' => $newDispositions,
'pendingFeedbacks' => $pendingFeedbacks,
'pendingTravels' => $pendingTravels,
'goLive' => $this->goLive,
]);
}
}
@@ -0,0 +1,49 @@
<?php
namespace App\Controller\HouseManager\Questionnaire;
use App\Config\QuestionnaireCatalog;
use App\Entity\Destination;
use App\Entity\User;
use App\Repository\DispositionRepository;
use App\Repository\QuestionnaireResponseRepository;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Routing\Requirement\Requirement;
use Symfony\Component\Security\Http\Attribute\IsGranted;
/**
* The submitted questionnaire about a travel, read-only, for the house's managers; below it the
* travel's teamers and their ratings, as on the form. Until it is submitted, the form is shown.
*/
class DetailController extends AbstractController
{
public function __construct(
private readonly QuestionnaireCatalog $catalog,
private readonly QuestionnaireResponseRepository $responseRepository,
private readonly DispositionRepository $dispositionRepository,
) {
}
#[Route('/house-manager/questionnaire/{id}/answers', name: 'app_house_manager_questionnaire_detail', requirements: ['id' => Requirement::DIGITS])]
#[IsGranted('QUESTIONNAIRE', subject: 'destination')]
public function index(Destination $destination): Response
{
$response = $this->responseRepository->findForDestination($destination);
if (true !== $response?->isSubmitted()) {
return $this->redirectToRoute('app_house_manager_questionnaire_edit', ['id' => $destination->getId()]);
}
/** @var User $user */
$user = $this->getUser();
return $this->render('house_manager/questionnaire/detail.html.twig', [
'destination' => $destination,
'dispositions' => $this->dispositionRepository->findForHouseManagerQuestionnaire($destination, $user->getTeamer()),
'definition' => $this->catalog->get($response->getQuestionnaire(), $response->getVersion()),
'response' => $response,
]);
}
}
@@ -0,0 +1,104 @@
<?php
namespace App\Controller\HouseManager\Questionnaire;
use App\Config\QuestionnaireCatalog;
use App\Entity\Destination;
use App\Entity\QuestionnaireResponse;
use App\Entity\User;
use App\Form\QuestionnaireType;
use App\Repository\DispositionRepository;
use App\Repository\QuestionnaireResponseRepository;
use App\Service\Questionnaire\DestinationContext;
use Doctrine\ORM\EntityManagerInterface;
use Psr\Log\LoggerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Routing\Requirement\Requirement;
use Symfony\Component\Security\Http\Attribute\IsGranted;
/**
* The house manager's questionnaire about a travel, one per travel whoever of the house's managers
* fills it in. Saved as a draft until submitted; submitted answers are final and only shown
* read-only (DetailController). Below the form, the travel's teamers link to the existing rating
* form ("Bewerte dein Wochenteam"), independent of the questionnaire.
*/
class EditController extends AbstractController
{
public function __construct(
private readonly QuestionnaireCatalog $catalog,
private readonly QuestionnaireResponseRepository $responseRepository,
private readonly DispositionRepository $dispositionRepository,
private readonly EntityManagerInterface $entityManager,
private readonly LoggerInterface $logger,
) {
}
#[Route('/house-manager/questionnaire/{id}', name: 'app_house_manager_questionnaire_edit', requirements: ['id' => Requirement::DIGITS])]
#[IsGranted('QUESTIONNAIRE', subject: 'destination')]
public function index(Destination $destination, Request $request): Response
{
$response = $this->responseRepository->findForDestination($destination);
if (true === $response?->isSubmitted()) {
return $this->redirectToRoute('app_house_manager_questionnaire_detail', ['id' => $destination->getId()]);
}
/** @var User $user */
$user = $this->getUser();
$definition = $this->catalog->get(QuestionnaireCatalog::HOUSE_MANAGER_FEEDBACK);
$dispositions = $this->dispositionRepository->findForHouseManagerQuestionnaire($destination, $user->getTeamer());
$form = $this->createForm(QuestionnaireType::class, [
$definition->key => $response?->getAnswers() ?? DestinationContext::initialAnswers($destination),
], [
'definitions' => [$definition],
'travel' => DestinationContext::travel($destination, $dispositions),
]);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$answers = $form->getData()[$definition->key];
$context = DestinationContext::build($destination, $dispositions);
$final = QuestionnaireType::isFinal($form);
if (null === $response) {
$response = QuestionnaireResponse::forDestination($definition, $destination);
$this->entityManager->persist($response);
}
if (true === $final) {
$response->submit($definition, $answers, $context, new \DateTimeImmutable());
} else {
$response->saveDraft($answers, $context);
}
$this->entityManager->flush();
$this->logger->info($final ? 'Submit house manager questionnaire' : 'Save house manager questionnaire draft', [
'questionnaire' => $response->getQuestionnaire(),
'questionnaire_response_id' => $response->getId(),
'destination_id' => $destination->getId(),
]);
if (true === $final) {
$this->addFlash('success', 'Danke! Dein Fragebogen wurde abgeschickt.');
return $this->redirectToRoute('app_house_manager_questionnaire_detail', ['id' => $destination->getId()]);
}
$this->addFlash('success', 'Dein Entwurf wurde gespeichert.');
return $this->redirectToRoute('app_house_manager_questionnaire_edit', ['id' => $destination->getId()]);
}
return $this->render('house_manager/questionnaire/edit.html.twig', [
'destination' => $destination,
'dispositions' => $dispositions,
'form' => $form,
'lastSaved' => null === $response ? null : $response->getUpdatedAt() ?? $response->getCreatedAt(),
]);
}
}
+27 -3
View File
@@ -23,14 +23,17 @@ use Symfony\Component\Uid\Uuid;
* 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.
* Its subject is a Disposition (the teamer's questionnaires) or a Destination (the house manager's,
* one per travel), each a nullable foreign key of its own rather than a generic subject column.
* Exactly one is set. Each unique key leaves out the rows of the other subject: MariaDB lets the
* NULLs repeat.
*
* Not soft-deletable: nothing in the UI deletes a response, and it goes with its disposition.
* Not soft-deletable: nothing in the UI deletes a response, and it goes with its subject.
*/
#[ORM\Entity(repositoryClass: QuestionnaireResponseRepository::class)]
#[ORM\HasLifecycleCallbacks]
#[ORM\UniqueConstraint(name: 'questionnaire_disposition_leg', columns: ['questionnaire', 'disposition_id', 'leg'])]
#[ORM\UniqueConstraint(name: 'questionnaire_destination', columns: ['questionnaire', 'destination_id'])]
class QuestionnaireResponse implements BlameableEntityInterface, TimestampableEntityInterface
{
use BlameableEntity;
@@ -72,6 +75,10 @@ class QuestionnaireResponse implements BlameableEntityInterface, TimestampableEn
#[ORM\JoinColumn(onDelete: 'CASCADE')]
private ?Disposition $disposition = null;
#[ORM\ManyToOne]
#[ORM\JoinColumn(onDelete: 'CASCADE')]
private ?Destination $destination = 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.
@@ -102,6 +109,18 @@ class QuestionnaireResponse implements BlameableEntityInterface, TimestampableEn
return $instance;
}
public static function forDestination(Definition $definition, Destination $destination): static
{
if ($definition->perBusLeg) {
throw new \LogicException(sprintf('Questionnaire "%s" needs a bus leg, a travel has none', $definition->key));
}
$instance = new static($definition);
$instance->destination = $destination;
return $instance;
}
/**
* Keeps every answer, including those to questions that are hidden right now: switching an
* answer back restores the follow-up already written.
@@ -199,6 +218,11 @@ class QuestionnaireResponse implements BlameableEntityInterface, TimestampableEn
return $this->disposition;
}
public function getDestination(): ?Destination
{
return $this->destination;
}
public function getLeg(): ?BusLeg
{
return BusLeg::tryFrom($this->leg);
+14 -1
View File
@@ -5,6 +5,11 @@ namespace App\Enum;
/**
* The kinds of question a questionnaire definition may use. Each maps to exactly one form field
* in QuestionnaireType; adding one means a case here and a line there, nothing more.
*
* TEAMER_GUIDINGS, TEAMER_COURSES and PROGRAMME are the house manager's bespoke widgets: their
* options are the guiding types, course types and programme items, and each picked option carries
* numbers of its own. The two teamer types offer the travel's placements, so they need the form's
* `travel` option.
*/
enum QuestionType: string
{
@@ -14,9 +19,17 @@ enum QuestionType: string
case MULTI = 'multi';
case DATE = 'date';
case RATING = 'rating';
case TEAMER_GUIDINGS = 'teamer_guidings';
case TEAMER_COURSES = 'teamer_courses';
case PROGRAMME = 'programme';
public function hasOptions(): bool
{
return self::CHOICE === $this || self::MULTI === $this;
return self::TEXT !== $this && self::TEXTAREA !== $this && self::DATE !== $this && self::RATING !== $this;
}
public function needsTravel(): bool
{
return self::TEAMER_GUIDINGS === $this || self::TEAMER_COURSES === $this;
}
}
+101
View File
@@ -0,0 +1,101 @@
<?php
namespace App\Form\Questionnaire;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\Extension\Core\Type\FormType;
use Symfony\Component\Form\Extension\Core\Type\IntegerType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormError;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
/**
* The house manager's bespoke questionnaire widgets (TeamerGuidingsType, TeamerCoursesType,
* ProgrammeType) are built from "picks": a checkbox, and below it the fields that only matter once
* it is ticked. The questionnaire_pick_row block renders them, and the CSS rule for
* .questionnaire-pick hides the fields while the box is unticked - no JavaScript. Unticked fields
* are still submitted; reverseTransform() drops them.
*
* Each type's model data is its stored answer, a plain array; the form data is the same with a
* PICKED flag per pick. Required checks run on submit only (QuestionnaireType asks addMissing()),
* so a draft takes any half-filled state.
*/
abstract class AbstractPickType extends AbstractType
{
public const string PICKED = 'picked';
protected const string MISSING = 'Bitte beantworte diese Frage.';
/**
* Adds the errors that stand in the way of submitting this answer. The field's data is the
* stored answer; errors go on the field or its children, where the template shows them.
*/
abstract public static function addMissing(FormInterface $field): void;
public function configureOptions(OptionsResolver $resolver): void
{
$resolver->setDefaults([
'compound' => true,
'required' => false,
'error_bubbling' => false,
'empty_data' => [],
]);
}
/**
* @param \Closure(FormBuilderInterface): void $addFields the fields shown once it is ticked
*/
protected function addPick(FormBuilderInterface $parent, string $name, string $label, \Closure $addFields, string $blockPrefix = 'questionnaire_pick'): void
{
$pick = $parent->create($name, FormType::class, [
'label' => false,
'required' => false,
'error_bubbling' => false,
'block_prefix' => $blockPrefix,
]);
$pick->add(self::PICKED, CheckboxType::class, [
'label' => $label,
'required' => false,
]);
$addFields($pick);
$parent->add($pick);
}
protected function addCount(FormBuilderInterface $pick, string $name, string $label): void
{
$pick->add($name, IntegerType::class, [
'label' => $label,
'required' => false,
'invalid_message' => 'Bitte gib eine ganze Zahl ein.',
'attr' => ['min' => 1],
]);
}
protected static function isPicked(mixed $data): bool
{
return is_array($data) && true === ($data[self::PICKED] ?? false);
}
/**
* Requires each named child of a ticked pick to hold a number above zero.
*
* @param list<string> $names
*/
protected static function requirePositive(FormInterface $pick, array $names): void
{
foreach ($names as $name) {
$value = $pick->get($name)->getData();
if (null === $value) {
$pick->get($name)->addError(new FormError(self::MISSING));
} elseif ($value <= 0) {
$pick->get($name)->addError(new FormError('Bitte gib eine Zahl größer als 0 ein.'));
}
}
}
}
@@ -0,0 +1,120 @@
<?php
namespace App\Form\Questionnaire;
use App\Model\Questionnaire\Option;
use Symfony\Component\Form\FormError;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
/**
* A pick per teamer of the travel (option `teamers`, disposition uuid => label), and inside each a
* pick per type the question offers (option `question_options`).
*
* Stored as a flat list, one row per teamer and type, so that a report unnests it with a single
* JSON_TABLE(answers, '$.<question>[*]' ...) and groups by any of its fields:
* [{disposition: <uuid>, type: <option key>, <field>: value, ...}, ...]. A teamer ticked without a
* type yet is a row without `type`; only a draft can hold one, since submitting demands a type.
*/
abstract class AbstractTeamerPickType extends AbstractPickType
{
public const string DISPOSITION = 'disposition';
public const string TYPE = 'type';
public function configureOptions(OptionsResolver $resolver): void
{
parent::configureOptions($resolver);
$resolver
->setRequired(['teamers', 'question_options'])
->setAllowedTypes('teamers', 'string[]')
->setAllowedTypes('question_options', Option::class.'[]')
;
}
/**
* Every ticked teamer needs a ticked type, and every ticked type its fields.
*
* @param \Closure(FormInterface): void $checkType
*/
protected static function addMissingPerTeamer(FormInterface $field, \Closure $checkType, string $noTypeMessage): void
{
foreach ($field as $teamer) {
if (true !== $teamer->get(self::PICKED)->getData()) {
continue;
}
$picked = 0;
foreach ($teamer as $name => $type) {
if (self::PICKED === $name || true !== $type->get(self::PICKED)->getData()) {
continue;
}
++$picked;
$checkType($type);
}
if (0 === $picked) {
$teamer->addError(new FormError($noTypeMessage));
}
}
}
/**
* @param list<array<string, mixed>> $stored one row per teamer and type, see the class docblock
* @param list<string> $fields
*
* @return array<string, mixed>
*/
protected static function toForm(array $stored, array $fields): array
{
$data = [];
foreach ($stored as $row) {
$uuid = (string) ($row[self::DISPOSITION] ?? '');
$data[$uuid][self::PICKED] = true;
if (null !== $type = $row[self::TYPE] ?? null) {
$data[$uuid][$type] = [self::PICKED => true] + array_intersect_key($row, array_flip($fields));
}
}
return $data;
}
/**
* @param array<string, mixed> $data
* @param list<string> $fields
*
* @return list<array<string, mixed>>
*/
protected static function toStored(array $data, array $fields): array
{
$stored = [];
foreach ($data as $uuid => $teamer) {
if (!self::isPicked($teamer)) {
continue;
}
$types = array_filter(
$teamer,
static fn (mixed $type, string $key): bool => self::PICKED !== $key && self::isPicked($type),
ARRAY_FILTER_USE_BOTH,
);
if ([] === $types) {
// ticked without a type yet: kept so a draft remembers the tick
$stored[] = [self::DISPOSITION => (string) $uuid];
}
foreach ($types as $key => $type) {
$values = array_intersect_key($type, array_flip($fields));
$stored[] = [self::DISPOSITION => (string) $uuid, self::TYPE => $key] + array_replace(array_fill_keys($fields, null), $values);
}
}
return $stored;
}
}
+108
View File
@@ -0,0 +1,108 @@
<?php
namespace App\Form\Questionnaire;
use App\Form\AutosizeTextareaType;
use App\Model\Questionnaire\Option;
use Symfony\Component\Form\CallbackTransformer;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormError;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
/**
* "Welches Programm hat stattgefunden?": the programme items (the question's options), each with
* its number of participants once ticked, and "Sonstiges" with a free text.
*
* Stored as {items: [{item: <option key>, participants}, ...], other: text}, either part only when
* ticked, an empty array when nothing is. The items are a flat list like the teamer questions', so a
* report unnests them with one JSON_TABLE(answers, '$.programme.items[*]' ...).
*/
class ProgrammeType extends AbstractPickType
{
public const string ITEMS = 'items';
public const string ITEM = 'item';
public const string OTHER = 'other';
public const string PARTICIPANTS = 'participants';
public const string TEXT = 'text';
public function buildForm(FormBuilderInterface $builder, array $options): void
{
/** @var list<Option> $items */
$items = $options['question_options'];
foreach ($items as $item) {
$this->addPick($builder, $item->key, $item->label, function (FormBuilderInterface $pick): void {
$this->addCount($pick, self::PARTICIPANTS, 'Teilnehmende');
}, 'questionnaire_pick_inline');
}
$this->addPick($builder, self::OTHER, 'Sonstiges', function (FormBuilderInterface $pick): void {
$pick->add(self::TEXT, AutosizeTextareaType::class, [
'label' => 'Was hat noch stattgefunden?',
'required' => false,
'min_rows' => 2,
]);
});
$builder->addModelTransformer(new CallbackTransformer(
static function (?array $stored): array {
$data = [];
foreach ($stored[self::ITEMS] ?? [] as $row) {
$data[(string) $row[self::ITEM]] = [self::PICKED => true, self::PARTICIPANTS => $row[self::PARTICIPANTS] ?? null];
}
if (array_key_exists(self::OTHER, $stored ?? [])) {
$data[self::OTHER] = [self::PICKED => true, self::TEXT => $stored[self::OTHER]];
}
return $data;
},
static function (?array $data): array {
$stored = [];
foreach ($data ?? [] as $key => $pick) {
if (!self::isPicked($pick)) {
continue;
}
if (self::OTHER === $key) {
$stored[self::OTHER] = $pick[self::TEXT] ?? null;
} else {
$stored[self::ITEMS][] = [self::ITEM => $key, self::PARTICIPANTS => $pick[self::PARTICIPANTS] ?? null];
}
}
return $stored;
},
));
}
public function configureOptions(OptionsResolver $resolver): void
{
parent::configureOptions($resolver);
$resolver
->setRequired('question_options')
->setAllowedTypes('question_options', Option::class.'[]')
// "other" is the Sonstiges pick
->setAllowedValues('question_options', static fn (array $items): bool => [] === array_filter($items, static fn (Option $item): bool => self::OTHER === $item->key))
;
}
public static function addMissing(FormInterface $field): void
{
foreach ($field as $name => $pick) {
if (true !== $pick->get(self::PICKED)->getData()) {
continue;
}
if (self::OTHER !== $name) {
self::requirePositive($pick, [self::PARTICIPANTS]);
} elseif ('' === trim((string) $pick->get(self::TEXT)->getData())) {
$pick->get(self::TEXT)->addError(new FormError(self::MISSING));
}
}
}
}
@@ -0,0 +1,89 @@
<?php
namespace App\Form\Questionnaire;
use App\Model\Questionnaire\Option;
use Symfony\Component\Form\CallbackTransformer;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\NumberType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormError;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
/**
* "Wer hat welche Kurse gegeben?": the travel's teamers to tick, per ticked teamer the course types
* (the question's options), and per ticked course type days × hours per day and the days it took
* place. The days to pick are the travel's own dates rather than Sunday to Saturday: a travel runs
* Saturday to Saturday, so a weekday alone would not say which Saturday.
*
* Stored as [{disposition, type, days, hours_per_day, dates: [Y-m-d, ...]}, ...]
* (AbstractTeamerPickType). The number of days is not checked against the dates picked.
*/
class TeamerCoursesType extends AbstractTeamerPickType
{
public const string DAYS = 'days';
public const string HOURS_PER_DAY = 'hours_per_day';
public const string DATES = 'dates';
public function buildForm(FormBuilderInterface $builder, array $options): void
{
/** @var list<Option> $courseTypes */
$courseTypes = $options['question_options'];
$dates = array_map(static fn (\DateTimeImmutable $day): string => $day->format('Y-m-d'), $options['days']);
// "So. 28.03.", as _answers.html.twig shows them
$dayLabel = new \IntlDateFormatter('de', \IntlDateFormatter::NONE, \IntlDateFormatter::NONE, null, null, 'EEEEEE dd.MM.');
foreach ($options['teamers'] as $uuid => $label) {
$this->addPick($builder, $uuid, $label, function (FormBuilderInterface $teamer) use ($courseTypes, $dates, $dayLabel): void {
foreach ($courseTypes as $courseType) {
$this->addPick($teamer, $courseType->key, $courseType->label, function (FormBuilderInterface $pick) use ($dates, $dayLabel): void {
$this->addCount($pick, self::DAYS, 'Tage');
$pick->add(self::HOURS_PER_DAY, NumberType::class, [
'label' => 'Stunden pro Tag',
'required' => false,
'scale' => 2,
'invalid_message' => 'Bitte gib eine Zahl ein.',
'attr' => ['inputmode' => 'decimal'],
]);
$pick->add(self::DATES, ChoiceType::class, [
'label' => 'Wann hat der Kurs stattgefunden?',
'required' => false,
'multiple' => true,
'expanded' => true,
'choices' => $dates,
'choice_label' => static fn (string $date): string => (string) $dayLabel->format(new \DateTimeImmutable($date)),
'block_prefix' => 'questionnaire_days',
]);
}, 'questionnaire_pick_course');
}
});
}
$builder->addModelTransformer(new CallbackTransformer(
static fn (?array $stored): array => self::toForm($stored ?? [], [self::DAYS, self::HOURS_PER_DAY, self::DATES]),
static fn (?array $data): array => self::toStored($data ?? [], [self::DAYS, self::HOURS_PER_DAY, self::DATES]),
));
}
public function configureOptions(OptionsResolver $resolver): void
{
parent::configureOptions($resolver);
$resolver
->setRequired('days')
->setAllowedTypes('days', \DateTimeImmutable::class.'[]')
;
}
public static function addMissing(FormInterface $field): void
{
self::addMissingPerTeamer($field, static function (FormInterface $pick): void {
self::requirePositive($pick, [self::DAYS, self::HOURS_PER_DAY]);
if ([] === ($pick->get(self::DATES)->getData() ?? [])) {
$pick->get(self::DATES)->addError(new FormError('Bitte wähle mindestens einen Tag aus.'));
}
}, 'Bitte wähle mindestens eine Kursart aus.');
}
}
@@ -0,0 +1,47 @@
<?php
namespace App\Form\Questionnaire;
use App\Model\Questionnaire\Option;
use Symfony\Component\Form\CallbackTransformer;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormInterface;
/**
* "Wer hat das Guiding gegeben?": the travel's teamers to tick, and per ticked teamer the guiding
* types (the question's options) with the number of guidings and the participants per guiding.
*
* Stored as [{disposition, type, count, participants}, ...] (AbstractTeamerPickType).
*/
class TeamerGuidingsType extends AbstractTeamerPickType
{
public const string COUNT = 'count';
public const string PARTICIPANTS = 'participants';
public function buildForm(FormBuilderInterface $builder, array $options): void
{
/** @var list<Option> $guidingTypes */
$guidingTypes = $options['question_options'];
foreach ($options['teamers'] as $uuid => $label) {
$this->addPick($builder, $uuid, $label, function (FormBuilderInterface $teamer) use ($guidingTypes): void {
foreach ($guidingTypes as $guidingType) {
$this->addPick($teamer, $guidingType->key, $guidingType->label, function (FormBuilderInterface $pick): void {
$this->addCount($pick, self::COUNT, 'Guidings');
$this->addCount($pick, self::PARTICIPANTS, 'Teilnehmende je Guiding');
}, 'questionnaire_pick_inline');
}
});
}
$builder->addModelTransformer(new CallbackTransformer(
static fn (?array $stored): array => self::toForm($stored ?? [], [self::COUNT, self::PARTICIPANTS]),
static fn (?array $data): array => self::toStored($data ?? [], [self::COUNT, self::PARTICIPANTS]),
));
}
public static function addMissing(FormInterface $field): void
{
self::addMissingPerTeamer($field, static fn (FormInterface $pick) => self::requirePositive($pick, [self::COUNT, self::PARTICIPANTS]), 'Bitte wähle mindestens ein Guiding aus.');
}
}
+72 -16
View File
@@ -5,9 +5,14 @@ namespace App\Form;
use App\Enum\BusLeg;
use App\Enum\ChoiceWidget;
use App\Enum\QuestionType;
use App\Form\Questionnaire\AbstractPickType;
use App\Form\Questionnaire\ProgrammeType;
use App\Form\Questionnaire\TeamerCoursesType;
use App\Form\Questionnaire\TeamerGuidingsType;
use App\Model\Questionnaire\Definition;
use App\Model\Questionnaire\Option;
use App\Model\Questionnaire\Question;
use App\Model\Questionnaire\Travel;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\ClickableInterface;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
@@ -33,8 +38,11 @@ use Symfony\Component\OptionsResolver\OptionsResolver;
* {legs: 'outbound'|'return'|'both'|null, outbound: {...}, return: {...}}. answerSets() turns the
* data into one answer set per questionnaire and chosen leg, the responses to store.
*
* The house manager's questionnaire asks about the travel's teamers; the `travel` option offers
* them (and the travel's days), and a definition using such a question cannot be built without it.
*
* 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
* that is shown, and of a bespoke widget (App\Form\Questionnaire) its own fields. 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
* questionnaire Stimulus controller applies on screen via the row's data-show-if.
*/
@@ -47,10 +55,19 @@ class QuestionnaireType extends AbstractType
private const int RATING_MAX = 5;
/**
* A radio question whose options are all this short - "Ja"/"Nein" and the like - is answered
* with a row of buttons beside the question instead of one full-width row per option.
*/
private const int INLINE_OPTIONS_MAX = 4;
private const int INLINE_LABEL_MAX = 20;
public function buildForm(FormBuilderInterface $builder, array $options): void
{
/** @var list<Definition> $definitions */
$definitions = $options['definitions'];
/** @var Travel|null $travel */
$travel = $options['travel'];
foreach ($definitions as $definition) {
$questionnaireBuilder = $builder->create($definition->key, FormType::class, [
@@ -62,9 +79,9 @@ class QuestionnaireType extends AbstractType
]);
if ($definition->perBusLeg) {
$this->addLegs($builder, $questionnaireBuilder, $definition);
$this->addLegs($builder, $questionnaireBuilder, $definition, $travel);
} else {
$this->addSections($builder, $questionnaireBuilder, $definition, $definition->key);
$this->addSections($builder, $questionnaireBuilder, $definition, $definition->key, $travel);
}
$builder->add($questionnaireBuilder);
@@ -101,13 +118,20 @@ class QuestionnaireType extends AbstractType
foreach ($definition->sections as $section) {
foreach ($section->questions as $question) {
if ($question->required
&& $definition->isVisible($question, $answers)
&& $this->isEmpty($answers[$question->key] ?? null)
) {
$parent->get($section->key)->get($question->key)->addError(
new FormError('Bitte beantworte diese Frage.')
);
if (!$definition->isVisible($question, $answers)) {
continue;
}
$field = $parent->get($section->key)->get($question->key);
if ($question->required && $this->isEmpty($answers[$question->key] ?? null)) {
$field->addError(new FormError('Bitte beantworte diese Frage.'));
}
$widget = $field->getConfig()->getType()->getInnerType();
if ($widget instanceof AbstractPickType) {
$widget::addMissing($field);
}
}
}
@@ -126,7 +150,9 @@ class QuestionnaireType extends AbstractType
->setDefaults([
'data_class' => null,
'empty_data' => [],
'travel' => null,
])
->setAllowedTypes('travel', ['null', Travel::class])
;
}
@@ -202,7 +228,7 @@ class QuestionnaireType extends AbstractType
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
private function addLegs(FormBuilderInterface $builder, FormBuilderInterface $questionnaireBuilder, Definition $definition, ?Travel $travel): void
{
$questionnaireBuilder->add(self::LEGS, ChoiceType::class, [
'label' => 'Welche Fahrten hast du begleitet?',
@@ -232,7 +258,7 @@ class QuestionnaireType extends AbstractType
],
]);
$this->addSections($builder, $legBuilder, $definition, $definition->key.'.'.$leg->value);
$this->addSections($builder, $legBuilder, $definition, $definition->key.'.'.$leg->value, $travel);
$questionnaireBuilder->add($legBuilder);
}
}
@@ -240,7 +266,7 @@ class QuestionnaireType extends AbstractType
/**
* @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
private function addSections(FormBuilderInterface $builder, FormBuilderInterface $parent, Definition $definition, string $prefix, ?Travel $travel): void
{
foreach ($definition->sections as $section) {
$sectionBuilder = $builder->create($section->key, FormType::class, [
@@ -251,7 +277,7 @@ class QuestionnaireType extends AbstractType
]);
foreach ($section->questions as $question) {
$sectionBuilder->add($question->key, ...$this->field($prefix, $question));
$sectionBuilder->add($question->key, ...$this->field($prefix, $question, $travel));
}
$parent->add($sectionBuilder);
@@ -261,7 +287,7 @@ class QuestionnaireType extends AbstractType
/**
* @return array{0: class-string, 1: array<string, mixed>}
*/
private function field(string $prefix, Question $question): array
private function field(string $prefix, Question $question, ?Travel $travel): array
{
$common = [
'label' => $question->label,
@@ -275,6 +301,8 @@ class QuestionnaireType extends AbstractType
'operator' => $question->showIf->operator->value,
'value' => $question->showIf->value,
], JSON_THROW_ON_ERROR),
// a follow-up is indented under the question that opened it
'class' => '-mt-2 border-l-2 border-gray-200 pl-4',
]),
];
@@ -285,7 +313,7 @@ class QuestionnaireType extends AbstractType
'expanded' => true,
// a radio list needs no "none" entry
'placeholder' => false,
'block_prefix' => 'questionnaire_choice',
'block_prefix' => $this->hasShortOptions($question) ? 'questionnaire_inline_choice' : 'questionnaire_choice',
] : [
'expanded' => false,
// a select needs an empty first line, or the first option would be preselected
@@ -306,6 +334,13 @@ class QuestionnaireType extends AbstractType
'placeholder' => false,
'block_prefix' => 'questionnaire_rating',
]],
QuestionType::TEAMER_GUIDINGS => [TeamerGuidingsType::class, $common + $this->travelOptions($question, $travel)],
QuestionType::TEAMER_COURSES => [TeamerCoursesType::class, $common + $this->travelOptions($question, $travel) + [
'days' => $travel->days,
]],
QuestionType::PROGRAMME => [ProgrammeType::class, $common + [
'question_options' => $question->options,
]],
};
}
@@ -323,6 +358,27 @@ class QuestionnaireType extends AbstractType
];
}
/**
* @return array{teamers: array<string, string>, question_options: list<Option>}
*/
private function travelOptions(Question $question, ?Travel $travel): array
{
if (null === $travel) {
throw new \LogicException(sprintf('Question "%s" needs the travel option', $question->key));
}
return [
'teamers' => $travel->teamers,
'question_options' => $question->options,
];
}
private function hasShortOptions(Question $question): bool
{
return count($question->options) <= self::INLINE_OPTIONS_MAX
&& [] === array_filter($question->options, static fn (Option $option): bool => mb_strlen($option->label) > self::INLINE_LABEL_MAX);
}
private function isEmpty(mixed $answer): bool
{
return null === $answer || '' === $answer || [] === $answer;
+1
View File
@@ -28,6 +28,7 @@ class HouseManagerMenuBuilder extends AbstractMenuBuilder
'icon' => 'feedback',
'routes' => [
['pattern' => '/^app_house_manager_feedback_/'],
['pattern' => '/^app_house_manager_questionnaire_/'],
],
],
]);
+34
View File
@@ -0,0 +1,34 @@
<?php
namespace App\Model\Questionnaire;
/**
* What the house manager's teamer questions offer to pick from: the travel's teamers and its days.
* Passed to QuestionnaireType as its `travel` option; built by DestinationContext::travel().
*/
readonly class Travel
{
/**
* @param array<string, string> $teamers disposition uuid => label, in the order to show them
* @param list<\DateTimeImmutable> $days every day of the travel, first to last
*/
public function __construct(
public array $teamers,
public array $days,
) {
}
/**
* @return list<\DateTimeImmutable>
*/
public static function daysBetween(\DateTimeImmutable $from, \DateTimeImmutable $to): array
{
$days = [];
for ($day = $from->setTime(0, 0); $day <= $to; $day = $day->modify('+1 day')) {
$days[] = $day;
}
return $days;
}
}
+120
View File
@@ -2,10 +2,17 @@
namespace App\Repository;
use App\Config\QuestionnaireCatalog;
use App\Entity\Assignment;
use App\Entity\Destination;
use App\Entity\Disposition;
use App\Entity\QuestionnaireResponse;
use App\Entity\Teamer;
use App\Enum\QuestionnaireResponseStatus;
use App\Model\DestinationFilterDto;
use App\Repository\Traits\QueryHelperTrait;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\Query;
use Doctrine\Persistence\ManagerRegistry;
@@ -161,4 +168,117 @@ class DestinationRepository extends ServiceEntityRepository
->getResult()
;
}
/**
* The ended travels a house manager still owes something for, one row per travel: the
* questionnaire is not submitted (only for travels ended on or after $goLive), or a placement
* still has no rating and is not waived. The two are independent - the questionnaire can be
* submitted while ratings are missing.
*
* A travel counts only with at least one placement a house manager rates
* (DispositionRepository::findForHouseManagerQuestionnaire() spells the same rule): a travel
* nobody worked on has nothing to report.
*
* Rows are [0 => Destination, 'questionnaireStatus' => ?string (QuestionnaireResponseStatus
* value, null without a response), 'placements' => int, 'openFeedbacks' => int].
*
* @param list<string>|null $hotelCodes the house manager's (User::$hotelCodes), matched on
* either end of the travel's code as everywhere else;
* null for every house
* @param Teamer|null $houseManager the house manager's own teamer, whose placement they
* do not rate
*/
public function getPendingForHouseManagerQuery(?array $hotelCodes, \DateTimeImmutable $goLive, \DateTimeImmutable $endedBy, ?Teamer $houseManager = null): Query
{
$qb = $this->createQueryBuilder('destination');
$em = $this->getEntityManager();
// a placement of this travel that a house manager rates; $alias keeps the subqueries apart
$placements = static function (string $alias, string $select, bool $unrated = false) use ($em, $houseManager): string {
$sub = $em->createQueryBuilder()
->select(sprintf($select, $alias))
->from(Disposition::class, $alias)
->innerJoin($alias.'.assignment', $alias.'_assignment')
->where($alias.'_assignment.destination = destination')
->andWhere($alias.'.status <> :dispositionCalledOff')
->andWhere($alias.'_assignment.status NOT IN (:assignmentStatuses)')
->andWhere($alias.'_assignment.skipFormalities = :skipFormalities')
;
if (null !== $houseManager) {
$sub->andWhere($alias.'.teamer <> :houseManager');
}
if ($unrated) {
$sub
->andWhere($alias.'.feedback IS NULL')
->andWhere($alias.'.feedbackWaived = :feedbackWaived')
;
}
return $sub->getDQL();
};
// this travel's house manager questionnaire
$response = static function (string $alias, string $select, bool $submitted = false) use ($em): string {
$sub = $em->createQueryBuilder()
->select(sprintf($select, $alias))
->from(QuestionnaireResponse::class, $alias)
->where($alias.'.destination = destination')
->andWhere($alias.'.questionnaire = :questionnaire')
;
if ($submitted) {
$sub->andWhere($alias.'.status = :submitted');
}
return $sub->getDQL();
};
$qb
->select(
'destination',
'('.$response('status_response', '%s.status').') AS questionnaireStatus',
'('.$placements('counted', 'COUNT(%s.id)').') AS placements',
'('.$placements('unrated_count', 'COUNT(%s.id)', true).') AS openFeedbacks',
)
->where($qb->expr()->andX(
$qb->expr()->isNull('destination.deletedAt'),
$qb->expr()->lte('destination.dateTo', ':endedBy'),
$qb->expr()->exists($placements('staffed', '%s.id')),
$qb->expr()->orX(
$qb->expr()->andX(
$qb->expr()->gte('destination.dateTo', ':goLive'),
$qb->expr()->not($qb->expr()->exists($response('submitted_response', '%s.id', true)))
),
$qb->expr()->exists($placements('unrated', '%s.id', true))
)
))
->orderBy('destination.dateTo', \SortDirection::Ascending)
->setParameter('endedBy', $endedBy, Types::DATE_IMMUTABLE)
->setParameter('goLive', $goLive, Types::DATE_IMMUTABLE)
->setParameter('questionnaire', QuestionnaireCatalog::HOUSE_MANAGER_FEEDBACK)
->setParameter('submitted', QuestionnaireResponseStatus::SUBMITTED)
->setParameter('dispositionCalledOff', Disposition::STATUS_CALLED_OFF)
->setParameter('assignmentStatuses', [Assignment::STATUS_CALLED_OFF, Assignment::STATUS_DELETED])
->setParameter('skipFormalities', false)
->setParameter('feedbackWaived', false)
;
if (null !== $houseManager) {
$qb->setParameter('houseManager', $houseManager);
}
if (null !== $hotelCodes) {
$qb
->andWhere($qb->expr()->orX(
$qb->expr()->in($qb->expr()->substring('destination.hotelCode', 1, 3), ':hotelCodes'),
$qb->expr()->in($qb->expr()->substring('destination.hotelCode', -3, 3), ':hotelCodes'),
))
->setParameter('hotelCodes', $hotelCodes)
;
}
return $qb->getQuery();
}
}
+75
View File
@@ -4,6 +4,7 @@ namespace App\Repository;
use App\Config\QuestionnaireCatalog;
use App\Entity\Assignment;
use App\Entity\Destination;
use App\Entity\Disposition;
use App\Entity\QuestionnaireResponse;
use App\Entity\Teamer;
@@ -393,6 +394,80 @@ class DispositionRepository extends ServiceEntityRepository
return $qb->getQuery();
}
/**
* The travel's teamers as the house manager's questionnaire lists them: every placement on it
* that is not called off, on an assignment that is neither called off nor deleted nor
* skip-formalities - the placements a house manager rates. The house manager's own placement,
* if they hold one, is left out: nobody rates themselves.
*
* DestinationRepository::getPendingForHouseManagerQuery() spells the same rule in DQL.
*
* @return list<Disposition> by job profile, then teamer; teamer, job profile and feedback loaded
*/
public function findForHouseManagerQuestionnaire(Destination $destination, ?Teamer $houseManager = null): array
{
$qb = $this->createHouseManagerPlacementsQueryBuilder([$destination]);
if (null !== $houseManager) {
$qb
->andWhere($qb->expr()->neq('disposition.teamer', ':houseManager'))
->setParameter('houseManager', $houseManager)
;
}
return $qb->getQuery()->getResult();
}
/**
* The same placements for several travels at once, for the house manager's pending list.
*
* @param list<Destination> $destinations
*
* @return array<int, list<Disposition>> keyed by destination id
*/
public function findForHouseManagerByDestinations(array $destinations): array
{
if ([] === $destinations) {
return [];
}
$placements = [];
foreach ($this->createHouseManagerPlacementsQueryBuilder($destinations)->getQuery()->getResult() as $disposition) {
$placements[$disposition->getAssignment()->getDestination()->getId()][] = $disposition;
}
return $placements;
}
/**
* @param list<Destination> $destinations
*/
private function createHouseManagerPlacementsQueryBuilder(array $destinations): QueryBuilder
{
$qb = $this->createQueryBuilder('disposition');
return $qb
->select('disposition', 'assignment', 'job_profile', 'teamer', 'feedback')
->innerJoin('disposition.assignment', 'assignment')
->innerJoin('assignment.jobProfile', 'job_profile')
->innerJoin('disposition.teamer', 'teamer')
->leftJoin('disposition.feedback', 'feedback')
->where($qb->expr()->andX(
$qb->expr()->in('assignment.destination', ':destinations'),
$qb->expr()->neq('disposition.status', ':dispositionCalledOff'),
$qb->expr()->notIn('assignment.status', ':assignmentStatuses'),
$this->excludesSkipFormalities($qb)
))
->orderBy('job_profile.name')
->addOrderBy('teamer.lastName')
->addOrderBy('teamer.firstName')
->setParameter('destinations', $destinations)
->setParameter('dispositionCalledOff', Disposition::STATUS_CALLED_OFF)
->setParameter('assignmentStatuses', [Assignment::STATUS_CALLED_OFF, Assignment::STATUS_DELETED])
;
}
public function findDispositionsWithOverdueFeedback(?int $offsetDays = null): array
{
return $this
@@ -2,6 +2,8 @@
namespace App\Repository;
use App\Config\QuestionnaireCatalog;
use App\Entity\Destination;
use App\Entity\Disposition;
use App\Entity\QuestionnaireResponse;
use App\Enum\QuestionnaireResponseStatus;
@@ -28,19 +30,16 @@ class QuestionnaireResponseRepository extends ServiceEntityRepository
/**
* Submitted responses to one questionnaire for the office's list. Drafts stay out: until the
* teamer submits, a response is theirs. Filtered and sorted on the live disposition rather
* than the snapshot in `context`, which JSON would make neither sortable nor indexable.
* respondent submits, a response is theirs. Filtered and sorted on the live disposition or
* travel rather than the snapshot in `context`, which JSON would make neither sortable nor
* indexable. The house manager's questionnaire is about a travel, so it has no teamer to
* filter by.
*/
public function getListQuery(string $questionnaire, QuestionnaireResponseFilterDto $filterDto): Query
{
$qb = $this->createQueryBuilder('response');
$qb
->select('response', 'disposition', 'teamer', 'assignment', 'destination')
->innerJoin('response.disposition', 'disposition')
->innerJoin('disposition.teamer', 'teamer')
->innerJoin('disposition.assignment', 'assignment')
->innerJoin('assignment.destination', 'destination')
->where($qb->expr()->andX(
$qb->expr()->eq('response.questionnaire', ':questionnaire'),
$qb->expr()->eq('response.status', ':submitted')
@@ -49,11 +48,26 @@ class QuestionnaireResponseRepository extends ServiceEntityRepository
->setParameter('submitted', QuestionnaireResponseStatus::SUBMITTED)
;
if (null !== $teamer = $filterDto->getTeamer()) {
if (QuestionnaireCatalog::HOUSE_MANAGER_FEEDBACK === $questionnaire) {
$qb
->andWhere($qb->expr()->eq('disposition.teamer', ':teamer'))
->setParameter('teamer', $teamer)
->select('response', 'destination')
->innerJoin('response.destination', 'destination')
;
} else {
$qb
->select('response', 'disposition', 'teamer', 'assignment', 'destination')
->innerJoin('response.disposition', 'disposition')
->innerJoin('disposition.teamer', 'teamer')
->innerJoin('disposition.assignment', 'assignment')
->innerJoin('assignment.destination', 'destination')
;
if (null !== $teamer = $filterDto->getTeamer()) {
$qb
->andWhere($qb->expr()->eq('disposition.teamer', ':teamer'))
->setParameter('teamer', $teamer)
;
}
}
if (null !== $hotel = $filterDto->getHotel()) {
@@ -95,4 +109,15 @@ class QuestionnaireResponseRepository extends ServiceEntityRepository
return $responses;
}
/**
* The house manager's questionnaire about this travel, draft or submitted.
*/
public function findForDestination(Destination $destination): ?QuestionnaireResponse
{
return $this->findOneBy([
'destination' => $destination,
'questionnaire' => QuestionnaireCatalog::HOUSE_MANAGER_FEEDBACK,
]);
}
}
+69
View File
@@ -0,0 +1,69 @@
<?php
namespace App\Security\Voter;
use App\Config\QuestionnaireCatalog;
use App\Entity\Destination;
use App\Entity\User;
use App\Repository\DispositionRepository;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Vote;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
/**
* @extends Voter<string, Destination>
*/
class DestinationVoter extends Voter
{
/**
* Fill in, and read once submitted, the house manager's questionnaire about this travel.
*/
public const QUESTIONNAIRE = 'QUESTIONNAIRE';
private readonly \DateTimeImmutable $goLive;
/**
* @param string $houseManagerQuestionnaireGoLive Y-m-d, the services.yaml parameter
* house_manager_questionnaire_go_live
*/
public function __construct(
private readonly Security $security,
private readonly DispositionRepository $dispositionRepository,
string $houseManagerQuestionnaireGoLive,
) {
$this->goLive = QuestionnaireCatalog::parseGoLive($houseManagerQuestionnaireGoLive);
}
protected function supports(string $attribute, mixed $subject): bool
{
return $subject instanceof Destination && self::QUESTIONNAIRE === $attribute;
}
/**
* A house manager of the travel's house (User::hasHotelCodeMatch(), as for rating its teamers),
* once the travel has ended - anchored on the date, like the teamer questionnaire - if it
* ended on or after the go-live and had at least one placement a house manager rates: a
* travel nobody worked on has nothing to report.
*/
protected function voteOnAttribute(string $attribute, mixed $subject, TokenInterface $token, ?Vote $vote = null): bool
{
if (!$this->security->isGranted('ROLE_HOUSE_MANAGER')) {
return false;
}
$user = $token->getUser();
if (!$user instanceof User || !$user->hasHotelCodeMatch((string) $subject->getHotelCode())) {
return false;
}
$dateTo = $subject->getDateTo();
return null === $subject->getDeletedAt()
&& null !== $dateTo
&& $dateTo >= $this->goLive
&& $dateTo <= new \DateTimeImmutable('today')
&& [] !== $this->dispositionRepository->findForHouseManagerQuestionnaire($subject);
}
}
+22 -9
View File
@@ -3,33 +3,46 @@
namespace App\Service\Cron;
use App\BusProNet\DataProvider\HotelDataProvider;
use App\Config\QuestionnaireCatalog;
use App\Email\Mailer;
use App\Entity\Disposition;
use App\Repository\DispositionRepository;
use App\Entity\Destination;
use App\Repository\DestinationRepository;
use App\Repository\UserRepository;
use Psr\Log\LoggerInterface;
/**
* Reminds house managers, daily, of the travels they still owe something for: the questionnaire
* about the travel or a teamer's rating - the house manager's pending list
* (DestinationRepository::getPendingForHouseManagerQuery()).
*/
class FeedbackReminderService
{
private readonly \DateTimeImmutable $goLive;
public function __construct(
private readonly DispositionRepository $dispositionRepository,
private readonly DestinationRepository $destinationRepository,
private readonly HotelDataProvider $hotelDataProvider,
private readonly UserRepository $userRepository,
private readonly Mailer $mailer,
private readonly LoggerInterface $logger,
string $houseManagerQuestionnaireGoLive,
) {
$this->goLive = QuestionnaireCatalog::parseGoLive($houseManagerQuestionnaireGoLive);
}
public function sendFeedbackReminders(): string
{
/** @var Disposition[] $dispositionsWithPendingFeedbacks */
$dispositionsWithPendingFeedbacks = $this->dispositionRepository->findDispositionsWithOverdueFeedback();
/** @var list<Destination> $pendingTravels */
$pendingTravels = array_column(
$this->destinationRepository->getPendingForHouseManagerQuery(null, $this->goLive, new \DateTimeImmutable('today'))->getResult(),
0,
);
$sortedFeedbacks = [];
foreach ($dispositionsWithPendingFeedbacks as $disposition) {
foreach ($pendingTravels as $destination) {
// Get hotel by bus pro id
$hotelBusProId = $disposition->getAssignment()->getDestination()->getHotelBusProId();
$hotelBusProId = $destination->getHotelBusProId();
$hotel = $this->hotelDataProvider->get($hotelBusProId);
if (null === $hotel) {
@@ -45,7 +58,7 @@ class FeedbackReminderService
}
// Sort feedback by hotel base code
$sortedFeedbacks[$hotelCode][] = $disposition;
$sortedFeedbacks[$hotelCode][] = $destination;
}
// find hotel managers by hotel codes starting or ending with base code
@@ -79,7 +92,7 @@ class FeedbackReminderService
'feedbacks' => $feedbacksForManager,
], [
'to' => $manager->getEmail(),
'subject' => 'Reminder: Offene Feedbacks',
'subject' => 'Reminder: Offene Feedbacks und Fragebögen',
'template' => 'email/reminder_pending_feedback.html.twig',
'transport' => Mailer::MAILJET_TRANSPORT,
]);
@@ -0,0 +1,91 @@
<?php
namespace App\Service\Questionnaire;
use App\Entity\Destination;
use App\Entity\Disposition;
use App\Model\Questionnaire\Travel;
/**
* What a travel already knows, for the house manager's questionnaire: snapshotted into the
* response (build()), offered to its teamer questions (travel()) and used to preselect answers
* (initialAnswers()).
*
* The placements are the travel's teamers as DispositionRepository::findForHouseManagerQuestionnaire()
* returns them; the caller leaves out the house manager's own.
*/
final class DestinationContext
{
/**
* The question preselected from the travel's pickups, and its options.
*/
private const string BUS_ARRIVAL = 'bus_arrival';
private const string YES = 'ja';
private const string NO = 'nein';
/**
* @param list<Disposition> $dispositions
*/
public static function travel(Destination $destination, array $dispositions): Travel
{
return new Travel(
array_column(array_map(static fn (Disposition $disposition): array => [
$disposition->getUuid(),
self::teamerLabel($disposition),
], $dispositions), 1, 0),
Travel::daysBetween($destination->getDateFrom(), $destination->getDateTo()),
);
}
/**
* Plain scalars (dates as Y-m-d), stored as JSON: the answers keyed by disposition uuid stay
* readable after a placement is called off or the teamer changes.
*
* @param list<Disposition> $dispositions
*
* @return array{
* destinationProduct: ?string,
* hotel: ?string,
* hotelCode: ?string,
* dateFrom: ?string,
* dateTo: ?string,
* teamers: array<string, array{name: ?string, jobProfileName: ?string}>,
* }
*/
public static function build(Destination $destination, array $dispositions): array
{
$teamers = [];
foreach ($dispositions as $disposition) {
$teamers[$disposition->getUuid()] = [
'name' => $disposition->getTeamer()?->getFullName(),
'jobProfileName' => $disposition->getAssignment()?->getJobProfile()?->getName(),
];
}
return [
'destinationProduct' => $destination->getProduct(),
'hotel' => $destination->getHotel(),
'hotelCode' => $destination->getHotelCode(),
'dateFrom' => $destination->getDateFrom()?->format('Y-m-d'),
'dateTo' => $destination->getDateTo()?->format('Y-m-d'),
'teamers' => $teamers,
];
}
/**
* The answers a new response starts with. "Busanreise?" is still asked, but preselected from
* whether the travel has pickups; the house manager may change it.
*
* @return array<string, mixed>
*/
public static function initialAnswers(Destination $destination): array
{
return [self::BUS_ARRIVAL => [] === $destination->getPickups() ? self::NO : self::YES];
}
private static function teamerLabel(Disposition $disposition): string
{
return sprintf('%s (%s)', $disposition->getTeamer()?->getFullName(), $disposition->getAssignment()?->getJobProfile()?->getName());
}
}
@@ -211,8 +211,15 @@
class="text-gray-700 hover:text-primary block px-4 py-2 text-sm"
role="menuitem"
tabindex="-1"
title="Den Fragebogen für diesen Einsatz ausprobieren, ohne etwas zu speichern">
Fragebogen testen
title="Das Reiseleitungsfeedback ansehen und ausprobieren, wie es Teamer:innen dieses Einsatzes bekommen. Es wird nichts gespeichert.">
Vorschau Reiseleitungsfeedback
</a>
<a href="{{ path('app_administrative_questionnaire_test_house_manager', { 'uuid': assignment.uuid, 'r': return_url() }) }}"
class="text-gray-700 hover:text-primary block px-4 py-2 text-sm"
role="menuitem"
tabindex="-1"
title="Das Hausleitungsfeedback zur Reise dieses Einsatzes ansehen und ausprobieren. Es wird nichts gespeichert.">
Vorschau Hausleitungsfeedback
</a>
</twig:DropDown>
</td>
@@ -8,19 +8,25 @@
{{ 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
{{ response.destination ? context.destinationProduct|default('-') : context.teamerName|default('-') }}, abgeschickt am {{ response.submittedAt|date('d.m.Y, H:i') }} Uhr
</p>
<div class="grid lg:grid-cols-3 gap-8 items-start">
<div class="lg:col-span-2">
{% include 'questionnaire/_answers.html.twig' with { 'answers': response.answers } %}
{% include 'questionnaire/_answers.html.twig' with { 'answers': response.answers, 'context': context } %}
</div>
<div>
{# the snapshot taken on submit, so it shows the placement as the teamer answered for it #}
{# the snapshot taken on submit, so it shows the placement or travel as it was answered for #}
<h2 class="text-lg font-bold pb-4">
Einsatz
{{ response.destination ? 'Reise' : 'Einsatz' }}
</h2>
<dl class="divide-y divide-gray-100 text-sm leading-6">
{% for label, value in {
{% for label, value in response.destination ? {
'Destination': context.destinationProduct|default(null),
'Haus': context.hotel|default(null) ? context.hotel ~ ' (' ~ context.hotelCode ~ ')' : null,
'Reisetermin': context.dateFrom|default(null) ? context.dateFrom|date('d.m.Y') ~ ' - ' ~ context.dateTo|date('d.m.Y') : null,
'Wochenteam': context.teamers|default([])|map(teamer => teamer.name ~ ' (' ~ teamer.jobProfileName ~ ')')|join(', ') ?: null,
'Abgeschickt von': response.updatedBy ?? response.createdBy,
} : {
'Teamer:in': context.teamerName|default(null),
'Jobprofil': context.jobProfileName|default(null),
'Destination': context.destinationProduct|default(null),
@@ -43,16 +43,26 @@
<div class="data-table-wrapper__inner">
<table class="data-table">
<thead>
{% set aboutTravel = definition.key == 'house_manager_feedback' %}
<tr>
<th>
{{ knp_pagination_sortable(pagination, 'Name', 'teamer.lastName') }}
</th>
<th>
{{ knp_pagination_sortable(pagination, 'Vorname', 'teamer.firstName') }}
</th>
<th>
{{ knp_pagination_sortable(pagination, 'Einsatzzeitraum', 'destination.dateFrom') }}
</th>
{% if aboutTravel %}
<th>
{{ knp_pagination_sortable(pagination, 'Destination', 'destination.product') }}
</th>
<th>
{{ knp_pagination_sortable(pagination, 'Reisezeitraum', 'destination.dateFrom') }}
</th>
{% else %}
<th>
{{ knp_pagination_sortable(pagination, 'Name', 'teamer.lastName') }}
</th>
<th>
{{ knp_pagination_sortable(pagination, 'Vorname', 'teamer.firstName') }}
</th>
<th>
{{ knp_pagination_sortable(pagination, 'Einsatzzeitraum', 'destination.dateFrom') }}
</th>
{% endif %}
<th>
{{ knp_pagination_sortable(pagination, 'Haus', 'destination.hotel') }}
</th>
@@ -70,15 +80,21 @@
<tbody>
{% for response in pagination %}
{% set disposition = response.disposition %}
{% set destination = disposition.assignment.destination %}
{% set destination = aboutTravel ? response.destination : disposition.assignment.destination %}
<tr>
<td>
{{ disposition.teamer.lastName }}
</td>
<td>
{{ disposition.teamer.firstName }}
{% include '_partials/_teamer_deleted_badge.html.twig' with { 'teamer': disposition.teamer } %}
</td>
{% if aboutTravel %}
<td>
{{ destination.product }}
</td>
{% else %}
<td>
{{ disposition.teamer.lastName }}
</td>
<td>
{{ disposition.teamer.firstName }}
{% include '_partials/_teamer_deleted_badge.html.twig' with { 'teamer': disposition.teamer } %}
</td>
{% endif %}
<td>
{{ destination.dateFrom|date('d.m.Y') }}-
<br>
@@ -103,7 +119,7 @@
</tr>
{% else %}
<tr>
<td colspan="{{ definition.perBusLeg ? 7 : 6 }}">
<td colspan="{{ definition.perBusLeg ? 7 : (aboutTravel ? 5 : 6) }}">
Keine Daten...
</td>
</tr>
@@ -1,16 +1,16 @@
{% extends 'administrative/layout.html.twig' %}
{% block title %}Fragebogen testen{% endblock %}
{% block title %}Vorschau Reiseleitungsfeedback{% endblock %}
{% block content %}
<div class="max-w-3xl">
<h1 class="text-2xl font-bold pb-2">
Fragebogen testen
Vorschau Reiseleitungsfeedback
</h1>
{% include 'questionnaire/_assignment_summary.html.twig' %}
{% include '_partials/_alert.html.twig' with {
'type': 'warning',
'message': 'Testmodus: Der Fragebogen verhält sich wie für Teamer:innen, es wird aber nichts gespeichert.'
'message': 'Vorschau: Der Fragebogen verhält sich wie für Teamer:innen, es wird aber nichts gespeichert.'
} %}
{% set otherVariant = path('app_administrative_questionnaire_test', { 'uuid': assignment.uuid, 'bus_escort': busEscort ? 0 : 1, 'r': app.request.query.get('r') }) %}
{% embed '_partials/_alert.html.twig' with { 'type': 'info' } %}
@@ -23,7 +23,7 @@
{% if busEscort != assignment.hasBusEscort %}
Dieser Einsatz hat {{ assignment.hasBusEscort ? 'eine' : 'keine' }} Busbegleitung.
{% endif %}
<a href="{{ otherVariant }}" class="underline">{{ busEscort ? 'Ohne' : 'Mit' }} Bus-Feedback testen</a>
<a href="{{ otherVariant }}" class="underline">{{ busEscort ? 'Ohne' : 'Mit' }} Bus-Feedback ansehen</a>
{% endblock %}
{% endembed %}
@@ -44,14 +44,14 @@
</div>
<div class="pt-8">
<a href="{{ path('app_administrative_questionnaire_test', { 'uuid': assignment.uuid, 'r': app.request.query.get('r') }) }}" class="btn btn--secondary">
Erneut testen
Erneut ausprobieren
</a>
</div>
{% else %}
{% if draft %}
{% include '_partials/_alert.html.twig' with {
'type': 'success',
'message': 'Der Entwurf wäre jetzt gespeichert. Im Testmodus bleiben die Angaben nur im Formular.'
'message': 'Der Entwurf wäre jetzt gespeichert. In der Vorschau bleiben die Angaben nur im Formular.'
} %}
{% endif %}
{% include 'questionnaire/_form.html.twig' %}
@@ -0,0 +1,58 @@
{% extends 'administrative/layout.html.twig' %}
{% block title %}Vorschau Hausleitungsfeedback{% endblock %}
{% block content %}
<div class="max-w-3xl">
<h1 class="text-2xl font-bold pb-2">
Vorschau Hausleitungsfeedback
</h1>
{% include 'house_manager/questionnaire/_travel_summary.html.twig' %}
{% include '_partials/_alert.html.twig' with {
'type': 'warning',
'message': 'Vorschau: Der Fragebogen verhält sich wie für die Hausleitung, es wird aber nichts gespeichert.'
} %}
{% if submitted is not null %}
{% include '_partials/_alert.html.twig' with {
'type': 'success',
'message': 'So würde der abgeschickte Fragebogen gespeichert. Ausgeblendete Fragen fallen dabei weg.'
} %}
{% include 'questionnaire/_answers.html.twig' with { 'answers': submitted } %}
<div class="pt-8">
<a href="{{ path('app_administrative_questionnaire_test_house_manager', { 'uuid': assignment.uuid, 'r': app.request.query.get('r') }) }}" class="btn btn--secondary">
Erneut ausprobieren
</a>
</div>
{% else %}
{% if draft %}
{% include '_partials/_alert.html.twig' with {
'type': 'success',
'message': 'Der Entwurf wäre jetzt gespeichert. In der Vorschau bleiben die Angaben nur im Formular.'
} %}
{% endif %}
{% include 'questionnaire/_form.html.twig' %}
<section class="pt-8">
<h2 class="text-xl font-bold pb-2">
Bewerte dein Wochenteam
</h2>
<p class="pb-2 text-sm text-gray-500">
Hier verlinkt die Hausleitung jede:n Teamer:in in die Bewertung:
</p>
<ul class="list-disc pl-5">
{% for disposition in dispositions %}
<li>{{ disposition.teamer.fullName }} <span class="text-gray-500">{{ disposition.assignment.jobProfile.name }}</span></li>
{% else %}
<li>-</li>
{% endfor %}
</ul>
</section>
{% endif %}
<div class="pt-8">
<a href="{{ returnUrl }}" class="underline">
zurück
</a>
</div>
</div>
{% endblock %}
@@ -2,6 +2,6 @@
{% block body %}
<h1>
Reminder zu ausstehenden Feedbacks
Reminder zu ausstehenden Feedbacks und Fragebögen
</h1>
{% endblock %}
+152
View File
@@ -252,6 +252,158 @@
</div>
{%- endblock questionnaire_rating_widget -%}
{#
# A questionnaire radio question with short options ("Ja"/"Nein"): the question and a row of
# answer buttons on one line, the radios themselves hidden. Stacked on narrow screens.
# App\Form\QuestionnaireType picks it by the length of the option labels.
#}
{%- block questionnaire_inline_choice_row -%}
<div{% with { attr: row_attr } %}{{ block('attributes') }}{% endwith %}>
<div class="sm:flex sm:items-start sm:justify-between sm:gap-x-6">
{{- form_label(form, null, { label_attr: { class: 'sm:pb-0 sm:pt-1.5' } }) -}}
{{- form_widget(form) -}}
</div>
{{- form_errors(form) -}}
{{- form_help(form) -}}
</div>
{%- endblock questionnaire_inline_choice_row -%}
{%- block questionnaire_inline_choice_widget -%}
<div class="flex shrink-0 flex-wrap gap-2" role="radiogroup">
{%- for child in form -%}
<label class="cursor-pointer">
{{- form_widget(child, { attr: { class: 'peer sr-only' } }) -}}
<span class="{{ html_classes('flex min-w-16 items-center justify-center rounded-md px-3 py-1.5 text-sm ring-1 ring-inset transition-colors hover:bg-gray-100 peer-checked:bg-primary peer-checked:text-white peer-checked:ring-primary peer-focus-visible:ring-2', { 'ring-red-500 text-red-500': errors|length, 'ring-gray-300 text-gray-900': not errors|length }) }}">
{{- child.vars.label -}}
</span>
</label>
{%- endfor -%}
</div>
{%- endblock questionnaire_inline_choice_widget -%}
{#
# A pick of the house manager questionnaire's widgets (App\Form\Questionnaire\AbstractPickType):
# its checkbox, its errors, and the fields shown only while it is ticked. The element with
# questionnaire-pick__body is hidden by assets/styles/components/questionnaire.css, so it must not
# carry a display utility itself: utilities outrank that rule. Layout goes on an inner element.
#
# A teamer (or "Sonstiges") opens its fields indented below it...
#}
{%- block questionnaire_pick_row -%}
<div class="questionnaire-pick">
{{- block('questionnaire_pick_toggle') -}}
<div class="questionnaire-pick__body ml-2 border-l-2 border-gray-200 pt-2 pb-1 pl-4">
<div class="flex flex-col gap-y-2">
{%- for child in form|filter(child => child.vars.name != 'picked') -%}
{{- form_row(child) -}}
{%- endfor -%}
</div>
</div>
</div>
{%- endblock questionnaire_pick_row -%}
{# ...a guiding type or programme item has its numbers on the same line... #}
{%- block questionnaire_pick_inline_row -%}
{%- set head_class = 'sm:w-72 sm:shrink-0' -%}
<div class="questionnaire-pick sm:flex sm:items-start sm:gap-x-4">
{{- block('questionnaire_pick_toggle') -}}
<div class="questionnaire-pick__body pt-2 sm:pt-0">
<div class="flex flex-wrap items-center gap-x-4 gap-y-2 text-sm">
{%- for child in form|filter(child => child.vars.name != 'picked') -%}
{{- block('questionnaire_pick_number') -}}
{%- endfor -%}
</div>
{{- block('questionnaire_pick_errors') -}}
</div>
</div>
{%- endblock questionnaire_pick_inline_row -%}
{# ...and a course type reads "[2] Tage × [3] Std. pro Tag", with the days it took place below. #}
{%- block questionnaire_pick_course_row -%}
{%- set head_class = 'sm:w-72 sm:shrink-0' -%}
<div class="questionnaire-pick sm:flex sm:items-start sm:gap-x-4">
{{- block('questionnaire_pick_toggle') -}}
<div class="questionnaire-pick__body min-w-0 pt-2 sm:pt-0">
<div class="flex flex-col gap-y-2">
<div class="flex flex-wrap items-center gap-x-2 text-sm">
{%- with { child: form.days } -%}{{- block('questionnaire_pick_number') -}}{%- endwith -%}
<span class="font-bold" aria-hidden="true">×</span>
{%- with { child: form.hours_per_day } -%}{{- block('questionnaire_pick_number') -}}{%- endwith -%}
</div>
<div>
<p class="pb-1 text-sm text-gray-700">{{ form.dates.vars.label }}</p>
{{- form_widget(form.dates) -}}
</div>
</div>
{{- block('questionnaire_pick_errors') -}}
</div>
</div>
{%- endblock questionnaire_pick_course_row -%}
{#
# The pick's checkbox as a clickable row, and the pick's own errors ("mindestens ein ..."). The
# head is what the CSS rule looks into; a row block with the fields beside it sets `head_class`.
#}
{%- block questionnaire_pick_toggle -%}
<div class="questionnaire-pick__head {{ head_class|default('') }}">
<label for="{{ form.picked.vars.id }}"
class="{{ html_classes('flex cursor-pointer select-none items-center gap-x-3 rounded-md px-3 py-1.5 text-sm ring-1 ring-inset transition-colors hover:bg-gray-100 has-[:checked]:bg-primary/10 has-[:checked]:ring-primary', { 'ring-red-500': errors|length, 'ring-gray-200': not errors|length }) }}">
{{- form_widget(form.picked) -}}
<span class="text-gray-900">{{ form.picked.vars.label }}</span>
</label>
{{- form_errors(form) -}}
</div>
{%- endblock questionnaire_pick_toggle -%}
{# One number of a pick, its input before its label: "[15] Teilnehmende je Guiding". Expects `child`. #}
{%- block questionnaire_pick_number -%}
<label class="flex items-center gap-x-2">
<span class="w-20">{{- form_widget(child) -}}</span>
<span class="{{ html_classes({ 'text-red-500': child.vars.errors|length, 'text-gray-700': not child.vars.errors|length }) }}">{{ child.vars.label }}</span>
</label>
{%- endblock questionnaire_pick_number -%}
{# The errors of a pick's fields, under them rather than between them. #}
{%- block questionnaire_pick_errors -%}
{%- for child in form|filter(child => child.vars.name != 'picked') -%}
{{- form_errors(child) -}}
{%- endfor -%}
{%- endblock questionnaire_pick_errors -%}
{# The days of a travel to tick, as a row of small buttons, the checkboxes themselves hidden. #}
{%- block questionnaire_days_widget -%}
<div class="flex flex-wrap gap-1.5">
{%- for child in form -%}
<label class="cursor-pointer">
<input type="checkbox" id="{{ child.vars.id }}" name="{{ child.vars.full_name }}" value="{{ child.vars.value }}" class="peer sr-only"{% if child.vars.checked %} checked="checked"{% endif %}>
<span class="{{ html_classes('flex items-center rounded-md px-2 py-1 text-xs ring-1 ring-inset peer-checked:bg-primary peer-checked:text-white peer-checked:ring-primary peer-focus-visible:ring-2', { 'ring-red-500 text-red-500': errors|length, 'ring-gray-300 text-gray-900': not errors|length }) }}">
{{- child.vars.label -}}
</span>
</label>
{%- endfor -%}
</div>
{%- endblock questionnaire_days_widget -%}
{# A teamer or programme widget's picks, stacked. #}
{%- block teamer_guidings_widget -%}
<div class="flex flex-col gap-y-2" {{ block('widget_container_attributes') }}>
{%- for child in form -%}
{{- form_row(child) -}}
{%- endfor -%}
{%- if form is empty -%}
<p class="text-sm text-gray-500">Für diese Reise sind keine Teamer:innen eingeteilt.</p>
{%- endif -%}
</div>
{%- endblock teamer_guidings_widget -%}
{%- block teamer_courses_widget -%}
{{- block('teamer_guidings_widget') -}}
{%- endblock teamer_courses_widget -%}
{%- block programme_widget -%}
{{- block('teamer_guidings_widget') -}}
{%- endblock programme_widget -%}
{%- block birthday_widget -%}
<div class="grid grid-cols-3 gap-x-1">
{{ form_widget(form.children['day']) }}
@@ -13,92 +13,80 @@
<table class="data-table">
<thead>
<tr>
<th></th>
<th>
{{ knp_pagination_sortable(pagination, 'Name', 'teamer.lastName') }}
</th>
<th>
Vorname
</th>
<th>
{{ knp_pagination_sortable(pagination, 'Einsatz&shy;zeitraum', 'destination.dateFrom') }}
{{ knp_pagination_sortable(pagination, 'Reise&shy;zeitraum', 'destination.dateTo') }}
</th>
<th>
{{ knp_pagination_sortable(pagination, 'Destination', 'destination.product') }}
</th>
<th>
{{ knp_pagination_sortable(pagination, 'Jobprofil', 'job_profile.name') }}
Fragebogen
</th>
<th>
Wochenteam bewerten
</th>
<th></th>
</tr>
</thead>
<tbody>
{% for disposition in pagination %}
{% set teamer = disposition.teamer %}
{% set assignment = disposition.assignment %}
{% for row in pagination %}
{% set destination = row[0] %}
{% set offered = destination.dateTo >= goLive %}
{% set unrated = (placements[destination.id] ?? [])|filter(disposition => disposition.feedback is null and not disposition.feedbackWaived and disposition.teamer != app.user.teamer) %}
<tr>
<td>
{% if teamer.photo %}
<img src="{{ asset(teamer.photo | upload_filename_full | imagine_filter('profile')) }}"
class="w-12 h-auto rounded-full"
alt="{{ teamer.firstName }}">
{% else %}
<div class="flex flex-col items-center justify-center w-12 h-12 border-2 border-gray-200 rounded-full">
{{ icon('user', 'w-10 h-10 text-gray-200') }}
{{ destination.dateFrom|date('d.m.Y') }} -
<br>
{{ destination.dateTo|date('d.m.Y') }}
</td>
<td>
<div class="flex items-start space-x-2">
{{ icon('flag-' ~ destination.country, 'w-5 h-5 shrink-0') }}
<div class="flex-1">
{{ destination.product }}
<br>
{{ destination.hotel }}
</div>
</div>
</td>
<td>
{% if not offered %}
-
{% elseif row.questionnaireStatus == 'submitted' %}
<a href="{{ path('app_house_manager_questionnaire_detail', { 'id': destination.id }) }}" class="inline-flex items-center gap-x-1">
{{ icon('check', 'w-4 h-4') }} abgeschickt
</a>
{% else %}
<a href="{{ path('app_house_manager_questionnaire_edit', { 'id': destination.id }) }}" class="btn btn--small whitespace-nowrap">
{{ row.questionnaireStatus == 'draft' ? 'Entwurf fortsetzen' : 'Ausfüllen' }}
</a>
{% endif %}
</td>
<td>
<a href="{{ path('app_administrative_feedback_provide', { 'uuid': disposition.uuid }) }}"
title="Feedback abgeben">
<span class="whitespace-nowrap">{{ teamer.lastName }}</span>
</a>
</td>
<td>
<a href="{{ path('app_administrative_feedback_provide', { 'uuid': disposition.uuid }) }}"
title="Feedback abgeben">
<span class="whitespace-nowrap">{{ teamer.firstName }}</span>
</a>
</td>
<td>
<a href="{{ path('app_administrative_feedback_provide', { 'uuid': disposition.uuid }) }}"
title="Feedback abgeben">
{{ assignment.destination.dateFrom|date('d.m.Y') }} -
<br>
{{ assignment.destination.dateTo|date('d.m.Y') }}
</a>
</td>
<td>
<a href="{{ path('app_administrative_feedback_provide', { 'uuid': disposition.uuid }) }}"
title="Feedback abgeben"
class="flex items-start space-x-2">
{{ icon('flag-' ~ assignment.destination.country, 'w-5 h-5 shrink-0') }}
<div class="flex-1">
{{ assignment.destination.product }}
<br>
{{ assignment.destination.hotel }}
</div>
</a>
</td>
<td>
<a href="{{ path('app_administrative_feedback_provide', { 'uuid': disposition.uuid }) }}"
title="Feedback abgeben">
{{ assignment.jobProfile.name }}
</a>
</td>
<td>
<div class="flex items-center space-x-1 justify-end">
<a href="{{ path('app_administrative_feedback_provide', { 'uuid': disposition.uuid }) }}"
title="Feedback abgeben">
{{ icon('feedback') }}
</a>
</div>
<ul class="flex flex-col gap-y-1">
{% for disposition in unrated %}
<li>
<a href="{{ path('app_administrative_feedback_provide', { 'uuid': disposition.uuid, 'r': return_url() }) }}"
title="Feedback abgeben"
class="inline-flex items-center gap-x-1">
{{ icon('feedback', 'w-4 h-4 shrink-0') }}
<span class="whitespace-nowrap">{{ disposition.teamer.fullName }}</span>
<span class="text-gray-500">{{ disposition.assignment.jobProfile.name }}</span>
</a>
</li>
{% else %}
<li class="inline-flex items-center gap-x-1">
{{ icon('check', 'w-4 h-4') }} alle bewertet
</li>
{% endfor %}
</ul>
</td>
</tr>
{% else %}
<td colspan="7">
Keine Daten...
</td>
<tr>
<td colspan="4">
Keine Daten...
</td>
</tr>
{% endfor %}
</tbody>
</table>
+16 -5
View File
@@ -46,13 +46,24 @@
Ausstehende Feedbacks
</h2>
<ul class="divide-y divide-gray-200">
{% for disposition in pendingFeedbacks %}
{% set assignment = disposition.assignment %}
{% for row in pendingTravels %}
{% set destination = row[0] %}
{% set questionnaireOpen = destination.dateTo >= goLive and row.questionnaireStatus != 'submitted' %}
<li class="py-2 first:pt-0 last:pb-0 overflow-x-hidden">
<a href="{{ path('app_administrative_feedback_provide', { 'uuid': disposition.uuid, 'r': return_url() }) }}"
class="flex items-center space-x-1">
<a href="{{ questionnaireOpen ? path('app_house_manager_questionnaire_edit', { 'id': destination.id }) : path('app_house_manager_feedback_index') }}"
class="flex flex-wrap items-center gap-x-1">
{{ icon('feedback', 'w-4 h-4 shrink-0') }}
{{ _self.dispositionData(disposition) }}
<span class="whitespace-nowrap">{{ destination.dateFrom|date('d.m.y') }} - {{ destination.dateTo|date('d.m.y') }}</span>
{% include '_partials/_dot.html.twig' %}
<span>{{ destination.product }}</span>
{% if questionnaireOpen %}
{% include '_partials/_dot.html.twig' %}
<span class="whitespace-nowrap">Fragebogen {{ row.questionnaireStatus == 'draft' ? 'im Entwurf' : 'offen' }}</span>
{% endif %}
{% if row.openFeedbacks > 0 %}
{% include '_partials/_dot.html.twig' %}
<span class="whitespace-nowrap">{{ row.openFeedbacks }} {{ row.openFeedbacks == 1 ? 'Bewertung' : 'Bewertungen' }} offen</span>
{% endif %}
</a>
</li>
{% else %}
@@ -0,0 +1,40 @@
{#
# "Bewerte dein Wochenteam": the travel's teamers, each linking to the existing rating form until
# rated. Not part of the questionnaire's answers; a rating is filed against the placement as
# always. Expects `dispositions` (DispositionRepository::findForHouseManagerQuestionnaire()).
#}
<section class="pt-8">
<h2 class="text-xl font-bold pb-2">
Bewerte dein Wochenteam
</h2>
{% if hint|default(false) %}
<p class="pb-4 text-sm text-gray-500">
Speichere deinen Fragebogen vorher als Entwurf, sonst gehen deine Eingaben verloren.
</p>
{% endif %}
<ul class="divide-y divide-gray-100">
{% for disposition in dispositions %}
<li class="flex flex-wrap items-center justify-between gap-2 py-3">
<span>
<span class="font-bold">{{ disposition.teamer.fullName }}</span>
<span class="text-sm text-gray-500">{{ disposition.assignment.jobProfile.name }}</span>
</span>
{% if disposition.feedback %}
<span class="inline-flex items-center gap-x-1 text-sm text-gray-500">
{{ icon('check', 'w-4 h-4') }} bewertet
</span>
{% elseif disposition.feedbackWaived %}
<span class="text-sm text-gray-500">nicht nötig</span>
{% else %}
<a href="{{ path('app_administrative_feedback_provide', { 'uuid': disposition.uuid, 'r': return_url() }) }}"
class="btn btn--small btn--secondary">
{{ icon('feedback', 'w-4 h-4') }}
Bewerten
</a>
{% endif %}
</li>
{% else %}
<li class="py-3 text-gray-500">-</li>
{% endfor %}
</ul>
</section>
@@ -0,0 +1,10 @@
{#
# The travel a house manager questionnaire is about, in one line above it. Expects `destination`.
#}
<p class="flex flex-wrap items-center gap-x-2 gap-y-1 pb-8 text-sm text-gray-700">
<span class="font-bold text-gray-900">{{ destination.product }}</span>
{% include '_partials/_dot.html.twig' %}
<span>{{ destination.hotel }}</span>
{% include '_partials/_dot.html.twig' %}
<span class="whitespace-nowrap">{{ destination.dateFrom|date('d.m.') }}–{{ destination.dateTo|date('d.m.Y') }}</span>
</p>
@@ -0,0 +1,17 @@
{% extends 'administrative/layout.html.twig' %}
{% block title %}Fragebogen zur Reise{% endblock %}
{% block content %}
<div class="max-w-3xl">
<h1 class="text-2xl font-bold pb-2">
Fragebogen zur Reise
</h1>
{% include 'house_manager/questionnaire/_travel_summary.html.twig' %}
<p class="-mt-6 pb-8 text-sm text-gray-500">
Abgeschickt am {{ response.submittedAt|date('d.m.Y, H:i') }} Uhr
</p>
{% include 'questionnaire/_answers.html.twig' with { 'answers': response.answers, 'context': response.context } %}
{% include 'house_manager/questionnaire/_team.html.twig' %}
</div>
{% endblock %}
@@ -0,0 +1,19 @@
{% extends 'administrative/layout.html.twig' %}
{% block title %}Fragebogen zur Reise{% endblock %}
{% block content %}
<div class="max-w-3xl">
<h1 class="text-2xl font-bold pb-2">
Fragebogen zur Reise
</h1>
{% include 'house_manager/questionnaire/_travel_summary.html.twig' %}
{% if lastSaved %}
<p class="-mt-6 pb-8 text-sm text-gray-500">
Entwurf zuletzt gespeichert am {{ lastSaved|date('d.m.Y, H:i') }} Uhr
</p>
{% endif %}
{% include 'questionnaire/_form.html.twig' %}
{% include 'house_manager/questionnaire/_team.html.twig' with { 'hint': true } %}
</div>
{% endblock %}
+30 -1
View File
@@ -1,9 +1,11 @@
{#
# Questionnaire answers, read-only. Expects `definition` (the version they were given under) and
# `answers`, keyed by question key. Questions that are hidden or were left open are skipped; an
# `answers`, keyed by question key; optionally the response's `context`, whose `teamers` name the
# placements the house manager's teamer questions are keyed by. Questions that are hidden or were left open are skipped; an
# answer the definition does not know (an option key since renamed) is shown as stored rather
# than dropped.
#}
{% set context = context|default({}) %}
<div class="flex flex-col gap-y-8">
{% for section in definition.sections %}
{% set shown = section.questions|filter(question => answers[question.key] is defined and definition.isVisible(question, answers)) %}
@@ -37,6 +39,33 @@
{{ answer|map(key => (question.option(key).label ?? key))|join(', ') }}
{% elseif question.type.value == 'date' %}
{{ answer|date('d.m.Y') }}
{% elseif question.type.value in ['teamer_guidings', 'teamer_courses'] %}
{# one row per teamer and type; a draft's teamer without a type has nothing to show #}
<ul>
{% for row in answer|filter(row => row.type is defined) %}
<li>
<span class="font-bold">{{ context.teamers[row.disposition].name ?? row.disposition }}</span>
{{ question.option(row.type).label ?? row.type }}:
{% if question.type.value == 'teamer_guidings' %}
{{ row.count ?? '-' }} × mit je {{ row.participants ?? '-' }} Teilnehmenden
{% else %}
{{ row.days ?? '-' }} × {{ (row.hours_per_day ?? '-')|replace({'.': ','}) }} Stunden
{%- if row.dates ?? [] is not empty %},
{{ row.dates|map(date => date|format_datetime(pattern='EEEEEE dd.MM.', locale='de'))|join(', ') }}
{%- endif %}
{% endif %}
</li>
{% endfor %}
</ul>
{% elseif question.type.value == 'programme' %}
<ul>
{% for row in answer.items ?? [] %}
<li>{{ question.option(row.item).label ?? row.item }}: {{ row.participants ?? '-' }} Teilnehmende</li>
{% endfor %}
{% if answer.other is defined %}
<li>Sonstiges: {{ answer.other|nl2br }}</li>
{% endif %}
</ul>
{% else %}
{{ answer|nl2br }}
{% endif %}
+2 -2
View File
@@ -59,10 +59,10 @@ class QuestionnaireCatalogTest extends TestCase
$this->assertFalse($catalog->get(QuestionnaireCatalog::TEAMER_FEEDBACK)->perBusLeg);
}
public function testTheTwoQuestionnairesAreTheCurrentKeys(): void
public function testTheThreeQuestionnairesAreTheCurrentKeys(): void
{
$this->assertSame(
[QuestionnaireCatalog::BUS_FEEDBACK, QuestionnaireCatalog::TEAMER_FEEDBACK],
[QuestionnaireCatalog::BUS_FEEDBACK, QuestionnaireCatalog::HOUSE_MANAGER_FEEDBACK, QuestionnaireCatalog::TEAMER_FEEDBACK],
new QuestionnaireCatalog(self::SHIPPED_DIR)->keys(),
);
}
+45 -2
View File
@@ -7,8 +7,10 @@ namespace App\Tests\Config;
use App\Config\QuestionnaireCatalog;
use App\Entity\Application;
use App\Entity\Assignment;
use App\Entity\Destination;
use App\Entity\Disposition;
use App\Entity\Teamer;
use App\Service\Questionnaire\DestinationContext;
use App\Service\Questionnaire\DispositionContext;
use PHPUnit\Framework\TestCase;
@@ -74,6 +76,43 @@ class QuestionnaireCompletenessTest extends TestCase
'Das ging gar nicht / ist besonders hervorzuheben:' => ['question:bus_remarks'],
];
/**
* The house manager briefing of 2026-11-11, question by question, follow-ups included. The
* per-teamer details of guidings and courses are one bespoke question each. "team" is the
* list of the travel's teamers linking into the rating form, which is not part of the answers.
*/
private const array HOUSE_MANAGER_FEEDBACK = [
'Gruppe(n) im Haus?' => ['question:groups_in_house'],
'Busanreise?' => ['question:bus_arrival'],
'Unpünktlich?' => ['question:bus_late'],
'Wann kam der Bus?' => ['question:bus_arrival_time'],
'Gab es No-Shows?' => ['question:no_shows'],
'Wurden Leistungen nicht bezogen?' => ['question:unused_services'],
'Bitte trage hier den Vorfall des Kunden mit VG Nummer ein' => ['question:unused_services_details'],
'Gab es Guidings?' => ['question:guidings'],
'Wer hat das Guiding gegeben? / Welches Guiding wurde gegeben? / Anzahl Guidings? / Teilnehmendenanzahl pro Guiding?' => ['question:guiding_teamers', 'context:teamers'],
'Gab es Kurse?' => ['question:courses'],
'Welche Art von Kurs? / Tageszahl × Stundenzahl / Wann hat der Kurs stattgefunden?' => ['question:course_teamers', 'context:teamers'],
'Gab es Besonderheiten/Abweichungen vom Beispiel-Programm?' => ['question:programme_deviations'],
'Bitte beschreibe was genau' => ['question:programme_deviations_details'],
'Welches Programm hat stattgefunden? (mit Teilnehmendenanzahl, Sonstiges)' => ['question:programme'],
'Gab es besondere Vorkommnisse?' => ['question:incidents'],
'(Freitext zu den Vorkommnissen)' => ['question:incidents_details'],
'Feedback zur Gruppe' => ['question:group_feedback'],
'Bewerte dein Wochenteam' => ['team'],
];
public function testEveryHouseManagerFeedbackQuestionIsAskedOrDerived(): void
{
$destination = (new Destination())->setDateFrom(new \DateTimeImmutable('2027-03-27'))->setDateTo(new \DateTimeImmutable('2027-04-03'));
$this->assertComplete(
QuestionnaireCatalog::HOUSE_MANAGER_FEEDBACK,
self::HOUSE_MANAGER_FEEDBACK,
array_keys(DestinationContext::build($destination, [])),
);
}
public function testEveryTeamerFeedbackQuestionIsAskedOrDerived(): void
{
$this->assertComplete(QuestionnaireCatalog::TEAMER_FEEDBACK, self::TEAMER_FEEDBACK);
@@ -112,11 +151,12 @@ class QuestionnaireCompletenessTest extends TestCase
/**
* @param array<string, list<string>> $googleQuestions
* @param list<string>|null $contextFields what the subject snapshots; a disposition's by default
*/
private function assertComplete(string $questionnaire, array $googleQuestions): void
private function assertComplete(string $questionnaire, array $googleQuestions, ?array $contextFields = null): void
{
$definition = new QuestionnaireCatalog(__DIR__.'/../../config/questionnaires')->get($questionnaire);
$contextFields = array_keys(DispositionContext::build(new Disposition(new Application(new Assignment(), new Teamer()))));
$contextFields ??= array_keys(DispositionContext::build(new Disposition(new Application(new Assignment(), new Teamer()))));
$mapped = [];
foreach ($googleQuestions as $label => $targets) {
@@ -125,6 +165,9 @@ class QuestionnaireCompletenessTest extends TestCase
if ('legs' === $kind) {
$this->assertTrue($definition->perBusLeg, sprintf('"%s" is not asked as the legs escorted', $label));
} elseif ('team' === $kind) {
// rendered by the house manager's page, not a question
$this->assertSame(QuestionnaireCatalog::HOUSE_MANAGER_FEEDBACK, $questionnaire);
} elseif ('question' === $kind) {
$this->assertNotNull($definition->getQuestion($key), sprintf('"%s" is not asked as "%s"', $label, $key));
$mapped[] = $key;
@@ -70,7 +70,7 @@ class TestControllerTest extends WebTestCase
$crawler = $this->open();
$this->assertResponseIsSuccessful();
$this->assertStringContainsString('Testmodus', $crawler->text());
$this->assertStringContainsString('Vorschau: Der Fragebogen', $crawler->text());
// the assignment has no escort, so the questionnaire comes without the bus part
$this->assertStringContainsString('Ohne das Bus-Feedback', $crawler->text());
$this->assertCount(0, $crawler->filter('[data-question-key="bus_feedback.bus_company"]'));
@@ -0,0 +1,373 @@
<?php
declare(strict_types=1);
namespace App\Tests\Controller\HouseManager\Questionnaire;
use App\Config\QuestionnaireCatalog;
use App\Entity\Application;
use App\Entity\Assignment;
use App\Entity\Destination;
use App\Entity\Disposition;
use App\Entity\JobProfile;
use App\Entity\QuestionnaireResponse;
use App\Entity\Teamer;
use App\Entity\User;
use App\Enum\QuestionnaireResponseStatus;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\KernelBrowser;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Symfony\Component\DomCrawler\Crawler;
/**
* The house manager's questionnaire about a travel, its read-only view and the pending list: one
* response per travel, the travel's teamers offered and linked for rating, the travel pending
* until the questionnaire is submitted and every teamer rated.
*
* Runs in a transaction that is rolled back; the client keeps its kernel so every request shares
* that connection.
*/
class EditControllerTest extends WebTestCase
{
private const string FIELD = 'questionnaire[house_manager_feedback]';
private KernelBrowser $client;
private EntityManagerInterface $entityManager;
private User $houseManager;
protected function setUp(): void
{
$this->client = static::createClient(server: ['HTTPS' => true]);
$this->client->disableReboot();
$this->entityManager = self::getContainer()->get(EntityManagerInterface::class);
$this->entityManager->getConnection()->beginTransaction();
$this->houseManager = $this->user('Hanna', 'Haus', ['ROLE_HOUSE_MANAGER'], ['DKI']);
$this->entityManager->flush();
$this->client->loginUser($this->houseManager);
}
protected function tearDown(): void
{
$this->entityManager->getConnection()->rollBack();
parent::tearDown();
}
public function testTheTravelsTeamersAreOfferedAndLinkedForRating(): void
{
[$destination, $anna, $ben] = $this->travel();
$crawler = $this->open($destination);
$this->assertResponseIsSuccessful();
$this->assertStringContainsString('Davos Klosters - Schwendi', $crawler->filter('h1 + p')->text());
$guidings = $crawler->filter('[data-question-key="house_manager_feedback.guiding_teamers"]');
$this->assertStringContainsString('Anna Alpin (Reiseleitung)', $guidings->text());
$this->assertStringContainsString('Ben Brett (Kursleitung Ski)', $guidings->text());
// "Busanreise?" preselected from the travel's pickups
$this->assertSame('ja', $crawler->filter(sprintf('input[name="%s[arrival][bus_arrival]"][checked]', self::FIELD))->attr('value'));
// question 11: each teamer links into the rating form
foreach ([$anna, $ben] as $disposition) {
$this->assertCount(1, $crawler->filter(sprintf('a[href^="/administrative/feedback/provide/%s"]', $disposition->getUuid())));
}
}
public function testADraftIsKeptAndTheSubmitIsFinal(): void
{
[$destination, $anna] = $this->travel();
$this->post($destination, ['arrival' => ['groups_in_house' => 'ja']], 'draft');
$this->assertResponseRedirects(sprintf('/house-manager/questionnaire/%d', $destination->getId()));
$this->assertSame(QuestionnaireResponseStatus::DRAFT, $this->response($destination)->getStatus());
$this->assertSame('ja', $this->open($destination)->filter(sprintf('input[name="%s[arrival][groups_in_house]"][checked]', self::FIELD))->attr('value'));
$this->post($destination, $this->complete($anna), 'submit');
$this->assertResponseRedirects(sprintf('/house-manager/questionnaire/%d/answers', $destination->getId()));
$response = $this->response($destination);
$this->assertSame(QuestionnaireResponseStatus::SUBMITTED, $response->getStatus());
$this->assertSame([['disposition' => $anna->getUuid(), 'type' => 'half_day', 'count' => 2, 'participants' => 15]], $response->getAnswers()['guiding_teamers']);
$this->assertSame('Anna Alpin', $response->getContext()['teamers'][$anna->getUuid()]['name']);
// read-only from now on, the guiding named by teamer
$answers = $this->client->request('GET', sprintf('/house-manager/questionnaire/%d/answers', $destination->getId()))->filter('body')->text();
$this->assertStringContainsString('Anna Alpin Halbtagesguiding: 2 × mit je 15 Teilnehmenden', $answers);
$this->assertStringContainsString('Dorfcheck am Anreisetag: 25 Teilnehmende', $answers);
$this->open($destination);
$this->assertResponseRedirects(sprintf('/house-manager/questionnaire/%d/answers', $destination->getId()));
}
/**
* Why guidings, courses and programme items are stored as flat lists: a report unnests them with
* one JSON_TABLE, and groups by teamer, type or house like any table.
*/
public function testStoredGuidingsUnnestWithOneJsonTable(): void
{
[$destination, $anna] = $this->travel();
$this->post($destination, $this->complete($anna), 'submit');
$rows = $this->entityManager->getConnection()->fetchAllAssociative(
"SELECT g.disposition, g.type, g.count, g.participants
FROM questionnaire_response r,
JSON_TABLE(r.answers, '$.guiding_teamers[*]' COLUMNS (
disposition VARCHAR(36) PATH '$.disposition',
type VARCHAR(32) PATH '$.type',
count INT PATH '$.count',
participants INT PATH '$.participants'
)) g
WHERE r.destination_id = ?",
[$destination->getId()],
);
$this->assertSame([['disposition' => $anna->getUuid(), 'type' => 'half_day', 'count' => 2, 'participants' => 15]], $rows);
}
public function testASubmitWithAnOpenFollowUpIsRefused(): void
{
[$destination, $anna] = $this->travel();
$answers = $this->complete($anna);
unset($answers['arrival']['bus_arrival_time']);
$this->post($destination, $answers, 'submit');
$this->assertResponseStatusCodeSame(422);
$this->assertNull($this->response($destination));
}
/**
* Access denied sends a house manager back to their dashboard.
*/
public function testAHouseManagerOfAnotherHouseIsDenied(): void
{
[$destination] = $this->travel();
$this->client->loginUser($this->user('Otto', 'Anders', ['ROLE_HOUSE_MANAGER'], ['AGR']));
$this->open($destination);
$this->assertResponseRedirects('/house-manager');
}
public function testATravelThatHasNotEndedIsDenied(): void
{
[$destination] = $this->travel(new \DateTimeImmutable('tomorrow'));
$this->open($destination);
$this->assertResponseRedirects('/house-manager');
}
/**
* A house manager who also holds a placement on the travel does not rate themselves.
*/
public function testTheHouseManagersOwnPlacementIsLeftOut(): void
{
[$destination] = $this->travel();
$own = (new Teamer())->setFirstName('Hanna')->setLastName('Haus')->setGender('d')->setUser($this->houseManager);
$this->houseManager->setTeamer($own);
$this->entityManager->persist($own);
$this->placement($destination, $own, 'Hausleitung');
$crawler = $this->open($destination);
$this->assertStringNotContainsString('Hanna Haus', $crawler->filter('[data-question-key="house_manager_feedback.guiding_teamers"]')->text());
}
public function testATravelStaysPendingUntilSubmittedAndRated(): void
{
[$destination, $anna, $ben] = $this->travel();
$this->assertStringContainsString('Ausfüllen', $this->pendingRow($destination)->text());
$this->post($destination, $this->complete($anna), 'submit');
// the ratings are still missing
$this->assertStringContainsString('abgeschickt', $this->pendingRow($destination)->text());
$this->assertStringContainsString('Anna Alpin', $this->pendingRow($destination)->text());
// the requests reset the entity manager, so the placements are loaded afresh
foreach ([$anna, $ben] as $placement) {
$this->entityManager->find(Disposition::class, $placement->getId())->setFeedbackWaived(true);
}
$this->entityManager->flush();
$this->assertCount(0, $this->pendingRow($destination));
}
/**
* The office lists the submitted questionnaire with the other questionnaires and reads it
* with the travel as it was submitted for.
*/
public function testTheOfficeReadsTheSubmittedQuestionnaire(): void
{
[$destination, $anna] = $this->travel();
$this->post($destination, $this->complete($anna), 'submit');
$this->client->loginUser($this->user('Mia', 'Manager', ['ROLE_MANAGER'], []));
$list = $this->client->request('GET', '/administrative/questionnaire/list/house_manager_feedback');
$this->assertResponseIsSuccessful();
$link = $list->filter('tbody a[title="Fragebogen anzeigen"]');
$this->assertCount(1, $link);
$this->assertStringContainsString('Davos Klosters - Schwendi', $list->filter('tbody')->text());
$detail = $this->client->click($link->link())->filter('body')->text();
$this->assertResponseIsSuccessful();
$this->assertStringContainsString('Anna Alpin Halbtagesguiding', $detail);
$this->assertStringContainsString('Ben Brett (Kursleitung Ski), Anna Alpin (Reiseleitung)', $detail);
}
/**
* Test mode: the questionnaire with the travel's teamers, and nothing saved.
*/
public function testTheOfficeTriesItOutOnAnAssignmentOfTheTravel(): void
{
[, $anna] = $this->travel();
$this->client->loginUser($this->user('Mia', 'Manager', ['ROLE_MANAGER'], []));
$url = sprintf('/administrative/questionnaire/test-house-manager/%s', $anna->getAssignment()->getUuid());
$crawler = $this->client->request('GET', $url);
$this->assertResponseIsSuccessful();
$this->assertStringContainsString('Ben Brett (Kursleitung Ski)', $crawler->filter('[data-question-key="house_manager_feedback.course_teamers"]')->text());
$this->client->request('POST', $url, ['questionnaire' => [
QuestionnaireCatalog::HOUSE_MANAGER_FEEDBACK => $this->complete($anna),
'submit' => '',
'_token' => $crawler->filter('input[name="questionnaire[_token]"]')->attr('value'),
]]);
$this->assertResponseIsSuccessful();
$this->assertStringContainsString('So würde der abgeschickte Fragebogen gespeichert', $this->client->getCrawler()->text());
$this->assertStringContainsString('Anna Alpin Halbtagesguiding', $this->client->getCrawler()->text());
$this->assertSame(0, $this->entityManager->getRepository(QuestionnaireResponse::class)->count([]));
}
/**
* @return array{0: Destination, 1: Disposition, 2: Disposition}
*/
private function travel(?\DateTimeImmutable $dateTo = null): array
{
$destination = (new Destination())
->setProduct('Davos Klosters - Schwendi')
->setHotel('Schwendi')
->setHotelCode('DKI')
->setHotelBusProId(1)
->setDateFrom(new \DateTimeImmutable('-8 days'))
->setDateTo($dateTo ?? new \DateTimeImmutable('yesterday'))
->setPickups([['busProId' => 4711, 'city' => 'Stuttgart', 'street' => 'Busbahnhof', 'time' => '21:30']])
;
$this->entityManager->persist($destination);
$anna = $this->placement($destination, (new Teamer())->setFirstName('Anna')->setLastName('Alpin')->setGender('w'), 'Reiseleitung');
$ben = $this->placement($destination, (new Teamer())->setFirstName('Ben')->setLastName('Brett')->setGender('m'), 'Kursleitung Ski');
return [$destination, $anna, $ben];
}
private function placement(Destination $destination, Teamer $teamer, string $jobProfileName): Disposition
{
$jobProfile = (new JobProfile())->setName($jobProfileName)->setCategory(JobProfile::CATEGORY_GUIDE);
$assignment = (new Assignment())
->setDestination($destination)
->setJobProfile($jobProfile)
->setPickup(0)
->setStatus(Assignment::STATUS_STAFFED)
;
$disposition = (new Disposition(new Application($assignment, $teamer)))->setStatus(Disposition::STATUS_ENDED);
foreach ([$teamer, $jobProfile, $assignment, $disposition] as $entity) {
$this->entityManager->persist($entity);
}
$this->entityManager->flush();
return $disposition;
}
/**
* @param list<string> $roles
* @param list<string> $hotelCodes
*/
private function user(string $firstName, string $lastName, array $roles, array $hotelCodes): User
{
$user = (new User())
->setFirstName($firstName)
->setLastName($lastName)
->setEmail(sprintf('%s.%[email protected]', strtolower($firstName), strtolower($lastName)))
->setRoles($roles)
->setHotelCodes($hotelCodes)
->setBusProAddressId(1)
->setBusProPersonId(1)
;
$this->entityManager->persist($user);
$this->entityManager->flush();
return $user;
}
/**
* Every question answered that "Ja" opens, Anna with one half-day guiding.
*
* @return array<string, array<string, mixed>> keyed by section
*/
private function complete(Disposition $anna): array
{
return [
'arrival' => [
'groups_in_house' => 'nein',
'bus_arrival' => 'ja',
'bus_late' => 'ja',
'bus_arrival_time' => 'Samstag, 14 Uhr',
'no_shows' => 'nein',
'unused_services' => 'nein',
],
'guidings_and_courses' => [
'guidings' => 'ja',
'guiding_teamers' => [
$anna->getUuid() => ['picked' => '1', 'half_day' => ['picked' => '1', 'count' => '2', 'participants' => '15']],
],
'courses' => 'nein',
],
'activities' => [
'programme_deviations' => 'nein',
'programme' => ['village_check' => ['picked' => '1', 'participants' => '25']],
],
'closing' => [
'incidents' => 'nein',
],
];
}
private function open(Destination $destination): Crawler
{
return $this->client->request('GET', sprintf('/house-manager/questionnaire/%d', $destination->getId()));
}
/**
* Posts the answers with the form's CSRF token, as the browser would with only these fields set.
*
* @param array<string, array<string, mixed>> $answers keyed by section
*/
private function post(Destination $destination, array $answers, string $button): void
{
$token = $this->open($destination)->filter('input[name="questionnaire[_token]"]')->attr('value');
$this->client->request('POST', sprintf('/house-manager/questionnaire/%d', $destination->getId()), ['questionnaire' => [
QuestionnaireCatalog::HOUSE_MANAGER_FEEDBACK => $answers,
$button => '',
'_token' => $token,
]]);
}
private function response(Destination $destination): ?QuestionnaireResponse
{
$this->entityManager->clear();
return $this->entityManager->getRepository(QuestionnaireResponse::class)->findOneBy(['destination' => $destination->getId()]);
}
private function pendingRow(Destination $destination): Crawler
{
return $this->client
->request('GET', '/house-manager/pending-feedback')
->filter('tbody tr')
->reduce(static fn (Crawler $row): bool => str_contains($row->html(), sprintf('/house-manager/questionnaire/%d', $destination->getId())))
;
}
}
@@ -0,0 +1,270 @@
<?php
declare(strict_types=1);
namespace App\Tests\Form;
use App\Config\QuestionnaireCatalog;
use App\Form\QuestionnaireType;
use App\Model\Questionnaire\Definition;
use App\Model\Questionnaire\Travel;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
use Symfony\Component\Form\FormFactoryInterface;
use Symfony\Component\Form\FormInterface;
/**
* The house manager's questionnaire against its shipped definition, with a travel of two teamers
* from Saturday to Saturday: the three bespoke widgets (guidings and courses per teamer, the
* programme with participants), their required fields, and what is stored.
*
* Every submit goes through Form::submit() with clearMissing, as a browser request does.
*/
class HouseManagerQuestionnaireTypeTest extends KernelTestCase
{
private const string ANNA = '11111111-1111-4111-8111-111111111111';
private const string BEN = '22222222-2222-4222-8222-222222222222';
private const string KEY = QuestionnaireCatalog::HOUSE_MANAGER_FEEDBACK;
public function testEmptyDraftIsValid(): void
{
$form = $this->createForm();
$form->submit([QuestionnaireType::DRAFT => '']);
$this->assertTrue($form->isValid(), (string) $form->getErrors(true));
}
/**
* Every yes/no is required, "Feedback zur Gruppe" is not.
*/
public function testEmptySubmitDemandsTheShownQuestionsButNotTheGroupFeedback(): void
{
$form = $this->createForm();
$form->submit([QuestionnaireType::SUBMIT => '']);
$this->assertFalse($form->isValid());
$this->assertSame(['groups_in_house', 'bus_arrival', 'no_shows', 'unused_services', 'guidings', 'courses', 'programme_deviations', 'programme', 'incidents'], $this->erroneous($form));
}
public function testCompleteSubmitStoresGuidingsCoursesAndProgramme(): void
{
$form = $this->createForm();
$form->submit($this->complete() + [QuestionnaireType::SUBMIT => '']);
$this->assertTrue($form->isValid(), (string) $form->getErrors(true));
$answers = $form->getData()[self::KEY];
// flat lists, one row per teamer and type (per item), for JSON_TABLE in reports
$this->assertSame([
['disposition' => self::ANNA, 'type' => 'half_day', 'count' => 2, 'participants' => 15],
['disposition' => self::ANNA, 'type' => 'full_day', 'count' => 1, 'participants' => 30],
], $answers['guiding_teamers']);
$this->assertSame([
['disposition' => self::BEN, 'type' => 'ski_beginner', 'days' => 2, 'hours_per_day' => 2.5, 'dates' => ['2027-03-28', '2027-03-29']],
], $answers['course_teamers']);
$this->assertSame([
'items' => [['item' => 'village_check', 'participants' => 25], ['item' => 'torch_hike', 'participants' => 18]],
'other' => 'Schneeballschlacht',
], $answers['programme']);
// left empty, and optional
$stored = $this->definition()->withoutHiddenAnswers($answers);
$this->assertArrayNotHasKey('group_feedback', $stored);
$this->assertSame('Fr 16 Uhr', $stored['bus_arrival_time']);
}
/**
* Unticked fields are submitted (they are only hidden) but not stored.
*/
public function testWhatIsNotTickedIsNotStored(): void
{
$data = $this->complete();
$data[self::KEY]['guidings_and_courses']['guiding_teamers'][self::BEN] = ['half_day' => ['count' => '3', 'participants' => '9']];
$data[self::KEY]['activities']['programme']['slope_snack'] = ['participants' => '40'];
$form = $this->createForm();
$form->submit($data + [QuestionnaireType::SUBMIT => '']);
$this->assertTrue($form->isValid(), (string) $form->getErrors(true));
$answers = $form->getData()[self::KEY];
$this->assertSame([self::ANNA], array_unique(array_column($answers['guiding_teamers'], 'disposition')));
$this->assertNotContains('slope_snack', array_column($answers['programme']['items'], 'item'));
}
public function testATickedTeamerNeedsAGuidingTypeAndATickedTypeItsNumbers(): void
{
$data = $this->complete();
$data[self::KEY]['guidings_and_courses']['guiding_teamers'] = [
self::ANNA => ['picked' => '1'],
self::BEN => ['picked' => '1', 'full_day' => ['picked' => '1', 'count' => '0']],
];
$form = $this->createForm();
$form->submit($data + [QuestionnaireType::SUBMIT => '']);
$guidings = $form->get(self::KEY)->get('guidings_and_courses')->get('guiding_teamers');
$this->assertSame(['Bitte wähle mindestens ein Guiding aus.'], $this->messages($guidings->get(self::ANNA)));
$this->assertSame(['Bitte gib eine Zahl größer als 0 ein.'], $this->messages($guidings->get(self::BEN)->get('full_day')->get('count')));
$this->assertSame(['Bitte beantworte diese Frage.'], $this->messages($guidings->get(self::BEN)->get('full_day')->get('participants')));
}
public function testATickedCourseNeedsDaysHoursAndAtLeastOneDate(): void
{
$data = $this->complete();
$data[self::KEY]['guidings_and_courses']['course_teamers'][self::BEN]['ski_beginner'] = ['picked' => '1'];
$form = $this->createForm();
$form->submit($data + [QuestionnaireType::SUBMIT => '']);
$course = $form->get(self::KEY)->get('guidings_and_courses')->get('course_teamers')->get(self::BEN)->get('ski_beginner');
$this->assertNotEmpty($this->messages($course->get('days')));
$this->assertNotEmpty($this->messages($course->get('hours_per_day')));
$this->assertSame(['Bitte wähle mindestens einen Tag aus.'], $this->messages($course->get('dates')));
}
/**
* A draft takes a half-filled pick, and the pick survives being stored and loaded again.
*/
public function testAHalfFilledDraftRoundTrips(): void
{
$form = $this->createForm();
$form->submit([
self::KEY => ['guidings_and_courses' => ['guidings' => 'ja', 'guiding_teamers' => [self::ANNA => ['picked' => '1']]]],
QuestionnaireType::DRAFT => '',
]);
$this->assertTrue($form->isValid(), (string) $form->getErrors(true));
$stored = $form->getData()[self::KEY];
$this->assertSame([['disposition' => self::ANNA]], $stored['guiding_teamers']);
$view = $this->createForm([self::KEY => $stored])->createView();
$teamers = $view[self::KEY]['guidings_and_courses']['guiding_teamers'];
$this->assertTrue($teamers[self::ANNA]['picked']->vars['checked']);
$this->assertFalse($teamers[self::BEN]['picked']->vars['checked']);
}
/**
* A travel runs Saturday to Saturday, so the course days are its dates, the Saturday twice.
*/
public function testCourseDaysAreTheTravelsDates(): void
{
$view = $this->createForm()->createView();
$dates = $view[self::KEY]['guidings_and_courses']['course_teamers'][self::ANNA]['ski_beginner']['dates'];
$this->assertCount(8, $dates->children);
$this->assertSame('Sa. 27.03.', $dates->children[0]->vars['label']);
$this->assertSame('Sa. 03.04.', $dates->children[7]->vars['label']);
}
/**
* Yes/no is answered with buttons beside the question, and a follow-up is indented under it.
*/
public function testShortChoicesAreInlineAndFollowUpsIndented(): void
{
$arrival = $this->createForm()->createView()[self::KEY]['arrival'];
$this->assertContains('questionnaire_inline_choice', $arrival['bus_arrival']->vars['block_prefixes']);
$this->assertArrayNotHasKey('class', $arrival['bus_arrival']->vars['row_attr']);
$this->assertStringContainsString('border-l-2', $arrival['bus_late']->vars['row_attr']['class']);
}
public function testATeamerQuestionCannotBeBuiltWithoutTheTravel(): void
{
self::bootKernel();
$this->expectException(\LogicException::class);
self::getContainer()->get(FormFactoryInterface::class)->create(QuestionnaireType::class, [], [
'definitions' => [$this->definition()],
'csrf_protection' => false,
]);
}
/**
* @return array<string, array<string, mixed>> a submission answering "Ja" wherever it opens more,
* keyed by questionnaire, then section
*/
private function complete(): array
{
return [self::KEY => [
'arrival' => [
'groups_in_house' => 'ja',
'bus_arrival' => 'ja',
'bus_late' => 'ja',
'bus_arrival_time' => 'Fr 16 Uhr',
'no_shows' => 'nein',
'unused_services' => 'ja',
'unused_services_details' => 'VG 12345: Skipass nicht abgeholt',
],
'guidings_and_courses' => [
'guidings' => 'ja',
'guiding_teamers' => [
self::ANNA => [
'picked' => '1',
'half_day' => ['picked' => '1', 'count' => '2', 'participants' => '15'],
'full_day' => ['picked' => '1', 'count' => '1', 'participants' => '30'],
],
],
'courses' => 'ja',
'course_teamers' => [
self::BEN => [
'picked' => '1',
'ski_beginner' => ['picked' => '1', 'days' => '2', 'hours_per_day' => '2,5', 'dates' => ['2027-03-28', '2027-03-29']],
],
],
],
'activities' => [
'programme_deviations' => 'nein',
'programme' => [
'village_check' => ['picked' => '1', 'participants' => '25'],
'torch_hike' => ['picked' => '1', 'participants' => '18'],
'other' => ['picked' => '1', 'text' => 'Schneeballschlacht'],
],
],
'closing' => [
'incidents' => 'nein',
],
]];
}
/**
* @return list<string> the questions with an error of their own, in form order
*/
private function erroneous(FormInterface $form): array
{
$keys = [];
foreach ($form->get(self::KEY) as $section) {
foreach ($section as $key => $question) {
if (0 < count($question->getErrors())) {
$keys[] = $key;
}
}
}
return $keys;
}
/**
* @return list<string>
*/
private function messages(FormInterface $field): array
{
return array_map(static fn ($error): string => $error->getMessage(), iterator_to_array($field->getErrors()));
}
private function definition(): Definition
{
return new QuestionnaireCatalog(__DIR__.'/../../config/questionnaires')->get(self::KEY);
}
private function createForm(array $data = []): FormInterface
{
self::bootKernel();
return self::getContainer()->get(FormFactoryInterface::class)->create(QuestionnaireType::class, $data, [
'definitions' => [$this->definition()],
'travel' => new Travel(
[self::ANNA => 'Anna Alpin (Reiseleitung)', self::BEN => 'Ben Brett (Kursleitung Ski)'],
Travel::daysBetween(new \DateTimeImmutable('2027-03-27'), new \DateTimeImmutable('2027-04-03')),
),
'csrf_protection' => false,
]);
}
}
@@ -0,0 +1,86 @@
<?php
declare(strict_types=1);
namespace App\Tests\Security\Voter;
use App\Entity\Destination;
use App\Entity\Disposition;
use App\Entity\User;
use App\Repository\DispositionRepository;
use App\Security\Voter\DestinationVoter;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\VoterInterface;
/**
* Who may fill in the house manager's questionnaire about a travel: a house manager of its house,
* once it has ended - on or after the go-live, and only if somebody worked on it. The house and
* the end date are also covered end to end by the HouseManager EditControllerTest.
*/
class DestinationVoterTest extends TestCase
{
private const string GO_LIVE = '2026-01-01';
public function testAHouseManagerOfTheHouseIsGrantedAnEndedTravel(): void
{
$this->assertSame(VoterInterface::ACCESS_GRANTED, $this->vote($this->travel('yesterday')));
}
/**
* @return iterable<string, array{0: Destination, 1?: bool, 2?: bool, 3?: list<string>}>
*/
public static function deniedCases(): iterable
{
yield 'travel not ended' => [self::travel('tomorrow')];
yield 'travel ended before the go-live' => [self::travel('2025-12-31')];
yield 'travel deleted' => [self::travel('yesterday')->setDeletedAt(new \DateTimeImmutable())];
yield 'nobody worked on the travel' => [self::travel('yesterday'), true, false];
yield 'not a house manager' => [self::travel('yesterday'), false];
yield 'house manager of another house' => [self::travel('yesterday'), true, true, ['AGR']];
}
/**
* @param list<string> $hotelCodes
*/
#[DataProvider('deniedCases')]
public function testDenied(Destination $destination, bool $houseManager = true, bool $placements = true, array $hotelCodes = ['DKI']): void
{
$this->assertSame(VoterInterface::ACCESS_DENIED, $this->vote($destination, $houseManager, $placements, $hotelCodes));
}
public function testOtherAttributesAndSubjectsAreNotVotedOn(): void
{
$voter = new DestinationVoter($this->createStub(Security::class), $this->createStub(DispositionRepository::class), self::GO_LIVE);
$token = $this->createStub(TokenInterface::class);
$this->assertSame(VoterInterface::ACCESS_ABSTAIN, $voter->vote($token, $this->travel('yesterday'), ['EDIT']));
$this->assertSame(VoterInterface::ACCESS_ABSTAIN, $voter->vote($token, new \stdClass(), [DestinationVoter::QUESTIONNAIRE]));
}
private static function travel(string $dateTo): Destination
{
return (new Destination())
->setHotelCode('DKI')
->setDateFrom(new \DateTimeImmutable($dateTo)->modify('-7 days'))
->setDateTo(new \DateTimeImmutable($dateTo)->setTime(0, 0))
;
}
/**
* @param list<string> $hotelCodes
*/
private function vote(Destination $destination, bool $houseManager = true, bool $placements = true, array $hotelCodes = ['DKI']): int
{
$security = $this->createStub(Security::class);
$security->method('isGranted')->willReturn($houseManager);
$repository = $this->createStub(DispositionRepository::class);
$repository->method('findForHouseManagerQuestionnaire')->willReturn($placements ? [$this->createStub(Disposition::class)] : []);
$token = $this->createStub(TokenInterface::class);
$token->method('getUser')->willReturn((new User())->setHotelCodes($hotelCodes));
return new DestinationVoter($security, $repository, self::GO_LIVE)->vote($token, $destination, [DestinationVoter::QUESTIONNAIRE]);
}
}
+8 -7
View File
@@ -69,9 +69,10 @@ class QuestionnaireTemplateTest extends KernelTestCase
}
/**
* Long scales are selects, starting empty; Ja/Nein stays radios, each answer a clickable row.
* Long scales are selects, starting empty; Ja/Nein stays radios, answered with a button each
* beside the question - the label around the hidden radio is the click target.
*/
public function testLongScalesAreSelectsAndYesNoAreClickableRows(): void
public function testLongScalesAreSelectsAndYesNoAreButtons(): void
{
$crawler = $this->renderForm();
@@ -80,13 +81,13 @@ class QuestionnaireTemplateTest extends KernelTestCase
$this->assertSame('', $seminar->filter('option')->first()->attr('value'));
$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
->filter('[data-question-key="teamer_feedback.had_organisational_problems"] label')
$buttons = $crawler
->filter('[data-question-key="teamer_feedback.had_organisational_problems"] [role="radiogroup"] label')
->reduce(static fn (Crawler $label): bool => 1 === $label->filter('input[type="radio"]')->count())
;
$this->assertCount(2, $rows);
$this->assertStringContainsString('hover:', $rows->first()->attr('class'));
$this->assertCount(2, $buttons);
$this->assertStringContainsString('sr-only', $buttons->first()->filter('input')->attr('class'));
$this->assertStringContainsString('hover:', $buttons->first()->filter('span')->attr('class'));
}
public function testRatingIsFiveRadiosInARadioGroup(): void