<?php
namespace Lnb\Shopware6\LnbReviewMail\Flow\Action;
use Psr\Log\LoggerInterface;
use Shopware\Core\Content\Flow\Dispatching\Action\FlowAction;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepository;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter;
use Shopware\Core\Framework\Event\FlowEvent;
use Shopware\Core\Framework\Event\OrderAware;
class SendReviewMailAction extends FlowAction
{
private EntityRepository $reviewMailRepository;
private LoggerInterface $logger;
public function __construct(EntityRepository $reviewMailRepository, LoggerInterface $logger)
{
$this->reviewMailRepository = $reviewMailRepository;
$this->logger = $logger;
}
public static function getName(): string
{
return 'lnbReviewMail.action.send.review.mail';
}
public static function getSubscribedEvents(): array
{
return [
self::getName() => 'handle',
];
}
public function requirements(): array
{
return [OrderAware::class];
}
public function handle(FlowEvent $event): void
{
if (! $event->getEvent() instanceof OrderAware) {
return; //flow is not supported
}
$orderId = $event->getEvent()->getOrderId();
$config = $event->getConfig();
if (! isset($config['days'])) {
$this->logger->critical(sprintf('Missing required parameter "days" for flow "%s" in action sendReviewMailAction', $event->getEvent()->getName()));
throw new \InvalidArgumentException('Missing required parameter "days"');
}
if (! isset($config['mailTemplateId'])) {
$this->logger->critical(sprintf('Missing required parameter "mailTemplateId" for flow "%s" in action sendReviewMailAction', $event->getEvent()->getName()));
throw new \InvalidArgumentException('Missing required parameter "mailTemplateId"');
}
if ($this->delayedMailAlreadyExists($orderId)) {
return;
}
try {
$this->reviewMailRepository->create([
[
'orderId' => $orderId,
'mailTemplateId' => $config['mailTemplateId'],
'status' => 'pending',
'days' => $config['days'],
'dueDate' => $this->getDueDate($config['days']),
],
], $event->getContext());
} catch (\Throwable $e) {
$this->logger->error('Could not create review mail', [
'orderId' => $orderId,
'mailTemplateId' => $config['mailTemplateId'],
'days' => $config['days'],
'dueDate' => $this->getDueDate($config['days']),
'error' => $e->getMessage(),
'trace' => $e->getTraceAsString(),
]);
}
}
private function getDueDate(int $days): \DateTimeInterface
{
return (new \DateTime())->modify(sprintf('+%d days', $days));
}
private function delayedMailAlreadyExists(string $orderId): bool
{
$criteria = new Criteria();
$criteria->addFilter(new EqualsFilter('orderId', $orderId));
$result = $this->reviewMailRepository->search($criteria, \Shopware\Core\Framework\Context::createDefaultContext());
return $result->getTotal() > 0;
}
}