src/Services/Contact/ContactService.php line 93

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Services\Contact;
  4. use Doctrine\Persistence\ManagerRegistry;
  5. use Symfony\Component\HttpFoundation\RequestStack;
  6. use Symfony\Component\HttpKernel\Exception\UnprocessableEntityHttpException;
  7. use Symfony\Component\Security\Core\Security;
  8. use Symfony\Component\Form\Form;
  9. use Symfony\Component\EventDispatcher\EventDispatcherInterface;
  10. use App\Entity\{ContactCsptypeCountryCampaign};
  11. use App\Services\SerializerService;
  12. use App\Repository\{ContactRepositoryContactConferenceRepository};
  13. use App\Services\{
  14.     Contact\RelatedContactService,
  15.     Campaign\DatasetService,
  16. };
  17. use App\Event\CampaignUpdateHistoryEvent;
  18. use App\Common\Traits\FormatTextToExportTrait;
  19. class ContactService
  20. {
  21.     use FormatTextToExportTrait;
  22.     
  23.     private const CSV_EXPORT_FILENAME 'contacts-export';
  24.     private ManagerRegistry $doctrine;
  25.     private RequestStack $requestStack;
  26.     private Security $security;
  27.     private EventDispatcherInterface $dispatcher;
  28.     private SerializerService $serializerService;
  29.     private ContactRepository $contactRepository;
  30.     private DatasetService $datasetService;
  31.     private RelatedContactService $relatedContactService;
  32.     private ContactConferenceRepository $contactConferenceRepository;
  33.     public function __construct(
  34.         ManagerRegistry $doctrine,
  35.         RequestStack $requestStack,
  36.         Security $security,
  37.         EventDispatcherInterface $dispatcher,
  38.         SerializerService $serializerService,
  39.         ContactRepository $contactRepository,
  40.         DatasetService $datasetService,
  41.         RelatedContactService $relatedContactService,
  42.         ContactConferenceRepository $contactConferenceRepository
  43.     ) {
  44.         $this->doctrine $doctrine;
  45.         $this->requestStack $requestStack;
  46.         $this->security $security;
  47.         $this->dispatcher $dispatcher;
  48.         $this->serializerService $serializerService;
  49.         $this->contactRepository $contactRepository;
  50.         $this->datasetService $datasetService;
  51.         $this->relatedContactService $relatedContactService;
  52.         $this->contactConferenceRepository $contactConferenceRepository;
  53.     }
  54.     public function getList(
  55.         int $mode,
  56.         ?array $sort = [],
  57.         int $from null,
  58.         int $to null
  59.     ): mixed {
  60.         $session $this->requestStack->getSession();
  61.         $contactSearchCriteria $session->has('contactSearchCriteria')
  62.             ? $session->get('contactSearchCriteria')
  63.             : []
  64.         ;
  65.         $contacts $this->contactRepository->findList($mode$sort$from$to$contactSearchCriteria);
  66.         if (in_array($mode, [13])) {
  67.             return $contacts;
  68.         }
  69.         return json_encode($contacts);
  70.     }
  71.     public function getContactsCount(): int
  72.     {
  73.         return $this->contactRepository->findList(1)['itemsCount'];
  74.     }
  75.     public function getContactCspsAndCountriesCount()
  76.     {
  77.         $session $this->requestStack->getSession();
  78.             $contactSearchCriteria $session->has('contactSearchCriteria')
  79.                 ? $session->get('contactSearchCriteria')
  80.                 : []
  81.             ;
  82.             $counts $this->contactRepository->findList(1, [], nullnull$contactSearchCriteriatrue);
  83.             return [
  84.                 'cspsCount' => $counts['cspsCount'],
  85.                 'countriesCount' => $counts['countriesCount'],
  86.                 'cspCountryCount' => $counts['cspCountryCount'],
  87.             ];
  88.     }
  89.     public function getCspContactCount(): int
  90.     {
  91.         return $this->contactRepository->getTotalCspContactCount();
  92.     }
  93.     public function getCountryContactCount(): int
  94.     {
  95.         return $this->contactRepository->getTotatCountryContactCount();
  96.     }
  97.     public function getCspCountryContactCount(): int
  98.     {
  99.         return $this->contactRepository->getTotatCspCountryContactCount();
  100.     }
  101.     /**
  102.      * @throws Exception
  103.      * @throws UnprocessableEntityHttpException
  104.      */
  105.     public function saveContact(
  106.         Contact $contact,
  107.         Form $form,
  108.         bool $editMod,
  109.         int $csptypeId,
  110.         ?int $countryId,
  111.         ?string $operation null,
  112.         ?Contact $refContact null,
  113.         ?Campaign $campaign null,
  114.         ?Contact $sourceContact null
  115.     ): void {
  116.         if (false === $editMod && $operation !== Contact::OPERATION_UPDATE) {
  117.             $this->checkIfEmailExists($contact);
  118.         }
  119.         $entityManager $this->doctrine->getManager();
  120.         $entityManager->getConnection()->beginTransaction();
  121.         try {
  122.             $contact->setCsptype($entityManager->getReference(Csptype::class, $csptypeId));
  123.             if ($countryId) {
  124.                 $contact->setCountry($entityManager->getReference(Country::class, $countryId));
  125.             }
  126.             $entityManager->persist($contact);
  127.             $entityManager->flush();
  128.             $updateHistory false;
  129.             if (null !== $campaign) {
  130.                 if (false === $editMod) {
  131.                     $this->datasetService->addContactToDataset($campaign$contact$operation$refContact);
  132.                     $updateHistory true;
  133.                 } else {
  134.                     $this->datasetService->saveCampaignContactData($campaign$contact$form);
  135.                     if ($sourceContact && false === $contact->equals($sourceContact)) {
  136.                         $updateHistory true;
  137.                     }
  138.                 }
  139.             }
  140.             if (
  141.                 $operation === Contact::OPERATION_RELATED
  142.                 && $refContact instanceof Contact
  143.             ) {
  144.                 $this->relatedContactService->linkRelatedContacts($refContact$contact);
  145.             }
  146.             if (
  147.                 $operation === Contact::OPERATION_UPDATE
  148.                 && $refContact instanceof Contact
  149.             ) {
  150.                 $this->contactConferenceRepository->updateContactConferences($contact$refContact);
  151.                 $entityManager->remove($refContact);
  152.                 $entityManager->flush();
  153.             }
  154.             if (true === $updateHistory) {
  155.                 if ($operation === Contact::OPERATION_UPDATE) {
  156.                     $entityManager->clear();
  157.                 }
  158.                 $this->dispatchCampaignUpdateHistory($campaign);
  159.             }
  160.             $entityManager->getConnection()->commit();
  161.         } catch (\Exception $exception) {
  162.             $entityManager->getConnection()->rollBack();
  163.             throw $exception;
  164.         }
  165.     }
  166.     private function dispatchCampaignUpdateHistory(Campaign $campaign): void
  167.     {
  168.         $this->dispatcher->dispatch(
  169.             new CampaignUpdateHistoryEvent($campaign$this->security->getUser()),
  170.             CampaignUpdateHistoryEvent::NAME
  171.         );
  172.     }
  173.     /**
  174.      * @throws UnprocessableEntityHttpException
  175.      */
  176.     private function checkIfEmailExists(Contact $contact): void
  177.     {
  178.         $checkContactEmail $this->doctrine->getRepository(Contact::class)->findOneBy(
  179.             ['email' => $contact->getEmail(),]
  180.         );
  181.         if ($checkContactEmail instanceof Contact) {
  182.             throw new UnprocessableEntityHttpException('The contact you are trying to add already exists in the CRM.<br />Please search and add using their email address');
  183.         }
  184.     }
  185.     public function setContactLockStatus(Contact $contactbool $lockStatusbool $forceUnlock false): void
  186.     {
  187.         if (
  188.             (true === $lockStatus && null !== $contact->getLockDate() && null !== $contact->getLockUser())
  189.             || (false === $forceUnlock && false === $lockStatus && $this->security->getUser() !== $contact->getLockUser())
  190.         ) {
  191.             return;
  192.         }
  193.         $entityManager $this->doctrine->getManager();
  194.         $contact
  195.             ->setLockDate(true === $lockStatus ? new \DateTime() : null)
  196.             ->setLockUser(true === $lockStatus $this->security->getUser() : null)
  197.         ;
  198.         $entityManager->flush();
  199.     }
  200.     public function moveToTrash(Contact $contact): void
  201.     {
  202.         $entityManager $this->doctrine->getManager();
  203.         $contact
  204.             ->setTrash(true)
  205.             ->setLockDate(null)
  206.             ->setLockUser(null)
  207.         ;
  208.         $entityManager->flush();
  209.     }
  210.     public function getCsvExportFilename(): string
  211.     {
  212.         return sprintf('%s-%s.csv'self::CSV_EXPORT_FILENAME, (new \DateTime())->format('YmdHis'));
  213.     }
  214.     public function getCsvExportData(array $data): string
  215.     {
  216.         ini_set('memory_limit', -1);
  217.         $rows = new \SplFixedArray(count($data) + 1);
  218.         $line = ["ID""Company""Group""Country""Region""Industry""Company Type""Title""Firstname",
  219.             "Lastname""Position""Division""Direct Phone Number""Mobile Phone Number"
  220.             "Email Address""National headquarter switchboard phone number",];
  221.         if ($this->security->isGranted('ROLE_PM')) {
  222.             $line array_merge(
  223.                 $line,
  224.                 ["LinkedIn Profile""Valid email""Comments""Last update""Conferences""Source",]
  225.             );
  226.         }
  227.         //$rows = implode(';', $line) . "\n";
  228.         $i 0;
  229.         $rows[$i++] = implode(';'$line); // . "\n";
  230.         foreach ($data as $contact) {
  231.             /*$rows .= $contact['id'].";".
  232.                 $contact['cspName'].";".
  233.                 $contact['cspGroup'].";".
  234.                 $contact['countryName'].";".
  235.                 $contact['regionName'].";".
  236.                 $contact['csptypeName'].";".
  237.                 $contact['title'].";".
  238.                 $contact['fname'].";".
  239.                 $contact['lname'].";".
  240.                 $contact['position'].";".
  241.                 $contact['division'].";".
  242.                 $contact['phone1'].";".
  243.                 $contact['phone2'].";".
  244.                 $contact['email'].";".
  245.                 $contact['switchboardPhone']
  246.             ;
  247.             if ($this->security->isGranted('ROLE_PM')) {
  248.                 $rows .= ";".$contact['linkedinUrl'].";".
  249.                     (int) $contact['validEmail'].";".
  250.                     $contact['comment'].";".
  251.                     ((null !== $contact['updatedAt']) ? $contact['updatedAt']->format('d/m/Y H:i') : '').";".
  252.                     $contact['conferences'].";".
  253.                     $contact['sourceName']
  254.                 ;
  255.             }*/
  256.             $line sprintf(
  257.                 "%s;%s;%s;%s;%s;%s;%s;%s;%s;%s;%s;%s;%s;%s;%s;%s",
  258.                 $contact['id'],
  259.                 $contact['cspName'],
  260.                 $contact['cspGroup'],
  261.                 $contact['countryName'],
  262.                 $contact['regionName'],
  263.                 $contact['csptypeName'],
  264.                 $contact['companyTypes'],
  265.                 $contact['title'],
  266.                 $contact['fname'],
  267.                 $contact['lname'],
  268.                 $contact['position'],
  269.                 $contact['division'],
  270.                 $contact['phone1'],
  271.                 $contact['phone2'],
  272.                 $contact['email'],
  273.                 $contact['switchboardPhone']
  274.             );
  275.             if ($this->security->isGranted('ROLE_PM')) {
  276.                 $comment $this->formatTextToExport($contact['comment']);
  277.                 $line .= sprintf(
  278.                     ";%s;%s;%s;%s;%s;%s",
  279.                     $contact['linkedinUrl'],
  280.                     (int) $contact['validEmail'],
  281.                     $comment,
  282.                     (null !== $contact['updatedAt']) ? $contact['updatedAt']->format('d/m/Y H:i') : '',
  283.                     $contact['conferences'],
  284.                     $contact['sourceName']
  285.                 );
  286.             }
  287.             //$line .= "\n";
  288.             $rows[$i++] = $line;
  289.         }
  290.         
  291.         //return $rows;
  292.         return implode("\n"$rows->toArray());
  293.     }
  294.     public function findContactDuplicates(Contact $contactstring $dup): array
  295.     {
  296.         $filter $dup === 'name'
  297.             ? ['fname' => $contact->getFname(), 'lname' => $contact->getLname(), 'csp' => $contact->getCsp(), 'trash' => false,]
  298.             : ['email' => $contact->getEmail(), 'trash' => false,]
  299.         ;
  300.         $duplicates $this->contactRepository->findBy($filter);
  301.         foreach ($duplicates as $key => $dup) {
  302.             if ($dup->getId() === $contact->getId()) {
  303.                 unset($duplicates[$key]);
  304.             }
  305.         }
  306.         return array_values($duplicates);
  307.     }
  308. }