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;
}
}
@@ -0,0 +1,139 @@
<?php
declare(strict_types=1);
namespace App\Tests\Repository;
use App\Entity\Application;
use App\Entity\Assignment;
use App\Entity\Destination;
use App\Entity\Disposition;
use App\Entity\Teamer;
use App\Model\TeamerMailingRecipient;
use App\Repository\TeamerRepository;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
/**
* Who an assignment mailing reaches. Run against db_test with real rows, because the question is
* which teamers come back: confirmed ones only, each once however many of the assignments they
* are on, and none from an assignment that was not picked.
*
* Every test runs inside a transaction that is rolled back, so db_test - shared between
* branches - keeps nothing.
*/
class TeamerRepositoryAssignmentMailingTest extends KernelTestCase
{
private EntityManagerInterface $entityManager;
private TeamerRepository $repository;
protected function setUp(): void
{
self::bootKernel();
$this->entityManager = self::getContainer()->get(EntityManagerInterface::class);
$this->repository = $this->entityManager->getRepository(Teamer::class);
$this->entityManager->getConnection()->beginTransaction();
}
protected function tearDown(): void
{
$this->entityManager->getConnection()->rollBack();
parent::tearDown();
}
public function testATeamerConfirmedOnTwoPickedAssignmentsIsWrittenToOnce(): void
{
$first = $this->assignment();
$second = $this->assignment();
$teamer = $this->teamer('Anna');
$this->place($teamer, $first, Disposition::STATUS_CONFIRMED);
$this->place($teamer, $second, Disposition::STATUS_CONFIRMED);
$this->assertSame(['Anna'], $this->recipientNames([$first, $second]));
}
public function testOnlyConfirmedDispositionsCount(): void
{
$assignment = $this->assignment();
$this->place($this->teamer('Anna'), $assignment, Disposition::STATUS_CONFIRMED);
$this->place($this->teamer('Bea'), $assignment, Disposition::STATUS_NEW);
$this->place($this->teamer('Cem'), $assignment, Disposition::STATUS_CHECKING_CONTRACT);
$this->place($this->teamer('Dana'), $assignment, Disposition::STATUS_CALLED_OFF);
$this->place($this->teamer('Emil'), $assignment, Disposition::STATUS_ENDED);
$this->assertSame(['Anna'], $this->recipientNames([$assignment]));
}
public function testAnAssignmentThatWasNotPickedIsLeftOut(): void
{
$picked = $this->assignment();
$other = $this->assignment();
$this->place($this->teamer('Anna'), $picked, Disposition::STATUS_CONFIRMED);
$this->place($this->teamer('Bea'), $other, Disposition::STATUS_CONFIRMED);
$this->assertSame(['Anna'], $this->recipientNames([$picked]));
}
public function testNoAssignmentsMeansNoRecipients(): void
{
$this->place($this->teamer('Anna'), $this->assignment(), Disposition::STATUS_CONFIRMED);
$this->assertSame([], $this->repository->getAssignmentMailingRecipients([]));
}
/**
* @param Assignment[] $assignments
*
* @return string[]
*/
private function recipientNames(array $assignments): array
{
$this->entityManager->flush();
$names = array_map(
fn (TeamerMailingRecipient $recipient) => $recipient->getFirstName(),
$this->repository->getAssignmentMailingRecipients($assignments)
);
sort($names);
return $names;
}
private function assignment(): Assignment
{
$destination = (new Destination())
->setProduct('Davos Klosters - Schwendi')
->setHotel('Schwendi')
->setHotelCode('DKI')
->setHotelBusProId(1)
->setDateFrom(new \DateTimeImmutable('+7 days'))
->setDateTo(new \DateTimeImmutable('+14 days'))
->setPickups([])
;
$assignment = (new Assignment())
->setDestination($destination)
->setStatus(Assignment::STATUS_STAFFED)
;
$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');
$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,168 @@
<?php
declare(strict_types=1);
namespace App\Tests\Service\Teamer;
use App\Entity\MailingTemplate;
use App\Entity\Upload;
use App\Entity\User;
use App\Model\UploadDto;
use App\Model\UploadSessionDto;
use App\Repository\MailingRepository;
use App\Service\Teamer\MailingAttachmentHandler;
use App\Service\Upload\UploadHandler;
use Doctrine\ORM\EntityManagerInterface;
use Flagception\Manager\FeatureManagerInterface;
use PHPUnit\Framework\Attributes\AllowMockObjectsWithoutExpectations;
use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
#[AllowMockObjectsWithoutExpectations]
class MailingAttachmentHandlerTest extends TestCase
{
private const int MB = 1024 * 1024;
private UploadSessionDto $uploadSession;
private UploadHandler&MockObject $uploadHandler;
private MailingRepository&MockObject $mailingRepository;
private EntityManagerInterface&MockObject $entityManager;
private MailingAttachmentHandler $handler;
/**
* @var string[] filenames the orphanage no longer holds
*/
private array $goneFromOrphanage = [];
protected function setUp(): void
{
$this->uploadSession = new UploadSessionDto();
$this->uploadHandler = $this->createMock(UploadHandler::class);
$this->uploadHandler->method('getUploadSession')->willReturnCallback(fn () => $this->uploadSession);
$this->uploadHandler->method('findOrphanageFilepath')->willReturnCallback(
fn (string $type, string $filename) => in_array($filename, $this->goneFromOrphanage, true) ? null : '/orphanage/'.$filename
);
$this->mailingRepository = $this->createMock(MailingRepository::class);
$this->entityManager = $this->createMock(EntityManagerInterface::class);
$this->handler = new MailingAttachmentHandler(
$this->uploadHandler,
$this->mailingRepository,
$this->entityManager,
$this->createStub(FeatureManagerInterface::class),
);
}
public function testAttachmentsWithinTheLimitPass(): void
{
$this->drop('a.pdf', 4 * self::MB, Upload::TYPE_MAILING_ATTACHMENT);
$this->assertNull($this->handler->validate(Upload::TYPE_MAILING_ATTACHMENT, 6 * self::MB));
}
public function testStoredAndPendingFilesTogetherMayNotPassTheLimit(): void
{
$this->drop('a.pdf', 4 * self::MB, Upload::TYPE_MAILING_ATTACHMENT);
$error = $this->handler->validate(Upload::TYPE_MAILING_ATTACHMENT, 6 * self::MB + 1);
$this->assertSame(
'Die Anhänge sind zusammen 10,1 MB groß, erlaubt sind 10,0 MB - sonst kommt die Mail nicht an',
$error
);
}
/**
* The template form and the compose page drop into the same session, told apart by type
* only. One page's files must not count against - or be saved by - the other.
*/
public function testOnlyThePendingFilesOfTheGivenTypeCount(): void
{
$this->drop('template.pdf', 5 * self::MB, Upload::TYPE_MAILING_TEMPLATE);
$this->drop('mailing.pdf', 1 * self::MB, Upload::TYPE_MAILING_ATTACHMENT);
$this->assertSame(1 * self::MB, $this->handler->getPendingSize(Upload::TYPE_MAILING_ATTACHMENT));
$this->assertNull($this->handler->validate(Upload::TYPE_MAILING_ATTACHMENT, 9 * self::MB));
}
public function testAPendingFileGoneFromTheOrphanageIsNamedAndDropped(): void
{
$this->drop('a.pdf', self::MB, Upload::TYPE_MAILING_ATTACHMENT, 'Packliste.pdf');
$this->goneFromOrphanage = ['a.pdf'];
$this->uploadHandler
->expects($this->once())
->method('removeUploadFromSession')
->with('uuid-a.pdf')
;
$this->assertSame(
'Bitte lade Packliste.pdf noch einmal hoch, sie liegt nicht mehr bereit',
$this->handler->validate(Upload::TYPE_MAILING_ATTACHMENT, 0)
);
}
public function testFilesTickedForRemovalNoLongerCountTowardsTheTemplateLimit(): void
{
$kept = $this->stored(6 * self::MB);
$removed = $this->stored(3 * self::MB);
$template = (new MailingTemplate())->addAttachment($kept)->addAttachment($removed);
$this->drop('a.pdf', 3 * self::MB, Upload::TYPE_MAILING_TEMPLATE);
$this->assertNotNull($this->handler->validateTemplateAttachments($template, []));
$this->assertNull($this->handler->validateTemplateAttachments($template, [$removed]));
}
/**
* A sent mailing lists the files it went out with; taking one off the template must not take
* it out of that record.
*/
public function testAFileASentMailingListsIsDetachedButKept(): void
{
$upload = $this->stored(self::MB);
$template = (new MailingTemplate())->addAttachment($upload);
$this->mailingRepository->method('hasAttachment')->willReturn(true);
$this->entityManager->expects($this->never())->method('remove');
$this->uploadHandler->expects($this->never())->method('removeUploadedFile');
$this->handler->saveTemplateAttachments($template, [$upload], new User());
$this->assertTrue($template->getAttachments()->isEmpty());
$this->assertNull($upload->getMailingTemplate());
}
public function testAFileNoMailingListsIsDeleted(): void
{
$upload = $this->stored(self::MB);
$template = (new MailingTemplate())->addAttachment($upload);
$this->mailingRepository->method('hasAttachment')->willReturn(false);
$this->entityManager->expects($this->once())->method('remove')->with($upload);
$this->uploadHandler->expects($this->once())->method('removeUploadedFile')->with($upload);
$this->handler->saveTemplateAttachments($template, [$upload], new User());
}
private function drop(string $filename, int $size, string $type, ?string $originalFilename = null): void
{
$this->uploadSession->addUpload(new UploadDto(
'uuid-'.$filename,
$filename,
$originalFilename ?? $filename,
'application/pdf',
$size,
$type
));
}
private function stored(int $size): Upload
{
return (new Upload())
->setType(Upload::TYPE_MAILING_TEMPLATE)
->setFilename(uniqid().'.pdf')
->setOriginalFilename('Datei.pdf')
->setSize($size)
;
}
}
@@ -6,9 +6,11 @@ namespace App\Tests\Service\Teamer;
use App\Email\MailBodyRenderer;
use App\Email\Mailer;
use App\Entity\Assignment;
use App\Entity\Teamer;
use App\Entity\User;
use App\Message\SendTeamerMailing;
use App\Model\EmailPathAttachmentDto;
use App\Model\TeamerFilterDto;
use App\Model\TeamerMailingDto;
use App\Model\TeamerMailingRecipient;
@@ -168,6 +170,83 @@ class TeamerMailingServiceTest extends TestCase
$this->service->sendMailing($this->createMailing('Betreff', 'Nachricht'));
}
public function testResolveAssignmentRecipientsPartitionsTheConfirmedTeamers(): void
{
$eligible = $this->createRecipient('Anna', 'Berg', '[email protected]');
$disabled = $this->createRecipient('Cem', 'Dal', '[email protected]', disabled: true);
$this->teamerRepository
->method('getAssignmentMailingRecipients')
->willReturn([$eligible, $disabled])
;
$recipients = $this->service->resolveAssignmentRecipients([new Assignment()]);
$this->assertSame([$eligible], $recipients->getEligible());
$this->assertSame(1, $recipients->getSkippedDisabled());
}
/**
* By path and nothing else: the queued mail of every recipient has to stay small, the file is
* read only when that mail is sent.
*/
public function testSendMailingAttachesTheFilesByPathToEveryMail(): void
{
$attached = [];
$this->mailer
->expects($this->exactly(2))
->method('createAndSendEmail')
->willReturnCallback(function (array $context, array $options) use (&$attached): void {
$attached[] = array_map(
fn (EmailPathAttachmentDto $attachment) => [$attachment->getPath(), $attachment->getName()],
$options['attachments']
);
})
;
$recipients = (new TeamerMailingRecipientsDto())
->addEligible($this->createRecipient('Anna', 'Berg', '[email protected]'))
->addEligible($this->createRecipient('Bea', 'Ohm', '[email protected]'))
;
$this->service->sendMailing(SendTeamerMailing::fromRecipients('Betreff', 'Nachricht', $recipients, [
['path' => '/uploads/mailing_template/a/a.pdf', 'name' => 'Packliste.pdf'],
]));
$this->assertSame([
[['/uploads/mailing_template/a/a.pdf', 'Packliste.pdf']],
[['/uploads/mailing_template/a/a.pdf', 'Packliste.pdf']],
], $attached);
}
public function testSendMailingWithoutAttachmentsAttachesNothing(): void
{
$this->mailer
->expects($this->once())
->method('createAndSendEmail')
->willReturnCallback(function (array $context, array $options): void {
$this->assertSame([], $options['attachments']);
})
;
$this->service->sendMailing($this->createMailing(
'Betreff',
'Nachricht',
$this->createRecipient('Anna', 'Berg', '[email protected]')
));
}
/**
* A mailing queued before the attachments existed comes out of the queue without the
* property; it has to send as it would have, not fail in the worker.
*/
public function testAMailingQueuedWithoutAttachmentsHasNone(): void
{
$mailing = (new \ReflectionClass(SendTeamerMailing::class))->newInstanceWithoutConstructor();
$this->assertSame([], $mailing->getAttachments());
}
/**
* A preview has to stay on the default relay and the default queue, or composing a
* mailing would wait on the same worker the mailing itself is queued behind.