custom/plugins/AmMacTradeCustomPlugins/src/Subscriber/MacTradeSubscriber.php line 586

Open in your IDE?
  1. <?php
  2. namespace AmMacTradeCustomPlugins\Subscriber;
  3. use Shopware\Core\Checkout\Cart\Event\AfterLineItemAddedEvent;
  4. use Shopware\Core\Checkout\Cart\Event\BeforeLineItemAddedEvent;
  5. use Shopware\Core\Checkout\Cart\Event\BeforeLineItemRemovedEvent;
  6. use Shopware\Core\Checkout\Cart\Event\CheckoutOrderPlacedEvent;
  7. use Shopware\Core\Checkout\Cart\LineItemFactoryRegistry;
  8. use Shopware\Core\Checkout\Cart\Price\QuantityPriceCalculator;
  9. use Shopware\Core\Checkout\Cart\Price\Struct\QuantityPriceDefinition;
  10. use Shopware\Core\Checkout\Cart\SalesChannel\CartService;
  11. use Shopware\Core\Checkout\Customer\Event\CustomerLoginEvent;
  12. use Shopware\Core\Checkout\Promotion\Cart\PromotionProcessor;
  13. use Shopware\Core\Content\Product\ProductEntity;
  14. use Shopware\Core\Framework\Adapter\Translation\AbstractTranslator;
  15. use Shopware\Core\Framework\Context;
  16. use Shopware\Core\Framework\DataAbstractionLayer\EntityRepository;
  17. use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
  18. use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsAnyFilter;
  19. use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter;
  20. use Shopware\Core\Framework\Struct\ArrayEntity;
  21. use Shopware\Storefront\Page\Checkout\Finish\CheckoutFinishPageLoadedEvent;
  22. use Shopware\Storefront\Page\Checkout\Offcanvas\OffcanvasCartPageLoadedEvent;
  23. use Shopware\Storefront\Page\Product\ProductPageLoadedEvent;
  24. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  25. use Symfony\Component\HttpFoundation\RequestStack;
  26. use Shopware\Core\Checkout\Cart\LineItem\LineItem;
  27. use Shopware\Core\System\SystemConfig\SystemConfigService;
  28. class MacTradeSubscriber implements EventSubscriberInterface
  29. {
  30. //    public const notableWeb = ["idealo.de/", "billiger.de/" , "geizhals.de/","testsieger.de/"];
  31.     public const SESSION_KEY_PROMOTION_CODES 'cart-promotion-codes';
  32.     public const SEARCH_RESTRICTIONS_WORDS = ["idealo""billiger""protection""protect","geizhals","testsieger"];
  33.     public const REFER_TAG = ["testsieger" => "testsieger.de/"];
  34.     public const SESSION_EXPIRE_TIME 1800//This is in seconds 120 = 2 minutes
  35.     protected EntityRepository $productRepository;
  36.     protected EntityRepository $macTradeInsuranceRepository;
  37.     protected EntityRepository $macTradeSppRepository;
  38.     protected EntityRepository $promotionRepository;
  39.     protected AbstractTranslator $abstractTranslator;
  40.     protected RequestStack $requestStack;
  41.     protected LineItemFactoryRegistry $factory;
  42.     protected CartService $cartService;
  43.     protected SystemConfigService $systemConfigService;
  44.     protected QuantityPriceCalculator $qPCalculator;
  45.     public function __construct(
  46.         EntityRepository        $productRepository,
  47.         EntityRepository        $macTradeInsuranceRepository,
  48.         EntityRepository        $macTradeSppRepository,
  49.         EntityRepository        $promotionRepository,
  50.         AbstractTranslator      $abstractTranslator,
  51.         RequestStack            $requestStack,
  52.         LineItemFactoryRegistry $factory,
  53.         CartService             $cartService,
  54.         SystemConfigService     $systemConfigService,
  55.         QuantityPriceCalculator $qPCalculator
  56.     )
  57.     {
  58.         $this->productRepository $productRepository;
  59.         $this->macTradeInsuranceRepository $macTradeInsuranceRepository;
  60.         $this->macTradeSppRepository $macTradeSppRepository;
  61.         $this->promotionRepository $promotionRepository;
  62.         $this->abstractTranslator $abstractTranslator;
  63.         $this->requestStack $requestStack;
  64.         $this->factory $factory;
  65.         $this->cartService $cartService;
  66.         $this->systemConfigService $systemConfigService;
  67.         $this->qPCalculator $qPCalculator;
  68.     }
  69.     public static function getSubscribedEvents()
  70.     {
  71.         return [
  72.             ProductPageLoadedEvent::class => 'onProductPageLoaded',
  73.             OffcanvasCartPageLoadedEvent::class => 'onOffCanvasCartPageLoaded',
  74.             BeforeLineItemAddedEvent::class => 'onBeforeLineItemAdded',
  75.             AfterLineItemAddedEvent::class => 'onAfterLineItemAdded',
  76.             BeforeLineItemRemovedEvent::class => 'onBeforeLineItemRemoved',
  77.             CustomerLoginEvent::class => 'onCustomerLoginEvent',
  78.             CheckoutFinishPageLoadedEvent::class => 'onCheckoutFinishPageLoadedEvent',
  79.             CheckoutOrderPlacedEvent::class => 'onCheckoutOrderPlacedEvent',
  80.         ];
  81.     }
  82.     public function onCustomerLoginEvent(CustomerLoginEvent $event): void
  83.     {
  84.         $salesChannelContext $event->getSalesChannelContext()->getSalesChannelId();
  85.         $config $this->getConfigValue($salesChannelContext);
  86.         $data = [];
  87.         $configInsuranceWarranty $config['amMacTradeInsuranceWarranty'] ?? false;
  88.         if ($configInsuranceWarranty) {
  89.             if (isset($_SESSION['session_token'])) {
  90.                 $cartTokenName $_SESSION['session_token'];
  91.                 $token $event->getContextToken();
  92.                 $criteria = new Criteria();
  93.                 $criteria->addFilter(new EqualsFilter('userId'$cartTokenName));
  94.                 $dataResults $this->macTradeInsuranceRepository->search($criteria$event->getContext());
  95.                 if ($dataResults->count() > 0) {
  96.                     $dataResult $dataResults->first();
  97.                     $data = [
  98.                         'id' => $dataResult->getId(),
  99.                         'userId' => $token,
  100.                         'productId' => $dataResult->getProductId(),
  101.                     ];
  102.                 }
  103.                 if ($data) {
  104.                     $this->macTradeInsuranceRepository->upsert([$data], Context::createDefaultContext());
  105.                 }
  106.             }
  107.         }
  108.     }
  109.     public function onBeforeLineItemRemoved(BeforeLineItemRemovedEvent $event): void
  110.     {
  111.         $salesChannelContext $event->getSalesChannelContext()->getSalesChannelId();
  112.         $config $this->getConfigValue($salesChannelContext);
  113.         $configInsuranceWarranty $config['amMacTradeInsuranceWarranty'] ?? false;
  114.         if ($configInsuranceWarranty) {
  115.             $deleteId $event->getLineItem()->getId();
  116.             $cartTokenName $event->getCart()->getToken();
  117.             if (!empty($cartTokenName)) {
  118.                 $dbResultData $dbProductData $dbInsuranceProductData = [];
  119.                 $criteria = new Criteria();
  120.                 $criteria->addFilter(new EqualsFilter('userId'$cartTokenName));
  121.                 $cartResult $this->macTradeInsuranceRepository->search($criteria$event->getContext());
  122.                 foreach ($cartResult as $cartRow) {
  123.                     $id $cartRow->getId();
  124.                     $productId $cartRow->getProductId();
  125.                     $insuranceId $cartRow->getInsuranceId();
  126.                     $dbResultData[$productId] = $cartRow;
  127.                     $dbResultData[$insuranceId] = $cartRow;
  128.                     $dbProductData[$productId] = !isset($dbProductData[$productId]) ? $dbProductData[$productId];
  129.                     $dbProductData[$productId]++;
  130.                     $dbInsuranceProductData[$insuranceId] = !isset($dbInsuranceProductData[$insuranceId]) ? $dbInsuranceProductData[$insuranceId];
  131.                     $dbInsuranceProductData[$insuranceId]++;
  132.                 }
  133.                 if (isset($dbInsuranceProductData[$deleteId])) {
  134.                     $criteria = new Criteria();
  135.                     $criteria->addFilter(new EqualsFilter('insuranceId'$insuranceId));
  136.                     $criteria->addFilter(new EqualsFilter('userId'$cartTokenName));
  137.                     $dataResults $this->macTradeInsuranceRepository->search($criteriaContext::createDefaultContext());
  138.                     if ($dataResults->count() > 0) {
  139.                         $deleteData = [];
  140.                         foreach ($dataResults as $dataResult) {
  141.                             $deleteData[] = ['id' => $dataResult->getId()];
  142.                         }
  143.                         $this->macTradeInsuranceRepository->delete($deleteDataContext::createDefaultContext());
  144.                     }
  145.                 }
  146.             }
  147.         }
  148.     }
  149.     public function onBeforeLineItemAdded(BeforeLineItemAddedEvent $event): void
  150.     {
  151.         $salesChannelContext $event->getSalesChannelContext()->getSalesChannelId();
  152.         $config $this->getConfigValue($salesChannelContext);
  153.         $configInsuranceWarranty $config['amMacTradeInsuranceWarranty'] ?? false;
  154.         $configIdealoFeed $config['idealoFeed'] ?? false;
  155.         if ($configInsuranceWarranty === true) {
  156.             $this->onBeforeLineItemAddedInsurance($event);
  157.         }
  158.         if ($configIdealoFeed === true) {
  159.             $this->onBeforeLineItemAddedIdealo($event);
  160.         }
  161.     }
  162.     public function onAfterLineItemAdded(AfterLineItemAddedEvent $event): void
  163.     {
  164.         unset($_SESSION['added_insurance']);
  165.     }
  166.     public function onProductPageLoaded(ProductPageLoadedEvent $event): void
  167.     {
  168.         $salesChannelContext $event->getSalesChannelContext()->getSalesChannelId();
  169.         $config $this->getConfigValue($salesChannelContext);
  170.         $configInsuranceWarranty $config['amMacTradeInsuranceWarranty'] ?? false;
  171.         $configSppProduct $config['sppProduct'] ?? false;
  172.         $configIdealoFeed $config['idealoFeed'] ?? false;
  173.         if ($configInsuranceWarranty === true) {
  174.             $this->onProductPageLoadedInsurance($event);
  175.         }
  176.         if ($configSppProduct === true) {
  177.             $this->onProductPageLoadedSpp($event);
  178.         }
  179.         if($configIdealoFeed === true) {
  180. //            $urls = $config['notableWeb'];
  181.             if (isset($config['notableWeb'])) {
  182.                 $configIdealNotableWeb $config['notableWeb'];
  183.                 $urls array_map('trim'explode(','str_replace(['"'' '], ''$configIdealNotableWeb)));
  184.             } else {
  185.                 $urls = ["idealo.de/""billiger.de/" "geizhals.de/","testsieger.de/"];
  186.             }
  187.             $this->onProductPageLoadedIdealo($event$urls);
  188.         }
  189.     }
  190.     public function onOffCanvasCartPageLoaded(OffcanvasCartPageLoadedEvent $event): void
  191.     {
  192.         $salesChannelContext $event->getSalesChannelContext()->getSalesChannelId();
  193.         $config $this->getConfigValue($salesChannelContext);
  194.         $configInsuranceWarranty $config['amMacTradeInsuranceWarranty'] ?? false;
  195.         if ($configInsuranceWarranty === true) {
  196.             if (isset($_SESSION['insu_id'])) {
  197.                 $page $event->getPage();
  198.                 $context $event->getContext();
  199.                 $productId = @$_SESSION['insu_id'];
  200.                 $criteria = new Criteria();
  201.                 $criteria->setLimit(1);
  202.                 $criteria->addFilter(new EqualsFilter('id'$productId));
  203.                 $insuranceProduct $this->getProduct($criteria$context);
  204.                 if ($insuranceProduct !== null) {
  205.                     $insuranceProductName $insuranceProduct->getName();
  206.                     $insuranceProductDescription $insuranceProduct->getDescription();
  207.                     $insuranceProductPrice $insuranceProduct->getPrice()->first()->getGross();
  208.                     $insuranceProductTitle $this->abstractTranslator->trans('macTrade.cart.insuranceProductTitle');
  209.                     $noInsuranceProduct $this->abstractTranslator->trans('macTrade.cart.noInsuranceProduct');
  210.                     $mainProductId = @$_SESSION['added_main_prod_id'];
  211.                     $insuranceWarranty = new ArrayEntity();
  212.                     $insuranceWarranty->set('product_id_insurance_add'0);
  213.                     $insuranceWarranty->set('insurance_name'$insuranceProductName);
  214.                     $insuranceWarranty->set('insurance_desc'$insuranceProductDescription);
  215.                     $insuranceWarranty->set('insurance_price'$insuranceProductPrice);
  216.                     $insuranceWarranty->set('insurance_add'$insuranceProductTitle);
  217.                     $insuranceWarranty->set('insurance_no'$noInsuranceProduct);
  218.                     $insuranceWarranty->set('insurance_prod_id'$productId);
  219.                     $insuranceWarranty->set('main_prod_id'$mainProductId);
  220.                     $page->addExtensions(['insurance_warranty' => $insuranceWarranty]);
  221.                 }
  222.             }
  223.         }
  224.         unset($_SESSION['insu_id']);
  225.     }
  226.     public function getProduct($criteria$context)
  227.     {
  228.         return $this->productRepository->search($criteria$context)->getEntities()->first();
  229.     }
  230.     public function getConfigValue($context)
  231.     {
  232.         return $this->systemConfigService->get('AmMacTradeCustomPlugins.config'$context);
  233.     }
  234.     public function onCheckoutFinishPageLoadedEvent(CheckoutFinishPageLoadedEvent $event): void
  235.     {
  236.         unset($_SESSION['sw-idealo-feed-product-id']);
  237.         unset($_SESSION['sw-platform-url']);
  238.         unset($_SESSION['CREATED']);
  239.     }
  240.     public function onCheckoutOrderPlacedEvent(CheckoutOrderPlacedEvent $event): void
  241.     {
  242.         unset($_SESSION['sw-idealo-feed-product-id']);
  243.         unset($_SESSION['sw-platform-url']);
  244.         unset($_SESSION['CREATED']);
  245.     }
  246.     public function onBeforeLineItemAddedInsurance(BeforeLineItemAddedEvent $event): void
  247.     {
  248.         $params $this->requestStack->getCurrentRequest()->request->all();
  249.         $payload $event->getLineItem()->getPayload();
  250.         if (isset($params['lineItems'])) {
  251.             $params array_values($params['lineItems'])[0];
  252.         }
  253.         if (isset($params['id'])) {
  254.             $productId $params['id'];
  255.         }
  256.         $randomId time();
  257.         $cartTokenName $event->getCart()->getToken();
  258.         $availableInsuranceId $this->requestStack->getCurrentRequest()->request->get('product_insurance_exist');
  259.         $time = @$_SESSION['added_insurance'];
  260.         if (!empty($availableInsuranceId) && empty($time)) {
  261.             $insuranceEvent $this->requestStack->getCurrentRequest()->request->get('product-insurance');
  262.             if ($insuranceEvent !== '0') {
  263.                 $_SESSION['added_insurance'] = time();
  264.                 $_SESSION['added_main_prod_id'] = $productId;
  265.                 $_SESSION['added_insu_prod_id'] = $availableInsuranceId;
  266.                 $lineItem $this->factory->create([
  267.                     'id' => $availableInsuranceId,
  268.                     'type' => LineItem::PRODUCT_LINE_ITEM_TYPE,
  269.                     'referencedId' => $availableInsuranceId,
  270.                     'quantity' => 1,
  271.                     'payload' => [
  272.                         'product_id_insurance' => $availableInsuranceId,
  273.                         'product_id_ref' => $productId,
  274.                     ]
  275.                 ], $event->getSalesChannelContext());
  276.                 $data = [
  277.                     'userId' => $cartTokenName,
  278.                     'productId' => $productId,
  279.                     'insuranceId' => $availableInsuranceId,
  280.                 ];
  281.                 $this->macTradeInsuranceRepository->create([$data], Context::createDefaultContext());
  282.                 $this->cartService->add($event->getCart(), $lineItem$event->getSalesChannelContext());
  283.                 $_SESSION['session_token'] = $cartTokenName;
  284.             } else {
  285.                 $_SESSION['insu_id'] = $availableInsuranceId;
  286.                 $_SESSION['added_main_prod_id'] = $productId;
  287.             }
  288.         }
  289.         $availableInsuranceId $this->requestStack->getCurrentRequest()->request->get('product-insurance-popup');
  290.         if (!empty($availableInsuranceId)) {
  291.             $productId $this->requestStack->getCurrentRequest()->request->get('product_main_id_from_popup');
  292.             $data = [
  293.                 'userId' => $cartTokenName,
  294.                 'productId' => $productId,
  295.                 'insuranceId' => $availableInsuranceId,
  296.             ];
  297.             $this->macTradeInsuranceRepository->create([$data], Context::createDefaultContext());
  298.             $_SESSION['session_token'] = $cartTokenName;
  299.         }
  300.     }
  301.     public function onBeforeLineItemAddedIdealo(BeforeLineItemAddedEvent $event): void
  302.     {
  303.         if (isset($config['notableWeb'])) {
  304.             $configIdealNotableWeb $config['notableWeb'];
  305.             $urls array_map('trim'explode(','str_replace(['"'' '], ''$configIdealNotableWeb)));
  306.         } else {
  307.             $urls = ["idealo.de/""billiger.de/" "geizhals.de/","testsieger.de/"];
  308.         }
  309.         $context $event->getSalesChannelContext();
  310.         $session $this->requestStack->getSession();
  311.         if ($event->getLineItem()->getType() === PromotionProcessor::LINE_ITEM_TYPE) {
  312.             $criteria = new Criteria();
  313.             $criteria->setTitle(PromotionProcessor::LINE_ITEM_TYPE);
  314.             $allPromotionCodesObj $this->promotionRepository->search($criteria$context->getContext());
  315.             $allPromotionCodes $allPromotionCodesObj->getElements();
  316.             $cart $event->getCart();
  317.             $lineTimes $cart->getLineItems();
  318.             $promotions $lineTimes->filterFlatByType(PromotionProcessor::LINE_ITEM_TYPE);
  319.             $notableWeb $urls;
  320.             $platFormUrl = @$_SESSION['sw-platform-url'];
  321.             if (@$_SESSION['CREATED'] && (time() - $_SESSION['CREATED'] > self::SESSION_EXPIRE_TIME)) {
  322.                 // session started more than 2 minutes ago
  323.                 unset($_SESSION['sw-idealo-feed-product-id']);
  324.                 unset($_SESSION['sw-platform-url']);
  325.                 unset($_SESSION['CREATED']);
  326.             }
  327.             array_filter($promotions, function($promotion) use ($notableWeb$platFormUrl$allPromotionCodes$event$context$lineTimes$cart$session) {
  328.                 if(@$_SESSION['sw-idealo-feed-product-id'] && sizeof($_SESSION['sw-idealo-feed-product-id']) > 0) {
  329.                     array_map(function($webURL) use ($platFormUrl$promotion$allPromotionCodes$event$context$lineTimes$cart$session) {
  330.                         $getName explode("."$webURL);
  331.                         $webName strtolower($getName[0]);
  332.                         if($webURL == @$platFormUrl) {
  333.                             $com str_contains(strtolower($promotion->getLabel()), $webName);
  334.                             if($com == true) {
  335.                                 array_filter($allPromotionCodes, function($allPromotionCode) use ($event$context$lineTimes$cart$platFormUrl$session$webName) {
  336.                                     if($allPromotionCode->getCode() == $event->getLineItem()->getReferencedId()) {
  337.                                         if (isset($config['notableWeb'])) {
  338.                                             $configIdealNotableWeb $config['notableWeb'];
  339.                                             $urls array_map('trim'explode(','str_replace(['"'' '], ''$configIdealNotableWeb)));
  340.                                         } else {
  341.                                             $urls = ["idealo.de/""billiger.de/" "geizhals.de/","testsieger.de/"];
  342.                                         }
  343.                                         $getPromotionDetail $allPromotionCode;
  344.                                         $promotionId $getPromotionDetail->getId();
  345.                                         $promotionName $getPromotionDetail->getCode();
  346.                                         $notableWeb $urls;
  347.                                         if(in_array(@$platFormUrl$notableWeb)) {
  348.                                             $promotionsCode $cart->getData()->getElements()['promotions-code']->getAutomaticPromotions();
  349.                                             array_map(function($promotionsCode) use ($webName$promotionId$promotionName$lineTimes$cart$context) {
  350.                                                 $comPar str_contains(strtolower($promotionsCode->getName()), $webName);
  351.                                                 if($comPar == true) {
  352.                                                     if(in_array($promotionId$promotionsCode->getExclusionIds())) {
  353.                                                         foreach ($lineTimes as $key => $value) {
  354.                                                             if($value->getReferencedId() == $promotionName) {
  355.                                                                 $lineTimes->removeElement($value);
  356.                                                                 $this->cartService->remove($cart$promotionId$context);
  357.                                                             }
  358.                                                         }
  359.                                                     }
  360.                                                 }
  361.                                             }, $promotionsCode);
  362.                                         }
  363.                                     }
  364.                                 });
  365.                             }
  366.                         }
  367.                     }, $notableWeb);
  368.                 }
  369.             });
  370.         }
  371.     }
  372.     public function onProductPageLoadedInsurance(ProductPageLoadedEvent $event): void
  373.     {
  374.         $_SESSION['product_id_insurance_add'] = 0;
  375.         $context $event->getContext();
  376.         $page $event->getPage();
  377.         $product $page->getProduct();
  378.         $customFields $product->getCustomFields();
  379.         if (array_key_exists('custom_insurance_product'$customFields)
  380.             && !empty($customFields['custom_insurance_product'])
  381.             && $customFields['custom_insurance_product'] !== '0'
  382.         ) {
  383.             $criteria = new Criteria();
  384.             $criteria->setLimit(1);
  385.             $criteria->addFilter(new EqualsFilter('productNumber'$customFields['custom_insurance_product']));
  386.             $criteria->addAssociation('cover.media');
  387.             $criteria->addAssociation('media.media');
  388.             $insuranceProduct $this->getProduct($criteria$context);
  389.             if ($insuranceProduct !== null) {
  390.                 $insuranceProductId $insuranceProduct->getId();
  391.                 $insuranceProductName $insuranceProduct->getName();
  392.                 $insuranceProductDescription $insuranceProduct->getDescription();
  393.                 $insuranceProductPrice $insuranceProduct->getPrice()->first()->getGross();
  394.                 $insurance = ['insurance' => $insuranceProduct];
  395.                 $page->assign($insurance);
  396.                 $insuranceProductTitle $this->abstractTranslator->trans('macTrade.pdp.insuranceProductTitle');
  397.                 $noInsuranceProduct $this->abstractTranslator->trans('macTrade.pdp.noInsuranceProduct');
  398.                 $insuranceWarranty = new ArrayEntity();
  399.                 $insuranceWarranty->set('insurance_prod_id'$insuranceProductId);
  400.                 $insuranceWarranty->set('insurance_title'$insuranceProductTitle);
  401.                 $insuranceWarranty->set('insurance_name'$insuranceProductName);
  402.                 $insuranceWarranty->set('insurance_desc'$insuranceProductDescription);
  403.                 $insuranceWarranty->set('insurance_price'$insuranceProductPrice);
  404.                 $insuranceWarranty->set('insurance_no'$noInsuranceProduct);
  405.                 $page->addExtensions(['insurance_warranty' => $insuranceWarranty]);
  406.             }
  407.         }
  408.     }
  409.     public function getSppCriteriaData($product$event)
  410.     {
  411.         $categoryIds $product->getCategoryTree();
  412. //        $categoryId = end($categoryIds);
  413.         $categoryId array_key_last($product->getSeoCategory()->getTranslated()['breadcrumb']);
  414.         $salesChannelId $event->getSalesChannelContext()->getSalesChannelId();
  415.         $criteria = new Criteria();
  416.         $criteria->addFilter(new EqualsFilter('categoryId'$categoryId));
  417.         $criteria->addFilter(new EqualsFilter('salesChannelId'$salesChannelId));
  418.         return $this->macTradeSppRepository->search($criteriaContext::createDefaultContext());
  419.     }
  420.     public function onProductPageLoadedSpp(ProductPageLoadedEvent $event): void
  421.     {
  422.         $page $event->getPage();
  423.         $product $page->getProduct();
  424.         $customFields $product->getCustomFields();
  425.         $sppId '';
  426.         $productNumber $product->getProductNumber();
  427.         $productNumber substr($productNumberstrpos($productNumber'.') + 1);
  428.         if (isset($customFields['custom_insurance_product']) && !empty($customFields['custom_insurance_product'])) {
  429.             if ($productNumber === '0001' && !empty($customFields['custom_insurance_product'])) {
  430.                 $dataResults $this->getSppCriteriaData($product$event);
  431. //                $sppId = $customFields['custom_main_variant_spp_configuration'] ?? '';
  432.                 if ($dataResults->count() !== 0) {
  433.                     foreach ($dataResults->getElements() as $dataElement) {
  434.                         $sppId $dataElement->getStoreRepresentProductId();
  435.                     }
  436.                 }
  437.             } else {
  438.                 $dataResults $this->getSppCriteriaData($product$event);
  439. //                $categoryIds = $product->getCategoryTree();
  440. //                $categoryId = end($categoryIds);
  441. //
  442. ////                $categoryId = $product->getSeoCategory()->getId();
  443. //
  444. ////                $categoryIds = $product->getSeoCategory()->getPlainBreadcrumb();
  445. ////                $categoryId = array_key_last($categoryIds);
  446. //
  447. //                $salesChannelId = $event->getSalesChannelContext()->getSalesChannelId();
  448. //
  449. //                $criteria = new Criteria();
  450. //                $criteria->addFilter(new EqualsFilter('categoryId', $categoryId));
  451. //                $criteria->addFilter(new EqualsFilter('salesChannelId', $salesChannelId));
  452. //                $dataResults = $this->macTradeSppRepository->search($criteria, Context::createDefaultContext());
  453.                 if ($dataResults->count() !== 0) {
  454.                     foreach ($dataResults->getElements() as $dataElement) {
  455.                         $sppId $dataElement->getNonRepresentProductId();
  456.                     }
  457.                 }
  458.             }
  459.             $customFieldsData = [
  460.                 'customSppId' => $sppId
  461.             ];
  462.             $this->productRepository->update([
  463.                 [
  464.                     'id' => $product->getId(),
  465.                     'customFields' => $customFieldsData,
  466.                 ]
  467.             ], Context::createDefaultContext());
  468.             $sppProduct = new ArrayEntity();
  469.             $sppProduct->set('spp'$sppId);
  470.             $page->addExtensions(['spp_product' => $sppProduct]);
  471.         }
  472.     }
  473.     public function onProductPageLoadedIdealo(ProductPageLoadedEvent $event$urls): void
  474.     {
  475.         $server $_SERVER;
  476.         $server_referer = @$server["HTTP_REFERER"];
  477. //        $server_referer = "https://www.idealo.de/preisvergleich/OffersOfProduct/201673212_-macbook-pro-14-2021-m1-pro-8-core-mkgp3d-a-z07975213-apple.html";
  478.         $tag = isset($_GET['tag']) ? $_GET['tag'] : '';
  479.         if(@$server_referer != null){
  480.             foreach ($urls as $url) {
  481.                 $com str_contains($server_referer$url);
  482.                 if($com != false){
  483.                     $StatuCheck $url;
  484.                 }
  485.             }
  486.         }
  487.         if(!isset($StatuCheck) && isset($tag)) {
  488.             if($tag == 'testsieger') {
  489.                 $StatuCheck self::REFER_TAG[$tag];
  490.             }
  491.         }
  492.         $product $event->getPage()->getProduct();
  493.         $getTaxRules $product->calculatedPrice->getTaxRules();
  494.         $getQuantity $product->calculatedPrice->getQuantity();
  495.         $getListPrice $product->calculatedPrice->getListPrice();
  496.         $getProductId $product->getId();
  497.         if($getListPrice){
  498.             $productPrice = ((@$getListPrice->getPrice() + @$getListPrice->getDiscount()));
  499.         } else {
  500.             $getUnitPriceWithoutListPrice $product->calculatedPrice->getUnitPrice();
  501.             $productPrice $getUnitPriceWithoutListPrice;
  502.         }
  503.         if (!isset($_SESSION['CREATED'])) {
  504.             $_SESSION['CREATED'] = time();
  505.         } else if (time() - $_SESSION['CREATED'] > self::SESSION_EXPIRE_TIME) {
  506.             // session started more than 2 minutes ago
  507.             unset($_SESSION['sw-idealo-feed-product-id']);
  508.             unset($_SESSION['sw-platform-url']);
  509.             unset($_SESSION['CREATED']);
  510.             sleep(1);
  511.         }
  512.         $sessionFeedProductId = @$_SESSION['sw-idealo-feed-product-id'];
  513.         $customPrice = @$product->translated['customFields']['product_custom_fields_idealo'] ? @$product->translated['customFields']['product_custom_fields_idealo'] : @$productPrice ;
  514.         if ((@$StatuCheck || (@$sessionFeedProductId && in_array($getProductId$sessionFeedProductId))) && @$customPrice) {
  515.             if (@$sessionFeedProductId && sizeof($sessionFeedProductId) > 0) {
  516.                 !in_array($getProductId$sessionFeedProductId) ? array_push($sessionFeedProductId$getProductId) : '';
  517.                 $_SESSION['sw-idealo-feed-product-id'] = $sessionFeedProductId;
  518.             } else {
  519.                 $_SESSION['sw-idealo-feed-product-id'] = array($getProductId);
  520.             }
  521.             $_SESSION['sw-platform-url'] = @$StatuCheck;
  522.             $newPrice = @$customPrice;
  523.             // build new price definition
  524.             $definition = new QuantityPriceDefinition(
  525.                 $newPrice,
  526.                 $getTaxRules,
  527.                 $getQuantity
  528.             );
  529.             if ($getListPrice !== null) {
  530.                 $definition->setListPrice($getListPrice->getPrice());
  531.             }
  532.             // build CalculatedPrice over calculator class for overwritten price
  533.             $QPCalculated $this->qPCalculator->calculate($definition$event->getSalesChannelContext());
  534.             // set new price into line item
  535.             $product->setCalculatedPrice($QPCalculated);
  536.         } else {
  537.             $newPrice $productPrice;
  538.             // build new price definition
  539.             $definition = new QuantityPriceDefinition(
  540.                 $newPrice,
  541.                 $getTaxRules,
  542.                 $getQuantity
  543.             );
  544.             if ($getListPrice !== null) {
  545.                 $definition->setListPrice($getListPrice->getPrice());
  546.             }
  547.             // build CalculatedPrice over calculator class for overwritten price
  548.             $QPCalculated $this->qPCalculator->calculate($definition$event->getSalesChannelContext());
  549.             // set new price into line item
  550.             $product->setCalculatedPrice($QPCalculated);
  551.         }
  552.         if(@$StatuCheck && (@$sessionFeedProductId && !in_array($getProductId$sessionFeedProductId))){
  553.             if(@$sessionFeedProductId && sizeof($sessionFeedProductId) > 0){
  554.                 !in_array($getProductId$sessionFeedProductId) ? array_push($sessionFeedProductId$getProductId) : '';
  555.                 $_SESSION['sw-idealo-feed-product-id'] = $sessionFeedProductId;
  556.             } else {
  557.                 $_SESSION['sw-idealo-feed-product-id'] = array($getProductId);
  558.             }
  559.         }
  560.     }
  561. }