src/Controller/Frontend/IndexController.php line 597

Open in your IDE?
  1. <?php
  2. namespace App\Controller\Frontend;
  3. use App\Controller\Frontend\Index\Service\VerifyContactCaptchaService;
  4. use App\Controller\Frontend\Index\Service\CaptureContactMessageService;
  5. use App\Web\Notification\Application\Service\SendInscriptionPhoneNotificationService;
  6. use App\Controller\Frontend\Payment\Service\ProcessRefundNotification;
  7. use App\Controller\Frontend\Payment\Service\ValidatePaymentNotification;
  8. use App\Controller\Shared\Livescoring\LivescoringCache;
  9. use App\Controller\Frontend\Tournament\Data\RefundTpvResolver;
  10. use App\Controller\Shared\MatchPlay\RyderCup\RyderCupResultsData;
  11. use App\Controller\Shared\Player\UpdatePlayerFromFederated;
  12. use App\Controller\Shared\Socket\LivescoringChannelKey;
  13. use App\DBAL\Backend\EnumEstadoInscrito;
  14. use App\DBAL\Backend\EnumEstadoRestringirLicencias;
  15. use App\Service\CalculateCurrentHoleService;
  16. use App\Entity\Backend\CompetitionSection;
  17. use App\Entity\Backend\CompetitionSectionHidden;
  18. use App\Service\Competition\PreferredLicenseClubChecker;
  19. use Doctrine\Common\Collections\ArrayCollection;
  20. use Doctrine\ORM\EntityManagerInterface;
  21. use Redis;
  22. use Symfony\Component\HttpFoundation\RedirectResponse;
  23. use Symfony\Component\Routing\Annotation\Route;
  24. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  25. use Symfony\Component\HttpFoundation\Request;
  26. use Symfony\Component\HttpFoundation\Response;
  27. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  28. use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
  29. use Symfony\Component\HttpFoundation\JsonResponse;
  30. use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
  31. use Symfony\Component\HttpKernel\KernelInterface;
  32. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  33. use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
  34. use Symfony\Component\Form\Extension\Core\Type\EmailType;
  35. use Symfony\Component\Form\Extension\Core\Type\HiddenType;
  36. use Symfony\Component\Form\Extension\Core\Type\TextType;
  37. use Symfony\Component\Form\Extension\Core\Type\TextareaType;
  38. use Symfony\Component\Form\Extension\Core\Type\SubmitType;
  39. use Symfony\Component\Form\FormError;
  40. use Symfony\Component\Validator\Constraints\NotBlank;
  41. use Symfony\Component\Validator\Constraints\Email;
  42. use Symfony\Component\Validator\Constraints\Length;
  43. use Symfony\Component\Asset\Packages;
  44. use Buzz\Browser;
  45. use Buzz\Client\FileGetContents;
  46. use Nyholm\Psr7\Factory\Psr17Factory;
  47. use App\Entity\Backend\Inscrito;
  48. use App\Entity\Backend\InscritoDocumento;
  49. use App\Entity\Backend\Log;
  50. use App\Entity\Backend\HcpJuego;
  51. use App\Entity\Backend\Equipo;
  52. use App\Util\Util;
  53. use App\Util\UtilStatic;
  54. use App\Util\UtilJugadores;
  55. use App\Util\Tarjetas;
  56. use App\Entity\Backend\Pedido;
  57. use App\Entity\Backend\TransaccionRedsys;
  58. use App\Entity\Backend\Jugador;
  59. use App\Entity\Backend\Categoria;
  60. use App\Entity\Backend\CategoriaConfig;
  61. use App\Entity\Backend\Clasificacion;
  62. use App\Entity\Backend\Clasificado;
  63. use App\Entity\Backend\Cliente;
  64. use App\Entity\Backend\Comunidad;
  65. use App\Service\FederatedWebService;
  66. // use App\Service\RFEGWebService;
  67. use App\Util\RedsysAPI;
  68. use App\Util\Recipe;
  69. use App\Entity\Backend\JugadorRGPD;
  70. use App\Service\EnvioCorreo;
  71. use App\Service\EnvioSms;
  72. use App\Service\NotificacionesService;
  73. use App\Util\Utilidades;
  74. use App\Entity\Backend\Club;
  75. use App\Entity\Backend\Competicion;
  76. use App\Entity\Backend\Estadisticas;
  77. use App\Entity\Backend\Horario;
  78. use App\Entity\Backend\Jornada;
  79. use App\Entity\Backend\JornadaConfig;
  80. use App\Entity\Backend\Resultado;
  81. use App\Entity\Backend\Sms;
  82. use App\Entity\Backend\SoftwareGolf;
  83. use App\Entity\Backend\Trazado;
  84. use App\Entity\Backend\TrazadoBarra;
  85. use App\Entity\Gestion\JugadorHorario;
  86. use App\Entity\Gestion\PartidaHorario;
  87. use App\Entity\User\User;
  88. use App\Entity\User\UserApp;
  89. use App\Entity\Backend\Provincia;
  90. use Doctrine\Persistence\ManagerRegistry;
  91. use Symfony\Component\HttpFoundation\BinaryFileResponse;
  92. use Symfony\Component\HttpFoundation\ResponseHeaderBag;
  93. use App\Util\SoftwareExternoUtil;
  94. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  95. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  96. class IndexController extends AbstractController
  97. {
  98. public function __construct(
  99. private readonly EntityManagerInterface $em,
  100. private readonly Util $util,
  101. private readonly Utilidades $utilidades,
  102. private readonly TokenStorageInterface $tokenStorage,
  103. private readonly SessionInterface $session,
  104. private readonly UpdatePlayerFromFederated $updatePlayerFromFederated,
  105. private readonly RyderCupResultsData $ryderCupResultsData
  106. )
  107. {
  108. }
  109. /**
  110. * F-017 Pagina principal
  111. *
  112. * @Route("/", name="portada")
  113. *
  114. */
  115. public function index(Request $request, VerifyContactCaptchaService $verifyCaptcha, CaptureContactMessageService $captureContact)
  116. {
  117. // $secret = $this->getParameter('secret');
  118. // $long = $this->getParameter('next.longitud.hash');
  119. // $cifrado = $this->util->encriptarLargo('majgolfacademyForSlope', $secret, $long);
  120. // Creamos el formulario. Lo creamos asi ya que no hace falta entidad para contacto.
  121. $form = $this->createContactForm();
  122. $form->handleRequest($request);
  123. $failureStatus = Response::HTTP_UNPROCESSABLE_ENTITY;
  124. if ($form->isSubmitted() && $form->isValid()) {
  125. $token = $request->request->all()['g-recaptcha-response'] ?? '';
  126. if ($verifyCaptcha(is_string($token) ? $token : '', $request->getHost())) {
  127. try {
  128. $captureContact($form->getData());
  129. } catch (\Throwable $exception) {
  130. $form->addError(new FormError('No se ha podido guardar tu mensaje. Vuelve a intentarlo.'));
  131. $failureStatus = Response::HTTP_INTERNAL_SERVER_ERROR;
  132. }
  133. if ($form->isValid()) {
  134. if ($request->isXmlHttpRequest()) {
  135. return new JsonResponse(['success' => true, 'message' => 'Hemos recibido tu mensaje.']);
  136. }
  137. $this->addFlash('success', 'Hemos recibido tu mensaje.');
  138. return $this->redirectToRoute('portada');
  139. }
  140. } else {
  141. $form->addError(new FormError('No se ha podido verificar reCAPTCHA. Vuelve a intentarlo antes de enviar el mensaje.'));
  142. }
  143. }
  144. if ($form->isSubmitted() && $request->isXmlHttpRequest()) {
  145. $errors = [];
  146. foreach ($form->getErrors(true) as $error) {
  147. $errors[] = $error->getMessage();
  148. }
  149. return new JsonResponse(['success' => false, 'message' => implode(' ', $errors)], $failureStatus);
  150. }
  151. $numTournaments = $this->em->getRepository(Competicion::class)->cuentaCompeticionesTotal();
  152. $totalPaidEnrolled = $this->em->getRepository(Inscrito::class)->countPaid();
  153. $competicionesInscripcionCercana = $this->em->getRepository(Competicion::class)->competicionesInscripcionCercana(12);
  154. return $this->render('frontend/Default/index.html.twig', [
  155. "form" => $form->createView(),
  156. "recaptchaSiteKey" => $this->getParameter('contact_recaptcha.site_key'),
  157. "limiteLivescoring" => 4, // tarjetas que se muestran por cada componente livescoring
  158. "competicionesInscripcionCercana" => $competicionesInscripcionCercana,
  159. "counter" => [
  160. "tournaments" => $numTournaments,
  161. "players" => $totalPaidEnrolled
  162. ]
  163. ]);
  164. }
  165. // Creamos aqui el formulario de contacto que tendra la index
  166. private function createContactForm()
  167. {
  168. $form = $this->createFormBuilder()
  169. ->setMethod("POST")
  170. ->add('name', TextType::class, array(
  171. 'constraints' => [new NotBlank(), new Length(['max' => 255])],
  172. "required" => true,
  173. "label" => "labels.contact.name",
  174. "translation_domain" => "FrontendBundle",
  175. 'label_attr' => [
  176. 'class' => 'label'
  177. ],
  178. 'attr' => [
  179. 'class' => "text-input"
  180. ]
  181. ))
  182. ->add('email', EmailType::class, array(
  183. 'constraints' => [new NotBlank(), new Email(), new Length(['max' => 254])],
  184. "required" => true,
  185. "label" => "labels.contact.email",
  186. "translation_domain" => "FrontendBundle",
  187. 'label_attr' => [
  188. 'class' => 'label'
  189. ],
  190. 'attr' => [
  191. 'class' => "text-input"
  192. ]
  193. ))
  194. ->add('club', TextType::class, array(
  195. 'constraints' => new Length(['max' => 255]),
  196. "required" => false,
  197. "label" => "labels.contact.club",
  198. "translation_domain" => "FrontendBundle",
  199. 'label_attr' => [
  200. 'class' => 'label'
  201. ],
  202. 'attr' => [
  203. 'class' => "text-input"
  204. ]
  205. ))
  206. ->add('license', TextType::class, array(
  207. 'constraints' => new Length(['max' => 255]),
  208. "required" => false,
  209. "label" => "labels.contact.license",
  210. "translation_domain" => "FrontendBundle",
  211. 'label_attr' => [
  212. 'class' => 'label'
  213. ],
  214. 'attr' => [
  215. 'class' => "text-input"
  216. ]
  217. ))
  218. ->add('message', TextareaType::class, array(
  219. 'constraints' => [new NotBlank(), new Length(['max' => 10000])],
  220. "required" => true,
  221. "label" => "labels.contact.message",
  222. "translation_domain" => "FrontendBundle",
  223. 'label_attr' => [
  224. 'class' => 'label'
  225. ],
  226. 'attr' => [
  227. "rows" => 4,
  228. "cols" => 50,
  229. 'class' => "textarea"
  230. ]
  231. ))
  232. ->add('privacyPolicy', CheckboxType::class, array(
  233. 'constraints' => new NotBlank(),
  234. "required" => true,
  235. "label" => false,
  236. 'label_attr' => [
  237. 'class' => 'label-check'
  238. ],
  239. "translation_domain" => "FrontendBundle"
  240. ))
  241. ->add('send', SubmitType::class, array(
  242. 'label' => "labels.contact.send",
  243. "translation_domain" => "FrontendBundle",
  244. 'attr' => [
  245. 'class' => "button enviar"
  246. ]
  247. ))
  248. ->getForm();
  249. return $form;
  250. }
  251. /**
  252. * @Route("/livescoring-start", name="livescoring_start")
  253. */
  254. public function indexLivescoringStart(LivescoringCache $livescoringCache, LivescoringChannelKey $livescoringChannelKey)
  255. {
  256. // Devuelve las jornadas que se quieren mostrar en el livescoring de la index
  257. $jornadasLivescoring = $this->em->getRepository(Jornada::class)->indexLivescoring();
  258. if (empty($jornadasLivescoring)) {
  259. return $this->json([]);
  260. }
  261. $roundIds = array_column($jornadasLivescoring, "id");
  262. $jornadas = $this->em->getRepository(Jornada::class)->findBy(['id' => $roundIds]);
  263. $jornadasById = [];
  264. foreach ($jornadas as $jornadaLoaded) {
  265. $jornadasById[$jornadaLoaded->getId()] = $jornadaLoaded;
  266. }
  267. $livescoring = [];
  268. foreach ($jornadasLivescoring as $jl) {
  269. if (!isset($jornadasById[$jl["id"]])) {
  270. continue;
  271. }
  272. $jornada = $jornadasById[$jl["id"]];
  273. $competicion = $jornada->getCompeticion();
  274. $livescoringParams = [
  275. 'isTeamLivescoring' => false
  276. ];
  277. $livescoring["l-" . $jl["id"]] = [
  278. ...$livescoringCache->__invoke($jornada, $livescoringParams),
  279. "compId" => $competicion->getId(),
  280. "nombreClub" => $competicion->getClub()->getNombre(),
  281. "nombreCompeticion" => $competicion->getNombre(),
  282. 'socketChannel' => $livescoringChannelKey->__invoke($competicion)
  283. ];
  284. }
  285. return $this->json($livescoring);
  286. }
  287. // public function contacto(Request $request, SendEmailUtil $mailer): Response {
  288. // $sended = 0;
  289. // //Creamos el formulario. Lo creamos asi ya que no hace falta entidad para contacto.
  290. // $form = $this->createContactForm([]);
  291. // $form->handleRequest($request);
  292. // if (count($form->getErrors()) > 0) {
  293. // $sended = -1;
  294. // }
  295. // if ($form->isSubmitted() && $form->isValid() /* && $this->captchaverify($request->get('g-recaptcha-response')) */) {
  296. // $mailer->sendEmail([
  297. // "from" => $this->getParameter('app.notifications.email_sender'),
  298. // "to" => $this->getParameter('email.contacto'),
  299. // "asunto" => 'Contacto FGM',
  300. // "cco" => "gest.slope@gmail.com",
  301. // "html" => $this->renderView('mail/contact_mail.html.twig', [
  302. // 'nombre' => $form->get("name")->getData(),
  303. // 'emailFrom' => $form->get("email")->getData(),
  304. // 'texto' => $form->get("text")->getData(),
  305. // 'telefono' => $form->get("phone")->getData(),
  306. // 'bloque' => 'contacto'
  307. // ])
  308. // ]);
  309. // //EmailContacto::sendEmailContact($form, $mailer, $this->getParameter('emails.contacto.user'));
  310. // //Limpiamos el array (lo creamos de nuevo)
  311. // $data = array();
  312. // $form = $this->createContactForm($data);
  313. // $sended = 1;
  314. // }
  315. // return $this->render('frontend/default/contacto.html.twig', array("form" => $form->createView(), "sended" => $sended));
  316. // }
  317. /**
  318. * @Route("/search-panel", name="searchPanel", options={"expose"=true})
  319. *
  320. * Hace la busqueda de competiciones y clubes en la index
  321. */
  322. public function searchPanel(Request $request)
  323. {
  324. $text = $request->request->get('text');
  325. $competicionesBusqueda = $this->em->getRepository(Competicion::class)->indexSearch($text);
  326. $clubes = $this->em->getRepository(Club::class)->findClubes($text);
  327. $competiciones = [];
  328. foreach ($competicionesBusqueda as $cb) {
  329. $competiciones[] = [
  330. "id" => $cb["id"],
  331. "nombre" => $cb["nombre"],
  332. "fecha" => $cb["fecha"]->format("Y-m-d"),
  333. "nombreClub" => $cb["nombreClub"]
  334. ];
  335. }
  336. return $this->json([
  337. "competiciones" => $competiciones,
  338. "clubes" => $clubes
  339. ]);
  340. }
  341. /**
  342. * F-018 Falso feed de calendario
  343. *
  344. * @Route("/{locale}/f/club/{club}/feed.ics", name="feed")
  345. *
  346. */
  347. public function feed($locale, $club)
  348. {
  349. return new JsonResponse(["club" => $club, "locale" => $locale]); //$this->redirect($this->generateUrl('_club', array('id' => $club)));
  350. }
  351. /**
  352. * F-019 Envio de SMS de prueba para los usuarios con rol marketing
  353. *
  354. * @Route("/sms-reset", name="sms_reset_marketing", options={"expose"=true})
  355. *
  356. */
  357. public function smsReset(Request $request, EnvioCorreo $mailer, EnvioSms $messaging, UtilJugadores $util_jugadores)
  358. {
  359. $respuesta = array();
  360. $numero = $request->request->get('numero');
  361. if (!$numero) {
  362. $respuesta['codigo'] = -2;
  363. $respuesta['mensaje'] = "No se ha indicado ningún numero de telefono al que mandar los mensajes";
  364. return new JsonResponse($respuesta);
  365. }
  366. //usamos el campo publicidad a modo de prioridad. Buscamos los que son de prioridad negativa, segun su usuario
  367. $usuario = $request->request->get('usuario');
  368. $smss = $this->em->getRepository(Sms::class)->findBy(array('publicidad' => (-1 * $usuario)));
  369. if (!$smss) {
  370. $respuesta['codigo'] = -1;
  371. $respuesta['mensaje'] = "No hay ningún SMS de ejemplo";
  372. return new JsonResponse($respuesta);
  373. }
  374. $ahora = new \DateTime('now');
  375. $secret = $this->getParameter('secret');
  376. //ponemos los mensjaes como no enviados y le asignamos el numero de telefono que le corresponde
  377. foreach ($smss as $sms) {
  378. $sms->setTelefono($numero, $secret);
  379. $sms->setUpdatedAt($ahora);
  380. $messaging->enviarSmsAPI($sms, true, 0, true);
  381. }
  382. $this->em->flush();
  383. //tomamos la IP y la localización del cliente para adjuntarla al email
  384. $client_location = Recipe::getClientLocation();
  385. $client_IP = Recipe::getClientIP();
  386. $user = $this->em->getRepository(User::class)->findOneBy(array('ccc' => $usuario));
  387. //mandamos email avisando del login
  388. $args = [
  389. "to" => "nacho.perez.benito@gmail.com",
  390. "subject" => 'NextCaddy - SMS de prueba enviados (pagina de marketing)',
  391. "html" => $this->renderView('backend/mail/email_envio_sms.html.twig', array(
  392. 'user' => $user,
  393. 'numero' => $numero,
  394. 'client_ip' => $client_IP,
  395. 'client_location' => $client_location))
  396. ];
  397. //EnvioCorreo::enviarCorreo($args);
  398. $mailer->enviarCorreo($args);
  399. $respuesta['codigo'] = 0;
  400. $respuesta['mensaje'] = "Se han enviado los mensajes de ejemplo";
  401. return new JsonResponse($respuesta);
  402. }
  403. /**
  404. * @Route("/field-f1", name="field_f1")
  405. */
  406. public function fieldF1()
  407. {
  408. $totalRoundsNumber = $this->em->getRepository(Jornada::class)->countAllWithDeleted();
  409. $totalPaidEnrolled = $this->em->getRepository(Inscrito::class)->countPaid();
  410. return $this->render("frontend/Television/formula1.html.twig", [
  411. "totalRoundsNumber" => $totalRoundsNumber,
  412. "totalPaidEnrolled" => $totalPaidEnrolled
  413. ]);
  414. }
  415. /**
  416. * F-020 Envio de SMS de prueba para demos y presentaciones
  417. *
  418. * @Route("/sms-reset/{numero}", name="sms_reset", options={"expose"=true})
  419. *
  420. */
  421. public function smsExample($numero, EnvioSms $messaging)
  422. {
  423. $respuesta = ['codigo' => 0];
  424. //usamos el campo publicidad a modo de prioridad. Buscamos los que son de maxima prioridad, ya que esos seran los que sean de ejemplo (prioridad minima 8, 9 o mas, no envia)
  425. $smss = $this->em->getRepository(Sms::class)->findBy(array('publicidad' => 0));
  426. if (!$smss) {
  427. $respuesta['codigo'] = -1;
  428. return $this->render("frontend/Default/smsExamples.html.twig", $respuesta);
  429. }
  430. $ahora = new \DateTime('now');
  431. $secret = $this->getParameter('secret');
  432. //ponemos los mensjaes como no enviados y le asignamos el numero de telefono que le corresponde
  433. foreach ($smss as $sms) {
  434. $sms->setTelefono($numero, $secret);
  435. $sms->setUpdatedAt($ahora);
  436. $messaging->enviarSmsAPI($sms, true, 0, true);
  437. }
  438. $this->em->flush();
  439. $log_message = "Envio de Sms de prueba al teléfono " . $numero;
  440. $log = new Log('i', $log_message, null);
  441. $this->em->persist($log);
  442. $this->em->flush();
  443. return $this->render("frontend/Default/smsExamples.html.twig", $respuesta);
  444. }
  445. /**
  446. * F-021 Envio de visita a la pagina para estadisticas de Google Analitycs para Internet Explorer o fallo de la libreria Javascript
  447. *
  448. * @Route("/collect", name="collect", options={"expose"=true})
  449. *
  450. */
  451. public function collect()
  452. {
  453. $params = array('v' => 1,
  454. 'tid' => "UA-61056427-1",
  455. 'cid' => rand(1000000, 9999999),
  456. 't' => "event",
  457. 'ec' => "Blocking",
  458. 'ea' => "NextCaddy",
  459. 'ni' => '0',
  460. 'z' => rand(1000000, 9999999),
  461. );
  462. $client = new FileGetContents(new Psr17Factory());
  463. $browser = new Browser($client, new Psr17Factory());
  464. $url = 'https://www.google-analytics.com/collect?' . http_build_query($params);
  465. try {
  466. $response = $browser->get($url);
  467. $res = $response->getStatusCode() == '200';
  468. } catch (\Throwable $e) {
  469. $res = false;
  470. }
  471. return new JsonResponse($res);
  472. }
  473. /**
  474. * F-022 Obtención de datos de un club concreto
  475. *
  476. * @Route("/getClubs", name="_ajGetClubs", options={"expose"=true})
  477. *
  478. */
  479. public function getClubsByName(Request $request)
  480. {
  481. //retrieve the query
  482. $query = $request->request->get("query");
  483. $Clubs = $this->em->getRepository(Club::class)->findClubByName($query);
  484. if (!$Clubs) {
  485. // throw exception
  486. }
  487. $response = new JsonResponse();
  488. $response->setData($Clubs);
  489. return $response;
  490. }
  491. /**
  492. * F-023 Obtención de datos de un jugador en un torneo
  493. *
  494. * @Route("/getJugador", name="_ajGetJugador", options={"expose"=true})
  495. *
  496. */
  497. public function getJugadorByName(Request $request)
  498. {
  499. //retrieve the query
  500. $query = $request->get('query');
  501. $tour = $request->get('tournament');
  502. $playersNames = $this->em->getRepository(Jugador::class)->findPlayerCard($query, $tour);
  503. if (!$playersNames) {
  504. // throw exception
  505. }
  506. $response = new JsonResponse();
  507. $response->setData($playersNames);
  508. return $response;
  509. }
  510. /**
  511. * F-024 Pagina de instrucciones para integrar NextCaddy en la web del club
  512. *
  513. * @Route("/integracion", name="integracion")
  514. */
  515. public function integracionWidget()
  516. {
  517. $clubs = $this->em->getRepository(Club::class)->findTodosParaRandom();
  518. if (!$clubs) {
  519. $this->addFlash(
  520. 'error', "Ha ocurrido un error. Por favor, inténtelo más tarde");
  521. //return $this->redirect($this->generateUrl('_club', array('id' => "AM00")));
  522. return $this->redirect($this->generateUrl('portada'));
  523. }
  524. return $this->render("frontend/Club/generarWidget.html.twig", [
  525. 'clubes' => $clubs
  526. ]);
  527. }
  528. /**
  529. * F-025 Pagina de Politica de cookies
  530. *
  531. * @Route("/cookies", name="cookies")
  532. */
  533. public function cookies()
  534. {
  535. return $this->render("frontend/Default/politica_cookies.html.twig");
  536. }
  537. /**
  538. * F-026 Pagina de Politica de privacidad
  539. *
  540. * @Route("/privacidad", name="privacidad")
  541. */
  542. public function privacidad()
  543. {
  544. return $this->render("frontend/Default/privacidad.html.twig");
  545. }
  546. /**
  547. * F-027 Pagina de Terminos y condiciones
  548. *
  549. * @Route("/terminos-y-condiciones", name="terminos_condiciones")
  550. */
  551. public function terminosCondiciones()
  552. {
  553. return $this->render("frontend/Default/terminos_condiciones.html.twig");
  554. }
  555. /**
  556. * F-029 Seleccionamos el tipo de livescoring para la competicion
  557. *
  558. * @Route("/livescoring-select/{id}/{ordenUrl}/{letra}", name="envivo_select", defaults={"letra"="H", "ordenUrl"=0}, options={"expose"=true})
  559. */
  560. public function envivoSelect($id, $ordenUrl, $letra): RedirectResponse
  561. {
  562. $competicion = $this->em->getRepository(Competicion::class)->find($id);
  563. if (empty($competicion)) {
  564. throw new \Exception("Competition with id $id not found");
  565. }
  566. if (in_array($competicion->getFormula()->getId(), ['R', 'P'])) {
  567. return $this->redirect($this->generateUrl('gestion_ryder_cup_livescoring', array('idc' => $id)));
  568. }
  569. //TODO search all uses and change to new livesoring route. While Redirect to new livescoring
  570. return $this->redirect($this->generateUrl('livescoring', array('id' => $id)));
  571. }
  572. /**
  573. * F-030 Visualización de competiciones a través del widget (iframe)
  574. *
  575. * @Route("/widget/{id}", name="_widget")
  576. */
  577. public function widget($id)
  578. {
  579. $entity = $this->em->getRepository(Club::class)->findOneBy(array("id" => $id, "habilitado" => true));
  580. if (!$entity) {
  581. $this->addFlash(
  582. 'error', "No encontramos el Club que nos ha solicitado");
  583. //return $this->redirect($this->generateUrl('_club', array('id' => "AM00")));
  584. return $this->redirect($this->generateUrl('portada'));
  585. }
  586. $futuras = array();
  587. $pasadas = array();
  588. if ($id != "AM00") {
  589. //Me traigo competiciones futuras y pasadas
  590. $futuras = $this->em->getRepository(Competicion::class)->getCompeticiones($id, 36, 0, "mayor", "ASC", true);
  591. $pasadas = $this->em->getRepository(Competicion::class)->getCompeticiones($id, 36, 0, "menor", "DESC", true);
  592. } else {
  593. //Me traigo competiciones futuras y pasadas
  594. $futuras = $this->em->getRepository(Competicion::class)->getCompeticionesOrganizador("AM00", 48, 0, "mayor", "ASC", true);
  595. $pasadas = $this->em->getRepository(Competicion::class)->getCompeticionesOrganizador("AM00", 48, 0, "menor", "DESC", true);
  596. }
  597. return $this->render("frontend/Club/widget.html.twig", [
  598. 'entity' => $entity,
  599. 'futuras' => $futuras,
  600. 'pasadas' => $pasadas
  601. ]);
  602. }
  603. /**
  604. * F-033 Mostrar inscritos estado de corte. [Creo que en desuso]
  605. *
  606. * @Route("/inscritoscorte", name="_ajInscritosCorte", options={"expose"=true})
  607. */
  608. public function inscritosCorte(Request $request)
  609. {
  610. $id = $request->request->get("id");
  611. //comprobar datos de ordenacion competicion.
  612. $comp_criteria = $this->em->getRepository(Competicion::class)->find($id);
  613. $num_jugadores = $comp_criteria->getJugadores();
  614. //Distinguimos entre si tenemos 1 o mas jugadores por equipo en la competicion,
  615. //de esta manera para parejas y equipos mostramos la lista sin linea de corte (que ha sido deshabilidada en el backend)
  616. //para mostrar el listado que está agrupado por parejas o equipos
  617. if ($num_jugadores == 1) {
  618. $params['competi'] = $comp_criteria;
  619. if ($comp_criteria->getCriterio() == null && $comp_criteria->getCriterio2() == null) {
  620. //comprobar datos de ordenacion categoria.
  621. //$cat_criteria = $this->em->getRepository(Categoria::class)->findByCompeticion($id);
  622. $cat_criteria = $this->em->getRepository(Categoria::class)->findCategoriasInscritosActivos($id);
  623. foreach ($cat_criteria as $crit) {
  624. $inscritosporcategoria[$crit->getId()] = $this->em->getRepository(Inscrito::class)->getPlayersByCatCorte($id, $crit->getId(), $crit->getCriterio(), $crit->getCriterio2());
  625. }
  626. $params['inscritosbycat'] = $inscritosporcategoria;
  627. $params['categorias'] = $cat_criteria;
  628. } else {
  629. $cri1 = null;
  630. $ord1 = "ASC";
  631. $cmpcr1 = $comp_criteria->getCriterio();
  632. if (!empty($cmpcr1)) {
  633. $cri1 = $cmpcr1->getCampo();
  634. $ord1 = $cmpcr1->getOrden();
  635. }
  636. $cri2 = null;
  637. $ord2 = "ASC";
  638. $cmpcr2 = $comp_criteria->getCriterio2();
  639. if (!empty($cmpcr2)) {
  640. $cri2 = $cmpcr2->getCampo();
  641. $ord2 = $cmpcr2->getOrden();
  642. }
  643. $players = $this->em->getRepository(Inscrito::class)->getPlayersByCorte($id, $cri1, $ord1, $cri2, $ord2);
  644. $params['inscritos'] = $players;
  645. }
  646. $params['showInscribeDateInWaitingList'] = $this->checkIfShowInscribeDateInWaitingList($id);
  647. return $this->render('frontend/Inscritos/inscritos_corte_tbl_new.html.twig', $params);
  648. } else {
  649. $players = $this->em->getRepository(Inscrito::class)->getPlayersParejasByCompeticion($comp_criteria, true);
  650. if ($num_jugadores == 2) {
  651. $view = 'frontend/Inscritos/inscritos_tbl_parejas_new.html.twig';
  652. } else {
  653. $view = 'frontend/Inscritos/inscritos_tbl_equipos_new.html.twig';
  654. }
  655. $list = array();
  656. foreach ($players as $i) {
  657. if (!in_array($i->getJugador()->getSexo(), $list, true)) {
  658. array_push($list, $i->getJugador()->getSexo());
  659. }
  660. }
  661. // if (!$players) {
  662. // $response = new JsonResponse();
  663. // return $response->setData('No data');
  664. // } else {
  665. return $this->render($view, array(
  666. 'inscritos' => $players,
  667. 'competi' => $comp_criteria,
  668. 'sexos' => count($list)
  669. ));
  670. // }
  671. }
  672. }
  673. /**
  674. * F-034 Mostrar inscritos con y sin linea de corte
  675. * Ya es la plantilla la que me lo separa. Yo solo mando array agrupado
  676. *
  677. * @Route("/getListadoInscritos", name="listado_inscritos", options={"expose"=true})
  678. *
  679. */
  680. public function listadoInscritos(Request $request)
  681. {
  682. $competitionId = $request->request->get("id", 0);
  683. $token = $request->request->get("token", null);
  684. //comprobar datos de ordenacion competicion.
  685. $competition = $this->em->getRepository(Competicion::class)->find($competitionId);
  686. if (!$competition) {
  687. return new JsonResponse(-1);
  688. }
  689. if (!$this->util->checkTokenValidIframe($competition, $token)) {
  690. return new JsonResponse(-1);
  691. }
  692. $numPlayersByTeam = $competition->getJugadores();
  693. //Distinguimos entre si tenemos 1 o mas jugadores por equipo en la competicion,
  694. //de esta manera para parejas y equipos mostramos la lista sin linea de corte (que ha sido deshabilidada en el backend)
  695. //para mostrar el listado que está agrupado por parejas o equipos
  696. if ($numPlayersByTeam == 1) {
  697. $numTotalJornadas = count($competition->getJornadas());
  698. $params['competition'] = $competition;
  699. $jornadaConfigByCategory = [];
  700. if ($competition->getCriterio() == null && $competition->getCriterio2() == null) {
  701. $inscritosByCategory = [];
  702. $categoriasByCompetition = [];
  703. $cutOffByCategory = false;
  704. $inscritos = $this->em->getRepository(Inscrito::class)->getActiveInscribedOrdered($competition);
  705. foreach ($inscritos as $inscrito) {
  706. $inscribedCategory = $inscrito->getCategoria();
  707. if (is_null($inscribedCategory)) {
  708. continue;
  709. }
  710. if (!isset($categoriasByCompetition[$inscribedCategory->getId()])) {
  711. $categoriasByCompetition[$inscribedCategory->getId()] = [
  712. 'id' => $inscribedCategory->getId(),
  713. 'name' => $inscribedCategory->getNombre(),
  714. 'criterio' => $inscribedCategory->getCriterio()?->getNombre(),
  715. 'criterio_id' => $inscribedCategory->getCriterio()?->getId(),
  716. 'criterio_orden' => $inscribedCategory->getCriterio()?->getOrden(),
  717. 'criterio2' => $inscribedCategory->getCriterio2()?->getNombre(),
  718. ];
  719. if (!$cutOffByCategory && !is_null($inscribedCategory->getCriterio())) {
  720. $cutOffByCategory = true;
  721. }
  722. $inscritosByCategory[$inscribedCategory->getId()] = [];
  723. }
  724. if ($inscrito->getParticipa() !== -1) {
  725. $inscritosByCategory[$inscribedCategory->getId()][] = $inscrito;
  726. }
  727. $inscritosByCategory['total'][] = $inscrito;
  728. }
  729. foreach ($categoriasByCompetition as $categoria) {
  730. if ($numTotalJornadas == 1) {
  731. $jornadaConfigByCategory[$categoria['id']] = $this->em->getRepository(JornadaConfig::class)->findOneByCategoria($categoria['id']);
  732. }
  733. if ($categoria['criterio_id'] == 'HCP') {
  734. usort($inscritosByCategory[$categoria['id']], function (Inscrito $a, Inscrito $b) use ($categoria, $competition) {
  735. $participaComparison = $b->getParticipa() <=> $a->getParticipa();
  736. if ($participaComparison !== 0) {
  737. return $participaComparison;
  738. }
  739. if ($competition->getRestringirLicencia() === EnumEstadoRestringirLicencias::PREFERENCIA) {
  740. $orderWaitingListComparison = $a->getOrderWaitingList() <=> $b->getOrderWaitingList();
  741. if ($orderWaitingListComparison !== 0) {
  742. return $orderWaitingListComparison;
  743. }
  744. }
  745. if ($categoria['criterio_orden'] == 'ASC') {
  746. $hcpComparison = $a->getHCP() <=> $b->getHCP();
  747. } else {
  748. $hcpComparison = $b->getHCP() <=> $a->getHCP();
  749. }
  750. if ($hcpComparison === 0) {
  751. return $a->getId() <=> $b->getId();
  752. }
  753. return $hcpComparison;
  754. });
  755. }
  756. }
  757. $categoriasByCompetition['total'] = [
  758. 'id' => 'total',
  759. 'name' => 'Total'
  760. ];
  761. if ($cutOffByCategory) {
  762. unset($inscritosByCategory['total']);
  763. unset($categoriasByCompetition['total']);
  764. }
  765. $params['inscritosByCat'] = $inscritosByCategory;
  766. $params['categories'] = $categoriasByCompetition;
  767. $params['jornadaConfig'] = $jornadaConfigByCategory;
  768. } else {
  769. $players = $this->em->getRepository(Inscrito::class)->getPlayersByCorte($competitionId, $competition->getCriterio()?->getCampo(), $competition->getCriterio()?->getOrden(), $competition->getCriterio2()?->getCampo(), $competition->getCriterio2()?->getOrden());
  770. $params['inscritos'] = $players;
  771. }
  772. $params['showInscribeDateInWaitingList'] = $this->checkIfShowInscribeDateInWaitingList($competitionId);
  773. return $this->render('frontend/Inscritos/inscritos_corte_tbl_new.html.twig', $params);
  774. } else {
  775. $players = $this->em->getRepository(Inscrito::class)->getPlayersParejasByCompeticion($competition, true);
  776. if ($numPlayersByTeam == 2 && $competition->getEstricto()) {
  777. $view = 'frontend/Inscritos/inscritos_tbl_parejas_new.html.twig';
  778. } else {
  779. $view = 'frontend/Inscritos/inscritos_tbl_equipos_new.html.twig';
  780. }
  781. $list = array();
  782. foreach ($players as $i) {
  783. if (!in_array($i->getJugador()->getSexo(), $list, true)) {
  784. array_push($list, $i->getJugador()->getSexo());
  785. }
  786. }
  787. if (!$players) {
  788. $response = new JsonResponse();
  789. return $response->setData('No data');
  790. } else {
  791. return $this->render($view, array(
  792. 'inscritos' => $players,
  793. 'competi' => $competition,
  794. 'sexos' => count($list)
  795. ));
  796. }
  797. }
  798. }
  799. private function checkIfShowInscribeDateInWaitingList(int $competitionId): bool
  800. {
  801. $competitionSectionInscribedDateInWaitingList = $this->em->getRepository(CompetitionSection::class)->findOneBy([
  802. "dom_id" => "fecha_lista_espera"
  803. ]);
  804. $competitionSectionHiddenInscribedDateInWaitingList = $this->em->getRepository(CompetitionSectionHidden::class)->findOneBy([
  805. "competition" => $competitionId,
  806. "competition_section" => $competitionSectionInscribedDateInWaitingList
  807. ]);
  808. return empty($competitionSectionHiddenInscribedDateInWaitingList);
  809. }
  810. /**
  811. * @Route("/f1/{roundId}", name="formula1", options={"expose"=true})
  812. */
  813. public function formula1($roundId)
  814. {
  815. $round = $this->em->getRepository(Jornada::class)->find($roundId);
  816. if (empty($round)) {
  817. return $this->json([]);
  818. }
  819. $calculateCurrentHoleService = new CalculateCurrentHoleService();
  820. $jornadaConfig = $this->em->getRepository(JornadaConfig::class)->findOneByJornada($round->getId());
  821. $holesRange = explode("-", $jornadaConfig->getHoyos());
  822. $holesRangeArray = range(intval($holesRange[0]), intval($holesRange[1]));
  823. $isIndividual = "I" === $round->getModalidad()->getId();
  824. $playerSchedules = $this->em->getRepository(JugadorHorario::class)->findJugadoresJornadaPublicada($round);
  825. $numberHolesPlayed = 0;
  826. $players = [];
  827. if ($playerSchedules) {
  828. foreach ($playerSchedules as $playerSchedule) {
  829. $match = $playerSchedule->getPartida();
  830. $lastHolePlayed = $this->em->getRepository(Resultado::class)->findUltimoHoyo($roundId, [$playerSchedule->getInscrito()->getId()])["hoyo"] ?? 0;
  831. $currentHole = $calculateCurrentHoleService->calculateCurrentHole($lastHolePlayed, $holesRangeArray, $match->getTee(), $numberHolesPlayed);
  832. if ($isIndividual) {
  833. $player = $playerSchedule->getInscrito()?->getJugador();
  834. $hcp_juego = $playerSchedule->getInscrito()->getHcpJuego() ? unserialize($playerSchedule->getInscrito()->getHcpJuego()) : "";
  835. if (!empty($hcp_juego)) {
  836. $hcpGame = $this->em->getRepository(HcpJuego::class)->findOneBy(["inscrito" => $playerSchedule->getInscrito(), "jornada" => array_keys($hcp_juego)[0]]);
  837. }
  838. $players[] = [
  839. "teamId" => $playerSchedule->getEquipo(),
  840. "pairId" => $playerSchedule->getPareja(),
  841. "hcp" => round($playerSchedule->getInscrito()?->getHcp(), 2),
  842. "hcp_game" => round($hcpGame?->getHcp(), 2),
  843. "matchId" => $match->getId(),
  844. "teeTime" => $match->getHora(),
  845. "currentHole" => $currentHole,
  846. "name" => $player->getNombre(),
  847. "surname" => $player->getApellidos(),
  848. "license" => $player->getLicencia()
  849. ];
  850. } else {
  851. $enrolleds = $this->em->getRepository(Inscrito::class)->findBy([
  852. "competicion" => $round->getCompeticion()?->getId(),
  853. "equipo" => $playerSchedule->getEquipo(),
  854. "pareja" => $playerSchedule->getPareja(),
  855. "participa" => 1,
  856. "estado" => "pagado"
  857. ]);
  858. foreach ($enrolleds as $enrolled) {
  859. $hcp_juego = $enrolled->getHcpJuego() ? unserialize($enrolled->getHcpJuego()) : "";
  860. $hcpGame = "";
  861. if (!empty($hcp_juego)) {
  862. $hcpGame = $this->em->getRepository(HcpJuego::class)->findOneBy(["inscrito" => $enrolled, "jornada" => array_keys($hcp_juego)[0]]);
  863. }
  864. $players[] = [
  865. "teamId" => $playerSchedule->getEquipo(),
  866. "pairId" => $playerSchedule->getPareja(),
  867. "hcp" => $enrolled?->getHcp(),
  868. "hcp_game" => round($hcpGame, 2),
  869. "matchId" => $match->getId(),
  870. "teeTime" => $match->getHora(),
  871. "currentHole" => $currentHole,
  872. "name" => $enrolled->getJugador()?->getNombre(),
  873. "surname" => $enrolled->getJugador()?->getApellidos(),
  874. "license" => $enrolled->getJugador()?->getLicencia()
  875. ];
  876. }
  877. }
  878. }
  879. }
  880. return $this->json($players);
  881. }
  882. /**
  883. * @Route("/3djs/{teeId}/{holeId}", name="3djs", options={"expose"=true})
  884. */
  885. public function apiInfoMarkers(Request $request)
  886. {
  887. $id = $request->request->get("id", 0);
  888. }
  889. /**
  890. * F-036 Mostrar listado de las clasificaciones publicadas
  891. *
  892. * @Route("/getListadoClasificaciones", name="listado_clasificaciones", options={"expose"=true})
  893. *
  894. */
  895. public function listadoClasificaciones(Request $request)
  896. {
  897. $id = $request->request->get("id", 0);
  898. $token = $request->request->get("token", null);
  899. //comprobar competicion.
  900. $competicion = $this->em->getRepository(Competicion::class)->find($id);
  901. if (!$competicion) {
  902. return new JsonResponse(-1);
  903. }
  904. if (!$this->util->checkTokenValidIframe($competicion, $token)) {
  905. return new JsonResponse(-1);
  906. }
  907. $tipoClasif = 0; //Normal, ExAequo, PlayOff
  908. $clasificaciones = array();
  909. $nombresEquipos = array();
  910. $equipos = array();
  911. $numJugadores = $competicion->getJugadores();
  912. //Me traigo todas las clasificaciones de esta competicion que sean visibles
  913. $clasifs = $this->em->getRepository(Clasificacion::class)->findBy(["competicion" => $id, "publicada" => true], array("orden" => "ASC", "id" => "DESC"));
  914. //Esta es la que sustituye a la anterior cuando se haga bien el menu para que no salga el icono de clasificaicones si no hay ninguna clasificacion visible
  915. //$clasifs = $this->em->getRepository(Clasificacion::class)->findBy(array("id" => $id, "publicada" => 1), array("id" => "DESC"));
  916. foreach ($clasifs as $clf) {
  917. $modalidad = ($numJugadores == 2 || $clf->getModalidad() != "pareja") ? $clf->getModalidad() : "equipo-pareja";
  918. $posicionAnt = 0;
  919. $classificationCalculation = $clf->getCalculo();
  920. if (empty($classificationCalculation)) {
  921. continue; // han llegado errores al correo que segun la base de datos tienen que ser de competiciones antiguas, pero para que no siga
  922. }
  923. $classificationId = $clf->getId();
  924. switch ($modalidad) {
  925. case "individual":
  926. //13/07/2018 Jose: Se saca fuera del for $njornadasAux = $this->em->getRepository(Clasificado::class)->getJornadasByClasificacion($competicion);
  927. //indexamos por clasificacion
  928. //Tengo un listado ordenado por clasificaciones, de manera que tengo primero todos los clasificados ordenados de la 1º clasif, despues la 2º clasif y asi
  929. $clasificaciones[$classificationId] = array("clasificacion" => $clf->getNombre(), "modalidad" => $modalidad, "calculo" => $classificationCalculation->getId(), "tipo" => $clf->getTipo(), "clasificados" => array(), "plantilla" => "Frontend:Clasificacion:clasificados_new-torneo-profesional.html.twig", "equipos" => array());
  930. $listado = $this->em->getRepository(Clasificado::class)->getClasificacionIndividualListado($id, $classificationCalculation->getId(), $classificationId);
  931. foreach ($listado as $elemento) {
  932. //El listado me repite el jugador para la siguiente jornada, me aprovecho de eso
  933. //Al estar indexado, no repito los datos del jugador
  934. if ($posicionAnt != $elemento["posicion"]) {
  935. $clasificaciones[$classificationId]["clasificados"][$elemento["posicion"]] = array("idi" => $elemento["idi"], "nombre" => $elemento["nombre"], "apellidos" => $elemento["apellidos"], "licencia" => $elemento["licencia"], "nacimiento" => $elemento["nacimiento"], "hcp" => $elemento["hcp"], "nivel" => $elemento["nivel"], "jornadas" => array());
  936. $posicionAnt = $elemento["posicion"];
  937. }
  938. //Como estoy indexando arrays y no necesito repetir el jugador, añado tantas jornadas con sus resultados como necesite para ese jugador
  939. $clasificaciones[$classificationId]["clasificados"][$elemento["posicion"]]["jornadas"][$elemento["jornada"]] = array(
  940. "bruto" => $elemento["bruto"],
  941. "neto" => $elemento["neto"],
  942. "contrapar" => $elemento["contrapar"],
  943. "ide" => $elemento["ide"],
  944. "penalidad" => $elemento["penalidad"],
  945. "hcpJuego" => $elemento["hcpJuego"],
  946. "especial" => $elemento["especial"]
  947. );
  948. }
  949. break;
  950. case "equipo-pareja":
  951. //caso inscritos equipo clasificacion parejas. La plantilla puede ser la de equipo y parejas
  952. $esEquipo = false;
  953. //13/07/2018 Jose: Se saca fuera del for $njornadasAux = $this->em->getRepository(Clasificado::class)->getJornadasByClasificacionCouple($competicion, $esEquipo);
  954. //Tengo un listado ordenado por clasificaciones, de manera que tengo primero todos los clasificados ordenados de la 1º clasif, despues la 2º clasif y asi
  955. $clasificaciones[$classificationId] = array("clasificacion" => $clf->getNombre(), "modalidad" => $modalidad, "calculo" => $classificationCalculation->getId(), "tipo" => $clf->getTipo(), "clasificados" => array(), "plantilla" => "Frontend:Clasificacion:clasificadosParejasEquipos_new-torneo.html.twig");
  956. $listado = $this->em->getRepository(Clasificado::class)->getClasificacionParejaListado($id, $competicion->getCalculo()->getId(), $classificationId);
  957. foreach ($listado as $elemento) {
  958. //El listado me repite el jugador para la siguiente jornada, me aprovecho de eso
  959. //Al estar indexado, no repito los datos del jugador
  960. if ($posicionAnt != $elemento["posicion"]) {
  961. $clasificaciones[$classificationId]["clasificados"][$elemento["posicion"]] = array("equipo" => $elemento["equipo"], "pareja" => $elemento["pareja"], "jornadas" => array());
  962. $posicionAnt = $elemento["posicion"];
  963. }
  964. //Como estoy indexando arrays y no necesito repetir el jugador, añado tantas jornadas con sus resultados como necesite para ese jugador
  965. $clasificaciones[$classificationId]["clasificados"][$elemento["posicion"]]["jornadas"][$elemento["jornada"]] = array(
  966. "bruto" => $elemento["bruto"],
  967. "neto" => $elemento["neto"],
  968. "contrapar" => $elemento["contrapar"],
  969. "ide" => $elemento["ide"],
  970. "especial" => $elemento["especial"]
  971. );
  972. }
  973. $equipos = array();
  974. //$nombresEquipos = array();
  975. $equiposAux = $this->em->getRepository(Inscrito::class)->getPlayersParejasByCompeticion($competicion);
  976. foreach ($equiposAux as $equipo) {
  977. $indice = $equipo->getEquipo() . "-" . $equipo->getPareja();
  978. if (!isset($equipos[$indice])) {
  979. $equipos[$indice] = array();
  980. $nombresEquipos[$indice] = $equipo->getNombreEquipo();
  981. }
  982. $jugador = $equipo->getJugador();
  983. $equipos[$indice][] = array(
  984. "idi" => $equipo->getId(),
  985. "nombre" => $jugador->getNombre(),
  986. "apellidos" => $jugador->getApellidos(),
  987. "licencia" => $equipo->getLicencia() ?: $jugador->getLicencia(),
  988. "nacimiento" => $jugador->getFecha(),
  989. "hcp" => $equipo->getHcp(),
  990. "nivel" => (!is_null($equipo->getNivel())) ? $equipo->getNivel()->getId() : "M"
  991. );
  992. }
  993. $clasificaciones[$classificationId]["equipos"] = $equipos;
  994. break;
  995. default:
  996. //caso inscritos equipo clasificacion equipo
  997. //caso inscritos parejas clasificacion parejas
  998. $equipos = array();
  999. $esEquipo = ($competicion->getJugadores() > 2);
  1000. //13/07/2018 Jose: Se saca fuera del for $njornadasAux = $this->em->getRepository(Clasificado::class)->getJornadasByClasificacionCouple($competicion, $esEquipo);
  1001. //Tengo un listado ordenado por clasificaciones, de manera que tengo primero todos los clasificados ordenados de la 1º clasif, despues la 2º clasif y asi
  1002. $clasificaciones[$classificationId] = array("clasificacion" => $clf->getNombre(), "modalidad" => $modalidad, "calculo" => $classificationCalculation->getId(), "tipo" => $clf->getTipo(), "clasificados" => array(), "plantilla" => "Frontend:Clasificacion:clasificadosParejasEquipos_new-torneo.html.twig");
  1003. $listado = $this->em->getRepository(Clasificado::class)->getClasificacionParejaListado($id, $competicion->getCalculo()->getId(), $classificationId);
  1004. foreach ($listado as $elemento) {
  1005. //El listado me repite el jugador para la siguiente jornada, me aprovecho de eso
  1006. //Al estar indexado, no repito los datos del jugador
  1007. if ($posicionAnt != $elemento["posicion"]) {
  1008. $clasificaciones[$classificationId]["clasificados"][$elemento["posicion"]] = array("equipo" => $elemento["equipo"], "equipoId" => $elemento["equipoId"], "pareja" => $elemento["pareja"], "jornadas" => array());
  1009. $posicionAnt = $elemento["posicion"];
  1010. }
  1011. //Como estoy indexando arrays y no necesito repetir el jugador, añado tantas jornadas con sus resultados como necesite para ese jugador
  1012. $clasificaciones[$classificationId]["clasificados"][$elemento["posicion"]]["jornadas"][$elemento["jornada"]] = array(
  1013. "bruto" => $elemento["bruto"],
  1014. "neto" => $elemento["neto"],
  1015. "contrapar" => $elemento["contrapar"],
  1016. "ide" => $elemento["ide"],
  1017. "especial" => $elemento["especial"]
  1018. );
  1019. //Para una competicion de equipos (clasif de equipos) ha ocurrido que (supongo con logica) ha publicado las clasificaciones con pareja = 0,
  1020. //entocnes a la hora de buscar por equipo-pareja no encuentra los miembros, por lo que no los pintaba en el listado
  1021. //Si filtramos de manera que si pareja = 0 coja todos los miembros del equipo, ya los debe de pintar
  1022. if ($elemento["equipoId"]) {
  1023. if ($elemento["pareja"] != 0) {
  1024. $miembros = $this->em->getRepository(Inscrito::class)->getParejaByEquipoEntidad($elemento["pareja"], $elemento["equipoId"]);
  1025. } else {
  1026. $miembros = $this->em->getRepository(Inscrito::class)->findBy(["estado" => "pagado", "equipo_entidad" => $elemento["equipoId"]]);
  1027. }
  1028. $indice = $elemento["equipoId"];
  1029. } else {
  1030. if ($elemento["pareja"] != 0) {
  1031. $miembros = $this->em->getRepository(Inscrito::class)->getInscritosParejaCompeticion($competicion->getId(), $elemento["pareja"], $elemento["equipo"]);
  1032. } else {
  1033. $miembros = $this->em->getRepository(Inscrito::class)->findBy(["estado" => "pagado", "equipo" => $elemento["equipo"], "pareja" => $elemento["pareja"], "competicion" => $competicion]);
  1034. }
  1035. $indice = $elemento["equipo"] . "-" . $elemento["pareja"];
  1036. }
  1037. foreach ($miembros as $miembro) {
  1038. $jugador = $miembro->getJugador();
  1039. $mid = $miembro->getId();
  1040. $equipos[$indice][$mid] = array(//indexamos el miembro por Id de inscrito para evitar que duplique, que es lo que ocurria
  1041. "idi" => $mid,
  1042. "nombre" => $jugador->getNombre(),
  1043. "apellidos" => $jugador->getApellidos(),
  1044. "licencia" => $miembro->getLicencia() ?: $jugador->getLicencia(),
  1045. "nacimiento" => $jugador->getFecha(),
  1046. "hcp" => $miembro->getHcp(),
  1047. "pais" => (!is_null($jugador->getPais())) ? $jugador->getPais()->getId() : "EX",
  1048. "nivel" => (!is_null($miembro->getNivel())) ? $miembro->getNivel()->getId() : "M"
  1049. );
  1050. }
  1051. }
  1052. //$nombresEquipos = array();
  1053. //$equiposEntidadAux = $this->em->getRepository(Equipo::class)->findEquiposEnClasificacion($clf->getId());
  1054. //$equiposAux = $this->em->getRepository(Inscrito::class)->getPlayersParejasByCompeticion($id);
  1055. /* if (count($equiposEntidadAux) > 1) { //26/07/2018 Jose: Si hay equipos de la entidad nueva se hace mas facil
  1056. foreach ($equiposEntidadAux as $idAux) {
  1057. $equipo = $this->em->getRepository(Equipo::class)->find($idAux[1]); //Tengo que hacer el "[1]" por como lo devuelve la query.
  1058. $indice = $equipo->getEquipo();
  1059. if (!isset($equipos[$indice])) {
  1060. $equipos[$indice] = array();
  1061. $nombresEquipos[$indice] = $equipo->getNombre();
  1062. }
  1063. foreach ($equipo->getInscritos() as $inscrito) {
  1064. $jugador = $inscrito->getJugador();
  1065. $equipos[$indice][] = array(
  1066. "idi" => $inscrito->getId(),
  1067. "nombre" => $jugador->getNombre(),
  1068. "apellidos" => $jugador->getApellidos(),
  1069. "licencia" => $jugador->getLicencia(),
  1070. "hcp" => $inscrito->getHcp(),
  1071. "nivel" => (!is_null($inscrito->getNivel())) ? $inscrito->getNivel()->getId() : "M"
  1072. );
  1073. }
  1074. }
  1075. } else {
  1076. */
  1077. /* foreach ($equiposAux as $equipo) {//"equipo" es inscrito
  1078. if (!$esEquipo) {
  1079. $indice = $equipo->getPareja();
  1080. } else {
  1081. $indice = $equipo->getEquipo();
  1082. }
  1083. if (!isset($equipos[$indice])) {
  1084. $equipos[$indice] = array();
  1085. $nombresEquipos[$indice] = $equipo->getNombreEquipo();
  1086. }
  1087. $jugador = $equipo->getJugador();
  1088. $equipos[$indice][] = array(
  1089. "idi" => $equipo->getId(),
  1090. "nombre" => $jugador->getNombre(),
  1091. "apellidos" => $jugador->getApellidos(),
  1092. "licencia" => $jugador->getLicencia(),
  1093. "nacimiento" => $jugador->getFecha(),
  1094. "hcp" => $equipo->getHcp(),
  1095. "nivel" => (!is_null($equipo->getNivel())) ? $equipo->getNivel()->getId() : "M"
  1096. );
  1097. } */
  1098. $equiposEntity = $this->em->getRepository(Equipo::class)->findEquiposParticipantesTodos($competicion);
  1099. if ($equiposEntity) {
  1100. foreach ($equiposEntity as $equipo) {
  1101. $nombresEquipos[$equipo->getEquipo()] = $equipo->getNombre();
  1102. }
  1103. }
  1104. //}
  1105. $clasificaciones[$classificationId]["equipos"] = $equipos;
  1106. break;
  1107. }
  1108. $clasificaciones[$classificationId]["posicion_corte"] = $clf->getPosicionCorte();
  1109. $clasificaciones[$classificationId]["etiqueta_corte"] = $clf->getEtiquetaCorte();
  1110. }
  1111. //13/07/2018 Jose: Se hace aqui porque no hay que calcularlo dentro de cada clasificacion
  1112. $njornadasAux = $this->em->getRepository(Clasificado::class)->getJornadasClasificacionByCompeticion($competicion);
  1113. //Busco cuantas jornadas tiene cada clasificacion, lo necesito para la cabecera de las tablas
  1114. $njornadas = array();
  1115. foreach ($njornadasAux as $nja) {
  1116. $njornadas[$nja['id']] = $nja['contador'];
  1117. }
  1118. // $zonasneutras = [];
  1119. // $bajadas = [];
  1120. // $znsAux = $this->em->getRepository(ZonaNeutra::class)->findBy([], ["tipoPrueba" => "ASC", "campoCorto" => "ASC", "son18hoyos" => "ASC", "categoria" => "ASC"]);
  1121. // foreach ($znsAux as $zn) {
  1122. // $zonasneutras[$zn->getTipoPrueba()][intval($zn->getCampoCorto())][intval($zn->getSon18hoyos())][$zn->getCategoria()->getId()] = ['max' => $zn->getPuntosMax(), 'min' => $zn->getPuntosMin(), 'subida' => $zn->getSubidaInferiorZn()];
  1123. // }
  1124. // $bajadasAux = $this->em->getRepository(Bajada::class)->findBy([], array('tipoPrueba' => 'ASC', 'campoCorto' => 'ASC', 'categoria' => 'ASC', 'puntos' => 'ASC'));
  1125. // foreach ($bajadasAux as $b) {
  1126. // $bajadas[$b->getTipoPrueba()][intval($b->getCampoCorto())][$b->getCategoria()->getId()][$b->getPuntos()] = $b->getBajada();
  1127. // }
  1128. // $categoriasHcp = $this->em->getRepository(CategoriaHandicap::class)->findAll();
  1129. return $this->render("frontend/Clasificacion/clasificacion_base.html.twig", [
  1130. 'clasificaciones' => $clasificaciones,
  1131. 'competicion' => $competicion,
  1132. 'njornadas' => $njornadas,
  1133. 'numJugadores' => $numJugadores,
  1134. 'equipos' => $equipos,
  1135. 'nombresEquipos' => $nombresEquipos,
  1136. 'tipoClasif' => $tipoClasif,
  1137. // "zonasneutras" => $zonasneutras,
  1138. // "bajadas" => $bajadas,
  1139. // "categoriasHcp" => $categoriasHcp,
  1140. ]);
  1141. }
  1142. /**
  1143. * F-037 Listado ordenado de resultados hasta un hoyo concreto
  1144. *
  1145. * @Route("/getListadoDinamicoClasificacion", name="listado_dinamico", options={"expose"=true})
  1146. *
  1147. */
  1148. public function listadoClasificacionDinamico(Request $request)
  1149. {
  1150. $id = $request->request->get("id", 0);
  1151. $token = $request->request->get("token", null);
  1152. //comprobar competicion.
  1153. $competicion = $this->em->getRepository(Competicion::class)->find($id);
  1154. if (!$competicion) {
  1155. return $this->render("frontend/Clasificacion/clasificacionListadoDinamico.html.twig", array('listado' => []));
  1156. }
  1157. if (!$this->util->checkTokenValidIframe($competicion, $token)) {
  1158. return new JsonResponse(-1);
  1159. }
  1160. $nJor = $this->em->getRepository(Jornada::class)->getCountPorCompeticion($competicion);
  1161. $clasificacionId = $request->request->get("clasificacion");
  1162. $clasificacion = $this->em->getRepository(Clasificacion::class)->find($clasificacionId);
  1163. if (is_null($clasificacion)) {
  1164. return $this->render("frontend/Clasificacion/clasificacionListadoDinamico.html.twig", array('listado' => []));
  1165. }
  1166. $orden = $request->request->get("orden", $nJor);
  1167. $jornada = $this->em->getRepository(Jornada::class)->findOneBy(array('competicion' => $competicion, 'orden' => intval($orden)));
  1168. if (!$jornada) {
  1169. return $this->render("frontend/Clasificacion/clasificacionListadoDinamico.html.twig", array('listado' => []));
  1170. }
  1171. $hoyo = $request->request->get("hoyo", 18);
  1172. $inscritos = $this->em->getRepository(Inscrito::class)->getPlayersByCompeticion($competicion);
  1173. foreach ($inscritos as $inscrito) {
  1174. $hcpJuego = unserialize($inscrito->getHcpJuego());
  1175. if (isset($hcpJuego[$jornada->getId()])) {
  1176. $hcpJuegoJornada = $hcpJuego[$jornada->getId()];
  1177. $hcpJuegoNuevaTabla = $this->em->getRepository(HcpJuego::class)->findOneBy(array('jornada' => $jornada, 'inscrito' => $inscrito));
  1178. if (is_null($hcpJuegoNuevaTabla)) {
  1179. $hcpJuegoNuevaTabla = new HcpJuego();
  1180. $hcpJuegoNuevaTabla->setHcp($hcpJuegoJornada);
  1181. $hcpJuegoNuevaTabla->setInscrito($inscrito);
  1182. $hcpJuegoNuevaTabla->setJornada($jornada);
  1183. $this->em->persist($hcpJuegoNuevaTabla);
  1184. $this->em->flush();
  1185. }
  1186. }
  1187. }
  1188. //Si es individual o si es Four Ball o Canada que se guarda también la tarjeta individual del jugador.
  1189. if ($clasificacion->getModalidad() == "individual" || $jornada->getModalidad()->getId() == "P" || $jornada->getModalidad()->getId() == "C") {
  1190. $listado = $this->em->getRepository(Resultado::class)->getListadoAcumuladoHoyos($clasificacion->getId(), $jornada, intval($hoyo), $clasificacion->getCalculo()->getId(), $competicion->getFormula()->getId());
  1191. } else {
  1192. /*
  1193. * Habria que hacer la query para clasificar individualmente a los miembros de la pareja en caso de haberse hecho una clasificacion individual de una Xsome.
  1194. */
  1195. }
  1196. return $this->render("frontend/Clasificacion/clasificacionListadoDinamico.html.twig", [
  1197. 'listado' => $listado,
  1198. 'hoyo' => $hoyo,
  1199. 'competicion' => $competicion,
  1200. 'njornadas' => $nJor,
  1201. 'clasificacion' => $clasificacion,
  1202. 'orden' => $orden
  1203. ]);
  1204. }
  1205. /**
  1206. * F-038 Listado ordenado de resultados de parejas hasta un hoyo concreto variable
  1207. *
  1208. * @Route("/getListadoDinamicoClasificacionPareja", name="listado_dinamico_pareja", options={"expose"=true})
  1209. *
  1210. */
  1211. public function listadoClasificacionDinamicoPareja(Request $request)
  1212. {
  1213. $id = $request->request->get("id");
  1214. //comprobar competicion.
  1215. $competicion = $this->em->getRepository(Competicion::class)->findOneById($id);
  1216. if (!$competicion) {
  1217. return new JsonResponse(-1);
  1218. }
  1219. $nJor = $this->em->getRepository(Jornada::class)->getCountPorCompeticion($competicion);
  1220. $numJugadores = $competicion->getJugadores();
  1221. $clasificacionId = $request->request->get("clasificacion");
  1222. $clasificacion = $this->em->getRepository(Clasificacion::class)->findOneById($clasificacionId);
  1223. if (is_null($clasificacion)) {
  1224. return new JsonResponse(-1);
  1225. }
  1226. $orden = $request->request->get("orden");
  1227. if (is_null($orden)) {
  1228. $orden = $nJor;
  1229. }
  1230. $jornada = $this->em->getRepository(Jornada::class)->findOneBy(array('competicion' => $competicion, 'orden' => intval($orden)));
  1231. if (!$jornada) {
  1232. return new JsonResponse(-1);
  1233. }
  1234. $hoyo = $request->request->get("hoyo", 18);
  1235. $inscritos = $this->em->getRepository(Inscrito::class)->getPlayersByCompeticion($competicion);
  1236. $nombresEquipos = array();
  1237. foreach ($inscritos as $inscrito) {
  1238. $hcpJuego = unserialize($inscrito->getHcpJuego());
  1239. if (isset($hcpJuego[$jornada->getId()])) {
  1240. $hcpJuegoJornada = $hcpJuego[$jornada->getId()];
  1241. $hcpJuegoNuevaTabla = $this->em->getRepository(HcpJuego::class)->findOneBy(array('jornada' => $jornada, 'inscrito' => $inscrito));
  1242. if (is_null($hcpJuegoNuevaTabla)) {
  1243. $hcpJuegoNuevaTabla = new HcpJuego();
  1244. $hcpJuegoNuevaTabla->setHcp($hcpJuegoJornada);
  1245. $hcpJuegoNuevaTabla->setInscrito($inscrito);
  1246. $hcpJuegoNuevaTabla->setJornada($jornada);
  1247. $this->em->persist($hcpJuegoNuevaTabla);
  1248. $this->em->flush();
  1249. }
  1250. }
  1251. if ($numJugadores != 2) {
  1252. if (!isset($nombresEquipos[$inscrito->getEquipo()])) {
  1253. $nombresEquipos[$inscrito->getEquipo()] = $inscrito->getNombreEquipo();
  1254. }
  1255. }
  1256. }
  1257. if ($clasificacion->getModalidad() == "pareja" || $clasificacion->getModalidad() == "equipo") {
  1258. $listado = $this->em->getRepository(Resultado::class)->getAcumuladoHoyosEquipo($clasificacion->getId(), $jornada, intval($hoyo), $clasificacion->getCalculo()->getId());
  1259. } else {
  1260. /*
  1261. * Habria que hacer la query para buscar la suma de cada miembro de la pareja.
  1262. */
  1263. }
  1264. $datosJugadores = array();
  1265. foreach ($listado as $equipo) {
  1266. $datosJugadores[$equipo["equipo"]] = $this->em->getRepository(Inscrito::class)->getDatosHcpJuegoByEquipo($equipo["equipo"], $jornada);
  1267. }
  1268. return $this->render("frontend/Clasificacion/clasificacionListadoDinamicoPareja.html.twig", array(
  1269. 'listado' => $listado,
  1270. 'datosJugadores' => $datosJugadores,
  1271. 'hoyo' => $hoyo,
  1272. 'competicion' => $competicion,
  1273. 'njornadas' => $nJor,
  1274. 'clasificacion' => $clasificacion,
  1275. 'numJugadores' => $numJugadores,
  1276. 'nombresEquipos' => $nombresEquipos,
  1277. 'orden' => $orden
  1278. ));
  1279. }
  1280. /**
  1281. * F-052 Verificacion del captcha
  1282. *
  1283. * @param type $recaptcha
  1284. * @return type
  1285. *
  1286. */
  1287. function captchaverify($recaptcha)
  1288. {
  1289. $url = "https://www.google.com/recaptcha/api/siteverify";
  1290. $ch = curl_init();
  1291. curl_setopt($ch, CURLOPT_URL, $url);
  1292. curl_setopt($ch, CURLOPT_HEADER, 0);
  1293. curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
  1294. curl_setopt($ch, CURLOPT_POST, true);
  1295. curl_setopt($ch, CURLOPT_POSTFIELDS, array(
  1296. "secret" => "6Ld1hVIUAAAAAPgO50zNtsjjVDmorOUMwMCf8J_U", "response" => $recaptcha));
  1297. $response = curl_exec($ch);
  1298. curl_close($ch);
  1299. $data = json_decode($response);
  1300. return $data->success;
  1301. }
  1302. /**
  1303. * F-060 Estadisticas de una partida tras haber sido jugada [EN DESUSO]
  1304. *
  1305. * @Route("/match/{token}/{publi}", name="_match", options={"expose"=true}, defaults={"publi" = 0})
  1306. */
  1307. public function partidaInscrito($token, $publi)
  1308. {
  1309. // TODO: COMPROBAR QUE ESTÉ EN DESUSO Y ELIMINAR O RECUPERAR EN TAL CASO
  1310. $i = 0;
  1311. $enc = false;
  1312. $partidas = $this->em->getRepository(PartidaHorario::class)->findByToken($token);
  1313. $tam = count($partidas);
  1314. while ($i < $tam && !$enc) {
  1315. $partida = $partidas[$i];
  1316. $enc = (strcmp($partida->getToken(), $token) == 0); //buscamos la partida exacta (antes habia un findoneby pero es caseinsensitive, por lo que no nos vale)
  1317. $i++;
  1318. }
  1319. if (!$enc) {
  1320. $this->addFlash('error', "No existe la partida");
  1321. return $this->redirect($this->generateUrl('competitions'));
  1322. }
  1323. $jornada = $partida->getHorario()->getJornada(); //Cuidado si horario es nulo porque no exista $partida
  1324. if (!$jornada) {
  1325. $this->addFlash('error', "No existe la Jornada");
  1326. return $this->redirect($this->generateUrl('competitions'));
  1327. }
  1328. //Deshabilitamos el filtro del softdelete, ya que como no tenemos el ID de la competicion no podemos hacer su busqueda explicita para la comprobacion,
  1329. //Al deshabilitarse la competicion va a existir, pero va a estar marcado el softdelete, por lo que si es así, avisamos de que está borrada
  1330. $this->em->getFilters()->disable('softdeleteable');
  1331. $competicion = $jornada->getCompeticion();
  1332. if (!$competicion || !is_null($competicion->getDeletedAt())) {
  1333. $this->addFlash('error', 'No se ha encontrado la competición');
  1334. return $this->redirect($this->generateUrl('competitions'));
  1335. }
  1336. $this->em->getFilters()->enable('softdeleteable');
  1337. //Si no tenemos resultados, rediigimos a la pagina de frontend
  1338. if (!$this->em->getRepository(Competicion::class)->hasResultados($competicion->getId())) {
  1339. $this->addFlash('error', 'Información de partida aún no disponible. Inténtelo más tarde');
  1340. return $this->redirect($this->generateUrl('_tournament', array('id' => $competicion->getId())));
  1341. }
  1342. $jornadaId = $jornada->getId();
  1343. $modalidad = $jornada->getModalidad()->getId();
  1344. $jugadoresAux = $this->em->getRepository(JugadorHorario::class)->findBy(['partida' => $partida->getId()], ['inscrito' => 'ASC']); //ordenamos por ID inscrito para mantener siempre el orden
  1345. $equipos = array();
  1346. $hcpJs = array();
  1347. $contrapares = array();
  1348. $resumen = array();
  1349. $valores = ["eagles" => -2, "birdies" => -1, "pares" => 0, "bogeys" => 1]; //Falta resultado Peor (> +1)
  1350. $acumulados = ["eagles" => 0, "birdies" => 0, "pares" => 0, "bogeys" => 0, "peor" => 0]; //Falta resultado Peor (> +1)
  1351. //$calculo = ($competicion->getCalculo()->getId() == "H" ? "Hcp" : "Scratch" );
  1352. //Si es medal play es susceptible de no tener los contrapares
  1353. //Por lo tanto preparamos los datos que nos hacen falta
  1354. if ($competicion->getFormula()->getId() == 'M') {
  1355. $jcs = $this->em->getRepository(JornadaConfig::class)->findByJornada($jornada);
  1356. $hoyosDatos = array();
  1357. $hoyosDatosAux = array();
  1358. foreach ($jcs as $jc) {
  1359. $jconfig_cat = $jc->getCategoria()->getId();
  1360. $cc = $this->em->getRepository(CategoriaConfig::class)->findOneByCategoria($jconfig_cat);
  1361. if ($cc->getSexo() == "" || $cc->getSexo() == "sin especificar") {
  1362. $cc->setSexo('masculino');
  1363. }
  1364. $hoyosDatosAux = $this->em->getRepository(Trazado::class)->findDatosHoyoByTrazado($jornada->getTrazado()->getNumero(), $jc->getBarra()->getId(), $cc->getSexo());
  1365. foreach ($hoyosDatosAux as $h) {
  1366. $hoyosDatos[$cc->getSexo()][$jconfig_cat][$h["numero"]] = $h;
  1367. }
  1368. }
  1369. }
  1370. if ($modalidad == "I") {
  1371. //Añadido para calculo de contrapares que no tengamos todavia de medal play.
  1372. if ($jornada->getCompeticion()->getFormula()->getId() == 'M') {
  1373. foreach ($jugadoresAux as $h) {
  1374. $insc = $h->getInscrito();
  1375. $inscId = $insc->getId();
  1376. $resultados = $this->em->getRepository(Resultado::class)->findBy(["jornada" => $jornadaId, "inscrito" => $inscId], ['hoyo' => 'ASC']);
  1377. foreach ($resultados as $r) {
  1378. if (is_null($r->getContraparScratch())) {
  1379. $par = $hoyosDatos[$insc->getJugador()->getSexo()][$insc->getCategoria()->getId()][$r->getHoyo()]["par"];
  1380. $r->setContraparScratch($r->getScratch() - $par);
  1381. $r->setContraparHcp($r->getHcp() - $par);
  1382. }
  1383. }
  1384. }
  1385. $this->em->flush();
  1386. }
  1387. foreach ($jugadoresAux as $h) {
  1388. $insc = $h->getInscrito();
  1389. $inscId = $insc->getId();
  1390. $jorConfig = $this->em->getRepository(JornadaConfig::class)->findOneBy(["jornada" => $jornadaId, "categoria" => $insc->getCategoria()]);
  1391. $tipo_hoyos = $jorConfig->getHoyos();
  1392. $limits = explode('-', $tipo_hoyos);
  1393. $esp = $this->em->getRepository(Resultado::class)->findResultadoEspecial($inscId, $jornadaId); //buscamos si tiene resultado especial para no incluirlo
  1394. if (!$esp) {
  1395. $hoyos = array_fill($limits[0], ($limits[1] - $limits[0]) + 1, true);
  1396. $hcpJs[$inscId] = $this->em->getRepository(HcpJuego::class)->findOneByInscrito($insc);
  1397. foreach ($valores as $k => $v) {
  1398. $resultados = $this->em->getRepository(Resultado::class)->findBy(["jornada" => $jornadaId, "inscrito" => $inscId, "contrapar_scratch" => $v], ['hoyo' => 'ASC']);
  1399. $valor = count($resultados);
  1400. $contrapares[$inscId][$k] = $valor;
  1401. $acumulados[$k] += $valor;
  1402. $resumen[$inscId][$k] = [];
  1403. foreach ($resultados as $resu) {
  1404. $resumen[$inscId][$k][] = $resu->getHoyo();
  1405. //eliminamos el hoyo, para saber cuales nos quedan sin usar, esos seran los resultados peores (ya que no son ni par, ni eagle, ni birdie ni bogey)
  1406. unset($hoyos[$resu->getHoyo()]);
  1407. }
  1408. }
  1409. //Lo que nos queda son los resultados peores
  1410. $peor = count($hoyos);
  1411. $contrapares[$inscId]["peor"] = $peor;
  1412. $acumulados["peor"] += $peor;
  1413. $resumen[$inscId]["peor"] = [];
  1414. foreach ($hoyos as $hoyo => $ho) {
  1415. $resumen[$inscId]["peor"][] = $hoyo;
  1416. }
  1417. $jugadores[] = $h;
  1418. }
  1419. }
  1420. } else {
  1421. //Añadido para calculo de contrapares que no tengamos todavia de medal play.
  1422. if ($jornada->getCompeticion()->getFormula()->getId() == 'M' && in_array($modalidad, ["C", "P"])) {
  1423. $teams = array();
  1424. foreach ($jugadoresAux as $h) {
  1425. $equipo = $h->getEquipo();
  1426. $pareja = $h->getPareja();
  1427. $teams[$h->getEquipo() . "-" . $h->getPareja()] = ["equipo" => $equipo, "pareja" => $pareja];
  1428. $inscritos = $this->em->getRepository(Inscrito::class)->findBy(['equipo' => $equipo, 'pareja' => $pareja, 'competicion' => $jornada->getCompeticion()->getId()], ['id' => 'ASC']);
  1429. $resultadosMiembros = array();
  1430. foreach ($inscritos as $inscrito) {
  1431. $resultados = $this->em->getRepository(Resultado::class)->findBy(["jornada" => $jornadaId, "inscrito" => $inscrito->getId()], ['hoyo' => 'ASC']);
  1432. foreach ($resultados as $r) {
  1433. if (is_null($r->getContraparScratch())) {
  1434. $par = $hoyosDatos[$inscrito->getJugador()->getSexo()][$inscrito->getCategoria()->getId()][$r->getHoyo()]["par"];
  1435. $r->setContraparScratch($r->getScratch() - $par);
  1436. $r->setContraparHcp($r->getHcp() - $par);
  1437. }
  1438. }
  1439. array_push($resultadosMiembros, $resultados);
  1440. }
  1441. $resultadosPareja = $this->em->getRepository(Resultado::class)->findBy(["jornada" => $jornadaId, 'equipo' => $equipo, 'pareja' => $pareja], ['hoyo' => 'ASC']);
  1442. foreach ($resultadosPareja as $loop => $rp) {
  1443. if (is_null($rp->getContraparScratch())) {
  1444. $m1 = $resultadosMiembros[0][$loop];
  1445. $m2 = $resultadosMiembros[1][$loop];
  1446. if ($modalidad == "C") {
  1447. $rp->setContraparScratch($m1->getContraparScratch() + $m2->getContraparScratch());
  1448. $rp->setContraparHcp($m1->getContraparHcp() + $m2->getContraparHcp());
  1449. } elseif ($modalidad == "P") {
  1450. $rp->setContraparScratch(min($m1->getContraparScratch(), $m2->getContraparScratch()));
  1451. $rp->setContraparHcp(min($m1->getContraparHcp(), $m2->getContraparHcp()));
  1452. }
  1453. }
  1454. }
  1455. }
  1456. $this->em->flush();
  1457. }
  1458. foreach ($jugadoresAux as $h) {
  1459. $equipo = $h->getEquipo();
  1460. $pareja = $h->getPareja();
  1461. $esp = $this->em->getRepository(Resultado::class)->findResultadoEspecialEquipoPareja($equipo, $pareja, $jornadaId);
  1462. if (!$esp) {
  1463. $jugadores[$equipo . "-" . $pareja] = "";
  1464. $inscritos = $this->em->getRepository(Inscrito::class)->findBy(['equipo' => $equipo, 'pareja' => $pareja, 'competicion' => $jornada->getCompeticion()->getId()], ['id' => 'ASC']);
  1465. foreach ($inscritos as $inscrito) {
  1466. $jugadores[$equipo . "-" . $pareja] .= $inscrito->getJugador()->getNombre() . " - ";
  1467. }
  1468. $jugadores[$equipo . "-" . $pareja] = substr($jugadores[$equipo . "-" . $pareja], 0, strlen($jugadores[$equipo . "-" . $pareja]) - 3);
  1469. $jorConfig = $this->em->getRepository(JornadaConfig::class)->findOneBy(["jornada" => $jornadaId, "categoria" => $inscrito->getCategoria()]);
  1470. $tipo_hoyos = $jorConfig->getHoyos();
  1471. $limits = explode('-', $tipo_hoyos);
  1472. $hcpJs[$equipo . "-" . $pareja] = $this->em->getRepository(HcpJuego::class)->findOneBy(['equipo' => $equipo, 'pareja' => $pareja, 'jornada' => $jornada->getId()]);
  1473. $equipos[$equipo . "-" . $pareja] = $this->em->getRepository(Inscrito::class)->findOneBy(['equipo' => $equipo, 'pareja' => $pareja, 'competicion' => $competicion->getId()]);
  1474. $hoyos = array_fill($limits[0], ($limits[1] - $limits[0]) + 1, true);
  1475. //Calculo de los detalles por hoyo
  1476. foreach ($valores as $k => $v) {
  1477. $resultados = $this->em->getRepository(Resultado::class)->findBy(["jornada" => $jornadaId, 'equipo' => $equipo, 'pareja' => $pareja, "contrapar_scratch" => $v], ['hoyo' => 'ASC']);
  1478. $valor = count($resultados);
  1479. $contrapares[$equipo . "-" . $pareja][$k] = $valor;
  1480. $acumulados[$k] += $valor;
  1481. $resumen[$equipo . "-" . $pareja][$k] = [];
  1482. foreach ($resultados as $resu) {
  1483. $resumen[$equipo . "-" . $pareja][$k][] = $resu->getHoyo();
  1484. //eliminamos el hoyo, para saber cuales nos quedan sin usar, esos seran los resultados peores (ya que no son ni par, ni eagle, ni birdie ni bogey)
  1485. unset($hoyos[$resu->getHoyo()]);
  1486. }
  1487. }
  1488. //Lo que nos queda son los resultados peores
  1489. $peor = count($hoyos);
  1490. $contrapares[$equipo . "-" . $pareja]["peor"] = $peor;
  1491. $acumulados["peor"] += $peor;
  1492. $resumen[$equipo . "-" . $pareja]["peor"] = [];
  1493. foreach ($hoyos as $hoyo => $ho) {
  1494. $resumen[$equipo . "-" . $pareja]["peor"][] = $hoyo;
  1495. }
  1496. }
  1497. }
  1498. }
  1499. // 2023/08/07 esto esta obsoleto a dia de hoy (deberia haberse ocultado en 2023/05/08)
  1500. // $url = $this->util->acortarUrl('_match', array('token' => $token));
  1501. return $this->render("frontend/Competicion/match.html.twig", [
  1502. 'competicion' => $competicion,
  1503. 'jugadores' => $jugadores,
  1504. 'hcpJs' => $hcpJs,
  1505. 'equipos' => $equipos,
  1506. 'ccc' => $publi,
  1507. 'contrapares' => $contrapares,
  1508. 'acumulados' => $acumulados,
  1509. 'resumen' => $resumen,
  1510. 'partida' => $partida,
  1511. // 'url' => $url,
  1512. 'modalidad' => $modalidad,
  1513. 'limits' => $limits
  1514. ]);
  1515. }
  1516. /**
  1517. * F-062
  1518. *
  1519. * @Route("/pago/{idi}/tpv/{idp}", name="pago_tpv")
  1520. */
  1521. public function tpv($idi, $idp, Request $request)
  1522. {
  1523. $params = array();
  1524. $inscrito = $this->em->getRepository(Inscrito::class)->find($idi);
  1525. if (!$inscrito) {
  1526. throw new NotFoundHttpException("No existe el inscrito");
  1527. }
  1528. $competicion = $inscrito->getCompeticion();
  1529. if (!$competicion) {
  1530. $this->addFlash(
  1531. 'error', "El torneo buscado no existe");
  1532. return $this->redirect($this->generateUrl('competiciones_abiertas'));
  1533. }
  1534. $pedido = $this->em->getRepository(Pedido::class)->find($idp);
  1535. if (!$pedido) {
  1536. //poner que redirija a competicion en un mensaje de esos flash
  1537. //y que ponga el inscrito y el pedido a "Error"
  1538. throw new NotFoundHttpException("No existe el pedido asociado a la inscripcion");
  1539. }
  1540. $secret = $this->getParameter('secret');
  1541. $redsys = new RedsysAPI();
  1542. $redsys->setParameter("DS_MERCHANT_AMOUNT", intval(number_format($pedido->getImporte() * 100, 0, "", "")));
  1543. $redsys->setParameter("DS_MERCHANT_ORDER", strval($inscrito->getPedido()->getNumero()));
  1544. $redsys->setParameter("DS_MERCHANT_CURRENCY", $this->getParameter('tpv.currency'));
  1545. $redsys->setParameter("DS_MERCHANT_TRANSACTIONTYPE", 0); //0 = Pago
  1546. /*
  1547. if (strpos($competicion->getOrganizador()->getId(), "AM") !== false) {
  1548. $usuario = $this->em->getRepository(User::class)->findOneByUsername("AM00");
  1549. } else {
  1550. $usuario = $this->em->getRepository(User::class)->findOneByUsername($competicion->getOrganizador()->getId());
  1551. }
  1552. */
  1553. $fechaTPVDesprosa = new \DateTime("2021-04-20 10:00:00"); //Desprosa es el nombre de la empresa y 20 de mayo es cuando se hizo este codigo
  1554. $fechaTPVSherry = new \DateTime("2022-03-14 00:00:00"); //Aunque el cambio se hace el dia 09/03/2022, hay competiciones abiertas hasta el dia 12, por lo que se espera a que se cierren
  1555. $fechaTPVAlhaurin = new \DateTime("2023-05-19 00:00:00"); //Peticion de la solicitud
  1556. $idComp = $competicion->getId();
  1557. //El pago, lo hace LV05 o CM81 o lo hacemos con nuestra pasarela
  1558. //IMportante!!! En la configuracion del TPV (en la web del redsys) debe de aparecer como "Asincrona"
  1559. $orgnzdr = "AM00";
  1560. switch (trim($competicion->getOrganizador()->getId())) {
  1561. case "LV05":
  1562. $orgnzdr = "LV05";
  1563. break;
  1564. case "GALN":
  1565. $orgnzdr = "GALN";
  1566. break;
  1567. case "CMC8":
  1568. $orgnzdr = "CMC8";
  1569. if ($competicion->getInicio()->format("U") < $fechaTPVDesprosa->format("U")) {
  1570. $orgnzdr = "AM00";
  1571. }
  1572. break;
  1573. case "CM81":
  1574. $orgnzdr = "CM81";
  1575. if ($competicion->getInicio()->format("U") < $fechaTPVDesprosa->format("U")) {
  1576. $orgnzdr = "AM00";
  1577. }
  1578. break;
  1579. case "AM15":
  1580. $orgnzdr = "AM15";
  1581. if ($competicion->getInicio()->format("U") < $fechaTPVDesprosa->format("U")) {
  1582. $orgnzdr = "AM00";
  1583. }
  1584. break;
  1585. case "AMC3":
  1586. $orgnzdr = "AMC3";
  1587. if ($competicion->getInicio()->format("U") < $fechaTPVSherry->format("U")) {
  1588. $orgnzdr = "AM00";
  1589. }
  1590. break;
  1591. case "AM22":
  1592. $orgnzdr = "AM22";
  1593. if ($competicion->getInicio()->format("U") < $fechaTPVAlhaurin->format("U")) {
  1594. $orgnzdr = "AM00";
  1595. }
  1596. break;
  1597. default:
  1598. $orgnzdr = "AM00";
  1599. break;
  1600. }
  1601. $usuario = $this->em->getRepository(User::class)->findOneByUsername($orgnzdr);
  1602. $usuarioTpv = $usuario->getTpv();
  1603. $merchantCode = $redsys->merchantCodeFromUser($usuarioTpv, $secret);
  1604. $terminal = $redsys->terminalFromUser($usuarioTpv, $secret);
  1605. $redsys->setParameter("DS_MERCHANT_MERCHANTCODE", $merchantCode);
  1606. $redsys->setParameter("DS_MERCHANT_TERMINAL", $terminal);
  1607. $params['Ds_Merchant_KEY_256'] = $redsys->keyFromUser($usuarioTpv, $secret); //Key de REAL del TPV correspondiente
  1608. //lineas originales
  1609. //$params['Ds_Merchant_KEY_256'] = $this->getParameter('tpv.key_test_256'); //Key de TEST.
  1610. //$params['Ds_Merchant_KEY_256'] = $this->getParameter('tpv.key_256'); //Key de REAL. Codigo antiguo
  1611. //$redsys->setParameter("DS_MERCHANT_MERCHANTCODE", $this->getParameter('tpv.merchant_code'));
  1612. //$redsys->setParameter("DS_MERCHANT_TERMINAL", $this->getParameter('tpv.terminal'));
  1613. //$dire = str_replace("https", "http", $this->generateUrl('pago_procesar', array(), UrlGeneratorInterface::ABSOLUTE_URL)); //Como el SSL de la pagina es Lets encrypt y el banco no lo admite, tenemos que hacerlo por HTTP, y no por HTTPS para evitar errores
  1614. $dire = $this->generateUrl('pago_procesar', array(), UrlGeneratorInterface::ABSOLUTE_URL);
  1615. $redsys->setParameter("DS_MERCHANT_MERCHANTURL", $dire); //URL de mi pagina para procesar el pago
  1616. //$redsys->setParameter("DS_MERCHANT_MERCHANTURL", $this->generateUrl('pago_procesar', array(), UrlGeneratorInterface::ABSOLUTE_URL)); //URL de mi pagina para procesar el pago
  1617. $idInsc = ($competicion->getJugadores() == 1) ? $inscrito->getId() : 0;
  1618. $paymentReturnParameters = array('id' => $idComp, 'idi' => $idInsc);
  1619. if ((string) $request->query->get('fromapp', '') === '1') {
  1620. $paymentReturnParameters['fromapp'] = 1;
  1621. }
  1622. $redsys->setParameter("DS_MERCHANT_URLOK", $this->generateUrl('pago_terminado', array_merge($paymentReturnParameters, array('token' => 'success')), UrlGeneratorInterface::ABSOLUTE_URL));
  1623. $redsys->setParameter("DS_MERCHANT_URLKO", $this->generateUrl('pago_terminado', array_merge($paymentReturnParameters, array('token' => 'fail')), UrlGeneratorInterface::ABSOLUTE_URL));
  1624. $redsys->setParameter("DS_MERCHANT_PAYMETHODS", "C"); //solo pago con tarjeta
  1625. $redsys->setParameter("DS_MERCHANT_MERCHANTNAME", $this->getParameter('tpv.merchant_name'));
  1626. $redsys->setParameter("DS_MERCHANT_MERCHANTDATA", base64_encode(json_encode(array('idi' => $idi, 'idp' => $idp))));
  1627. $params['Ds_Merchant_URL_Pago'] = $this->getParameter('tpv.url');
  1628. $params['Ds_SignatureVersion'] = $this->getParameter('tpv.version'); //Version SHA256 --> esto no se usa
  1629. $params['Ds_MerchantParameters'] = $redsys->createMerchantParameters(); //Parametros, una vez codificados
  1630. $params['Ds_Signature'] = $redsys->createMerchantSignature($params['Ds_Merchant_KEY_256']); //Firma de SHA256
  1631. return $this->render('frontend/Default/tpv.html.twig', $params);
  1632. }
  1633. /**
  1634. * F-063 Genera el formulario de devolución del banco
  1635. *
  1636. * @Route("/devolucion/{idi}/tpv/{idp}", name="devolucion_tpv")
  1637. */
  1638. public function tpvDevolucion($idi, $idp, RefundTpvResolver $refundTpvResolver)
  1639. {
  1640. $params = array();
  1641. $inscrito = $this->em->getRepository(Inscrito::class)->find($idi);
  1642. if (!$inscrito) {
  1643. throw new NotFoundHttpException("No existe el inscrito");
  1644. }
  1645. $competicion = $inscrito->getCompeticion();
  1646. if (!$competicion) {
  1647. $this->addFlash(
  1648. 'error', "El torneo buscado no existe");
  1649. return $this->redirect($this->generateUrl('competiciones_abiertas'));
  1650. }
  1651. $pedido = $this->em->getRepository(Pedido::class)->find($idp);
  1652. if (!$pedido) {
  1653. //poner que redirija a competicion en un mensaje de esos flash
  1654. //y que ponga el inscrito y el pedido a "Error"
  1655. throw new NotFoundHttpException("No existe el pedido asociado a la inscripcion");
  1656. }
  1657. if ($inscrito->getPedido()?->getId() !== $pedido->getId()) {
  1658. throw new NotFoundHttpException('El pedido no pertenece a la inscripción.');
  1659. }
  1660. if ($pedido->isFullyRefunded()) {
  1661. return $this->render('frontend/Default/tpv.html.twig', [
  1662. 'alreadyRefunded' => true,
  1663. 'message' => 'El pedido ya se ha devuelto. No se ha realizado ninguna devolución adicional.',
  1664. ]);
  1665. }
  1666. if ($competicion->getEstado() !== 'abierta' || $competicion->getModo()->getId() < 3) {
  1667. throw new BadRequestHttpException('La cancelación online no está disponible para esta competición.');
  1668. }
  1669. // Historical cancellations stored their intended refund state before
  1670. // receiving the bank result. Keep their existing recovery link usable.
  1671. $legacyPendingCancellation = in_array($pedido->getEstado(), ['devolucion', 'anulado'], true)
  1672. && null !== $pedido->getPayedAt()
  1673. && in_array($inscrito->getEstado(), ['devolucion', 'anulado'], true)
  1674. && $inscrito->getParticipa() == 0;
  1675. if (null !== $pedido->getReturnedAt()
  1676. || ($pedido->getEstado() !== 'pagado' && !$legacyPendingCancellation)
  1677. || $pedido->getConcepto() !== 'ionline'
  1678. || !preg_match('/^\d+(?:\.\d{1,2})?$/', (string) $pedido->getImporte())
  1679. || (float) $pedido->getImporte() <= 0) {
  1680. throw new BadRequestHttpException('El pedido no tiene un saldo cobrado pendiente de devolución.');
  1681. }
  1682. if ($this->em->getRepository(TransaccionRedsys::class)->findPendingRefundByPedido($pedido)) {
  1683. throw new BadRequestHttpException('Hay una devolución pendiente de confirmar. Revise su resultado antes de repetirla.');
  1684. }
  1685. $secret = $this->getParameter('secret');
  1686. $importeDev = intval(number_format($pedido->getImporte() * 100, 0, "", ""));
  1687. $redsys = new RedsysAPI();
  1688. $redsys->setParameter("DS_MERCHANT_AMOUNT", $importeDev);
  1689. $redsys->setParameter("DS_MERCHANT_ORDER", $this->util->reformatPedido($pedido));
  1690. $redsys->setParameter("DS_MERCHANT_CURRENCY", $this->getParameter('tpv.currency'));
  1691. $redsys->setParameter("DS_MERCHANT_TRANSACTIONTYPE", 3); //3 = Devolucion
  1692. $idComp = $competicion->getId();
  1693. $usuarioTpv = $refundTpvResolver->resolve($competicion);
  1694. if (null === $usuarioTpv) {
  1695. throw new NotFoundHttpException('No existe el TPV asociado a la devolución.');
  1696. }
  1697. $redsys->setParameter("DS_MERCHANT_MERCHANTCODE", $redsys->merchantCodeFromUser($usuarioTpv, $secret));
  1698. $redsys->setParameter("DS_MERCHANT_TERMINAL", $redsys->terminalFromUser($usuarioTpv, $secret));
  1699. $params['Ds_Merchant_KEY_256'] = $redsys->keyFromUser($usuarioTpv, $secret); //Key de REAL del TPV correspondiente
  1700. //lineas originales
  1701. //$redsys->setParameter("DS_MERCHANT_MERCHANTCODE", $this->getParameter('tpv.merchant_code'));
  1702. //$redsys->setParameter("DS_MERCHANT_TERMINAL", $this->getParameter('tpv.terminal'));
  1703. //$dire = str_replace("https", "http", $this->generateUrl('competicion_cancelainscrito', array('id' => $idComp, 'pedido' => $idp), UrlGeneratorInterface::ABSOLUTE_URL)); //Como el SSL de la pagina es Lets encrypt y el banco no lo admite, tenemos que hacerlo por HTTP, y no por HTTPS para evitar errores
  1704. $dire = $this->generateUrl('competicion_cancelainscrito', array('id' => $idComp, 'pedido' => $idp), UrlGeneratorInterface::ABSOLUTE_URL);
  1705. $redsys->setParameter("DS_MERCHANT_MERCHANTURL", $dire); //URL de mi pagina para procesar el pago
  1706. //$redsys->setParameter("DS_MERCHANT_MERCHANTURL", $this->generateUrl('pago_procesar', array(), UrlGeneratorInterface::ABSOLUTE_URL)); //URL de mi pagina para procesar el pago
  1707. $idInsc = ($competicion->getJugadores() == 1) ? $inscrito->getId() : 0;
  1708. $redsys->setParameter("DS_MERCHANT_URLOK", $this->generateUrl('pago_terminado', array('token' => 'cancel', 'id' => $idComp, 'idi' => $idInsc), UrlGeneratorInterface::ABSOLUTE_URL));
  1709. $redsys->setParameter("DS_MERCHANT_URLKO", $this->generateUrl('pago_terminado', array('token' => 'fail', 'id' => $idComp, 'idi' => $idInsc), UrlGeneratorInterface::ABSOLUTE_URL));
  1710. $redsys->setParameter("DS_MERCHANT_PAYMETHODS", "C"); //solo pago con tarjeta
  1711. $redsys->setParameter("DS_MERCHANT_MERCHANTNAME", $this->getParameter('tpv.merchant_name'));
  1712. $redsys->setParameter("DS_MERCHANT_MERCHANTDATA", base64_encode(json_encode(array('idi' => $idi, 'idp' => $idp))));
  1713. //$params['Ds_Merchant_KEY_256'] = $this->getParameter('tpv.key_test_256'); //Key de TEST.
  1714. //$params['Ds_Merchant_KEY_256'] = $this->getParameter('tpv.key_256'); //Key de REAL. Codigo antiguo
  1715. //$params['Ds_Merchant_URL_Pago'] = $this->getParameter('tpv.url_test'); //Direccion de TEST
  1716. $params['Ds_Merchant_URL_Pago'] = $this->getParameter('tpv.url'); //Direccion REAL
  1717. $params['Ds_SignatureVersion'] = $this->getParameter('tpv.version'); //Version SHA256 --> esto no se usa
  1718. $params['Ds_MerchantParameters'] = $redsys->createMerchantParameters(); //Parametros, una vez codificados
  1719. $params['Ds_Signature'] = $redsys->createMerchantSignature($params['Ds_Merchant_KEY_256']); //Firma de SHA256
  1720. return $this->render('frontend/Default/tpv.html.twig', $params);
  1721. }
  1722. /**
  1723. * F-064 Landing de retorno al pago en el banco
  1724. *
  1725. * @Route("/pago/{idi}/intermedio/{idp}", name="pago_intermedio")
  1726. */
  1727. public function pagoIntermedio($idi, $idp)
  1728. {
  1729. $inscrito = $this->em->getRepository(Inscrito::class)->find($idi);
  1730. if (!$inscrito) {
  1731. throw new NotFoundHttpException("No existe el inscrito");
  1732. }
  1733. $pedido = $this->em->getRepository(Pedido::class)->find($idp);
  1734. if (!$pedido) {
  1735. //poner que redirija a competicion en un mensaje de esos flash
  1736. //y que ponga el inscrito y el pedido a "Error"
  1737. throw new NotFoundHttpException("No existe el pedido asociado a la inscripcion");
  1738. }
  1739. return $this->render("frontend/Default/pagoIntermedio.html.twig", [
  1740. 'inscrito' => $inscrito,
  1741. 'pedido' => $pedido
  1742. ]);
  1743. }
  1744. /**
  1745. * F-065 Landing de retorno al pago en el banco
  1746. *
  1747. * @Route("/pago-terminado/{token}/{id}/{idi}", name="pago_terminado", defaults={"idi" = 0})
  1748. */
  1749. public function pagoTerminado($token, $id, $idi, UtilJugadores $util_jugadores)
  1750. {
  1751. $competicion = $this->em->getRepository(Competicion::class)->find($id);
  1752. if (!$competicion) {
  1753. $this->addFlash(
  1754. 'error', "El torneo buscado no existe");
  1755. return $this->redirect($this->generateUrl('_tournament', array('id' => $id)));
  1756. }
  1757. $params = [
  1758. 'token' => $token,
  1759. 'id' => $id,
  1760. 'idj' => null,
  1761. ];
  1762. if ($idi != 0) {
  1763. $inscrito = $this->em->getRepository(Inscrito::class)->find($idi);
  1764. if (!empty($inscrito) && ($token == "success")) {
  1765. $jugador = $inscrito->getJugador();
  1766. $cl = $competicion->getOrganizador()->getCliente();
  1767. $telefono = $util_jugadores->getDatoPlanoDesdeJugador($jugador, "Telefono", $cl); //
  1768. if (empty($telefono)) {
  1769. $params["idj"] = $jugador->getId();
  1770. }
  1771. }
  1772. }
  1773. /*
  1774. $tarifa = $this->em->getRepository(Tarifa::class)->find($idt);
  1775. if (!$tarifa) {
  1776. //poner que redirija a competicion en un mensaje de esos flash
  1777. //y que ponga el inscrito y el pedido a "Error"
  1778. throw new NotFoundHttpException("No existe la tarifa");
  1779. }
  1780. */
  1781. return $this->render("frontend/Default/pagoTerminado.html.twig", $params);
  1782. }
  1783. /**
  1784. * F-066 Procesamiento del pago tras aviso del banco
  1785. *
  1786. * @Route("/pago-procesar", name="pago_procesar")
  1787. *
  1788. */
  1789. public function pagoProcesar(Request $request, EnvioCorreo $mailer, NotificacionesService $notificator, EnvioSms $messaging, UtilJugadores $util_jugadores, SoftwareExternoUtil $swutil, PreferredLicenseClubChecker $preferredLicenseClubChecker, SendInscriptionPhoneNotificationService $sendInscriptionPhoneNotification, ProcessRefundNotification $processRefundNotification, ValidatePaymentNotification $validatePaymentNotification)
  1790. {
  1791. $payload = $request->request->all();
  1792. $Ds_MerchantParameters = $payload['Ds_MerchantParameters'] ?? null;
  1793. if (!is_string($Ds_MerchantParameters) || '' === $Ds_MerchantParameters) {
  1794. return new JsonResponse([], 400);
  1795. }
  1796. $decodec = base64_decode(strtr($Ds_MerchantParameters, '-_', '+/'), true);
  1797. $fields = false === $decodec ? null : json_decode($decodec, true);
  1798. if (!is_array($fields) || !is_string($fields['Ds_MerchantData'] ?? null)) {
  1799. return new JsonResponse([], 400);
  1800. }
  1801. foreach (['Ds_Order', 'Ds_Response', 'Ds_TransactionType'] as $field) {
  1802. if (!isset($fields[$field]) || (!is_string($fields[$field]) && !is_int($fields[$field])) || '' === (string) $fields[$field]) {
  1803. return new JsonResponse([], 400);
  1804. }
  1805. }
  1806. foreach (['Ds_Amount', 'Ds_MerchantCode', 'Ds_Terminal', 'Ds_Currency'] as $field) {
  1807. if (array_key_exists($field, $fields) && !is_string($fields[$field]) && !is_int($fields[$field])) {
  1808. return new JsonResponse([], 400);
  1809. }
  1810. }
  1811. $merchantData = base64_decode(strtr($fields['Ds_MerchantData'], '-_', '+/'), true);
  1812. $other_fields = false === $merchantData ? null : json_decode($merchantData, true);
  1813. if (!is_array($other_fields)) {
  1814. return new JsonResponse([], 400);
  1815. }
  1816. foreach (['idi', 'idp'] as $idField) {
  1817. $id = $other_fields[$idField] ?? null;
  1818. if ((!is_int($id) && !is_string($id)) || !preg_match('/^[1-9]\d*$/', (string) $id)
  1819. || false === filter_var($id, FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]])) {
  1820. return new JsonResponse([], 400);
  1821. }
  1822. }
  1823. $inscritos = array();
  1824. $jugadores = array();
  1825. $secret = $this->getParameter('secret');
  1826. $inscrito = $this->em->getRepository(Inscrito::class)->find($other_fields['idi']);
  1827. if (!$inscrito) {
  1828. return new JsonResponse([]);
  1829. }
  1830. $pedido = $this->em->getRepository(Pedido::class)->find($other_fields['idp']);
  1831. if (!$pedido) {
  1832. return new JsonResponse([]);
  1833. }
  1834. $refundNotification = '3' === (string) $fields['Ds_TransactionType'];
  1835. $refundReference = $other_fields['refund_reference'] ?? null;
  1836. // Redsys also documents type 2 in its synchronous refund response.
  1837. // Only an existing refund attempt can correlate that ambiguous type.
  1838. if ('2' === (string) $fields['Ds_TransactionType']
  1839. && is_string($refundReference) && preg_match('/^[a-f0-9]{32}$/', $refundReference)) {
  1840. $trackedRefund = $this->em->getRepository(TransaccionRedsys::class)
  1841. ->findRefundByReference((string) $fields['Ds_Order'], $fields['Ds_MerchantData']);
  1842. $refundNotification = null !== $trackedRefund;
  1843. }
  1844. if ($refundNotification) {
  1845. return $processRefundNotification($request, $fields, $inscrito, $pedido, $secret, $swutil);
  1846. }
  1847. if (!$validatePaymentNotification($request, $fields, $inscrito, $pedido)) {
  1848. return new JsonResponse([], 400);
  1849. }
  1850. $competicion = $inscrito->getCompeticion();
  1851. $num_inscritos = $this->em->getRepository(Inscrito::class)->getCountInscritosByEstadoCorrecto($competicion->getId(), false, ["pagado"]);
  1852. $lista_espera = (($num_inscritos >= $competicion->getPlazas()) && $competicion->getListaEspera());
  1853. //Permitimos que se terminen de inscribir aquellos, que aun habiendo acbado el plazo, la competicion sigue abierta a la espera de que la tarea la ponga en "finalizada"
  1854. if (($competicion->getModo()->getId() != 3) && ($competicion->getEstado() != "abierta")) {
  1855. //Mandamos correo a soporte para avisar
  1856. $args = [
  1857. "to" => $this->getParameter('next.email.rfga'),
  1858. "bcc" => false,
  1859. "competicion" => $competicion,
  1860. "subject" => '⛳ NEXTCADDY - Inscripción AL LÍMITE [' . $pedido->getNumero() . ']',
  1861. "html" => $this->renderView('frontend/Inscritos/emailInscripcionLimite.html.twig', array('jugador' => $inscrito->getJugador(),
  1862. 'inscrito' => $inscrito,
  1863. 'competicion' => $competicion,
  1864. 'pedido' => $pedido,
  1865. 'tarifa' => $pedido->getTarifa()
  1866. ))
  1867. ];
  1868. //EnvioCorreo::enviarCorreo($args);
  1869. $mailer->enviarCorreo($args);
  1870. return new JsonResponse([]);
  1871. }
  1872. //SWGOLF
  1873. //$gmutil = new GolfmanagerUtilidad();
  1874. $swbd = $this->em->getRepository(SoftwareGolf::class)->findOneBy(["innerClass" => "Club", "cliente" => $competicion->getOrganizador()->getCliente(), "clubId" => $competicion->getClub()->getId()]);
  1875. if ($swbd) {
  1876. $swutil->init($swbd);
  1877. }
  1878. if (in_array($inscrito->getEstado(), ["espera", "error"]) && in_array($pedido->getEstado(), ["espera", "error"])) {
  1879. $avisar = false;
  1880. if ($fields['Ds_Order'] == $pedido->getNumero()) {
  1881. if (intval($fields['Ds_Response']) < 100) {
  1882. $estado = "pagado";
  1883. $avisar = true;
  1884. /*
  1885. } else if (intval($fields['Ds_Response']) == 900) {
  1886. $estado = "devolucion";
  1887. $avisar = false;
  1888. *
  1889. */
  1890. $pedido->setPayedAt(new \DateTime('now'));
  1891. } else {
  1892. $pedido->setCodigoError($fields['Ds_Response']);
  1893. $estado = "error";
  1894. $avisar = false;
  1895. }
  1896. //04/03/20 Subimos el pedido set estado aqui porque sospechamos que el guardaCsv ha podido dar error, para que el pedido e quede en "pagado"/"error" para evitar que la tarea que busca los "en espera" lo limpie.
  1897. $pedido->setEstado($estado);
  1898. $pedido->setUpdatedAt(new \DateTime('now'));
  1899. //buscamos todos los inscritos que tienen el mismo pedido para cambiarle el estado
  1900. $inscritos = $this->em->getRepository(Inscrito::class)->findBy(array('pedido' => $pedido->getId()));
  1901. foreach ($inscritos as $ins) {
  1902. $ins->setEstado($estado);
  1903. $participateValue = $lista_espera ? -1 : 1;
  1904. if ($competicion->getListaEspera() && $competicion->getRestringirLicencia() === EnumEstadoRestringirLicencias::PREFERENCIA) {
  1905. $belongsToPreferredClub = $preferredLicenseClubChecker->belongsToPreferredClub($ins->getLicencia(), $competicion);
  1906. if (!$belongsToPreferredClub) {
  1907. $participateValue = -1;
  1908. }
  1909. }
  1910. $ins->setParticipa($participateValue);
  1911. $ins->setUpdatedAt(new \DateTime('now'));
  1912. $jugador = $ins->getJugador();
  1913. $log_message = "Inscripción online en Competicion " . $competicion->getNombre() . "(" . $competicion->getId() . "): " . $jugador->getLicencia() . " - " . $estado . " - (" . $pedido->getNumero() . ")";
  1914. $log = new Log('i', $log_message, null);
  1915. $this->em->persist($log);
  1916. $this->em->flush();
  1917. try {
  1918. $this->util->guardaCsvInscripciones($ins);
  1919. } catch (\Throwable $ex) {
  1920. $log_message = "Error guardaCsvInscripciones inscripcion online en Competicion " . $competicion->getNombre() . "(" . $competicion->getId() . "): " . $jugador->getLicencia() . " - " . $estado . " - (" . $pedido->getNumero() . ")";
  1921. $log = new Log('i', $log_message, null);
  1922. $this->em->persist($log);
  1923. $this->em->flush();
  1924. }
  1925. //Pablo 22/02/2024: Borramos esta condicion, me da igual el softwaregolf que tengamos que ha de ejecutarse la funcion de agregar,
  1926. // como es de pago avisamos aqui al proveedor (pago formalziado)
  1927. if ($swbd) {
  1928. $swutil->addClientToActivity($inscrito, $this->em, true);
  1929. }
  1930. }
  1931. $this->em->flush();
  1932. }
  1933. //Separado, para eviar que falle y deje a la mitad la inscripcion, sino iria arriba. De esta manera nos aseguramos que
  1934. if ($avisar) {
  1935. $cl = $competicion->getOrganizador()->getCliente();
  1936. foreach ($inscritos as $ins) {
  1937. $jugador = $ins->getJugador();
  1938. //Preparación y envio del SMS
  1939. $privacidad = $ins->getJugador()->getPrivacidadSimple();
  1940. $rgpd = false;
  1941. if (strpos($competicion->getOrganizador()->getId(), "AM") !== false) { //si organiza alguien de la RFGA, buscamos la privacidad de RFGA
  1942. if (isset($privacidad["AM00"]) && $privacidad["AM00"]) {
  1943. $rgpd = true;
  1944. }
  1945. } else {//buscamos la privacidad del organizador
  1946. if ((isset($privacidad[$competicion->getOrganizador()->getId()]) && $privacidad[$competicion->getOrganizador()->getId()]) || (isset($privacidad["AM00"]) && $privacidad["AM00"])) {
  1947. $rgpd = true;
  1948. }
  1949. }
  1950. $telefono = $util_jugadores->getDatoPlanoDesdeJugador($jugador, "Telefono", $cl);
  1951. if ($rgpd && !empty($telefono)) {
  1952. $userApp = $this->em->getRepository(UserApp::class)->findOneByTelefono($telefono);
  1953. //if (!$userApp) {
  1954. $api = $cl?->getId() > 2;
  1955. $notificationData = $sendInscriptionPhoneNotification($ins, $telefono, 2, $api);
  1956. $texto = $notificationData['text'];
  1957. $url = $notificationData['variables']['url'];
  1958. //} else {
  1959. $args = [];
  1960. $args["title"] = "Nueva inscripción en torneo";
  1961. $args["msg"] = $texto;
  1962. $args["url"] = $url;
  1963. $args["destinatario"] = $userApp;
  1964. $args["tipo"] = "new-inscription";
  1965. $args["competicion"] = $competicion->getId();
  1966. $notificator->enviarNotificacion($args);
  1967. //}
  1968. }
  1969. $jugadores[] = $jugador;
  1970. }
  1971. //$email = $pedido->getEmail();
  1972. $email = $pedido->getEmailCodDecod($secret);
  1973. if (count($jugadores) == 1) {
  1974. $html = $this->renderView('frontend/Inscritos/emailInscripcion.html.twig', array('jugador' => $jugador,
  1975. 'competicion' => $competicion,
  1976. 'pedido' => $pedido,
  1977. 'inscrito' => $inscrito,
  1978. 'barras' => $this->em->getRepository(JornadaConfig::class)->findByInscrito($inscrito),
  1979. 'tarifa' => $pedido->getTarifa(),
  1980. 'lista_espera' => $lista_espera
  1981. ));
  1982. /* $email_send->addTo($email)
  1983. ->setBcc($this->getParameter('next.email.rfga'))
  1984. ->setFrom('mailing@nextcaddy.com')
  1985. ->setSubject('⛳ NextCaddy - Inscripción online [' . $pedido->getNumero() . ']')
  1986. ->setHtml($this->renderView('frontend/Inscritos/emailInscripcion.html.twig', array('jugador' => $jugador,
  1987. 'competicion' => $competicion,
  1988. 'pedido' => $pedido,
  1989. 'tarifa' => $pedido->getTarifa()
  1990. ))
  1991. ); */
  1992. } else {
  1993. $html = $this->renderView('frontend/Inscritos/emailInscripcionPareja.html.twig', array('jugadores' => $jugadores,
  1994. 'competicion' => $competicion,
  1995. 'inscritos' => $inscritos,
  1996. 'pedido' => $pedido,
  1997. 'tarifas' => $pedido->getImporte() . "€",
  1998. 'lista_espera' => $lista_espera
  1999. ));
  2000. }
  2001. /* $organizador = (substr($competicion->getOrganizador()->getId(), 0, 2) == "AM") ? "AM00" : $competicion->getOrganizador()->getId();
  2002. $userSendgrid = $this->em->getRepository(User::class)->findOneByUsername($organizador);
  2003. $sendgridKey = $userSendgrid->getSocialRed($this->getParameter('secret'), "sendgrid");
  2004. $sendgrid = new \SendGrid($sendgridKey["api_key"]); //segun usuario
  2005. if ($_SERVER['SERVER_NAME'] != 'localhost') {
  2006. $sendgrid->send($email_send); } */
  2007. $args = [
  2008. "to" => $email,
  2009. "competicion" => $competicion,
  2010. "subject" => '⛳ NEXTCADDY - Inscripción online [' . $pedido->getNumero() . ']',
  2011. "html" => $html
  2012. ];
  2013. //EnvioCorreo::enviarCorreo($args);
  2014. $mailer->enviarCorreo($args);
  2015. }
  2016. }
  2017. return new JsonResponse([]);
  2018. }
  2019. /**
  2020. * Muestra los encuentros de resultados para competiciones Ryder Cup.
  2021. *
  2022. * @Route("/getListadoResultados", name="listado_resultados", options={"expose"=true})
  2023. */
  2024. public function listadoResultados(Request $request): JsonResponse|Response
  2025. {
  2026. $competitionId = (int)$request->request->get("id", 0);
  2027. $token = $request->request->get("token", null);
  2028. $competition = $this->em->getRepository(Competicion::class)->find($competitionId);
  2029. if (!$competition) {
  2030. return new JsonResponse(-1);
  2031. }
  2032. if (!$this->util->checkTokenValidIframe($competition, $token)) {
  2033. return new JsonResponse(-1);
  2034. }
  2035. if ($competition->getFormula()?->getId() !== 'R') {
  2036. return $this->render('frontend/Competicion/components/results_ryder.html.twig', [
  2037. 'results' => ['teams' => [], 'rounds' => [], 'matches' => []],
  2038. 'mode' => 'results',
  2039. ]);
  2040. }
  2041. return $this->render('frontend/Competicion/components/results_ryder.html.twig', [
  2042. 'results' => $this->ryderCupResultsData->__invoke($competition),
  2043. 'mode' => 'results',
  2044. ]);
  2045. }
  2046. /**
  2047. * Muestra los enfrentamientos definidos para competiciones Ryder Cup.
  2048. *
  2049. * @Route("/getListadoEnfrentamientos", name="listado_enfrentamientos", options={"expose"=true})
  2050. */
  2051. public function listadoEnfrentamientos(Request $request): JsonResponse|Response
  2052. {
  2053. $competitionId = (int)$request->request->get("id", 0);
  2054. $token = $request->request->get("token", null);
  2055. $competition = $this->em->getRepository(Competicion::class)->find($competitionId);
  2056. if (!$competition) {
  2057. return new JsonResponse(-1);
  2058. }
  2059. if (!$this->util->checkTokenValidIframe($competition, $token)) {
  2060. return new JsonResponse(-1);
  2061. }
  2062. if ($competition->getFormula()?->getId() !== 'R') {
  2063. return $this->render('frontend/Competicion/components/results_ryder.html.twig', [
  2064. 'results' => ['teams' => [], 'rounds' => [], 'matches' => []],
  2065. 'mode' => 'fixtures',
  2066. ]);
  2067. }
  2068. return $this->render('frontend/Competicion/components/results_ryder.html.twig', [
  2069. 'results' => $this->ryderCupResultsData->buildFixtures($competition),
  2070. 'mode' => 'fixtures',
  2071. ]);
  2072. }
  2073. /**
  2074. * F-067 Muestra un listado con los cambios de handicap tras el torneo
  2075. *
  2076. * @Route("/getListadoCambiosHandicap", name="listado_cambios_handicap", options={"expose"=true})
  2077. *
  2078. */
  2079. public function listadoCambiosHandicap(Request $request)
  2080. {
  2081. $id = $request->request->get("id");
  2082. //comprobar competicion.
  2083. $competicion = $this->em->getRepository(Competicion::class)->findOneById($id);
  2084. if (!$competicion) {
  2085. return new JsonResponse(-1);
  2086. }
  2087. $diferencias = array();
  2088. $inscritos = array();
  2089. $inscritosAux = $this->em->getRepository(Inscrito::class)->getHandicapsSms($id);
  2090. foreach ($inscritosAux as $inscrito) {
  2091. $idi = $inscrito->getId();
  2092. $handicaps = unserialize($inscrito->getHcpSms());
  2093. $long = count($handicaps);
  2094. $cambio = 0;
  2095. for ($i = 1; $i <= $long; $i++) {
  2096. if ($i != 1) {
  2097. $diferencias[$i] = number_format($handicaps[$i], 1) - number_format($handicaps[$i - 1], 1);
  2098. $cambio += $diferencias[$i];
  2099. } else {
  2100. $diferencias[$i] = number_format($handicaps[$i], 1) - $inscrito->getHcp();
  2101. $cambio += $diferencias[$i];
  2102. }
  2103. }
  2104. $inscritos[$idi] = [
  2105. "nombre" => $inscrito->getJugador()->getNombre(),
  2106. "apellidos" => $inscrito->getJugador()->getApellidos(),
  2107. "licencia" => $inscrito->getJugador()->getLicencia(),
  2108. "hcp" => $inscrito->getHcp(),
  2109. "handicaps" => $handicaps,
  2110. "cambio" => $cambio,
  2111. "diferencias" => $diferencias
  2112. ];
  2113. }
  2114. $cmp = function ($a, $b) {
  2115. $a1 = number_format($a["cambio"], 1);
  2116. $b1 = number_format($b["cambio"], 1);
  2117. if ($a1 == $b1) {
  2118. if (number_format($a["hcp"]) == number_format($b["hcp"])) {
  2119. return 0;
  2120. }
  2121. return (number_format($a["hcp"]) < number_format($b["hcp"])) ? -1 : 1;
  2122. }
  2123. return ($a1 < $b1) ? -1 : 1;
  2124. };
  2125. //ordenamos
  2126. usort($inscritos, $cmp);
  2127. return $this->render("frontend/Inscritos/listado_cambio_handicap.html.twig", [
  2128. 'competicion' => $competicion,
  2129. 'inscritos' => $inscritos
  2130. ]);
  2131. }
  2132. /**
  2133. * F-068 Devuelve las estadisticas de una competicion
  2134. *
  2135. * @Route("/getListadoEstadisticas", name="listado_estadisticas", options={"expose"=true})
  2136. *
  2137. */
  2138. public function listadoEstadisticas(Request $request)
  2139. {
  2140. //$isAjax = $request->isXMLHttpRequest();
  2141. //if ($isAjax) {
  2142. $response = new JsonResponse();
  2143. //comprobar que hay Puntuaciones publicadas.
  2144. $competicion = $request->get("id");
  2145. $estadisticas = $this->em->getRepository(Estadisticas::class)->findBy(array('competicion' => $competicion));
  2146. if ($estadisticas) {
  2147. $arDatos = array();
  2148. foreach ($estadisticas as $data) {
  2149. if (!isset($arDatos[$data->getJornada()])) {
  2150. $arDatos[$data->getJornada()] = array();
  2151. }
  2152. $arDatos[$data->getJornada()][$data->getTipo()] = array("id" => $data->getId(), "datos" => $data->getDatos());
  2153. }
  2154. $response->setData($arDatos);
  2155. } else {
  2156. $response->setData("No data");
  2157. }
  2158. return $response;
  2159. //} else {
  2160. // return new Response('This is not ajax!', 400);
  2161. //}
  2162. }
  2163. /**
  2164. * F-069 Muestra las estadisticas de una competicion
  2165. *
  2166. * @Route("/renderStats", name="_ajRenderStats", options={"expose"=true})
  2167. *
  2168. */
  2169. public function renderEstadistica(Request $request)
  2170. {
  2171. $isAjax = $request->isXMLHttpRequest();
  2172. $response = new JsonResponse();
  2173. $competicion = $request->get("id");
  2174. if ($isAjax) {
  2175. $datos = array();
  2176. $fechas = array(0 => ""); //primer elemento ficticio para el total
  2177. //comprobar que hay Puntuaciones publicadas.
  2178. $estadisticas = $this->em->getRepository(Estadisticas::class)->findBy(array('competicion' => $competicion), array("jornada" => "ASC"));
  2179. if (!$estadisticas) {
  2180. $response->setData("No data");
  2181. } else {
  2182. foreach ($estadisticas as $data) {
  2183. if (!isset($datos[$data->getJornada()])) {
  2184. $datos[$data->getJornada()] = array();
  2185. $jornada = $this->em->getRepository(Jornada::class)->findOneBy(array('competicion' => $competicion, "orden" => $data->getJornada()));
  2186. if ($jornada) {
  2187. $fechas[$data->getJornada()] = $jornada->getFecha();
  2188. }
  2189. }
  2190. $datos[$data->getJornada()][$data->getTipo()] = array('id' => $data->getId(), 'datos' => $data->getDatos());
  2191. }
  2192. }
  2193. return $this->render('frontend/Estadisticas/index.html.twig', array("datos" => $datos, "fechas" => $fechas));
  2194. } else {
  2195. return new Response('This is not ajax!', 400);
  2196. }
  2197. }
  2198. /**
  2199. * F-070 Pagina de bienvenida a jugadores
  2200. *
  2201. * @Route("/bienvenido/{lic}", name="bienvenido_nextcaddy")
  2202. */
  2203. public function bienvenido($lic)
  2204. {
  2205. $inicialFed = substr(trim($lic), 0, 2);
  2206. $jugador = $this->em->getRepository(Jugador::class)->findOneBy(array('habilitado' => 1, 'licencia_corta' => substr($lic, -6)));
  2207. if (!$jugador) {
  2208. //creamos un jugador por defecto si no existe, para que vaya a la pagina de club de la federacion
  2209. $jugador = new Jugador(__METHOD__);
  2210. $jugador->setLicencia($inicialFed . "00123456");
  2211. }
  2212. $club = $this->em->getRepository(Club::class)->findOneBy(array('id' => substr(trim($jugador->getLicencia()), 0, 4), 'habilitado' => true));
  2213. if (!$club) {
  2214. $club = $this->em->getRepository(Club::class)->find($inicialFed . "00");
  2215. if (!$club) {
  2216. return $this->redirect($this->generateUrl('provincias'));
  2217. }
  2218. }
  2219. return $this->render("frontend/Default/bienvenido.html.twig", [
  2220. 'club' => $club,
  2221. 'jugador' => $jugador
  2222. ]);
  2223. }
  2224. /**
  2225. * F-071 Listado de clubes agrupados por provincia
  2226. *
  2227. * @Route("/provincias/{id}", name="provincias", defaults={"id" = 0})
  2228. */
  2229. public function provinces($id): Response
  2230. {
  2231. $clubRepository = $this->em->getRepository(Club::class);
  2232. $provinceRepository = $this->em->getRepository(Provincia::class);
  2233. $regionRepository = $this->em->getRepository(Comunidad::class);
  2234. $clubsByProvince = $this->getClubsByProvince($clubRepository);
  2235. $provincesWithCount = $this->getProvincesWithClubCount($clubsByProvince, $provinceRepository);
  2236. $regionsWithProvinces = $this->getRegionsWithProvinces($provincesWithCount, $provinceRepository, $regionRepository);
  2237. return $this->render("frontend/Default/provincias.html.twig", [
  2238. 'id' => $id,
  2239. 'clubsByProvince' => $clubsByProvince,
  2240. 'provincesWithCount' => $provincesWithCount,
  2241. 'regions' => $regionsWithProvinces
  2242. ]);
  2243. }
  2244. private function getClubsByProvince($clubRepository): array
  2245. {
  2246. $clubs = $clubRepository->findTodosProvincia();
  2247. $clubsByProvince = [];
  2248. foreach ($clubs as $club) {
  2249. $locality = $club->getLocalidad();
  2250. $province = $locality?->getProvincia();
  2251. if (!$province) {
  2252. continue;
  2253. }
  2254. $provinceId = $province->getId();
  2255. $clubsByProvince[$provinceId]['name'] = $province->getNombre();
  2256. $clubsByProvince[$provinceId]['clubs'][] = [
  2257. 'id' => $club->getId(),
  2258. 'name' => $club->getNombre(),
  2259. 'locality' => $locality->getNombre(),
  2260. 'phone' => $club->getTelefono() ?? 'No disponible'
  2261. ];
  2262. }
  2263. return $clubsByProvince;
  2264. }
  2265. private function getProvincesWithClubCount(array $clubsByProvince, $provinceRepository): array
  2266. {
  2267. $provinces = $provinceRepository->findAll();
  2268. $provincesWithCount = [];
  2269. foreach ($provinces as $province) {
  2270. $provinceId = $province->getId();
  2271. $provincesWithCount[$provinceId] = [
  2272. 'name' => $province->getNombre(),
  2273. 'num_clubs' => count($clubsByProvince[$provinceId]['clubs'] ?? [])
  2274. ];
  2275. }
  2276. return $provincesWithCount;
  2277. }
  2278. private function getRegionsWithProvinces(array $provincesWithCount, $provinceRepository, $regionRepository): array
  2279. {
  2280. $regions = $regionRepository->findAll();
  2281. $regionsWithProvinces = [];
  2282. foreach ($regions as $region) {
  2283. $regionsWithProvinces[$region->getId()] = [
  2284. 'name' => $region->getNombre(),
  2285. 'default_logo' => $region->getDefaultLogo() ?? 'https://resources.nextcaddy.com/clubResources/nextcaddy/logos/SVG/nextcaddy.svg',
  2286. 'provinces' => []
  2287. ];
  2288. }
  2289. foreach ($provincesWithCount as $provinceId => $provinceData) {
  2290. $province = $provinceRepository->find($provinceId);
  2291. $regionId = $province->getComunidad()->getId();
  2292. if (isset($regionsWithProvinces[$regionId])) {
  2293. $regionsWithProvinces[$regionId]['provinces'][$provinceId] = $provinceData;
  2294. }
  2295. }
  2296. return $regionsWithProvinces;
  2297. }
  2298. /**
  2299. * F-072 Pagina para felicitar el año nuevo
  2300. * @Route("/felicitacion-navidad/{token}", name="felicitacion_navidad")
  2301. *
  2302. * Más info: https://slopenxt.atlassian.net/wiki/spaces/NXT/pages/638386177/Felicitaci+n+de+Navidad
  2303. *
  2304. */
  2305. public function felicitacionNavidad($token)
  2306. {
  2307. $key = $this->getParameter('secret');
  2308. $cadena = UtilStatic::desencriptar($token, $key); //LICENCIA-AÑO
  2309. $f = new \DateTime("now");
  2310. if (intval($f->format("Y")) > 2020) {
  2311. $valores = explode("_", $cadena); //asi los profesionales pueden verlo sin que sea generico
  2312. } else {
  2313. $valores = explode("-", $cadena);
  2314. }
  2315. $licencia = $valores[0];
  2316. $year = $valores[1];
  2317. $jugador = $this->em->getRepository(Jugador::class)->findOneBy(array('habilitado' => 1, 'licencia' => $licencia));
  2318. if ($jugador) {
  2319. //Excepcion en el año 2019 por culpa de la RGPD
  2320. if ($year != 2019) {
  2321. if (substr($jugador->getLicencia(), 0, 2) != "CM") {
  2322. //buscamos las competiciones del año anterior
  2323. $competiciones = $this->em->getRepository(Inscrito::class)->getCompeticionesAnualLicencia($licencia, "" . ($year - 1));
  2324. }
  2325. }
  2326. } else {
  2327. //creamos un jugador por defecto si no existe, para que vaya a la pagina de club de la federacion
  2328. $jugador = new Jugador(__METHOD__);
  2329. $jugador->setNombre("Golfista");
  2330. $jugador->setLicencia("AM00123456");
  2331. $competiciones = [];
  2332. }
  2333. if ($year >= 2020) {
  2334. $view = "frontend/Navidad/navidad_" . $year . ".html.twig";
  2335. } else {
  2336. $view = "frontend/Navidad/navidad.html.twig";
  2337. }
  2338. return $this->render($view, array(
  2339. 'year' => $year,
  2340. 'jugador' => $jugador,
  2341. 'competiciones' => $competiciones,
  2342. 'leones' => false //in_array($licencia, ["AM85111566"])
  2343. ));
  2344. }
  2345. /**
  2346. * F-073 Pagina para felicitar las fiestas navideñas 2016/17
  2347. *
  2348. * @Route("/navidad/{licencia}", name="navidad")
  2349. */
  2350. public function navidad($licencia)
  2351. {
  2352. $key = $this->getParameter('secret');
  2353. $token = UtilStatic::encriptar($licencia . "-" . 2017, $key);
  2354. return $this->redirect($this->generateUrl('felicitacion_navidad', array("token" => $token)));
  2355. /*
  2356. $jugador = $this->em->getRepository(Jugador::class)->findOneBy(array('licencia' => $licencia));
  2357. if (!$jugador) {
  2358. //creamos un jugador por defecto si no existe, para que vaya a la pagina de club de la federacion
  2359. $jugador = new Jugador(__METHOD__);
  2360. $jugador->setNombre("Golfista");
  2361. $jugador->setLicencia("AM00123456");
  2362. }
  2363. $competiciones = $this->em->getRepository(Inscrito::class)->getCompeticionesAnualLicencia($licencia, "2016");
  2364. return array('jugador' => $jugador,
  2365. 'competiciones' => $competiciones
  2366. );
  2367. * */
  2368. }
  2369. // Pablo 10/08/2023: Se comenta ya que estan llegando muchos errores a esta pagina (posiblemente un bot);
  2370. // y asi evitar el bombardeo de emails de error en esta pagina obsoleta y sin mantenimiento
  2371. // /**
  2372. // * F-074 Cambio de handicap de un jugador tras competicion
  2373. // *
  2374. // * @Route("/cambio-hcp/{id}/{orden}/{ccc}", name="cambio_hcp", defaults={ "ccc" = 0 })
  2375. // */
  2376. // public function cambioHcp($id, $orden, $ccc) {
  2377. // $inscrito = $this->em->getRepository(Inscrito::class)->find($id);
  2378. // if (!$inscrito) {
  2379. // $this->addFlash(
  2380. // 'error', "No encontramos el Inscrito que nos ha solicitado");
  2381. // return $this->redirect($this->generateUrl('portada'));
  2382. // }
  2383. // $this->em->getFilters()->disable('softdeleteable');
  2384. // $competicion = $inscrito->getCompeticion();
  2385. // if (!$competicion || !is_null($competicion->getDeletedAt())) {
  2386. // $this->addFlash('error', 'No se ha encontrado la competición');
  2387. // return $this->redirect($this->generateUrl('portada'));
  2388. // }
  2389. // $this->em->getFilters()->enable('softdeleteable');
  2390. // //$totalJornadas = count($this->em->getRepository(Jornada'::class->findBy(array('competicion' => $competicion->getId()), array('orden' => 'ASC')));
  2391. // $totalJornadas = count($competicion->getJornadas());
  2392. // $jornada = $this->em->getRepository(Jornada::class)->findOneBy(array('competicion' => $competicion->getId(), 'orden' => $orden));
  2393. // if (!$jornada) {
  2394. // $this->addFlash(
  2395. // 'error', "No encontramos la Jornada que nos ha solicitado");
  2396. // return $this->redirect($this->generateUrl('portada'));
  2397. // }
  2398. // $hcpInscrito = $inscrito->getHcp();
  2399. // //buscamos la categoria de HCP para empezar a mirar la tabla
  2400. // $categoria = $this->em->getRepository(CategoriaHandicap::class)->findOneByHandicapRange($hcpInscrito);
  2401. // $handicaps = unserialize($inscrito->getHcpSms());
  2402. // $diferencia = 0;
  2403. // $precision = 1;
  2404. // if ($categoria->getId() == 6) {
  2405. // $precision = 0; //Para 6a categoria se redondea sin decimales para que queden numeros enteros
  2406. // }
  2407. // if ((!isset($handicaps[$orden - 1])) || ($orden == 1)) {
  2408. // $diferencia = round($handicaps[$orden] - $inscrito->getHcp(), $precision);
  2409. // } else {
  2410. // $diferencia = round($handicaps[$orden] - $handicaps[$orden - 1], $precision);
  2411. // }
  2412. // $array_bajada = array();
  2413. // $clasificado = array();
  2414. // $acumulado = 0;
  2415. // if ($competicion->getFormula() != NULL) {
  2416. // if ($competicion->getFormula()->getId() == "S") {
  2417. // $clasificaciones = $this->em->getRepository(Clasificacion::class)->findBy(array('competicion' => $competicion->getId(), 'calculo' => 'H'));
  2418. // $parciales = $this->em->getRepository(Parcial::class)->findBy(array('jornada' => null, 'clasificacion' => $clasificaciones));
  2419. // $clasificado = $this->em->getRepository(Clasificado::class)->findOneBy(array('parcial' => $parciales, 'inscrito' => $inscrito->getId()));
  2420. // if ($clasificado) {
  2421. // //buscamos en la zona neutra una vez que sabemos la categoriahcp
  2422. // $tipo_prueba = "i";
  2423. // if ($jornada->getModalidad()->getId() == "P") {
  2424. // $tipo_prueba = "p";
  2425. // }
  2426. // $son18hoyos = true;
  2427. // if ($tipo_prueba != "p") { //el distinguir entre 18 o 9 hoyos solo tiene sentido para Individual o CanadaCup
  2428. // $jc = $this->em->getRepository(JornadaConfig::class)->findOneBy(array('jornada' => $jornada->getId(), 'categoria' => $inscrito->getCategoria()));
  2429. // if (!empty($jc)) {
  2430. // if ($jc->getHoyos() != "1-18") {
  2431. // $son18hoyos = false;
  2432. // }
  2433. // }
  2434. // }
  2435. // $campoCorto = false;
  2436. // $t = $jornada->getTrazado();
  2437. // if (!is_null($t->getCampoCorto())) {
  2438. // $campoCorto = $t->getCampoCorto();
  2439. // } else {
  2440. // // Consultar a la española la primera vez y guardar el dato para las siguientes consultas
  2441. // $numero_trazado = $t->spanishFederationNumberCourseFormat();
  2442. // $this->cws->init();
  2443. // //$resultado = $coursews->listar(array("courseCode" => $numero_trazado));
  2444. // //$campoCorto = $resultado->course->shortCourse;
  2445. // $resultado = $this->cws->listar2020(array("courseCode" => $numero_trazado));
  2446. // $campoCorto = $resultado->courses->course->shortCourse; //En este caso solo se busca por un trzado en concreto, por lo que podemos acceder directamente
  2447. // $t->setCampoCorto($campoCorto);
  2448. // $this->em->flush();
  2449. // }
  2450. // $zona_neutra = $this->em->getRepository(ZonaNeutra::class)->findOneBy(array('categoria' => $categoria, 'tipoPrueba' => $tipo_prueba, 'campoCorto' => $campoCorto, 'son18hoyos' => $son18hoyos));
  2451. // $ascValor = $jornada->getAscValor();
  2452. // if ($ascValor == 99) {
  2453. // $ascValor = 2;
  2454. // }
  2455. // $suma_asc_neto = $clasificado->getNeto() + $ascValor; //$jornada->getAscValor();
  2456. // if ($suma_asc_neto < $zona_neutra->getPuntosMin()) {
  2457. // $array_bajada[$clasificado->getNeto() + $ascValor /* $jornada->getAscValor() */] = $zona_neutra->getSubidaInferiorZn();
  2458. // } else {
  2459. // if ($suma_asc_neto < $zona_neutra->getPuntosMax()) {
  2460. // $array_bajada[$clasificado->getNeto() + $ascValor /* $jornada->getAscValor() */] = 0;
  2461. // } else {
  2462. // if ($suma_asc_neto > 72) {
  2463. // $suma_asc_neto = 72;
  2464. // }
  2465. // if ($tipo_prueba == "i") {
  2466. // for ($b = ($zona_neutra->getPuntosMax() + 1); $b <= $suma_asc_neto; $b++) {
  2467. // $bajada = $this->em->getRepository(Bajada::class)->findBajadasExact($b, $categoria->getId(), $tipo_prueba, $campoCorto);
  2468. // $array_bajada[$b] = $bajada->getBajada();
  2469. // $acumulado += $bajada->getBajada();
  2470. // //comprobamos si tenemos que actualizar categoria para cambiar los valores
  2471. // $acu = $inscrito->getHcp() + $acumulado;
  2472. // if (($acu < $categoria->getHcpMin()) || ($acu > $categoria->getHcpMax())) {
  2473. // $categoria = $this->em->getRepository(CategoriaHandicap::class)->findOneByHandicapRange($inscrito->getHcp() + $acumulado);
  2474. // }
  2475. // }
  2476. // } else {
  2477. // $bajada = $this->em->getRepository(Bajada::class)->findBajadasExact($suma_asc_neto, $categoria->getId(), $tipo_prueba, $campoCorto);
  2478. // $array_bajada[$suma_asc_neto] = $bajada->getBajada();
  2479. // $acumulado += $bajada->getBajada();
  2480. // }
  2481. // }
  2482. // }
  2483. // }
  2484. // }
  2485. // }
  2486. // $jugador = $inscrito->getjugador();
  2487. // $fb = $this->createFormBuilder($jugador, array('action' => $this->generateUrl('tour_autocomplete_update_rgpd'), 'method' => 'POST'))
  2488. // ->add('newsletters', CheckboxType::class, array('mapped' => false, "label" => "También quiero recibir newsletters", "required" => false, "attr" => array("checked" => (strpos($competicion->getOrganizador()->getId(), "AM") !== false))))
  2489. // ->add('organizador', HiddenType::class, array('mapped' => false, 'attr' => array('value' => $competicion->getOrganizador()->getId())))
  2490. // ->add('rgpd', HiddenType::class, array('mapped' => false))
  2491. // ->add('id', HiddenType::class);
  2492. // //$secret = $this->getParameter('secret');
  2493. // //if (empty($jugador->getEmail())) {
  2494. // if (empty($jugador->getEmailCod())) {
  2495. // $fb->add('email', EmailType::class, array("label" => false, "required" => false, "attr" => array("placeholder" => "Introduzca email")));
  2496. // }
  2497. // $form = $fb->getForm();
  2498. // return $this->render("frontend/Default/cambioHcp.html.twig", [
  2499. // 'hcp' => $handicaps[$orden],
  2500. // 'diferencia' => $diferencia,
  2501. // 'competicion' => $competicion,
  2502. // 'clasificado' => $clasificado,
  2503. // 'orden' => $orden,
  2504. // 'form' => $form,
  2505. // 'id' => $id,
  2506. // 'ccc' => $ccc,
  2507. // 'inscrito' => $inscrito,
  2508. // 'acumulado' => round($acumulado, 1), //Es necesario redondear. Se manda para solucionar temporalmente el probblema del campo corto
  2509. // 'jornada' => $jornada,
  2510. // 'totalJornadas' => $totalJornadas,
  2511. // 'array_bajada' => $array_bajada
  2512. // ]);
  2513. // }
  2514. // /**
  2515. // * F-075 Muestra la pagina de información de marketing
  2516. // *
  2517. // * @Route("/descripcion", name="marketing")
  2518. // */
  2519. // public function marketing()
  2520. // {
  2521. // $user = $this->getUser();
  2522. //
  2523. // if (!$this->utilidades->compruebaRol(["NUEVA_FEDE", "PUBLICIDAD"], false)) {
  2524. // $this->addFlash(
  2525. // 'error', "No tiene permisos suficientes para acceder a la página solicitada");
  2526. //
  2527. // return $this->redirect($this->generateUrl('_club', array('id' => 'AM00')));
  2528. // }
  2529. //
  2530. // return $this->render("frontend/Default/marketing.html.twig", [
  2531. // 'user' => $user,
  2532. // ]);
  2533. // }
  2534. /**
  2535. * F-076 Demo de visualización del Hándicap actual de acceso al campeonato de España INFANTIL
  2536. *
  2537. * @Route("/acceso-campeonato-rfeg/{licencia}", name="acceso_campeonato_rfeg")
  2538. */
  2539. public function accesoCampeonatosEspania($licencia, FederatedWebService $rfeg)
  2540. {
  2541. $lic = substr($licencia, 4);
  2542. $rfeg->init("AM00");
  2543. //$jugadores = $rfeg->searchByCode(array('federationCode' => $lic));
  2544. $dataForRequest = ['federatedCodes' => ['federatedCode' => $lic]];
  2545. $jugadores = $rfeg->listByCode2020($dataForRequest);
  2546. if (isset($jugadores->federateds)) {
  2547. if (isset($jugadores->federateds->federated)) {
  2548. $jugador = $this->em->getRepository(Jugador::class)->findByLicenciaCortaNoTemporal($lic);
  2549. if (!$jugador) {
  2550. $jugador = new Jugador(__METHOD__);
  2551. }
  2552. $dataFromFederated = $jugadores->federateds->federated;
  2553. $saceDataRequest = $rfeg->getSACEData($dataForRequest);
  2554. $saceData = $saceDataRequest->federateds->federated ?? null;
  2555. $this->updatePlayerFromFederated->__invoke($dataFromFederated, $saceData, $jugador);
  2556. }
  2557. //vemos si es el tercer o cuarto mejor handicap
  2558. $posicionHcp = ($jugador->getNivel()->getId() != "B") ? 4 : 3;
  2559. return $this->render("frontend/Default/acceso_campeonato_rfeg.html.twig", [
  2560. 'jugador' => $jugador,
  2561. 'posicionHcp' => $posicionHcp,
  2562. ]);
  2563. } else {
  2564. $this->addFlash('error', 'No existen datos para ese jugador');
  2565. return $this->redirect($this->generateUrl('competiciones_abiertas'));
  2566. }
  2567. }
  2568. /**
  2569. * @Route("/calculo-hcpjuego", name="nxt_calculo_hcpjuego", options={"expose"=true})
  2570. */
  2571. public function calculoHcpjuego(Request $request)
  2572. {
  2573. $data = $request->request;
  2574. $hcp = str_replace(",", ".", $data->get('handicap')); //arreglo que en JS no funcionaba
  2575. $tramo = $data->get('tramo');
  2576. $barraNombre = $data->get('barra');
  2577. $trazadoNombre = $data->get('trazado');
  2578. $porcentaje = $data->get('porcentaje');
  2579. $parAnt = 0;
  2580. $hcps_juego = array();
  2581. $trazado_barra = $this->em->getRepository(TrazadoBarra::class)->getTrazadoBarraByName($trazadoNombre, $barraNombre);
  2582. foreach ($trazado_barra as $tb) {
  2583. $vs = $tb["slope"];
  2584. $vc = $tb["campo"];
  2585. $par = $tb["par"];
  2586. switch ($tramo) {
  2587. case "1-9":
  2588. $vs = $tb["slope19"];
  2589. $vc = $tb["campo19"];
  2590. $par = $tb["par19"];
  2591. break;
  2592. case "10-18":
  2593. $vs = $tb["slope1018"];
  2594. $vc = $tb["campo1018"];
  2595. $par = $tb["par1018"];
  2596. break;
  2597. }
  2598. if (!$par || $par == 0) {
  2599. $par = $parAnt;
  2600. }
  2601. $hcps_juego[$tb["sexo"]] = null;
  2602. if (!is_null($vs) && !is_null($vc) && ($par != 0)) {
  2603. $hcps_juego[$tb["sexo"]] = Tarjetas::calcularHcpJuego(null, $hcp, $vs, $vc, $par, $tramo, $porcentaje);
  2604. }
  2605. $parAnt = $par;
  2606. }
  2607. return new JsonResponse($hcps_juego);
  2608. }
  2609. /**
  2610. * F-079 Calcula el handicap de juego de un jugador para la vista de calculadora de club
  2611. *
  2612. * TODO Ya existe funcion "nxt_calculo_hcpjuego" que sustituye a esta, cuando se introduzca el nuevo componente en nextcaddy se debera eliminar
  2613. *
  2614. * @Route("/calculadora", name="nextcaddy_calculadora_hcpjuego", options={"expose"=true})
  2615. */
  2616. public function calculadoraHcpJuego(Request $request)
  2617. {
  2618. $data = $request->request;
  2619. $hcp = str_replace(",", ".", $data->get('handicap')); //arreglo que en JS no funcionaba
  2620. $hoyo = $data->get('hoyo');
  2621. $barra = $data->get('barra');
  2622. $trazado = $data->get('trazado');
  2623. $parAnt = 0;
  2624. $hcps_juego = array();
  2625. $trazado_barra = $this->em->getRepository(TrazadoBarra::class)->findBy(array('trazado' => $trazado, 'barra' => $barra, 'activo' => 1));
  2626. foreach ($trazado_barra as $tb) {
  2627. $hoyos = '1-18';
  2628. $vs = $tb->getSlope();
  2629. $vc = $tb->getCampo();
  2630. $par = $tb->getPar();
  2631. switch ($hoyo) {
  2632. case 1:
  2633. $hoyos = '1-9';
  2634. $vs = $tb->getSlope19();
  2635. $vc = $tb->getCampo19();
  2636. $par = $tb->getPar19();
  2637. break;
  2638. case 2:
  2639. $hoyos = '10-18';
  2640. $vs = $tb->getSlope1018();
  2641. $vc = $tb->getCampo1018();
  2642. $par = $tb->getPar1018();
  2643. break;
  2644. }
  2645. //$limites = explode("-", $hoyos);
  2646. //$par = $this->em->getRepository(Hoyo::class)->getSumaPar($tb->getId(), $limites[0], $limites[1]);
  2647. if (!$par || $par == 0) {
  2648. $par = $parAnt;
  2649. }
  2650. $hcps_juego[$tb->getSexo()] = null;
  2651. if (!is_null($vs) && !is_null($vc) && ($par != 0)) {
  2652. $hcps_juego[$tb->getSexo()] = Tarjetas::calcularHcpJuego(null, $hcp, $vs, $vc, $par, $hoyos);
  2653. }
  2654. $parAnt = $par;
  2655. }
  2656. return new JsonResponse($hcps_juego);
  2657. }
  2658. // Esta vista deja de ser accesible, se comenta
  2659. // /*
  2660. // * F-080 URL de acceso rapido en la pagina de marketing para usuarios de rol Gerente
  2661. // *
  2662. // * @Route("/info", name="info", options={"expose"=true})
  2663. // *
  2664. // */
  2665. // public function accesoGerente() {
  2666. // $username = "gerente";
  2667. // $token = strtoupper(sha1($username . $this->getParameter('next.secret')));
  2668. //
  2669. // return $this->redirect($this->generateUrl('get_auto_login', array('username' => $username, 'token' => $token)));
  2670. // }
  2671. /**
  2672. * F-081 Hace autologin y redirige
  2673. *
  2674. * @Route("/redirect-login", name="redirect_login", options={"expose"=true}, methods={"GET"})
  2675. */
  2676. public function redirectAutoLogin(Request $request)
  2677. {
  2678. $data = json_decode(base64_decode($request->query->get("g")));
  2679. $secret = $this->getParameter("secret");
  2680. $nxtSecret = $this->getParameter("next.secret");
  2681. $id = UtilStatic::desencriptar($data->i, $secret);
  2682. $username = UtilStatic::desencriptar($data->u, $secret);
  2683. $url = UtilStatic::desencriptar($data->r, $secret);
  2684. $token = UtilStatic::desencriptar($data->t, $secret);
  2685. $iat = new \DateTime(UtilStatic::desencriptar($data->a, $secret));
  2686. $hoy = new \DateTime("now");
  2687. if ($hoy->format("U") > $iat->format("U")) {
  2688. $this->addFlash('error', "Imposible acceder (-1)");
  2689. return $this->redirect($this->generateUrl("portada"));
  2690. }
  2691. $user = $this->em->getRepository(User::class)->findOneBy(array('username' => $username, "enabled" => 1));
  2692. if (!$user) {
  2693. $this->addFlash('error', "Imposible acceder (-2)");
  2694. return $this->redirect($this->generateUrl("portada"));
  2695. }
  2696. if (strtoupper($token) != strtoupper(sha1($nxtSecret . UtilStatic::encriptar($username, $secret) . $secret))) {
  2697. $this->addFlash('error', "Imposible acceder (-3)");
  2698. return $this->redirect($this->generateUrl("portada"));
  2699. }
  2700. $roles = $user->getRoles();
  2701. $uspsto = new UsernamePasswordToken($user, null, 'main', $roles);
  2702. $this->get('security.token_storage')->setToken($uspsto);
  2703. $this->get('session')->set('_security_main', serialize($uspsto));
  2704. return $this->redirect($this->generateUrl($url, ['idc' => $id]));
  2705. }
  2706. /**
  2707. * @Route("/staff-redirect/{params}", name="staff_redirect", methods={"GET"})
  2708. */
  2709. public function staffRedirect($params)
  2710. {
  2711. $params = json_decode(base64_decode($params));
  2712. $secret = $this->getParameter("secret");
  2713. $nxtSecret = $this->getParameter("next.secret");
  2714. $username = UtilStatic::desencriptar($params->username, $secret);
  2715. $token = UtilStatic::desencriptar($params->authToken, $secret);
  2716. $url = UtilStatic::desencriptar($params->url, $secret);
  2717. $user = $this->em->getRepository(User::class)->findOneBy(array('username' => $username, "enabled" => 1));
  2718. if (!$user) {
  2719. return $this->json([
  2720. 'success' => false
  2721. ]);
  2722. }
  2723. if (strtoupper($token) != strtoupper(sha1($nxtSecret . UtilStatic::encriptar($username, $secret) . $secret))) {
  2724. return $this->json([
  2725. 'success' => false
  2726. ]);
  2727. }
  2728. $uspsto = new UsernamePasswordToken($user, null, 'main', $user->getRoles());
  2729. $this->tokenStorage->setToken($uspsto);
  2730. $this->session->set('_security_main', serialize($uspsto));
  2731. return $this->redirect($url);
  2732. }
  2733. /**
  2734. * F-082 Muestra la pagina de suscripcion del telefono
  2735. *
  2736. * @Route("/suscripcion/{token}", name="next_suscribe_rgpd", options={"expose"=true})
  2737. */
  2738. public function suscripcionRgpd($token)
  2739. {
  2740. $key = $this->getParameter('secret');
  2741. $idj = UtilStatic::desencriptar($token, $key);
  2742. $jugador = $this->em->getRepository(Jugador::class)->find($idj);
  2743. $clientes = $this->em->getRepository(Cliente::class)->findFederaciones(); //findBy(['nombreCorto' => array("AM00", "LV05", "CM41")]);
  2744. return $this->render("frontend/User/suscribe_rgpd.html.twig", [
  2745. "idj" => $idj,
  2746. "clientes" => $clientes,
  2747. 'jugadorRGPD' => $jugador->getPrivacidadAsArray(),
  2748. 'jugador' => $jugador
  2749. ]);
  2750. }
  2751. /**
  2752. * F-083 Guarda la configuracion de privacidad del jugador
  2753. *
  2754. * @Route("/realizar-suscripcion", name="next_realizar_suscripcion", options={"expose"=true}, methods={"POST"})
  2755. */
  2756. public function realizarSuscripcion(Request $request, EnvioSms $messaging, UtilJugadores $util_jugadores)
  2757. {
  2758. $telefono = $request->request->get('telefono');
  2759. $idj = $request->request->get('idj');
  2760. $privacidad = array();
  2761. //$clientes = $this->em->getRepository(Cliente::class)->findBy(['nombreCorto' => array("AM00", "LV05", "CM41")]);
  2762. //$clientes = array("AM00", "LV05", "CM41");
  2763. $clientes = $this->em->getRepository(Cliente::class)->findFederaciones();
  2764. $todas = boolval($request->request->get('pTodas'));
  2765. if ($todas) {
  2766. foreach ($clientes as $cn) {
  2767. $c = $cn->getNombreCorto();
  2768. $privacidad[$c] = true;
  2769. }
  2770. } else {
  2771. foreach ($clientes as $cn) {
  2772. $c = $cn->getNombreCorto();
  2773. $privacidad[$c] = boolval($request->request->get('p' . $c));
  2774. }
  2775. }
  2776. $jugador = $this->em->getRepository(Jugador::class)->find($idj);
  2777. if ($jugador) {
  2778. $jpriv = $jugador->getPrivacidadSimple();
  2779. $tel = $util_jugadores->getDatoPlanoDesdeJugador($jugador, "Telefono");
  2780. if ($telefono != $tel) {
  2781. $log_message = "Cambio de teléfono del Jugador " . $jugador->getNombreCompleto() . " (" . $jugador->getLicencia() . ") en el método " . __METHOD__ . ", de " . ($tel ?: "(vacio)") . " a " . $telefono;
  2782. $jugador = $util_jugadores->setDatoPlanoDesdeJugador($jugador, "Telefono", $telefono, false);
  2783. $log = new \App\Entity\Backend\Log('i', $log_message, null);
  2784. $this->em->persist($log);
  2785. }
  2786. $new = false;
  2787. foreach ($privacidad as $key => $priv) {
  2788. if ($priv) {
  2789. if (isset($jpriv[$key])) {
  2790. $jugadorRGPD = $this->em->getRepository(JugadorRGPD::class)->findBy(['jugador' => $jugador, 'aceptacion' => $key])[0];
  2791. } else {
  2792. $jugadorRGPD = new JugadorRGPD();
  2793. $jugadorRGPD->setCliente($this->em->getRepository(Cliente::class)->findOneBy(['nombreCorto' => $key]));
  2794. $jugadorRGPD->setAceptacion($key);
  2795. $jugadorRGPD->setJugador($jugador);
  2796. $new = true;
  2797. }
  2798. $jugadorRGPD->setRgpdExtra($request->headers->get("user-agent"));
  2799. $jugadorRGPD->setRgpdIP($request->getClientIp());
  2800. $jugadorRGPD->setRgpd(true);
  2801. if ($new) {
  2802. $this->em->persist($jugadorRGPD);
  2803. }
  2804. }
  2805. }
  2806. $this->em->flush();
  2807. $competi = null;
  2808. $api = false; //mandamos por la api segun corresponda
  2809. //Buscamos la ultima competicion donde se ha inscrito. Lo normal es que llegue a suscripcion porque se ha inscrito y no tenemos el telefono
  2810. $inscrito = $this->em->getRepository(Inscrito::class)->findOneBy(['jugador' => $jugador], ["created_at" => "DESC"]);
  2811. if ($inscrito) {
  2812. $competi = $inscrito->getCompeticion();
  2813. $org = $competi->getOrganizador()->getCliente()->getId();
  2814. $api = ($org >= 3); //1-RFGA 2-LV05 3-FCG 4y5-FGM
  2815. }
  2816. $messaging->enviarSms($telefono, "Bienvenido a Nextcaddy, " . $jugador->getNombre() . ". " . $this->generateUrl('bienvenido_nextcaddy', array('lic' => $jugador->getLicencia()), UrlGeneratorInterface::ABSOLUTE_URL), $competi, 5, $api);
  2817. }
  2818. return new JsonResponse(true);
  2819. }
  2820. // Se elimina esta funcion ya que desaparece el covid de la inscripcion NEX-1838
  2821. // /**
  2822. // * F-086 Guardado del FLP. Protocolo covid-19
  2823. // *
  2824. // * @Route("/formulario/{idc}", name="_formulario", options={"expose"=true}, methods={"POST"})
  2825. // */
  2826. // public function formularioCovid($idc, Request $request, KernelInterface $kernel) {
  2827. // $competicion = $this->em->getRepository(Competicion::class)->find($idc);
  2828. // $datos = [];
  2829. // //$organizadorId = $competicion->getOrganizador()->getId();
  2830. // /* if (!in_array($organizadorId, ["CM00", "AM00"])) {
  2831. // return new JsonResponse(["error" => "La competición no está organizada por la Federación de Golf", "codigo" => false]);
  2832. // } */
  2833. // /*
  2834. // //Se cambia segun tarea NEX-1447-5
  2835. // if (strpos($competicion->getOrganizador()->getId(), "0") !== false) {
  2836. // //if ('NEW-FORM' != $competicion->getCodigo() && $competicion->getOrganizador()->getId() != "CM00") {
  2837. // return new JsonResponse(["error" => "La competición no tiene disponible esta funcionalidad", "codigo" => false]);
  2838. // } */
  2839. // $cliente = $competicion->getOrganizador()->getCliente();
  2840. // $ruta_temporal = $kernel->getProjectDir() . "/public/uploads/inscritoCovid/$idc";
  2841. // if (!file_exists($ruta_temporal)) {
  2842. // mkdir($ruta_temporal, 0777, true);
  2843. // }
  2844. // $filenameid = sha1(uniqid(mt_rand(), true));
  2845. // if ($request->request->get('riesgo', 0)) {
  2846. // $filenameid .= "_x";
  2847. // }
  2848. // if (file_exists($ruta_temporal . '/' . $filenameid . '.pdf')) {
  2849. // unlink($ruta_temporal . '/' . $filenameid . '.pdf');
  2850. // }
  2851. // if (in_array($cliente->getId(), [4, 5])) {
  2852. // $datos['dni'] = $request->request->get('dni');
  2853. // $params["vulnerable"] = $request->request->get('vulnerable', 0);
  2854. // if (boolval($params["vulnerable"])) {
  2855. // $params["vulnerable_entidad"] = $request->request->get('vulnerable_entidad', "-");
  2856. // $params["vulnerable_actividades"] = $request->request->get('vulnerable_actividad', "-");
  2857. // $params["vulnerable_fecha"] = $request->request->get('vulnerable_fecha', "-");
  2858. // }
  2859. // } elseif (1 == $cliente->getId()) {
  2860. // $datos['competicion'] = $request->request->get('competicion');
  2861. // $datos['telefono'] = $request->request->get('telefono', "");
  2862. // $datos['emailCovid'] = $request->request->get('emailCovid', "");
  2863. // $datos['ciudad'] = $request->request->get('ciudad');
  2864. // $params['contacto'] = $request->request->get('contacto');
  2865. // $params['atencion'] = $request->request->get('atencion');
  2866. // $params['ambiente'] = $request->request->get('ambiente');
  2867. // $params['cercana'] = $request->request->get('cercana');
  2868. // $params['viaje'] = $request->request->get('viaje');
  2869. // $params['vivir'] = $request->request->get('vivir');
  2870. // $params['detalles'] = $request->request->get('detalles');
  2871. // // if(count($competicion->getJornadas()) > 1){
  2872. // // $params['consciente'] = $request->request->get('detalles');
  2873. // // }
  2874. // }
  2875. // $datos['nombre'] = $request->request->get('nombre');
  2876. // $params['datos'] = $datos;
  2877. // $params['firma'] = $request->request->get('firma', null);
  2878. // $params["propio"] = $request->request->get('propio', 1);
  2879. // if ($params["propio"] == 0) {
  2880. // $interesado['nombre'] = $request->request->get('interesado-nombre');
  2881. // $interesado['dni'] = $request->request->get('interesado-dni', "");
  2882. // } else {
  2883. // $interesado['nombre'] = "";
  2884. // $interesado['dni'] = "";
  2885. // }
  2886. // $params['interesado'] = $interesado;
  2887. // $params['flp'] = $request->request->get('flp', 0);
  2888. // setlocale(LC_ALL, "es_ES");
  2889. // $params['fecha'] = strftime("%A %d de %B del %Y");
  2890. // $params['localidad'] = ucwords($request->request->get('localidad'));
  2891. // $params['jornadas'] = $competicion->getJornadas();
  2892. // $html = $this->render('frontend/Competicion/formulario_covid_' . strtolower(substr($cliente->getNombreCorto(), 0, 2)) . '.html.twig', $params);
  2893. // $myfile = fopen($ruta_temporal . "/" . $filenameid . ".html", "w");
  2894. // fwrite($myfile, $html);
  2895. // fclose($myfile);
  2896. // try {
  2897. // $isProd = ($kernel->getEnvironment() == 'prod');
  2898. // if ($_SERVER['SERVER_ADDR'] == "178.33.230.218") {
  2899. // $cmd = "/opt/plesk/node/8/bin/relaxed " . $ruta_temporal . "/" . $filenameid . ".html --bo";
  2900. // } else {
  2901. // La direccion ha quedado obsoleta
  2902. // $cmd = "relaxed " . $ruta_temporal . "/" . $filenameid . ".html --build-once";
  2903. // }
  2904. // exec($cmd);
  2905. // if ($isProd) {
  2906. // //Borramos los ficheros temporales generados
  2907. // if (file_exists($ruta_temporal . '/' . $filenameid . '.html')) {
  2908. // unlink($ruta_temporal . '/' . $filenameid . '.html');
  2909. // }
  2910. // if (file_exists($ruta_temporal . '/' . $filenameid . '_temp.htm')) {
  2911. // unlink($ruta_temporal . '/' . $filenameid . '_temp.htm');
  2912. // }
  2913. // }
  2914. // $keyAge = $this->getParameter('age.key');
  2915. // $rutaArchivo = $ruta_temporal . '/' . $filenameid . '.pdf';
  2916. // if ($isProd) {
  2917. // $cmd = "/var/www/vhosts/nextcaddy.com/.linuxbrew/bin/age -r " . $keyAge . " " . $rutaArchivo . " > " . $rutaArchivo . ".age";
  2918. // } else {
  2919. // $cmd = "C:\age\age.exe -r " . $keyAge . " " . $rutaArchivo . " > " . $rutaArchivo . ".age";
  2920. // }
  2921. // exec($cmd);
  2922. // if (file_exists($rutaArchivo) && file_exists($rutaArchivo . ".age")) {
  2923. // unlink($rutaArchivo);
  2924. // }
  2925. // } catch (\Exception $excptn) {
  2926. // return new JsonResponse(["error" => "Error generando el PDF", "codigo" => false]);
  2927. // }
  2928. // //$file = $ruta_temporal . "/" . $idc . "_formcovid.pdf";
  2929. // //Si ya tenemos inscrito (es el formulario del horario) entonces añadimos el nuevo documento y lo marcamos como ya modificado
  2930. // $idi = $request->request->get("idi", null);
  2931. // if (!empty($idi)) {
  2932. // try {
  2933. // $inscrito = $this->em->getRepository(Inscrito::class)->find($idi);
  2934. // if ($inscrito) {
  2935. // $documento = new InscritoDocumento();
  2936. // $documento->setInscrito($inscrito);
  2937. // $documento->setDocumento($filenameid . ".pdf");
  2938. // $documento->setTipo(2);
  2939. // $inscrito->addDocumento($documento);
  2940. // //if (is_null($inscrito->getCovidModif())) {
  2941. // // $inscrito->setCovidModif(0);
  2942. // //} else {
  2943. // $inscrito->setCovidModif(1);
  2944. // //}
  2945. // $this->em->flush();
  2946. // }
  2947. // } catch (\Throwable $ex) {
  2948. // throw new NotFoundHttpException("Error generando el PDF");
  2949. // }
  2950. // // // Segun la nota informativa del 28/03/2022 se comenta esta parte
  2951. // // } else {
  2952. // // try {
  2953. // // $certificado = $request->files->get("certificado", 0);
  2954. // //
  2955. // // if ($certificado) {
  2956. // // $certname = md5(rand() . "_" . uniqid('certCov19')) . ".pdf";
  2957. // //
  2958. // // $rutaCarpeta = __DIR__ . '/../../../../web/uploads/inscritoCovid/' . $idc;
  2959. // // $rutaArchivo = $rutaCarpeta . "/" . $certname;
  2960. // //
  2961. // // $certificado->move($rutaCarpeta, $certname);
  2962. // //
  2963. // // $keyAge = $this->getParameter('age.key');
  2964. // // $isProd = ($kernel->getEnvironment() == 'prod');
  2965. // // if ($isProd) {
  2966. // // $cmd = "/var/www/vhosts/nextcaddy.com/.linuxbrew/bin/age -r " . $keyAge . " " . $rutaArchivo . " > " . $rutaArchivo . ".age";
  2967. // // } else {
  2968. // // $cmd = "C:\age\age.exe -r " . $keyAge . " " . $rutaArchivo . " > " . $rutaArchivo . ".age";
  2969. // // }
  2970. // // exec($cmd);
  2971. // //
  2972. // // if (file_exists($rutaArchivo) && file_exists($rutaArchivo . ".age")) {
  2973. // // unlink($rutaArchivo);
  2974. // // }
  2975. // // } else {
  2976. // // $certname = 0;
  2977. // // }
  2978. // // } catch (\Throwable $ex) {
  2979. // // $log_message = "Error guardando fichero certificado covid " . $idc;
  2980. // // $log = new Log('i', $log_message, null);
  2981. // // $this->em->persist($log);
  2982. // // $this->em->flush();
  2983. // // }
  2984. // }
  2985. // $flp = $request->request->get("flp", 0);
  2986. // if ($flp) {
  2987. // $this->addFlash(
  2988. // 'success', "Formulario rellenado correctamente");
  2989. // }
  2990. // return new JsonResponse(["file" => $filenameid . ".pdf", "codigo" => true /* , "certificado" => $certname */]);
  2991. // }
  2992. // Se elimina esta funcion ya que desaparece el covid de la inscripcion NEX-1838
  2993. // /**
  2994. // * F-087 Mostrar formulario FLP - Protocolo covid-19
  2995. // *
  2996. // * @Route("/flp/{idc}/{idi}", name="flp", options={"expose"=true})
  2997. // */
  2998. // function formularioFLP($idc, $idi) {
  2999. // $competicion = $this->em->getRepository(Competicion::class)->find($idc);
  3000. // if (!$competicion) {
  3001. // $this->addFlash('error', "El torneo buscado no existe");
  3002. // return $this->redirect($this->generateUrl('portada'));
  3003. // }
  3004. // $inscrito = $this->em->getRepository(Inscrito::class)->find($idi);
  3005. // if (!$inscrito) {
  3006. // $this->addFlash('error', "No se ha encontrado al jugador solicitado");
  3007. // return $this->redirect($this->generateUrl('_tournament', array('id' => $idc)));
  3008. // }
  3009. // $secret = $this->getParameter('secret');
  3010. // return $this->render("frontend/Default/flp.html.twig", [
  3011. // 'competicion' => $competicion,
  3012. // 'jornadas' => $competicion->getJornadas(),
  3013. // 'inscrito' => $inscrito,
  3014. // 'secret' => $secret
  3015. // ]);
  3016. // }
  3017. /**
  3018. * F-158 - Mostrar url tokenizada de archivo
  3019. *
  3020. * @Route("/resource/{token}", name="resource", options={"expose"=true})
  3021. *
  3022. */
  3023. public function mostrarArchivo($token): Response
  3024. {
  3025. try {
  3026. $ruta = explode("|", UtilStatic::desencriptarNew($token, $this->getParameter('secret')));
  3027. $response = new BinaryFileResponse($ruta[1]);
  3028. switch ($ruta[2]) {
  3029. case 'txt':
  3030. $documento = 'Documento.txt';
  3031. break;
  3032. case 'exe':
  3033. $documento = 'Programa.exe';
  3034. break;
  3035. case 'zip':
  3036. $documento = 'Programa.zip';
  3037. break;
  3038. case 'rar':
  3039. $documento = 'Programa.rar';
  3040. break;
  3041. default:
  3042. $documento = 'Documento.pdf';
  3043. break;
  3044. }
  3045. $response->setContentDisposition(
  3046. ResponseHeaderBag::DISPOSITION_INLINE, $documento, $documento
  3047. );
  3048. } catch (\Exception $e) {
  3049. throw new \Exception("Error, no existe el documento");
  3050. }
  3051. return $response;
  3052. }
  3053. /**
  3054. *
  3055. * @Route("/lionsLanding", name="lions_landing", options={"expose"=true})
  3056. *
  3057. */
  3058. public function lionsLanding(): Response
  3059. {
  3060. return $this->render('frontend/Landing/lions2026.html.twig');
  3061. }
  3062. // /**
  3063. // * @Route("/livescoring-new-template", name="livescoring_new_template")
  3064. // */
  3065. // public function livescoringNewTemplate(): Response
  3066. // {
  3067. // return $this->render('frontend/Default/livescoring_new_template.html.twig');
  3068. // }
  3069. }