<?php
namespace B2bSellersCore\Components\Order\Subscriber;
use B2bSellersCore\Components\B2bPlatform\Traits\B2bContextTrait;
use Shopware\Core\Checkout\Cart\Event\CheckoutOrderPlacedCriteriaEvent;
use B2bSellersCore\Components\Order\Service\OrderMailRecipientServiceInterface;
use Shopware\Core\Checkout\Cart\Event\CheckoutOrderPlacedEvent;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepository;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class OrderPlacedSubscriber implements EventSubscriberInterface
{
use B2bContextTrait;
private EntityRepository $customerRepository;
private EntityRepository $employeeRepository;
private OrderMailRecipientServiceInterface $orderMailRecipientService;
public function __construct(
EntityRepository $customerRepository,
EntityRepository $employeeRepository,
OrderMailRecipientServiceInterface $orderMailRecipientService
)
{
$this->customerRepository = $customerRepository;
$this->employeeRepository = $employeeRepository;
$this->orderMailRecipientService = $orderMailRecipientService;
}
public static function getSubscribedEvents(): array
{
return [
CheckoutOrderPlacedEvent::class => [
['replaceMailRecipients', -10],
['addOrderExtensions'],
['addEmployeeData']
],
CheckoutOrderPlacedCriteriaEvent::class => 'addB2bExtensionAssociations'
];
}
public function replaceMailRecipients(CheckoutOrderPlacedEvent $event): void
{
$recipients = $this->orderMailRecipientService->getRecipientsByOrder($event->getOrder(), $event->getContext(), true);
$event->getMailStruct()->setRecipients($recipients->getRecipients());
}
public function addOrderExtensions(CheckoutOrderPlacedEvent $event): void
{
$customFields = $event->getOrder()->getCustomFields();
if (empty($customFields['b2b_order_sales_representative_id'])) {
return;
}
$customer = $this->customerRepository->search(new Criteria([$customFields['b2b_order_sales_representative_id']]), $event->getContext())->first();
if (empty($customer)) {
return;
}
$event->getOrder()->addExtension('salesRepresentative', $customer);
}
public function addEmployeeData(CheckoutOrderPlacedEvent $event): void
{
$customFields = $event->getOrder()->getCustomFields();
if (empty($customFields['b2b_order_customer_employee_id'])) {
return;
}
$employee = $this->employeeRepository->search(new Criteria([$customFields['b2b_order_customer_employee_id']]), $event->getContext())->first();
if (empty($employee)) {
return;
}
$event->getOrder()->getOrderCustomer()->addExtension('employee', $employee);
}
public function addB2bExtensionAssociations(CheckoutOrderPlacedCriteriaEvent $event)
{
$event->getCriteria()->addAssociations([
'b2bOrderExtension.employee',
'b2bOrderExtension.salesRepresentative'
]);
}
}