<?php declare(strict_types=1);
namespace Dtgs\DeliveryDate\Subscriber;
use DateTime;
use Shopware\Core\Checkout\Cart\Event\CheckoutOrderPlacedEvent;
use Shopware\Core\Checkout\Order\OrderEntity;
use Shopware\Core\Framework\Context;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface;
use Shopware\Core\System\SystemConfig\SystemConfigService;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Session\Session;
class OrderSubscriber implements EventSubscriberInterface
{
/**
* @var SystemConfigService
*/
private $systemConfigService;
/**
* @var EntityRepositoryInterface
*/
private $orderRepository;
/**
* @var Session
*/
private $session;
public function __construct(SystemConfigService $systemConfigService,
EntityRepositoryInterface $orderRepository,
Session $session)
{
$this->systemConfigService = $systemConfigService;
$this->orderRepository = $orderRepository;
$this->session = $session;
}
public static function getSubscribedEvents(): array
{
return[
CheckoutOrderPlacedEvent::class => 'onOrderPlaced',
];
}
/**
* Event für alle Seiten
*
* @param CheckoutOrderPlacedEvent $event
* @throws \Exception
*/
public function onOrderPlaced(CheckoutOrderPlacedEvent $event)
{
$deliveryDateConfig = $this->systemConfigService->get('DtgsDeliveryDateSw6.config', $event->getSalesChannelId());
$deliveryDateFormat = ($deliveryDateConfig['deliveryDateEnableTimePicker']) ? 'd.m.Y H:i' : 'd.m.Y';
$order = $event->getOrder();
$orderId = $order->getId();
$context = $event->getContext();
$deliveryDate = $this->session->get('deliverydate', null);
if($deliveryDate) {
$this->orderRepository->upsert([[
'id' => $orderId,
'customFields' => ['dtgs_delivery_date' => $deliveryDate]
]], $context);
//Set as earliest shipping date
if(isset($deliveryDateConfig['deliveryDateSetAsEarliestDate']) && $deliveryDateConfig['deliveryDateSetAsEarliestDate']) {
$this->setAsEarliestShippingDate($order, $deliveryDate, $deliveryDateFormat, $context);
}
}
$existingCustomFields = $event->getOrder()->getCustomFields();
if(!$existingCustomFields) $existingCustomFields = [];
//add delivery date
$deliverydateCustomFields = [
'deliveryDate' => $deliveryDate
];
$mergedCustomFields = array_merge($existingCustomFields, $deliverydateCustomFields);
$event->getOrder()->setCustomFields($mergedCustomFields);
//unset session key
$this->session->remove('deliverydate');
}
/**
* since V6.0.6
*
* @param OrderEntity $order
* @param $deliveryDate
* @param string $dateFormat
* @param Context $context
*/
private function setAsEarliestShippingDate(OrderEntity $order, $deliveryDate, string $dateFormat, Context $context)
{
$delivery = $order->getDeliveries()->first();
$this->orderRepository->upsert([[
'id' => $order->getId(),
'deliveries' => [
[
'id' => $delivery->getId(),
'shippingDateEarliest' => DateTime::createFromFormat($dateFormat, $deliveryDate)
]
],
]], $context);
}
}