src/Controller/ClientController.php line 656

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