src/Controller/ClientController.php line 591

Open in your IDE?
  1. <?php
  2. /**
  3.  * Created by Mediterranean Develup Solutions
  4.  * User: jorge.defreitas@develup.solutions
  5.  * Date: 29/06/2017
  6.  * Time: 14:17
  7.  */
  8. namespace App\Controller;
  9. use App\Entity\Cities;
  10. use App\Entity\ClientContact;
  11. use App\Entity\ReturnInvestment;
  12. use App\Entity\Client;
  13. use App\Entity\Country;
  14. use App\Entity\Group;
  15. use App\Entity\Provinces;
  16. use App\Entity\Regions;
  17. use App\Entity\SettingsOffice;
  18. use App\Entity\User;
  19. use App\Form\ClientType;
  20. use Doctrine\ORM\EntityManagerInterface;
  21. use Psr\Log\LoggerInterface;
  22. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  23. use Symfony\Component\Routing\Annotation\Route;
  24. use Symfony\Component\HttpFoundation\JsonResponse;
  25. use Symfony\Component\HttpFoundation\Request;
  26. use Symfony\Contracts\Translation\TranslatorInterface;
  27. class ClientController extends AbstractController
  28. {
  29.     private $translator;
  30.     private EntityManagerInterface $em;
  31.     public function __construct(TranslatorInterface $translatorEntityManagerInterface $em) {
  32.         $this->translator $translator;
  33.         $this->em $em;
  34.     }
  35.     
  36.     /**
  37.      * @Route("/client/add",  name="client_add")
  38.      */
  39.     public function addClientAction(Request $request)
  40.     {
  41.         $user $this->getUser();
  42.         // Crear un nuevo cliente
  43.         $client = new Client();
  44.         if($user->getOffice() == 2){
  45.             // Para los usuarios de barcelona se muestra los datos de barcelona
  46.             $client->setCountry(62)
  47.                 ->setRegion(967)
  48.                 ->setProvince(8)
  49.                 ->setPopulation(697806);
  50.         }else{
  51.             //Para todos los demás se muestra madrid
  52.             $client->setCountry(62)
  53.                 ->setRegion(969)
  54.                 ->setProvince(28)
  55.                 ->setPopulation(713549);
  56.         }
  57.         // Crear el formulario, pasando las entidades como opciones
  58.         $form $this->createClientCreateForm($client);
  59.         // Renderizar la plantilla del formulario
  60.         return $this->render('client/client/add-client.html.twig', [
  61.             'form' => $form->createView(),
  62.         ]);
  63.     }
  64.     /**
  65.      * @Route("/client/list/{idgroup}", defaults={"idgroup" = 0}, name="client_index")
  66.      */
  67.     public function indexAction($idgroupRequest $request) {
  68.         $group $this->em->getRepository(Group::class)->findById($idgroup);
  69.         if ($idgroup == 0){
  70.             $client $this->em->getRepository(Client::class)->findAll();
  71.         }else{
  72.             $client $this->em->getRepository(Client::class)->findBy(
  73.                 array( 'groupId' => $idgroup)
  74.             );
  75.         }
  76.         return $this->render('client/client/list-client.html.twig',
  77.             array(
  78.                 'groups' => $group,
  79.                 'clients' => $client
  80.             )
  81.         );
  82.     }
  83. //    /**
  84. //     * @Route("/client/add/{idgroup}", defaults={"idgroup" = 0}, name="client_add")
  85. //     */
  86. //    public function addClientAction($idgroup, Request $request)
  87. //    {
  88. //        $client = new Client();
  89. //        $client->setGroupId($idgroup);
  90. //        $form = $this->createClientCreateForm($client);
  91. //
  92. //        return $this->render('client/client/add-client.html.twig', array('form' => $form->createView()));
  93. //    }
  94.     private function createClientCreateForm(Client $entity)
  95.     {
  96.         $form $this->createForm(ClientType::class, $entity, array(
  97.             'action' => $this->generateUrl('client_create'),
  98.             'method' => 'POST'
  99.         ));
  100.         return $form;
  101.     }
  102.     /**
  103.      * @Route("/client/create", name="client_create")
  104.      */
  105.     public function createAction(Request $requestLoggerInterface $loggerEntityManagerInterface $em)
  106.     {
  107.         $returnnew $request->request->get('client_esp')['returnnew'];
  108.         // Crear un nuevo cliente
  109.         $client = new Client();
  110.         $client->setPopulation($request->request->get('client')['population']);
  111.         $form $this->createClientCreateForm($client);
  112.         $form->handleRequest($request);
  113.         $isClientInOut $form->get('is_client_in_out')->getData();
  114.         $isClientGreenPatio $form->get('is_client_green_patio')->getData();
  115.         $isClientAvExpress $form->get('is_client_av_express')->getData();
  116.         $isClientDevelup $form->get('is_client_develup')->getData();
  117.         if(!is_null($isClientInOut)){
  118.             $client->setIsClientInOut($isClientInOut);
  119.         }
  120.         if(!is_null($isClientGreenPatio)){
  121.             $client->setIsClientGreenPatio($isClientGreenPatio);
  122.         }
  123.         if(!is_null($isClientAvExpress)){
  124.             $client->setIsClientAvExpress($isClientAvExpress);
  125.         }
  126.         if(!is_null($isClientDevelup)){
  127.             $client->setIsClientDevelup($isClientDevelup);
  128.         }
  129.         $telephone_data $form->get('telephone')->getData();
  130.         $office_client $form->get('idOffice')->getData();
  131.         if(!is_null($office_client)){
  132.             $client->setIdOffice($office_client->getId());
  133.         }
  134.         $errores=0;
  135.         $campo="";
  136.         if (empty($client->getPopulation())){
  137.             $errores 1;
  138.             $campo $this->translator->trans("City");
  139.         }elseif (empty($client->getProvince())){
  140.             $errores 1;
  141.             $campo $this->translator->trans("Province");
  142.         }
  143.         $group_client $form->get('groupId')->getData();
  144.         if(!is_null($group_client)){
  145.             $client->setGroupId($group_client->getId());
  146.         }
  147.         $returninvestment_data $form->get('returninvestment')->getData();
  148.         if(!is_null($returninvestment_data)){
  149.             $client->setReturnInvestment($returninvestment_data->getName());
  150.         }
  151.         $verifico_phone $this->em->getRepository(Client::class)->findOneByTelephone($telephone_data);
  152.         if($errores == "0") {
  153.             if (empty($verifico_phone)) {
  154.                 if($form->isValid())
  155.                 {
  156.                     /* Obtengo usuario logueado */
  157.                     $user_logueado $this->get('security.token_storage')->getToken()->getUser();
  158.                     $user_id $user_logueado->getId();
  159.                     $client->setCreatedId($user_id);
  160.                     $client->setUpdatedId($user_id);
  161.                     //                $this->em->persist($client);
  162.                     //                $this->em->flush();
  163.                     /* Gestión de eventos en Log */
  164.                     $user_lastname $user_logueado->getLastname();
  165.                     $user_name $user_logueado->getName();
  166.                     $user_email $user_logueado->getEmail();
  167.                     $user_rol $user_logueado->getRoles();
  168.                     $event_url $request->getPathInfo();
  169.                     $event_complete $user_name.' '.$user_lastname.' - '.$user_email.' - '.$user_rol[0].' | '.$event_url;
  170.                     try{
  171.                         $this->em->persist($client);
  172.                         $this->em->flush();
  173.                         $event 'The Client has been created. Now, add some contacts';
  174.                         $successMessage $this->translator->trans($event);
  175.                         $this->addFlash('mensajeclient'$successMessage);
  176.                         if(!empty($returnnew)){
  177.                             $client->setReturnInvestment($returnnew);
  178.                             $returninvestment = new ReturnInvestment();
  179.                             $returninvestment->setName($returnnew);
  180.                             $this->em->persist($returninvestment);
  181.                             $this->em->flush();
  182.                         }
  183.                         $logger->info($event_complete.' | '.$event);
  184.                     } catch (\Exception $e){
  185.                         $event 'An error occurred: '.$e->getMessage();
  186.                         /* Para el log */
  187.                         $logger->error($event_complete.' | '.$event);
  188.                         /* Para el usuario */
  189.                         $errorMessage $this->translator->trans($event);
  190.                         $this->addFlash('mensajeclienterror'$errorMessage);
  191.                     }
  192.                     /* Fin Gestión de eventos en Log */
  193.                     //                $clientrappelcontrol = new ClientRappelControl();
  194.                     //                $clientrappelcontrol->setClientId($client->getId());
  195.                     //                $clientrappelcontrol->setCreatedId($user_id);
  196.                     //                $clientrappelcontrol->setUpdatedId($user_id);
  197.                     //                $this->em->persist($clientrappelcontrol);
  198.                     //                $this->em->flush();
  199. //                    $v = $client->getId();                        //GEAO
  200. //                    d($v);                                        //GEAO
  201. //
  202. //                    if(!empty($v)) {
  203.                     return $this->redirectToRoute('contact_add',
  204.                         array(
  205.                             'idclient' => $client->getId()
  206.                         )
  207.                     );
  208. //                    }
  209.                 }else{
  210.                     $errorMessage $this->translator->trans('Error, some fields are empty');
  211.                     $this->addFlash('mensajeclienterror'$errorMessage);
  212.                 }
  213.             }else{
  214.                 $errorMessage $this->translator->trans('The Client already exists');
  215.                 $this->addFlash('mensajeclienterror'$errorMessage);
  216.             }
  217.         } else {
  218.             $errorMessage $this->translator->trans('Error, this field is empty ');
  219.             $this->addFlash('mensajeclienterror'$errorMessage.$campo);
  220.         }
  221.         return $this->render('client/client/add-client.html.twig', array(
  222.                 'form' => $form->createView()
  223.             )
  224.         );
  225.     }
  226.     /**
  227.      * @Route("/client/edit/{id}", name="client_edit")
  228.      */
  229.     public function editAction($id)
  230.     {
  231.         $client $this->em->getRepository(Client::class)->findOneById($id);
  232.         $contacts $this->em->getRepository(ClientContact::class)->findByClient_id($id);
  233.         $usuarios $this->em->getRepository(User::class)->findAll();
  234.         $contactos null;
  235.         $nombres_usuarios = array();
  236.         foreach ($contacts as $contact){
  237.             $user $this->em->getRepository(User::class)->findOneById($contact->getAssignedAgent());
  238.             $creator $this->em->getRepository(User::class)->findOneById($contact->getCreatedId());
  239. //            $contact->setAssignedAgent($user->getName()." ".$user->getLastName());
  240.             $contact->setAssignedAgent(
  241.                 $user
  242.                     $user->getName() . ' ' $user->getLastName()
  243.                     : 'Usuario de baja'
  244.             );
  245. //            $contact->setCreatedId($creator->getName()." ".$creator->getLastName());
  246.             $contact->setCreatedId(
  247.                 $creator
  248.                     $creator->getName() . ' ' $creator->getLastName()
  249.                     : 'Usuario de baja'
  250.             );
  251.             $contactos[] = $contact;
  252.         }
  253.         foreach ($usuarios as $usuario){
  254.             $nombres_usuarios[] = array(
  255.                 "id" => $usuario->getId(),
  256.                 "nombre" => $usuario->getName()." ".$usuario->getLastName(),
  257.             );
  258.         }
  259.         /*
  260.          * Office, Company y Userrol son entityclass (en el formulario) que funcionan como
  261.          * unos campos <select>,
  262.          * por lo tanto necesitan que le pases el objeto para poder recordar los campos y no
  263.          * le vale que le metas a pelo el id o el nombre del campo recuperado
  264.          */
  265.         $office $this->em->getRepository(SettingsOffice::class)->findOneById($client->getIdOffice());
  266.         $client->setIdOffice($office);
  267.         $grupo $this->em->getRepository(Group::class)->findOneById($client->getGroupId());
  268.         $client->setGroupId($grupo);
  269.         $returninvestment $this->em->getRepository(ReturnInvestment::class)->findOneByName($client->getReturnInvestment());
  270.         $client->setReturnInvestment($returninvestment);
  271.         $form $this->createEditClientForm($client$id);
  272.         return $this->render('client/client/edit-client.html.twig',
  273.             array(
  274.                 'id' => $id,
  275.                 'client' => $client,
  276.                 'nombres_usuarios' => $nombres_usuarios,
  277.                 'contact' => $contactos,
  278.                 'idClient' => $id,
  279.                 'form' => $form->createView()
  280.             )
  281.         );
  282.     }
  283.     private function createEditClientForm(Client $entity$id)
  284.     {
  285.         $form $this->createForm(ClientType::class, $entity,
  286.             array(
  287.                 'action' => $this->generateUrl('client_update',
  288.                     array(
  289.                         'id' => $id
  290.                     )
  291.                 ), 'method' => 'PUT'));
  292.         return $form;
  293.     }
  294.     /**
  295.      * @Route("/client/update/{id}", name="client_update", methods={"POST", "PUT"})
  296.      */
  297.     public function updateAction($idRequest $requestLoggerInterface $loggerEntityManagerInterface $em)
  298.     {
  299.         // $region = $_POST['client']['region'];
  300.         // $province = $_POST['client']['province'];
  301.         // $population = $_POST['client']['population'];
  302.         $returnnew $request->request->get('client_esp')['returnnew'];
  303.         $client $this->em->getRepository(Client::class)->findOneById($id);
  304.         $contacts $this->em->getRepository(ClientContact::class)->findByClient_id($id);
  305.         $usuarios $this->em->getRepository(User::class)->findAll();
  306.         $contactos = array();
  307.         $nombres_usuarios = array();
  308.         foreach ($contacts as $contact){
  309.             $user $this->em->getRepository(User::class)->findOneById($contact->getAssignedAgent());
  310.             $creator $this->em->getRepository(User::class)->findOneById($contact->getCreatedId());
  311.             $datos_agent =array(
  312.                 'assignedAgent' => $user->getName()." ".$user->getLastName(),
  313.                 'createdId' => $user->getName()." ".$user->getLastName(),
  314.             );
  315.             $contactos[] = $datos_agent;
  316.         }
  317.         foreach ($usuarios as $usuario){
  318.             $nombres_usuarios[] = array(
  319.                 "id" => $usuario->getId(),
  320.                 "nombre" => $usuario->getName()." ".$usuario->getLastName(),
  321.             );
  322.         }
  323.         $form $this->createEditClientForm($client$id);
  324.         $form->handleRequest($request);
  325.         
  326.         $office_usuario $form->get('idOffice')->getData();
  327.         if(!is_null($office_usuario)){
  328.             $client->setIdOffice($office_usuario->getId());
  329.         }
  330.         $groupId $form->get('groupId')->getData();
  331.         if(!is_null($groupId)){
  332.             $client->setGroupId($groupId->getId());
  333.         }
  334.         $returninvestment_data $form->get('returninvestment')->getData();
  335.         if(!is_null($returninvestment_data)){
  336.             $client->setReturnInvestment($returninvestment_data->getName());
  337.         }
  338.         $group_client $form->get('groupId')->getData();
  339.         if(!is_null($group_client)){
  340.             $client->setGroupId($group_client->getId());
  341.         }
  342.         if($form->isValid())
  343.         {
  344.             if(!empty($returnnew)){
  345.                 $client->setReturnInvestment($returnnew);
  346.                 $returninvestment = new ReturnInvestment();
  347.                 $returninvestment->setName($returnnew);
  348.                 $this->em->persist($returninvestment);
  349.             }
  350.             /* Obtengo usuario logueado */
  351.             $user_logueado $this->get('security.token_storage')->getToken()->getUser();
  352.             $user_id $user_logueado->getId();
  353.             $client->getUpdatedId($user_id);
  354. //            $this->em->persist($client);
  355. //            $this->em->flush();
  356.             /* Gestión de eventos en Log */
  357.             $user_lastname $user_logueado->getLastname();
  358.             $user_name $user_logueado->getName();
  359.             $user_email $user_logueado->getEmail();
  360.             $user_rol $user_logueado->getRoles();
  361.             $event_url $request->getPathInfo();
  362.             $event_complete $user_name.' '.$user_lastname.' - '.$user_email.' - '.$user_rol[0].' | '.$event_url;
  363.             try{
  364.                 $this->em->persist($client);
  365.                 $this->em->flush();
  366.                 $event 'The Client has been Updated. Now';
  367.                 $successMessage $this->translator->trans($event);
  368.                 $this->addFlash('mensajeclient'$successMessage);
  369.                 $logger->info($event_complete.' | '.$event);
  370.             } catch (\Exception $e){
  371.                 $event 'An error occurred: '.$e->getMessage();
  372.                 /* Para el log */
  373.                 $logger->error($event_complete.' | '.$event);
  374.                 /* Para el usuario */
  375.                 $errorMessage $this->translator->trans($event);
  376.                 $this->addFlash('mensajeclienterror'$errorMessage);
  377.             }
  378.             /* Fin Gestión de eventos en Log */
  379. //            return $this->redirectToRoute('client_list');
  380.             return $this->render('client/client/edit-client.html.twig',
  381.                 array(
  382.                     'id' => $client->getId(),
  383.                     'client' => $client,
  384.                     'nombres_usuarios' => $nombres_usuarios,
  385.                     'contact' => $contactos,
  386.                     'idClient' => $id,
  387.                     'form' => $form->createView()
  388.                 )
  389.             );
  390.         }else{
  391.             $errorMessage $this->translator->trans('Error, some fields are empty');
  392.             $this->addFlash('mensajeclienterror'$errorMessage);
  393.         }
  394.         return $this->render('client/client/edit-client.html.twig',
  395.             array(
  396.                 'id' => $client->getId(),
  397.                 'client' => $client,
  398.                 'nombres_usuarios' => $nombres_usuarios,
  399.                 'contact' => $contactos,
  400.                 'idClient' => $id,
  401.                 'form' => $form->createView()
  402.             )
  403.         );
  404.     }
  405.     /**
  406.      * @Route("/client/add-image", name="client_image")
  407.      */
  408.     public function addClientImage()
  409.     {
  410.         $dataa $_POST['image'];
  411.         list($type$data) = explode(';'$dataa);
  412.         list(, $data)      = explode(','$data);
  413.         $data base64_decode($data);
  414.         $imageName time().'.png';
  415.         $ruta "assets/images/clients/";
  416.         if (!file_exists($ruta)) {
  417.             mkdir($ruta,0777,true);
  418.         }
  419.         $file fopen($ruta.$imageName"wb");
  420.         fwrite($file$data);
  421.         fclose($file);
  422.         $return = array(
  423.             'base64' => $dataa,
  424.             'nombre_archivo' => $ruta.$imageName,
  425.         );
  426.         $response = new JsonResponse($return);
  427.         return $response;
  428.     }
  429.     /**
  430.      * @Route("/client/editt/addContact", name="client_add_contact_from_modal")
  431.      */
  432.     public function addContactFromModal()
  433.     {
  434.         $name $_POST['name'];
  435.         $lastName $_POST['lastName'];
  436.         $position $_POST['position'];
  437.         $department $_POST['department'];
  438.         $birthday $_POST['birthday'];
  439.         $typeclient $_POST['typeclient'];
  440.         $assignedAgent $_POST['assignedAgent'];
  441.         $email $_POST['email'];
  442.         $phone $_POST['phone'];
  443.         $mobile $_POST['mobile'];
  444.         $idClient $_POST['idClient'];
  445. //        d($birthday);
  446.         $contact = new ClientContact();
  447.         $contact->setName($name);
  448.         $contact->setLastName($lastName);
  449.         $contact->setPosition($position);
  450.         $contact->setDepartment($department);
  451.         $contact->setBirthday($birthday);
  452.         $contact->setTypeclient($typeclient);
  453.         $contact->setAssignedAgent($assignedAgent);
  454.         $contact->setEmail($email);
  455.         $contact->setPhone($phone);
  456.         $contact->setMobile($mobile);
  457.         $contact->setClientId($idClient);
  458.         $contact->setClientId($idClient);
  459. //        $contact->setClientId($idClient);
  460. //        $contact->setClientId($idClient);
  461. //        $contact->set($idClient);
  462. //        $contact->setClientId($idClient);
  463. //        d($contact);
  464.         $this->em->persist($contact);
  465.         $this->em->flush();
  466.     }
  467.     /**
  468.      * @Route("/client/listdesplegable", name="get_client_select")
  469.      */
  470.     public function clientSelectAction(Request $request) {
  471.         $clients $this->em->getRepository(Client::class)->findAll();
  472.         $datos = array();
  473.         if (!empty($clients)){
  474.             foreach($clients as $client){
  475.                 $datos[] = array(
  476.                     "id" => $client->getId(),
  477.                     "name" => $client->getName(),
  478.                     "title" => $client->getTitle()
  479.                 );
  480.             }
  481.         }
  482.         else
  483.         {
  484.             $datos[] = array(
  485.                 "id" => '',
  486.                 "name" => '',
  487.                 "title" => ''
  488.             );
  489.         }
  490.         $return = array(
  491.             'clients' => $datos,
  492.         );
  493.         $response = new JsonResponse($return);
  494.         return $response;
  495.     }
  496.     /**
  497.      * Devuelve el cliente según el id recibido por url
  498.      * 
  499.      * @Route("/client/get/{id}", name="get_client", methods={"GET"})
  500.      */
  501.     public function getClientAction($id) {
  502.         $client $this->em->getRepository(Client::class)->findOneById($id);
  503.         $return = array(
  504.             'id' => $client->getId(),
  505.             'name' => $client->getName(),
  506.             'title' => $client->getTitle(),
  507.             'typology' => $client->getTypology(),
  508.         );
  509.         $response = new JsonResponse($return);
  510.         return $response;
  511.     }
  512. }