custom/plugins/ProcOrderSimulate/src/Subscriber/OrderSimulateSubscriber.php line 229

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace Proc\ProcOrderSimulate\Subscriber;
  4. use Proc\ProcFoundation\Helper\RequestHandler;
  5. use Proc\ProcFoundation\Helper\ErrorHandler;
  6. use Proc\ProcFoundation\Service\ProcFoundationService;
  7. use Proc\ProcOrderSimulate\Helper\BuildRequestHelper;
  8. use Shopware\Core\Checkout\Cart\Cart;
  9. use Shopware\Core\Checkout\Cart\Event\CheckoutOrderPlacedEvent;
  10. use Shopware\Core\Checkout\Cart\LineItem\LineItem;
  11. use Shopware\Core\Checkout\Cart\LineItem\LineItemCollection;
  12. use Shopware\Core\Checkout\Cart\Price\Struct\CartPrice;
  13. use Shopware\Core\Checkout\Cart\Tax\Struct\CalculatedTax;
  14. use Shopware\Core\Checkout\Cart\Tax\Struct\CalculatedTaxCollection;
  15. use Shopware\Core\Checkout\Cart\Price\Struct\CalculatedPrice;
  16. use Shopware\Core\Checkout\Cart\Tax\Struct\TaxRuleCollection;
  17. use Shopware\Core\Checkout\Cart\Tax\Struct\TaxRule;
  18. use Shopware\Core\Checkout\Order\OrderEntity;
  19. use Shopware\Core\Content\MailTemplate\Service\Event\MailBeforeValidateEvent;
  20. use Shopware\Core\Content\Product\ProductEntity;
  21. use Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface;
  22. use Shopware\Core\Framework\DataAbstractionLayer\Exception\InconsistentCriteriaIdsException;
  23. use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
  24. use Shopware\Core\System\SalesChannel\Context\AbstractSalesChannelContextFactory;
  25. use Shopware\Core\System\SalesChannel\Context\SalesChannelContextFactory;
  26. use Shopware\Core\System\SalesChannel\Context\SalesChannelContextService;
  27. use Shopware\Core\System\SalesChannel\SalesChannelContext;
  28. use Shopware\Core\System\SystemConfig\SystemConfigService;
  29. use Shopware\Storefront\Page\Checkout\Cart\CheckoutCartPageLoadedEvent;
  30. use Shopware\Storefront\Page\Checkout\Confirm\CheckoutConfirmPageLoadedEvent;
  31. use Shopware\Storefront\Page\Checkout\Finish\CheckoutFinishPageLoadedEvent;
  32. use Shopware\Storefront\Page\Checkout\Offcanvas\OffcanvasCartPageLoadedEvent;
  33. use Shopware\Storefront\Page\PageLoadedEvent;
  34. use Shopware\Core\Checkout\Cart\Delivery\Struct\Delivery;
  35. use Shopware\Core\Checkout\Cart\Delivery\Struct\DeliveryCollection;
  36. use Shopware\Core\Framework\DataAbstractionLayer\EntityCollection;
  37. use Shopware\Core\Checkout\Cart\AbstractCartPersister;
  38. use Shopware\Storefront\Page\Product\ProductPageLoadedEvent;
  39. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  40. /**
  41.  * Class OrderSimulateSubscriber
  42.  *
  43.  * @package Proc\ProcOrderSimulate\Subscriber
  44.  */
  45. class OrderSimulateSubscriber implements EventSubscriberInterface
  46. {
  47.     private const PLUGINNAME 'ProcOderSimulate';
  48.     private const PATH '/iman/order-simulate';
  49.     public const EUR_THRESHOLD 250;
  50.     public const ZLOTY_THRESHOLD 1062;
  51.     public const POUND_THRESHOLD 210;
  52.     
  53.     /**
  54.      * @var RequestHandler
  55.      */
  56.     private $requestHandler;
  57.     /**
  58.      * @var ErrorHandler
  59.      */
  60.     private $errorHandler;
  61.     /**
  62.      * @var string
  63.      */
  64.     private $host,
  65.         $port,
  66.         $customerNumber;
  67.     private $error null;
  68.     /**
  69.      * @var ProcFoundationService
  70.      */
  71.     private $foundationService;
  72.     /**
  73.      * @var EntityRepositoryInterface
  74.      */
  75.     private $productRepository;
  76.     /**
  77.      * @var CheckoutCartPageLoadedEvent | CheckoutConfirmPageLoadedEvent | CheckoutFinishPageLoadedEvent | ProductPageLoadedEvent | CheckoutOrderPlacedEvent | MailBeforeValidateEvent
  78.      */
  79.     private $event;
  80.     /**
  81.      * @var array
  82.      */
  83.     private $result;
  84.     /**
  85.      * @var CalculatedTaxCollection
  86.      */
  87.     private $calculatedTaxCollection;
  88.     /**
  89.      * @var TaxRuleCollection
  90.      */
  91.     private $taxRuleCollection;
  92.     /**
  93.      * @var LineItemCollection
  94.      */
  95.     private $lineItems;
  96.     /**
  97.      * @var Cart
  98.      */
  99.     private $cart;
  100.     /**
  101.      * @var float
  102.      */
  103.     private $lineItemsCost;
  104.     private $baseObj;
  105.     /**
  106.      * @var array
  107.      */
  108.     private $taxValues = [];
  109.     /**
  110.      * @var AbstractCartPersister
  111.      */
  112.     private $persister;
  113.     /**
  114.      * @var EntityRepositoryInterface
  115.      */
  116.     private $orderRepository;
  117.     /**
  118.      * @var DeliveryCollection
  119.      */
  120.     private $delivery;
  121.     /**
  122.      * @return array
  123.      */
  124.     static function getSubscribedEvents(): array
  125.     {
  126.         return [
  127.             ProductPageLoadedEvent::class         => ['onProductPageLoaded'1],
  128.             CheckoutCartPageLoadedEvent::class    => ['onCartPageLoaded'1],
  129.             CheckoutConfirmPageLoadedEvent::class => ['onCartPageLoaded'1],
  130.             OffcanvasCartPageLoadedEvent::class   => ['onCartPageLoaded'1],
  131.             CheckoutFinishPageLoadedEvent::class  => ['onFinishPageLoaded'1],
  132.             CheckoutOrderPlacedEvent::class       => ['onCheckoutOrderPlaced'1],
  133.             MailBeforeValidateEvent::class        => ['mailBeforeSent'1]
  134.         ];
  135.     }
  136.     /**
  137.      * OrderSimulateSubscriber constructor.
  138.      *
  139.      * @param ProcFoundationService     $foundationService
  140.      * @param RequestHandler            $requestHandler
  141.      * @param ErrorHandler              $errorHandler
  142.      * @param EntityRepositoryInterface $repositoryInterface
  143.      * @param SystemConfigService       $configService
  144.      * @param AbstractCartPersister     $persister
  145.      * @param SalesChannelContextFactory       $salesChannelContextFactory
  146.      */
  147.     public function __construct(
  148.         ProcFoundationService     $foundationService,
  149.         RequestHandler            $requestHandler,
  150.         ErrorHandler              $errorHandler,
  151.         EntityRepositoryInterface $repositoryInterface,
  152.         AbstractCartPersister     $persister,
  153.         EntityRepositoryInterface $orderRepository,
  154.         AbstractSalesChannelContextFactory  $salesChannelContextFactory
  155.     ) {
  156.         $this->foundationService $foundationService;
  157.         $this->requestHandler $requestHandler;
  158.         $this->errorHandler $errorHandler;
  159.         $this->productRepository $repositoryInterface;
  160.         $this->persister $persister;
  161.         $this->orderRepository $orderRepository;
  162.         $this->salesChannelContextFactory $salesChannelContextFactory;
  163.     }
  164.     public function mailBeforeSent(MailBeforeValidateEvent $event)
  165.     {
  166.         $this->event $event;
  167.         $discount null;
  168.         $globalDiscountRate null;
  169.         $globalDiscountValue null;
  170.         $globalTotalAmount null;
  171.         $globalTotalNetAmount null;
  172.         $globalShippingAmount=null;
  173.         if (array_key_exists('priceInformations'$this->event->getContext()->getExtensions())) {
  174.             $discount $this->event->getContext()->getExtensions()['priceInformations']['discountSum'];
  175.             $globalDiscountValue $this->event->getContext()->getExtensions()['priceInformations']['globalDiscountValue'];
  176.             $globalDiscountRate $this->event->getContext()->getExtensions()['priceInformations']['globalDiscountRate'];
  177.         }
  178.         if (array_key_exists('priceTotalInformations'$this->event->getContext()->getExtensions())) {
  179.             $globalTotalAmount $this->event->getContext()->getExtensions()['priceTotalInformations']['globalTotalAmount'];
  180.             $globalTotalNetAmount $this->event->getContext()->getExtensions()['priceTotalInformations']['globalTotalNetAmount'];
  181.             $globalShippingAmount $this->event->getContext()->getExtensions()['priceTotalInformations']['globalShippingAmount'];
  182.             
  183.         }
  184.         $this->event->addTemplateData('discount'$discount);
  185.         $this->event->addTemplateData('globalDiscountValue'$globalDiscountValue);
  186.         $this->event->addTemplateData('globalDiscountRate'$globalDiscountRate);
  187.         $this->event->addTemplateData('globalTotalAmount'$globalTotalAmount);
  188.         $this->event->addTemplateData('globalTotalNetAmount'$globalTotalNetAmount);
  189.         $this->event->addTemplateData('globalShippingAmount'$globalShippingAmount);
  190.     }
  191.     /**
  192.      * @param PageLoadedEvent $event
  193.      * @throws \Exception
  194.      */
  195.     public function onProductPageLoaded(ProductPageLoadedEvent $event): void
  196.     {
  197.         $this->event $event;
  198.         /**
  199.          * Prüfung ob Benutzer angemeldet ist, sonst keine Live-Abfrage.
  200.          */
  201.         if (!($this->customerNumber $this->foundationService->checkLogin($this->event->getSalesChannelContext(), self::PLUGINNAME)))
  202.             return;
  203.         /**
  204.          * Configeinstellungen prüfen und setzen.
  205.          */
  206.         if (!$this->checkConfig())
  207.             return;
  208.         /**
  209.          * @var array $articles
  210.          */
  211.         $product $this->event->getPage()->getProduct();
  212.         $articles $this->articleData($product);
  213.         $this->result $this->getArticleInfo($articles);
  214.         if (isset($this->result['shipping-costs']) && isset($this->result['shipping-costs']['free-shipping-threshold'])) {
  215.             $freeShippingThreshold = (int) $this->result['shipping-costs']['free-shipping-threshold'];
  216.         } else {
  217.             $freeShippingThreshold $this->calculateShippingThreshold();
  218.         }
  219.         $extension = [
  220.             'freeShippingThreshold' => $freeShippingThreshold,
  221.         ];
  222.         $this->event->getSalesChannelContext()->getShippingMethod()->addArrayExtension('deliveryInformations'$extension);
  223.         $this->error $this->errorHandler->error($this->errorHandler::UNKNOWN_REQUESTget_class($this), 'Result: ' print_r($this->resulttrue));
  224.         $this->errorHandler->writeErrorLog($this->error);
  225.     }
  226.     private function articleData($product): array
  227.     {
  228.         $articleData = [];
  229.         $customFields $product->getCustomFields();
  230.         $article['number'] = $product->getProductNumber();
  231.         $article['quantity'] = $product->getCalculatedPrice()->getQuantity();
  232.         $article['division'] = $customFields['custom_salesdata_division'];
  233.         $article['quantity-unit'] = $product->getPackUnit();
  234.         $articleData[] = $article;
  235.         return $articleData;
  236.     }
  237.     public function onCartPageLoaded(PageLoadedEvent $event): void
  238.     {
  239.         $this->event $event;
  240.         /**
  241.          * Prüfung ob Benutzer angemeldet ist, sonst keine Live-Abfrage.
  242.          */
  243.         if (!($this->customerNumber $this->foundationService->checkLogin($this->event->getSalesChannelContext(), self::PLUGINNAME)))
  244.             return;
  245.         /**
  246.          * Configeinstellungen prüfen und setzen.
  247.          */
  248.         if (!$this->checkConfig())
  249.             return;
  250.         $this->cart $this->event->getPage()->getCart();
  251.         $this->lineItems $this->cart->getLineItems()->filterType(LineItem::PRODUCT_LINE_ITEM_TYPE);
  252.         if ($this->lineItems->count() < 1)
  253.             return;
  254.         /**
  255.          * @var array $articles
  256.          */
  257.         $articles $this->lineItemsToArticles();
  258.         $this->result $this->getArticleInfo($articles);
  259.         $this->error $this->errorHandler->error($this->errorHandler::UNKNOWN_REQUESTget_class($this), 'Result: ' print_r($this->resulttrue));
  260.         $this->errorHandler->writeErrorLog($this->error);
  261.         if (array_key_exists('head'$this->result) && $this->result['head']['status'] == 'NOK') {
  262.             return;
  263.         }
  264.         $this->taxRuleCollection = new TaxRuleCollection();
  265.         $this->calculatedTaxCollection = new CalculatedTaxCollection();
  266.         $sum $this->lineItemsCost $this->calculateLineItems();
  267.         $this->setDiscount($sum);
  268.         /**
  269.          * @var CalculatedTax $shippingCosts
  270.          */
  271.         $this->cart->setPrice($this->calculateNewCartPrice());
  272.         if (isset($this->result['shipping-costs']) && isset($this->result['shipping-costs']['free-shipping-threshold'])) {
  273.             //            $shippingCosts = $this->result['shipping-costs']['condition-value'];
  274.             $freeShippingThreshold = (int) $this->result['shipping-costs']['free-shipping-threshold'];
  275.         } else {
  276.             $freeShippingThreshold $this->calculateShippingThreshold();
  277.         }
  278.         $extension = [
  279.             'freeShippingThreshold' => $freeShippingThreshold,
  280.         ];
  281.         $this->event->getPage()->getCart()->getDeliveries()->addArrayExtension('deliveryInformations'$extension);
  282.         $this->persister->save($this->cart$this->event->getSalesChannelContext());
  283.     }
  284.     public function onCheckoutOrderPlaced(CheckoutOrderPlacedEvent $event)
  285.     {
  286.         $this->event $event;
  287.         $this->order $this->event->getOrder();
  288.         /**
  289.          * Configeinstellungen prüfen und setzen.
  290.          */
  291.         if (!$this->checkConfig())
  292.             return;
  293.         $this->lineItems $this->event->getOrder()->getLineItems();
  294.         if ($this->lineItems->count() < 1)
  295.             return;
  296.         /**
  297.          * @var array $articles
  298.          */
  299.         $articles $this->lineItemsToArticles();
  300.         $this->result $this->getArticleInfo($articles);
  301.         $this->error $this->errorHandler->error($this->errorHandler::UNKNOWN_REQUESTget_class($this), 'Result: ' print_r($this->resulttrue));
  302.         $this->errorHandler->writeErrorLog($this->error);
  303.         if (array_key_exists('head'$this->result) && $this->result['head']['status'] == 'NOK') {
  304.             return;
  305.         }
  306.         $this->taxRuleCollection = new TaxRuleCollection();
  307.         $this->calculatedTaxCollection = new CalculatedTaxCollection();
  308.         $sum $this->lineItemsCost $this->calculateLineItems();
  309.         $this->setDiscount($sum);
  310.         $this->calculateNewTotals();
  311.     }
  312.     /**
  313.      * @param CheckoutFinishPageLoadedEvent $event
  314.      * @throws InconsistentCriteriaIdsException
  315.      */
  316.     public function onFinishPageLoaded(CheckoutFinishPageLoadedEvent $event)
  317.     {
  318.         $this->event $event;
  319.         /**
  320.          * Prüfung ob Benutzer angemeldet ist, sonst keine Live-Abfrage.
  321.          */
  322.         if (!($this->customerNumber $this->foundationService->checkLogin($this->event->getSalesChannelContext(), self::PLUGINNAME)))
  323.             // $this->errorHandler->writeErrorLog(['foundationService']);
  324.             return;
  325.         /**
  326.          * Configeinstellungen prüfen und setzen.
  327.          */
  328.         if (!$this->checkConfig())
  329.             // $this->errorHandler->writeErrorLog(['checkConfig']);
  330.             return;
  331.         $this->lineItems $this->event->getPage()->getOrder()->getLineItems();
  332.         /**
  333.          * @var array $articles
  334.          */
  335.         $articles $this->lineItemsToArticles();
  336.         if ($articles === false)
  337.             return;
  338.         $this->result $this->getArticleInfo($articles);
  339.         if ($this->result['head']['status'] == 'NOK') {
  340.             // $this->errorHandler->writeErrorLog(['status']);
  341.             return;
  342.         }
  343.         $freeShippingThreshold $this->calculateShippingThreshold();
  344.         $shippingCosts 0;
  345.         if (array_key_exists('free-shipping-threshold'$this->result['shipping-costs']))
  346.             $freeShippingThreshold = (int) $this->result['shipping-costs']['free-shipping-threshold'];
  347.         if (array_key_exists('pickup-only'$this->result['shipping-costs'])) {
  348.             $pickupOnly = (bool) $this->result['shipping-costs']['pickup-only'];
  349.         } else {
  350.             $pickupOnly false;
  351.         }
  352.         $this->taxRuleCollection = new TaxRuleCollection();
  353.         $this->calculatedTaxCollection = new CalculatedTaxCollection();
  354.         $sum $this->lineItemsCost $this->calculateLineItems();
  355.         $this->setDiscount($sum);
  356.         /**
  357.          * @var OrderEntity $order
  358.          */
  359.         $order $this->event->getPage()->getOrder();
  360.         $order->setPrice($this->calculateNewCartPrice());
  361.         $netPrice $order->getPrice()->getPositionPrice();
  362.         if (array_key_exists('condition-value'$this->result['shipping-costs']) && ($netPrice $freeShippingThreshold)) {
  363.             $shippingCosts = (float) $this->result['shipping-costs']['condition-value'];
  364.         }
  365.         $this->saveOrder($order->getId(), $order->getPrice(), $pickupOnly$freeShippingThreshold$shippingCosts$this->result['shipping-costs']);
  366.     }
  367.     /**
  368.      * @param string    $orderId
  369.      * @param CartPrice $price
  370.      * @return void
  371.      */
  372.     private function saveOrder(string $orderIdCartPrice $price$pickupOnly$freeShippingThreshold$shippingCosts$tempConditionTree)
  373.     {
  374.         $tax = (float) $tempConditionTree['condition-value'];
  375.         $taxRate = (float) $tempConditionTree['condition-rate'];
  376.         $calTaxCollection = new CalculatedTaxCollection();
  377.         $taxRuleCollection = new TaxRuleCollection();
  378.         $calTaxCollection->add(new CalculatedTax($tax$taxRate$price->getTotalPrice()));
  379.         $taxRuleCollection->add(new TaxRule($taxRate));
  380.         foreach ($this->lineItems as $lineItem) {
  381.             $lineItems[] = [
  382.                 "id" => $lineItem->getId(),
  383.                 "identifier" => $lineItem->getIdentifier(),
  384.                 "totalPrice" => $lineItem->getPrice()->getTotalPrice(),
  385.                 "unitPrice" => $lineItem->getPrice()->getUnitPrice(),
  386.                 "label" => $lineItem->getLabel(),
  387.                 "price" => $lineItem->getPrice(),
  388.                 "quantity" => $lineItem->getQuantity(),
  389.             ];
  390.         }
  391.         $shippingCostsArray = [
  392.             'taxRules' => $taxRuleCollection,
  393.             'calculatedTaxes' => $calTaxCollection,
  394.             'quantity' => 1,
  395.             'totalPrice' => $shippingCosts,
  396.             'unitPrice' => $shippingCosts
  397.         ];
  398.         $orderData = [
  399.             'id'           => $orderId,
  400.             'price'        => $price,
  401.             'shippingCosts' =>  $shippingCostsArray,
  402.             'lineItems' => $lineItems,
  403.             'deliveries' => [
  404.                 [
  405.                     'id' => $this->delivery->getId(),
  406.                     'shippingCosts' => $shippingCostsArray,
  407.                     'shippingDateLatest' => $this->delivery->getShippingDateLatest(),
  408.                     'shippingDateEarliest' => $this->delivery->getShippingDateEarliest(),
  409.                     'shippingOrderAddressId' => $this->delivery->getShippingOrderAddressId(),
  410.                     'shippingMethodId' => $this->delivery->getShippingMethodId(),
  411.                     'trackingCodes' => $this->delivery->getTrackingCodes()
  412.                 ]
  413.             ],
  414.             'customFields' => [
  415.                 'custom_shippingCosts_pickupOnly'            => (bool) $pickupOnly,
  416.                 'custom_shippingCosts_freeShippingThreshold' => (int) $freeShippingThreshold
  417.             ]
  418.         ];
  419.         $this->errorHandler->writeErrorLog($orderData);
  420.         $this->orderRepository->update([$orderData], $this->event->getContext());
  421.     }
  422.     /**
  423.      * @param array  $articles
  424.      * @param int    $shopInstance
  425.      * @param string $salesOrganization
  426.      * @param string $distributionChannel
  427.      * @param string $division
  428.      * @param string $currency
  429.      * @param string $language
  430.      * @return array
  431.      */
  432.     public function getArticleInfo(
  433.         array  $articles,
  434.         int    $shopInstance 1,
  435.         string $salesOrganization 'DE01',
  436.         string $distributionChannel '01',
  437.         string $division '00',
  438.         string $language 'DE'
  439.     ): array {
  440.         if (!$this->customerNumber && $this->order)
  441.             $this->customerNumber $this->order->getOrderCustomer()->getCustomer()->getCustomFields()['custom_sap_number'];
  442.         $params = [
  443.             'shop-instance' => $shopInstance,
  444.             'language'      => $language,
  445.             'customer'      => $this->customerNumber,
  446.             'customer-we'   => $this->customerNumber,
  447.             'order-type'    => 'ZDSA',
  448.             'currency'      => $this->getCurrencyISO(),
  449.             'delivery-date' => date('Y-m-d'),
  450.         ];
  451.         $buildRequestHelper = new BuildRequestHelper($params$articles$this->errorHandler);
  452.         /**
  453.          * @var string $request
  454.          */
  455.         $request $this->requestHandler->buildRequest($buildRequestHelperself::PLUGINNAME);
  456.         if ($request !== '') {
  457.             /**
  458.              * @var string $result
  459.              */
  460.             $result $this->requestHandler->sendRequest($this->host$this->portself::PATH$request);
  461.         } else {
  462.             $this->error $this->errorHandler->error($this->errorHandler::UNKNOWN_REQUESTget_class($this), 'Fehler im Aufbau des Request');
  463.             $this->errorHandler->writeErrorLog($this->error);
  464.             return [];
  465.         }
  466.         /**
  467.          * @var array $resultArray
  468.          */
  469.         return $this->requestHandler->parseResult($result);
  470.     }
  471.     /**
  472.      * @return bool
  473.      */
  474.     private function checkConfig(): bool
  475.     {
  476.         if ($this->foundationService->getConfigStatus()) {
  477.             $this->host $this->foundationService->getHost();
  478.             $this->port $this->foundationService->getPort();
  479.             return true;
  480.         }
  481.         $this->error $this->errorHandler->error($this->errorHandler::CONFIG_NOT_VALIDget_class($this), 'Konnte die Konfiguration nicht ermitteln');
  482.         $this->errorHandler->writeErrorLog($this->error);
  483.         return false;
  484.     }
  485.     /**
  486.      * @return array
  487.      */
  488.     private function lineItemsToArticles(): array
  489.     {
  490.         /**
  491.          * @var array $articles
  492.          */
  493.         $articles = [];
  494.         /**
  495.          * @todo Die position-id noch richtig machen
  496.          */
  497.         $count 0;
  498.         foreach ($this->lineItems as $lineItem) {
  499.             $count++;
  500.             $product $this->getProduct($lineItem->getReferencedId());
  501.             $customFields $product->getCustomFields();
  502.             $article['position'] = $count;
  503.             $article['number'] = $product->getProductNumber();
  504.             $article['quantity'] = $lineItem->getPrice()->getQuantity();
  505.             $article['division'] = $customFields['custom_salesdata_division'];
  506.             $article['quantity-unit'] = $product->getPackUnit();
  507.             $articles[] = $article;
  508.         }
  509.         return $articles;
  510.     }
  511.     /**
  512.      * @param string $productID
  513.      * @return ProductEntity
  514.      */
  515.     public function getProduct(string $productID, array $associations null): ProductEntity
  516.     {
  517.         /**
  518.          * @var Criteria $criteria
  519.          */
  520.         $criteria = new Criteria([$productID]);
  521.         if ($associations !== null) {
  522.             foreach ($associations as $association) {
  523.                 $criteria->addAssociation($association);
  524.             }
  525.         }
  526.         /**
  527.          * @var EntityCollection $products
  528.          */
  529.         $products $this->productRepository->search($criteria\Shopware\Core\Framework\Context::createDefaultContext());
  530.         /**
  531.          * @var array $productList
  532.          */
  533.         $productList $products->getElements();
  534.         /**
  535.          * @var ProductEntity $product
  536.          */
  537.         $product $productList[$productID];
  538.         return $product;
  539.     }
  540.     function calculateLineItems(): float
  541.     {
  542.         // $this->result = Ergebnis des Requests
  543.         $count 0;
  544.         $sum 0.0;
  545.         foreach ($this->lineItems as $lineItem) {
  546.             if (array_key_exists(0$this->result['articles']['article'])) {
  547.                 $articleArray $this->result['articles']['article'][$count];
  548.             } else {
  549.                 $articleArray $this->result['articles']['article'];
  550.             }
  551.             $tempConditionTree null;
  552.             if (array_key_exists(0$articleArray['conditions']['condition'])) {
  553.                 if ($articleArray['conditions']['condition'][0]['condition-type'] === 'MWST') {
  554.                     $tempConditionTree $articleArray['conditions']['condition'][0];
  555.                 } else {
  556.                     $tempConditionTree $articleArray['conditions']['condition'][1];
  557.                 }
  558.             } else {
  559.                 $tempConditionTree $articleArray['conditions']['condition'];
  560.             }
  561.             $tax $price = (float) $tempConditionTree['condition-value'];
  562.             $taxRate = (float) $tempConditionTree['condition-rate'];
  563.             $calTaxCollection = new CalculatedTaxCollection();
  564.             $taxRuleCollection = new TaxRuleCollection();
  565.             $calTaxCollection->add(new CalculatedTax($tax$taxRate$price));
  566.             $taxRuleCollection->add(new TaxRule($taxRate));
  567.             if (!array_key_exists((string) $taxRate$this->taxValues)) {
  568.                 $this->taxValues[(string) $taxRate] = 0.0;
  569.             }
  570.             $this->taxValues[(string) $taxRate] += $price;
  571.             $this->taxRuleCollection->add(new TaxRule($taxRate));
  572.             $newCalculatedPrice = new CalculatedPrice(
  573.                 (float) $articleArray['net-position-value'],
  574.                 (float) $articleArray['net-position-sum'],
  575.                 $calTaxCollection,
  576.                 $taxRuleCollection,
  577.                 (int) $articleArray['quantity']
  578.             );
  579.             $sum += (float) $articleArray['net-position-sum'];
  580.             $lineItem->setPrice($newCalculatedPrice);
  581.             $count++;
  582.         }
  583.         return $sum;
  584.     }
  585.     function calculateNewTotals(){
  586.        
  587.         /**
  588.          * @var CalculatedPrice
  589.          */
  590.         $pickup false;
  591.         $addPrice=0;
  592.         if ($this->result['shipping-costs']) {
  593.             $addPrice = (float) $this->result['shipping-costs']['condition-value'];
  594.             if (isset($this->result['shipping-costs']['free-shipping-threshold'])) {
  595.                 $freeShippingThreshold = (int) $this->result['shipping-costs']['free-shipping-threshold'];
  596.             } else {
  597.                 $freeShippingThreshold $this->calculateShippingThreshold();
  598.             }
  599.             if ($this->lineItemsCost >= $freeShippingThreshold || $pickup)
  600.                 $addPrice 0.0;
  601.         }
  602.         /**
  603.          * @var CalculatedPrice
  604.          */
  605.         $newShippingPrice $this->getNewShippingPrice($addPrice);
  606.         $taxSum 0.0;
  607.         foreach ($this->taxValues as $key => $value) {
  608.             $this->calculatedTaxCollection->add(new CalculatedTax($value, (float) $key$value));
  609.             $taxSum += $value;
  610.         }
  611.         $globalTotalAmount $this->lineItemsCost $newShippingPrice->getTotalPrice() + $taxSum;
  612.         $globalTotalNetAmount $this->lineItemsCost $newShippingPrice->getTotalPrice();
  613.         $extension = array();
  614.         $extension['globalTotalAmount'] = (float)$globalTotalAmount;
  615.         $extension['globalTotalNetAmount'] = (float)$globalTotalNetAmount;
  616.         $extension['globalShippingAmount'] = (float)$addPrice;
  617.         $this->event->getContext()->addArrayExtension('priceTotalInformations'$extension);
  618.         
  619.     }
  620.     function calculateNewCartPrice()
  621.     {
  622.         if ($this->event instanceof CheckoutFinishPageLoadedEvent) {
  623.             $this->baseObj $this->event->getPage()->getOrder();
  624.         } else {
  625.             $this->baseObj $this->event->getPage()->getCart();
  626.         }
  627.         /**
  628.          * @var CartPrice
  629.          */
  630.         $cartPrice $this->baseObj->getPrice();
  631.         /**
  632.          * @var DeliveryCollection
  633.          */
  634.         $deliveryCosts $this->baseObj->getDeliveries();
  635.         /**
  636.          * @var Delivery
  637.          */
  638.         $delivery $deliveryCosts->first();
  639.         /**
  640.          * @var CalculatedPrice
  641.          */
  642.         $customfields $this->event->getSalesChannelContext()->getCustomer()->getCustomFields();
  643.         $pickup key_exists('custom_sap_pickup'$customfields) ? $customfields['custom_sap_pickup'] : false;
  644.         if ($this->result['shipping-costs']) {
  645.             $addPrice = (float) $this->result['shipping-costs']['condition-value'];
  646.             if (isset($this->result['shipping-costs']['free-shipping-threshold'])) {
  647.                 $freeShippingThreshold = (int) $this->result['shipping-costs']['free-shipping-threshold'];
  648.             } else {
  649.                 $freeShippingThreshold $this->calculateShippingThreshold();
  650.             }
  651.             if ($this->lineItemsCost >= $freeShippingThreshold || $pickup)
  652.                 $addPrice 0.0;
  653.         }
  654.         /**
  655.          * @var CalculatedPrice
  656.          */
  657.         $newShippingPrice $this->getNewShippingPrice($addPrice);
  658.         $delivery->setShippingCosts($newShippingPrice);
  659.         $this->delivery $delivery;
  660.         $taxSum 0.0;
  661.         foreach ($this->taxValues as $key => $value) {
  662.             $this->calculatedTaxCollection->add(new CalculatedTax($value, (float) $key$value));
  663.             $taxSum += $value;
  664.         }
  665.         $globalTotalAmount $this->lineItemsCost $newShippingPrice->getTotalPrice() + $taxSum;
  666.         $globalTotalNetAmount $this->lineItemsCost $newShippingPrice->getTotalPrice();
  667.         $newCartPrice = new CartPrice(
  668.             $globalTotalNetAmount,
  669.             $globalTotalAmount,
  670.             $this->lineItemsCost,
  671.             $this->calculatedTaxCollection,
  672.             $this->taxRuleCollection,
  673.             $cartPrice->getTaxStatus()
  674.         );
  675.         return $newCartPrice;
  676.     }
  677.     private function getNewShippingPrice(float $addPrice): CalculatedPrice
  678.     {
  679.         $unitPrice $totalPrice $addPrice;
  680.         return new CalculatedPrice($unitPrice$totalPrice, new CalculatedTaxCollection(), new TaxRuleCollection());
  681.     }
  682.     private function setDiscount($sum)
  683.     {
  684.         /**
  685.          * @var int $count
  686.          */
  687.         $count 0;
  688.         $discountSum 0;
  689.         $globalDiscountValueSum 0;
  690.         $globalDiscountRate 0;
  691.         $discountRate 0;
  692.         foreach ($this->lineItems as $lineItem) {
  693.             if (count($this->lineItems) > && array_key_exists($count$this->result['articles']['article'])) {
  694.                 $articleArray $this->result['articles']['article'][$count];
  695.             } else {
  696.                 $articleArray $this->result['articles']['article'];
  697.             }
  698.             if (array_key_exists('condition-type'$condition $articleArray['conditions']['condition'])) {
  699.                 if ($condition['condition-type'] == "ZRN1") {
  700.                     $discountValue $condition['condition-value'];
  701.                     $discountRate $condition['condition-rate'];
  702.                     $extension = [
  703.                         'discountValue' => (float) $discountValue,
  704.                         'discountRate' => round((float) $discountRate2)
  705.                     ];
  706.                     $lineItem->addArrayExtension('lineItemDiscount'$extension);
  707.                     $discountSum += $discountValue;
  708.                 } elseif ($condition['condition-type'] == "ZECO") {
  709.                     $globalDiscountValue $condition['condition-value'];
  710.                     $globalDiscountValueSum += $globalDiscountValue;
  711.                     $globalDiscountRate $condition['condition-rate'];
  712.                     $extension = [
  713.                         'globalDiscountValue' => (float) $globalDiscountValue,
  714.                         'globalDiscountRate' => round((float) $globalDiscountRate2)
  715.                     ];
  716.                     $lineItem->addArrayExtension('lineItemGlobalDiscount'$extension);
  717.                 }
  718.             } else {
  719.                 foreach ($articleArray['conditions']['condition'] as $condition) {
  720.                     if ($condition['condition-type'] == "ZRN1") {
  721.                         $discountValue $condition['condition-value'];
  722.                         $discountRate $condition['condition-rate'];
  723.                         $extension = [
  724.                             'discountValue' => (float) $discountValue,
  725.                             'discountRate' => round((float) $discountRate2)
  726.                         ];
  727.                         $lineItem->addArrayExtension('lineItemDiscount'$extension);
  728.                         $discountSum += $discountValue;
  729.                     }
  730.                     if ($condition['condition-type'] == "ZECO") {
  731.                         $globalDiscountValue $condition['condition-value'];
  732.                         $globalDiscountValueSum += $globalDiscountValue;
  733.                         $globalDiscountRate $condition['condition-rate'];
  734.                         $extension = [
  735.                             'globalDiscountValue' => (float) $globalDiscountValue,
  736.                             'globalDiscountRate' => round((float) $globalDiscountRate2)
  737.                         ];
  738.                         $lineItem->addArrayExtension('lineItemGlobalDiscount'$extension);
  739.                     }
  740.                 }
  741.             }
  742.             $count++;
  743.         }
  744.         $extension = [
  745.             'discountRate' =>  round((float) $discountRate2),
  746.             'discountSum'  => $discountSum,
  747.             'globalDiscountValue' => (float) $globalDiscountValueSum,
  748.             'globalDiscountRate' => round((float) $globalDiscountRate2),
  749.         ];
  750.         $this->event->getContext()->addArrayExtension('priceInformations'$extension);
  751.     }
  752.     /**
  753.      * fts - Retrieve currency iso code from saleschannel context
  754.      * @return string
  755.      */
  756.     private function getCurrencyISO(): string
  757.     {
  758.         return $this->getSalesChannelContext?->getCurrency()->getIsoCode() ?? "EUR";
  759.     }
  760.     /**
  761.      * If the current currency is not EUR, then the default threshold (250€)
  762.      * will be converted to the appropriate currency using the currency factor.
  763.      * @return int
  764.      */
  765.     private function calculateShippingThreshold(): int
  766.     {
  767.         if ($this->getSalesChannelContext()->getCurrency()->getIsoCode() === "PLN") {
  768.             return self::ZLOTY_THRESHOLD;
  769.         } else if ($this->getSalesChannelContext()->getCurrency()->getIsoCode() === "GBP") {
  770.             return self::POUND_THRESHOLD;
  771.         } else {
  772.             return self::EUR_THRESHOLD;
  773.         }
  774.     }
  775.     private function getSalesChannelContext(): SalesChannelContext {
  776.         if ($this->event instanceof CheckoutOrderPlacedEvent) {
  777.             return $this->salesChannelContextFactory->create(""$this->event->getSalesChannelId());
  778.         } else {
  779.             return $this->event->getSalesChannelContext();
  780.         }
  781.     }
  782. }