src/Controller/ClientController.php line 656

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