src/Controller/ClientController.php line 43

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 $translator, EntityManagerInterface $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($idgroup, Request $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 $request, LoggerInterface $logger, EntityManagerInterface $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($id, Request $request, LoggerInterface $logger, EntityManagerInterface $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.             // Si el usuario es vacío, saltamos al siguiente contacto
  312.             if (!$user) { continue; }
  313.             $datos_agent =array(
  314.                 'assignedAgent' => $user->getName()." ".$user->getLastName(),
  315.                 'createdId' => $user->getName()." ".$user->getLastName(),
  316.             );
  317.             $contactos[] = $datos_agent;
  318.         }
  319.         foreach ($usuarios as $usuario){
  320.             $nombres_usuarios[] = array(
  321.                 "id" => $usuario->getId(),
  322.                 "nombre" => $usuario->getName()." ".$usuario->getLastName(),
  323.             );
  324.         }
  325.         $form = $this->createEditClientForm($client, $id);
  326.         $form->handleRequest($request);
  327.         
  328.         $office_usuario = $form->get('idOffice')->getData();
  329.         if(!is_null($office_usuario)){
  330.             $client->setIdOffice($office_usuario->getId());
  331.         }
  332.         $groupId = $form->get('groupId')->getData();
  333.         if(!is_null($groupId)){
  334.             $client->setGroupId($groupId->getId());
  335.         }
  336.         $returninvestment_data = $form->get('returninvestment')->getData();
  337.         if(!is_null($returninvestment_data)){
  338.             $client->setReturnInvestment($returninvestment_data->getName());
  339.         }
  340.         $group_client = $form->get('groupId')->getData();
  341.         if(!is_null($group_client)){
  342.             $client->setGroupId($group_client->getId());
  343.         }
  344.         if($form->isValid())
  345.         {
  346.             if(!empty($returnnew)){
  347.                 $client->setReturnInvestment($returnnew);
  348.                 $returninvestment = new ReturnInvestment();
  349.                 $returninvestment->setName($returnnew);
  350.                 $this->em->persist($returninvestment);
  351.             }
  352.             /* Obtengo usuario logueado */
  353.             $user_logueado = $this->get('security.token_storage')->getToken()->getUser();
  354.             $user_id = $user_logueado->getId();
  355.             $client->getUpdatedId($user_id);
  356. //            $this->em->persist($client);
  357. //            $this->em->flush();
  358.             /* Gestión de eventos en Log */
  359.             $user_lastname = $user_logueado->getLastname();
  360.             $user_name = $user_logueado->getName();
  361.             $user_email = $user_logueado->getEmail();
  362.             $user_rol = $user_logueado->getRoles();
  363.             $event_url = $request->getPathInfo();
  364.             $event_complete = $user_name.' '.$user_lastname.' - '.$user_email.' - '.$user_rol[0].' | '.$event_url;
  365.             try{
  366.                 $this->em->persist($client);
  367.                 $this->em->flush();
  368.                 $event = 'The Client has been Updated. Now';
  369.                 $successMessage = $this->translator->trans($event);
  370.                 $this->addFlash('mensajeclient', $successMessage);
  371.                 $logger->info($event_complete.' | '.$event);
  372.             } catch (\Exception $e){
  373.                 $event = 'An error occurred: '.$e->getMessage();
  374.                 /* Para el log */
  375.                 $logger->error($event_complete.' | '.$event);
  376.                 /* Para el usuario */
  377.                 $errorMessage = $this->translator->trans($event);
  378.                 $this->addFlash('mensajeclienterror', $errorMessage);
  379.             }
  380.             /* Fin Gestión de eventos en Log */
  381. //            return $this->redirectToRoute('client_list');
  382.             return $this->render('client/client/edit-client.html.twig',
  383.                 array(
  384.                     'id' => $client->getId(),
  385.                     'client' => $client,
  386.                     'nombres_usuarios' => $nombres_usuarios,
  387.                     'contact' => $contactos,
  388.                     'idClient' => $id,
  389.                     'form' => $form->createView()
  390.                 )
  391.             );
  392.         }else{
  393.             $errorMessage = $this->translator->trans('Error, some fields are empty');
  394.             $this->addFlash('mensajeclienterror', $errorMessage);
  395.         }
  396.         return $this->render('client/client/edit-client.html.twig',
  397.             array(
  398.                 'id' => $client->getId(),
  399.                 'client' => $client,
  400.                 'nombres_usuarios' => $nombres_usuarios,
  401.                 'contact' => $contactos,
  402.                 'idClient' => $id,
  403.                 'form' => $form->createView()
  404.             )
  405.         );
  406.     }
  407.     /**
  408.      * @Route("/client/add-image", name="client_image")
  409.      */
  410.     public function addClientImage()
  411.     {
  412.         $dataa = $_POST['image'];
  413.         list($type, $data) = explode(';', $dataa);
  414.         list(, $data)      = explode(',', $data);
  415.         $data = base64_decode($data);
  416.         $imageName = time().'.png';
  417.         $ruta = "assets/images/clients/";
  418.         if (!file_exists($ruta)) {
  419.             mkdir($ruta,0777,true);
  420.         }
  421.         $file = fopen($ruta.$imageName, "wb");
  422.         fwrite($file, $data);
  423.         fclose($file);
  424.         $return = array(
  425.             'base64' => $dataa,
  426.             'nombre_archivo' => $ruta.$imageName,
  427.         );
  428.         $response = new JsonResponse($return);
  429.         return $response;
  430.     }
  431.     /**
  432.      * @Route("/client/editt/addContact", name="client_add_contact_from_modal")
  433.      */
  434.     public function addContactFromModal()
  435.     {
  436.         $name = $_POST['name'];
  437.         $lastName = $_POST['lastName'];
  438.         $position = $_POST['position'];
  439.         $department = $_POST['department'];
  440.         $birthday = $_POST['birthday'];
  441.         $typeclient = $_POST['typeclient'];
  442.         $assignedAgent = $_POST['assignedAgent'];
  443.         $email = $_POST['email'];
  444.         $phone = $_POST['phone'];
  445.         $mobile = $_POST['mobile'];
  446.         $idClient = $_POST['idClient'];
  447. //        d($birthday);
  448.         $contact = new ClientContact();
  449.         $contact->setName($name);
  450.         $contact->setLastName($lastName);
  451.         $contact->setPosition($position);
  452.         $contact->setDepartment($department);
  453.         $contact->setBirthday($birthday);
  454.         $contact->setTypeclient($typeclient);
  455.         $contact->setAssignedAgent($assignedAgent);
  456.         $contact->setEmail($email);
  457.         $contact->setPhone($phone);
  458.         $contact->setMobile($mobile);
  459.         $contact->setClientId($idClient);
  460.         $contact->setClientId($idClient);
  461. //        $contact->setClientId($idClient);
  462. //        $contact->setClientId($idClient);
  463. //        $contact->set($idClient);
  464. //        $contact->setClientId($idClient);
  465. //        d($contact);
  466.         $this->em->persist($contact);
  467.         $this->em->flush();
  468.     }
  469.     /**
  470.      * @Route("/client/listdesplegable", name="get_client_select")
  471.      */
  472.     public function clientSelectAction(Request $request) {
  473.         $clients = $this->em->getRepository(Client::class)->findAll();
  474.         $datos = array();
  475.         if (!empty($clients)){
  476.             foreach($clients as $client){
  477.                 $datos[] = array(
  478.                     "id" => $client->getId(),
  479.                     "name" => $client->getName(),
  480.                     "title" => $client->getTitle()
  481.                 );
  482.             }
  483.         }
  484.         else
  485.         {
  486.             $datos[] = array(
  487.                 "id" => '',
  488.                 "name" => '',
  489.                 "title" => ''
  490.             );
  491.         }
  492.         $return = array(
  493.             'clients' => $datos,
  494.         );
  495.         $response = new JsonResponse($return);
  496.         return $response;
  497.     }
  498.     /**
  499.      * Devuelve el cliente según el id recibido por url
  500.      * 
  501.      * @Route("/client/get/{id}", name="get_client", methods={"GET"})
  502.      */
  503.     public function getClientAction($id) {
  504.         $client = $this->em->getRepository(Client::class)->findOneById($id);
  505.         $return = array(
  506.             'id' => $client->getId(),
  507.             'name' => $client->getName(),
  508.             'title' => $client->getTitle(),
  509.             'typology' => $client->getTypology(),
  510.         );
  511.         $response = new JsonResponse($return);
  512.         return $response;
  513.     }
  514. }