<?php
namespace CustomPricePlugin\Subscriber;
use Psr\Log\LoggerInterface;
use Shopware\Core\Content\Product\ProductEvents;
//use Shopware\Core\Content\Product\ProductLoadedEvent;
use Shopware\Core\Framework\Context;
use Symfony\Bundle\FrameworkBundle\Controller\RedirectController;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Shopware\Core\Checkout\Cart\Event\CartConvertedEvent;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface;
use Shopware\Core\Framework\DataAbstractionLayer\Event\EntityLoadedEvent;
use Doctrine\DBAL\Connection;
use Shopware\Core\Content\Product\Events\ProductListingResultEvent;
use Shopware\Core\Checkout\Cart\Price\Struct\CalculatedPrice;
use Shopware\Core\Content\Product\DataAbstractionLayer\CheapestPrice\CalculatedCheapestPrice;
use Shopware\Core\Framework\DataAbstractionLayer\Pricing\Price;
use Shopware\Core\Framework\DataAbstractionLayer\Pricing\PriceCollection;
use Shopware\Core\Checkout\Cart\Tax\Struct\TaxRuleCollection;
use Shopware\Core\Checkout\Cart\Tax\Struct\TaxRule;
use \Shopware\Core\Checkout\Cart\Tax\Struct\CalculatedTaxCollection;
use \Shopware\Core\Checkout\Cart\Tax\Struct\CalculatedTax;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\HttpKernel\Exception\RedirectResponseException;
use Shopware\Core\Content\Product\Aggregate\ProductPrice\ProductPriceCollection;
use Shopware\Core\Content\Product\Aggregate\ProductPrice\ProductPriceEntity;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Shopware\Core\Checkout\Cart\Cart;
use Shopware\Core\Checkout\Cart\CartCalculator;
use Shopware\Core\Checkout\Cart\CartPersisterInterface;
use Shopware\Core\Checkout\Cart\Event\CartChangedEvent;
use Shopware\Core\System\SalesChannel\SalesChannelContext;
use Shopware\Core\System\SalesChannel\SalesChannelEntity;
use Shopware\Core\System\SalesChannel\SalesChannelRepository;
use Shopware\Core\Content\Product\SalesChannel\SalesChannelProductCollection;
use Shopware\Core\Content\Product\SalesChannel\SalesChannelProductEntity;
use Shopware\Storefront\Page\Checkout\Finish\CheckoutFinishPageLoadedEvent;
use Shopware\Core\Content\Category\Event\CategoryPageLoadedEvent;
use Shopware\Core\System\Salutation\SalutationCollection;
use Shopware\Core\Checkout\Cart\LineItem\LineItem;
use Shopware\Core\Checkout\Cart\SalesChannel\CartService;
use Shopware\Core\Checkout\Cart\Event\CheckoutOrderPlacedEvent;
use Shopware\Core\Checkout\Cart\Event\AfterLineItemAddedEvent;
use Shopware\Core\Checkout\Cart\Event\BeforeLineItemAddedEvent;
use Shopware\Storefront\Page\Product\ProductVariantListingPriceEvent;
use Shopware\Storefront\Page\Product\ProductPageLoadedEvent;
use Shopware\Core\Content\MailTemplate\Service\Event\MailBeforeValidateEvent;
use Shopware\Core\System\Country\CountryStateCollection;
use Shopware\Core\System\Country\CountryCollection;
use Shopware\Core\System\Country\CountryEntity;
use Shopware\Core\System\Country\Aggregate\CountryState\CountryStateEntity;
use Shopware\Core\System\ZipCode\ZipCodeEntity;
use Shopware\Core\System\ZipCode\ZipCodeCollection;
use Shopware\Core\System\ZipCode\ZipCodeRepository;
use Shopware\Core\System\Country\Aggregate\CountryState\CountryStateRepository;
use Shopware\Core\System\Country\CountryRepository;
use Shopware\Storefront\Page\Checkout\Confirm\CheckoutConfirmPageLoadedEvent;
use Shopware\Core\System\Checkout\Customer\CustomerEntity;
use Shopware\Core\Checkout\Customer\Aggregate\CustomerAddress\CustomerAddressEntity;
use Shopware\Core\Checkout\Customer\Aggregate\CustomerAddress\CustomerAddressCollection;
use Shopware\Core\System\Customer\CustomerAddress\CustomerAddressRepository;
use Shopware\Core\Framework\Uuid\Uuid;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Cache\CacheCriteriaEvent;
use Shopware\Core\Content\Product\Events\ProductDetailRouteCacheKeyEvent;
use Shopware\Core\Content\Product\Events\ProductListingRouteCacheKeyEvent;
use Shopware\Core\Content\Product\Events\ProductSearchRouteCacheKeyEvent;
use Shopware\Core\Content\Product\Events\ProductSuggestRouteCacheKeyEvent;
use Shopware\Core\Content\Product\SalesChannel\CrossSelling\CrossSellingRouteCacheKeyEvent;
use Shopware\Core\Framework\Store\Api\StoreApiRouteCacheKeyEvent;
use Shopware\Core\System\CustomField\CustomFieldEntity;
use Shopware\Core\System\CustomField\CustomFieldTypes;
use Shopware\Core\System\CustomField\DataAbstractionLayer\CustomFieldRepository;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\ContainsFilter;
use Shopware\Core\Content\Product\Events\ProductLoadedEvent;
class CustomPriceSubscriber implements EventSubscriberInterface
{
private $connection;
private $requestStack;
private $logger;
private CartService $cartService;
private $container;
private $router;
private EntityRepositoryInterface $orderRepository;
private $countryRepository;
private $salutationRepository;
private $salutations;
private $customerAddressRepository;
private $salesChannelRepository;
private $customFieldRepository;
private $productRepository;
public function __construct(CartService $cartService,
ContainerInterface $container,
RequestStack $requestStack,
LoggerInterface $logger,
RouterInterface $router,
EntityRepositoryInterface $orderRepository,
EntityRepositoryInterface $countryRepository,
EntityRepositoryInterface $customerRepository,
EntityRepositoryInterface $salutationRepository,
EntityRepositoryInterface $customFieldRepository,
EntityRepositoryInterface $productRepository,
EntityRepositoryInterface $salesChannelRepository
)
{
$this->cartService = $cartService;
$this->container = $container;
$this->connection = $container->get(Connection::class);
$this->requestStack = $requestStack;
$this->logger = $logger;
$this->router = $router;
$this->orderRepository = $orderRepository;
$this->countryRepository = $countryRepository;
$this->customerRepository = $customerRepository;
$this->salutationRepository = $salutationRepository;
$this->customFieldRepository = $customFieldRepository;
$this->productRepository = $productRepository;
$this->salesChannelRepository = $salesChannelRepository;
$this->logger->warning('CustomPriceSubscriber: constructor was called.');
}
/****
* Events to functions mapping
*/
public static function getSubscribedEvents(): array
{
return [
ProductListingResultEvent::class => ['onProductListingResult',500],
ProductPageLoadedEvent::class => ['onProductPageLoaded',500],
CategoryPageLoadedEvent::class => 'onCategoryPageLoaded',
MailBeforeValidateEvent::class => 'onMailBeforeValidate',
CheckoutOrderPlacedEvent::class => 'onOrderPlaced',
CheckoutFinishPageLoadedEvent::class => 'onCheckoutFinishPageLoaded',
CheckoutConfirmPageLoadedEvent::class => 'onConfirmPageLoaded',
ProductDetailRouteCacheKeyEvent::class => 'onCacheKeyEvent',
ProductListingRouteCacheKeyEvent::class => 'onCacheKeyEvent1',
ProductSearchRouteCacheKeyEvent::class => 'onCacheKeyEvent2',
ProductSuggestRouteCacheKeyEvent::class => 'onCacheKeyEvent3',
CrossSellingRouteCacheKeyEvent::class => 'onCacheKeyEvent4',
CacheCriteriaEvent::class => 'onCacheCriteriaEvent',
ProductLoadedEvent::class => 'onProductsLoaded',
ProductVariantListingPriceEvent::class => ['onVariantListingPrice',500]
];
}
public function onProductsLoaded(ProductLoadedEvent $event): void
{
$products = $event->getEntities();
}
public function onCacheKeyEvent(ProductDetailRouteCacheKeyEvent $event): void
{
$event->disableCaching();
}
public function onCacheKeyEvent1(ProductListingRouteCacheKeyEvent $event): void
{
$event->disableCaching();
}
public function onCacheKeyEvent2(ProductSearchRouteCacheKeyEvent $event): void
{
$event->disableCaching();
}
public function onCacheKeyEvent3(ProductSuggestRouteCacheKeyEvent $event): void
{
$event->disableCaching();
}
public function onCacheKeyEvent4(CrossSellingRouteCacheKeyEvent $event): void
{
$event->disableCaching();
}
public function getTranslatedCustomFields(array $customFieldOptions, array $customFieldValues, array $customFieldLabels) : array
{
$customFieldTranslated = [];
foreach ($customFieldValues as $fieldName => $values) {
// Label für den Feldnamen holen
$fieldLabel = $customFieldLabels[$fieldName]['en-GB'] ?? $fieldName;
$fieldType = 'string'; // Standardwert ist 'string'
// Werte für das Feld verarbeiten
$translatedValues = [];
if (is_array($values)) {
foreach ($values as $value) {
$found = false;
if (isset($customFieldOptions[$fieldName])) {
foreach ($customFieldOptions[$fieldName] as $option) {
if ($option['value'] === $value) {
$translatedValues[] = $option['label']['en-GB'] ?? $value;
$found = true;
break;
}
}
}
if (!$found) {
// Originalwert hinzufügen, wenn keine Übersetzung gefunden wurde
$translatedValues[] = $value;
}
}
} else {
// Behandlung von Nicht-Array-Werten (z.B. einfache Zahlen oder Strings)
$translatedValues = $values;
}
// Überprüfen, ob der Wert eine einzelne boolean value ist
if (is_bool($values) || (is_array($values) && count($values) === 1 && isset($values[0]) && is_bool($values[0]))) {
$fieldType = 'bool';
}
// Ergebnis-Array zusammenstellen
$customFieldTranslated[$fieldName] = [
'type' => $fieldType,
'label' => $fieldLabel,
'values' => $translatedValues
];
}
return $customFieldTranslated ;
}
public function getProductCustomFieldOptions(string $productId, string $prefix, Context $context): array
{
$criteria = new Criteria([$productId]);
$criteria->addAssociation('customFields');
$product = $this->productRepository->search($criteria, $context)->first();
if (!$product) {
return [];
}
$customFields = $product->getCustomFields() ?? [];
$filteredFields = [];
foreach ($customFields as $key => $value) {
if (strpos($key, $prefix) === 0) {
// $filteredFields[$key] = $value;
$customFieldOptions = $this->getCustomFieldOptions($key, $context);
$filteredFields[$key] = $customFieldOptions;
}
}
return $filteredFields;
}
public function getProductCustomFieldValues(string $productId, string $prefix, Context $context): array
{
$criteria = new Criteria([$productId]);
$criteria->addAssociation('customFields');
$product = $this->productRepository->search($criteria, $context)->first();
if (!$product) {
return [];
}
$customFields = $product->getCustomFields() ?? [];
$filteredFields = [];
$labels = [];
foreach ($customFields as $key => $value) {
if (strpos($key, $prefix) === 0) {
$filteredFields[$key] = $value;
$customFieldConfig = $this->getCustomFieldConfig($key, $context);
$fieldLabels = [];
if( is_array($value) )
{
foreach ($value as $value1) {
if (isset($customFieldConfig['options'][$value1])) {
$fieldLabels[$value1] = $customFieldConfig['options'][$value1]['label'] ?? $value1;
}
}
}
else
{
if (isset($customFieldConfig['options'][$value])) {
$fieldLabels[$value] = $customFieldConfig['options'][$value]['label'] ?? $value;
}
}
if( empty($fieldLabels) )
$labels[$key] = $value;
else
$labels[$key] = $fieldLabels;
}
}
return $labels;
}
public function getCustomFieldLabels(string $prefix, Context $context): array
{
$criteria = new Criteria();
$criteria->addFilter(new ContainsFilter('name', $prefix));
$customFields = $this->customFieldRepository->search($criteria, $context);
$fieldsLabels = [];
foreach ($customFields as $customField) {
// Prüfen, ob der Feldname mit dem Präfix beginnt
if (strpos($customField->getName(), $prefix) === 0) {
$config = $customField->getConfig();
$label = $config['label'] ?? $customField->getName();
$fieldsLabels[$customField->getName()] = $label;
}
}
return $fieldsLabels;
}
private function getCustomFieldConfig(string $customFieldKey, Context $context): array
{
$criteria = new Criteria();
$criteria->addFilter(new EqualsFilter('name', $customFieldKey));
$customField = $this->customFieldRepository->search($criteria, $context)->first();
if (!$customField) {
return [];
}
return $customField->getConfig() ?? [];
}
public function getCustomFieldOptions(string $customFieldKey, Context $context): array
{
$criteria = new Criteria();
$criteria->addFilter(new EqualsFilter('customFieldSet.relations.entityName', 'product'));
$criteria->addFilter(new EqualsFilter('name', $customFieldKey));
/** @var CustomFieldEntity $customField */
$customField = $this->customFieldRepository->search($criteria, $context)->first();
if (!$customField || $customField->getType() !== CustomFieldTypes::SELECT) {
return [];
}
$options = $customField->getConfig()['options'] ?? [];
// Transformieren Sie die Optionen hier nach Bedarf
return $options;
}
public function onCacheCriteriaEvent(CacheCriteriaEvent $event): void
{
// Prüfen, ob das Event für das Produktlisting ist
if ($event->getContext()->getResource() === 'product_listing') {
// Deaktivieren des Cachings für das Produktlisting
$event->getCriteria()->addExtension('disable-cache', true);
}
}
/*****
* get the salutations from Repository
* Herr, Frau, Familie ...
**/
private function getSalutations(SalesChannelContext $salesChannelContext): SalutationCollection
{
$salutations = $this->salutationRoute->load(new Request(), $salesChannelContext, new Criteria())->getSalutations();
$salutations->sort(function (SalutationEntity $a, SalutationEntity $b) {
return $b->getSalutationKey() <=> $a->getSalutationKey();
});
return $salutations;
}
/******
* prüfe ob es ein sonderstore, oder der normale ist
*/
function isNotOilPelletsFuelStore( $scname )
{
$scarray = array("EMOVA Heizöl", "EMOVA Diesel", "EMOVA Pellets","EMOVA Tankreinigung");
if (!in_array($scname, $scarray))
{
return(true);
}
return( false );
}
/******
* lösche Variablen die nichjt mehr gebraucht werden
****/
function removeSessionParsAfterOrderFinished($session)
{
$session->remove('poid');
$session->remove('ev_city');
$session->remove('ev_quantity');
$session->remove('ev_postcode');
$session->remove('ev_numaddresses');
$session->remove('ev_prodrequested');
$session->remove('ev_addresses');
$session->remove('evre_addresses');
$session->remove('ev_liefertermine');
$session->remove('ev_address_data');
$session->remove('ev_address_id');
$session->remove('evre_address_id');
if ($session->has('client-note')) {
$clientNote = $session->get('client-note');
$session->set('client-note-prev',$clientNote);
}
$session->remove('client-note');
$session->remove('client-delivery');
// nicht wegsetzen, wird in der Betsätigung noch gebraucht
//$session->remove('client-deliverytext');
//$session->remove('ev_voucher_code_valid');
//$session->remove('ev_mandantor');
$session->remove('ev_voucher_code');
//$session->remove('ev_voucher_code_valid'); // nicht löschen, muss noch angezeigt werden !
$session->remove('ev_voucher_error');
$session->remove('productReq');
}
/*********
* last page after order is set, mail is sent. This shows the order confirmed from the shop.
****/
public function onCheckoutFinishPageLoaded(CheckoutFinishPageLoadedEvent $event): void
{
$request = $this->requestStack->getCurrentRequest();
$session = $request->getSession();
$salesContext = $event->getSalesChannelContext();
$salesChannel = $salesContext->getSalesChannel();
$scname = $salesChannel->getName();
/* normal store should not execute our code */
if( $this->isNotOilPelletsFuelStore($scname) == true )
{
return;
}
$this->removeSessionParsAfterOrderFinished($session);
//$readdress = $session->get('re_address');
//$validvoucher = $session->get('ev_voucher_code_valid');
}
function getGermanCountry( $salesChannelContext )
{
// Fetch the country collection
$criteria = new Criteria();
$criteria->addFilter(
new EqualsFilter('iso', 'DE')
);
/** @var CountryCollection $countries */
$countries = $this->countryRepository->search(
$criteria,
$salesChannelContext->getContext()
)->getEntities();
// Find the country with name "Deutschland"
/** @var CountryEntity|null $germanyCountry */
$germanyCountry = $countries->first(); //function (CountryEntity $country) {
return( $germanyCountry );
}
/*******
* get the salutation for a anrede text
***/
function getSalutation( $anrede, $salesChannelContext )
{
if( !isset($salutations) ) {
/** @var SalutationCollection $salutations */
$salutations = $this->salutationRepository->search(new Criteria(), $salesChannelContext->getContext())->getEntities();
}
$salutationFound = null;
foreach ($salutations as $salutation) {
if ($salutation->displayName === $anrede) {
$salutationId = $salutation->getId();
$salutationFound = $salutation;
return($salutation);
}
}
return( null );
}
/*********
* the confirmPage for the user is loaded. This is the last page where the user has to click the 'order' button
* this is called from checkout/voucher and from /checkout/register too
* the code should be executed only when it is not called for checkout/confirm itself
* all the stuff is in cart, not in order yet
******/
public function onConfirmPageLoaded(CheckoutConfirmPageLoadedEvent $event): void
{
// Hier können Sie auf die Bestellungsbestätigungsseite zugreifen
$doDump = false;
$page = $event->getPage();
$request = $this->requestStack->getCurrentRequest();
// this should be executed on this :
// "https://shop.emova.de/heizoel/checkout/voucher"
// "https://shop.emova.de/heizoel/checkout/register"
// not on this :
// "https://shop.emova.de/heizoel/checkout/confirm"
if ($request->headers->has('Referer')) {
// Get the value of the Referer header
$referer = $request->headers->get('Referer');
if (strpos($referer, '/checkout/confirm', -strlen($referer)) !== false) {
return;
}
}
$session = $request->getSession();
$salesContext = $event->getSalesChannelContext();
$salesChannel = $salesContext->getSalesChannel();
if( $doDump )
{
$customFields = $salesChannel->getCustomFields();
dump($customFields);
}
$scname = $salesChannel->getName();
$scarray = array("EMOVA Heizöl", "EMOVA Diesel", "EMOVA Pellets","EMOVA Tankreinigung");
if (!in_array($scname, $scarray))
{
return;
}
$salesChannelContext = $event->getSalesChannelContext();
$customer = $salesChannelContext->getCustomer();
$ev_addresses = $session->get('ev_address_data');
$evre_addresses = $session->get('evre_address_data');
$ev_addressid = $session->get('ev_address_id');
$evre_addressid = $session->get('evre_address_id');
if( $evre_addresses != null ) //&& $ev_addressid === null )
{
$session->set('evre_addresses',$ev_addresses);
}
if( $ev_addresses != null ) //&& $ev_addressid === null )
{
$session->set('ev_addresses',$ev_addresses);
if( $doDump )
dump($ev_addresses[0]);
// Create a new shipping address entity
$newShippingAddress = new CustomerAddressEntity();
$anrede = '' . $ev_addresses[0]['ev_anrede'];
$salutationFound = $this->getSalutation( $anrede, $salesChannelContext );
$salutationId = $salutationFound->getId();
$newShippingAddress->setSalutationId($salutationId);
$session->set('ev_salutationid',$salutationId);
$newShippingAddress->setSalutation($salutationFound);
//$newShippingAddress->setAccountType('privat');// . $ev_addresses[0]['ev_accounttype'] );
if( !isset($ev_addresses[0]['ev_firstname']) )
$newShippingAddress->setFirstName(' ');
else
$newShippingAddress->setFirstName('' . $ev_addresses[0]['ev_firstname'] );
$newShippingAddress->setTitle('');
$newShippingAddress->setLastName('' . $ev_addresses[0]['ev_name'] );
$newShippingAddress->setStreet('' . $ev_addresses[0]['ev_street'] . ' ' . $ev_addresses[0]['ev_housenr'] );
$newShippingAddress->setPhoneNumber('' . $ev_addresses[0]['ev_phone'] );
$newShippingAddress->setZipcode('' . $ev_addresses[0]['ev_postcode'] );
$newShippingAddress->setAdditionalAddressLine1('' . $ev_addresses[0]['ev_info'] );
$newShippingAddress->setCity('' . $ev_addresses[0]['ev_city'] );
if( $ev_addressid === null )
{
$ev_addressid = Uuid::randomHex();
$session->set('ev_address_id',$ev_addressid);
}
$newShippingAddress->setId($ev_addressid);
$germanyCountry = $this->getGermanCountry($salesChannelContext);
if ($germanyCountry != null ) {
// Get the CountryId for Germany
$germanyCountryId = $germanyCountry->getId();
$newShippingAddress->setCountry($germanyCountry );
$newShippingAddress->setCountryId($germanyCountryId );
}
$customerId = null;
if($customer)
{
$customerId = $customer->getId();
$newShippingAddress->setCustomerId($customerId);
}
$cadrs = $customer->getAddresses();
$newAddressData = [
'id' => $newShippingAddress->getId(),
'firstName' => $newShippingAddress->getFirstName(),
'lastName' => $newShippingAddress->getLastName(),
'street' => $newShippingAddress->getStreet(),
'phoneNumber' => $newShippingAddress->getPhoneNumber(),
'zipcode' => $newShippingAddress->getZipcode(),
'city' => $newShippingAddress->getCity(),
'countryId' => '' . $germanyCountryId ,
'customerId' => '' . $customerId ,
'salutationId' => $newShippingAddress->getSalutationId(),
];
$this->customerRepository->update(
[
[
'id' => $customerId,
'defaultShippingAddressId' => $newShippingAddress->getId(),
'addresses' => [$newAddressData],
]
],
$salesChannelContext->getContext()
);
// Set the new shipping address as the default shipping address
if( $customer) {
$customer->setDefaultShippingAddress($newShippingAddress);
$customer->setActiveShippingAddress($customer->getDefaultShippingAddress() ); //$newShippingAddress);
}
if( $doDump )
dump($newShippingAddress);
}
$readrfilled = false;
if( $evre_addresses != null )
{
$readrfilled = true;
if (!isset($evre_addresses['ev_anrede']) || empty($evre_addresses['ev_anrede'])) {
$readrfilled = false;
}
if (!isset($evre_addresses['ev_readrset']) || empty($evre_addresses['ev_readrset']) || ($evre_addresses['ev_readrset'] !== 'on') ) {
$readrfilled = false;
}
if (!isset($evre_addresses['ev_firstname']) || empty($evre_addresses['ev_firstname'])) {
$readrfilled = false;
}
if (!isset($evre_addresses['ev_name']) || empty($evre_addresses['ev_name'])) {
$readrfilled = false;
}
if (!isset($evre_addresses['ev_street']) || empty($evre_addresses['ev_street'])) {
$readrfilled = false;
}
if (!isset($evre_addresses['ev_housenr']) || empty($evre_addresses['ev_housenr'])) {
$readrfilled = false;
}
if (!isset($evre_addresses['ev_phone']) || empty($evre_addresses['ev_phone'])) {
$readrfilled = false;
}
if (!isset($evre_addresses['ev_postcode']) || empty($evre_addresses['ev_postcode'])) {
$readrfilled = false;
}
if (!isset($evre_addresses['ev_city']) || empty($evre_addresses['ev_city'])) {
$readrfilled = false;
}
}
if( $evre_addresses != null )
{
$session->set('evre_addresses',$evre_addresses);
}
if( $evre_addresses != null && $readrfilled )
{
$session->set('evre_addresses',$evre_addresses);
if( $doDump )
dump($evre_addresses);
// Create a new shipping address entity
$newInvoiceAddress = new CustomerAddressEntity();
$anrede = '' . $evre_addresses['ev_anrede'];
$salutationFound = $this->getSalutation( $anrede, $salesChannelContext );
$salutationId = $salutationFound->getId();
$newInvoiceAddress->setSalutationId($salutationId);
$session->set('ev_salutationid',$salutationId);
$newInvoiceAddress->setSalutation($salutationFound);
//$newInvoiceAddress->setAccountType('privat');// . $evre_addresses[0]['ev_accounttype'] );
if( !isset($evre_addresses['ev_firstname']) )
$newInvoiceAddress->setFirstName(' ');
else
$newInvoiceAddress->setFirstName('' . $evre_addresses['ev_firstname'] );
$newInvoiceAddress->setTitle('');
$newInvoiceAddress->setLastName('' . $evre_addresses['ev_name'] );
$newInvoiceAddress->setStreet('' . $evre_addresses['ev_street'] . ' ' . $evre_addresses['ev_housenr'] );
$newInvoiceAddress->setPhoneNumber('' . $evre_addresses['ev_phone'] );
$newInvoiceAddress->setZipcode('' . $evre_addresses['ev_postcode'] );
//$newInvoiceAddress->setAdditionalAddressLine1('' . $evre_addresses['ev_info'] );
$newInvoiceAddress->setCity('' . $evre_addresses['ev_city'] );
if( $evre_addressid === null )
{
$evre_addressid = Uuid::randomHex();
$session->set('evre_address_id',$evre_addressid);
}
$newInvoiceAddress->setId($evre_addressid);
$germanyCountry = $this->getGermanCountry($salesChannelContext);
if ($germanyCountry != null ) {
// Get the CountryId for Germany
$germanyCountryId = $germanyCountry->getId();
$newInvoiceAddress->setCountry($germanyCountry );
$newInvoiceAddress->setCountryId($germanyCountryId );
}
$customerId = null;
if($customer)
{
$customerId = $customer->getId();
$newInvoiceAddress->setCustomerId($customerId);
}
$cadrs = $customer->getAddresses();
$newAddressData = [
'id' => $newInvoiceAddress->getId(),
'firstName' => $newInvoiceAddress->getFirstName(),
'lastName' => $newInvoiceAddress->getLastName(),
'street' => $newInvoiceAddress->getStreet(),
'phoneNumber' => $newInvoiceAddress->getPhoneNumber(),
'zipcode' => $newInvoiceAddress->getZipcode(),
'city' => $newInvoiceAddress->getCity(),
'countryId' => '' . $germanyCountryId ,
'customerId' => '' . $customerId ,
'salutationId' => $newInvoiceAddress->getSalutationId(),
];
$this->customerRepository->update(
[
[
'id' => $customerId,
'defaultBillingAddressId' => $newInvoiceAddress->getId(),
'addresses' => [$newAddressData],
]
],
$salesChannelContext->getContext()
);
// Set the new shipping address as the default shipping address
if( $customer) {
$customer->setDefaultBillingAddress($newInvoiceAddress);
$customer->setActiveBillingAddress($customer->getDefaultBillingAddress() ); //$newInvoiceAddress);
}
if( $doDump )
dump($newInvoiceAddress);
if( $doDump )
dump($customer);
if( $doDump )
dump('confirmPage:8');
}
}
/*****
* get the salesChannel if we have the id only
*/
public function getCurrentSalesChannel(string $salesChannelId): ?SalesChannelEntity
{
// Holen Sie die ID des aktuellen SalesChannels aus der Session
if ($salesChannelId) {
// Rufen Sie den SalesChannel aus der Datenbank ab
$context = Context::createDefaultContext();
return $this->salesChannelRepository->search(
(new Criteria())->addFilter(new EqualsFilter('id', $salesChannelId)),
$context
)->first();
}
return null;
}
/*********
* this is called immediatly before the mail is sent.
* here we need to add some data that we want to put to the mail
* this is added into the template data
***/
public function onMailBeforeValidate(MailBeforeValidateEvent $event)
{
$doTrace = false;
$context = $event->getContext();
$data = $event->getTemplateData();
$request = $this->requestStack->getCurrentRequest();
$session = $request->getSession();
$session->remove('ev_mailBeforeValidate');
if( $doTrace )
$session->set('ev_mailBeforeValidate', 'true');
$addresses = $session->get('ev_addresses');
$validvoucher = $session->get('ev_voucher_code_valid');
$salesChannelId = $session->get('sw-sales-channel-id');
$salesContext = $request->attributes->get('sw-sales-channel-context');
$salesChannel = null;
if( $salesContext != null )
{
$salesChannel = $salesContext->getSalesChannel();
}
else if( $salesChannelId )
{
$salesChannel = $this->getCurrentSalesChannel($salesChannelId); //$event->getSalesChannelContext();
}
$scname = '';
if( $salesChannel != null )
{
$scname = $salesChannel->getName();
}
if( $scname != "EMOVA Heizöl" )
{
$addresses = null;
}
if( $scname == "EMOVA Heizöl" )
{
if ( !($validvoucher === null) && strpos($validvoucher, 'EHO') != 0)
{
$validvoucher = null;
}
}
if( $scname == "EMOVA Pellets" )
{
if ( !($validvoucher === null) && strpos($validvoucher, 'EPE') != 0)
{
$validvoucher = null;
}
}
if( $scname == "EMOVA Tankreinigung" )
{
$validvoucher = null;
}
if( $scname == "EMOVA Store" )
{
if ( !($validvoucher === null)
&& strpos($validvoucher, 'EWB') != 0
&& strpos($validvoucher, 'EBK') != 0
)
{
$validvoucher = null;
}
}
if (!($validvoucher === null ) && !(empty($validvoucher)) )
{
//$sql = "SELECT * FROM ev_voucher WHERE code = ? AND validuntil >= NOW() ORDER BY createdate DESC LIMIT 1";
$sql = "SELECT * FROM ev_voucher WHERE code = ? ORDER BY createdate DESC LIMIT 1";
$params = [$validvoucher];
$voucherData = $this->connection->executeQuery($sql, $params)->fetch();
$currentDateTime = new \DateTime(); // Aktuelles Datum/Uhrzeit
if ($voucherData !== false) {
$voucherId = $voucherData['void'];
}
else
{
$validvoucher = '';
}
}
if ($session->has('client-note')) {
$clientNote = $session->get('client-note');
}
else
{
$clientNote = '';
}
if ($session->has('client-delivery')) {
$clientDelivery = $session->get('client-delivery');
}
else
{
$clientDelivery = '';
}
if ($session->has('client-deliverytext')) {
$clientDeliveryText = $session->get('client-deliverytext');
}
else
{
$clientDeliveryText = '';
}
$data["ev_clientDeliveryText"] = $clientDeliveryText;
$data["ev_clientDelivery"] = $clientDelivery;
$data["ev_clientNote"] = $clientNote;
if (isset($data["ev_addresses"])) {
$adr2 = $data["ev_addresses"];
if( $adr2 !== null )
{
$data["ev_addresses2"] = $adr2;
}
}
if( $addresses !== null )
{
$data["ev_addresses"] = $addresses;
$anzahlElemente = count($addresses);
if( $anzahlElemente > 0 )
{
$data["ev_addressesvalid"] = 'true';
}
else
{
$data["ev_addressesvalid"] = 'false';
}
}
else
{
$data["ev_addressesvalid"] = 'false';
}
$data["ev_validvoucher"] = $validvoucher;
$customFields = null;
if( $salesChannel ) {
$customFields = $salesChannel->getCustomFields();
}
if( $customFields != null )
{
// context.salesChannel.customFields.
$data["emova_settings_lieferp_text"] = ($customFields["emova_settings_lieferp_text"]);
$data["emova_settings_ust"] = ($customFields["emova_settings_ust"]);
$data["emova_settings_lp_brutto"] = ($customFields["emova_settings_lp_brutto"]);
$data["emova_settings_lp_netto"] = ($customFields["emova_settings_lp_netto"]);
$data["emova_settings_einheit"] = ($customFields["emova_settings_einheit"]);
}
else
{
// context.salesChannel.customFields.
$data["emova_settings_lieferp_text"] = ("emova_settings_lieferp_text");
$data["emova_settings_ust"] = (19);
$data["emova_settings_lp_brutto"] = (42);
$data["emova_settings_lp_netto"] = (35);
$data["emova_settings_einheit"] = ("einheit");
}
$event->setTemplateData($data);
}
/**
* @param CheckoutOrderPlacedEvent $event
* @throws \Exception
*/
public function onOrderPlaced(CheckoutOrderPlacedEvent $event)
{
$request = $this->requestStack->getCurrentRequest();
$doDump = false;
if( $doDump )
{
dump('CustomPricePlugin:onOrderPlaced');
dump($event);
dump($request);
}
$session = $request->getSession();
$addresses = $session->get('ev_addresses');
$validvoucher = $session->get('ev_voucher_code_valid');
$orderNumber = $event->getOrder()->getOrderNumber(); // Bestellnummer aus dem Event
$salesChannelId = $session->get('sw-sales-channel-id');
$salesContext = $request->attributes->get('sw-sales-channel-context');
$salesChannel = null;
if( $salesContext != null )
{
$salesChannel = $salesContext->getSalesChannel();
}
else if( $salesChannelId )
{
$salesChannel = $this->getCurrentSalesChannel($salesChannelId); //$event->getSalesChannelContext();
}
if( $doDump )
dump($event->getOrder());
$scname = $salesChannel->getName();
if( $doDump )
dump('CustomPricePlugin:onOrderPlaced');
$session->set('ev_onOrderPlaced start', 'true');
if( $scname != "EMOVA Heizöl" )
{
$addresses = null;
}
if( $scname == "EMOVA Heizöl" )
{
if ( !($validvoucher === null) && strpos($validvoucher, 'EHO') != 0)
{
$validvoucher = null;
}
}
if( $scname == "EMOVA Pellets" )
{
if ( !($validvoucher === null) && strpos($validvoucher, 'EPE') != 0)
{
$validvoucher = null;
}
}
if( $scname == "EMOVA Tankreinigung" )
{
$validvoucher = null;
}
if( $scname == "EMOVA Diesel" )
{
if ( !($validvoucher === null) && strpos($validvoucher, 'EDI') != 0)
{
$validvoucher = null;
}
}
if( $scname == "EMOVA Store" )
{
if ( !($validvoucher === null)
&& strpos($validvoucher, 'EWB') != 0
&& strpos($validvoucher, 'EBK') != 0
)
{
$validvoucher = null;
}
}
if( $doDump )
dump('CustomPricePlugin:onOrderPlaced mid');
if (!($validvoucher === null ) && !(empty($validvoucher)) )
{
//$sql = "SELECT * FROM ev_voucher WHERE code = ? AND validuntil >= NOW() ORDER BY createdate DESC LIMIT 1";
$sql = "SELECT * FROM ev_voucher WHERE code = ? ORDER BY createdate DESC LIMIT 1";
$params = [$validvoucher];
$voucherData = $this->connection->executeQuery($sql, $params)->fetch();
$currentDateTime = new \DateTime(); // Aktuelles Datum/Uhrzeit
if ($voucherData !== false) {
$voucherId = $voucherData['void'];
$sql = "UPDATE ev_voucher SET orderdate = :orderdate, ordernumber = :ordernumber WHERE void = :voucherId";
$params = [
':orderdate' => $currentDateTime->format('Y-m-d H:i:s'),
':ordernumber' => $orderNumber,
':voucherId' => $voucherId,
];
$this->connection->executeStatement($sql, $params);
}
else
{
$validvoucher = '';
}
}
if( $doDump )
dump('CustomPricePlugin:onOrderPlaced mid2');
if ($request->query->has('poid'))
{
$priceOfferId = $request->query->get('poid');
$poidIsSet=true;
$session->set('poid', $priceOfferId);
}
else
{
$session = $request->getSession();
if ($session->has('poid'))
{
$priceOfferId = $session->get('poid');
$poidIsSet=true;
}
else
{
$priceOfferId = '';
}
}
if ($session->has('client-note')) {
$clientNote = $session->get('client-note');
}
else
{
$clientNote = '';
}
if ($session->has('client-delivery')) {
$clientDelivery = $session->get('client-delivery');
}
else
{
$clientDelivery = '';
}
if ($session->has('client-deliverytext')) {
$clientDeliveryText = $session->get('client-deliverytext');
}
else
{
$clientDeliveryText = '';
}
if( $doDump )
dump('CustomPricePlugin:onOrderPlaced mid3');
$customFieldPoidValue = $priceOfferId;
$customFields = $salesChannel->getCustomFields();
$emova_settings_lieferp_text = '';
$emova_settings_ust = 0;
$emova_settings_lp_brutto = 0;
$emova_settings_lp_netto = 0;
$emova_settings_einheit = '';
$emova_sepa_allowed = '';
$emova_sepa_iban = '';
$emova_sepa_accountholder = '';
if( $request->request->has('ev_customer_payment_allowsepa') )
{
$emova_sepa_allowed = $request->request->get('ev_customer_payment_allowsepa');
$emova_sepa_iban = $request->request->get('ev_customer_payment_iban');
$emova_sepa_accountholder = $request->request->get('ev_customer_payment_accountholder');
}
if( $customFields != null )
{
// context.salesChannel.customFields.
$emova_settings_lieferp_text = ($customFields["emova_settings_lieferp_text"]);
$emova_settings_ust = ($customFields["emova_settings_ust"]);
$emova_settings_lp_brutto = ($customFields["emova_settings_lp_brutto"]);
$emova_settings_lp_netto = ($customFields["emova_settings_lp_netto"]);
$emova_settings_einheit = ($customFields["emova_settings_einheit"]);
if( $emova_settings_lieferp_text = null )
$emova_settings_lieferp_text = '';
if( $emova_settings_ust = null )
$emova_settings_ust = 0;
if( $emova_settings_lp_brutto = null )
$emova_settings_lp_brutto = 0;
if( $emova_settings_lp_netto )
$emova_settings_lp_netto = 0;
if( $emova_settings_einheit = null )
$emova_settings_einheit = '';
}
if( $doDump )
dump('CustomPricePlugin:onOrderPlaced mid4');
$orderId = $event->getOrder()->getId();
$this->orderRepository->upsert([[
'id' => $orderId,
'customFields' => [
'custom_order_fields_poid' => $customFieldPoidValue,
'custom_order_fields_note' => $clientNote,
'custom_order_fields_delivery' => $clientDelivery,
'custom_order_fields_deliverytext' => $clientDeliveryText,
'custom_order_fields_addresses' => $addresses,
'custom_order_fields_evaccountholder' => $emova_sepa_accountholder,
'custom_order_fields_eviban' => $emova_sepa_iban,
'custom_order_fields_evsepa' => $emova_sepa_allowed,
'emova_settings_lieferp_text' => $emova_settings_lieferp_text,
'emova_settings_ust' => $emova_settings_ust,
'emova_settings_lp_brutto' => $emova_settings_lp_brutto,
'emova_settings_lp_netto' => $emova_settings_lp_netto,
'emova_settings_einheit' => $emova_settings_einheit,
'custom_order_fields_voucher' => $validvoucher,
]
]], $event->getContext());
if( $doDump )
dump($event->getOrder());
if( $doDump )
dump('CustomPricePlugin:onOrderPlaced mid4');
$session->set('ev_onOrderPlaced end', 'true');
}
public function onVariantListingPrice(ProductVariantListingPriceEvent $event): void
{
$salesContext = $event->getSalesChannelContext();
$salesChannel = $salesContext->getSalesChannel();
$scname = $salesChannel->getName();
$scarray = array("EMOVA Heizöl", "EMOVA Diesel", "EMOVA Pellets","EMOVA Tankreinigung");
if (!in_array($scname, $scarray))
{
return;
}
$variants = $event->getPage()->getProduct()->getVariants();
foreach ($variants as $variant) {
$variant->setCalculatedPrice(new CalculatedPrice(10.0, 10.0, 0, false));
}
}
function getCityForZipCode(string $zipCode): ?string
{
$sql = "SELECT * FROM ev_zip_city WHERE plz = ? LIMIT 1";
$params = [$zipCode];
$result = $this->connection->executeQuery($sql, $params)->fetch();
if ($result === false)
{
return null;
}
return $result['ort'];
}
//BeforeLineItemAddedEvent::class => ['onLineItemAdded',2500],
/* public function onLineItemAdded(BeforeLineItemAddedEvent $event): void
{
// dump('CustomPricePlugin:onLineItemAdded');
// $lineItem = $event->getLineItem();
// dump('here the LineItem');
// dump($lineItem);
// if ($event->getLineItem()->getType() === PromotionProcessor::LINE_ITEM_TYPE) {
// $code = $event->getLineItem()->getReferencedId();
// }
}
*/
public function productPrice(
$product,
SessionInterface $session,
String $priceOfferId, $entities, $key, $event )
{
$doDump = false;
$productId = $product->getId();
$productNumber = $product->getProductNumber();
if( $doDump )
{
dump($productNumber);
}
if( $productNumber == null )
return;
$dot_position = strpos($productNumber, '.');
$productNumber = $dot_position !== false ? substr($productNumber, 0, $dot_position) : $productNumber;
$price = $product->getCalculatedPrice();
$sql = "SELECT * FROM ev_preisanfragen WHERE productnumber = ? AND priceofferid = ? AND validuntil >= NOW() ORDER BY createdate DESC LIMIT 1";
$params = [$productNumber,$priceOfferId];
$priceData = $this->connection->executeQuery($sql, $params)->fetch();
if( $doDump )
{
dump($productNumber);
dump($priceOfferId);
dump($priceData);
}
$unit = 100;
switch ($productNumber) {
case '4000':
case '4020':
case '4001':
case '4021':
$unit = 1000;
}
if ($priceData !== false) {
$postcode =$priceData['postcode'];
$session->set('ev_postcode', $postcode);
$countt =$priceData['countt'];
$session->set('ev_countt', $countt);
$huelle =$priceData['huelle'];
$session->set('ev_huelle', $huelle);
$numaddresses =$priceData['numaddresses'];
$session->set('ev_numaddresses', $numaddresses);
$type = gettype($postcode);
$emova_city = $this->getCityForZipCode($postcode);
$session->set('ev_city', $emova_city);
$liefertermine = $priceData['liefertermine'];
$session->set('ev_liefertermine', $liefertermine);
$newPrice = (float) $priceData['pricenet'];
$taxRate = (float) $priceData['taxpercent'];
$tax = (float) $priceData['pricetax'];
$quantity = (float) $priceData['quantity'];
$session->set('ev_quantity', $quantity);
$mandantor = $priceData['mandantor'];
if( $mandantor == 'Kreuzmayr Bayern GmbH' )
{
$mandantor = 'DS Emova GmbH';
}
$session->set('ev_mandantor',$mandantor);
$productnumrequested = $priceData['productNumRequested'];
$session->set('ev_prodrequested',$productnumrequested);
$precision = (float)6;
$unitPrice= ($newPrice/$quantity)*$unit;
if( $doDump )
{
dump('new and unitPrice');
dump($priceData);
dump($unitPrice);
}
$calculatedTax = new CalculatedTax(
$tax, $taxRate, $newPrice,
$quantity, $precision);
$calculatedTaxCollection = new CalculatedTaxCollection([$calculatedTax]);
$price = new CalculatedPrice(
$unitPrice, $newPrice, $calculatedTaxCollection,
new TaxRuleCollection([new TaxRule($taxRate)]),
$quantity
);
$product->setCalculatedPrice($price);
$ccprice = new CalculatedCheapestPrice(
$unitPrice, $newPrice, $calculatedTaxCollection,
new TaxRuleCollection([new TaxRule($taxRate)]),
$quantity
);
$product->setCalculatedCheapestPrice($ccprice);
// Modify the price object
$pnewPrice = new Price(
'b7d2554b0ce847cd82f3ac9bd1c0dfca', //$price->getCurrencyId(),
$newPrice, $newPrice, false
);
// Replace the price object in the collection
$priceCollection = new PriceCollection([$pnewPrice]);
// Set the new price collection for the product
$product->setPrice($priceCollection);
// Modify the price object
$pnewPrice = new Price(
'b7d2554b0ce847cd82f3ac9bd1c0dfca', //$price->getCurrencyId(),
$newPrice,
$newPrice,
false
);
// Replace the price object in the collection
$priceCollection = new PriceCollection([$pnewPrice]);
// Set the new price collection for the product
$product->setPurchasePrices($priceCollection);
}
else
{
if( $entities != null )
{
$entities->remove($key);
$event->getResult()->remove($key);
}
}
}
public function onCategoryPageLoaded(CategoryPageLoadedEvent $event): void
{
//dump('CustomPricePlugin:onCategoryPageLoaded');
}
public function onProductPageLoaded(ProductPageLoadedEvent $event): void
{
/** @var ProductEntity $product */
$doDump = false;
if( $doDump )
dump('CustomPricePlugin:onProductPageLoaded');
$priceOfferId=null;
$poidIsSet=false;
$request = $this->requestStack->getCurrentRequest();
$salesContext = $event->getSalesChannelContext();
/** @var SalutationCollection $salutations */
$salutations = $this->salutationRepository->search(new Criteria(), $salesContext->getContext())->getEntities();
$salesChannel = $salesContext->getSalesChannel();
$scname = $salesChannel->getName();
$productId = $event->getPage()->getProduct()->getId();
$customFieldValues = $this->getProductCustomFieldValues($productId, 'ev_wallbox', $event->getContext());
$customFieldOpts = $this->getProductCustomFieldOptions($productId, 'ev_wallbox', $event->getContext());
$customFieldLabels = $this->getCustomFieldLabels('ev_wallbox', $event->getContext());
$customFieldTranslated = $this->getTranslatedCustomFields( $customFieldOpts, $customFieldValues, $customFieldLabels);
$event->getPage()->assign(['customFieldTranslated' => $customFieldTranslated]);
// $myCustomFieldOptions = $this->getCustomFieldOptions('ev_wallboxdaten_voltagesVolt', $event->getContext());
// $event->getPage()->assign(['customFieldOptions' => $myCustomFieldOptions]);
$scarray = array("EMOVA Heizöl", "EMOVA Diesel", "EMOVA Pellets","EMOVA Tankreinigung");
if (!in_array($scname, $scarray))
{
if( $doDump )
dump($scname);
return;
}
$cart = $this->cartService->getCart($salesContext->getToken(), $salesContext);
if( $doDump )
dump('lineitems:');
$lineItemsRemoved=false;
// Durchgehen aller LineItems im Warenkorb
foreach ($cart->getLineItems() as $lineItem)
{
if( $doDump )
dump($lineItem);
if( $lineItem != null )
{
$payload = $lineItem->getPayload();
if (isset($payload['productNumber']))
{
$productNumber = $payload['productNumber'];
$cart->remove($lineItem->getId());
$lineItemsRemoved=true;
if( $doDump )
dump($productNumber);
}
}
}
if( $lineItemsRemoved )
$this->cartService->recalculate($cart, $salesContext);
if( $doDump )
dump($request);
if ($request->query->has('poid'))
{
$priceOfferId = $request->query->get('poid');
$poidIsSet=true;
$session = $request->getSession();
if( $doDump )
dump('session set poid 2');
$session->set('poid', $priceOfferId);
}
else
{
$session = $request->getSession();
if ($session->has('poid'))
{
$priceOfferId = $session->get('poid');
$poidIsSet=true;
}
}
$product = $event->getPage()->getProduct();
if( $priceOfferId != null )
$this->productPrice( $product, $session, $priceOfferId,
null, null,null );
if( $doDump ) {
dump($priceOfferId);
dump($salesChannel);
dump($scname);
dump($event);
dump($product);
}
}
private function sortProducts(array $products, $prodSelected): array
{
// Gewuenschte Reihenfolge
$order = ['1121', '1101', '1120', '1100', '1020','1000', '2020', '2000', '4021','4020','4001','4000','9640','9641','9642'];
// es gibt :
// B+V und H : 1121 1101 ecovita 1001 1000 normal
// Kreuzmayr : 1120 1100 vitatherm 1001 1000 normal
// 2000, 2020 Diesel, 4000,4001,4020, 4021 Pellets
// Produkte, deren Nummer mit .. beginnt, filtern
$doDump = false;
$doDelete = false;
$prodToDelete = '9999';
$prodToDelete2 = '9999';
switch ($prodSelected) {
case '1120':
$order = ['1121', '1101', '1120', '1100', '1020', '1000'];
$doDelete = true;
$prodToDelete = '1020'; // 1020
$prodToDelete2 = '1020'; // 1020
break;
case '1121':
$order = ['1121', '1101', '1120', '1100', '1020', '1000'];
$doDelete = true;
$prodToDelete = '1020'; // 1020
$prodToDelete2 = '1020'; // 1020
break;
case '1100':
$order = ['1101', '1121', '1100', '1120', '1020', '1000'];
$doDelete = true;
$prodToDelete = '1020'; // 1120
$prodToDelete2 = '1020'; // 1120
break;
case '1101':
$order = ['1101', '1121', '1100', '1120', '1020', '1000'];
$doDelete = true;
$prodToDelete = '1020'; // 1120
$prodToDelete2 = '1020'; // 1120
break;
case '1000':
$order = ['1000', '1101', '1121', '1100', '1120', '1020'];
$doDelete = true;
$prodToDelete = '1020'; // 1101
$prodToDelete2 = '1020'; // 1100
break;
case '1020':
$order = ['1020', '1101', '1121', '1100', '1120', '1000'];
$doDelete = true;
$prodToDelete = '1000';
$prodToDelete2 = '1000';
break;
case '9640':
$order = ['9640', '9641', '9642'];
$doDelete = true;
$prodToDelete = '9641';
$prodToDelete2 = '9642';
break;
case '9641':
$order = ['9641', '9642', '9640'];
$doDelete = true;
$prodToDelete = '9642';
$prodToDelete2 = '9640';
break;
case '9642':
$order = ['9642', '9641', '9640'];
$doDelete = true;
$prodToDelete = '9640';
$prodToDelete2 = '9641';
break;
}
// Produkte nach der gegebenen Reihenfolge sortieren
usort($products, function(SalesChannelProductEntity $a, SalesChannelProductEntity $b) use ($order) {
$startNumberA = substr($a->getProductNumber(), 0, 4);
$startNumberB = substr($b->getProductNumber(), 0, 4);
$indexA = array_search($startNumberA, $order);
$indexB = array_search($startNumberB, $order);
if ($indexA === false && $indexB === false) { // Beide Startnummern sind nicht in der Reihenfolge
return 0;
} elseif ($indexA === false) { // Nur die Startnummer von a ist nicht in der Reihenfolge
return 1;
} elseif ($indexB === false) { // Nur die Startnummer von b ist nicht in der Reihenfolge
return -1;
} else { // Beide Startnummern sind in der Reihenfolge
return $indexA - $indexB;
}
});
$filteredProducts2= array_filter($products, function(\Shopware\Core\Content\Product\SalesChannel\SalesChannelProductEntity $product) use( $prodToDelete) {
return strpos($product->getProductNumber(), $prodToDelete) !== 0;
});
$filteredProducts= array_filter($filteredProducts2, function(\Shopware\Core\Content\Product\SalesChannel\SalesChannelProductEntity $product) use( $prodToDelete2) {
return strpos($product->getProductNumber(), $prodToDelete2) !== 0;
});
// Produkte, deren Nummer mit $prodSelected beginnt, finden und an den Anfang setzen
$productsStartingWith200 = array_filter($filteredProducts, function(SalesChannelProductEntity $product) use ($prodSelected) {
return strpos($product->getProductNumber(), $prodSelected) === 0;
});
$filteredProducts2= array_udiff($filteredProducts, $productsStartingWith200, function ($productA, $productB) {
return strcmp($productA->getId(), $productB->getId());
});
$sortedProducts = array_merge($productsStartingWith200, $filteredProducts2);
if( $doDump ) {
dump('productsStartingWith200');
dump($productsStartingWith200);
dump("productToDelete");
dump($prodToDelete);
dump("prodSelected");
dump($prodSelected);
dump('$filteredProducts');
dump($filteredProducts);
dump('$filteredProducts2');
dump($filteredProducts2);
dump('$sortedProducts');
dump($sortedProducts);
}
return $sortedProducts;
}
private function sortWallboxes(array $products, $productNumbersToKeep): array
{
$filteredProducts = array_filter($products, function ($product) use ($productNumbersToKeep) {
// Hier nehmen wir an, dass die Produktnummer in einem Feld mit dem Namen 'productNumber' gespeichert ist.
$productNumber = $product->get('productNumber');
// Wenn die Produktnummer in der Liste der zu behaltenden Produktnummern ist, behalten wir das Produkt.
return in_array($productNumber, $productNumbersToKeep);
});
return $filteredProducts;
}
public function onProductListingResult(ProductListingResultEvent $event): void
{
$doDump = false;
if( $doDump )
dump('CustomPricePlugin:onProductListingResult');
$priceOfferId=null;
$poidIsSet=false;
$request = $this->requestStack->getCurrentRequest();
$salesContext = $event->getSalesChannelContext();
$salesChannel = $salesContext->getSalesChannel();
$scname = $salesChannel->getName();
$scarray = array("EMOVA Heizöl", "EMOVA Diesel", "EMOVA Pellets","EMOVA Tankreinigung");
if (!in_array($scname, $scarray))
{
// normaler store
if( $doDump )
{
dump('scname');
dump($scname);
}
$productIds = $request->query->get('products', []);
$request->getSession()->set('ev_wallboxes', $productIds);
if( !empty($productIds) && !($productIds === null))
{
// Set the productIds as a session variable
$request->getSession()->set('ev_wallboxes', $productIds);
$entities = $event->getResult()->getEntities();
// Sammlung in ein Array konvertieren
$productToSort = $entities->getElements();
foreach ($productIds as &$product) {
if (strpos($product, "DP") === 0) { // Prüfen, ob die Produktnummer mit "DP" beginnt
$product = substr_replace($product, "0", -1); // Ersetze die letzte Ziffer durch eine 0
}
}
unset($product);
$sortedProducts = $this->sortWallboxes($productToSort,$productIds);
// Neue Produkt-Sammlung erstellen und setzen
$event->getResult()->clear();
$event->getResult()->fill($sortedProducts);
$entities = $event->getResult()->getEntities();
}
return;
}
//
// hier Heizöl, Pellets, Diesel
$session = $request->getSession();
if ($request->query->has('poid'))
{
$priceOfferId = $request->query->get('poid');
$poidIsSet=true;
if( $doDump )
{
dump('request set poid');
dump($priceOfferId);
}
$session->set('poid', $priceOfferId);
}
else
{
$session = $request->getSession();
if ($session->has('poid'))
{
$priceOfferId = $session->get('poid');
if( $doDump )
{
dump('session set poid ');
dump($priceOfferId);
}
$poidIsSet=true;
}
}
if ($request->query->has('product'))
{
$productReq = $request->query->get('product');
$session = $request->getSession();
$session->set('productReq', $productReq);
}
else
{
$session = $request->getSession();
if ($session->has('productReq'))
{
$productReq = $session->get('productReq');
}
}
$entities = $event->getResult()->getEntities();
$elements = $event->getResult()->getElements();
if( $doDump ) {
dump('productReq');
dump($productReq);
dump($salesChannel);
dump($scname);
dump($event);
dump($entities);
}
if( $poidIsSet )
{
if( $doDump ) {
dump('poidisSet');
}
$entities = $event->getResult()->getEntities();
// Sammlung in ein Array konvertieren
$productToSort = $entities->getElements();
// Produkte sortieren
$sortedProducts = $this->sortProducts($productToSort,$productReq);
//$sortedProducts = $event->getResult()->getEntities();
// Neue Produkt-Sammlung erstellen und setzen
$event->getResult()->clear();
$event->getResult()->fill($sortedProducts);
$entities = $event->getResult()->getEntities();
if( $doDump ) {
dump($entities);
}
$this->logger->warning('CustomPriceSubscriber: onProductListingResult poidSet.');
foreach ($entities as $key => $product)
{
$this->productPrice( $product, $session, $priceOfferId,
$entities, $key, $event );
}
$postcode = $session->get('ev_postcode');
$ev_addresses = $session->get('ev_address_data');
$session->remove('ev_voucher_code');
$session->remove('ev_voucher_code_valid');
if( $ev_addresses !== null )
{
if( $postcode !== $ev_addresses[0]['ev_postcode'] )
{
$session->remove('ev_addresses');
$session->remove('ev_liefertermine');
$session->remove('ev_address_data');
$session->remove('ev_address_id');
$session->remove('evre_address_id');
$session->remove('ev_voucher_code');
$session->remove('ev_voucher_code_valid');
$session->remove('ev_numaddresses');
$session->remove('ev_prodrequested');
$session->remove('ev_addresses');
$session->remove('evre_addresses');
}
}
}
if( $doDump )
{
dump($entities);
$entities = $event->getResult()->getEntities();
dump($entities);
dump($event);
}
}
}