<?php
declare(strict_types=1);
namespace K3n\K3nFindConsultant\Storefront\Subscriber;
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Request;
use Shopware\Core\Checkout\Cart\Event\CheckoutOrderPlacedEvent;
use Shopware\Core\Checkout\Order\Aggregate\OrderAddress\OrderAddressCollection;
use Shopware\Core\Checkout\Order\Aggregate\OrderAddress\OrderAddressEntity;
use Shopware\Core\Checkout\Order\Event\OrderStateMachineStateChangeEvent;
use Shopware\Core\Checkout\Order\OrderEntity;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Shopware\Core\Framework\Event\EventData\MailRecipientStruct;
use Shopware\Core\System\StateMachine\Event\StateMachineStateChangeEvent;
use Shopware\Core\System\SystemConfig\SystemConfigService;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter;
use VioRepresentativeLogin\Entity\Agent\AgentEntity;
use VioRepresentativeLogin\VioRepresentativeLogin;
class ValidateSubscriber implements EventSubscriberInterface
{
/** @var EntityRepositoryInterface */
private $orderRepository;
/** @var SystemConfigService */
private $systemConfigService;
/**
* @var Client
*/
private $client;
private EntityRepositoryInterface $agentRepository;
public function __construct(
EntityRepositoryInterface $orderRepository,
SystemConfigService $systemConfigService,
EntityRepositoryInterface $agentRepository
) {
$this->orderRepository = $orderRepository;
$this->systemConfigService = $systemConfigService;
$this->client = new Client();
$this->agentRepository = $agentRepository;
}
public static function getSubscribedEvents(): array
{
return [
CheckoutOrderPlacedEvent::class => 'onCheckoutOrderPlaced',
];
}
/**
* @param CheckoutOrderPlacedEvent $event
*/
public function onCheckoutOrderPlaced(CheckoutOrderPlacedEvent $event): void
{
// skip if order already has a agent, because a mail to the
// rep will be send in this case from K3nExtendVioRepresentativeLogin.
// This function here a just needed for orders from farmers.
if($this->orderHasAgent($event->getOrder())) {
return;
}
$isDebugMode = $this->systemConfigService->get('K3nFindConsultant.config.debugMode');
if ($isDebugMode) {
$consultantEmail = $this->systemConfigService->get('K3nFindConsultant.config.debugModeEmail');
if(!$consultantEmail) {
return;
}
$consultantName = 'Test';
} else {
/** @var OrderEntity $order */
$order = $event->getOrder();
/** @var OrderAddressCollection $adresses */
$adresses = $order->getAddresses();
$zipcode = '';
/** @var OrderAddressEntity $address */
foreach ($adresses as $address) {
if ($address->getZipcode()) {
$zipcode = $address->getZipcode();
break;
}
}
if (!$zipcode) {
return;
}
$host = 'www.lgseeds.pl/storage-salesrep/api?search='.$zipcode;
$request = new Request(
'GET',
$host,
[
'Content-Type' => 'application/json',
'Accept: application/json'
]
);
$response = $this->client->send($request);
$response = $response->getBody()->getContents();
$resultArray = json_decode($response, true);
if (!$resultArray['success'] or empty($resultArray['data'])) {
return;
}
$consultantEmail = $resultArray['data'][0]['contact']['email'];
$consultantName = $resultArray['data'][0]['name'];
}
if(!$consultantEmail) {
return;
}
$this->assignAgentToOrder($consultantEmail, $event);
/** @var MailRecipientStruct $mailStruct */
$mailStruct = $event->getMailStruct();
$recipientArray = $mailStruct->getRecipients();
$recipientArray[$consultantEmail] = $consultantName;
$mailStruct->setRecipients($recipientArray);
}
public function assignAgentToOrder(string $agentEmail, CheckoutOrderPlacedEvent $event)
{
// skip if order already has a agent
if($this->orderHasAgent($event->getOrder())) {
return;
}
$criteria = new Criteria();
$criteria->addFilter(new EqualsFilter('email', $agentEmail));
/** @var AgentEntity|null $agent */
$agent = $this->agentRepository
->search($criteria, $event->getContext())
->first();
if ($agent && $agent instanceof AgentEntity) {
$this->orderRepository->update([[
'id' => $event->getOrderId(),
'customFields' => [VioRepresentativeLogin::AGENT_FIELD => $agent->getId()]
]], $event->getContext());
}
}
public function orderHasAgent(OrderEntity $order): bool
{
$customFields = $order->getCustomFields();
return is_array($customFields) && array_key_exists(VioRepresentativeLogin::AGENT_FIELD, $customFields) && $customFields[VioRepresentativeLogin::AGENT_FIELD];
}
}