<?php
namespace B2bSellersCore\Components\CustomerActivity\Subscriber;
use B2bSellersCore\Components\B2bPlatform\Traits\B2bContextTrait;
use B2bSellersCore\Components\CustomerActivity\Aggregate\CustomerActivityType\ActivityTypes;
use B2bSellersCore\Components\CustomerActivity\Service\ActivityServiceInterface;
use Shopware\Core\Checkout\Cart\Event\CheckoutOrderPlacedEvent;
use Shopware\Core\Checkout\Order\OrderDefinition;
use Shopware\Core\PlatformRequest;
use Shopware\Core\System\SalesChannel\Context\SalesChannelContextServiceInterface;
use Shopware\Core\System\SalesChannel\Context\SalesChannelContextServiceParameters;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RequestStack;
class OrderPlacedSubscriber implements EventSubscriberInterface
{
use B2bContextTrait;
private ActivityServiceInterface $activityService;
private SalesChannelContextServiceInterface $contextService;
private RequestStack $requestStack;
public const ACTIVITY_CREATE_ORDER_PLACED_SNIPPET = 'b2bPlatform.activity.order.placed';
public function __construct(
ActivityServiceInterface $activityService,
SalesChannelContextServiceInterface $channelContextService,
RequestStack $requestStack
)
{
$this->activityService = $activityService;
$this->contextService = $channelContextService;
$this->requestStack = $requestStack;
}
public static function getSubscribedEvents(): array
{
return [
CheckoutOrderPlacedEvent::class => 'addOrderPlacedActivity'
];
}
public function addOrderPlacedActivity(CheckoutOrderPlacedEvent $event): void
{
$request = $this->requestStack->getCurrentRequest();
if (!isset($request)) {
return;
}
if (!$request->headers->has(PlatformRequest::HEADER_CONTEXT_TOKEN)) {
return;
}
$contextToken = $request->headers->get(PlatformRequest::HEADER_CONTEXT_TOKEN);
$salesChannelContext = $this->contextService->get(
new SalesChannelContextServiceParameters(
$event->getSalesChannelId(),
$contextToken,
$event->getContext()->getLanguageId(),
$event->getContext()->getCurrencyId()
)
);
if (!$this->hasB2bPlatformContext($salesChannelContext)) {
return;
}
if ($this->isLoggedInAsSalesRepresentative($salesChannelContext)) {
return;
}
try {
$this->activityService->addActivity(
ActivityTypes::ACTIVITY_TYPE_ORDER,
'',
self::ACTIVITY_CREATE_ORDER_PLACED_SNIPPET,
OrderDefinition::ENTITY_NAME,
$event->getOrder()->getId(),
$salesChannelContext
);
} catch (\Exception $exception) {
}
}
}