@senior-gestao-empresarial/angular-components 4.22.0 → 4.22.2-7c0b6b2c-1273-4faf-bd8a-91d677cec9bd

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -4,7 +4,7 @@ import { CommonModule } from '@angular/common';
4
4
  import { BreadcrumbModule as BreadcrumbModule$1 } from 'primeng/breadcrumb';
5
5
  import { NavigationEnd, PRIMARY_OUTLET, ActivatedRoute, Router, RouterModule } from '@angular/router';
6
6
  import { Subject, throwError, interval, of, ReplaySubject } from 'rxjs';
7
- import { takeUntil, filter, catchError, map, takeWhile, switchMap, take } from 'rxjs/operators';
7
+ import { takeUntil, filter, catchError, map, takeWhile, switchMap, first, finalize, take } from 'rxjs/operators';
8
8
  import * as moment_ from 'moment';
9
9
  import { FormField, FieldType } from '@seniorsistemas/angular-components';
10
10
  import { HttpParams, HttpClient } from '@angular/common/http';
@@ -15,7 +15,6 @@ import { user } from '@seniorsistemas/senior-platform-data';
15
15
  import { FormControl, FormGroup } from '@angular/forms';
16
16
  import { get } from 'js-cookie';
17
17
  import { Stomp } from '@stomp/stompjs';
18
- import { CookieService } from 'ngx-cookie-service';
19
18
  import * as SockJS from 'sockjs-client';
20
19
 
21
20
  let BreadcrumbComponent = class BreadcrumbComponent {
@@ -6014,95 +6013,95 @@ NpsService = __decorate([
6014
6013
 
6015
6014
  var WebsocketService_1;
6016
6015
  let WebsocketService = WebsocketService_1 = class WebsocketService {
6017
- constructor(cookieService) {
6018
- this.cookieService = cookieService;
6019
- this.baseUrl = null;
6020
- this.username = null;
6016
+ constructor() {
6021
6017
  this.focused = true;
6018
+ this.wasConnected = false;
6022
6019
  this.connected = false;
6023
6020
  this.isConnecting = false;
6024
- this.stompSubscriptions = new Map();
6025
- // private primitiveSubjects: Map<string, Subject<any>> = new Map<string, Subject<any>>();
6026
6021
  this.primitiveManagers = new Map();
6027
- this.disconnectSubject = new Subject();
6028
6022
  this.connect$ = new Subject();
6023
+ this.disconnect$ = new Subject();
6024
+ this.reconnect$ = new Subject();
6025
+ this.error$ = new Subject();
6029
6026
  window.onfocus = this.onFocus;
6030
6027
  window.onblur = this.onBlur;
6031
6028
  this.connect();
6032
6029
  }
6033
6030
  /**
6034
- * Observable resposável por emitir uma notificação quando a conexão websocket é estabelecida.
6035
- * @return Um `Observable<void>` que emite uma notificação quando a conexão websocket é estabelecida ou já está em andamento.
6031
+ * Observable responsável por emitir uma notificação quando a conexão websocket é estabelecida.
6032
+ * @return Um `Observable<void>` que emite uma notificação quando a conexão websocket é estabelecida.
6036
6033
  */
6037
6034
  onConnect() {
6038
6035
  setTimeout(() => {
6039
6036
  if (this.isConnected()) {
6040
- this.publishOnConnect();
6037
+ this.connect$.next();
6041
6038
  }
6042
6039
  }, 0);
6043
- return this.connect$.asObservable();
6040
+ return this.connect$.pipe(first());
6044
6041
  }
6045
6042
  /**
6046
- * Observable resposável por emitir uma notificação quando a conexão é finalizada.
6047
- * @return Um `Observable<void>` que emite uma notificação quando a conexão é finalizada.
6043
+ * Observable responsável por emitir uma notificação quando a conexão é desconectada.
6044
+ * @return Um `Observable<void>` que emite uma notificação quando a conexão é desconectada.
6048
6045
  */
6049
6046
  onDisconnect() {
6050
- return this.disconnectSubject.asObservable();
6047
+ return this.disconnect$.asObservable();
6048
+ }
6049
+ /**
6050
+ * Observable responsável por emitir uma notificação quando a conexão é reconectada.
6051
+ * @return Um `Observable<void>` que emite uma notificação quando a conexão é reconectada.
6052
+ */
6053
+ onReconnect() {
6054
+ return this.reconnect$.asObservable();
6055
+ }
6056
+ /**
6057
+ * Observable responsável por emitir uma notificação quando ocorre algum erro.
6058
+ * @return Um `Observable<FrameImpl>` que emite uma notificação quando ocorre algum erro.
6059
+ */
6060
+ onError() {
6061
+ return this.error$.asObservable();
6051
6062
  }
6052
6063
  /**
6053
6064
  * Observable responsável por emitir uma notificação quando um evento é publicado.
6054
6065
  * @typeParam `<T>` Tipo do objeto que o retorno do `observable` vai devolver.
6055
- * @param domain Dominio da primitva.
6066
+ * @param domain Dominio da primitiva.
6056
6067
  * @param service Service da primitiva.
6057
6068
  * @param primitive Primitiva que será "observada" pelo client.
6058
- * @param identifierPath Caminho até a propriedade considerada o indentificador do registro.
6069
+ * @param identifierPath Caminho até a propriedade considerada o identificador do registro.
6059
6070
  * @return Um `observable` que emite notificações toda vez que o respectivo evento é publicado no sistema.
6060
6071
  */
6061
6072
  onEvent(domain, service, primitive, identifierPath) {
6062
- let primitiveManager = this.primitiveManagers.get(primitive);
6063
- if (primitiveManager) {
6064
- return primitiveManager.subject.asObservable();
6073
+ if (this.primitiveManagers.has(primitive)) {
6074
+ return this.primitiveManagers.get(primitive).subject.asObservable();
6065
6075
  }
6066
- primitiveManager = {
6076
+ const primitiveManager = {
6077
+ domain: domain,
6078
+ service: service,
6079
+ primitive: primitive,
6080
+ stompSubscriptions: [],
6067
6081
  subject: new Subject(),
6068
6082
  identifierPath: identifierPath,
6069
6083
  publishedEvents: [],
6070
6084
  };
6085
+ this.primitiveManagers.set(primitive, primitiveManager);
6071
6086
  if (this.isConnected()) {
6072
- const url = this.getSubscriptionUserUrl(domain, service, primitive);
6073
- this.primitiveManagers.set(primitive, primitiveManager);
6074
- const stompSubscription = this._stompClient.subscribe(url, (message) => {
6075
- const event = JSON.parse(message.body || "{}");
6076
- this.addPublishedEvent(primitiveManager, event);
6077
- primitiveManager.subject.next(event);
6078
- });
6079
- this.stompSubscriptions.set(primitive, stompSubscription);
6080
- return primitiveManager.subject.asObservable();
6087
+ this.createStompSubscriptions(primitiveManager);
6088
+ return primitiveManager.subject.pipe(finalize(() => this.disconnectPrimitiveOnFinalize(primitive)));
6081
6089
  }
6082
6090
  else {
6083
6091
  if (!this.isConnecting) {
6084
6092
  this.connect();
6085
6093
  }
6086
- this.onConnect()
6087
- .pipe(take(1))
6088
- .subscribe(() => {
6089
- const url = this.getSubscriptionUserUrl(domain, service, primitive);
6090
- this.primitiveManagers.set(primitive, primitiveManager);
6091
- const stompSubscription = this._stompClient.subscribe(url, (message) => {
6092
- const event = JSON.parse(message.body || "{}");
6093
- this.addPublishedEvent(primitiveManager, event);
6094
- primitiveManager.subject.next(event);
6095
- });
6096
- this.stompSubscriptions.set(primitive, stompSubscription);
6094
+ this.connect$.pipe(first()).subscribe(() => {
6095
+ this.createStompSubscriptions(primitiveManager);
6097
6096
  });
6098
- return primitiveManager.subject.asObservable();
6097
+ return primitiveManager.subject.pipe(finalize(() => this.disconnectPrimitiveOnFinalize(primitive)));
6099
6098
  }
6100
6099
  }
6101
6100
  /**
6102
- * Retorna todos os eventos ouvidos para a respectiva primitiva.
6101
+ * Retorna todos os eventos ouvidos pela primitiva com os respectivos identificadores.
6103
6102
  * @typeParam `<T>` Tipo do evento retornado pela primitiva.
6104
6103
  * @param primitive Primitiva que será "observada" pelo client.
6105
- * @param identifiers Array com os indentificadores interessados.
6104
+ * @param identifiers Array com os identificadores interessados.
6106
6105
  * @return Array contendo o último evento recebido de cada identificador fornecido.
6107
6106
  */
6108
6107
  getPublishedEvents(primitive, identifiers) {
@@ -6126,6 +6125,13 @@ let WebsocketService = WebsocketService_1 = class WebsocketService {
6126
6125
  primitiveManager.publishedEvents.push(event);
6127
6126
  }
6128
6127
  }
6128
+ createStompSubscriptions(primitiveManager) {
6129
+ const withTokenUrl = this.getSubscriptionUrlWithToken(primitiveManager.domain, primitiveManager.service, primitiveManager.primitive);
6130
+ const stompSubscriptionWithToken = this.createStompSubscription(withTokenUrl, primitiveManager);
6131
+ const withoutTokenUrl = this.getSubscriptionUrlWithoutToken(primitiveManager.domain, primitiveManager.service, primitiveManager.primitive);
6132
+ const stompSubscriptionWithoutToken = this.createStompSubscription(withoutTokenUrl, primitiveManager);
6133
+ primitiveManager.stompSubscriptions = [stompSubscriptionWithToken, stompSubscriptionWithoutToken];
6134
+ }
6129
6135
  getIdentifierFromEvent(identifierPath, event) {
6130
6136
  const properties = identifierPath.split(".");
6131
6137
  let identifier = event;
@@ -6137,21 +6143,24 @@ let WebsocketService = WebsocketService_1 = class WebsocketService {
6137
6143
  connect() {
6138
6144
  this.createStompClient();
6139
6145
  this.isConnecting = true;
6146
+ this._stompClient.activate();
6140
6147
  this._stompClient.connect({}, () => {
6141
- this.setConnected(true);
6142
- // console.log('setou false isConnecting');
6143
6148
  this.isConnecting = false;
6144
- // console.log('connectou dentro do connect cb');
6145
- this.publishOnConnect();
6146
- }, () => {
6149
+ this.setConnected(true);
6150
+ if (this.wasConnected) {
6151
+ this.reconnectPrimitives();
6152
+ this.reconnect$.next();
6153
+ }
6154
+ else {
6155
+ this.wasConnected = true;
6156
+ this.connect$.next();
6157
+ }
6158
+ }, (error) => {
6147
6159
  this.setConnected(false);
6148
- // this.reconnectWebSocket();
6160
+ this.error$.next(error);
6161
+ this.reconnect();
6149
6162
  });
6150
6163
  }
6151
- publishOnConnect() {
6152
- this.connect$.next();
6153
- this.connect$.observers = [];
6154
- }
6155
6164
  onFocus() {
6156
6165
  this.focused = true;
6157
6166
  }
@@ -6159,25 +6168,24 @@ let WebsocketService = WebsocketService_1 = class WebsocketService {
6159
6168
  this.focused = false;
6160
6169
  }
6161
6170
  disconnect() {
6162
- let observersCount = 0;
6171
+ const observersCount = this.getObserversCount();
6172
+ if (observersCount > 0)
6173
+ return;
6163
6174
  for (const primitiveManager of this.primitiveManagers.values()) {
6164
- observersCount += primitiveManager.subject.observers.length;
6165
- }
6166
- if (observersCount === 0) {
6167
- this.stompSubscriptions.forEach(stompSubscription => {
6175
+ for (const stompSubscription of primitiveManager.stompSubscriptions) {
6168
6176
  stompSubscription.unsubscribe();
6169
- });
6170
- for (const primitiveManager of this.primitiveManagers.values()) {
6171
- primitiveManager.subject.complete();
6172
6177
  }
6173
- this.stompSubscriptions.clear();
6174
- this.primitiveManagers.clear();
6175
- this._stompClient.disconnect();
6176
- this._stompClient.deactivate();
6177
- this.setConnected(false);
6178
- this.isConnecting = false;
6179
- this.disconnectSubject.next();
6180
6178
  }
6179
+ for (const primitiveManager of this.primitiveManagers.values()) {
6180
+ primitiveManager.subject.complete();
6181
+ }
6182
+ this.primitiveManagers.clear();
6183
+ this._stompClient.disconnect();
6184
+ this._stompClient.deactivate();
6185
+ this.setConnected(false);
6186
+ this.isConnecting = false;
6187
+ this.wasConnected = false;
6188
+ this.disconnect$.next();
6181
6189
  }
6182
6190
  isConnected() {
6183
6191
  return this.connected;
@@ -6185,55 +6193,79 @@ let WebsocketService = WebsocketService_1 = class WebsocketService {
6185
6193
  setConnected(connected) {
6186
6194
  this.connected = connected;
6187
6195
  }
6188
- getSubscriptionUserUrl(domain, service, primitive) {
6196
+ getSubscriptionUrlWithToken(domain, service, primitive) {
6189
6197
  const tenant = WebsocketService_1.TOKEN ? WebsocketService_1.TOKEN.username.split("@")[1] : null;
6190
6198
  const token = WebsocketService_1.TOKEN ? WebsocketService_1.TOKEN.access_token : null;
6191
6199
  return `/topic/${tenant}/${token}/${domain}/${service}/${primitive}`;
6192
6200
  }
6201
+ getSubscriptionUrlWithoutToken(domain, service, primitive) {
6202
+ const tenant = WebsocketService_1.TOKEN ? WebsocketService_1.TOKEN.username.split("@")[1] : null;
6203
+ return `/topic/${tenant}/${domain}/${service}/${primitive}`;
6204
+ }
6205
+ createStompSubscription(destination, primitiveManager) {
6206
+ return this._stompClient.subscribe(destination, (message) => {
6207
+ const event = JSON.parse(message.body || "{}");
6208
+ this.addPublishedEvent(primitiveManager, event);
6209
+ primitiveManager.subject.next(event);
6210
+ });
6211
+ }
6193
6212
  createStompClient() {
6194
6213
  const ws = new SockJS(`${WebsocketService_1.WEBSOCKET_URL}subscription`, null, { timeout: WebsocketService_1.CONNECTION_TIMEOUT });
6195
6214
  this._stompClient = Stomp.over(ws);
6215
+ // this._stompClient.debug = (str) => console.log(new Date().toISOString(), str);
6196
6216
  this._stompClient.debug = () => { }; // Para remover os logs.
6197
6217
  }
6198
- getBaseUrl() {
6199
- return this.cookieService.get("com.senior.base.url");
6200
- }
6201
- getUserName() {
6202
- const token = this.cookieService.get("com.senior.token");
6203
- return token && JSON.parse(token).username;
6204
- }
6205
- reconnectWebSocket() {
6206
- this._stompClient.disconnect();
6207
- const baseUrl = this.getBaseUrl();
6208
- if (this.baseUrl !== null && baseUrl != this.baseUrl) {
6209
- // //console.log('ws disconnected: base url changed', this.baseUrl, ' -> ', baseUrl || 'null');
6210
- return;
6211
- }
6212
- const username = this.getUserName();
6213
- if (this.username !== null && username != this.username) {
6214
- // //console.log('ws disconnected: username changed', this.username, ' -> ', username || 'null');
6215
- return;
6216
- }
6218
+ reconnect() {
6219
+ if (this.connected)
6220
+ this._stompClient.disconnect();
6217
6221
  setTimeout(() => {
6222
+ if (this.getObserversCount() === 0)
6223
+ return;
6218
6224
  if (this.focused) {
6219
6225
  this.connect();
6220
6226
  }
6221
6227
  else {
6222
- this.reconnectWebSocket();
6228
+ this.reconnect();
6223
6229
  }
6224
6230
  }, WebsocketService_1.RECONNECT_TIMER);
6225
6231
  }
6232
+ reconnectPrimitives() {
6233
+ for (const primitiveManager of this.primitiveManagers.values()) {
6234
+ for (const stompSubscription of primitiveManager.stompSubscriptions) {
6235
+ stompSubscription.unsubscribe();
6236
+ }
6237
+ this.createStompSubscriptions(primitiveManager);
6238
+ }
6239
+ }
6240
+ getObserversCount() {
6241
+ let observersCount = 0;
6242
+ for (const primitiveManager of this.primitiveManagers.values()) {
6243
+ observersCount += primitiveManager.subject.observers.length;
6244
+ }
6245
+ return observersCount;
6246
+ }
6247
+ disconnectPrimitiveOnFinalize(primitive) {
6248
+ const primitiveManager = this.primitiveManagers.get(primitive);
6249
+ if (!primitiveManager)
6250
+ return;
6251
+ // @IMPORTANT: Replace .observers.length with .observed in rxjs 7.0+
6252
+ const hasObservers = !(primitiveManager.subject.observers.length === 1);
6253
+ if (hasObservers)
6254
+ return;
6255
+ for (const stompSubscription of primitiveManager.stompSubscriptions) {
6256
+ stompSubscription.unsubscribe();
6257
+ }
6258
+ this.primitiveManagers.delete(primitive);
6259
+ this.disconnect();
6260
+ }
6226
6261
  };
6227
6262
  WebsocketService.RECONNECT_TIMER = 3000;
6228
- WebsocketService.CONNECTION_TIMEOUT = 30000;
6263
+ WebsocketService.CONNECTION_TIMEOUT = 15000;
6229
6264
  WebsocketService.BASE_URL_COOKIE = "com.senior.base.url";
6230
6265
  WebsocketService.TOKEN_COOKIE = "com.senior.token";
6231
6266
  WebsocketService.TOKEN = JSON.parse(get(WebsocketService_1.TOKEN_COOKIE) || "{}");
6232
6267
  WebsocketService.WEBSOCKET_URL = get(WebsocketService_1.BASE_URL_COOKIE) + "/websocket/";
6233
- WebsocketService.ctorParameters = () => [
6234
- { type: CookieService }
6235
- ];
6236
- WebsocketService.ɵprov = ɵɵdefineInjectable({ factory: function WebsocketService_Factory() { return new WebsocketService(ɵɵinject(CookieService)); }, token: WebsocketService, providedIn: "root" });
6268
+ WebsocketService.ɵprov = ɵɵdefineInjectable({ factory: function WebsocketService_Factory() { return new WebsocketService(); }, token: WebsocketService, providedIn: "root" });
6237
6269
  WebsocketService = WebsocketService_1 = __decorate([
6238
6270
  Injectable({
6239
6271
  providedIn: "root",