feat: create Mailjet lists for travel mailings
This commit is contained in:
1 parent
d63fa10a56
commit
c16f368293
15 files changed
+851
-1
No files matched your search
@@ -0,0 +1,67 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Command;
|
||||
|
||||
use App\Exception\NewsletterProviderException;
|
||||
use App\Repository\TravelMailingListRepository;
|
||||
use App\Service\TravelMailingListManager;
|
||||
use Psr\Log\LoggerInterface;
|
||||
use Symfony\Component\Console\Attribute\AsCommand;
|
||||
use Symfony\Component\Console\Command\Command;
|
||||
use Symfony\Component\Console\Input\InputInterface;
|
||||
use Symfony\Component\Console\Output\OutputInterface;
|
||||
use Symfony\Component\Console\Style\SymfonyStyle;
|
||||
|
||||
#[AsCommand(
|
||||
name: 'app:cleanup:travel-mailing-lists',
|
||||
description: 'Deletes travel mailing lists and their orphaned contacts from Mailjet 30 days after the travel started',
|
||||
)]
|
||||
class CleanupTravelMailingListsCommand extends Command
|
||||
{
|
||||
public function __construct(
|
||||
private readonly TravelMailingListRepository $travelMailingListRepository,
|
||||
private readonly TravelMailingListManager $travelMailingListManager,
|
||||
private readonly LoggerInterface $logger,
|
||||
) {
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
protected function execute(InputInterface $input, OutputInterface $output): int
|
||||
{
|
||||
$io = new SymfonyStyle($input, $output);
|
||||
|
||||
$mailingLists = $this->travelMailingListRepository->findDueForDeletion(new \DateTimeImmutable());
|
||||
if ([] === $mailingLists) {
|
||||
$io->success('No travel mailing lists due for deletion.');
|
||||
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
|
||||
$failed = 0;
|
||||
foreach ($mailingLists as $mailingList) {
|
||||
try {
|
||||
$deletedContacts = $this->travelMailingListManager->delete($mailingList);
|
||||
$io->writeln(sprintf('Deleted %s (list %d) and %d orphaned contact(s).', $mailingList->getTravelCode(), $mailingList->getMailjetListId(), $deletedContacts));
|
||||
} catch (NewsletterProviderException $exception) {
|
||||
// The row stays, so the next run picks the list up again.
|
||||
++$failed;
|
||||
$this->logger->error('Delete travel mailing list failed', [
|
||||
'travel_code' => $mailingList->getTravelCode(),
|
||||
'mailjet_list_id' => $mailingList->getMailjetListId(),
|
||||
'error' => $exception->getMessage(),
|
||||
]);
|
||||
$io->error(sprintf('%s (list %d): %s', $mailingList->getTravelCode(), $mailingList->getMailjetListId(), $exception->getMessage()));
|
||||
}
|
||||
}
|
||||
|
||||
if ($failed > 0) {
|
||||
return Command::FAILURE;
|
||||
}
|
||||
|
||||
$io->success(sprintf('Deleted %d travel mailing list(s).', count($mailingLists)));
|
||||
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Controller\Admin\TravelMailing;
|
||||
|
||||
use App\BpnConnect\Exception\BpnConnectException;
|
||||
use App\BpnConnect\TravelsClient;
|
||||
use App\BusProNet\Utility\DateCodeUtility;
|
||||
use App\Exception\NewsletterProviderException;
|
||||
use App\Repository\TravelMailingListRepository;
|
||||
use App\Service\TravelDataProvider;
|
||||
use App\Service\TravelMailingListManager;
|
||||
use Psr\Log\LoggerInterface;
|
||||
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
|
||||
use Symfony\Component\HttpFoundation\Request;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
use Symfony\Component\Routing\Attribute\Route;
|
||||
use Symfony\Component\Security\Http\Attribute\IsGranted;
|
||||
|
||||
#[IsGranted('ROLE_CUSTOMER_EXPERT')]
|
||||
class CreateListController extends AbstractController
|
||||
{
|
||||
public const string CSRF_TOKEN_ID = 'create_travel_mailing_list';
|
||||
|
||||
public function __construct(
|
||||
private readonly TravelsClient $travelsClient,
|
||||
private readonly TravelDataProvider $travelDataProvider,
|
||||
private readonly TravelMailingListRepository $travelMailingListRepository,
|
||||
private readonly TravelMailingListManager $travelMailingListManager,
|
||||
private readonly LoggerInterface $adminLogger,
|
||||
) {
|
||||
}
|
||||
|
||||
#[Route('/admin/travel-mailing/list', name: 'app_admin_travelmailing_createlist', methods: ['POST'])]
|
||||
public function index(Request $request): Response
|
||||
{
|
||||
if (!$this->isCsrfTokenValid(self::CSRF_TOKEN_ID, $request->request->getString('_token'))) {
|
||||
throw $this->createAccessDeniedException('Invalid CSRF token.');
|
||||
}
|
||||
|
||||
$travelCode = (new DateCodeUtility())->sanitize($request->request->getString('travelCode'));
|
||||
$returnUrl = $this->generateUrl('app_admin_travelmailing', ['travelCode' => $travelCode]);
|
||||
|
||||
if (null !== $this->travelMailingListRepository->findOneByTravelCode($travelCode)) {
|
||||
$this->addFlash('error', sprintf('Für %s gibt es bereits eine Mailjet-Liste.', $travelCode));
|
||||
|
||||
return $this->redirect($returnUrl);
|
||||
}
|
||||
|
||||
$travelStartsAt = $this->travelDataProvider->mapDateCodeToStartDate($travelCode);
|
||||
if (null === $travelStartsAt) {
|
||||
$this->addFlash('error', sprintf('Für %s ist kein Reisebeginn bekannt, die Liste könnte nicht automatisch gelöscht werden.', $travelCode));
|
||||
|
||||
return $this->redirect($returnUrl);
|
||||
}
|
||||
|
||||
// Fetched again rather than posted from the page, so the list holds what BusPro reports now.
|
||||
try {
|
||||
$recipients = $this->travelsClient->getMailingRecipients($travelCode)->data;
|
||||
} catch (BpnConnectException) {
|
||||
$this->addFlash('error', 'Die Teilnehmerliste konnte nicht von BusPro abgerufen werden. Bitte später erneut versuchen.');
|
||||
|
||||
return $this->redirect($returnUrl);
|
||||
}
|
||||
|
||||
if ([] === $recipients) {
|
||||
$this->addFlash('error', sprintf('Keine Empfänger für %s gefunden.', $travelCode));
|
||||
|
||||
return $this->redirect($returnUrl);
|
||||
}
|
||||
|
||||
try {
|
||||
$mailingList = $this->travelMailingListManager->create($travelCode, $recipients, $travelStartsAt);
|
||||
} catch (NewsletterProviderException $exception) {
|
||||
$this->adminLogger->error('Create travel mailing list failed', [
|
||||
'travel_code' => $travelCode,
|
||||
'error' => $exception->getMessage(),
|
||||
]);
|
||||
$this->addFlash('error', 'Die Mailjet-Liste konnte nicht angelegt werden: '.$exception->getMessage());
|
||||
|
||||
return $this->redirect($returnUrl);
|
||||
}
|
||||
|
||||
$this->adminLogger->info('Create travel mailing list', [
|
||||
'travel_code' => $travelCode,
|
||||
'mailjet_list_id' => $mailingList->getMailjetListId(),
|
||||
'recipients' => count($recipients),
|
||||
]);
|
||||
$this->addFlash('success', sprintf('Die Mailjet-Liste %s wurde mit %d Empfängern angelegt.', $travelCode, count($recipients)));
|
||||
|
||||
return $this->redirect($returnUrl);
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,7 @@ use App\BpnConnect\TravelsClient;
|
||||
use App\BusProNet\Utility\DateCodeUtility;
|
||||
use App\Form\Admin\TravelMailingLookupType;
|
||||
use App\Form\Model\TravelMailingLookupDto;
|
||||
use App\Repository\TravelMailingListRepository;
|
||||
use App\Service\TravelDataProvider;
|
||||
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
|
||||
use Symfony\Component\HttpFoundation\Request;
|
||||
@@ -22,6 +23,7 @@ class IndexController extends AbstractController
|
||||
public function __construct(
|
||||
private readonly TravelsClient $travelsClient,
|
||||
private readonly TravelDataProvider $travelDataProvider,
|
||||
private readonly TravelMailingListRepository $travelMailingListRepository,
|
||||
) {
|
||||
}
|
||||
|
||||
@@ -36,6 +38,8 @@ class IndexController extends AbstractController
|
||||
|
||||
$result = null;
|
||||
$travelLabel = null;
|
||||
$travelStartsAt = null;
|
||||
$mailingList = null;
|
||||
$failed = false;
|
||||
if ($form->isSubmitted() && $form->isValid()) {
|
||||
// The local index matches codes exactly, so "lpjmp-281126" has to become "LPJMP281126"
|
||||
@@ -45,6 +49,8 @@ class IndexController extends AbstractController
|
||||
try {
|
||||
$result = $this->travelsClient->getMailingRecipients($travelCode);
|
||||
$travelLabel = $this->travelDataProvider->mapDateCodeToLabel($travelCode);
|
||||
$travelStartsAt = $this->travelDataProvider->mapDateCodeToStartDate($travelCode);
|
||||
$mailingList = $this->travelMailingListRepository->findOneByTravelCode($travelCode);
|
||||
} catch (BpnConnectException) {
|
||||
// The client has already logged the cause; the page only needs to say it failed.
|
||||
$failed = true;
|
||||
@@ -55,6 +61,8 @@ class IndexController extends AbstractController
|
||||
'form' => $form,
|
||||
'result' => $result,
|
||||
'travel_label' => $travelLabel,
|
||||
'travel_starts_at' => $travelStartsAt,
|
||||
'mailing_list' => $mailingList,
|
||||
'failed' => $failed,
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Entity;
|
||||
|
||||
use App\Repository\TravelMailingListRepository;
|
||||
use Doctrine\ORM\Mapping as ORM;
|
||||
|
||||
/**
|
||||
* A Mailjet contact list created for one travel's participants. The row exists so the list can
|
||||
* be deleted again once the travel is past; the list itself is never updated after creation.
|
||||
*/
|
||||
#[ORM\Entity(repositoryClass: TravelMailingListRepository::class)]
|
||||
class TravelMailingList
|
||||
{
|
||||
#[ORM\Id]
|
||||
#[ORM\GeneratedValue]
|
||||
#[ORM\Column(type: 'integer')]
|
||||
private ?int $id = null;
|
||||
|
||||
#[ORM\Column(type: 'string', length: 32, unique: true)]
|
||||
private string $travelCode;
|
||||
|
||||
#[ORM\Column(type: 'integer')]
|
||||
private int $mailjetListId;
|
||||
|
||||
#[ORM\Column(type: 'datetime_immutable')]
|
||||
private \DateTimeImmutable $deleteAfter;
|
||||
|
||||
#[ORM\Column(type: 'datetime_immutable')]
|
||||
private \DateTimeImmutable $createdAt;
|
||||
|
||||
public function __construct(string $travelCode, int $mailjetListId, \DateTimeImmutable $deleteAfter)
|
||||
{
|
||||
$this->travelCode = $travelCode;
|
||||
$this->mailjetListId = $mailjetListId;
|
||||
$this->deleteAfter = $deleteAfter;
|
||||
$this->createdAt = new \DateTimeImmutable();
|
||||
}
|
||||
|
||||
public function getId(): ?int
|
||||
{
|
||||
return $this->id;
|
||||
}
|
||||
|
||||
public function getTravelCode(): string
|
||||
{
|
||||
return $this->travelCode;
|
||||
}
|
||||
|
||||
public function getMailjetListId(): int
|
||||
{
|
||||
return $this->mailjetListId;
|
||||
}
|
||||
|
||||
public function getDeleteAfter(): \DateTimeImmutable
|
||||
{
|
||||
return $this->deleteAfter;
|
||||
}
|
||||
|
||||
public function getCreatedAt(): \DateTimeImmutable
|
||||
{
|
||||
return $this->createdAt;
|
||||
}
|
||||
}
|
||||
+147
-1
@@ -12,6 +12,7 @@ class ApiClient
|
||||
{
|
||||
private const string DEFAULT_BASE_URL = 'https://api.mailjet.com/v3/REST';
|
||||
private const int NAME_MAX_LENGTH = 255;
|
||||
private const int PAGE_LIMIT = 1000;
|
||||
|
||||
/**
|
||||
* @param array{firstName?: string, lastName?: string} $contactMetadataFields
|
||||
@@ -141,6 +142,139 @@ class ApiClient
|
||||
]);
|
||||
}
|
||||
|
||||
public function createContactsList(string $name): int
|
||||
{
|
||||
$this->assertConfigured();
|
||||
|
||||
$response = $this->request('POST', 'contactslist', [
|
||||
'json' => [
|
||||
'Name' => $name,
|
||||
],
|
||||
]);
|
||||
|
||||
$listId = $response['Data'][0]['ID'] ?? null;
|
||||
if (null === $listId) {
|
||||
throw new NewsletterProviderException(sprintf('Mailjet did not return an id for the new contact list %s', $name));
|
||||
}
|
||||
|
||||
return (int) $listId;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds the contacts as subscribed, including any who unsubscribed from this list before.
|
||||
* Mailjet processes the request as an asynchronous job.
|
||||
*
|
||||
* @param list<array{email: string, firstName: ?string}> $contacts
|
||||
*
|
||||
* @return int|null the job id
|
||||
*/
|
||||
public function addContactsToList(int $listId, array $contacts): ?int
|
||||
{
|
||||
$this->assertConfigured();
|
||||
|
||||
$payload = [];
|
||||
foreach ($contacts as $contact) {
|
||||
$entry = ['Email' => $this->normalizeEmail($contact['email'])];
|
||||
|
||||
$firstName = $this->normalizeName($contact['firstName']);
|
||||
if (null !== $firstName && true === isset($this->contactMetadataFields['firstName'])) {
|
||||
$entry['Properties'] = [$this->contactMetadataFields['firstName'] => $firstName];
|
||||
}
|
||||
|
||||
$payload[] = $entry;
|
||||
}
|
||||
|
||||
$response = $this->request('POST', sprintf('contactslist/%d/managemanycontacts', $listId), [
|
||||
'json' => [
|
||||
'Action' => 'addforce',
|
||||
'Contacts' => $payload,
|
||||
],
|
||||
]);
|
||||
|
||||
$jobId = $response['Data'][0]['JobID'] ?? null;
|
||||
|
||||
return null !== $jobId ? (int) $jobId : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<int>
|
||||
*/
|
||||
public function getListContactIds(int $listId): array
|
||||
{
|
||||
$this->assertConfigured();
|
||||
|
||||
$contactIds = [];
|
||||
$offset = 0;
|
||||
do {
|
||||
$response = $this->request('GET', 'listrecipient', [
|
||||
'query' => [
|
||||
'ContactsList' => $listId,
|
||||
'Limit' => self::PAGE_LIMIT,
|
||||
'Offset' => $offset,
|
||||
],
|
||||
]);
|
||||
|
||||
$entries = true === is_array($response['Data'] ?? null) ? $response['Data'] : [];
|
||||
foreach ($entries as $entry) {
|
||||
if (true === is_array($entry) && true === isset($entry['ContactID'])) {
|
||||
$contactIds[] = (int) $entry['ContactID'];
|
||||
}
|
||||
}
|
||||
|
||||
$offset += self::PAGE_LIMIT;
|
||||
} while (self::PAGE_LIMIT === count($entries));
|
||||
|
||||
return array_values(array_unique($contactIds));
|
||||
}
|
||||
|
||||
/**
|
||||
* Lists the contact is on, subscribed or not. Mailjet includes lists deleted within the last 60 days.
|
||||
*
|
||||
* @return list<int>
|
||||
*/
|
||||
public function getContactListIds(int $contactId): array
|
||||
{
|
||||
$this->assertConfigured();
|
||||
|
||||
$response = $this->request('GET', sprintf('contact/%d/getcontactslists', $contactId), [
|
||||
'allow_404' => true,
|
||||
]);
|
||||
|
||||
$listIds = [];
|
||||
foreach ($response['Data'] ?? [] as $entry) {
|
||||
if (true === is_array($entry) && true === isset($entry['ListID'])) {
|
||||
$listIds[] = (int) $entry['ListID'];
|
||||
}
|
||||
}
|
||||
|
||||
return $listIds;
|
||||
}
|
||||
|
||||
public function deleteContactsList(int $listId): void
|
||||
{
|
||||
$this->assertConfigured();
|
||||
|
||||
$this->request('DELETE', sprintf('contactslist/%d', $listId), [
|
||||
'allow_404' => true,
|
||||
'allow_empty' => true,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* GDPR deletion: Mailjet anonymises the contact immediately and purges it after 30 days.
|
||||
* This cannot be undone.
|
||||
*/
|
||||
public function deleteContact(int $contactId): void
|
||||
{
|
||||
$this->assertConfigured();
|
||||
|
||||
$this->request('DELETE', sprintf('contacts/%d', $contactId), [
|
||||
'allow_404' => true,
|
||||
'allow_empty' => true,
|
||||
'api_version' => 'v4',
|
||||
]);
|
||||
}
|
||||
|
||||
private function findOrCreateContactId(string $email): int
|
||||
{
|
||||
$contactId = $this->resolveContactId($email);
|
||||
@@ -246,15 +380,17 @@ class ApiClient
|
||||
{
|
||||
$allow404 = true === ($options['allow_404'] ?? false);
|
||||
$allowEmpty = true === ($options['allow_empty'] ?? false);
|
||||
$baseUrl = 'v4' === ($options['api_version'] ?? null) ? $this->getV4BaseUrl() : $this->getBaseUrl();
|
||||
unset($options['allow_404']);
|
||||
unset($options['allow_empty']);
|
||||
unset($options['api_version']);
|
||||
|
||||
$resourcePath = trim($resource, '/');
|
||||
|
||||
try {
|
||||
$response = $this->httpClient->request(
|
||||
$method,
|
||||
sprintf('%s/%s', $this->getBaseUrl(), $resourcePath),
|
||||
sprintf('%s/%s', $baseUrl, $resourcePath),
|
||||
array_merge($options, [
|
||||
'auth_basic' => sprintf('%s:%s', $this->apiKey, $this->apiSecret),
|
||||
])
|
||||
@@ -310,6 +446,16 @@ class ApiClient
|
||||
return rtrim($baseUrl, '/');
|
||||
}
|
||||
|
||||
/**
|
||||
* The configured base URL points at v3 (`…/v3/REST`); the v4 API sits beside it on the same host.
|
||||
*/
|
||||
private function getV4BaseUrl(): string
|
||||
{
|
||||
$baseUrl = preg_replace('~/v3/REST$~i', '', $this->getBaseUrl());
|
||||
|
||||
return sprintf('%s/v4', $baseUrl);
|
||||
}
|
||||
|
||||
private function assertConfigured(): void
|
||||
{
|
||||
if (true === empty($this->apiKey) || true === empty($this->apiSecret)) {
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Repository;
|
||||
|
||||
use App\Entity\TravelMailingList;
|
||||
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
|
||||
use Doctrine\Persistence\ManagerRegistry;
|
||||
|
||||
/**
|
||||
* @extends ServiceEntityRepository<TravelMailingList>
|
||||
*/
|
||||
class TravelMailingListRepository extends ServiceEntityRepository
|
||||
{
|
||||
public function __construct(ManagerRegistry $registry)
|
||||
{
|
||||
parent::__construct($registry, TravelMailingList::class);
|
||||
}
|
||||
|
||||
public function findOneByTravelCode(string $travelCode): ?TravelMailingList
|
||||
{
|
||||
return $this->findOneBy(['travelCode' => $travelCode]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<TravelMailingList>
|
||||
*/
|
||||
public function findDueForDeletion(\DateTimeImmutable $now): array
|
||||
{
|
||||
return $this->createQueryBuilder('l')
|
||||
->where('l.deleteAfter <= :now')
|
||||
->setParameter('now', $now)
|
||||
->orderBy('l.deleteAfter', 'ASC')
|
||||
->getQuery()
|
||||
->getResult();
|
||||
}
|
||||
}
|
||||
@@ -432,6 +432,18 @@ class TravelDataProvider
|
||||
return $this->travelLookupService->mapDateCodeToLabel($dateCode);
|
||||
}
|
||||
|
||||
/**
|
||||
* Map date code to the travel's start date.
|
||||
*
|
||||
* @param string $dateCode The date code to map
|
||||
*
|
||||
* @return \DateTimeImmutable|null The start date or null if not found
|
||||
*/
|
||||
public function mapDateCodeToStartDate(string $dateCode): ?\DateTimeImmutable
|
||||
{
|
||||
return $this->travelLookupService->mapDateCodeToStartDate($dateCode);
|
||||
}
|
||||
|
||||
/**
|
||||
* Map hotel code to hotel ID.
|
||||
*
|
||||
|
||||
@@ -127,6 +127,26 @@ class TravelIndex
|
||||
return $this->generateFilesMap()[$dateId]['label'] ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve a date code to the travel's start date.
|
||||
*
|
||||
* @param string $dateCode The date code to resolve
|
||||
*
|
||||
* @return \DateTimeImmutable|null The start date, or null if the code is not found or the travel has none
|
||||
*/
|
||||
public function mapDateCodeToStartDate(string $dateCode): ?\DateTimeImmutable
|
||||
{
|
||||
$dateId = $this->mapDateCodeToId($dateCode);
|
||||
|
||||
if (null === $dateId) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$dateFrom = $this->generateFilesMap()[$dateId]['dateFrom'] ?? null;
|
||||
|
||||
return $dateFrom instanceof \DateTimeImmutable ? $dateFrom : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert a hotel code string to its corresponding hotel ID.
|
||||
*
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Service;
|
||||
|
||||
use App\BpnConnect\Model\TravelMailingRecipient;
|
||||
use App\Entity\TravelMailingList;
|
||||
use App\Exception\NewsletterProviderException;
|
||||
use App\Mailjet\ApiClient;
|
||||
use Doctrine\ORM\EntityManagerInterface;
|
||||
use Psr\Log\LoggerInterface;
|
||||
|
||||
/**
|
||||
* Creates one Mailjet contact list per travel and deletes it again 30 days after the travel
|
||||
* started, together with every contact that is on no other Mailjet list.
|
||||
*/
|
||||
class TravelMailingListManager
|
||||
{
|
||||
private const string DELETE_AFTER = '+30 days';
|
||||
|
||||
public function __construct(
|
||||
private readonly ApiClient $mailjet,
|
||||
private readonly EntityManagerInterface $entityManager,
|
||||
private readonly LoggerInterface $logger,
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
* @param TravelMailingRecipient[] $recipients
|
||||
*
|
||||
* @throws NewsletterProviderException
|
||||
*/
|
||||
public function create(string $travelCode, array $recipients, \DateTimeImmutable $travelStartsAt): TravelMailingList
|
||||
{
|
||||
$listId = $this->mailjet->createContactsList($travelCode);
|
||||
|
||||
// Tracked before the contacts go in, so a list Mailjet already holds is never left without a row
|
||||
// that the cleanup would find.
|
||||
$mailingList = new TravelMailingList($travelCode, $listId, $travelStartsAt->modify(self::DELETE_AFTER));
|
||||
$this->entityManager->persist($mailingList);
|
||||
$this->entityManager->flush();
|
||||
|
||||
try {
|
||||
$jobId = $this->mailjet->addContactsToList($listId, $this->buildContacts($recipients));
|
||||
} catch (NewsletterProviderException $exception) {
|
||||
$this->discardEmptyList($mailingList);
|
||||
|
||||
throw $exception;
|
||||
}
|
||||
|
||||
$this->logger->info('Created Mailjet travel mailing list', [
|
||||
'travel_code' => $travelCode,
|
||||
'mailjet_list_id' => $listId,
|
||||
'mailjet_job_id' => $jobId,
|
||||
'recipients' => count($recipients),
|
||||
]);
|
||||
|
||||
return $mailingList;
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes the orphaned contacts first and the list last, so a run that fails halfway can be
|
||||
* repeated: the list still names whoever is left.
|
||||
*
|
||||
* @return int the number of contacts deleted
|
||||
*
|
||||
* @throws NewsletterProviderException
|
||||
*/
|
||||
public function delete(TravelMailingList $mailingList): int
|
||||
{
|
||||
$listId = $mailingList->getMailjetListId();
|
||||
|
||||
$deletedContacts = 0;
|
||||
foreach ($this->mailjet->getListContactIds($listId) as $contactId) {
|
||||
// Anyone who is, or recently was, on another list is kept: their newsletter consent or
|
||||
// another travel's mailing still needs the contact.
|
||||
if ([$listId] !== array_values(array_unique($this->mailjet->getContactListIds($contactId)))) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$this->mailjet->deleteContact($contactId);
|
||||
++$deletedContacts;
|
||||
}
|
||||
|
||||
$this->mailjet->deleteContactsList($listId);
|
||||
|
||||
$this->entityManager->remove($mailingList);
|
||||
$this->entityManager->flush();
|
||||
|
||||
$this->logger->info('Deleted Mailjet travel mailing list', [
|
||||
'travel_code' => $mailingList->getTravelCode(),
|
||||
'mailjet_list_id' => $listId,
|
||||
'deleted_contacts' => $deletedContacts,
|
||||
]);
|
||||
|
||||
return $deletedContacts;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param TravelMailingRecipient[] $recipients
|
||||
*
|
||||
* @return list<array{email: string, firstName: ?string}>
|
||||
*/
|
||||
private function buildContacts(array $recipients): array
|
||||
{
|
||||
// Several participants can share one address; the first name that comes with it wins.
|
||||
$contacts = [];
|
||||
foreach ($recipients as $recipient) {
|
||||
$email = mb_strtolower(trim($recipient->email));
|
||||
if ('' === $email || true === isset($contacts[$email])) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$contacts[$email] = [
|
||||
'email' => $email,
|
||||
'firstName' => '' !== trim($recipient->firstName) ? $recipient->firstName : null,
|
||||
];
|
||||
}
|
||||
|
||||
return array_values($contacts);
|
||||
}
|
||||
|
||||
private function discardEmptyList(TravelMailingList $mailingList): void
|
||||
{
|
||||
try {
|
||||
$this->mailjet->deleteContactsList($mailingList->getMailjetListId());
|
||||
} catch (NewsletterProviderException $exception) {
|
||||
// The row stays, so the scheduled cleanup removes the list later.
|
||||
$this->logger->error('Could not delete Mailjet travel mailing list after a failed import', [
|
||||
'travel_code' => $mailingList->getTravelCode(),
|
||||
'mailjet_list_id' => $mailingList->getMailjetListId(),
|
||||
'error' => $exception->getMessage(),
|
||||
]);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$this->entityManager->remove($mailingList);
|
||||
$this->entityManager->flush();
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user