src/Controller/PerfilController.php line 230
- <?php
- namespace App\Controller;
- use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
- use Symfony\Component\HttpFoundation\Request;
- use Symfony\Component\HttpFoundation\Response;
- use Symfony\Component\Routing\Annotation\Route;
- use Symfony\Component\HttpFoundation\JsonResponse;
- use Symfony\Component\HttpFoundation\ResponseHeaderBag;
- use Symfony\Component\HttpFoundation\BinaryFileResponse;
- use Symfony\Contracts\Translation\TranslatorInterface;
- use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
- use Doctrine\ORM\EntityManagerInterface;
- use Knp\Component\Pager\PaginatorInterface;
- use Symfony\Component\HttpFoundation\Cookie;
- use Symfony\Component\HttpFoundation\RequestStack;
- use Doctrine\Persistence\ManagerRegistry as PersistenceManagerRegistry;
- use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
- use Symfony\Component\Security\Core\Security;
- use Symfony\Component\HttpClient\HttpClient;
- use Symfony\Component\HttpFoundation\File\File;
- use Symfony\Component\Cache\Adapter\FilesystemAdapter;
- use Symfony\Contracts\Cache\ItemInterface;
- use App\Utils\Util;
- use Psr\Log\LoggerInterface;
- use App\Entity\Contenido;
- use App\Entity\Reserva;
- use App\Entity\AddresLog;
- use App\Entity\Alerta;
- use App\Entity\User;
- use App\Services\ConfigurationManager;
- use App\Services\SettingsManager;
- use App\Services\WebServiceOficinas;
- use App\Services\WebServiceReservas;
- use App\Services\WebServiceTarifasTPV;
- use App\Services\WebServiceTPV;
- use App\Services\WebServiceUsuarios;
- use App\Services\WebServiceDivisas;
- use App\Services\WebServiceFunciones;
- use App\Services\Mailer;
- use Symfony\Component\Form\Extension\Core\Type\HiddenType;
- use App\Form\ViajeType;
- use App\Form\ProfileType;
- use App\Form\CardType;
- use App\Form\AlertasType;
- use App\Form\ClientType;
- class PerfilController extends AbstractController
- {
- private $authorizationChecker;
- public function __construct(AuthorizationCheckerInterface $authorizationChecker)
- {
- $this->authorizationChecker = $authorizationChecker;
- }
- public function saveProfile($profileForm, $WSF, $UserId, $em)
- {
- $profile = $profileForm->getData();
- //var_dump($profile);
- $direccion2 = '';
- if (strlen($profile->getDireccion1()) > 50) {
- $direccion1 = substr($profile->getDireccion1(), 0, 50);
- $direccion2 = substr($profile->getDireccion1(), 50, 50);
- } else {
- $direccion1 = $profile->getDireccion1();
- $direccion2 = '';
- }
- $WSF->modificarDireccion1($UserId, $direccion1);
- $WSF->modificarDireccion2($UserId, $direccion2);
- $WSF->modificarPoblacion($UserId, $profile->getCiudad());
- $WSF->modificarTelefono($UserId, $profile->getTlf());
- $WSF->modificarCodPostal($UserId, $profile->getCp());
- $WSF->modificarEmail($UserId, $profile->getEmail());
- $WSF->modificarProvincia($UserId, $profile->getCounty());
- $user = $this->getUser();
- $user->setEmail($profile->getEmail());
- $em->persist($user);
- $em->flush();
- }
- public function saveIdCard($WSF, $usrEnt, $fileName, $em, $logger)
- {
- // $user = $this->getUser();
- // $card = $cardForm->getData();
- // $erpDate = $card->getFechaCaducidad()->format('Y-m-d');
- // $nacFecha = $card->getFechaNacimiento()->format('Y-m-d');
- if ($usrEnt->getUrlImagen()) {
- $file = $this->getParameter('dni_directory').'/'.$fileName;
- try {
- //Upload the image to Eurochange FTP
- $ftp_server = $this->getParameter('get_ftp_domain');
- $ftp_user_name = $this->getParameter('get_ftp_user');
- $ftp_user_pass = $this->getParameter('get_ftp_password');
- $ftp_user_folder = $this->getParameter('get_ftp_dni_folder');
- $conn_id = ftp_connect($ftp_server);
- $login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
- if ((!$conn_id) || (!$login_result)) {
- return $this->redirect($this->generateUrl('app_critical_error'));
- }
- ftp_pasv($conn_id, true);
- $upload = ftp_put($conn_id, $ftp_user_folder . $fileName, $file, FTP_BINARY);
- /**ACTIVAR PRODUCCION**/
- // $WS = $this->container->get('web.service.funciones', $em);
- // $WSF->CargarImagen($this->getUser()->getErpId(), $fileName);
- /****/
- //Tras subir la imagen al FTP del ERP, borramos la nuestra
- // if (file_exists($file)) {
- // unlink($file);
- // }
- $usrEnt->setUrlImagen($fileName);
- // $em->persist($usrEnt);
- // $em->flush();
- } catch (\Exception $e) {
- // $logger = $this->get('logger');
- $logger->info('[DINAMIC][ERROR][PROFILE] :' . $e);
- return $this->redirect($this->generateUrl('app_critical_error'));
- }
- // if(file_exists($this->getParameter('dni_directory') . '/' . $usrEnt->getUrlImagen())){
- // unlink($this->getParameter('dni_directory') . '/' . $usrEnt->getUrlImagen());
- // }
- }
- $WSF->modificarNombre($usrEnt->getErpId(), $usrEnt->getName());
- $WSF->modificarTipoId($usrEnt->getErpId(), $usrEnt->getTipoDocumento()->getCodigo());
- $WSF->modificarFechaExpiracion($usrEnt->getErpId(), $usrEnt->getFechaCaducidad()->format('Y-m-d'));
- $WSF->modificarNumId($usrEnt->getErpId(), $usrEnt->getIdCard());
- $WSF->modificarPais($usrEnt->getErpId(), $usrEnt->getPais());
- $WSF->modificarFechaNacimiento($usrEnt->getErpId(), $usrEnt->getFechaNacimiento()->format('Y-m-d'));
- }
- #[Route(path: [
- 'es' => '/perfil/descargar',
- 'en' => '/en/profile/download'
- ], name: 'app_profile_download')]
- public function downloadAction(Request $request, PersistenceManagerRegistry $doctrine, WebServiceFunciones $wsf)
- {
- try {
- $user = $this->getUser();
- $filename = $request->query->get('ticket');
- $em = $doctrine->getManager();
- // $WS = $this->container->get('web.service.funciones', $em);
- $ftp_server = $this->getParameter('get_ftp_domain');
- $ftp_user_name = $this->getParameter('get_ftp_user');
- $ftp_user_pass = $this->getParameter('get_ftp_password');
- $ftp_user_folder = $this->getParameter('get_ftp_ticket_folder');
- // $path = $this->get('kernel')->getRootDir() . "/../ticket/";
- $path = $this->getParameter('kernel.project_dir'). "/ticket/";
- // dump($path); die();
- $conn_id = ftp_connect($ftp_server);
- $admin = $this->authorizationChecker->isGranted('ROLE_ADMIN');
- $gestor = $this->authorizationChecker->isGranted('ROLE_MANAGER');
- if (!$admin and !$gestor) {
- $historial = $wsf->getHistorial($user->getErpId());
- //Comprobamos que el fichero pertenece al usuario
- if ($historial) {
- $owner = false;
- foreach ($historial->Lineas as $key => $linea) {
- if ($linea->NoDocOperacion == $filename) {
- $owner = true;
- }
- }
- }
- }
- if ($admin || $gestor || $owner) {
- if ($wsf->generarPDFTicket($filename)) {
- $filename = str_replace('/', '', $filename . '.pdf');
- $login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
- ftp_pasv($conn_id, true);
- if (ftp_get($conn_id, $path . $filename, $ftp_user_folder . $filename, FTP_BINARY)) {
- $response = new BinaryFileResponse($path . $filename);
- $response->setContentDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT);
- return $response;
- }
- }
- }
- } catch (\Exception $e) {
- die(utf8_decode($e->getMessage()));
- }
- //No es el propietario, el ticket no existe, etc...
- throw $this->createNotFoundException('404');
- }
- #[Route(path: [
- 'es' => '/500',
- 'en' => '/en/500'
- ], name: 'app_critical_error')]
- public function erpCritical()
- {
- return $this->render('default/criticalError.html.twig');
- }
- #[Route(path: [
- 'es' => '/perfil',
- 'en' => '/en/profile'
- ], name: 'app_profile')]
- public function perfil(Request $request, PersistenceManagerRegistry $doctrine, TranslatorInterface $translator, WebServiceUsuarios $wsu, SettingsManager $sm, WebServiceFunciones $wsf, Mailer $mailer, LoggerInterface $logger): Response
- {
- //obtener noticia
- // try {
- // $logeado = $this->authorizationChecker->isGranted('ROLE_USER');
- //Al administrador lo mandamos al panel de administracion
- if ($this->authorizationChecker->isGranted('ROLE_ADMIN')) {
- return $this->redirect($this->generateUrl('sonata_admin_dashboard'));
- } else if ($this->authorizationChecker->isGranted('ROLE_MANAGER')) {
- return $this->redirect($this->generateUrl('sonata_admin_dashboard'));
- }
- //Carga de los datos de usuario de sesion y del ERP
- $usrEnt = $this->getUser();
- $em = $doctrine->getManager();
- // $WSU = $this->container->get('web.service.usuarios', $em);
- // $WSF = $this->container->get('web.service.funciones', $em);
- // $puntos = $wsf->GetPuntosAcumulados($usrEnt->getErpId());
- $puntos = 0;
- $user = $wsu->findBy('No', $usrEnt->getErpId());
- // dump($usrEnt);die();
- // $settings = $this->get('dinamic_settings.manager');
- // $local = $this->get('request')->getLocale();
- $local = $request->getLocale();
- // $request = $this->get('request');
- //Buscamos las entidades para poder preseleccionar pais y tipo de documento
- $user['tipoDocumentoEntity'] = $em->getRepository("App\Entity\TipoDocumento")->findOneByCodigo($user['tipoDoc']);
- $user['paisEntity'] = $em->getRepository("App\Entity\Pais")->findOneByIso2($user['pais']);
- // $idioma = $em->getRepository("App\Entity\Idioma")->findOneByUrl($request->getLocale())->getId();
- //Cargamos los formularios
- $addresEnt = new AddresLog();
- $profileForm = $this->createForm(ProfileType::class, $addresEnt, array('userERP' => $user, 'userLocal' => $usrEnt, 'settings' => $sm));
- $cardForm = $this->createForm(CardType::class, $usrEnt, array('user' => $user, 'settings' => $sm));
- // Campo para albergar el DNI actual
- // $cardForm->add('cUrlImagen', HiddenType::class, [
- // 'label' => false,
- // 'required' => false,
- // 'mapped' => false,
- // 'data' => $this->getUser()->getUrlImagen()
- // ]);
- $filename_anterior = $usrEnt->getUrlImagen();
- //Validacion del formulario de carne de identidad
- $cardForm->handleRequest($request);
- if ($cardForm->isSubmitted() && $cardForm->isValid()) {
- $fileName = null;
- // dump($userProv);die();
- // Guardamos el archivo DNI Temporal
- if ($usrEnt->getUrlImagen()) {
- // var_dump($cardForm['urlImagen']->getData());die();
- $file = $usrEnt->getUrlImagen();
- // dump($file->guessExtension());die();
- if ($file->guessExtension() == 'pdf') {
- $randName = md5(uniqid());
- $pdfName = $randName . '.pdf';
- $file->move($this->getParameter('dni_directory'), $pdfName);
- $pdfFile = $this->getParameter('dni_directory').'/'.$pdfName;
- $outputFile = $this->getParameter('dni_directory').'/'.$randName.'.jpg';
- //exec("/usr/bin/gs -dNOPAUSE -dBATCH -sDEVICE=jpeg -r150 -dFirstPage=1 -dLastPage=1 -sOutputFile=\"$outputFile\" \"$pdfFile\"", $output, $returnVar);
- shell_exec("/bin/gs -dNOPAUSE -dBATCH -sDEVICE=jpeg -r150 -dFirstPage=1 -dLastPage=1 -sOutputFile=\"$outputFile\" \"$pdfFile\"");
- unlink($this->getParameter('dni_directory').'/'.$pdfName);
- // dump($returnVar);die();
- if (!file_exists($outputFile)) {
- throw new \Exception("Error al convertir PDF a JPG");
- }
- $fileName = $randName.'.jpg';
- } else {
- $fileName = md5(uniqid()) . '.' . $file->guessExtension();
- $file->move($this->getParameter('dni_directory'), $fileName);
- }
- $file_image = Util::smart_resize_image($this->getParameter('dni_directory').'/'.$fileName,null, 1200, 1200, true, $this->getParameter('dni_directory').'/'.$fileName, true, false, 100);
- // $file_image = imagecreatefromjpeg($this->getParameter('dni_directory').'/'.$fileName);
- $file_image = imagecreatefromstring(file_get_contents($this->getParameter('dni_directory').'/'.$fileName));
- $fileName1=NULL;
- $filename_image = md5(uniqid());
- //Miramos si tenemos el archivo2 y lo movemos a la carpeta
- if ($usrEnt->getUrlImagen2()) {
- $file1 = $usrEnt->getUrlImagen2();
- $fileName1 = md5(uniqid()) . '.' . $file1->guessExtension();
- $file1->move($this->getParameter('dni_directory'), $fileName1);
- $file1_image = "";
- if(file_exists($this->getParameter('dni_directory').'/'.$fileName1)){
- $file1_image = Util::smart_resize_image($this->getParameter('dni_directory').'/'.$fileName1,null, 1200, 1200, true, $this->getParameter('dni_directory').'/'.$fileName1, true, false, 100);
- // $file1_image = imagecreatefromjpeg($this->getParameter('dni_directory').'/'.$fileName1);
- $file1_image = imagecreatefromstring(file_get_contents($this->getParameter('dni_directory').'/'.$fileName1));
- }
- $tamano1 = getimagesize($this->getParameter('dni_directory').'/'.$fileName);
- $tamano2 = getimagesize($this->getParameter('dni_directory').'/'.$fileName1);
- $anchoGrande = 0;
- if($tamano1[0] > $tamano2[0]){
- $anchoGrande = $tamano1[0];
- }else{
- $anchoGrande = $tamano2[0];
- }
- $altura = $tamano1[1]+$tamano2[1];
- $altura1 = $altura - $tamano2[1];
- $image_aux = imagecreatetruecolor($anchoGrande,$altura);
- imagecopymerge($image_aux, $file_image, 0, 0, 0, 0, $tamano1[0], $tamano1[1], 100);
- imagecopymerge($image_aux, $file1_image, 0, $altura1, 0, 0, $tamano2[0], $tamano2[1], 100);
- imagealphablending($image_aux, false);
- imagesavealpha($image_aux,true);
- imagepng($image_aux,$this->getParameter('dni_directory').'/'.$filename_image.'.png');
- $file= $image_aux;
- unlink( $this->getParameter('dni_directory').'/'.$fileName);
- $fileName = $filename_image.'.png';
- unlink( $this->getParameter('dni_directory').'/'.$fileName1);
- }
- }
- // dump($usrEnt);die();
- $mailer->editProfile($usrEnt, $fileName);
- $this->saveIdCard($wsf, $usrEnt, $fileName, $em, $logger);
- $em->persist($usrEnt);
- $em->flush();
- if($filename_anterior != null && file_exists($this->getParameter('dni_directory') . '/' . $filename_anterior)){
- unlink($this->getParameter('dni_directory') . '/' . $filename_anterior);
- }
- return $this->redirect($this->generateUrl('app_profile'));
- } else {
- // if ($cardForm->isSubmitted() && !$cardForm->isValid()) {
- // var_dump('aaaaaa');die();
- // } else {
- //
- // }
- // print_r($cardForm->getErrorsAsString());
- }
- //Validacion del formulario de datos de perfil
- $profileForm->handleRequest($request);
- if ($profileForm->isSubmitted() && $profileForm->isValid()) {
- $this->saveProfile($profileForm, $wsf, $usrEnt->getErpId(), $em);
- return $this->redirect($this->generateUrl('app_profile'));
- //$this->saveAlerts(profileForm,$divisas);s
- } else {
- //echo "Datos invalidos";
- //print_r($profileForm->getErrorsAsString());
- }
- //dump($user);
- $returnArray = array(
- 'user' => $user,
- 'puntos' => $puntos,
- 'form' => $profileForm->createView(),
- 'cardForm' => $cardForm->createView(),
- 'dniDirectory' => $this->getParameter('dni_directory_public')
- );
- return $this->render('default/perfil/perfil.html.twig', $returnArray);
- // } catch (\Exception $e) {
- // // return $this->redirect($this->generateUrl('app_critical_error_' . $local));
- // // die(utf8_decode($e->getMessage()));
- // }
- $response = $this->render('default/perfil/perfil.html.twig');
- return $response;
- }
- #[Route(path: [
- 'es' => '/perfil/historial-de-cambios',
- 'en' => '/en/profile/list-of-changes'
- ], name: 'app_profile_list')]
- public function historialAction(PersistenceManagerRegistry $doctrine, WebServiceUsuarios $wsu, WebServiceFunciones $wsf)
- {
- $usrEnt = $this->getUser();
- $em = $doctrine->getManager();
- // $WSU = $this->container->get('web.service.usuarios', $em);
- // $WSF = $this->container->get('web.service.funciones', $em);
- $user = $wsu->findBy('No', $usrEnt->getErpId());
- $puntos = $wsf->GetPuntosAcumulados($usrEnt->getErpId());
- $historial = $wsf->getHistorial($usrEnt->getErpId());
- $rpLineas = $em->getRepository('App\Entity\TransaccionLinea');
- //Buscamos las transacciones del ERP en nuestra base de datos para mostrar los estados de envio
- if ($historial) {
- if (!is_array($historial->Lineas)) {
- $obj = $historial->Lineas;
- $historial->Lineas = array();
- $historial->Lineas[] = $obj;
- }
- foreach ($historial->Lineas as $operacion) {
- //Cuando se hace una llamada al ERP de un historial vacio
- //este devuelve 1 operación vacÃa en vez de devolver null o un array
- //vacio. Because fuck us.
- if (isset($operacion->NoDocOperacion)) {
- $ownLinea = $rpLineas->findOneByErpCode($operacion->NoDocOperacion);
- if ($ownLinea) {
- $operacion->Estado = $ownLinea->getTransaccion()->getEstadoEnvio();
- if($ownLinea->getTransaccion()->getNacex() != null) {
- $operacion->Nacex = $ownLinea->getTransaccion()->getNacex()->getReferencia();
- }
- } //Operaciones antiguas del ERP que no tenemos en la base de datos
- else {
- $operacion->Estado = 'ENTREGADO';
- }
- }
- }
- }
- //Listado de oficinas para enlazarlas con la oficina del ERP
- $listaOficinas = $em->getRepository('App\Entity\Oficina')->findAllEager();
- foreach ($listaOficinas as $key => $oficina) {
- $oficinas[$oficina->getOficinaErp()->getCodigo()] = $oficina;
- }
- $returnArray = array(
- 'user' => $user,
- 'puntos' => $puntos,
- 'historial' => $historial,
- 'oficinas' => $oficinas,
- );
- return $this->render('default/perfil/history.html.twig', $returnArray);
- }
- #[Route(path: [
- 'es' => '/perfil/reservas',
- 'en' => '/en/profile/reservations'
- ], name: 'app_profile_reservations')]
- public function listaReservasAction(PersistenceManagerRegistry $doctrine, WebServiceUsuarios $wsu, WebServiceFunciones $wsf)
- {
- $usrEnt = $this->getUser();
- $em = $doctrine->getManager();
- // $WSU = $this->container->get('web.service.usuarios', $em);
- // $WSF = $this->container->get('web.service.funciones', $em);
- $user = $wsu->findBy('No', $usrEnt->getErpId());
- $puntos = $wsf->GetPuntosAcumulados($usrEnt->getErpId());
- $reservas = $em->getRepository("App\Entity\Reserva")->getUserReservas($this->getUser());
- $returnArray = array(
- 'user' => $user,
- 'puntos' => $puntos,
- 'reservas' => $reservas,
- );
- return $this->render('default/perfil/booking.html.twig', $returnArray);
- }
- #[Route(path: [
- 'es' => '/perfil/alertas',
- 'en' => '/en/profile/alerts'
- ], name: 'app_profile_alerts')]
- public function alertsAction(Request $request, PersistenceManagerRegistry $doctrine, WebServiceUsuarios $wsu, WebServiceFunciones $wsf, SettingsManager $sm)
- {
- $usrEnt = $this->getUser();
- $em = $doctrine->getManager();
- // $WSU = $this->container->get('web.service.usuarios', $em);
- // $WSF = $this->container->get('web.service.funciones', $em);
- $user = $wsu->findBy('No', $usrEnt->getErpId());
- $puntos = $wsf->GetPuntosAcumulados($usrEnt->getErpId());
- // $settings = $this->get('dinamic_settings.manager');
- // $idioma = $this->getRepository("DinamicShopBundle:Idioma")->findOneByUrl($request->getLocale())->getId();
- $locale = $request->getLocale();
- $divisas = $em->getRepository("App\Entity\Divisa")->findBy(array('visible' => "1"));
- $oficinas = $em->getRepository("App\Entity\Oficina")->findAll();
- $alertas = $em->getRepository("App\Entity\Alerta")->findByUsuario($usrEnt);
- $alertsForm = $this->createForm(AlertasType::class, $user, array('divisas' => $divisas, 'alertas' => $alertas, 'oficinas' => $oficinas, 'settings' => $sm));
- $totalDivisas = count($divisas);
- //Validacion del formulario de alertas
- $alertsForm->handleRequest($request);
- if ($alertsForm->isSubmitted() && $alertsForm->isValid()) {
- $this->saveAlerts($alertsForm, $divisas, $em);
- return $this->redirectToRoute('app_profile_alerts');
- } else {
- //print_r($alertsForm->getErrorsAsString());
- }
- $returnArray = array(
- 'user' => $user,
- 'puntos' => $puntos,
- 'alertsForm' => $alertsForm->createView(),
- 'alertas' => $alertas,
- 'totalDivisas' => $totalDivisas,
- 'divisas' => $divisas
- );
- return $this->render('default/perfil/alerts.html.twig', $returnArray);
- }
- public function saveAlerts($alertsForm, $divisas, $em)
- {
- $usr = $this->getUser();
- $alerts = $alertsForm->getData();
- // $local = $this->get('request')->getLocale();
- // $usr->setIdiomaPreferido($local);
- $em->persist($usr);
- $em->flush();
- foreach ($divisas as $key => $divisa) {
- $Encontrado = $em->getRepository("App\Entity\Alerta")->findOneBy(array('usuario' => $usr, 'divisa' => $divisa));
- //Si marco la opcion en el check
- if ($alerts['chk' . $divisa->getId()]) {
- $valido = true;
- if (!$alerts['fechaInicio' . $divisa->getId()]) {
- $valido = false;
- }
- if ($valido) {
- //Si ya existe esa divisa
- $ofiId = $alerts['oficina' . $divisa->getId()];
- $ofi = $em->getRepository("App\Entity\Oficina")->findOneBy(array('id' => $ofiId));
- if ($Encontrado) {
- //$Encontrado->setFechaInicio()
- $Encontrado->setFechaFin($alerts['fechaFin' . $divisa->getId()]);
- $Encontrado->setFechaInicio($alerts['fechaInicio' . $divisa->getId()]);
- $Encontrado->setPrecioMinimo($alerts['precioMinimo' . $divisa->getId()]);
- $Encontrado->setFrecuencia($alerts['frecuencia' . $divisa->getId()]);
- $Encontrado->setTipo($alerts['tipo' . $divisa->getId()]);
- $Encontrado->setActivo(1);
- $Encontrado->setOficina($ofi);
- $em->persist($Encontrado);
- $em->flush();
- } else {
- $alrt = new Alerta();
- $alrt->setUsuario($usr);
- $alrt->setDivisa($divisa);
- $alrt->setFechaFin($alerts['fechaFin' . $divisa->getId()]);
- $alrt->setFechaInicio($alerts['fechaInicio' . $divisa->getId()]);
- $alrt->setPrecioMinimo($alerts['precioMinimo' . $divisa->getId()]);
- $alrt->setFrecuencia($alerts['frecuencia' . $divisa->getId()]);
- $alrt->setTipo($alerts['tipo' . $divisa->getId()]);
- $alrt->setActivo(1);
- $alrt->setOficina($ofi);
- $em->persist($alrt);
- $em->flush();
- }
- } else {
- }
- } //Si esta en la base de datos y lo ha desmarcado
- else if ($Encontrado) {
- $em->remove($Encontrado);
- $em->flush();
- }
- }
- }
- #[Route(path: [
- 'es' => '/perfil/afiliados',
- 'en' => '/en/profile/afiliados'
- ], name: 'app_profile_afiliados')]
- public function afiliadosAction(Request $request, PersistenceManagerRegistry $doctrine, WebServiceUsuarios $wsu, WebServiceFunciones $wsf, SettingsManager $sm)
- {
- $this->denyAccessUnlessGranted('ROLE_AFILIADO', null, 'Unable to access this page!');
- $orden = 'ASC';
- $ordenacionActivado = false;
- $filtroActivado = false;
- $usrEnt = $this->getUser();
- $em = $doctrine->getManager();
- // $WSU = $this->container->get('web.service.usuarios', $em);
- // $WSF = $this->container->get('web.service.funciones', $em);
- $user = $wsu->findBy('No', $usrEnt->getErpId());
- $puntos = $wsf->GetPuntosAcumulados($usrEnt->getErpId());
- // $settings = $this->get('dinamic_settings.manager');
- // $idioma = $this->getRepository("DinamicShopBundle:Idioma")->findOneByUrl($request->getLocale())->getId();
- $usuario = $this->getUser();
- $form = $this->createForm(
- ClientType::class,
- $usuario, array(/*'action' => $this->generateUrl('admin_customer_show', array('id' => $usuario->getId())),
- 'method' => 'POST',*/'action' => "",
- )
- );
- $id_usuario = $usuario->getId();
- $ordenacioon = $request->query->get('ord');
- if($ordenacioon == 'desc'){
- // return $this->redirect($this->generateUrl('admin_customer_show', array('id' => $customer->getId(), 'ord' => 'asc')));
- $orden = 'desc';
- $ordenacionActivado = true;
- }else{
- // return $this->redirect($this->generateUrl('admin_customer_show', array('id' => $customer->getId(), 'ord' => 'desc')));
- $orden = 'asc';
- $ordenacionActivado = true;
- }
- $transaccionesAfiliadas = $em->getRepository("App\Entity\TransaccionAfiliado")->findBy(array('afiliado' => $id_usuario), array('id' => $orden));
- $total_conseguido = 0;
- $cantidad_afiliado = 0;
- foreach($transaccionesAfiliadas as $trans){
- $total_conseguido = $total_conseguido + $trans->getTotalTransaccion();
- if($trans->getTipo() == "PENDIENTE"){
- $cantidad_afiliado = $cantidad_afiliado + $trans->getParteAfiliado();
- }else if(($trans->getTipo() == "PAGADO")){
- $cantidad_afiliado = $cantidad_afiliado - $trans->getParteAfiliado();
- }
- }
- $form->handleRequest($request);
- if ($form->isSubmitted()) {
- // if ($form->isValid()) {
- if ($form->getClickedButton() && 'filtrofecha' === $form->getClickedButton()->getName()) {
- $fechaCom = $form['tiempoCom']->getData();
- $fechaFin = $form['tiempoFin']->getData();
- //$total_pagar_afi = $total_pagar_afi - $cantidad;
- $transaccionesFiltradas = $em->getRepository("App\Entity\TransaccionAfiliado")->findByRange($fechaCom, $fechaFin, $id_usuario);
- // var_dump($transaccionesFiltradas);die();
- $transaccionesAfiliadas = $transaccionesFiltradas;
- $filtroActivado = true;
- // $this->addSuccessMessage('Filtrado Realizado Correctamente');
- $this->addFlash(
- 'success',
- 'Filtrado Realizado Correctamente'
- );
- // }
- }
- }
- //Validacion del formulario de alertas
- $returnArray = array(
- 'user' => $user,
- 'puntos' => $puntos,
- 'totalConseguido' => $total_conseguido,
- 'totalAfiliado' => $cantidad_afiliado,
- 'transaccionesRelacionadas' => $transaccionesAfiliadas,
- 'id' => $id_usuario,
- 'ordenacionActivado' => $ordenacionActivado,
- 'filtroActivado' => $filtroActivado,
- 'form' => $form->createView()
- );
- return $this->render('default/perfil/afiliados.html.twig', $returnArray);
- }
- #[Route(path: [
- 'es' => '/perfil/recursos',
- 'en' => '/en/profile/recursos'
- ], name: 'app_profile_recursos')]
- public function recursosAction(Request $request, PersistenceManagerRegistry $doctrine, WebServiceUsuarios $wsu, WebServiceFunciones $wsf, SettingsManager $sm)
- {
- $this->denyAccessUnlessGranted('ROLE_AFILIADO', null, 'Unable to access this page!');
- $usrEnt = $this->getUser();
- $em = $doctrine->getManager();
- // $WSU = $this->container->get('web.service.usuarios', $em);
- // $WSF = $this->container->get('web.service.funciones', $em);
- $user = $wsu->findBy('No', $usrEnt->getErpId());
- $puntos = $wsf->GetPuntosAcumulados($usrEnt->getErpId());
- // $settings = $this->get('dinamic_settings.manager');
- // $idioma = $this->getRepository("DinamicShopBundle:Idioma")->findOneByUrl($request->getLocale())->getId();
- $usuario = $this->getUser();
- $id_usuario = $usuario->getId();
- $id_usuario = Util::encode_afcode($id_usuario);
- $afiliadoPath = $this->generateUrl('index' , array('afcode' => $id_usuario), true);
- $transaccionesAfiliadas = $usuario->getTransaccionesDelAfiliado();
- $total_conseguido = 0;
- $cantidad_afiliado = 0;
- foreach($transaccionesAfiliadas as $trans){
- $total_conseguido = $total_conseguido + $trans->getTotalTransaccion();
- if($trans->getTipo() == "PENDIENTE"){
- $cantidad_afiliado = $cantidad_afiliado + $trans->getParteAfiliado();
- }else if(($trans->getTipo() == "PAGADO")){
- $cantidad_afiliado = $cantidad_afiliado - $trans->getParteAfiliado();
- }
- }
- //Validacion del formulario de alertas
- $returnArray = array(
- 'user' => $user,
- 'puntos' => $puntos,
- 'totalConseguido' => $total_conseguido,
- 'totalAfiliado' => $cantidad_afiliado,
- 'path' => $afiliadoPath,
- 'transaccionesRelacionadas' => $transaccionesAfiliadas,
- 'id' => $id_usuario,
- );
- return $this->render('default/perfil/recursos.html.twig', $returnArray);
- }
- #[Route(path: [
- 'es' => '/cancelar-reserva/{id}',
- 'en' => '/en/cancel-booking/{id}'
- ], name: 'app_profile_cancel_booking')]
- public function cancelReservaAction(Request $request, PersistenceManagerRegistry $doctrine, WebServiceFunciones $wsf, Mailer $mailer, $id)
- {
- // Cogemos el EntityManager
- $em = $doctrine->getManager();
- $usuario = $this->getUser();
- $reserva = $em->getRepository('App\Entity\Reserva')->findOneBy(["id" => $id, "usuario" => $usuario]);
- if (!$reserva)
- throw $this->createNotFoundException('404');
- $lineas = $reserva->getLineas();
- $canceled = false;
- foreach ($lineas as $linea) {
- $canceled = $wsf->CancelarReserva($linea->getErpCode());
- // dump($linea->getErpCode());
- }
- // dump($canceled);
- if ($this->getUser() == $reserva->getUsuario() && $canceled) {
- // dump("AAA");
- $mailer->cancelBooking($this->getUser(), $reserva);
- $reserva->setEstado('CANCELADA');
- $em->persist($reserva);
- $em->flush();
- // $this->addSuccessMessage();
- $this->addFlash(
- 'success',
- 'booking.cancelled'
- );
- }
- // die();
- return $this->redirect($this->generateUrl('app_profile_reservations'));
- }
- #[Route(path: [
- 'es' => '/perfil/tarjeta',
- 'en' => '/en/profile/tarjeta'
- ], name: 'app_profile_tarjeta')]
- public function tarjetaAction(Request $request, PersistenceManagerRegistry $doctrine, WebServiceUsuarios $wsu, WebServiceFunciones $wsf, SettingsManager $sm)
- {
- // $this->denyAccessUnlessGranted('ROLE_AFILIADO', null, 'Unable to access this page!');
- $usrEnt = $this->getUser();
- $em = $doctrine->getManager();
- $user = $wsu->findBy('No', $usrEnt->getErpId());
- $puntos = $wsf->GetPuntosAcumulados($usrEnt->getErpId());
- $usuario = $this->getUser();
- $id_usuario = $usuario->getId();
- $id_usuario = Util::encode_afcode($id_usuario);
- if ($user['fidelizacion'] != '') {
- $generator = new \Picqer\Barcode\BarcodeGeneratorSVG();
- $codigoBarras = $generator->getBarcode($user['fidelizacion'], $generator::TYPE_CODE_128,4,90);
- } else {
- $codigoBarras = '';
- }
- $transaccionesAfiliadas = $usuario->getTransaccionesDelAfiliado();
- $total_conseguido = 0;
- $cantidad_afiliado = 0;
- foreach($transaccionesAfiliadas as $trans){
- $total_conseguido = $total_conseguido + $trans->getTotalTransaccion();
- if($trans->getTipo() == "PENDIENTE"){
- $cantidad_afiliado = $cantidad_afiliado + $trans->getParteAfiliado();
- }else if(($trans->getTipo() == "PAGADO")){
- $cantidad_afiliado = $cantidad_afiliado - $trans->getParteAfiliado();
- }
- }
- //Validacion del formulario de alertas
- $returnArray = array(
- 'user' => $user,
- 'puntos' => $puntos,
- 'totalConseguido' => $total_conseguido,
- 'totalAfiliado' => $cantidad_afiliado,
- 'transaccionesRelacionadas' => $transaccionesAfiliadas,
- 'id' => $id_usuario,
- 'codigoBarras' => $codigoBarras,
- );
- return $this->render('default/perfil/tarjeta_afiliados.html.twig', $returnArray);
- }
- /* #[Route(path: [
- 'es' => '/usuarios/ver-usuario/{id}',
- 'en' => '/en/user/see-user/{id}'
- ], name: 'admin_customer_show')]
- public function showAction(Request $request, PersistenceManagerRegistry $doctrine, WebServiceUsuarios $wsu)
- {
- // try {
- $orden = 'ASC';
- $ordenacionActivado = false;
- $em = $doctrine->getManager();
- $customer = $this->getUser();
- $erpId = $customer->getErpId();
- $WSU = $this->container->get('web.service.usuarios', $em);
- $erpUser = null;
- $filtroFecha = false;
- $ordenacionActivado = false;
- if ($erpId) {
- $erpUser = $wsu->findBy('No', $erpId);
- }
- $form = $this->createForm(
- new ClientType(),
- $customer, array('action' => $this->generateUrl('admin_customer_show', array('id' => $customer->getId())),
- 'method' => 'POST',
- )
- );
- $ordenacioon = $request->query->get('ord');
- if($ordenacioon == 'desc'){
- // return $this->redirect($this->generateUrl('admin_customer_show', array('id' => $customer->getId(), 'ord' => 'asc')));
- $orden = 'desc';
- $ordenacionActivado = true;
- }else{
- // return $this->redirect($this->generateUrl('admin_customer_show', array('id' => $customer->getId(), 'ord' => 'desc')));
- $orden = 'asc';
- $ordenacionActivado = true;
- }
- //CONSEGUIR TRANSACCIONESAFILIADO DEL USUARIO
- $id_afi = $customer->getId();
- $transaccionesRel = $em->getRepository("App\Entity\TransaccionAfiliado")->buscarTransaccionesAfiliado($id_afi, $orden);
- //VARIABLES PARA MANTENER LOS TOTALES
- $total_pagar_afi = 0;
- $total_afiliado = 0;
- $signo = "";
- foreach($transaccionesRel as $trans){
- if($trans->getTipo() == "PENDIENTE"){
- $total_pagar_afi =$total_pagar_afi + $trans->getParteAfiliado();
- $total_afiliado = $total_afiliado + $trans->getTotalTransaccion();
- $signo = "+";
- }else if($trans->getTipo() == "PAGADO"){
- $total_pagar_afi = $total_pagar_afi - $trans->getParteAfiliado();
- $signo = "-";
- }
- }
- $repository = $em->getRepository("App\Entity\TransaccionAfiliado");
- $array_trans = array();
- $form->handleRequest($request);
- if ($form->isSubmitted()) {
- if ($form->isValid()) {
- if ($form['newPassword']->getData()) $customer->setPlainPassword($form['newPassword']->getData());
- // $userManager = $this->container->get('fos_user.user_manager');
- //SI EL SUBMIT ERA PAGO CREAMOS NUEVA TRANSACCIONAFILIADO
- if ($form->getClickedButton() && 'pago' === $form->getClickedButton()->getName()) {
- $cantidad = $form['cantidad']->getData();
- //$total_pagar_afi = $total_pagar_afi - $cantidad;
- $transAfi = new TransaccionAfiliado();
- $transAfi->setParteAfiliado($cantidad);
- $transAfi->setAfiliado($customer);
- $transAfi->setTipo("PAGADO");
- $transAfil = $transAfi;
- $em->persist($transAfi);
- $em->flush();
- $this->addSuccessMessage('Pago Realizado Correctamente');
- return $this->redirect($this->generateUrl('admin_customer_show', array('id' => $customer->getId())));
- }
- if ($form->getClickedButton() && 'filtrofecha' === $form->getClickedButton()->getName()) {
- $fechaCom = $form['tiempoCom']->getData();
- $fechaFin = $form['tiempoFin']->getData();
- //$total_pagar_afi = $total_pagar_afi - $cantidad;
- $transaccionesFiltradas = $repository->findByRange($fechaCom, $fechaFin, $id_afi);
- $transaccionesRel = $transaccionesFiltradas;
- $filtroFecha = true;
- $this->addSuccessMessage('Filtrado Realizado Correctamente');
- }
- if (!$filtroFecha) {
- if($form['role'][0]->getData()){
- $customer->addRole("ROLE_AFILIADO");
- $var_aux = $this->redirect($this->generateUrl('admin_afiliado_index'));
- }else{
- $customer->removeRole("ROLE_AFILIADO");
- $var_aux = $this->redirect($this->generateUrl('admin_customer_index'));
- }
- // var_dump($customer)
- // $userManager->updateUser($customer, true);
- $this->addSuccessMessage('Usuario Actualizado');
- return $var_aux;
- }
- } else {
- $this->addErrorMessage('Error al modificar el usuario');
- return $this->redirect($this->generateUrl('admin_customer_show'));
- }
- }
- $returnArray = array(
- 'form' => (isset($form)) ? $form->createView():"",
- 'cantTotalAfi' => $total_afiliado,
- 'cantTotalAPag' => $total_pagar_afi,
- 'transaccionesRelacionadas' => $transaccionesRel,
- 'customer' => $customer,
- 'signo' => $signo,
- 'erpUser' => $erpUser,
- 'filtroFecha' => $filtroFecha,
- 'ordenacionActivado' => $ordenacionActivado
- );
- return $returnArray;
- // } catch (\Exception $e) {
- // }
- }*/
- }