<?php declare(strict_types=1);
namespace NieMehrStreichenTheme\Service;
use Shopware\Core\Checkout\Order\OrderEvents;
use Shopware\Core\Framework\DataAbstractionLayer\Event\EntityWrittenEvent;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepository;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use GuzzleHttp\Client;
class ListenToOrderChanges implements EventSubscriberInterface
{
private $restClient;
private EntityRepository $repository;
private OrderTransactionRepository $OrderTransactionRepository;
public function __construct(
EntityRepository $repository,
EntityRepository $orderTransactionRepository
) {
$this->repository = $repository;
$this->orderTransactionRepository = $orderTransactionRepository;
$this->restClient = new Client();
}
public static function getSubscribedEvents(): array
{
return [
OrderEvents::ORDER_WRITTEN_EVENT => 'notifyNewOrderToContactPro',
OrderEvents::ORDER_TRANSACTION_WRITTEN_EVENT => 'notifyPayedOrderToContactPro',
];
}
public function notifyPayedOrderToContactPro(EntityWrittenEvent $event): void
{
$criteria = new Criteria([$event->getIds()[0]]);
$order = $this->orderTransactionRepository->search($criteria, $event->getContext())->first();
if($order->getStateId() == "06be24d74fe14faeaa7de5f153fdd847"){ // paid
$this->sendNotifyToContactPro($event, $order->getOrderId());
}
}
public function notifyNewOrderToContactPro(EntityWrittenEvent $event): void
{
foreach ($event->getWriteResults() as $writeResult) {
$orderID = $writeResult->getPrimaryKey();
$this->sendNotifyToContactPro($event, $orderID);
}
}
public function sendNotifyToContactPro($event, $orderID) {
$criteria = new Criteria([$orderID]);
$criteria->addAssociation('transactions');
$criteria->addAssociation('orderCustomer');
$criteria->addAssociation('lineItems');
$order = $this->repository->search($criteria, $event->getContext())->first();
$request = new \GuzzleHttp\Psr7\Request(
'POST',
'https://objednavky-transform.animatec.cz/transform/shopware/niemehr-order',
[
'Content-Type' => 'application/json',
'Authorization' => 'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJrMDRzajNnOXU4ZzR2Nm10bWZsNWJuMXYyNyIsImlhdCI6MTY4NTQzNTU0NSwiZXhwIjpudWxsfQ.jp9ZTZRotWIeSBagO8zBWK7NbegM9yPYYbJuh0Y5mW4',
],
json_encode([
'external_id' => $order->orderNumber,
])
);
$this->restClient->send($request);
}
}