Skip to content

Commit

Permalink
Merge pull request #4 from flrossetto/master
Browse files Browse the repository at this point in the history
Adiciona abertura automática de link na notificação
  • Loading branch information
gdfreitas authored Feb 12, 2021
2 parents 70db351 + b63d719 commit 998288a
Show file tree
Hide file tree
Showing 10 changed files with 70 additions and 74 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@betha-plataforma/estrutura-componentes",
"version": "1.0.5",
"version": "1.1.0",
"description": "Coleção de Web Components para compor a estrutura de uma aplicação front-end da Betha Sistemas.",
"main": "dist/index.js",
"module": "dist/index.mjs",
Expand Down
5 changes: 2 additions & 3 deletions src/components/marca-produto/marca-produto.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -94,12 +94,11 @@ export class MarcaProduto implements ComponentInterface {
const UserAccountsApi = new Api(authorization, this.authorization.handleUnauthorizedAccess, `${this.getUserAccountsApi()}/api`);

const promise = UserAccountsApi.request('GET', `access/${authorization.accessId}/systems`)
.then(res => res.json())
.then(produtos => {
this.produtos = produtos.filter((produto: Produto) => produto.id !== authorization.systemId);
})
.catch(() => {
this.isApiIndisponivel = true;
});
.catch(() => this.isApiIndisponivel = true);

this.tracker.addPromise(promise);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,7 @@ export class NotificacaoItem implements ComponentInterface {

private onClick = (event: UIEvent) => {
event.preventDefault();
event.stopPropagation();

const payload: NotificacaoLeituraEvent = {
id: this.identificador
Expand Down
2 changes: 2 additions & 0 deletions src/components/notificacoes/notificacoes.interfaces.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ export interface NotificacaoLink {
label?: string;
target: string;
href: string;
autoOpen: boolean;
}

export interface NotificacaoLeituraEvent {
Expand All @@ -25,6 +26,7 @@ export interface NotificacaoComLinkEvent {
// Esta interface representa a estrutura da notificação que vem da API
export interface Notificacao {
id: string;
systemId?: number;
sequence: number;
text: string;
source: string;
Expand Down
14 changes: 9 additions & 5 deletions src/components/notificacoes/notificacoes.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,19 +10,23 @@ export class NotificacoesService {
}

async buscar(params: PaginationQueryParams = { offset: 0, limit: 20 }): Promise<any> {
return this.api.request('GET', `api/messages/?limit=${params.limit}&offset=${params.offset}`);
return this.api.request('GET', `api/messages/?limit=${params.limit}&offset=${params.offset}`)
.then(res => res.json());
}

async buscarNaoLidas(params: PaginationQueryParams = { offset: 0, limit: 20 }): Promise<any> {
return this.api.request('GET', `api/messages/unreads/all?limit=${params.limit}&offset=${params.offset}`);
return this.api.request('GET', `api/messages/unreads/all?limit=${params.limit}&offset=${params.offset}`)
.then(res => res.json());
}

async buscarLidas(params: PaginationQueryParams = { offset: 0, limit: 20 }): Promise<any> {
return this.api.request('GET', `api/messages/reads?limit=${params.limit}&offset=${params.offset}`);
return this.api.request('GET', `api/messages/reads?limit=${params.limit}&offset=${params.offset}`)
.then(res => res.json());
}

async buscarEmProgresso(params: PaginationQueryParams = { offset: 0, limit: 20 }): Promise<any> {
return this.api.request('GET', `api/messages/in-progress?limit=${params.limit}&offset=${params.offset}`);
return this.api.request('GET', `api/messages/in-progress?limit=${params.limit}&offset=${params.offset}`)
.then(res => res.json());
}

async clearInProgressUnread(): Promise<any> {
Expand All @@ -33,7 +37,7 @@ export class NotificacoesService {
return this.api.request('DELETE', 'api/messages/unread?keepInProgress=true');
}

async setRead(notificationId: string): Promise<any> {
async setRead(notificationId: string): Promise<Response> {
return this.api.request('PUT', `api/messages/${notificationId}/read`);
}

Expand Down
28 changes: 25 additions & 3 deletions src/components/notificacoes/notificacoes.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -100,9 +100,7 @@ export class Notificacoes implements ComponentInterface {

this.notificacoesService
.setRead(event.detail.id)
.catch(() => {
this.marcarNotificacaoComoNaoLida(notificacao);
});
.catch(() => this.marcarNotificacaoComoNaoLida(notificacao));

this.marcarNotificacaoComoLida(notificacao);
}
Expand Down Expand Up @@ -278,6 +276,30 @@ export class Notificacoes implements ComponentInterface {
}

if (!isNill(message.link)) {

if (message.link.autoOpen) {
var auth = this.authorization.getAuthorization();

var timeout = message.systemId == null || (auth && message.systemId === auth.systemId)
? 0
: 3000;

setTimeout(() => {
this.notificacoesService.setRead(message.id)
.then((res) => {
if (res.status === 200) {
var target = '_blank';

if (isNill(message.identifier) && message.identifier != '') {
target = message.identifier as string;
}

window.open(message.link.href, target);
}
});
}, timeout);
}

this.novaNotificacaoComLink.emit({ texto: message.text, link: message.link });
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/components/novidades/novidades.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ export class NovidadesService {
}

async buscar(): Promise<any> {
return this.api.request('GET', 'api/novidades');
return this.api.request('GET', 'api/novidades').then(res => res.json());
}

marcarComoLida(novidadeId: string): void {
Expand Down
24 changes: 12 additions & 12 deletions src/global/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import { isNill } from '../utils/functions';
import { Authorization, AuthorizationConfig } from './interfaces';

const UNAUTHORIZED_STATUS_CODE = 401;
const OK_STATUS_CODE = 200;

export const isValidAuthorizationConfig = (authorization: AuthorizationConfig) => {
if (isNill(authorization)) {
Expand All @@ -25,19 +24,20 @@ export class Api {
private baseUrl: string
) { }

async request(method: string, path: string, retryUnauthorizedAccess: boolean = true): Promise<any> {
const response = await fetch(`${this.baseUrl}/${path}`, { method, headers: this.getHeaders() });
async request(method: string, path: string, retryUnauthorizedAccess: boolean = true): Promise<Response> {
return await fetch(`${this.baseUrl}/${path}`, { method, headers: this.getHeaders() })
.then(async response => {
if (response.status === UNAUTHORIZED_STATUS_CODE && retryUnauthorizedAccess && this.handleUnauthorizedAccess !== undefined) {
await this.handleUnauthorizedAccess();
return await this.request(method, path, false);
}

if (response.status === UNAUTHORIZED_STATUS_CODE && retryUnauthorizedAccess && this.handleUnauthorizedAccess !== undefined) {
await this.handleUnauthorizedAccess();
return await this.request(method, path, false);
}
if (response.status < 200 || response.status >= 300) {
throw new Error(response.statusText);
}

if (response.status !== OK_STATUS_CODE) {
throw new Error(response.statusText);
}

return await response.json().catch(() => null);
return Promise.resolve(response);
});
}

private getHeaders(): Headers {
Expand Down
4 changes: 2 additions & 2 deletions src/global/test/api.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ describe('Api', () => {
const baseUrl = 'https://site.com';
const apiEndpoint = 'api/v1/tests';
const siteApi = new Api({ accessToken }, () => Promise.resolve(), baseUrl);
await siteApi.request('GET', apiEndpoint);
await siteApi .request('GET', apiEndpoint) .then(res => res.json());

expect(fetchMock).toBeCalledTimes(1);
const expectedFetchOptions = {
Expand All @@ -81,7 +81,7 @@ describe('Api', () => {
});

const siteApi = new Api({ accessToken }, handleUnauthorizedAccess, baseUrl);
const response = await siteApi.request('GET', apiEndpoint);
const response = await siteApi.request('GET', apiEndpoint).then(res => res.json());

expect(response).not.toBeNull();
expect(fetchMock).toBeCalledTimes(2);
Expand Down
62 changes: 15 additions & 47 deletions src/utils/date.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,64 +13,32 @@ export function getDataHoraDescrita(dateTime: number | string): string {
const data = new Date(dateTime);
const dataAgora = new Date();

let tempoFormatado = '';
if (isHoje(data, dataAgora)) {
if (!isMesmaHora(data, dataAgora)) {
const horas = getDiferencaEmHoras(data, dataAgora);
const minutos = getDiferencaEmMinutos(data, dataAgora);

tempoFormatado = 'há ' + horas + ' hora';

if (horas > 1) {
tempoFormatado += 's';
}

return tempoFormatado;
}

if (!isMesmoMinuto(data, dataAgora)) {
const minutos = getDiferencaEmMinutos(data, dataAgora);

if (minutos > 0) {
tempoFormatado = 'há ' + minutos + ' minuto';

if (minutos > 1) {
tempoFormatado += 's';
}
// Menos de 1 minuto
if (minutos < 1) {
return 'agora há pouco';
}

return tempoFormatado;
}
}
// Menos de uma hora
if (minutos < 60) {
return 'há ' + minutos + ' minuto' + (minutos > 1 ? 's' : '');
}

return 'agora há pouco';
// Menos de 24 horas
if (minutos < 1440) {
const horas = Math.trunc(minutos / 60);
return 'há ' + horas + ' hora' + (horas > 1 ? 's' : '');
}

// Mais de 24 horas
return formatarData(data) + ' às ' + data.toTimeString().substring(0, 5);
}

function formatarData(data: Date) {
return data.toLocaleString('pt-BR').substring(0, 10);
}

function isHoje(dataA: Date, dataB: Date) {
return getDateISOString(dataA) === getDateISOString(dataB);
}

function getDateISOString(data: Date) {
return data.toISOString().substring(0, 10);
}

function isMesmaHora(dataA: Date, dataB: Date) {
return getDiferencaEmMinutos(dataA, dataB) < 60;
}

function getDiferencaEmMinutos(dataA: Date, dataB: Date) {
return Math.floor((dataB.valueOf() - dataA.valueOf()) / (60 * 1000));
}

function getDiferencaEmHoras(dataA: Date, dataB: Date) {
return dataB.getHours() - dataA.getHours();
}

function isMesmoMinuto(dataA: Date, dataB: Date) {
return dataB.getMinutes() === dataA.getMinutes();
return Math.floor((dataB.getTime() - dataA.getTime()) / (60 * 1000));
}

0 comments on commit 998288a

Please sign in to comment.