custom/plugins/WbfkMultipleDeliveries/src/Subscriber/OrderDeliveryStateChangeEventSubscriber.php line 30

Open in your IDE?
  1. <?php
  2. namespace Wbfk\MultipleDeliveries\Subscriber;
  3. use Shopware\Core\Checkout\Order\Aggregate\OrderDelivery\OrderDeliveryEntity;
  4. use Shopware\Core\Checkout\Order\Api\OrderActionController;
  5. use Shopware\Core\Framework\DataAbstractionLayer\EntityRepository;
  6. use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
  7. use Shopware\Core\Framework\DataAbstractionLayer\Search\Sorting\FieldSorting;
  8. use Shopware\Core\System\StateMachine\Event\StateMachineStateChangeEvent;
  9. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  10. use Symfony\Component\HttpFoundation\Request;
  11. class OrderDeliveryStateChangeEventSubscriber implements EventSubscriberInterface
  12. {
  13.     public function __construct(
  14.         private readonly EntityRepository $orderDeliveryRepository,
  15.         private readonly OrderActionController $orderActionController,
  16.     ) {
  17.     }
  18.     public static function getSubscribedEvents(): array
  19.     {
  20.         return [
  21.             'state_machine.order_delivery.state_changed' => 'onOrderDeliveryStateChange',
  22.         ];
  23.     }
  24.     public function onOrderDeliveryStateChange(StateMachineStateChangeEvent $event): void
  25.     {
  26.         $deliveryId $event->getTransition()->getEntityId();
  27.         // Get the order based on the delivery id
  28.         // Check if the delivery is a partial delivery, if then check main delivery state is changed to partially delivered
  29.         // if not then change main delivery state to partially delivered
  30.         $criteria = new Criteria([$deliveryId]);
  31.         $criteria->addAssociation('order.deliveries');
  32.         $criteria->getAssociation('order.deliveries')->addSorting(new FieldSorting('createdAt'));
  33.         /** @var OrderDeliveryEntity $orderDelivery */
  34.         $orderDelivery $this->orderDeliveryRepository->search($criteria$event->getContext())->first();
  35.         if ($orderDelivery->getOrder()->getDeliveries()->count() === 1) {
  36.             return;
  37.         }
  38.         /** @var OrderDeliveryEntity $mainDelivery */
  39.         $mainDelivery $orderDelivery->getOrder()->getDeliveries()->first();
  40.         if ($mainDelivery->getId() === $deliveryId ||
  41.             $mainDelivery->getStateMachineState()->getTechnicalName() === 'shipped_partially' ||
  42.             $orderDelivery->getStateMachineState()->getTechnicalName() !== 'shipped') {
  43.             return;
  44.         }
  45.         $this->orderActionController->orderDeliveryStateTransition(
  46.             $mainDelivery->getId(),
  47.             'ship_partially',
  48.             new Request(),
  49.             $event->getContext(),
  50.         );
  51.     }
  52. }