src/EventSubscriber/Onboarding/LeadPostWriteSubcriber.php line 73

Open in your IDE?
  1. <?php
  2. /**
  3.  * Created by PhpStorm.
  4.  * User: SEBASTIAN TOVAR
  5.  * Date: 25/06/2019
  6.  * Time: 06:10 PM
  7.  */
  8. namespace App\EventSubscriber\Onboarding;
  9. use App\Entity\App\Role;
  10. use App\Entity\App\Ticket\Ticket;
  11. use App\Entity\Onboarding\Invitation;
  12. use App\Entity\Onboarding\Lead;
  13. use App\Entity\Onboarding\LeadStaff;
  14. use App\Repository\App\UserRepository;
  15. use App\Repository\Onboarding\LeadStaffRepository;
  16. use App\Services\InvitationService;
  17. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  18. use Symfony\Component\HttpKernel\Event\ViewEvent;
  19. use Symfony\Component\HttpKernel\KernelEvents;
  20. use Symfony\Contracts\Translation\TranslatorInterface;
  21. use ApiPlatform\Core\EventListener\EventPriorities;
  22. use Doctrine\ORM\EntityManagerInterface;
  23. use App\Repository\App\VendorRepository;
  24. use App\Repository\App\CompanyRepository;
  25. use App\Services\VendorService;
  26. use App\Services\UserService;
  27. use App\Entity\App\User;
  28. use App\Entity\App\Vendor;
  29. class LeadPostWriteSubcriber implements EventSubscriberInterface
  30. {
  31.     private $userRepository;
  32.     private $leadStaffRepository;
  33.     private $invitationService;
  34.     private $translator;
  35.     private $vendorRepository;
  36.     private $userService;
  37.     private $vendorService;
  38.     private $entityManager;
  39.     private $companyRepository;
  40.     public function __construct(
  41.         EntityManagerInterface $entityManager,
  42.         UserRepository $userRepository,
  43.         LeadStaffRepository $leadStaffRepository,
  44.         CompanyRepository $companyRepository,
  45.         VendorRepository $vendorRepository,
  46.         VendorService $vendorService,
  47.         UserService $userService,
  48.         InvitationService $invitationService,
  49.         TranslatorInterface $translator)
  50.     {
  51.         $this->entityManager $entityManager;
  52.         $this->userRepository $userRepository;
  53.         $this->leadStaffRepository $leadStaffRepository;
  54.         $this->invitationService $invitationService;
  55.         $this->translator $translator;
  56.         $this->vendorRepository $vendorRepository;
  57.         $this->userService $userService;
  58.         $this->vendorService $vendorService;
  59.         $this->companyRepository $companyRepository;
  60.     }
  61.     /**
  62.      * @param ViewEvent $event
  63.      * @throws \Doctrine\ORM\NonUniqueResultException
  64.      */
  65.     public function onKernelView(ViewEvent $event)
  66.     {
  67.         $lead $event->getControllerResult();
  68.         $request $event->getRequest();
  69.         $route $request->attributes->get('_route');
  70.         if (!($lead instanceof Lead))
  71.             return;
  72.         if(false == $this->entityManager->getConnection()->ping()){
  73.             $this->entityManager->getConnection()->close();
  74.             $this->entityManager->getConnection()->connect();
  75.         }
  76.         if ('api_leads_put_item' == $route) {
  77.             if ($lead->getFinish()) {
  78.                 $lead->setIsCompleted(true);
  79.                 $this->entityManager->persist($lead);
  80.                 $this->entityManager->flush();
  81.             }
  82.             $data json_decode($request->getContent(), true);
  83.             $version $lead->getVersion();
  84.             switch ($version) {
  85.                 case 1:
  86.                     $this->runEntitiesCreationV1($lead,$data);
  87.                     break;
  88.                 case 2:
  89.                     $this->runEntitiesCreationV2($lead,$data);
  90.                     break;
  91.             }
  92.         }
  93.     }
  94.     /**
  95.      * @param $vendorName
  96.      * @return mixed|string
  97.      */
  98.     protected function generateVendorCode($vendorName)
  99.     {
  100.         $baseCode strtoupper(iconv('UTF-8''ASCII//TRANSLIT'preg_replace('/\s/'''$vendorName)));
  101.         $baseCode str_replace("'"''$baseCode);
  102.         $code $baseCode;
  103.         do {
  104.             $vendorWithCode $this->entityManager->getRepository(Vendor::class)->findOneBy(['signUpCode' => $code]);
  105.             if (!$vendorWithCode instanceof Vendor) {
  106.                 break;
  107.             }
  108.             $code $baseCode.rand(1999);
  109.         } while (true);
  110.         return $code;
  111.     }
  112.     /**
  113.      * @param Lead $lead
  114.      * @param $data
  115.      * @throws \Doctrine\ORM\NonUniqueResultException
  116.      */
  117.     protected function runEntitiesCreationV2(Lead $lead$data)
  118.     {
  119.         //Se reporta que el formulario se ha completado
  120.         if ($lead->getIsCompleted()) {
  121.             $status null;
  122.             $success true;
  123.             //Create vendor
  124.             try {
  125.                 $vendor = new Vendor();
  126.                 $vendor->setName($lead->getVendorName());
  127.                 $vendor->setSignUpCode($this->generateVendorCode($vendor->getName()));
  128.                 $this->entityManager->persist($vendor);
  129.                 //$this->entityManager->merge($vendor);
  130.                 $lead->setVendor($vendor);
  131.                 $this->entityManager->persist($lead);
  132.                 //$this->entityManager->merge($lead);
  133.                 $this->entityManager->flush();
  134.                 $status['vendor'] = $this->translator->trans(
  135.                     'Vendor was successfully created',
  136.                     ['%name%' => $lead->getVendorName()],
  137.                     null,
  138.                     'es'
  139.                 );
  140.             } catch (\Exception $e) {
  141.                 $status['vendor'] = $this->translator->trans(
  142.                     'Error! Vendor was not created, user invitations could not be sent.',
  143.                     ['%name%' => $lead->getVendorName()],
  144.                     null,
  145.                     'es'
  146.                 );
  147.                 $success false;
  148.             }
  149.             if ($success) {
  150.                 //Create admin user
  151.                 $criteria $lead->getEmail() ?? $lead->getMobileNumber();
  152.                 $dataType $lead->getEmail() ? 'email' 'mobile';
  153.                 $msj '';
  154.                 $success $this->invitationService->createUserInvitationV2($vendor$lead, ['admin'], $msj);
  155.                 $status['admin'] = array(
  156.                     'criteria' => $criteria,
  157.                     'status' => $success,
  158.                     'msj' => $msj
  159.                 );
  160.                 if ($success) {
  161.                     //Create Requests
  162.                     $identify 1;
  163.                     if (!is_null($lead->getTask1())) {
  164.                         $success $this->invitationService->createTicket($identify$vendor$lead->getTask1());
  165.                         $status['task'][1] = $success $this->translator->trans(
  166.                             'Ticket was successfully created',
  167.                             [],
  168.                             null,
  169.                             'es'
  170.                         ) : $this->translator->trans('Error!, Ticket could not be created', [], null'es');
  171.                         $identify $success $identify;
  172.                     }
  173.                     if (!is_null($lead->getTask2())) {
  174.                         $success $this->invitationService->createTicket($identify$vendor$lead->getTask2());
  175.                         $status['task'][2] = $success $this->translator->trans(
  176.                             'Ticket was successfully created',
  177.                             [],
  178.                             null,
  179.                             'es'
  180.                         ) : $this->translator->trans('Error!, Ticket could not be created', [], null'es');
  181.                     }
  182.                 } else {
  183.                     //$this->entityManager->remove($vendor);
  184.                     $lead->setIsCompleted(false);
  185.                     $lead->setVendor(null);
  186.                 }
  187.             }
  188.             $lead->setStatusSummary($status);
  189.             if (false == $this->entityManager->getConnection()->ping()) {
  190.                 $this->entityManager->getConnection()->close();
  191.                 $this->entityManager->getConnection()->connect();
  192.             }
  193.             if (!$this->entityManager->isOpen()) {
  194.                 $this->entityManager = \Doctrine\ORM\EntityManager::create(
  195.                     $this->entityManager->getConnection(),
  196.                     $this->entityManager->getConfiguration()
  197.                 );
  198.             }
  199.             $this->entityManager->merge($lead);
  200.             $this->entityManager->flush();
  201.             $this->entityManager->clear();
  202.         }
  203.     }
  204.     /**
  205.      * @param Lead $lead
  206.      * @param $data
  207.      * @throws \Doctrine\ORM\NonUniqueResultException
  208.      */
  209.     protected function runEntitiesCreationV1(Lead $lead$data)
  210.     {
  211.         switch ($lead->getStep()) {
  212.             case Lead::USERS_STEP:
  213.                 $this->createLeadStaff($data['users'], $lead$lead->getStep());
  214.                 break;
  215.             case Lead::OPERATORS_STEP:
  216.                 $this->createLeadStaff($data['operators'], $lead$lead->getStep());
  217.                 break;
  218.             case Lead::TASKS_STEP:
  219.                 break;
  220.         }
  221.         //Se reporta que el formulario se ha completado
  222.         if ($lead->getIsCompleted()) {
  223.             $status null;
  224.             $success true;
  225.             //Create vendor
  226.             try {
  227.                 $vendor = new Vendor();
  228.                 $vendor->setName($lead->getVendorName());
  229.                 $vendor->setSignUpCode($this->generateVendorCode($vendor->getName()));
  230.                 $this->entityManager->persist($vendor);
  231.                 $lead->setVendor($vendor);
  232.                 $this->entityManager->persist($lead);
  233.                 $this->entityManager->flush();
  234.                 $status['vendor'] = $this->translator->trans(
  235.                     'Vendor was successfully created',
  236.                     ['%name%' => $lead->getVendorName()],
  237.                     null,
  238.                     'es'
  239.                 );
  240.             } catch (\Exception $e) {
  241.                 $status['vendor'] = $this->translator->trans(
  242.                     'Error! Vendor was not created, user invitations could not be sent.',
  243.                     ['%name%' => $lead->getVendorName()],
  244.                     null,
  245.                     'es'
  246.                 );
  247.                 $success false;
  248.             }
  249.             if ($success) {
  250.                 //Create admin user
  251.                 $criteria $lead->getEmail() ?? $lead->getMobileNumber();
  252.                 $dataType $lead->getEmail() ? 'email' 'mobile';
  253.                 $msj '';
  254.                 $success $this->invitationService->createUserInvitation(
  255.                     $vendor,
  256.                     $criteria,
  257.                     $dataType,
  258.                     [Role::ROLE_ADMIN],
  259.                     $lead->getName(),
  260.                     $msj,
  261.                     true,
  262.                     $lead->getName()
  263.                 );
  264.                 $status['admin'] = array(
  265.                     'criteria' => $criteria,
  266.                     'status' => $success,
  267.                     'msj' => $msj
  268.                 );
  269.                 //Create staff
  270.                 $leadStaff $lead->getLeadStaff();
  271.                 $count 0;
  272.                 foreach ($leadStaff as $staffItem) {
  273.                     $roles null;
  274.                     if ($staffItem->getIsUser()) {
  275.                         $roles[] = Role::ROLE_USER;
  276.                     }
  277.                     if ($staffItem->getIsOperator()) {
  278.                         $roles[] = Role::ROLE_OPERATOR;
  279.                     }
  280.                     if (!is_null($roles)) {
  281.                         $criteria $staffItem->getEmail() ?? $staffItem->getPhoneNumber();
  282.                         $dataType $staffItem->getEmail() ? 'email' 'mobile';
  283.                         $msj '';
  284.                         $success $this->invitationService->createUserInvitation(
  285.                             $vendor,
  286.                             $criteria,
  287.                             $dataType,
  288.                             $roles,
  289.                             $lead->getName(),
  290.                             $msj
  291.                         );
  292.                         $status['staff'][$count] = array(
  293.                             "criteria" => $criteria,
  294.                             "status" => $success,
  295.                             "msj" => $msj
  296.                         );
  297.                         if ($success) {
  298.                             $staffItem->setIsAlreadyInvited(true);
  299.                             $this->entityManager->persist($staffItem);
  300.                             $this->entityManager->flush();
  301.                         }
  302.                         $count++;
  303.                     }
  304.                 }
  305.                 //Create Requests
  306.                 $identify 1;
  307.                 if (!is_null($lead->getTask1())) {
  308.                     $success $this->invitationService->createTicket($identify$vendor$lead->getTask1());
  309.                     $status['task'][1] = $success $this->translator->trans(
  310.                         'Ticket was successfully created',
  311.                         [],
  312.                         null,
  313.                         'es'
  314.                     ) : $this->translator->trans('Error!, Ticket could not be created', [], null'es');
  315.                     $identify $success $identify;
  316.                 }
  317.                 if (!is_null($lead->getTask2())) {
  318.                     $success $this->invitationService->createTicket($identify$vendor$lead->getTask2());
  319.                     $status['task'][2] = $success $this->translator->trans(
  320.                         'Ticket was successfully created',
  321.                         [],
  322.                         null,
  323.                         'es'
  324.                     ) : $this->translator->trans('Error!, Ticket could not be created', [], null'es');
  325.                 }
  326.             }
  327.             $lead->setStatusSummary($status);
  328.             if (false == $this->entityManager->getConnection()->ping()) {
  329.                 $this->entityManager->getConnection()->close();
  330.                 $this->entityManager->getConnection()->connect();
  331.             }
  332.             $this->entityManager->persist($lead);
  333.             $this->entityManager->flush();
  334.         }
  335.     }
  336.     protected function createLeadStaff($contactsFieldLead $lead$step) {
  337.         $contactArray = array();
  338.         if (!is_null($contactsField)) {
  339.             $contactArray explode(",",preg_replace('/\s+/','',$contactsField));
  340.             //Adding leadStaff
  341.             foreach ($contactArray as $contact) {
  342.                 if(!empty($contact)) {
  343.                     $leadStaff $this->leadStaffRepository->loadLeadByEmailMobile($contact,$lead);
  344.                     if (!$leadStaff instanceof  LeadStaff) {
  345.                         $leadStaff = new LeadStaff();
  346.                         $leadStaff->setLead($lead);
  347.                         if (filter_var($contactFILTER_VALIDATE_EMAIL)) {
  348.                             $leadStaff->setEmail($contact);
  349.                         }
  350.                         elseif (preg_match('/^\+[\d -]+$/'$contact)) {
  351.                             $leadStaff->setPhoneNumber($contact);
  352.                         }
  353.                     }
  354.                     if ($step == Lead::OPERATORS_STEP) {
  355.                         $leadStaff->setIsOperator(true);
  356.                     }
  357.                     elseif ($step == Lead::USERS_STEP) {
  358.                         $leadStaff->setIsUser(true);
  359.                     }
  360.                     $this->entityManager->persist($leadStaff);
  361.                     $this->entityManager->flush();
  362.                 }
  363.             }
  364.         }
  365.         //Removing leadStaff
  366.         $leadStaff $lead->getLeadStaff();
  367.         foreach ($leadStaff as $leadStaffItem) {
  368.             $criteria $leadStaffItem->getEmail() ?? $leadStaffItem->getPhoneNumber();
  369.             if (!in_array($criteria$contactArray)) {
  370.                 if ($step == Lead::USERS_STEP && $leadStaffItem->getIsUser()) {
  371.                     $leadStaffItem->setIsUser(false);
  372.                 }
  373.                 elseif ($step == Lead::OPERATORS_STEP && $leadStaffItem->getIsOperator()) {
  374.                     $leadStaffItem->setIsOperator(false);
  375.                 }
  376.                 $this->entityManager->persist($leadStaffItem);
  377.                 $this->entityManager->flush();
  378.             }
  379.         }
  380.     }
  381.     public static function getSubscribedEvents()
  382.     {
  383.         return [
  384.             KernelEvents::VIEW => ['onKernelView'EventPriorities::POST_WRITE]
  385.         ];
  386.     }
  387. }