integracao-core

This commit is contained in:
2025-10-23 16:58:21 -03:00
parent 8b5c940976
commit c8c2ca8c5b
19 changed files with 408 additions and 16 deletions
+286
View File
@@ -0,0 +1,286 @@
import { jwtDecode } from 'jwt-decode';
import { RedirectService } from './pages/RedirectService';
export class GlobalFunctions {
public static getTranferAreaObj(): TransferAreaResponse {
let objRetorno: TransferAreaResponse = {
aplicativoID: 0,
aplicativoNome: "",
areaTransferenciaID: 0,
dataRegistro: "",
estabelecimentoID: 0,
usuarioID: 0,
usuarioEmail: "",
usuarioNome: "",
aplicativoShareCode: "",
nivelAcesso: 0
};
try {
const objTransferStr = sessionStorage.getItem("TRANSFER_AREA");
if (
objTransferStr != null &&
objTransferStr != undefined &&
objTransferStr.trim() != ""
) {
const objTransfer = <TransferAreaResponse>JSON.parse(objTransferStr);
objRetorno = objTransfer;
}
} catch (error) {}
return objRetorno;
}
public static getRedirectComponent(): string {
let objRetorno = "";
try {
const objTransfer = GlobalFunctions.getTranferAreaObj();
if (objTransfer != null) {
// let objRedir = objTransfer.find(x => x.name == 'REDIRECT');
// objRetorno = objRedir?.value ?? '';
objRetorno = objTransfer.urlDestino ?? "";
if (objRetorno.startsWith("/")) objRetorno = objRetorno.substring(1);
} else {
objRetorno = "";
}
} catch (error) {
//console.log(error);
objRetorno = "";
}
return objRetorno;
}
public static getTransferProperty(propertyName: TransferAreaProperties): any {
let objRetorno: any = "";
try {
const objTransfer = this.getTranferAreaObj();
if (objTransfer != null) {
//let obj: any = objTransfer[propertyName];
const element = objTransfer[propertyName];
objRetorno = element;
} else {
objRetorno = null;
}
} catch (error) {
objRetorno = null;
}
return objRetorno;
}
public static isUsuarioLogado(): boolean {
let jsonUsuario = sessionStorage.getItem('usuarioLogado');
if (jsonUsuario) {
let tokenDecode: any = GlobalFunctions.getUsuarioLogado();
let d: Date = new Date();
let dateAtual: number = Date.UTC(d.getFullYear(), d.getUTCMonth(), d.getUTCDate(), d.getUTCHours(), d.getUTCMinutes() + 5, d.getUTCSeconds()) / 1000;
if (dateAtual > tokenDecode.exp) return false;
return true;
}
return false;
}
public static tokenExpired(tokenDecode: any): boolean {
let d: Date = new Date();
let dateAtual: number = Date.UTC(d.getFullYear(), d.getUTCMonth(), d.getUTCDate(), d.getUTCHours(), d.getUTCMinutes() + 5, d.getUTCSeconds()) / 1000;
if (dateAtual > tokenDecode.exp) return true;
return false;
}
public static handleNavigateBack(): void {
try {
// Verifica se existe histórico de navegação
if (window.history && window.history.length > 1) {
window.history.back();
return;
}
// Tenta fechar a janela
if (!window.closed) {
try {
const windowRef = window.open('', '_self');
if (windowRef) {
windowRef.close();
// Pequeno timeout para verificar se a janela foi fechada
setTimeout(() => {
// Se ainda estiver aberta, redireciona
if (!windowRef.closed) {
window.location.href = "https://core.hgtx.com.br/aplicativos/";
}
}, 100);
return;
}
} catch (closeError) {
console.warn("Não foi possível fechar a janela:", closeError);
}
}
// Se não conseguiu fechar, redireciona
window.location.href = "https://core.hgtx.com.br/aplicativos/";
} catch (error) {
// Em caso de qualquer erro, garante o redirecionamento
console.error("Erro ao tentar navegar:", error);
window.location.href = "https://core.hgtx.com.br/aplicativos/";
}
}
public static getUsuarioLogado(): UsuarioLogadoData {
const jsonUsuario = sessionStorage.getItem("usuarioLogado") ?? "";
try {
const objJwt = JSON.parse(jsonUsuario);
//return jwt_decode(objJwt.token);
return jwtDecode(objJwt.token);
} catch (error) {}
return {
EID: "0",
email: "",
exp: 0,
iat: 0,
jti: "",
name: "",
nbf: 0,
UID: "0",
};
}
public static getUsuarioLogadoToken(): string {
let retorno = "";
const jsonUsuario = sessionStorage.getItem("usuarioLogado") ?? "";
try {
const objJwt = JSON.parse(jsonUsuario);
retorno = objJwt.token;
} catch (error) {}
return retorno;
}
public static getUsuarioLogadoRefreshToken(): string {
let retorno = "";
const jsonUsuario = sessionStorage.getItem("usuarioLogado") ?? "";
try {
const objJwt = JSON.parse(jsonUsuario);
retorno = objJwt.refreshToken;
} catch (error) {}
return retorno;
}
public static getPerfilUsuario(): PerfilUsuario | null {
let retorno: PerfilUsuario | null = null;
const jsonUsuario = sessionStorage.getItem("perfilUsuario") ?? "";
try {
const objJwt = <PerfilUsuario>JSON.parse(jsonUsuario);
retorno = objJwt;
} catch (error) {
retorno = null;
}
return retorno;
}
public static getHighUserProfile(): number {
let retorno = 6;
const objPerfil = GlobalFunctions.getPerfilUsuario();
if (objPerfil) {
const tiposPerfil: number[] = objPerfil.results.map((v) => v.tipoPerfil);
retorno = Math.min(...tiposPerfil);
}
return retorno;
}
public static async getToken(): Promise<string> {
let token: string = GlobalFunctions.getUsuarioLogadoToken();
const tokenDecode: any = GlobalFunctions.getUsuarioLogado();
let currentDate = new Date();
// JWT exp is in seconds
if ((tokenDecode.exp * 1000) < currentDate.getTime()) {
//console.log("Token expired.");
let gsikey: number = parseInt(sessionStorage.getItem('gsikey') ?? '0');
RedirectService.loadTransferArea(gsikey).then((response) => {
if(response.data.errorCode == 0){
sessionStorage.setItem('TRANSFER_AREA',JSON.stringify(response.data.areTrs));
sessionStorage.setItem('usuarioLogado',JSON.stringify({
token: response.data.jwt.token,
refreshToken: response.data.jwt.refreshToken
}));
token = response.data.jwt.token;
}
// else if(error !== 1401){
// navigate('/',{replace: true});
// }
});
}
// else {
// //console.log("Valid token");
// result = true;
// }
return token;
}
}
export interface UsuarioLogadoData {
UID: string;
EID: string;
name: string;
email: string;
jti: string;
nbf: number;
exp: number;
iat: number;
}
export interface TransferAreaResponse {
estabelecimentoID: number;
nivelAcesso: number;
aplicativoID: number;
usuarioID: number;
areaTransferenciaID: number;
dataRegistro: string;
urlBase?: string;
urlDestino?: string;
aplicativoNome: string;
usuarioNome: string;
usuarioEmail: string;
aplicativoShareCode: string;
}
export enum TransferAreaProperties {
EstabelecimentoCodigo = "estabelecimentoID",
UsuarioCodigo = "usuarioID",
UsuarioNome = "usuarioNome",
UsuarioEmail = "usuarioEmail",
APP_COD = "aplicativoID",
APP_TITULO = "aplicativoNome",
areaTransferenciaID = "areaTransferenciaID",
urlBase = "urlBase",
urlDestino = "urlDestino",
aplicativoShareCode = "aplicativoShareCode",
nivelAcesso = "nivelAcesso",
}
type PerfilUsuario = {
errorCode: number;
errorMessage: string;
results: PerfilUsuarioResult[];
};
export type PerfilUsuarioResult = {
tipoPerfil: number;
itens: PerfilUsuarioItem[];
};
type PerfilUsuarioItem = {
id: number;
descricao: string;
identificador: string;
};