Files
myep-team/tests/Controller/HouseManager/Questionnaire/EditControllerTest.php
T

374 lines
16 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?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())))
;
}
}