<?php declare(strict_types=1);
namespace Okeonline\KejeDocumentImport\Storefront\Subscriber;
use Shopware\Core\Checkout\Document\DocumentEntity;
use Shopware\Core\Checkout\Document\DocumentService;
use Shopware\Core\Checkout\Order\OrderEntity;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepository;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsAnyFilter;
use Shopware\Core\System\SystemConfig\SystemConfigService;
use Shopware\Storefront\Event\RouteRequest\OrderRouteRequestEvent;
use Shopware\Storefront\Page\Account\Order\AccountOrderPageLoadedEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class OrderRouteRequestEventSubscriber implements EventSubscriberInterface
{
/**
* @var OrderRouteRequestEvent
*/
private $event;
/**
* @var EntityRepository
*/
private $documentRepository;
/**
* @var SystemConfigService
*/
private $configService;
/**
* @var DocumentService
*/
private $documentService;
public function __construct(
EntityRepository $documentRepository,
SystemConfigService $configService,
DocumentService $documentService
)
{
$this->documentRepository = $documentRepository;
$this->configService = $configService;
$this->documentService = $documentService;
}
public static function getSubscribedEvents(): array
{
return [
// OrderRouteRequestEvent::class => ['addDocumentsAssociation', 0],
AccountOrderPageLoadedEvent::class => ['addDocumentsToOrdersAlternative', 0]
];
}
public function addDocumentsAssociation(OrderRouteRequestEvent $event)
{
$this->event = $event;
$criteria = $event->getCriteria();
$criteria->addAssociation('documents');
// what is going wrong with this method is that Shopware somehow adds some filters to this association, thereby the documents are not showing...
}
public function addDocumentsToOrdersAlternative(AccountOrderPageLoadedEvent $event)
{
$orders = $event->getPage()->getOrders();
$allOrderIds = $orders->getIds();
$criteria = new Criteria();
$criteria->addAssociation('documentMediaFile');
$criteria->addFilter(new EqualsAnyFilter('orderId', $allOrderIds));
$criteria->addFilter(new EqualsAnyFilter('documentTypeId', [
$this->configService->get('OkeonlineKejeDocumentImport.config.invoiceDocumentType'),
$this->configService->get('OkeonlineKejeDocumentImport.config.deliveryNoteDocumentType')
]));
$documentsResult = $this->documentRepository->search($criteria, $event->getContext());
foreach ($orders as $order)
{
$documentCollection = $documentsResult->getEntities()->filterByProperty('orderId', $order->getId());
/**
* @var string $key
* @var DocumentEntity $document
*/
foreach ($documentCollection as $key => $document)
{
try {
$this->documentService->getDocument($document, $event->getContext());
} catch (\Throwable $e) {
$documentCollection->remove($key);
}
}
/** @var OrderEntity $order */
$order->setDocuments($documentCollection);
}
}
}