custom/plugins/AbmAdjustments/src/Core/Checkout/Cart/OverwritePriceCollector.php line 121

Open in your IDE?
  1. <?php declare(strict_types=1);
  2. namespace AbmAdjustments\Core\Checkout\Cart;
  3. use Psr\Cache\InvalidArgumentException;
  4. use Shopware\Core\System\SystemConfig\SystemConfigService;
  5. use Symfony\Component\Cache\Adapter\FilesystemAdapter;
  6. use Symfony\Contracts\Cache\CacheInterface;
  7. use Shopware\Core\Checkout\Cart\Cart;
  8. use Shopware\Core\Checkout\Cart\CartBehavior;
  9. use Shopware\Core\Checkout\Cart\CartDataCollectorInterface;
  10. use Shopware\Core\Checkout\Cart\CartProcessorInterface;
  11. use Shopware\Core\Checkout\Cart\LineItem\CartDataCollection;
  12. use Shopware\Core\Checkout\Cart\LineItem\LineItem;
  13. use Shopware\Core\Checkout\Cart\Price\QuantityPriceCalculator;
  14. use Shopware\Core\Checkout\Cart\Price\Struct\QuantityPriceDefinition;
  15. use Shopware\Core\Checkout\Cart\Tax\Struct\TaxRule;
  16. use Shopware\Core\Checkout\Cart\Tax\Struct\TaxRuleCollection;
  17. use Shopware\Core\Framework\Context;
  18. use Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface;
  19. use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
  20. use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter;
  21. use Shopware\Core\System\SalesChannel\SalesChannelContext;
  22. use Symfony\Component\DependencyInjection\ContainerInterface;
  23. use Symfony\Component\HttpFoundation\RequestStack;
  24. class OverwritePriceCollector implements CartDataCollectorInterfaceCartProcessorInterface
  25. {
  26.     const ALL_ZERO_TAX_GROSS_NET_STG 'all-zero-tax-gross-net-stg';
  27.     const ALL_ZERO_TAX_GROSS_NET_LIVE 'all-zero-tax-gross-net-live';
  28.     private QuantityPriceCalculator $calculator;
  29.     /**
  30.      * @var EntityRepositoryInterface
  31.      */
  32.     private $productRepository;
  33.     /**
  34.      * @var RequestStack
  35.      */
  36.     private $requestStack;
  37.     private ContainerInterface $container;
  38.     private $systemConfigService;
  39.     public function __construct(
  40.         QuantityPriceCalculator   $calculator,
  41.         EntityRepositoryInterface $productRepository,
  42.         RequestStack              $requestStack,
  43.         ContainerInterface        $container,
  44.         SystemConfigService       $systemConfigService
  45.     )
  46.     {
  47.         $this->calculator $calculator;
  48.         $this->productRepository $productRepository;
  49.         $this->requestStack $requestStack;
  50.         $this->container $container;
  51.         $this->systemConfigService $systemConfigService;
  52.     }
  53.     public function collect(CartDataCollection $dataCart $originalSalesChannelContext $contextCartBehavior $behavior): void
  54.     {
  55.         // get all product ids of current cart
  56.         $productIds $original->getLineItems()->filterType(LineItem::PRODUCT_LINE_ITEM_TYPE)->getReferenceIds();
  57.         // remove all product ids which are already fetched from the database
  58.         $filtered $this->filterAlreadyFetchedPrices($productIds$data);
  59.         // Skip execution if there are no prices to be saved
  60. //        if (empty($filtered) || $this->systemConfigService->get(self::FORCE_BRUT_TAX_SETTING)) {
  61.         if (empty($filtered)) {
  62.             return;
  63.         }
  64.         foreach ($filtered as $id) {
  65.             $key $this->buildKey($id);
  66.             $criteria = (new Criteria())->addAssociation('prices');
  67.             $criteria->addFilter(new EqualsFilter('id'$id));
  68.             /*  @var  Shopware\Core\Content\Product\ProductEntity $productEntity */
  69.             $productEntity $this->productRepository->search($criteriaContext::createDefaultContext())->first();
  70.             $bTax $productEntity->getTranslated()['customFields']['taxrate'] ?? 1;
  71.             if (empty($bTax)) {
  72.                 if (!empty($productEntity->getPrices()->first())) {
  73.                     $newPrice = (float)$productEntity->getPrices()->first()->getPrice()->first()->getNet() ?? null;
  74.                 }
  75.             }
  76.             // we have to set a value for each product id to prevent duplicate queries in next calculation
  77.             if (!empty($newPrice)) {
  78.                 $data->set($key$newPrice);
  79.             }
  80.         }
  81.     }
  82.     private function filterAlreadyFetchedPrices(array $productIdsCartDataCollection $data): array
  83.     {
  84.         $filtered = [];
  85.         foreach ($productIds as $id) {
  86.             $key $this->buildKey($id);
  87.             // already fetched from database?
  88.             if ($data->has($key)) {
  89.                 continue;
  90.             }
  91.             $filtered[] = $id;
  92.         }
  93.         return $filtered;
  94.     }
  95.     private function buildKey(string $id): string
  96.     {
  97.         return 'price-overwrite-' $id;
  98.     }
  99.     public function process(CartDataCollection $dataCart $originalCart $toCalculateSalesChannelContext $contextCartBehavior $behavior): void
  100.     {
  101.         $oCurrentSession $this->requestStack->getCurrentRequest()->getSession();
  102.         $oCurrentSession->set('isZeroTaxCart'false);
  103.         // get all product line items
  104.         $products $original->getLineItems()->filterType(LineItem::PRODUCT_LINE_ITEM_TYPE);
  105.         $cache = new FilesystemAdapter();
  106.         $sRoute $this->requestStack->getCurrentRequest()->attributes->get('_route');
  107.         if (empty($original->getLineItems()->count()) || $sRoute == 'frontend.account.register.save') {
  108.             $oCurrentSession->remove('zero_tax_consent');
  109.         }
  110.         $i 0;
  111.         $bFirstCheckoutEntry false;
  112.         if($sRoute == 'frontend.checkout.confirm.page') {
  113.             if(!$oCurrentSession->get('first_checkout_entry')) {
  114.                 $oCurrentSession->set('first_checkout_entry'true);
  115.                 $bFirstCheckoutEntry true;
  116.             }
  117.         }
  118.         $now = new \DateTime('now', new \DateTimeZone('Europe/Berlin'));
  119.         $now->setTime(000);
  120.         foreach ($products as $product) {
  121.             if (true) {
  122.                 $releaseDateString $product->getPayloadValue('releaseDate');
  123.                 if (!is_null($releaseDateString)) {
  124.                     $releaseDate = new \DateTime($releaseDateString, new \DateTimeZone('Europe/Berlin'));
  125.                     $releaseDate->setTime(000);
  126.                     if ($releaseDate $now) {
  127.                         $interval $now->diff($releaseDate);
  128.                         $daysDifference $interval->days;
  129.                         $earliest $product->getDeliveryInformation()->getDeliveryTime()->getMin() + $daysDifference;
  130.                         $latest $product->getDeliveryInformation()->getDeliveryTime()->getMax() + $daysDifference;
  131.                         $product->getDeliveryInformation()->getDeliveryTime()->setMin($earliest);
  132.                         $product->getDeliveryInformation()->getDeliveryTime()->setMax($latest);
  133.                     }
  134.                 }
  135.             }
  136.             $newPrice null;
  137.             $key $this->buildKey($product->getReferencedId());
  138.             if (!$data->has($key) || $data->get($key) === null) {
  139.                 continue;
  140.             }
  141.             $criteria = new Criteria([$product->getReferencedId()]);
  142.             $products $this->productRepository->search($criteriaContext::createDefaultContext());
  143.             $productEntity $products->first();
  144.             $oTaxRepository $this->container->get('tax.repository');
  145.             /* To remove */
  146.             $taxRate = (!empty($oCurrentSession->get('zero_tax_consent')) || $bFirstCheckoutEntry) ? 0.0 19;
  147.             if($bFirstCheckoutEntry || $oCurrentSession->get('zero_tax_waiver')) {
  148.                 $taxRate 19;
  149.             }
  150.             /* To add */
  151. //            $taxRate = (empty($oCurrentSession->get('zero_tax_consent')) || $bFirstCheckoutEntry) && false ? 19 : 0.0;
  152. //            $sTaxMode = (
  153. //                false &&
  154. //                (!$oCurrentSession->get('zero_tax_consent') && !$bFirstCheckoutEntry) ||
  155. //                $bFirstCheckoutEntry
  156. //            ) ? 'gross' : 'net';
  157.             /* to remove */
  158.             $sTaxMode = !$oCurrentSession->get('zero_tax_consent') && !$bFirstCheckoutEntry 'gross' 'net';
  159.             if($bFirstCheckoutEntry  || $oCurrentSession->get('zero_tax_waiver')) {
  160.                 $sTaxMode 'gross';
  161.             }
  162.             if(empty($oCurrentSession->get('zero_tax_consent')) && empty($oCurrentSession->get('zero_tax_waiver'))) {
  163.                 $sTaxMode 'net';
  164.                 $taxRate 0.0;
  165.             }
  166.             $criteria = new Criteria();
  167.             $criteria->addFilter(new EqualsFilter('taxRate'$taxRate));
  168.             $taxes $oTaxRepository->search($criteriaContext::createDefaultContext());
  169.             $tax $taxes->first();;
  170.             $productEntity->setTax($tax);
  171.             $taxRule = new TaxRule(
  172.                 $taxRate,
  173.                 100
  174.             );
  175.             $aLinePayload $original->getLineItems()->getPayload()[$product->getReferencedId()];
  176.             $aLinePayload['taxId'] = $tax->getId();
  177.             $product->setPayload($aLinePayload);
  178.             $criteria = (new Criteria())->addAssociation('prices');
  179.             $criteria->addFilter(new EqualsFilter('id'$product->getReferencedId()));
  180.             /*  @var  \Shopware\Core\Content\Product\ProductEntity $productEntity */
  181.             $productEntity $this->productRepository->search($criteriaContext::createDefaultContext())->first();
  182.             $bTax $productEntity->getTranslated()['customFields']['taxrate'] ?? 1;
  183. //
  184. //            dump($oCurrentSession->get('zero_tax_consent'));
  185. //            dump($oCurrentSession->get('zero_tax_waiver'));
  186. //            dump($sTaxMode);
  187. //            dd($taxRate);
  188. //
  189.             /* @var Shopware\Core\Checkout\Cart\LineItem\LineItem $product */
  190.             if (empty($bTax)) {
  191.                 $i++;
  192.                 $oCurrentSession->set('isZeroTaxCart'true);
  193.                 if (!empty($productEntity->getPrices()->first())) {
  194.                     if ($sTaxMode == 'net') {
  195.                         $newPrice = (float)$productEntity->getPrices()->first()->getPrice()->first()->getNet() ?? null;
  196.                     } elseif ($sTaxMode == 'gross') {
  197.                         $newPrice = (float)$productEntity->getPrices()->first()->getPrice()->first()->getGross() ?? null;
  198.                     }
  199.                 }
  200.             } else {
  201.                 continue;
  202.             }
  203.             if (empty($product->getPrice()) || empty($newPrice)) {
  204.                 continue;
  205.             }
  206.             $definition = new QuantityPriceDefinition(
  207.                 $newPrice,
  208.                 new TaxRuleCollection([$taxRule]),
  209.                 $product->getPrice()->getQuantity() ?? $product->getQuantity()
  210.             );
  211.             $calculated $this->calculator->calculate($definition$context);
  212.             $product->setPrice($calculated);
  213.             $product->setPriceDefinition($definition);
  214.             $oCurrentSession->set('isZeroTaxCart'true);
  215.         }
  216.         if (empty($i)) {
  217. //            $oCurrentSession->remove('zero_tax_consent');
  218. //            $oCurrentSession->remove('first_checkout_entry');
  219.         }
  220.     }
  221. }