<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Bridge\Twig\Mime\TemplatedEmail;
use Symfony\Component\Mime\Email;
use Symfony\Component\HttpFoundation\{Request, Response};
use Symfony\Component\Routing\Annotation\Route;
use App\Utils\Ticketing;
use App\Utils\Functions;
use App\Entity\User;
use Symfony\Component\HttpFoundation\JsonResponse;
use Endroid\QrCode\QrCode;
use Dompdf\Dompdf;
use Dompdf\Options;
use Doctrine\Persistence\ManagerRegistry;
class TicketController extends AbstractController
{
/**
* @var Ticketing
*/
private $ticketing;
/**
* @var Functions
*/
private $functions;
/**
* @var ManagerRegistry
*/
private $doctrine;
/**
* @param Ticketing $ticketing
* @param Functions $functions
* @param ManagerRegistry $doctrine
*/
public function __construct(Ticketing $ticketing, Functions $functions, ManagerRegistry $doctrine)
{
$this->ticketing = $ticketing;
$this->functions = $functions;
$this->doctrine = $doctrine;
}
/**
* @Route("/tickets", name="tickets")
*/
public function tickets(Request $request): Response
{
$session = $request->getSession();
if($request->get("ref")){
$session->set('ref', $request->get("ref"));
}
$events = $this->ticketing->curl("events", "normal", array(), "GET");
$keys = $this->ticketing->curl("tickets?limit=3&orderBy=price&order=desc", "normal", array(), "GET");
$filters = array_filter($request->query->all());
$request->request->set('saleuser', 1);
return $this->render('tickets/tickets.html.twig', [
'events' => $events["events"],
'filters' => $filters,
'keys' => $keys["tickets"]
]);
}
/**
* @Route("/include-tickets", name="include_tickets")
*/
public function includeTickets(Request $request): Response
{
$session = $request->getSession();
$user=$this->functions->getUserLogged();
$check_user_session = true;
if(!$user) {
$check_user_session = false;
}
if (!$request->get("saleuser")) {
$sintax = "&pack=null";
} else {
$sintax = "";
}
if ($request->get("type")) {
switch ($request->get("type")) {
case "2":
$sintax .= "&maxPrice=1000";
break;
case "4":
$sintax .= "&minPrice=1000";
break;
default:
$sintax .= "";
break;
}
}
if ($request->get("order") && $request->get("order") == "2") {
$sintax .= "&order=desc";
} else {
$sintax .= "&order=asc";
}
if ($request->get("name")) {
$sintax .= "&name=" . urlencode($request->get("name"));
}
if ($request->get("price_equal")) {
$sintax .= "&maxPrice=" . $request->get("price_equal") . "&minPrice=" . $request->get("price_equal");
}
if ($request->get("offset")) {
$sintax .= "&offset=" . $request->get("offset");
}
if ($request->get("limit")) {
$sintax .= "&limit=" . $request->get("limit");
} else {
$sintax .= "&limit=12";
}
if ($request->get("event")) {
$sintax .= "&event=" . $request->get("event");
}
if ($request->get("group")) {
$sintax .= "&groupBy=price";
}
// Geolocation ip
$from_argentina = false;
$ip = $this->functions->get_user_ip();
if($ip AND function_exists('geoip_country_code_by_name')) {
$country_code = geoip_country_code_by_name($ip);
if($country_code == 'AR')
$from_argentina = true;
}
if ($request->get("small")) {
$page = $this->onSaleTrueFalse($sintax, true, $request);
$pageSoldOut = $this->onSaleTrueFalse($sintax, false, $request);
return $this->render('events/include-event-tickets.html.twig', [
'page' => $page,
'pageSoldOut' => $pageSoldOut,
'check_user_session' => $check_user_session,
'from_argentina' => $from_argentina,
'conversion' => Functions::CONVERSION
]);
} else {
if ($request->get("saleuser")) {
$sintax .= "&onSaleByUser=true";
} else {
$sintax .= "&onSale=true";
}
$page = $this->ticketing->curl("tickets?orderBy=price" . $sintax, "normal", array(), "GET");
return $this->render('tickets/include-tickets.html.twig', [
'page' => $page,
'from_argentina' => $from_argentina,
'conversion' => Functions::CONVERSION
]);
}
}
/**
* @Route("/ticket-detail/{ticketId}", name="ticket-detail")
* @Route("/ticket-detail-finished/{ticketId}", name="ticket-detail-finished")
*/
public function ticketDetail(Request $request,$ticketId): Response
{
$em = $this->doctrine->getManager();
$session = $request->getSession();
if($request->get("ref")){
$session->set('ref', $request->get("ref"));
}
$userId=false;
$max=0;
$quantity=1;
$history["activity"]=array();
$ticket = $this->ticketing->curl("tickets/".$ticketId, "normal", array(), "GET");
if(!$ticket || $ticket["code"]!="200"){
$this->addFlash(
'notice',
'No se puede acceder al ticket'
);
return $this->redirectToRoute('home');
}
if($ticket["price"]>=8000){
return $this->redirectToRoute('key-detail',array("keyId" => $ticketId));
}
//Si el ticket pertence a un usuario
if($ticket["user"]){
$userId=$this->functions->getUserLogged();
if(!$userId){
$this->addFlash(
'notice',
'Debe iniciar sesión como usuario'
);
return $this->redirectToRoute('access',array("redirect" => $this->generateUrl('ticket-detail',array("ticketId" => $ticketId))));
}
if($ticket["user"]["userId"]!=$userId && !$ticket["onSaleUser"]){
$this->addFlash(
'notice',
'No se puede acceder a este ticket'
);
return $this->redirectToRoute('home');
}
if(!empty($ticket["pack"])){
$page = $this->ticketing->curl("packs?event=".$ticket["event"]["id"]."&onSale=true&category=".$ticket["pack"]["category"]["id"], "normal", array(), "GET");
$sold = $this->ticketing->curl("packs?event=".$ticket["event"]["id"]."&onSale=false&category=".$ticket["pack"]["category"]["id"], "normal", array(), "GET");
}
else{
$page = $this->ticketing->curl("tickets?event=".$ticket["event"]["id"]."&onSale=true&pack=null&maxPrice=".$ticket["price"]."&minPrice=".$ticket["price"], "normal", array(), "GET");
$sold = $this->ticketing->curl("tickets?event=".$ticket["event"]["id"]."&onSale=false&pack=null&maxPrice=".$ticket["price"]."&minPrice=".$ticket["price"], "normal", array(), "GET");
}
$history = $this->ticketing->curl("tickets/activity?ticket=".$ticketId, "normal", array(), "GET");
foreach($history["activity"] as $key => $activity){
if(array_key_exists("newUser", $activity) && !empty($activity["newUser"])){
$auxUser = $em->getRepository('App:User')->findOneBy(['user_id' => $activity["newUser"]["userId"]]);
$alias = !empty($auxUser->getAlias()) ? $auxUser->getAlias() : "(unknown)";
$history["activity"][$key]["newUser"]["alias"] = $alias;
}
}
}
else{
//Si es un ticket en venta
if(!empty($ticket["pack"])){
$this->addFlash(
'notice',
'Ticket no a la venta en este momento'
);
return $this->redirectToRoute('home');
}
$page = $this->ticketing->curl("tickets?event=".$ticket["event"]["id"]."&onSale=true&pack=null&maxPrice=".$ticket["price"]."&minPrice=".$ticket["price"], "normal", array(), "GET");
if($page && array_key_exists("total", $page)){
$max=$page["total"];
if($max>15){
$max=15;
}
}
else{
$max=1;
}
$sold = $this->ticketing->curl("tickets?event=".$ticket["event"]["id"]."&onSale=false&pack=null&maxPrice=".$ticket["price"]."&minPrice=".$ticket["price"], "normal", array(), "GET");
}
if($request->get("quantity")){
if($request->get("quantity")>$max){
$this->addFlash(
'notice',
'Ha solicitado más unidades de las disponibles, se le ha ajustado la cantidad al máximo'
);
$quantity=$max;
}
else{
$quantity=$request->get("quantity");
}
}
$routeName = $request->attributes->get('_route');
return $this->render('tickets/'.$routeName.'.html.twig', [
"ticket" => $ticket,
"max" => $max,
"onSale" => $page["total"],
"sold" => $sold["total"],
"quantity" => $quantity,
"userId" => $userId,
"history" => $history["activity"]
]);
}
/**
* @Route("/ticket-buy/{ticketId}", name="ticket-buy")
*/
public function ticketBuy(Request $request,$ticketId): Response
{
$csession = $request->getSession();
$userId=$this->functions->getUserLogged();
if(!$userId)
return $this->redirectToRoute('home');
$userId=false;
// eXCxKChv is secret code discount
if (!empty($request->get('eXCxKChv'))) {
$discount = (int)$request->get('eXCxKChv');
$csession->set('coupon', $request->get('code'));
} else {
$discount = 0;
}
$type="tickets";
$max=0;
$item = $this->ticketing->curl("tickets/".$ticketId, "normal", array(), "GET");
if(!$item || $item["code"]!="200"){
$this->addFlash(
'notice',
'No se puede acceder al ticket'
);
return $this->redirectToRoute('home');
}
//Si es un ticket a venta de la plataforma y se trata de un pack
if(!$item["user"] && !empty($item["pack"])){
$this->addFlash(
'notice',
'Ticket no a la venta en este momento'
);
return $this->redirectToRoute('home');
}
$userId=$this->functions->getUserLogged();
//Si el ticket pertenece a un usuario y no está a la venta
if($item["user"] && !$item["onSaleUser"]){
$this->addFlash(
'notice',
'Ticket no a la venta en este momento'
);
return $this->redirectToRoute('home');
}
//Si el usuario que compra es el mismo que el que vende
if(!empty($item["user"]["userId"]) && ($userId && $item["user"]["userId"] == $userId)) {
$this->addFlash(
'notice',
'No puede comprar un ticket de su propiedad'
);
return $this->redirectToRoute('home');
}
if($item["price"]>=8000){
return $this->redirectToRoute('key-detail',array("keyId" => $ticketId));
}
if(!$item["user"]){
$page = $this->ticketing->curl("tickets?onSale=true&pack=null&maxPrice=".$item["price"]."&minPrice=".$item["price"], "normal", array(), "GET");
if($page && array_key_exists("total", $page)){
$max=$page["total"];
if($max>15){
$max=15;
}
}
else{
$max=1;
}
}
else{
$max=1;
}
if(!$request->get("quantity") || $request->get("quantity")<1 || $request->get("quantity")>$max){
return $this->redirectToRoute('home');
}
// eXCxKChv is secret code discount
if (empty($request->get('eXCxKChv')))
$discount = $this->getDiscount($ticketId);
$checkoutPublicKey = $_ENV['PAYPAL_CLIENT_ID'];
$from_argentina = false;
$ip = $this->functions->get_user_ip();
if($ip AND function_exists('geoip_country_code_by_name')) {
$country_code = geoip_country_code_by_name($ip);
if($country_code == 'AR') {
$from_argentina = true;
$checkoutPublicKey = $_ENV['MERCADOPAGO_PUBLIC_KEY'];
}
}
$version = $this->functions->addAppVersion();
return $this->render('tickets/ticket-buy.html.twig', [
"item" => $item,
"quantity" => $request->get("quantity"),
"type" => $type,
"image" => $item["image"],
"discount" => $discount,
"env" => $_ENV['APP_ENV'],
"from_argentina" => $from_argentina,
"checkout_public_key" => $checkoutPublicKey,
'conversion' => Functions::CONVERSION,
'version' => $version
]);
}
/**
* @Route("/ticket-buy/test/{payment_gateway}/{ticketId}", requirements={"payment_gateway": "paypal|mercadopago"})
*/
public function ticket_buy_test(Request $request,$ticketId, $payment_gateway): Response
{
$csession = $request->getSession();
$session = $request->getSession();
$userId=$this->functions->getUserLogged();
if(!$userId) {
return $this->redirectToRoute('home');
}
if($request->get("ref")){
$csession->set('ref', $request->get("ref"));
}
$userId=false;
$discount=0;
$type="tickets";
$max=0;
$item = $this->ticketing->curl("tickets/".$ticketId, "normal", array(), "GET");
if(!$item || $item["code"]!="200"){
$this->addFlash(
'notice',
'No se puede acceder al ticket'
);
return $this->redirectToRoute('home');
}
//Si es un ticket a venta de la plataforma y se trata de un pack
if(!$item["user"] && !empty($item["pack"])){
$this->addFlash(
'notice',
'Ticket no a la venta en este momento'
);
return $this->redirectToRoute('home');
}
//Si el ticket pertenece a un usuario y no está a la venta
if($item["user"] && !$item["onSaleUser"]){
$this->addFlash(
'notice',
'Ticket no a la venta en este momento'
);
return $this->redirectToRoute('home');
}
//Si el usuario que compra es el mismo que el que vende
if(!empty($item["user"]["userId"]) && ($userId && $item["user"]["userId"] == $userId)) {
$this->addFlash(
'notice',
'No puede comprar un ticket de su propiedad'
);
return $this->redirectToRoute('home');
}
if($item["price"]>=8000){
return $this->redirectToRoute('key-detail',array("keyId" => $ticketId));
}
if(!$item["user"]){
$page = $this->ticketing->curl("tickets?onSale=true&pack=null&maxPrice=".$item["price"]."&minPrice=".$item["price"], "normal", array(), "GET");
if($page && array_key_exists("total", $page)){
$max=$page["total"];
if($max>15){
$max=15;
}
}
else{
$max=1;
}
}
else{
$max=1;
}
if(!$request->get("quantity") || $request->get("quantity")<1 || $request->get("quantity")>$max){
return $this->redirectToRoute('home');
}
if($csession->get('ref') && !$item["user"]){
$discount=25;
}
$checkoutPublicKey = $_ENV['PAYPAL_CLIENT_ID'];
$from_argentina = false;
/*
$ip = $this->functions->get_user_ip();
if($ip) {
$country_code = geoip_country_code_by_name($ip);
if($country_code == 'AR') {
$from_argentina = true;
$checkoutPublicKey = $_ENV['MERCADOPAGO_PUBLIC_KEY'];
}
}
*/
if($payment_gateway == 'mercadopago') {
$checkoutPublicKey = $_ENV['MERCADOPAGO_PUBLIC_KEY'];
$from_argentina = true;
}
return $this->render('tickets/ticket-buy-test.html.twig', [
"item" => $item,
"quantity" => $request->get("quantity"),
"type" => $type,
"image" => $item["image"],
"discount" => $discount,
"from_argentina" => $from_argentina,
"checkout_public_key" => $checkoutPublicKey,
"env" => $_ENV['APP_ENV'],
'conversion' => Functions::CONVERSION
]);
}
/**
* @Route("/keys", name="keys")
*/
public function keys(Request $request): Response
{
$session = $request->getSession();
if($request->get("ref")){
$session->set('ref', $request->get("ref"));
}
$keys = $this->ticketing->curl("tickets?limit=3&orderBy=price&order=desc", "normal", array(), "GET");
return $this->render('keys/keys.html.twig', [
'keys' => $keys["tickets"]
]);
}
/**
* @Route("/key-detail/{keyId}", name="key-detail")
*/
public function keyDetail(Request $request,$keyId): Response
{
$session = $request->getSession();
if($request->get("ref")){
$session->set('ref', $request->get("ref"));
}
$key = $this->ticketing->curl("tickets/".$keyId, "normal", array(), "GET");
return $this->render('keys/key-detail.html.twig', [
"key" => $key
]);
}
/**
* @Route("/key-request/{keyId}", name="key-request")
*/
public function keyRequest(Request $request, MailerInterface $mailer, $keyId): Response
{
$key = $this->ticketing->curl("tickets/".$keyId, "normal", array(), "GET");
if($request->get('send-form')){
$name = $request->get('name');
$surname = $request->get('surname');
$phone = $request->get('phone');
$email = $request->get('email');
$key = $request->get('key');
$mail = (new TemplatedEmail())
->from($this->getParameter('mailer_from'))
->to($this->getParameter('mailer_contact'))
->subject('DBT - Solicitud Key')
->htmlTemplate('mail/key-request.html.twig')
->context([
'name' => $name,
'surname' => $surname,
'phone' => $phone,
'correo' => $email,
'key' => $key
]);
$mailer->send($mail);
$this->addFlash(
'success',
'Solicitud enviada'
);
return $this->redirectToRoute('home');
}
return $this->render('ticket/key-request.html.twig', [
"key" => $key
]);
}
/**
* @Route("/ticket-transfer/{ticketId}", name="ticket-transfer")
*/
public function ticket_transfer(Request $request, MailerInterface $mailer, $ticketId)
{
$em = $this->doctrine->getManager();
$user=$this->functions->getUserLogged();
if(!$user){
$this->addFlash(
'notice',
'Debe iniciar sesión como usuario'
);
return new JsonResponse([
'status' => false,
'message' => '#ERROR1#',
'data' => []
], 403);
}
if(!$request->get("user")){
return new JsonResponse([
'status' => false,
'message' => 'El email no ha sido especificado',
'data' => []
], 403);
}
if(!filter_var($request->get("user"), FILTER_VALIDATE_EMAIL)) {
return new JsonResponse([
'status' => false,
'message' => 'No es un email válido',
'data' => []
], 403);
}
if($user==$request->get("user")){
return new JsonResponse([
'status' => false,
'message' => 'No puede enviarse la entrada a sí mismo',
'data' => []
], 403);
}
$ticket = $this->ticketing->curl("tickets/".$ticketId, "normal", array(), "GET");
if(!$ticket || $ticket["code"]!="200"){
$this->addFlash(
'notice',
'No se puede acceder al ticket'
);
return $this->redirectToRoute('home');
}
if($ticket["user"]["userId"]!=$user){
$this->addFlash(
'notice',
'No se puede acceder a este ticket'
);
return $this->redirectToRoute('home');
}
$wh_token=bin2hex(random_bytes(45));
$transfer = $this->ticketing->curl("tickets/".$ticketId."/transfer", "normal", array("token" => $wh_token, "user" => $request->get("user")), "PATCH");
if($transfer["code"]!="200"){
return new JsonResponse([
'status' => false,
'message' => 'El ticket no ha podido transferirse en este momento. Vuelva a intentarlo más tarde',
'data' => []
], 403);
}
if(array_key_exists('registerCode', $transfer)){
$objUser = $em->getRepository(User::class)->findOneBy(['user_id' => $request->get("user")]);
if(!$objUser){
$objUser = new User();
$objUser->setUserId($request->get("user"));
$objUser->setCreatedAt(new \DateTime());
$em->persist($objUser);
$em->flush();
}
$email = (new TemplatedEmail())
->from($this->getParameter('mailer_from'))
->to($request->get("user"))
->subject('DBT - Entradas recibidas')
->htmlTemplate('mail/register2.html.twig')
->context([
'userId' => $request->get("user"),
'registerCode' => $transfer["registerCode"],
'event' => $ticket["event"]["name"]
]);
} else {
$email = (new TemplatedEmail())
->from($this->getParameter('mailer_from'))
->to($request->get("user"))
->subject('DBT - Entradas recibidas')
->htmlTemplate('mail/receive-tickets.html.twig')
->context([
'event' => $ticket["event"]["name"]
]);
}
try {
$mailer->send($email);
} catch (\Exception $e) {
$status = 'sender_error';
}
return new JsonResponse([
'status' => true,
'message' => 'El ticket se ha enviado con éxito'
]);
}
/**
* @Route("/ticket-sell/{ticketId}", name="ticket-sell")
*/
public function ticket_sell(Request $request, MailerInterface $mailer, $ticketId)
{
$em = $this->doctrine->getManager();
$user=$this->functions->getUserLogged();
if(!$user){
$this->addFlash(
'notice',
'Debe iniciar sesión como usuario'
);
return new JsonResponse([
'status' => false,
'message' => '#ERROR1#',
'data' => []
], 403);
}
if(!$request->get("price")){
return new JsonResponse([
'status' => false,
'message' => 'El precio no ha sido especificado',
'data' => []
], 403);
}
$ticket = $this->ticketing->curl("tickets/".$ticketId, "normal", array(), "GET");
if(!$ticket || $ticket["code"]!="200"){
return new JsonResponse([
'status' => false,
'message' => 'No se puede acceder al ticket',
'data' => []
], 403);
}
if($ticket["user"]["userId"]!=$user){
return new JsonResponse([
'status' => false,
'message' => 'No se puede acceder al ticket',
'data' => []
], 403);
}
$sell = $this->ticketing->curl("sales", "normal", array("ticket" => $ticketId, "price" => $request->get("price")), "POST");
if($sell["code"]!="200"){
return new JsonResponse([
'status' => false,
'message' => 'El ticket no ha podido ponserse en venta. Vuelva a intentarlo más tarde',
'data' => []
], 403);
}
return new JsonResponse([
'status' => true,
'message' => 'El ticket se ha puesto en venta satisfactoriamente'
]);
}
/**
* @Route("/ticket-retire-sell/{ticketId}", name="ticket-retire-sell")
*/
public function ticket_retire_sell(Request $request, $ticketId)
{
$em = $this->doctrine->getManager();
$user=$this->functions->getUserLogged();
if(!$user){
$this->addFlash(
'notice',
'Debe iniciar sesión como usuario'
);
return new JsonResponse([
'status' => false,
'message' => '#ERROR1#',
'data' => []
], 403);
}
$ticket = $this->ticketing->curl("tickets/".$ticketId, "normal", array(), "GET");
if(!$ticket || $ticket["code"]!="200"){
return new JsonResponse([
'status' => false,
'message' => 'No se puede acceder al ticket',
'data' => []
], 403);
}
if($ticket["user"]["userId"]!=$user){
return new JsonResponse([
'status' => false,
'message' => 'No se puede acceder al ticket',
'data' => []
], 403);
}
$sell = $this->ticketing->curl("sales/".$ticketId, "normal", array(), "DELETE");
if($sell["code"]!="200"){
return new JsonResponse([
'status' => false,
'message' => 'El ticket no ha podido retirarse de la venta. Vuelva a intentarlo más tarde',
'data' => []
], 403);
}
return new JsonResponse([
'status' => true,
'message' => 'El ticket se ha retirado de la venta satisfactoriamente'
]);
}
/**
* @Route("/ticket-activation/{ticketId}", name="ticket-activation")
*/
public function ticket_activation(Request $request, MailerInterface $mailer, $ticketId)
{
$em = $this->doctrine->getManager();
$user=$this->functions->getUserLogged();
if(!$user){
$this->addFlash(
'notice',
'Debe iniciar sesión como usuario'
);
return new JsonResponse([
'status' => false,
'message' => '#ERROR1#',
'data' => []
], 403);
}
$ticket = $this->ticketing->curl("tickets/".$ticketId, "normal", array(), "GET");
if(!$ticket || $ticket["code"]!="200"){
$this->addFlash(
'notice',
'No se puede acceder al QR'
);
return $this->redirectToRoute('home');
}
if($ticket["user"]["userId"]!=$user){
$this->addFlash(
'notice',
'No se puede acceder a este ticket'
);
return $this->redirectToRoute('home');
}
if(!$ticket["active"]){
$event = $this->ticketing->curl("events/".$ticket["event"]["id"], "normal", array(), "GET");
if(!$event || $event["code"]!="200"){
$this->addFlash(
'notice',
'No se puede acceder al QR'
);
return $this->redirectToRoute('home');
}
$ticket = $this->ticketing->curl("tickets/".$ticketId."/activate", "normal", array("latitude" => $event["latitude"], "longitude" => $event["longitude"]), "PATCH");
if($ticket["code"]!="200"){
return new JsonResponse([
'status' => false,
'message' => $ticket["message"],
'data' => []
], 403);
}
}
$qr = new QrCode($ticket["accessCode"]);
return new JsonResponse([
'status' => true,
'accessCode' => $qr->writeDataUri()
]);
}
/**
* @Route("/view-qr/{ticketId}", name="view-qr")
*/
public function view_qr(Request $request, MailerInterface $mailer, $ticketId)
{
$em = $this->doctrine->getManager();
$user=$this->functions->getUserLogged();
if(!$user){
$this->addFlash(
'notice',
'Debe iniciar sesión como usuario'
);
return $this->redirectToRoute('login');
}
$ticket = $this->ticketing->curl("tickets/".$ticketId, "normal", array(), "GET");
if(!$ticket || $ticket["code"]!="200" || !$ticket["active"]){
$this->addFlash(
'notice',
'No se puede acceder al QR'
);
return $this->redirectToRoute('home');
}
if($ticket["user"]["userId"]!=$user){
$this->addFlash(
'notice',
'No se puede acceder a este ticket'
);
return $this->redirectToRoute('home');
}
$qr = new QrCode($ticket["accessCode"]);
// Configure Dompdf according to your needs
$pdfOptions = new Options();
$pdfOptions->set('defaultFont', 'Arial');
$pdfOptions->set('isRemoteEnabled', TRUE);
$pdfOptions->set('isHtml5ParserEnabled', TRUE);
// Instantiate Dompdf with our options
$dompdf = new Dompdf($pdfOptions);
// Retrieve the HTML generated in our twig file
$html = $this->renderView('mail/view-qr.html.twig', [
"ticket" => $ticket
]);
// Load HTML to Dompdf
$dompdf->loadHtml($html);
// (Optional) Setup the paper size and orientation 'portrait' or 'portrait'
$dompdf->setPaper('A4', 'portrait');
// Render the HTML as PDF
$dompdf->render();
// Output the generated PDF to Browser (force download)
$dompdf->stream("ticket-".$ticket["id"].".pdf", [
"Attachment" => true
]);
}
/**
* @Route("/select-ticket", name="select-ticket")
*/
public function selectTicket(Request $request): Response
{
//Keep url for url referrals
$session = $request->getSession();
if($request->get("ref")){
$session->set('ref', $request->get("ref"));
}
return $this->redirectToRoute('events');
}
/**
* @Route("/ticket-recover/{ticketId}", name="ticket-recover")
*/
public function ticket_recover(Request $request, MailerInterface $mailer, $ticketId)
{
$em = $this->doctrine->getManager();
$user = $this->functions->getUserLogged();
if(!$user){
$this->addFlash(
'notice',
'Debe iniciar sesión como usuario'
);
return new JsonResponse([
'status' => false,
'message' => '#ERROR1#',
'data' => []
], 403);
}
$ticket = $this->ticketing->curl("tickets/".$ticketId, "normal", [], "GET");
if(!$ticket || $ticket["code"] != "200") {
$this->addFlash(
'notice',
'No se puede acceder al ticket'
);
return $this->redirectToRoute('home');
}
$wh_token = bin2hex(random_bytes(45));
$transfer = $this->ticketing->curl("tickets/".$ticketId."/recover", "normal", ["token" => $wh_token, "oldUserId" => $request->get("oldUserId"), "newUserId" => $request->get("newUserId")], "PATCH");
if($transfer["code"] != "200") {
return new JsonResponse([
'status' => false,
'message' => 'El ticket no ha podido recuperarse en este momento. Vuelva a intentarlo más tarde',
'data' => []
], 403);
}
return new JsonResponse([
'status' => true,
'message' => 'El ticket se ha recuperado con éxito '. $transfer['status_description']
]);
}
/**
* @param $sintax
* @param $onSale
* @param $event
* @return array|mixed
*/
private function onSaleTrueFalse($sintax, $onSale, $request)
{
// On sale false
if ($onSale) {
if ($request->get("saleuser")) {
$sintax .= "&onSaleByUser=true";
} else {
$sintax .= "&onSale=true";
}
} else {
$sintax .= "&onSale=false";
}
if ($request->get("event"))
$event = $request->get("event");
// Searching params for tickets that are not for sale
$sintaxAdd = !$onSale ? '&onSale=false&event=' . $event : '';
$page = $this->ticketing->curl("tickets?orderBy=price" . $sintax, "normal", [], "GET");
foreach ($page["tickets"] as $key => $ticket) {
if (!$onSale) {
$aux = $this->ticketing->curl("tickets?onSale=false&limit=1&maxPrice=" . (float)$ticket["price"] . "&minPrice=" . (float)$ticket["price"] . $sintaxAdd, "normal", [], "GET");
$auxTotal = $this->ticketing->curl("tickets?limit=1000&maxPrice=" . (float)$ticket["price"] . "&minPrice=" . (float)$ticket["price"] . "&event=" . $event, "normal", [], "GET");
} else {
$aux = $this->ticketing->curl("tickets?onSale=true&limit=1&maxPrice=" . (float)$ticket["price"] . "&minPrice=" . (float)$ticket["price"], "normal", [], "GET");
}
$page["tickets"][$key]["quantity"] = $aux["total"];
if ($page["tickets"][$key]["quantity"] > 15)
$page["tickets"][$key]["quantity"] = 15;
// Delete block of tickets that are not fully sold out
if (isset($auxTotal) && $auxTotal['total'] != $aux['total'])
unset($page['tickets'][$key]);
}
return $page;
}
/**
* @param $id
* @return int|mixed
*/
private function getDiscount($id){
$user = $this->functions->getUserLogged();
$tickets = $this->ticketing->curl("tickets/activity?destination=" . $user . "&order=asc&limit=1", "normal", [], "GET");
if (empty($tickets))
return 0;
$category = !empty($tickets['activity'][0]['ticket']['category']) ? strtolower($tickets['activity'][0]['ticket']['category']['name']) : '';
$discounts = [];
// First ticket buyed
switch ($category) {
case 'congreso':
$discounts = [
'congreso' => 0,
'taller4' => 10,
'taller8' => 15,
];
break;
case 'taller4':
$discounts = [
'congreso' => 4,
'taller4' => 10,
'taller8' => 15,
];
break;
case 'taller8':
$discounts = [
'congreso' => 9,
'taller4' => 10,
'taller8' => 0,
];
break;
}
// Ticket to buy
$ticket = $this->ticketing->curl("tickets/" . $id, "normal", array(), "GET");
$category = !empty($ticket['category']['name']) ? strtolower($ticket['category']['name']) : '';
$type = '';
switch ($category) {
case 'congreso':
$type = 'congreso';
break;
case 'taller4':
$type = 'taller4';
break;
case 'taller8':
$type = 'taller8';
break;
}
return array_key_exists($type, $discounts) ? $discounts[$type] : 0;
}
}