src/Controller/PerfilController.php line 230

  1. <?php
  2. namespace App\Controller;
  3. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  4. use Symfony\Component\HttpFoundation\Request;
  5. use Symfony\Component\HttpFoundation\Response;
  6. use Symfony\Component\Routing\Annotation\Route;
  7. use Symfony\Component\HttpFoundation\JsonResponse;
  8. use Symfony\Component\HttpFoundation\ResponseHeaderBag;
  9. use Symfony\Component\HttpFoundation\BinaryFileResponse;
  10. use Symfony\Contracts\Translation\TranslatorInterface;
  11. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  12. use Doctrine\ORM\EntityManagerInterface;
  13. use Knp\Component\Pager\PaginatorInterface;
  14. use Symfony\Component\HttpFoundation\Cookie;
  15. use Symfony\Component\HttpFoundation\RequestStack;
  16. use Doctrine\Persistence\ManagerRegistry as PersistenceManagerRegistry;
  17. use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
  18. use Symfony\Component\Security\Core\Security;
  19. use Symfony\Component\HttpClient\HttpClient;
  20. use Symfony\Component\HttpFoundation\File\File;
  21. use Symfony\Component\Cache\Adapter\FilesystemAdapter;
  22. use Symfony\Contracts\Cache\ItemInterface;
  23. use App\Utils\Util;
  24. use Psr\Log\LoggerInterface;
  25. use App\Entity\Contenido;
  26. use App\Entity\Reserva;
  27. use App\Entity\AddresLog;
  28. use App\Entity\Alerta;
  29. use App\Entity\User;
  30. use App\Services\ConfigurationManager;
  31. use App\Services\SettingsManager;
  32. use App\Services\WebServiceOficinas;
  33. use App\Services\WebServiceReservas;
  34. use App\Services\WebServiceTarifasTPV;
  35. use App\Services\WebServiceTPV;
  36. use App\Services\WebServiceUsuarios;
  37. use App\Services\WebServiceDivisas;
  38. use App\Services\WebServiceFunciones;
  39. use App\Services\Mailer;
  40. use Symfony\Component\Form\Extension\Core\Type\HiddenType;
  41. use App\Form\ViajeType;
  42. use App\Form\ProfileType;
  43. use App\Form\CardType;
  44. use App\Form\AlertasType;
  45. use App\Form\ClientType;
  46. class PerfilController extends AbstractController
  47. {
  48.     private $authorizationChecker;
  49.     
  50.     public function __construct(AuthorizationCheckerInterface $authorizationChecker
  51.     {
  52.             $this->authorizationChecker $authorizationChecker;
  53.     }
  54.     public function saveProfile($profileForm$WSF$UserId$em)
  55.     {
  56.         $profile $profileForm->getData();
  57.         //var_dump($profile);
  58.         $direccion2 '';
  59.         if (strlen($profile->getDireccion1()) > 50) {
  60.             $direccion1 substr($profile->getDireccion1(), 050);
  61.             $direccion2 substr($profile->getDireccion1(), 5050);
  62.         } else {
  63.             $direccion1 $profile->getDireccion1();
  64.             $direccion2 '';
  65.         }
  66.         $WSF->modificarDireccion1($UserId$direccion1);
  67.         $WSF->modificarDireccion2($UserId$direccion2);
  68.         $WSF->modificarPoblacion($UserId$profile->getCiudad());
  69.         $WSF->modificarTelefono($UserId$profile->getTlf());
  70.         $WSF->modificarCodPostal($UserId$profile->getCp());
  71.         $WSF->modificarEmail($UserId$profile->getEmail());
  72.         $WSF->modificarProvincia($UserId$profile->getCounty());
  73.         $user $this->getUser();
  74.         $user->setEmail($profile->getEmail());
  75.         $em->persist($user);
  76.         $em->flush();
  77.     }
  78.     
  79.     
  80.     public function saveIdCard($WSF$usrEnt$fileName$em$logger)
  81.     {
  82. //         $user = $this->getUser();
  83. //         $card = $cardForm->getData();
  84. //         $erpDate = $card->getFechaCaducidad()->format('Y-m-d');
  85. //         $nacFecha = $card->getFechaNacimiento()->format('Y-m-d');
  86.         
  87.         if ($usrEnt->getUrlImagen()) {
  88.         
  89.             $file $this->getParameter('dni_directory').'/'.$fileName;
  90.             
  91.             try {
  92.                 //Upload the image to Eurochange FTP
  93.                 $ftp_server $this->getParameter('get_ftp_domain');
  94.                 $ftp_user_name $this->getParameter('get_ftp_user');
  95.                 $ftp_user_pass $this->getParameter('get_ftp_password');
  96.                 $ftp_user_folder $this->getParameter('get_ftp_dni_folder');
  97.                 
  98.                 $conn_id ftp_connect($ftp_server);
  99.                 $login_result ftp_login($conn_id$ftp_user_name$ftp_user_pass);
  100.                 
  101.                 if ((!$conn_id) || (!$login_result)) {
  102.                     return $this->redirect($this->generateUrl('app_critical_error'));
  103.                 }
  104.                 
  105.                 ftp_pasv($conn_idtrue);
  106.                 $upload ftp_put($conn_id$ftp_user_folder $fileName$fileFTP_BINARY);
  107.                 
  108.                 /**ACTIVAR PRODUCCION**/
  109.     //             $WS = $this->container->get('web.service.funciones', $em);
  110.                 // $WSF->CargarImagen($this->getUser()->getErpId(), $fileName);
  111.                 /****/
  112.                 
  113.                 //Tras subir la imagen al FTP del ERP, borramos la nuestra
  114.                 // if (file_exists($file)) {
  115.                 //     unlink($file);
  116.                 // }
  117.                 
  118.                 $usrEnt->setUrlImagen($fileName);
  119. //                 $em->persist($usrEnt);
  120. //                 $em->flush();
  121.             } catch (\Exception $e) {
  122. //                 $logger = $this->get('logger');
  123.                 $logger->info('[DINAMIC][ERROR][PROFILE] :' $e);
  124.                 return $this->redirect($this->generateUrl('app_critical_error'));
  125.             }
  126.             
  127.             // if(file_exists($this->getParameter('dni_directory') . '/' . $usrEnt->getUrlImagen())){
  128.             //     unlink($this->getParameter('dni_directory') . '/' . $usrEnt->getUrlImagen());
  129.             // }
  130.             
  131.         }
  132.         $WSF->modificarNombre($usrEnt->getErpId(), $usrEnt->getName());
  133.         $WSF->modificarTipoId($usrEnt->getErpId(), $usrEnt->getTipoDocumento()->getCodigo());
  134.         $WSF->modificarFechaExpiracion($usrEnt->getErpId(), $usrEnt->getFechaCaducidad()->format('Y-m-d'));
  135.         $WSF->modificarNumId($usrEnt->getErpId(), $usrEnt->getIdCard());
  136.         $WSF->modificarPais($usrEnt->getErpId(), $usrEnt->getPais());
  137.         $WSF->modificarFechaNacimiento($usrEnt->getErpId(), $usrEnt->getFechaNacimiento()->format('Y-m-d'));
  138.         
  139.     }
  140.     
  141.      #[Route(path: [
  142.         'es' => '/perfil/descargar',
  143.         'en' => '/en/profile/download'
  144.     ], name'app_profile_download')]
  145.     public function downloadAction(Request $requestPersistenceManagerRegistry $doctrineWebServiceFunciones $wsf)
  146.     {
  147.         try {
  148.             $user $this->getUser();
  149.             $filename $request->query->get('ticket');
  150.             $em $doctrine->getManager();
  151. //             $WS = $this->container->get('web.service.funciones', $em);
  152.             $ftp_server $this->getParameter('get_ftp_domain');
  153.             $ftp_user_name $this->getParameter('get_ftp_user');
  154.             $ftp_user_pass $this->getParameter('get_ftp_password');
  155.             $ftp_user_folder $this->getParameter('get_ftp_ticket_folder');
  156. //             $path = $this->get('kernel')->getRootDir() . "/../ticket/";
  157.             $path $this->getParameter('kernel.project_dir'). "/ticket/";
  158. // dump($path); die();
  159.             $conn_id ftp_connect($ftp_server);
  160.             $admin $this->authorizationChecker->isGranted('ROLE_ADMIN');
  161.             $gestor $this->authorizationChecker->isGranted('ROLE_MANAGER');
  162.             if (!$admin and !$gestor) {
  163.                 $historial $wsf->getHistorial($user->getErpId());
  164.                 //Comprobamos que el fichero pertenece al usuario
  165.                 if ($historial) {
  166.                     $owner false;
  167.                     foreach ($historial->Lineas as $key => $linea) {
  168.                         if ($linea->NoDocOperacion == $filename) {
  169.                             $owner true;
  170.                         }
  171.                     }
  172.                 }
  173.             }
  174.             if ($admin || $gestor || $owner) {
  175.                 if ($wsf->generarPDFTicket($filename)) {
  176.                     $filename str_replace('/'''$filename '.pdf');
  177.                     $login_result ftp_login($conn_id$ftp_user_name$ftp_user_pass);
  178.                     ftp_pasv($conn_idtrue);
  179.                     if (ftp_get($conn_id$path $filename$ftp_user_folder $filenameFTP_BINARY)) {
  180.                         $response = new BinaryFileResponse($path $filename);
  181.                         $response->setContentDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT);
  182.                         return $response;
  183.                     }
  184.                 }
  185.             }
  186.         } catch (\Exception $e) {
  187.            die(utf8_decode($e->getMessage()));
  188.         }
  189.         //No es el propietario, el ticket no existe, etc...
  190.         throw $this->createNotFoundException('404');
  191.     }
  192.     
  193.     
  194.      #[Route(path: [
  195.         'es' => '/500',
  196.         'en' => '/en/500'
  197.     ], name'app_critical_error')]
  198.     public function erpCritical()
  199.     {
  200.         
  201.         return $this->render('default/criticalError.html.twig');
  202.     }
  203.     
  204.     #[Route(path: [
  205.         'es' => '/perfil',
  206.         'en' => '/en/profile'
  207.     ], name'app_profile')]
  208.     public function perfil(Request $requestPersistenceManagerRegistry $doctrineTranslatorInterface $translatorWebServiceUsuarios $wsuSettingsManager $smWebServiceFunciones $wsfMailer $mailerLoggerInterface $logger): Response
  209.     {
  210.         //obtener noticia
  211.         
  212. //         try {
  213. //             $logeado = $this->authorizationChecker->isGranted('ROLE_USER');
  214.             //Al administrador lo mandamos al panel de administracion
  215.             if ($this->authorizationChecker->isGranted('ROLE_ADMIN')) {
  216.                 return $this->redirect($this->generateUrl('sonata_admin_dashboard'));
  217.             } else if ($this->authorizationChecker->isGranted('ROLE_MANAGER')) {
  218.                 return $this->redirect($this->generateUrl('sonata_admin_dashboard'));
  219.             }
  220.             
  221.             
  222.             //Carga de los datos de usuario de sesion y del ERP
  223.             $usrEnt $this->getUser();
  224.             
  225.             $em $doctrine->getManager();
  226. //             $WSU = $this->container->get('web.service.usuarios', $em);
  227. //             $WSF = $this->container->get('web.service.funciones', $em);
  228.             // $puntos = $wsf->GetPuntosAcumulados($usrEnt->getErpId());
  229.             $puntos 0;
  230.             $user $wsu->findBy('No'$usrEnt->getErpId());
  231.             
  232. //             dump($usrEnt);die();
  233. //             $settings = $this->get('dinamic_settings.manager');
  234. //             $local = $this->get('request')->getLocale();
  235.             $local $request->getLocale();
  236. //             $request = $this->get('request');
  237.             //Buscamos las entidades para poder preseleccionar pais y tipo de documento
  238.             $user['tipoDocumentoEntity'] = $em->getRepository("App\Entity\TipoDocumento")->findOneByCodigo($user['tipoDoc']);
  239.             $user['paisEntity'] = $em->getRepository("App\Entity\Pais")->findOneByIso2($user['pais']);
  240. //             $idioma = $em->getRepository("App\Entity\Idioma")->findOneByUrl($request->getLocale())->getId();
  241.             //Cargamos los formularios
  242.             $addresEnt = new AddresLog();
  243.             $profileForm $this->createForm(ProfileType::class, $addresEnt, array('userERP' => $user'userLocal' => $usrEnt'settings' => $sm));
  244.             $cardForm $this->createForm(CardType::class, $usrEnt, array('user' => $user'settings' => $sm));
  245.             // Campo para albergar el DNI actual
  246. //             $cardForm->add('cUrlImagen', HiddenType::class, [
  247. //                 'label' => false,
  248. //                 'required' => false,
  249. //                 'mapped' => false,
  250. //                 'data' => $this->getUser()->getUrlImagen()
  251. //             ]);
  252.             $filename_anterior $usrEnt->getUrlImagen();
  253.             //Validacion del formulario de carne de identidad
  254.             $cardForm->handleRequest($request);
  255.             if ($cardForm->isSubmitted() && $cardForm->isValid()) {
  256.                 $fileName null;
  257.                 // dump($userProv);die();
  258.                 // Guardamos el archivo DNI Temporal
  259.                 if ($usrEnt->getUrlImagen()) {
  260. //                     var_dump($cardForm['urlImagen']->getData());die();
  261.                     $file $usrEnt->getUrlImagen();
  262.                     // dump($file->guessExtension());die();
  263.                     if ($file->guessExtension() == 'pdf') {
  264.                         $randName md5(uniqid());
  265.                         $pdfName $randName '.pdf';
  266.                         $file->move($this->getParameter('dni_directory'), $pdfName);
  267.                         $pdfFile $this->getParameter('dni_directory').'/'.$pdfName;
  268.                         $outputFile $this->getParameter('dni_directory').'/'.$randName.'.jpg';
  269.                         //exec("/usr/bin/gs -dNOPAUSE -dBATCH -sDEVICE=jpeg -r150 -dFirstPage=1 -dLastPage=1 -sOutputFile=\"$outputFile\" \"$pdfFile\"", $output, $returnVar);
  270.                         shell_exec("/bin/gs -dNOPAUSE -dBATCH -sDEVICE=jpeg -r150 -dFirstPage=1 -dLastPage=1 -sOutputFile=\"$outputFile\" \"$pdfFile\"");
  271.                         unlink($this->getParameter('dni_directory').'/'.$pdfName);
  272. // dump($returnVar);die();
  273.                         if (!file_exists($outputFile)) {
  274.                             throw new \Exception("Error al convertir PDF a JPG");
  275.                         }
  276.                         $fileName $randName.'.jpg';
  277.                     } else {
  278.                         $fileName md5(uniqid()) . '.' $file->guessExtension();
  279.                         $file->move($this->getParameter('dni_directory'), $fileName);
  280.                     }
  281.                     $file_image Util::smart_resize_image($this->getParameter('dni_directory').'/'.$fileName,null12001200true$this->getParameter('dni_directory').'/'.$fileNametruefalse100);
  282. //                     $file_image = imagecreatefromjpeg($this->getParameter('dni_directory').'/'.$fileName);
  283.                     $file_image imagecreatefromstring(file_get_contents($this->getParameter('dni_directory').'/'.$fileName));
  284.                     $fileName1=NULL;
  285.                     $filename_image md5(uniqid());
  286.                     //Miramos si tenemos el archivo2 y lo movemos a la carpeta
  287.                     if ($usrEnt->getUrlImagen2()) {
  288.                         $file1 $usrEnt->getUrlImagen2();
  289.                         $fileName1 md5(uniqid()) . '.' $file1->guessExtension();
  290.                         $file1->move($this->getParameter('dni_directory'), $fileName1);
  291.                         $file1_image "";
  292.                         if(file_exists($this->getParameter('dni_directory').'/'.$fileName1)){
  293.                             $file1_image Util::smart_resize_image($this->getParameter('dni_directory').'/'.$fileName1,null12001200true$this->getParameter('dni_directory').'/'.$fileName1truefalse100);
  294. //                             $file1_image = imagecreatefromjpeg($this->getParameter('dni_directory').'/'.$fileName1);
  295.                             $file1_image imagecreatefromstring(file_get_contents($this->getParameter('dni_directory').'/'.$fileName1));
  296.                         }
  297.                         $tamano1 getimagesize($this->getParameter('dni_directory').'/'.$fileName);
  298.                         $tamano2 getimagesize($this->getParameter('dni_directory').'/'.$fileName1);
  299.                         $anchoGrande 0;
  300.                         if($tamano1[0] > $tamano2[0]){
  301.                             $anchoGrande $tamano1[0];
  302.                         }else{
  303.                             $anchoGrande $tamano2[0];
  304.                         }
  305.                         $altura $tamano1[1]+$tamano2[1];
  306.                         $altura1 $altura $tamano2[1];
  307.                         $image_aux imagecreatetruecolor($anchoGrande,$altura);
  308.                         imagecopymerge($image_aux$file_image0000$tamano1[0], $tamano1[1], 100);
  309.                         imagecopymerge($image_aux$file1_image0$altura100$tamano2[0], $tamano2[1], 100);
  310.                         imagealphablending($image_auxfalse);
  311.                         imagesavealpha($image_aux,true);
  312.                         imagepng($image_aux,$this->getParameter('dni_directory').'/'.$filename_image.'.png');
  313.                         $file$image_aux;
  314.                         unlink$this->getParameter('dni_directory').'/'.$fileName);
  315.                         $fileName $filename_image.'.png';
  316.                         unlink$this->getParameter('dni_directory').'/'.$fileName1);
  317.                     }
  318.                 }
  319.                 // dump($usrEnt);die();
  320.                 
  321.                 $mailer->editProfile($usrEnt$fileName);
  322.                 $this->saveIdCard($wsf$usrEnt$fileName$em$logger);
  323.                 
  324.                 $em->persist($usrEnt);
  325.                 $em->flush();
  326.                 if($filename_anterior != null && file_exists($this->getParameter('dni_directory') . '/' $filename_anterior)){
  327.                     unlink($this->getParameter('dni_directory') . '/' $filename_anterior);
  328.                 }
  329.                 return $this->redirect($this->generateUrl('app_profile'));
  330.             } else {
  331.                 // if ($cardForm->isSubmitted() && !$cardForm->isValid()) {
  332.                 //     var_dump('aaaaaa');die();
  333.                 // } else {
  334.                 //
  335.                 // }
  336.                 // print_r($cardForm->getErrorsAsString());
  337.             }
  338.             //Validacion del formulario de datos de perfil
  339.             $profileForm->handleRequest($request);
  340.             if ($profileForm->isSubmitted() && $profileForm->isValid()) {
  341.                 $this->saveProfile($profileForm$wsf$usrEnt->getErpId(), $em);
  342.                 return $this->redirect($this->generateUrl('app_profile'));
  343.                 //$this->saveAlerts(profileForm,$divisas);s
  344.             } else {
  345.                 //echo "Datos invalidos";
  346.                 //print_r($profileForm->getErrorsAsString());
  347.             }
  348.             //dump($user);
  349.             $returnArray = array(
  350.                 'user' => $user,
  351.                 'puntos' => $puntos,
  352.                 'form' => $profileForm->createView(),
  353.                 'cardForm' => $cardForm->createView(),
  354.                 'dniDirectory' => $this->getParameter('dni_directory_public')
  355.             );
  356.             
  357.             return $this->render('default/perfil/perfil.html.twig'$returnArray);
  358. //         } catch (\Exception $e) {
  359. //           //  return $this->redirect($this->generateUrl('app_critical_error_' . $local));
  360. //   //            die(utf8_decode($e->getMessage()));
  361. //         }
  362.     
  363.         $response $this->render('default/perfil/perfil.html.twig');
  364.         
  365.         return $response;
  366.     }
  367.     
  368.     #[Route(path: [
  369.         'es' => '/perfil/historial-de-cambios',
  370.         'en' => '/en/profile/list-of-changes'
  371.     ], name'app_profile_list')]
  372.     public function historialAction(PersistenceManagerRegistry $doctrineWebServiceUsuarios $wsuWebServiceFunciones $wsf)
  373.     {
  374.         $usrEnt $this->getUser();
  375.         $em $doctrine->getManager();
  376. //         $WSU = $this->container->get('web.service.usuarios', $em);
  377. //         $WSF = $this->container->get('web.service.funciones', $em);
  378.         $user $wsu->findBy('No'$usrEnt->getErpId());
  379.         $puntos $wsf->GetPuntosAcumulados($usrEnt->getErpId());
  380.         $historial $wsf->getHistorial($usrEnt->getErpId());
  381.         $rpLineas $em->getRepository('App\Entity\TransaccionLinea');
  382.         //Buscamos las transacciones del ERP en nuestra base de datos para mostrar los estados de envio
  383.         if ($historial) {
  384.             if (!is_array($historial->Lineas)) {
  385.                 $obj $historial->Lineas;
  386.                 $historial->Lineas = array();
  387.                 $historial->Lineas[] = $obj;
  388.             }
  389.             foreach ($historial->Lineas as $operacion) {
  390.                 //Cuando se hace una llamada al ERP de un historial vacio
  391.                 //este devuelve 1 operación vacía en vez de devolver null o un array
  392.                 //vacio. Because fuck us.
  393.                 if (isset($operacion->NoDocOperacion)) {
  394.                     $ownLinea $rpLineas->findOneByErpCode($operacion->NoDocOperacion);
  395.                     if ($ownLinea) {
  396.                         $operacion->Estado $ownLinea->getTransaccion()->getEstadoEnvio();
  397.                         if($ownLinea->getTransaccion()->getNacex() != null) {
  398.                             $operacion->Nacex $ownLinea->getTransaccion()->getNacex()->getReferencia();
  399.                         }
  400.                     } //Operaciones antiguas del ERP que no tenemos en la base de datos
  401.                     else {
  402.                         $operacion->Estado 'ENTREGADO';
  403.                     }
  404.                 }
  405.             }
  406.         }
  407.         //Listado de oficinas para enlazarlas con la oficina del ERP
  408.         $listaOficinas $em->getRepository('App\Entity\Oficina')->findAllEager();
  409.         foreach ($listaOficinas as $key => $oficina) {
  410.             $oficinas[$oficina->getOficinaErp()->getCodigo()] = $oficina;
  411.         }
  412.         $returnArray = array(
  413.             'user' => $user,
  414.             'puntos' => $puntos,
  415.             'historial' => $historial,
  416.             'oficinas' => $oficinas,
  417.         );
  418.         return $this->render('default/perfil/history.html.twig'$returnArray);
  419.     }
  420.     
  421.     
  422.     #[Route(path: [
  423.         'es' => '/perfil/reservas',
  424.         'en' => '/en/profile/reservations'
  425.     ], name'app_profile_reservations')]
  426.     public function listaReservasAction(PersistenceManagerRegistry $doctrineWebServiceUsuarios $wsuWebServiceFunciones $wsf)
  427.     {
  428.         $usrEnt $this->getUser();
  429.         $em $doctrine->getManager();
  430. //         $WSU = $this->container->get('web.service.usuarios', $em);
  431. //         $WSF = $this->container->get('web.service.funciones', $em);
  432.         $user $wsu->findBy('No'$usrEnt->getErpId());
  433.         $puntos $wsf->GetPuntosAcumulados($usrEnt->getErpId());
  434.         $reservas $em->getRepository("App\Entity\Reserva")->getUserReservas($this->getUser());
  435.         $returnArray = array(
  436.             'user' => $user,
  437.             'puntos' => $puntos,
  438.             'reservas' => $reservas,
  439.         );
  440.         
  441.         return $this->render('default/perfil/booking.html.twig'$returnArray);
  442.     }
  443.     
  444.     #[Route(path: [
  445.         'es' => '/perfil/alertas',
  446.         'en' => '/en/profile/alerts'
  447.     ], name'app_profile_alerts')]
  448.     public function alertsAction(Request $requestPersistenceManagerRegistry $doctrineWebServiceUsuarios $wsuWebServiceFunciones $wsfSettingsManager $sm)
  449.     {
  450.         $usrEnt $this->getUser();
  451.         $em $doctrine->getManager();
  452. //         $WSU = $this->container->get('web.service.usuarios', $em);
  453. //         $WSF = $this->container->get('web.service.funciones', $em);
  454.         $user $wsu->findBy('No'$usrEnt->getErpId());
  455.         $puntos $wsf->GetPuntosAcumulados($usrEnt->getErpId());
  456. //         $settings = $this->get('dinamic_settings.manager');
  457. //         $idioma = $this->getRepository("DinamicShopBundle:Idioma")->findOneByUrl($request->getLocale())->getId();
  458.         $locale $request->getLocale();
  459.         $divisas $em->getRepository("App\Entity\Divisa")->findBy(array('visible' => "1"));
  460.         $oficinas $em->getRepository("App\Entity\Oficina")->findAll();
  461.         $alertas $em->getRepository("App\Entity\Alerta")->findByUsuario($usrEnt);
  462.         $alertsForm $this->createForm(AlertasType::class, $user, array('divisas' => $divisas'alertas' => $alertas'oficinas' => $oficinas'settings' => $sm));
  463.         $totalDivisas count($divisas);
  464.         //Validacion del formulario de alertas
  465.         $alertsForm->handleRequest($request);
  466.         if ($alertsForm->isSubmitted() && $alertsForm->isValid()) {
  467.             $this->saveAlerts($alertsForm$divisas$em);
  468.             return $this->redirectToRoute('app_profile_alerts');
  469.         } else {
  470.             //print_r($alertsForm->getErrorsAsString());
  471.         }
  472.         $returnArray = array(
  473.             'user' => $user,
  474.             'puntos' => $puntos,
  475.             'alertsForm' => $alertsForm->createView(),
  476.             'alertas' => $alertas,
  477.             'totalDivisas' => $totalDivisas,
  478.             'divisas' => $divisas
  479.         );
  480.         
  481.         return $this->render('default/perfil/alerts.html.twig'$returnArray);
  482.     }
  483.     
  484.     public function saveAlerts($alertsForm$divisas$em)
  485.     {
  486.         $usr $this->getUser();
  487.         $alerts $alertsForm->getData();
  488. //         $local = $this->get('request')->getLocale();
  489. //         $usr->setIdiomaPreferido($local);
  490.         $em->persist($usr);
  491.         $em->flush();
  492.         foreach ($divisas as $key => $divisa) {
  493.             $Encontrado $em->getRepository("App\Entity\Alerta")->findOneBy(array('usuario' => $usr'divisa' => $divisa));
  494.             //Si marco la opcion en el check
  495.             if ($alerts['chk' $divisa->getId()]) {
  496.                 $valido true;
  497.                 if (!$alerts['fechaInicio' $divisa->getId()]) {
  498.                     $valido false;
  499.                 }
  500.                 if ($valido) {
  501.                     //Si ya existe esa divisa
  502.                     $ofiId $alerts['oficina' $divisa->getId()];
  503.                     $ofi $em->getRepository("App\Entity\Oficina")->findOneBy(array('id' => $ofiId));
  504.                     if ($Encontrado) {
  505.                         //$Encontrado->setFechaInicio()
  506.                         $Encontrado->setFechaFin($alerts['fechaFin' $divisa->getId()]);
  507.                         $Encontrado->setFechaInicio($alerts['fechaInicio' $divisa->getId()]);
  508.                         $Encontrado->setPrecioMinimo($alerts['precioMinimo' $divisa->getId()]);
  509.                         $Encontrado->setFrecuencia($alerts['frecuencia' $divisa->getId()]);
  510.                         $Encontrado->setTipo($alerts['tipo' $divisa->getId()]);
  511.                         $Encontrado->setActivo(1);
  512.                         $Encontrado->setOficina($ofi);
  513.                         $em->persist($Encontrado);
  514.                         $em->flush();
  515.                     } else {
  516.                         $alrt = new Alerta();
  517.                         $alrt->setUsuario($usr);
  518.                         $alrt->setDivisa($divisa);
  519.                         $alrt->setFechaFin($alerts['fechaFin' $divisa->getId()]);
  520.                         $alrt->setFechaInicio($alerts['fechaInicio' $divisa->getId()]);
  521.                         $alrt->setPrecioMinimo($alerts['precioMinimo' $divisa->getId()]);
  522.                         $alrt->setFrecuencia($alerts['frecuencia' $divisa->getId()]);
  523.                         $alrt->setTipo($alerts['tipo' $divisa->getId()]);
  524.                         $alrt->setActivo(1);
  525.                         $alrt->setOficina($ofi);
  526.                         $em->persist($alrt);
  527.                         $em->flush();
  528.                     }
  529.                 } else {
  530.                 }
  531.             } //Si esta en la base de datos y lo ha desmarcado
  532.             else if ($Encontrado) {
  533.                 $em->remove($Encontrado);
  534.                 $em->flush();
  535.             }
  536.         }
  537.     }
  538.     
  539.     #[Route(path: [
  540.         'es' => '/perfil/afiliados',
  541.         'en' => '/en/profile/afiliados'
  542.     ], name'app_profile_afiliados')]
  543.     public function afiliadosAction(Request $requestPersistenceManagerRegistry $doctrineWebServiceUsuarios $wsuWebServiceFunciones $wsfSettingsManager $sm)
  544.     {
  545.       $this->denyAccessUnlessGranted('ROLE_AFILIADO'null'Unable to access this page!');
  546.         $orden 'ASC';
  547.         $ordenacionActivado false;
  548.         $filtroActivado false;
  549.         $usrEnt $this->getUser();
  550.         $em $doctrine->getManager();
  551. //         $WSU = $this->container->get('web.service.usuarios', $em);
  552. //         $WSF = $this->container->get('web.service.funciones', $em);
  553.         $user $wsu->findBy('No'$usrEnt->getErpId());
  554.         $puntos $wsf->GetPuntosAcumulados($usrEnt->getErpId());
  555. //         $settings = $this->get('dinamic_settings.manager');
  556. //         $idioma = $this->getRepository("DinamicShopBundle:Idioma")->findOneByUrl($request->getLocale())->getId();
  557.         $usuario $this->getUser();
  558.         $form $this->createForm(
  559.             ClientType::class,
  560.             $usuario, array(/*'action' => $this->generateUrl('admin_customer_show', array('id' => $usuario->getId())),
  561.                             'method' => 'POST',*/'action' => "",
  562.             )
  563.         );
  564.         $id_usuario $usuario->getId();
  565.         $ordenacioon $request->query->get('ord');
  566.         if($ordenacioon == 'desc'){
  567.         //    return $this->redirect($this->generateUrl('admin_customer_show', array('id' => $customer->getId(), 'ord' => 'asc')));
  568.             $orden 'desc';
  569.             $ordenacionActivado true;
  570.         }else{
  571.         //    return $this->redirect($this->generateUrl('admin_customer_show', array('id' => $customer->getId(), 'ord' => 'desc')));
  572.             $orden 'asc';
  573.             $ordenacionActivado true;
  574.         }
  575.         $transaccionesAfiliadas $em->getRepository("App\Entity\TransaccionAfiliado")->findBy(array('afiliado' => $id_usuario), array('id' => $orden));
  576.         $total_conseguido 0;
  577.         $cantidad_afiliado 0;
  578.         foreach($transaccionesAfiliadas as $trans){
  579.           $total_conseguido $total_conseguido $trans->getTotalTransaccion();
  580.           if($trans->getTipo() == "PENDIENTE"){
  581.             $cantidad_afiliado $cantidad_afiliado $trans->getParteAfiliado();
  582.           }else if(($trans->getTipo() == "PAGADO")){
  583.             $cantidad_afiliado $cantidad_afiliado $trans->getParteAfiliado();
  584.           }
  585.         }
  586.         $form->handleRequest($request);
  587.         if ($form->isSubmitted()) {
  588.   //          if ($form->isValid()) {
  589.               
  590.               if ($form->getClickedButton() && 'filtrofecha' === $form->getClickedButton()->getName()) {
  591.                 $fechaCom $form['tiempoCom']->getData();
  592.                 $fechaFin $form['tiempoFin']->getData();
  593.                 //$total_pagar_afi = $total_pagar_afi - $cantidad;
  594.                 $transaccionesFiltradas $em->getRepository("App\Entity\TransaccionAfiliado")->findByRange($fechaCom$fechaFin$id_usuario);
  595.             //    var_dump($transaccionesFiltradas);die();
  596.                 $transaccionesAfiliadas $transaccionesFiltradas;
  597.                 $filtroActivado true;
  598. //                 $this->addSuccessMessage('Filtrado Realizado Correctamente');
  599.                 $this->addFlash(
  600.                     'success',
  601.                     'Filtrado Realizado Correctamente'
  602.                 );
  603.           //  }
  604.             }
  605.         }
  606.         //Validacion del formulario de alertas
  607.         
  608.         $returnArray = array(
  609.             'user' => $user,
  610.             'puntos' => $puntos,
  611.             'totalConseguido' => $total_conseguido,
  612.             'totalAfiliado' => $cantidad_afiliado,
  613.             'transaccionesRelacionadas' => $transaccionesAfiliadas,
  614.             'id'  => $id_usuario,
  615.             'ordenacionActivado' => $ordenacionActivado,
  616.             'filtroActivado' => $filtroActivado,
  617.             'form' => $form->createView()
  618.         );
  619.         
  620.         return $this->render('default/perfil/afiliados.html.twig'$returnArray);
  621.         
  622.     }
  623.     
  624.      #[Route(path: [
  625.         'es' => '/perfil/recursos',
  626.         'en' => '/en/profile/recursos'
  627.     ], name'app_profile_recursos')]
  628.     public function recursosAction(Request $requestPersistenceManagerRegistry $doctrineWebServiceUsuarios $wsuWebServiceFunciones $wsfSettingsManager $sm)
  629.     {
  630.       $this->denyAccessUnlessGranted('ROLE_AFILIADO'null'Unable to access this page!');
  631.         $usrEnt $this->getUser();
  632.         $em $doctrine->getManager();
  633. //         $WSU = $this->container->get('web.service.usuarios', $em);
  634. //         $WSF = $this->container->get('web.service.funciones', $em);
  635.         $user $wsu->findBy('No'$usrEnt->getErpId());
  636.         $puntos $wsf->GetPuntosAcumulados($usrEnt->getErpId());
  637. //         $settings = $this->get('dinamic_settings.manager');
  638. //         $idioma = $this->getRepository("DinamicShopBundle:Idioma")->findOneByUrl($request->getLocale())->getId();
  639.         $usuario $this->getUser();
  640.         $id_usuario $usuario->getId();
  641.         $id_usuario Util::encode_afcode($id_usuario);
  642.         $afiliadoPath $this->generateUrl('index' , array('afcode' => $id_usuario), true);
  643.         $transaccionesAfiliadas $usuario->getTransaccionesDelAfiliado();
  644.         $total_conseguido 0;
  645.         $cantidad_afiliado 0;
  646.         foreach($transaccionesAfiliadas as $trans){
  647.           $total_conseguido $total_conseguido $trans->getTotalTransaccion();
  648.           if($trans->getTipo() == "PENDIENTE"){
  649.             $cantidad_afiliado $cantidad_afiliado $trans->getParteAfiliado();
  650.           }else if(($trans->getTipo() == "PAGADO")){
  651.             $cantidad_afiliado $cantidad_afiliado $trans->getParteAfiliado();
  652.           }
  653.         }
  654.         //Validacion del formulario de alertas
  655.         $returnArray = array(
  656.             'user' => $user,
  657.             'puntos' => $puntos,
  658.             'totalConseguido' => $total_conseguido,
  659.             'totalAfiliado' => $cantidad_afiliado,
  660.             'path' => $afiliadoPath,
  661.             'transaccionesRelacionadas' => $transaccionesAfiliadas,
  662.             'id'  => $id_usuario,
  663.         );
  664.         
  665.         return $this->render('default/perfil/recursos.html.twig'$returnArray);
  666.     }
  667.     
  668.     #[Route(path: [
  669.         'es' => '/cancelar-reserva/{id}',
  670.         'en' => '/en/cancel-booking/{id}'
  671.     ], name'app_profile_cancel_booking')]
  672.     public function cancelReservaAction(Request $requestPersistenceManagerRegistry $doctrineWebServiceFunciones $wsfMailer $mailer$id)
  673.     {
  674.         // Cogemos el EntityManager
  675.         $em $doctrine->getManager();
  676.         $usuario $this->getUser();
  677.         $reserva $em->getRepository('App\Entity\Reserva')->findOneBy(["id" => $id"usuario" => $usuario]);
  678.         
  679.         if (!$reserva)
  680.             throw $this->createNotFoundException('404');
  681.         $lineas $reserva->getLineas();
  682.         $canceled false;
  683.         foreach ($lineas as $linea) {
  684.             $canceled $wsf->CancelarReserva($linea->getErpCode());
  685. //             dump($linea->getErpCode());
  686.         }
  687. //          dump($canceled); 
  688.         
  689.         if ($this->getUser() == $reserva->getUsuario() && $canceled) {
  690. //             dump("AAA");  
  691.             $mailer->cancelBooking($this->getUser(), $reserva);
  692.             $reserva->setEstado('CANCELADA');
  693.             $em->persist($reserva);
  694.             $em->flush();
  695. //             $this->addSuccessMessage();
  696.             $this->addFlash(
  697.                 'success',
  698.                 'booking.cancelled'
  699.             );
  700.         }
  701. //          die();
  702.         
  703.         return $this->redirect($this->generateUrl('app_profile_reservations'));
  704.     }
  705.     
  706.     #[Route(path: [
  707.         'es' => '/perfil/tarjeta',
  708.         'en' => '/en/profile/tarjeta'
  709.     ], name'app_profile_tarjeta')]
  710.     public function tarjetaAction(Request $requestPersistenceManagerRegistry $doctrineWebServiceUsuarios $wsuWebServiceFunciones $wsfSettingsManager $sm)
  711.     {
  712. //       $this->denyAccessUnlessGranted('ROLE_AFILIADO', null, 'Unable to access this page!');
  713.         $usrEnt $this->getUser();
  714.         $em $doctrine->getManager();
  715.         $user $wsu->findBy('No'$usrEnt->getErpId());
  716.         $puntos $wsf->GetPuntosAcumulados($usrEnt->getErpId());
  717.         $usuario $this->getUser();
  718.         $id_usuario $usuario->getId();
  719.         $id_usuario Util::encode_afcode($id_usuario);
  720.         
  721.         if ($user['fidelizacion'] != '') {
  722.             $generator = new \Picqer\Barcode\BarcodeGeneratorSVG();
  723.             $codigoBarras $generator->getBarcode($user['fidelizacion'], $generator::TYPE_CODE_128,4,90);
  724.         } else {
  725.             $codigoBarras '';
  726.         }
  727.         
  728.         $transaccionesAfiliadas $usuario->getTransaccionesDelAfiliado();
  729.         $total_conseguido 0;
  730.         $cantidad_afiliado 0;
  731.         foreach($transaccionesAfiliadas as $trans){
  732.           $total_conseguido $total_conseguido $trans->getTotalTransaccion();
  733.           if($trans->getTipo() == "PENDIENTE"){
  734.             $cantidad_afiliado $cantidad_afiliado $trans->getParteAfiliado();
  735.           }else if(($trans->getTipo() == "PAGADO")){
  736.             $cantidad_afiliado $cantidad_afiliado $trans->getParteAfiliado();
  737.           }
  738.         }
  739.         //Validacion del formulario de alertas
  740.         $returnArray = array(
  741.             'user' => $user,
  742.             'puntos' => $puntos,
  743.             'totalConseguido' => $total_conseguido,
  744.             'totalAfiliado' => $cantidad_afiliado,
  745.             'transaccionesRelacionadas' => $transaccionesAfiliadas,
  746.             'id' => $id_usuario,
  747.             'codigoBarras' => $codigoBarras,
  748.         );
  749.         
  750.         return $this->render('default/perfil/tarjeta_afiliados.html.twig'$returnArray);
  751.     }
  752.     
  753. /*    #[Route(path: [
  754.         'es' => '/usuarios/ver-usuario/{id}',
  755.         'en' => '/en/user/see-user/{id}'
  756.     ], name: 'admin_customer_show')]
  757.     public function showAction(Request $request, PersistenceManagerRegistry $doctrine, WebServiceUsuarios $wsu)
  758.     {
  759. //         try {
  760.             $orden = 'ASC';
  761.             $ordenacionActivado = false;
  762.             $em = $doctrine->getManager();
  763.             $customer = $this->getUser();
  764.             $erpId = $customer->getErpId();
  765.             $WSU = $this->container->get('web.service.usuarios', $em);
  766.             $erpUser = null;
  767.             $filtroFecha = false;
  768.             $ordenacionActivado = false;
  769.             if ($erpId) {
  770.                 $erpUser = $wsu->findBy('No', $erpId);
  771.             }
  772.             $form = $this->createForm(
  773.                 new ClientType(),
  774.                 $customer, array('action' => $this->generateUrl('admin_customer_show', array('id' => $customer->getId())),
  775.                     'method' => 'POST',
  776.                 )
  777.             );
  778.             $ordenacioon = $request->query->get('ord');
  779.             if($ordenacioon == 'desc'){
  780.           //    return $this->redirect($this->generateUrl('admin_customer_show', array('id' => $customer->getId(), 'ord' => 'asc')));
  781.               $orden = 'desc';
  782.               $ordenacionActivado = true;
  783.             }else{
  784.           //    return $this->redirect($this->generateUrl('admin_customer_show', array('id' => $customer->getId(), 'ord' => 'desc')));
  785.               $orden = 'asc';
  786.               $ordenacionActivado = true;
  787.             }
  788.             //CONSEGUIR TRANSACCIONESAFILIADO DEL USUARIO
  789.             $id_afi = $customer->getId();
  790.             $transaccionesRel    = $em->getRepository("App\Entity\TransaccionAfiliado")->buscarTransaccionesAfiliado($id_afi, $orden);
  791.             //VARIABLES PARA MANTENER LOS TOTALES
  792.             $total_pagar_afi = 0;
  793.             $total_afiliado = 0;
  794.             $signo = "";
  795.             foreach($transaccionesRel as $trans){
  796.               if($trans->getTipo() == "PENDIENTE"){
  797.                   $total_pagar_afi =$total_pagar_afi + $trans->getParteAfiliado();
  798.                   $total_afiliado = $total_afiliado + $trans->getTotalTransaccion();
  799.                   $signo = "+";
  800.               }else if($trans->getTipo() == "PAGADO"){
  801.                   $total_pagar_afi = $total_pagar_afi - $trans->getParteAfiliado();
  802.                   $signo = "-";
  803.               }
  804.             }
  805.             $repository = $em->getRepository("App\Entity\TransaccionAfiliado");
  806.             $array_trans = array();
  807.             $form->handleRequest($request);
  808.             if ($form->isSubmitted()) {
  809.                 if ($form->isValid()) {
  810.                     if ($form['newPassword']->getData()) $customer->setPlainPassword($form['newPassword']->getData());
  811. //                     $userManager = $this->container->get('fos_user.user_manager');
  812.                     //SI EL SUBMIT ERA PAGO CREAMOS NUEVA TRANSACCIONAFILIADO
  813.                     if ($form->getClickedButton() && 'pago' === $form->getClickedButton()->getName()) {
  814.                         $cantidad = $form['cantidad']->getData();
  815.                         //$total_pagar_afi = $total_pagar_afi - $cantidad;
  816.                         $transAfi = new TransaccionAfiliado();
  817.                         $transAfi->setParteAfiliado($cantidad);
  818.                         $transAfi->setAfiliado($customer);
  819.                         $transAfi->setTipo("PAGADO");
  820.                         $transAfil = $transAfi;
  821.                         $em->persist($transAfi);
  822.                         $em->flush();
  823.                         $this->addSuccessMessage('Pago Realizado Correctamente');
  824.                         return $this->redirect($this->generateUrl('admin_customer_show', array('id' => $customer->getId())));
  825.                     }
  826.                     if ($form->getClickedButton() && 'filtrofecha' === $form->getClickedButton()->getName()) {
  827.                         $fechaCom = $form['tiempoCom']->getData();
  828.                         $fechaFin = $form['tiempoFin']->getData();
  829.                         //$total_pagar_afi = $total_pagar_afi - $cantidad;
  830.                         $transaccionesFiltradas = $repository->findByRange($fechaCom, $fechaFin, $id_afi);
  831.                         $transaccionesRel = $transaccionesFiltradas;
  832.                         $filtroFecha = true;
  833.                         $this->addSuccessMessage('Filtrado Realizado Correctamente');
  834.                     }
  835.                     if (!$filtroFecha) {
  836.                         if($form['role'][0]->getData()){
  837.                             $customer->addRole("ROLE_AFILIADO");
  838.                             $var_aux = $this->redirect($this->generateUrl('admin_afiliado_index'));
  839.                         }else{
  840.                             $customer->removeRole("ROLE_AFILIADO");
  841.                             $var_aux = $this->redirect($this->generateUrl('admin_customer_index'));
  842.                         }
  843.                     //    var_dump($customer)
  844. //                         $userManager->updateUser($customer, true);
  845.                         $this->addSuccessMessage('Usuario Actualizado');
  846.                         return $var_aux;
  847.                     }
  848.                 } else {
  849.                     $this->addErrorMessage('Error al modificar el usuario');
  850.                     return $this->redirect($this->generateUrl('admin_customer_show'));
  851.                 }
  852.             }
  853.             $returnArray = array(
  854.                 'form' => (isset($form)) ? $form->createView():"",
  855.                 'cantTotalAfi' => $total_afiliado,
  856.                 'cantTotalAPag' => $total_pagar_afi,
  857.                 'transaccionesRelacionadas' => $transaccionesRel,
  858.                 'customer' => $customer,
  859.                 'signo' => $signo,
  860.                 'erpUser' => $erpUser,
  861.                 'filtroFecha' => $filtroFecha,
  862.                 'ordenacionActivado' => $ordenacionActivado
  863.             );
  864.             return $returnArray;
  865. //         } catch (\Exception $e) {
  866. //         }
  867.     }*/
  868. }