<?php
namespace Wbfk\MultipleDeliveries\Subscriber;
use Shopware\Core\Checkout\Order\Aggregate\OrderDelivery\OrderDeliveryEntity;
use Shopware\Core\Checkout\Order\Api\OrderActionController;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepository;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Sorting\FieldSorting;
use Shopware\Core\System\StateMachine\Event\StateMachineStateChangeEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Request;
class OrderDeliveryStateChangeEventSubscriber implements EventSubscriberInterface
{
public function __construct(
private readonly EntityRepository $orderDeliveryRepository,
private readonly OrderActionController $orderActionController,
) {
}
public static function getSubscribedEvents(): array
{
return [
'state_machine.order_delivery.state_changed' => 'onOrderDeliveryStateChange',
];
}
public function onOrderDeliveryStateChange(StateMachineStateChangeEvent $event): void
{
$deliveryId = $event->getTransition()->getEntityId();
// Get the order based on the delivery id
// Check if the delivery is a partial delivery, if then check main delivery state is changed to partially delivered
// if not then change main delivery state to partially delivered
$criteria = new Criteria([$deliveryId]);
$criteria->addAssociation('order.deliveries');
$criteria->getAssociation('order.deliveries')->addSorting(new FieldSorting('createdAt'));
/** @var OrderDeliveryEntity $orderDelivery */
$orderDelivery = $this->orderDeliveryRepository->search($criteria, $event->getContext())->first();
if ($orderDelivery->getOrder()->getDeliveries()->count() === 1) {
return;
}
/** @var OrderDeliveryEntity $mainDelivery */
$mainDelivery = $orderDelivery->getOrder()->getDeliveries()->first();
if ($mainDelivery->getId() === $deliveryId ||
$mainDelivery->getStateMachineState()->getTechnicalName() === 'shipped_partially' ||
$orderDelivery->getStateMachineState()->getTechnicalName() !== 'shipped') {
return;
}
$this->orderActionController->orderDeliveryStateTransition(
$mainDelivery->getId(),
'ship_partially',
new Request(),
$event->getContext(),
);
}
}