x-tql-service 1.19.4

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.
Files changed (39) hide show
  1. package/README.md +24 -0
  2. package/fesm2022/x-tql-service.mjs +2232 -0
  3. package/fesm2022/x-tql-service.mjs.map +1 -0
  4. package/index.d.ts +5 -0
  5. package/lib/constants/error-status.enum.d.ts +5 -0
  6. package/lib/constants/index.d.ts +5 -0
  7. package/lib/constants/key.constant.d.ts +12 -0
  8. package/lib/constants/language.constant.d.ts +14 -0
  9. package/lib/constants/map.constant.d.ts +25 -0
  10. package/lib/constants/mics.constant.d.ts +9 -0
  11. package/lib/controllers/dialog/tql-dialog-controller.service.d.ts +28 -0
  12. package/lib/controllers/index.d.ts +5 -0
  13. package/lib/controllers/route/tql-route-controller.service.d.ts +6 -0
  14. package/lib/controllers/site-map/tql-site-map-controller.service.d.ts +23 -0
  15. package/lib/controllers/table/tql-table-controller.service.d.ts +11 -0
  16. package/lib/controllers/toast/tql-toast-controller.service.d.ts +19 -0
  17. package/lib/interceptor/index.d.ts +1 -0
  18. package/lib/interceptor/tql-api.interceptor.d.ts +17 -0
  19. package/lib/models/default/default-component.d.ts +55 -0
  20. package/lib/models/default/default-dialog-component.d.ts +35 -0
  21. package/lib/models/default/default-directive.d.ts +7 -0
  22. package/lib/models/default/default-map-component.d.ts +19 -0
  23. package/lib/models/default/default-model.d.ts +68 -0
  24. package/lib/models/default/default-model.interface.d.ts +5 -0
  25. package/lib/models/default/dynamic-model.d.ts +11 -0
  26. package/lib/models/index.d.ts +9 -0
  27. package/lib/models/payload.model.d.ts +33 -0
  28. package/lib/models/ws-payload.model.d.ts +13 -0
  29. package/lib/services/api/tql-api-lib.service.d.ts +81 -0
  30. package/lib/services/config/tql-global-config.service.d.ts +9 -0
  31. package/lib/services/error-handler/tql-error-handler.service.d.ts +69 -0
  32. package/lib/services/index.d.ts +7 -0
  33. package/lib/services/log/tql-logger.service.d.ts +23 -0
  34. package/lib/services/translate/tql-translate.service.d.ts +64 -0
  35. package/lib/services/utils/tql-utils.service.d.ts +138 -0
  36. package/lib/services/ws/tql-ws.service.d.ts +123 -0
  37. package/lib/tql-service.module.d.ts +8 -0
  38. package/package.json +23 -0
  39. package/public-api.d.ts +6 -0
@@ -0,0 +1,2232 @@
1
+ import * as _ from 'lodash';
2
+ import ___default, { isUndefined } from 'lodash';
3
+ export { _ };
4
+ import * as xml2js from 'xml2js';
5
+ export { xml2js };
6
+ import * as i0 from '@angular/core';
7
+ import { InjectionToken, EventEmitter, Output, Directive, Injectable, Optional, Inject, provideAppInitializer, LOCALE_ID, inject, NgModule } from '@angular/core';
8
+ import { Subscription, BehaviorSubject, Subject, throwError, skipWhile, first, Observable, catchError as catchError$1, of, map } from 'rxjs';
9
+ import { LoadingBarService } from '@ngx-loading-bar/core';
10
+ import * as i1 from '@angular/material/dialog';
11
+ import { DatePipe, CommonModule } from '@angular/common';
12
+ import * as i1$1 from '@angular/material/snack-bar';
13
+ import * as i1$2 from '@angular/common/http';
14
+ import { HttpHeaders } from '@angular/common/http';
15
+ import { tap, catchError, timeout } from 'rxjs/operators';
16
+ import * as i1$3 from '@ngx-translate/core';
17
+ import { TranslateService, TranslateModule, MissingTranslationHandler, TranslateLoader } from '@ngx-translate/core';
18
+ import { v4 } from 'uuid';
19
+
20
+ // import * as moment from 'moment';
21
+ const DATA_TYPE = {
22
+ DATE: 'date',
23
+ YES_NO: 'yes-no',
24
+ };
25
+ const TQL_LIBRARY_CONFIG = new InjectionToken('TQL Library Configuration');
26
+
27
+ var ErrorStatusEnum;
28
+ (function (ErrorStatusEnum) {
29
+ ErrorStatusEnum[ErrorStatusEnum["FORBIDDEN"] = 0] = "FORBIDDEN";
30
+ ErrorStatusEnum["SUCCESS"] = "Success";
31
+ ErrorStatusEnum["ERROR"] = "Error";
32
+ })(ErrorStatusEnum || (ErrorStatusEnum = {}));
33
+
34
+ const PRE_FIX = '';
35
+ const KEY_CONSTANT = {
36
+ ALL: 'all',
37
+ LOCAL_STORAGE: {
38
+ USER: `${PRE_FIX}User`,
39
+ EXPIRE: `${PRE_FIX}expiry`,
40
+ SESSION_TOKEN: `${PRE_FIX}sessionToken`,
41
+ USER_TOKEN: `${PRE_FIX}userToken`,
42
+ },
43
+ SYS_ID: 'sysId',
44
+ STUDIO_KEY: 'x-atomiton-studio-key',
45
+ SESSION_KEY: 'x-atomiton-session-key',
46
+ };
47
+
48
+ const MAP_STYLES = [
49
+ {
50
+ featureType: 'administrative',
51
+ elementType: 'geometry',
52
+ stylers: [{ visibility: 'off' }],
53
+ },
54
+ { featureType: 'landscape.natural', elementType: 'geometry', stylers: [{ visibility: 'off' }] },
55
+ {
56
+ featureType: 'poi',
57
+ stylers: [{ visibility: 'off' }],
58
+ },
59
+ { featureType: 'road', elementType: 'geometry.fill', stylers: [{ color: '#c0c0c0' }] },
60
+ {
61
+ featureType: 'road',
62
+ elementType: 'labels.icon',
63
+ stylers: [{ visibility: 'off' }],
64
+ },
65
+ { featureType: 'road.highway', elementType: 'geometry.fill', stylers: [{ weight: 2 }] },
66
+ {
67
+ featureType: 'road.highway',
68
+ elementType: 'geometry.stroke',
69
+ stylers: [{ visibility: 'off' }],
70
+ },
71
+ { featureType: 'transit', stylers: [{ visibility: 'off' }] },
72
+ ];
73
+
74
+ const LANGUAGES = {
75
+ EN: 'en-US',
76
+ PT: 'pt-BR',
77
+ };
78
+ const LANGUAGE_DEFAULT = LANGUAGES.EN;
79
+ const KEY_LANGUAGES_LOCAL_STORAGE = 'TQL_language';
80
+ const TYPE_LANGUAGES_HIGH_CHART = {
81
+ shortMonths: 'shortMonths',
82
+ months: 'months',
83
+ weekdays: 'weekdays',
84
+ };
85
+ const TRANSLATE_KEY = {
86
+ key: 'AIzaSyBxnsG8frZ9zX9_26LA5vkGb8CNUzh6AhA',
87
+ };
88
+
89
+ class DefaultModel {
90
+ /**
91
+ *
92
+ * @param _data
93
+ * @param idKey
94
+ * @param isAutoAssign
95
+ */
96
+ constructor(_data = {}, idKey = '', isAutoAssign = false, isAssignRawData = true) {
97
+ /**
98
+ * all keys are in lowercase
99
+ * @type {{}}
100
+ * @private
101
+ */
102
+ this._data = {};
103
+ /**
104
+ * all keys are raw
105
+ * @type {{}}
106
+ * @private
107
+ */
108
+ this._raw = {};
109
+ if (_data) {
110
+ // set raw
111
+ if (_data.hasOwnProperty('_raw')) {
112
+ delete _data['_raw'];
113
+ }
114
+ this._raw = _data;
115
+ // store data to new place
116
+ for (const key of Object.keys(_data)) {
117
+ this._data[key.toLowerCase()] = this._raw[key];
118
+ }
119
+ const self = this;
120
+ // setTimeout(() => {
121
+ if (isAutoAssign) {
122
+ if (isAssignRawData) {
123
+ Object.assign(self, self._raw);
124
+ }
125
+ else {
126
+ Object.assign(self, self._data);
127
+ }
128
+ }
129
+ // });
130
+ }
131
+ if (idKey) {
132
+ // set id key
133
+ this._idKey = idKey.toLowerCase();
134
+ this._id = this.getId();
135
+ }
136
+ }
137
+ /**
138
+ * get value of id
139
+ * @return {any}
140
+ */
141
+ getId() {
142
+ if (this._idKey && this._data[this._idKey]) {
143
+ return this._data[this._idKey];
144
+ }
145
+ return null;
146
+ }
147
+ setId(id) {
148
+ this._data[this._idKey] = id;
149
+ this._id = this.getId();
150
+ }
151
+ /**
152
+ * delete object property
153
+ * @param key: string
154
+ */
155
+ deleteProperty(key) {
156
+ const self = this;
157
+ if (!!self?.key) {
158
+ delete self[key];
159
+ }
160
+ }
161
+ /**
162
+ * get key of id
163
+ * @returns {string}
164
+ */
165
+ getIdKey() {
166
+ return this._idKey || '';
167
+ }
168
+ /**
169
+ * get value of _data by key
170
+ * @param key: string
171
+ * @returns {any}
172
+ */
173
+ getValue(key) {
174
+ return this._data[_.toLower(key)];
175
+ }
176
+ /**
177
+ * set value of _data by key & value of this object's attribute if existed
178
+ * @param key: string
179
+ * @param value: string
180
+ * @returns {any}
181
+ */
182
+ setValue(key, value) {
183
+ const self = this;
184
+ if (self.hasOwnProperty(key)) {
185
+ self[key] = value;
186
+ }
187
+ return (this._data[key.toLowerCase()] = value);
188
+ }
189
+ /**
190
+ * get raw value of _data by key
191
+ * @param key: string
192
+ * @returns {any}
193
+ */
194
+ getRawValue(key) {
195
+ return this._raw[key];
196
+ }
197
+ /**
198
+ * set value of _data by key
199
+ * @param key: string
200
+ * @param value: string
201
+ * @returns {any}
202
+ */
203
+ setRawValue(key, value) {
204
+ return (this._raw[key] = value);
205
+ }
206
+ /*STATIC*/
207
+ static describe(instance) {
208
+ return _.filter(Object.getOwnPropertyNames(instance), (x) => !_.startsWith(x, '_'));
209
+ }
210
+ }
211
+
212
+ class DefaultComponent {
213
+ /**
214
+ * pass injector into here if you want to check loading work
215
+ * ex: in child class
216
+ * Constructor(private _Injector: Injector) {
217
+ * super(_Injector)
218
+ * }
219
+ */
220
+ constructor(_Injector) {
221
+ /**
222
+ * emit event trigger when all _promises called
223
+ * @type {EventEmitter<any>}
224
+ */
225
+ this.onPromise = new EventEmitter();
226
+ this._promises = [];
227
+ this._isLoading = false;
228
+ // when init, unsubscribe all
229
+ this.unsubscribeAll();
230
+ if (_Injector) {
231
+ this._LoadingBarService = _Injector.get(LoadingBarService);
232
+ this.addSubscribes(this._LoadingBarService.value$.subscribe((flat) => {
233
+ this._isLoading = !!flat;
234
+ }));
235
+ }
236
+ }
237
+ /**
238
+ * IMPORTANT
239
+ * when destroy, unsubscribe all
240
+ */
241
+ ngOnDestroy() {
242
+ this.unsubscribeAll();
243
+ // console.log('DESTROYED ' + this.constructor.name);
244
+ }
245
+ /**
246
+ * unsubscribe all subscription which add into the component
247
+ * it is important to prevent subscription still exist when component is destroyed
248
+ */
249
+ unsubscribeAll() {
250
+ if (this._subscriptionList) {
251
+ this._subscriptionList.unsubscribe();
252
+ }
253
+ this._subscriptionList = new Subscription();
254
+ }
255
+ /**
256
+ * add subscriptions to component storage
257
+ * @param subscriptions
258
+ */
259
+ addSubscribes(...subscriptions) {
260
+ subscriptions.forEach((el) => {
261
+ this._subscriptionList.add(el);
262
+ });
263
+ }
264
+ /**
265
+ * add promises into an array
266
+ * @param promises
267
+ */
268
+ addPromises(...promises) {
269
+ promises.forEach((el) => {
270
+ this._promises.push(el);
271
+ });
272
+ this.onPromise.emit(Promise.all(this._promises).then(() => {
273
+ this._promises = [];
274
+ }));
275
+ }
276
+ /**
277
+ * get list of current stored promises
278
+ * @returns {Promise<any>[]}
279
+ */
280
+ get promises() {
281
+ return this._promises;
282
+ }
283
+ static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.17", ngImport: i0, type: DefaultComponent, deps: [{ token: i0.Injector }], target: i0.ɵɵFactoryTarget.Directive }); }
284
+ static { this.ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "19.2.17", type: DefaultComponent, isStandalone: true, outputs: { onPromise: "onPromise" }, ngImport: i0 }); }
285
+ }
286
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.17", ngImport: i0, type: DefaultComponent, decorators: [{
287
+ type: Directive
288
+ }], ctorParameters: () => [{ type: i0.Injector }], propDecorators: { onPromise: [{
289
+ type: Output
290
+ }] } });
291
+
292
+ class DefaultDirective extends DefaultComponent {
293
+ constructor() {
294
+ super();
295
+ }
296
+ static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.17", ngImport: i0, type: DefaultDirective, deps: [], target: i0.ɵɵFactoryTarget.Directive }); }
297
+ static { this.ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "19.2.17", type: DefaultDirective, isStandalone: true, usesInheritance: true, ngImport: i0 }); }
298
+ }
299
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.17", ngImport: i0, type: DefaultDirective, decorators: [{
300
+ type: Directive
301
+ }], ctorParameters: () => [] });
302
+
303
+ class DefaultDialogComponent extends DefaultComponent {
304
+ static { this.DEFAULT_WIDTH = '90vw'; }
305
+ static { this.DEFAULT_HEIGHT = 'auto'; }
306
+ constructor(dialogRef, _Injector, ...args) {
307
+ super(_Injector);
308
+ this.dialogRef = dialogRef;
309
+ this._Injector = _Injector;
310
+ if (!this.dialogRef.disableClose) {
311
+ this.dialogRef.backdropClick().subscribe(() => {
312
+ this.onCancel();
313
+ });
314
+ }
315
+ }
316
+ /**
317
+ *
318
+ * @param arg
319
+ */
320
+ onCancel(arg = false) {
321
+ this.dialogRef.close(arg);
322
+ }
323
+ /**
324
+ *
325
+ * @private
326
+ */
327
+ onClose() {
328
+ this.dialogRef.close(false);
329
+ }
330
+ /**
331
+ *
332
+ * @private
333
+ * @param arg
334
+ */
335
+ onOk(arg = true) {
336
+ this.dialogRef.close(arg);
337
+ }
338
+ static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.17", ngImport: i0, type: DefaultDialogComponent, deps: "invalid", target: i0.ɵɵFactoryTarget.Directive }); }
339
+ static { this.ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "19.2.17", type: DefaultDialogComponent, isStandalone: true, usesInheritance: true, ngImport: i0 }); }
340
+ }
341
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.17", ngImport: i0, type: DefaultDialogComponent, decorators: [{
342
+ type: Directive
343
+ }], ctorParameters: () => [{ type: i1.MatDialogRef }, { type: i0.Injector }, { type: undefined }] });
344
+ (function (DefaultDialogComponent) {
345
+ let State;
346
+ (function (State) {
347
+ State[State["OPENING"] = 0] = "OPENING";
348
+ State[State["CLOSED"] = 1] = "CLOSED";
349
+ })(State = DefaultDialogComponent.State || (DefaultDialogComponent.State = {}));
350
+ })(DefaultDialogComponent || (DefaultDialogComponent = {}));
351
+
352
+ class DynamicDataModel {
353
+ constructor(component, data = null) {
354
+ this.component = component;
355
+ this.data = data;
356
+ }
357
+ }
358
+
359
+ class DefaultMapComponent extends DefaultComponent {
360
+ constructor() {
361
+ super();
362
+ this.DEFAULT_ZOOM = 13;
363
+ this.styles = MAP_STYLES;
364
+ this.zoom = this.DEFAULT_ZOOM;
365
+ if (typeof google !== 'undefined') {
366
+ this.center = new google.maps.LatLng(0, 0);
367
+ }
368
+ this.resetMapBounds();
369
+ }
370
+ /**
371
+ * reset map
372
+ */
373
+ resetMapBounds() {
374
+ if (typeof google !== 'undefined') {
375
+ this.bounds = new google.maps.LatLngBounds();
376
+ }
377
+ }
378
+ setMapBounds(map, points = [], minZoom = null) {
379
+ if (!(!!map && points.length)) {
380
+ return;
381
+ }
382
+ const self = this;
383
+ if (!self.bounds) {
384
+ this.resetMapBounds();
385
+ }
386
+ if (typeof google !== 'undefined' && map) {
387
+ for (let i = 0; i < points.length; i++) {
388
+ if (points[i]) {
389
+ self.bounds.extend(points[i]);
390
+ }
391
+ }
392
+ map.fitBounds(self.bounds);
393
+ let listener = google.maps.event.addListener(map, 'idle', function () {
394
+ //TODO tmp disabled, nam, 12/02/2019
395
+ // if (map.getZoom() > self.DEFAULT_ZOOM) {
396
+ // map.setZoom(self.DEFAULT_ZOOM);
397
+ // }
398
+ if (minZoom && map.getZoom() > minZoom) {
399
+ map.setZoom(minZoom);
400
+ }
401
+ google.maps.event.removeListener(listener);
402
+ });
403
+ }
404
+ }
405
+ getCenterOfArray(points = []) {
406
+ if (!points.length || typeof google === 'undefined') {
407
+ return null;
408
+ }
409
+ const bounds = new google.maps.LatLngBounds();
410
+ points.map((el) => bounds.extend(el));
411
+ // console.log(bounds.getCenter());
412
+ const center = bounds.getCenter();
413
+ // console.log(new GeoPoint(center.lat(), center.lng()));
414
+ return { lat: center.lat(), lng: center.lng() };
415
+ }
416
+ static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.17", ngImport: i0, type: DefaultMapComponent, deps: [], target: i0.ɵɵFactoryTarget.Directive }); }
417
+ static { this.ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "19.2.17", type: DefaultMapComponent, isStandalone: true, usesInheritance: true, ngImport: i0 }); }
418
+ }
419
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.17", ngImport: i0, type: DefaultMapComponent, decorators: [{
420
+ type: Directive
421
+ }], ctorParameters: () => [] });
422
+
423
+ class TqlUtilsService {
424
+ static { this._DatePipe = new DatePipe('en-US'); }
425
+ constructor() { }
426
+ /**
427
+ * replace all {find} inside {str} by {replace}
428
+ * @param text: string
429
+ * @param find: string
430
+ * @param replace: string
431
+ * @returns any
432
+ */
433
+ static replaceAll(text, find, replace) {
434
+ function escapeRegExp(str) {
435
+ return str.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, '\\$1');
436
+ }
437
+ return text.replace(new RegExp(escapeRegExp(find), 'g'), replace);
438
+ }
439
+ /**
440
+ * replace all with params
441
+ * param format: {number}
442
+ * @param text
443
+ * @param params
444
+ * @returns {string}
445
+ */
446
+ static replaceWithParams(text, params) {
447
+ _.map(params, (x, index) => {
448
+ text = TqlUtilsService.replaceAll(text, `{${index}}`, x);
449
+ });
450
+ return text;
451
+ }
452
+ /**
453
+ * check if is array, if is not, return [value]
454
+ * @param value: string
455
+ * @returns any
456
+ */
457
+ static toArray(value) {
458
+ return _.isArray(value) ? value : !!value ? [value] : [];
459
+ }
460
+ /**
461
+ * parse string to object
462
+ * @param xmlString: string
463
+ * @param callback: function
464
+ * @returns Promise<any>
465
+ */
466
+ static parseXml(xmlString, callback = (rs) => { }) {
467
+ return new Promise((resolve, reject) => {
468
+ xml2js.parseString(xmlString, { explicitArray: false, mergeAttrs: true }, (error, result) => {
469
+ if (error) {
470
+ reject(error);
471
+ throw new Error(error);
472
+ }
473
+ else {
474
+ resolve(result);
475
+ callback(result);
476
+ }
477
+ });
478
+ });
479
+ }
480
+ /**
481
+ * Clean management response
482
+ * @param data: management response
483
+ * @returns any
484
+ */
485
+ static transferData(data) {
486
+ if (!!data['data'] &&
487
+ !!data['data']['Find'] &&
488
+ (data['data']['Find']['Status'] === 'Success' || data['data']['Status'] === 'Success') &&
489
+ !!data['data']['Find']['Result']) {
490
+ return data['data']['Find']['Result'];
491
+ }
492
+ if (data['data'] && data['data']['Status'] === 'Success') {
493
+ if (!!_.get(data, 'management.Save')) {
494
+ return _.get(data, 'management.Save');
495
+ }
496
+ return data['data'];
497
+ }
498
+ return null;
499
+ }
500
+ /**
501
+ * Check and convert management
502
+ * @param data: Data response
503
+ * @param modelType: Model type
504
+ * @param key: If model type of management response other than model type (optional)
505
+ * @returns Model[]
506
+ */
507
+ static convertData(data, modelType, key = null) {
508
+ data = TqlUtilsService.transferData(data);
509
+ return this.convert(data, modelType, key);
510
+ }
511
+ /**
512
+ * Convert management to Model Type
513
+ * ! { Model.name } is undefined in run build
514
+ * @param data: Data response
515
+ * @param modelType: Model type
516
+ * @param key: If model type of management response other than model type (optional)
517
+ * @returns Model[]
518
+ */
519
+ static convert(data, modelType, key) {
520
+ if (!data || TqlUtilsService.isEmpty(data)) {
521
+ return [];
522
+ }
523
+ return _.concat(data).map((d) => {
524
+ const model = new modelType();
525
+ key = key || modelType.name;
526
+ // Convert response management to management Model
527
+ // Convert key name to camelcase
528
+ _.forEach(_.keys(d[key]), (k) => {
529
+ return (model[`${k.charAt(0).toLowerCase()}${k.substring(1)}`] = d[key][k]);
530
+ });
531
+ return model;
532
+ });
533
+ }
534
+ static jsonToModel(data, modelType) {
535
+ return _.concat(data).map((d) => {
536
+ const model = new modelType(d);
537
+ // Convert response management to management Model
538
+ // Convert key name to camelcase
539
+ _.forEach(_.keys(d), (k) => {
540
+ return (model[`${k.charAt(0).toLowerCase()}${k.substring(1)}`] = d[k]);
541
+ });
542
+ return model;
543
+ });
544
+ }
545
+ static signData(data, model, keyRepresent, key) {
546
+ const obj = {};
547
+ const arr = this.convertData(data, model, key);
548
+ obj[keyRepresent] = arr ? arr[0] : null;
549
+ return obj;
550
+ }
551
+ /**
552
+ * Return true if response is successful
553
+ * @param data: management
554
+ * @param path: string
555
+ * @returns ({message: undefined, status: boolean} | boolean | {message: undefined, status: boolean})
556
+ */
557
+ static isSuccess(data, path = 'data') {
558
+ const paths = ['Save', 'Create', 'DeleteAll', 'Update'];
559
+ let pathResult = '';
560
+ for (const p of paths) {
561
+ if (!!_.get(data, `${path}.${p}`)) {
562
+ pathResult = `${path}.${p}`;
563
+ }
564
+ }
565
+ if (!!_.get(data, path) && !pathResult) {
566
+ pathResult = path;
567
+ }
568
+ if (_.get(data, `${pathResult}.Status`) === 'Success' || _.get(data, `${pathResult}.status`) === 'Success') {
569
+ return {
570
+ status: _.get(data, `${pathResult}.Status`) === 'Success',
571
+ message: _.get(data, `${pathResult}.Message`),
572
+ };
573
+ }
574
+ return false;
575
+ }
576
+ /**
577
+ * Return true if response is failed
578
+ * @param data: management
579
+ * @returns boolean
580
+ */
581
+ static isError(data) {
582
+ if (data && data['Result'] && data['Result']['Status'] === 'Error') {
583
+ return true;
584
+ }
585
+ return false;
586
+ }
587
+ /**
588
+ * check if management is empty
589
+ * @param data: string
590
+ * @returns boolean
591
+ */
592
+ static isEmpty(data) {
593
+ if (data['data'] && data['data']['Find'] && data['data']['Find']['Status'] === 'NoResult') {
594
+ return true;
595
+ }
596
+ return false;
597
+ }
598
+ /**
599
+ * get file extension
600
+ * @param fileName: string
601
+ * @returns any
602
+ */
603
+ static getFileExtension(fileName) {
604
+ return _.last(_.split(fileName, '.'));
605
+ }
606
+ /**
607
+ * set string to clipboard
608
+ * @param str: string
609
+ */
610
+ static copyStringToClipboard(str) {
611
+ // Create new element
612
+ const el = document.createElement('textarea');
613
+ // Set value (string to be copied)
614
+ el.value = str;
615
+ // Set non-editable to avoid focus and move outside of view
616
+ el.setAttribute('readonly', '');
617
+ document.body.appendChild(el);
618
+ // Select text inside element
619
+ el.select();
620
+ // Copy text to clipboard
621
+ document.execCommand('copy');
622
+ // Remove temporary element
623
+ document.body.removeChild(el);
624
+ }
625
+ /**
626
+ * get enum key by its value
627
+ * @param myEnum
628
+ * @param enumValue
629
+ * @param isCaseSensitive
630
+ * @return {null}
631
+ */
632
+ static getEnumKeyByEnumValue(myEnum, enumValue, isCaseSensitive = true) {
633
+ return (_.find(Object.keys(myEnum), (x) => isCaseSensitive
634
+ ? myEnum[x] === enumValue
635
+ : myEnum[x].toString().toLowerCase() === enumValue.toString().toLowerCase()) || null);
636
+ }
637
+ /**
638
+ * shorten number
639
+ * @param value
640
+ * @returns {any}
641
+ */
642
+ static abbreviateNumber(value) {
643
+ let newValue = value;
644
+ const suffixes = ['', 'kb', 'mb', 'b', 'tb'];
645
+ let suffixNum = 0;
646
+ while (newValue >= 1000 && suffixNum < _.size(suffixes)) {
647
+ newValue = (newValue / 1000).toFixed(1);
648
+ suffixNum++;
649
+ // for (let precision = 2; precision >= 1; precision--) {
650
+ // shortValue = parseFloat((suffixNum !== 0 ? value / Math.pow(1000, suffixNum) : value).toPrecision(precision));
651
+ // const dotLessShortValue = (shortValue + '').replace(/[^a-zA-Z 0-9]+/g, '');
652
+ // if (dotLessShortValue.length <= 2) {
653
+ // break;
654
+ // }
655
+ // }
656
+ // if (shortValue % 1 !== 0) {
657
+ // shortValue = shortValue.toFixed(1);
658
+ // }
659
+ // newValue = shortValue + suffixes[suffixNum];
660
+ }
661
+ return newValue + suffixes[suffixNum];
662
+ }
663
+ /**
664
+ * convert json to tree
665
+ * @param json
666
+ * @param key
667
+ * @returns {any}
668
+ */
669
+ static jsonToTree(data) {
670
+ if (TqlUtilsService.isObject(data)) {
671
+ const keys = Object.keys(data);
672
+ return _.map(keys, (x) => {
673
+ if (TqlUtilsService.isObject(data[x])) {
674
+ return {
675
+ title: x,
676
+ children: TqlUtilsService.jsonToTree(data[x]),
677
+ };
678
+ }
679
+ if (TqlUtilsService.isArray(data[x])) {
680
+ return {
681
+ title: x,
682
+ children: _.flatten(TqlUtilsService.jsonToTree(data[x])),
683
+ };
684
+ }
685
+ else {
686
+ return {
687
+ title: x,
688
+ name: data[x],
689
+ };
690
+ }
691
+ });
692
+ }
693
+ else if (TqlUtilsService.isArray(data)) {
694
+ return _.map(data, (x) => TqlUtilsService.jsonToTree(x));
695
+ }
696
+ else {
697
+ return {
698
+ name: data,
699
+ };
700
+ }
701
+ }
702
+ /**
703
+ * swap element in array
704
+ * @param array
705
+ * @param firstIndex
706
+ * @param secondIndex
707
+ */
708
+ static swap(array, firstIndex, secondIndex) {
709
+ if (!!array[firstIndex] && !!array[secondIndex]) {
710
+ const tmp = array[firstIndex];
711
+ array[firstIndex] = array[secondIndex];
712
+ array[secondIndex] = tmp;
713
+ }
714
+ }
715
+ static isObject(data) {
716
+ return data?.constructor === {}.constructor;
717
+ }
718
+ static isArray(data) {
719
+ return data?.constructor === [].constructor;
720
+ }
721
+ static buildTreeFromChild(child) {
722
+ let parent;
723
+ while (child?.parent) {
724
+ parent = child?.parent;
725
+ parent.children = [child];
726
+ child = parent;
727
+ }
728
+ return parent || child;
729
+ }
730
+ static traversalTree(list, callback, parent) {
731
+ _.map(list, (x) => {
732
+ if (!!x) {
733
+ x.parent = null;
734
+ if (!!parent) {
735
+ x.parent = parent;
736
+ }
737
+ if (x?.children?.length) {
738
+ TqlUtilsService.traversalTree(x.children, callback, x);
739
+ }
740
+ callback(x, parent);
741
+ }
742
+ });
743
+ }
744
+ static traversalTreeReverse(node, callback) {
745
+ callback(node);
746
+ if (!!node.parent) {
747
+ TqlUtilsService.traversalTreeReverse(node.parent, callback);
748
+ }
749
+ }
750
+ static findNodeOfTree(list, condition) {
751
+ let found = null;
752
+ for (let i = 0; i < list.length; i++) {
753
+ if (condition(list[i])) {
754
+ found = list[i];
755
+ break;
756
+ }
757
+ else if (list[i]?.children?.length) {
758
+ found = TqlUtilsService.findNodeOfTree(list[i].children, condition);
759
+ if (found) {
760
+ break;
761
+ }
762
+ }
763
+ }
764
+ return found;
765
+ }
766
+ static filterNodeOfTree(list, condition) {
767
+ const foundList = [];
768
+ this.traversalTree(list, (x) => {
769
+ if (condition(x)) {
770
+ foundList.push(x);
771
+ }
772
+ });
773
+ return foundList;
774
+ }
775
+ /**
776
+ * get parent route when using in guard
777
+ * @param route
778
+ */
779
+ static getRedirectToRoute(route) {
780
+ return route.pathFromRoot
781
+ .filter((p) => p !== route && p.url !== null && p.url.length > 0)
782
+ .reduce((arr, p) => arr.concat(p.url.map((u) => u.path)), new Array());
783
+ }
784
+ static getResolvedUrl(route) {
785
+ return ('/' +
786
+ route.pathFromRoot
787
+ .filter((v) => v.url?.length)
788
+ .map((v) => v.url.map((segment) => segment.toString()).join('/'))
789
+ .join('/'));
790
+ }
791
+ static getUrlFromSegments(segments) {
792
+ if (!!segments) {
793
+ return encodeURI('/' +
794
+ _.join(_.map(segments, (x) => x?.path), '/'));
795
+ }
796
+ return '';
797
+ }
798
+ static clearLineBreakR(s) {
799
+ return _.replace(s, /(\r\n|\r)/g, '\n');
800
+ }
801
+ static transferToCapitalText(s, exceptions = {}) {
802
+ function capitalize(s) {
803
+ if (typeof s !== 'string') {
804
+ return '';
805
+ }
806
+ return s.charAt(0).toUpperCase() + s.slice(1);
807
+ }
808
+ s = capitalize(s);
809
+ return !!exceptions[s] ? exceptions[s] : s.replace(/([A-Z])/g, ' $1').trim();
810
+ }
811
+ static parsePayloadWithObject(query, dataObject) {
812
+ if (!Object.keys(dataObject).length) {
813
+ return query;
814
+ }
815
+ Object.keys(dataObject).forEach((k) => {
816
+ query = TqlUtilsService.replaceAll(query.toString(), `{${k}}`, dataObject[k]);
817
+ });
818
+ return query;
819
+ }
820
+ static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.17", ngImport: i0, type: TqlUtilsService, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
821
+ static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "19.2.17", ngImport: i0, type: TqlUtilsService }); }
822
+ }
823
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.17", ngImport: i0, type: TqlUtilsService, decorators: [{
824
+ type: Injectable
825
+ }], ctorParameters: () => [] });
826
+
827
+ class SiteMap {
828
+ constructor(key, children = []) {
829
+ this.key = key;
830
+ this.children = children;
831
+ }
832
+ addChild(child) {
833
+ this.children.push(child);
834
+ }
835
+ set lazyLoading(value) {
836
+ this._lazyLoading = value;
837
+ }
838
+ get lazyLoading() {
839
+ return this._lazyLoading;
840
+ }
841
+ checkLazyLoading(compareClassName, siteMaps) {
842
+ let isMatch = false;
843
+ if (this.lazyLoading) {
844
+ // remove 'Routing' text then compare
845
+ if (TqlUtilsService.replaceAll(compareClassName, 'Routing', '') === this.lazyLoading) {
846
+ isMatch = true;
847
+ this.children = siteMaps;
848
+ }
849
+ }
850
+ return isMatch;
851
+ }
852
+ }
853
+ class TqlSiteMapControllerService {
854
+ static { this.SiteMap = SiteMap; }
855
+ constructor() {
856
+ this._siteMap = new Map();
857
+ }
858
+ async addRoutes(routes, appName, routingClassName) {
859
+ // console.log(appName);
860
+ // console.log(routingClassName);
861
+ // console.log(routes);
862
+ const newRoute = {
863
+ path: 'root',
864
+ children: routes,
865
+ };
866
+ const newSiteMap = await this.traversalRoute(newRoute);
867
+ const foundSiteMap = this._siteMap.get(appName);
868
+ if (newSiteMap) {
869
+ if (!!foundSiteMap) {
870
+ // existed
871
+ foundSiteMap.checkLazyLoading(routingClassName, newSiteMap.children);
872
+ }
873
+ else {
874
+ // new
875
+ this._siteMap.set(appName, newSiteMap);
876
+ }
877
+ }
878
+ // console.log(this._siteMap.get(appName));
879
+ // console.log('');
880
+ // this.print(newSiteMap);
881
+ }
882
+ async traversalRoute(route) {
883
+ if (isUndefined(route.path)) {
884
+ return;
885
+ }
886
+ const newSiteMap = new SiteMap(route.path);
887
+ // children
888
+ if (route.children) {
889
+ route.children.map(async (r, index) => {
890
+ const child = await this.traversalRoute(r);
891
+ if (child) {
892
+ newSiteMap.addChild(child);
893
+ }
894
+ });
895
+ }
896
+ // lazy loading
897
+ if (route.loadChildren) {
898
+ try {
899
+ const fn = route?.loadChildren;
900
+ newSiteMap.lazyLoading = (await fn()).name;
901
+ }
902
+ catch (e) { }
903
+ }
904
+ return newSiteMap;
905
+ }
906
+ print(siteMap, index = 0) {
907
+ if (!!siteMap) {
908
+ index++;
909
+ const preFix = _.map(_.range(index), () => '_').join('');
910
+ console.log(preFix + siteMap.key);
911
+ _.map(siteMap.children, (x) => {
912
+ this.print(x, index);
913
+ });
914
+ }
915
+ }
916
+ static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.17", ngImport: i0, type: TqlSiteMapControllerService, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
917
+ static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "19.2.17", ngImport: i0, type: TqlSiteMapControllerService }); }
918
+ }
919
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.17", ngImport: i0, type: TqlSiteMapControllerService, decorators: [{
920
+ type: Injectable
921
+ }], ctorParameters: () => [] });
922
+
923
+ class TqlToastControllerService {
924
+ constructor(_MatSnackBar) {
925
+ this._MatSnackBar = _MatSnackBar;
926
+ this.X_BUTTON = 'Close';
927
+ }
928
+ openSimple(message, duration = TqlToastControllerService.DURATION.SHORT) {
929
+ this._MatSnackBar.open(message, this.X_BUTTON, { duration });
930
+ }
931
+ openSuccess(message, duration = TqlToastControllerService.DURATION.SHORT) {
932
+ // TODO
933
+ this._MatSnackBar.open(message, this.X_BUTTON, { duration });
934
+ }
935
+ openError(message, duration = TqlToastControllerService.DURATION.SHORT) {
936
+ // TODO
937
+ this._MatSnackBar.open(message, this.X_BUTTON, { duration });
938
+ }
939
+ openWarning(message, duration = TqlToastControllerService.DURATION.SHORT) {
940
+ // TODO
941
+ this._MatSnackBar.open(message, this.X_BUTTON, { duration });
942
+ }
943
+ static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.17", ngImport: i0, type: TqlToastControllerService, deps: [{ token: i1$1.MatSnackBar }], target: i0.ɵɵFactoryTarget.Injectable }); }
944
+ static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "19.2.17", ngImport: i0, type: TqlToastControllerService }); }
945
+ }
946
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.17", ngImport: i0, type: TqlToastControllerService, decorators: [{
947
+ type: Injectable
948
+ }], ctorParameters: () => [{ type: i1$1.MatSnackBar }] });
949
+ (function (TqlToastControllerService) {
950
+ let DURATION;
951
+ (function (DURATION) {
952
+ DURATION[DURATION["SHORT"] = 3000] = "SHORT";
953
+ DURATION[DURATION["LONG"] = 20000] = "LONG";
954
+ })(DURATION = TqlToastControllerService.DURATION || (TqlToastControllerService.DURATION = {}));
955
+ })(TqlToastControllerService || (TqlToastControllerService = {}));
956
+
957
+ class TqlDialogControllerService {
958
+ constructor(_MatDialog) {
959
+ this._MatDialog = _MatDialog;
960
+ this._openingDialogs = [];
961
+ this._Observable_Is_Opening_Dialogs = new BehaviorSubject(DefaultDialogComponent.State.CLOSED);
962
+ }
963
+ /**
964
+ * add dialog to storage to check opening status
965
+ * @param dialog
966
+ * @private
967
+ */
968
+ _addDialog(dialog) {
969
+ this._openingDialogs.push(dialog);
970
+ this._Observable_Is_Opening_Dialogs.next(this._openingDialogs.length > 0
971
+ ? DefaultDialogComponent.State.OPENING
972
+ : DefaultDialogComponent.State.CLOSED);
973
+ }
974
+ /**
975
+ * remove dialog to storage to check opening status
976
+ * @param dialog
977
+ * @private
978
+ */
979
+ _removeDialog(dialog) {
980
+ _.remove(this._openingDialogs, dialog);
981
+ this._Observable_Is_Opening_Dialogs.next(this._openingDialogs.length > 0
982
+ ? DefaultDialogComponent.State.OPENING
983
+ : DefaultDialogComponent.State.CLOSED);
984
+ }
985
+ open(classComp, data = {}, options = {}) {
986
+ // default not allow close when click backdrop
987
+ options['disableClose'] = true;
988
+ // width
989
+ options['width'] = classComp.DEFAULT_WIDTH;
990
+ options['height'] = classComp.DEFAULT_HEIGHT;
991
+ options['maxHeight'] = '80vh';
992
+ const dialog = this._MatDialog.open(classComp, {
993
+ ...options,
994
+ data: data,
995
+ autoFocus: false,
996
+ });
997
+ if (options['callback']) {
998
+ options['callback'](dialog);
999
+ }
1000
+ // tmp store dialog
1001
+ this._addDialog(dialog);
1002
+ return new Promise((resolve, reject) => {
1003
+ dialog.afterClosed().subscribe((result) => {
1004
+ // remove dialog from the tmp stored
1005
+ this._removeDialog(dialog);
1006
+ resolve(result);
1007
+ });
1008
+ });
1009
+ }
1010
+ confirm(text) {
1011
+ return confirm(text);
1012
+ }
1013
+ alert(text) {
1014
+ alert(text);
1015
+ }
1016
+ prompt(text) {
1017
+ return prompt(text);
1018
+ }
1019
+ static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.17", ngImport: i0, type: TqlDialogControllerService, deps: [{ token: i1.MatDialog }], target: i0.ɵɵFactoryTarget.Injectable }); }
1020
+ static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "19.2.17", ngImport: i0, type: TqlDialogControllerService }); }
1021
+ }
1022
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.17", ngImport: i0, type: TqlDialogControllerService, decorators: [{
1023
+ type: Injectable
1024
+ }], ctorParameters: () => [{ type: i1.MatDialog }] });
1025
+
1026
+ class TqlRouteControllerService {
1027
+ constructor() { }
1028
+ static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.17", ngImport: i0, type: TqlRouteControllerService, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
1029
+ static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "19.2.17", ngImport: i0, type: TqlRouteControllerService }); }
1030
+ }
1031
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.17", ngImport: i0, type: TqlRouteControllerService, decorators: [{
1032
+ type: Injectable
1033
+ }], ctorParameters: () => [] });
1034
+
1035
+ class TqlTableControllerService {
1036
+ constructor() {
1037
+ this.filterGroup = {};
1038
+ }
1039
+ generateFilter(id) {
1040
+ if (!this.filterGroup[id]) {
1041
+ this.filterGroup[id] = {
1042
+ onUpdate$: new Subject(),
1043
+ onUpdateUI$: new Subject(),
1044
+ };
1045
+ }
1046
+ }
1047
+ getFilter(id) {
1048
+ return this.filterGroup[id];
1049
+ }
1050
+ static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.17", ngImport: i0, type: TqlTableControllerService, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
1051
+ static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "19.2.17", ngImport: i0, type: TqlTableControllerService, providedIn: 'root' }); }
1052
+ }
1053
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.17", ngImport: i0, type: TqlTableControllerService, decorators: [{
1054
+ type: Injectable,
1055
+ args: [{
1056
+ providedIn: 'root',
1057
+ }]
1058
+ }], ctorParameters: () => [] });
1059
+
1060
+ // import moment from 'moment';
1061
+ class TqlLoggerService {
1062
+ constructor() {
1063
+ this.log$ = new BehaviorSubject('');
1064
+ }
1065
+ /**
1066
+ * log result
1067
+ * @param data: any
1068
+ */
1069
+ _logResult(...data) {
1070
+ // console.log(`[${this.constructor.name}]`, 'result \n', ...data);
1071
+ }
1072
+ /**
1073
+ * log error
1074
+ * @param error: any
1075
+ */
1076
+ _logError(...error) {
1077
+ console.error(`[${this.constructor.name}]`, 'error \n', ...error);
1078
+ }
1079
+ /**
1080
+ * log message
1081
+ * @param message
1082
+ */
1083
+ log(message) {
1084
+ // console.log(`${moment().format()} `, message);
1085
+ this.log$.next(message + '');
1086
+ }
1087
+ static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.17", ngImport: i0, type: TqlLoggerService, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
1088
+ static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "19.2.17", ngImport: i0, type: TqlLoggerService, providedIn: 'root' }); }
1089
+ }
1090
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.17", ngImport: i0, type: TqlLoggerService, decorators: [{
1091
+ type: Injectable,
1092
+ args: [{
1093
+ providedIn: 'root',
1094
+ }]
1095
+ }], ctorParameters: () => [] });
1096
+
1097
+ // import {LoadingBarService} from '@ngx-loading-bar/core';
1098
+ class TqlErrorHandlerService extends TqlLoggerService {
1099
+ constructor(_Injector) {
1100
+ super();
1101
+ if (_Injector) {
1102
+ this._TqlToastControllerService = _Injector.get(TqlToastControllerService);
1103
+ }
1104
+ }
1105
+ /**
1106
+ *
1107
+ * @param error
1108
+ * @returns {EErrorStatus.FORBIDDEN | null}
1109
+ */
1110
+ handleHttpError(error) {
1111
+ // if forbidden or un-authentication then return forbidden
1112
+ if ([401, 403].includes(error.status)) {
1113
+ return TqlErrorHandlerService.EErrorStatus.FORBIDDEN;
1114
+ }
1115
+ if (error.error instanceof ErrorEvent) {
1116
+ // A client-side or network error occurred. Handle it accordingly.
1117
+ this._logError('An error occurred: ', error.error.message);
1118
+ }
1119
+ else {
1120
+ // The backend returned an unsuccessful response code.
1121
+ // The response body may contain clues as to what went wrong,
1122
+ this._logError(`Backend returned code ${error.status}, `, `message was: ${error.message}`);
1123
+ }
1124
+ // return an observable with a user-facing error message
1125
+ throwError('Something bad happened; please try again later.');
1126
+ return null;
1127
+ }
1128
+ /**
1129
+ *
1130
+ * @param response
1131
+ * @returns {boolean}
1132
+ */
1133
+ handleSimpleResponse(response) {
1134
+ const event = {
1135
+ status: false,
1136
+ message: 'Error',
1137
+ data: response['data'],
1138
+ };
1139
+ if (response['data']['Response']) {
1140
+ event.status = response['data']['Response']['Status'] === 'Success';
1141
+ event.message = response['data']['Response']['Message'];
1142
+ }
1143
+ // print message
1144
+ return this.handleStatusMessage(event);
1145
+ }
1146
+ /**
1147
+ *
1148
+ * @param response
1149
+ * @returns {boolean}
1150
+ */
1151
+ handleAPIResponseMessage(response) {
1152
+ const event = {
1153
+ status: false,
1154
+ message: 'Error',
1155
+ data: response['data'],
1156
+ };
1157
+ if (response['data']['APIResponse']) {
1158
+ event.status = response['data']['APIResponse']['Status'] === 'Success';
1159
+ event.message = response['data']['APIResponse']['Message'];
1160
+ }
1161
+ // print message
1162
+ return this.handleStatusMessage(event);
1163
+ }
1164
+ /**
1165
+ *
1166
+ * @param response
1167
+ * @returns {boolean}
1168
+ */
1169
+ handleCreate(response) {
1170
+ const event = {
1171
+ status: false,
1172
+ message: 'Error',
1173
+ data: response['data'],
1174
+ };
1175
+ if (response['data']['Create']) {
1176
+ event.status = response['data']['Create']['Status'] === 'Success';
1177
+ event.message = 'Creation is successful';
1178
+ }
1179
+ else {
1180
+ event.message = 'Creation occurs error';
1181
+ }
1182
+ // print message
1183
+ return this.handleStatusMessage(event);
1184
+ }
1185
+ /**
1186
+ *
1187
+ * @param response
1188
+ * @returns {boolean}
1189
+ */
1190
+ handleUpdate(response) {
1191
+ const event = {
1192
+ status: false,
1193
+ message: 'Error',
1194
+ data: response['data'],
1195
+ };
1196
+ if (response['data']['Save']) {
1197
+ event.status = response['data']['Save']['Status'] === 'Success';
1198
+ event.message = 'Update is successful';
1199
+ }
1200
+ else if (response['data']['Update']) {
1201
+ event.status = response['data']['Update']['Status'] === 'Success';
1202
+ event.message = 'Update is successful';
1203
+ }
1204
+ else {
1205
+ event.message = 'Update occurs error';
1206
+ }
1207
+ // print message
1208
+ return this.handleStatusMessage(event);
1209
+ }
1210
+ /**
1211
+ * show message base on status
1212
+ * @param event
1213
+ * @return {boolean}
1214
+ */
1215
+ handleStatusMessage(event) {
1216
+ if (event.status) {
1217
+ this._showSuccessMessage(event.message);
1218
+ }
1219
+ else {
1220
+ this._showErrorMessage(event.message);
1221
+ }
1222
+ return event.status;
1223
+ }
1224
+ /**
1225
+ *
1226
+ * @param message
1227
+ */
1228
+ _showSuccessMessage(message) {
1229
+ this._TqlToastControllerService.openSuccess(message, TqlToastControllerService.DURATION.SHORT);
1230
+ }
1231
+ /**
1232
+ *
1233
+ * @param message
1234
+ */
1235
+ _showErrorMessage(message = 'Some error occur') {
1236
+ this._TqlToastControllerService.openError(message, TqlToastControllerService.DURATION.LONG);
1237
+ }
1238
+ static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.17", ngImport: i0, type: TqlErrorHandlerService, deps: [{ token: i0.Injector }], target: i0.ɵɵFactoryTarget.Injectable }); }
1239
+ static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "19.2.17", ngImport: i0, type: TqlErrorHandlerService }); }
1240
+ }
1241
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.17", ngImport: i0, type: TqlErrorHandlerService, decorators: [{
1242
+ type: Injectable
1243
+ }], ctorParameters: () => [{ type: i0.Injector }] });
1244
+ (function (TqlErrorHandlerService) {
1245
+ let EErrorStatus;
1246
+ (function (EErrorStatus) {
1247
+ EErrorStatus[EErrorStatus["FORBIDDEN"] = 0] = "FORBIDDEN";
1248
+ EErrorStatus["SUCCESS"] = "Success";
1249
+ EErrorStatus["ERROR"] = "Error";
1250
+ })(EErrorStatus = TqlErrorHandlerService.EErrorStatus || (TqlErrorHandlerService.EErrorStatus = {}));
1251
+ })(TqlErrorHandlerService || (TqlErrorHandlerService = {}));
1252
+
1253
+ class TqlApiLibService extends TqlLoggerService {
1254
+ constructor(_HttpClient, _TqlErrorHandlerService) {
1255
+ super();
1256
+ this._HttpClient = _HttpClient;
1257
+ this._TqlErrorHandlerService = _TqlErrorHandlerService;
1258
+ }
1259
+ /**
1260
+ *
1261
+ * @param url
1262
+ */
1263
+ initialize(url) {
1264
+ this._default_url = url;
1265
+ }
1266
+ /**
1267
+ * reset all subscription
1268
+ */
1269
+ reset() { }
1270
+ /**
1271
+ * get url
1272
+ * @returns string
1273
+ */
1274
+ getUrl() {
1275
+ return `${this._default_url}`;
1276
+ }
1277
+ /**
1278
+ * Execute payload
1279
+ * @param payload: Payload
1280
+ * @param headers: Headers of query
1281
+ * @param url: URL custom (optional)
1282
+ * @returns {Promise<T | string>}
1283
+ * @param params
1284
+ * @param contentType
1285
+ */
1286
+ async execute(payload, params = [], headers = {}, url, contentType = 'text/plain') {
1287
+ return await this.executeHttpClient(payload, params, headers, url, contentType)
1288
+ .toPromise()
1289
+ .then((data) => {
1290
+ // this.checkPermission(data);
1291
+ return data;
1292
+ });
1293
+ }
1294
+ /**
1295
+ * Execute http client
1296
+ * @param payload: Payload
1297
+ * @param headers: Headers of query
1298
+ * @param url: URL custom (optional)
1299
+ * @param params
1300
+ * @param contentType
1301
+ * @returns {Observable<T | string>}
1302
+ */
1303
+ executeHttpClient(payload, params = [], headers = {}, url, contentType = 'text/plain') {
1304
+ return this._HttpClient
1305
+ .post(url || this.getUrl(), payload.buildPayload(params), {
1306
+ headers: new HttpHeaders({
1307
+ 'Content-Type': contentType,
1308
+ ...headers,
1309
+ }),
1310
+ responseType: 'text',
1311
+ })
1312
+ .pipe(tap(this._TqlErrorHandlerService._logResult, this._TqlErrorHandlerService._logError),
1313
+ // then handle the error
1314
+ catchError((err) => {
1315
+ return this._TqlErrorHandlerService.handleHttpError(err);
1316
+ }));
1317
+ }
1318
+ async get(url, contentType = 'text/plain', headers = {}) {
1319
+ return await this._HttpClient
1320
+ .get(url, {
1321
+ headers: new HttpHeaders({
1322
+ 'Content-Type': contentType,
1323
+ ...headers,
1324
+ }),
1325
+ responseType: 'text',
1326
+ })
1327
+ .toPromise();
1328
+ }
1329
+ /**
1330
+ *
1331
+ * @param payload
1332
+ * @param params
1333
+ * @param headers
1334
+ * @param url
1335
+ * @param contentType
1336
+ * @return {Promise<{data: any[], raw: {}} | {data: any[], raw: {}}>}
1337
+ */
1338
+ async findRaw(payload, params = [], headers = {}, url, contentType) {
1339
+ return await this.execute(payload, params, headers, url, contentType)
1340
+ .then(async (data) => {
1341
+ let json = {};
1342
+ try {
1343
+ json = {
1344
+ data: JSON.parse(data),
1345
+ };
1346
+ }
1347
+ catch (e) {
1348
+ json = TqlUtilsService.parseXml(`<data>${data}</data>`);
1349
+ }
1350
+ return json;
1351
+ })
1352
+ .then((json) => {
1353
+ const pathRoot = 'data';
1354
+ let array = [];
1355
+ if (payload.objectPath !== null && payload.objectPath !== undefined) {
1356
+ array = _.get(json, `${pathRoot}${payload.objectPath && '.' + payload.objectPath}`) || [];
1357
+ array = TqlUtilsService.toArray(array);
1358
+ }
1359
+ array = payload.parse(array);
1360
+ return {
1361
+ raw: json,
1362
+ data: array,
1363
+ };
1364
+ });
1365
+ }
1366
+ /**
1367
+ * find management and convert to management model
1368
+ * @param payload: Payload
1369
+ * @param params: any
1370
+ * @param headers: any
1371
+ * @param url: string
1372
+ * @param contentType
1373
+ * @return {Promise<any[]>}
1374
+ */
1375
+ async find(payload, params = [], headers = {}, url, contentType) {
1376
+ return await this.findRaw(payload, params, headers, url, contentType).then(({ raw, data }) => {
1377
+ return data;
1378
+ });
1379
+ }
1380
+ /**
1381
+ *
1382
+ * @param payload
1383
+ * @param params
1384
+ * @param headers
1385
+ * @param url
1386
+ * @param contentType
1387
+ * @returns {Promise<{}>}
1388
+ */
1389
+ async post(payload, params = [], headers = {}, url, contentType) {
1390
+ return await this.findRaw(payload, params, headers, url, contentType).then(({ raw, data }) => {
1391
+ return raw;
1392
+ });
1393
+ }
1394
+ static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.17", ngImport: i0, type: TqlApiLibService, deps: [{ token: i1$2.HttpClient }, { token: TqlErrorHandlerService }], target: i0.ɵɵFactoryTarget.Injectable }); }
1395
+ static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "19.2.17", ngImport: i0, type: TqlApiLibService }); }
1396
+ }
1397
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.17", ngImport: i0, type: TqlApiLibService, decorators: [{
1398
+ type: Injectable
1399
+ }], ctorParameters: () => [{ type: i1$2.HttpClient }, { type: TqlErrorHandlerService }] });
1400
+
1401
+ class TqlWsService extends TqlLoggerService {
1402
+ static { this.maxDefaultReconnectCount = 10; }
1403
+ static { this.maxDefaultSameTimeApi = 100; }
1404
+ constructor() {
1405
+ super();
1406
+ /**
1407
+ * status
1408
+ * @type {BehaviorSubject<TqlWsService.Status>}
1409
+ */
1410
+ this.status$ = new BehaviorSubject(new TqlWsService.Status());
1411
+ /**
1412
+ * message
1413
+ * @type {BehaviorSubject<string>}
1414
+ */
1415
+ this.message$ = new BehaviorSubject('');
1416
+ this.autoReconnect = false;
1417
+ this.url = '';
1418
+ this.pendingPayloads = [];
1419
+ this.storedPayloads = [];
1420
+ /**
1421
+ * events
1422
+ * @type {any}
1423
+ */
1424
+ this.events = {
1425
+ open: TqlWsService.ENUM_TYPES.EMPTY,
1426
+ close: TqlWsService.ENUM_TYPES.EMPTY,
1427
+ error: TqlWsService.ENUM_TYPES.EMPTY,
1428
+ message: TqlWsService.ENUM_TYPES.EMPTY,
1429
+ };
1430
+ /*options*/
1431
+ this.options = {
1432
+ max_reconnect_count: TqlWsService.maxDefaultReconnectCount,
1433
+ max_same_time_api: TqlWsService.maxDefaultSameTimeApi,
1434
+ };
1435
+ this.handleMessage();
1436
+ }
1437
+ /**
1438
+ * connect to url
1439
+ * @param url
1440
+ * @param autoReconnect
1441
+ * @param options
1442
+ */
1443
+ connect(url, autoReconnect = false, options = {
1444
+ max_reconnect_count: TqlWsService.maxDefaultReconnectCount,
1445
+ }) {
1446
+ // options
1447
+ this.original_options = ___default.cloneDeep(options);
1448
+ if (___default.isUndefined(this.original_options?.max_same_time_api)) {
1449
+ this.original_options.max_same_time_api = TqlWsService.maxDefaultSameTimeApi;
1450
+ }
1451
+ // make sure options not empty
1452
+ this.options = ___default.cloneDeep(this.original_options);
1453
+ // reset
1454
+ const $end = this.end(this.socket ? TqlWsService.ENUM_CODES.RESTART : TqlWsService.ENUM_CODES.START);
1455
+ $end.then(() => {
1456
+ //
1457
+ this.autoReconnect = autoReconnect;
1458
+ this.url = url;
1459
+ // set events
1460
+ this.setEvents();
1461
+ // start socket
1462
+ this.socket = new WebSocket(this.url);
1463
+ this.socket.addEventListener('open', this.events.open);
1464
+ this.socket.addEventListener('close', this.events.close);
1465
+ this.socket.addEventListener('error', this.events.error);
1466
+ this.socket.addEventListener('message', this.events.message);
1467
+ });
1468
+ }
1469
+ /**
1470
+ * reconnect
1471
+ */
1472
+ reconnect() {
1473
+ this.log(`Socket reconnect.`);
1474
+ if (this.url) {
1475
+ this.options.max_reconnect_count--;
1476
+ if (this.options.max_reconnect_count > 0) {
1477
+ this.connect(this.url, this.autoReconnect, this.options);
1478
+ }
1479
+ else {
1480
+ this.updateStatus(TqlWsService.ENUM_ACTIONS.DISCONNECT);
1481
+ }
1482
+ }
1483
+ }
1484
+ /**
1485
+ * end the connection
1486
+ * @param code
1487
+ * @returns {Promise<boolean>}
1488
+ */
1489
+ end(code = TqlWsService.ENUM_CODES.END) {
1490
+ return new Promise((resolve) => {
1491
+ this.autoReconnect = false;
1492
+ // remove events & close socket
1493
+ if (this.socket) {
1494
+ this.socket.close(TqlWsService.CODES[code].code, TqlWsService.CODES[code].message);
1495
+ this.status$
1496
+ .pipe(skipWhile((x) => x.connected), first())
1497
+ .subscribe((rs) => {
1498
+ ___default.map(this.events, (x, k) => {
1499
+ if (x !== TqlWsService.ENUM_TYPES.EMPTY) {
1500
+ this.socket?.removeEventListener(k, x);
1501
+ }
1502
+ });
1503
+ // disconnect
1504
+ this.reset();
1505
+ // status
1506
+ this.updateStatus(TqlWsService.ENUM_ACTIONS.END);
1507
+ resolve(true);
1508
+ });
1509
+ }
1510
+ else {
1511
+ // disconnect
1512
+ this.reset();
1513
+ // status
1514
+ this.updateStatus(TqlWsService.ENUM_ACTIONS.END);
1515
+ resolve(false);
1516
+ }
1517
+ });
1518
+ }
1519
+ /**
1520
+ * reset all values
1521
+ */
1522
+ reset() {
1523
+ // reset
1524
+ this.socket = null;
1525
+ this.url = '';
1526
+ this.events = {
1527
+ open: TqlWsService.ENUM_TYPES.EMPTY,
1528
+ close: TqlWsService.ENUM_TYPES.EMPTY,
1529
+ error: TqlWsService.ENUM_TYPES.EMPTY,
1530
+ message: TqlWsService.ENUM_TYPES.EMPTY,
1531
+ };
1532
+ }
1533
+ /**
1534
+ * call api
1535
+ * @param payload
1536
+ * @param isWaiver - not wait for response
1537
+ * @returns {Promise<any>}
1538
+ */
1539
+ call(payload, isWaiver = false) {
1540
+ if (this.socket) {
1541
+ if (!isWaiver) {
1542
+ // store if it is not waiver
1543
+ this.storedPayloads.push(payload);
1544
+ this.processPayload();
1545
+ }
1546
+ else {
1547
+ // send if it is waiver
1548
+ this.socket?.send(payload?.query);
1549
+ }
1550
+ }
1551
+ return payload.$promise;
1552
+ }
1553
+ processPayload() {
1554
+ while (this.storedPayloads?.length && this.pendingPayloads.length < (this.options?.max_same_time_api || 0)) {
1555
+ const payload = this.storedPayloads.shift();
1556
+ if (!!payload) {
1557
+ this.pendingPayloads.push(payload);
1558
+ this.socket?.send(payload?.query);
1559
+ }
1560
+ }
1561
+ }
1562
+ /**
1563
+ * set event after connect
1564
+ */
1565
+ setEvents() {
1566
+ this.events.open = () => {
1567
+ this.log(`Socket connected.`);
1568
+ // status
1569
+ this.updateStatus(TqlWsService.ENUM_ACTIONS.CONNECT);
1570
+ // options
1571
+ this.options = ___default.cloneDeep(this.original_options);
1572
+ };
1573
+ this.events.close = () => {
1574
+ this.log(`Socket closed.`);
1575
+ // status
1576
+ this.updateStatus(TqlWsService.ENUM_ACTIONS.DISCONNECT);
1577
+ if (this.autoReconnect) {
1578
+ this.reconnect();
1579
+ }
1580
+ else {
1581
+ this.reset();
1582
+ }
1583
+ };
1584
+ this.events.error = (event) => {
1585
+ this.log(`Socket errored.`);
1586
+ this.log(event);
1587
+ // status
1588
+ this.updateStatus(TqlWsService.ENUM_ACTIONS.DISCONNECT);
1589
+ if (this.autoReconnect) {
1590
+ this.reconnect();
1591
+ }
1592
+ else {
1593
+ this.reset();
1594
+ }
1595
+ };
1596
+ this.events.message = (event) => {
1597
+ const data = event?.data;
1598
+ if (data) {
1599
+ this.log(`Socket has message come.`);
1600
+ this.log(data);
1601
+ this.message$.next(data);
1602
+ }
1603
+ };
1604
+ }
1605
+ /**
1606
+ * handle coming message
1607
+ */
1608
+ handleMessage() {
1609
+ this.message$
1610
+ // .pipe(concatMap((data) => from(this.resolveMessage(data))))
1611
+ .subscribe((data) => {
1612
+ // console.log(this.pendingPayloads);
1613
+ ___default.forEach(this.pendingPayloads, (x) => {
1614
+ if (x.resolve(data)) {
1615
+ ___default.remove(this.pendingPayloads, x);
1616
+ this.processPayload();
1617
+ return false;
1618
+ }
1619
+ return true;
1620
+ });
1621
+ this.log('|||||||||||| Pending Payloads: ' + this.pendingPayloads?.length);
1622
+ if (this.pendingPayloads?.length <= 10) {
1623
+ this.log(this.pendingPayloads);
1624
+ }
1625
+ });
1626
+ }
1627
+ /**
1628
+ * update status$
1629
+ * @param action
1630
+ */
1631
+ updateStatus(action) {
1632
+ const status = this.status$.value;
1633
+ switch (action) {
1634
+ case TqlWsService.ENUM_ACTIONS.CONNECT:
1635
+ status.setConnect();
1636
+ break;
1637
+ case TqlWsService.ENUM_ACTIONS.DISCONNECT:
1638
+ status.setDisconnect();
1639
+ break;
1640
+ case TqlWsService.ENUM_ACTIONS.END:
1641
+ status.setEnd();
1642
+ break;
1643
+ }
1644
+ status.setReconnectCount(this.options.max_reconnect_count);
1645
+ this.status$.next(status);
1646
+ }
1647
+ static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.17", ngImport: i0, type: TqlWsService, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
1648
+ static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "19.2.17", ngImport: i0, type: TqlWsService }); }
1649
+ }
1650
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.17", ngImport: i0, type: TqlWsService, decorators: [{
1651
+ type: Injectable
1652
+ }], ctorParameters: () => [] });
1653
+ (function (TqlWsService) {
1654
+ let ENUM_TYPES;
1655
+ (function (ENUM_TYPES) {
1656
+ ENUM_TYPES[ENUM_TYPES["EMPTY"] = 0] = "EMPTY";
1657
+ })(ENUM_TYPES = TqlWsService.ENUM_TYPES || (TqlWsService.ENUM_TYPES = {}));
1658
+ let ENUM_CODES;
1659
+ (function (ENUM_CODES) {
1660
+ ENUM_CODES[ENUM_CODES["START"] = 0] = "START";
1661
+ ENUM_CODES[ENUM_CODES["END"] = 1] = "END";
1662
+ ENUM_CODES[ENUM_CODES["RESTART"] = 2] = "RESTART";
1663
+ })(ENUM_CODES = TqlWsService.ENUM_CODES || (TqlWsService.ENUM_CODES = {}));
1664
+ let ENUM_ACTIONS;
1665
+ (function (ENUM_ACTIONS) {
1666
+ ENUM_ACTIONS[ENUM_ACTIONS["CONNECT"] = 0] = "CONNECT";
1667
+ ENUM_ACTIONS[ENUM_ACTIONS["DISCONNECT"] = 1] = "DISCONNECT";
1668
+ ENUM_ACTIONS[ENUM_ACTIONS["END"] = 2] = "END";
1669
+ })(ENUM_ACTIONS = TqlWsService.ENUM_ACTIONS || (TqlWsService.ENUM_ACTIONS = {}));
1670
+ /*The value must be an integer: either 1000, or else a custom code of your choosing in the range 3000-4999.
1671
+ If you specify a code value, you should also specify a reason value.*/
1672
+ TqlWsService.CODES = {
1673
+ [ENUM_CODES.START]: { code: 300, message: 'Socket started first time' },
1674
+ [ENUM_CODES.END]: { code: 3001, message: 'Socket is ended' },
1675
+ [ENUM_CODES.RESTART]: { code: 3002, message: 'Socket is restart' },
1676
+ };
1677
+ class Status {
1678
+ get connected() {
1679
+ return this._connected;
1680
+ }
1681
+ get reconnectCount() {
1682
+ return this._reconnectCount;
1683
+ }
1684
+ get end() {
1685
+ return this._end;
1686
+ }
1687
+ constructor() {
1688
+ this.connectStartTime = 0;
1689
+ this.connectEndTime = 0;
1690
+ this._connected = false;
1691
+ this._end = false;
1692
+ }
1693
+ setDisconnect() {
1694
+ this._connected = false;
1695
+ this.connectEndTime = new Date().getTime();
1696
+ }
1697
+ setConnect() {
1698
+ this._connected = true;
1699
+ this.connectStartTime = new Date().getTime();
1700
+ this.connectEndTime = 0;
1701
+ }
1702
+ setEnd() {
1703
+ this._connected = false;
1704
+ this._end = true;
1705
+ this.connectEndTime = new Date().getTime();
1706
+ }
1707
+ setReconnectCount(count) {
1708
+ this._reconnectCount = count;
1709
+ }
1710
+ }
1711
+ TqlWsService.Status = Status;
1712
+ })(TqlWsService || (TqlWsService = {}));
1713
+
1714
+ class TqlTranslateService {
1715
+ constructor(http, injector) {
1716
+ this.http = http;
1717
+ this.injector = injector;
1718
+ this.translationDataLoaded$ = new BehaviorSubject(null);
1719
+ this.translationData = [];
1720
+ }
1721
+ loaded$() {
1722
+ this.translationData.push(this.translationDataLoaded$.value);
1723
+ return this.translationDataLoaded$;
1724
+ }
1725
+ getDataTranslate(keyLang) {
1726
+ const itemFind = this.translationData.find((x) => x.key === keyLang);
1727
+ if (itemFind) {
1728
+ return new Observable((x) => {
1729
+ x.next(itemFind.data);
1730
+ x.complete();
1731
+ });
1732
+ }
1733
+ return new Observable((x) => {
1734
+ const path = `config/language/${keyLang}.json`;
1735
+ try {
1736
+ this.http
1737
+ .get(path)
1738
+ .pipe(catchError$1((res) => {
1739
+ // console.error('Something went wrong for the following translation file:', path);
1740
+ // console.error(res.message);
1741
+ return of({});
1742
+ }))
1743
+ .subscribe((rs) => {
1744
+ x.next(rs);
1745
+ x.complete();
1746
+ const data = ___default.assign({ ...TqlTranslateService.getJsonLocalStorage(keyLang) }, rs);
1747
+ this.translationDataLoaded$.next(data);
1748
+ this.translationData.push({
1749
+ key: keyLang,
1750
+ data: data,
1751
+ });
1752
+ });
1753
+ }
1754
+ catch (e) { }
1755
+ });
1756
+ }
1757
+ translateGG(text) {
1758
+ const obj = new GoogleObj(text);
1759
+ switch (this.getLanguage()) {
1760
+ case LANGUAGES.PT: {
1761
+ obj.target = 'pt';
1762
+ break;
1763
+ }
1764
+ case LANGUAGES.EN: {
1765
+ return new Observable((x) => {
1766
+ this.saveTextTranslate(text, text);
1767
+ x.next(text);
1768
+ x.complete();
1769
+ });
1770
+ }
1771
+ }
1772
+ return this.http
1773
+ .post('https://translation.googleapis.com/language/translate/v2?key=' + TRANSLATE_KEY.key, obj)
1774
+ .pipe(map((x) => {
1775
+ if (x?.['data']?.translations?.[0]?.translatedText) {
1776
+ this.saveTextTranslate(x?.['data']?.translations?.[0]?.translatedText, text);
1777
+ }
1778
+ return x?.['data']?.translations?.[0]?.translatedText ?? text;
1779
+ }));
1780
+ }
1781
+ saveTextTranslate(rs, text) {
1782
+ this.translationData[0].data;
1783
+ this.translationData[0].data[text] = rs;
1784
+ const object = {};
1785
+ object[text] = rs;
1786
+ TqlTranslateService.updateJsonDataLocalStorage(object);
1787
+ }
1788
+ static getDataLocalStorage() {
1789
+ if (typeof window === 'undefined' || !window?.localStorage?.getItem(KEY_LANGUAGES_LOCAL_STORAGE)) {
1790
+ return {};
1791
+ }
1792
+ try {
1793
+ const data = JSON.parse(window?.localStorage?.getItem(KEY_LANGUAGES_LOCAL_STORAGE) ?? '{}');
1794
+ return data ?? {};
1795
+ }
1796
+ catch (error) {
1797
+ return {};
1798
+ }
1799
+ }
1800
+ getLanguage() {
1801
+ return TqlTranslateService.getLanguage();
1802
+ }
1803
+ static getLanguage() {
1804
+ if (this.getDataLocalStorage()?.key) {
1805
+ return this.getDataLocalStorage()?.key;
1806
+ }
1807
+ TqlTranslateService.updateKeyLanguage(LANGUAGE_DEFAULT);
1808
+ return LANGUAGE_DEFAULT;
1809
+ }
1810
+ static getJsonLocalStorage(keyLang) {
1811
+ return this.getDataLocalStorage()?.[keyLang ?? this.getLanguage()] ?? {};
1812
+ }
1813
+ static updateKeyLanguage(keyLang) {
1814
+ const data = this.getDataLocalStorage();
1815
+ data['key'] = keyLang;
1816
+ if (typeof window !== 'undefined')
1817
+ window?.localStorage.setItem(KEY_LANGUAGES_LOCAL_STORAGE, JSON.stringify(data));
1818
+ }
1819
+ static updateJsonDataLocalStorage(dataTranslate) {
1820
+ const keyLang = TqlTranslateService.getLanguage();
1821
+ const data = this.getDataLocalStorage();
1822
+ data[keyLang] = ___default.assign({ ...TqlTranslateService.getJsonLocalStorage(keyLang) }, dataTranslate);
1823
+ if (typeof window !== 'undefined')
1824
+ window?.localStorage.setItem(KEY_LANGUAGES_LOCAL_STORAGE, JSON.stringify(data));
1825
+ }
1826
+ async instant(data) {
1827
+ const translate = this.injector.get(TranslateService);
1828
+ return await translate.stream(data).pipe(first()).toPromise();
1829
+ }
1830
+ static getTranslateHighCharts(type) {
1831
+ const langue = this.getLanguage();
1832
+ switch (type) {
1833
+ case TYPE_LANGUAGES_HIGH_CHART.shortMonths: {
1834
+ switch (langue) {
1835
+ case LANGUAGES.PT: {
1836
+ return [
1837
+ 'Jan',
1838
+ 'Fev',
1839
+ 'Março',
1840
+ 'Abril',
1841
+ 'Maio',
1842
+ 'Junho',
1843
+ 'Julho',
1844
+ 'Agosto',
1845
+ 'Set',
1846
+ 'Out',
1847
+ 'Nov',
1848
+ 'Dez',
1849
+ ];
1850
+ }
1851
+ default: {
1852
+ return ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
1853
+ }
1854
+ }
1855
+ }
1856
+ case TYPE_LANGUAGES_HIGH_CHART.months: {
1857
+ switch (langue) {
1858
+ case LANGUAGES.PT: {
1859
+ return [
1860
+ 'Janeiro',
1861
+ 'Fevereiro',
1862
+ 'Março',
1863
+ 'Abril',
1864
+ 'Maio',
1865
+ 'Junho',
1866
+ 'Julho',
1867
+ 'Agosto',
1868
+ 'Setembro',
1869
+ 'Outubro',
1870
+ 'Novembro',
1871
+ 'Dezembro',
1872
+ ];
1873
+ }
1874
+ default: {
1875
+ return [
1876
+ 'January',
1877
+ 'February',
1878
+ 'March',
1879
+ 'April',
1880
+ 'May',
1881
+ 'June',
1882
+ 'July',
1883
+ 'August',
1884
+ 'September',
1885
+ 'October',
1886
+ 'November',
1887
+ 'December',
1888
+ ];
1889
+ }
1890
+ }
1891
+ }
1892
+ case TYPE_LANGUAGES_HIGH_CHART.weekdays: {
1893
+ switch (langue) {
1894
+ case LANGUAGES.PT: {
1895
+ return [
1896
+ 'Domingo',
1897
+ 'Segunda-feira',
1898
+ 'Terça-feira',
1899
+ 'Quarta-feira',
1900
+ 'Quinta-feira',
1901
+ 'Sexta-feira',
1902
+ 'Sábado',
1903
+ ];
1904
+ }
1905
+ default: {
1906
+ return ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
1907
+ }
1908
+ }
1909
+ }
1910
+ }
1911
+ }
1912
+ static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.17", ngImport: i0, type: TqlTranslateService, deps: [{ token: i1$2.HttpClient }, { token: i0.Injector }], target: i0.ɵɵFactoryTarget.Injectable }); }
1913
+ static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "19.2.17", ngImport: i0, type: TqlTranslateService }); }
1914
+ }
1915
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.17", ngImport: i0, type: TqlTranslateService, decorators: [{
1916
+ type: Injectable
1917
+ }], ctorParameters: () => [{ type: i1$2.HttpClient }, { type: i0.Injector }] });
1918
+ (function (TqlTranslateService) {
1919
+ class MyMissingTranslationHandler {
1920
+ constructor(_TqlTranslateService) {
1921
+ this._TqlTranslateService = _TqlTranslateService;
1922
+ }
1923
+ handle(params) {
1924
+ const itemFind = this._TqlTranslateService.translationData[0]?.data?.[params?.key];
1925
+ if (itemFind) {
1926
+ return itemFind;
1927
+ }
1928
+ return this._TqlTranslateService.translateGG(params?.key);
1929
+ }
1930
+ }
1931
+ TqlTranslateService.MyMissingTranslationHandler = MyMissingTranslationHandler;
1932
+ function HandleMyMissing(_TqlTranslateService) {
1933
+ return new MyMissingTranslationHandler(_TqlTranslateService);
1934
+ }
1935
+ TqlTranslateService.HandleMyMissing = HandleMyMissing;
1936
+ // AoT requires an exported function for factories
1937
+ function HttpLoaderFactory(_TqlTranslateService) {
1938
+ return new MultiTranslateHttpLoader(_TqlTranslateService);
1939
+ }
1940
+ TqlTranslateService.HttpLoaderFactory = HttpLoaderFactory;
1941
+ class MultiTranslateHttpLoader {
1942
+ constructor(_TqlTranslateService) {
1943
+ this._TqlTranslateService = _TqlTranslateService;
1944
+ }
1945
+ getTranslation() {
1946
+ return new Observable((x) => {
1947
+ x.next(this._TqlTranslateService.translationData[0].data);
1948
+ x.complete();
1949
+ });
1950
+ }
1951
+ }
1952
+ TqlTranslateService.MultiTranslateHttpLoader = MultiTranslateHttpLoader;
1953
+ function initializeTranslations(_TqlTranslateService) {
1954
+ return async () => {
1955
+ return _TqlTranslateService.getDataTranslate(_TqlTranslateService.getLanguage()).toPromise();
1956
+ };
1957
+ }
1958
+ TqlTranslateService.initializeTranslations = initializeTranslations;
1959
+ TqlTranslateService.languageHighChart = {
1960
+ lang: {
1961
+ thousandsSep: ',',
1962
+ shortMonths: TqlTranslateService.getTranslateHighCharts('shortMonths'),
1963
+ months: TqlTranslateService.getTranslateHighCharts('months'),
1964
+ weekdays: TqlTranslateService.getTranslateHighCharts('weekdays'),
1965
+ },
1966
+ };
1967
+ })(TqlTranslateService || (TqlTranslateService = {}));
1968
+ class GoogleObj {
1969
+ constructor(q) {
1970
+ this.source = 'en';
1971
+ this.target = 'pt';
1972
+ this.format = 'text';
1973
+ this.q = q;
1974
+ }
1975
+ }
1976
+
1977
+ class TqlGlobalConfigService {
1978
+ constructor(externalConfig) {
1979
+ this.externalConfig = externalConfig;
1980
+ this.config = { spinTemplate: null };
1981
+ console.log(externalConfig);
1982
+ _.assign(this.config, externalConfig);
1983
+ }
1984
+ getConfig() {
1985
+ return this.config;
1986
+ }
1987
+ static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.17", ngImport: i0, type: TqlGlobalConfigService, deps: [{ token: TQL_LIBRARY_CONFIG, optional: true }], target: i0.ɵɵFactoryTarget.Injectable }); }
1988
+ static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "19.2.17", ngImport: i0, type: TqlGlobalConfigService, providedIn: 'root' }); }
1989
+ }
1990
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.17", ngImport: i0, type: TqlGlobalConfigService, decorators: [{
1991
+ type: Injectable,
1992
+ args: [{
1993
+ providedIn: 'root',
1994
+ }]
1995
+ }], ctorParameters: () => [{ type: undefined, decorators: [{
1996
+ type: Optional
1997
+ }, {
1998
+ type: Inject,
1999
+ args: [TQL_LIBRARY_CONFIG]
2000
+ }] }] });
2001
+
2002
+ class PayloadModel {
2003
+ /**
2004
+ *
2005
+ * @param query
2006
+ * @param objectName
2007
+ * @param objectClass
2008
+ * @param objectPath
2009
+ */
2010
+ constructor(query, objectName, objectPath, objectClass) {
2011
+ this.query = query;
2012
+ this.objectName = objectName;
2013
+ this.objectPath = objectPath;
2014
+ this.objectClass = objectClass;
2015
+ }
2016
+ /**
2017
+ *
2018
+ * @param params
2019
+ * @returns {string}
2020
+ */
2021
+ buildPayload(params = []) {
2022
+ let data = this.query.toString();
2023
+ if (!params || !Object.keys(params).length) {
2024
+ return data;
2025
+ }
2026
+ return _.reduce(params, (result, v, index) => TqlUtilsService.replaceAll(result.toString(), `{${index}}`, v), data);
2027
+ }
2028
+ /**
2029
+ *
2030
+ * @param dataObject
2031
+ * @returns {string}
2032
+ */
2033
+ buildPayloadWithObject(dataObject) {
2034
+ if (!Object.keys(dataObject).length) {
2035
+ return this.query;
2036
+ }
2037
+ return _.reduce(Object.keys(dataObject), (result, v, k) => TqlUtilsService.replaceAll(result.toString(), `{${k}}`, dataObject[k]), this.query);
2038
+ }
2039
+ /**
2040
+ *
2041
+ * @param array
2042
+ * @returns {any[]}
2043
+ */
2044
+ parse(array = []) {
2045
+ if (_.isUndefined(this.objectClass) || _.isUndefined(this.objectName)) {
2046
+ return array;
2047
+ }
2048
+ const data = [];
2049
+ try {
2050
+ for (let i = 0; i < array.length; i++) {
2051
+ if (_.get(array, this.objectName ? [i, this.objectName] : [i])) {
2052
+ data.push(new this.objectClass(_.get(array, this.objectName ? [i, this.objectName] : [i])));
2053
+ }
2054
+ }
2055
+ }
2056
+ catch (e) {
2057
+ console.error(e);
2058
+ }
2059
+ return data;
2060
+ }
2061
+ }
2062
+
2063
+ class WSPayloadModel {
2064
+ constructor(query, params = [], id) {
2065
+ this.id = id || v4();
2066
+ this.query = TqlUtilsService.replaceAll(query, '{mid}', this.id);
2067
+ ___default.map(params, (x, k) => {
2068
+ this.query = TqlUtilsService.replaceAll(this.query, `{${k}}`, x);
2069
+ });
2070
+ this.$promise = new Promise((resolve) => {
2071
+ this.promiseResolve = resolve;
2072
+ });
2073
+ }
2074
+ /**
2075
+ *
2076
+ * @param data
2077
+ * @returns {boolean}
2078
+ */
2079
+ resolve(data) {
2080
+ if (data.includes(this.id)) {
2081
+ data = TqlUtilsService.replaceAll(data, '---Self---', `""`);
2082
+ let json = data;
2083
+ try {
2084
+ json = JSON.parse(data);
2085
+ }
2086
+ catch (e) { }
2087
+ this.promiseResolve(json);
2088
+ return true;
2089
+ }
2090
+ return false;
2091
+ }
2092
+ }
2093
+
2094
+ /* default */
2095
+
2096
+ class TqlApiInterceptor {
2097
+ constructor() {
2098
+ }
2099
+ intercept(request, next) {
2100
+ // timeout
2101
+ let $timeout = 300000;
2102
+ if (request.headers.has(TqlApiInterceptor.HEADER_KEYS.TIMEOUT)) {
2103
+ $timeout = parseInt(request.headers.get(TqlApiInterceptor.HEADER_KEYS.TIMEOUT));
2104
+ request = request.clone({
2105
+ headers: request.headers.delete(TqlApiInterceptor.HEADER_KEYS.TIMEOUT)
2106
+ });
2107
+ }
2108
+ // check token
2109
+ if (request.headers.has(TqlApiInterceptor.HEADER_KEYS.NO_TOKEN) || request.headers.has(TqlApiInterceptor.HEADER_KEYS.REQUIRE_TOKEN)) {
2110
+ request = request.clone({
2111
+ headers: request.headers.delete(TqlApiInterceptor.HEADER_KEYS.NO_TOKEN).delete(TqlApiInterceptor.HEADER_KEYS.REQUIRE_TOKEN)
2112
+ });
2113
+ // check token
2114
+ }
2115
+ // console.log(request);
2116
+ return next.handle(request)
2117
+ .pipe(timeout($timeout));
2118
+ }
2119
+ static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.17", ngImport: i0, type: TqlApiInterceptor, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
2120
+ static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "19.2.17", ngImport: i0, type: TqlApiInterceptor }); }
2121
+ }
2122
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.17", ngImport: i0, type: TqlApiInterceptor, decorators: [{
2123
+ type: Injectable
2124
+ }], ctorParameters: () => [] });
2125
+ (function (TqlApiInterceptor) {
2126
+ let HEADER_KEYS;
2127
+ (function (HEADER_KEYS) {
2128
+ HEADER_KEYS["TIMEOUT"] = "timeout";
2129
+ HEADER_KEYS["NO_TOKEN"] = "noToken";
2130
+ HEADER_KEYS["REQUIRE_TOKEN"] = "requiteToken";
2131
+ HEADER_KEYS["REQUIRE_USER_TOKEN"] = "requiteUserToken";
2132
+ })(HEADER_KEYS = TqlApiInterceptor.HEADER_KEYS || (TqlApiInterceptor.HEADER_KEYS = {}));
2133
+ })(TqlApiInterceptor || (TqlApiInterceptor = {}));
2134
+
2135
+ // export * from './api/tql-api-lib.service';
2136
+
2137
+ class TqlServiceModule {
2138
+ static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.17", ngImport: i0, type: TqlServiceModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule }); }
2139
+ static { this.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "19.2.17", ngImport: i0, type: TqlServiceModule, imports: [CommonModule, i1$3.TranslateModule], exports: [TranslateModule] }); }
2140
+ static { this.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "19.2.17", ngImport: i0, type: TqlServiceModule, providers: [
2141
+ TqlSiteMapControllerService,
2142
+ TqlToastControllerService,
2143
+ TqlDialogControllerService,
2144
+ TqlRouteControllerService,
2145
+ TqlApiLibService,
2146
+ TqlErrorHandlerService,
2147
+ TqlLoggerService,
2148
+ TqlUtilsService,
2149
+ TqlWsService,
2150
+ TqlTranslateService,
2151
+ provideAppInitializer(() => {
2152
+ const translateService = inject(TqlTranslateService);
2153
+ return TqlTranslateService.initializeTranslations(translateService)();
2154
+ }),
2155
+ {
2156
+ provide: LOCALE_ID,
2157
+ deps: [TqlTranslateService],
2158
+ useFactory: (_TqlTranslateService) => _TqlTranslateService.getLanguage(),
2159
+ },
2160
+ { provide: TQL_LIBRARY_CONFIG, useValue: {} },
2161
+ ], imports: [CommonModule,
2162
+ TranslateModule.forRoot({
2163
+ loader: {
2164
+ provide: TranslateLoader,
2165
+ useFactory: TqlTranslateService.HttpLoaderFactory,
2166
+ deps: [TqlTranslateService],
2167
+ },
2168
+ missingTranslationHandler: {
2169
+ provide: MissingTranslationHandler,
2170
+ useFactory: TqlTranslateService.HandleMyMissing,
2171
+ deps: [TqlTranslateService],
2172
+ },
2173
+ useDefaultLang: false,
2174
+ }), TranslateModule] }); }
2175
+ }
2176
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.17", ngImport: i0, type: TqlServiceModule, decorators: [{
2177
+ type: NgModule,
2178
+ args: [{
2179
+ declarations: [],
2180
+ imports: [
2181
+ CommonModule,
2182
+ TranslateModule.forRoot({
2183
+ loader: {
2184
+ provide: TranslateLoader,
2185
+ useFactory: TqlTranslateService.HttpLoaderFactory,
2186
+ deps: [TqlTranslateService],
2187
+ },
2188
+ missingTranslationHandler: {
2189
+ provide: MissingTranslationHandler,
2190
+ useFactory: TqlTranslateService.HandleMyMissing,
2191
+ deps: [TqlTranslateService],
2192
+ },
2193
+ useDefaultLang: false,
2194
+ }),
2195
+ ],
2196
+ providers: [
2197
+ TqlSiteMapControllerService,
2198
+ TqlToastControllerService,
2199
+ TqlDialogControllerService,
2200
+ TqlRouteControllerService,
2201
+ TqlApiLibService,
2202
+ TqlErrorHandlerService,
2203
+ TqlLoggerService,
2204
+ TqlUtilsService,
2205
+ TqlWsService,
2206
+ TqlTranslateService,
2207
+ provideAppInitializer(() => {
2208
+ const translateService = inject(TqlTranslateService);
2209
+ return TqlTranslateService.initializeTranslations(translateService)();
2210
+ }),
2211
+ {
2212
+ provide: LOCALE_ID,
2213
+ deps: [TqlTranslateService],
2214
+ useFactory: (_TqlTranslateService) => _TqlTranslateService.getLanguage(),
2215
+ },
2216
+ { provide: TQL_LIBRARY_CONFIG, useValue: {} },
2217
+ ],
2218
+ exports: [TranslateModule],
2219
+ }]
2220
+ }] });
2221
+
2222
+ /*
2223
+ * Public API Surface of tql-service
2224
+ */
2225
+ // controllers
2226
+
2227
+ /**
2228
+ * Generated bundle index. Do not edit.
2229
+ */
2230
+
2231
+ export { DATA_TYPE, DefaultComponent, DefaultDialogComponent, DefaultDirective, DefaultMapComponent, DefaultModel, DynamicDataModel, ErrorStatusEnum, GoogleObj, KEY_CONSTANT, KEY_LANGUAGES_LOCAL_STORAGE, LANGUAGES, LANGUAGE_DEFAULT, MAP_STYLES, PayloadModel, TQL_LIBRARY_CONFIG, TRANSLATE_KEY, TYPE_LANGUAGES_HIGH_CHART, TqlApiInterceptor, TqlApiLibService, TqlDialogControllerService, TqlErrorHandlerService, TqlGlobalConfigService, TqlLoggerService, TqlRouteControllerService, TqlServiceModule, TqlSiteMapControllerService, TqlTableControllerService, TqlToastControllerService, TqlTranslateService, TqlUtilsService, TqlWsService, WSPayloadModel };
2232
+ //# sourceMappingURL=x-tql-service.mjs.map