<?php
declare(strict_types=1);
namespace WbfkExtensions\Subscriber;
use Shopware\Core\Checkout\Customer\CustomerEntity;
use Shopware\Core\Checkout\Customer\CustomerEvents;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Shopware\Core\Framework\Event\DataMappingEvent;
use Shopware\Core\System\SalesChannel\SalesChannelEntity;
use Shopware\Core\System\SystemConfig\SystemConfigService;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class AutoApproveOrSetFallbackB2BCustomerGroup implements EventSubscriberInterface
{
public function __construct(
private readonly SystemConfigService $systemConfigService,
private readonly EntityRepositoryInterface $salesChannelRepository,
) {
}
public static function getSubscribedEvents(): array
{
return [
CustomerEvents::MAPPING_REGISTER_CUSTOMER => 'customerGroupAssignmentWorkflow',
CustomerEvents::MAPPING_CUSTOMER_PROFILE_SAVE => 'customerGroupAssignmentWorkflow',
];
}
public function customerGroupAssignmentWorkflow(DataMappingEvent $event): void
{
if ($event->getInput()->get('accountType') === CustomerEntity::ACCOUNT_TYPE_PRIVATE) {
$this->setDefaultCustomerGroup($event);
return;
}
$requestedCustomerGroupId = $event->getInput()->get('requestedGroupId');
if (!$requestedCustomerGroupId) {
return;
}
if ($this->isAutoApprovedB2BCustomerGroup($requestedCustomerGroupId)) {
$this->autoApproveB2BCustomerGroup($event, $requestedCustomerGroupId);
return;
}
$this->setFallBackB2BCustomerGroup($event);
}
private
function autoApproveB2BCustomerGroup(
DataMappingEvent $event,
string $requestedCustomerGroupId
): void {
$output = $event->getOutput();
$output['groupId'] = $requestedCustomerGroupId;
$output['requestedGroupId'] = null;
$event->setOutput($output);
}
public
function isAutoApprovedB2BCustomerGroup(
string $requestedCustomerGroupId
): bool {
$autoApprovedB2BCustomerGroupIds = $this->systemConfigService->get(
'WbfkExtensions.config.autoApprovedB2BCustomerGroupIds'
);
return in_array($requestedCustomerGroupId, $autoApprovedB2BCustomerGroupIds);
}
private
function setFallBackB2BCustomerGroup(
DataMappingEvent $event
): void {
$input = $event->getInput();
$output = $event->getOutput();
$output['groupId'] = $this->systemConfigService->get('WbfkExtensions.config.fallbackB2BCustomerGroupId');
$output['requestedGroupId'] = $input->get('requestedGroupId');
$event->setOutput($output);
}
private function setDefaultCustomerGroup(DataMappingEvent $event): void
{
$criteria = new Criteria([$event->getContext()->getSource()->getSalesChannelId()]);
/** @var SalesChannelEntity $salesChannel */
$salesChannel = $this->salesChannelRepository->search($criteria, $event->getContext())->first();
$output = $event->getOutput();
$output['groupId'] = $salesChannel->getCustomerGroupId();
$output['requestedGroupId'] = null;
$event->setOutput($output);
}
}