src/Controller/ClientController.php line 580

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->setCreatedId($creator->getName()." ".$creator->getLastName());
  241.             $contactos[] = $contact;
  242.         }
  243.         foreach ($usuarios as $usuario){
  244.             $nombres_usuarios[] = array(
  245.                 "id" => $usuario->getId(),
  246.                 "nombre" => $usuario->getName()." ".$usuario->getLastName(),
  247.             );
  248.         }
  249.         /*
  250.          * Office, Company y Userrol son entityclass (en el formulario) que funcionan como
  251.          * unos campos <select>,
  252.          * por lo tanto necesitan que le pases el objeto para poder recordar los campos y no
  253.          * le vale que le metas a pelo el id o el nombre del campo recuperado
  254.          */
  255.         $office $this->em->getRepository(SettingsOffice::class)->findOneById($client->getIdOffice());
  256.         $client->setIdOffice($office);
  257.         $grupo $this->em->getRepository(Group::class)->findOneById($client->getGroupId());
  258.         $client->setGroupId($grupo);
  259.         $returninvestment $this->em->getRepository(ReturnInvestment::class)->findOneByName($client->getReturnInvestment());
  260.         $client->setReturnInvestment($returninvestment);
  261.         $form $this->createEditClientForm($client$id);
  262.         return $this->render('client/client/edit-client.html.twig',
  263.             array(
  264.                 'id' => $id,
  265.                 'client' => $client,
  266.                 'nombres_usuarios' => $nombres_usuarios,
  267.                 'contact' => $contactos,
  268.                 'idClient' => $id,
  269.                 'form' => $form->createView()
  270.             )
  271.         );
  272.     }
  273.     private function createEditClientForm(Client $entity$id)
  274.     {
  275.         $form $this->createForm(ClientType::class, $entity,
  276.             array(
  277.                 'action' => $this->generateUrl('client_update',
  278.                     array(
  279.                         'id' => $id
  280.                     )
  281.                 ), 'method' => 'PUT'));
  282.         return $form;
  283.     }
  284.     /**
  285.      * @Route("/client/update/{id}", name="client_update", methods={"POST", "PUT"})
  286.      */
  287.     public function updateAction($idRequest $requestLoggerInterface $loggerEntityManagerInterface $em)
  288.     {
  289.         // $region = $_POST['client']['region'];
  290.         // $province = $_POST['client']['province'];
  291.         // $population = $_POST['client']['population'];
  292.         $returnnew $request->request->get('client_esp')['returnnew'];
  293.         $client $this->em->getRepository(Client::class)->findOneById($id);
  294.         $contacts $this->em->getRepository(ClientContact::class)->findByClient_id($id);
  295.         $usuarios $this->em->getRepository(User::class)->findAll();
  296.         $contactos = array();
  297.         $nombres_usuarios = array();
  298.         foreach ($contacts as $contact){
  299.             $user $this->em->getRepository(User::class)->findOneById($contact->getAssignedAgent());
  300.             $creator $this->em->getRepository(User::class)->findOneById($contact->getCreatedId());
  301.             $datos_agent =array(
  302.                 'assignedAgent' => $user->getName()." ".$user->getLastName(),
  303.                 'createdId' => $user->getName()." ".$user->getLastName(),
  304.             );
  305.             $contactos[] = $datos_agent;
  306.         }
  307.         foreach ($usuarios as $usuario){
  308.             $nombres_usuarios[] = array(
  309.                 "id" => $usuario->getId(),
  310.                 "nombre" => $usuario->getName()." ".$usuario->getLastName(),
  311.             );
  312.         }
  313.         $form $this->createEditClientForm($client$id);
  314.         $form->handleRequest($request);
  315.         
  316.         $office_usuario $form->get('idOffice')->getData();
  317.         if(!is_null($office_usuario)){
  318.             $client->setIdOffice($office_usuario->getId());
  319.         }
  320.         $groupId $form->get('groupId')->getData();
  321.         if(!is_null($groupId)){
  322.             $client->setGroupId($groupId->getId());
  323.         }
  324.         $returninvestment_data $form->get('returninvestment')->getData();
  325.         if(!is_null($returninvestment_data)){
  326.             $client->setReturnInvestment($returninvestment_data->getName());
  327.         }
  328.         $group_client $form->get('groupId')->getData();
  329.         if(!is_null($group_client)){
  330.             $client->setGroupId($group_client->getId());
  331.         }
  332.         if($form->isValid())
  333.         {
  334.             if(!empty($returnnew)){
  335.                 $client->setReturnInvestment($returnnew);
  336.                 $returninvestment = new ReturnInvestment();
  337.                 $returninvestment->setName($returnnew);
  338.                 $this->em->persist($returninvestment);
  339.             }
  340.             /* Obtengo usuario logueado */
  341.             $user_logueado $this->get('security.token_storage')->getToken()->getUser();
  342.             $user_id $user_logueado->getId();
  343.             $client->getUpdatedId($user_id);
  344. //            $this->em->persist($client);
  345. //            $this->em->flush();
  346.             /* Gestión de eventos en Log */
  347.             $user_lastname $user_logueado->getLastname();
  348.             $user_name $user_logueado->getName();
  349.             $user_email $user_logueado->getEmail();
  350.             $user_rol $user_logueado->getRoles();
  351.             $event_url $request->getPathInfo();
  352.             $event_complete $user_name.' '.$user_lastname.' - '.$user_email.' - '.$user_rol[0].' | '.$event_url;
  353.             try{
  354.                 $this->em->persist($client);
  355.                 $this->em->flush();
  356.                 $event 'The Client has been Updated. Now';
  357.                 $successMessage $this->translator->trans($event);
  358.                 $this->addFlash('mensajeclient'$successMessage);
  359.                 $logger->info($event_complete.' | '.$event);
  360.             } catch (\Exception $e){
  361.                 $event 'An error occurred: '.$e->getMessage();
  362.                 /* Para el log */
  363.                 $logger->error($event_complete.' | '.$event);
  364.                 /* Para el usuario */
  365.                 $errorMessage $this->translator->trans($event);
  366.                 $this->addFlash('mensajeclienterror'$errorMessage);
  367.             }
  368.             /* Fin Gestión de eventos en Log */
  369. //            return $this->redirectToRoute('client_list');
  370.             return $this->render('client/client/edit-client.html.twig',
  371.                 array(
  372.                     'id' => $client->getId(),
  373.                     'client' => $client,
  374.                     'nombres_usuarios' => $nombres_usuarios,
  375.                     'contact' => $contactos,
  376.                     'idClient' => $id,
  377.                     'form' => $form->createView()
  378.                 )
  379.             );
  380.         }else{
  381.             $errorMessage $this->translator->trans('Error, some fields are empty');
  382.             $this->addFlash('mensajeclienterror'$errorMessage);
  383.         }
  384.         return $this->render('client/client/edit-client.html.twig',
  385.             array(
  386.                 'id' => $client->getId(),
  387.                 'client' => $client,
  388.                 'nombres_usuarios' => $nombres_usuarios,
  389.                 'contact' => $contactos,
  390.                 'idClient' => $id,
  391.                 'form' => $form->createView()
  392.             )
  393.         );
  394.     }
  395.     /**
  396.      * @Route("/client/add-image", name="client_image")
  397.      */
  398.     public function addClientImage()
  399.     {
  400.         $dataa $_POST['image'];
  401.         list($type$data) = explode(';'$dataa);
  402.         list(, $data)      = explode(','$data);
  403.         $data base64_decode($data);
  404.         $imageName time().'.png';
  405.         $ruta "assets/images/clients/";
  406.         if (!file_exists($ruta)) {
  407.             mkdir($ruta,0777,true);
  408.         }
  409.         $file fopen($ruta.$imageName"wb");
  410.         fwrite($file$data);
  411.         fclose($file);
  412.         $return = array(
  413.             'base64' => $dataa,
  414.             'nombre_archivo' => $ruta.$imageName,
  415.         );
  416.         $response = new JsonResponse($return);
  417.         return $response;
  418.     }
  419.     /**
  420.      * @Route("/client/editt/addContact", name="client_add_contact_from_modal")
  421.      */
  422.     public function addContactFromModal()
  423.     {
  424.         $name $_POST['name'];
  425.         $lastName $_POST['lastName'];
  426.         $position $_POST['position'];
  427.         $department $_POST['department'];
  428.         $birthday $_POST['birthday'];
  429.         $typeclient $_POST['typeclient'];
  430.         $assignedAgent $_POST['assignedAgent'];
  431.         $email $_POST['email'];
  432.         $phone $_POST['phone'];
  433.         $mobile $_POST['mobile'];
  434.         $idClient $_POST['idClient'];
  435. //        d($birthday);
  436.         $contact = new ClientContact();
  437.         $contact->setName($name);
  438.         $contact->setLastName($lastName);
  439.         $contact->setPosition($position);
  440.         $contact->setDepartment($department);
  441.         $contact->setBirthday($birthday);
  442.         $contact->setTypeclient($typeclient);
  443.         $contact->setAssignedAgent($assignedAgent);
  444.         $contact->setEmail($email);
  445.         $contact->setPhone($phone);
  446.         $contact->setMobile($mobile);
  447.         $contact->setClientId($idClient);
  448.         $contact->setClientId($idClient);
  449. //        $contact->setClientId($idClient);
  450. //        $contact->setClientId($idClient);
  451. //        $contact->set($idClient);
  452. //        $contact->setClientId($idClient);
  453. //        d($contact);
  454.         $this->em->persist($contact);
  455.         $this->em->flush();
  456.     }
  457.     /**
  458.      * @Route("/client/listdesplegable", name="get_client_select")
  459.      */
  460.     public function clientSelectAction(Request $request) {
  461.         $clients $this->em->getRepository(Client::class)->findAll();
  462.         $datos = array();
  463.         if (!empty($clients)){
  464.             foreach($clients as $client){
  465.                 $datos[] = array(
  466.                     "id" => $client->getId(),
  467.                     "name" => $client->getName(),
  468.                     "title" => $client->getTitle()
  469.                 );
  470.             }
  471.         }
  472.         else
  473.         {
  474.             $datos[] = array(
  475.                 "id" => '',
  476.                 "name" => '',
  477.                 "title" => ''
  478.             );
  479.         }
  480.         $return = array(
  481.             'clients' => $datos,
  482.         );
  483.         $response = new JsonResponse($return);
  484.         return $response;
  485.     }
  486.     /**
  487.      * Devuelve el cliente según el id recibido por url
  488.      * 
  489.      * @Route("/client/get/{id}", name="get_client", methods={"GET"})
  490.      */
  491.     public function getClientAction($id) {
  492.         $client $this->em->getRepository(Client::class)->findOneById($id);
  493.         $return = array(
  494.             'id' => $client->getId(),
  495.             'name' => $client->getName(),
  496.             'title' => $client->getTitle(),
  497.             'typology' => $client->getTypology(),
  498.         );
  499.         $response = new JsonResponse($return);
  500.         return $response;
  501.     }
  502. }