src/EventSubscriber/Order/SendEmailsSubscriber.php line 146

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber\Order;
  3. use App\Ecommerce\Model\Order;
  4. use App\Model\Customer;
  5. use App\Repository\OrderRepository;
  6. use Factory\CartBundle\Classes\DataMapper\CartDataMapper;
  7. use Factory\CheckoutBundle\Model\AbstractOrder;
  8. use Factory\OrderManagementBundle\Classes\CsrEvents;
  9. use Factory\OrderManagementBundle\Repository\OrderRepository as FactoryOrderRepository;
  10. use Factory\SupportBundle\Contract\AbstractEvent;
  11. use Pimcore;
  12. use Pimcore\Bundle\EcommerceFrameworkBundle\EnvironmentInterface;
  13. use Pimcore\Bundle\EcommerceFrameworkBundle\Factory;
  14. use Pimcore\Event\Ecommerce\CommitOrderProcessorEvents;
  15. use Pimcore\Event\Model\Ecommerce\SendConfirmationMailEvent;
  16. use Pimcore\HttpKernel\BundleLocator\NotFoundException;
  17. use App\Classes\DataMapper\Invoice\InvoiceDataMapper;
  18. use App\Classes\StoeltingEvents;
  19. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
  20. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  21. use Symfony\Component\HttpFoundation\Request;
  22. use Symfony\Component\HttpFoundation\RequestStack;
  23. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  24. use Symfony\Component\Routing\RouterInterface;
  25. use Symfony\Contracts\Translation\TranslatorInterface;
  26. use Twig\Environment as TwigEnv;
  27. use function PHPUnit\Framework\throwException;
  28. class SendEmailsSubscriber implements EventSubscriberInterface
  29. {
  30.     /**
  31.      * @var RequestStack
  32.      */
  33.     protected $requestStack;
  34.     /**
  35.      * @var EnvironmentInterface
  36.      */
  37.     protected $environment;
  38.     /**
  39.      * @var OrderRepository
  40.      */
  41.     protected $orderRepository;
  42.     /**
  43.      * @var TwigEnv
  44.      */
  45.     protected $twig;
  46.     /**
  47.      * @var ParameterBagInterface
  48.      */
  49.     protected $parametarBag;
  50.     /**
  51.      * @var RouterInterface
  52.      */
  53.     protected $router;
  54.     /**
  55.      * @var TranslatorInterface
  56.      */
  57.     protected $translator;
  58.     protected $session;
  59.     protected $availableEmails = [
  60.         'emails.order-placed' => '/emails/order/order-placed',
  61.         'emails.order-placed-admin' => '/emails/order/order-placed-admin',
  62.         'emails.quote-save' => '/emails/quote/quote-saved',
  63.         'emails.quote-request' => '/emails/quote/quote-requested',
  64.         'emails.quote-request-admin' => '/emails/quote/quote-requested-admin',
  65.     ];
  66.     protected $factoryOrderRepository;
  67.     public static function getSubscribedEvents()
  68.     {
  69.         return [
  70.             StoeltingEvents::ORDER_PAID => [
  71.                 ['sendOrderPaidEmail'10]
  72.             ],
  73.             CsrEvents::ORDER_PAID => [
  74.                 ['sendOrderPaidEmail'10]
  75.             ],
  76.             StoeltingEvents::QUOTE_ORDER_PAID => [
  77.                 ['sendOrderPaidEmail'10]
  78.             ],
  79.             CommitOrderProcessorEvents::SEND_CONFIRMATION_MAILS => [
  80.                 ['sendOrderPlacedEmail'10],
  81.                 ['sendQuoteSavedEmail'10],
  82.                 ['sendQuoteRequestedEmail'10]
  83.             ],
  84.             CsrEvents::QUOTE_SEND_INVOICE_MANUAL => [
  85.                 ['simpleSendQuoteEmail'10]
  86.             ]
  87.         ];
  88.     }
  89.     public function __construct(
  90.         RequestStack $requestStack,
  91.         OrderRepository $orderRepository,
  92.         EnvironmentInterface $environment,
  93.         TwigEnv $twig,
  94.         FactoryOrderRepository $factoryOrderRepository,
  95.         TranslatorInterface $translator,
  96.         ParameterBagInterface $parameterBag,
  97.         RouterInterface $router,
  98.         SessionInterface $session
  99.     ) {
  100.         $this->requestStack $requestStack;
  101.         $this->environment $environment;
  102.         $this->orderRepository $orderRepository;
  103.         $this->twig $twig;
  104.         $this->factoryOrderRepository $factoryOrderRepository;
  105.         $this->translator $translator;
  106.         $this->parametarBag $parameterBag;
  107.         $this->router $router;
  108.         $this->session $session;
  109.     }
  110.     protected function getRequest(): Request
  111.     {
  112.         return $this->requestStack->getMasterRequest();
  113.     }
  114.     protected function getCurrentCustomer(): Customer
  115.     {
  116.         if (!$this->customer) {
  117.             $env Factory::getInstance()->getEnvironment();
  118.             $this->customer Customer::getById($env->getCurrentUserId());
  119.         }
  120.         return $this->customer;
  121.     }
  122.     protected function getCustomerAddress(string $addressId)
  123.     {
  124.         $customer $this->getCurrentCustomer();
  125.         return $customer->getAddress($addressId);
  126.     }
  127.     public function sendOrderPlacedEmail(SendConfirmationMailEvent $event)
  128.     {
  129.         if ($event->getOrder()->getOrderType() != Order::ORDER_TYPE_ORDER) {
  130.             return;
  131.         }
  132.         $event->setSkipDefaultBehaviour(true);
  133.         $path $this->getPath('emails.order-placed');
  134.         $customer $event->getOrder()->getCustomer();
  135.         $order $event->getOrder();
  136.         $params = [
  137.             'orderId' => $order->getId(),
  138.             'customerId' => $customer $customer->getId() : null,
  139.             'invoiceHtml' => $this->getInvoiceContent($event->getOrder()),
  140.             'order' => $event->getOrder()
  141.         ];
  142.         $mail $this->sendEmail($path$params, function (\Pimcore\Mail $mail) use ($params$order$customer) {
  143.             $name $order->getCustomerFirstname().' '.$order->getCustomerLastname();
  144.             $mail->addTo($order->getCustomerEmail(), $name);
  145.         });
  146.     }
  147.     public function sendOrderPaidEmail(AbstractEvent $event)
  148.     {
  149.         try {
  150.             $order $event->getSubject();
  151.             if (!$order instanceof AbstractOrder || $order->getOrderType() != Order::ORDER_TYPE_ORDER) {
  152.                 return;
  153.             }
  154.             $event->stopPropagation(true);
  155.             $path $this->getPath('emails.order-placed');
  156.             $ccEmail $this->getAdditionalEmail($order);
  157.             $customer $order->getCustomer();
  158.             $params = [
  159.                 'orderId' => $order->getId(),
  160.                 'customerId' => $customer $customer->getId() : null,
  161.                 'invoiceHtml' => $this->getInvoiceContent($order),
  162.                 'order' => $order
  163.             ];
  164.             $mail $this->sendEmail($path$params, function (\Pimcore\Mail $mail) use ($params$order$customer$ccEmail) {
  165.                 $name $order->getCustomerFirstname().' '.$order->getCustomerLastname();
  166.                 $mail->addTo($order->getCustomerEmail(), $name);
  167.                 if ($ccEmail) {
  168.                     $mail->addCc($ccEmail);
  169.                 }
  170.             });
  171.             $adminPath $this->getPath('emails.order-placed-admin');
  172.             $mail $this->sendEmail($adminPath$params, function (\Pimcore\Mail $mail) {
  173.             });
  174.         } catch (\Exception $e) {
  175.             // Log exception
  176.             \Pimcore\Log\Simple::log('stoelting''CHECKOUT [email]: '.$e->getMessage());
  177.             if (empty($event->hasArgument('xhr'))) {
  178.                 $this->session
  179.                     ->getFlashBag()
  180.                     ->add('error'$this->translator->trans('stoelting.payment.email.error'));
  181.                 return;
  182.             }
  183.             throw new \Exception($this->translator->trans('stoelting.payment.email.error'), 0$e);
  184.         }
  185.     }
  186.     public function sendQuoteSavedEmail(SendConfirmationMailEvent $event)
  187.     {
  188.         if ($event->getOrder()->getOrderType() != Order::ORDER_TYPE_QUOUTE_SAVED) {
  189.             return;
  190.         }
  191.         $event->setSkipDefaultBehaviour(true);
  192.         $path $this->getPath('emails.quote-save');
  193.         $customer $event->getOrder()->getCustomer();
  194.         $order $event->getOrder();
  195.         $params = [
  196.             'orderId' => $order->getId(),
  197.             'customerId' => $customer $customer->getId() : null,
  198.             'invoiceHtml' => $this->getInvoiceContent($event->getOrder()),
  199.             'order' => $event->getOrder()
  200.         ];
  201.         $this->sendEmail($path$params, function (\Pimcore\Mail $mail) use ($params$order$customer) {
  202.             $name $order->getCustomerFirstname().' '.$order->getCustomerLastname();
  203.             $mail->addTo($order->getCustomerEmail(), $name);
  204.         });
  205.     }
  206.     public function sendQuoteReminderEmail($documentPath$quoteReminders$quoteReminderLinks)
  207.     {
  208.         $document \Pimcore\Model\Document::getByPath($documentPath);
  209.         if (!$document) {
  210.             throw new \Exception('Unable to find email template!');
  211.         }
  212.         $request = new Request();
  213.         $request->setLocale($this->getEmailLocale());
  214.         $request->setDefaultLocale($this->getEmailLocale());
  215.         foreach ($quoteReminders as $key => $quoteReminder) {
  216.             $this->translator->setLocale($this->getEmailLocale());
  217.             $params = [
  218.                 'invoiceHtml' => $this->getInvoiceContent($quoteReminder$request),
  219.                 'link' => $quoteReminderLinks[$key]
  220.             ];
  221.             //sending the email
  222.             $mail = new \Pimcore\Mail();
  223.             $mail->setDocument($document);
  224.             $mail->setParams($params);
  225.             // This fixed sentry issue but caused sending of the broken emails to customers so this needs to be handled
  226.             // in the future
  227.             //$mail->addTo($quoteReminder->getCustomerEmail());
  228.             $mail->send();
  229.         }
  230.     }
  231.     public function sendPricesImportEmail($documentPath)
  232.     {
  233.         $document \Pimcore\Model\Document::getByPath($documentPath);
  234.         if (!$document) {
  235.             throw new \Exception('Unable to find email template!');
  236.         }
  237.         //sending the email
  238.         $mail = new \Pimcore\Mail();
  239.         $mail->setDocument($document);
  240.         $mail->send();
  241.     }
  242.     public function getEmailLocale() {
  243.         return 'en';
  244.     }
  245.     public function sendQuoteRequestedEmail(SendConfirmationMailEvent $event)
  246.     {
  247.         if ($event->getOrder()->getOrderType() != Order::ORDER_TYPE_QUOUTE_REQUEST) {
  248.             return;
  249.         }
  250.         $event->setSkipDefaultBehaviour(true);
  251.         $this->__sendEmail($event->getOrder(), $this->getPath('emails.quote-request'));
  252.         $order $event->getOrder();
  253.         $customer $order->getCustomer();
  254.         $params = [
  255.             'orderId' => $order->getId(),
  256.             'customerId' => $customer $customer->getId() : null,
  257.             'invoiceHtml' => $this->getInvoiceContent($order),
  258.             'order' => $order
  259.         ];
  260.         $adminPath $this->getPath('emails.quote-request-admin');
  261.         $this->sendEmail($adminPath$params, function (\Pimcore\Mail $mail) {
  262.         });
  263.     }
  264.     public function simpleSendQuoteEmail (AbstractEvent $event)
  265.     {
  266.         $order $event->getSubject();
  267.         $path $this->getPath('emails.quote-request');
  268.         $customer $order->getCustomer();
  269.         $toName $order->getCustomerFirstname().' '.$order->getCustomerLastname();
  270.         $toEmail $order->getCustomerEmail();
  271.         $ccEmail $this->getAdditionalEmail($order);
  272.         $params = [
  273.             'orderId' => $order->getId(),
  274.             'customerId' => $customer $customer->getId() : null,
  275.             'invoiceHtml' => $this->getInvoiceContent($order),
  276.             'order' => $order
  277.         ];
  278.         $this->sendEmail($path$params, function (\Pimcore\Mail $mail) use ($toName$toEmail$ccEmail) {
  279.             $mail->addTo($toEmail$toName);
  280.             if ($ccEmail) {
  281.                 $mail->addCc($ccEmail$ccEmail);
  282.             }
  283.         });
  284.         $adminPath $this->getPath('emails.quote-request-admin');
  285.         $this->sendEmail($adminPath$params, function (\Pimcore\Mail $mail) {
  286.         });
  287.     }
  288.     /**
  289.      * @param AbstractOrder $order
  290.      *
  291.      * @return null|string
  292.      */
  293.     private function getAdditionalEmail($order)
  294.     {
  295.         $customized $order->getCustomized();
  296.         if (!in_array('getOrderAditionalEmailAddress'$customized->getBrickGetters())) {
  297.             return null;
  298.         }
  299.         $additionalAddress $customized->getOrderAditionalEmailAddress();
  300.         if (!$additionalAddress) {
  301.             return null;
  302.         }
  303.         return $additionalAddress->getEmail();
  304.     }
  305.     private function __sendEmail($order$path)
  306.     {
  307.         $customer $order->getCustomer();
  308.         $params = [
  309.             'orderId' => $order->getId(),
  310.             'customerId' => $customer $customer->getId() : null,
  311.             'invoiceHtml' => $this->getInvoiceContent($order),
  312.             'order' => $order
  313.         ];
  314.         $this->sendEmail($path$params, function (\Pimcore\Mail $mail) use ($order) {
  315.             $name $order->getCustomerFirstname().' '.$order->getCustomerLastname();
  316.             $mail->addTo($order->getCustomerEmail(), $name);
  317.         });
  318.     }
  319.     protected function getPath($name)
  320.     {
  321.         $path $this->availableEmails[$name] ?? null;
  322.         if (Pimcore::getContainer()->hasParameter($name)) {
  323.             $path Pimcore::getContainer()->getParameter($name);
  324.         }
  325.         return $path;
  326.     }
  327.     protected function sendEmail($documentPath, array $params = [], $callable null)
  328.     {
  329.         $document \Pimcore\Model\Document::getByPath($documentPath);
  330.         if (!$document) {
  331.             throw new \Exception(sprintf('Unable to find email template %s.'$documentPath));
  332.         }
  333.         //sending the email
  334.         $mail = new \Pimcore\Mail();
  335.         $mail->setDocument($document);
  336.         $mail->setParams($params);
  337.         if ($callable && is_callable($callable)) {
  338.             $callable($mail$params$document);
  339.         }
  340.         try {
  341.             return $mail->send();
  342.         } catch (\Throwable $e) {
  343.             \Pimcore\Log\Simple::log('stoelting-email'$e->getMessage() . $e->getTraceAsString());
  344.             throw $e;
  345.         }
  346.     }
  347.     protected function getInvoiceContent($order$request null)
  348.     {
  349.         $order $this->factoryOrderRepository->findOrFail($order->getId());
  350.         if (!$order || $order->getOrderState() != AbstractOrder::ORDER_STATE_COMMITTED) {
  351.             throw new NotFoundException($this->translator->trans('stoelting.not-found.order'));
  352.         }
  353.         if (!$request) {
  354.             $request $this->getRequest();
  355.         }
  356.         return $this->twig->render('email/invoice.html.twig', [
  357.             'data' => (new InvoiceDataMapper($order))->toArray($request),
  358.             'summary' => (new CartDataMapper($order))->toArray($request)
  359.         ]);
  360.     }
  361. }