<?php
namespace B2bSellersCore\Components\Product\Subscriber;
use B2bSellersCore\Components\B2bPlatform\Traits\B2bContextTrait;
use B2bSellersCore\Components\Employee\Exception\InsufficientEmployeePermissionException;
use B2bSellersCore\Components\Employee\Permission\EmployeePermissionTrait;
use B2bSellersCore\Components\Employee\Permission\Permissions;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Sorting\FieldSorting;
use Shopware\Storefront\Page\Product\ProductPageLoadedEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class ProductAlreadyBoughtSubscriber implements EventSubscriberInterface
{
use EmployeePermissionTrait;
use B2bContextTrait;
private EntityRepositoryInterface $orderRepository;
public function __construct(
EntityRepositoryInterface $orderRepository
)
{
$this->orderRepository = $orderRepository;
}
public static function getSubscribedEvents(): array
{
return [
ProductPageLoadedEvent::class => 'onProductsLoaded'
];
}
public function onProductsLoaded(ProductPageLoadedEvent $event)
{
if (!$event->getSalesChannelContext()->getCustomer()
|| !$this->hasB2bPlatformContext($event->getSalesChannelContext())
|| !$this->getEmployee($event->getSalesChannelContext())) {
return;
}
$productId = $event->getPage()->getProduct()->getId();
$customerId = $event->getSalesChannelContext()->getCustomer()->getId();
$criteria = new Criteria();
$criteria->addSorting(new FieldSorting('createdAt', 'DESC'));
$criteria->addAssociation('lineItems');
$criteria->addAssociation('lineItems.product');
$criteria->addAssociation('lineItems.product.options');
$criteria->addAssociation('lineItems.product.properties');
$criteria->addFilter(new EqualsFilter('orderCustomer.customerId', $customerId));
$criteria->addFilter(new EqualsFilter('lineItems.productId', $productId));
try {
$this->checkB2bPlatformPermission([Permissions::EMPLOYEE_PERMISSION_VIEW_ALL_ORDERS], $event->getSalesChannelContext());
} catch (InsufficientEmployeePermissionException $e) {
$employee = $this->getEmployee($event->getSalesChannelContext());
if (!$employee) {
return;
}
$criteria->addFilter(new EqualsFilter(
'order.customFields.b2b_order_customer_employee_id',
$employee->getId()
));
}
$order = $this->orderRepository->search($criteria, $event->getContext())->first();
if ($order) {
foreach ($order->getLineItems() as $lineItem) {
if ($lineItem->productId === $productId) {
$event->getPage()->addExtension('orderProductAlreadyBought', $lineItem);
}
}
}
}
}