<?php declare(strict_types=1);
namespace AbmAdjustments\Subscriber;
use Shopware\Core\Framework\Event\BusinessEventCollector;
use Shopware\Core\Framework\Event\BusinessEventCollectorEvent;
use AbmAdjustments\Flow\OrderDeliveryShippedEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Shopware\Core\Framework\Event\MailRecipientStruct;
use Shopware\Core\Checkout\Cart\Event\CheckoutOrderPlacedEvent;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepository;
class OrderTriggerSubscriber implements EventSubscriberInterface
{
private BusinessEventCollector $businessEventCollector;
private EntityRepository $orderRepository;
public function __construct(BusinessEventCollector $businessEventCollector, EntityRepository $orderRepository) {
$this->businessEventCollector = $businessEventCollector;
$this->orderRepository = $orderRepository;
}
public static function getSubscribedEvents()
{
return [
BusinessEventCollectorEvent::NAME => ['onAddOrderDeliveryShippedEvent', 1000],
CheckoutOrderPlacedEvent::class => 'onOrderPlaced'
];
}
public function onAddOrderDeliveryShippedEvent(BusinessEventCollectorEvent $event): void
{
$collection = $event->getCollection();
$definition = $this->businessEventCollector->define(OrderDeliveryShippedEvent::class);
if (!$definition) {
return;
}
$collection->set($definition->getName(), $definition);
}
public function onOrderPlaced(CheckoutOrderPlacedEvent $event): void
{
$latestReleaseDate = null;
$hasPreorderItem = false;
foreach ($event->getOrder()->getLineItems() as $lineItem) {
$payload = $lineItem->getPayload();
if (isset($payload['releaseDate'])) {
$releaseDate = new \DateTime($payload['releaseDate']);
$now = new \DateTime();
if ($releaseDate > $now) {
$hasPreorderItem = true;
if ($latestReleaseDate === null || $releaseDate > $latestReleaseDate) {
$latestReleaseDate = $releaseDate;
}
}
}
}
if ($hasPreorderItem && $latestReleaseDate !== null) {
$formattedDate = $latestReleaseDate->format('d.m.Y');
$existingComment = $event->getOrder()->getCustomerComment() ?? '';
$newComment = trim($existingComment . "\n" . ' Vorbestellung mit Datum: ' . $formattedDate);
$this->orderRepository->update([
[
'id' => $event->getOrderId(),
'customerComment' => $newComment
]
], $event->getContext());
}
}
}