From e285646bb292a71e091a0fcd43e2b9ecda220203 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bj=C3=B6rn=20Fromme?= Date: Wed, 11 Nov 2026 14:02:55 +0100 Subject: [PATCH] feat: add mailing templates and mail the confirmed teamers of selected assignments --- config/packages/oneup_uploader.yaml | 22 ++ migrations/Version20261111115642.php | 52 +++ .../Autocomplete/AssignmentController.php | 31 ++ .../AbstractAssignmentMailingController.php | 99 +++++ .../AddAssignmentController.php | 38 ++ .../AssignmentMailing/ComposeController.php | 81 ++++ .../AssignmentMailing/ConfirmController.php | 32 ++ .../AssignmentMailing/DiscardController.php | 21 ++ .../AssignmentMailing/DraftController.php | 26 ++ .../RemoveAssignmentController.php | 29 ++ .../AssignmentMailing/SendController.php | 54 +++ .../AssignmentMailing/TemplateController.php | 49 +++ .../MailingTemplate/CreateController.php | 75 ++++ .../MailingTemplate/DeleteController.php | 52 +++ .../System/MailingTemplate/EditController.php | 85 +++++ .../MailingTemplate/IndexController.php | 25 ++ src/Entity/Mailing.php | 165 ++++++++ src/Entity/MailingTemplate.php | 144 +++++++ src/Entity/Upload.php | 30 ++ src/Form/AbstractMailingType.php | 27 ++ src/Form/AssignmentMailingAddType.php | 28 ++ src/Form/AssignmentMailingType.php | 28 ++ src/Form/MailingTemplateType.php | 53 +++ src/Form/TeamerMailingType.php | 14 +- src/Menu/AdminMenuBuilder.php | 11 + src/Menu/ManagerMenuBuilder.php | 11 + src/Message/SendTeamerMailing.php | 27 +- src/Model/AssignmentMailingDto.php | 50 +++ src/Repository/AssignmentRepository.php | 92 +++++ src/Repository/MailingRepository.php | 42 +++ src/Repository/MailingTemplateRepository.php | 36 ++ src/Repository/TeamerRepository.php | 53 +++ .../Teamer/AssignmentMailingDraftHandler.php | 111 ++++++ .../Teamer/AssignmentMailingService.php | 115 ++++++ .../Teamer/MailingAttachmentHandler.php | 247 ++++++++++++ src/Service/Teamer/TeamerMailingService.php | 45 ++- src/Service/Upload/UploadHandler.php | 17 + .../_partials/_mailing_placeholders.html.twig | 14 + .../_partials/_pending_uploads.html.twig | 26 ++ templates/admin/teamer/mailing.html.twig | 14 +- .../administrative/assignment/index.html.twig | 27 +- .../assignment_mailing/_assignments.html.twig | 67 ++++ .../assignment_mailing/_attachments.html.twig | 22 ++ .../assignment_mailing/_fields.html.twig | 5 + .../assignment_mailing/compose.html.twig | 119 ++++++ .../modal_confirm.html.twig | 56 +++ .../assignment_mailing/template.html.twig | 5 + .../system/mailing_template/_form.html.twig | 59 +++ .../system/mailing_template/create.html.twig | 12 + .../system/mailing_template/edit.html.twig | 12 + .../system/mailing_template/index.html.twig | 81 ++++ .../mailing_template/modal_delete.html.twig | 8 + .../AssignmentMailingControllerTest.php | 357 ++++++++++++++++++ .../MailingTemplateControllerTest.php | 169 +++++++++ .../TeamerRepositoryAssignmentMailingTest.php | 139 +++++++ .../Teamer/MailingAttachmentHandlerTest.php | 168 +++++++++ .../Teamer/TeamerMailingServiceTest.php | 79 ++++ 57 files changed, 3525 insertions(+), 31 deletions(-) create mode 100644 migrations/Version20261111115642.php create mode 100644 src/Controller/Admin/Autocomplete/AssignmentController.php create mode 100644 src/Controller/Administrative/AssignmentMailing/AbstractAssignmentMailingController.php create mode 100644 src/Controller/Administrative/AssignmentMailing/AddAssignmentController.php create mode 100644 src/Controller/Administrative/AssignmentMailing/ComposeController.php create mode 100644 src/Controller/Administrative/AssignmentMailing/ConfirmController.php create mode 100644 src/Controller/Administrative/AssignmentMailing/DiscardController.php create mode 100644 src/Controller/Administrative/AssignmentMailing/DraftController.php create mode 100644 src/Controller/Administrative/AssignmentMailing/RemoveAssignmentController.php create mode 100644 src/Controller/Administrative/AssignmentMailing/SendController.php create mode 100644 src/Controller/Administrative/AssignmentMailing/TemplateController.php create mode 100644 src/Controller/Administrative/System/MailingTemplate/CreateController.php create mode 100644 src/Controller/Administrative/System/MailingTemplate/DeleteController.php create mode 100644 src/Controller/Administrative/System/MailingTemplate/EditController.php create mode 100644 src/Controller/Administrative/System/MailingTemplate/IndexController.php create mode 100644 src/Entity/Mailing.php create mode 100644 src/Entity/MailingTemplate.php create mode 100644 src/Form/AbstractMailingType.php create mode 100644 src/Form/AssignmentMailingAddType.php create mode 100644 src/Form/AssignmentMailingType.php create mode 100644 src/Form/MailingTemplateType.php create mode 100644 src/Model/AssignmentMailingDto.php create mode 100644 src/Repository/MailingRepository.php create mode 100644 src/Repository/MailingTemplateRepository.php create mode 100644 src/Service/Teamer/AssignmentMailingDraftHandler.php create mode 100644 src/Service/Teamer/AssignmentMailingService.php create mode 100644 src/Service/Teamer/MailingAttachmentHandler.php create mode 100644 templates/_partials/_mailing_placeholders.html.twig create mode 100644 templates/_partials/_pending_uploads.html.twig create mode 100644 templates/administrative/assignment_mailing/_assignments.html.twig create mode 100644 templates/administrative/assignment_mailing/_attachments.html.twig create mode 100644 templates/administrative/assignment_mailing/_fields.html.twig create mode 100644 templates/administrative/assignment_mailing/compose.html.twig create mode 100644 templates/administrative/assignment_mailing/modal_confirm.html.twig create mode 100644 templates/administrative/assignment_mailing/template.html.twig create mode 100644 templates/administrative/system/mailing_template/_form.html.twig create mode 100644 templates/administrative/system/mailing_template/create.html.twig create mode 100644 templates/administrative/system/mailing_template/edit.html.twig create mode 100644 templates/administrative/system/mailing_template/index.html.twig create mode 100644 templates/administrative/system/mailing_template/modal_delete.html.twig create mode 100644 tests/Controller/Administrative/AssignmentMailing/AssignmentMailingControllerTest.php create mode 100644 tests/Controller/Administrative/System/MailingTemplate/MailingTemplateControllerTest.php create mode 100644 tests/Repository/TeamerRepositoryAssignmentMailingTest.php create mode 100644 tests/Service/Teamer/MailingAttachmentHandlerTest.php diff --git a/config/packages/oneup_uploader.yaml b/config/packages/oneup_uploader.yaml index c86dd1b..4b67dd1 100644 --- a/config/packages/oneup_uploader.yaml +++ b/config/packages/oneup_uploader.yaml @@ -68,6 +68,28 @@ oneup_uploader: namer: app.upload_namer storage: 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: maxage: 86400 storage: diff --git a/migrations/Version20261111115642.php b/migrations/Version20261111115642.php new file mode 100644 index 0000000..db69890 --- /dev/null +++ b/migrations/Version20261111115642.php @@ -0,0 +1,52 @@ +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'); + } +} diff --git a/src/Controller/Admin/Autocomplete/AssignmentController.php b/src/Controller/Admin/Autocomplete/AssignmentController.php new file mode 100644 index 0000000..c59239e --- /dev/null +++ b/src/Controller/Admin/Autocomplete/AssignmentController.php @@ -0,0 +1,31 @@ +getContent(), true, 512, JSON_THROW_ON_ERROR); + $queryString = (string) $query['search']; + } catch (\JsonException $e) { + throw $this->createNotFoundException(); + } + + return $this->json($this->assignmentRepository->getMailingAutocompletionData($queryString)); + } +} diff --git a/src/Controller/Administrative/AssignmentMailing/AbstractAssignmentMailingController.php b/src/Controller/Administrative/AssignmentMailing/AbstractAssignmentMailingController.php new file mode 100644 index 0000000..49a94ca --- /dev/null +++ b/src/Controller/Administrative/AssignmentMailing/AbstractAssignmentMailingController.php @@ -0,0 +1,99 @@ +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, + ]; + } +} diff --git a/src/Controller/Administrative/AssignmentMailing/AddAssignmentController.php b/src/Controller/Administrative/AssignmentMailing/AddAssignmentController.php new file mode 100644 index 0000000..67fd885 --- /dev/null +++ b/src/Controller/Administrative/AssignmentMailing/AddAssignmentController.php @@ -0,0 +1,38 @@ +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)); + } +} diff --git a/src/Controller/Administrative/AssignmentMailing/ComposeController.php b/src/Controller/Administrative/AssignmentMailing/ComposeController.php new file mode 100644 index 0000000..2af2b4f --- /dev/null +++ b/src/Controller/Administrative/AssignmentMailing/ComposeController.php @@ -0,0 +1,81 @@ +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)); + } +} diff --git a/src/Controller/Administrative/AssignmentMailing/ConfirmController.php b/src/Controller/Administrative/AssignmentMailing/ConfirmController.php new file mode 100644 index 0000000..78b77bf --- /dev/null +++ b/src/Controller/Administrative/AssignmentMailing/ConfirmController.php @@ -0,0 +1,32 @@ +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)); + } +} diff --git a/src/Controller/Administrative/AssignmentMailing/DiscardController.php b/src/Controller/Administrative/AssignmentMailing/DiscardController.php new file mode 100644 index 0000000..189c870 --- /dev/null +++ b/src/Controller/Administrative/AssignmentMailing/DiscardController.php @@ -0,0 +1,21 @@ +draftHandler->resetDraft(); + $this->attachmentHandler->discardPending(Upload::TYPE_MAILING_ATTACHMENT); + + return $this->redirectToRoute('app_administrative_assignment_index'); + } +} diff --git a/src/Controller/Administrative/AssignmentMailing/DraftController.php b/src/Controller/Administrative/AssignmentMailing/DraftController.php new file mode 100644 index 0000000..3c7b507 --- /dev/null +++ b/src/Controller/Administrative/AssignmentMailing/DraftController.php @@ -0,0 +1,26 @@ +createMailingForm($request)->getData(); + + $this->draftHandler->saveDraft($mailingDto); + + return $this->render('admin/teamer/_mailing_preview.html.twig', $this->renderPreview($mailingDto)); + } +} diff --git a/src/Controller/Administrative/AssignmentMailing/RemoveAssignmentController.php b/src/Controller/Administrative/AssignmentMailing/RemoveAssignmentController.php new file mode 100644 index 0000000..2e38544 --- /dev/null +++ b/src/Controller/Administrative/AssignmentMailing/RemoveAssignmentController.php @@ -0,0 +1,29 @@ + '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)); + } +} diff --git a/src/Controller/Administrative/AssignmentMailing/SendController.php b/src/Controller/Administrative/AssignmentMailing/SendController.php new file mode 100644 index 0000000..b73cf2e --- /dev/null +++ b/src/Controller/Administrative/AssignmentMailing/SendController.php @@ -0,0 +1,54 @@ +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')); + } +} diff --git a/src/Controller/Administrative/AssignmentMailing/TemplateController.php b/src/Controller/Administrative/AssignmentMailing/TemplateController.php new file mode 100644 index 0000000..1266641 --- /dev/null +++ b/src/Controller/Administrative/AssignmentMailing/TemplateController.php @@ -0,0 +1,49 @@ +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)); + } +} diff --git a/src/Controller/Administrative/System/MailingTemplate/CreateController.php b/src/Controller/Administrative/System/MailingTemplate/CreateController.php new file mode 100644 index 0000000..2c101cf --- /dev/null +++ b/src/Controller/Administrative/System/MailingTemplate/CreateController.php @@ -0,0 +1,75 @@ +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, + ]); + } +} diff --git a/src/Controller/Administrative/System/MailingTemplate/DeleteController.php b/src/Controller/Administrative/System/MailingTemplate/DeleteController.php new file mode 100644 index 0000000..f943ad7 --- /dev/null +++ b/src/Controller/Administrative/System/MailingTemplate/DeleteController.php @@ -0,0 +1,52 @@ + '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, + ]); + } +} diff --git a/src/Controller/Administrative/System/MailingTemplate/EditController.php b/src/Controller/Administrative/System/MailingTemplate/EditController.php new file mode 100644 index 0000000..76e8c30 --- /dev/null +++ b/src/Controller/Administrative/System/MailingTemplate/EditController.php @@ -0,0 +1,85 @@ + '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, + ]); + } +} diff --git a/src/Controller/Administrative/System/MailingTemplate/IndexController.php b/src/Controller/Administrative/System/MailingTemplate/IndexController.php new file mode 100644 index 0000000..4cc2165 --- /dev/null +++ b/src/Controller/Administrative/System/MailingTemplate/IndexController.php @@ -0,0 +1,25 @@ +render('administrative/system/mailing_template/index.html.twig', [ + 'templates' => $this->mailingTemplateRepository->findActive(), + ]); + } +} diff --git a/src/Entity/Mailing.php b/src/Entity/Mailing.php new file mode 100644 index 0000000..8dcd0bd --- /dev/null +++ b/src/Entity/Mailing.php @@ -0,0 +1,165 @@ + + */ + #[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 + */ + #[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 + */ + 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 + */ + 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; + } +} diff --git a/src/Entity/MailingTemplate.php b/src/Entity/MailingTemplate.php new file mode 100644 index 0000000..2cda51c --- /dev/null +++ b/src/Entity/MailingTemplate.php @@ -0,0 +1,144 @@ + + */ + #[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 + */ + 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()); + } +} diff --git a/src/Entity/Upload.php b/src/Entity/Upload.php index 4425077..22253e6 100644 --- a/src/Entity/Upload.php +++ b/src/Entity/Upload.php @@ -43,6 +43,21 @@ class Upload implements BlameableEntityInterface, TimestampableEntityInterface */ public const TYPE_WORK_MONTH = 'work_month'; + /** + * A PDF of a mailing template, sent with every mailing that starts from it. + * + * Kept apart from TYPE_MAILING_ATTACHMENT although both end up attached to a Mailing: files + * waiting in the upload session are told apart by type only, and a file dropped on the + * compose page must not be saved to the template edited in another tab, or the reverse. + * Neither is readable by teamers through the portal - they get it by mail. + */ + public const TYPE_MAILING_TEMPLATE = 'mailing_template'; + + /** + * A PDF added to one single assignment mailing, on top of its template's files. + */ + public const TYPE_MAILING_ATTACHMENT = 'mailing_attachment'; + public const STATUS_NEW = 'new'; public const STATUS_PENDING = 'pending'; public const STATUS_CHECKED = 'checked'; @@ -98,6 +113,9 @@ class Upload implements BlameableEntityInterface, TimestampableEntityInterface #[ORM\ManyToOne(inversedBy: 'documents')] private ?TeamerWorkMonth $teamerWorkMonth = null; + #[ORM\ManyToOne(inversedBy: 'attachments')] + private ?MailingTemplate $mailingTemplate = null; + #[ORM\Column(type: Types::TEXT, nullable: true)] private ?string $comment = null; @@ -319,6 +337,18 @@ class Upload implements BlameableEntityInterface, TimestampableEntityInterface return $this; } + public function getMailingTemplate(): ?MailingTemplate + { + return $this->mailingTemplate; + } + + public function setMailingTemplate(?MailingTemplate $mailingTemplate): static + { + $this->mailingTemplate = $mailingTemplate; + + return $this; + } + public function getComment(): ?string { return $this->comment; diff --git a/src/Form/AbstractMailingType.php b/src/Form/AbstractMailingType.php new file mode 100644 index 0000000..58b1419 --- /dev/null +++ b/src/Form/AbstractMailingType.php @@ -0,0 +1,27 @@ +add('subject', TextType::class, [ + 'label' => 'Betreff', + ]) + ->add('message', AutosizeTextareaType::class, [ + 'label' => 'Nachricht', + 'min_rows' => 12, + ]) + ; + } +} diff --git a/src/Form/AssignmentMailingAddType.php b/src/Form/AssignmentMailingAddType.php new file mode 100644 index 0000000..8c56f53 --- /dev/null +++ b/src/Form/AssignmentMailingAddType.php @@ -0,0 +1,28 @@ +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', + ]) + ; + } +} diff --git a/src/Form/AssignmentMailingType.php b/src/Form/AssignmentMailingType.php new file mode 100644 index 0000000..3ecba96 --- /dev/null +++ b/src/Form/AssignmentMailingType.php @@ -0,0 +1,28 @@ +addMailFields($builder); + } + + public function configureOptions(OptionsResolver $resolver): void + { + $resolver + ->setDefaults([ + 'data_class' => AssignmentMailingDto::class, + ]) + ; + } +} diff --git a/src/Form/MailingTemplateType.php b/src/Form/MailingTemplateType.php new file mode 100644 index 0000000..d92dfa6 --- /dev/null +++ b/src/Form/MailingTemplateType.php @@ -0,0 +1,53 @@ +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, + ]) + ; + } +} diff --git a/src/Form/TeamerMailingType.php b/src/Form/TeamerMailingType.php index 9ced363..05de23e 100644 --- a/src/Form/TeamerMailingType.php +++ b/src/Form/TeamerMailingType.php @@ -3,24 +3,14 @@ namespace App\Form; use App\Model\TeamerMailingDto; -use Symfony\Component\Form\AbstractType; -use Symfony\Component\Form\Extension\Core\Type\TextType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolver; -class TeamerMailingType extends AbstractType +class TeamerMailingType extends AbstractMailingType { public function buildForm(FormBuilderInterface $builder, array $options): void { - $builder - ->add('subject', TextType::class, [ - 'label' => 'Betreff', - ]) - ->add('message', AutosizeTextareaType::class, [ - 'label' => 'Nachricht', - 'min_rows' => 12, - ]) - ; + $this->addMailFields($builder); } public function configureOptions(OptionsResolver $resolver): void diff --git a/src/Menu/AdminMenuBuilder.php b/src/Menu/AdminMenuBuilder.php index bda6afb..8a4335d 100644 --- a/src/Menu/AdminMenuBuilder.php +++ b/src/Menu/AdminMenuBuilder.php @@ -355,6 +355,17 @@ class AdminMenuBuilder extends AbstractMenuBuilder ], ], ]); + $settingsMenu->addChild('Mailvorlagen', [ + 'route' => 'app_administrative_system_mailing_template_index', + 'linkAttributes' => [ + 'title' => 'Mailvorlagen', + ], + 'extras' => [ + 'routes' => [ + ['pattern' => '/^app_administrative_system_mailing_template_/'], + ], + ], + ]); $settingsMenu->addChild('Ansprechpersonen', [ 'route' => 'app_admin_system_contact_index', 'linkAttributes' => [ diff --git a/src/Menu/ManagerMenuBuilder.php b/src/Menu/ManagerMenuBuilder.php index b81a9f8..38ec27a 100644 --- a/src/Menu/ManagerMenuBuilder.php +++ b/src/Menu/ManagerMenuBuilder.php @@ -233,6 +233,17 @@ class ManagerMenuBuilder extends AbstractMenuBuilder ], ], ]); + $settingsMenu->addChild('Mailvorlagen', [ + 'route' => 'app_administrative_system_mailing_template_index', + 'linkAttributes' => [ + 'title' => 'Mailvorlagen', + ], + 'extras' => [ + 'routes' => [ + ['pattern' => '/^app_administrative_system_mailing_template_/'], + ], + ], + ]); $this->addAdminItem($menu); $this->addTeamerItem($menu); diff --git a/src/Message/SendTeamerMailing.php b/src/Message/SendTeamerMailing.php index 6de6810..391a42a 100644 --- a/src/Message/SendTeamerMailing.php +++ b/src/Message/SendTeamerMailing.php @@ -12,21 +12,33 @@ use App\Model\TeamerMailingRecipientsDto; * the one the confirmation modal showed, and the filter itself carries hydrated entities * that have no business being serialized into a queue row. Plain arrays also survive a * deploy that changes TeamerMailingRecipient while messages are still queued. + * + * Attachments travel the same way, as plain paths: the files are read only when each mail is + * finally sent, so a queued mailing never carries their content. */ class SendTeamerMailing { /** * @param array $recipients + * @param array $attachments */ public function __construct( private readonly string $subject, private readonly string $message, private readonly array $recipients, + private readonly array $attachments = [], ) { } - public static function fromRecipients(string $subject, string $message, TeamerMailingRecipientsDto $recipients): self - { + /** + * @param array $attachments + */ + public static function fromRecipients( + string $subject, + string $message, + TeamerMailingRecipientsDto $recipients, + array $attachments = [], + ): self { $snapshot = []; foreach ($recipients->getEligible() as $recipient) { @@ -43,7 +55,7 @@ class SendTeamerMailing ]; } - return new self($subject, $message, $snapshot); + return new self($subject, $message, $snapshot, $attachments); } public function getSubject(): string @@ -64,6 +76,15 @@ class SendTeamerMailing return $this->recipients; } + /** + * @return array + */ + public function getAttachments(): array + { + // a mailing queued before attachments existed unserializes without the property + return $this->attachments ?? []; + } + public function getRecipientCount(): int { return count($this->recipients); diff --git a/src/Model/AssignmentMailingDto.php b/src/Model/AssignmentMailingDto.php new file mode 100644 index 0000000..a34d2a7 --- /dev/null +++ b/src/Model/AssignmentMailingDto.php @@ -0,0 +1,50 @@ +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; + } +} diff --git a/src/Repository/AssignmentRepository.php b/src/Repository/AssignmentRepository.php index 2717b7f..b2b8fc1 100644 --- a/src/Repository/AssignmentRepository.php +++ b/src/Repository/AssignmentRepository.php @@ -62,6 +62,98 @@ class AssignmentRepository extends ServiceEntityRepository return $qb->getQuery(); } + /** + * The assignments a mailing can go to, of those given: not deleted, and with at least one + * confirmed teamer - an assignment without one would only make the recipient count look + * wrong. In the order of the overview, by travel date. + * + * @param string[] $uuids + * + * @return Assignment[] + */ + public function findForMailing(array $uuids): array + { + if ([] === $uuids) { + return []; + } + + $qb = $this->createQueryBuilder('assignment'); + + return $qb + ->select('assignment', 'destination', 'job_profile') + ->innerJoin('assignment.destination', 'destination') + ->leftJoin('assignment.jobProfile', 'job_profile') + ->where($qb->expr()->andX( + $qb->expr()->in('assignment.uuid', ':uuids'), + $qb->expr()->isNull('assignment.deletedAt'), + $this->hasConfirmedDisposition() + )) + ->setParameter('uuids', $uuids) + ->setParameter('confirmed', Disposition::STATUS_CONFIRMED) + ->orderBy('destination.dateFrom', \SortDirection::Ascending) + ->addOrderBy('assignment.id', \SortDirection::Ascending) + ->getQuery() + ->getResult() + ; + } + + /** + * Assignments to add to a mailing: not deleted, not over yet and with a confirmed teamer, the + * same as findForMailing(). Searched like the destination autocomplete, plus the job profile. + * + * @return array + */ + public function getMailingAutocompletionData(string $search): array + { + $qb = $this->createQueryBuilder('assignment'); + + $assignments = $qb + ->select('assignment', 'destination', 'job_profile') + ->innerJoin('assignment.destination', 'destination') + ->innerJoin('assignment.jobProfile', 'job_profile') + ->where($qb->expr()->andX( + $qb->expr()->isNull('assignment.deletedAt'), + $qb->expr()->gte('destination.dateTo', ':today'), + $this->hasConfirmedDisposition(), + $qb->expr()->orX( + $qb->expr()->like('destination.product', ':search'), + $qb->expr()->like('destination.hotel', ':search'), + $qb->expr()->like('job_profile.name', ':search'), + $qb->expr()->like('DATE_FORMAT(destination.dateFrom, \'%d.%m.%y\')', ':search') + ) + )) + ->setParameter('today', new \DateTimeImmutable('today')) + ->setParameter('search', '%'.$this->escapeLikeWildcards($search).'%') + ->setParameter('confirmed', Disposition::STATUS_CONFIRMED) + ->orderBy('destination.dateFrom', \SortDirection::Ascending) + ->addOrderBy('assignment.id', \SortDirection::Ascending) + ->setMaxResults(30) + ->getQuery() + ->getResult() + ; + + return array_map(fn (Assignment $assignment) => [ + 'value' => $assignment->getUuid(), + 'text' => sprintf( + '%s · %s · %s', + $assignment->getDestination(), + $assignment->getDestination()?->getHotel(), + $assignment->getJobProfile()?->getName() + ), + ], $assignments); + } + + /** + * DQL for "assignment has a confirmed disposition"; the caller binds :confirmed. + */ + private function hasConfirmedDisposition(): string + { + return sprintf( + 'EXISTS (SELECT confirmed_disposition.id FROM %s confirmed_disposition WHERE confirmed_disposition.assignment = assignment AND confirmed_disposition.status = :confirmed)', + Disposition::class + ); + } + public function getListQueryForTeamer(Teamer $teamer, AssignmentFilterDto $filterDto): Query { // Find ids of assignments with available slots first diff --git a/src/Repository/MailingRepository.php b/src/Repository/MailingRepository.php new file mode 100644 index 0000000..f13ea05 --- /dev/null +++ b/src/Repository/MailingRepository.php @@ -0,0 +1,42 @@ + + * + * @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() + ; + } +} diff --git a/src/Repository/MailingTemplateRepository.php b/src/Repository/MailingTemplateRepository.php new file mode 100644 index 0000000..6339653 --- /dev/null +++ b/src/Repository/MailingTemplateRepository.php @@ -0,0 +1,36 @@ + + * + * @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]); + } +} diff --git a/src/Repository/TeamerRepository.php b/src/Repository/TeamerRepository.php index 3c3de91..529777b 100644 --- a/src/Repository/TeamerRepository.php +++ b/src/Repository/TeamerRepository.php @@ -2,6 +2,8 @@ namespace App\Repository; +use App\Entity\Assignment; +use App\Entity\Disposition; use App\Entity\License; use App\Entity\Teamer; use App\Model\TeamerFilterDto; @@ -75,6 +77,57 @@ class TeamerRepository extends ServiceEntityRepository return array_map(TeamerMailingRecipient::fromRow(...), $rows); } + /** + * The teamers with a confirmed disposition on any of the given assignments, each once + * however many of them they are on. Same projection as getMailingRecipients(). + * + * @param Assignment[] $assignments + * + * @return TeamerMailingRecipient[] + */ + public function getAssignmentMailingRecipients(array $assignments): array + { + if ([] === $assignments) { + return []; + } + + return array_map( + TeamerMailingRecipient::fromRow(...), + $this->createAssignmentMailingQueryBuilder($assignments)->getQuery()->getArrayResult() + ); + } + + /** + * @param Assignment[] $assignments + */ + public function createAssignmentMailingQueryBuilder(array $assignments): QueryBuilder + { + $qb = $this->createQueryBuilder('teamer'); + + return $qb + ->distinct() + ->select( + 'teamer.id AS id', + 'teamer.firstName AS firstName', + 'teamer.lastName AS lastName', + 'teamer.communication.email AS email', + 'teamer.deletedAt AS deletedAt', + 'user.disabledAt AS disabledAt' + ) + ->innerJoin('teamer.dispositions', 'disposition') + ->leftJoin('teamer.user', 'user') + ->where($qb->expr()->andX( + $qb->expr()->in('disposition.assignment', ':assignments'), + $qb->expr()->eq('disposition.status', ':status') + )) + ->setParameter('assignments', $assignments) + ->setParameter('status', Disposition::STATUS_CONFIRMED) + // the compose page lists the names in this order + ->addOrderBy('teamer.lastName', \SortDirection::Ascending) + ->addOrderBy('teamer.firstName', \SortDirection::Ascending) + ; + } + private function createListQueryBuilder(TeamerFilterDto $filterDto): QueryBuilder { $qb = $this->createQueryBuilder('teamer'); diff --git a/src/Service/Teamer/AssignmentMailingDraftHandler.php b/src/Service/Teamer/AssignmentMailingDraftHandler.php new file mode 100644 index 0000000..095fafb --- /dev/null +++ b/src/Service/Teamer/AssignmentMailingDraftHandler.php @@ -0,0 +1,111 @@ +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(); + } +} diff --git a/src/Service/Teamer/AssignmentMailingService.php b/src/Service/Teamer/AssignmentMailingService.php new file mode 100644 index 0000000..561b366 --- /dev/null +++ b/src/Service/Teamer/AssignmentMailingService.php @@ -0,0 +1,115 @@ +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; + } +} diff --git a/src/Service/Teamer/MailingAttachmentHandler.php b/src/Service/Teamer/MailingAttachmentHandler.php new file mode 100644 index 0000000..538e214 --- /dev/null +++ b/src/Service/Teamer/MailingAttachmentHandler.php @@ -0,0 +1,247 @@ + + */ + 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 + */ + 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(); + } +} diff --git a/src/Service/Teamer/TeamerMailingService.php b/src/Service/Teamer/TeamerMailingService.php index d45cf24..5346dcf 100644 --- a/src/Service/Teamer/TeamerMailingService.php +++ b/src/Service/Teamer/TeamerMailingService.php @@ -2,10 +2,13 @@ namespace App\Service\Teamer; +use App\Email\EmailAttachmentInterface; use App\Email\MailBodyRenderer; use App\Email\Mailer; +use App\Entity\Assignment; use App\Entity\User; use App\Message\SendTeamerMailing; +use App\Model\EmailPathAttachmentDto; use App\Model\TeamerFilterDto; use App\Model\TeamerMailingDto; use App\Model\TeamerMailingRecipient; @@ -50,10 +53,28 @@ class TeamerMailingService * asked for them in the filter. */ public function resolveRecipients(TeamerFilterDto $filterDto): TeamerMailingRecipientsDto + { + return $this->partitionRecipients($this->teamerRepository->getMailingRecipients($filterDto)); + } + + /** + * The same split for the teamers confirmed on any of the given assignments. + * + * @param Assignment[] $assignments + */ + public function resolveAssignmentRecipients(array $assignments): TeamerMailingRecipientsDto + { + return $this->partitionRecipients($this->teamerRepository->getAssignmentMailingRecipients($assignments)); + } + + /** + * @param TeamerMailingRecipient[] $candidates + */ + private function partitionRecipients(array $candidates): TeamerMailingRecipientsDto { $recipients = new TeamerMailingRecipientsDto(); - foreach ($this->teamerRepository->getMailingRecipients($filterDto) as $recipient) { + foreach ($candidates as $recipient) { if (true === $recipient->isDeleted()) { $recipients->addSkippedDeleted(); @@ -88,6 +109,13 @@ class TeamerMailingService */ public function sendMailing(SendTeamerMailing $mailing): void { + // By path, so the queued mail of every recipient carries only the path and the file is + // read when that mail is actually handed to the mail server. + $attachments = array_map( + fn (array $attachment) => new EmailPathAttachmentDto($attachment['path'], $attachment['name']), + $mailing->getAttachments() + ); + foreach ($mailing->getRecipients() as $recipient) { $values = $this->buildValues( $recipient['firstName'], @@ -99,6 +127,7 @@ class TeamerMailingService $recipient['email'], $this->render($mailing->getSubject(), $values), $this->mailBodyRenderer->render($mailing->getMessage(), $values), + $attachments, self::TRANSPORT, $this->mailingBusTransport ); @@ -107,6 +136,7 @@ class TeamerMailingService $this->logger->info('Send teamer mailing', [ 'subject' => $mailing->getSubject(), 'recipients' => $mailing->getRecipientCount(), + 'attachments' => count($attachments), ]); } @@ -114,14 +144,18 @@ class TeamerMailingService * Send the very same mail the recipients would get to the composing admin, with their * own name filled in for the placeholders. */ - public function sendPreview(TeamerMailingDto $mailingDto, User $admin): void + /** + * @param EmailAttachmentInterface[] $attachments + */ + public function sendPreview(TeamerMailingDto $mailingDto, User $admin, array $attachments = []): void { $values = $this->placeholderValuesForUser($admin); $this->sendTo( $admin->getUserIdentifier(), self::PREVIEW_SUBJECT_PREFIX.$this->render($mailingDto->getSubject(), $values), - $this->mailBodyRenderer->render($mailingDto->getMessage(), $values) + $this->mailBodyRenderer->render($mailingDto->getMessage(), $values), + $attachments ); $this->logger->info('Send teamer mailing preview', [ @@ -194,10 +228,14 @@ class TeamerMailingService * and the same queue as the rest of the application, so it arrives while the admin is * still looking at the compose page. */ + /** + * @param EmailAttachmentInterface[] $attachments + */ private function sendTo( string $email, string $subject, string $bodyHtml, + array $attachments = [], ?string $transport = null, ?string $busTransport = null, ): void { @@ -209,6 +247,7 @@ class TeamerMailingService 'to' => $email, 'subject' => $subject, 'template' => self::TEMPLATE, + 'attachments' => $attachments, 'transport' => $transport, 'bus_transport' => $busTransport, ]); diff --git a/src/Service/Upload/UploadHandler.php b/src/Service/Upload/UploadHandler.php index 3fa8a1e..21e7ee2 100644 --- a/src/Service/Upload/UploadHandler.php +++ b/src/Service/Upload/UploadHandler.php @@ -129,6 +129,23 @@ class UploadHandler return $manager->uploadFiles($files); } + /** + * Where a file dropped in this session waits in the orphanage, or null once it is gone - + * moved on by a save, or cleared away after the orphanage maxage (oneup_uploader.yaml). + */ + public function findOrphanageFilepath(string $uploader, string $filename): ?string + { + try { + foreach ($this->orphanageManager->get($uploader)->getFiles()->files()->name($filename) as $file) { + return $file->getPathname(); + } + } catch (\Exception $e) { + // the session's orphanage directory does not exist until its first upload + } + + return null; + } + public function removeUploadedFile(Upload $upload): void { $filepath = $this->getUploadFilepath($upload); diff --git a/templates/_partials/_mailing_placeholders.html.twig b/templates/_partials/_mailing_placeholders.html.twig new file mode 100644 index 0000000..2b0d523 --- /dev/null +++ b/templates/_partials/_mailing_placeholders.html.twig @@ -0,0 +1,14 @@ +{# The placeholders of the teamer mailing, listed under every editor that writes one. #} +
+
+ Platzhalter für Betreff und Nachricht, sie werden beim Senden pro Person ersetzt: +
+
+ {% for placeholder, label in placeholders %} + + {{ placeholder }} + {{ label }} + + {% endfor %} +
+
diff --git a/templates/_partials/_pending_uploads.html.twig b/templates/_partials/_pending_uploads.html.twig new file mode 100644 index 0000000..84e04ee --- /dev/null +++ b/templates/_partials/_pending_uploads.html.twig @@ -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 %} +
+
+ Bereits hochgeladen: +
+
    + {% for upload in uploads %} +
  • + {{ icon('document', 'w-4 h-4 shrink-0') }} + {{ upload.originalFilename }} + {{ upload.size|file_size(1) }} + +
  • + {% endfor %} +
+
+{% endif %} diff --git a/templates/admin/teamer/mailing.html.twig b/templates/admin/teamer/mailing.html.twig index c43759b..c563378 100644 --- a/templates/admin/teamer/mailing.html.twig +++ b/templates/admin/teamer/mailing.html.twig @@ -55,18 +55,8 @@ {{ include('_partials/_markdown_hint.html.twig') }} -
-
- Platzhalter für Betreff und Nachricht, sie werden beim Senden pro Person ersetzt: -
-
- {% for placeholder, label in placeholders %} - - {{ placeholder }} - {{ label }} - - {% endfor %} -
+
+ {{ include('_partials/_mailing_placeholders.html.twig', { 'placeholders': placeholders }) }}
diff --git a/templates/administrative/assignment/index.html.twig b/templates/administrative/assignment/index.html.twig index f5c2042..73ed34d 100644 --- a/templates/administrative/assignment/index.html.twig +++ b/templates/administrative/assignment/index.html.twig @@ -23,6 +23,19 @@
+ {# 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. #} +
+ + {# starts a new mailing even with nothing ticked, rather than reopening the last draft #} + + +
Neu @@ -40,6 +53,9 @@ + @@ -72,6 +88,15 @@ {% for assignment in pagination %} + @@ -226,7 +251,7 @@ {% else %} - diff --git a/templates/administrative/assignment_mailing/_assignments.html.twig b/templates/administrative/assignment_mailing/_assignments.html.twig new file mode 100644 index 0000000..86a3e9a --- /dev/null +++ b/templates/administrative/assignment_mailing/_assignments.html.twig @@ -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. #} +
+
+ {{ recipients.eligibleCount }} Empfänger:innen +
+
+ 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 %} +
+ {% if recipients.eligibleCount > 0 %} +
+ {{ recipients.eligible|map(recipient => recipient.fullName)|join(', ') }} +
+ {% endif %} + +
    + {% for assignment in mailingDto.assignments %} +
  • + {{ icon('flag-' ~ assignment.destination.country, 'w-5 h-5 shrink-0') }} +
    + + {{ assignment.destination.dateFrom|date('d.m.Y') }} - {{ assignment.destination.dateTo|date('d.m.Y') }} + + {{ 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(). #} +
    + bestätigt: {{ assignment.dispositions + |filter(disposition => disposition.status == constant('App\\Entity\\Disposition::STATUS_CONFIRMED')) + |map(disposition => disposition.teamer.fullName) + |join(', ') }} +
    +
    + +
  • + {% else %} +
  • + Noch kein Einsatz ausgewählt. +
  • + {% endfor %} +
+ + {# 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) }} +
diff --git a/templates/administrative/assignment_mailing/_attachments.html.twig b/templates/administrative/assignment_mailing/_attachments.html.twig new file mode 100644 index 0000000..11d4330 --- /dev/null +++ b/templates/administrative/assignment_mailing/_attachments.html.twig @@ -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. #} +
+ {% if mailingDto.template and mailingDto.template.attachments is not empty %} +
+ Aus der Vorlage, gehen immer mit: +
+ + {% endif %} +
diff --git a/templates/administrative/assignment_mailing/_fields.html.twig b/templates/administrative/assignment_mailing/_fields.html.twig new file mode 100644 index 0000000..0099e59 --- /dev/null +++ b/templates/administrative/assignment_mailing/_fields.html.twig @@ -0,0 +1,5 @@ +{# Swapped when a template is picked, which replaces subject and message. #} +
+ {{ form_row(form.subject) }} + {{ form_row(form.message) }} +
diff --git a/templates/administrative/assignment_mailing/compose.html.twig b/templates/administrative/assignment_mailing/compose.html.twig new file mode 100644 index 0000000..4494236 --- /dev/null +++ b/templates/administrative/assignment_mailing/compose.html.twig @@ -0,0 +1,119 @@ +{% extends 'administrative/layout.html.twig' %} + +{% block title %}Mail an Teamer:innen{% endblock %} + +{% block content %} +
+

+ Mail an die Teamer:innen von Einsätzen +

+ + Zurück zur Einsatzübersicht + +
+ +
+
+ {{ 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. #} +
+ + +
+ Betreff und Nachricht der Vorlage ersetzen, was oben steht. Änderungen hier gelten + nur für diese Mail, die Vorlage bleibt, wie sie ist. + Vorlagen verwalten +
+
+ + {# 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') }} + +
+ {{ include('_partials/_mailing_placeholders.html.twig', { 'placeholders': placeholders }) }} + {{ include('_partials/_markdown_hint.html.twig') }} +
+ +
+
+ Anhänge +
+
+ Nur PDF, bis 5 MB je Datei und {{ maxAttachmentBytes|file_size(0) }} zusammen. +
+ {{ 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', + } %} +
+ +
+ + + {% if hasDraft %} + + Entwurf verwerfen + + {% endif %} +
+ {{ form_rest(form) }} + {{ form_end(form) }} +
+ +
+
+ Vorschau +
+
+
+ {{ include('admin/teamer/_mailing_preview.html.twig', preview) }} +
+
+ {{ include('_partials/_spinner.html.twig', { 'class': 'w-8 h-8' }) }} +
+
+
+
+{% endblock %} diff --git a/templates/administrative/assignment_mailing/modal_confirm.html.twig b/templates/administrative/assignment_mailing/modal_confirm.html.twig new file mode 100644 index 0000000..801d3b3 --- /dev/null +++ b/templates/administrative/assignment_mailing/modal_confirm.html.twig @@ -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 %} +
+ Betreff und Nachricht müssen ausgefüllt sein, bevor die Mail gesendet werden kann. +
+ {% elseif attachmentError is not null %} +
+ {{ attachmentError }} +
+ {% elseif recipients.eligibleCount == 0 %} +
+ Auf den ausgewählten Einsätzen ist niemand bestätigt eingeteilt, dem geschrieben werden kann. +
+ {% else %} +
+ Die Mail geht an {{ recipients.eligibleCount }} Teamer:innen auf + {{ mailingDto.assignments|length }} {{ mailingDto.assignments|length == 1 ? 'Einsatz' : 'Einsätzen' }}. + Das lässt sich nicht zurücknehmen. +
+
+
{{ mailingDto.subject }}
+
{{ mailingDto.message | u.truncate(400, '…', false) | nl2br }}
+
+ {% set attachmentNames = (mailingDto.template ? mailingDto.template.attachments|map(a => a.displayName ?? a.originalFilename) : [])|merge(pending|map(u => u.originalFilename)) %} + {% if attachmentNames is not empty %} +
+ Anhänge ({{ attachmentSize|file_size(1) }}): + {{ attachmentNames|join(', ') }} +
+ {% endif %} + {% if recipients.hasSkipped %} +
+ {{ include('admin/teamer/_mailing_skipped.html.twig', { 'recipients': recipients }) }} +
+ {% endif %} + + {% 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 %} diff --git a/templates/administrative/assignment_mailing/template.html.twig b/templates/administrative/assignment_mailing/template.html.twig new file mode 100644 index 0000000..de37fe4 --- /dev/null +++ b/templates/administrative/assignment_mailing/template.html.twig @@ -0,0 +1,5 @@ +{{ include('administrative/assignment_mailing/_fields.html.twig') }} +{{ include('administrative/assignment_mailing/_attachments.html.twig', { 'oob': true }) }} +
+ {{ include('admin/teamer/_mailing_preview.html.twig', preview) }} +
diff --git a/templates/administrative/system/mailing_template/_form.html.twig b/templates/administrative/system/mailing_template/_form.html.twig new file mode 100644 index 0000000..ce60f73 --- /dev/null +++ b/templates/administrative/system/mailing_template/_form.html.twig @@ -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) }} +
+ {{ form_row(form.name) }} + {{ form_row(form.subject) }} + {{ form_row(form.message) }} +
+
+ {{ include('_partials/_mailing_placeholders.html.twig', { 'placeholders': placeholders }) }} + {{ include('_partials/_markdown_hint.html.twig') }} +
+ +
+
+ Anhänge +
+
+ Sie gehen mit jeder Mail aus dieser Vorlage mit. Nur PDF, bis 5 MB je Datei und + {{ maxAttachmentBytes|file_size(0) }} zusammen. +
+ {% if form.removeAttachments is defined %} +
    + {% for choice in form.removeAttachments %} + {% set attachment = template.attachments|filter(a => a.uuid == choice.vars.value)|first %} +
  • + {{ icon('document', 'w-4 h-4 shrink-0') }} + + {{ choice.vars.label }} + + {{ attachment.size|file_size(1) }} + +
  • + {% endfor %} +
+ {% 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', + } %} +
+ +
+ + + Abbrechen + +
+{{ form_rest(form) }} +{{ form_end(form) }} diff --git a/templates/administrative/system/mailing_template/create.html.twig b/templates/administrative/system/mailing_template/create.html.twig new file mode 100644 index 0000000..4759b73 --- /dev/null +++ b/templates/administrative/system/mailing_template/create.html.twig @@ -0,0 +1,12 @@ +{% extends 'administrative/layout.html.twig' %} + +{% block title %}Einstellungen - Mailvorlage anlegen{% endblock %} + +{% block content %} +
+

+ Mailvorlage anlegen +

+ {% include 'administrative/system/mailing_template/_form.html.twig' %} +
+{% endblock %} diff --git a/templates/administrative/system/mailing_template/edit.html.twig b/templates/administrative/system/mailing_template/edit.html.twig new file mode 100644 index 0000000..45ab78d --- /dev/null +++ b/templates/administrative/system/mailing_template/edit.html.twig @@ -0,0 +1,12 @@ +{% extends 'administrative/layout.html.twig' %} + +{% block title %}Einstellungen - Mailvorlage bearbeiten{% endblock %} + +{% block content %} +
+

+ Mailvorlage bearbeiten +

+ {% include 'administrative/system/mailing_template/_form.html.twig' %} +
+{% endblock %} diff --git a/templates/administrative/system/mailing_template/index.html.twig b/templates/administrative/system/mailing_template/index.html.twig new file mode 100644 index 0000000..e1c867f --- /dev/null +++ b/templates/administrative/system/mailing_template/index.html.twig @@ -0,0 +1,81 @@ +{% extends 'administrative/layout.html.twig' %} + +{% block title %}Einstellungen - Mailvorlagen{% endblock %} + +{% block content %} +

+ Mailvorlagen +

+
+ Vorlagen für Mails an die Teamer:innen von Einsätzen. Die Einsätze wählst du in der + Einsatzübersicht aus. +
+
+
+
+ Für Mail auswählen + {{ knp_pagination_sortable(pagination, 'ID', ['assignment.id']) }}
+ + {{ assignment.id }}
+ Keine Daten...
+ + + + + + + + + + + {% for template in templates %} + + + + + + + + {% else %} + + + + {% endfor %} + +
+ Name + + Betreff + + Anhänge + + Geändert +
+ + {{ template.name }} + + + {{ template.subject }} + + {{ template.attachments|length }} + + {{ (template.updatedAt ?? template.createdAt)|date('d.m.Y') }} + +
+ + + {{ icon('edit') }} + +
+
+ Keine Daten... +
+
+ + + Neu + +{% endblock %} diff --git a/templates/administrative/system/mailing_template/modal_delete.html.twig b/templates/administrative/system/mailing_template/modal_delete.html.twig new file mode 100644 index 0000000..96babc7 --- /dev/null +++ b/templates/administrative/system/mailing_template/modal_delete.html.twig @@ -0,0 +1,8 @@ +{% extends 'htmx_confirmation_modal.html.twig' %} + +{% block content %} +
+ Möchtest du die Mailvorlage {{ template.name }} wirklich löschen? Bereits + gesendete Mails bleiben davon unberührt. +
+{% endblock %} diff --git a/tests/Controller/Administrative/AssignmentMailing/AssignmentMailingControllerTest.php b/tests/Controller/Administrative/AssignmentMailing/AssignmentMailingControllerTest.php new file mode 100644 index 0000000..da93173 --- /dev/null +++ b/tests/Controller/Administrative/AssignmentMailing/AssignmentMailingControllerTest.php @@ -0,0 +1,357 @@ +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 + */ + 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).'.muster@example.com')) + ; + $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); + } +} diff --git a/tests/Controller/Administrative/System/MailingTemplate/MailingTemplateControllerTest.php b/tests/Controller/Administrative/System/MailingTemplate/MailingTemplateControllerTest.php new file mode 100644 index 0000000..3fe54e5 --- /dev/null +++ b/tests/Controller/Administrative/System/MailingTemplate/MailingTemplateControllerTest.php @@ -0,0 +1,169 @@ +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; + } +} diff --git a/tests/Repository/TeamerRepositoryAssignmentMailingTest.php b/tests/Repository/TeamerRepositoryAssignmentMailingTest.php new file mode 100644 index 0000000..0a03f19 --- /dev/null +++ b/tests/Repository/TeamerRepositoryAssignmentMailingTest.php @@ -0,0 +1,139 @@ +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); + } +} diff --git a/tests/Service/Teamer/MailingAttachmentHandlerTest.php b/tests/Service/Teamer/MailingAttachmentHandlerTest.php new file mode 100644 index 0000000..cdefff3 --- /dev/null +++ b/tests/Service/Teamer/MailingAttachmentHandlerTest.php @@ -0,0 +1,168 @@ +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) + ; + } +} diff --git a/tests/Service/Teamer/TeamerMailingServiceTest.php b/tests/Service/Teamer/TeamerMailingServiceTest.php index ada9b8e..7489373 100644 --- a/tests/Service/Teamer/TeamerMailingServiceTest.php +++ b/tests/Service/Teamer/TeamerMailingServiceTest.php @@ -6,9 +6,11 @@ namespace App\Tests\Service\Teamer; use App\Email\MailBodyRenderer; use App\Email\Mailer; +use App\Entity\Assignment; use App\Entity\Teamer; use App\Entity\User; use App\Message\SendTeamerMailing; +use App\Model\EmailPathAttachmentDto; use App\Model\TeamerFilterDto; use App\Model\TeamerMailingDto; use App\Model\TeamerMailingRecipient; @@ -168,6 +170,83 @@ class TeamerMailingServiceTest extends TestCase $this->service->sendMailing($this->createMailing('Betreff', 'Nachricht')); } + public function testResolveAssignmentRecipientsPartitionsTheConfirmedTeamers(): void + { + $eligible = $this->createRecipient('Anna', 'Berg', 'anna@example.org'); + $disabled = $this->createRecipient('Cem', 'Dal', 'cem@example.org', 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', 'anna@example.org')) + ->addEligible($this->createRecipient('Bea', 'Ohm', 'bea@example.org')) + ; + + $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', 'anna@example.org') + )); + } + + /** + * A mailing queued before the attachments existed comes out of the queue without the + * property; it has to send as it would have, not fail in the worker. + */ + public function testAMailingQueuedWithoutAttachmentsHasNone(): void + { + $mailing = (new \ReflectionClass(SendTeamerMailing::class))->newInstanceWithoutConstructor(); + + $this->assertSame([], $mailing->getAttachments()); + } + /** * A preview has to stay on the default relay and the default queue, or composing a * mailing would wait on the same worker the mailing itself is queued behind.