feat: add mailing templates and mail the confirmed teamers of selected assignments

This commit is contained in:
fromme committed 2026-11-11 14:02:55 +01:00
1 parent 6c89f1b8a9
commit e285646bb2
57 files changed
+3525 -31

No files matched your search

@@ -0,0 +1,357 @@
<?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;
/**
* 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;
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()));
$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());
}
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');
}
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);
}
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);
}
}
@@ -0,0 +1,169 @@
<?php
declare(strict_types=1);
namespace App\Tests\Controller\Administrative\System\MailingTemplate;
use App\Entity\Mailing;
use App\Entity\MailingTemplate;
use App\Entity\Upload;
use App\Entity\User;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\KernelBrowser;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Symfony\Component\HttpFoundation\Response;
/**
* The shared library of mailing templates, kept by managers and admins alike.
*
* Every test runs inside a transaction that is rolled back, so db_test - shared between
* branches - keeps nothing.
*/
class MailingTemplateControllerTest extends WebTestCase
{
private const string LIST_URL = '/administrative/system/mailing-template';
private KernelBrowser $client;
private EntityManagerInterface $entityManager;
private User $user;
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->user = (new User())
->setFirstName('Mia')
->setLastName('Manager')
->setEmail(uniqid('template.', true).'@example.com')
->setRoles(['ROLE_MANAGER'])
->setBusProAddressId(1)
->setBusProPersonId(1)
;
$this->entityManager->persist($this->user);
$this->entityManager->flush();
$this->client->loginUser($this->user);
}
protected function tearDown(): void
{
$this->entityManager->getConnection()->rollBack();
parent::tearDown();
}
public function testAManagerCreatesATemplate(): void
{
$this->client->request('GET', self::LIST_URL.'/create');
$this->assertResponseIsSuccessful();
$this->client->submitForm('Speichern', [
'mailing_template[name]' => 'Packliste',
'mailing_template[subject]' => 'Deine Packliste',
'mailing_template[message]' => 'Hallo {{vorname}}',
]);
$this->assertResponseRedirects(self::LIST_URL);
$template = $this->entityManager->getRepository(MailingTemplate::class)->findOneBy(['name' => 'Packliste']);
$this->assertNotNull($template);
$this->assertSame('Deine Packliste', $template->getSubject());
}
public function testATemplateWithoutSubjectIsNotSaved(): void
{
$this->client->request('GET', self::LIST_URL.'/create');
$this->client->submitForm('Speichern', [
'mailing_template[name]' => 'Packliste',
'mailing_template[subject]' => '',
'mailing_template[message]' => 'Hallo',
]);
// re-rendered rather than redirected, like every form in this app
$this->assertResponseIsSuccessful();
$this->assertSelectorTextContains('body', 'Bitte gib einen Betreff an');
$this->assertNull($this->entityManager->getRepository(MailingTemplate::class)->findOneBy(['name' => 'Packliste']));
}
/**
* Deleting is soft: the mailings sent from the template keep pointing at it. It is gone from
* the list and can no longer be edited.
*/
public function testDeletingATemplateHidesItButKeepsTheRow(): void
{
$template = $this->template('Packliste');
$this->client->request('POST', sprintf('%s/delete/%s', self::LIST_URL, $template->getUuid()));
$this->assertSame(self::LIST_URL, $this->client->getResponse()->headers->get('HX-Redirect'));
$this->entityManager->clear();
$this->assertTrue($this->entityManager->find(MailingTemplate::class, $template->getId())->isDeleted());
$crawler = $this->client->request('GET', self::LIST_URL);
$this->assertStringNotContainsString('Packliste', $crawler->filter('table')->text());
$this->client->request('GET', sprintf('%s/edit/%s', self::LIST_URL, $template->getUuid()));
$this->assertResponseStatusCodeSame(Response::HTTP_NOT_FOUND);
}
/**
* A file a sent mailing went out with stays in that record when it comes off the template;
* one nobody sent is deleted with it.
*/
public function testTickedAttachmentsComeOffTheTemplateOnSave(): void
{
$template = $this->template('Packliste');
$sent = $this->attachment($template, 'Anreise.pdf');
$unsent = $this->attachment($template, 'Entwurf.pdf');
$this->entityManager->persist((new Mailing())->setSubject('S')->setMessage('M')->addAttachment($sent));
$this->entityManager->flush();
$sentId = $sent->getId();
$unsentId = $unsent->getId();
$crawler = $this->client->request('GET', sprintf('%s/edit/%s', self::LIST_URL, $template->getUuid()));
$form = $crawler->selectButton('Speichern')->form();
foreach ($form['mailing_template[removeAttachments]'] as $checkbox) {
$checkbox->tick();
}
$this->client->submit($form);
$this->assertResponseRedirects(self::LIST_URL);
$this->entityManager->clear();
$this->assertCount(0, $this->entityManager->find(MailingTemplate::class, $template->getId())->getAttachments());
$this->assertNotNull($this->entityManager->find(Upload::class, $sentId));
$this->assertNull($this->entityManager->find(Upload::class, $unsentId));
}
private function template(string $name): MailingTemplate
{
$template = (new MailingTemplate())->setName($name)->setSubject('Betreff')->setMessage('Nachricht');
$this->entityManager->persist($template);
$this->entityManager->flush();
return $template;
}
private function attachment(MailingTemplate $template, string $filename): Upload
{
// No file on disk: removing a missing file is a no-op for UploadHandler::removeUploadedFile().
$upload = (new Upload())
->setType(Upload::TYPE_MAILING_TEMPLATE)
->setFilename(sprintf('test-%s-%s', bin2hex(random_bytes(4)), $filename))
->setOriginalFilename($filename)
->setMimeType('application/pdf')
->setSize(1024)
->setOwner($this->user)
;
$template->addAttachment($upload);
$this->entityManager->persist($upload);
$this->entityManager->flush();
return $upload;
}
}