<?php
namespace App\Salesforce\EventListener;
use App\Dictionary\DictionaryMap;
use App\Entity\PrivateUser;
use App\Entity\ProUser;
use App\Entity\User;
use App\Event\UserEvents;
use App\Mailer\TranslatableMailer;
use App\Salesforce\Api\ClientInterface;
use App\Salesforce\Object\DataHydrator;
use App\Salesforce\Utils\Constants;
use App\Salesforce\Utils\Formatter;
use App\Twig\Extension\CountryExtension;
use Doctrine\ORM\EntityManagerInterface;
use FOS\UserBundle\Event\FilterUserResponseEvent;
use FOS\UserBundle\Event\UserEvent;
use FOS\UserBundle\FOSUserEvents;
use Psr\Log\LoggerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
use Symfony\Component\Security\Http\SecurityEvents;
use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
/**
* SalesForce Event listener for the FOS and user-related kernel events.
*/
class SalesForceFOSListener implements EventSubscriberInterface
{
public function __construct(
private readonly ClientInterface $sfClient,
private readonly EntityManagerInterface $em,
private readonly RouterInterface $router,
private readonly DictionaryMap $dictionaryMap,
private readonly DataHydrator $hydrator,
private readonly EventDispatcherInterface $eventDispatcher,
private readonly TranslatableMailer $mailer,
private readonly LoggerInterface $salesforceLogger,
private readonly LoggerInterface $salesforceDetailLogger,
private readonly string $baseUri,
) {
}
public static function getSubscribedEvents()
{
return [
FOSUserEvents::REGISTRATION_COMPLETED => 'onUserRegistrationComplete',
FOSUserEvents::REGISTRATION_CONFIRMED => 'onUserRegistrationConfirmed',
SecurityEvents::INTERACTIVE_LOGIN => 'onUserInteractiveLogin',
UserEvents::EDIT_COMPLETED => 'onUserProfileEditComplete',
UserEvents::UPDATE_USER_BY_SERVICE_BUS => 'onUserProfileEditComplete',
UserEvents::UPDATE_ID_SALESFORCE => 'onUserProfileEditComplete',
UserEvents::CREATE_USER_BY_SERVICE_BUS => 'onUserCustomerPortalComplete',
UserEvents::CONVERT_COMPLETED => 'onUserConversionComplete',
UserEvents::DELETE_COMPLETED => 'onUserDeletionComplete',
UserEvents::OPTIN_CHANGED => 'onOptinChanged',
UserEvents::CHANGE_COMPANY => 'onChangeCompany',
UserEvents::CATCH_UP => 'onUserRegistrationComplete',
];
}
/**
* FOSUser Event REGISTRATION_COMPLETED handling method.
*
* @param FilterUserResponseEvent $evt - The event
*/
public function onUserRegistrationComplete(FilterUserResponseEvent $evt): void
{
$this->sfClient->initiate();
$user = $evt->getUser();
if ($user instanceof ProUser) {
$this->registerProUser($user);
} elseif ($user instanceof User) {
$this->registerUser($user);
}
}
/**
* FOSUser Event REGISTRATION_CONFIRMED handling method.
*
* @param FilterUserResponseEvent $evt - The event
*/
public function onUserRegistrationConfirmed(FilterUserResponseEvent $evt): void
{
$this->sfClient->initiate();
$user = $evt->getUser();
if ($user instanceof ProUser) {
if (null !== $user->getSfLeadId()) {
$data = $this->sfClient->convert($user->getSfLeadId(), $user->getId());
if (!empty($data)) {
$user->setSfAccountId($data[0]->accountId);
$user->setSfContactId($data[0]->contactId);
$user->setSfLeadId(null);
$this->em->flush();
$this->eventDispatcher->dispatch(new UserEvent($user), UserEvents::ID_SEND_USER_BY_SALESFORCE);
}
}
} else {
if (in_array(
strtolower($user->getCountry()),
[CountryExtension::COUNTRY_PORTUGAL]
)) {
if (null !== $user->getSfLeadId()) {
$data = $this->sfClient->convert($user->getSfLeadId(), $user->getId());
if (!empty($data)) {
$user->setSfAccountId($data[0]->accountId);
$user->setSfLeadId(null);
$this->em->flush();
}
}
} else {
$sUser = [
'Id' => $user->getSfAccountId(),
'Validation__c' => 'Validé',
];
$this->sfClient->upsert('Id', (object) $sUser, 'Account');
}
}
}
/**
* Symfony Event security.interactive_login handling method.
*
* @param InteractiveLoginEvent $evt - The event
*/
public function onUserInteractiveLogin(InteractiveLoginEvent $evt): void
{
$this->sfClient->initiate();
$user = $evt->getAuthenticationToken()->getUser();
// Temp removal of society interaction with SF
if ($user instanceof PrivateUser && $user->isSociety()) {
return;
}
if ($user instanceof ProUser) {
if (null === $user->getSfAccountId() || null === $user->getSfContactId()) {
if (false === $exists = $this->sfClient->exists('Contact', ['ExternalId__c' => $user->getEmail()])) {
return;
}
$user->setSfAccountId($exists['accId'] ?? null);
$user->setSfContactId($exists['id']);
$this->em->flush();
}
} else {
if (null === $user->getSfAccountId()) {
if (false === $exists = $this->sfClient->exists('Account', ['ExternalId__c' => $user->getEmail()])) {
return;
}
$user->setSfAccountId($exists['id']);
$this->em->flush();
}
}
if ($user instanceof ProUser) {
$sUser = $this->sfClient->findOne([
'LastName',
'FirstName',
'Phone',
'MobilePhone',
'Account.Name',
'Account.NoTVAIntracommunautaire__c',
'Account.Siret__c',
'Account.Fax',
'Account.BillingStreet',
'Account.BillingCity',
'Account.BillingCountry',
'Account.BillingPostalCode',
'Account.Statut__c',
'Account.Banni_par_le_commercial__c',
'Account.Owner.Email',
],
'Contact',
['Id' => $user->getSfContactId()]
);
$upSContact = array_filter([
'Id' => $user->getSfContactId(),
'Last_login__c' => Formatter::date($user->getLastLogin()),
]);
$this->sfClient->upsert('Id', (object) $upSContact, 'Contact');
$this->salesforceDetailLogger->info(sprintf('SF %s, Contact | Connection: %s %s', __FUNCTION__, $user->getSfContactId(), json_encode($upSContact, JSON_PRETTY_PRINT)));
$upSAccount = array_filter([
'Id' => $user->getSfAccountId(),
'Last_login__c' => Formatter::date($user->getLastLogin()),
]);
$this->sfClient->upsert('Id', (object) $upSAccount, 'Account');
$this->salesforceDetailLogger->info(sprintf('SF %s, Account | Connection: %s %s', __FUNCTION__, $user->getSfAccountId(), json_encode($upSAccount, JSON_PRETTY_PRINT)));
} else {
$sUser = $this->sfClient->findOne([
'LastName',
'FirstName',
'Phone',
'Fax',
'PersonMailingStreet',
'PersonMailingCity',
'PersonMailingCountry',
'PersonMailingPostalCode',
'Inscription_Newsletter__c',
'CanauxActifs__c',
'DateInscriptionWeb__c',
],
'Account',
['Id' => $user->getSfAccountId()]
);
$upSUser = array_filter([
'Id' => $user->getSfAccountId(),
'DateInscriptionWeb__c' => empty($sUser->DateInscriptionWeb__c) ? Formatter::date($user->getCreatedAt()) : null,
'DerniereVisite__c' => Formatter::date($user->getLastLogin()),
]);
$this->sfClient->upsert('Id', (object) $upSUser, 'Account');
$this->salesforceDetailLogger->info(sprintf('SF %s, Account | Connection: %s %s', __FUNCTION__, $user->getSfAccountId(), json_encode($upSUser, JSON_PRETTY_PRINT)));
}
$this->hydrator->hydrate($sUser, $user);
$this->em->flush();
}
/**
* Custom event EDIT_COMPLETED handling method.
* Custom event UPDATE_USER_BY_SERVICE_BUS handling method.
* Custom event UPDATE_ID_SALESFORCE handling method.
*
* @param UserEvent $evt - The event
*/
public function onUserProfileEditComplete(UserEvent $evt): void
{
$user = $evt->getUser();
// Temp removal of society interaction with SF
if ($user instanceof PrivateUser && $user->isSociety()) {
return;
}
if (null === $user->getSfAccountId()) {
return;
}
if ($user instanceof ProUser) {
$shippingAddress = !$user->getShippingAddresses()->isEmpty() ? $user->getShippingAddresses()->first() : false;
$sAccount = array_filter([
'Name' => $user->getCompany(),
'NoTVAIntracommunautaire__c' => $user->getVAT(),
'BillingPostalCode' => $user->getZipCode(),
'BillingStreet' => $user->getAddress(),
'BillingCity' => $user->getCity(),
'ShippingPostalCode' => $shippingAddress ? $shippingAddress->getZipCode() : null,
'ShippingStreet' => $shippingAddress ? $shippingAddress->getAddress() : null,
'ShippingCity' => $shippingAddress ? $shippingAddress->getCity() : null,
'Inscription_Newsletter__c' => Formatter::bool($user->getNewsletter()),
'Date_Heure_Inscription_Newsletter__c' => Formatter::date($user->getLastOptinChangeDate()),
'Siret__c' => null !== $user->getCompanyId() ? $user->getSiret() : null,
'N_de_Siren__c' => null !== $user->getCompanyId() ? $user->getSiren() : null,
'Id' => $user->getSfAccountId(),
]);
$sContact = array_filter([
'Email' => $user->getEmail(),
'Phone' => $user->getPhone(),
'MobilePhone' => $user->getMobile(),
'FirstName' => $user->getFirstname(),
'LastName' => $user->getLastname(),
'ExternalId__c' => $user->getEmail(),
'Id' => $user->getSfContactId(),
]);
} else {
if ('PT' === $user->getCountry()) {
$sAccount = array_filter([
'LastName' => $user->getLastname(),
'FirstName' => $user->getFirstname(),
'PersonEmail' => $user->getEmail(),
'PersonMailingStreet' => $user->getAddress(),
'PersonMailingPostalCode' => $user->getZipCode(),
'PersonMailingCity' => $user->getCity(),
'PersonMailingCountry' => $this->getCountryFrenchName($user->getCountry()),
'Phone' => $user->getPhone(),
'PersonMobilePhone' => $user->getMobile(),
'ExternalId__c' => $user->getEmail(),
'Id' => $user->getSfAccountId(),
]);
} else {
$sAccount = array_filter([
'LastName' => $user->getLastname(),
'FirstName' => $user->getFirstname(),
'PersonEmail' => $user->getEmail(),
'PersonMailingPostalCode' => $user->getZipCode(),
'PersonMailingStreet' => $user->getAddress(),
'PersonMailingCity' => $user->getCity(),
'PersonMailingCountry' => $this->getCountryFrenchName($user->getCountry()),
'Phone' => $user->getPhone(),
'PersonMobilePhone' => $user->getMobile(),
'DerniereVisite__c' => Formatter::date($user->getLastLogin()),
'Inscription_Newsletter__c' => Formatter::bool($user->getNewsletter()),
'Date_Heure_Inscription_Newsletter__c' => Formatter::date($user->getLastOptinChangeDate()),
'ExternalId__c' => $user->getEmail(),
'Id' => $user->getSfAccountId(),
]);
}
}
$this->sfClient->initiate()->upsert('Id', (object) $sAccount, 'Account');
$this->salesforceDetailLogger->info(sprintf('SF %s, Account | Update: %s %s', __FUNCTION__, $user->getSfAccountId(), json_encode($sAccount, JSON_PRETTY_PRINT)));
if ($user instanceof ProUser) {
$this->sfClient->upsert('Id', (object) $sContact, 'Contact');
$this->salesforceDetailLogger->info(sprintf('SF %s, Contact | Update: %s %s', __FUNCTION__, $user->getSfContactId(), json_encode($sContact, JSON_PRETTY_PRINT)));
}
}
/**
* Custom event CONVERT_COMPLETED handling method.
* Needs to be two-step because you cannot update type and data at the same time.
*/
public function onUserConversionComplete(UserEvent $evt): void
{
$user = $evt->getUser();
$upSUser = array_filter([
'Id' => $user->getSfAccountId(),
'RecordTypeId' => $user instanceof PrivateUser && !$user->isSociety() ? Constants::ACCOUNT_PERSON : Constants::ACCOUNT_BUSINESS,
]);
$this->sfClient->initiate()->upsert('Id', (object) $upSUser, 'Account');
$upSUser = array_filter([
'Id' => $user->getSfAccountId(),
'Type_d_entreprise__c' => $user instanceof PrivateUser ? ($user->isSociety() ? 'Société' : 'Particulier') : 'Professionnel',
]);
$this->sfClient->initiate()->upsert('Id', (object) $upSUser, 'Account');
}
/**
* Custom event CHANGE_COMPANY handling method.
*/
public function onChangeCompany(UserEvent $evt): void
{
$user = $evt->getUser();
$upSContact = array_filter([
'Id' => $user->getSfContactId(),
'AccountId' => $user->getSfAccountId(),
]);
$this->salesforceDetailLogger->info(sprintf('SF %s, Contact | Change company: %s %s', __FUNCTION__, $user->getSfContactId(), json_encode($upSContact, JSON_PRETTY_PRINT)));
$this->sfClient->upsert('Id', (object) $upSContact, 'Contact');
}
/**
* Custom event OPTIN_CHANGED handling method.
*/
public function onOptinChanged(UserEvent $evt): void
{
$user = $evt->getUser();
if ($user instanceof ProUser) {
$upSUser = [
'Id' => $user->getSfContactId(),
'Email_actualite_des_ventes__c' => Formatter::bool($user->isEmailOptin()),
'Date_email_actualiet_des_ventes__c' => date('c', time()),
'SMS_actualite_des_ventes__c' => Formatter::bool($user->isSmsOptin()),
'Date_SMS_actualite_des_ventes__c' => date('c', time()),
];
$this->sfClient->initiate()->upsert('Id', (object) $upSUser, 'Contact');
$this->salesforceDetailLogger->info(sprintf('SF %s, Contact | Update: %s %s', __FUNCTION__, $user->getSfContactId(), json_encode($upSUser, JSON_PRETTY_PRINT)));
}
}
/**
* Custom ProfileController Event DELETE_COMPLETED handling method.
*
* @param UserEvent $evt - The event
*/
public function onUserDeletionComplete(UserEvent $evt): void
{
$user = $evt->getUser();
if ($user instanceof PrivateUser) {
$upSUser = [
'Id' => $user->getSfAccountId(),
'Description' => 'Cet utilisateur a désactivé son compte vpauto.fr.',
];
$this->sfClient->initiate()->upsert('Id', (object) $upSUser, 'Account');
$this->salesforceDetailLogger->info(sprintf('SF %s, Account | Disabled: %s %s', __FUNCTION__, $user->getSfAccountId(), json_encode($upSUser, JSON_PRETTY_PRINT)));
}
}
/**
* Custom event CREATE_USER_BY_SERVICE_BUS handling method.
*
* @param UserEvent $evt - The event
*/
public function onUserCustomerPortalComplete(UserEvent $evt): void
{
$this->sfClient->initiate();
/* @var ProUser $user */
$user = $evt->getUser();
$this->salesforceLogger->info(sprintf('Event CREATE_USER_BY_SERVICE_BUS on %s with userId = %s', __FUNCTION__, $user->getId()));
if (null !== $exists = $this->searchAccount($user)) {
$id = $exists['id'];
} else {
$shippingAddress = !$user->getShippingAddresses()->isEmpty() ? $user->getShippingAddresses()->first() : false;
$owner = null;
if (null !== $user->getSalesman()) {
$data = $this->sfClient->findOne(['Id'], 'User', ['Email' => $user->getSalesman()->getEmail()]);
$owner = $data->Id ?? null;
}
$sAccount = array_filter([
'Name' => $user->getCompany(),
'NoTVAIntracommunautaire__c' => $user->getVAT(),
'BillingPostalCode' => $user->getZipCode(),
'BillingStreet' => $user->getAddress(),
'BillingCity' => $user->getCity(),
'BillingCountry' => $this->getCountryFrenchName($user->getCountry()),
'Siret__c' => $user->getSiret(),
'N_de_Siren__c' => $user->getSiren(),
'ShippingPostalCode' => $shippingAddress ? $shippingAddress->getZipCode() : null,
'ShippingStreet' => $shippingAddress ? $shippingAddress->getAddress() : null,
'ShippingCity' => $shippingAddress ? $shippingAddress->getCity() : null,
'Inscription_Newsletter__c' => Formatter::bool($user->getNewsletter()),
'Date_Heure_Inscription_Newsletter__c' => Formatter::date($user->getLastOptinChangeDate()),
'ExternalId__c' => $user->getEmail(),
'Type_d_entreprise__c' => 'Professionnel',
'DateInscriptionWeb__c' => Formatter::date($user->getCreatedAt()),
'DerniereVisite__c' => Formatter::date($user->getLastLogin()),
'Carte_d_identitee__c' => $user->getIdentityCard(),
'K_BIS__c' => $user->getKbis(),
'Piece_justificative_supplementaire__c' => $user->getAdditionalFile(),
'PersonMobilePhone' => $user->getMobile(),
'Procuration_d_achat__c' => $user->getMandate(),
'Volume_annuel_VO__c' => $user->getSoldVehiclesByYear(),
'Langue__c' => $user->getLanguage(),
'Email_principal__c' => $user->getEmail(),
'OwnerId' => $owner,
]);
$account = $this->sfClient->upsert('ExternalId__c', (object) $sAccount, 'Account');
$id = $account[0]->id;
$this->salesforceDetailLogger->info(sprintf('SF %s, Account | Create by service bus: %s %s', __FUNCTION__, $id, json_encode($sAccount, JSON_PRETTY_PRINT)));
}
$data = $this->createContactWithAccount($user, $id);
$user->setSfAccountId($id);
$user->setSfContactId($data[0]->id);
$this->em->flush();
$this->eventDispatcher->dispatch(new UserEvent($user), UserEvents::ID_SEND_USER_BY_SALESFORCE_AFTER_BUS);
}
private function registerProUser(ProUser $user): void
{
// We check if an account already exists so we only create the contact
if (null !== $exists = $this->searchAccount($user)) {
$id = $exists['id'];
// We check if a contact already exists so as not to create a duplicate
if (null !== $exists = $this->searchContact($user->getEmail())) {
$upSContact = array_filter([
'Id' => $exists['id'],
'AccountId' => $id,
]);
$this->sfClient->upsert('Id', (object) $upSContact, 'Contact');
$this->salesforceDetailLogger->info(sprintf('SF %s, Contact | Create: %s %s', __FUNCTION__, $exists['id'], json_encode($upSContact, JSON_PRETTY_PRINT)));
$user->setSfContactId($exists['id']);
} else {
$upSContact = array_filter([
'LastName' => $user->getLastname(),
'FirstName' => $user->getFirstname(),
'Email' => $user->getEmail(),
'Phone' => $user->getPhone(),
'Fonction__c' => $user->getBusinessRole(),
'ExternalId__c' => $user->getEmail(),
'AccountId' => $id,
]);
$data = $this->sfClient->upsert('ExternalId__c', (object) $upSContact, 'Contact');
$user->setSfContactId($data[0]->id);
$this->salesforceDetailLogger->info(sprintf('SF %s, Contact | Create: %s %s', __FUNCTION__, $data[0]->id, json_encode($upSContact, JSON_PRETTY_PRINT)));
}
$user->setSfAccountId($id);
$sUser = $this->sfClient->findOne([
'Name',
'Owner.Email',
],
'Account',
['Id' => $id]
);
$salesman = $this->em->getRepository(User::class)->findOneByEmail($sUser->Owner->Email);
if ($salesman) {
$this->mailer->send(
$salesman,
'/Mail/notif_sf_new_contact.html.twig',
[
'company' => $sUser->Name,
'customer' => $user->getLastname().' '.$user->getFirstname(),
'email' => $user->getEmail(),
'phone' => $user->getPhone(),
'adId' => $user->getAdId(),
'url' => $this->router->generate('backend_user_view', ['id' => $user->getId()], UrlGeneratorInterface::ABSOLUTE_URL),
]
);
}
} else {
if (User::ORIGIN_SHOWVROOM === $user->getOrigin()) {
$validationUrl = $this->baseUri.$this->router->generate('fos_user_registration_confirm', ['token' => $user->getConfirmationToken()], UrlGeneratorInterface::ABSOLUTE_PATH);
} else {
$validationUrl = $this->router->generate('fos_user_registration_confirm', ['token' => $user->getConfirmationToken()], UrlGeneratorInterface::ABSOLUTE_URL);
}
$countryName = $this->getCountryFrenchName($user->getCountry());
$upSLead = array_filter([
'LastName' => $user->getLastname(),
'FirstName' => $user->getFirstname(),
'Email' => $user->getEmail(),
'Street' => $user->getAddress(),
'PostalCode' => $user->getZipCode(),
'City' => $user->getCity(),
'Country' => $countryName,
'Fonction__c' => $user->getBusinessRole(),
'Company' => $user->getCompany(),
'Nombre_employes__c' => $user->getNbEmployees(),
'Volume_annuel_VO__c' => $user->getSoldVehiclesByYear(),
'LeadSource' => User::ORIGIN_SHOWVROOM === $user->getOrigin() ? 'Alliance automotive' : 'Inscription site',
'Carte_d_identitee__c' => $user->getIdentityCard(),
'K_BIS__c' => $user->getKbis(),
'Piece_justificative_supplementaire__c' => $user->getAdditionalFile(),
'Langue__c' => $user->getLanguage(),
'Type_de_lead__c' => $user->getSource(),
'TVA_Intracom__c' => $user->getVAT(),
'SIRET__c' => $user->getSiret(),
'Phone' => $user->getPhone(),
'MobilePhone' => $user->getMobile(),
'Type_de_societe__c' => $user->getCompanyTypeOther() ?? $user->getCompanyType(),
'Procuration_achat__c' => $user->getMandate(),
'Carte_identitee_demandeur__c' => $user->getEmployeeIdentityCard(),
'Email_actualite_des_ventes__c' => $user->isEmailOptin() ?? '',
'Date_email_actualite_des_ventes__c' => $user->isEmailOptin() ? date('c', time()) : '',
'SMS_actualite_des_ventes__c' => $user->isSmsOptin() ?? '',
'Date_SMS_actualite_des_ventes__c' => $user->isSmsOptin() ? date('c', time()) : '',
'Validation_Url__c' => $validationUrl,
]);
$data = $this->sfClient->upsert('Email', (object) $upSLead, 'Lead');
$this->salesforceDetailLogger->info(sprintf('SF %s, Lead | Create: %s %s', __FUNCTION__, $data[0]->id ?? null, json_encode($upSLead, JSON_PRETTY_PRINT)));
if (!empty($data)) {
$user->setSfLeadId($data[0]->id);
}
}
$this->em->flush();
}
private function registerUser(User $user): void
{
switch ($user->getCountry()) {
case 'PT':
$this->registerUserForCountry($user);
break;
default:
$id = null;
$upSUser = [];
if (false !== $leadExists = $this->sfClient->exists('Lead', ['Email' => $user->getEmail()])) {
$data = $this->sfClient->convert($leadExists['id'], $user->getId());
$id = $data[0]->accountId;
} elseif (false !== $exists = $this->sfClient->exists('Account', ['ExternalId__c' => $user->getEmail(), 'IsPersonAccount' => true])) {
$id = $exists['id'];
$user->setSfAccountId($id);
$sUser = $this->sfClient->findOne([
'Phone',
'PersonMobilePhone',
'Fax',
'PersonMailingStreet',
'PersonMailingCity',
'PersonMailingCountry',
'PersonMailingPostalCode',
'CanauxActifs__c',
],
'Account',
['Id' => $id]
);
$this->hydrator->hydrate($sUser, $user);
$upSUser = array_filter([
'DateInscriptionWeb__c' => date('c', time()),
'DerniereVisite__c' => date('c', time()),
'Id' => $id,
]);
} else {
$upSUser = array_filter([
'LastName' => 'Nouvel inscrit',
'PersonEmail' => $user->getEmail(),
'RecordTypeId' => Constants::ACCOUNT_PERSON,
]);
}
$upSUser = array_merge($upSUser, array_filter([
'Inscription_Newsletter__c' => Formatter::bool($user->getNewsletter()),
'Date_Heure_Inscription_Newsletter__c' => Formatter::date($user->getLastOptinChangeDate()),
'DateInscriptionWeb__c' => date('c', time()),
'DerniereVisite__c' => date('c', time()),
'ExternalId__c' => $user->getEmail(),
'Validation__c' => 'En attente',
'Origine_de_la_piste_compte__c' => $user->getReferralSource(),
'PersonLeadSource' => $user->getReferralSource(),
]));
$countryName = $this->getCountryFrenchName($user->getCountry());
if ('ES' === $user->getCountry()) {
$upSUser = array_merge($upSUser, array_filter([
'FirstName' => $user->getFirstname(),
'LastName' => $user->getLastname(),
'Phone' => $user->getPhone(),
// Address
'PersonMailingStreet' => $user->getAddress(),
'PersonMailingPostalCode' => $user->getZipCode(),
'PersonMailingCity' => $user->getCity(),
// Metadata
'Origine_de_la_piste_compte__c' => 'Inscription '.$countryName,
// Attachments
'Carte_d_identite_recto__c' => $this->router->generate('fos_user_get_document', ['fileField' => 'CNIRectoFile', 'user' => $user->getId()], UrlGeneratorInterface::ABSOLUTE_URL),
'Carte_d_identit_verso__c' => $this->router->generate('fos_user_get_document', ['fileField' => 'CNIVersoFile', 'user' => $user->getId()], UrlGeneratorInterface::ABSOLUTE_URL),
]));
} elseif ('BE' === $user->getCountry()) {
$upSUser = array_merge($upSUser, array_filter([
'Origine_de_la_piste_compte__c' => 'Inscription '.$countryName,
]));
}
$upSUser = array_merge($upSUser, array_filter([
'PersonMailingCountry' => $countryName,
]));
$data = $this->sfClient->upsert(null === $id ? 'ExternalId__c' : 'Id', (object) $upSUser, 'Account');
$this->salesforceDetailLogger->info(sprintf('SF %s, Account | Create by form user: %s %s', __FUNCTION__, $data[0]->id ?? null, json_encode($upSUser, JSON_PRETTY_PRINT)));
if (!empty($data)) {
$user->setSfAccountId($data[0]->id);
$this->em->flush();
}
}
}
private function registerUserForCountry(User $user): void
{
$validationUrl = $this->router->generate('fos_user_registration_confirm', ['token' => $user->getConfirmationToken()], UrlGeneratorInterface::ABSOLUTE_URL);
$countryName = $this->getCountryFrenchName($user->getCountry());
$upSLead = array_filter([
'LastName' => $user->getLastname(),
'FirstName' => $user->getFirstname(),
'Email' => $user->getEmail(),
'Street' => $user->getAddress(),
'PostalCode' => $user->getZipCode(),
'City' => $user->getCity(),
'Country' => $countryName,
'Phone' => $user->getPhone(),
'MobilePhone' => $user->getMobile(),
'Langue__c' => $user->getLanguage(),
'Carte_d_identite_recto__c' => $this->router->generate('fos_user_get_document', ['fileField' => 'CNIRectoFile', 'user' => $user->getId()], UrlGeneratorInterface::ABSOLUTE_URL),
'Carte_d_identite_verso__c' => $this->router->generate('fos_user_get_document', ['fileField' => 'CNIVersoFile', 'user' => $user->getId()], UrlGeneratorInterface::ABSOLUTE_URL),
'Justificatif_de_domicile__c' => $this->router->generate('fos_user_get_document', ['fileField' => 'domiciliationFile', 'user' => $user->getId()], UrlGeneratorInterface::ABSOLUTE_URL),
'N_NIF__c' => $user->getNIFNumber(),
'LeadSource' => 'Inscription '.$countryName,
'Validation_Url__c' => $validationUrl,
]);
$data = $this->sfClient->upsert('Email', (object) $upSLead, 'Lead');
$this->salesforceDetailLogger->info(sprintf('SF %s, Lead | Create other country: %s %s', __FUNCTION__, $data[0]->id ?? null, json_encode($upSLead, JSON_PRETTY_PRINT)));
if (!empty($data)) {
$user->setSfLeadId($data[0]->id);
$this->em->flush();
}
}
private function getCountryFrenchName(?string $country): string
{
if (null === $country) {
return '';
}
$countries = $this->dictionaryMap->get('registration_form_country', 'fr')->getValues();
return array_search($country, $countries) ?: '';
}
private function createContactWithAccount($user, $id): array
{
if (!$user instanceof ProUser) {
return [];
}
$upSContact = array_filter([
'LastName' => $user->getLastname(),
'FirstName' => $user->getFirstname(),
'Email' => $user->getEmail(),
'Phone' => $user->getPhone() ?? $user->getMobile(),
'Fonction__c' => $user->getBusinessRole(),
'ExternalId__c' => $user->getEmail(),
'Email_actualite_des_ventes__c' => Formatter::bool($user->isEmailOptin()),
'Date_email_actualiet_des_ventes__c' => date('c', time()),
'SMS_actualite_des_ventes__c' => Formatter::bool($user->isSmsOptin()),
'Date_SMS_actualite_des_ventes__c' => date('c', time()),
'AccountId' => $id,
]);
$this->salesforceDetailLogger->info(sprintf('SF %s, Contact | Create: %s %s', __FUNCTION__, $id, json_encode($upSContact, JSON_PRETTY_PRINT)));
return $this->sfClient->upsert('ExternalId__c', (object) $upSContact, 'Contact');
}
private function searchAccount(ProUser $user): ?array
{
$vat = $user->getVAT();
$siret = $user->getSiret();
$id = $user->getId();
$companyName = $user->getCompany();
if (null !== $vat) {
$data = $this->sfClient->findOne(['Id', 'Name'], 'Account', ['NoTVAIntracommunautaire__c' => $vat, 'IsPersonAccount' => false]);
if (false !== $data) {
$exists = array_filter([
'id' => $data->Id,
'name' => $data->Name ?? null,
]);
if ($companyName != $exists['name']) {
$this->salesforceLogger->error(sprintf('IDVP : %s, IDSF : %s, Company SF : %s, Company VP : %s', $id, $exists['id'], $exists['name'], $companyName));
}
$this->salesforceLogger->info(sprintf('%s on NoTVAIntracommunautaire__c with VAT : %s FOUND with ID = %s', __FUNCTION__, $vat, $exists['id']));
return $exists;
}
$this->salesforceLogger->info(sprintf('%s on NoTVAIntracommunautaire__c with VAT : %s NOT FOUND', __FUNCTION__, $vat));
}
if (null !== $siret) {
$data = $this->sfClient->findOne(['Id', 'Name'], 'Account', ['Siret__c' => $siret, 'IsPersonAccount' => false]);
if (false !== $data) {
$exists = array_filter([
'id' => $data->Id,
'name' => $data->Name ?? null,
]);
if ($companyName != $exists['name']) {
$this->salesforceLogger->error(sprintf('IDVP : %s, IDSF : %s, Company SF : %s, Company VP : %s', $id, $exists['id'], $exists['name'], $companyName));
}
$this->salesforceLogger->info(sprintf('%s on Siret__c with SIRET : %s FOUND with ID = %s', __FUNCTION__, $siret, $exists['id']));
return $exists;
}
$this->salesforceLogger->info(sprintf('%s on Siret__c with SIRET : %s NOT FOUND', __FUNCTION__, $siret));
}
return null;
}
private function searchContact(string $email)
{
if (false !== $exists = $this->sfClient->exists('Contact', ['Email' => $email])) {
return $exists;
}
return null;
}
}