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,31 @@
<?php
namespace App\Controller\Admin\Autocomplete;
use App\Repository\AssignmentRepository;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Attribute\IsGranted;
class AssignmentController extends AbstractController
{
public function __construct(private readonly AssignmentRepository $assignmentRepository)
{
}
#[Route('/admin/autocomplete/assignment', name: 'app_admin_autocomplete_assignment')]
#[IsGranted('ROLE_ADMINISTRATIVE')]
public function index(Request $request): JsonResponse
{
try {
$query = json_decode($request->getContent(), true, 512, JSON_THROW_ON_ERROR);
$queryString = (string) $query['search'];
} catch (\JsonException $e) {
throw $this->createNotFoundException();
}
return $this->json($this->assignmentRepository->getMailingAutocompletionData($queryString));
}
}
@@ -0,0 +1,99 @@
<?php
namespace App\Controller\Administrative\AssignmentMailing;
use App\Controller\Traits\AuthenticatedUserTrait;
use App\Email\MailBodyRenderer;
use App\Entity\Upload;
use App\Form\AssignmentMailingAddType;
use App\Form\AssignmentMailingType;
use App\Model\AssignmentMailingDto;
use App\Service\Teamer\AssignmentMailingDraftHandler;
use App\Service\Teamer\AssignmentMailingService;
use App\Service\Teamer\MailingAttachmentHandler;
use App\Service\Teamer\TeamerMailingService;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Contracts\Service\Attribute\Required;
/**
* What the actions of the assignment mailing share: the draft, the form over its wording and the
* pieces of the compose page that htmx swaps on their own.
*/
abstract class AbstractAssignmentMailingController extends AbstractController
{
use AuthenticatedUserTrait;
protected AssignmentMailingDraftHandler $draftHandler;
protected AssignmentMailingService $mailingService;
protected MailingAttachmentHandler $attachmentHandler;
protected TeamerMailingService $teamerMailingService;
protected MailBodyRenderer $mailBodyRenderer;
#[Required]
public function setMailingDependencies(
AssignmentMailingDraftHandler $draftHandler,
AssignmentMailingService $mailingService,
MailingAttachmentHandler $attachmentHandler,
TeamerMailingService $teamerMailingService,
MailBodyRenderer $mailBodyRenderer,
): void {
$this->draftHandler = $draftHandler;
$this->mailingService = $mailingService;
$this->attachmentHandler = $attachmentHandler;
$this->teamerMailingService = $teamerMailingService;
$this->mailBodyRenderer = $mailBodyRenderer;
}
/**
* The form over the draft: a GET shows the parked wording, a POST carries the current one.
* Assignments and template stay what the draft says, the form has no fields for them.
*/
protected function createMailingForm(Request $request, ?AssignmentMailingDto $mailingDto = null): FormInterface
{
$form = $this->createForm(AssignmentMailingType::class, $mailingDto ?? $this->draftHandler->getDraft());
$form->handleRequest($request);
return $form;
}
/**
* What the composing user would receive, see the teamer mailing's renderPreview().
*
* @return array{subject: string, bodyHtml: string}
*/
protected function renderPreview(AssignmentMailingDto $mailingDto): array
{
$values = $this->teamerMailingService->placeholderValuesForUser($this->getAuthenticatedUser());
return [
'subject' => $this->teamerMailingService->render($mailingDto->getSubject(), $values),
'bodyHtml' => $this->mailBodyRenderer->render($mailingDto->getMessage(), $values),
];
}
/**
* For administrative/assignment_mailing/_assignments.html.twig.
*/
protected function assignmentsContext(AssignmentMailingDto $mailingDto): array
{
return [
'mailingDto' => $mailingDto,
'recipients' => $this->mailingService->resolveRecipients($mailingDto),
'addForm' => $this->createForm(AssignmentMailingAddType::class)->createView(),
];
}
/**
* For administrative/assignment_mailing/_attachments.html.twig.
*/
protected function attachmentsContext(AssignmentMailingDto $mailingDto): array
{
return [
'mailingDto' => $mailingDto,
'pending' => $this->attachmentHandler->getPending(Upload::TYPE_MAILING_ATTACHMENT),
'maxAttachmentBytes' => MailingAttachmentHandler::MAX_TOTAL_BYTES,
];
}
}
@@ -0,0 +1,38 @@
<?php
namespace App\Controller\Administrative\AssignmentMailing;
use App\Entity\Assignment;
use App\Form\AssignmentMailingAddType;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Attribute\IsGranted;
class AddAssignmentController extends AbstractAssignmentMailingController
{
#[Route('/administrative/assignment/mailing/add', name: 'app_administrative_assignment_mailing_add', methods: ['POST'])]
#[IsGranted('ROLE_ADMINISTRATIVE')]
public function index(Request $request): Response
{
$mailingDto = $this->draftHandler->getDraft();
$form = $this->createForm(AssignmentMailingAddType::class);
$form->handleRequest($request);
/** @var Assignment|null $assignment */
$assignment = $form->isSubmitted() && $form->isValid() ? $form->get('assignment')->getData() : null;
if (null !== $assignment && false === $assignment->isDeleted()
&& false === in_array($assignment, $mailingDto->getAssignments(), true)) {
$this->draftHandler->saveDraft(
$mailingDto->setAssignments([...$mailingDto->getAssignments(), $assignment])
);
// read back, so the list comes in the draft's order
$mailingDto = $this->draftHandler->getDraft();
}
return $this->render('administrative/assignment_mailing/_assignments.html.twig', $this->assignmentsContext($mailingDto));
}
}
@@ -0,0 +1,81 @@
<?php
namespace App\Controller\Administrative\AssignmentMailing;
use App\Controller\Traits\ReturnUrlTrait;
use App\Entity\Upload;
use App\Repository\MailingTemplateRepository;
use App\Service\Teamer\TeamerMailingService;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Attribute\IsGranted;
/**
* Compose a mail to the teamers confirmed on a set of assignments.
*
* Arriving from the overview's "Mail an Teamer:innen" (?start=1, plus the ticked assignments)
* starts a new mailing for them; arriving otherwise continues the one in the draft. A submit of the form sends the preview
* to the composing user, the real send goes through the confirmation modal.
*/
class ComposeController extends AbstractAssignmentMailingController
{
use ReturnUrlTrait;
public function __construct(private readonly MailingTemplateRepository $mailingTemplateRepository)
{
}
#[Route('/administrative/assignment/mailing', name: 'app_administrative_assignment_mailing_compose')]
#[IsGranted('ROLE_ADMINISTRATIVE')]
public function index(Request $request): Response
{
if (true === $request->query->has('start')) {
$omitted = $this->draftHandler->startDraft(array_filter($request->query->all('assignments'), 'is_string'));
$this->attachmentHandler->discardPending(Upload::TYPE_MAILING_ATTACHMENT);
if ($omitted > 0) {
$this->addFlash('info', 1 === $omitted
? 'Ein Einsatz ohne bestätigte Teamer:innen wurde weggelassen'
: sprintf('%d Einsätze ohne bestätigte Teamer:innen wurden weggelassen', $omitted));
}
// without the selection in the address, a reload continues this mailing instead of
// starting it over
return $this->redirectToRoute('app_administrative_assignment_mailing_compose', [
'r' => $request->query->get('r'),
]);
}
$form = $this->createMailingForm($request);
$mailingDto = $form->getData();
if ($form->isSubmitted()) {
$this->draftHandler->saveDraft($mailingDto);
}
if ($form->isSubmitted() && $form->isValid()) {
if (null !== $error = $this->mailingService->validateAttachments($mailingDto)) {
$this->addFlash('error', $error);
} else {
$this->mailingService->sendPreview($mailingDto, $this->getAuthenticatedUser());
$this->addFlash('success', sprintf(
'Die Vorschau wurde an %s gesendet',
$this->getAuthenticatedUser()->getUserIdentifier()
));
}
}
// no redirect after the preview mail, the composed mail has to survive it
return $this->render('administrative/assignment_mailing/compose.html.twig', [
'form' => $form->createView(),
'mailingDto' => $mailingDto,
'preview' => $this->renderPreview($mailingDto),
'templates' => $this->mailingTemplateRepository->findActive(),
'placeholders' => TeamerMailingService::PLACEHOLDERS,
'hasDraft' => $this->draftHandler->hasDraft(),
'returnUrl' => $this->getReturnUrl($request, 'app_administrative_assignment_index'),
] + $this->assignmentsContext($mailingDto) + $this->attachmentsContext($mailingDto));
}
}
@@ -0,0 +1,32 @@
<?php
namespace App\Controller\Administrative\AssignmentMailing;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Attribute\IsGranted;
class ConfirmController extends AbstractAssignmentMailingController
{
#[Route('/administrative/assignment/mailing/confirm', name: 'app_administrative_assignment_mailing_confirm', methods: ['POST'])]
#[IsGranted('ROLE_ADMINISTRATIVE')]
public function index(Request $request): Response
{
$form = $this->createMailingForm($request);
$mailingDto = $form->getData();
$this->draftHandler->saveDraft($mailingDto);
// Only the wording is carried on in hidden fields. Assignments, template and the dropped
// files are the draft's and the upload session's, which is where the send reads them.
return $this->render('administrative/assignment_mailing/modal_confirm.html.twig', [
'form' => $form->createView(),
'mailingDto' => $mailingDto,
'valid' => $form->isSubmitted() && $form->isValid(),
'attachmentError' => $this->mailingService->validateAttachments($mailingDto),
'attachmentSize' => $this->mailingService->getAttachmentSize($mailingDto),
'recipients' => $this->mailingService->resolveRecipients($mailingDto),
] + $this->attachmentsContext($mailingDto));
}
}
@@ -0,0 +1,21 @@
<?php
namespace App\Controller\Administrative\AssignmentMailing;
use App\Entity\Upload;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Attribute\IsGranted;
class DiscardController extends AbstractAssignmentMailingController
{
#[Route('/administrative/assignment/mailing/discard', name: 'app_administrative_assignment_mailing_discard')]
#[IsGranted('ROLE_ADMINISTRATIVE')]
public function index(): Response
{
$this->draftHandler->resetDraft();
$this->attachmentHandler->discardPending(Upload::TYPE_MAILING_ATTACHMENT);
return $this->redirectToRoute('app_administrative_assignment_index');
}
}
@@ -0,0 +1,26 @@
<?php
namespace App\Controller\Administrative\AssignmentMailing;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Attribute\IsGranted;
/**
* Parks the wording typed so far and answers with its preview, in one request for the same
* reason as the teamer mailing's draft route.
*/
class DraftController extends AbstractAssignmentMailingController
{
#[Route('/administrative/assignment/mailing/draft', name: 'app_administrative_assignment_mailing_draft', methods: ['POST'])]
#[IsGranted('ROLE_ADMINISTRATIVE')]
public function index(Request $request): Response
{
$mailingDto = $this->createMailingForm($request)->getData();
$this->draftHandler->saveDraft($mailingDto);
return $this->render('admin/teamer/_mailing_preview.html.twig', $this->renderPreview($mailingDto));
}
}
@@ -0,0 +1,29 @@
<?php
namespace App\Controller\Administrative\AssignmentMailing;
use App\Entity\Assignment;
use Symfony\Bridge\Doctrine\Attribute\MapEntity;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Attribute\IsGranted;
class RemoveAssignmentController extends AbstractAssignmentMailingController
{
#[Route('/administrative/assignment/mailing/remove/{uuid}', name: 'app_administrative_assignment_mailing_remove', methods: ['POST'])]
#[IsGranted('ROLE_ADMINISTRATIVE')]
public function index(
#[MapEntity(mapping: ['uuid' => 'uuid'])]
Assignment $assignment,
): Response {
$mailingDto = $this->draftHandler->getDraft();
$mailingDto->setAssignments(array_filter(
$mailingDto->getAssignments(),
fn (Assignment $selected) => $selected !== $assignment
));
$this->draftHandler->saveDraft($mailingDto);
return $this->render('administrative/assignment_mailing/_assignments.html.twig', $this->assignmentsContext($mailingDto));
}
}
@@ -0,0 +1,54 @@
<?php
namespace App\Controller\Administrative\AssignmentMailing;
use App\Htmx\HxRedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Attribute\IsGranted;
class SendController extends AbstractAssignmentMailingController
{
#[Route('/administrative/assignment/mailing/send', name: 'app_administrative_assignment_mailing_send', methods: ['POST'])]
#[IsGranted('ROLE_ADMINISTRATIVE')]
public function index(Request $request): Response
{
$form = $this->createMailingForm($request);
$mailingDto = $form->getData();
if (false === $form->isSubmitted() || false === $form->isValid()) {
return $this->backToCompose('Die Mail konnte nicht gesendet werden, Betreff oder Nachricht fehlen');
}
if (null !== $error = $this->mailingService->validateAttachments($mailingDto)) {
return $this->backToCompose($error);
}
$recipients = $this->mailingService->resolveRecipients($mailingDto);
if (0 === $recipients->getEligibleCount()) {
return $this->backToCompose('Die Mail konnte nicht gesendet werden, sie hat keine Empfänger:innen');
}
$this->mailingService->send($mailingDto, $recipients, $this->getAuthenticatedUser());
// it is on its way, the next mailing starts on a blank page
$this->draftHandler->resetDraft();
// not "wurde gesendet", see the teamer mailing: nothing has reached a mail server yet
$this->addFlash('success', sprintf(
'Die Mail wird an %d Teamer:innen gesendet',
$recipients->getEligibleCount()
));
return new HxRedirectResponse($this->generateUrl('app_administrative_assignment_index'));
}
private function backToCompose(string $error): Response
{
$this->addFlash('error', $error);
return new HxRedirectResponse($this->generateUrl('app_administrative_assignment_mailing_compose'));
}
}
@@ -0,0 +1,49 @@
<?php
namespace App\Controller\Administrative\AssignmentMailing;
use App\Form\AssignmentMailingType;
use App\Repository\MailingTemplateRepository;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Attribute\IsGranted;
/**
* Picks the template the mailing starts from: its subject and message replace what is in the
* form, and its files join the mailing. Picking none keeps the wording and drops the files.
*
* Answers with the subject and message fields, the attachments and the preview, the last two
* swapped out of band.
*/
class TemplateController extends AbstractAssignmentMailingController
{
public function __construct(private readonly MailingTemplateRepository $mailingTemplateRepository)
{
}
#[Route('/administrative/assignment/mailing/template', name: 'app_administrative_assignment_mailing_template', methods: ['POST'])]
#[IsGranted('ROLE_ADMINISTRATIVE')]
public function index(Request $request): Response
{
$mailingDto = $this->createMailingForm($request)->getData();
$template = $this->mailingTemplateRepository->findActiveByUuid((string) $request->request->get('template'));
$mailingDto->setTemplate($template);
if (null !== $template) {
$mailingDto
->setSubject($template->getSubject())
->setMessage($template->getMessage())
;
}
$this->draftHandler->saveDraft($mailingDto);
// a fresh form, so the fields show the template's wording rather than what was posted
return $this->render('administrative/assignment_mailing/template.html.twig', [
'form' => $this->createForm(AssignmentMailingType::class, $mailingDto)->createView(),
'preview' => $this->renderPreview($mailingDto),
] + $this->attachmentsContext($mailingDto));
}
}
@@ -0,0 +1,75 @@
<?php
namespace App\Controller\Administrative\System\MailingTemplate;
use App\Controller\Traits\AuthenticatedUserTrait;
use App\Entity\MailingTemplate;
use App\Entity\Upload;
use App\Form\MailingTemplateType;
use App\Service\Teamer\MailingAttachmentHandler;
use App\Service\Teamer\TeamerMailingDraftHandler;
use App\Service\Teamer\TeamerMailingService;
use Doctrine\ORM\EntityManagerInterface;
use Psr\Log\LoggerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Form\FormError;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Attribute\IsGranted;
class CreateController extends AbstractController
{
use AuthenticatedUserTrait;
public function __construct(
private readonly MailingAttachmentHandler $attachmentHandler,
private readonly EntityManagerInterface $entityManager,
private readonly LoggerInterface $logger,
) {
}
#[Route('/administrative/system/mailing-template/create', name: 'app_administrative_system_mailing_template_create')]
#[IsGranted('ROLE_ADMINISTRATIVE')]
public function index(Request $request): Response
{
$template = (new MailingTemplate())->setMessage(TeamerMailingDraftHandler::NEW_MESSAGE);
$form = $this->createForm(MailingTemplateType::class, $template);
$form->handleRequest($request);
// files left over from a template form that was never saved must not end up on this one
if (false === $form->isSubmitted()) {
$this->attachmentHandler->discardPending(Upload::TYPE_MAILING_TEMPLATE);
}
if ($form->isSubmitted() && $form->isValid()) {
if (null !== $error = $this->attachmentHandler->validateTemplateAttachments($template, [])) {
$form->addError(new FormError($error));
}
}
if ($form->isSubmitted() && $form->isValid()) {
$this->attachmentHandler->saveTemplateAttachments($template, [], $this->getAuthenticatedUser());
$this->entityManager->persist($template);
$this->entityManager->flush();
$this->addFlash('success', 'Die Mailvorlage wurde angelegt');
$this->logger->info('Create mailing template', [
'mailing_template_id' => $template->getId(),
'mailing_template_name' => $template->getName(),
'attachments' => $template->getAttachments()->count(),
]);
return $this->redirectToRoute('app_administrative_system_mailing_template_index');
}
return $this->render('administrative/system/mailing_template/create.html.twig', [
'form' => $form->createView(),
'template' => $template,
'pending' => $this->attachmentHandler->getPending(Upload::TYPE_MAILING_TEMPLATE),
'placeholders' => TeamerMailingService::PLACEHOLDERS,
'maxAttachmentBytes' => MailingAttachmentHandler::MAX_TOTAL_BYTES,
]);
}
}
@@ -0,0 +1,52 @@
<?php
namespace App\Controller\Administrative\System\MailingTemplate;
use App\Entity\MailingTemplate;
use App\Htmx\HxRedirectResponse;
use Doctrine\ORM\EntityManagerInterface;
use Psr\Log\LoggerInterface;
use Symfony\Bridge\Doctrine\Attribute\MapEntity;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Attribute\IsGranted;
/**
* Soft, so the mailings sent from the template keep pointing at it - and at its files, which are
* left where they are.
*/
class DeleteController extends AbstractController
{
public function __construct(
private readonly EntityManagerInterface $entityManager,
private readonly LoggerInterface $logger,
) {
}
#[Route('/administrative/system/mailing-template/delete/{uuid}', name: 'app_administrative_system_mailing_template_delete')]
#[IsGranted('ROLE_ADMINISTRATIVE')]
public function index(
#[MapEntity(mapping: ['uuid' => 'uuid'])]
MailingTemplate $template,
Request $request,
): Response {
if (true === $request->isMethod('POST')) {
$template->setDeleted();
$this->entityManager->flush();
$this->addFlash('success', 'Die Mailvorlage wurde gelöscht');
$this->logger->info('Delete mailing template', [
'mailing_template_id' => $template->getId(),
'mailing_template_name' => $template->getName(),
]);
return new HxRedirectResponse($this->generateUrl('app_administrative_system_mailing_template_index'));
}
return $this->render('administrative/system/mailing_template/modal_delete.html.twig', [
'template' => $template,
]);
}
}
@@ -0,0 +1,85 @@
<?php
namespace App\Controller\Administrative\System\MailingTemplate;
use App\Controller\Traits\AuthenticatedUserTrait;
use App\Entity\MailingTemplate;
use App\Entity\Upload;
use App\Form\MailingTemplateType;
use App\Service\Teamer\MailingAttachmentHandler;
use App\Service\Teamer\TeamerMailingService;
use Doctrine\ORM\EntityManagerInterface;
use Psr\Log\LoggerInterface;
use Symfony\Bridge\Doctrine\Attribute\MapEntity;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Form\FormError;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Attribute\IsGranted;
class EditController extends AbstractController
{
use AuthenticatedUserTrait;
public function __construct(
private readonly MailingAttachmentHandler $attachmentHandler,
private readonly EntityManagerInterface $entityManager,
private readonly LoggerInterface $logger,
) {
}
#[Route('/administrative/system/mailing-template/edit/{uuid}', name: 'app_administrative_system_mailing_template_edit')]
#[IsGranted('ROLE_ADMINISTRATIVE')]
public function index(
#[MapEntity(mapping: ['uuid' => 'uuid'])]
MailingTemplate $template,
Request $request,
): Response {
if (true === $template->isDeleted()) {
throw $this->createNotFoundException('Die Mailvorlage wurde gelöscht');
}
$form = $this->createForm(MailingTemplateType::class, $template);
$form->handleRequest($request);
// files left over from a template form that was never saved must not end up on this one
if (false === $form->isSubmitted()) {
$this->attachmentHandler->discardPending(Upload::TYPE_MAILING_TEMPLATE);
}
/** @var Upload[] $remove */
$remove = $form->has('removeAttachments')
? iterator_to_array($form->get('removeAttachments')->getData() ?? [], false)
: [];
if ($form->isSubmitted() && $form->isValid()) {
if (null !== $error = $this->attachmentHandler->validateTemplateAttachments($template, $remove)) {
$form->addError(new FormError($error));
}
}
if ($form->isSubmitted() && $form->isValid()) {
$this->attachmentHandler->saveTemplateAttachments($template, $remove, $this->getAuthenticatedUser());
$this->entityManager->flush();
$this->addFlash('success', 'Die Mailvorlage wurde aktualisiert');
$this->logger->info('Edit mailing template', [
'mailing_template_id' => $template->getId(),
'mailing_template_name' => $template->getName(),
'attachments' => $template->getAttachments()->count(),
'attachments_removed' => count($remove),
]);
return $this->redirectToRoute('app_administrative_system_mailing_template_index');
}
return $this->render('administrative/system/mailing_template/edit.html.twig', [
'form' => $form->createView(),
'template' => $template,
'pending' => $this->attachmentHandler->getPending(Upload::TYPE_MAILING_TEMPLATE),
'placeholders' => TeamerMailingService::PLACEHOLDERS,
'maxAttachmentBytes' => MailingAttachmentHandler::MAX_TOTAL_BYTES,
]);
}
}
@@ -0,0 +1,25 @@
<?php
namespace App\Controller\Administrative\System\MailingTemplate;
use App\Repository\MailingTemplateRepository;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Attribute\IsGranted;
class IndexController extends AbstractController
{
public function __construct(private readonly MailingTemplateRepository $mailingTemplateRepository)
{
}
#[Route('/administrative/system/mailing-template', name: 'app_administrative_system_mailing_template_index')]
#[IsGranted('ROLE_ADMINISTRATIVE')]
public function index(): Response
{
return $this->render('administrative/system/mailing_template/index.html.twig', [
'templates' => $this->mailingTemplateRepository->findActive(),
]);
}
}
+165
View File
@@ -0,0 +1,165 @@
<?php
namespace App\Entity;
use App\Entity\Traits\BlameableEntity;
use App\Entity\Traits\SoftDeletableEntity;
use App\Entity\Traits\TimestampableEntity;
use App\Repository\MailingRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Uid\Uuid;
/**
* The record of one assignment mailing as it was sent: wording after any change made for it,
* the assignments it went to and every file attached. Blameable names the sender, createdAt is
* when it was handed to the queue.
*
* It is also what owns the files added to this one mailing - they belong to no template, and the
* worker reads them by path after the request that sent the mailing has long ended.
*/
#[ORM\Entity(repositoryClass: MailingRepository::class)]
class Mailing implements BlameableEntityInterface, TimestampableEntityInterface, SoftDeletableEntityInterface
{
use BlameableEntity;
use TimestampableEntity;
use SoftDeletableEntity;
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
private ?int $id = null;
#[ORM\Column(type: 'string', length: 36, unique: true)]
private string $uuid;
#[ORM\Column(length: 255)]
private ?string $subject = null;
#[ORM\Column(type: Types::TEXT)]
private ?string $message = null;
#[ORM\ManyToOne]
private ?MailingTemplate $template = null;
/**
* @var Collection<int, Assignment>
*/
#[ORM\ManyToMany(targetEntity: Assignment::class)]
#[ORM\JoinTable(name: 'mailing_assignment')]
private Collection $assignments;
/**
* The template's files and the ones added to this mailing alike. A template file is shared
* with every mailing that sent it, which is why this is not a column on Upload.
*
* @var Collection<int, Upload>
*/
#[ORM\ManyToMany(targetEntity: Upload::class)]
#[ORM\JoinTable(name: 'mailing_attachment')]
private Collection $attachments;
#[ORM\Column]
private int $recipientCount = 0;
public function __construct()
{
$this->uuid = Uuid::v4();
$this->assignments = new ArrayCollection();
$this->attachments = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getUuid(): string
{
return $this->uuid;
}
public function getSubject(): ?string
{
return $this->subject;
}
public function setSubject(?string $subject): static
{
$this->subject = $subject;
return $this;
}
public function getMessage(): ?string
{
return $this->message;
}
public function setMessage(?string $message): static
{
$this->message = $message;
return $this;
}
public function getTemplate(): ?MailingTemplate
{
return $this->template;
}
public function setTemplate(?MailingTemplate $template): static
{
$this->template = $template;
return $this;
}
/**
* @return Collection<int, Assignment>
*/
public function getAssignments(): Collection
{
return $this->assignments;
}
public function addAssignment(Assignment $assignment): static
{
if (!$this->assignments->contains($assignment)) {
$this->assignments->add($assignment);
}
return $this;
}
/**
* @return Collection<int, Upload>
*/
public function getAttachments(): Collection
{
return $this->attachments;
}
public function addAttachment(Upload $attachment): static
{
if (!$this->attachments->contains($attachment)) {
$this->attachments->add($attachment);
}
return $this;
}
public function getRecipientCount(): int
{
return $this->recipientCount;
}
public function setRecipientCount(int $recipientCount): static
{
$this->recipientCount = $recipientCount;
return $this;
}
}
+144
View File
@@ -0,0 +1,144 @@
<?php
namespace App\Entity;
use App\Entity\Traits\BlameableEntity;
use App\Entity\Traits\SoftDeletableEntity;
use App\Entity\Traits\TimestampableEntity;
use App\Repository\MailingTemplateRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Uid\Uuid;
use Symfony\Component\Validator\Constraints as Assert;
/**
* A reusable starting point for an assignment mailing, shared by all managers and admins.
*
* Picking it fills subject and message of a mailing, which can then be changed for that one
* mailing without touching the template. Its attachments always go out with the mailing.
*/
#[ORM\Entity(repositoryClass: MailingTemplateRepository::class)]
class MailingTemplate implements BlameableEntityInterface, TimestampableEntityInterface, SoftDeletableEntityInterface
{
use BlameableEntity;
use TimestampableEntity;
use SoftDeletableEntity;
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
private ?int $id = null;
#[ORM\Column(type: 'string', length: 36, unique: true)]
private string $uuid;
#[ORM\Column(length: 255)]
#[Assert\NotBlank(message: 'Bitte gib einen Namen an')]
private ?string $name = null;
#[ORM\Column(length: 255)]
#[Assert\NotBlank(message: 'Bitte gib einen Betreff an')]
private ?string $subject = null;
#[ORM\Column(type: Types::TEXT)]
#[Assert\NotBlank(message: 'Bitte gib eine Nachricht ein')]
private ?string $message = null;
/**
* @var Collection<int, Upload>
*/
#[ORM\OneToMany(targetEntity: Upload::class, mappedBy: 'mailingTemplate')]
#[ORM\OrderBy(['id' => \SortDirection::Ascending])]
private Collection $attachments;
public function __construct()
{
$this->uuid = Uuid::v4();
$this->attachments = new ArrayCollection();
}
public function __toString(): string
{
return (string) $this->name;
}
public function getId(): ?int
{
return $this->id;
}
public function getUuid(): string
{
return $this->uuid;
}
public function getName(): ?string
{
return $this->name;
}
public function setName(?string $name): static
{
$this->name = $name;
return $this;
}
public function getSubject(): ?string
{
return $this->subject;
}
public function setSubject(?string $subject): static
{
$this->subject = $subject;
return $this;
}
public function getMessage(): ?string
{
return $this->message;
}
public function setMessage(?string $message): static
{
$this->message = $message;
return $this;
}
/**
* @return Collection<int, Upload>
*/
public function getAttachments(): Collection
{
return $this->attachments;
}
public function addAttachment(Upload $attachment): static
{
if (!$this->attachments->contains($attachment)) {
$this->attachments->add($attachment);
$attachment->setMailingTemplate($this);
}
return $this;
}
public function removeAttachment(Upload $attachment): static
{
if ($this->attachments->removeElement($attachment) && $attachment->getMailingTemplate() === $this) {
$attachment->setMailingTemplate(null);
}
return $this;
}
public function getAttachmentSize(): int
{
return array_sum($this->attachments->map(fn (Upload $upload) => (int) $upload->getSize())->toArray());
}
}
+30
View File
@@ -43,6 +43,21 @@ class Upload implements BlameableEntityInterface, TimestampableEntityInterface
*/
public const TYPE_WORK_MONTH = 'work_month';
/**
* A PDF of a mailing template, sent with every mailing that starts from it.
*
* Kept apart from TYPE_MAILING_ATTACHMENT although both end up attached to a Mailing: files
* waiting in the upload session are told apart by type only, and a file dropped on the
* compose page must not be saved to the template edited in another tab, or the reverse.
* Neither is readable by teamers through the portal - they get it by mail.
*/
public const TYPE_MAILING_TEMPLATE = 'mailing_template';
/**
* A PDF added to one single assignment mailing, on top of its template's files.
*/
public const TYPE_MAILING_ATTACHMENT = 'mailing_attachment';
public const STATUS_NEW = 'new';
public const STATUS_PENDING = 'pending';
public const STATUS_CHECKED = 'checked';
@@ -98,6 +113,9 @@ class Upload implements BlameableEntityInterface, TimestampableEntityInterface
#[ORM\ManyToOne(inversedBy: 'documents')]
private ?TeamerWorkMonth $teamerWorkMonth = null;
#[ORM\ManyToOne(inversedBy: 'attachments')]
private ?MailingTemplate $mailingTemplate = null;
#[ORM\Column(type: Types::TEXT, nullable: true)]
private ?string $comment = null;
@@ -319,6 +337,18 @@ class Upload implements BlameableEntityInterface, TimestampableEntityInterface
return $this;
}
public function getMailingTemplate(): ?MailingTemplate
{
return $this->mailingTemplate;
}
public function setMailingTemplate(?MailingTemplate $mailingTemplate): static
{
$this->mailingTemplate = $mailingTemplate;
return $this;
}
public function getComment(): ?string
{
return $this->comment;
+27
View File
@@ -0,0 +1,27 @@
<?php
namespace App\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
/**
* Subject and message of a mail written for teamers - the teamer mailing, the assignment mailing
* and the templates the latter starts from.
*/
abstract class AbstractMailingType extends AbstractType
{
protected function addMailFields(FormBuilderInterface $builder): void
{
$builder
->add('subject', TextType::class, [
'label' => 'Betreff',
])
->add('message', AutosizeTextareaType::class, [
'label' => 'Nachricht',
'min_rows' => 12,
])
;
}
}
+28
View File
@@ -0,0 +1,28 @@
<?php
namespace App\Form;
use App\Entity\Assignment;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
/**
* Adds one assignment to the mailing being composed - for the one that was not on the page of
* the overview the mailing was started from.
*/
class AssignmentMailingAddType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder
->add('assignment', AutocompleteEntityType::class, [
'label' => 'Einsatz hinzufügen',
'class' => Assignment::class,
'identifier' => 'uuid',
'required' => false,
'placeholder' => 'Datum, Reise, Hotel oder Jobprofil',
'endpoint_route' => 'app_admin_autocomplete_assignment',
])
;
}
}
+28
View File
@@ -0,0 +1,28 @@
<?php
namespace App\Form;
use App\Model\AssignmentMailingDto;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
/**
* Only the wording travels in this form. Assignments and template are picked through their own
* htmx actions and kept in the draft, see App\Service\Teamer\AssignmentMailingDraftHandler.
*/
class AssignmentMailingType extends AbstractMailingType
{
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$this->addMailFields($builder);
}
public function configureOptions(OptionsResolver $resolver): void
{
$resolver
->setDefaults([
'data_class' => AssignmentMailingDto::class,
])
;
}
}
+53
View File
@@ -0,0 +1,53 @@
<?php
namespace App\Form;
use App\Entity\MailingTemplate;
use App\Entity\Upload;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
class MailingTemplateType extends AbstractMailingType
{
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder
->add('name', TextType::class, [
'label' => 'Name der Vorlage',
'help' => 'Nur intern, die Teamer:innen sehen ihn nicht',
])
;
$this->addMailFields($builder);
/** @var MailingTemplate|null $template */
$template = $options['data'] ?? null;
// Ticked files come off the template on save, together with everything else in the
// form - removing one right away would reload the page and lose unsaved changes.
if (null !== $template && false === $template->getAttachments()->isEmpty()) {
$builder->add('removeAttachments', EntityType::class, [
'label' => false,
'class' => Upload::class,
'choices' => $template->getAttachments()->toArray(),
'choice_value' => 'uuid',
'choice_label' => fn (Upload $upload) => $upload->getDisplayName() ?? $upload->getOriginalFilename(),
'multiple' => true,
'expanded' => true,
'mapped' => false,
'required' => false,
]);
}
}
public function configureOptions(OptionsResolver $resolver): void
{
$resolver
->setDefaults([
'data_class' => MailingTemplate::class,
])
;
}
}
+2 -12
View File
@@ -3,24 +3,14 @@
namespace App\Form;
use App\Model\TeamerMailingDto;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
class TeamerMailingType extends AbstractType
class TeamerMailingType extends AbstractMailingType
{
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder
->add('subject', TextType::class, [
'label' => 'Betreff',
])
->add('message', AutosizeTextareaType::class, [
'label' => 'Nachricht',
'min_rows' => 12,
])
;
$this->addMailFields($builder);
}
public function configureOptions(OptionsResolver $resolver): void
+11
View File
@@ -355,6 +355,17 @@ class AdminMenuBuilder extends AbstractMenuBuilder
],
],
]);
$settingsMenu->addChild('Mailvorlagen', [
'route' => 'app_administrative_system_mailing_template_index',
'linkAttributes' => [
'title' => 'Mailvorlagen',
],
'extras' => [
'routes' => [
['pattern' => '/^app_administrative_system_mailing_template_/'],
],
],
]);
$settingsMenu->addChild('Ansprechpersonen', [
'route' => 'app_admin_system_contact_index',
'linkAttributes' => [
+11
View File
@@ -233,6 +233,17 @@ class ManagerMenuBuilder extends AbstractMenuBuilder
],
],
]);
$settingsMenu->addChild('Mailvorlagen', [
'route' => 'app_administrative_system_mailing_template_index',
'linkAttributes' => [
'title' => 'Mailvorlagen',
],
'extras' => [
'routes' => [
['pattern' => '/^app_administrative_system_mailing_template_/'],
],
],
]);
$this->addAdminItem($menu);
$this->addTeamerItem($menu);
+24 -3
View File
@@ -12,21 +12,33 @@ use App\Model\TeamerMailingRecipientsDto;
* the one the confirmation modal showed, and the filter itself carries hydrated entities
* that have no business being serialized into a queue row. Plain arrays also survive a
* deploy that changes TeamerMailingRecipient while messages are still queued.
*
* 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.
*/
class SendTeamerMailing
{
/**
* @param array<int, array{email: string, firstName: string, lastName: string, fullName: string}> $recipients
* @param array<int, array{path: string, name: string}> $attachments
*/
public function __construct(
private readonly string $subject,
private readonly string $message,
private readonly array $recipients,
private readonly array $attachments = [],
) {
}
public static function fromRecipients(string $subject, string $message, TeamerMailingRecipientsDto $recipients): self
{
/**
* @param array<int, array{path: string, name: string}> $attachments
*/
public static function fromRecipients(
string $subject,
string $message,
TeamerMailingRecipientsDto $recipients,
array $attachments = [],
): self {
$snapshot = [];
foreach ($recipients->getEligible() as $recipient) {
@@ -43,7 +55,7 @@ class SendTeamerMailing
];
}
return new self($subject, $message, $snapshot);
return new self($subject, $message, $snapshot, $attachments);
}
public function getSubject(): string
@@ -64,6 +76,15 @@ class SendTeamerMailing
return $this->recipients;
}
/**
* @return array<int, array{path: string, name: string}>
*/
public function getAttachments(): array
{
// a mailing queued before attachments existed unserializes without the property
return $this->attachments ?? [];
}
public function getRecipientCount(): int
{
return count($this->recipients);
+50
View File
@@ -0,0 +1,50 @@
<?php
namespace App\Model;
use App\Entity\Assignment;
use App\Entity\MailingTemplate;
/**
* A teamer mailing addressed by assignment: subject and message as in the teamer mailing, plus
* the assignments whose confirmed teamers it goes to and the template it started from.
*/
class AssignmentMailingDto extends TeamerMailingDto
{
private ?MailingTemplate $template = null;
/**
* @var Assignment[]
*/
private array $assignments = [];
public function getTemplate(): ?MailingTemplate
{
return $this->template;
}
public function setTemplate(?MailingTemplate $template): static
{
$this->template = $template;
return $this;
}
/**
* @return Assignment[]
*/
public function getAssignments(): array
{
return $this->assignments;
}
/**
* @param Assignment[] $assignments
*/
public function setAssignments(array $assignments): static
{
$this->assignments = array_values($assignments);
return $this;
}
}
+92
View File
@@ -62,6 +62,98 @@ class AssignmentRepository extends ServiceEntityRepository
return $qb->getQuery();
}
/**
* The assignments a mailing can go to, of those given: not deleted, and with at least one
* confirmed teamer - an assignment without one would only make the recipient count look
* wrong. In the order of the overview, by travel date.
*
* @param string[] $uuids
*
* @return Assignment[]
*/
public function findForMailing(array $uuids): array
{
if ([] === $uuids) {
return [];
}
$qb = $this->createQueryBuilder('assignment');
return $qb
->select('assignment', 'destination', 'job_profile')
->innerJoin('assignment.destination', 'destination')
->leftJoin('assignment.jobProfile', 'job_profile')
->where($qb->expr()->andX(
$qb->expr()->in('assignment.uuid', ':uuids'),
$qb->expr()->isNull('assignment.deletedAt'),
$this->hasConfirmedDisposition()
))
->setParameter('uuids', $uuids)
->setParameter('confirmed', Disposition::STATUS_CONFIRMED)
->orderBy('destination.dateFrom', \SortDirection::Ascending)
->addOrderBy('assignment.id', \SortDirection::Ascending)
->getQuery()
->getResult()
;
}
/**
* Assignments to add to a mailing: not deleted, not over yet and with a confirmed teamer, the
* same as findForMailing(). Searched like the destination autocomplete, plus the job profile.
*
* @return array<int, array{value: string, text: string}>
*/
public function getMailingAutocompletionData(string $search): array
{
$qb = $this->createQueryBuilder('assignment');
$assignments = $qb
->select('assignment', 'destination', 'job_profile')
->innerJoin('assignment.destination', 'destination')
->innerJoin('assignment.jobProfile', 'job_profile')
->where($qb->expr()->andX(
$qb->expr()->isNull('assignment.deletedAt'),
$qb->expr()->gte('destination.dateTo', ':today'),
$this->hasConfirmedDisposition(),
$qb->expr()->orX(
$qb->expr()->like('destination.product', ':search'),
$qb->expr()->like('destination.hotel', ':search'),
$qb->expr()->like('job_profile.name', ':search'),
$qb->expr()->like('DATE_FORMAT(destination.dateFrom, \'%d.%m.%y\')', ':search')
)
))
->setParameter('today', new \DateTimeImmutable('today'))
->setParameter('search', '%'.$this->escapeLikeWildcards($search).'%')
->setParameter('confirmed', Disposition::STATUS_CONFIRMED)
->orderBy('destination.dateFrom', \SortDirection::Ascending)
->addOrderBy('assignment.id', \SortDirection::Ascending)
->setMaxResults(30)
->getQuery()
->getResult()
;
return array_map(fn (Assignment $assignment) => [
'value' => $assignment->getUuid(),
'text' => sprintf(
'%s · %s · %s',
$assignment->getDestination(),
$assignment->getDestination()?->getHotel(),
$assignment->getJobProfile()?->getName()
),
], $assignments);
}
/**
* DQL for "assignment has a confirmed disposition"; the caller binds :confirmed.
*/
private function hasConfirmedDisposition(): string
{
return sprintf(
'EXISTS (SELECT confirmed_disposition.id FROM %s confirmed_disposition WHERE confirmed_disposition.assignment = assignment AND confirmed_disposition.status = :confirmed)',
Disposition::class
);
}
public function getListQueryForTeamer(Teamer $teamer, AssignmentFilterDto $filterDto): Query
{
// Find ids of assignments with available slots first
+42
View File
@@ -0,0 +1,42 @@
<?php
namespace App\Repository;
use App\Entity\Mailing;
use App\Entity\Upload;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
/**
* @extends ServiceEntityRepository<Mailing>
*
* @method Mailing|null find($id, $lockMode = null, $lockVersion = null)
* @method Mailing|null findOneBy(array $criteria, array $orderBy = null)
* @method Mailing[] findAll()
* @method Mailing[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
*/
class MailingRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, Mailing::class);
}
/**
* Whether a sent mailing still points at this file, in which case removing it from its
* template must leave the file and its row alone.
*/
public function hasAttachment(Upload $upload): bool
{
$qb = $this->createQueryBuilder('mailing');
return 0 < (int) $qb
->select('COUNT(mailing.id)')
->innerJoin('mailing.attachments', 'attachment')
->where($qb->expr()->eq('attachment', ':upload'))
->setParameter('upload', $upload)
->getQuery()
->getSingleScalarResult()
;
}
}
@@ -0,0 +1,36 @@
<?php
namespace App\Repository;
use App\Entity\MailingTemplate;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
/**
* @extends ServiceEntityRepository<MailingTemplate>
*
* @method MailingTemplate|null find($id, $lockMode = null, $lockVersion = null)
* @method MailingTemplate|null findOneBy(array $criteria, array $orderBy = null)
* @method MailingTemplate[] findAll()
* @method MailingTemplate[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
*/
class MailingTemplateRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, MailingTemplate::class);
}
/**
* @return MailingTemplate[]
*/
public function findActive(): array
{
return $this->findBy(['deletedAt' => null], ['name' => 'ASC']);
}
public function findActiveByUuid(string $uuid): ?MailingTemplate
{
return $this->findOneBy(['uuid' => $uuid, 'deletedAt' => null]);
}
}
+53
View File
@@ -2,6 +2,8 @@
namespace App\Repository;
use App\Entity\Assignment;
use App\Entity\Disposition;
use App\Entity\License;
use App\Entity\Teamer;
use App\Model\TeamerFilterDto;
@@ -75,6 +77,57 @@ class TeamerRepository extends ServiceEntityRepository
return array_map(TeamerMailingRecipient::fromRow(...), $rows);
}
/**
* The teamers with a confirmed disposition on any of the given assignments, each once
* however many of them they are on. Same projection as getMailingRecipients().
*
* @param Assignment[] $assignments
*
* @return TeamerMailingRecipient[]
*/
public function getAssignmentMailingRecipients(array $assignments): array
{
if ([] === $assignments) {
return [];
}
return array_map(
TeamerMailingRecipient::fromRow(...),
$this->createAssignmentMailingQueryBuilder($assignments)->getQuery()->getArrayResult()
);
}
/**
* @param Assignment[] $assignments
*/
public function createAssignmentMailingQueryBuilder(array $assignments): QueryBuilder
{
$qb = $this->createQueryBuilder('teamer');
return $qb
->distinct()
->select(
'teamer.id AS id',
'teamer.firstName AS firstName',
'teamer.lastName AS lastName',
'teamer.communication.email AS email',
'teamer.deletedAt AS deletedAt',
'user.disabledAt AS disabledAt'
)
->innerJoin('teamer.dispositions', 'disposition')
->leftJoin('teamer.user', 'user')
->where($qb->expr()->andX(
$qb->expr()->in('disposition.assignment', ':assignments'),
$qb->expr()->eq('disposition.status', ':status')
))
->setParameter('assignments', $assignments)
->setParameter('status', Disposition::STATUS_CONFIRMED)
// the compose page lists the names in this order
->addOrderBy('teamer.lastName', \SortDirection::Ascending)
->addOrderBy('teamer.firstName', \SortDirection::Ascending)
;
}
private function createListQueryBuilder(TeamerFilterDto $filterDto): QueryBuilder
{
$qb = $this->createQueryBuilder('teamer');
@@ -0,0 +1,111 @@
<?php
namespace App\Service\Teamer;
use App\Entity\Assignment;
use App\Model\AssignmentMailingDto;
use App\Repository\AssignmentRepository;
use App\Repository\MailingTemplateRepository;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
/**
* Keeps the assignment mailing being composed in the session, the same way
* TeamerMailingDraftHandler keeps the teamer mailing.
*
* Assignments and template are kept by uuid and looked up again on every read, so one that is
* deleted - or no longer has a confirmed teamer - while the mailing is composed simply drops out
* of it.
*/
class AssignmentMailingDraftHandler
{
private const NAMESPACE = 'mailing:assignment';
public function __construct(
private readonly RequestStack $requestStack,
private readonly AssignmentRepository $assignmentRepository,
private readonly MailingTemplateRepository $mailingTemplateRepository,
) {
}
/**
* A new mailing for the given assignments, replacing whatever was composed before: picking
* assignments on the overview is the start of a mailing, not an addition to the last one.
*
* Assignments nobody is confirmed on are left out right here, see
* AssignmentRepository::findForMailing().
*
* @param string[] $assignmentUuids
*
* @return int how many of the given assignments were left out
*/
public function startDraft(array $assignmentUuids): int
{
$assignmentUuids = array_values(array_unique($assignmentUuids));
$assignments = $this->assignmentRepository->findForMailing($assignmentUuids);
$this->getSession()->set(self::NAMESPACE, [
'assignments' => array_map(fn (Assignment $assignment) => $assignment->getUuid(), $assignments),
'template' => null,
'subject' => null,
'message' => TeamerMailingDraftHandler::NEW_MESSAGE,
]);
return count($assignmentUuids) - count($assignments);
}
public function getDraft(): AssignmentMailingDto
{
$data = $this->getSession()->get(self::NAMESPACE) ?? [
'message' => TeamerMailingDraftHandler::NEW_MESSAGE,
];
$template = null !== ($data['template'] ?? null)
? $this->mailingTemplateRepository->findActiveByUuid($data['template'])
: null;
return (new AssignmentMailingDto())
->setSubject($data['subject'] ?? null)
->setMessage($data['message'] ?? null)
->setTemplate($template)
->setAssignments($this->findAssignments($data['assignments'] ?? []))
;
}
public function hasDraft(): bool
{
return $this->getSession()->has(self::NAMESPACE);
}
public function saveDraft(AssignmentMailingDto $mailingDto): void
{
$this->getSession()->set(self::NAMESPACE, [
'assignments' => array_map(fn (Assignment $assignment) => $assignment->getUuid(), $mailingDto->getAssignments()),
'template' => $mailingDto->getTemplate()?->getUuid(),
'subject' => $mailingDto->getSubject(),
'message' => $mailingDto->getMessage(),
]);
}
public function resetDraft(): void
{
$this->getSession()->remove(self::NAMESPACE);
}
/**
* @param string[] $uuids
*
* @return Assignment[]
*/
private function findAssignments(array $uuids): array
{
// looked up again on every read, so an assignment whose last confirmed teamer was called
// off while the mailing is composed drops out of it as well
return $this->assignmentRepository->findForMailing($uuids);
}
private function getSession(): SessionInterface
{
return $this->requestStack->getSession();
}
}
@@ -0,0 +1,115 @@
<?php
namespace App\Service\Teamer;
use App\Entity\Mailing;
use App\Entity\Upload;
use App\Entity\User;
use App\Message\SendTeamerMailing;
use App\Model\AssignmentMailingDto;
use App\Model\TeamerMailingRecipientsDto;
use Doctrine\ORM\EntityManagerInterface;
use Psr\Log\LoggerInterface;
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.
*/
class AssignmentMailingService
{
public function __construct(
private readonly TeamerMailingService $teamerMailingService,
private readonly MailingAttachmentHandler $attachmentHandler,
private readonly EntityManagerInterface $entityManager,
private readonly MessageBusInterface $messageBus,
private readonly LoggerInterface $logger,
) {
}
public function resolveRecipients(AssignmentMailingDto $mailingDto): TeamerMailingRecipientsDto
{
return $this->teamerMailingService->resolveAssignmentRecipients($mailingDto->getAssignments());
}
/**
* The template's files plus the ones dropped for this mailing, in bytes.
*/
public function getAttachmentSize(AssignmentMailingDto $mailingDto): int
{
return (int) $mailingDto->getTemplate()?->getAttachmentSize()
+ $this->attachmentHandler->getPendingSize(Upload::TYPE_MAILING_ATTACHMENT);
}
/**
* Why the mailing cannot go out with its attachments as they stand, or null when it can.
* Shared by the preview, the confirmation and the send, so none of them lets through what
* another would stop.
*/
public function validateAttachments(AssignmentMailingDto $mailingDto): ?string
{
return $this->attachmentHandler->validate(
Upload::TYPE_MAILING_ATTACHMENT,
(int) $mailingDto->getTemplate()?->getAttachmentSize()
);
}
public function sendPreview(AssignmentMailingDto $mailingDto, User $user): void
{
$this->teamerMailingService->sendPreview(
$mailingDto,
$user,
$this->attachmentHandler->toPreviewAttachments($mailingDto->getTemplate())
);
}
/**
* 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.
*
* The caller has made sure that no pending file has gone missing and the limit is kept.
*/
public function send(AssignmentMailingDto $mailingDto, TeamerMailingRecipientsDto $recipients, User $sender): Mailing
{
$attachments = [
...($mailingDto->getTemplate()?->getAttachments()->toArray() ?? []),
...$this->attachmentHandler->storePending(Upload::TYPE_MAILING_ATTACHMENT, $sender),
];
$mailing = (new Mailing())
->setSubject((string) $mailingDto->getSubject())
->setMessage((string) $mailingDto->getMessage())
->setTemplate($mailingDto->getTemplate())
->setRecipientCount($recipients->getEligibleCount())
;
foreach ($mailingDto->getAssignments() as $assignment) {
$mailing->addAssignment($assignment);
}
foreach ($attachments as $attachment) {
$mailing->addAttachment($attachment);
}
$this->entityManager->persist($mailing);
$this->entityManager->flush();
$this->messageBus->dispatch(SendTeamerMailing::fromRecipients(
(string) $mailingDto->getSubject(),
(string) $mailingDto->getMessage(),
$recipients,
$this->attachmentHandler->toMessageAttachments($attachments)
));
$this->logger->info('Send assignment mailing', [
'mailing_id' => $mailing->getId(),
'template_id' => $mailing->getTemplate()?->getId(),
'assignment_ids' => $mailing->getAssignments()->map(fn ($assignment) => $assignment->getId())->toArray(),
'attachments' => count($attachments),
'recipients' => $mailing->getRecipientCount(),
]);
return $mailing;
}
}
@@ -0,0 +1,247 @@
<?php
namespace App\Service\Teamer;
use App\Email\EmailAttachmentInterface;
use App\Entity\MailingTemplate;
use App\Entity\Upload;
use App\Entity\User;
use App\Model\EmailAttachmentDto;
use App\Model\EmailPathAttachmentDto;
use App\Model\UploadDto;
use App\Repository\MailingRepository;
use App\Service\Upload\UploadHandler;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\EntityManagerInterface;
use Flagception\Manager\FeatureManagerInterface;
/**
* The PDFs of mailing templates and assignment mailings: the ones dropped on a page and still
* waiting in the upload session, and the stored ones they become on save or send.
*
* The pending files are addressed by type - Upload::TYPE_MAILING_TEMPLATE on the template form,
* Upload::TYPE_MAILING_ATTACHMENT on the compose page - so the two pages never take each
* other's files.
*/
class MailingAttachmentHandler
{
/**
* What all attachments of one mail may add up to. Mailjet refuses a message over 15 MB, and
* base64 makes every attachment about a third larger on the way, so 10 MB of files is what
* still fits with the mail itself.
*/
public const MAX_TOTAL_BYTES = 10 * 1024 * 1024;
public function __construct(
private readonly UploadHandler $uploadHandler,
private readonly MailingRepository $mailingRepository,
private readonly EntityManagerInterface $entityManager,
private readonly FeatureManagerInterface $featureManager,
) {
}
/**
* @return Collection<int, UploadDto>
*/
public function getPending(string $type): Collection
{
return $this->uploadHandler->getUploadSession()->getUploadsByType($type);
}
public function getPendingSize(string $type): int
{
return array_sum($this->getPending($type)->map(fn (UploadDto $upload) => $upload->getSize())->toArray());
}
public function discardPending(string $type): void
{
$this->uploadHandler->removeUploadSessionUploadsByType($type);
}
/**
* Why the attachments of a mail cannot go out, or null when they can: a pending file that
* has gone from the orphanage, or the total over MAX_TOTAL_BYTES.
*
* @param int $storedSize the files that are already stored, before the pending ones of $type
*/
public function validate(string $type, int $storedSize): ?string
{
if ([] !== $missing = $this->pruneMissingPending($type)) {
return sprintf(
'Bitte lade %s noch einmal hoch, sie liegt nicht mehr bereit',
implode(', ', $missing)
);
}
$size = $storedSize + $this->getPendingSize($type);
if ($size > self::MAX_TOTAL_BYTES) {
return sprintf(
'Die Anhänge sind zusammen %s groß, erlaubt sind %s - sonst kommt die Mail nicht an',
$this->formatBytes($size),
$this->formatBytes(self::MAX_TOTAL_BYTES)
);
}
return null;
}
/**
* Drops the session entries of pending files no longer in the orphanage - they are cleared
* away after the orphanage maxage - and returns their original names.
*
* @return string[]
*/
private function pruneMissingPending(string $type): array
{
$missing = [];
foreach ($this->getPending($type) as $upload) {
if (null === $this->uploadHandler->findOrphanageFilepath($type, $upload->getFilename())) {
$missing[] = $upload->getOriginalFilename();
$this->uploadHandler->removeUploadFromSession($upload->getUuid());
}
}
return $missing;
}
/**
* Turns the pending files into stored uploads and empties the session of them. The caller
* checks validate() first, so every file is still there to be moved.
*
* @return Upload[] persisted, not flushed
*/
public function storePending(string $type, User $owner): array
{
$uploadSession = $this->uploadHandler->getUploadSession();
$uploads = [];
foreach ($this->getPending($type) as $uploadDto) {
$upload = Upload::fromUploadDto($uploadDto, $owner, $type);
$this->entityManager->persist($upload);
$uploads[] = $upload;
}
if ([] === $uploads) {
return [];
}
$this->uploadHandler->moveUploadSessionFilesFromOrphanage($type, $uploadSession);
$this->discardPending($type);
if (true === $this->featureManager->isActive('sanitize_uploads')) {
foreach ($uploads as $upload) {
$this->uploadHandler->ensurePdf($upload);
}
}
return $uploads;
}
/**
* validate() for a template about to be saved.
*
* @param Upload[] $remove files ticked for removal, which no longer count towards the limit
*/
public function validateTemplateAttachments(MailingTemplate $template, array $remove): ?string
{
$storedSize = $template->getAttachmentSize()
- array_sum(array_map(fn (Upload $upload) => (int) $upload->getSize(), $remove));
return $this->validate(Upload::TYPE_MAILING_TEMPLATE, $storedSize);
}
/**
* Applies the removals and adds the pending files to the template. Persisted, not flushed.
*
* @param Upload[] $remove
*/
public function saveTemplateAttachments(MailingTemplate $template, array $remove, User $owner): void
{
foreach ($remove as $upload) {
$this->removeFromTemplate($template, $upload);
}
foreach ($this->storePending(Upload::TYPE_MAILING_TEMPLATE, $owner) as $upload) {
$template->addAttachment($upload);
}
}
/**
* Rounded up, so a total just over the limit never reads as the limit itself.
*/
public function formatBytes(int $bytes): string
{
return number_format(ceil($bytes / 1024 / 1024 * 10) / 10, 1, ',', '.').' MB';
}
/**
* Takes a file off its template. A sent mailing that still lists it keeps the file and its
* row, so the record of what went out stays complete; otherwise both are removed.
*/
private function removeFromTemplate(MailingTemplate $template, Upload $upload): void
{
$template->removeAttachment($upload);
if (false === $this->mailingRepository->hasAttachment($upload)) {
$this->uploadHandler->removeUploadedFile($upload);
$this->entityManager->remove($upload);
}
}
/**
* What travels in the queued message: the path the worker reads the file from when each mail
* is sent, and the name it carries.
*
* @param Upload[] $uploads
*
* @return array<int, array{path: string, name: string}>
*/
public function toMessageAttachments(array $uploads): array
{
return array_map(fn (Upload $upload) => [
'path' => $this->uploadHandler->getResolvedUploadFilepath($upload),
'name' => $this->getAttachmentName($upload),
], $uploads);
}
/**
* For the preview of an assignment mailing. The template's files by path, the pending ones by
* content: a pending file still sits in the
* orphanage, and a send right after the preview moves it away before a queued preview mail
* would get round to reading it.
*
* @return EmailAttachmentInterface[]
*/
public function toPreviewAttachments(?MailingTemplate $template): array
{
$attachments = [];
foreach ($template?->getAttachments() ?? [] as $upload) {
$attachments[] = new EmailPathAttachmentDto(
$this->uploadHandler->getResolvedUploadFilepath($upload),
$this->getAttachmentName($upload)
);
}
foreach ($this->getPending(Upload::TYPE_MAILING_ATTACHMENT) as $uploadDto) {
$path = $this->uploadHandler->findOrphanageFilepath(Upload::TYPE_MAILING_ATTACHMENT, $uploadDto->getFilename());
if (null !== $path) {
$attachments[] = new EmailAttachmentDto(
$uploadDto->getOriginalFilename(),
(string) file_get_contents($path),
'application/pdf'
);
}
}
return $attachments;
}
private function getAttachmentName(Upload $upload): string
{
return $upload->getDisplayName() ?? (string) $upload->getOriginalFilename();
}
}
+42 -3
View File
@@ -2,10 +2,13 @@
namespace App\Service\Teamer;
use App\Email\EmailAttachmentInterface;
use App\Email\MailBodyRenderer;
use App\Email\Mailer;
use App\Entity\Assignment;
use App\Entity\User;
use App\Message\SendTeamerMailing;
use App\Model\EmailPathAttachmentDto;
use App\Model\TeamerFilterDto;
use App\Model\TeamerMailingDto;
use App\Model\TeamerMailingRecipient;
@@ -50,10 +53,28 @@ class TeamerMailingService
* asked for them in the filter.
*/
public function resolveRecipients(TeamerFilterDto $filterDto): TeamerMailingRecipientsDto
{
return $this->partitionRecipients($this->teamerRepository->getMailingRecipients($filterDto));
}
/**
* The same split for the teamers confirmed on any of the given assignments.
*
* @param Assignment[] $assignments
*/
public function resolveAssignmentRecipients(array $assignments): TeamerMailingRecipientsDto
{
return $this->partitionRecipients($this->teamerRepository->getAssignmentMailingRecipients($assignments));
}
/**
* @param TeamerMailingRecipient[] $candidates
*/
private function partitionRecipients(array $candidates): TeamerMailingRecipientsDto
{
$recipients = new TeamerMailingRecipientsDto();
foreach ($this->teamerRepository->getMailingRecipients($filterDto) as $recipient) {
foreach ($candidates as $recipient) {
if (true === $recipient->isDeleted()) {
$recipients->addSkippedDeleted();
@@ -88,6 +109,13 @@ class TeamerMailingService
*/
public function sendMailing(SendTeamerMailing $mailing): void
{
// By path, so the queued mail of every recipient carries only the path and the file is
// read when that mail is actually handed to the mail server.
$attachments = array_map(
fn (array $attachment) => new EmailPathAttachmentDto($attachment['path'], $attachment['name']),
$mailing->getAttachments()
);
foreach ($mailing->getRecipients() as $recipient) {
$values = $this->buildValues(
$recipient['firstName'],
@@ -99,6 +127,7 @@ class TeamerMailingService
$recipient['email'],
$this->render($mailing->getSubject(), $values),
$this->mailBodyRenderer->render($mailing->getMessage(), $values),
$attachments,
self::TRANSPORT,
$this->mailingBusTransport
);
@@ -107,6 +136,7 @@ class TeamerMailingService
$this->logger->info('Send teamer mailing', [
'subject' => $mailing->getSubject(),
'recipients' => $mailing->getRecipientCount(),
'attachments' => count($attachments),
]);
}
@@ -114,14 +144,18 @@ class TeamerMailingService
* Send the very same mail the recipients would get to the composing admin, with their
* own name filled in for the placeholders.
*/
public function sendPreview(TeamerMailingDto $mailingDto, User $admin): void
/**
* @param EmailAttachmentInterface[] $attachments
*/
public function sendPreview(TeamerMailingDto $mailingDto, User $admin, array $attachments = []): void
{
$values = $this->placeholderValuesForUser($admin);
$this->sendTo(
$admin->getUserIdentifier(),
self::PREVIEW_SUBJECT_PREFIX.$this->render($mailingDto->getSubject(), $values),
$this->mailBodyRenderer->render($mailingDto->getMessage(), $values)
$this->mailBodyRenderer->render($mailingDto->getMessage(), $values),
$attachments
);
$this->logger->info('Send teamer mailing preview', [
@@ -194,10 +228,14 @@ class TeamerMailingService
* 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
*/
private function sendTo(
string $email,
string $subject,
string $bodyHtml,
array $attachments = [],
?string $transport = null,
?string $busTransport = null,
): void {
@@ -209,6 +247,7 @@ class TeamerMailingService
'to' => $email,
'subject' => $subject,
'template' => self::TEMPLATE,
'attachments' => $attachments,
'transport' => $transport,
'bus_transport' => $busTransport,
]);
+17
View File
@@ -129,6 +129,23 @@ class UploadHandler
return $manager->uploadFiles($files);
}
/**
* Where a file dropped in this session waits in the orphanage, or null once it is gone -
* moved on by a save, or cleared away after the orphanage maxage (oneup_uploader.yaml).
*/
public function findOrphanageFilepath(string $uploader, string $filename): ?string
{
try {
foreach ($this->orphanageManager->get($uploader)->getFiles()->files()->name($filename) as $file) {
return $file->getPathname();
}
} catch (\Exception $e) {
// the session's orphanage directory does not exist until its first upload
}
return null;
}
public function removeUploadedFile(Upload $upload): void
{
$filepath = $this->getUploadFilepath($upload);