src/Controller/ClientController.php line 658

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