File: /var/www/vhost/disk-apps/comfama.sports-crowd.com/public/js/web_ticketing.js
selectedTickets = [];
user = null;
activeMatchEvent = null;
tribunes = [];
zones = [];
activeTribune = null;
globalTotal = 0;
const userTribuneStatus = {
userId: null,
UserDocument: null,
available_tickets: {}
};
$(document).on('ready', function (e) {
setCurrencyFormat();
$('#user_form input[name=email]').on('change input oninvalid focus blur', function () {
this.setCustomValidity('');
field = document.getElementById("email");
if (!field.checkValidity()) {
field.setCustomValidity('Debes ingresar un formato válido de correo electrónico, por ejemplo: pepitoperez@gmail.com');
} else if ($('#user_form input[name=confirm_email]').val() && this.value != $('#user_form input[name=confirm_email]').val()) {
document.getElementById("confirm_email").setCustomValidity('Los correos no coinciden');
}
});
$('#user_form input[name=confirm_email]').on('change input oninvalid focus blur', function () {
this.setCustomValidity('');
field = document.getElementById("confirm_email");
if (!field.checkValidity()) {
field.setCustomValidity('Debes ingresar un formato válido de correo electrónico, por ejemplo: pepitoperez@gmail.com');
} else if ($('#user_form input[name=email]').val() && this.value != $('#user_form input[name=email]').val()) {
field.setCustomValidity('Los correos no coinciden');
}
});
$('#user_form input[name=confirm_email]').on('input', function (event) {
if (this.value && event.detail == undefined) {
this.value = '';
}
});
$('#user_form input[name=first_name]').on('change input onkeyup oninvalid focus', function () {
this.setCustomValidity('');
if (!this.checkValidity()) {
this.setCustomValidity('Debes ingresar los nombres del usuario, por ejemplo: Pepito');
}
});
$('#user_form input[name=last_name]').on('change input onkeyup oninvalid focus', function () {
this.setCustomValidity('');
if (!this.checkValidity()) {
this.setCustomValidity('Debes ingresar los apellidos del usuario, por ejemplo: Perez');
}
});
$('#user_form input[name=phone]').on('change input onkeyup oninvalid focus', function (event) {
this.setCustomValidity('');
if (!this.checkValidity()) {
this.setCustomValidity('Debes ingresar un telefono válido, por ejemplo: 3000000001');
} else if (this.value && this.value.length > 10) {
this.value = this.value.slice(0, 10);
event.preventDefault();
return false;
}
});
$("#modal_sell_seat").on("hidden.bs.modal", function (e) {
var seat = JSON.parse(localStorage.getItem("current_seat"));
var is_add_seat = ticketsToBuy.find((item) => item.seat.id == seat.id);
if (!is_add_seat) {
$(current_e).removeClass("bg-seat-selected");
}
});
})
var me = this;
$(document).on('scroll click', function (e) {
me.resizePage();
});
function onchangeSelect(sel, event, color) {
var existIndex = selectedTickets.findIndex(item => item.zone_id === event.zone_id);
var couponValue = $('#additional-input').val();
if (existIndex != -1) {
selectedTickets.splice(existIndex, 1);
}
if (sel.value > 0) {
event['quantity'] = sel.value;
selectedTickets.push(event);
}
html = `
<div class="row" id="checkout-title" style="color: ` + color + ` ;">
<div class="col-md-4 col-4">
<h5>Tribuna</h5>
</div>
<div class="col-md-3 col-3 text-center">
<h5>Precio boleta</h5>
</div>
<div class="col-md-2 col-2 text-center">
<h5>Boletas</h5>
</div>
<div class="col-md-3 col-3 text-end">
<h5>Valor compra</h5>
</div>
</div>
`;
globalTotal = 0;
selectedTickets.forEach(function (element) {
let oldPrice = element.price
if (element.apply_coupon_type == 'special_price' && element.coupon == couponValue) {
element.price = element.special_price
}
total = element.quantity * element.price;
globalTotal += total;
html += `
<hr class="rounded">
<div class="row">
<div class="col-md-4 col-4">
<h5>` + element.zone + `</h5>
</div>
<div class="col-md-3 col-3 text-center">
<h5 class="currency">` + element.price + `</h5>
</div>
<div class="col-md-2 col-2 text-center">
<h5>` + element.quantity + `</h5>
</div>
<div class="col-md-3 col-3 text-end">
<h5 class="currency">` + total + `</h5>
</div>
</div>
`;
if (element.apply_coupon_type == 'special_price') {
element.price = oldPrice
}
});
$("#checkout-body").html(html);
$("#total").html(globalTotal);
if (selectedTickets.length > 0) {
$('#buy-btn').show();
} else {
$('#buy-btn').hide();
}
setCurrencyFormat();
}
function resetSelectedTickets() {
$("#checkout-body").html('');
$("#total").html(0);
selectedTickets = [];
ticketsToBuy = [];
$('#buy-btn').hide();
$('.ticket-select').val(0);
$("#tribunes-container-coupon").html('');
$("#additional-input").val('');
$("#additional-input").prop("disabled", false);
$("#aplicar-cupon-btn").prop("disabled", false);
}
function getUserByDocument() {
user = null;
onChangeId();
$("#search_button").prop('disabled', true);
$("#validate_button").prop('disabled', false);
id = $("#document").val();
$.ajax({
url: "/user/getByDocument/" + id,
type: "GET",
contentType: "application/json",
async: false,
headers: {
"Content-Type": "application/json",
},
success: function (r) {
if (r.length) {
$('#email-select').empty();
$('#email-select').append($('<option>', {
value: 0,
text: 'Seleccione'
}));
r.forEach(function (user) {
emailSplit = user.email.split('@');
$('#email-select').append($('<option>', {
value: JSON.stringify(user),
text: emailSplit[0].replace(/.(?=.{5})/g, '*') + '@' + emailSplit[1]
}));
});
$('#email-select').append($('<option>', {
value: -1,
text: 'Otro'
}));
$('#email-select').show();
} else {
$("#email").prop('disabled', false);
$("#confirm_email").prop('disabled', false);
$("#first_name").prop('disabled', false);
$("#last_name").prop('disabled', false);
$("#phone").prop('disabled', false);
$("#confirm_email").prop('required', true);
$("#first_name").prop('required', true);
$("#last_name").prop('required', true);
$("#email").prop('required', true);
$("#phone").prop('required', true);
$('#email').show();
$('#user-info-container').show();
$('#user-info-footer').show();
}
$('#email-container').show();
}
});
}
function onSelectedEmail(selection) {
user = null;
selected = JSON.parse(selection.value);
$("#confirm_email").prop('required', true);
$("#first_name").prop('required', true);
$("#last_name").prop('required', true);
$("#phone").prop('required', true);
if (selected == -1) {
$('#email').show();
$("#document").prop("type", "number");
$("#phone").prop("type", "number");
$('#email').val('');
$('#confirm_email').val('');
$('#first_name').val('');
$('#last_name').val('');
$('#phone').val('');
$("#email").prop('disabled', false);
$("#confirm_email").prop('disabled', false);
$("#first_name").prop('disabled', false);
$("#last_name").prop('disabled', false);
$("#phone").prop('disabled', false);
} else {
$('#email').hide();
user = selected.id;
$("#phone").prop("type", "text");
$('#first_name').val(selected.first_name.replace(/.(?=.{4})/g, '*'));
$('#last_name').val(selected.last_name.replace(/.(?=.{4})/g, '*'));
$('#phone').val(selected.phone.replace(/.(?=.{4})/g, '*'));
$('#email').val(selected.email);
emailSplit = selected.email.split('@');
$('#confirm_email').val(emailSplit[0].replace(/.(?=.{5})/g, '*') + '@' + emailSplit[1]);
$("#confirm_email").prop('disabled', true);
$("#first_name").prop('disabled', true);
$("#last_name").prop('disabled', true);
$("#phone").prop('disabled', true);
}
$('#user-info-container').show();
$('#user-info-footer').show();
$('#tribunes').hide();
resetSelectedTickets();
$("#validate_button").prop('disabled', false);
}
function getAvailableTickets(event) {
if (!$("#email").val())
return
resetSelectedTickets();
$("#email").prop('disabled', true);
$("#confirm_email").prop('disabled', true);
$("#first_name").prop('disabled', true);
$("#last_name").prop('disabled', true);
$("#phone").prop('disabled', true);
$("#validate_button").prop('disabled', true);
if (user) {
$.ajax({
url: "/ticket/getAvailableTickets/" + event.match_event_id + "/" + user,
type: "GET",
contentType: "application/json",
async: false,
headers: {
"Content-Type": "application/json",
},
success: function (r) {
if (r.length) {
userTribuneStatus.available_tickets = {};
r.forEach(function (element) {
if (element.available_tickets < 1) {
$('#amount-' + element.id).hide();
} else {
html = '';
for (i = 0; i <= element.available_tickets; i++) {
html += '<option value=' + i + '>' + i + '</option>';
}
$('#select-' + element.id).html(html);
$('#select-' + element.id).val(0);
}
userTribuneStatus.available_tickets[element.id] = element.available_tickets;
});
userTribuneStatus.userId = user;
userTribuneStatus.UserDocument = $('#document').val();
}
}
});
}
$('#tribunes').show();
}
function createClient() {
activateLoadingButton($("#buy_button"), $("#loading_button"));
if (!user) {
$("#email").prop('disabled', false);
$("#confirm_email").prop('disabled', false);
$("#first_name").prop('disabled', false);
$("#last_name").prop('disabled', false);
$("#phone").prop('disabled', false);
data = buildInfoForApi('#user_form');
$.ajax({
url: '/clients/create/true/false',
type: "POST",
contentType: "application/json",
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
"Content-Type": "application/json"
},
data: JSON.stringify(data),
success: function (r) {
$("#email").prop('disabled', true);
$("#confirm_email").prop('disabled', true);
$("#first_name").prop('disabled', true);
$("#last_name").prop('disabled', true);
$("#phone").prop('disabled', true);
user = r.d;
if (r.r) {
if (ticketsToBuy.length)
createBlocks();
else
validateSeatsAvailableByCapacity();
} else {
swal("Error", r.m, "error");
activateLoadingButton($("#buy_button"), $("#loading_button"), false);
}
},
error: function (e) {
$("#email").prop('disabled', true);
$("#confirm_email").prop('disabled', true);
$("#first_name").prop('disabled', true);
$("#last_name").prop('disabled', true);
$("#phone").prop('disabled', true);
swal("Error", "¡Hubo un error al crear el usuario!", "error");
activateLoadingButton($("#buy_button"), $("#loading_button"), false);
},
});
} else {
if (typeof user == 'number')
user = { id: user };
validateSeatsAvailableByCapacity();
}
}
function validateSeatsAvailableByCapacity() {
data = selectedTickets;
$.ajax({
url: '/api/flash_tickets/validateSeatsAvailableByCapacity',
type: "POST",
contentType: "application/json",
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
"Content-Type": "application/json"
},
data: JSON.stringify(data),
success: function (r) {
if (r) {
createBlocks(r);
} else {
swal("Error", r.m, "error");
activateLoadingButton($("#buy_button"), $("#loading_button"), false);
}
},
error: function (e) {
swal("Error", "¡Hubo un error No hay sillas disponibles para la tribuna!", "error");
activateLoadingButton($("#buy_button"), $("#loading_button"), false);
},
});
}
function createBlocks(tribunes = []) {
var tickets = [];
if (ticketsToBuy.length) {
tickets = ticketsToBuy;
} else {
var couponValue = $('#additional-input').val();
for (i = 0; i < tribunes.length; i++) {
element = tribunes[i];
seats = element.seats;
let oldPrice = element.price
if (element.apply_coupon_type == 'special_price' && element.coupon == couponValue) {
element.price = element.special_price
}
if (Array.isArray(seats)) {
seats.forEach(function (seat) {
tickets.push({
'seat': {
'id': seat.id,
'zone_id': seat.zone_id
},
'match_event_id': element.match_event_id,
'ticket_type_id': 1,
'price': element.price
});
});
} else {
swal("Error", "No hay sillas disponibles para la tribuna: " + element.zone, "error");
activateLoadingButton($("#buy_button"), $("#loading_button"), false);
return;
}
if (element.apply_coupon_type == 'special_price') {
element.price = oldPrice
}
}
}
let data = {
tickets: tickets,
type_process: "block",
subtotal: globalTotal,
serviceCharge: 0,
amount: globalTotal,
ticket_type_id: 1,
season_id: tribunes.length ? tribunes[0].season_id : null
};
$.ajax({
url: '/api/tickets/createBlocks/' + user.id + '/web',
type: "POST",
contentType: "application/json",
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
"Content-Type": "application/json"
},
data: JSON.stringify(data),
success: function (r) {
if (r.r) {
activateLoadingButton($("#buy_button"), $("#loading_button"), false);
window.open("../../payment_gateway/selection/ticket/" + r.data, "_self")
} else {
swal("Error", r.m, "error");
activateLoadingButton($("#buy_button"), $("#loading_button"), false);
}
},
error: function (e) {
swal("Error", "¡Hubo un error al comprar boletas!", "error");
activateLoadingButton($("#buy_button"), $("#loading_button"), false);
},
});
}
function setCurrencyFormat() {
$(".currency").each(function () {
let originalValue = $(this).html();
if (!isNaN(originalValue)) {
$(this).html(currencyMask(originalValue));
}
});
}
function currencyMask(data) {
const formatter = new Intl.NumberFormat('es-CO', {
style: 'currency',
currency: 'COP',
minimumFractionDigits: 0,
maximumFractionDigits: 0,
});
return formatter.format(data);
}
function onChangeId() {
if (!$('#document').val().length) {
$("#search_button").prop('disabled', true);
} else {
$("#search_button").prop('disabled', false);
}
$('#email').val('');
$('#confirm_email').val('');
$('#first_name').val('');
$('#last_name').val('');
$('#phone').val('');
$("#confirm_email").prop('required', false);
$("#first_name").prop('required', false);
$("#last_name").prop('required', false);
$("#phone").prop('required', false);
$('#email').hide();
$('#email-select').hide();
$('#email-container').hide();
$('#user-info-container').hide();
$('#user-info-footer').hide();
$('#tribunes').hide();
resetSelectedTickets();
$("#tribunes-container").find('[id^="amount-"]').each(function (element, val) {
$(val).show();
});
}
function activateLoadingButton(actionButton, loadingButton, activated = true, time = 3000) {
if (activated) {
actionButton.addClass("hide");
loadingButton.removeClass("hide");
} else {
setTimeout(function () {
actionButton.removeClass("hide");
loadingButton.addClass("hide");
}, time);
}
}
function showStadiumZones(event = null) {
if (ticketsToBuy.length)
swal('Estás seguro de cambiar de sector, ya que esta acción eliminara las sillas seleccionadas?', {
closeOnClickOutside: false,
icon: "warning",
buttons: {
cancel: {
text: "No",
value: false,
visible: true,
className: "",
closeModal: true,
},
confirm: {
text: "Si, estoy seguro",
value: true,
visible: true,
className: "",
closeModal: true
}
},
}).then((confirm) => {
if (confirm) {
ticketsToBuy = [];
validateCheckout();
loadStadiumZones(event);
}
});
else
loadStadiumZones(event);
}
function loadStadiumZones(event = null) {
resetSelectedTickets();
hideContainers();
if (event){
if (!event.id){
event.id = event.event_id;
}
activeMatchEvent = event;
}
$("#email").prop('disabled', true);
$("#confirm_email").prop('disabled', true);
$("#first_name").prop('disabled', true);
$("#last_name").prop('disabled', true);
$("#phone").prop('disabled', true);
$("#validate_button").prop('disabled', true);
var me = this;
$.ajax({
url: `/tickets/loadStadiumZones`,
type: "GET",
contentType: "application/json",
async: false,
headers: {
"Content-Type": "application/json",
},
data: {
matchEventId: activeMatchEvent.event_id
},
success: function (r) {
if (r.r) {
tribunes = r.data;
if (!tribunes.length) {
$('#tribunes').hide();
$('#stadiumContainer').hide();
$('#stadiumLabel').hide();
swal("Advertencia", 'No existen sectores configurados con precio para el evento (' + activeMatchEvent.name + ').', "warning");
return;
}
for (let i = 0; i < tribunes.length; i++) {
zones = $('[alt="' + tribunes[i].alias);
if (zones.length) {
for (let j = 0; j < zones.length; j++) {
elClone = zones[j].cloneNode(true);
zones[j].parentNode.replaceChild(elClone, zones[j]);
// Agregar titulo del sector
snackbar = document.getElementById("snackbar");
snackbarTitle = document.getElementById("snackbar-title");
snackbarSubtitle = document.getElementById("snackbar-subtitle");
elClone.style.fill = 'D8D8D6';
if (tribunes[i].locked) {
elClone.style.fill = '#6A6A6A';
elClone.addEventListener('click', () => alert('El sector "' + tribunes[i].name + '" está bloqueado'));
elClone.addEventListener('mousemove', () => {
snackbarTitle.textContent = tribunes[i].name;
snackbarSubtitle.textContent = "El sector esta bloqueado";
snackbar.className = "show";
});
elClone.addEventListener('mouseleave', () => {
snackbarTitle.textContent = "";
snackbarSubtitle.textContent = "";
snackbar.className = "hide";
});
} else if (!tribunes[i].available_seats) {
elClone.style.fill = '#FF0000';
elClone.addEventListener('click', () => alert('El sector "' + tribunes[i].name + '" no tiene sillas disponibles'));
elClone.addEventListener('mousemove', () => {
snackbarTitle.textContent = tribunes[i].name;
snackbarSubtitle.textContent = "El sector no tiene sillas disponibles";
snackbar.className = "show";
});
elClone.addEventListener('mouseleave', () => {
snackbarTitle.textContent = "";
snackbarSubtitle.textContent = "";
snackbar.className = "hide";
});
} else {
elClone.addEventListener('click', () => { me.loadStadiumSeats(activeMatchEvent.id, tribunes[i].id, tribunes[i].name); });
elClone.addEventListener('mousemove', () => {
snackbarTitle.textContent = tribunes[i].name;
snackbarSubtitle.textContent = "Sillas disponibles: " + tribunes[i].available_seats;
snackbar.className = "show";
});
elClone.addEventListener('mouseleave', () => {
snackbarTitle.textContent = "";
snackbarSubtitle.textContent = "";
snackbar.className = "hide";
});
}
}
}
}
}
$('#tribunes').show();
$('#stadiumContainer').show();
$('#stadiumLabel').hide();
}
});
}
function loadStadiumSeats(matchEventId, zoneId, zoneName) {
validateZone = {
id: zoneId,
name: zoneName,
};
$.ajax({
url: "/tickets/seats/" + zoneId + "/" + matchEventId,
type: "GET",
contentType: "application/json",
headers: {
"X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content"),
"Content-Type": "application/json",
},
success: function (r) {
if (r.r) {
$("#seatsContainer").empty();
var seats = r.data;
if (!seats.length) {
swal("Advertencia", 'No hay sillas disponibles para el sector (' + zoneName + ')', "warning");
return;
}
var group_seats = orderGroupBy(seats, "letter_id");
if (group_seats) {
group_seats = group_seats.slice().reverse();
}
s3Url = $('#s3Url').val();
time = new Date().getTime();
for (let j = 0; j < group_seats.length; j++) {
var item = group_seats[j];
item.value = item.value.sort(function (a, b) {
return parseFloat(a.code) - parseFloat(b.code);
});
var list_seats = "";
for (let m = 0; m < item.value.length; m++) {
var seat = item.value[m];
let seatImage = "";
let openmodal = true;
if (!seat.ticket && !seat.ticket_user_block) {
seatImage = "available.png";
}
if (seat.ticket_user_block) {
openmodal = false;
seatImage = "not_available.png";
}
0
if (seat.ticket) {
openmodal = false;
seatImage = "not_available.png";
}
if (seat.presubscription) {
openmodal = false;
seatImage = "not_available.png";
}
if (seat.match_event_stage.length) {
openmodal = false;
seatImage = "not_available.png";
}
list_seats += `<div class="d-i-t text-center cursor" id="${seat.id}" onclick="modalSeat(this,'${window.btoa(
JSON.stringify(seat)
)}',${openmodal})">\
<img class="seat-image" src="${s3Url}/ticketing/seats/${seatImage}?_dc=${time}" alt="">\
<span>${seat.code}</span>\
</div>`;
}
var letter = item.value[0].letter.name;
var row = `<div class="row container_row"><span class="label_letter">${letter}</span>${list_seats}</div>`;
$("#seatsContainer").append(row);
$("#seats").show();
$("#seatsContainer").show();
//activeTribune.hide();
$('#tribunes').show();
$('#stadiumLabel').show();
$("#stadiumContainer").hide();
//$('#stadiumBreadcrumbs').show();
$('#tribuneBreadcrumbs').show();
$("#activeZoneLabel").html(capitalizeFirstLetter(zoneName));
}
} else {
swal("Advertencia", r.m, "warning");
}
},
});
}
function hideContainers() {
$('#tribunes').hide();
$("#occidental").hide();
$("#oriental").hide();
$("#norte").hide();
$("#sur").hide();
$("#stadiumContainer").hide();
$("#stadiumLabel").hide();
$("#stadiumBreadcrumbs").hide();
$("#tribuneBreadcrumbs").hide();
$("#seats").hide();
$("#seatsContainer").hide();
}
function activateStadium(event = null) {
if (ticketsToBuy.length)
swal('Estás seguro de cambiar de tribuna, ya que esta acción eliminara las sillas seleccionadas?', {
closeOnClickOutside: false,
icon: "warning",
buttons: {
cancel: {
text: "No",
value: false,
visible: true,
className: "",
closeModal: true,
},
confirm: {
text: "Si, estoy seguro",
value: true,
visible: true,
className: "",
closeModal: true
}
},
}).then((confirm) => {
if (confirm) {
ticketsToBuy = [];
validateCheckout();
loadTribunes(event);
}
});
else
loadTribunes(event);
}
function loadTribunes(event = null) {
tribunes = [];
resetSelectedTickets();
hideContainers();
if (event)
activeMatchEvent = event;
$("#email").prop('disabled', true);
$("#confirm_email").prop('disabled', true);
$("#first_name").prop('disabled', true);
$("#last_name").prop('disabled', true);
$("#phone").prop('disabled', true);
$("#validate_button").prop('disabled', true);
$.ajax({
url: `/tickets/tribunesParent/${activeMatchEvent.event_id}`,
type: "GET",
contentType: "application/json",
async: false,
headers: {
"Content-Type": "application/json",
},
success: function (r) {
if (r.r) {
tribunes = r.data;
}
$('#tribunes').show();
$('#stadiumContainer').show();
$('#stadiumLabel').hide();
}
});
}
function showTribune(tribune = null) {
if (ticketsToBuy.length)
swal('Estás seguro de cambiar de sector, ya que esta acción eliminara las sillas seleccionadas?', {
closeOnClickOutside: false,
icon: "warning",
buttons: {
cancel: {
text: "No",
value: false,
visible: true,
className: "",
closeModal: true,
},
confirm: {
text: "Si, estoy seguro",
value: true,
visible: true,
className: "",
closeModal: true
}
},
}).then((confirm) => {
if (confirm) {
ticketsToBuy = [];
validateCheckout();
loadZones(tribune);
}
});
else
loadZones(tribune);
}
function loadZones(tribune = null) {
zones = [];
tribuneName = tribune ? tribune.title : $('area[alt="' + activeTribune[0].id + '"]')[0].title;
if (tribune) {
tribuneContainer = $("#" + tribuneName);
activeTribune = tribuneContainer;
} else {
tribuneContainer = activeTribune;
}
validateTribune = tribunes.find(item => item.alias == tribuneName);
if (validateTribune && validateTribune.match_event_stage.length) {
swal("Advertencia", "Tribuna (" + capitalizeFirstLetter(tribuneName) + ") no disponible para este partido.", "warning");
return;
}
$("#tribuneLabel").html(capitalizeFirstLetter(tribuneName));
$.ajax({
url: "/tickets/subZones/" + validateTribune.id + "/" + activeMatchEvent.event_id,
type: "GET",
contentType: "application/json",
headers: {
"X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content"),
"Content-Type": "application/json",
},
success: function (r) {
if (r.r) {
zones = r.data;
hideContainers();
tribuneContainer.show();
$('#tribunes').show();
$('#stadiumLabel').show();
$("#stadiumContainer").hide();
} else {
swal("Advertencia", r.m, "warning");
}
},
});
}
function showZone(zone) {
validateZone = zones.find(item => item.alias == zone.title);
if (validateZone && parseInt(validateZone.available_seats) <= 0) {
swal("Advertencia", 'Ya se ha alcanzado el límite de aforo vendible para este sector (' + validateZone.name + ')', "warning");
return;
}
$.ajax({
url: "/tickets/seats/" + validateZone.id + "/" + activeMatchEvent.event_id,
type: "GET",
contentType: "application/json",
headers: {
"X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content"),
"Content-Type": "application/json",
},
success: function (r) {
if (r.r) {
$("#seatsContainer").empty();
var seats = r.data;
if (!seats.length) {
swal("Advertencia", 'No hay sillas disponibles para el sector (' + validateZone.name + ')', "warning");
return;
}
var group_seats = orderGroupBy(seats, "letter_id");
if (group_seats) {
group_seats = group_seats.slice().reverse();
}
for (let j = 0; j < group_seats.length; j++) {
var item = group_seats[j];
item.value = item.value.sort(function (a, b) {
return parseFloat(a.code) - parseFloat(b.code);
});
var list_seats = "";
var s3Url = $('#s3Url').val();
for (let m = 0; m < item.value.length; m++) {
var seat = item.value[m];
let seatImage = "";
let openmodal = true;
if (!seat.ticket && !seat.ticket_user_block) {
seatImage = "available.png";
}
if (seat.ticket_user_block && seat.is_social_distancing) {
openmodal = false;
seatImage = "distancing.png";
}
if (seat.ticket_user_block && !seat.is_social_distancing) {
openmodal = false;
seatImage = "tempblock.png";
}
if (seat.ticket && seat.ticket_type_id == 1) {
openmodal = false;
seatImage = "not_available.png";
}
if (seat.ticket && seat.ticket_type_id == 2) {
openmodal = false;
seatImage = "suscription.png";
}
if (seat.ticket && seat.ticket_type_id == 3) {
openmodal = false;
seatImage = "courtesy.png";
}
if (seat.ticket && seat.ticket_type_id == 4) {
openmodal = false;
seatImage = "not_available.png";
}
if (seat.match_event_stage.length) {
openmodal = false;
seatImage = "block.png";
}
list_seats += `<div class="d-i-t text-center cursor" id="${seat.id}" onclick="modalSeat(this,'${window.btoa(
JSON.stringify(seat)
)}',${openmodal})">\
<img class="seat-image" src="${s3Url}/ticketing/seats/${seatImage}" alt="">\
<span>${seat.code}</span>\
</div>`;
}
var letter = item.value[0].letter.name;
var row = `<div class="row container_row"><span class="label_letter">${letter}</span>${list_seats}</div>`;
$("#seatsContainer").append(row);
$("#seatsContainer").show();
activeTribune.hide();
$('#tribunes').show();
$('#stadiumLabel').show();
$("#stadiumContainer").hide();
$('#stadiumBreadcrumbs').show();
$('#tribuneBreadcrumbs').show();
$("#activeZoneLabel").html(capitalizeFirstLetter(validateZone.name));
}
} else {
swal("Advertencia", r.m, "warning");
}
},
});
}
function orderGroupBy(collection, property) {
const groupedCollection = collection.reduce((previous, current) => {
if (!previous[current[property]]) {
previous[current[property]] = [current];
} else {
previous[current[property]].push(current);
}
return previous;
}, {});
return Object.keys(groupedCollection).map((key) => ({
key,
value: groupedCollection[key],
}));
}
var formatter = new Intl.NumberFormat("en-US", {
style: "currency",
currency: "USD",
minimumFractionDigits: 0,
});
var current_e;
function modalSeat(e, seat, openmodal) {
localStorage.removeItem("current_seat");
current_e = e;
seat = JSON.parse(window.atob(seat));
var is_add_seat = ticketsToBuy.find((item) => item.seat.id == seat.id);
if (is_add_seat) {
const indexTicket = (item) => item.seat.id == seat.id;
let index = ticketsToBuy.findIndex(indexTicket);
if (index >= 0) {
removeSeatListBuy(index, $(e));
}
} else {
if (openmodal) {
document.getElementById("form_sell_seat").reset();
$("#seat_letter").val(seat.letter.name);
$("#seat_code").val(seat.code);
$.ajax({
url: "/tickets/price/" + seat.zone_id + "/" + activeMatchEvent.event_id,
type: "GET",
contentType: "application/json",
headers: {
"X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr(
"content"
),
"Content-Type": "application/json",
},
success: function (r) {
if (r.r) {
var price = r.data;
if (price) {
localStorage.setItem("current_seat", JSON.stringify(seat));
localStorage.setItem("current_price", JSON.stringify(price));
$(".modal-body #price").val(
formatter.format(price.price)
);
$(e).addClass("bg-seat-selected");
$("#modal_sell_seat").modal("show");
return;
}
}
swal("Advertencia", r.m ? r.m : "¡La zona seleccionada no tiene precios asignados para el evento!", "warning");
},
});
}
}
}
var ticketsToBuy = [];
function addSeat(presuscription = null) {
if (validateAddSeat(/*ticket_type_id, presuscription*/)) {
ticketsToBuy.push({
seat: JSON.parse(localStorage.getItem("current_seat")),
match_event_id: activeMatchEvent.event_id,
ticket_type_id: 1,
match_event_price: JSON.parse(localStorage.getItem("current_price")),
dataTicket: null
});
validateCheckout();
$("#modal_sell_seat").modal("toggle");
}
}
function validateCheckout() {
html = ``;
if (ticketsToBuy.length)
html = `
<div class="row" id="checkout-title">
<div class="col-md-1 col-1">
<h5> </h5>
</div>
<div class="col-md-2 col-2 text-center">
<h5>Sector</h5>
</div>
<div class="col-md-3 col-3 text-center">
<h5>Letra</h5>
</div>
<div class="col-md-3 col-3 text-center">
<h5>Código</h5>
</div>
<div class="col-md-3 col-3 text-end">
<h5>Precio</h5>
</div>
</div>
`;
globalTotal = 0;
ticketsToBuy.forEach(function (element) {
seatLetter = element.seat.letter.name;
seatCode = element.seat.code;
total = element.match_event_price.price ? element.match_event_price.price : 0;
globalTotal += total;
html += `
<hr class="rounded">
<div class="row">
<div class="col-md-1 col-1" style="display: flex; flex-flow: row;">
<img class="icon-remove-sign" src="/img/removeSeat.png" onclick="validateRemoveSeatListBuy(` + element.seat.id + `);">
</div>
<div class="col-md-2 col-2 text-center">
<h5>` + validateZone.name + `</h5>
</div>
<div class="col-md-3 col-3 text-center">
<h5>` + seatLetter + `</h5>
</div>
<div class="col-md-3 col-3 text-center">
<h5>` + seatCode + `</h5>
</div>
<div class="col-md-3 col-3 text-end">
<h5 class="currency">` + total + `</h5>
</div>
</div>
`;
});
$("#checkout-body").html(html);
$("#total").html(globalTotal);
if (ticketsToBuy.length > 0) {
$('#buy-btn').show();
} else {
$('#buy-btn').hide();
}
setCurrencyFormat();
$("html, body").animate({ scrollTop: $(document).height() }, 500);
}
function validateAddSeat(ticket_type_id, presuscription) {
/*if (!ticket_type_id || ticket_type_id == 0) {
swal("Advertencia", "¡Debes seleccionar tipo de boleta!", "warning");
return;
}
if (presuscription && ticket_type_id == 1) {
swal("Advertencia", "Por el momento solo está habilitada la venta de abonos.", "warning");
return;
}
if (ticket_type_id == 1 && ticketsToBuy.filter(ticket => ticket.ticket_type_id == 2).length) {
swal("Advertencia", "Solo puedes agregar boletas tipo Abonado en esta transacción.", "warning");
return;
}
if (ticket_type_id == 2 && ticketsToBuy.filter(ticket => ticket.ticket_type_id == 1).length) {
swal("Advertencia", "Solo puedes agregar boletas tipo Venta libre en esta transacción.", "warning");
return;
}*/
return true;
}
function removeSeatListBuy(index, seatContainer) {
swal('Estás seguro de eliminar la silla?', {
closeOnClickOutside: false,
icon: "warning",
buttons: {
cancel: {
text: "No",
value: false,
visible: true,
className: "",
closeModal: true,
},
confirm: {
text: "Si, estoy seguro",
value: true,
visible: true,
className: "",
closeModal: true
}
},
}).then((confirm) => {
if (confirm) {
seatContainer.removeClass('bg-seat-selected');
if (ticketsToBuy && ticketsToBuy.length) {
ticketsToBuy.splice(index, 1);
}
validateCheckout();
}
});
}
function tribunaHtml(tribuneJson, iconColor) {
const price = tribuneJson.apply_coupon_type == 'special_price' ? tribuneJson.special_price : tribuneJson.price;
const availableTickets = Object.keys(userTribuneStatus.available_tickets).length > 0 ? userTribuneStatus.available_tickets[tribuneJson.id] : tribuneJson.maximum_number_ballots;
const arrayOfBallots = Array.from({ length: availableTickets + 1 }, (_, i) => i);
return `
<div id="amount-cupon-${tribuneJson.id}">
<div class="row">
<div class="col-md-7 col-7">
<h5>${tribuneJson.zone}</h5>
</div>
<div class="col-md-3 col-3 text-center">
<h5 class="currency">\$ ${price}</h5>
</div>
<div class="col-md-2 col-2 text-center">
<select style="font-size: 16px; min-width: 40px;" id="select-${tribuneJson.id}"
class="ticket-select"
onchange="onchangeSelect(this,${JSON.stringify(tribuneJson).replace(/"/g, """,)},'${iconColor}');">
${arrayOfBallots.map((ballot) => `<option value="${ballot}">${ballot}</option>`)}
</select>
</div>
</div>
<hr class="rounded">
</div>
`;
}
function handleCuponQuery(matchEventIdAuxi, iconColor) {
var couponValue = $('#additional-input').val();
$("#alert-cupon").hide();
if (!couponValue) {
return;
}
$.ajax({
url: '/procesar-cupon/' + couponValue + '/' + 'yes' + '/' + matchEventIdAuxi,
type: 'GET',
success: function (response) {
resetSelectedTickets();
const tribunesContainerCoupon = $('#tribunes-container-coupon');
if (response) {
let unavailableTickets = false;
response.forEach(function (tribunaJson) {
if (!Object.keys(userTribuneStatus.available_tickets).length || userTribuneStatus.available_tickets[tribunaJson.id] > 0) {
tribunesContainerCoupon.append(tribunaHtml(tribunaJson, iconColor));
$(`#amount-${tribunaJson.id}`).hide();
} else {
unavailableTickets = true;
}
});
if (unavailableTickets) {
$("#alert-cupon-unavailable").show();
setTimeout(function () {
$("#alert-cupon-unavailable").hide();
}, 3000);
}
if (response.length) {
$("#success-cupon").show();
setTimeout(function () {
$("#success-cupon").hide();
}, 3000);
$("#additional-input").val(couponValue);
if (!unavailableTickets) {
$("#additional-input").prop("disabled", true);
$("#aplicar-cupon-btn").prop("disabled", true);
}
} else {
$("#alert-cupon").show();
setTimeout(function () {
$("#alert-cupon").hide();
}, 3000);
}
}
},
error: function (error) {
$("#alert-cupon").show();
}
});
}
function capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
function validateRemoveSeatListBuy(seatId) {
const indexTicket = (item) => item.seat.id == seatId;
let index = ticketsToBuy.findIndex(indexTicket);
if (index >= 0) {
removeSeatListBuy(index, $(`#${seatId}`));
}
}
const isMobile = {
Android: function () {
return navigator.userAgent.match(/Android/i);
},
BlackBerry: function () {
return navigator.userAgent.match(/BlackBerry/i);
},
iOS: function () {
return navigator.userAgent.match(/iPhone|iPad|iPod/i);
},
Opera: function () {
return navigator.userAgent.match(/Opera Mini/i);
},
Windows: function () {
return navigator.userAgent.match(/IEMobile/i) || navigator.userAgent.match(/WPDesktop/i);
},
any: function () {
return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows());
}
};
function resizePage() {
if (isMobile.any()) {
let childs = document.getElementsByClassName('col-md-6 col-12 p-xs-0');
let height = 0;
for (let i = 0; i < childs.length; i++) {
height += childs[i].offsetHeight;
}
document.body.style.height = height + 'px';
}
}