feat: list the other recipients and reply to the sender in assignment mailings

This commit is contained in:
fromme committed 2026-11-11 17:34:45 +01:00
1 parent e0496dc61f
commit f45ac6ac0b
15 files changed
+311 -19

No files matched your search

@@ -61,7 +61,7 @@ abstract class AbstractAssignmentMailingController extends AbstractController
/**
* What the composing user would receive, see the teamer mailing's renderPreview().
*
* @return array{subject: string, bodyHtml: string}
* @return array{subject: string, bodyHtml: string, colleagues: array<int, array{fullName: string, email: string}>}
*/
protected function renderPreview(AssignmentMailingDto $mailingDto): array
{
@@ -70,6 +70,7 @@ abstract class AbstractAssignmentMailingController extends AbstractController
return [
'subject' => $this->teamerMailingService->render($mailingDto->getSubject(), $values),
'bodyHtml' => $this->mailBodyRenderer->render($mailingDto->getMessage(), $values),
'colleagues' => $this->mailingService->getPreviewColleagues($mailingDto),
];
}
@@ -33,6 +33,8 @@ class AddAssignmentController extends AbstractAssignmentMailingController
$mailingDto = $this->draftHandler->getDraft();
}
return $this->render('administrative/assignment_mailing/_assignments.html.twig', $this->assignmentsContext($mailingDto));
return $this->render('administrative/assignment_mailing/assignments.html.twig', [
'preview' => $this->renderPreview($mailingDto),
] + $this->assignmentsContext($mailingDto));
}
}
@@ -24,6 +24,8 @@ class RemoveAssignmentController extends AbstractAssignmentMailingController
$this->draftHandler->saveDraft($mailingDto);
return $this->render('administrative/assignment_mailing/_assignments.html.twig', $this->assignmentsContext($mailingDto));
return $this->render('administrative/assignment_mailing/assignments.html.twig', [
'preview' => $this->renderPreview($mailingDto),
] + $this->assignmentsContext($mailingDto));
}
}
+6
View File
@@ -100,6 +100,10 @@ class Mailer
$email->getHeaders()->addTextHeader('X-Bus-Transport', $config['bus_transport']);
}
if (null !== $config['reply_to']) {
$email->replyTo($config['reply_to']);
}
foreach ($config['attachments'] as $attachment) {
/* @var EmailAttachmentInterface $attachment */
$attachment->attachTo($email);
@@ -141,6 +145,7 @@ class Mailer
'attachments' => [],
'transport' => null,
'bus_transport' => null,
'reply_to' => null,
])
->setRequired([
'template',
@@ -153,6 +158,7 @@ class Mailer
->setAllowedTypes('attachments', 'array')
->setAllowedTypes('transport', ['null', 'string'])
->setAllowedTypes('bus_transport', ['null', 'string'])
->setAllowedTypes('reply_to', ['null', 'string'])
;
return $resolver->resolve($options);
+21 -1
View File
@@ -15,6 +15,10 @@ use App\Model\TeamerMailingRecipientsDto;
*
* Attachments travel the same way, as plain paths: the files are read only when each mail is
* finally sent, so a queued mailing never carries their content.
*
* With $listColleagues every mail ends with the names and addresses of the other recipients,
* taken from the same snapshot. $replyTo is the sender's address, kept here because the worker
* has no logged-in user to ask.
*/
class SendTeamerMailing
{
@@ -27,6 +31,8 @@ class SendTeamerMailing
private readonly string $message,
private readonly array $recipients,
private readonly array $attachments = [],
private readonly bool $listColleagues = false,
private readonly ?string $replyTo = null,
) {
}
@@ -38,6 +44,8 @@ class SendTeamerMailing
string $message,
TeamerMailingRecipientsDto $recipients,
array $attachments = [],
bool $listColleagues = false,
?string $replyTo = null,
): self {
$snapshot = [];
@@ -55,7 +63,7 @@ class SendTeamerMailing
];
}
return new self($subject, $message, $snapshot, $attachments);
return new self($subject, $message, $snapshot, $attachments, $listColleagues, $replyTo);
}
public function getSubject(): string
@@ -85,6 +93,18 @@ class SendTeamerMailing
return $this->attachments ?? [];
}
public function listsColleagues(): bool
{
// a mailing queued before the colleagues section unserializes without the property
return $this->listColleagues ?? false;
}
public function getReplyTo(): ?string
{
// a mailing queued before the reply-to unserializes without the property
return $this->replyTo ?? null;
}
public function getRecipientCount(): int
{
return count($this->recipients);
@@ -15,7 +15,8 @@ use Symfony\Component\Messenger\MessageBusInterface;
/**
* Sends a mailing to the teamers confirmed on a set of assignments. Recipients, placeholders and
* the fan-out in the worker are the teamer mailing's, see TeamerMailingService; what this adds is
* the attachments and the Mailing record of what went out.
* the attachments, the list of colleagues at the end of each mail and the Mailing record of what
* went out.
*/
class AssignmentMailingService
{
@@ -60,10 +61,31 @@ class AssignmentMailingService
$this->teamerMailingService->sendPreview(
$mailingDto,
$user,
$this->attachmentHandler->toPreviewAttachments($mailingDto->getTemplate())
$this->attachmentHandler->toPreviewAttachments($mailingDto->getTemplate()),
$this->getPreviewColleagues($mailingDto)
);
}
/**
* The colleagues section as the composing user sees it. They are no recipient, so it lists
* every recipient; a single one would see none in their mail, so the preview shows none either.
*
* @return array<int, array{fullName: string, email: string}>
*/
public function getPreviewColleagues(AssignmentMailingDto $mailingDto): array
{
$colleagues = [];
foreach ($this->resolveRecipients($mailingDto)->getEligible() as $recipient) {
// resolveRecipients() already guaranteed the address, this only narrows the type
if (null !== $email = $recipient->getEmail()) {
$colleagues[] = ['fullName' => $recipient->getFullName(), 'email' => $email];
}
}
return count($colleagues) < 2 ? [] : $colleagues;
}
/**
* Records the mailing and queues it. The recipients are the ones the confirmation showed,
* passed in rather than resolved again, for the same reason SendTeamerMailing snapshots them.
@@ -99,7 +121,10 @@ class AssignmentMailingService
(string) $mailingDto->getSubject(),
(string) $mailingDto->getMessage(),
$recipients,
$this->attachmentHandler->toMessageAttachments($attachments)
$this->attachmentHandler->toMessageAttachments($attachments),
listColleagues: true,
// answers go to whoever wrote the mailing, not to the app's sender address
replyTo: $sender->getEmail()
));
$this->logger->info('Send assignment mailing', [
+40 -11
View File
@@ -116,7 +116,9 @@ class TeamerMailingService
$mailing->getAttachments()
);
foreach ($mailing->getRecipients() as $recipient) {
$recipients = $mailing->getRecipients();
foreach ($recipients as $index => $recipient) {
$values = $this->buildValues(
$recipient['firstName'],
$recipient['lastName'],
@@ -129,7 +131,9 @@ class TeamerMailingService
$this->mailBodyRenderer->render($mailing->getMessage(), $values),
$attachments,
self::TRANSPORT,
$this->mailingBusTransport
$this->mailingBusTransport,
$mailing->listsColleagues() ? self::colleaguesOf($recipients, $index) : [],
$mailing->getReplyTo()
);
}
@@ -143,11 +147,11 @@ class TeamerMailingService
/**
* Send the very same mail the recipients would get to the composing admin, with their
* own name filled in for the placeholders.
*
* @param EmailAttachmentInterface[] $attachments
* @param array<int, array{fullName: string, email: string}> $colleagues
*/
/**
* @param EmailAttachmentInterface[] $attachments
*/
public function sendPreview(TeamerMailingDto $mailingDto, User $admin, array $attachments = []): void
public function sendPreview(TeamerMailingDto $mailingDto, User $admin, array $attachments = [], array $colleagues = []): void
{
$values = $this->placeholderValuesForUser($admin);
@@ -155,7 +159,8 @@ class TeamerMailingService
$admin->getUserIdentifier(),
self::PREVIEW_SUBJECT_PREFIX.$this->render($mailingDto->getSubject(), $values),
$this->mailBodyRenderer->render($mailingDto->getMessage(), $values),
$attachments
$attachments,
colleagues: $colleagues
);
$this->logger->info('Send teamer mailing preview', [
@@ -214,6 +219,25 @@ class TeamerMailingService
return $this->buildValues($firstName, $lastName, $fullName);
}
/**
* The colleagues section of one mail: everyone else in the mailing, in the snapshot's order.
* By position, not by address - the recipients are distinct teamers, but two of them may
* share an address.
*
* @param array<int, array{email: string, fullName: string}> $recipients
*
* @return array<int, array{fullName: string, email: string}>
*/
private static function colleaguesOf(array $recipients, int $index): array
{
unset($recipients[$index]);
return array_values(array_map(
fn (array $recipient) => ['fullName' => $recipient['fullName'], 'email' => $recipient['email']],
$recipients
));
}
private function buildValues(string $firstName, string $lastName, string $fullName): array
{
return [
@@ -227,9 +251,9 @@ class TeamerMailingService
* The preview leaves the transports unset on purpose: it goes out over the same relay
* and the same queue as the rest of the application, so it arrives while the admin is
* still looking at the compose page.
*/
/**
* @param EmailAttachmentInterface[] $attachments
*
* @param EmailAttachmentInterface[] $attachments
* @param array<int, array{fullName: string, email: string}> $colleagues
*/
private function sendTo(
string $email,
@@ -238,11 +262,15 @@ class TeamerMailingService
array $attachments = [],
?string $transport = null,
?string $busTransport = null,
array $colleagues = [],
?string $replyTo = null,
): void {
// $bodyHtml is already rendered and escaped mail HTML, see MailBodyRenderer -
// email/teamer_mailing.html.twig prints it with |raw.
// email/teamer_mailing.html.twig prints it with |raw. The colleagues are plain values,
// escaped by Twig.
$this->mailer->createAndSendEmail([
'bodyHtml' => $bodyHtml,
'colleagues' => $colleagues,
], [
'to' => $email,
'subject' => $subject,
@@ -250,6 +278,7 @@ class TeamerMailingService
'attachments' => $attachments,
'transport' => $transport,
'bus_transport' => $busTransport,
'reply_to' => $replyTo,
]);
}
}
@@ -5,6 +5,7 @@
makes |raw safe here - see the contract on that class. #}
<div class="mail-body border border-gray-200 rounded-md p-4">
{{ bodyHtml | raw }}
{{ include('email/_colleagues.html.twig', {colleagues: colleagues | default([])}) }}
<p>
<span class="btn inline-block">Zum Portal</span>
</p>
@@ -12,4 +13,8 @@
<div class="pt-4 text-sm text-gray-500">
Platzhalter sind mit deinem eigenen Namen gefüllt, beim Versand steht dort der Name der
jeweiligen Person. Logo und Fußzeile der E-Mail sind hier nicht abgebildet.
{% if colleagues | default([]) is not empty %}
Die Liste der Kolleg:innen zeigt hier alle Empfänger:innen, in jeder E-Mail fehlt darin
die Person selbst.
{% endif %}
</div>
@@ -0,0 +1,5 @@
{{ include('administrative/assignment_mailing/_assignments.html.twig') }}
{# the colleagues in the preview are the recipients, which the list just changed #}
<div id="mailing-preview" hx-swap-oob="true">
{{ include('admin/teamer/_mailing_preview.html.twig', preview) }}
</div>
+10
View File
@@ -0,0 +1,10 @@
{# The other recipients of an assignment mailing, see TeamerMailingService::sendMailing().
Plain values, auto-escaped - never pass them through |raw. #}
{% if colleagues is not empty %}
<h3>Deine Kolleg:innen sind:</h3>
<ul>
{% for colleague in colleagues %}
<li>{{ colleague.fullName }} (<a href="mailto:{{ colleague.email }}">{{ colleague.email }}</a>)</li>
{% endfor %}
</ul>
{% endif %}
+2
View File
@@ -5,4 +5,6 @@
Do not pass anything into this template that did not come out of that renderer. #}
{% block body %}
{{ bodyHtml | raw }}
{{ include('email/_colleagues.html.twig', {colleagues: colleagues | default([])}) }}
{% endblock %}
@@ -18,6 +18,7 @@ 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
@@ -37,6 +38,8 @@ class AssignmentMailingControllerTest extends WebTestCase
private JobProfile $jobProfile;
private User $sender;
protected function setUp(): void
{
$this->client = static::createClient(server: ['HTTPS' => true]);
@@ -217,6 +220,10 @@ class AssignmentMailingControllerTest extends WebTestCase
$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);
@@ -225,6 +232,72 @@ class AssignmentMailingControllerTest extends WebTestCase
$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');
@@ -265,6 +338,24 @@ class AssignmentMailingControllerTest extends WebTestCase
$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();
@@ -308,6 +399,7 @@ class AssignmentMailingControllerTest extends WebTestCase
$this->entityManager->flush();
$this->client->loginUser($user);
$this->sender = $user;
}
private function assignment(string $hotel): Assignment
@@ -84,6 +84,7 @@ class EmailTextMailRenderingTest extends KernelTestCase
'attachments' => [],
'transport' => null,
'bus_transport' => null,
'reply_to' => null,
]);
$html = $email->getHtmlBody();
+1
View File
@@ -49,6 +49,7 @@ class MailerTest extends KernelTestCase
'attachments' => [],
'transport' => $transport,
'bus_transport' => null,
'reply_to' => null,
]);
}
}
@@ -247,6 +247,97 @@ class TeamerMailingServiceTest extends TestCase
$this->assertSame([], $mailing->getAttachments());
}
public function testSendMailingListsEveryOtherRecipientAsColleague(): void
{
$colleagues = [];
$this->mailer
->expects($this->exactly(3))
->method('createAndSendEmail')
->willReturnCallback(function (array $context, array $options) use (&$colleagues): void {
$colleagues[$options['to']] = array_column($context['colleagues'], 'email', 'fullName');
})
;
$recipients = (new TeamerMailingRecipientsDto())
->addEligible($this->createRecipient('Anna', 'Berg', '[email protected]'))
->addEligible($this->createRecipient('Bea', 'Ohm', '[email protected]'))
->addEligible($this->createRecipient('Cem', 'Dal', '[email protected]'))
;
$this->service->sendMailing(SendTeamerMailing::fromRecipients('Betreff', 'Nachricht', $recipients, listColleagues: true));
$this->assertSame([
'[email protected]' => ['Bea Ohm' => '[email protected]', 'Cem Dal' => '[email protected]'],
'[email protected]' => ['Anna Berg' => '[email protected]', 'Cem Dal' => '[email protected]'],
'[email protected]' => ['Anna Berg' => '[email protected]', 'Bea Ohm' => '[email protected]'],
], $colleagues);
}
public function testASingleRecipientHasNoColleagues(): void
{
$this->mailer
->expects($this->once())
->method('createAndSendEmail')
->willReturnCallback(function (array $context): void {
$this->assertSame([], $context['colleagues']);
})
;
$recipients = (new TeamerMailingRecipientsDto())->addEligible($this->createRecipient('Anna', 'Berg', '[email protected]'));
$this->service->sendMailing(SendTeamerMailing::fromRecipients('Betreff', 'Nachricht', $recipients, listColleagues: true));
}
/**
* The teamer mailing writes to whoever a filter matched - people who need not know each other.
*/
public function testAMailingWithoutTheFlagListsNoColleagues(): void
{
$this->mailer
->expects($this->exactly(2))
->method('createAndSendEmail')
->willReturnCallback(function (array $context): void {
$this->assertSame([], $context['colleagues']);
})
;
$this->service->sendMailing($this->createMailing(
'Betreff',
'Nachricht',
$this->createRecipient('Anna', 'Berg', '[email protected]'),
$this->createRecipient('Bea', 'Ohm', '[email protected]')
));
}
public function testAMailingQueuedWithoutTheNewOptionsHasNone(): void
{
$mailing = (new \ReflectionClass(SendTeamerMailing::class))->newInstanceWithoutConstructor();
$this->assertFalse($mailing->listsColleagues());
$this->assertNull($mailing->getReplyTo());
}
public function testSendMailingSetsTheReplyToOnEveryMail(): void
{
$replyTo = [];
$this->mailer
->expects($this->exactly(2))
->method('createAndSendEmail')
->willReturnCallback(function (array $context, array $options) use (&$replyTo): void {
$replyTo[] = $options['reply_to'];
})
;
$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, replyTo: '[email protected]'));
$this->assertSame(['[email protected]', '[email protected]'], $replyTo);
}
/**
* 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.
@@ -296,7 +387,7 @@ class TeamerMailingServiceTest extends TestCase
->expects($this->once())
->method('createAndSendEmail')
->with(
['bodyHtml' => '<p>Servus Rita Kern</p>'],
['bodyHtml' => '<p>Servus Rita Kern</p>', 'colleagues' => []],
$this->callback(function (array $options): bool {
$this->assertSame('[email protected]', $options['to']);
$this->assertSame('[Vorschau] Hallo Rita', $options['subject']);