File: /var/www/vhost/disk-apps/pwa.sports-crowd.com/src/app/pages/flash-tickets/flash-tickets.page.ts
import { Component, OnInit, ViewChild } from '@angular/core';
import { AlertController, NavController } from "@ionic/angular";
import { StorageService } from '../../services/storage.service';
import { TicketsService } from "../../services/tickets.service";
import { UtilsService } from "../../services/utils.service";
import { UserService } from "../../services/user.service";
import { TranslateService } from "@ngx-translate/core";
import { CurrencyPipe } from "@angular/common";
import { ActivatedRoute, Router } from '@angular/router';
import { ParameterService } from '../../services/parameter.service';
import { CorporateIdentityService } from '../../services/corporate-identity.service';
@Component({
selector: 'app-flash-tickets',
templateUrl: './flash-tickets.page.html',
styleUrls: ['./flash-tickets.page.scss'],
})
export class FlashTicketsPage implements OnInit {
@ViewChild('content') private content: any;
emptySettingsSlide: any = {};
matchEvents: any = [];
tribunesParent: any = [];
activeTribunesParent: any = [];
matchEventId: number;
seasonId: number;
buyTickets: any = [];
tickets: any = [];
ticketTypeId: number = 1; // Venta libre
subtotal: number = 0;
serviceChargeEnabled: boolean = false;
serviceCharge: number = 0;
total: number;
oldTotal: number = 0;
valuePointsCoin: any;
currentCoinsInMoney: number = 0;
payWithCoins: boolean = false;
credit_locked: boolean = true;
maximum: number = 0;
purchased: number = 0;
availabled: number = 0;
tribuneParentId: any;
quantity: number = 0;
disableAddButton: boolean = false;
parameters: any;
flashTicketIcon: string = 'assets/img/appicon.png';
flashStadiumImage: string = 'assets/img/appicon.png'
widthStadiumImage: string = '50%';
showImgSport: boolean;
infoUser: any = {};
isSubscriptionPurchase: boolean = false;
preSubscriberTickets: any = [];
enablePaymentWithCoins: boolean = false;
time: number;
currentCupon: string = "";
availableCupon: 'yes' | 'no' = "no";
showCouponInput: boolean = false;
availableInputCupon: boolean = true;
presuscription: number = 0;
currency: string;
constructor(
public userProvider: UserService,
private storage: StorageService,
private ticketsService: TicketsService,
private utilsService: UtilsService,
public translateService: TranslateService,
public alertController: AlertController,
public navCtrl: NavController,
private currencyPipe: CurrencyPipe,
private router: Router,
public parameterService: ParameterService,
public route: ActivatedRoute,
private corporateIdentityService: CorporateIdentityService
) {
this.currency = this.corporateIdentityService.getCurrency();
}
async ngOnInit() {
this.matchEventId = parseInt(this.route.snapshot.paramMap.get("matchEventId")) ?? 0;
this.presuscription = parseInt(this.route.snapshot.paramMap.get("presuscription")) ?? 0;
this.time = new Date().getTime();
this.parameterService.getParameters('flash_ticket_icon,flash_stadium_image,service_charge_enabled').then((resp: any) => {
this.parameters = resp.parameters;
if (this.parameters.flash_ticket_icon)
this.flashTicketIcon = this.parameters.flash_ticket_icon;
if (this.parameters.flash_stadium_image) {
this.flashStadiumImage = this.parameters.flash_stadium_image
this.widthStadiumImage = '100%';
}
if (this.parameters.service_charge_enabled)
this.serviceChargeEnabled = this.parameters.service_charge_enabled;
if (this.presuscription > 0) {
this.emptySettingsSlide = {
showImage: false,
urlImage: "",
showText: true,
text: this.translateService.instant("tickets.empty_subscriptions"),
};
this.isSubscriptionPurchase = true;
this.storage.get("infoUser").then((infoUser) => {
this.infoUser = infoUser;
this.getTicketsSubscriptions(infoUser.document);
});
} else {
this.emptySettingsSlide = {
showImage: false,
urlImage: "",
showText: true,
text: this.translateService.instant("tickets.empty_events"),
};
this.isSubscriptionPurchase = false;
this.getMatchEvents(this.matchEventId);
}
});
}
getMatchEvents(matchEventId = null) {
this.buyTickets = [], this.matchEvents = [];
this.quantity = 0;
if (matchEventId) {
this.matchEvents = this.ticketsService.matchEvents;
this.getTribunesParentFlashTicket(matchEventId);
} else {
this.storage.get("token").then(async (token) => {
this.utilsService.presentLoading(this.translateService.instant("all.loading"));
(await this.ticketsService.getMatchEvents(token.access_token)).subscribe(
(resp: any) => {
this.utilsService.dismissLoading();
this.showImgSport = true;
resp.forEach((item: any) => {
if (this.utilsService.validateDate(item.event_start_sale, "start") && this.utilsService.validateDate(item.event_end_sale, "end")) {
this.matchEvents.push(item);
}
});
if (this.matchEvents.length == 1) {
this.getTribunesParentFlashTicket(this.matchEvents[0].id);
}
},
(error) => {
this.utilsService.dismissLoading();
this.utilsService.presentToast(3000, "danger", "top", this.translateService.instant("all.error_request"));
console.log("error getMatchEvents: ", error);
}
);
});
}
}
getTribunesParentFlashTicket(matchEventId: number, availableCupon = false) {
this.availableInputCupon = true;
if (matchEventId) {
this.showImgSport = false;
this.buyTickets = [], this.tribunesParent = [], this.activeTribunesParent = [];
this.maximum = 0, this.purchased = 0, this.availabled = 0, this.quantity = 0;
this.tribuneParentId = null;
let matchEvent = this.matchEvents.find((match: object) => match['id'] === matchEventId);
this.matchEventId = matchEventId;
this.seasonId = matchEvent['season_id'];
this.storage.get("token").then(async (token) => {
this.utilsService.presentLoading(this.translateService.instant("all.loading"));
(await this.ticketsService.validateUserTickets(token.access_token, this.ticketTypeId, this.matchEventId)).subscribe(
async (resp: any) => {
if (resp.r) {
this.maximum = resp.maximum;
this.purchased = resp.purchased;
this.availabled = resp.maximum - resp.purchased;
this.utilsService.presentToast(5000, "success", "top", this.translateService.instant("flash_tickets.msg_match_ticket_summary", { availabled: this.availabled, purchased: this.purchased }));
(await this.ticketsService.getTribunesParentFlashTicket(token.access_token, this.matchEventId, availableCupon, this.currentCupon)).subscribe(
(resp: any) => {
this.showCouponInput = resp.validateCouponexits;
resp.flashTicket.forEach((item: any) => {
if (item.apply_coupon_type == 'special_price' && item.coupon == this.currentCupon) {
item.price = item.special_price;
}
});
resp = resp.flashTicket;
this.utilsService.dismissLoading();
this.tribunesParent = resp;
if (resp.length == 1) {
this.activeTribunesParent = resp;
this.scrollToBottom();
}
if (this.serviceChargeEnabled)
this.serviceCharge = Math.max(...this.tribunesParent.map((tribune: any) => tribune.service_charge));
},
(error) => {
this.utilsService.dismissLoading();
this.utilsService.presentToast(3000, "danger", "top", this.translateService.instant("all.error_request"));
console.log("error getTribunesParentFlashTicket: ", error);
}
);
} else {
this.utilsService.dismissLoading();
this.utilsService.presentToast(4000, "warning", "top", resp.m);
}
},
(error) => {
this.utilsService.dismissLoading();
this.utilsService.presentToast(3000, "danger", "top", this.translateService.instant("all.error_request"));
console.log("error validateUserTickets: ", error);
}
);
});
}
}
getActiveTribunesParent(tribunesParent: any) {
this.activeTribunesParent = [];
this.activeTribunesParent = this.tribunesParent.filter((tribune: object) => tribunesParent.includes(tribune['id']));
this.tribunesParent = this.tribunesParent.map((tribune: object) => {
if (!tribunesParent.includes(tribune['id'])) {
tribune['quantity'] = 0;
}
return tribune;
});
this.buyTickets = this.buyTickets.filter((tribune: object) => tribunesParent.includes(tribune['id']));
this.disabledAddButtonOptions();
this.calculateTotal();
this.scrollToBottom();
}
removeTicketCart(tribune: object) {
let variablePrice = 'price'
if (!tribune['quantity']) {
tribune['quantity'] = 0;
}
let ticket = this.buyTickets.find((ticket: object) => ticket['id'] === tribune['id']);
if (ticket) {
tribune['quantity']--;
tribune['priceTickets'] = tribune['quantity'] * tribune[variablePrice];
ticket['quantity'] = tribune['quantity'];
ticket['priceTickets'] = tribune['priceTickets'];
if (ticket['quantity'] === 0) {
this.buyTickets = this.buyTickets.filter((item: object) => item !== ticket);
}
}
this.disabledAddButtonOptions();
this.calculateTotal();
this.scrollToBottom();
}
addTicketCart(tribune: object) {
let variablePrice = 'price';
if (!tribune['quantity']) {
tribune['quantity'] = 0;
}
let ticket = this.buyTickets.find((ticket: object) => ticket['id'] === tribune['id']);
if (!ticket) {
tribune['quantity'] = 1;
tribune['priceTickets'] = tribune[variablePrice];
this.buyTickets.push({
'id': tribune['id'],
'zone_id': tribune['zone_id'],
'match_event_id': this.matchEventId,
'quantity': tribune['quantity'],
'price': tribune[variablePrice],
'priceTickets': tribune['priceTickets']
});
} else {
tribune['quantity']++;
tribune['priceTickets'] = tribune['quantity'] * tribune[variablePrice];
ticket['quantity'] = tribune['quantity'];
ticket['priceTickets'] = tribune['priceTickets'];
}
this.disabledAddButtonOptions();
this.calculateTotal();
this.scrollToBottom();
}
calculateTotal() {
this.subtotal = 0;
if (this.buyTickets.length) {
this.subtotal = this.buyTickets.reduce((accumulator, obj) => {
return accumulator + obj.priceTickets;
}, 0);
}
this.total = this.subtotal + this.serviceCharge;
}
scrollToBottom() {
setTimeout(() => {
this.content.scrollToBottom(500);
}, 200);
}
disabledAddButtonOptions() {
this.quantity = this.buyTickets.reduce((accumulator, obj) => {
return accumulator + obj.quantity;
}, 0);
if (this.quantity === this.availabled) {
this.disableAddButton = true;
} else {
this.disableAddButton = false;
}
}
validateCreateBlocks() {
if (this.userProvider.validateAlertsUseApp()) {
this.tickets = [];
this.storage.get("token").then(async (token) => {
this.utilsService.presentLoading(this.translateService.instant("all.loading"));
(await this.ticketsService.validateSeatsAvailableByCapacity(token.access_token, this.buyTickets)).subscribe(
(resp: any) => {
this.utilsService.dismissLoading();
for (let i = 0; i < resp.length; i++) {
let tribune = resp[i];
if (!tribune['seats']) {
this.utilsService.dismissLoading();
let tribuneParent = this.tribunesParent.find((item: object) => item['id'] === tribune['id']);
this.utilsService.presentToast(4000, "warning", "top", this.translateService.instant("flash_tickets.msg_maximum_capacity", { location: tribuneParent['zone']['name'] }));
return false;
}
for (let j = 0; j < tribune['seats'].length; j++) {
let seat = tribune['seats'][j];
this.tickets.push({
'seat': {
'id': seat['id'],
'zone_id': seat['zone_id']
},
'match_event_id': this.matchEventId,
'ticket_type_id': this.ticketTypeId,
'price': tribune['price']
});
}
}
this.createBlocks();
},
(error) => {
this.utilsService.dismissLoading();
this.utilsService.presentToast(3000, "danger", "top", this.translateService.instant("all.error_request"));
console.log("error validateCreateBlocks: ", error);
}
);
});
}
}
createBlocks() {
this.storage.get("token").then(async (token) => {
this.utilsService.presentLoading(this.translateService.instant("all.loading"));
let info = {
tickets: this.tickets,
type_process: "block",
subtotal: this.subtotal,
serviceCharge: this.serviceCharge,
amount: this.total,
ticket_type_id: this.ticketTypeId,
season_id: this.seasonId,
payWithCoins: this.payWithCoins,
coinsInMoney: this.oldTotal,
coinsUsed: Math.round(this.oldTotal / this.valuePointsCoin),
currentValuePoint: this.valuePointsCoin
};
(await this.ticketsService.createBlocks(token.access_token, info)).subscribe(
async (resp: any) => {
if (resp.r) {
if (!this.payWithCoins) {
this.utilsService.dismissLoading();
this.utilsService.presentToast(5000, "success", "top", resp.m.replaceAll('\\n', '\n'), true);
this.router.navigate(["/payment-gateway-selection"], { state: { ticketId: resp.data } });
} else {
(await this.ticketsService.generateTicketBycoins(token.access_token, resp.data)).subscribe(
(resp: any) => {
this.utilsService.dismissLoading();
if (resp.r) {
this.alertForceBack(this.translateService.instant("tickets.alert"), this.translateService.instant("tickets.msg_ticketByCoins"));
} else {
if (resp.locked) {
this.credit_locked = true;
}
this.utilsService.presentToast(4000, "warning", "top", resp.m);
}
},
(error) => {
this.utilsService.dismissLoading();
this.utilsService.presentToast(3000, "danger", "top", this.translateService.instant("all.error_request"));
console.log("error generateTicketBycoins: ", error);
});
}
} else {
this.utilsService.dismissLoading();
this.utilsService.presentToast(4000, "warning", "top", resp.m);
}
},
(error) => {
this.utilsService.dismissLoading();
this.utilsService.presentToast(3000, "danger", "top", this.translateService.instant("all.error_request"));
console.log("error createBlocks: ", error);
}
);
});
}
async presentAlertConfirmExit() {
const alert = await this.alertController.create({
header: this.translateService.instant("tickets.alert"),
message: this.translateService.instant("tickets.exit_alert"),
buttons: [
{
text: "No",
role: "cancel",
cssClass: "secondary",
handler: () => { },
},
{
text: "Si",
handler: () => {
this.back();
},
},
],
});
await alert.present();
}
async alertForceBack(header: string, message: string) {
const alert = await this.alertController.create({
header: header,
message: message,
backdropDismiss: false,
buttons: [
{
text: "Ok",
handler: () => {
this.back();
},
},
],
});
await alert.present();
}
back() {
this.navCtrl.back();
}
getCurrency(amount: number) {
return this.currencyPipe.transform(amount, "USD", "symbol", "1.0-0");
}
getTicketsSubscriptions(document: any) {
this.buyTickets = [], this.preSubscriberTickets = [];
this.storage.get("token").then(async (token) => {
this.utilsService.presentLoading(this.translateService.instant("all.loading"));
(await this.ticketsService.getTicketsSubscriptions(token.access_token, document)).subscribe(
(resp: any) => {
this.utilsService.dismissLoading();
if (!resp.r) {
this.alertForceBack(this.translateService.instant("tickets.alert"), resp.message.replaceAll('\\n', '\n'));
return;
}
if (resp.pre_subscriber) {
resp.pre_subscriber.forEach((item: any) => {
item.seat_name = item.seat.zone.zone.name + ' - ' + item.seat.zone.name + ' - ' + item.seat.letter.name + ' - ' + item.seat.code;
this.preSubscriberTickets.push(item);
});
}
},
(error) => {
this.utilsService.dismissLoading();
this.utilsService.presentToast(3000, "danger", "top", this.translateService.instant("all.error_request"));
console.log("error getTicketsSubscriptions: ", error);
}
);
});
}
changePurchaseStatus(e) {
let id = parseInt(e.detail.value);
let ticket = this.buyTickets.find((item: object) => item['id'] === id);
if (!ticket) {
ticket = this.preSubscriberTickets.find((item: object) => item['id'] === id);
this.buyTickets.push({
'id': id,
'priceTickets': ticket['price']
});
} else {
this.buyTickets = this.buyTickets.filter((item: object) => item !== ticket);
}
this.calculateTotal();
this.scrollToBottom();
}
createPurchaseSubscribers() {
if (this.userProvider.validateAlertsUseApp()) {
this.parameterService.getParameters('presuscription').then((resp: any) => {
this.parameters = resp.parameters;
if (!this.parameters.presuscription) {
this.utilsService.presentToast(4000, "warning", "top", this.parameters.msj_inactivity_subscriber_ticket_sales ?? this.translateService.instant("tickets.title_message_9"));
return;
}
let subscribers = this.buyTickets.map((item: object) => { return item['id'] });
let document = this.infoUser.document;
let info = {
abonados_array: subscribers,
user_abonado: document,
match_event_id: this.matchEventId
}
this.storage.get("token").then(async (token) => {
this.utilsService.presentLoading(this.translateService.instant("all.loading"));
(await this.ticketsService.createPurchaseSubscribers(token.access_token, info)).subscribe(
(resp: any) => {
this.utilsService.dismissLoading();
if (!resp.r) {
this.utilsService.presentToast(4000, "warning", "top", resp.m.replaceAll('\\n', '\n'));
return;
}
this.utilsService.presentToast(5000, "success", "top", resp.m);
this.router.navigate(["/payment-gateway-selection"], { state: { ticketId: resp.data } });
},
(error) => {
this.utilsService.dismissLoading();
this.utilsService.presentToast(3000, "danger", "top", this.translateService.instant("all.error_request"));
console.log("error createPurchaseSubscribers: ", error);
}
);
});
});
}
}
onKeyPress(event: any) {
if (event.key === ' ') {
event.preventDefault();
}
}
inputCupon() {
// validate if exist a cupon is not empty
if (this.currentCupon.trim().length == 0) {
return;
}
// cuponlist is a current cupont split with ,
this.currentCupon = this.currentCupon.trim();
this.ticketsService.validateCouponExist(this.matchEventId, this.currentCupon).then((resp: any) => {
if (resp.status) {
this.getTribunesParentFlashTicket(this.matchEventId, true);
this.availableInputCupon = false;
this.utilsService.presentToast(4000, "success", "top", resp.message);
} else {
this.utilsService.presentToast(4000, "warning", "top", resp.message);
}
});
}
validatePrice(tribune: any): number {
return tribune.price;
}
}