src/Controller/ClientController.php line 655

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