Site/src/app/chaves/chaves.component.ts

321 lines
9.3 KiB
TypeScript

import { Component, OnInit } from '@angular/core';
import { SistemasService } from '../services/sistemas.service';
import { Chaves, Sistemas, ListChaves } from '../models/sistemasModel';
import { ActivatedRoute, Router } from '@angular/router';
import { environment } from 'src/environments/environment';
import { UsuariosService } from '../services/usuarios.service';
import { Usuarios } from '../models/usuariosModel';
import { ProdutosService } from '../services/produtosService';
import { ProdutosModel } from '../models/produtosModel';
@Component({
selector: 'app-chaves',
templateUrl: './chaves.component.html',
styleUrls: ['./chaves.component.scss', './../app.component.scss']
})
export class ChavesComponent implements OnInit {
FormChaves: Chaves = new Chaves();
Sistema: Sistemas = new Sistemas();
ListaDeChaves: ListChaves[];
Usuario: Usuarios = new Usuarios();
UserID: number = parseInt(localStorage.getItem("UserID"));
idsistemas: number = this.route.snapshot.params['idsistemas'];
LinkImagem: string;
Produtos: ProdutosModel[] = [];
constructor(
private sistemasService: SistemasService,
private route: ActivatedRoute,
private usuariosService: UsuariosService,
private router: Router,
private produtosService: ProdutosService
) { }
ngOnInit() {
this.sistemasService.getSistemaByID(this.idsistemas).then(resSistema => {
this.Sistema = resSistema;
this.LinkImagem = environment.LinkProjeto + "/sistemas/" + this.idsistemas + "/icone.png";
});
this.usuariosService.getUsuarioByID(this.UserID).then(resUsuario => {
this.Usuario = resUsuario;
});
this.produtosService.getProdutosSell(this.idsistemas).then(resProdutos => {
this.Produtos = resProdutos;
});
this.AtualizaChaves();
}
AtualizaChaves() {
this.sistemasService.getChavesSistemaLista(this.idsistemas, this.UserID).then(resChave => {
this.ListaDeChaves = resChave;
})
}
btnGerarClick() {
let Mensagem: string;
if (this.ListaDeChaves.length == 0) {
Mensagem = "A primeira chave do sistema é gerada gratuitamente com validade de 30 dias a partir de sua data de geração! Deseja gerar sua chave de avaliação agora?";
}
else {
//this.Pagamento = true;
//this.GerarChave(30);
if (confirm("Deseja solicitar uma nova chave de sistema?")) {
this.produtosService.buySistema(this.idsistemas, this.UserID, 1).then(res => {
//console.log(res);
alert("Você será redirecionado para a tela de pagamentos do Mercado Pago.\rQuando o pagamento for confirmado, a licença será gerada automaticamente e já aparecerá na sua lista de chaves!");
const paymentUrl = res['url'];
window.open(paymentUrl, '_blank');
});
}
return;
}
if (confirm(Mensagem)) {
this.GerarChave(30);
}
else {
return;
}
//this.GerarChave(30);
}
DataValidade(Dias: number) {
let DataAtual = new Date();
DataAtual.setDate(DataAtual.getDate() + Dias);
let DataFix =
DataAtual.toLocaleDateString()[0] +
DataAtual.toLocaleDateString()[1] +
DataAtual.toLocaleDateString()[3] +
DataAtual.toLocaleDateString()[4] +
DataAtual.toLocaleDateString()[6] +
DataAtual.toLocaleDateString()[7] +
DataAtual.toLocaleDateString()[8] +
DataAtual.toLocaleDateString()[9];
return DataFix;
}
GerarChave(Dias: number) {
let SerialKey: string;
let CPF = this.CryptText(this.Usuario.cpf);
let Validade = this.CryptText(this.DataValidade(Dias));
SerialKey =
Validade[0].toString() +
CPF[13].toString() +
CPF[0].toString() +
Validade[1].toString() +
CPF[12].toString() +
CPF[1].toString() +
Validade[2].toString() +
CPF[11].toString() +
CPF[2].toString() +
Validade[3].toString() +
CPF[10].toString() +
CPF[3].toString() +
Validade[4].toString() +
CPF[9].toString() +
CPF[4].toString() +
Validade[5].toString() +
CPF[8].toString() +
CPF[5].toString() +
Validade[6].toString() +
CPF[7].toString() +
CPF[6].toString() +
Validade[7].toString();
let DatValidade = new Date();
DatValidade.setDate(DatValidade.getDate() + Dias);
this.FormChaves.licenca = SerialKey;
this.FormChaves.idusuarios = this.UserID;
this.FormChaves.idsistemas = this.idsistemas;
this.FormChaves.data_validade = DatValidade;
this.sistemasService.insertChave(this.FormChaves).then(resInsert => {
if (resInsert['status'] == 200) {
alert("Chave de licença gerada com sucesso!");
this.AtualizaChaves();
}
else {
alert("Erro ao gerar chave! Por favor tente novamente mais tarde!");
}
})
}
CryptText(Texto: string)
{
let RandNumber: number;
let NewChar: string;
let FinalString: string = "";
let SwitchChar: string = "";
for (let i = 0; i <= Texto.length; i++)
{
RandNumber = Math.floor(Math.random() * 2);
SwitchChar = Texto.substring(i, 1)[Texto.substring(i, 1).length - 1];
if (SwitchChar != undefined) {
switch (SwitchChar)
{
case "0":
if (RandNumber == 0)
NewChar = "q";
else
NewChar = "3";
break;
case "1":
if (RandNumber == 0)
NewChar = "w";
else
NewChar = "5";
break;
case "2":
if (RandNumber == 0)
NewChar = "r";
else
NewChar = "4";
break;
case "3":
if (RandNumber == 0)
NewChar = "D";
else
NewChar = "6";
break;
case "4":
if (RandNumber == 0)
NewChar = "H";
else
NewChar = "9";
break;
case "5":
if (RandNumber == 0)
NewChar = "b";
else
NewChar = "7";
break;
case "6":
if (RandNumber == 0)
NewChar = "U";
else
NewChar = "8";
break;
case "7":
if (RandNumber == 0)
NewChar = "k";
else
NewChar = "1";
break;
case "8":
if (RandNumber == 0)
NewChar = "I";
else
NewChar = "0";
break;
case "9":
if (RandNumber == 0)
NewChar = "p";
else
NewChar = "2";
break;
default:
NewChar = "-";
break;
}
FinalString += NewChar;
}
}
return FinalString;
}
comprarLicenca(Produto: ProdutosModel) {
if (confirm("Deseja solicitar uma nova chave de sistema na versão " + Produto.descricao + "?")) {
this.produtosService.buySistema(Produto.idprodutos, this.UserID, 1).then(res => {
//console.log(res);
if (res['chave'] != null) {
alert("Chave gerada com sucesso!");
this.AtualizaChaves();
}
else {
alert("Você será redirecionado para a tela de pagamentos do Mercado Pago.\rQuando o pagamento for confirmado, a licença será gerada automaticamente e já aparecerá na sua lista de chaves!");
const paymentUrl = res['url'];
window.open(paymentUrl, '_blank');
}
});
}
}
copyToClipboard(chave: string) {
navigator.clipboard.writeText(chave).then(() => {
alert("Chave copiada para a área de transferência!");
});
}
NavegarSistema() {
const url = this.router.serializeUrl(
this.router.createUrlTree(['/detalhes/' + this.idsistemas])
);
window.open(url, '_blank');
}
getKeyCardClass(Chave: any): string {
const hoje = new Date();
hoje.setHours(0, 0, 0, 0);
const validade = new Date(Chave.DataValidade);
validade.setHours(0, 0, 0, 0);
const status = (Chave.Status || '').toString().toLowerCase();
const ativada = (Chave.Ativada || '').toString().toLowerCase();
const expirou = validade < hoje;
const estaAtivada =
ativada === 'sim' ||
ativada === 'true' ||
ativada === '1' ||
ativada === 'ativada';
const estaValida =
!expirou &&
(
status.includes('válida') ||
status.includes('valid') ||
status.includes('ativa') ||
status.includes('vigente') ||
status === 'ok'
);
//console.log("status: " + status + ", ativada: " + ativada + ", expirou: " + expirou + ", estaAtivada: " + estaAtivada + ", estaValida: " + estaValida)
if (expirou || status.includes('expir') || status.includes('venc')) {
return 'key-card-expired';
}
if (estaValida && estaAtivada) {
return 'key-card-active';
}
if (estaValida && !estaAtivada) {
return 'key-card-pending';
}
return 'key-card-neutral';
}
getKeyStatusLabel(Chave: any): string {
const cardClass = this.getKeyCardClass(Chave);
if (cardClass === 'key-card-expired') {
return 'Expirada';
}
if (cardClass === 'key-card-active') {
return 'Válida e ativada';
}
if (cardClass === 'key-card-pending') {
return 'Válida, aguardando ativação';
}
return 'Status indefinido';
}
}