<?php declare(strict_types=1);
namespace WabsAuftragsdatenSync\Subscriber;
use Exception;
use Psr\Log\LoggerInterface;
use Shopware\Core\Checkout\Customer\CustomerEntity;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface;
use Shopware\Storefront\Page\Checkout\Finish\CheckoutFinishPageLoadedEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use WabsAuftragsdatenSync\Services\WabsAuftragsdatenSyncService;
class WabsAuftragsdatenSyncSubscriber implements EventSubscriberInterface
{
/** @var WabsAuftragsdatenSyncService $wabsAuftragsdatenSyncService */
private $wabsAuftragsdatenSyncService;
/** @var LoggerInterface $logger */
private $logger;
/** @var EntityRepositoryInterface */
private $orderCustomerRepository;
public function __construct(
WabsAuftragsdatenSyncService $wabsAuftragsdatenSyncService,
LoggerInterface $logger,
\Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface $orderCustomerRepository
) {
$this->wabsAuftragsdatenSyncService = $wabsAuftragsdatenSyncService;
$this->logger = $logger;
$this->orderCustomerRepository = $orderCustomerRepository;
}
public static function getSubscribedEvents(): array
{
return [
CheckoutFinishPageLoadedEvent::class => 'onCheckoutFinish'
];
}
public function onCheckoutFinish(CheckoutFinishPageLoadedEvent $event)
{
try {
$orderCustomer = $event->getPage()->getOrder()->getOrderCustomer();
$customerId = $orderCustomer->getCustomerId();
/** @var CustomerEntity $customer */
$customer = $this->wabsAuftragsdatenSyncService->getCustomerById($customerId);
$order = [
"id" => $event->getPage()->getOrder()->getId(),
"customFields" => [
"igm_mbs_order_customer_group" => $customer->getGroupId()
]
];
$this->wabsAuftragsdatenSyncService->saveGroupIdOnOrder($order);
} catch (Exception $exception) {
$this->logger->error("Could not save CustomerGroupId on Order!");
}
try {
$customerCustomFields = $customer->getCustomFields();
if (isset($customerCustomFields['customerDistrict'])) {
$data = [
'id' => $orderCustomer->getId(),
'customFields' => ['customerDistrict' => $customerCustomFields['customerDistrict']]
];
$this->orderCustomerRepository->update([$data], $event->getContext());
}
} catch (Exception $exception) {
$this->logger->error("Could not save customerDistrict on OrderCustomer!");
}
}
}