src/Salesforce/EventListener/SalesForceFOSListener.php line 350

Open in your IDE?
  1. <?php
  2. namespace App\Salesforce\EventListener;
  3. use App\Dictionary\DictionaryMap;
  4. use App\Entity\PrivateUser;
  5. use App\Entity\ProUser;
  6. use App\Entity\User;
  7. use App\Event\UserEvents;
  8. use App\Mailer\TranslatableMailer;
  9. use App\Salesforce\Api\ClientInterface;
  10. use App\Salesforce\Object\DataHydrator;
  11. use App\Salesforce\Utils\Constants;
  12. use App\Salesforce\Utils\Formatter;
  13. use App\Twig\Extension\CountryExtension;
  14. use Doctrine\ORM\EntityManagerInterface;
  15. use FOS\UserBundle\Event\FilterUserResponseEvent;
  16. use FOS\UserBundle\Event\UserEvent;
  17. use FOS\UserBundle\FOSUserEvents;
  18. use Psr\Log\LoggerInterface;
  19. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  20. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  21. use Symfony\Component\Routing\RouterInterface;
  22. use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
  23. use Symfony\Component\Security\Http\SecurityEvents;
  24. use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
  25. /**
  26.  * SalesForce Event listener for the FOS and user-related kernel events.
  27.  */
  28. class SalesForceFOSListener implements EventSubscriberInterface
  29. {
  30.     public function __construct(
  31.         private readonly ClientInterface $sfClient,
  32.         private readonly EntityManagerInterface $em,
  33.         private readonly RouterInterface $router,
  34.         private readonly DictionaryMap $dictionaryMap,
  35.         private readonly DataHydrator $hydrator,
  36.         private readonly EventDispatcherInterface $eventDispatcher,
  37.         private readonly TranslatableMailer $mailer,
  38.         private readonly LoggerInterface $salesforceLogger,
  39.         private readonly LoggerInterface $salesforceDetailLogger,
  40.         private readonly string $baseUri,
  41.     ) {
  42.     }
  43.     public static function getSubscribedEvents()
  44.     {
  45.         return [
  46.             FOSUserEvents::REGISTRATION_COMPLETED => 'onUserRegistrationComplete',
  47.             FOSUserEvents::REGISTRATION_CONFIRMED => 'onUserRegistrationConfirmed',
  48.             SecurityEvents::INTERACTIVE_LOGIN => 'onUserInteractiveLogin',
  49.             UserEvents::EDIT_COMPLETED => 'onUserProfileEditComplete',
  50.             UserEvents::UPDATE_USER_BY_SERVICE_BUS => 'onUserProfileEditComplete',
  51.             UserEvents::UPDATE_ID_SALESFORCE => 'onUserProfileEditComplete',
  52.             UserEvents::CREATE_USER_BY_SERVICE_BUS => 'onUserCustomerPortalComplete',
  53.             UserEvents::CONVERT_COMPLETED => 'onUserConversionComplete',
  54.             UserEvents::DELETE_COMPLETED => 'onUserDeletionComplete',
  55.             UserEvents::OPTIN_CHANGED => 'onOptinChanged',
  56.             UserEvents::CHANGE_COMPANY => 'onChangeCompany',
  57.             UserEvents::CATCH_UP => 'onUserRegistrationComplete',
  58.         ];
  59.     }
  60.     /**
  61.      * FOSUser Event REGISTRATION_COMPLETED handling method.
  62.      *
  63.      * @param FilterUserResponseEvent $evt - The event
  64.      */
  65.     public function onUserRegistrationComplete(FilterUserResponseEvent $evt): void
  66.     {
  67.         $this->sfClient->initiate();
  68.         $user $evt->getUser();
  69.         if ($user instanceof ProUser) {
  70.             $this->registerProUser($user);
  71.         } elseif ($user instanceof User) {
  72.             $this->registerUser($user);
  73.         }
  74.     }
  75.     /**
  76.      * FOSUser Event REGISTRATION_CONFIRMED handling method.
  77.      *
  78.      * @param FilterUserResponseEvent $evt - The event
  79.      */
  80.     public function onUserRegistrationConfirmed(FilterUserResponseEvent $evt): void
  81.     {
  82.         $this->sfClient->initiate();
  83.         $user $evt->getUser();
  84.         if ($user instanceof ProUser) {
  85.             if (null !== $user->getSfLeadId()) {
  86.                 $data $this->sfClient->convert($user->getSfLeadId(), $user->getId());
  87.                 if (!empty($data)) {
  88.                     $user->setSfAccountId($data[0]->accountId);
  89.                     $user->setSfContactId($data[0]->contactId);
  90.                     $user->setSfLeadId(null);
  91.                     $this->em->flush();
  92.                     $this->eventDispatcher->dispatch(new UserEvent($user), UserEvents::ID_SEND_USER_BY_SALESFORCE);
  93.                 }
  94.             }
  95.         } else {
  96.             if (in_array(
  97.                 strtolower($user->getCountry()),
  98.                 [CountryExtension::COUNTRY_PORTUGAL]
  99.             )) {
  100.                 if (null !== $user->getSfLeadId()) {
  101.                     $data $this->sfClient->convert($user->getSfLeadId(), $user->getId());
  102.                     if (!empty($data)) {
  103.                         $user->setSfAccountId($data[0]->accountId);
  104.                         $user->setSfLeadId(null);
  105.                         $this->em->flush();
  106.                     }
  107.                 }
  108.             } else {
  109.                 $sUser = [
  110.                     'Id' => $user->getSfAccountId(),
  111.                     'Validation__c' => 'Validé',
  112.                 ];
  113.                 $this->sfClient->upsert('Id', (object) $sUser'Account');
  114.             }
  115.         }
  116.     }
  117.     /**
  118.      * Symfony Event security.interactive_login handling method.
  119.      *
  120.      * @param InteractiveLoginEvent $evt - The event
  121.      */
  122.     public function onUserInteractiveLogin(InteractiveLoginEvent $evt): void
  123.     {
  124.         $this->sfClient->initiate();
  125.         $user $evt->getAuthenticationToken()->getUser();
  126.         // Temp removal of society interaction with SF
  127.         if ($user instanceof PrivateUser && $user->isSociety()) {
  128.             return;
  129.         }
  130.         if ($user instanceof ProUser) {
  131.             if (null === $user->getSfAccountId() || null === $user->getSfContactId()) {
  132.                 if (false === $exists $this->sfClient->exists('Contact', ['ExternalId__c' => $user->getEmail()])) {
  133.                     return;
  134.                 }
  135.                 $user->setSfAccountId($exists['accId'] ?? null);
  136.                 $user->setSfContactId($exists['id']);
  137.                 $this->em->flush();
  138.             }
  139.         } else {
  140.             if (null === $user->getSfAccountId()) {
  141.                 if (false === $exists $this->sfClient->exists('Account', ['ExternalId__c' => $user->getEmail()])) {
  142.                     return;
  143.                 }
  144.                 $user->setSfAccountId($exists['id']);
  145.                 $this->em->flush();
  146.             }
  147.         }
  148.         if ($user instanceof ProUser) {
  149.             $sUser $this->sfClient->findOne([
  150.                 'LastName',
  151.                 'FirstName',
  152.                 'Phone',
  153.                 'MobilePhone',
  154.                 'Account.Name',
  155.                 'Account.NoTVAIntracommunautaire__c',
  156.                 'Account.Siret__c',
  157.                 'Account.Fax',
  158.                 'Account.BillingStreet',
  159.                 'Account.BillingCity',
  160.                 'Account.BillingCountry',
  161.                 'Account.BillingPostalCode',
  162.                 'Account.Statut__c',
  163.                 'Account.Banni_par_le_commercial__c',
  164.                 'Account.Owner.Email',
  165.             ],
  166.                 'Contact',
  167.                 ['Id' => $user->getSfContactId()]
  168.             );
  169.             $upSContact array_filter([
  170.                 'Id' => $user->getSfContactId(),
  171.                 'Last_login__c' => Formatter::date($user->getLastLogin()),
  172.             ]);
  173.             $this->sfClient->upsert('Id', (object) $upSContact'Contact');
  174.             $this->salesforceDetailLogger->info(sprintf('SF %s, Contact | Connection: %s %s'__FUNCTION__$user->getSfContactId(), json_encode($upSContactJSON_PRETTY_PRINT)));
  175.             $upSAccount array_filter([
  176.                 'Id' => $user->getSfAccountId(),
  177.                 'Last_login__c' => Formatter::date($user->getLastLogin()),
  178.             ]);
  179.             $this->sfClient->upsert('Id', (object) $upSAccount'Account');
  180.             $this->salesforceDetailLogger->info(sprintf('SF %s, Account | Connection: %s %s'__FUNCTION__$user->getSfAccountId(), json_encode($upSAccountJSON_PRETTY_PRINT)));
  181.         } else {
  182.             $sUser $this->sfClient->findOne([
  183.                 'LastName',
  184.                 'FirstName',
  185.                 'Phone',
  186.                 'Fax',
  187.                 'PersonMailingStreet',
  188.                 'PersonMailingCity',
  189.                 'PersonMailingCountry',
  190.                 'PersonMailingPostalCode',
  191.                 'Inscription_Newsletter__c',
  192.                 'CanauxActifs__c',
  193.                 'DateInscriptionWeb__c',
  194.             ],
  195.                 'Account',
  196.                 ['Id' => $user->getSfAccountId()]
  197.             );
  198.             $upSUser array_filter([
  199.                 'Id' => $user->getSfAccountId(),
  200.                 'DateInscriptionWeb__c' => empty($sUser->DateInscriptionWeb__c) ? Formatter::date($user->getCreatedAt()) : null,
  201.                 'DerniereVisite__c' => Formatter::date($user->getLastLogin()),
  202.             ]);
  203.             $this->sfClient->upsert('Id', (object) $upSUser'Account');
  204.             $this->salesforceDetailLogger->info(sprintf('SF %s, Account | Connection: %s  %s'__FUNCTION__$user->getSfAccountId(), json_encode($upSUserJSON_PRETTY_PRINT)));
  205.         }
  206.         $this->hydrator->hydrate($sUser$user);
  207.         $this->em->flush();
  208.     }
  209.     /**
  210.      * Custom event EDIT_COMPLETED handling method.
  211.      * Custom event UPDATE_USER_BY_SERVICE_BUS handling method.
  212.      * Custom event UPDATE_ID_SALESFORCE handling method.
  213.      *
  214.      * @param UserEvent $evt - The event
  215.      */
  216.     public function onUserProfileEditComplete(UserEvent $evt): void
  217.     {
  218.         $user $evt->getUser();
  219.         // Temp removal of society interaction with SF
  220.         if ($user instanceof PrivateUser && $user->isSociety()) {
  221.             return;
  222.         }
  223.         if (null === $user->getSfAccountId()) {
  224.             return;
  225.         }
  226.         if ($user instanceof ProUser) {
  227.             $shippingAddress = !$user->getShippingAddresses()->isEmpty() ? $user->getShippingAddresses()->first() : false;
  228.             $sAccount array_filter([
  229.                 'Name' => $user->getCompany(),
  230.                 'NoTVAIntracommunautaire__c' => $user->getVAT(),
  231.                 'BillingPostalCode' => $user->getZipCode(),
  232.                 'BillingStreet' => $user->getAddress(),
  233.                 'BillingCity' => $user->getCity(),
  234.                 'ShippingPostalCode' => $shippingAddress $shippingAddress->getZipCode() : null,
  235.                 'ShippingStreet' => $shippingAddress $shippingAddress->getAddress() : null,
  236.                 'ShippingCity' => $shippingAddress $shippingAddress->getCity() : null,
  237.                 'Inscription_Newsletter__c' => Formatter::bool($user->getNewsletter()),
  238.                 'Date_Heure_Inscription_Newsletter__c' => Formatter::date($user->getLastOptinChangeDate()),
  239.                 'Siret__c' => null !== $user->getCompanyId() ? $user->getSiret() : null,
  240.                 'N_de_Siren__c' => null !== $user->getCompanyId() ? $user->getSiren() : null,
  241.                 'Id' => $user->getSfAccountId(),
  242.             ]);
  243.             $sContact array_filter([
  244.                 'Email' => $user->getEmail(),
  245.                 'Phone' => $user->getPhone(),
  246.                 'MobilePhone' => $user->getMobile(),
  247.                 'FirstName' => $user->getFirstname(),
  248.                 'LastName' => $user->getLastname(),
  249.                 'ExternalId__c' => $user->getEmail(),
  250.                 'Id' => $user->getSfContactId(),
  251.             ]);
  252.         } else {
  253.             if ('PT' === $user->getCountry()) {
  254.                 $sAccount array_filter([
  255.                     'LastName' => $user->getLastname(),
  256.                     'FirstName' => $user->getFirstname(),
  257.                     'PersonEmail' => $user->getEmail(),
  258.                     'PersonMailingStreet' => $user->getAddress(),
  259.                     'PersonMailingPostalCode' => $user->getZipCode(),
  260.                     'PersonMailingCity' => $user->getCity(),
  261.                     'PersonMailingCountry' => $this->getCountryFrenchName($user->getCountry()),
  262.                     'Phone' => $user->getPhone(),
  263.                     'PersonMobilePhone' => $user->getMobile(),
  264.                     'ExternalId__c' => $user->getEmail(),
  265.                     'Id' => $user->getSfAccountId(),
  266.                 ]);
  267.             } else {
  268.                 $sAccount array_filter([
  269.                     'LastName' => $user->getLastname(),
  270.                     'FirstName' => $user->getFirstname(),
  271.                     'PersonEmail' => $user->getEmail(),
  272.                     'PersonMailingPostalCode' => $user->getZipCode(),
  273.                     'PersonMailingStreet' => $user->getAddress(),
  274.                     'PersonMailingCity' => $user->getCity(),
  275.                     'PersonMailingCountry' => $this->getCountryFrenchName($user->getCountry()),
  276.                     'Phone' => $user->getPhone(),
  277.                     'PersonMobilePhone' => $user->getMobile(),
  278.                     'DerniereVisite__c' => Formatter::date($user->getLastLogin()),
  279.                     'Inscription_Newsletter__c' => Formatter::bool($user->getNewsletter()),
  280.                     'Date_Heure_Inscription_Newsletter__c' => Formatter::date($user->getLastOptinChangeDate()),
  281.                     'ExternalId__c' => $user->getEmail(),
  282.                     'Id' => $user->getSfAccountId(),
  283.                 ]);
  284.             }
  285.         }
  286.         $this->sfClient->initiate()->upsert('Id', (object) $sAccount'Account');
  287.         $this->salesforceDetailLogger->info(sprintf('SF %s, Account | Update: %s %s'__FUNCTION__$user->getSfAccountId(), json_encode($sAccountJSON_PRETTY_PRINT)));
  288.         if ($user instanceof ProUser) {
  289.             $this->sfClient->upsert('Id', (object) $sContact'Contact');
  290.             $this->salesforceDetailLogger->info(sprintf('SF %s, Contact | Update: %s %s'__FUNCTION__$user->getSfContactId(), json_encode($sContactJSON_PRETTY_PRINT)));
  291.         }
  292.     }
  293.     /**
  294.      * Custom event CONVERT_COMPLETED handling method.
  295.      * Needs to be two-step because you cannot update type and data at the same time.
  296.      */
  297.     public function onUserConversionComplete(UserEvent $evt): void
  298.     {
  299.         $user $evt->getUser();
  300.         $upSUser array_filter([
  301.             'Id' => $user->getSfAccountId(),
  302.             'RecordTypeId' => $user instanceof PrivateUser && !$user->isSociety() ? Constants::ACCOUNT_PERSON Constants::ACCOUNT_BUSINESS,
  303.         ]);
  304.         $this->sfClient->initiate()->upsert('Id', (object) $upSUser'Account');
  305.         $upSUser array_filter([
  306.             'Id' => $user->getSfAccountId(),
  307.             'Type_d_entreprise__c' => $user instanceof PrivateUser ? ($user->isSociety() ? 'Société' 'Particulier') : 'Professionnel',
  308.         ]);
  309.         $this->sfClient->initiate()->upsert('Id', (object) $upSUser'Account');
  310.     }
  311.     /**
  312.      * Custom event CHANGE_COMPANY handling method.
  313.      */
  314.     public function onChangeCompany(UserEvent $evt): void
  315.     {
  316.         $user $evt->getUser();
  317.         $upSContact array_filter([
  318.             'Id' => $user->getSfContactId(),
  319.             'AccountId' => $user->getSfAccountId(),
  320.         ]);
  321.         $this->salesforceDetailLogger->info(sprintf('SF %s, Contact | Change company: %s %s'__FUNCTION__$user->getSfContactId(), json_encode($upSContactJSON_PRETTY_PRINT)));
  322.         $this->sfClient->upsert('Id', (object) $upSContact'Contact');
  323.     }
  324.     /**
  325.      * Custom event OPTIN_CHANGED handling method.
  326.      */
  327.     public function onOptinChanged(UserEvent $evt): void
  328.     {
  329.         $user $evt->getUser();
  330.         if ($user instanceof ProUser) {
  331.             $upSUser = [
  332.                 'Id' => $user->getSfContactId(),
  333.                 'Email_actualite_des_ventes__c' => Formatter::bool($user->isEmailOptin()),
  334.                 'Date_email_actualiet_des_ventes__c' => date('c'time()),
  335.                 'SMS_actualite_des_ventes__c' => Formatter::bool($user->isSmsOptin()),
  336.                 'Date_SMS_actualite_des_ventes__c' => date('c'time()),
  337.             ];
  338.             $this->sfClient->initiate()->upsert('Id', (object) $upSUser'Contact');
  339.             $this->salesforceDetailLogger->info(sprintf('SF %s, Contact | Update: %s %s'__FUNCTION__$user->getSfContactId(), json_encode($upSUserJSON_PRETTY_PRINT)));
  340.         }
  341.     }
  342.     /**
  343.      * Custom ProfileController Event DELETE_COMPLETED handling method.
  344.      *
  345.      * @param UserEvent $evt - The event
  346.      */
  347.     public function onUserDeletionComplete(UserEvent $evt): void
  348.     {
  349.         $user $evt->getUser();
  350.         if ($user instanceof PrivateUser) {
  351.             $upSUser = [
  352.                 'Id' => $user->getSfAccountId(),
  353.                 'Description' => 'Cet utilisateur a désactivé son compte vpauto.fr.',
  354.             ];
  355.             $this->sfClient->initiate()->upsert('Id', (object) $upSUser'Account');
  356.             $this->salesforceDetailLogger->info(sprintf('SF %s, Account | Disabled: %s %s'__FUNCTION__$user->getSfAccountId(), json_encode($upSUserJSON_PRETTY_PRINT)));
  357.         }
  358.     }
  359.     /**
  360.      * Custom event CREATE_USER_BY_SERVICE_BUS handling method.
  361.      *
  362.      * @param UserEvent $evt - The event
  363.      */
  364.     public function onUserCustomerPortalComplete(UserEvent $evt): void
  365.     {
  366.         $this->sfClient->initiate();
  367.         /* @var ProUser $user */
  368.         $user $evt->getUser();
  369.         $this->salesforceLogger->info(sprintf('Event CREATE_USER_BY_SERVICE_BUS on %s with userId = %s'__FUNCTION__$user->getId()));
  370.         if (null !== $exists $this->searchAccount($user)) {
  371.             $id $exists['id'];
  372.         } else {
  373.             $shippingAddress = !$user->getShippingAddresses()->isEmpty() ? $user->getShippingAddresses()->first() : false;
  374.             $owner null;
  375.             if (null !== $user->getSalesman()) {
  376.                 $data $this->sfClient->findOne(['Id'], 'User', ['Email' => $user->getSalesman()->getEmail()]);
  377.                 $owner $data->Id ?? null;
  378.             }
  379.             $sAccount array_filter([
  380.                 'Name' => $user->getCompany(),
  381.                 'NoTVAIntracommunautaire__c' => $user->getVAT(),
  382.                 'BillingPostalCode' => $user->getZipCode(),
  383.                 'BillingStreet' => $user->getAddress(),
  384.                 'BillingCity' => $user->getCity(),
  385.                 'BillingCountry' => $this->getCountryFrenchName($user->getCountry()),
  386.                 'Siret__c' => $user->getSiret(),
  387.                 'N_de_Siren__c' => $user->getSiren(),
  388.                 'ShippingPostalCode' => $shippingAddress $shippingAddress->getZipCode() : null,
  389.                 'ShippingStreet' => $shippingAddress $shippingAddress->getAddress() : null,
  390.                 'ShippingCity' => $shippingAddress $shippingAddress->getCity() : null,
  391.                 'Inscription_Newsletter__c' => Formatter::bool($user->getNewsletter()),
  392.                 'Date_Heure_Inscription_Newsletter__c' => Formatter::date($user->getLastOptinChangeDate()),
  393.                 'ExternalId__c' => $user->getEmail(),
  394.                 'Type_d_entreprise__c' => 'Professionnel',
  395.                 'DateInscriptionWeb__c' => Formatter::date($user->getCreatedAt()),
  396.                 'DerniereVisite__c' => Formatter::date($user->getLastLogin()),
  397.                 'Carte_d_identitee__c' => $user->getIdentityCard(),
  398.                 'K_BIS__c' => $user->getKbis(),
  399.                 'Piece_justificative_supplementaire__c' => $user->getAdditionalFile(),
  400.                 'PersonMobilePhone' => $user->getMobile(),
  401.                 'Procuration_d_achat__c' => $user->getMandate(),
  402.                 'Volume_annuel_VO__c' => $user->getSoldVehiclesByYear(),
  403.                 'Langue__c' => $user->getLanguage(),
  404.                 'Email_principal__c' => $user->getEmail(),
  405.                 'OwnerId' => $owner,
  406.             ]);
  407.             $account $this->sfClient->upsert('ExternalId__c', (object) $sAccount'Account');
  408.             $id $account[0]->id;
  409.             $this->salesforceDetailLogger->info(sprintf('SF %s, Account | Create by service bus: %s %s'__FUNCTION__$idjson_encode($sAccountJSON_PRETTY_PRINT)));
  410.         }
  411.         $data $this->createContactWithAccount($user$id);
  412.         $user->setSfAccountId($id);
  413.         $user->setSfContactId($data[0]->id);
  414.         $this->em->flush();
  415.         $this->eventDispatcher->dispatch(new UserEvent($user), UserEvents::ID_SEND_USER_BY_SALESFORCE_AFTER_BUS);
  416.     }
  417.     private function registerProUser(ProUser $user): void
  418.     {
  419.         // We check if an account already exists so we only create the contact
  420.         if (null !== $exists $this->searchAccount($user)) {
  421.             $id $exists['id'];
  422.             // We check if a contact already exists so as not to create a duplicate
  423.             if (null !== $exists $this->searchContact($user->getEmail())) {
  424.                 $upSContact array_filter([
  425.                     'Id' => $exists['id'],
  426.                     'AccountId' => $id,
  427.                 ]);
  428.                 $this->sfClient->upsert('Id', (object) $upSContact'Contact');
  429.                 $this->salesforceDetailLogger->info(sprintf('SF %s, Contact | Create: %s %s'__FUNCTION__$exists['id'], json_encode($upSContactJSON_PRETTY_PRINT)));
  430.                 $user->setSfContactId($exists['id']);
  431.             } else {
  432.                 $upSContact array_filter([
  433.                     'LastName' => $user->getLastname(),
  434.                     'FirstName' => $user->getFirstname(),
  435.                     'Email' => $user->getEmail(),
  436.                     'Phone' => $user->getPhone(),
  437.                     'Fonction__c' => $user->getBusinessRole(),
  438.                     'ExternalId__c' => $user->getEmail(),
  439.                     'AccountId' => $id,
  440.                 ]);
  441.                 $data $this->sfClient->upsert('ExternalId__c', (object) $upSContact'Contact');
  442.                 $user->setSfContactId($data[0]->id);
  443.                 $this->salesforceDetailLogger->info(sprintf('SF %s, Contact | Create: %s %s'__FUNCTION__$data[0]->idjson_encode($upSContactJSON_PRETTY_PRINT)));
  444.             }
  445.             $user->setSfAccountId($id);
  446.             $sUser $this->sfClient->findOne([
  447.                 'Name',
  448.                 'Owner.Email',
  449.             ],
  450.                 'Account',
  451.                 ['Id' => $id]
  452.             );
  453.             $salesman $this->em->getRepository(User::class)->findOneByEmail($sUser->Owner->Email);
  454.             if ($salesman) {
  455.                 $this->mailer->send(
  456.                     $salesman,
  457.                     '/Mail/notif_sf_new_contact.html.twig',
  458.                     [
  459.                         'company' => $sUser->Name,
  460.                         'customer' => $user->getLastname().' '.$user->getFirstname(),
  461.                         'email' => $user->getEmail(),
  462.                         'phone' => $user->getPhone(),
  463.                         'adId' => $user->getAdId(),
  464.                         'url' => $this->router->generate('backend_user_view', ['id' => $user->getId()], UrlGeneratorInterface::ABSOLUTE_URL),
  465.                     ]
  466.                 );
  467.             }
  468.         } else {
  469.             if (User::ORIGIN_SHOWVROOM === $user->getOrigin()) {
  470.                 $validationUrl $this->baseUri.$this->router->generate('fos_user_registration_confirm', ['token' => $user->getConfirmationToken()], UrlGeneratorInterface::ABSOLUTE_PATH);
  471.             } else {
  472.                 $validationUrl $this->router->generate('fos_user_registration_confirm', ['token' => $user->getConfirmationToken()], UrlGeneratorInterface::ABSOLUTE_URL);
  473.             }
  474.             $countryName $this->getCountryFrenchName($user->getCountry());
  475.             $upSLead array_filter([
  476.                 'LastName' => $user->getLastname(),
  477.                 'FirstName' => $user->getFirstname(),
  478.                 'Email' => $user->getEmail(),
  479.                 'Street' => $user->getAddress(),
  480.                 'PostalCode' => $user->getZipCode(),
  481.                 'City' => $user->getCity(),
  482.                 'Country' => $countryName,
  483.                 'Fonction__c' => $user->getBusinessRole(),
  484.                 'Company' => $user->getCompany(),
  485.                 'Nombre_employes__c' => $user->getNbEmployees(),
  486.                 'Volume_annuel_VO__c' => $user->getSoldVehiclesByYear(),
  487.                 'LeadSource' => User::ORIGIN_SHOWVROOM === $user->getOrigin() ? 'Alliance automotive' 'Inscription site',
  488.                 'Carte_d_identitee__c' => $user->getIdentityCard(),
  489.                 'K_BIS__c' => $user->getKbis(),
  490.                 'Piece_justificative_supplementaire__c' => $user->getAdditionalFile(),
  491.                 'Langue__c' => $user->getLanguage(),
  492.                 'Type_de_lead__c' => $user->getSource(),
  493.                 'TVA_Intracom__c' => $user->getVAT(),
  494.                 'SIRET__c' => $user->getSiret(),
  495.                 'Phone' => $user->getPhone(),
  496.                 'MobilePhone' => $user->getMobile(),
  497.                 'Type_de_societe__c' => $user->getCompanyTypeOther() ?? $user->getCompanyType(),
  498.                 'Procuration_achat__c' => $user->getMandate(),
  499.                 'Carte_identitee_demandeur__c' => $user->getEmployeeIdentityCard(),
  500.                 'Email_actualite_des_ventes__c' => $user->isEmailOptin() ?? '',
  501.                 'Date_email_actualite_des_ventes__c' => $user->isEmailOptin() ? date('c'time()) : '',
  502.                 'SMS_actualite_des_ventes__c' => $user->isSmsOptin() ?? '',
  503.                 'Date_SMS_actualite_des_ventes__c' => $user->isSmsOptin() ? date('c'time()) : '',
  504.                 'Validation_Url__c' => $validationUrl,
  505.             ]);
  506.             $data $this->sfClient->upsert('Email', (object) $upSLead'Lead');
  507.             $this->salesforceDetailLogger->info(sprintf('SF %s, Lead | Create: %s %s'__FUNCTION__$data[0]->id ?? nulljson_encode($upSLeadJSON_PRETTY_PRINT)));
  508.             if (!empty($data)) {
  509.                 $user->setSfLeadId($data[0]->id);
  510.             }
  511.         }
  512.         $this->em->flush();
  513.     }
  514.     private function registerUser(User $user): void
  515.     {
  516.         switch ($user->getCountry()) {
  517.             case 'PT':
  518.                 $this->registerUserForCountry($user);
  519.                 break;
  520.             default:
  521.                 $id null;
  522.                 $upSUser = [];
  523.                 if (false !== $leadExists $this->sfClient->exists('Lead', ['Email' => $user->getEmail()])) {
  524.                     $data $this->sfClient->convert($leadExists['id'], $user->getId());
  525.                     $id $data[0]->accountId;
  526.                 } elseif (false !== $exists $this->sfClient->exists('Account', ['ExternalId__c' => $user->getEmail(), 'IsPersonAccount' => true])) {
  527.                     $id $exists['id'];
  528.                     $user->setSfAccountId($id);
  529.                     $sUser $this->sfClient->findOne([
  530.                         'Phone',
  531.                         'PersonMobilePhone',
  532.                         'Fax',
  533.                         'PersonMailingStreet',
  534.                         'PersonMailingCity',
  535.                         'PersonMailingCountry',
  536.                         'PersonMailingPostalCode',
  537.                         'CanauxActifs__c',
  538.                     ],
  539.                         'Account',
  540.                         ['Id' => $id]
  541.                     );
  542.                     $this->hydrator->hydrate($sUser$user);
  543.                     $upSUser array_filter([
  544.                         'DateInscriptionWeb__c' => date('c'time()),
  545.                         'DerniereVisite__c' => date('c'time()),
  546.                         'Id' => $id,
  547.                     ]);
  548.                 } else {
  549.                     $upSUser array_filter([
  550.                         'LastName' => 'Nouvel inscrit',
  551.                         'PersonEmail' => $user->getEmail(),
  552.                         'RecordTypeId' => Constants::ACCOUNT_PERSON,
  553.                     ]);
  554.                 }
  555.                 $upSUser array_merge($upSUserarray_filter([
  556.                     'Inscription_Newsletter__c' => Formatter::bool($user->getNewsletter()),
  557.                     'Date_Heure_Inscription_Newsletter__c' => Formatter::date($user->getLastOptinChangeDate()),
  558.                     'DateInscriptionWeb__c' => date('c'time()),
  559.                     'DerniereVisite__c' => date('c'time()),
  560.                     'ExternalId__c' => $user->getEmail(),
  561.                     'Validation__c' => 'En attente',
  562.                     'Origine_de_la_piste_compte__c' => $user->getReferralSource(),
  563.                     'PersonLeadSource' => $user->getReferralSource(),
  564.                 ]));
  565.                 $countryName $this->getCountryFrenchName($user->getCountry());
  566.                 if ('ES' === $user->getCountry()) {
  567.                     $upSUser array_merge($upSUserarray_filter([
  568.                         'FirstName' => $user->getFirstname(),
  569.                         'LastName' => $user->getLastname(),
  570.                         'Phone' => $user->getPhone(),
  571.                         // Address
  572.                         'PersonMailingStreet' => $user->getAddress(),
  573.                         'PersonMailingPostalCode' => $user->getZipCode(),
  574.                         'PersonMailingCity' => $user->getCity(),
  575.                         // Metadata
  576.                         'Origine_de_la_piste_compte__c' => 'Inscription '.$countryName,
  577.                         // Attachments
  578.                         'Carte_d_identite_recto__c' => $this->router->generate('fos_user_get_document', ['fileField' => 'CNIRectoFile''user' => $user->getId()], UrlGeneratorInterface::ABSOLUTE_URL),
  579.                         'Carte_d_identit_verso__c' => $this->router->generate('fos_user_get_document', ['fileField' => 'CNIVersoFile''user' => $user->getId()], UrlGeneratorInterface::ABSOLUTE_URL),
  580.                     ]));
  581.                 } elseif ('BE' === $user->getCountry()) {
  582.                     $upSUser array_merge($upSUserarray_filter([
  583.                         'Origine_de_la_piste_compte__c' => 'Inscription '.$countryName,
  584.                     ]));
  585.                 }
  586.                 $upSUser array_merge($upSUserarray_filter([
  587.                     'PersonMailingCountry' => $countryName,
  588.                 ]));
  589.                 $data $this->sfClient->upsert(null === $id 'ExternalId__c' 'Id', (object) $upSUser'Account');
  590.                 $this->salesforceDetailLogger->info(sprintf('SF %s, Account | Create by form user: %s %s'__FUNCTION__$data[0]->id ?? nulljson_encode($upSUserJSON_PRETTY_PRINT)));
  591.                 if (!empty($data)) {
  592.                     $user->setSfAccountId($data[0]->id);
  593.                     $this->em->flush();
  594.                 }
  595.         }
  596.     }
  597.     private function registerUserForCountry(User $user): void
  598.     {
  599.         $validationUrl $this->router->generate('fos_user_registration_confirm', ['token' => $user->getConfirmationToken()], UrlGeneratorInterface::ABSOLUTE_URL);
  600.         $countryName $this->getCountryFrenchName($user->getCountry());
  601.         $upSLead array_filter([
  602.             'LastName' => $user->getLastname(),
  603.             'FirstName' => $user->getFirstname(),
  604.             'Email' => $user->getEmail(),
  605.             'Street' => $user->getAddress(),
  606.             'PostalCode' => $user->getZipCode(),
  607.             'City' => $user->getCity(),
  608.             'Country' => $countryName,
  609.             'Phone' => $user->getPhone(),
  610.             'MobilePhone' => $user->getMobile(),
  611.             'Langue__c' => $user->getLanguage(),
  612.             'Carte_d_identite_recto__c' => $this->router->generate('fos_user_get_document', ['fileField' => 'CNIRectoFile''user' => $user->getId()], UrlGeneratorInterface::ABSOLUTE_URL),
  613.             'Carte_d_identite_verso__c' => $this->router->generate('fos_user_get_document', ['fileField' => 'CNIVersoFile''user' => $user->getId()], UrlGeneratorInterface::ABSOLUTE_URL),
  614.             'Justificatif_de_domicile__c' => $this->router->generate('fos_user_get_document', ['fileField' => 'domiciliationFile''user' => $user->getId()], UrlGeneratorInterface::ABSOLUTE_URL),
  615.             'N_NIF__c' => $user->getNIFNumber(),
  616.             'LeadSource' => 'Inscription '.$countryName,
  617.             'Validation_Url__c' => $validationUrl,
  618.         ]);
  619.         $data $this->sfClient->upsert('Email', (object) $upSLead'Lead');
  620.         $this->salesforceDetailLogger->info(sprintf('SF %s, Lead | Create other country: %s %s'__FUNCTION__$data[0]->id ?? nulljson_encode($upSLeadJSON_PRETTY_PRINT)));
  621.         if (!empty($data)) {
  622.             $user->setSfLeadId($data[0]->id);
  623.             $this->em->flush();
  624.         }
  625.     }
  626.     private function getCountryFrenchName(?string $country): string
  627.     {
  628.         if (null === $country) {
  629.             return '';
  630.         }
  631.         $countries $this->dictionaryMap->get('registration_form_country''fr')->getValues();
  632.         return array_search($country$countries) ?: '';
  633.     }
  634.     private function createContactWithAccount($user$id): array
  635.     {
  636.         if (!$user instanceof ProUser) {
  637.             return [];
  638.         }
  639.         $upSContact array_filter([
  640.             'LastName' => $user->getLastname(),
  641.             'FirstName' => $user->getFirstname(),
  642.             'Email' => $user->getEmail(),
  643.             'Phone' => $user->getPhone() ?? $user->getMobile(),
  644.             'Fonction__c' => $user->getBusinessRole(),
  645.             'ExternalId__c' => $user->getEmail(),
  646.             'Email_actualite_des_ventes__c' => Formatter::bool($user->isEmailOptin()),
  647.             'Date_email_actualiet_des_ventes__c' => date('c'time()),
  648.             'SMS_actualite_des_ventes__c' => Formatter::bool($user->isSmsOptin()),
  649.             'Date_SMS_actualite_des_ventes__c' => date('c'time()),
  650.             'AccountId' => $id,
  651.         ]);
  652.         $this->salesforceDetailLogger->info(sprintf('SF %s, Contact | Create: %s %s'__FUNCTION__$idjson_encode($upSContactJSON_PRETTY_PRINT)));
  653.         return $this->sfClient->upsert('ExternalId__c', (object) $upSContact'Contact');
  654.     }
  655.     private function searchAccount(ProUser $user): ?array
  656.     {
  657.         $vat $user->getVAT();
  658.         $siret $user->getSiret();
  659.         $id $user->getId();
  660.         $companyName $user->getCompany();
  661.         if (null !== $vat) {
  662.             $data $this->sfClient->findOne(['Id''Name'], 'Account', ['NoTVAIntracommunautaire__c' => $vat'IsPersonAccount' => false]);
  663.             if (false !== $data) {
  664.                 $exists array_filter([
  665.                     'id' => $data->Id,
  666.                     'name' => $data->Name ?? null,
  667.                 ]);
  668.                 if ($companyName != $exists['name']) {
  669.                     $this->salesforceLogger->error(sprintf('IDVP : %s, IDSF : %s, Company SF : %s, Company VP : %s'$id$exists['id'], $exists['name'], $companyName));
  670.                 }
  671.                 $this->salesforceLogger->info(sprintf('%s on NoTVAIntracommunautaire__c with VAT : %s FOUND with ID = %s'__FUNCTION__$vat$exists['id']));
  672.                 return $exists;
  673.             }
  674.             $this->salesforceLogger->info(sprintf('%s on NoTVAIntracommunautaire__c with VAT : %s NOT FOUND'__FUNCTION__$vat));
  675.         }
  676.         if (null !== $siret) {
  677.             $data $this->sfClient->findOne(['Id''Name'], 'Account', ['Siret__c' => $siret'IsPersonAccount' => false]);
  678.             if (false !== $data) {
  679.                 $exists array_filter([
  680.                     'id' => $data->Id,
  681.                     'name' => $data->Name ?? null,
  682.                 ]);
  683.                 if ($companyName != $exists['name']) {
  684.                     $this->salesforceLogger->error(sprintf('IDVP : %s, IDSF : %s, Company SF : %s, Company VP : %s'$id$exists['id'], $exists['name'], $companyName));
  685.                 }
  686.                 $this->salesforceLogger->info(sprintf('%s on Siret__c with SIRET : %s FOUND with ID = %s'__FUNCTION__$siret$exists['id']));
  687.                 return $exists;
  688.             }
  689.             $this->salesforceLogger->info(sprintf('%s on Siret__c with SIRET : %s NOT FOUND'__FUNCTION__$siret));
  690.         }
  691.         return null;
  692.     }
  693.     private function searchContact(string $email)
  694.     {
  695.         if (false !== $exists $this->sfClient->exists('Contact', ['Email' => $email])) {
  696.             return $exists;
  697.         }
  698.         return null;
  699.     }
  700. }