<?php declare(strict_types=1);
namespace DkcPentagastOrderExport\Subscriber;
use DkcPentagastOrderExport\Service\PentagastOrderExportService;
use Shopware\Core\Checkout\Order\Aggregate\OrderTransaction\OrderTransactionEntity;
use Shopware\Core\Checkout\Order\Aggregate\OrderTransaction\OrderTransactionStates;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepository;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Shopware\Core\System\SalesChannel\SalesChannelEntity;
use Shopware\Core\System\StateMachine\Event\StateMachineTransitionEvent;
use Shopware\Core\System\SystemConfig\SystemConfigService;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class OrderPaidSubscriber implements EventSubscriberInterface
{
public function __construct(
private readonly PentagastOrderExportService $exportService,
private readonly EntityRepository $orderTransactionRepository,
private readonly EntityRepository $salesChannelRepository,
private readonly SystemConfigService $systemConfigService
) {
}
public static function getSubscribedEvents(): array
{
return [
StateMachineTransitionEvent::class => 'onStateMachineTransition',
];
}
public function onStateMachineTransition(StateMachineTransitionEvent $event): void
{
if ($event->getStateMachineName() !== OrderTransactionStates::STATE_MACHINE) {
return;
}
if ($event->getToPlace() !== OrderTransactionStates::STATE_PAID) {
return;
}
$transactionId = $event->getEntityId();
/** @var OrderTransactionEntity|null $transaction */
$transaction = $this->orderTransactionRepository->search(
(new Criteria([$transactionId]))
->addAssociation('order')
->addAssociation('order.salesChannel')
->addAssociation('order.lineItems')
->addAssociation('order.deliveries')
->addAssociation('order.deliveries.shippingOrderAddress.country')
->addAssociation('order.transactions.paymentMethod')
->addAssociation('order.billingAddress.country')
->addAssociation('order.orderCustomer'),
$event->getContext()
)->first();
if (!$transaction) {
return;
}
$order = $transaction->getOrder();
if (!$order) {
return;
}
/** @var SalesChannelEntity|null $salesChannel */
$salesChannel = $order->getSalesChannel();
if (!$salesChannel) {
$salesChannelId = $order->getSalesChannelId();
$salesChannel = $this->salesChannelRepository->search(
new Criteria([$salesChannelId]),
$event->getContext()
)->first();
if (!$salesChannel) {
return;
}
}
$salesChannelId = $salesChannel->getId();
$triggerState = (string) ($this->systemConfigService->get(
'DkcPentagastOrderExport.config.triggerState',
$salesChannelId
) ?? 'transaction_paid');
if ($triggerState !== 'transaction_paid') {
return;
}
$this->exportService->exportOrder($order, $salesChannel);
}
}