<?php declare(strict_types=1);
namespace Shopware\B2B\Budget\BridgePlatform;
use Shopware\B2B\Budget\Framework\BudgetService;
use Shopware\B2B\Budget\Framework\InsufficientBudgetException;
use Shopware\B2B\Currency\Framework\CurrencyService;
use Shopware\B2B\Order\BridgePlatform\OrderContextStateChangedEvent;
use Shopware\B2B\Order\Framework\OrderContextRepository;
use Shopware\B2B\StoreFrontAuthentication\Framework\AuthenticationService;
use Shopware\Core\Checkout\Cart\Event\CheckoutOrderPlacedEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class BudgetTransactionOrderSync implements EventSubscriberInterface
{
/**
* @var AuthenticationService
*/
private $authenticationService;
/**
* @var CurrencyService
*/
private $currencyService;
/**
* @var OrderContextRepository
*/
private $orderContextRepository;
/**
* @var BudgetService
*/
private $budgetService;
public static function getSubscribedEvents(): array
{
return [
CheckoutOrderPlacedEvent::class => 'addTransaction',
OrderContextStateChangedEvent::class => 'updateTransactionStatus',
];
}
public function __construct(
AuthenticationService $authenticationService,
OrderContextRepository $orderContextRepository,
BudgetService $budgetService,
CurrencyService $currencyService
) {
$this->authenticationService = $authenticationService;
$this->currencyService = $currencyService;
$this->orderContextRepository = $orderContextRepository;
$this->budgetService = $budgetService;
}
public function addTransaction(CheckoutOrderPlacedEvent $event): void
{
if (!$this->authenticationService->isB2b()) {
return;
}
$order = $event->getOrder();
$currencyContext = $this->currencyService->createCurrencyContext();
$identity = $this->authenticationService->getIdentity();
$amount = $order->getAmountNet() + $order->getShippingTotal();
$orderContext = $this->orderContextRepository
->fetchOneOrderContextByOrderNumber($order->getOrderNumber());
try {
$this->budgetService
->addTransaction($orderContext, $amount, $currencyContext, $identity->getOwnershipContext());
} catch (InsufficientBudgetException $e) {
if (!$identity->isSuperAdmin()) {
throw $e;
}
}
}
public function updateTransactionStatus(OrderContextStateChangedEvent $event): void
{
$this->budgetService->updateTransactionStatus($event->getOrderContext());
}
}