@senior-gestao-empresarial/angular-components 4.22.0 → 4.22.2-7ecfc706-3270-4664-9d10-a6918ef49acd

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, finalize, first, 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,25 +6013,23 @@ 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(() => {
@@ -6043,66 +6040,68 @@ let WebsocketService = WebsocketService_1 = class WebsocketService {
6043
6040
  return this.connect$.asObservable();
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,15 +6143,22 @@ 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.publishOnConnect();
6157
+ }
6158
+ }, (error) => {
6147
6159
  this.setConnected(false);
6148
- // this.reconnectWebSocket();
6160
+ this.error$.next(error);
6161
+ this.reconnect();
6149
6162
  });
6150
6163
  }
6151
6164
  publishOnConnect() {
@@ -6159,25 +6172,23 @@ let WebsocketService = WebsocketService_1 = class WebsocketService {
6159
6172
  this.focused = false;
6160
6173
  }
6161
6174
  disconnect() {
6162
- let observersCount = 0;
6175
+ const observersCount = this.getObserversCount();
6176
+ if (observersCount > 0)
6177
+ return;
6163
6178
  for (const primitiveManager of this.primitiveManagers.values()) {
6164
- observersCount += primitiveManager.subject.observers.length;
6165
- }
6166
- if (observersCount === 0) {
6167
- this.stompSubscriptions.forEach(stompSubscription => {
6179
+ for (const stompSubscription of primitiveManager.stompSubscriptions) {
6168
6180
  stompSubscription.unsubscribe();
6169
- });
6170
- for (const primitiveManager of this.primitiveManagers.values()) {
6171
- primitiveManager.subject.complete();
6172
6181
  }
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
6182
  }
6183
+ for (const primitiveManager of this.primitiveManagers.values()) {
6184
+ primitiveManager.subject.complete();
6185
+ }
6186
+ this.primitiveManagers.clear();
6187
+ this._stompClient.disconnect();
6188
+ this._stompClient.deactivate();
6189
+ this.setConnected(false);
6190
+ this.isConnecting = false;
6191
+ this.disconnect$.next();
6181
6192
  }
6182
6193
  isConnected() {
6183
6194
  return this.connected;
@@ -6185,55 +6196,79 @@ let WebsocketService = WebsocketService_1 = class WebsocketService {
6185
6196
  setConnected(connected) {
6186
6197
  this.connected = connected;
6187
6198
  }
6188
- getSubscriptionUserUrl(domain, service, primitive) {
6199
+ getSubscriptionUrlWithToken(domain, service, primitive) {
6189
6200
  const tenant = WebsocketService_1.TOKEN ? WebsocketService_1.TOKEN.username.split("@")[1] : null;
6190
6201
  const token = WebsocketService_1.TOKEN ? WebsocketService_1.TOKEN.access_token : null;
6191
6202
  return `/topic/${tenant}/${token}/${domain}/${service}/${primitive}`;
6192
6203
  }
6204
+ getSubscriptionUrlWithoutToken(domain, service, primitive) {
6205
+ const tenant = WebsocketService_1.TOKEN ? WebsocketService_1.TOKEN.username.split("@")[1] : null;
6206
+ return `/topic/${tenant}/${domain}/${service}/${primitive}`;
6207
+ }
6208
+ createStompSubscription(destination, primitiveManager) {
6209
+ return this._stompClient.subscribe(destination, (message) => {
6210
+ const event = JSON.parse(message.body || "{}");
6211
+ this.addPublishedEvent(primitiveManager, event);
6212
+ primitiveManager.subject.next(event);
6213
+ });
6214
+ }
6193
6215
  createStompClient() {
6194
6216
  const ws = new SockJS(`${WebsocketService_1.WEBSOCKET_URL}subscription`, null, { timeout: WebsocketService_1.CONNECTION_TIMEOUT });
6195
6217
  this._stompClient = Stomp.over(ws);
6218
+ // this._stompClient.debug = (str) => console.log(new Date().toISOString(), str);
6196
6219
  this._stompClient.debug = () => { }; // Para remover os logs.
6197
6220
  }
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
- }
6221
+ reconnect() {
6222
+ if (this.connected)
6223
+ this._stompClient.disconnect();
6217
6224
  setTimeout(() => {
6225
+ if (this.getObserversCount() === 0)
6226
+ return;
6218
6227
  if (this.focused) {
6219
6228
  this.connect();
6220
6229
  }
6221
6230
  else {
6222
- this.reconnectWebSocket();
6231
+ this.reconnect();
6223
6232
  }
6224
6233
  }, WebsocketService_1.RECONNECT_TIMER);
6225
6234
  }
6235
+ reconnectPrimitives() {
6236
+ for (const primitiveManager of this.primitiveManagers.values()) {
6237
+ for (const stompSubscription of primitiveManager.stompSubscriptions) {
6238
+ stompSubscription.unsubscribe();
6239
+ }
6240
+ this.createStompSubscriptions(primitiveManager);
6241
+ }
6242
+ }
6243
+ getObserversCount() {
6244
+ let observersCount = 0;
6245
+ for (const primitiveManager of this.primitiveManagers.values()) {
6246
+ observersCount += primitiveManager.subject.observers.length;
6247
+ }
6248
+ return observersCount;
6249
+ }
6250
+ disconnectPrimitiveOnFinalize(primitive) {
6251
+ const primitiveManager = this.primitiveManagers.get(primitive);
6252
+ if (!primitiveManager)
6253
+ return;
6254
+ // @IMPORTANT: Replace .observers.length with .observed in rxjs 7.0+
6255
+ const hasObservers = !(primitiveManager.subject.observers.length === 1);
6256
+ if (hasObservers)
6257
+ return;
6258
+ for (const stompSubscription of primitiveManager.stompSubscriptions) {
6259
+ stompSubscription.unsubscribe();
6260
+ }
6261
+ this.primitiveManagers.delete(primitive);
6262
+ this.disconnect();
6263
+ }
6226
6264
  };
6227
6265
  WebsocketService.RECONNECT_TIMER = 3000;
6228
- WebsocketService.CONNECTION_TIMEOUT = 30000;
6266
+ WebsocketService.CONNECTION_TIMEOUT = 15000;
6229
6267
  WebsocketService.BASE_URL_COOKIE = "com.senior.base.url";
6230
6268
  WebsocketService.TOKEN_COOKIE = "com.senior.token";
6231
6269
  WebsocketService.TOKEN = JSON.parse(get(WebsocketService_1.TOKEN_COOKIE) || "{}");
6232
6270
  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" });
6271
+ WebsocketService.ɵprov = ɵɵdefineInjectable({ factory: function WebsocketService_Factory() { return new WebsocketService(); }, token: WebsocketService, providedIn: "root" });
6237
6272
  WebsocketService = WebsocketService_1 = __decorate([
6238
6273
  Injectable({
6239
6274
  providedIn: "root",