custom/plugins/CustomPricePlugin/src/Subscriber/CustomPriceSubscriber.php line 1623

Open in your IDE?
  1. <?php
  2. namespace CustomPricePlugin\Subscriber;
  3. use Psr\Log\LoggerInterface;
  4. use Shopware\Core\Content\Product\ProductEvents;
  5. //use Shopware\Core\Content\Product\ProductLoadedEvent;
  6. use Shopware\Core\Framework\Context;
  7. use Symfony\Bundle\FrameworkBundle\Controller\RedirectController;
  8. use Symfony\Component\HttpFoundation\RedirectResponse;
  9. use Symfony\Component\HttpFoundation\RequestStack;
  10. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  11. use Symfony\Component\DependencyInjection\ContainerInterface;
  12. use Shopware\Core\Checkout\Cart\Event\CartConvertedEvent;
  13. use Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface;
  14. use Shopware\Core\Framework\DataAbstractionLayer\Event\EntityLoadedEvent;
  15. use Doctrine\DBAL\Connection;
  16. use Shopware\Core\Content\Product\Events\ProductListingResultEvent;
  17. use Shopware\Core\Checkout\Cart\Price\Struct\CalculatedPrice;
  18. use Shopware\Core\Content\Product\DataAbstractionLayer\CheapestPrice\CalculatedCheapestPrice;
  19. use Shopware\Core\Framework\DataAbstractionLayer\Pricing\Price;
  20. use Shopware\Core\Framework\DataAbstractionLayer\Pricing\PriceCollection;
  21. use Shopware\Core\Checkout\Cart\Tax\Struct\TaxRuleCollection;
  22. use Shopware\Core\Checkout\Cart\Tax\Struct\TaxRule;
  23. use \Shopware\Core\Checkout\Cart\Tax\Struct\CalculatedTaxCollection;
  24. use \Shopware\Core\Checkout\Cart\Tax\Struct\CalculatedTax;
  25. use Symfony\Component\Routing\RouterInterface;
  26. use Symfony\Component\HttpKernel\Exception\RedirectResponseException;
  27. use Shopware\Core\Content\Product\Aggregate\ProductPrice\ProductPriceCollection;
  28. use Shopware\Core\Content\Product\Aggregate\ProductPrice\ProductPriceEntity;
  29. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  30. use Shopware\Core\Checkout\Cart\Cart;
  31. use Shopware\Core\Checkout\Cart\CartCalculator;
  32. use Shopware\Core\Checkout\Cart\CartPersisterInterface;
  33. use Shopware\Core\Checkout\Cart\Event\CartChangedEvent;
  34. use Shopware\Core\System\SalesChannel\SalesChannelContext;
  35. use Shopware\Core\System\SalesChannel\SalesChannelEntity;
  36. use Shopware\Core\System\SalesChannel\SalesChannelRepository;
  37. use Shopware\Core\Content\Product\SalesChannel\SalesChannelProductCollection;
  38. use Shopware\Core\Content\Product\SalesChannel\SalesChannelProductEntity;
  39. use Shopware\Storefront\Page\Checkout\Finish\CheckoutFinishPageLoadedEvent;
  40. use Shopware\Core\Content\Category\Event\CategoryPageLoadedEvent;
  41. use Shopware\Core\System\Salutation\SalutationCollection;
  42. use Shopware\Core\Checkout\Cart\LineItem\LineItem;
  43. use Shopware\Core\Checkout\Cart\SalesChannel\CartService;
  44. use Shopware\Core\Checkout\Cart\Event\CheckoutOrderPlacedEvent;
  45. use Shopware\Core\Checkout\Cart\Event\AfterLineItemAddedEvent;
  46. use Shopware\Core\Checkout\Cart\Event\BeforeLineItemAddedEvent;
  47. use Shopware\Storefront\Page\Product\ProductVariantListingPriceEvent;
  48. use Shopware\Storefront\Page\Product\ProductPageLoadedEvent;
  49. use Shopware\Core\Content\MailTemplate\Service\Event\MailBeforeValidateEvent;
  50. use Shopware\Core\System\Country\CountryStateCollection;
  51. use Shopware\Core\System\Country\CountryCollection;
  52. use Shopware\Core\System\Country\CountryEntity;
  53. use Shopware\Core\System\Country\Aggregate\CountryState\CountryStateEntity;
  54. use Shopware\Core\System\ZipCode\ZipCodeEntity;
  55. use Shopware\Core\System\ZipCode\ZipCodeCollection;
  56. use Shopware\Core\System\ZipCode\ZipCodeRepository;
  57. use Shopware\Core\System\Country\Aggregate\CountryState\CountryStateRepository;
  58. use Shopware\Core\System\Country\CountryRepository;
  59. use Shopware\Storefront\Page\Checkout\Confirm\CheckoutConfirmPageLoadedEvent;
  60. use Shopware\Core\System\Checkout\Customer\CustomerEntity;
  61. use Shopware\Core\Checkout\Customer\Aggregate\CustomerAddress\CustomerAddressEntity;
  62. use Shopware\Core\Checkout\Customer\Aggregate\CustomerAddress\CustomerAddressCollection;
  63. use Shopware\Core\System\Customer\CustomerAddress\CustomerAddressRepository;
  64. use Shopware\Core\Framework\Uuid\Uuid;
  65. use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
  66. use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter;
  67. use Shopware\Core\Framework\DataAbstractionLayer\Search\Cache\CacheCriteriaEvent;
  68. use Shopware\Core\Content\Product\Events\ProductDetailRouteCacheKeyEvent;
  69. use Shopware\Core\Content\Product\Events\ProductListingRouteCacheKeyEvent;
  70. use Shopware\Core\Content\Product\Events\ProductSearchRouteCacheKeyEvent;
  71. use Shopware\Core\Content\Product\Events\ProductSuggestRouteCacheKeyEvent;
  72. use Shopware\Core\Content\Product\SalesChannel\CrossSelling\CrossSellingRouteCacheKeyEvent;
  73. use Shopware\Core\Framework\Store\Api\StoreApiRouteCacheKeyEvent;
  74. use Shopware\Core\System\CustomField\CustomFieldEntity;
  75. use Shopware\Core\System\CustomField\CustomFieldTypes;
  76. use Shopware\Core\System\CustomField\DataAbstractionLayer\CustomFieldRepository;
  77. use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\ContainsFilter;
  78. use Shopware\Core\Content\Product\Events\ProductLoadedEvent;
  79. class CustomPriceSubscriber implements EventSubscriberInterface
  80. {
  81.     private $connection;
  82.     private $requestStack;
  83.     private $logger;
  84.     private CartService $cartService;
  85.     private $container;
  86.     private $router;
  87.     private EntityRepositoryInterface $orderRepository;
  88.     private $countryRepository;
  89.     private $salutationRepository;
  90.     private $salutations;
  91.     private $customerAddressRepository;
  92.     private $salesChannelRepository;
  93.     private $customFieldRepository;
  94.     private $productRepository;
  95.     public function __construct(CartService $cartService,
  96.         ContainerInterface $container,
  97.         RequestStack $requestStack,
  98.     LoggerInterface $logger,
  99.     RouterInterface $router,
  100.     EntityRepositoryInterface $orderRepository,
  101.         EntityRepositoryInterface $countryRepository,
  102.         EntityRepositoryInterface $customerRepository,
  103.     EntityRepositoryInterface $salutationRepository,
  104.     EntityRepositoryInterface $customFieldRepository,
  105.     EntityRepositoryInterface $productRepository,
  106.         EntityRepositoryInterface $salesChannelRepository
  107.     
  108.     {
  109.       $this->cartService $cartService;
  110.       $this->container $container;
  111.       $this->connection $container->get(Connection::class);
  112.       $this->requestStack $requestStack;
  113.       $this->logger $logger;
  114.       $this->router $router;
  115.       $this->orderRepository $orderRepository;
  116.       $this->countryRepository $countryRepository;
  117.       $this->customerRepository $customerRepository;
  118.       $this->salutationRepository $salutationRepository;
  119.       $this->customFieldRepository $customFieldRepository;
  120.       $this->productRepository $productRepository;
  121.       $this->salesChannelRepository $salesChannelRepository;
  122.       $this->logger->warning('CustomPriceSubscriber: constructor was called.');
  123.     }
  124.     /****
  125.      * Events to functions mapping
  126.      */
  127.     public static function getSubscribedEvents(): array
  128.     {
  129.         return [
  130.           ProductListingResultEvent::class => ['onProductListingResult',500],
  131.           ProductPageLoadedEvent::class => ['onProductPageLoaded',500],
  132.           CategoryPageLoadedEvent::class => 'onCategoryPageLoaded',
  133.           MailBeforeValidateEvent::class => 'onMailBeforeValidate',
  134.           CheckoutOrderPlacedEvent::class => 'onOrderPlaced',
  135.           CheckoutFinishPageLoadedEvent::class => 'onCheckoutFinishPageLoaded',
  136.           CheckoutConfirmPageLoadedEvent::class => 'onConfirmPageLoaded',
  137.           ProductDetailRouteCacheKeyEvent::class => 'onCacheKeyEvent',
  138.           ProductListingRouteCacheKeyEvent::class => 'onCacheKeyEvent1',
  139.           ProductSearchRouteCacheKeyEvent::class => 'onCacheKeyEvent2',
  140.           ProductSuggestRouteCacheKeyEvent::class => 'onCacheKeyEvent3',
  141.           CrossSellingRouteCacheKeyEvent::class => 'onCacheKeyEvent4',
  142.       CacheCriteriaEvent::class => 'onCacheCriteriaEvent',
  143.       ProductLoadedEvent::class => 'onProductsLoaded',
  144.           ProductVariantListingPriceEvent::class => ['onVariantListingPrice',500]
  145.         ];
  146.     }
  147.     public function onProductsLoaded(ProductLoadedEvent $event): void
  148.     {
  149.         $products $event->getEntities();
  150.     }
  151.     public function onCacheKeyEvent(ProductDetailRouteCacheKeyEvent $event): void
  152.     {
  153.            $event->disableCaching();
  154.     }
  155.     public function onCacheKeyEvent1(ProductListingRouteCacheKeyEvent $event): void
  156.     {
  157.            $event->disableCaching();
  158.     }
  159.     public function onCacheKeyEvent2(ProductSearchRouteCacheKeyEvent $event): void
  160.     {
  161.            $event->disableCaching();
  162.     }
  163.     public function onCacheKeyEvent3(ProductSuggestRouteCacheKeyEvent $event): void
  164.     {
  165.            $event->disableCaching();
  166.     }
  167.     public function onCacheKeyEvent4(CrossSellingRouteCacheKeyEvent $event): void
  168.     {
  169.            $event->disableCaching();
  170.     }
  171.     public function getTranslatedCustomFields(array $customFieldOptions, array $customFieldValues, array $customFieldLabels) : array
  172.     {
  173.        $customFieldTranslated = [];
  174.        foreach ($customFieldValues as $fieldName => $values) {
  175.            // Label für den Feldnamen holen
  176.            $fieldLabel $customFieldLabels[$fieldName]['en-GB'] ?? $fieldName;
  177.            $fieldType 'string'// Standardwert ist 'string'
  178.            // Werte für das Feld verarbeiten
  179.            $translatedValues = [];
  180.            if (is_array($values)) {
  181.                foreach ($values as $value) {
  182.                    $found false;
  183.                    if (isset($customFieldOptions[$fieldName])) {
  184.                        foreach ($customFieldOptions[$fieldName] as $option) {
  185.                            if ($option['value'] === $value) {
  186.                                $translatedValues[] = $option['label']['en-GB'] ?? $value;
  187.                                $found true;
  188.                                break;
  189.                            }
  190.                        }
  191.                    }
  192.                    if (!$found) {
  193.                        // Originalwert hinzufügen, wenn keine Übersetzung gefunden wurde
  194.                        $translatedValues[] = $value;
  195.                    }
  196.                }
  197.            } else {
  198.                // Behandlung von Nicht-Array-Werten (z.B. einfache Zahlen oder Strings)
  199.                $translatedValues $values;
  200.        }
  201.            // Überprüfen, ob der Wert eine einzelne boolean value ist
  202.            if (is_bool($values) || (is_array($values) && count($values) === && isset($values[0]) && is_bool($values[0]))) {
  203.                $fieldType 'bool';
  204.            }
  205.           
  206.            
  207.            // Ergebnis-Array zusammenstellen
  208.        $customFieldTranslated[$fieldName] = [
  209.                'type' => $fieldType,
  210.                'label' => $fieldLabel,
  211.                'values' => $translatedValues
  212.            ];
  213.        }
  214.        return $customFieldTranslated ;
  215.     }
  216.     public function getProductCustomFieldOptions(string $productIdstring $prefixContext $context): array
  217.     {
  218.         $criteria = new Criteria([$productId]);
  219.         $criteria->addAssociation('customFields');
  220.         $product $this->productRepository->search($criteria$context)->first();
  221.         if (!$product) {
  222.             return [];
  223.         }
  224.     $customFields $product->getCustomFields() ?? [];
  225.     $filteredFields = [];
  226.         foreach ($customFields as $key => $value) {
  227.             if (strpos($key$prefix) === 0) {
  228.     //        $filteredFields[$key] = $value;
  229.                         $customFieldOptions $this->getCustomFieldOptions($key$context);
  230.                 $filteredFields[$key] = $customFieldOptions;
  231.         }
  232.         }
  233.         return $filteredFields;
  234.     }
  235.     public function getProductCustomFieldValues(string $productIdstring $prefixContext $context): array
  236.     {
  237.         $criteria = new Criteria([$productId]);
  238.         $criteria->addAssociation('customFields');
  239.         $product $this->productRepository->search($criteria$context)->first();
  240.         if (!$product) {
  241.             return [];
  242.         }
  243.     $customFields $product->getCustomFields() ?? [];
  244.     $filteredFields = [];
  245.         $labels = [];
  246.         foreach ($customFields as $key => $value) {
  247.             if (strpos($key$prefix) === 0) {
  248.             $filteredFields[$key] = $value;
  249.                         $customFieldConfig $this->getCustomFieldConfig($key$context);
  250.             $fieldLabels = [];
  251.             if( is_array($value) )
  252.             {
  253.                          foreach ($value as $value1) {
  254.                             if (isset($customFieldConfig['options'][$value1])) {
  255.                                  $fieldLabels[$value1] = $customFieldConfig['options'][$value1]['label'] ?? $value1;
  256.                             }
  257.              }
  258.             }
  259.             else
  260.             {
  261.                             if (isset($customFieldConfig['options'][$value])) {
  262.                     $fieldLabels[$value] = $customFieldConfig['options'][$value]['label'] ?? $value;
  263.                 }
  264.             }
  265.             if( empty($fieldLabels) )
  266.                 $labels[$key] = $value;
  267.             else
  268.                             $labels[$key] = $fieldLabels;
  269.             }
  270.             }
  271.         return $labels;
  272.     }    
  273.     public function getCustomFieldLabels(string $prefixContext $context): array
  274.     {
  275.         $criteria = new Criteria();
  276.         $criteria->addFilter(new ContainsFilter('name'$prefix));
  277.         $customFields $this->customFieldRepository->search($criteria$context);
  278.         $fieldsLabels = [];
  279.         foreach ($customFields as $customField) {
  280.             // Prüfen, ob der Feldname mit dem Präfix beginnt
  281.             if (strpos($customField->getName(), $prefix) === 0) {
  282.                 $config $customField->getConfig();
  283.                 $label $config['label'] ?? $customField->getName();
  284.                 $fieldsLabels[$customField->getName()] = $label;
  285.             }
  286.         }
  287.         return $fieldsLabels;
  288.     }
  289.     private function getCustomFieldConfig(string $customFieldKeyContext $context): array
  290.     {
  291.         $criteria = new Criteria();
  292.         $criteria->addFilter(new EqualsFilter('name'$customFieldKey));
  293.         $customField $this->customFieldRepository->search($criteria$context)->first();
  294.         if (!$customField) {
  295.             return [];
  296.         }
  297.         return $customField->getConfig() ?? [];
  298.     }
  299.     public function getCustomFieldOptions(string $customFieldKeyContext $context): array
  300.     {
  301.         $criteria = new Criteria();
  302.         $criteria->addFilter(new EqualsFilter('customFieldSet.relations.entityName''product'));
  303.         $criteria->addFilter(new EqualsFilter('name'$customFieldKey));
  304.         /** @var CustomFieldEntity $customField */
  305.         $customField $this->customFieldRepository->search($criteria$context)->first();
  306.         if (!$customField || $customField->getType() !== CustomFieldTypes::SELECT) {
  307.             return [];
  308.         }
  309.     $options $customField->getConfig()['options'] ?? [];
  310.         // Transformieren Sie die Optionen hier nach Bedarf
  311.         return $options;
  312.     }
  313.     public function onCacheCriteriaEvent(CacheCriteriaEvent $event): void
  314.     {
  315.         // Prüfen, ob das Event für das Produktlisting ist
  316.         if ($event->getContext()->getResource() === 'product_listing') {
  317.             // Deaktivieren des Cachings für das Produktlisting
  318.             $event->getCriteria()->addExtension('disable-cache'true);
  319.         }
  320.     }
  321.     /*****
  322.      * get the salutations from Repository
  323.      * Herr, Frau, Familie ...
  324.      **/
  325.     private function getSalutations(SalesChannelContext $salesChannelContext): SalutationCollection
  326.     {
  327.         $salutations $this->salutationRoute->load(new Request(), $salesChannelContext, new Criteria())->getSalutations();
  328.         $salutations->sort(function (SalutationEntity $aSalutationEntity $b) {
  329.             return $b->getSalutationKey() <=> $a->getSalutationKey();
  330.         });
  331.         return $salutations;
  332.     }
  333.     /******
  334.      * prüfe ob es ein sonderstore, oder der normale ist
  335.      */
  336.     function isNotOilPelletsFuelStore$scname )
  337.     {
  338.          $scarray = array("EMOVA Heizöl""EMOVA Diesel""EMOVA Pellets","EMOVA Tankreinigung");
  339.          if (!in_array($scname$scarray)) 
  340.          {
  341.             return(true);
  342.          }
  343.          return( false );
  344.     }
  345.     /******
  346.      *  lösche Variablen die nichjt mehr gebraucht werden
  347.      ****/
  348.     function removeSessionParsAfterOrderFinished($session)
  349.     {
  350.         $session->remove('poid');
  351.         $session->remove('ev_city');
  352.         $session->remove('ev_quantity');
  353.         $session->remove('ev_postcode');
  354.         $session->remove('ev_numaddresses');
  355.         $session->remove('ev_prodrequested');
  356.         $session->remove('ev_addresses');
  357.         $session->remove('evre_addresses');
  358.         $session->remove('ev_liefertermine');
  359.         $session->remove('ev_address_data');
  360.         $session->remove('ev_address_id');
  361.         $session->remove('evre_address_id');
  362.         if ($session->has('client-note')) {
  363.             $clientNote $session->get('client-note');
  364.             $session->set('client-note-prev',$clientNote);
  365.         }
  366.         $session->remove('client-note');
  367.         $session->remove('client-delivery');
  368.         // nicht wegsetzen, wird in der Betsätigung noch gebraucht
  369.         //$session->remove('client-deliverytext');
  370.         //$session->remove('ev_voucher_code_valid');
  371.         //$session->remove('ev_mandantor');
  372.         $session->remove('ev_voucher_code');
  373.         //$session->remove('ev_voucher_code_valid'); // nicht löschen, muss noch angezeigt werden !
  374.         $session->remove('ev_voucher_error');
  375.         $session->remove('productReq');
  376.     }
  377.     /*********
  378.      * last page after order is set, mail is sent. This shows the order confirmed from the shop.
  379.      ****/
  380.     public function onCheckoutFinishPageLoaded(CheckoutFinishPageLoadedEvent $event): void
  381.     {
  382.     $request $this->requestStack->getCurrentRequest();
  383.         $session $request->getSession();
  384.     $salesContext $event->getSalesChannelContext();
  385.     $salesChannel $salesContext->getSalesChannel();
  386.         $scname $salesChannel->getName();
  387.         /* normal store should not execute our code */
  388.         if( $this->isNotOilPelletsFuelStore($scname) == true )
  389.         {
  390.            return;
  391.         }
  392.         $this->removeSessionParsAfterOrderFinished($session);
  393.         
  394.         //$readdress =  $session->get('re_address');
  395.         //$validvoucher = $session->get('ev_voucher_code_valid');
  396.     }
  397.   
  398.     function getGermanCountry$salesChannelContext )
  399.     {
  400.         // Fetch the country collection
  401.         $criteria = new Criteria();
  402.         $criteria->addFilter(
  403.           new EqualsFilter('iso''DE')
  404.         );
  405.         /** @var CountryCollection $countries */
  406.         $countries $this->countryRepository->search(
  407.           $criteria,
  408.           $salesChannelContext->getContext()
  409.         )->getEntities();
  410.            // Find the country with name "Deutschland"
  411.            /** @var CountryEntity|null $germanyCountry */
  412.            $germanyCountry $countries->first(); //function (CountryEntity $country) {
  413.         return( $germanyCountry );
  414.     }
  415.     /*******
  416.      *  get the salutation for a anrede text
  417.      ***/
  418.     function getSalutation$anrede$salesChannelContext )
  419.     {
  420.           if( !isset($salutations) ) {
  421.             /** @var SalutationCollection $salutations */
  422.             $salutations $this->salutationRepository->search(new Criteria(), $salesChannelContext->getContext())->getEntities();
  423.           }
  424.           $salutationFound null;
  425.           foreach ($salutations as $salutation) {
  426.              if ($salutation->displayName === $anrede) {
  427.                  $salutationId $salutation->getId();
  428.                  $salutationFound $salutation;
  429.                  return($salutation);
  430.              }
  431.           }
  432.           return( null );   
  433.     }
  434.     /*********
  435.      *  the confirmPage for the user is loaded. This is the last page where the user has to click the 'order' button
  436.      *  this is called from checkout/voucher and from /checkout/register too
  437.      *  the code should be executed only when it is not called for checkout/confirm itself 
  438.      *  all the stuff is in cart, not in order yet
  439.      ******/
  440.     public function onConfirmPageLoaded(CheckoutConfirmPageLoadedEvent $event): void
  441.     {
  442.         // Hier können Sie auf die Bestellungsbestätigungsseite zugreifen
  443.         $doDump false;
  444.         $page $event->getPage();
  445.                 $request $this->requestStack->getCurrentRequest();
  446.         // this should be executed on this :
  447.         // "https://shop.emova.de/heizoel/checkout/voucher"
  448.         // "https://shop.emova.de/heizoel/checkout/register"
  449.         // not on this : 
  450.         // "https://shop.emova.de/heizoel/checkout/confirm"
  451.         if ($request->headers->has('Referer')) {
  452.             // Get the value of the Referer header
  453.             $referer $request->headers->get('Referer');
  454.             if (strpos($referer'/checkout/confirm', -strlen($referer)) !== false) {
  455.                 return;
  456.             }
  457.         }
  458.         $session $request->getSession();
  459.                 $salesContext $event->getSalesChannelContext();
  460.                 $salesChannel $salesContext->getSalesChannel();
  461.         if( $doDump )
  462.         {
  463.            $customFields $salesChannel->getCustomFields();
  464.            dump($customFields);
  465.         }
  466.         $scname $salesChannel->getName();
  467.         $scarray = array("EMOVA Heizöl""EMOVA Diesel""EMOVA Pellets","EMOVA Tankreinigung");
  468.         if (!in_array($scname$scarray)) 
  469.         {
  470.             return;
  471.         }
  472.            $salesChannelContext $event->getSalesChannelContext();
  473.            $customer $salesChannelContext->getCustomer();
  474.         $ev_addresses $session->get('ev_address_data');
  475.         $evre_addresses $session->get('evre_address_data');
  476.         $ev_addressid $session->get('ev_address_id');
  477.         $evre_addressid $session->get('evre_address_id');
  478.         if( $evre_addresses != null //&& $ev_addressid === null )
  479.         {
  480.           $session->set('evre_addresses',$ev_addresses);
  481.         }
  482.         if( $ev_addresses != null //&& $ev_addressid === null )
  483.         {
  484.           $session->set('ev_addresses',$ev_addresses);
  485.           if( $doDump )
  486.               dump($ev_addresses[0]);
  487.           // Create a new shipping address entity
  488.           $newShippingAddress = new CustomerAddressEntity();
  489.           $anrede '' $ev_addresses[0]['ev_anrede'];
  490.           $salutationFound $this->getSalutation$anrede$salesChannelContext );
  491.           $salutationId $salutationFound->getId();
  492.           $newShippingAddress->setSalutationId($salutationId);
  493.           $session->set('ev_salutationid',$salutationId);
  494.           $newShippingAddress->setSalutation($salutationFound);
  495.           //$newShippingAddress->setAccountType('privat');// . $ev_addresses[0]['ev_accounttype'] );
  496.           if( !isset($ev_addresses[0]['ev_firstname']) )
  497.                 $newShippingAddress->setFirstName(' ');
  498.           else
  499.                 $newShippingAddress->setFirstName('' $ev_addresses[0]['ev_firstname'] );
  500.              $newShippingAddress->setTitle('');
  501.              $newShippingAddress->setLastName('' $ev_addresses[0]['ev_name'] );
  502.              $newShippingAddress->setStreet('' $ev_addresses[0]['ev_street']  . ' ' $ev_addresses[0]['ev_housenr'] );
  503.              $newShippingAddress->setPhoneNumber('' $ev_addresses[0]['ev_phone'] );
  504.              $newShippingAddress->setZipcode('' $ev_addresses[0]['ev_postcode'] );
  505.              $newShippingAddress->setAdditionalAddressLine1('' $ev_addresses[0]['ev_info'] );
  506.              $newShippingAddress->setCity('' $ev_addresses[0]['ev_city'] );
  507.           if( $ev_addressid === null )
  508.           {
  509.             $ev_addressid Uuid::randomHex();
  510.             $session->set('ev_address_id',$ev_addressid);
  511.           }
  512.       $newShippingAddress->setId($ev_addressid);
  513.           $germanyCountry $this->getGermanCountry($salesChannelContext);
  514.           if ($germanyCountry != null ) {
  515.             // Get the CountryId for Germany
  516.             $germanyCountryId $germanyCountry->getId();
  517.                $newShippingAddress->setCountry($germanyCountry );
  518.                $newShippingAddress->setCountryId($germanyCountryId );
  519.              }
  520.           $customerId null;
  521.           if($customer)
  522.           {
  523.             $customerId $customer->getId();
  524.               $newShippingAddress->setCustomerId($customerId);
  525.           }
  526.           $cadrs $customer->getAddresses();
  527.           $newAddressData = [
  528.               'id' => $newShippingAddress->getId(),
  529.               'firstName' => $newShippingAddress->getFirstName(),
  530.               'lastName' => $newShippingAddress->getLastName(),
  531.               'street' => $newShippingAddress->getStreet(),
  532.               'phoneNumber' => $newShippingAddress->getPhoneNumber(),
  533.               'zipcode' => $newShippingAddress->getZipcode(),
  534.               'city' => $newShippingAddress->getCity(),
  535.               'countryId' => '' $germanyCountryId ,
  536.               'customerId' => '' $customerId ,
  537.               'salutationId' => $newShippingAddress->getSalutationId(),  
  538.           ];
  539.           $this->customerRepository->update(
  540.              [
  541.                    [
  542.                      'id' => $customerId,
  543.                  'defaultShippingAddressId' => $newShippingAddress->getId(),
  544.                      'addresses' => [$newAddressData],
  545.                    ] 
  546.              ],
  547.              $salesChannelContext->getContext()
  548.           );
  549.             // Set the new shipping address as the default shipping address
  550.           if( $customer) {
  551.               $customer->setDefaultShippingAddress($newShippingAddress);
  552.               $customer->setActiveShippingAddress($customer->getDefaultShippingAddress() ); //$newShippingAddress);
  553.           }
  554.           if( $doDump )
  555.                dump($newShippingAddress);
  556.         }
  557.         $readrfilled false;
  558.         if( $evre_addresses != null )
  559.         {
  560.                 $readrfilled true;
  561.                 if (!isset($evre_addresses['ev_anrede']) || empty($evre_addresses['ev_anrede'])) {
  562.                     $readrfilled false;
  563.                 }
  564.                 if (!isset($evre_addresses['ev_readrset']) || empty($evre_addresses['ev_readrset']) || ($evre_addresses['ev_readrset'] !== 'on') ) {
  565.                     $readrfilled false;
  566.                 }
  567.                 if (!isset($evre_addresses['ev_firstname']) || empty($evre_addresses['ev_firstname'])) {
  568.                     $readrfilled false;
  569.                 }
  570.                 if (!isset($evre_addresses['ev_name']) || empty($evre_addresses['ev_name'])) {
  571.                     $readrfilled false;
  572.                 }
  573.                 if (!isset($evre_addresses['ev_street']) || empty($evre_addresses['ev_street'])) {
  574.                     $readrfilled false;
  575.                 }
  576.                 if (!isset($evre_addresses['ev_housenr']) || empty($evre_addresses['ev_housenr'])) {
  577.                     $readrfilled false;
  578.                 }
  579.                 if (!isset($evre_addresses['ev_phone']) || empty($evre_addresses['ev_phone'])) {
  580.                     $readrfilled false;
  581.                 }
  582.                 if (!isset($evre_addresses['ev_postcode']) || empty($evre_addresses['ev_postcode'])) {
  583.                     $readrfilled false;
  584.                 }
  585.                 if (!isset($evre_addresses['ev_city']) || empty($evre_addresses['ev_city'])) {
  586.                     $readrfilled false;
  587.                 }
  588.         }
  589.         if( $evre_addresses != null  
  590.         {
  591.           $session->set('evre_addresses',$evre_addresses);
  592.         }
  593.         if( $evre_addresses != null && $readrfilled 
  594.         {
  595.           $session->set('evre_addresses',$evre_addresses);
  596.           if( $doDump )
  597.               dump($evre_addresses);
  598.           // Create a new shipping address entity
  599.           $newInvoiceAddress = new CustomerAddressEntity();
  600.           $anrede '' $evre_addresses['ev_anrede'];
  601.           $salutationFound $this->getSalutation$anrede$salesChannelContext );
  602.           $salutationId $salutationFound->getId();
  603.           $newInvoiceAddress->setSalutationId($salutationId);
  604.           $session->set('ev_salutationid',$salutationId);
  605.           $newInvoiceAddress->setSalutation($salutationFound);
  606.           //$newInvoiceAddress->setAccountType('privat');// . $evre_addresses[0]['ev_accounttype'] );
  607.           if( !isset($evre_addresses['ev_firstname']) )
  608.                  $newInvoiceAddress->setFirstName(' ');
  609.           else
  610.                  $newInvoiceAddress->setFirstName('' $evre_addresses['ev_firstname'] );
  611.           $newInvoiceAddress->setTitle('');
  612.           $newInvoiceAddress->setLastName('' $evre_addresses['ev_name'] );
  613.           $newInvoiceAddress->setStreet('' $evre_addresses['ev_street']  . ' ' $evre_addresses['ev_housenr'] );
  614.           $newInvoiceAddress->setPhoneNumber('' $evre_addresses['ev_phone'] );
  615.           $newInvoiceAddress->setZipcode('' $evre_addresses['ev_postcode'] );
  616.           //$newInvoiceAddress->setAdditionalAddressLine1('' . $evre_addresses['ev_info'] );
  617.           $newInvoiceAddress->setCity('' $evre_addresses['ev_city'] );
  618.           if( $evre_addressid === null )
  619.           {
  620.             $evre_addressid Uuid::randomHex();
  621.             $session->set('evre_address_id',$evre_addressid);
  622.           }
  623.       $newInvoiceAddress->setId($evre_addressid);
  624.           $germanyCountry $this->getGermanCountry($salesChannelContext);
  625.           if ($germanyCountry != null ) {
  626.             // Get the CountryId for Germany
  627.             $germanyCountryId $germanyCountry->getId();
  628.             $newInvoiceAddress->setCountry($germanyCountry );
  629.             $newInvoiceAddress->setCountryId($germanyCountryId );
  630.           }
  631.           $customerId null;
  632.           if($customer)
  633.           {
  634.             $customerId $customer->getId();
  635.             $newInvoiceAddress->setCustomerId($customerId);
  636.           }
  637.           $cadrs $customer->getAddresses();
  638.           $newAddressData = [
  639.               'id' => $newInvoiceAddress->getId(),
  640.               'firstName' => $newInvoiceAddress->getFirstName(),
  641.               'lastName' => $newInvoiceAddress->getLastName(),
  642.               'street' => $newInvoiceAddress->getStreet(),
  643.               'phoneNumber' => $newInvoiceAddress->getPhoneNumber(),
  644.               'zipcode' => $newInvoiceAddress->getZipcode(),
  645.               'city' => $newInvoiceAddress->getCity(),
  646.               'countryId' => '' $germanyCountryId ,
  647.               'customerId' => '' $customerId ,
  648.               'salutationId' => $newInvoiceAddress->getSalutationId(),  
  649.           ];
  650.           $this->customerRepository->update(
  651.              [
  652.                    [
  653.                      'id' => $customerId,
  654.                  'defaultBillingAddressId' => $newInvoiceAddress->getId(),
  655.                      'addresses' => [$newAddressData],
  656.                    ] 
  657.              ],
  658.              $salesChannelContext->getContext()
  659.           );
  660.           // Set the new shipping address as the default shipping address
  661.           if( $customer) {
  662.             $customer->setDefaultBillingAddress($newInvoiceAddress);
  663.             $customer->setActiveBillingAddress($customer->getDefaultBillingAddress() ); //$newInvoiceAddress);
  664.           }
  665.           if( $doDump )
  666.               dump($newInvoiceAddress);
  667.           if( $doDump )
  668.               dump($customer);
  669.           if( $doDump )
  670.               dump('confirmPage:8');
  671.         }
  672.     }
  673.     /*****
  674.      * get the salesChannel if we have the id only
  675.      */
  676.     public function getCurrentSalesChannel(string $salesChannelId): ?SalesChannelEntity
  677.     {
  678.         // Holen Sie die ID des aktuellen SalesChannels aus der Session
  679.         if ($salesChannelId) {
  680.             // Rufen Sie den SalesChannel aus der Datenbank ab
  681.             $context Context::createDefaultContext();
  682.             return $this->salesChannelRepository->search(
  683.                 (new Criteria())->addFilter(new EqualsFilter('id'$salesChannelId)),
  684.                 $context
  685.             )->first();
  686.         }
  687.         return null;
  688.     }
  689.     /*********
  690.      *  this is called immediatly before the mail is sent.
  691.      *  here we need to add some data that we want to put to the mail
  692.      *  this is added into the template data
  693.      ***/
  694.     public function onMailBeforeValidate(MailBeforeValidateEvent $event)
  695.     {
  696.         $doTrace false;
  697.         $context $event->getContext();
  698.         $data $event->getTemplateData();
  699.         $request $this->requestStack->getCurrentRequest();
  700.         $session $request->getSession();
  701.          $session->remove('ev_mailBeforeValidate');
  702.         if( $doTrace )
  703.           $session->set('ev_mailBeforeValidate''true');
  704.         $addresses =  $session->get('ev_addresses');
  705.         $validvoucher $session->get('ev_voucher_code_valid');
  706.         $salesChannelId $session->get('sw-sales-channel-id');
  707.     $salesContext $request->attributes->get('sw-sales-channel-context');
  708.         $salesChannel null;
  709.         if( $salesContext != null )
  710.         {
  711.                   $salesChannel $salesContext->getSalesChannel();
  712.         }
  713.         else if( $salesChannelId )
  714.         {
  715.                   $salesChannel $this->getCurrentSalesChannel($salesChannelId); //$event->getSalesChannelContext();
  716.         }
  717.         $scname '';
  718.         if( $salesChannel != null )
  719.         {
  720.            $scname $salesChannel->getName();
  721.         }
  722.         if( $scname != "EMOVA Heizöl" )
  723.         {
  724.             $addresses null;
  725.         }
  726.        
  727.         if( $scname == "EMOVA Heizöl" )
  728.         {
  729.             if ( !($validvoucher === null) && strpos($validvoucher'EHO') != 0
  730.             {
  731.                $validvoucher null;
  732.             }
  733.         }
  734.         if( $scname == "EMOVA Pellets" )
  735.         {
  736.             if ( !($validvoucher === null) && strpos($validvoucher'EPE') != 0
  737.             {
  738.                $validvoucher null;
  739.             }
  740.         }
  741.         if( $scname == "EMOVA Tankreinigung" )
  742.         {
  743.                $validvoucher null;
  744.         }
  745.         if( $scname == "EMOVA Store" )
  746.         {
  747.             if ( !($validvoucher === null
  748.                  && strpos($validvoucher'EWB') != 
  749.                  && strpos($validvoucher'EBK') != 
  750.             
  751.             {
  752.                $validvoucher null;
  753.             }
  754.         }
  755.         if (!($validvoucher === null ) && !(empty($validvoucher)) )
  756.         {
  757.           //$sql = "SELECT * FROM ev_voucher WHERE code = ? AND validuntil >= NOW() ORDER BY createdate DESC LIMIT 1";
  758.           $sql "SELECT * FROM ev_voucher WHERE code = ? ORDER BY createdate DESC LIMIT 1";
  759.           $params = [$validvoucher];
  760.           $voucherData $this->connection->executeQuery($sql$params)->fetch();
  761.           $currentDateTime = new \DateTime(); // Aktuelles Datum/Uhrzeit
  762.           if ($voucherData !== false) {
  763.              $voucherId $voucherData['void'];
  764.           }
  765.           else
  766.           {
  767.             $validvoucher '';
  768.           }
  769.     
  770.         }
  771.         if ($session->has('client-note')) {
  772.             $clientNote $session->get('client-note');
  773.         }
  774.         else
  775.         {
  776.         $clientNote '';
  777.         }
  778.         if ($session->has('client-delivery')) {
  779.             $clientDelivery $session->get('client-delivery');
  780.         }
  781.         else
  782.         {
  783.         $clientDelivery '';
  784.         }
  785.         if ($session->has('client-deliverytext')) {
  786.             $clientDeliveryText $session->get('client-deliverytext');
  787.         }
  788.         else
  789.         {
  790.             $clientDeliveryText '';
  791.         }
  792.         $data["ev_clientDeliveryText"] = $clientDeliveryText;
  793.         $data["ev_clientDelivery"] = $clientDelivery;
  794.         $data["ev_clientNote"] = $clientNote;
  795.         if (isset($data["ev_addresses"])) {
  796.            $adr2 $data["ev_addresses"];
  797.            if( $adr2 !== null )
  798.            {
  799.                $data["ev_addresses2"] = $adr2;
  800.            }
  801.         }
  802.         if( $addresses !== null )
  803.         {
  804.             $data["ev_addresses"] = $addresses;
  805.             $anzahlElemente count($addresses);
  806.             if( $anzahlElemente )
  807.             {
  808.                 $data["ev_addressesvalid"] = 'true';
  809.             }
  810.             else
  811.             {
  812.                 $data["ev_addressesvalid"] = 'false';
  813.             }
  814.            
  815.         }
  816.         else
  817.         {
  818.             $data["ev_addressesvalid"] = 'false';
  819.         }
  820.     $data["ev_validvoucher"] = $validvoucher;
  821.         $customFields null;
  822.     if( $salesChannel ) {
  823.         $customFields $salesChannel->getCustomFields();
  824.     }
  825.         if( $customFields != null )
  826.         { 
  827.             // context.salesChannel.customFields.
  828.             $data["emova_settings_lieferp_text"] = ($customFields["emova_settings_lieferp_text"]);
  829.             $data["emova_settings_ust"] = ($customFields["emova_settings_ust"]);
  830.             $data["emova_settings_lp_brutto"] = ($customFields["emova_settings_lp_brutto"]);
  831.             $data["emova_settings_lp_netto"] = ($customFields["emova_settings_lp_netto"]);
  832.             $data["emova_settings_einheit"] = ($customFields["emova_settings_einheit"]);
  833.     }
  834.     else
  835.         { 
  836.             // context.salesChannel.customFields.
  837.             $data["emova_settings_lieferp_text"] = ("emova_settings_lieferp_text");
  838.             $data["emova_settings_ust"] = (19);
  839.             $data["emova_settings_lp_brutto"] = (42);
  840.             $data["emova_settings_lp_netto"] = (35);
  841.             $data["emova_settings_einheit"] = ("einheit");
  842.     }
  843.         $event->setTemplateData($data);
  844.     }
  845. /**
  846.      * @param CheckoutOrderPlacedEvent $event
  847.      * @throws \Exception
  848.      */
  849.     public function onOrderPlaced(CheckoutOrderPlacedEvent $event)
  850.     {
  851.         $request $this->requestStack->getCurrentRequest();
  852.         $doDump false;
  853.         if( $doDump )
  854.         {
  855.             dump('CustomPricePlugin:onOrderPlaced');
  856.             dump($event);
  857.             dump($request);
  858.         }
  859.         $session $request->getSession();
  860.         $addresses =  $session->get('ev_addresses');
  861.         $validvoucher $session->get('ev_voucher_code_valid');
  862.         $orderNumber $event->getOrder()->getOrderNumber(); // Bestellnummer aus dem Event
  863.         $salesChannelId $session->get('sw-sales-channel-id');
  864.         $salesContext $request->attributes->get('sw-sales-channel-context');
  865.         $salesChannel null;
  866.         if( $salesContext != null )
  867.         {
  868.                   $salesChannel $salesContext->getSalesChannel();
  869.         }
  870.         else if( $salesChannelId )
  871.         {
  872.                   $salesChannel $this->getCurrentSalesChannel($salesChannelId); //$event->getSalesChannelContext();
  873.         }
  874.         if( $doDump )
  875.             dump($event->getOrder());
  876.         $scname $salesChannel->getName();
  877.         if( $doDump )
  878.             dump('CustomPricePlugin:onOrderPlaced');
  879.         $session->set('ev_onOrderPlaced start''true');
  880.         if( $scname != "EMOVA Heizöl" )
  881.         {
  882.             $addresses null;
  883.         }
  884.        
  885.         if( $scname == "EMOVA Heizöl" )
  886.         {
  887.             if ( !($validvoucher === null) && strpos($validvoucher'EHO') != 0
  888.             {
  889.                $validvoucher null;
  890.             }
  891.         }
  892.         if( $scname == "EMOVA Pellets" )
  893.         {
  894.             if ( !($validvoucher === null) && strpos($validvoucher'EPE') != 0
  895.             {
  896.                $validvoucher null;
  897.             }
  898.         }
  899.         if( $scname == "EMOVA Tankreinigung" )
  900.         {
  901.                $validvoucher null;
  902.         }
  903.         if( $scname == "EMOVA Diesel" )
  904.         {
  905.             if ( !($validvoucher === null) && strpos($validvoucher'EDI') != 0
  906.             {
  907.                $validvoucher null;
  908.             }
  909.         }
  910.         if( $scname == "EMOVA Store" )
  911.         {
  912.             if ( !($validvoucher === null
  913.                  && strpos($validvoucher'EWB') != 
  914.                  && strpos($validvoucher'EBK') != 
  915.             
  916.             {
  917.                $validvoucher null;
  918.             }
  919.         }
  920.         if( $doDump )
  921.             dump('CustomPricePlugin:onOrderPlaced mid');
  922.         if (!($validvoucher === null ) && !(empty($validvoucher)) )
  923.         {
  924.           //$sql = "SELECT * FROM ev_voucher WHERE code = ? AND validuntil >= NOW() ORDER BY createdate DESC LIMIT 1";
  925.           $sql "SELECT * FROM ev_voucher WHERE code = ? ORDER BY createdate DESC LIMIT 1";
  926.           $params = [$validvoucher];
  927.           $voucherData $this->connection->executeQuery($sql$params)->fetch();
  928.           $currentDateTime = new \DateTime(); // Aktuelles Datum/Uhrzeit
  929.           
  930.           if ($voucherData !== false) {
  931.              $voucherId $voucherData['void'];
  932.              $sql "UPDATE ev_voucher SET orderdate = :orderdate, ordernumber = :ordernumber WHERE void = :voucherId";
  933.              $params = [
  934.                  ':orderdate' => $currentDateTime->format('Y-m-d H:i:s'),
  935.                  ':ordernumber' => $orderNumber,
  936.                  ':voucherId' => $voucherId,
  937.              ];
  938.              $this->connection->executeStatement($sql$params);
  939.           }
  940.           else
  941.           {
  942.             $validvoucher '';
  943.           }
  944.     
  945.         }
  946.         if( $doDump )
  947.             dump('CustomPricePlugin:onOrderPlaced mid2');
  948.         
  949.         
  950.         if ($request->query->has('poid'))
  951.         {
  952.           $priceOfferId $request->query->get('poid');
  953.           $poidIsSet=true;
  954.           $session->set('poid'$priceOfferId);
  955.         }
  956.         else
  957.         {
  958.           $session $request->getSession();
  959.           if ($session->has('poid'))
  960.           {
  961.            $priceOfferId $session->get('poid');
  962.            $poidIsSet=true;
  963.           }
  964.           else
  965.           {
  966.                    $priceOfferId '';
  967.           }
  968.         }
  969.         if ($session->has('client-note')) {
  970.             $clientNote $session->get('client-note');
  971.         }
  972.         else
  973.         {
  974.         $clientNote '';
  975.         }
  976.         if ($session->has('client-delivery')) {
  977.             $clientDelivery $session->get('client-delivery');
  978.         }
  979.         else
  980.         {
  981.         $clientDelivery '';
  982.         }
  983.         if ($session->has('client-deliverytext')) {
  984.             $clientDeliveryText $session->get('client-deliverytext');
  985.         }
  986.         else
  987.         {
  988.         $clientDeliveryText '';
  989.         }
  990.         if( $doDump )
  991.             dump('CustomPricePlugin:onOrderPlaced mid3');
  992.         $customFieldPoidValue $priceOfferId;
  993.         $customFields $salesChannel->getCustomFields();
  994.         $emova_settings_lieferp_text '';
  995.         $emova_settings_ust 0;
  996.         $emova_settings_lp_brutto 0;
  997.         $emova_settings_lp_netto 0;
  998.         $emova_settings_einheit '';
  999.         $emova_sepa_allowed '';
  1000.         $emova_sepa_iban '';
  1001.         $emova_sepa_accountholder '';
  1002.         if( $request->request->has('ev_customer_payment_allowsepa') )
  1003.         {
  1004.            $emova_sepa_allowed $request->request->get('ev_customer_payment_allowsepa');
  1005.            $emova_sepa_iban $request->request->get('ev_customer_payment_iban');
  1006.            $emova_sepa_accountholder $request->request->get('ev_customer_payment_accountholder');
  1007.         }
  1008.         
  1009.         if( $customFields != null )
  1010.         {
  1011.             // context.salesChannel.customFields.
  1012.             $emova_settings_lieferp_text = ($customFields["emova_settings_lieferp_text"]);
  1013.             $emova_settings_ust = ($customFields["emova_settings_ust"]);
  1014.             $emova_settings_lp_brutto = ($customFields["emova_settings_lp_brutto"]);
  1015.             $emova_settings_lp_netto = ($customFields["emova_settings_lp_netto"]);
  1016.             $emova_settings_einheit = ($customFields["emova_settings_einheit"]);
  1017.             if( $emova_settings_lieferp_text null )
  1018.                 $emova_settings_lieferp_text '';
  1019.             if( $emova_settings_ust =  null )
  1020.                 $emova_settings_ust 0;
  1021.             if( $emova_settings_lp_brutto null )
  1022.                 $emova_settings_lp_brutto 0;
  1023.             if( $emova_settings_lp_netto )
  1024.                 $emova_settings_lp_netto 0;
  1025.             if( $emova_settings_einheit null )
  1026.                 $emova_settings_einheit '';
  1027.         } 
  1028.         if( $doDump )
  1029.             dump('CustomPricePlugin:onOrderPlaced mid4');
  1030.         $orderId $event->getOrder()->getId();
  1031.             $this->orderRepository->upsert([[
  1032.                 'id' => $orderId,
  1033.                                 'customFields' => [
  1034.                 'custom_order_fields_poid' => $customFieldPoidValue,
  1035.                 'custom_order_fields_note' => $clientNote,
  1036.                 'custom_order_fields_delivery' => $clientDelivery,
  1037.                 'custom_order_fields_deliverytext' => $clientDeliveryText,
  1038.                 'custom_order_fields_addresses' => $addresses,
  1039.                 'custom_order_fields_evaccountholder' => $emova_sepa_accountholder,
  1040.                 'custom_order_fields_eviban' => $emova_sepa_iban,
  1041.                 'custom_order_fields_evsepa' => $emova_sepa_allowed,
  1042.                 'emova_settings_lieferp_text' => $emova_settings_lieferp_text,
  1043.                 'emova_settings_ust' => $emova_settings_ust,
  1044.                 'emova_settings_lp_brutto' => $emova_settings_lp_brutto,
  1045.                 'emova_settings_lp_netto' => $emova_settings_lp_netto,
  1046.                 'emova_settings_einheit' => $emova_settings_einheit,
  1047.                 'custom_order_fields_voucher' => $validvoucher,
  1048.             ]
  1049.             ]], $event->getContext());
  1050.         if( $doDump )
  1051.             dump($event->getOrder());
  1052.         if( $doDump )
  1053.             dump('CustomPricePlugin:onOrderPlaced mid4');
  1054.         $session->set('ev_onOrderPlaced end''true');
  1055.     
  1056.         }
  1057.     public function onVariantListingPrice(ProductVariantListingPriceEvent $event): void
  1058.     {
  1059.                 $salesContext $event->getSalesChannelContext();
  1060.                 $salesChannel $salesContext->getSalesChannel();
  1061.         $scname $salesChannel->getName();
  1062.               $scarray = array("EMOVA Heizöl""EMOVA Diesel""EMOVA Pellets","EMOVA Tankreinigung");
  1063.                 if (!in_array($scname$scarray)) 
  1064.               {
  1065.                     return;
  1066.         }
  1067.         $variants $event->getPage()->getProduct()->getVariants();
  1068.         
  1069.         foreach ($variants as $variant) {
  1070.             $variant->setCalculatedPrice(new CalculatedPrice(10.010.00false));
  1071.         }
  1072.     }
  1073.     function getCityForZipCode(string $zipCode): ?string
  1074.     {
  1075.         $sql "SELECT * FROM ev_zip_city WHERE plz = ? LIMIT 1";
  1076.         $params = [$zipCode];
  1077.       $result $this->connection->executeQuery($sql$params)->fetch();
  1078.         if ($result === false
  1079.             {
  1080.         return null;
  1081.         }
  1082.         return $result['ort'];
  1083.       }
  1084.               //BeforeLineItemAddedEvent::class => ['onLineItemAdded',2500],
  1085. /*    public function onLineItemAdded(BeforeLineItemAddedEvent $event): void
  1086.     {
  1087.        //     dump('CustomPricePlugin:onLineItemAdded');
  1088.          //   $lineItem = $event->getLineItem();
  1089.            //   dump('here the LineItem');
  1090.          //    dump($lineItem);   
  1091.             // if ($event->getLineItem()->getType() === PromotionProcessor::LINE_ITEM_TYPE) {
  1092.           // $code = $event->getLineItem()->getReferencedId();
  1093.         //       }
  1094.     }
  1095. */
  1096.     public function productPrice
  1097.      $product,
  1098.      SessionInterface $session
  1099.      String $priceOfferId$entities$key$event )
  1100.         {
  1101.           $doDump false;
  1102.           $productId $product->getId();
  1103.           $productNumber $product->getProductNumber();
  1104.           if( $doDump )
  1105.           {
  1106.             dump($productNumber);
  1107.           }
  1108.           if( $productNumber == null )
  1109.               return;
  1110.           $dot_position strpos($productNumber'.');
  1111.           $productNumber $dot_position !== false substr($productNumber0$dot_position) : $productNumber;
  1112.           $price $product->getCalculatedPrice();
  1113.           $sql "SELECT * FROM ev_preisanfragen WHERE productnumber = ? AND priceofferid = ? AND validuntil >= NOW() ORDER BY createdate DESC LIMIT 1";
  1114.           $params = [$productNumber,$priceOfferId];
  1115.           $priceData $this->connection->executeQuery($sql$params)->fetch();
  1116.           if( $doDump )
  1117.           {
  1118.             dump($productNumber);
  1119.             dump($priceOfferId);
  1120.             dump($priceData);
  1121.           }
  1122.           $unit 100;
  1123.           switch ($productNumber) {
  1124.                  case '4000':
  1125.                  case '4020':
  1126.                  case '4001':
  1127.                  case '4021':
  1128.                    $unit 1000;
  1129.           }
  1130.           if ($priceData !== false) {
  1131.               $postcode =$priceData['postcode'];
  1132.               $session->set('ev_postcode'$postcode);
  1133.               $countt =$priceData['countt'];
  1134.               $session->set('ev_countt'$countt);
  1135.               $huelle =$priceData['huelle'];
  1136.               $session->set('ev_huelle'$huelle);
  1137.               $numaddresses =$priceData['numaddresses'];
  1138.               $session->set('ev_numaddresses'$numaddresses);
  1139.               $type gettype($postcode);
  1140.               $emova_city $this->getCityForZipCode($postcode);
  1141.               $session->set('ev_city'$emova_city);
  1142.               $liefertermine $priceData['liefertermine'];
  1143.               $session->set('ev_liefertermine'$liefertermine);
  1144.               $newPrice = (float) $priceData['pricenet'];
  1145.               $taxRate = (float) $priceData['taxpercent'];
  1146.               $tax = (float) $priceData['pricetax'];
  1147.               $quantity = (float) $priceData['quantity'];
  1148.               $session->set('ev_quantity'$quantity);
  1149.               $mandantor =  $priceData['mandantor'];
  1150.               if( $mandantor == 'Kreuzmayr Bayern GmbH' )
  1151.               {
  1152.                  $mandantor =  'DS Emova GmbH';
  1153.               }
  1154.               $session->set('ev_mandantor',$mandantor);
  1155.               $productnumrequested $priceData['productNumRequested'];
  1156.               $session->set('ev_prodrequested',$productnumrequested);
  1157.               $precision = (float)6;
  1158.               $unitPrice= ($newPrice/$quantity)*$unit;
  1159.           if( $doDump )
  1160.           {
  1161.             dump('new and unitPrice');
  1162.             dump($priceData);
  1163.             dump($unitPrice);
  1164.           }
  1165.               $calculatedTax = new CalculatedTax(
  1166.               $tax$taxRate$newPrice,
  1167.               $quantity$precision);
  1168.               $calculatedTaxCollection = new CalculatedTaxCollection([$calculatedTax]);
  1169.               $price = new CalculatedPrice(
  1170.                 $unitPrice$newPrice$calculatedTaxCollection,
  1171.                 new TaxRuleCollection([new TaxRule($taxRate)]),
  1172.                 $quantity
  1173.               );
  1174.               $product->setCalculatedPrice($price);
  1175.               $ccprice = new CalculatedCheapestPrice(
  1176.               $unitPrice$newPrice$calculatedTaxCollection,
  1177.                 new TaxRuleCollection([new TaxRule($taxRate)]),
  1178.                 $quantity
  1179.               );
  1180.               $product->setCalculatedCheapestPrice($ccprice);
  1181.              // Modify the price object
  1182.               $pnewPrice = new Price(
  1183.                'b7d2554b0ce847cd82f3ac9bd1c0dfca'//$price->getCurrencyId(),
  1184.                $newPrice$newPricefalse
  1185.              );
  1186.             // Replace the price object in the collection
  1187.             $priceCollection = new PriceCollection([$pnewPrice]);
  1188.             // Set the new price collection for the product
  1189.             $product->setPrice($priceCollection);
  1190.             // Modify the price object
  1191.             $pnewPrice = new Price(
  1192.                'b7d2554b0ce847cd82f3ac9bd1c0dfca'//$price->getCurrencyId(),
  1193.                $newPrice,
  1194.                $newPrice,
  1195.                false
  1196.              );
  1197.             // Replace the price object in the collection
  1198.             $priceCollection = new PriceCollection([$pnewPrice]);
  1199.             // Set the new price collection for the product
  1200.             $product->setPurchasePrices($priceCollection);
  1201.           }
  1202.           else
  1203.           {
  1204.                         if( $entities != null )
  1205.                         {
  1206.                 $entities->remove($key);
  1207.                 $event->getResult()->remove($key);
  1208.               }
  1209.           }
  1210.         }
  1211.     public function onCategoryPageLoaded(CategoryPageLoadedEvent $event): void
  1212.     {
  1213.             //dump('CustomPricePlugin:onCategoryPageLoaded');
  1214.     }
  1215.     public function onProductPageLoaded(ProductPageLoadedEvent $event): void
  1216.     {
  1217.         /** @var ProductEntity $product */
  1218.         $doDump false;
  1219.         if( $doDump )
  1220.                dump('CustomPricePlugin:onProductPageLoaded');
  1221.         $priceOfferId=null;
  1222.         $poidIsSet=false;
  1223.         $request $this->requestStack->getCurrentRequest();
  1224.         $salesContext $event->getSalesChannelContext();
  1225.         /** @var SalutationCollection $salutations */
  1226.         $salutations $this->salutationRepository->search(new Criteria(), $salesContext->getContext())->getEntities();
  1227.         $salesChannel $salesContext->getSalesChannel();
  1228.     $scname $salesChannel->getName();
  1229.         $productId $event->getPage()->getProduct()->getId();
  1230.     $customFieldValues $this->getProductCustomFieldValues($productId'ev_wallbox'$event->getContext());
  1231.     $customFieldOpts $this->getProductCustomFieldOptions($productId'ev_wallbox'$event->getContext());
  1232.     $customFieldLabels $this->getCustomFieldLabels('ev_wallbox'$event->getContext());
  1233.         $customFieldTranslated $this->getTranslatedCustomFields$customFieldOpts$customFieldValues$customFieldLabels);
  1234.     $event->getPage()->assign(['customFieldTranslated' => $customFieldTranslated]);
  1235. //    $myCustomFieldOptions = $this->getCustomFieldOptions('ev_wallboxdaten_voltagesVolt', $event->getContext());
  1236. //    $event->getPage()->assign(['customFieldOptions' => $myCustomFieldOptions]);
  1237.         $scarray = array("EMOVA Heizöl""EMOVA Diesel""EMOVA Pellets","EMOVA Tankreinigung");
  1238.         if (!in_array($scname$scarray)) 
  1239.         {
  1240.        if( $doDump )
  1241.                dump($scname);
  1242.            return;
  1243.         }
  1244.         $cart $this->cartService->getCart($salesContext->getToken(), $salesContext);
  1245.         if( $doDump )
  1246.              dump('lineitems:');
  1247.         $lineItemsRemoved=false;
  1248.         // Durchgehen aller LineItems im Warenkorb
  1249.         foreach ($cart->getLineItems() as $lineItem
  1250.         {
  1251.             if( $doDump )
  1252.                   dump($lineItem);
  1253.             if( $lineItem != null 
  1254.             {
  1255.               $payload $lineItem->getPayload();
  1256.               if (isset($payload['productNumber'])) 
  1257.               {
  1258.                $productNumber $payload['productNumber'];
  1259.                $cart->remove($lineItem->getId());
  1260.            $lineItemsRemoved=true;
  1261.            if( $doDump )
  1262.                     dump($productNumber);
  1263.           }
  1264.         }
  1265.         }
  1266.         if( $lineItemsRemoved )
  1267.             $this->cartService->recalculate($cart$salesContext);
  1268.         if( $doDump )
  1269.             dump($request);
  1270.         if ($request->query->has('poid'))
  1271.         {
  1272.           $priceOfferId $request->query->get('poid');
  1273.           $poidIsSet=true;
  1274.           $session $request->getSession();
  1275.           if( $doDump )
  1276.             dump('session set poid 2');
  1277.           $session->set('poid'$priceOfferId);
  1278.         }
  1279.         else
  1280.         {
  1281.           $session $request->getSession();
  1282.           if ($session->has('poid'))
  1283.           {
  1284.            $priceOfferId $session->get('poid');
  1285.            $poidIsSet=true;
  1286.           }
  1287.         }
  1288.         $product $event->getPage()->getProduct();
  1289.         if( $priceOfferId != null )
  1290.         $this->productPrice$product$session$priceOfferId,
  1291.                  nullnull,null );
  1292.         if( $doDump ) {
  1293.           dump($priceOfferId);
  1294.           dump($salesChannel);
  1295.           dump($scname);
  1296.           dump($event);
  1297.           dump($product);
  1298.         }
  1299.     }
  1300.     private function sortProducts(array $products$prodSelected): array
  1301.     {
  1302.     // Gewuenschte Reihenfolge
  1303.     $order = ['1121''1101''1120''1100''1020','1000''2020''2000''4021','4020','4001','4000','9640','9641','9642'];
  1304.         // es gibt :
  1305.         // B+V und H : 1121 1101 ecovita 1001 1000 normal
  1306.         // Kreuzmayr : 1120 1100 vitatherm 1001 1000 normal 
  1307.     // 2000, 2020 Diesel, 4000,4001,4020, 4021 Pellets
  1308.     // Produkte, deren Nummer mit ..  beginnt, filtern
  1309.         $doDump false;
  1310.         $doDelete false;
  1311.         $prodToDelete '9999';
  1312.         $prodToDelete2 '9999';
  1313.         switch ($prodSelected) {
  1314.     case '1120':
  1315.         $order = ['1121''1101''1120''1100''1020''1000'];
  1316.                 $doDelete true;
  1317.                 $prodToDelete '1020'// 1020
  1318.                 $prodToDelete2 '1020'// 1020
  1319.         break;
  1320.     case '1121':
  1321.         $order = ['1121''1101''1120''1100''1020''1000'];
  1322.                 $doDelete true;
  1323.                 $prodToDelete '1020'// 1020
  1324.                 $prodToDelete2 '1020'// 1020
  1325.         break;
  1326.     case '1100':
  1327.         $order = ['1101''1121''1100''1120''1020''1000'];
  1328.                 $doDelete true;
  1329.                 $prodToDelete '1020'// 1120
  1330.                 $prodToDelete2 '1020'// 1120
  1331.         break;
  1332.     case '1101':
  1333.         $order = ['1101''1121''1100''1120''1020''1000'];
  1334.                 $doDelete true;
  1335.                 $prodToDelete '1020'// 1120
  1336.                 $prodToDelete2 '1020'// 1120
  1337.         break;
  1338.     case '1000':
  1339.         $order = ['1000''1101''1121''1100''1120''1020'];
  1340.                 $doDelete true;
  1341.                 $prodToDelete '1020'// 1101
  1342.                 $prodToDelete2 '1020'// 1100
  1343.         break;
  1344.     case '1020':
  1345.         $order = ['1020''1101''1121''1100''1120''1000'];
  1346.                 $doDelete true;
  1347.                 $prodToDelete '1000';
  1348.                 $prodToDelete2 '1000';
  1349.         break;
  1350.     case '9640':
  1351.         $order = ['9640''9641''9642'];
  1352.                 $doDelete true;
  1353.                 $prodToDelete '9641';
  1354.                 $prodToDelete2 '9642';
  1355.         break;
  1356.     case '9641':
  1357.         $order = ['9641''9642''9640'];
  1358.                 $doDelete true;
  1359.                 $prodToDelete '9642';
  1360.                 $prodToDelete2 '9640';
  1361.         break;
  1362.     case '9642':
  1363.         $order = ['9642''9641''9640'];
  1364.                 $doDelete true;
  1365.                 $prodToDelete '9640';
  1366.                 $prodToDelete2 '9641';
  1367.         break;
  1368.         }    
  1369.     // Produkte nach der gegebenen Reihenfolge sortieren
  1370.     usort($products, function(SalesChannelProductEntity $aSalesChannelProductEntity $b) use ($order) {
  1371.         $startNumberA substr($a->getProductNumber(), 04);
  1372.         $startNumberB substr($b->getProductNumber(), 04);
  1373.         $indexA array_search($startNumberA$order);
  1374.         $indexB array_search($startNumberB$order);
  1375.         if ($indexA === false && $indexB === false) { // Beide Startnummern sind nicht in der Reihenfolge
  1376.             return 0;
  1377.         } elseif ($indexA === false) { // Nur die Startnummer von a ist nicht in der Reihenfolge
  1378.             return 1;
  1379.         } elseif ($indexB === false) { // Nur die Startnummer von b ist nicht in der Reihenfolge
  1380.             return -1;
  1381.         } else { // Beide Startnummern sind in der Reihenfolge
  1382.             return $indexA $indexB;
  1383.         }
  1384.     });
  1385.        $filteredProducts2array_filter($products, function(\Shopware\Core\Content\Product\SalesChannel\SalesChannelProductEntity $product) use( $prodToDelete) {
  1386.         return strpos($product->getProductNumber(), $prodToDelete) !== 0;
  1387.        });
  1388.        $filteredProductsarray_filter($filteredProducts2, function(\Shopware\Core\Content\Product\SalesChannel\SalesChannelProductEntity $product) use( $prodToDelete2) {
  1389.         return strpos($product->getProductNumber(), $prodToDelete2) !== 0;
  1390.        });
  1391.     // Produkte, deren Nummer mit $prodSelected beginnt, finden und an den Anfang setzen
  1392.     $productsStartingWith200 array_filter($filteredProducts, function(SalesChannelProductEntity $product) use ($prodSelected) {
  1393.         return strpos($product->getProductNumber(), $prodSelected) === 0;
  1394.     });
  1395.         $filteredProducts2array_udiff($filteredProducts$productsStartingWith200, function ($productA$productB) {
  1396.     return strcmp($productA->getId(), $productB->getId());
  1397.         });
  1398.     $sortedProducts array_merge($productsStartingWith200$filteredProducts2);
  1399.         if( $doDump ) {
  1400.         dump('productsStartingWith200');
  1401.         dump($productsStartingWith200);
  1402.         dump("productToDelete");
  1403.         dump($prodToDelete);
  1404.         dump("prodSelected");
  1405.         dump($prodSelected);
  1406.         dump('$filteredProducts');
  1407.         dump($filteredProducts);
  1408.         dump('$filteredProducts2');
  1409.         dump($filteredProducts2);
  1410.         dump('$sortedProducts');
  1411.         dump($sortedProducts);
  1412.         }
  1413.     return $sortedProducts;
  1414.     }
  1415.     private function sortWallboxes(array $products$productNumbersToKeep): array
  1416.     {
  1417.             $filteredProducts array_filter($products, function ($product) use ($productNumbersToKeep) {
  1418.                 // Hier nehmen wir an, dass die Produktnummer in einem Feld mit dem Namen 'productNumber' gespeichert ist.
  1419.                 $productNumber $product->get('productNumber');
  1420.     
  1421.                 // Wenn die Produktnummer in der Liste der zu behaltenden Produktnummern ist, behalten wir das Produkt.
  1422.                 return in_array($productNumber$productNumbersToKeep);
  1423.             });
  1424.             return $filteredProducts;
  1425.     }
  1426.     public function onProductListingResult(ProductListingResultEvent $event): void
  1427.     {
  1428.         $doDump false;
  1429.         if( $doDump )
  1430.             dump('CustomPricePlugin:onProductListingResult');
  1431.         $priceOfferId=null;
  1432.         $poidIsSet=false;
  1433.         $request $this->requestStack->getCurrentRequest();
  1434.         $salesContext $event->getSalesChannelContext();
  1435.         $salesChannel $salesContext->getSalesChannel();
  1436.         $scname $salesChannel->getName();
  1437.         $scarray = array("EMOVA Heizöl""EMOVA Diesel""EMOVA Pellets","EMOVA Tankreinigung");
  1438.     if (!in_array($scname$scarray)) 
  1439.     {
  1440.             // normaler store
  1441.             if( $doDump )
  1442.             {
  1443.             dump('scname');
  1444.             dump($scname);
  1445.             }
  1446.             $productIds $request->query->get('products', []);
  1447.             $request->getSession()->set('ev_wallboxes'$productIds);
  1448.         if( !empty($productIds) && !($productIds === null)) 
  1449.         {
  1450.                 // Set the productIds as a session variable
  1451.                 $request->getSession()->set('ev_wallboxes'$productIds);
  1452.                 $entities $event->getResult()->getEntities();
  1453.                 // Sammlung in ein Array konvertieren
  1454.                 $productToSort $entities->getElements();
  1455.                 foreach ($productIds as &$product) {
  1456.                     if (strpos($product"DP") === 0) { // Prüfen, ob die Produktnummer mit "DP" beginnt
  1457.                         $product substr_replace($product"0", -1); // Ersetze die letzte Ziffer durch eine 0
  1458.                     }
  1459.                 }
  1460.         unset($product);
  1461.         $sortedProducts $this->sortWallboxes($productToSort,$productIds);
  1462.             // Neue Produkt-Sammlung erstellen und setzen
  1463.             $event->getResult()->clear();
  1464.             $event->getResult()->fill($sortedProducts);
  1465.             $entities $event->getResult()->getEntities();
  1466.             }
  1467.             return;
  1468.     }
  1469.     //
  1470.     // hier Heizöl, Pellets, Diesel
  1471.      
  1472.         $session $request->getSession();
  1473.         if ($request->query->has('poid')) 
  1474.         {
  1475.                $priceOfferId $request->query->get('poid');
  1476.                $poidIsSet=true;
  1477.                if( $doDump )
  1478.                {
  1479.                    dump('request set poid');
  1480.                    dump($priceOfferId);
  1481.                }
  1482.                $session->set('poid'$priceOfferId);
  1483.         } 
  1484.         else 
  1485.         {
  1486.                $session $request->getSession();
  1487.                if ($session->has('poid')) 
  1488.                {
  1489.                    $priceOfferId $session->get('poid');
  1490.                    if( $doDump )
  1491.                    {
  1492.                           dump('session set poid ');
  1493.                           dump($priceOfferId);
  1494.                    }
  1495.                    $poidIsSet=true;
  1496.                } 
  1497.         }
  1498.         if ($request->query->has('product'))
  1499.         {
  1500.           $productReq $request->query->get('product');
  1501.           $session $request->getSession();
  1502.           $session->set('productReq'$productReq);
  1503.         }
  1504.         else
  1505.         {
  1506.           $session $request->getSession();
  1507.           if ($session->has('productReq'))
  1508.           {
  1509.            $productReq $session->get('productReq');
  1510.           }
  1511.         }
  1512.            
  1513.         $entities $event->getResult()->getEntities();
  1514.         $elements $event->getResult()->getElements();
  1515.         if( $doDump ) {
  1516.         dump('productReq');
  1517.         dump($productReq);
  1518.         dump($salesChannel);
  1519.         dump($scname);
  1520.         dump($event);
  1521.         dump($entities);
  1522.         }
  1523.         
  1524.         if( $poidIsSet 
  1525.            {
  1526.              if( $doDump ) {
  1527.                dump('poidisSet');
  1528.           }
  1529.           $entities $event->getResult()->getEntities();
  1530.           // Sammlung in ein Array konvertieren
  1531.           $productToSort $entities->getElements();
  1532.           // Produkte sortieren
  1533.           $sortedProducts $this->sortProducts($productToSort,$productReq);
  1534.       //$sortedProducts = $event->getResult()->getEntities();
  1535.           // Neue Produkt-Sammlung erstellen und setzen
  1536.       $event->getResult()->clear();
  1537.           $event->getResult()->fill($sortedProducts);
  1538.           $entities $event->getResult()->getEntities();
  1539.       if( $doDump ) {
  1540.         dump($entities);
  1541.       }
  1542.           $this->logger->warning('CustomPriceSubscriber: onProductListingResult poidSet.');
  1543.           foreach ($entities as $key => $product
  1544.       {
  1545.          $this->productPrice$product$session$priceOfferId
  1546.              $entities$key$event );
  1547.       }
  1548.           $postcode $session->get('ev_postcode');
  1549.           $ev_addresses $session->get('ev_address_data');
  1550.           $session->remove('ev_voucher_code');
  1551.           $session->remove('ev_voucher_code_valid');
  1552.           if( $ev_addresses !== null )
  1553.           {
  1554.             if( $postcode !== $ev_addresses[0]['ev_postcode'] )
  1555.             {
  1556.               $session->remove('ev_addresses');
  1557.               $session->remove('ev_liefertermine');
  1558.               $session->remove('ev_address_data');
  1559.               $session->remove('ev_address_id');
  1560.               $session->remove('evre_address_id');
  1561.               $session->remove('ev_voucher_code');
  1562.               $session->remove('ev_voucher_code_valid');
  1563.                  $session->remove('ev_numaddresses');
  1564.               $session->remove('ev_prodrequested');
  1565.               $session->remove('ev_addresses');
  1566.               $session->remove('evre_addresses');
  1567.             }
  1568.           } 
  1569.        }
  1570.        if( $doDump )
  1571.        {
  1572.         dump($entities);
  1573.         $entities $event->getResult()->getEntities();
  1574.         dump($entities);
  1575.         dump($event);
  1576.        }
  1577.    }
  1578. }