<?php
namespace App\Salesforce\EventListener;
use App\Api\Event\ImportEvent;
use App\Api\Event\ImportEvents;
use App\Entity\Sale;
use App\Entity\Vehicle;
use App\Repository\SaleEventRepository;
use App\Repository\VehicleRepository;
use App\Salesforce\Api\ClientInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
/**
* SalesForce Event listener for the Import events.
*/
class SalesForceImportListener implements EventSubscriberInterface
{
public function __construct(private readonly ClientInterface $sfClient, private readonly VehicleRepository $vehicleRepository, private readonly SaleEventRepository $saleEventRepository)
{
}
public static function getSubscribedEvents()
{
return [
ImportEvents::DATA_LAST => 'onLastData',
];
}
/**
* DO NOT call $sale->getEvents() or any other form to get the events here, it seems Doctrine isn't fully done with them
* Use queries from the repository, that works.
*/
public function onLastData(ImportEvent $event): void
{
$object = $event->getObject();
if (!$object instanceof Vehicle) {
return;
}
$sale = $object->getSale();
$events = '';
if (Sale::TYPE_PHYSICAL === $sale->getType()) {
$events = join(' / ',
array_map(
fn ($e) => $e->getStartTime().' - '.$e->getTitle()->getName(),
$this->saleEventRepository->findAllInSales([$sale])
)
);
}
$sSale = array_filter([
'ExternalId__c' => $sale->getId(),
'NbrVehiculesProposes__c' => $this->vehicleRepository->countAllActiveBySale($sale),
'Sous_vente_physique_V2__c' => $events,
]);
$this->sfClient->initiate()->upsert('ExternalId__c', (object) $sSale, 'SessionVente__c');
}
}