File: /var/www/vhost/disk-apps/pwa.sports-crowd.com/src/app/pages/ticket-detail/ticket-detail.page.ts
import { ImageService } from './../../services/image.service';
import { Component, OnInit } from "@angular/core";
import { StorageService } from '../../services/storage.service';
import { CityService } from "../../services/city.service";
import { UtilsService } from "../../services/utils.service";
import { ActivatedRoute } from "@angular/router";
import { Platform } from "@ionic/angular";
import { TranslateService } from "@ngx-translate/core";
import { HomeService } from "../../services/home.service";
import { CartService } from "../../services/cart.service";
import { TicketsService } from "../../services/tickets.service";
import { TermService } from "../../services/term.service";
import { Capacitor } from '@capacitor/core';
import { Share } from '@capacitor/share';
import { Directory, Filesystem } from '@capacitor/filesystem';
import { Http, HttpDownloadFileResult } from '@capacitor-community/http';
import { trigger, style, transition, animate } from '@angular/animations';
import * as CryptoJS from 'crypto-js';
import { PrivacyScreen } from '@capacitor-community/privacy-screen';
import { OfflineTicketingService } from 'src/app/services/ticketing/offline-ticketing.service';
@Component({
selector: "app-ticket-detail",
templateUrl: "./ticket-detail.page.html",
styleUrls: ["./ticket-detail.page.scss"],
animations: [
trigger('imageChange', [
transition(':enter', [
style({ opacity: 0 }),
animate('0.5s', style({ opacity: 1 })),
]),
transition(':leave', [
animate('0.5s', style({ opacity: 0 }))
])
])
]
})
export class TicketDetailPage implements OnInit {
width: any;
showDetails: boolean;
txtTerms: string;
params: any;
ticketParams: any = {};
data_ticket: any = {};
userInfo: any = {};
classTicketZone: string = "fz-12";
private timer: any;
public timerPercent = 100;
public qrRotationAngle = 0;
private urlGallery;
public currentTicket;
time: number;
constructor(
private cityService: CityService,
public homeProvider: HomeService,
public cartService: CartService,
private storage: StorageService,
public route: ActivatedRoute,
public platform: Platform,
private utilsService: UtilsService,
public translateService: TranslateService,
private imageService: ImageService,
public ticketService: TicketsService,
public termService: TermService,
public ticketsService: TicketsService,
private offlineTicketingService: OfflineTicketingService
) { }
ionViewWillEnter() {
this.platform.ready().then((readySource) => {
this.width = this.platform.width() > 415 ? 415 : this.platform.width();
this.utilsService.closeAllAlerts();
});
}
ngOnInit() {
let code = this.route.snapshot.paramMap.get('code');
this.offlineTicketingService.getTickets().then(async (data) => {
this.currentTicket = data.filter(item => item.code_ticket === code)[0];
this.loadInit();
});
this.showDetails = false;
this.time = new Date().getTime();
}
loadInit(time = 0) {
setTimeout(() => {
return new Promise((resolve, reject) => {
this.utilsService.presentLoading(this.translateService.instant("all.loading")).then(async () => {
Promise.all([
this.urlGallery = await this.cityService.getGalleryUrl(),
await this.storage.get("parameters").then((parameters) => {
if (parameters) {
this.params = parameters;
this.params['hideDataSeat'] = this.params.activate_flash_ticketing && !this.params.presuscription;
}
}),
await this.offlineTicketingService.getTicketParameters().then(async (data) => {
this.ticketParams = data;
}),
await this.storage.get("infoUser").then((u) => {
this.userInfo = u;
}),
this.translateService.get(["terms_and_conditions_body", "terms_and_conditions_body_footer"]).subscribe((txt) => {
this.txtTerms = txt.terms_and_conditions_body + " " + txt.terms_and_conditions_body_footer;
}),
this.setDataTicket(),
this.setDynamicQrInterval(),
this.setScreenshotPermission()
]).then(() => {
this.utilsService.closeAllAlerts();
resolve(false);
}).catch((error) => {
this.utilsService.closeAllAlerts();
console.log('Error loadInit TicketDetails', error);
reject(error);
});
});
});
}, time);
}
async setDataTicket() {
let teamData = await this.offlineTicketingService.getTeamData();
this.data_ticket["code_ticket"] = this.getQrCodeData();
this.data_ticket["url_ticket_backgroung"] = this.currentTicket.match_event.season.tournament.ticket_background ?
this.urlGallery + 'tournaments/' + this.currentTicket.match_event.season.tournament.ticket_background : this.params.url_ticket_backgroung;
this.data_ticket["url_ticket_sponsor"] = this.currentTicket.match_event.season.tournament.footer_sponsors ?
this.urlGallery + 'tournaments/' + this.currentTicket.match_event.season.tournament.footer_sponsors : this.params.url_ticket_sponsor;
this.data_ticket["url_team_main"] = 'assets/img/appicon.png';
this.data_ticket["url_tournament"] = this.currentTicket.match_event.season.tournament?.logo ? this.urlGallery + 'tournaments/' + this.currentTicket.match_event.season.tournament.logo : null;
this.data_ticket["url_organizer"] = this.currentTicket.match_event.season.tournament?.tournament_organizer?.logo ? this.urlGallery + 'organizer/' + this.currentTicket.match_event.season.tournament.tournament_organizer.logo : null;
this.data_ticket["tournament"] = this.currentTicket.match_event.season.tournament.name;
this.data_ticket["date_name"] = this.currentTicket.match_event.date_name;
if (this.currentTicket.match_event.stadium_to_play) {
this.data_ticket["stadium_to_play"] = this.currentTicket.match_event.stadium_to_play;
}
this.data_ticket["match_teams"] = `${teamData.display_name} vs ${this.currentTicket.match_event.team.display_name}`;
this.data_ticket["date_event"] = `${this.utilsService.formataDate(this.currentTicket.match_event.event_start, 'dd-mm-yyy')}`;
this.data_ticket["abbr_local"] = `${teamData?.abbreviation}`;
this.data_ticket["abbr_visit"] = `${this.currentTicket.match_event.team.abbreviation}`;
this.data_ticket["time"] = `${this.currentTicket.match_event.event_start.slice(11, 16)}`;
let tribune = this.params.hideDataSeat ? `${this.currentTicket.seat.zone.zone.name}` : `${this.currentTicket.seat.zone.zone.name.slice(0, 3)}`;
let zones = `${this.currentTicket.zone}`.split("_"); // explode("_", $this->ticket->zone);
let zone = zones[0];
let ticketZone = '';
if (zones.length > 1)
ticketZone = zones[1];
else {
zones = `${this.currentTicket.zone}`.split(" ");
if (zones[0].includes(tribune)) {
zone = zones[1];
} else {
zone = zones[0];
}
ticketZone = `${this.currentTicket.zone}`.split(zone + ' ')[1];
zone = zone.slice(0, 3);
}
tribune = tribune.toUpperCase();
if (zone)
this.data_ticket["tribune"] = tribune + '-' + zone;
else
this.data_ticket["tribune"] = tribune;
if (ticketZone.length > 10) {
this.classTicketZone = "fz-8";
} else if (ticketZone.length > 2 && ticketZone.length <= 10) {
this.classTicketZone = "fz-10";
} else {
this.classTicketZone = "fz-12";
}
this.data_ticket["specialTicket"] = `${this.currentTicket.special_text}`;
this.data_ticket["ticketZone"] = ticketZone;
this.data_ticket["ticketRow"] = `${this.currentTicket.seat.letter.name}`;
this.data_ticket["ticketSeat"] = `${this.currentTicket.seat.code}`;
this.data_ticket["user"] = `${this.userInfo.first_name.split(" ")[0]} ${this.userInfo.last_name.split(" ")[0]}`;
this.data_ticket["document"] = `${this.userInfo.document}`;
this.data_ticket["price"] = `${this.utilsService.formatCurrency(this.currentTicket.price)}`;
if (this.currentTicket.cufe) {
this.data_ticket["cufe"] = `${this.currentTicket.cufe}`;
}
if (this.currentTicket.invoice_link) {
this.data_ticket["invoice_link"] = `${this.currentTicket.invoice_link}`;
}
}
calculateWidth(percentage) {
if (percentage && this.width) {
let cal = (this.width * percentage) / 100;
return parseInt(cal.toString());
}
}
toggleDetails() {
if (this.ticketParams.terms) {
this.utilsService.presentSeeDocument(this.translateService.instant("terms_and_conditions_tickets"), this.ticketParams.terms);
return;
}
this.showDetails = !this.showDetails;
}
toggleInvoice(link) {
this.utilsService.openLink(link);
}
async downloadTicket() {
if (Capacitor.getPlatform() === 'ios') {
this.utilsService.presentLoading(this.translateService.instant("all.loading"));
(await this.ticketsService.getPdf(this.data_ticket.code_ticket, Capacitor.getPlatform())).subscribe(async (resp: any) => {
let fileName = "SportsCrowd_" + new Date().getTime() + '.pdf';
const options = {
url: (await this.cityService.getApiUrl()) + '/ticket/pdf/' + resp.data,
filePath: fileName,
fileDirectory: Directory.Documents,
method: 'GET',
};
const response: HttpDownloadFileResult = await Http.downloadFile(options);
if (response.path) {
const finalPhotoUri = await Filesystem.getUri({
directory: Directory.Documents,
path: fileName
});
this.utilsService.dismissLoading();
Share.share({
title: fileName,
url: finalPhotoUri.uri
}).then(() => {
this.utilsService.presentToast(3000, "success", "top", this.translateService.instant("ticket_download"));
this.utilsService.dismissLoading();
}).catch(e => {
});
}
},
(error) => {
console.log("error getTickets: ", error);
}
);
} else {
var pdfBlock = document.getElementById("print-wrapper");
this.imageService.exportCanvasImage(pdfBlock, this.translateService.instant("ticket_download"));
}
}
ngOnDestroy() {
clearInterval(this.timer);
}
setScreenshotPermission() {
if (Capacitor.isNativePlatform()) {
switch (this.ticketParams.qrcode_type) {
case 'static':
PrivacyScreen.disable();
break;
default:
PrivacyScreen.enable();
break;
}
}
}
setDynamicQrInterval() {
if (this.ticketParams.qrcode_type != 'static' && Number(this.ticketParams.qrcode_time) > 0) {
this.timer = setInterval(() => {
this.timerPercent = 0;
if (this.ticketParams.qrcode_type != 'with_timestamp') {
this.qrRotationAngle += 90;
}
setTimeout(async () => {
this.data_ticket.code_ticket = this.getQrCodeData();
this.timerPercent = 100;
}, 200);
}, this.ticketParams.qrcode_time * 1000);
}
}
encryptDataAES(data) {
var key = CryptoJS.enc.Hex.parse("0123456789abcdef0123456789abcdef");
var iv = CryptoJS.enc.Hex.parse("abcdef9876543210abcdef9876543210");
var secret = '{"timestamp": "' + new Date().getTime() + '", "data": "' + data + '"}';
var encrypted = CryptoJS.AES.encrypt(secret, key, { iv: iv });
encrypted = encrypted.ciphertext.toString(CryptoJS.enc.Base64).replace('+', '-').replace('/', '_');
return encrypted
}
getQrCodeData() {
let ticketCode = `${this.currentTicket.code_ticket}`;
switch (this.ticketParams.qrcode_type) {
case 'with_timestamp':
return this.encryptDataAES(ticketCode);
default:
return ticketCode;
}
}
}