vendor/crehler/mojebambino-engine/src/Subscriber/CheckoutSubscriber.php line 92

Open in your IDE?
  1. <?php declare(strict_types=1);
  2. namespace Crehler\MojeBambinoEngine\Subscriber;
  3. use Crehler\MojeBambinoEngine\Struct\AddressStruct;
  4. use Crehler\MojeBambinoEngine\Struct\NewsletterStruct;
  5. use Crehler\MojeBambinoEngine\Util\Lifecycle\ActivateDeactivate;
  6. use Shopware\Core\Checkout\Cart\Event\CheckoutOrderPlacedEvent;
  7. use Shopware\Core\Checkout\Customer\CustomerEntity;
  8. use Shopware\Core\Content\Newsletter\SalesChannel\NewsletterSubscribeRoute;
  9. use Shopware\Core\Framework\Context;
  10. use Shopware\Core\Framework\DataAbstractionLayer\EntityRepository;
  11. use Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface;
  12. use Shopware\Core\Framework\DataAbstractionLayer\Exception\InconsistentCriteriaIdsException;
  13. use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
  14. use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter;
  15. use Shopware\Core\Framework\Uuid\Uuid;
  16. use Shopware\Core\Framework\Validation\DataBag\RequestDataBag;
  17. use Shopware\Core\System\Country\CountryCollection;
  18. use Shopware\Core\System\SalesChannel\SalesChannelContext;
  19. use Shopware\Core\System\Salutation\SalutationCollection;
  20. use Shopware\Core\System\Salutation\SalutationEntity;
  21. use Shopware\Storefront\Page\Checkout\Confirm\CheckoutConfirmPageLoadedEvent;
  22. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  23. use Symfony\Component\HttpFoundation\ParameterBag;
  24. use Symfony\Component\HttpFoundation\Request;
  25. use Symfony\Component\HttpFoundation\RequestStack;
  26. use Symfony\Component\HttpKernel\Event\ControllerEvent;
  27. use Symfony\Component\HttpKernel\Event\RequestEvent;
  28. use Symfony\Component\HttpKernel\KernelEvents;
  29. class CheckoutSubscriber implements EventSubscriberInterface
  30. {
  31.     private EntityRepository $salutationRepository;
  32.     private EntityRepository $countryRepository;
  33.     private EntityRepository $orderAddressRepository;
  34.     private EntityRepository $orderRepository;
  35.     private NewsletterSubscribeRoute $newsletterService;
  36.     private RequestStack $request;
  37.     public function __construct(
  38.         EntityRepository         $salutationRepository,
  39.         EntityRepository         $countryRepository,
  40.         EntityRepository         $orderAddressRepository,
  41.         EntityRepository         $orderRepository,
  42.         NewsletterSubscribeRoute $newsletterService,
  43.         RequestStack             $request
  44.     )
  45.     {
  46.         $this->salutationRepository $salutationRepository;
  47.         $this->countryRepository $countryRepository;
  48.         $this->orderAddressRepository $orderAddressRepository;
  49.         $this->orderRepository $orderRepository;
  50.         $this->newsletterService $newsletterService;
  51.         $this->request $request;
  52.     }
  53.     /**
  54.      * @return array
  55.      */
  56.     public static function getSubscribedEvents(): array
  57.     {
  58.         return [
  59.             CheckoutConfirmPageLoadedEvent::class => 'onCheckoutConfirmPage',
  60.             CheckoutOrderPlacedEvent::class => 'onCheckoutOrderPlaced'
  61.         ];
  62.     }
  63.     /**
  64.      * @param CheckoutConfirmPageLoadedEvent $event
  65.      */
  66.     public function onCheckoutConfirmPage(CheckoutConfirmPageLoadedEvent $event)
  67.     {
  68.         $page $event->getPage();
  69.         $salesChannelContext $event->getSalesChannelContext();
  70.         $page->addExtension(
  71.             'address',
  72.             (new AddressStruct())
  73.                 ->setSalutations($this->getSalutations($salesChannelContext))
  74.                 ->setCountries($this->getCountries($salesChannelContext))
  75.         );
  76.         $newsletter $event->getSalesChannelContext()->getCustomer()->getNewsletter();
  77.         $page->addExtension('newsletter', new NewsletterStruct((bool)$newsletter));
  78.     }
  79.     /**
  80.      * @param CheckoutOrderPlacedEvent $event
  81.      */
  82.     public function onCheckoutOrderPlaced(CheckoutOrderPlacedEvent $event)
  83.     {
  84.         $request $this->request->getCurrentRequest();
  85.         $address $request->get('shippingAddress'null);
  86.         $isAfterSellerVisit $request->get('afterSellerVisit'false);
  87.         $custInvoiceValue $request->get('custInvoiceValue');
  88.         $govProject $request->get('govProject');
  89.         $subscribeNewsletter $request->get('subscribeNewsletter'null);
  90.         $emailConfirm = (bool)$request->get('emailConfirm'false);
  91.         $telephoneConfirm = (bool)$request->get('telephoneConfirm'false);
  92.         $salesChannelContext $request->attributes->get('sw-sales-channel-context');
  93.         $customer $salesChannelContext->getCustomer();
  94.         //Subscribe newsletter
  95.         if (!empty($subscribeNewsletter) && !empty($salesChannelContext)) {
  96.             $dataBag = new RequestDataBag([
  97.                 'option' => 'direct',
  98.                 'storefrontUrl' => $request->attributes->get('sw-sales-channel-absolute-base-url')
  99.             ]);
  100.             try {
  101.                 $this->newsletterService->subscribe($this->hydrateFromCustomer($dataBag$customer), $salesChannelContext);
  102.             } catch (\Exception $exception) {
  103.             }
  104.         }
  105.         //Insert after Seller visit state
  106.         $data = [
  107.             'id' => $event->getOrder()->getId(),
  108.             'customFields' => [
  109.                 ActivateDeactivate::ORDER_CUSTOM_FIELDS[0]['name'] => (bool)$isAfterSellerVisit,
  110.                 ActivateDeactivate::ORDER_CUSTOM_FIELDS[1]['name'] => $custInvoiceValue,
  111.                 ActivateDeactivate::ORDER_CUSTOM_FIELDS[2]['name'] => $govProject,
  112.                 'emailconfirm' => $emailConfirm,
  113.                 'telephoneconfirm' => $telephoneConfirm
  114.             ]
  115.         ];
  116.         //Insert invoice VAT address
  117.         if (!empty($address)) {
  118.             $address['salutationId'] = $this->getValidSalutationId($event->getContext());
  119.             $address['lastName'] = ' ';
  120.             $order $event->getOrder();
  121.             $context $event->getContext();
  122.             $countryId $customer->getDefaultShippingAddress()->getCountry()->getId();
  123.             $id $this->insertOrderInvoiceAddress($address$order->getId(), $countryId$context);
  124.             $data['customFields']['invoice_address_id'] = $id;
  125.         }
  126.         $this->orderRepository->update([$data], $event->getContext());
  127.     }
  128.     /**
  129.      * @throws InconsistentCriteriaIdsException
  130.      */
  131.     private function getSalutations(SalesChannelContext $salesChannelContext): SalutationCollection
  132.     {
  133.         /** @var SalutationCollection $salutations */
  134.         $salutations $this->salutationRepository->search(new Criteria(), $salesChannelContext->getContext())->getEntities();
  135.         $salutations->sort(function (SalutationEntity $aSalutationEntity $b) {
  136.             return $b->getSalutationKey() <=> $a->getSalutationKey();
  137.         });
  138.         return $salutations;
  139.     }
  140.     /**
  141.      * @throws InconsistentCriteriaIdsException
  142.      */
  143.     private function getCountries(SalesChannelContext $salesChannelContext): CountryCollection
  144.     {
  145.         $criteria = (new Criteria())
  146.             ->addFilter(new EqualsFilter('country.active'true))
  147.             ->addAssociation('states');
  148.         /** @var CountryCollection $countries */
  149.         $countries $this->countryRepository->search($criteria$salesChannelContext->getContext())->getEntities();
  150.         $countries->sortCountryAndStates();
  151.         return $countries;
  152.     }
  153.     private function insertOrderInvoiceAddress(array $invoiceOrderAddressstring $orderIdstring $countryIdContext $context): string
  154.     {
  155.         $id Uuid::randomHex();
  156.         $invoiceOrderAddress['orderId'] = $orderId;
  157.         $invoiceOrderAddress['id'] = $id;
  158.         if (empty($invoiceOrderAddress['firstName'])) {
  159.             $invoiceOrderAddress['firstName'] = ' ';
  160.         }
  161.         if (empty($invoiceOrderAddress['street'])) {
  162.             $invoiceOrderAddress['street'] = ' ';
  163.         }
  164.         if (empty($invoiceOrderAddress['zipcode'])) {
  165.             $invoiceOrderAddress['zipcode'] = ' ';
  166.         }
  167.         if (empty($invoiceOrderAddress['city'])) {
  168.             $invoiceOrderAddress['city'] = ' ';
  169.         }
  170.         if (empty($invoiceOrderAddress['countryId'])) {
  171.             $invoiceOrderAddress['countryId'] = $countryId;
  172.         }
  173.         $this->orderAddressRepository->upsert([$invoiceOrderAddress], $context);
  174.         return $id;
  175.     }
  176.     private function getValidSalutationId(Context $context): string
  177.     {
  178.         $criteria = (new Criteria())->setLimit(1);
  179.         return $this->salutationRepository->searchIds($criteria$context)->getIds()[0];
  180.     }
  181.     private function hydrateFromCustomer(RequestDataBag $dataBagCustomerEntity $customer): RequestDataBag
  182.     {
  183.         $dataBag->set('email'$customer->getEmail());
  184.         $dataBag->set('salutationId'$customer->getSalutationId());
  185.         $dataBag->set('title'$customer->getTitle());
  186.         $dataBag->set('firstName'$customer->getFirstName());
  187.         $dataBag->set('lastName'$customer->getLastName());
  188.         $dataBag->set('zipCode'$customer->getDefaultShippingAddress()->getZipCode());
  189.         $dataBag->set('city'$customer->getDefaultShippingAddress()->getCity());
  190.         return $dataBag;
  191.     }
  192. }