custom/plugins/fgitsAutoinvoiceSW6/src/Subscriber/OrderSubscriber.php line 236

Open in your IDE?
  1. <?php declare(strict_types=1);
  2. namespace Fgits\AutoInvoice\Subscriber;
  3. use Fgits\AutoInvoice\ScheduledTask\Export\AutoInvoiceExportTask;
  4. use Fgits\AutoInvoice\ScheduledTask\OrderScan\AutoInvoiceOrderScanTask;
  5. use Fgits\AutoInvoice\Service\CustomFields\OrderCustomFields;
  6. use Fgits\AutoInvoice\Service\DB\Order as DBOrder;
  7. use Fgits\AutoInvoice\Service\FgitsLibrary\ScheduledTask;
  8. use Fgits\AutoInvoice\Service\FgitsLibrary\Utility;
  9. use Fgits\AutoInvoice\Service\OrderProcessor;
  10. use Psr\Log\LoggerInterface;
  11. use Shopware\Core\Checkout\Cart\Event\CheckoutOrderPlacedEvent;
  12. use Shopware\Core\Checkout\Cart\Exception\OrderDeliveryNotFoundException;
  13. use Shopware\Core\Checkout\Cart\Exception\OrderNotFoundException;
  14. use Shopware\Core\Checkout\Cart\Exception\OrderTransactionNotFoundException;
  15. use Shopware\Core\Checkout\Order\Aggregate\OrderDelivery\OrderDeliveryEntity;
  16. use Shopware\Core\Checkout\Order\Aggregate\OrderTransaction\OrderTransactionEntity;
  17. use Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface;
  18. use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
  19. use Shopware\Core\System\StateMachine\Event\StateMachineStateChangeEvent;
  20. use Shopware\Core\System\SystemConfig\SystemConfigService;
  21. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  22. use Symfony\Component\HttpFoundation\RequestStack;
  23. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  24. /**
  25.  * Copyright (c) 2020. GOLLE IT.
  26.  *
  27.  * @author Andrey Grigorkin <andrey@golle-it.de>
  28.  */
  29. class OrderSubscriber implements EventSubscriberInterface
  30. {
  31.     private DBOrder $dbOrder;
  32.     private OrderCustomFields $orderCustomFields;
  33.     private ScheduledTask $scheduledTask;
  34.     private OrderProcessor $orderProcessor;
  35.     private EntityRepositoryInterface $orderRepository;
  36.     private EntityRepositoryInterface $orderDeliveryRepository;
  37.     private EntityRepositoryInterface $orderTransactionRepository;
  38.     private Utility $utility;
  39.     private RequestStack $requestStack;
  40.     private SessionInterface $session;
  41.     private SystemConfigService $systemConfigService;
  42.     private LoggerInterface $logger;
  43.     /**
  44.      * OrderSubscriber constructor.
  45.      *
  46.      * @param DBOrder $dbOrder
  47.      * @param OrderCustomFields $orderCustomFields
  48.      * @param ScheduledTask $scheduledTask
  49.      * @param OrderProcessor $orderProcessor
  50.      * @param EntityRepositoryInterface $orderRepository
  51.      * @param EntityRepositoryInterface $orderDeliveryRepository
  52.      * @param EntityRepositoryInterface $orderTransactionRepository
  53.      * @param Utility $utility
  54.      * @param RequestStack $requestStack
  55.      * @param SessionInterface $session
  56.      * @param SystemConfigService $systemConfigService
  57.      * @param LoggerInterface $logger
  58.      */
  59.     public function __construct(
  60.         DBOrder $dbOrder,
  61.         OrderCustomFields $orderCustomFields,
  62.         ScheduledTask $scheduledTask,
  63.         OrderProcessor $orderProcessor,
  64.         EntityRepositoryInterface $orderRepository,
  65.         EntityRepositoryInterface $orderDeliveryRepository,
  66.         EntityRepositoryInterface $orderTransactionRepository,
  67.         Utility $utility,
  68.         RequestStack $requestStack,
  69.         SessionInterface $session,
  70.         SystemConfigService $systemConfigService,
  71.         LoggerInterface $logger
  72.     ) {
  73.         $this->dbOrder                    $dbOrder;
  74.         $this->orderCustomFields          $orderCustomFields;
  75.         $this->scheduledTask              $scheduledTask;
  76.         $this->orderProcessor             $orderProcessor;
  77.         $this->orderRepository            $orderRepository;
  78.         $this->orderDeliveryRepository    $orderDeliveryRepository;
  79.         $this->orderTransactionRepository $orderTransactionRepository;
  80.         $this->utility                    $utility;
  81.         $this->requestStack               $requestStack;
  82.         $this->session                    $session;
  83.         $this->systemConfigService        $systemConfigService;
  84.         $this->logger                     $logger;
  85.     }
  86.     public static function getSubscribedEvents(): array
  87.     {
  88.         return[
  89.             CheckoutOrderPlacedEvent::class => [['scheduleScheduledTasks'], ['onOrderPlaced']],
  90.             'state_machine.order_transaction.state_changed' => 'onOrderTransactionStateChanged',
  91.             'state_machine.order_delivery.state_changed' => 'onOrderDeliveryStateChanged',
  92.             'state_machine.order.state_changed' => [['onOrderStateChanged'], ['onOrderStateChangedTickets']]
  93.         ];
  94.     }
  95.     public function scheduleScheduledTasks(): void
  96.     {
  97.         $this->scheduledTask->schedule(AutoInvoiceExportTask::getTaskName());
  98.         $this->scheduledTask->schedule(AutoInvoiceOrderScanTask::getTaskName());
  99.     }
  100.     /**
  101.      * Gets invoked when an order is created.
  102.      *
  103.      * @param CheckoutOrderPlacedEvent $event
  104.      */
  105.     public function onOrderPlaced(CheckoutOrderPlacedEvent $event): void
  106.     {
  107.         $this->session->set('fgits_autoinvoice_latest_order_id'$event->getOrder()->getId());
  108.         $config $this->systemConfigService->get('fgitsAutoinvoiceSW6.config'$event->getSalesChannelId());
  109.         if (!$config['active']) {
  110.             return;
  111.         }
  112.         $request $this->requestStack->getCurrentRequest();
  113.         if ($config['changeCheckoutEmail'] && isset($request) && $request->get('fgitsChangeCheckoutEmail')) {
  114.             $this->orderCustomFields->setCheckoutEmail($event->getOrder(), $request->get('fgitsChangeCheckoutEmail'));
  115.         }
  116.         if ($config['sendCustomerInvoice'] && isset($request) && !$request->get('fgitsSendCustomerInvoice')) {
  117.             $this->orderCustomFields->setCustomerNoInvoice($event->getOrder());
  118.         }
  119.         $context $this->utility->getContext($event->getOrder(), $event->getContext());
  120.         $order $this->dbOrder->getOrderById($event->getOrderId(), $this->utility->getOrderAssociations(), $context);
  121.         try {
  122.             $this->orderProcessor->processOrder($order$contexttrue);
  123.         } catch (\Exception $e) {
  124.             $this->logger->error('[#fgits] fgitsAutoinvoiceSW6: ' __CLASS__ '::' __FUNCTION__ '(): Order #' $order->getOrderNumber() . ': ' print_r($e->getMessage(), true));
  125.         }
  126.     }
  127.     /**
  128.      * Gets invoked when the payment status is changed.
  129.      *
  130.      * @param StateMachineStateChangeEvent $event
  131.      */
  132.     public function onOrderTransactionStateChanged(StateMachineStateChangeEvent $event): void
  133.     {
  134.         $config $this->systemConfigService->get('fgitsAutoinvoiceSW6.config'$event->getSalesChannelId());
  135.         if (!$config['active'] || empty($config['conditionPaymentStatus'])) {
  136.             return;
  137.         }
  138.         $orderTransactionId $event->getTransition()->getEntityId();
  139.         $criteria = new Criteria([$orderTransactionId]);
  140.         $criteria->addAssociation('paymentMethod');
  141.         $criteria->addAssociation('order.orderCustomer');
  142.         $criteria->addAssociation('order.transactions');
  143.         /** @var OrderTransactionEntity|null $orderTransaction */
  144.         $orderTransaction $this->orderTransactionRepository->search($criteria$event->getContext())->first();
  145.         if ($orderTransaction === null) {
  146.             throw new OrderTransactionNotFoundException($orderTransactionId);
  147.         }
  148.         if ($orderTransaction->getPaymentMethod() === null) {
  149.             throw new OrderTransactionNotFoundException($orderTransactionId);
  150.         }
  151.         if ($orderTransaction->getOrder() === null) {
  152.             throw new OrderNotFoundException($orderTransactionId);
  153.         }
  154.         $context $this->utility->getContext($orderTransaction->getOrder(), $event->getContext());
  155.         $order $this->dbOrder->getOrderById($orderTransaction->getOrderId(), $this->utility->getOrderAssociations(), $context);
  156.         $order->fgitsAutoinvoiceOrderTransactionId $orderTransactionId;
  157.         try {
  158.             $this->orderProcessor->processOrder($order$context);
  159.         } catch (\Exception $e) {
  160.             $this->logger->error('[#fgits] fgitsAutoinvoiceSW6: ' __CLASS__ '::' __FUNCTION__ '(): Order #' $order->getOrderNumber() . ': ' print_r($e->getMessage(), true));
  161.         }
  162.     }
  163.     /**
  164.      * Gets invoked when the delivery status is changed.
  165.      *
  166.      * @param StateMachineStateChangeEvent $event
  167.      */
  168.     public function onOrderDeliveryStateChanged(StateMachineStateChangeEvent $event): void
  169.     {
  170.         $config $this->systemConfigService->get('fgitsAutoinvoiceSW6.config'$event->getSalesChannelId());
  171.         if (!$config['active'] || empty($config['conditionDeliveryStatus'])) {
  172.             return;
  173.         }
  174.         $orderDeliveryId $event->getTransition()->getEntityId();
  175.         $criteria = new Criteria([$orderDeliveryId]);
  176.         $criteria->addAssociation('order.orderCustomer');
  177.         $criteria->addAssociation('order.transactions');
  178.         /** @var OrderDeliveryEntity|null $orderDelivery */
  179.         $orderDelivery $this->orderDeliveryRepository->search($criteria$event->getContext())->first();
  180.         if ($orderDelivery === null) {
  181.             throw new OrderDeliveryNotFoundException($orderDeliveryId);
  182.         }
  183.         if ($orderDelivery->getOrder() === null) {
  184.             throw new OrderNotFoundException($orderDeliveryId);
  185.         }
  186.         $context $this->utility->getContext($orderDelivery->getOrder(), $event->getContext());
  187.         $order $this->dbOrder->getOrderById($orderDelivery->getOrderId(), $this->utility->getOrderAssociations(), $context);
  188.         try {
  189.             $this->orderProcessor->processOrder($order$context);
  190.         } catch (\Exception $e) {
  191.             $this->logger->error('[#fgits] fgitsAutoinvoiceSW6: ' __CLASS__ '::' __FUNCTION__ '(): Order #' $order->getOrderNumber() . ': ' print_r($e->getMessage(), true));
  192.         }
  193.     }
  194.     /**
  195.      * Gets invoked when the order status is changed.
  196.      *
  197.      * @param StateMachineStateChangeEvent $event
  198.      */
  199.     public function onOrderStateChanged(StateMachineStateChangeEvent $event): void
  200.     {
  201.         $config $this->systemConfigService->get('fgitsAutoinvoiceSW6.config'$event->getSalesChannelId());
  202.         if (!$config['active'] || empty($config['conditionOrderStatus'])) {
  203.             return;
  204.         }
  205.         $orderId $event->getTransition()->getEntityId();
  206.         $criteria = new Criteria([$orderId]);
  207.         $criteria->addAssociation('orderCustomer');
  208.         $criteria->addAssociation('transactions');
  209.         $order $this->orderRepository->search($criteria$event->getContext())->first();
  210.         if ($order === null) {
  211.             throw new OrderNotFoundException($orderId);
  212.         }
  213.         $context $this->utility->getContext($order$event->getContext());
  214.         $order $this->dbOrder->getOrderById($orderId$this->utility->getOrderAssociations(), $context);
  215.         try {
  216.             $this->orderProcessor->processOrder($order$context);
  217.         } catch (\Exception $e) {
  218.             $this->logger->error('[#fgits] fgitsAutoinvoiceSW6: ' __CLASS__ '::' __FUNCTION__ '(): Order #' $order->getOrderNumber() . ': ' print_r($e->getMessage(), true));
  219.         }
  220.     }
  221.     /**
  222.      * Gets invoked when the order status is changed.
  223.      *
  224.      * @param StateMachineStateChangeEvent $event
  225.      */
  226.     public function onOrderStateChangedTickets(StateMachineStateChangeEvent $event): void
  227.     {
  228.         $config $this->systemConfigService->get('FgitsTicketsV3.config'$event->getSalesChannelId());
  229.         if (!$this->utility->isPluginActive('FgitsTicketsV3') || !$config['extrasActive'] || ($config['extrasActionOnCancel'] == 'none' && $config['extrasActionOnReopen'] == 'none')) {
  230.             return;
  231.         }
  232.         if ($event->getNextState()->getTechnicalName() == 'cancelled') {
  233.             $ticketsExtras $this->utility->getService('Fgits\FgitsTicketsV3\Service\Extras');
  234.             switch ($config['extrasActionOnCancel']) {
  235.                 case 'deactivate':
  236.                     $ticketsExtras->deactivateTickets($event->getTransition()->getEntityId(), $event->getContext());
  237.                     break;
  238.                 case 'delete':
  239.                     $ticketsExtras->deleteTickets($event->getTransition()->getEntityId(), $event->getContext());
  240.                     break;
  241.             }
  242.         } elseif ($event->getNextState()->getTechnicalName() == 'open' && $event->getPreviousState()->getTechnicalName() == 'cancelled' && $config['extrasActionOnReopen'] == 'activate') {
  243.             $ticketsExtras $this->utility->getService('Fgits\FgitsTicketsV3\Service\Extras');
  244.             $ticketsExtras->activateTickets($event->getTransition()->getEntityId(), $event->getContext());
  245.         }
  246.     }
  247. }