Files
myep-team/tests/Controller/Administrative/AssignmentMailing/AssignmentMailingControllerTest.php
T

450 lines
18 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Tests\Controller\Administrative\AssignmentMailing;
use App\Entity\Application;
use App\Entity\Assignment;
use App\Entity\Destination;
use App\Entity\Disposition;
use App\Entity\Embeddable\Communication;
use App\Entity\JobProfile;
use App\Entity\Mailing;
use App\Entity\MailingTemplate;
use App\Entity\Teamer;
use App\Entity\User;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\KernelBrowser;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Symfony\Component\DomCrawler\Crawler;
use Symfony\Component\Mime\Email;
/**
* The assignment mailing from picking assignments on the overview to the queued mails, for a
* manager - the role the teamer mailing never let in. Mail goes nowhere in the test environment
* (null transports, messenger sync), so a send can run for real and be counted.
*
* Every test runs inside a transaction that is rolled back, so db_test - shared between
* branches - keeps nothing.
*/
class AssignmentMailingControllerTest extends WebTestCase
{
private const string COMPOSE_URL = '/administrative/assignment/mailing';
private KernelBrowser $client;
private EntityManagerInterface $entityManager;
private JobProfile $jobProfile;
private User $sender;
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->jobProfile = (new JobProfile())->setName('Reiseleitung')->setCategory(JobProfile::CATEGORY_GUIDE);
$this->entityManager->persist($this->jobProfile);
}
protected function tearDown(): void
{
$this->entityManager->getConnection()->rollBack();
parent::tearDown();
}
public function testTheOverviewOffersEachAssignmentForTheMailing(): void
{
$assignment = $this->assignment('Schwendi');
$this->login('ROLE_MANAGER');
$crawler = $this->client->request('GET', '/administrative/assignment');
$this->assertResponseIsSuccessful();
$this->assertSame(self::COMPOSE_URL, $crawler->filter('form#assignment-mailing-select')->attr('action'));
$this->assertCount(1, $crawler->filter(sprintf(
'input[type="checkbox"][form="assignment-mailing-select"][value="%s"]',
$assignment->getUuid()
)));
}
public function testPickedAssignmentsStartAMailingForTheirConfirmedTeamers(): void
{
$first = $this->assignment('Schwendi');
$second = $this->assignment('Alpenrose');
$this->place($this->teamer('Anna'), $first, Disposition::STATUS_CONFIRMED);
$this->place($this->teamer('Cem'), $second, Disposition::STATUS_CONFIRMED);
$this->login('ROLE_MANAGER');
$crawler = $this->startMailing($first, $second);
$this->assertResponseIsSuccessful();
$this->assertStringContainsString('2 Empfänger:innen', $crawler->filter('#mailing-assignments')->text());
$this->assertStringContainsString('Schwendi', $crawler->filter('#mailing-assignments')->text());
$this->assertStringContainsString('Alpenrose', $crawler->filter('#mailing-assignments')->text());
}
/**
* An assignment nobody is confirmed on would only make the count look wrong, so it is left
* out - and the user is told, since they ticked it.
*/
public function testAssignmentsWithoutConfirmedTeamersAreLeftOut(): void
{
$staffed = $this->assignment('Schwendi');
$pending = $this->assignment('Alpenrose');
$empty = $this->assignment('Edelweiss');
$this->place($this->teamer('Anna'), $staffed, Disposition::STATUS_CONFIRMED);
$this->place($this->teamer('Bea'), $pending, Disposition::STATUS_NEW);
$this->login('ROLE_MANAGER');
$crawler = $this->startMailing($staffed, $pending, $empty);
$panel = $crawler->filter('#mailing-assignments');
$this->assertStringContainsString('Schwendi', $panel->text());
$this->assertStringNotContainsString('Alpenrose', $panel->text());
$this->assertStringNotContainsString('Edelweiss', $panel->text());
// toasts carry their text in a Stimulus value, not in the page text
$this->assertStringContainsString(
'2 Einsätze ohne bestätigte Teamer:innen wurden weggelassen',
(string) $this->client->getResponse()->getContent()
);
}
public function testTheSearchOnlyOffersAssignmentsWithConfirmedTeamers(): void
{
$staffed = $this->assignment('Schwendi');
$pending = $this->assignment('Alpenrose');
$this->place($this->teamer('Anna'), $staffed, Disposition::STATUS_CONFIRMED);
$this->place($this->teamer('Bea'), $pending, Disposition::STATUS_NEW);
$this->login('ROLE_MANAGER');
$this->entityManager->flush();
$this->client->request('POST', '/admin/autocomplete/assignment', content: json_encode(['search' => 'Davos']));
$values = array_column(json_decode((string) $this->client->getResponse()->getContent(), true), 'value');
$this->assertContains($staffed->getUuid(), $values);
$this->assertNotContains($pending->getUuid(), $values);
}
/**
* Someone confirmed on two of the picked assignments is one recipient; the names make the
* count add up for whoever is looking at it.
*/
public function testTheComposePageNamesTheRecipientsAndWhoIsConfirmedWhere(): void
{
$first = $this->assignment('Schwendi');
$second = $this->assignment('Alpenrose');
$anna = $this->teamer('Anna');
$this->place($anna, $first, Disposition::STATUS_CONFIRMED);
$this->place($anna, $second, Disposition::STATUS_CONFIRMED);
$this->place($this->teamer('Cem'), $second, Disposition::STATUS_CONFIRMED);
$this->login('ROLE_MANAGER');
$panel = $this->startMailing($first, $second)->filter('#mailing-assignments');
$this->assertStringContainsString('2 Empfänger:innen', $panel->text());
$this->assertStringContainsString('Anna Muster, Cem Muster', $panel->text());
$this->assertStringContainsString('bestätigt: Anna Muster, Cem Muster', $panel->filter('li')->eq(1)->text());
$this->assertStringContainsString('bestätigt: Anna Muster', $panel->filter('li')->eq(0)->text());
}
public function testAnAssignmentCanBeAddedAndRemovedOnTheComposePage(): void
{
$picked = $this->assignment('Schwendi');
$added = $this->assignment('Alpenrose');
$this->place($this->teamer('Cem'), $picked, Disposition::STATUS_CONFIRMED);
$this->place($this->teamer('Anna'), $added, Disposition::STATUS_CONFIRMED);
$this->login('ROLE_MANAGER');
$crawler = $this->startMailing($picked);
$token = $crawler->filter('input[name="assignment_mailing_add[_token]"]')->attr('value');
$panel = $this->client->request('POST', self::COMPOSE_URL.'/add', [
'assignment_mailing_add' => ['assignment' => $added->getUuid(), '_token' => $token],
]);
$this->assertStringContainsString('Alpenrose', $panel->text());
$this->assertStringContainsString('2 Empfänger:innen', $panel->text());
$panel = $this->client->request('POST', sprintf('%s/remove/%s', self::COMPOSE_URL, $added->getUuid()));
$this->assertStringNotContainsString('Alpenrose', $panel->text());
$this->assertStringContainsString('1 Empfänger:innen', $panel->text());
}
public function testPickingATemplateReplacesSubjectAndMessage(): void
{
$assignment = $this->assignment('Schwendi');
$template = (new MailingTemplate())
->setName('Packliste')
->setSubject('Deine Packliste')
->setMessage('Hallo {{vorname}}, bitte denk an die Schneeschuhe.')
;
$this->entityManager->persist($template);
$this->login('ROLE_MANAGER');
$crawler = $this->startMailing($assignment);
$response = $this->client->request('POST', self::COMPOSE_URL.'/template', [
'template' => $template->getUuid(),
'assignment_mailing' => $this->mailingFields($crawler, 'Eigener Betreff', 'Eigene Nachricht'),
]);
$this->assertSame('Deine Packliste', $response->filter('#assignment_mailing_subject')->attr('value'));
$this->assertStringContainsString('Schneeschuhe', $response->filter('#assignment_mailing_message')->text());
// the preview, swapped out of band, already shows it
$this->assertStringContainsString('Deine Packliste', $response->filter('#mailing-preview')->text());
}
public function testSendingRecordsTheMailingAndWritesEachConfirmedTeamerOnce(): void
{
$first = $this->assignment('Schwendi');
$second = $this->assignment('Alpenrose');
$anna = $this->teamer('Anna');
$this->place($anna, $first, Disposition::STATUS_CONFIRMED);
$this->place($anna, $second, Disposition::STATUS_CONFIRMED);
$this->place($this->teamer('Bea'), $second, Disposition::STATUS_CALLED_OFF);
$this->login('ROLE_MANAGER');
$crawler = $this->startMailing($first, $second);
$this->client->request('POST', self::COMPOSE_URL.'/send', [
'assignment_mailing' => $this->mailingFields($crawler, 'Treffpunkt', 'Hallo {{vorname}}'),
]);
$this->assertResponseIsSuccessful();
$this->assertSame('/administrative/assignment', $this->client->getResponse()->headers->get('HX-Redirect'));
$this->assertEmailCount(1);
$this->assertSame('Hallo Anna', trim((new Crawler($this->getMailerMessage()->getHtmlBody()))->filter('p')->first()->text()));
// answers reach the manager who sent it
$this->assertSame($this->sender->getEmail(), $this->getMailerMessage()->getReplyTo()[0]->getAddress());
// alone in the mailing, so nobody to list
$this->assertStringNotContainsString('Deine Kolleg:innen', (string) $this->getMailerMessage()->getHtmlBody());
$mailings = $this->entityManager->getRepository(Mailing::class)->findAll();
$this->assertCount(1, $mailings);
$this->assertSame('Treffpunkt', $mailings[0]->getSubject());
$this->assertSame(1, $mailings[0]->getRecipientCount());
$this->assertCount(2, $mailings[0]->getAssignments());
}
/**
* The list is the mailing's recipients, not the teamers of each assignment: the body is the
* same in every mail.
*/
public function testEachMailListsTheOtherRecipientsOfTheMailing(): void
{
$first = $this->assignment('Schwendi');
$second = $this->assignment('Alpenrose');
$this->place($this->teamer('Anna'), $first, Disposition::STATUS_CONFIRMED);
$this->place($this->teamer('Cem'), $second, Disposition::STATUS_CONFIRMED);
$this->place($this->teamer('Bea'), $second, Disposition::STATUS_CALLED_OFF);
$this->login('ROLE_MANAGER');
$crawler = $this->startMailing($first, $second);
$this->client->request('POST', self::COMPOSE_URL.'/send', [
'assignment_mailing' => $this->mailingFields($crawler, 'Treffpunkt', 'Hallo'),
]);
$this->assertEmailCount(2);
$this->assertSame(['Cem Muster ([email protected])'], $this->colleaguesIn('[email protected]'));
$this->assertSame(['Anna Muster ([email protected])'], $this->colleaguesIn('[email protected]'));
}
public function testColleagueNamesAreEscaped(): void
{
$assignment = $this->assignment('Schwendi');
$this->place($this->teamer('Anna'), $assignment, Disposition::STATUS_CONFIRMED);
$this->place($this->teamer('Bea')->setLastName('<em>Muster</em>'), $assignment, Disposition::STATUS_CONFIRMED);
$this->login('ROLE_MANAGER');
$crawler = $this->startMailing($assignment);
$this->client->request('POST', self::COMPOSE_URL.'/send', [
'assignment_mailing' => $this->mailingFields($crawler, 'Treffpunkt', 'Hallo'),
]);
$this->assertSame(['Bea <em>Muster</em> ([email protected])'], $this->colleaguesIn('[email protected]'));
}
/**
* The composing user is no recipient, so the preview lists all of them - and follows the
* list when an assignment is removed.
*/
public function testThePreviewListsTheRecipientsAsColleagues(): void
{
$first = $this->assignment('Schwendi');
$second = $this->assignment('Alpenrose');
$this->place($this->teamer('Anna'), $first, Disposition::STATUS_CONFIRMED);
$this->place($this->teamer('Cem'), $second, Disposition::STATUS_CONFIRMED);
$this->login('ROLE_MANAGER');
$crawler = $this->startMailing($first, $second);
$preview = $crawler->filter('#mailing-preview')->text();
$this->assertStringContainsString('Deine Kolleg:innen sind:', $preview);
$this->assertStringContainsString('Anna Muster ([email protected])', $preview);
$this->assertStringContainsString('Cem Muster ([email protected])', $preview);
$response = $this->client->request('POST', sprintf('%s/remove/%s', self::COMPOSE_URL, $second->getUuid()));
$this->assertResponseIsSuccessful();
// one recipient left, whose mail lists nobody
$this->assertStringNotContainsString('Deine Kolleg:innen', $response->filter('#mailing-preview')->text());
}
public function testAMailingWithoutRecipientsIsNotSent(): void
{
$assignment = $this->assignment('Schwendi');
$this->place($this->teamer('Bea'), $assignment, Disposition::STATUS_NEW);
$this->login('ROLE_MANAGER');
$crawler = $this->startMailing($assignment);
$this->client->request('POST', self::COMPOSE_URL.'/send', [
'assignment_mailing' => $this->mailingFields($crawler, 'Treffpunkt', 'Hallo'),
]);
$this->assertSame(self::COMPOSE_URL, $this->client->getResponse()->headers->get('HX-Redirect'));
$this->assertEmailCount(0);
$this->assertCount(0, $this->entityManager->getRepository(Mailing::class)->findAll());
}
public function testStartingWithNothingTickedDoesNotReopenTheLastDraft(): void
{
$this->assignment('Schwendi');
$this->login('ROLE_MANAGER');
$this->startMailing(...$this->entityManager->getRepository(Assignment::class)->findAll());
$crawler = $this->startMailing();
$this->assertStringContainsString('Noch kein Einsatz ausgewählt', $crawler->filter('#mailing-assignments')->text());
}
/**
* A refused administrative page sends a teamer back to their own start page.
*/
public function testATeamerCannotComposeAMailing(): void
{
$this->login('ROLE_TEAMER');
$this->client->request('GET', self::COMPOSE_URL);
$this->assertResponseRedirects('/teamer');
}
/**
* The colleagues section of the mail sent to the given address, one entry per line.
*
* @return string[]
*/
private function colleaguesIn(string $to): array
{
foreach ($this->getMailerMessages() as $message) {
if ($message instanceof Email && $to === $message->getTo()[0]->getAddress()) {
return (new Crawler((string) $message->getHtmlBody()))
->filter('h3:contains("Deine Kolleg:innen sind:") + ul li')
->each(fn (Crawler $item) => trim($item->text()));
}
}
$this->fail(sprintf('No mail to %s', $to));
}
private function startMailing(Assignment ...$assignments): Crawler
{
$this->entityManager->flush();
$this->client->request('GET', self::COMPOSE_URL, [
'start' => 1,
'assignments' => array_map(fn (Assignment $assignment) => $assignment->getUuid(), $assignments),
]);
$this->assertResponseRedirects(self::COMPOSE_URL);
return $this->client->followRedirect();
}
/**
* @return array<string, string>
*/
private function mailingFields(Crawler $crawler, string $subject, string $message): array
{
$fields = ['subject' => $subject, 'message' => $message];
$token = $crawler->filter('input[name="assignment_mailing[_token]"]');
if ($token->count() > 0) {
$fields['_token'] = (string) $token->attr('value');
}
return $fields;
}
private function login(string $role): void
{
$user = (new User())
->setFirstName('Mia')
->setLastName('Manager')
->setEmail(uniqid('mailing.', true).'@example.com')
->setRoles([$role])
->setBusProAddressId(1)
->setBusProPersonId(1)
;
$this->entityManager->persist($user);
$this->entityManager->flush();
$this->client->loginUser($user);
$this->sender = $user;
}
private function assignment(string $hotel): Assignment
{
$destination = (new Destination())
->setProduct('Davos Klosters')
->setHotel($hotel)
->setHotelCode('DKI')
->setHotelBusProId(1)
->setCountry('CH')
->setDateFrom(new \DateTimeImmutable('+7 days'))
->setDateTo(new \DateTimeImmutable('+14 days'))
->setPickups([])
;
$assignment = (new Assignment())
->setDestination($destination)
->setJobProfile($this->jobProfile)
->setAvailableDispositions(2)
->setStatus(Assignment::STATUS_PUBLISHED)
;
$this->entityManager->persist($destination);
$this->entityManager->persist($assignment);
return $assignment;
}
private function teamer(string $firstName): Teamer
{
$teamer = (new Teamer())
->setFirstName($firstName)
->setLastName('Muster')
->setGender('d')
->setCommunication((new Communication())->setEmail(strtolower($firstName).'[email protected]'))
;
$this->entityManager->persist($teamer);
return $teamer;
}
private function place(Teamer $teamer, Assignment $assignment, string $status): void
{
$disposition = (new Disposition(new Application($assignment, $teamer)))->setStatus($status);
$this->entityManager->persist($disposition);
}
}