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

+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