<?php
declare(strict_types=1);
namespace WbfkExtensions\Subscriber;
use Shopware\Core\Framework\Context;
use Shopware\Core\Framework\DataAbstractionLayer\EntityWriteResult;
use Shopware\Core\Framework\DataAbstractionLayer\Event\EntityWrittenEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use WbfkExtensions\Service\InvoiceStateMachineService;
class DocumentEntitySubscriber implements EventSubscriberInterface
{
public const INVOICE_DOCUMENT_TYPE_ID = '7ebec1ff1f57459684dd3d040a5f87d1';
public const STORNO_DOCUMENT_TYPE_ID = '4c7238b29af340cda90b2ba1e084698a';
public function __construct(
private readonly InvoiceStateMachineService $invoiceStateMachineService,
) {
}
public static function getSubscribedEvents(): array
{
return [
'document.written' => 'onDocumentWritten',
];
}
public function onDocumentWritten(EntityWrittenEvent $event): void
{
array_map(function (EntityWriteResult $result) use ($event) {
if ($result->getOperation() !== EntityWriteResult::OPERATION_INSERT) {
return;
}
match ($result->getPayload()['documentTypeId']) {
self::INVOICE_DOCUMENT_TYPE_ID => $this->setInvoiceStateInvoiced($result, $event->getContext()),
self::STORNO_DOCUMENT_TYPE_ID => $this->setInvoiceStateOpen($result, $event->getContext()),
default => null,
};
}, $event->getWriteResults());
}
private function setInvoiceStateInvoiced(EntityWriteResult $result, Context $context): void
{
$this->invoiceStateMachineService->invoiceStateTransition(
$result->getPayload()['orderId'],
'invoice',
$context
);
}
private function setInvoiceStateOpen(EntityWriteResult $result, Context $context): void
{
$this->invoiceStateMachineService->invoiceStateTransition(
$result->getPayload()['orderId'],
'cancel_invoice',
$context
);
}
}