src/Controller/TicketController.php line 148

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  4. use Symfony\Component\Mailer\MailerInterface;
  5. use Symfony\Bridge\Twig\Mime\TemplatedEmail;
  6. use Symfony\Component\Mime\Email;
  7. use Symfony\Component\HttpFoundation\{RequestResponse};
  8. use Symfony\Component\Routing\Annotation\Route;
  9. use App\Utils\Ticketing;
  10. use App\Utils\Functions;
  11. use App\Entity\User;
  12. use Symfony\Component\HttpFoundation\JsonResponse;
  13. use Endroid\QrCode\QrCode;
  14. use Dompdf\Dompdf;
  15. use Dompdf\Options;
  16. use Doctrine\Persistence\ManagerRegistry;
  17. class TicketController extends AbstractController
  18. {
  19.     /**
  20.      * @var Ticketing
  21.      */
  22.     private $ticketing;
  23.     /**
  24.      * @var Functions
  25.      */
  26.     private $functions;
  27.     /**
  28.      * @var ManagerRegistry
  29.      */
  30.     private $doctrine;
  31.     /**
  32.      * @param Ticketing $ticketing
  33.      * @param Functions $functions
  34.      * @param ManagerRegistry $doctrine
  35.      */
  36.     public function __construct(Ticketing $ticketingFunctions $functionsManagerRegistry $doctrine)
  37.     {
  38.         $this->ticketing $ticketing;
  39.         $this->functions $functions;
  40.         $this->doctrine  $doctrine;
  41.     }
  42.     /**
  43.      * @Route("/tickets", name="tickets")
  44.      */
  45.     public function tickets(Request $request): Response
  46.     {
  47.         $session $request->getSession();
  48.         if($request->get("ref")){
  49.             $session->set('ref'$request->get("ref"));
  50.         }
  51.         $events $this->ticketing->curl("events""normal", array(), "GET");
  52.         $keys $this->ticketing->curl("tickets?limit=3&orderBy=price&order=desc""normal", array(), "GET");
  53.         $filters array_filter($request->query->all());
  54.         $request->request->set('saleuser'1);
  55.         return $this->render('tickets/tickets.html.twig', [
  56.             'events' => $events["events"],
  57.             'filters' => $filters,
  58.             'keys' => $keys["tickets"]
  59.         ]);
  60.     }
  61.     /**
  62.      * @Route("/include-tickets", name="include_tickets")
  63.      */
  64.     public function includeTickets(Request $request): Response
  65.     {
  66.         $session $request->getSession();
  67.         $user=$this->functions->getUserLogged();
  68.         $check_user_session true;
  69.         if(!$user) {
  70.             $check_user_session false;
  71.         }
  72.         if (!$request->get("saleuser")) {
  73.             $sintax "&pack=null";
  74.         } else {
  75.             $sintax "";
  76.         }
  77.         if ($request->get("type")) {
  78.             switch ($request->get("type")) {
  79.                 case "2":
  80.                     $sintax .= "&maxPrice=1000";
  81.                     break;
  82.                 case "4":
  83.                     $sintax .= "&minPrice=1000";
  84.                     break;
  85.                 default:
  86.                     $sintax .= "";
  87.                     break;
  88.             }
  89.         }
  90.         if ($request->get("order") && $request->get("order") == "2") {
  91.             $sintax .= "&order=desc";
  92.         } else {
  93.             $sintax .= "&order=asc";
  94.         }
  95.         if ($request->get("name")) {
  96.             $sintax .= "&name=" urlencode($request->get("name"));
  97.         }
  98.         if ($request->get("price_equal")) {
  99.             $sintax .= "&maxPrice=" $request->get("price_equal") . "&minPrice=" $request->get("price_equal");
  100.         }
  101.         if ($request->get("offset")) {
  102.             $sintax .= "&offset=" $request->get("offset");
  103.         }
  104.         if ($request->get("limit")) {
  105.             $sintax .= "&limit=" $request->get("limit");
  106.         } else {
  107.             $sintax .= "&limit=12";
  108.         }
  109.         if ($request->get("event")) {
  110.             $sintax .= "&event=" $request->get("event");
  111.         }
  112.         if ($request->get("group")) {
  113.             $sintax .= "&groupBy=price";
  114.         }
  115.         // Geolocation ip
  116.         $from_argentina false;
  117.         $ip $this->functions->get_user_ip();
  118.         if($ip AND function_exists('geoip_country_code_by_name')) {
  119.             $country_code geoip_country_code_by_name($ip);
  120.             if($country_code == 'AR')
  121.                 $from_argentina true;
  122.         }
  123.         if ($request->get("small")) {
  124.             $page $this->onSaleTrueFalse($sintaxtrue$request);
  125.             $pageSoldOut $this->onSaleTrueFalse($sintaxfalse$request);
  126.             return $this->render('events/include-event-tickets.html.twig', [
  127.                 'page' => $page,
  128.                 'pageSoldOut' => $pageSoldOut,
  129.                 'check_user_session' => $check_user_session,
  130.                 'from_argentina' => $from_argentina,
  131.                 'conversion' => Functions::CONVERSION
  132.             ]);
  133.         } else {
  134.             if ($request->get("saleuser")) {
  135.                 $sintax .= "&onSaleByUser=true";
  136.             } else {
  137.                 $sintax .= "&onSale=true";
  138.             }
  139.             $page $this->ticketing->curl("tickets?orderBy=price" $sintax"normal", array(), "GET");
  140.             return $this->render('tickets/include-tickets.html.twig', [
  141.                 'page' => $page,
  142.                 'from_argentina' => $from_argentina,
  143.                 'conversion' => Functions::CONVERSION
  144.             ]);
  145.         }
  146.     }
  147.     /**
  148.      * @Route("/ticket-detail/{ticketId}", name="ticket-detail")
  149.      * @Route("/ticket-detail-finished/{ticketId}", name="ticket-detail-finished")
  150.      */
  151.     public function ticketDetail(Request $request,$ticketId): Response
  152.     {
  153.         $em $this->doctrine->getManager();
  154.         $session $request->getSession();
  155.         if($request->get("ref")){
  156.             $session->set('ref'$request->get("ref"));
  157.         }
  158.         $userId=false;
  159.         $max=0;
  160.         $quantity=1;
  161.         $history["activity"]=array();
  162.         $ticket $this->ticketing->curl("tickets/".$ticketId"normal", array(), "GET");
  163.         if(!$ticket || $ticket["code"]!="200"){
  164.             $this->addFlash(
  165.                 'notice',
  166.                 'No se puede acceder al ticket'
  167.             );
  168.             return $this->redirectToRoute('home');
  169.         }
  170.         if($ticket["price"]>=8000){
  171.             return $this->redirectToRoute('key-detail',array("keyId" => $ticketId));
  172.         }
  173.         //Si el ticket pertence a un usuario
  174.         if($ticket["user"]){
  175.             $userId=$this->functions->getUserLogged();
  176.             if(!$userId){
  177.                 $this->addFlash(
  178.                     'notice',
  179.                     'Debe iniciar sesión como usuario'
  180.                 );
  181.                 return $this->redirectToRoute('access',array("redirect" => $this->generateUrl('ticket-detail',array("ticketId" => $ticketId))));
  182.             }
  183.             if($ticket["user"]["userId"]!=$userId && !$ticket["onSaleUser"]){
  184.                 $this->addFlash(
  185.                     'notice',
  186.                     'No se puede acceder a este ticket'
  187.                 );
  188.                 return $this->redirectToRoute('home');
  189.             }
  190.             if(!empty($ticket["pack"])){
  191.                 $page $this->ticketing->curl("packs?event=".$ticket["event"]["id"]."&onSale=true&category=".$ticket["pack"]["category"]["id"], "normal", array(), "GET");
  192.                 $sold $this->ticketing->curl("packs?event=".$ticket["event"]["id"]."&onSale=false&category=".$ticket["pack"]["category"]["id"], "normal", array(), "GET");
  193.             }
  194.             else{
  195.                 $page $this->ticketing->curl("tickets?event=".$ticket["event"]["id"]."&onSale=true&pack=null&maxPrice=".$ticket["price"]."&minPrice=".$ticket["price"], "normal", array(), "GET");
  196.                 $sold $this->ticketing->curl("tickets?event=".$ticket["event"]["id"]."&onSale=false&pack=null&maxPrice=".$ticket["price"]."&minPrice=".$ticket["price"], "normal", array(), "GET");
  197.             }
  198.             $history $this->ticketing->curl("tickets/activity?ticket=".$ticketId"normal", array(), "GET");
  199.             foreach($history["activity"] as $key => $activity){
  200.                 if(array_key_exists("newUser"$activity) && !empty($activity["newUser"])){
  201.                     $auxUser $em->getRepository('App:User')->findOneBy(['user_id' => $activity["newUser"]["userId"]]);
  202.                     $alias = !empty($auxUser->getAlias()) ? $auxUser->getAlias() : "(unknown)";
  203.                     $history["activity"][$key]["newUser"]["alias"] = $alias;
  204.                 }
  205.             }
  206.         }
  207.         else{
  208.             //Si es un ticket en venta
  209.             if(!empty($ticket["pack"])){
  210.                 $this->addFlash(
  211.                     'notice',
  212.                     'Ticket no a la venta en este momento'
  213.                 );
  214.                 return $this->redirectToRoute('home');
  215.             }
  216.             $page $this->ticketing->curl("tickets?event=".$ticket["event"]["id"]."&onSale=true&pack=null&maxPrice=".$ticket["price"]."&minPrice=".$ticket["price"], "normal", array(), "GET");
  217.             if($page && array_key_exists("total"$page)){
  218.                 $max=$page["total"];
  219.                 if($max>15){
  220.                     $max=15;
  221.                 }
  222.             }
  223.             else{
  224.                 $max=1;
  225.             }
  226.             $sold $this->ticketing->curl("tickets?event=".$ticket["event"]["id"]."&onSale=false&pack=null&maxPrice=".$ticket["price"]."&minPrice=".$ticket["price"], "normal", array(), "GET");
  227.         }
  228.         if($request->get("quantity")){
  229.             if($request->get("quantity")>$max){
  230.                 $this->addFlash(
  231.                     'notice',
  232.                     'Ha solicitado más unidades de las disponibles, se le ha ajustado la cantidad al máximo'
  233.                 );
  234.                 $quantity=$max;
  235.             }
  236.             else{
  237.                 $quantity=$request->get("quantity");
  238.             }
  239.         }
  240.         $routeName $request->attributes->get('_route');
  241.         return $this->render('tickets/'.$routeName.'.html.twig', [
  242.             "ticket" => $ticket,
  243.             "max" => $max,
  244.             "onSale" => $page["total"],
  245.             "sold" => $sold["total"],
  246.             "quantity" => $quantity,
  247.             "userId" => $userId,
  248.             "history" => $history["activity"]
  249.         ]);
  250.     }
  251.     /**
  252.      * @Route("/ticket-buy/{ticketId}", name="ticket-buy")
  253.      */
  254.     public function ticketBuy(Request $request,$ticketId): Response
  255.     {
  256.         $csession $request->getSession();
  257.         $userId=$this->functions->getUserLogged();
  258.         if(!$userId)
  259.             return $this->redirectToRoute('home');
  260.         $userId=false;
  261.         // eXCxKChv is secret code discount
  262.         if (!empty($request->get('eXCxKChv'))) {
  263.             $discount = (int)$request->get('eXCxKChv');
  264.             $csession->set('coupon'$request->get('code'));
  265.         } else {
  266.             $discount 0;
  267.         }
  268.         $type="tickets";
  269.         $max=0;
  270.         $item $this->ticketing->curl("tickets/".$ticketId"normal", array(), "GET");
  271.         if(!$item || $item["code"]!="200"){
  272.             $this->addFlash(
  273.                 'notice',
  274.                 'No se puede acceder al ticket'
  275.             );
  276.             return $this->redirectToRoute('home');
  277.         }
  278.         //Si es un ticket a venta de la plataforma y se trata de un pack
  279.         if(!$item["user"] && !empty($item["pack"])){
  280.             $this->addFlash(
  281.                 'notice',
  282.                 'Ticket no a la venta en este momento'
  283.             );
  284.             return $this->redirectToRoute('home');
  285.         }
  286.         $userId=$this->functions->getUserLogged();
  287.         //Si el ticket pertenece a un usuario y no está a la venta
  288.         if($item["user"] && !$item["onSaleUser"]){
  289.             $this->addFlash(
  290.                 'notice',
  291.                 'Ticket no a la venta en este momento'
  292.             );
  293.             return $this->redirectToRoute('home');
  294.         }
  295.         //Si el usuario que compra es el mismo que el que vende
  296.         if(!empty($item["user"]["userId"]) && ($userId && $item["user"]["userId"] == $userId)) {
  297.             $this->addFlash(
  298.                 'notice',
  299.                 'No puede comprar un ticket de su propiedad'
  300.             );
  301.             return $this->redirectToRoute('home');
  302.         }
  303.         if($item["price"]>=8000){
  304.             return $this->redirectToRoute('key-detail',array("keyId" => $ticketId));
  305.         }
  306.         if(!$item["user"]){
  307.             $page $this->ticketing->curl("tickets?onSale=true&pack=null&maxPrice=".$item["price"]."&minPrice=".$item["price"], "normal", array(), "GET");
  308.             if($page && array_key_exists("total"$page)){
  309.                 $max=$page["total"];
  310.                 if($max>15){
  311.                     $max=15;
  312.                 }
  313.             }
  314.             else{
  315.                 $max=1;
  316.             }
  317.         }
  318.         else{
  319.             $max=1;
  320.         }
  321.         if(!$request->get("quantity") || $request->get("quantity")<|| $request->get("quantity")>$max){
  322.             return $this->redirectToRoute('home');
  323.         }
  324.         // eXCxKChv is secret code discount
  325.         if (empty($request->get('eXCxKChv')))
  326.             $discount $this->getDiscount($ticketId);
  327.         $checkoutPublicKey $_ENV['PAYPAL_CLIENT_ID'];
  328.         $from_argentina false;
  329.         $ip $this->functions->get_user_ip();
  330.         if($ip AND function_exists('geoip_country_code_by_name')) {
  331.             $country_code geoip_country_code_by_name($ip);
  332.             if($country_code == 'AR') {
  333.                 $from_argentina true;
  334.                 $checkoutPublicKey $_ENV['MERCADOPAGO_PUBLIC_KEY'];
  335.             }
  336.         }
  337.         $version $this->functions->addAppVersion();
  338.         return $this->render('tickets/ticket-buy.html.twig', [
  339.             "item" => $item,
  340.             "quantity" => $request->get("quantity"),
  341.             "type" => $type,
  342.             "image" => $item["image"],
  343.             "discount" => $discount,
  344.             "env" => $_ENV['APP_ENV'],
  345.             "from_argentina" => $from_argentina,
  346.             "checkout_public_key" => $checkoutPublicKey,
  347.             'conversion' => Functions::CONVERSION,
  348.             'version' => $version
  349.         ]);
  350.     }
  351.     /**
  352.      * @Route("/ticket-buy/test/{payment_gateway}/{ticketId}", requirements={"payment_gateway": "paypal|mercadopago"})
  353.      */
  354.     public function ticket_buy_test(Request $request,$ticketId$payment_gateway): Response
  355.     {
  356.         $csession $request->getSession();
  357.         $session $request->getSession();
  358.         $userId=$this->functions->getUserLogged();
  359.         if(!$userId) {
  360.             return $this->redirectToRoute('home');
  361.         }
  362.         if($request->get("ref")){
  363.             $csession->set('ref'$request->get("ref"));
  364.         }
  365.         $userId=false;
  366.         $discount=0;
  367.         $type="tickets";
  368.         $max=0;
  369.         $item $this->ticketing->curl("tickets/".$ticketId"normal", array(), "GET");
  370.         if(!$item || $item["code"]!="200"){
  371.             $this->addFlash(
  372.                 'notice',
  373.                 'No se puede acceder al ticket'
  374.             );
  375.             return $this->redirectToRoute('home');
  376.         }
  377.         //Si es un ticket a venta de la plataforma y se trata de un pack
  378.         if(!$item["user"] && !empty($item["pack"])){
  379.             $this->addFlash(
  380.                 'notice',
  381.                 'Ticket no a la venta en este momento'
  382.             );
  383.             return $this->redirectToRoute('home');
  384.         }
  385.         //Si el ticket pertenece a un usuario y no está a la venta
  386.         if($item["user"] && !$item["onSaleUser"]){
  387.             $this->addFlash(
  388.                 'notice',
  389.                 'Ticket no a la venta en este momento'
  390.             );
  391.             return $this->redirectToRoute('home');
  392.         }
  393.         //Si el usuario que compra es el mismo que el que vende
  394.         if(!empty($item["user"]["userId"]) && ($userId && $item["user"]["userId"] == $userId)) {
  395.             $this->addFlash(
  396.                 'notice',
  397.                 'No puede comprar un ticket de su propiedad'
  398.             );
  399.             return $this->redirectToRoute('home');
  400.         }
  401.         if($item["price"]>=8000){
  402.             return $this->redirectToRoute('key-detail',array("keyId" => $ticketId));
  403.         }
  404.         if(!$item["user"]){
  405.             $page $this->ticketing->curl("tickets?onSale=true&pack=null&maxPrice=".$item["price"]."&minPrice=".$item["price"], "normal", array(), "GET");
  406.             if($page && array_key_exists("total"$page)){
  407.                 $max=$page["total"];
  408.                 if($max>15){
  409.                     $max=15;
  410.                 }
  411.             }
  412.             else{
  413.                 $max=1;
  414.             }
  415.         }
  416.         else{
  417.             $max=1;
  418.         }
  419.         if(!$request->get("quantity") || $request->get("quantity")<|| $request->get("quantity")>$max){
  420.             return $this->redirectToRoute('home');
  421.         }
  422.         if($csession->get('ref') && !$item["user"]){
  423.             $discount=25;
  424.         }
  425.         $checkoutPublicKey $_ENV['PAYPAL_CLIENT_ID'];
  426.         $from_argentina false;
  427. /*
  428.         $ip = $this->functions->get_user_ip();
  429.         if($ip) {
  430.             $country_code = geoip_country_code_by_name($ip);
  431.             if($country_code == 'AR') {
  432.                 $from_argentina = true;
  433.                 $checkoutPublicKey = $_ENV['MERCADOPAGO_PUBLIC_KEY'];
  434.             }
  435.         }
  436. */
  437.         if($payment_gateway == 'mercadopago') {
  438.             $checkoutPublicKey $_ENV['MERCADOPAGO_PUBLIC_KEY'];
  439.             $from_argentina true;
  440.         }
  441.         return $this->render('tickets/ticket-buy-test.html.twig', [
  442.             "item" => $item,
  443.             "quantity" => $request->get("quantity"),
  444.             "type" => $type,
  445.             "image" => $item["image"],
  446.             "discount" => $discount,
  447.             "from_argentina" => $from_argentina,
  448.             "checkout_public_key" => $checkoutPublicKey,
  449.             "env" => $_ENV['APP_ENV'],            
  450.             'conversion' => Functions::CONVERSION
  451.         ]);
  452.     }
  453.     /**
  454.      * @Route("/keys", name="keys")
  455.      */
  456.     public function keys(Request $request): Response
  457.     {
  458.         $session $request->getSession();
  459.         if($request->get("ref")){
  460.             $session->set('ref'$request->get("ref"));
  461.         }
  462.         $keys $this->ticketing->curl("tickets?limit=3&orderBy=price&order=desc""normal", array(), "GET");
  463.         return $this->render('keys/keys.html.twig', [
  464.             'keys' => $keys["tickets"]
  465.         ]);
  466.     }
  467.     /**
  468.      * @Route("/key-detail/{keyId}", name="key-detail")
  469.      */
  470.     public function keyDetail(Request $request,$keyId): Response
  471.     {
  472.         $session $request->getSession();
  473.         if($request->get("ref")){
  474.             $session->set('ref'$request->get("ref"));
  475.         }
  476.         $key $this->ticketing->curl("tickets/".$keyId"normal", array(), "GET");
  477.         return $this->render('keys/key-detail.html.twig', [
  478.             "key" => $key
  479.         ]);
  480.     }
  481.     /**
  482.      * @Route("/key-request/{keyId}", name="key-request")
  483.      */
  484.     public function keyRequest(Request $requestMailerInterface $mailer$keyId): Response
  485.     {
  486.         $key $this->ticketing->curl("tickets/".$keyId"normal", array(), "GET");
  487.         if($request->get('send-form')){
  488.             $name $request->get('name');
  489.             $surname $request->get('surname');
  490.             $phone $request->get('phone');
  491.             $email $request->get('email');
  492.             $key $request->get('key');
  493.             $mail = (new TemplatedEmail())
  494.                 ->from($this->getParameter('mailer_from'))
  495.                 ->to($this->getParameter('mailer_contact'))
  496.                 ->subject('DBT - Solicitud Key')
  497.                 ->htmlTemplate('mail/key-request.html.twig')
  498.                 ->context([
  499.                     'name' => $name,
  500.                     'surname' => $surname,
  501.                     'phone' => $phone,
  502.                     'correo' => $email,
  503.                     'key' => $key
  504.                 ]);
  505.             $mailer->send($mail);
  506.             $this->addFlash(
  507.                 'success',
  508.                 'Solicitud enviada'
  509.             );
  510.             return $this->redirectToRoute('home');
  511.         }
  512.         return $this->render('ticket/key-request.html.twig', [
  513.             "key" => $key
  514.         ]);
  515.     }
  516.     /**
  517.      * @Route("/ticket-transfer/{ticketId}", name="ticket-transfer")
  518.      */
  519.     public function ticket_transfer(Request $requestMailerInterface $mailer$ticketId)
  520.     {
  521.         $em $this->doctrine->getManager();
  522.         $user=$this->functions->getUserLogged();
  523.         if(!$user){
  524.             $this->addFlash(
  525.                 'notice',
  526.                 'Debe iniciar sesión como usuario'
  527.             );
  528.             return new JsonResponse([
  529.                 'status' => false,
  530.                 'message' => '#ERROR1#',
  531.                 'data' => []
  532.             ], 403);
  533.         }
  534.         if(!$request->get("user")){
  535.             return new JsonResponse([
  536.                 'status' => false,
  537.                 'message' => 'El email no ha sido especificado',
  538.                 'data' => []
  539.             ], 403);
  540.         }
  541.         if(!filter_var($request->get("user"), FILTER_VALIDATE_EMAIL)) {
  542.             return new JsonResponse([
  543.                 'status' => false,
  544.                 'message' => 'No es un email válido',
  545.                 'data' => []
  546.             ], 403);
  547.         }
  548.         if($user==$request->get("user")){
  549.             return new JsonResponse([
  550.                 'status' => false,
  551.                 'message' => 'No puede enviarse la entrada a sí mismo',
  552.                 'data' => []
  553.             ], 403);
  554.         }
  555.         $ticket $this->ticketing->curl("tickets/".$ticketId"normal", array(), "GET");
  556.         if(!$ticket || $ticket["code"]!="200"){
  557.             $this->addFlash(
  558.                 'notice',
  559.                 'No se puede acceder al ticket'
  560.             );
  561.             return $this->redirectToRoute('home');
  562.         }
  563.         if($ticket["user"]["userId"]!=$user){
  564.             $this->addFlash(
  565.                 'notice',
  566.                 'No se puede acceder a este ticket'
  567.             );
  568.             return $this->redirectToRoute('home');
  569.         }
  570.         $wh_token=bin2hex(random_bytes(45));
  571.         $transfer $this->ticketing->curl("tickets/".$ticketId."/transfer""normal", array("token" => $wh_token"user" => $request->get("user")), "PATCH");
  572.         if($transfer["code"]!="200"){
  573.             return new JsonResponse([
  574.                 'status' => false,
  575.                 'message' => 'El ticket no ha podido transferirse en este momento. Vuelva a intentarlo más tarde',
  576.                 'data' => []
  577.             ], 403);
  578.         }
  579.         if(array_key_exists('registerCode'$transfer)){
  580.             $objUser $em->getRepository(User::class)->findOneBy(['user_id' => $request->get("user")]);
  581.             if(!$objUser){
  582.                 $objUser = new User();
  583.                 $objUser->setUserId($request->get("user"));
  584.                 $objUser->setCreatedAt(new \DateTime());
  585.                 $em->persist($objUser);
  586.                 $em->flush();
  587.             }
  588.             $email = (new TemplatedEmail())
  589.                 ->from($this->getParameter('mailer_from'))
  590.                 ->to($request->get("user"))
  591.                 ->subject('DBT - Entradas recibidas')
  592.                 ->htmlTemplate('mail/register2.html.twig')
  593.                 ->context([
  594.                     'userId' => $request->get("user"),
  595.                     'registerCode' => $transfer["registerCode"],
  596.                     'event' => $ticket["event"]["name"]
  597.                 ]);
  598.         } else {
  599.             $email = (new TemplatedEmail())
  600.                 ->from($this->getParameter('mailer_from'))
  601.                 ->to($request->get("user"))
  602.                 ->subject('DBT - Entradas recibidas')
  603.                 ->htmlTemplate('mail/receive-tickets.html.twig')
  604.                 ->context([
  605.                     'event' => $ticket["event"]["name"]
  606.                 ]);
  607.         }
  608.         try {
  609.             $mailer->send($email);
  610.         } catch (\Exception $e) {
  611.             $status 'sender_error';
  612.         }
  613.         return new JsonResponse([
  614.             'status' => true,
  615.             'message' => 'El ticket se ha enviado con éxito'
  616.         ]);
  617.     }
  618.     /**
  619.      * @Route("/ticket-sell/{ticketId}", name="ticket-sell")
  620.      */
  621.     public function ticket_sell(Request $requestMailerInterface $mailer$ticketId)
  622.     {
  623.         $em $this->doctrine->getManager();
  624.         $user=$this->functions->getUserLogged();
  625.         if(!$user){
  626.             $this->addFlash(
  627.                 'notice',
  628.                 'Debe iniciar sesión como usuario'
  629.             );
  630.             return new JsonResponse([
  631.                 'status' => false,
  632.                 'message' => '#ERROR1#',
  633.                 'data' => []
  634.             ], 403);
  635.         }
  636.         if(!$request->get("price")){
  637.             return new JsonResponse([
  638.                 'status' => false,
  639.                 'message' => 'El precio no ha sido especificado',
  640.                 'data' => []
  641.             ], 403);
  642.         }
  643.         $ticket $this->ticketing->curl("tickets/".$ticketId"normal", array(), "GET");
  644.         if(!$ticket || $ticket["code"]!="200"){
  645.             return new JsonResponse([
  646.                 'status' => false,
  647.                 'message' => 'No se puede acceder al ticket',
  648.                 'data' => []
  649.             ], 403);
  650.         }
  651.         if($ticket["user"]["userId"]!=$user){
  652.             return new JsonResponse([
  653.                 'status' => false,
  654.                 'message' => 'No se puede acceder al ticket',
  655.                 'data' => []
  656.             ], 403);
  657.         }
  658.         $sell $this->ticketing->curl("sales""normal", array("ticket" => $ticketId"price" => $request->get("price")), "POST");
  659.         if($sell["code"]!="200"){
  660.             return new JsonResponse([
  661.                 'status' => false,
  662.                 'message' => 'El ticket no ha podido ponserse en venta. Vuelva a intentarlo más tarde',
  663.                 'data' => []
  664.             ], 403);
  665.         }
  666.         return new JsonResponse([
  667.             'status' => true,
  668.             'message' => 'El ticket se ha puesto en venta satisfactoriamente'
  669.         ]);
  670.     }
  671.     /**
  672.      * @Route("/ticket-retire-sell/{ticketId}", name="ticket-retire-sell")
  673.      */
  674.     public function ticket_retire_sell(Request $request$ticketId)
  675.     {
  676.         $em $this->doctrine->getManager();
  677.         $user=$this->functions->getUserLogged();
  678.         if(!$user){
  679.             $this->addFlash(
  680.                 'notice',
  681.                 'Debe iniciar sesión como usuario'
  682.             );
  683.             return new JsonResponse([
  684.                 'status' => false,
  685.                 'message' => '#ERROR1#',
  686.                 'data' => []
  687.             ], 403);
  688.         }
  689.         $ticket $this->ticketing->curl("tickets/".$ticketId"normal", array(), "GET");
  690.         if(!$ticket || $ticket["code"]!="200"){
  691.             return new JsonResponse([
  692.                 'status' => false,
  693.                 'message' => 'No se puede acceder al ticket',
  694.                 'data' => []
  695.             ], 403);
  696.         }
  697.         if($ticket["user"]["userId"]!=$user){
  698.             return new JsonResponse([
  699.                 'status' => false,
  700.                 'message' => 'No se puede acceder al ticket',
  701.                 'data' => []
  702.             ], 403);
  703.         }
  704.         $sell $this->ticketing->curl("sales/".$ticketId"normal", array(), "DELETE");
  705.         if($sell["code"]!="200"){
  706.             return new JsonResponse([
  707.                 'status' => false,
  708.                 'message' => 'El ticket no ha podido retirarse de la venta. Vuelva a intentarlo más tarde',
  709.                 'data' => []
  710.             ], 403);
  711.         }
  712.         return new JsonResponse([
  713.             'status' => true,
  714.             'message' => 'El ticket se ha retirado de la venta satisfactoriamente'
  715.         ]);
  716.     }
  717.     /**
  718.      * @Route("/ticket-activation/{ticketId}", name="ticket-activation")
  719.      */
  720.     public function ticket_activation(Request $requestMailerInterface $mailer$ticketId)
  721.     {
  722.         $em $this->doctrine->getManager();
  723.         $user=$this->functions->getUserLogged();
  724.         if(!$user){
  725.             $this->addFlash(
  726.                 'notice',
  727.                 'Debe iniciar sesión como usuario'
  728.             );
  729.             return new JsonResponse([
  730.                 'status' => false,
  731.                 'message' => '#ERROR1#',
  732.                 'data' => []
  733.             ], 403);
  734.         }
  735.         $ticket $this->ticketing->curl("tickets/".$ticketId"normal", array(), "GET");
  736.         if(!$ticket || $ticket["code"]!="200"){
  737.             $this->addFlash(
  738.                 'notice',
  739.                 'No se puede acceder al QR'
  740.             );
  741.             return $this->redirectToRoute('home');
  742.         }
  743.         if($ticket["user"]["userId"]!=$user){
  744.             $this->addFlash(
  745.                 'notice',
  746.                 'No se puede acceder a este ticket'
  747.             );
  748.             return $this->redirectToRoute('home');
  749.         }
  750.         if(!$ticket["active"]){
  751.             $event $this->ticketing->curl("events/".$ticket["event"]["id"], "normal", array(), "GET");
  752.             if(!$event || $event["code"]!="200"){
  753.                 $this->addFlash(
  754.                     'notice',
  755.                     'No se puede acceder al QR'
  756.                 );
  757.                 return $this->redirectToRoute('home');
  758.             }
  759.             $ticket $this->ticketing->curl("tickets/".$ticketId."/activate""normal", array("latitude" => $event["latitude"], "longitude" => $event["longitude"]), "PATCH");
  760.             if($ticket["code"]!="200"){
  761.                 return new JsonResponse([
  762.                     'status' => false,
  763.                     'message' => $ticket["message"],
  764.                     'data' => []
  765.                 ], 403);
  766.             }
  767.         }
  768.         $qr = new QrCode($ticket["accessCode"]);
  769.         return new JsonResponse([
  770.             'status' => true,
  771.             'accessCode' => $qr->writeDataUri()
  772.         ]);
  773.     }
  774.     /**
  775.      * @Route("/view-qr/{ticketId}", name="view-qr")
  776.      */
  777.     public function view_qr(Request $requestMailerInterface $mailer$ticketId)
  778.     {
  779.         $em $this->doctrine->getManager();
  780.         $user=$this->functions->getUserLogged();
  781.         if(!$user){
  782.             $this->addFlash(
  783.                 'notice',
  784.                 'Debe iniciar sesión como usuario'
  785.             );
  786.             return $this->redirectToRoute('login');
  787.         }
  788.         $ticket $this->ticketing->curl("tickets/".$ticketId"normal", array(), "GET");
  789.         if(!$ticket || $ticket["code"]!="200" || !$ticket["active"]){
  790.             $this->addFlash(
  791.                 'notice',
  792.                 'No se puede acceder al QR'
  793.             );
  794.             return $this->redirectToRoute('home');
  795.         }
  796.         if($ticket["user"]["userId"]!=$user){
  797.             $this->addFlash(
  798.                 'notice',
  799.                 'No se puede acceder a este ticket'
  800.             );
  801.             return $this->redirectToRoute('home');
  802.         }
  803.         $qr = new QrCode($ticket["accessCode"]);
  804.         // Configure Dompdf according to your needs
  805.         $pdfOptions = new Options();
  806.         $pdfOptions->set('defaultFont''Arial');
  807.         $pdfOptions->set('isRemoteEnabled'TRUE);
  808.         $pdfOptions->set('isHtml5ParserEnabled'TRUE);
  809.         // Instantiate Dompdf with our options
  810.         $dompdf = new Dompdf($pdfOptions);
  811.         // Retrieve the HTML generated in our twig file
  812.         $html $this->renderView('mail/view-qr.html.twig', [
  813.             "ticket" => $ticket
  814.         ]);
  815.         // Load HTML to Dompdf
  816.         $dompdf->loadHtml($html);
  817.         // (Optional) Setup the paper size and orientation 'portrait' or 'portrait'
  818.         $dompdf->setPaper('A4''portrait');
  819.         // Render the HTML as PDF
  820.         $dompdf->render();
  821.         // Output the generated PDF to Browser (force download)
  822.         $dompdf->stream("ticket-".$ticket["id"].".pdf", [
  823.             "Attachment" => true
  824.         ]);
  825.     }
  826.     /**
  827.      * @Route("/select-ticket", name="select-ticket")
  828.      */
  829.     public function selectTicket(Request $request): Response
  830.     {
  831.         //Keep url for url referrals
  832.         $session $request->getSession();
  833.         if($request->get("ref")){
  834.             $session->set('ref'$request->get("ref"));
  835.         }
  836.         return $this->redirectToRoute('events');
  837.     }
  838.     /**
  839.      * @Route("/ticket-recover/{ticketId}", name="ticket-recover")
  840.      */
  841.     public function ticket_recover(Request $requestMailerInterface $mailer$ticketId)
  842.     {
  843.         $em     $this->doctrine->getManager();
  844.         $user   $this->functions->getUserLogged();
  845.         if(!$user){
  846.             $this->addFlash(
  847.                 'notice',
  848.                 'Debe iniciar sesión como usuario'
  849.             );
  850.             return new JsonResponse([
  851.                 'status'    => false,
  852.                 'message'   => '#ERROR1#',
  853.                 'data'      => []
  854.             ], 403);
  855.         }
  856.         $ticket $this->ticketing->curl("tickets/".$ticketId"normal", [], "GET");
  857.         if(!$ticket || $ticket["code"] != "200") {
  858.             $this->addFlash(
  859.                 'notice',
  860.                 'No se puede acceder al ticket'
  861.             );
  862.             return $this->redirectToRoute('home');
  863.         }
  864.         $wh_token bin2hex(random_bytes(45));
  865.         $transfer $this->ticketing->curl("tickets/".$ticketId."/recover""normal", ["token" => $wh_token"oldUserId" => $request->get("oldUserId"), "newUserId" => $request->get("newUserId")], "PATCH");
  866.         if($transfer["code"] != "200") {
  867.             return new JsonResponse([
  868.                 'status'    => false,
  869.                 'message'   => 'El ticket no ha podido recuperarse en este momento. Vuelva a intentarlo más tarde',
  870.                 'data'      => []
  871.             ], 403);
  872.         }
  873.         return new JsonResponse([
  874.             'status' => true,
  875.             'message' => 'El ticket se ha recuperado con éxito '$transfer['status_description']
  876.         ]);
  877.     }
  878.     /**
  879.      * @param $sintax
  880.      * @param $onSale
  881.      * @param $event
  882.      * @return array|mixed
  883.      */
  884.     private function onSaleTrueFalse($sintax$onSale$request)
  885.     {
  886.         // On sale false
  887.         if ($onSale) {
  888.             if ($request->get("saleuser")) {
  889.                 $sintax .= "&onSaleByUser=true";
  890.             } else {
  891.                 $sintax .= "&onSale=true";
  892.             }
  893.         } else {
  894.             $sintax .= "&onSale=false";
  895.         }
  896.         if ($request->get("event"))
  897.             $event $request->get("event");
  898.         // Searching params for tickets that are not for sale
  899.         $sintaxAdd = !$onSale '&onSale=false&event=' $event '';
  900.         $page $this->ticketing->curl("tickets?orderBy=price" $sintax"normal", [], "GET");
  901.         foreach ($page["tickets"] as $key => $ticket) {
  902.             if (!$onSale) {
  903.                 $aux $this->ticketing->curl("tickets?onSale=false&limit=1&maxPrice=" . (float)$ticket["price"] . "&minPrice=" . (float)$ticket["price"] . $sintaxAdd"normal", [], "GET");
  904.                 $auxTotal $this->ticketing->curl("tickets?limit=1000&maxPrice=" . (float)$ticket["price"] . "&minPrice=" . (float)$ticket["price"] . "&event=" $event"normal", [], "GET");
  905.             } else {
  906.                 $aux $this->ticketing->curl("tickets?onSale=true&limit=1&maxPrice=" . (float)$ticket["price"] . "&minPrice=" . (float)$ticket["price"], "normal", [], "GET");
  907.             }
  908.             $page["tickets"][$key]["quantity"] = $aux["total"];
  909.             if ($page["tickets"][$key]["quantity"] > 15)
  910.                 $page["tickets"][$key]["quantity"] = 15;
  911.             // Delete block of tickets that are not fully sold out
  912.             if (isset($auxTotal) && $auxTotal['total'] != $aux['total'])
  913.                 unset($page['tickets'][$key]);
  914.             // Free tickets or tickets with price 0
  915.             if ((int)$ticket['price'] == || (!empty($page["tickets"][$key]["category"] && $page["tickets"][$key]["category"]["name"] == 'free') ))
  916.                 unset($page['tickets'][$key]);
  917.         }
  918.         return $page;
  919.     }
  920.     /**
  921.      * @param $id
  922.      * @return int|mixed
  923.      */
  924.     private function getDiscount($id){
  925.         $user $this->functions->getUserLogged();
  926.         $tickets $this->ticketing->curl("tickets/activity?destination=" $user "&order=asc&limit=1""normal", [], "GET");
  927.         if (empty($tickets))
  928.             return 0;
  929.         $category = !empty($tickets['activity'][0]['ticket']['category']) ? strtolower($tickets['activity'][0]['ticket']['category']['name']) : '';
  930.         $discounts = [];
  931.         // First ticket buyed
  932.         switch ($category) {
  933.             case 'congreso':
  934.                 $discounts = [
  935.                     'congreso' => 0,
  936.                     'taller4' => 10,
  937.                     'taller8' => 15,
  938.                 ];
  939.                 break;
  940.             case 'taller4':
  941.                 $discounts = [
  942.                     'congreso' => 4,
  943.                     'taller4' => 10,
  944.                     'taller8' => 15,
  945.                 ];
  946.                 break;
  947.             case 'taller8':
  948.                 $discounts = [
  949.                     'congreso' => 9,
  950.                     'taller4' => 10,
  951.                     'taller8' => 0,
  952.                 ];
  953.                 break;
  954.         }
  955.         // Ticket to buy
  956.         $ticket $this->ticketing->curl("tickets/" $id"normal", array(), "GET");
  957.         $category = !empty($ticket['category']['name']) ? strtolower($ticket['category']['name']) : '';
  958.         $type '';
  959.         switch ($category) {
  960.             case 'congreso':
  961.                 $type 'congreso';
  962.                 break;
  963.             case 'taller4':
  964.                 $type 'taller4';
  965.                 break;
  966.             case 'taller8':
  967.                 $type 'taller8';
  968.                 break;
  969.         }
  970.         return array_key_exists($type$discounts) ? $discounts[$type] : 0;
  971.     }
  972. }