<?php
namespace B2bOffer\Subscriber;
use B2bSellersCore\Components\B2bPlatform\Traits\B2bContextTrait;
use Shopware\Core\Framework\Context;
use Shopware\Core\Framework\DataAbstractionLayer\EntityCollection;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsAnyFilter;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Sorting\FieldSorting;
use Shopware\Core\System\SalesChannel\SalesChannelContext;
use Shopware\Core\System\SystemConfig\SystemConfigService;
use Shopware\Storefront\Page\Product\ProductPageLoadedEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class ProductPageSubscriber implements EventSubscriberInterface
{
use B2bContextTrait;
private SystemConfigService $configService;
private EntityRepositoryInterface $offerRepository;
public function __construct(
SystemConfigService $configService,
EntityRepositoryInterface $offerRepository
)
{
$this->configService = $configService;
$this->offerRepository = $offerRepository;
}
public static function getSubscribedEvents(): array
{
return [
ProductPageLoadedEvent::class => 'addOpenOfferData',
];
}
public function addOpenOfferData(ProductPageLoadedEvent $event): void
{
if ($event->getSalesChannelContext()->getCustomer()) {
$event->getPage()->addExtension('B2bOpenOffers', $this->getOffers($event->getSalesChannelContext(), $event->getContext()));
}
}
private function getOffers(SalesChannelContext $salesChannelContext, Context $context): EntityCollection
{
$criteria = new Criteria();
$criteria->addFilter(new EqualsFilter('salesChannelId', $salesChannelContext->getSalesChannelId()));
$criteria->addFilter(new EqualsFilter('offerCustomer.customerId', $salesChannelContext->getCustomer()->getId()));
$criteria->addAssociation('offerCustomer');
$criteria->addAssociation('status');
$criteria->addAssociation('employee');
$config = $this->getPluginConfig();
$statusIdsWhereProductsCanBeAdded = $config['statusIdsWhereProductsCanBeAdded'] ?? [$config['defaultCartStatusId']];
$criteria->addFilter(new EqualsAnyFilter('statusId', $statusIdsWhereProductsCanBeAdded));
$criteria->addSorting(new FieldSorting('createdAt', FieldSorting::DESCENDING));
$criteria->setLimit('10');
return $this->offerRepository->search($criteria, $context)->getEntities();
}
public function getPluginConfig()
{
return $this->configService->get('B2bOffer.config');
}
}