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

+22
View File
@@ -68,6 +68,28 @@ oneup_uploader:
namer: app.upload_namer namer: app.upload_namer
storage: storage:
directory: '%kernel.project_dir%/uploads/work_month' directory: '%kernel.project_dir%/uploads/work_month'
# PDFs of mailing templates and of single assignment mailings. Keys and directories are
# exactly Upload::TYPE_MAILING_TEMPLATE and TYPE_MAILING_ATTACHMENT, like above. The
# dropzone limits size and type in the browser only, so the same limits are enforced
# here: 5 MB (5 * 1024 * 1024) and PDF by content, whatever the file is called.
mailing_template:
frontend: dropzone
use_orphanage: true
namer: app.upload_namer
max_size: 5242880
allowed_mimetypes:
application/pdf: []
storage:
directory: '%kernel.project_dir%/uploads/mailing_template'
mailing_attachment:
frontend: dropzone
use_orphanage: true
namer: app.upload_namer
max_size: 5242880
allowed_mimetypes:
application/pdf: []
storage:
directory: '%kernel.project_dir%/uploads/mailing_attachment'
chunks: chunks:
maxage: 86400 maxage: 86400
storage: storage:
+52
View File
@@ -0,0 +1,52 @@
<?php
declare(strict_types=1);
namespace DoctrineMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
/**
* Written by hand from the diff, keeping only the mailing tables and upload.mailing_template_id:
* doctrine:migrations:diff also sweeps in the pre-existing drift of the dev database.
*/
final class Version20261111115642 extends AbstractMigration
{
public function getDescription(): string
{
return 'Add mailing templates and the record of sent assignment mailings';
}
public function up(Schema $schema): void
{
$this->addSql('CREATE TABLE mailing_template (id INT AUTO_INCREMENT NOT NULL, uuid VARCHAR(36) NOT NULL, name VARCHAR(255) NOT NULL, subject VARCHAR(255) NOT NULL, message LONGTEXT NOT NULL, created_by VARCHAR(255) DEFAULT NULL, updated_by VARCHAR(255) DEFAULT NULL, created_at DATETIME NOT NULL, updated_at DATETIME DEFAULT NULL, deleted_at DATETIME DEFAULT NULL, UNIQUE INDEX UNIQ_4A7CB3AFD17F50A6 (uuid), PRIMARY KEY (id)) DEFAULT CHARACTER SET utf8mb4');
$this->addSql('CREATE TABLE mailing (id INT AUTO_INCREMENT NOT NULL, uuid VARCHAR(36) NOT NULL, subject VARCHAR(255) NOT NULL, message LONGTEXT NOT NULL, recipient_count INT NOT NULL, created_by VARCHAR(255) DEFAULT NULL, updated_by VARCHAR(255) DEFAULT NULL, created_at DATETIME NOT NULL, updated_at DATETIME DEFAULT NULL, deleted_at DATETIME DEFAULT NULL, template_id INT DEFAULT NULL, UNIQUE INDEX UNIQ_3ED9315ED17F50A6 (uuid), INDEX IDX_3ED9315E5DA0FB8 (template_id), PRIMARY KEY (id)) DEFAULT CHARACTER SET utf8mb4');
$this->addSql('CREATE TABLE mailing_assignment (mailing_id INT NOT NULL, assignment_id INT NOT NULL, INDEX IDX_D6941DCB3931AB76 (mailing_id), INDEX IDX_D6941DCBD19302F8 (assignment_id), PRIMARY KEY (mailing_id, assignment_id)) DEFAULT CHARACTER SET utf8mb4');
$this->addSql('CREATE TABLE mailing_attachment (mailing_id INT NOT NULL, upload_id INT NOT NULL, INDEX IDX_9F0E80CA3931AB76 (mailing_id), INDEX IDX_9F0E80CACCCFBA31 (upload_id), PRIMARY KEY (mailing_id, upload_id)) DEFAULT CHARACTER SET utf8mb4');
$this->addSql('ALTER TABLE mailing ADD CONSTRAINT FK_3ED9315E5DA0FB8 FOREIGN KEY (template_id) REFERENCES mailing_template (id)');
$this->addSql('ALTER TABLE mailing_assignment ADD CONSTRAINT FK_D6941DCB3931AB76 FOREIGN KEY (mailing_id) REFERENCES mailing (id) ON DELETE CASCADE');
$this->addSql('ALTER TABLE mailing_assignment ADD CONSTRAINT FK_D6941DCBD19302F8 FOREIGN KEY (assignment_id) REFERENCES assignment (id) ON DELETE CASCADE');
$this->addSql('ALTER TABLE mailing_attachment ADD CONSTRAINT FK_9F0E80CA3931AB76 FOREIGN KEY (mailing_id) REFERENCES mailing (id) ON DELETE CASCADE');
$this->addSql('ALTER TABLE mailing_attachment ADD CONSTRAINT FK_9F0E80CACCCFBA31 FOREIGN KEY (upload_id) REFERENCES upload (id) ON DELETE CASCADE');
$this->addSql('ALTER TABLE upload ADD mailing_template_id INT DEFAULT NULL');
$this->addSql('ALTER TABLE upload ADD CONSTRAINT FK_17BDE61F223E1F4B FOREIGN KEY (mailing_template_id) REFERENCES mailing_template (id)');
$this->addSql('CREATE INDEX IDX_17BDE61F223E1F4B ON upload (mailing_template_id)');
}
public function down(Schema $schema): void
{
$this->addSql('ALTER TABLE upload DROP FOREIGN KEY FK_17BDE61F223E1F4B');
$this->addSql('DROP INDEX IDX_17BDE61F223E1F4B ON upload');
$this->addSql('ALTER TABLE upload DROP mailing_template_id');
$this->addSql('ALTER TABLE mailing DROP FOREIGN KEY FK_3ED9315E5DA0FB8');
$this->addSql('ALTER TABLE mailing_assignment DROP FOREIGN KEY FK_D6941DCB3931AB76');
$this->addSql('ALTER TABLE mailing_assignment DROP FOREIGN KEY FK_D6941DCBD19302F8');
$this->addSql('ALTER TABLE mailing_attachment DROP FOREIGN KEY FK_9F0E80CA3931AB76');
$this->addSql('ALTER TABLE mailing_attachment DROP FOREIGN KEY FK_9F0E80CACCCFBA31');
$this->addSql('DROP TABLE mailing_attachment');
$this->addSql('DROP TABLE mailing_assignment');
$this->addSql('DROP TABLE mailing');
$this->addSql('DROP TABLE mailing_template');
}
}
@@ -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'; 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_NEW = 'new';
public const STATUS_PENDING = 'pending'; public const STATUS_PENDING = 'pending';
public const STATUS_CHECKED = 'checked'; public const STATUS_CHECKED = 'checked';
@@ -98,6 +113,9 @@ class Upload implements BlameableEntityInterface, TimestampableEntityInterface
#[ORM\ManyToOne(inversedBy: 'documents')] #[ORM\ManyToOne(inversedBy: 'documents')]
private ?TeamerWorkMonth $teamerWorkMonth = null; private ?TeamerWorkMonth $teamerWorkMonth = null;
#[ORM\ManyToOne(inversedBy: 'attachments')]
private ?MailingTemplate $mailingTemplate = null;
#[ORM\Column(type: Types::TEXT, nullable: true)] #[ORM\Column(type: Types::TEXT, nullable: true)]
private ?string $comment = null; private ?string $comment = null;
@@ -319,6 +337,18 @@ class Upload implements BlameableEntityInterface, TimestampableEntityInterface
return $this; return $this;
} }
public function getMailingTemplate(): ?MailingTemplate
{
return $this->mailingTemplate;
}
public function setMailingTemplate(?MailingTemplate $mailingTemplate): static
{
$this->mailingTemplate = $mailingTemplate;
return $this;
}
public function getComment(): ?string public function getComment(): ?string
{ {
return $this->comment; 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; namespace App\Form;
use App\Model\TeamerMailingDto; 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\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver; use Symfony\Component\OptionsResolver\OptionsResolver;
class TeamerMailingType extends AbstractType class TeamerMailingType extends AbstractMailingType
{ {
public function buildForm(FormBuilderInterface $builder, array $options): void public function buildForm(FormBuilderInterface $builder, array $options): void
{ {
$builder $this->addMailFields($builder);
->add('subject', TextType::class, [
'label' => 'Betreff',
])
->add('message', AutosizeTextareaType::class, [
'label' => 'Nachricht',
'min_rows' => 12,
])
;
} }
public function configureOptions(OptionsResolver $resolver): void 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', [ $settingsMenu->addChild('Ansprechpersonen', [
'route' => 'app_admin_system_contact_index', 'route' => 'app_admin_system_contact_index',
'linkAttributes' => [ '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->addAdminItem($menu);
$this->addTeamerItem($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 * 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 * that have no business being serialized into a queue row. Plain arrays also survive a
* deploy that changes TeamerMailingRecipient while messages are still queued. * 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 class SendTeamerMailing
{ {
/** /**
* @param array<int, array{email: string, firstName: string, lastName: string, fullName: string}> $recipients * @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( public function __construct(
private readonly string $subject, private readonly string $subject,
private readonly string $message, private readonly string $message,
private readonly array $recipients, 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 = []; $snapshot = [];
foreach ($recipients->getEligible() as $recipient) { 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 public function getSubject(): string
@@ -64,6 +76,15 @@ class SendTeamerMailing
return $this->recipients; 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 public function getRecipientCount(): int
{ {
return count($this->recipients); 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(); 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 public function getListQueryForTeamer(Teamer $teamer, AssignmentFilterDto $filterDto): Query
{ {
// Find ids of assignments with available slots first // 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; namespace App\Repository;
use App\Entity\Assignment;
use App\Entity\Disposition;
use App\Entity\License; use App\Entity\License;
use App\Entity\Teamer; use App\Entity\Teamer;
use App\Model\TeamerFilterDto; use App\Model\TeamerFilterDto;
@@ -75,6 +77,57 @@ class TeamerRepository extends ServiceEntityRepository
return array_map(TeamerMailingRecipient::fromRow(...), $rows); 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 private function createListQueryBuilder(TeamerFilterDto $filterDto): QueryBuilder
{ {
$qb = $this->createQueryBuilder('teamer'); $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; namespace App\Service\Teamer;
use App\Email\EmailAttachmentInterface;
use App\Email\MailBodyRenderer; use App\Email\MailBodyRenderer;
use App\Email\Mailer; use App\Email\Mailer;
use App\Entity\Assignment;
use App\Entity\User; use App\Entity\User;
use App\Message\SendTeamerMailing; use App\Message\SendTeamerMailing;
use App\Model\EmailPathAttachmentDto;
use App\Model\TeamerFilterDto; use App\Model\TeamerFilterDto;
use App\Model\TeamerMailingDto; use App\Model\TeamerMailingDto;
use App\Model\TeamerMailingRecipient; use App\Model\TeamerMailingRecipient;
@@ -50,10 +53,28 @@ class TeamerMailingService
* asked for them in the filter. * asked for them in the filter.
*/ */
public function resolveRecipients(TeamerFilterDto $filterDto): TeamerMailingRecipientsDto 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(); $recipients = new TeamerMailingRecipientsDto();
foreach ($this->teamerRepository->getMailingRecipients($filterDto) as $recipient) { foreach ($candidates as $recipient) {
if (true === $recipient->isDeleted()) { if (true === $recipient->isDeleted()) {
$recipients->addSkippedDeleted(); $recipients->addSkippedDeleted();
@@ -88,6 +109,13 @@ class TeamerMailingService
*/ */
public function sendMailing(SendTeamerMailing $mailing): void 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) { foreach ($mailing->getRecipients() as $recipient) {
$values = $this->buildValues( $values = $this->buildValues(
$recipient['firstName'], $recipient['firstName'],
@@ -99,6 +127,7 @@ class TeamerMailingService
$recipient['email'], $recipient['email'],
$this->render($mailing->getSubject(), $values), $this->render($mailing->getSubject(), $values),
$this->mailBodyRenderer->render($mailing->getMessage(), $values), $this->mailBodyRenderer->render($mailing->getMessage(), $values),
$attachments,
self::TRANSPORT, self::TRANSPORT,
$this->mailingBusTransport $this->mailingBusTransport
); );
@@ -107,6 +136,7 @@ class TeamerMailingService
$this->logger->info('Send teamer mailing', [ $this->logger->info('Send teamer mailing', [
'subject' => $mailing->getSubject(), 'subject' => $mailing->getSubject(),
'recipients' => $mailing->getRecipientCount(), '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 * Send the very same mail the recipients would get to the composing admin, with their
* own name filled in for the placeholders. * 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); $values = $this->placeholderValuesForUser($admin);
$this->sendTo( $this->sendTo(
$admin->getUserIdentifier(), $admin->getUserIdentifier(),
self::PREVIEW_SUBJECT_PREFIX.$this->render($mailingDto->getSubject(), $values), 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', [ $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 * and the same queue as the rest of the application, so it arrives while the admin is
* still looking at the compose page. * still looking at the compose page.
*/ */
/**
* @param EmailAttachmentInterface[] $attachments
*/
private function sendTo( private function sendTo(
string $email, string $email,
string $subject, string $subject,
string $bodyHtml, string $bodyHtml,
array $attachments = [],
?string $transport = null, ?string $transport = null,
?string $busTransport = null, ?string $busTransport = null,
): void { ): void {
@@ -209,6 +247,7 @@ class TeamerMailingService
'to' => $email, 'to' => $email,
'subject' => $subject, 'subject' => $subject,
'template' => self::TEMPLATE, 'template' => self::TEMPLATE,
'attachments' => $attachments,
'transport' => $transport, 'transport' => $transport,
'bus_transport' => $busTransport, 'bus_transport' => $busTransport,
]); ]);
+17
View File
@@ -129,6 +129,23 @@ class UploadHandler
return $manager->uploadFiles($files); 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 public function removeUploadedFile(Upload $upload): void
{ {
$filepath = $this->getUploadFilepath($upload); $filepath = $this->getUploadFilepath($upload);
@@ -0,0 +1,14 @@
{# The placeholders of the teamer mailing, listed under every editor that writes one. #}
<div class="text-sm text-gray-500">
<div class="pb-2">
Platzhalter für Betreff und Nachricht, sie werden beim Senden pro Person ersetzt:
</div>
<div class="flex flex-wrap gap-2">
{% for placeholder, label in placeholders %}
<span class="inline-flex items-center space-x-1 py-1 px-2 bg-gray-50 border border-gray-200 rounded-sm">
<code>{{ placeholder }}</code>
<span>{{ label }}</span>
</span>
{% endfor %}
</div>
</div>
@@ -0,0 +1,26 @@
{# Files dropped earlier and still waiting in the upload session. The dropzone forgets them when
the page is rendered again - after a failed save, say - but the next save still takes them, so
they are listed here and can be dropped one by one. #}
{% if uploads is not empty %}
<div class="pb-2">
<div class="text-sm text-gray-500 pb-1">
Bereits hochgeladen:
</div>
<ul class="flex flex-col space-y-1">
{% for upload in uploads %}
<li class="flex items-center space-x-2 bg-gray-100 border rounded-sm px-2 py-1">
{{ icon('document', 'w-4 h-4 shrink-0') }}
<span class="flex-1">{{ upload.originalFilename }}</span>
<span class="text-sm text-gray-500">{{ upload.size|file_size(1) }}</span>
<button type="button"
title="Datei entfernen"
hx-delete="{{ path('app_upload_delete', { 'uuid': upload.uuid }) }}"
hx-target="closest li"
hx-swap="delete">
{{ icon('delete', 'w-5 h-5') }}
</button>
</li>
{% endfor %}
</ul>
</div>
{% endif %}
+2 -12
View File
@@ -55,18 +55,8 @@
{{ include('_partials/_markdown_hint.html.twig') }} {{ include('_partials/_markdown_hint.html.twig') }}
</div> </div>
<div class="pb-8 text-sm text-gray-500"> <div class="pb-8">
<div class="pb-2"> {{ include('_partials/_mailing_placeholders.html.twig', { 'placeholders': placeholders }) }}
Platzhalter für Betreff und Nachricht, sie werden beim Senden pro Person ersetzt:
</div>
<div class="flex flex-wrap gap-2">
{% for placeholder, label in placeholders %}
<span class="inline-flex items-center space-x-1 py-1 px-2 bg-gray-50 border border-gray-200 rounded-sm">
<code>{{ placeholder }}</code>
<span>{{ label }}</span>
</span>
{% endfor %}
</div>
</div> </div>
</div> </div>
@@ -23,6 +23,19 @@
</button> </button>
<div class="flex items-center space-x-2"> <div class="flex items-center space-x-2">
{# The checkboxes in the table name this form, which sits outside the table so
none of the htmx buttons in the rows posts the selection along. #}
<form id="assignment-mailing-select" method="get" action="{{ path('app_administrative_assignment_mailing_compose') }}">
<input type="hidden" name="r" value="{{ return_url() }}">
{# starts a new mailing even with nothing ticked, rather than reopening the last draft #}
<input type="hidden" name="start" value="1">
<button type="submit"
class="btn btn--small btn--secondary"
title="Mail an die bestätigten Teamer:innen der ausgewählten Einsätze">
{{ icon('mail', 'w-4 h-4 shrink-0') }}
<span class="whitespace-nowrap">Mail an Teamer:innen</span>
</button>
</form>
<a href="{{ path('app_administrative_assignment_create', { 'r': return_url() }) }}" class="btn btn--small"> <a href="{{ path('app_administrative_assignment_create', { 'r': return_url() }) }}" class="btn btn--small">
Neu Neu
</a> </a>
@@ -40,6 +53,9 @@
<table class="data-table"> <table class="data-table">
<thead> <thead>
<tr> <tr>
<th>
<span class="sr-only">Für Mail auswählen</span>
</th>
<th> <th>
{{ knp_pagination_sortable(pagination, 'ID', ['assignment.id']) }} {{ knp_pagination_sortable(pagination, 'ID', ['assignment.id']) }}
</th> </th>
@@ -72,6 +88,15 @@
<tbody> <tbody>
{% for assignment in pagination %} {% for assignment in pagination %}
<tr> <tr>
<td>
<input type="checkbox"
name="assignments[]"
value="{{ assignment.uuid }}"
form="assignment-mailing-select"
class="h-4 w-4 rounded-sm text-primary border-gray-300 focus:ring-primary"
title="Für Mail auswählen"
aria-label="Einsatz {{ assignment.id }} für Mail auswählen">
</td>
<td> <td>
{{ assignment.id }} {{ assignment.id }}
</td> </td>
@@ -226,7 +251,7 @@
</tr> </tr>
{% else %} {% else %}
<tr> <tr>
<td colspan="8"> <td colspan="9">
Keine Daten... Keine Daten...
</td> </td>
</tr> </tr>
@@ -0,0 +1,67 @@
{# Swapped as a whole whenever an assignment is added or removed, so the recipient count is
always the one for the list shown with it. #}
<div id="mailing-assignments" class="pb-6">
<div class="text-xl font-bold">
{{ recipients.eligibleCount }} Empfänger:innen
</div>
<div class="text-sm text-gray-500">
Teamer:innen mit bestätigter Einteilung, auch auf mehreren Einsätzen nur eine Mail.
Einsätze ohne bestätigte Teamer:innen werden weggelassen.
{% if recipients.hasSkipped %}
{{ include('admin/teamer/_mailing_skipped.html.twig', { 'recipients': recipients }) }}
{% endif %}
</div>
{% if recipients.eligibleCount > 0 %}
<div class="pt-2 text-sm">
{{ recipients.eligible|map(recipient => recipient.fullName)|join(', ') }}
</div>
{% endif %}
<ul class="flex flex-col space-y-1 py-4">
{% for assignment in mailingDto.assignments %}
<li class="flex items-center space-x-2 border rounded-sm px-2 py-1">
{{ icon('flag-' ~ assignment.destination.country, 'w-5 h-5 shrink-0') }}
<div class="flex-1">
<span class="whitespace-nowrap">
{{ assignment.destination.dateFrom|date('d.m.Y') }} - {{ assignment.destination.dateTo|date('d.m.Y') }}
</span>
{{ assignment.destination.hotel }}, {{ assignment.jobProfile.name }}
{# who is confirmed here, so a teamer on two of the assignments - counted once
above - is plain to see. Never empty: assignments nobody is confirmed on are
left out of the mailing, see AssignmentRepository::findForMailing(). #}
<div class="text-sm text-gray-500">
bestätigt: {{ assignment.dispositions
|filter(disposition => disposition.status == constant('App\\Entity\\Disposition::STATUS_CONFIRMED'))
|map(disposition => disposition.teamer.fullName)
|join(', ') }}
</div>
</div>
<button type="button"
class="text-red-500"
title="Einsatz entfernen"
hx-post="{{ path('app_administrative_assignment_mailing_remove', { 'uuid': assignment.uuid }) }}"
hx-target="#mailing-assignments"
hx-swap="outerHTML">
{{ icon('delete', 'w-5 h-5') }}
</button>
</li>
{% else %}
<li class="text-gray-500">
Noch kein Einsatz ausgewählt.
</li>
{% endfor %}
</ul>
{# Its own form, outside the mailing form: forms cannot nest, and typing here must not park
the search as a draft. The autocomplete dispatches a "select" event of its own; the
[detail] filter keeps out the native one a text selection in the input fires. #}
{{ form_start(addForm, { 'action': path('app_administrative_assignment_mailing_add') }) }}
{{ form_row(addForm.assignment, { 'attr': {
'hx-post': path('app_administrative_assignment_mailing_add'),
'hx-trigger': 'select[detail]',
'hx-target': '#mailing-assignments',
'hx-swap': 'outerHTML',
} }) }}
{{ form_rest(addForm) }}
{{ form_end(addForm) }}
</div>
@@ -0,0 +1,22 @@
{# The template's files, swapped when a template is picked. The files dropped for this mailing
are listed outside of it, by the dropzone, which a swap would otherwise empty. #}
<div id="mailing-attachments" {% if oob|default(false) %}hx-swap-oob="true"{% endif %}>
{% if mailingDto.template and mailingDto.template.attachments is not empty %}
<div class="text-sm text-gray-500 pb-1">
Aus der Vorlage, gehen immer mit:
</div>
<ul class="flex flex-col space-y-1 pb-2">
{% for attachment in mailingDto.template.attachments %}
<li class="flex items-center space-x-2 border rounded-sm px-2 py-1">
{{ icon('document', 'w-4 h-4 shrink-0') }}
<a href="{{ path('app_common_download', { 'uuid': attachment.uuid, 'inline': 1 }) }}"
target="_blank"
class="flex-1 underline">
{{ attachment.displayName ?? attachment.originalFilename }}
</a>
<span class="text-sm text-gray-500">{{ attachment.size|file_size(1) }}</span>
</li>
{% endfor %}
</ul>
{% endif %}
</div>
@@ -0,0 +1,5 @@
{# Swapped when a template is picked, which replaces subject and message. #}
<div id="mailing-fields" class="flex flex-col space-y-4 pb-4">
{{ form_row(form.subject) }}
{{ form_row(form.message) }}
</div>
@@ -0,0 +1,119 @@
{% extends 'administrative/layout.html.twig' %}
{% block title %}Mail an Teamer:innen{% endblock %}
{% block content %}
<div class="flex items-start justify-between pb-4">
<h1 class="text-2xl font-bold">
Mail an die Teamer:innen von Einsätzen
</h1>
<a href="{{ returnUrl }}" class="btn btn--small btn--secondary shrink-0">
Zurück zur Einsatzübersicht
</a>
</div>
<div class="grid lg:grid-cols-2 gap-8 items-start">
<div>
{{ include('administrative/assignment_mailing/_assignments.html.twig') }}
{# Outside the mailing form, so picking a template is not also parked as a draft
by the form's input trigger - the template route parks it itself. #}
<div class="pb-4">
<label for="mailing-template" class="block font-bold pb-2">
Vorlage
</label>
<select id="mailing-template"
name="template"
class="block w-full rounded-md border-0 py-1.5 text-gray-900 shadow-xs ring-1 ring-inset ring-gray-300 focus:ring-2 focus:ring-inset focus:ring-primary text-sm"
hx-post="{{ path('app_administrative_assignment_mailing_template') }}"
hx-trigger="change"
hx-include="#mailing-form"
hx-target="#mailing-fields"
hx-swap="outerHTML">
<option value="">keine Vorlage</option>
{% for template in templates %}
<option value="{{ template.uuid }}" {% if mailingDto.template and mailingDto.template.uuid == template.uuid %}selected{% endif %}>
{{ template.name }}
</option>
{% endfor %}
</select>
<div class="pt-1 text-sm text-gray-500">
Betreff und Nachricht der Vorlage ersetzen, was oben steht. Änderungen hier gelten
nur für diese Mail, die Vorlage bleibt, wie sie ist.
<a href="{{ path('app_administrative_system_mailing_template_index') }}" class="underline">Vorlagen verwalten</a>
</div>
</div>
{# The draft trigger works as in the teamer mailing, see the comment there. #}
{% set guardAttr = stimulus_controller('form-upload-guard')|stimulus_action('form-upload-guard', 'guard', 'submit') %}
{{ form_start(form, { 'attr': {
'id': 'mailing-form',
'hx-post': path('app_administrative_assignment_mailing_draft'),
'hx-trigger': 'input delay:500ms',
'hx-target': '#mailing-preview',
'hx-swap': 'innerHTML',
'hx-indicator': '#mailing-preview-indicator',
}|merge(guardAttr.toArray()) }) }}
{{ include('administrative/assignment_mailing/_fields.html.twig') }}
<div class="flex flex-col space-y-4 pb-6">
{{ include('_partials/_mailing_placeholders.html.twig', { 'placeholders': placeholders }) }}
{{ include('_partials/_markdown_hint.html.twig') }}
</div>
<div class="pb-8">
<div class="font-bold">
Anhänge
</div>
<div class="pb-2 text-sm text-gray-500">
Nur PDF, bis 5 MB je Datei und {{ maxAttachmentBytes|file_size(0) }} zusammen.
</div>
{{ include('administrative/assignment_mailing/_attachments.html.twig') }}
{{ include('_partials/_pending_uploads.html.twig', { 'uploads': pending }) }}
{% include '_partials/_upload_collection_form.html.twig' with {
'endpoint_upload': path('_uploader_upload_mailing_attachment'),
'max_filesize': 5,
'accepted_files': 'application/pdf',
} %}
</div>
<div class="flex items-center space-x-2 pb-8">
<button type="button"
class="btn"
hx-post="{{ path('app_administrative_assignment_mailing_confirm') }}"
hx-include="closest form"
hx-target="body"
hx-swap="beforeend"
{{ stimulus_target('form-upload-guard', 'submit') }}>
{{ icon('mail', 'w-4 h-4 shrink-0') }}
<span>Senden</span>
</button>
<button type="submit" class="btn btn--secondary" {{ stimulus_target('form-upload-guard', 'submit') }}>
Vorschau an mich senden
</button>
{% if hasDraft %}
<a href="{{ path('app_administrative_assignment_mailing_discard') }}" class="btn btn--secondary">
Entwurf verwerfen
</a>
{% endif %}
</div>
{{ form_rest(form) }}
{{ form_end(form) }}
</div>
<div class="lg:sticky lg:top-4">
<div class="font-bold pb-2">
Vorschau
</div>
<div class="relative">
<div id="mailing-preview">
{{ include('admin/teamer/_mailing_preview.html.twig', preview) }}
</div>
<div class="htmx-indicator absolute inset-0 bg-white/75 flex items-center justify-center"
id="mailing-preview-indicator">
{{ include('_partials/_spinner.html.twig', { 'class': 'w-8 h-8' }) }}
</div>
</div>
</div>
</div>
{% endblock %}
@@ -0,0 +1,56 @@
{% extends 'htmx_confirmation_modal.html.twig' %}
{% set sendable = valid and attachmentError is null and recipients.eligibleCount > 0 %}
{% block title %}Mail wirklich senden?{% endblock %}
{% block content %}
{% if not valid %}
<div class="pb-4">
Betreff und Nachricht müssen ausgefüllt sein, bevor die Mail gesendet werden kann.
</div>
{% elseif attachmentError is not null %}
<div class="pb-4">
{{ attachmentError }}
</div>
{% elseif recipients.eligibleCount == 0 %}
<div class="pb-4">
Auf den ausgewählten Einsätzen ist niemand bestätigt eingeteilt, dem geschrieben werden kann.
</div>
{% else %}
<div class="pb-4">
Die Mail geht an <strong>{{ recipients.eligibleCount }}</strong> Teamer:innen auf
{{ mailingDto.assignments|length }} {{ mailingDto.assignments|length == 1 ? 'Einsatz' : 'Einsätzen' }}.
Das lässt sich nicht zurücknehmen.
</div>
<div class="p-4 bg-gray-50 border border-gray-200 rounded-md">
<div class="font-bold pb-2">{{ mailingDto.subject }}</div>
<div class="text-sm">{{ mailingDto.message | u.truncate(400, '…', false) | nl2br }}</div>
</div>
{% set attachmentNames = (mailingDto.template ? mailingDto.template.attachments|map(a => a.displayName ?? a.originalFilename) : [])|merge(pending|map(u => u.originalFilename)) %}
{% if attachmentNames is not empty %}
<div class="pt-4 text-sm">
<span class="font-bold">Anhänge ({{ attachmentSize|file_size(1) }}):</span>
{{ attachmentNames|join(', ') }}
</div>
{% endif %}
{% if recipients.hasSkipped %}
<div class="pt-4 text-sm text-gray-500">
{{ include('admin/teamer/_mailing_skipped.html.twig', { 'recipients': recipients }) }}
</div>
{% endif %}
<div id="mailing-confirm-fields" class="hidden">
<input type="hidden" name="{{ field_name(form.subject) }}" value="{{ field_value(form.subject) }}">
{# a textarea keeps the line breaks of the message intact #}
<textarea name="{{ field_name(form.message) }}">{{ field_value(form.message) }}</textarea>
{% if form._token is defined %}
{{ form_widget(form._token) }}
{% endif %}
</div>
{% endif %}
{% endblock %}
{# without a sendable mail there is nothing to confirm, the button only leads back to the draft #}
{% block button_confirm %}{{ sendable ? 'Jetzt senden' : 'Zurück zum Entwurf' }}{% endblock %}
{% block button_attribute %}{% if sendable %}hx-post="{{ path('app_administrative_assignment_mailing_send') }}" hx-include="#mailing-confirm-fields"{% else %}{{ stimulus_action('modal', 'close') }}{% endif %}{% endblock %}
@@ -0,0 +1,5 @@
{{ include('administrative/assignment_mailing/_fields.html.twig') }}
{{ include('administrative/assignment_mailing/_attachments.html.twig', { 'oob': true }) }}
<div id="mailing-preview" hx-swap-oob="true">
{{ include('admin/teamer/_mailing_preview.html.twig', preview) }}
</div>
@@ -0,0 +1,59 @@
{% set formAttr = stimulus_controller('form-upload-guard')|stimulus_action('form-upload-guard', 'guard', 'submit') %}
{{ form_start(form, { 'attr': formAttr.toArray() }) }}
{{ form_errors(form) }}
<div class="flex flex-col space-y-4 pb-4">
{{ form_row(form.name) }}
{{ form_row(form.subject) }}
{{ form_row(form.message) }}
</div>
<div class="flex flex-col space-y-4 pb-8">
{{ include('_partials/_mailing_placeholders.html.twig', { 'placeholders': placeholders }) }}
{{ include('_partials/_markdown_hint.html.twig') }}
</div>
<div class="pb-8">
<div class="font-bold">
Anhänge
</div>
<div class="pb-2 text-sm text-gray-500">
Sie gehen mit jeder Mail aus dieser Vorlage mit. Nur PDF, bis 5 MB je Datei und
{{ maxAttachmentBytes|file_size(0) }} zusammen.
</div>
{% if form.removeAttachments is defined %}
<ul class="flex flex-col space-y-1 pb-2">
{% for choice in form.removeAttachments %}
{% set attachment = template.attachments|filter(a => a.uuid == choice.vars.value)|first %}
<li class="flex items-center space-x-2 border rounded-sm px-2 py-1">
{{ icon('document', 'w-4 h-4 shrink-0') }}
<a href="{{ path('app_common_download', { 'uuid': attachment.uuid, 'inline': 1 }) }}"
target="_blank"
class="flex-1 underline">
{{ choice.vars.label }}
</a>
<span class="text-sm text-gray-500">{{ attachment.size|file_size(1) }}</span>
<label class="flex items-center space-x-1 text-sm">
{{ form_widget(choice) }}
<span>entfernen</span>
</label>
</li>
{% endfor %}
</ul>
{% endif %}
{{ include('_partials/_pending_uploads.html.twig', { 'uploads': pending }) }}
{% include '_partials/_upload_collection_form.html.twig' with {
'endpoint_upload': path('_uploader_upload_mailing_template'),
'max_filesize': 5,
'accepted_files': 'application/pdf',
} %}
</div>
<div class="flex items-center space-x-2">
<button type="submit" class="btn" {{ stimulus_target('form-upload-guard', 'submit') }}>
Speichern
</button>
<a href="{{ path('app_administrative_system_mailing_template_index') }}" class="btn btn--secondary">
Abbrechen
</a>
</div>
{{ form_rest(form) }}
{{ form_end(form) }}
@@ -0,0 +1,12 @@
{% extends 'administrative/layout.html.twig' %}
{% block title %}Einstellungen - Mailvorlage anlegen{% endblock %}
{% block content %}
<div class="max-w-screen-md">
<h1 class="text-2xl font-bold pb-8">
Mailvorlage anlegen
</h1>
{% include 'administrative/system/mailing_template/_form.html.twig' %}
</div>
{% endblock %}
@@ -0,0 +1,12 @@
{% extends 'administrative/layout.html.twig' %}
{% block title %}Einstellungen - Mailvorlage bearbeiten{% endblock %}
{% block content %}
<div class="max-w-screen-md">
<h1 class="text-2xl font-bold pb-8">
Mailvorlage bearbeiten
</h1>
{% include 'administrative/system/mailing_template/_form.html.twig' %}
</div>
{% endblock %}
@@ -0,0 +1,81 @@
{% extends 'administrative/layout.html.twig' %}
{% block title %}Einstellungen - Mailvorlagen{% endblock %}
{% block content %}
<h1 class="text-2xl font-bold pb-2">
Mailvorlagen
</h1>
<div class="pb-8 text-gray-500">
Vorlagen für Mails an die Teamer:innen von Einsätzen. Die Einsätze wählst du in der
Einsatzübersicht aus.
</div>
<div class="data-table-wrapper">
<div class="data-table-wrapper__inner">
<table class="data-table">
<thead>
<tr>
<th class="w-1/4">
Name
</th>
<th class="w-2/5">
Betreff
</th>
<th>
Anhänge
</th>
<th>
Geändert
</th>
<th></th>
</tr>
</thead>
<tbody>
{% for template in templates %}
<tr>
<td>
<a href="{{ path('app_administrative_system_mailing_template_edit', { 'uuid': template.uuid }) }}">
{{ template.name }}
</a>
</td>
<td>
{{ template.subject }}
</td>
<td>
{{ template.attachments|length }}
</td>
<td class="whitespace-nowrap">
{{ (template.updatedAt ?? template.createdAt)|date('d.m.Y') }}
</td>
<td>
<div class="flex items-center space-x-2 justify-end">
<button type="button"
class="text-red-500"
title="Mailvorlage löschen"
hx-get="{{ path('app_administrative_system_mailing_template_delete', { 'uuid': template.uuid }) }}"
hx-target="body"
hx-swap="beforeend">
{{ icon('delete') }}
</button>
<a href="{{ path('app_administrative_system_mailing_template_edit', { 'uuid': template.uuid }) }}"
title="Mailvorlage bearbeiten">
{{ icon('edit') }}
</a>
</div>
</td>
</tr>
{% else %}
<tr>
<td colspan="5">
Keine Daten...
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
<a href="{{ path('app_administrative_system_mailing_template_create') }}" class="btn">
Neu
</a>
{% endblock %}
@@ -0,0 +1,8 @@
{% extends 'htmx_confirmation_modal.html.twig' %}
{% block content %}
<div>
Möchtest du die Mailvorlage <em>{{ template.name }}</em> wirklich löschen? Bereits
gesendete Mails bleiben davon unberührt.
</div>
{% endblock %}
@@ -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\MailBodyRenderer;
use App\Email\Mailer; use App\Email\Mailer;
use App\Entity\Assignment;
use App\Entity\Teamer; use App\Entity\Teamer;
use App\Entity\User; use App\Entity\User;
use App\Message\SendTeamerMailing; use App\Message\SendTeamerMailing;
use App\Model\EmailPathAttachmentDto;
use App\Model\TeamerFilterDto; use App\Model\TeamerFilterDto;
use App\Model\TeamerMailingDto; use App\Model\TeamerMailingDto;
use App\Model\TeamerMailingRecipient; use App\Model\TeamerMailingRecipient;
@@ -168,6 +170,83 @@ class TeamerMailingServiceTest extends TestCase
$this->service->sendMailing($this->createMailing('Betreff', 'Nachricht')); $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 * 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. * mailing would wait on the same worker the mailing itself is queued behind.