@esfaenza/extensions 15.2.45 → 16.2.0

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 (65) hide show
  1. package/{esm2020 → esm2022}/esfaenza-extensions.mjs +4 -4
  2. package/esm2022/lib/models/CallResult.mjs +24 -0
  3. package/esm2022/lib/models/CsvHeaders.mjs +26 -0
  4. package/{esm2020 → esm2022}/lib/models/ExportConsts.mjs +31 -31
  5. package/esm2022/lib/models/ExtensionsModuleConfig.mjs +10 -0
  6. package/esm2022/lib/models/GenericItem.mjs +10 -0
  7. package/{esm2020 → esm2022}/lib/models/InboundMessageTypes.mjs +6 -6
  8. package/esm2022/lib/models/InterComMessage.mjs +16 -0
  9. package/{esm2020 → esm2022}/lib/models/TypeCode.mjs +24 -24
  10. package/{esm2020 → esm2022}/lib/modules/extensions.module.mjs +32 -32
  11. package/esm2022/lib/pipes/loc_date.pipe.mjs +38 -0
  12. package/esm2022/lib/services/extensions.base.mjs +30 -0
  13. package/esm2022/lib/services/extensions.clipboard.service.mjs +221 -0
  14. package/esm2022/lib/services/extensions.dates.service.mjs +244 -0
  15. package/esm2022/lib/services/extensions.embedding.service.mjs +213 -0
  16. package/esm2022/lib/services/extensions.exports.service.mjs +617 -0
  17. package/esm2022/lib/services/extensions.hashing.service.mjs +308 -0
  18. package/esm2022/lib/services/extensions.intercom.service.mjs +52 -0
  19. package/esm2022/lib/services/extensions.messages.service.mjs +450 -0
  20. package/esm2022/lib/services/extensions.utilities.service.mjs +250 -0
  21. package/{esm2020 → esm2022}/lib/tokens.mjs +11 -11
  22. package/{esm2020 → esm2022}/public-api.mjs +21 -21
  23. package/{fesm2020 → fesm2022}/esfaenza-extensions.mjs +2509 -2441
  24. package/fesm2022/esfaenza-extensions.mjs.map +1 -0
  25. package/index.d.ts +5 -5
  26. package/lib/models/CallResult.d.ts +23 -23
  27. package/lib/models/CsvHeaders.d.ts +25 -25
  28. package/lib/models/ExportConsts.d.ts +31 -31
  29. package/lib/models/ExtensionsModuleConfig.d.ts +9 -9
  30. package/lib/models/GenericItem.d.ts +9 -9
  31. package/lib/models/InboundMessageTypes.d.ts +5 -5
  32. package/lib/models/InterComMessage.d.ts +12 -12
  33. package/lib/models/TypeCode.d.ts +23 -23
  34. package/lib/modules/extensions.module.d.ts +11 -11
  35. package/lib/pipes/loc_date.pipe.d.ts +24 -24
  36. package/lib/services/extensions.base.d.ts +22 -22
  37. package/lib/services/extensions.clipboard.service.d.ts +54 -54
  38. package/lib/services/extensions.dates.service.d.ts +99 -99
  39. package/lib/services/extensions.embedding.service.d.ts +28 -28
  40. package/lib/services/extensions.exports.service.d.ts +234 -234
  41. package/lib/services/extensions.hashing.service.d.ts +121 -121
  42. package/lib/services/extensions.intercom.service.d.ts +28 -28
  43. package/lib/services/extensions.messages.service.d.ts +195 -195
  44. package/lib/services/extensions.utilities.service.d.ts +107 -107
  45. package/lib/tokens.d.ts +11 -11
  46. package/package.json +13 -19
  47. package/public-api.d.ts +18 -18
  48. package/esm2020/lib/models/CallResult.mjs +0 -6
  49. package/esm2020/lib/models/CsvHeaders.mjs +0 -6
  50. package/esm2020/lib/models/ExtensionsModuleConfig.mjs +0 -4
  51. package/esm2020/lib/models/GenericItem.mjs +0 -6
  52. package/esm2020/lib/models/InterComMessage.mjs +0 -14
  53. package/esm2020/lib/pipes/loc_date.pipe.mjs +0 -37
  54. package/esm2020/lib/services/extensions.base.mjs +0 -29
  55. package/esm2020/lib/services/extensions.clipboard.service.mjs +0 -219
  56. package/esm2020/lib/services/extensions.dates.service.mjs +0 -242
  57. package/esm2020/lib/services/extensions.embedding.service.mjs +0 -208
  58. package/esm2020/lib/services/extensions.exports.service.mjs +0 -615
  59. package/esm2020/lib/services/extensions.hashing.service.mjs +0 -310
  60. package/esm2020/lib/services/extensions.intercom.service.mjs +0 -54
  61. package/esm2020/lib/services/extensions.messages.service.mjs +0 -433
  62. package/esm2020/lib/services/extensions.utilities.service.mjs +0 -252
  63. package/fesm2015/esfaenza-extensions.mjs +0 -2513
  64. package/fesm2015/esfaenza-extensions.mjs.map +0 -1
  65. package/fesm2020/esfaenza-extensions.mjs.map +0 -1
@@ -1,2513 +0,0 @@
1
- import * as i0 from '@angular/core';
2
- import { InjectionToken, Injectable, Optional, Inject, Pipe, NgModule, Injector } from '@angular/core';
3
- import * as i1 from '@esfaenza/localizations';
4
- import { LocalizationModule } from '@esfaenza/localizations';
5
- import { __awaiter } from 'tslib';
6
- import { first, filter, take, map } from 'rxjs/operators';
7
- import { of, Subject } from 'rxjs';
8
- import { ToastrService } from 'ngx-toastr';
9
- import swal from 'sweetalert2';
10
- import * as i2 from '@angular/router';
11
- import * as i3 from '@angular/common';
12
-
13
- /**
14
- * Token che indica il prefisso delle searchView che serve per storicizzarle evitando di tirarsi in memoria anche tutti gli oggetti. Se vuoto viene supposto 'Hot'
15
- */
16
- const APPSEARCH_PREFIX = new InjectionToken('APPSEARCH_PREFIX');
17
- /**
18
- * Token che indica se i metodi di estensione che utilizzano le date permettono l'uso di date in utc
19
- */
20
- const EXT_ALLOW_UTC = new InjectionToken('EXT_ALLOW_UTC');
21
- /** Modalità di Debug */
22
- const EXT_DEBUG_MODE = new InjectionToken('EXT_DEBUG_MODE');
23
-
24
- /**
25
- * Service che fornisce dei metodi di estensione per la gestione/manipolazione delle date
26
- */
27
- class DateService {
28
- /**
29
- * Costruttore
30
- *
31
- * @ignore
32
- */
33
- constructor(locProvider, allowUtc) {
34
- this.locProvider = locProvider;
35
- this.allowUtc = allowUtc;
36
- /**
37
- * Oggetto statico di localizzazione per i messaggi di questa Service
38
- */
39
- this.loc = {
40
- "SMALL_DATE_FORMAT": { 'en-US': "MM/DD/YYYY", 'it-IT': "DD/MM/YYYY" },
41
- "FULL_DATE_FORMAT": { 'en-US': "MM/DD/YYYY HH:mm:ss", 'it-IT': "DD/MM/YYYY HH:mm:ss" },
42
- "FULL_DATE_FORMAT_NO_SS": { 'en-US': "MM/DD/YYYY HH:mm", 'it-IT': "DD/MM/YYYY HH:mm" },
43
- "SMALL_DATE_DISPLAY_FORMAT": { 'en-US': "DD/MM/YYYY", 'it-IT': "DD/MM/YYYY" },
44
- "SMALL_DATE_DISPLAY_FORMAT_WITH_HOUR": { 'en-US': "DD/MM/YYYY HH", 'it-IT': "DD/MM/YYYY HH" },
45
- "SMALL_DATE_DISPLAY_FORMAT_WITH_MINUTE": { 'en-US': "DD/MM/YYYY HH:mm", 'it-IT': "DD/MM/YYYY HH:mm" },
46
- "FULL_DATE_DISPLAY_FORMAT": { 'en-US': "DD/MM/YYYY HH:mm:ss", 'it-IT': "DD/MM/YYYY HH:mm:ss" },
47
- "FULL_DATE_DISPLAY_FORMAT_NO_SS": { 'en-US': "DD/MM/YYYY HH:mm", 'it-IT': "DD/MM/YYYY HH:mm" }
48
- };
49
- /**
50
- * Oggetto di configurazione per tenere da conto le informazioni sui formati
51
- */
52
- this.cfg = {
53
- fulldate: "",
54
- fulldateDisplay: "",
55
- smallDate: "",
56
- fulldateNoSS: "",
57
- smallDateWithH: "",
58
- smallDateWithM: "",
59
- fulldateDisplayNoSS: ""
60
- };
61
- this.init();
62
- }
63
- init() {
64
- return __awaiter(this, void 0, void 0, function* () {
65
- let LOCALE = this.locProvider ? yield this.locProvider.Locale.pipe(first()).toPromise() : 'it-IT';
66
- this.cfg.smallDate = this.loc["SMALL_DATE_FORMAT"][LOCALE];
67
- this.cfg.fulldate = this.loc["FULL_DATE_FORMAT"][LOCALE];
68
- this.cfg.fulldateNoSS = this.loc["FULL_DATE_FORMAT_NO_SS"][LOCALE];
69
- this.cfg.fulldateDisplay = this.loc["FULL_DATE_DISPLAY_FORMAT"][LOCALE];
70
- this.cfg.fulldateDisplayNoSS = this.loc["FULL_DATE_DISPLAY_FORMAT_NO_SS"][LOCALE];
71
- this.cfg.smallDate = this.loc["SMALL_DATE_DISPLAY_FORMAT"][LOCALE];
72
- this.cfg.smallDateWithH = this.loc["SMALL_DATE_DISPLAY_FORMAT_WITH_HOUR"][LOCALE];
73
- this.cfg.smallDateWithM = this.loc["SMALL_DATE_DISPLAY_FORMAT_WITH_MINUTE"][LOCALE];
74
- });
75
- }
76
- /**
77
- * Aggiusta una data in "istante finale" in base a qual è la parte di data significativa.
78
- *
79
- * Es. Istante finale delle ore: 05/10/1992 --> 04/10/1992 24:00(:00)
80
- *
81
- * @param {any} date Data qualsiasi (Date, stringa, dayjs...), verrà ricondotta ad un oggetto dayJs
82
- * @param {'day' | 'hour' | 'minute'} timepart Parte significativa della data
83
- * @param {boolean} printSeconds Indica se effettuare la stampa dei secondi o no
84
- */
85
- adjustDateToFinalInstant(date, timepart, printSeconds = true) {
86
- let mydt = this.getDateConvertion(date);
87
- if (mydt == null)
88
- return "FE: Not a Date";
89
- let isZeroTime = mydt.startOf(timepart).valueOf() === mydt.valueOf();
90
- if (!isZeroTime) {
91
- if (timepart == "day" && mydt.subtract(1, "hour").hour() == mydt.hour()) {
92
- // Se l'ora precedente è lo stesso orario dell'ora attuale l'istante finale dev'essere mandato avanti di 1
93
- mydt = mydt.add(1, "hour");
94
- }
95
- return printSeconds ? mydt.format(this.cfg.fulldateDisplay) : mydt.format(this.cfg.fulldateDisplayNoSS);
96
- }
97
- let tmpValue = mydt.subtract(1, timepart);
98
- let value = "";
99
- // Istante finale delle ore: 05/10/1992 --> 04/10/1992 24:00(:00)
100
- if (timepart == 'day')
101
- value = tmpValue.format(this.cfg.smallDate) + " 24:00" + (printSeconds ? ':00' : '');
102
- // Istante finale dei minuti: giorno 05/10/1992 04:00:00 --> 05/10/1992 03:60(:00)
103
- else if (timepart == 'hour')
104
- value = tmpValue.format(this.cfg.smallDateWithH) + ":60" + (printSeconds ? ':00' : '');
105
- // Istante finale dei secondi: giorno 05/10/1992 04:10:00 --> 05/10/1992 04:09:60
106
- else if (timepart == 'minute')
107
- value = tmpValue.format(this.cfg.smallDateWithM) + ":60";
108
- return value;
109
- }
110
- /**
111
- * Funzione che effettua l'ordinamento fra 2 date in base alla direzione specificata
112
- *
113
- * @param {any} a Prima data per il confronto
114
- * @param {any} b Seconda data per il confronto
115
- * @param {'asc' | 'desc'} direction Direzione rispetto a cui ordinare le due date
116
- *
117
- * @returns {number} 0 se le date sono uguali, 1 se la data A deve venire logicamente prima della data B, -1 altrimenti
118
- */
119
- dateSort(a, b, direction) {
120
- if (a < b)
121
- return direction == 'asc' ? 1 : -1;
122
- else if (a > b)
123
- return direction == 'asc' ? -1 : 1;
124
- // con a uguale a b
125
- return 0;
126
- }
127
- /**
128
- * Effettua il trim dei secondi da una data espressa come stringa
129
- *
130
- * @param {string} value Data espressa come stringa
131
- *
132
- * @returns {string} Data senza i secondi
133
- */
134
- trimSeconds(value) {
135
- //I numeri mangiati da dayjs spesso vengono ricondotti a date vere. Mi assicuro che se ci sono solo numeri proseguo
136
- if (!isNaN(value))
137
- return value;
138
- //Se non ho qualcosa del tipo XX/YY/ZZZZ aa:bb:cc di sicuro non è una data che mi interessa
139
- if (!/^\d\d\/\d\d\/\d\d\d\d \d\d:\d\d:\d\d$/g.test(value))
140
- return value;
141
- //In questo caso mi arrivano valori che devono essere stampati as-is, solo tagliando i secondi
142
- return "'" + value.substr(0, value.length - 3);
143
- }
144
- /**
145
- * Data una lista di date Da e una lista di date A restituisce un oggetto rappresentante il range che include tutte le date passate
146
- *
147
- * @param {any[]} fromDates Lista dei Da
148
- * @param {any[]} toDates Lista dei A
149
- *
150
- * @returns {{ from: any, to: any }} Range di date Da - A che include tutti i valori di **fromDates** e **toDates**
151
- */
152
- getMinMaxDatesRange(fromDates, toDates) {
153
- let datesFroms = [];
154
- let datesTo = [];
155
- for (let i = 0; i < fromDates.length; i++) {
156
- let d = fromDates[i];
157
- var convertion = this.getDateConvertion(d);
158
- if (convertion)
159
- datesFroms.push(convertion);
160
- }
161
- for (let i = 0; i < toDates.length; i++) {
162
- let d = toDates[i];
163
- var convertion = this.getDateConvertion(d);
164
- if (convertion)
165
- datesTo.push(convertion);
166
- }
167
- return { from: dayjs.min(datesFroms), to: dayjs.max(datesTo) };
168
- }
169
- /**
170
- * Ottiene la conversione di una data in qualsiasi formato al formato standard DayJs
171
- *
172
- * @param {any} date Oggetto rappresentante una data. Potrebbe essere una stringa, un Date o già un DayJs
173
- * @param {boolean} useUtc Indica se usare l'estensione utc di Dayjs per parsare la data o no
174
- *
175
- * @returns {any} Data in modalità DayJs
176
- */
177
- getDateConvertion(date, useUtc = false) {
178
- if (!date)
179
- return null;
180
- if (this.isDayJs(date))
181
- return date;
182
- if (this.isJsDate(date))
183
- return useUtc ? dayjs.utc(date) : dayjs(date);
184
- // Se non c'è la proprietà length vuol dire che non è una stringa e a questo punto non ho idea di che minchia sia
185
- let length = date.length;
186
- if (!length)
187
- return null;
188
- if (useUtc && !this.allowUtc)
189
- throw "@esfaenza/extensions: Richiesta data UTC ma da configurazione la libreria non lo supporta";
190
- // Per risparmiare chiamate a tentoni, in base alla lunghezza della stringa chiamo direttamente il metodo giusto,
191
- // controllando poi che mi generi una data come me la aspetto io
192
- let tryThis = null;
193
- let toCall = useUtc ? dayjs.utc : dayjs;
194
- // Se la data contiene la lettera "T" vuol dire che è una data del tipo 2020-10-15T00:00:00, direttamente parsabile dal dayjs col locale corretto.
195
- // Per il resto mi baso sulla lunghezza della stringa
196
- if (date.includes("T"))
197
- tryThis = toCall(date);
198
- else if (length == this.cfg.fulldate.length)
199
- tryThis = toCall(date, this.cfg.fulldate);
200
- else if (length == this.cfg.smallDate.length)
201
- tryThis = toCall(date, this.cfg.smallDate);
202
- else if (length == this.cfg.fulldateNoSS.length)
203
- tryThis = toCall(date, this.cfg.fulldateNoSS);
204
- if (tryThis && tryThis.isValid && tryThis.isValid())
205
- return tryThis;
206
- // Se niente funziona, null.
207
- // Ricondurre l'Input ad una data non è possibile.
208
- return null;
209
- }
210
- /**
211
- * Helper che restituisce **true** qualora l'oggetto passato fosse una data vera e propria, **false** altrimenti
212
- *
213
- * @param {any} check Oggetto da controllare
214
- *
215
- * @returns {boolean} Indicazione se l'oggetto è un vero Date di Javascript o no
216
- */
217
- isJsDate(check) {
218
- return check && Object.prototype.toString.call(check) === "[object Date]" && !isNaN(check);
219
- }
220
- /**
221
- * Helper che restituisce **true** qualora l'oggetto passato fosse un DayJs vero e proprio, **false** altrimenti
222
- *
223
- * @param {any} check Oggetto da controllare
224
- * @returns {boolean} Indicazione se l'oggetto è un vero DayJs o no
225
- */
226
- isDayJs(check) {
227
- // Non uso instanceof perché sarebbe estremamente più lento
228
- // Non uso nemmeno isDayjs() della libreria Dayjs dato che ha lo stesso problema: https://github.com/iamkun/dayjs/blob/06f88f425828b1ce96b737332d25145a95a4ee9d/src/index.js#L9
229
- return check.$D !== undefined && check.$M !== undefined && check.$y !== undefined;
230
- }
231
- /**
232
- * Ottiene la formattazione di una data in base alla versione richiesta "small" o "long" e a se stampare o meno i secondi
233
- *
234
- * @param {any} date Oggetto rappresentante una data. Potrebbe essere una stringa, un Date o già un DayJs
235
- * @param {boolean} small Indica se formattarla con un formato breve (se **true**) o un formato più lungo (se **false**)
236
- *
237
- * @returns {string} Data formattata nel formato richiesto
238
- */
239
- getFormatted(date, small, seconds) {
240
- var date = this.getDateConvertion(date);
241
- if (!date)
242
- return null;
243
- return date.format(small ? this.cfg.smallDate : seconds ? this.cfg.fulldateDisplay : this.cfg.fulldateDisplayNoSS);
244
- }
245
- }
246
- DateService.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.2.9", ngImport: i0, type: DateService, deps: [{ token: i1.BaseLocalization, optional: true }, { token: EXT_ALLOW_UTC, optional: true }], target: i0.ɵɵFactoryTarget.Injectable });
247
- DateService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.2.9", ngImport: i0, type: DateService, providedIn: "root" });
248
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.2.9", ngImport: i0, type: DateService, decorators: [{
249
- type: Injectable,
250
- args: [{ providedIn: "root" }]
251
- }], ctorParameters: function () {
252
- return [{ type: i1.BaseLocalization, decorators: [{
253
- type: Optional
254
- }] }, { type: undefined, decorators: [{
255
- type: Optional
256
- }, {
257
- type: Inject,
258
- args: [EXT_ALLOW_UTC]
259
- }] }];
260
- } });
261
-
262
- // Angular
263
- /**
264
- * Pipe che permette di formattare una data in base al formato specificato. Utilizza il **DateService** di **@esfaenza/extensions** per ricondurre l'input a una data valida
265
- */
266
- class LocDatePipe {
267
- /**
268
- * @ignore
269
- */
270
- constructor(dts) {
271
- this.dts = dts;
272
- }
273
- /**
274
- * Trasformazione della data in input in base al formato richiesto
275
- *
276
- * @param {any} value Valore da ricondurre ad una data e formattare
277
- * @param {string} format Formato in output della data da visualizzare
278
- *
279
- * @returns {string} Data formattata in base al formato
280
- */
281
- transform(value, format = "DD/MM/YYYY") {
282
- if (value == null || value === "")
283
- return null;
284
- var detatchedValue = JSON.parse(JSON.stringify(value));
285
- var dt = this.dts.getDateConvertion(detatchedValue);
286
- return dt.format(format);
287
- }
288
- }
289
- LocDatePipe.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.2.9", ngImport: i0, type: LocDatePipe, deps: [{ token: DateService }], target: i0.ɵɵFactoryTarget.Pipe });
290
- LocDatePipe.ɵpipe = i0.ɵɵngDeclarePipe({ minVersion: "14.0.0", version: "15.2.9", ngImport: i0, type: LocDatePipe, name: "loc_date" });
291
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.2.9", ngImport: i0, type: LocDatePipe, decorators: [{
292
- type: Pipe,
293
- args: [{ name: "loc_date", pure: true }]
294
- }], ctorParameters: function () { return [{ type: DateService }]; } });
295
-
296
- // Angular
297
- class ExtensionsModule {
298
- static forRoot(config) {
299
- return {
300
- ngModule: ExtensionsModule,
301
- providers: [
302
- { provide: APPSEARCH_PREFIX, useValue: (config === null || config === void 0 ? void 0 : config.appsearch_prefix) || 'Hot' },
303
- { provide: EXT_ALLOW_UTC, useValue: (config === null || config === void 0 ? void 0 : config.allow_utc) == null ? false : config === null || config === void 0 ? void 0 : config.allow_utc },
304
- { provide: EXT_DEBUG_MODE, useValue: (config === null || config === void 0 ? void 0 : config.debugMode) || false },
305
- ]
306
- };
307
- }
308
- }
309
- ExtensionsModule.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.2.9", ngImport: i0, type: ExtensionsModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule });
310
- ExtensionsModule.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "15.2.9", ngImport: i0, type: ExtensionsModule, declarations: [LocDatePipe], imports: [LocalizationModule], exports: [LocDatePipe] });
311
- ExtensionsModule.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "15.2.9", ngImport: i0, type: ExtensionsModule, imports: [LocalizationModule] });
312
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.2.9", ngImport: i0, type: ExtensionsModule, decorators: [{
313
- type: NgModule,
314
- args: [{
315
- imports: [LocalizationModule],
316
- declarations: [LocDatePipe],
317
- exports: [LocDatePipe]
318
- }]
319
- }] });
320
-
321
- // Angular
322
- /**
323
- * Service che fornisce alcuni semplici funzioni di Hashing / GUID / ecc...
324
- */
325
- class HashingService {
326
- constructor() {
327
- /**
328
- * Blacklist dei tipi da ignorare quando si effettua l'hashing degli oggetti
329
- */
330
- this.objBlacklist = {
331
- "NgForm": true, "ElementRef": true, "ExtensionsService": true, "ToastrService": true, "LocaleService": true, "AppState": true, "Router": true,
332
- "ActivatedRoute": true, "HTTPService": true, "Location": true, "CanvasComponent": true, "ModalDirective": true, "ChangeDetectorRef": true,
333
- "DateService": true, "EventEmitter": true, "ViewRef_": true, "Subscriber": true, "ItemLocalization": true
334
- };
335
- /**
336
- * Array dei possibili valori di un simbolo esadecimale
337
- */
338
- this.hex_chr = '0123456789abcdef'.split('');
339
- }
340
- /**
341
- * Generazione di un GUID pseudo-univoco
342
- *
343
- * @returns {string} il GUID generato
344
- */
345
- getGUID() {
346
- return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, c => {
347
- var r = Math.random() * 16 | 0, v = c == "x" ? r : (r & 0x3 | 0x8);
348
- return v.toString(16);
349
- });
350
- }
351
- /**
352
- * Calcolo dell'hash su un oggetto
353
- *
354
- * @param {any} o Oggetto di cui calcolare l'hash
355
- * @param {number} level Livello di ricorsione nel caso venga effettuato l'hash di un oggetto che contiene altri oggetti
356
- * @param {boolean} navigateFullDepth Indica se navigare l'oggetto per l'intera lunghezza. In caso contrario si ferma al secondo livello
357
- *
358
- * @returns {string} Hash generato per l'oggetto in questione
359
- */
360
- hashObject(o, level = 0, navigateFullDepth = false, precise = false) {
361
- var strDef = this.stringify(o, level, navigateFullDepth);
362
- var hash = precise ? this.md5(strDef) : this.simpleHash(strDef);
363
- return hash;
364
- }
365
- /**
366
- * Hash più semplice e più veloce dell'md5, ma meno sicuro
367
- *
368
- * Vedi https://stackoverflow.com/questions/7616461/generate-a-hash-from-string-in-javascript
369
- *
370
- * @param {string} str Stringa di cui calcolare l'hash
371
- */
372
- simpleHash(str, seed = 0) {
373
- let h1 = 0xdeadbeef ^ seed, h2 = 0x41c6ce57 ^ seed;
374
- for (let i = 0, ch; i < str.length; i++) {
375
- ch = str.charCodeAt(i);
376
- h1 = Math.imul(h1 ^ ch, 2654435761);
377
- h2 = Math.imul(h2 ^ ch, 1597334677);
378
- }
379
- h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507) ^ Math.imul(h2 ^ (h2 >>> 13), 3266489909);
380
- h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507) ^ Math.imul(h1 ^ (h1 >>> 13), 3266489909);
381
- return (4294967296 * (2097151 & h2) + (h1 >>> 0)).toString();
382
- }
383
- /**
384
- * Genera una stringa che identifica univocamente l'oggetto in questione
385
- *
386
- * @param {any} o Oggetto di cui calcolare la stringa univoca
387
- * @param {number} level Livello di ricorsione nel caso venga effettuato l'hash di un oggetto che contiene altri oggetti
388
- * @param {boolean} navigateFullDepth Indica se navigare l'oggetto per l'intera lunghezza. In caso contrario si ferma al secondo livello
389
- */
390
- stringify(o, level, navigateFullDepth) {
391
- var i, r;
392
- if (o === null)
393
- return "n";
394
- if (o === true)
395
- return "t";
396
- if (o === false)
397
- return "f";
398
- if (o instanceof Date)
399
- return 'd:' + o.valueOf().toString();
400
- i = typeof o;
401
- if (i === "string")
402
- return "s:" + o;
403
- if (i === "number")
404
- return "n:" + o;
405
- if (o instanceof Function)
406
- return "m:" + o.toString();
407
- if (o instanceof Array) {
408
- r = [];
409
- for (i = 0; i < o.length; i++) {
410
- let res = this.stringify(o[i], level, navigateFullDepth);
411
- if (res)
412
- r.push(res);
413
- }
414
- return r.length > 0 ? "a:" + r.join(";") : "";
415
- }
416
- r = [];
417
- //Se è oggetto, escludo tutti quelli di sistema/inutili
418
- if (o) {
419
- var name = o.__proto__.constructor.name;
420
- if (!this.objBlacklist[name]) {
421
- for (i in o) {
422
- if (o.hasOwnProperty(i) && (level <= 2 || navigateFullDepth)) {
423
- let res = this.stringify(o[i], level + 1, navigateFullDepth);
424
- if (res)
425
- r.push(i + ":" + res);
426
- }
427
- }
428
- }
429
- }
430
- return r.length > 0 ? "o:" + r.join(";") : "";
431
- }
432
- /**
433
- * Data una stringa restituisce l'md5
434
- *
435
- * @param {string} s Stringa di cui calcolare l'md5
436
- * @returns {string} md5 della stringa **s**
437
- */
438
- md5(s) {
439
- return this.hex(this.md51(s));
440
- }
441
- /**
442
- * @ignore
443
- *
444
- * Metodo di utilità per il calcolo dell'md5
445
- */
446
- md5cycle(x, k) {
447
- var a = x[0], b = x[1], c = x[2], d = x[3];
448
- a = this.ff(a, b, c, d, k[0], 7, -680876936);
449
- d = this.ff(d, a, b, c, k[1], 12, -389564586);
450
- c = this.ff(c, d, a, b, k[2], 17, 606105819);
451
- b = this.ff(b, c, d, a, k[3], 22, -1044525330);
452
- a = this.ff(a, b, c, d, k[4], 7, -176418897);
453
- d = this.ff(d, a, b, c, k[5], 12, 1200080426);
454
- c = this.ff(c, d, a, b, k[6], 17, -1473231341);
455
- b = this.ff(b, c, d, a, k[7], 22, -45705983);
456
- a = this.ff(a, b, c, d, k[8], 7, 1770035416);
457
- d = this.ff(d, a, b, c, k[9], 12, -1958414417);
458
- c = this.ff(c, d, a, b, k[10], 17, -42063);
459
- b = this.ff(b, c, d, a, k[11], 22, -1990404162);
460
- a = this.ff(a, b, c, d, k[12], 7, 1804603682);
461
- d = this.ff(d, a, b, c, k[13], 12, -40341101);
462
- c = this.ff(c, d, a, b, k[14], 17, -1502002290);
463
- b = this.ff(b, c, d, a, k[15], 22, 1236535329);
464
- a = this.gg(a, b, c, d, k[1], 5, -165796510);
465
- d = this.gg(d, a, b, c, k[6], 9, -1069501632);
466
- c = this.gg(c, d, a, b, k[11], 14, 643717713);
467
- b = this.gg(b, c, d, a, k[0], 20, -373897302);
468
- a = this.gg(a, b, c, d, k[5], 5, -701558691);
469
- d = this.gg(d, a, b, c, k[10], 9, 38016083);
470
- c = this.gg(c, d, a, b, k[15], 14, -660478335);
471
- b = this.gg(b, c, d, a, k[4], 20, -405537848);
472
- a = this.gg(a, b, c, d, k[9], 5, 568446438);
473
- d = this.gg(d, a, b, c, k[14], 9, -1019803690);
474
- c = this.gg(c, d, a, b, k[3], 14, -187363961);
475
- b = this.gg(b, c, d, a, k[8], 20, 1163531501);
476
- a = this.gg(a, b, c, d, k[13], 5, -1444681467);
477
- d = this.gg(d, a, b, c, k[2], 9, -51403784);
478
- c = this.gg(c, d, a, b, k[7], 14, 1735328473);
479
- b = this.gg(b, c, d, a, k[12], 20, -1926607734);
480
- a = this.hh(a, b, c, d, k[5], 4, -378558);
481
- d = this.hh(d, a, b, c, k[8], 11, -2022574463);
482
- c = this.hh(c, d, a, b, k[11], 16, 1839030562);
483
- b = this.hh(b, c, d, a, k[14], 23, -35309556);
484
- a = this.hh(a, b, c, d, k[1], 4, -1530992060);
485
- d = this.hh(d, a, b, c, k[4], 11, 1272893353);
486
- c = this.hh(c, d, a, b, k[7], 16, -155497632);
487
- b = this.hh(b, c, d, a, k[10], 23, -1094730640);
488
- a = this.hh(a, b, c, d, k[13], 4, 681279174);
489
- d = this.hh(d, a, b, c, k[0], 11, -358537222);
490
- c = this.hh(c, d, a, b, k[3], 16, -722521979);
491
- b = this.hh(b, c, d, a, k[6], 23, 76029189);
492
- a = this.hh(a, b, c, d, k[9], 4, -640364487);
493
- d = this.hh(d, a, b, c, k[12], 11, -421815835);
494
- c = this.hh(c, d, a, b, k[15], 16, 530742520);
495
- b = this.hh(b, c, d, a, k[2], 23, -995338651);
496
- a = this.ii(a, b, c, d, k[0], 6, -198630844);
497
- d = this.ii(d, a, b, c, k[7], 10, 1126891415);
498
- c = this.ii(c, d, a, b, k[14], 15, -1416354905);
499
- b = this.ii(b, c, d, a, k[5], 21, -57434055);
500
- a = this.ii(a, b, c, d, k[12], 6, 1700485571);
501
- d = this.ii(d, a, b, c, k[3], 10, -1894986606);
502
- c = this.ii(c, d, a, b, k[10], 15, -1051523);
503
- b = this.ii(b, c, d, a, k[1], 21, -2054922799);
504
- a = this.ii(a, b, c, d, k[8], 6, 1873313359);
505
- d = this.ii(d, a, b, c, k[15], 10, -30611744);
506
- c = this.ii(c, d, a, b, k[6], 15, -1560198380);
507
- b = this.ii(b, c, d, a, k[13], 21, 1309151649);
508
- a = this.ii(a, b, c, d, k[4], 6, -145523070);
509
- d = this.ii(d, a, b, c, k[11], 10, -1120210379);
510
- c = this.ii(c, d, a, b, k[2], 15, 718787259);
511
- b = this.ii(b, c, d, a, k[9], 21, -343485551);
512
- x[0] = this.add32(a, x[0]);
513
- x[1] = this.add32(b, x[1]);
514
- x[2] = this.add32(c, x[2]);
515
- x[3] = this.add32(d, x[3]);
516
- }
517
- /**
518
- * @ignore
519
- *
520
- * Metodo di utilità per il calcolo dell'md5
521
- */
522
- cmn(q, a, b, x, s, t) {
523
- a = this.add32(this.add32(a, q), this.add32(x, t));
524
- return this.add32((a << s) | (a >>> (32 - s)), b);
525
- }
526
- /**
527
- * @ignore
528
- *
529
- * Metodo di utilità per il calcolo dell'md5
530
- */
531
- ff(a, b, c, d, x, s, t) {
532
- return this.cmn((b & c) | ((~b) & d), a, b, x, s, t);
533
- }
534
- /**
535
- * @ignore
536
- *
537
- * Metodo di utilità per il calcolo dell'md5
538
- */
539
- gg(a, b, c, d, x, s, t) {
540
- return this.cmn((b & d) | (c & (~d)), a, b, x, s, t);
541
- }
542
- /**
543
- * @ignore
544
- *
545
- * Metodo di utilità per il calcolo dell'md5
546
- */
547
- hh(a, b, c, d, x, s, t) {
548
- return this.cmn(b ^ c ^ d, a, b, x, s, t);
549
- }
550
- /**
551
- * @ignore
552
- *
553
- * Metodo di utilità per il calcolo dell'md5
554
- */
555
- ii(a, b, c, d, x, s, t) {
556
- return this.cmn(c ^ (b | (~d)), a, b, x, s, t);
557
- }
558
- /**
559
- * @ignore
560
- *
561
- * Metodo di utilità per il calcolo dell'md5
562
- */
563
- md51(s) {
564
- var n = s.length, state = [1732584193, -271733879, -1732584194, 271733878], i;
565
- for (i = 64; i <= s.length; i += 64)
566
- this.md5cycle(state, this.md5blk(s.substring(i - 64, i)));
567
- s = s.substring(i - 64);
568
- var tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
569
- for (i = 0; i < s.length; i++)
570
- tail[i >> 2] |= s.charCodeAt(i) << ((i % 4) << 3);
571
- tail[i >> 2] |= 0x80 << ((i % 4) << 3);
572
- if (i > 55) {
573
- this.md5cycle(state, tail);
574
- for (i = 0; i < 16; i++)
575
- tail[i] = 0;
576
- }
577
- tail[14] = n * 8;
578
- this.md5cycle(state, tail);
579
- return state;
580
- }
581
- /**
582
- * @ignore
583
- *
584
- * Metodo di utilità per il calcolo dell'md5
585
- */
586
- md5blk(s) {
587
- var md5blks = [], i;
588
- for (i = 0; i < 64; i += 4)
589
- md5blks[i >> 2] = s.charCodeAt(i) + (s.charCodeAt(i + 1) << 8) + (s.charCodeAt(i + 2) << 16) + (s.charCodeAt(i + 3) << 24);
590
- return md5blks;
591
- }
592
- /**
593
- * @ignore
594
- *
595
- * Metodo di utilità per il calcolo dell'md5
596
- */
597
- rhex(n) {
598
- var s = '', j = 0;
599
- for (; j < 4; j++)
600
- s += this.hex_chr[(n >> (j * 8 + 4)) & 0x0F] + this.hex_chr[(n >> (j * 8)) & 0x0F];
601
- return s;
602
- }
603
- /**
604
- * @ignore
605
- *
606
- * Metodo di utilità per il calcolo dell'md5
607
- */
608
- hex(x) {
609
- for (var i = 0; i < x.length; i++)
610
- x[i] = this.rhex(x[i]);
611
- return x.join('');
612
- }
613
- /**
614
- * @ignore
615
- *
616
- * Metodo di utilità per il calcolo dell'md5
617
- */
618
- add32(a, b) {
619
- return (a + b) & 0xFFFFFFFF;
620
- }
621
- }
622
- HashingService.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.2.9", ngImport: i0, type: HashingService, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
623
- HashingService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.2.9", ngImport: i0, type: HashingService, providedIn: "root" });
624
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.2.9", ngImport: i0, type: HashingService, decorators: [{
625
- type: Injectable,
626
- args: [{ providedIn: "root" }]
627
- }] });
628
-
629
- /**
630
- * Service che fornisce funzionalità di alert nei tipi fondamentali: success, info, warning e danger
631
- */
632
- class MessageService {
633
- /** Costruttore @ignore */
634
- constructor(injector, locProvider, hash) {
635
- this.injector = injector;
636
- this.locProvider = locProvider;
637
- this.hash = hash;
638
- /** Oggetto statico in supporto alla localizzazione */
639
- this.loc = {
640
- 'Confirm': { 'en-US': "Confirm", 'it-IT': "Conferma", },
641
- 'Cancel': { 'en-US': "Cancel", 'it-IT': "Annulla", },
642
- 'Close': { 'en-US': "Close", 'it-IT': "Chiudi", },
643
- 'Error': { 'en-US': "Error", 'it-IT': "Errore", },
644
- 'Info': { 'en-US': "Info", 'it-IT': "Informazione", },
645
- 'Success': { 'en-US': "Success", 'it-IT': "Successo", },
646
- 'Warning': { 'en-US': "Warning", 'it-IT': "Attenzione", }
647
- };
648
- /** Supporto all'Embedding */
649
- this.Embedded = false;
650
- this.MainWindow = null;
651
- this.MessageObserver = null;
652
- this.GuidRepsonseFunctionsMap = {};
653
- this.init();
654
- }
655
- /** Getter per il servizio dei toast. ngx-toastr è fatta talmente male che la service dev'essere recuperata in questo modo */
656
- get toastr() {
657
- return this.injector.get(ToastrService);
658
- }
659
- configureEmbeddability(mainWindow, messageObserver) {
660
- this.Embedded = true;
661
- this.MainWindow = mainWindow;
662
- this.MessageObserver = messageObserver;
663
- }
664
- init() {
665
- return __awaiter(this, void 0, void 0, function* () {
666
- let LOCALE = this.locProvider ? yield this.locProvider.Locale.pipe(first()).toPromise() : 'it-IT';
667
- this.expiredSessionSwal = swal.mixin({
668
- showCancelButton: false,
669
- confirmButtonText: 'Login',
670
- customClass: {
671
- confirmButton: "btn btn-primary",
672
- container: "app-wrap",
673
- },
674
- buttonsStyling: false,
675
- reverseButtons: false,
676
- allowOutsideClick: false,
677
- icon: "warning"
678
- });
679
- this.successSwalWithCancel = swal.mixin({
680
- title: this.loc["Success"][LOCALE],
681
- customClass: {
682
- confirmButton: "btn btn-primary",
683
- cancelButton: "btn btn-secondary app-margin-right-10",
684
- container: "app-wrap",
685
- },
686
- buttonsStyling: false,
687
- reverseButtons: true,
688
- showCancelButton: true,
689
- confirmButtonText: this.loc["Confirm"][LOCALE],
690
- cancelButtonText: this.loc["Cancel"][LOCALE],
691
- icon: "success"
692
- });
693
- this.warningSwalWithCancel = swal.mixin({
694
- title: this.loc["Warning"][LOCALE],
695
- customClass: {
696
- confirmButton: "btn btn-primary",
697
- cancelButton: "btn btn-secondary app-margin-right-10",
698
- container: "app-wrap",
699
- },
700
- buttonsStyling: false,
701
- reverseButtons: true,
702
- showCancelButton: true,
703
- confirmButtonText: this.loc["Confirm"][LOCALE],
704
- cancelButtonText: this.loc["Cancel"][LOCALE],
705
- icon: "warning"
706
- });
707
- this.warningSwal = swal.mixin({
708
- title: this.loc["Warning"][LOCALE],
709
- customClass: {
710
- confirmButton: "btn btn-primary",
711
- container: "app-wrap",
712
- },
713
- buttonsStyling: false,
714
- reverseButtons: true,
715
- showCancelButton: false,
716
- confirmButtonText: this.loc["Close"][LOCALE],
717
- icon: "warning"
718
- });
719
- this.successSwal = swal.mixin({
720
- title: this.loc["Success"][LOCALE],
721
- customClass: {
722
- confirmButton: "btn btn-primary",
723
- container: "app-wrap",
724
- },
725
- buttonsStyling: false,
726
- reverseButtons: true,
727
- showCancelButton: false,
728
- confirmButtonText: this.loc["Close"][LOCALE],
729
- icon: "success"
730
- });
731
- this.errorSwal = swal.mixin({
732
- title: this.loc["Error"][LOCALE],
733
- customClass: {
734
- confirmButton: "btn btn-primary",
735
- container: "app-wrap",
736
- },
737
- buttonsStyling: false,
738
- reverseButtons: true,
739
- showCancelButton: false,
740
- confirmButtonText: this.loc["Close"][LOCALE],
741
- icon: "error"
742
- });
743
- this.infoSwal = swal.mixin({
744
- title: this.loc["Info"][LOCALE],
745
- customClass: {
746
- confirmButton: "btn btn-primary",
747
- container: "app-wrap",
748
- },
749
- buttonsStyling: false,
750
- reverseButtons: true,
751
- showCancelButton: false,
752
- confirmButtonText: this.loc["Close"][LOCALE],
753
- icon: "info"
754
- });
755
- });
756
- }
757
- /**
758
- * Presentazione di un semplice messaggio di successo
759
- *
760
- * Se viene chiamato con le impostazioni di default e toastr è abilitato, viene mostrato al centro
761
- * Se viene chiamato con override su toastr vuol dire che è una notifica secondaria e appare in alto a destra
762
- *
763
- * @param {string} text Testo da mostrare
764
- * @param {"toastr" | "swal" | null} secondaryNotificationType Qualora sia una notifica secondaria, ne indica il tipo
765
- */
766
- simpleSuccess(text, secondaryNotificationType = null, secondaryNotificationTimeout = null) {
767
- if (this.Embedded) {
768
- this.MainWindow.postMessage({ type: "alert", level: 'success', msg: text }, "*");
769
- return;
770
- }
771
- let tos = this.toastrOrSwal(secondaryNotificationType);
772
- if (tos == "swal")
773
- this.successSwal.fire("", text);
774
- else
775
- this.toastr.success(text, null, { positionClass: tos == "toastr" ? "toast-top-right" : "toast-top-center", timeOut: secondaryNotificationTimeout || (tos == "toastr" ? 0 : 5000), extendedTimeOut: tos == "toastr" ? 0 : 1000 });
776
- }
777
- /**
778
- * Presentazione di un semplice messaggio di informazione
779
- *
780
- * Se viene chiamato con le impostazioni di default e toastr è abilitato, viene mostrato al centro
781
- * Se viene chiamato con override su toastr vuol dire che è una notifica secondaria e appare in alto a destra
782
- *
783
- * @param {string} text Testo da mostrare
784
- * @param {"toastr" | "swal" | null} secondaryNotificationType Qualora sia una notifica secondaria, ne indica il tipo
785
- */
786
- simpleInfo(text, secondaryNotificationType = null, secondaryNotificationTimeout = null) {
787
- if (this.Embedded) {
788
- this.MainWindow.postMessage({ type: "alert", level: 'info', msg: text }, "*");
789
- return;
790
- }
791
- let tos = this.toastrOrSwal(secondaryNotificationType);
792
- if (tos == "swal")
793
- this.infoSwal.fire("", text);
794
- else
795
- this.toastr.info(text, null, { positionClass: tos == "toastr" ? "toast-top-right" : "toast-top-center", timeOut: secondaryNotificationTimeout || (tos == "toastr" ? 0 : 5000), extendedTimeOut: tos == "toastr" ? 0 : 1000 });
796
- }
797
- /**
798
- * Presentazione di un semplice messaggio di errore
799
- *
800
- * Se viene chiamato con le impostazioni di default e toastr è abilitato, viene mostrato al centro
801
- * Se viene chiamato con override su toastr vuol dire che è una notifica secondaria e appare in alto a destra
802
- *
803
- * @param {string} text Testo da mostrare
804
- * @param {"toastr" | "swal" | null} secondaryNotificationType Qualora sia una notifica secondaria, ne indica il tipo
805
- */
806
- simpleError(text, secondaryNotificationType = null, secondaryNotificationTimeout = null) {
807
- if (this.Embedded) {
808
- this.MainWindow.postMessage({ type: "alert", level: 'error', msg: text }, "*");
809
- return;
810
- }
811
- let tos = this.toastrOrSwal(secondaryNotificationType);
812
- if (tos == "swal")
813
- this.errorSwal.fire("", text);
814
- else
815
- this.toastr.error(text, null, { positionClass: tos == "toastr" ? "toast-top-right" : "toast-top-center", timeOut: secondaryNotificationTimeout || (tos == "toastr" ? 0 : 5000), extendedTimeOut: tos == "toastr" ? 0 : 1000 });
816
- }
817
- /**
818
- * Presentazione di un semplice messaggio di avviso
819
- *
820
- * Se viene chiamato con le impostazioni di default e toastr è abilitato, viene mostrato al centro
821
- * Se viene chiamato con override su toastr vuol dire che è una notifica secondaria e appare in alto a destra
822
- *
823
- * @param {string} text Testo da mostrare
824
- * @param {"toastr" | "swal" | null} secondaryNotificationType Qualora sia una notifica secondaria, ne indica il tipo
825
- */
826
- simpleWarning(text, secondaryNotificationType = null, secondaryNotificationTimeout = null) {
827
- if (this.Embedded) {
828
- this.MainWindow.postMessage({ type: "alert", level: 'warning', msg: text }, "*");
829
- return;
830
- }
831
- let tos = this.toastrOrSwal(secondaryNotificationType);
832
- if (tos == "swal")
833
- this.warningSwal.fire("", text);
834
- else
835
- this.toastr.warning(text, null, { positionClass: tos == "toastr" ? "toast-top-right" : "toast-top-center", timeOut: secondaryNotificationTimeout || (tos == "toastr" ? 0 : 5000), extendedTimeOut: tos == "toastr" ? 0 : 1000 });
836
- }
837
- /**
838
- * Ripulisce tutti i messaggi presenti in un dato momento sullo schermo
839
- */
840
- clearMessages() {
841
- this.toastr.clear();
842
- swal.close();
843
- }
844
- /**
845
- * Mostra un messaggio di avviso con richiesta di conferma
846
- *
847
- * @param {string} title Titolo del messaggio
848
- * @param {string} text Contenuto del messaggio
849
- *
850
- * @returns {Promise} Restituisce una Promise col risultato scelto dall'utente (conferma o no)
851
- */
852
- promiseWarningWithChoice(title, text) {
853
- return this.warningSwalWithCancel.fire(title, text);
854
- }
855
- /**
856
- * In base alla configurazione attuale e all'eventuale override per la chiamata del caso indica se bisogna utilizzare toastr o sweetalert
857
- *
858
- * @param {"toastr" | "swal" | null} providerOverride Override alla modalità configurata
859
- *
860
- * @returns {"toastr" | "swal"} Indicazione su che provider di messaggi di avviso debba essere utilizzato
861
- */
862
- toastrOrSwal(providerOverride) {
863
- if (providerOverride != null)
864
- return providerOverride;
865
- return "swal";
866
- }
867
- simpleWarningWithChoice(title, text, onsuccess, onerror, confirmtext = "", aborttext = '') {
868
- this.withChoiceBase("warning", title, text, onsuccess, onerror, confirmtext, aborttext);
869
- }
870
- simpleSuccessWithChoice(title, text, onsuccess, onerror, confirmtext = "", aborttext = '') {
871
- this.withChoiceBase("success", title, text, onsuccess, onerror, confirmtext, aborttext);
872
- }
873
- withChoiceBase(level, title, text, onsuccess, onerror, confirmtext = "", aborttext = '') {
874
- if (this.Embedded) {
875
- let guid = this.hash.getGUID();
876
- this.GuidRepsonseFunctionsMap[guid] = { onsuccess, onerror };
877
- this.MainWindow.postMessage({ type: "confirm", level, title, text, guid }, "*");
878
- // Observe sulla risposta
879
- console.log("Inviata confirm request alla pagina principale, in attesa di risposta...");
880
- this.MessageObserver.pipe(filter(event => { var _a, _b; return ((_a = event === null || event === void 0 ? void 0 : event.data) === null || _a === void 0 ? void 0 : _a.type) == "confirm-response" && ((_b = event === null || event === void 0 ? void 0 : event.data) === null || _b === void 0 ? void 0 : _b.guid) == guid; }), take(1)).subscribe(event => {
881
- var _a, _b;
882
- console.log("Event listener su window-message. Risposta pergiunta");
883
- if (((_a = event === null || event === void 0 ? void 0 : event.data) === null || _a === void 0 ? void 0 : _a.result) === true)
884
- this.GuidRepsonseFunctionsMap[guid].onsuccess();
885
- else if (((_b = event === null || event === void 0 ? void 0 : event.data) === null || _b === void 0 ? void 0 : _b.result) === true)
886
- this.GuidRepsonseFunctionsMap[guid].onerror();
887
- });
888
- }
889
- else
890
- (level == "warning" ? this._simpleWarningWithChoice.bind(this) : this._simpleSuccessWithChoice.bind(this))(title, text, onsuccess, onerror, confirmtext, aborttext);
891
- }
892
- /**
893
- * Mostra un messaggio di avviso con richiesta di conferma e gestisce il risultato chiamato i callback **onsuccess** o **onerror**
894
- *
895
- * @param {string} title Titolo del messaggio
896
- * @param {string} text Contenuto del messaggio
897
- * @param {Function} onsuccess Callback da chimare su conferma
898
- * @param {Function} onerror Callback da chimare su errori
899
- */
900
- _simpleWarningWithChoice(title, text, onconfirm = null, onabort = null, confirmtext = "", aborttext = '') {
901
- this._simpleWithChoice(this.warningSwalWithCancel, title, text, onconfirm, onabort, confirmtext, aborttext);
902
- }
903
- /**
904
- * Mostra un messaggio di success con richiesta di conferma e gestisce il risultato chiamato i callback **onconfirm** o **onabort**
905
- *
906
- * @param {string} title Titolo del messaggio
907
- * @param {string} text Contenuto del messaggio
908
- * @param {Function} onconfirm Callback da chimare su conferma
909
- * @param {Function} onabort Callback da chimare su annullamento
910
- * @param {string} confirmtext Testo del pulsante di azione
911
- * @param {string} aborttext Testo del pulsante di annullamento
912
- */
913
- _simpleSuccessWithChoice(title, text, onconfirm = null, onabort = null, confirmtext = "", aborttext = '') {
914
- this._simpleWithChoice(this.successSwalWithCancel, title, text, onconfirm, onabort, confirmtext, aborttext);
915
- }
916
- /**
917
- * Metodo base per richiedere una scelta all'utente
918
- *
919
- * @param {any} swal Swal mixin da utilizzare per visualizzare il messaggio di choice
920
- * @param {string} title Titolo del messaggio
921
- * @param {string} text Contenuto del messaggio
922
- * @param {Function} onconfirm Callback da chimare su conferma
923
- * @param {Function} onabort Callback da chimare su annullamento
924
- * @param {string} confirmtext Testo del pulsante di azione
925
- * @param {string} aborttext Testo del pulsante di annullamento
926
- */
927
- _simpleWithChoice(swal, title, text, onconfirm = null, onabort = null, confirmtext = "", aborttext = '') {
928
- var configuration = {
929
- title: title,
930
- html: text
931
- };
932
- if (confirmtext)
933
- configuration["confirmButtonText"] = confirmtext;
934
- if (aborttext)
935
- configuration["cancelButtonText"] = aborttext;
936
- swal.fire(configuration).then((result) => {
937
- if (result.value && onconfirm)
938
- onconfirm();
939
- else if (onabort)
940
- onabort();
941
- });
942
- }
943
- /**
944
- * Mostra un messaggio di avviso con richiesta di conferma e gestisce il risultato chiamato i callback **onsuccess** o **onerror**
945
- *
946
- * @param {string} title Titolo del messaggio
947
- * @param {string} text Contenuto del messaggio
948
- */
949
- observableSimpleWarningWithChoice(title, text) {
950
- return of(this.warningSwalWithCancel.fire(title, text)).pipe(map(t => !!t.value));
951
- }
952
- /**
953
- * Mostra un messaggio di avviso che la sessione corrente è scaduta e propone all'utente di navigare al login. Qualora l'utente decidesse di farlo
954
- * verrà chiamata la funzione di callback **onnavigate
955
- *
956
- * @param {string} title Titolo del messaggio
957
- * @param {string} text Contenuto del messaggio
958
- * @param {Function} onnavigate Callback da chimare su navigazione in corso
959
- */
960
- expiredSessionMessage(title, text, onnavigate = null) {
961
- this.expiredSessionSwal.fire(title, text).then((result) => {
962
- if (result.value && onnavigate)
963
- onnavigate();
964
- });
965
- }
966
- /**
967
- * Metodo helper per gestire in maniera standardizzata una risposta di tipo **CallResult**
968
- *
969
- * @param {CallResult} response Risposta ricevuta dal server
970
- * @param {string} successMsg Messaggio da visualizzare in caso di successo
971
- * @param {string} errorMsg Messaggio da visualizzare in caso di fallimento
972
- * @param {Function} postSuccess Callback da chimare in caso di successo
973
- * @param {Function} postFailure Callback da chimare in caso di fallimento
974
- */
975
- manageCallResultResponse(response, successMsg, errorMsg, postSuccess = null, postFailure = null) {
976
- let anyReponse = response;
977
- if (response.success || anyReponse.Success) {
978
- if (response.haswarning || anyReponse.HasWarning)
979
- this.simpleWarning(response.warning || anyReponse.Warning);
980
- else if (successMsg)
981
- this.simpleSuccess(successMsg);
982
- if (postSuccess)
983
- postSuccess();
984
- }
985
- else {
986
- this.simpleError((errorMsg ? errorMsg + ": " : "") + ((response.haserror || anyReponse.HasError) ? (response.error || anyReponse.Error) : '[NO ERR.]'));
987
- if (postFailure)
988
- postFailure();
989
- }
990
- }
991
- /**
992
- * Metodo helper per gestire in maniera standardizzata una risposta di tipo **string**, considerando che:
993
- *
994
- * Stringa vuota --> Tutto bene
995
- *
996
- * Stringa piena --> Questo è il messaggio d'errore per cui la chiamata è fallita
997
- *
998
- * @param {string} response Risposta ricevuta dal server
999
- * @param {string} successMsg Messaggio da visualizzare in caso di successo
1000
- * @param {string} errorMsg Messaggio da visualizzare in caso di fallimento
1001
- * @param {Function} postSuccess Callback da chimare in caso di successo
1002
- * @param {Function} postFailure Callback da chimare in caso di fallimento
1003
- */
1004
- manageStringResponse(response, successMsg, errorMsg, postSuccess = null, postFailure = null) {
1005
- if (!response) {
1006
- if (successMsg)
1007
- this.simpleSuccess(successMsg);
1008
- if (postSuccess)
1009
- postSuccess();
1010
- }
1011
- else {
1012
- if (errorMsg)
1013
- this.simpleError(errorMsg + ": " + response);
1014
- if (postFailure)
1015
- postFailure();
1016
- }
1017
- }
1018
- /**
1019
- * Metodo helper per gestire in maniera standardizzata una risposta di tipo **boolean**
1020
- *
1021
- * @param {string} response Risposta ricevuta dal server
1022
- * @param {string} successMsg Messaggio da visualizzare in caso di successo
1023
- * @param {string} errorMsg Messaggio da visualizzare in caso di fallimento
1024
- * @param {Function} postSuccess Callback da chimare in caso di successo
1025
- * @param {Function} postFailure Callback da chimare in caso di fallimento
1026
- */
1027
- manageStringResponseBool(response, successMsg, errorMsg, postSuccess = null, postFailure = null) {
1028
- if (response) {
1029
- if (successMsg)
1030
- this.simpleSuccess(successMsg);
1031
- if (postSuccess)
1032
- postSuccess();
1033
- }
1034
- else {
1035
- if (errorMsg)
1036
- this.simpleError(errorMsg);
1037
- if (postFailure)
1038
- postFailure();
1039
- }
1040
- }
1041
- }
1042
- MessageService.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.2.9", ngImport: i0, type: MessageService, deps: [{ token: Injector }, { token: i1.BaseLocalization, optional: true }, { token: HashingService }], target: i0.ɵɵFactoryTarget.Injectable });
1043
- MessageService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.2.9", ngImport: i0, type: MessageService, providedIn: "root" });
1044
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.2.9", ngImport: i0, type: MessageService, decorators: [{
1045
- type: Injectable,
1046
- args: [{ providedIn: "root" }]
1047
- }], ctorParameters: function () {
1048
- return [{ type: i0.Injector, decorators: [{
1049
- type: Inject,
1050
- args: [Injector]
1051
- }] }, { type: i1.BaseLocalization, decorators: [{
1052
- type: Optional
1053
- }] }, { type: HashingService }];
1054
- } });
1055
-
1056
- // Angular
1057
- /* Classe che contiene tutte le informazioni sull'embedding in un unico contenitore per semplicità */
1058
- class AppEmbeddingExtensions {
1059
- constructor(msgService, router, location) {
1060
- var _a;
1061
- this.msgService = msgService;
1062
- this.router = router;
1063
- this.location = location;
1064
- this.sidebarWidth = 230;
1065
- this.Embedded = false;
1066
- this.EmbeddingLevel = 0;
1067
- this.MessageObserver = new Subject();
1068
- this._reloadAllowed = true;
1069
- this.MainWindow = window;
1070
- while (this.MainWindow.parent != this.MainWindow) {
1071
- this.MainWindow = this.MainWindow.parent;
1072
- this.EmbeddingLevel++;
1073
- this.Embedded = true;
1074
- // Fallback per farlo funzionare forzatamente mentre lo testo
1075
- this.EmbeddedModule = (_a = this.location.path().match(/module=([a-zA-Z_]+)/)) === null || _a === void 0 ? void 0 : _a[1];
1076
- if (!this.EmbeddedModule)
1077
- this.waitForMyConfigAndForceEmbeddedModule();
1078
- }
1079
- this.configureEmbeddability();
1080
- if (this.Embedded)
1081
- this.msgService.configureEmbeddability(this.MainWindow, this.MessageObserver);
1082
- }
1083
- waitForMyConfigAndForceEmbeddedModule() {
1084
- // Aspetto di ricevere il myconfig e setto con lui l'embeddedmodule. Questo viene eseguito solo se this.location.path() per qualche motivo non contiene il module
1085
- let interval = setInterval(() => {
1086
- var _a;
1087
- if ((_a = myconfig === null || myconfig === void 0 ? void 0 : myconfig.AppData) === null || _a === void 0 ? void 0 : _a.ModuleId) {
1088
- this.EmbeddedModule = myconfig.AppData.ModuleId;
1089
- clearInterval(interval);
1090
- }
1091
- }, 250);
1092
- }
1093
- IsReloadAllowed() {
1094
- let ret = this._reloadAllowed;
1095
- this._reloadAllowed = true;
1096
- return ret;
1097
- }
1098
- configureEmbeddability() {
1099
- window.onmessage = (event) => {
1100
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14;
1101
- // Ignoro i miei messaggi dato che mi interessano solo quelli degli altri iframe
1102
- if (event.source == window && ((_a = event === null || event === void 0 ? void 0 : event.data) === null || _a === void 0 ? void 0 : _a.type) != "modal-open")
1103
- return;
1104
- this.MessageObserver.next({ event: "window-message", data: event === null || event === void 0 ? void 0 : event.data });
1105
- if (((_b = event === null || event === void 0 ? void 0 : event.data) === null || _b === void 0 ? void 0 : _b.type) == "alert") {
1106
- console.log(`Window message - alert -> Level: ${(_c = event === null || event === void 0 ? void 0 : event.data) === null || _c === void 0 ? void 0 : _c.level}, Message: ${(_d = event === null || event === void 0 ? void 0 : event.data) === null || _d === void 0 ? void 0 : _d.msg}`);
1107
- switch ((_e = event === null || event === void 0 ? void 0 : event.data) === null || _e === void 0 ? void 0 : _e.level) {
1108
- case "success":
1109
- this.msgService.simpleSuccess((_f = event === null || event === void 0 ? void 0 : event.data) === null || _f === void 0 ? void 0 : _f.msg);
1110
- break;
1111
- case "warning":
1112
- this.msgService.simpleWarning((_g = event === null || event === void 0 ? void 0 : event.data) === null || _g === void 0 ? void 0 : _g.msg);
1113
- break;
1114
- case "error":
1115
- this.msgService.simpleError((_h = event === null || event === void 0 ? void 0 : event.data) === null || _h === void 0 ? void 0 : _h.msg);
1116
- break;
1117
- case "info":
1118
- this.msgService.simpleInfo((_j = event === null || event === void 0 ? void 0 : event.data) === null || _j === void 0 ? void 0 : _j.msg);
1119
- break;
1120
- }
1121
- }
1122
- else if (((_k = event === null || event === void 0 ? void 0 : event.data) === null || _k === void 0 ? void 0 : _k.type) == "replace-state") {
1123
- console.log(`Window message - replace-state -> Url: ${(_l = event === null || event === void 0 ? void 0 : event.data) === null || _l === void 0 ? void 0 : _l.url}`);
1124
- this.location.replaceState((_m = event === null || event === void 0 ? void 0 : event.data) === null || _m === void 0 ? void 0 : _m.url);
1125
- }
1126
- else if (((_o = event === null || event === void 0 ? void 0 : event.data) === null || _o === void 0 ? void 0 : _o.type) == "confirm") {
1127
- console.log(`Window message - confirm -> Level: ${(_p = event === null || event === void 0 ? void 0 : event.data) === null || _p === void 0 ? void 0 : _p.level}, Message: ${(_q = event === null || event === void 0 ? void 0 : event.data) === null || _q === void 0 ? void 0 : _q.text}, Title: ${(_r = event === null || event === void 0 ? void 0 : event.data) === null || _r === void 0 ? void 0 : _r.title}, ID: ${(_s = event === null || event === void 0 ? void 0 : event.data) === null || _s === void 0 ? void 0 : _s.guid}`);
1128
- var sourceWindow = event.source;
1129
- var baseResponse = { type: "confirm-response", guid: (_t = event === null || event === void 0 ? void 0 : event.data) === null || _t === void 0 ? void 0 : _t.guid };
1130
- switch ((_u = event === null || event === void 0 ? void 0 : event.data) === null || _u === void 0 ? void 0 : _u.level) {
1131
- case "success":
1132
- this.msgService.simpleSuccessWithChoice((_v = event === null || event === void 0 ? void 0 : event.data) === null || _v === void 0 ? void 0 : _v.title, (_w = event === null || event === void 0 ? void 0 : event.data) === null || _w === void 0 ? void 0 : _w.text, () => {
1133
- sourceWindow.postMessage(Object.assign({ result: true }, baseResponse), "*");
1134
- }, () => {
1135
- sourceWindow.postMessage(Object.assign({ result: false }, baseResponse), "*");
1136
- });
1137
- break;
1138
- case "warning":
1139
- this.msgService.simpleWarningWithChoice((_x = event === null || event === void 0 ? void 0 : event.data) === null || _x === void 0 ? void 0 : _x.title, (_y = event === null || event === void 0 ? void 0 : event.data) === null || _y === void 0 ? void 0 : _y.text, () => {
1140
- sourceWindow.postMessage(Object.assign({ result: true }, baseResponse), "*");
1141
- }, () => {
1142
- sourceWindow.postMessage(Object.assign({ result: false }, baseResponse), "*");
1143
- });
1144
- break;
1145
- }
1146
- }
1147
- else if (((_z = event === null || event === void 0 ? void 0 : event.data) === null || _z === void 0 ? void 0 : _z.type) == "navigate") {
1148
- console.log(`Window message - navigate -> ${(_0 = event === null || event === void 0 ? void 0 : event.data) === null || _0 === void 0 ? void 0 : _0.url}`);
1149
- var newTab = (_1 = event === null || event === void 0 ? void 0 : event.data) === null || _1 === void 0 ? void 0 : _1.newTab;
1150
- var replaceState = (_2 = event === null || event === void 0 ? void 0 : event.data) === null || _2 === void 0 ? void 0 : _2.replaceState;
1151
- // Controllo se il router sta seguendo la chiamata attuale. Escludo i query params che sono gli unici che possono essere seccati dai replaceState
1152
- // e che potrebbero fare del casino
1153
- if (!window.location.href.includes(this.router.url.split("?")[0])) {
1154
- console.warn("Doppia chiamata di navigazione, ignoro il secondo evento scoordinato dal router");
1155
- return;
1156
- }
1157
- let newRelativeUrl = this.router.createUrlTree([(_3 = event === null || event === void 0 ? void 0 : event.data) === null || _3 === void 0 ? void 0 : _3.url]);
1158
- let baseUrl = window.location.href.replace(this.router.url.replace("?ignoreStorage=true", ''), '');
1159
- let newUrl = baseUrl + decodeURIComponent(newRelativeUrl.toString());
1160
- if (replaceState)
1161
- history.pushState({ _pushed: true }, "", newUrl);
1162
- else if (newTab)
1163
- window.open(newUrl, '_blank');
1164
- }
1165
- else if (((_4 = event === null || event === void 0 ? void 0 : event.data) === null || _4 === void 0 ? void 0 : _4.type) == "navigate-back") {
1166
- console.log(`Window message - navigate-back -> ${(_5 = event === null || event === void 0 ? void 0 : event.data) === null || _5 === void 0 ? void 0 : _5.url}`);
1167
- if (history.state._pushed) {
1168
- this._reloadAllowed = false;
1169
- history.back();
1170
- }
1171
- }
1172
- else if (((_6 = event === null || event === void 0 ? void 0 : event.data) === null || _6 === void 0 ? void 0 : _6.type) == "redirect") {
1173
- console.log(`Window message - redirect -> ${(_7 = event === null || event === void 0 ? void 0 : event.data) === null || _7 === void 0 ? void 0 : _7.url}`);
1174
- window.location.href = (_8 = event === null || event === void 0 ? void 0 : event.data) === null || _8 === void 0 ? void 0 : _8.url;
1175
- }
1176
- else if (((_9 = event === null || event === void 0 ? void 0 : event.data) === null || _9 === void 0 ? void 0 : _9.type) == "navigation") {
1177
- console.log(`Window message - Navigation -> ${((_10 = event === null || event === void 0 ? void 0 : event.data) === null || _10 === void 0 ? void 0 : _10.internalNavigation) ? "[internal]" : ""} ${(_11 = event === null || event === void 0 ? void 0 : event.data) === null || _11 === void 0 ? void 0 : _11.title}`);
1178
- this.MessageObserver.next({ event: "navigation", data: event === null || event === void 0 ? void 0 : event.data });
1179
- }
1180
- else if (((_12 = event === null || event === void 0 ? void 0 : event.data) === null || _12 === void 0 ? void 0 : _12.type) == "modal-open") {
1181
- const wrapper = document.body.getElementsByClassName("main-wrapper")[0];
1182
- let wrapperStyles = window.getComputedStyle(wrapper);
1183
- const wrapperPaddingLeft = parseInt(wrapperStyles.getPropertyValue("padding-left"));
1184
- const wrapperPaddingRight = parseInt(wrapperStyles.getPropertyValue("padding-right"));
1185
- console.log(`Window message - Modal Open -> Backdrop Height: ${(_13 = event === null || event === void 0 ? void 0 : event.data) === null || _13 === void 0 ? void 0 : _13.backdropHeight}`);
1186
- var topHeight = 80; // valore fisso, distanza fra il top e l'inizio dell'iframe, non sarà mai diverso
1187
- var rightSpace = wrapperPaddingRight; // valore fisso, distanza fra la fine dell'iframe e il lato sinistro dello schermo, non sarà mai diverso
1188
- var leftSpace = this.sidebarWidth + wrapperPaddingLeft;
1189
- let commonStyles = "position: absolute; z-index: 9999; background-color: #000; opacity: 0.5; ";
1190
- wrapper.style.setProperty("overflow", "hidden", "important");
1191
- const top = document.createElement("div");
1192
- top.className = "embedded-modal-top";
1193
- top.style.cssText = commonStyles + `height: ${topHeight}px; top: 0; width: calc(100% - ${leftSpace}px); left: ${leftSpace}px`;
1194
- top.id = "top";
1195
- const left = document.createElement("div");
1196
- left.className = "embedded-modal-left";
1197
- left.style.cssText = commonStyles + `height: 100%; top: 0; width: ${leftSpace}px;`;
1198
- left.id = "left";
1199
- const right = document.createElement("div");
1200
- right.className = "embedded-modal-right";
1201
- right.style.cssText = commonStyles + `height: calc(100% - ${topHeight}px); top: ${topHeight}px; right: 0; width: ${rightSpace}px;`;
1202
- right.id = "right";
1203
- // const bottom = document.createElement("div");
1204
- // bottom.className = "embedded-modal-bottom";
1205
- // bottom.style.cssText = commonStyles + `height: ${topHeight}px; bottom: 0; width: calc(100% - ${leftSpace}px); left: ${leftSpace}px`;
1206
- // bottom.id = "bottom";
1207
- document.body.appendChild(top);
1208
- document.body.appendChild(left);
1209
- document.body.appendChild(right);
1210
- }
1211
- else if (((_14 = event === null || event === void 0 ? void 0 : event.data) === null || _14 === void 0 ? void 0 : _14.type) == "modal-close") {
1212
- console.log(`Window message - Modal Close`);
1213
- let wrapper = document.body.getElementsByClassName("main-wrapper")[0];
1214
- wrapper.style.removeProperty("overflow");
1215
- const top = document.getElementById("top");
1216
- const left = document.getElementById("left");
1217
- const right = document.getElementById("right");
1218
- if (top)
1219
- document.body.removeChild(top);
1220
- if (left)
1221
- document.body.removeChild(left);
1222
- if (right)
1223
- document.body.removeChild(right);
1224
- }
1225
- };
1226
- if (this.Embedded)
1227
- document.body.style.setProperty("overflow-y", "auto", "important");
1228
- }
1229
- replaceState(basePath, url) {
1230
- // Esempio basePath: pages
1231
- // Esempio url: parties/leads_search
1232
- // Normalizzazione senza slash prima o dopo
1233
- basePath = basePath.endsWith("/") ? basePath.substring(0, basePath.length - 2) : basePath;
1234
- url = url.startsWith("/") ? url.substring(1) : url;
1235
- this.location.replaceState(`${basePath}/${url}`);
1236
- this.MainWindow.postMessage({ type: "replace-state", url: `pages/embed/${this.EmbeddedModule}/${url}` }, "*");
1237
- }
1238
- refreshBoundariesOnMenuCollapse() {
1239
- const wrapper = document.body.getElementsByClassName("main-wrapper")[0];
1240
- let wrapperStyles = window.getComputedStyle(wrapper);
1241
- const wrapperPaddingLeft = parseInt(wrapperStyles.getPropertyValue("padding-left"));
1242
- var leftSpace = 230 + wrapperPaddingLeft;
1243
- const left = document.getElementById("left");
1244
- const top = document.getElementById("top");
1245
- if (top) {
1246
- top.style.setProperty("left", (leftSpace) + "px");
1247
- top.style.setProperty("width", `calc(100% - ${leftSpace}px)`);
1248
- }
1249
- if (left)
1250
- left.style.setProperty("width", leftSpace + "px");
1251
- }
1252
- }
1253
- AppEmbeddingExtensions.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.2.9", ngImport: i0, type: AppEmbeddingExtensions, deps: [{ token: MessageService }, { token: i2.Router }, { token: i3.Location }], target: i0.ɵɵFactoryTarget.Injectable });
1254
- AppEmbeddingExtensions.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.2.9", ngImport: i0, type: AppEmbeddingExtensions, providedIn: "root" });
1255
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.2.9", ngImport: i0, type: AppEmbeddingExtensions, decorators: [{
1256
- type: Injectable,
1257
- args: [{ providedIn: "root" }]
1258
- }], ctorParameters: function () { return [{ type: MessageService }, { type: i2.Router }, { type: i3.Location }]; } });
1259
-
1260
- // Angular
1261
- /**
1262
- * Service che fornisce un accesso base in lettura/scrittura sulla clipboard
1263
- */
1264
- class BaseExtensionsService {
1265
- constructor(emb) {
1266
- this.emb = emb;
1267
- this.RedirectMap = {};
1268
- this.RoutesMap = {};
1269
- for (let prop in this.RedirectMap) {
1270
- this.RoutesMap[prop] = { route: null };
1271
- this.RoutesMap[prop].route = (param) => {
1272
- let obj = {};
1273
- obj[this.RedirectMap[prop].params[0]] = param;
1274
- return [(this.emb.Embedded ? "pages_ext/" : "pages/") + this.RedirectMap[prop].url, obj];
1275
- };
1276
- }
1277
- }
1278
- }
1279
- BaseExtensionsService.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.2.9", ngImport: i0, type: BaseExtensionsService, deps: [{ token: AppEmbeddingExtensions }], target: i0.ɵɵFactoryTarget.Injectable });
1280
- BaseExtensionsService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.2.9", ngImport: i0, type: BaseExtensionsService, providedIn: "root" });
1281
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.2.9", ngImport: i0, type: BaseExtensionsService, decorators: [{
1282
- type: Injectable,
1283
- args: [{ providedIn: "root" }]
1284
- }], ctorParameters: function () { return [{ type: AppEmbeddingExtensions }]; } });
1285
-
1286
- /**
1287
- * Suffisso della proprietà da generare in cui salvare il navigatore
1288
- * utilizzato dal servizio di esportazione per prendere il valore delle proprietà di un oggetto
1289
- */
1290
- const csvValueNavigator = "_csvnav";
1291
- /** Suffisso con le informazioni del tipo per le esportazioni di oggetti */
1292
- const csvValueType = "_csvtype";
1293
- /** Suffisso della proprietà da generare in cui salvare l'ordine di esportazione */
1294
- const csvOrdPrefix = "_csvord";
1295
- /** Suffisso della proprietà da generare in cui salvare la visibilità di questa proprietà */
1296
- const csvVisPrefix = "_csvvis";
1297
- /** Suffisso della proprietà da generare in cui salvare il nome della colonna in cui salvare questa proprietà */
1298
- const csvHdrPrefix = "_csvhdr";
1299
- /** Suffisso della proprietà da generare in cui salvare il codice del th a cui si riferisce questo campo */
1300
- const csvPropKey = "_csvkey";
1301
- /** Suffisso della proprietà da generare in cui salvare il valore da prendere per una proprietà di tipo Lista */
1302
- const listCsvValPrefix = "_listcsvval";
1303
- /** Suffisso della proprietà da generare in cui salvare l'Header della proprietà di tipo Lista relativo al valore esportato nella proprietà con suffisso **listCsvValPrefix** */
1304
- const listCsvHdrPrefix = "_listcsvhdr";
1305
- /** Suffisso della proprietà da generare in cui salvare il formato della proprietà di tipo Lista relativo al valore esportato nella proprietà con suffisso **listCsvValPrefix** */
1306
- const listCsvValFormat = "_listcsvvalformat";
1307
- /** Suffisso della proprietà da generare in cui salvare il valore da prendere per una proprietà di tipo Dizionario */
1308
- const dictionaryCsvValPrefix = "_flatlistcsvval";
1309
- /** Suffisso della proprietà da generare in cui salvare l'Header della proprietà di un Dizionario relativo al valore esportato nella proprietà con suffisso **dictionaryCsvValPrefix** */
1310
- const dictionaryCsvHdrPrefix = "_flatlistcsvhdr";
1311
- /** Suffisso della proprietà da generare in cui salvare il formato della proprietà che si sta esportando */
1312
- const csvFormatPrefix = "_csvfmt";
1313
- /** Nome della proprietà che contiene tutti i nomi di tutte le proprietà da esportare */
1314
- const exportList = "__export_list__";
1315
- /** Nome della proprietà che contiene la classe di localizzazione da utilizzare per una data esportazione */
1316
- const locProperty = "__loc__";
1317
-
1318
- /**
1319
- * Mappatura del TypeCode del C#
1320
- */
1321
- var TypeCode;
1322
- (function (TypeCode) {
1323
- /** @ignore */ TypeCode[TypeCode["Empty"] = 0] = "Empty";
1324
- /** @ignore */ TypeCode[TypeCode["Obj"] = 1] = "Obj";
1325
- /** @ignore */ TypeCode[TypeCode["DBNull"] = 2] = "DBNull";
1326
- /** @ignore */ TypeCode[TypeCode["Boolean"] = 3] = "Boolean";
1327
- /** @ignore */ TypeCode[TypeCode["Char"] = 4] = "Char";
1328
- /** @ignore */ TypeCode[TypeCode["SByte"] = 5] = "SByte";
1329
- /** @ignore */ TypeCode[TypeCode["Byte"] = 6] = "Byte";
1330
- /** @ignore */ TypeCode[TypeCode["Int16"] = 7] = "Int16";
1331
- /** @ignore */ TypeCode[TypeCode["UInt16"] = 8] = "UInt16";
1332
- /** @ignore */ TypeCode[TypeCode["Int32"] = 9] = "Int32";
1333
- /** @ignore */ TypeCode[TypeCode["UInt32"] = 10] = "UInt32";
1334
- /** @ignore */ TypeCode[TypeCode["Int64"] = 11] = "Int64";
1335
- /** @ignore */ TypeCode[TypeCode["UInt64"] = 12] = "UInt64";
1336
- /** @ignore */ TypeCode[TypeCode["Single"] = 13] = "Single";
1337
- /** @ignore */ TypeCode[TypeCode["Double"] = 14] = "Double";
1338
- /** @ignore */ TypeCode[TypeCode["Decimal"] = 15] = "Decimal";
1339
- /** @ignore */ TypeCode[TypeCode["DateTime"] = 16] = "DateTime";
1340
- /** @ignore */ TypeCode[TypeCode["String"] = 18] = "String";
1341
- })(TypeCode || (TypeCode = {}));
1342
-
1343
- // Angular
1344
- /**
1345
- * Service che fornisce metodi di pubblica utilità
1346
- */
1347
- class UtilityService {
1348
- constructor() {
1349
- // Funzione di throttling per non spammare richieste in caso di animazioni attivate
1350
- //TODO: spostarla in un metodo di utilit� (esfaenza/extensions)
1351
- /** @ignore */
1352
- this.executionTimers = {};
1353
- }
1354
- /**
1355
- * Deseleziona il testo eventualmente selezionato
1356
- */
1357
- clearTextSelection() {
1358
- if (window.getSelection) {
1359
- if (window.getSelection().empty) // Chrome
1360
- window.getSelection().empty();
1361
- else if (window.getSelection().removeAllRanges) // Firefox
1362
- window.getSelection().removeAllRanges();
1363
- }
1364
- else if (document.selection) // IE?
1365
- document.selection.empty();
1366
- }
1367
- /**
1368
- * Partendo da una lista, dato il nome della proprietà chiave e il valore della chiave selezionata,
1369
- * trova e restituisce l'oggetto desiderato
1370
- *
1371
- * @param {T[]} sourceList Lista di oggetti dentro cui cercare
1372
- * @param {string} sourceItemIdField Nome della proprietà che rappresenta la chiave di un oggetto di tipo T
1373
- * @param {string} selectedValue Valore di chiave selezionato
1374
- *
1375
- * @returns {T} Oggetto la cui proprietà **sourceItemIdField** assume il valore **selectedValue**
1376
- */
1377
- getSelectedItem(sourceList, sourceItemIdField, selectedValue) {
1378
- for (let i = 0; i < sourceList.length; i++) {
1379
- var item = sourceList[i];
1380
- if (item[sourceItemIdField] == selectedValue)
1381
- return item;
1382
- }
1383
- return null;
1384
- }
1385
- /**
1386
- * Effettua il reset di un Form di Angular
1387
- *
1388
- * @param {NgForm} form Form da resettare
1389
- * @param {string} exception1 Campo da non resettare
1390
- * @param {string} exception2 Campo da non resettare
1391
- */
1392
- cleanForm(form, exception1 = null, exception2 = null) {
1393
- for (let name in form.controls) {
1394
- if (name && name != exception1 && name != exception1 + "_internal" && name != exception2 && name != exception2 + "_internal") {
1395
- form.controls[name].reset();
1396
- }
1397
- else {
1398
- form.controls[name].markAsPristine();
1399
- form.controls[name].markAsUntouched();
1400
- }
1401
- }
1402
- //Reimposto il submitted
1403
- form.submitted = false;
1404
- }
1405
- /**
1406
- * Helper che permette di scaricare un file dato un URL (Generato da una chiamata ad **window.URL.createObjectURL**)
1407
- *
1408
- * @param {string} url ObjectURL che rappresenta il file da scaricare
1409
- * @param {string} filename Nome del file suggerito in fase di salvataggio
1410
- */
1411
- fileDownload(url, fileName) {
1412
- var a = document.createElement("a");
1413
- document.body.appendChild(a);
1414
- a.className = "ta-display-none";
1415
- a.href = url;
1416
- a.download = fileName;
1417
- a.click();
1418
- window.URL.revokeObjectURL(url);
1419
- document.body.removeChild(a);
1420
- }
1421
- /**
1422
- * Helper per la formattazione di un numero di millisecondi in una stringa più comprensibile per un umano
1423
- *
1424
- * @param {number} duration Tempo espresso in millisecondi
1425
- *
1426
- * @returns {string} Durata formattata
1427
- */
1428
- msToTime(duration) {
1429
- if (!duration)
1430
- return "";
1431
- var milliseconds = parseInt(((duration % 1000) / 100).toString()), seconds = parseInt(((duration / 1000) % 60).toString()), minutes = parseInt(((duration / (1000 * 60)) % 60).toString()), hours = parseInt(((duration / (1000 * 60 * 60)) % 24).toString());
1432
- var st_hours = (hours < 10) ? "0" + hours : hours;
1433
- var st_minutes = (minutes < 10) ? "0" + minutes : minutes;
1434
- var st_seconds = (seconds < 10) ? "0" + seconds : seconds;
1435
- return st_hours + ":" + st_minutes + ":" + st_seconds + "." + milliseconds;
1436
- }
1437
- /**
1438
- * Helper che permette di scaricare un file in Base64
1439
- *
1440
- * @param {string} base64Data Base64 che rappresenta il file da scaricare
1441
- * @param {string} filename Nome del file suggerito in fase di salvataggio
1442
- */
1443
- saveFile(base64Data, filename) {
1444
- var sampleArr = this.base64ToArrayBuffer(base64Data);
1445
- this.saveByteArray(sampleArr, filename);
1446
- }
1447
- /**
1448
- * Trasforma un Base64 in un ArrayBuffer
1449
- *
1450
- * @param {string} base64Data Base64 da trasformare
1451
- *
1452
- * @returns {Uint8Array} Array UTF8
1453
- */
1454
- base64ToArrayBuffer(base64Data) {
1455
- var binaryString = window.atob(base64Data);
1456
- var binaryLen = binaryString.length;
1457
- var bytes = new Uint8Array(binaryLen);
1458
- for (var i = 0; i < binaryLen; i++) {
1459
- var ascii = binaryString.charCodeAt(i);
1460
- bytes[i] = ascii;
1461
- }
1462
- return bytes;
1463
- }
1464
- /**
1465
- * Helper che permette di scaricare un file dato un array di Byte (**Uint8Array**)
1466
- *
1467
- * @param {Uint8Array} byte Rappresentazione del file da scaricare
1468
- * @param {string} filename Nome del file suggerito in fase di salvataggio
1469
- */
1470
- saveByteArray(byte, filename) {
1471
- var blob = new Blob([byte]);
1472
- var link = document.createElement("a");
1473
- document.body.appendChild(link);
1474
- link.href = window.URL.createObjectURL(blob);
1475
- var fileName = filename;
1476
- link.download = fileName;
1477
- link.click();
1478
- document.body.removeChild(link);
1479
- }
1480
- ;
1481
- /**
1482
- * Utility per lo swap di due elementi di un array
1483
- *
1484
- * @param {any[]} array Array di cui invertire due elementi
1485
- * @param {number} x Indice del primo elemento
1486
- * @param {number} y Indice del secondo elemento
1487
- */
1488
- swap(array, x, y) {
1489
- var b = array[x];
1490
- array[x] = array[y];
1491
- array[y] = b;
1492
- }
1493
- /**
1494
- * Helper di trascodifica da tipo c# a tipo Typescript
1495
- *
1496
- * @param {TypeCode} type Tipo da trascodificare
1497
- *
1498
- * @returns {"boolean" | "number" | "string" | "date"} Tipo Typescript corrispondente
1499
- */
1500
- getJsTypeFromTypeCode(type) {
1501
- switch (type) {
1502
- case TypeCode.Boolean:
1503
- return "boolean";
1504
- case TypeCode.Decimal:
1505
- case TypeCode.Double:
1506
- case TypeCode.Single:
1507
- case TypeCode.Int16:
1508
- case TypeCode.Int32:
1509
- case TypeCode.Int64:
1510
- case TypeCode.Byte:
1511
- case TypeCode.SByte:
1512
- case TypeCode.UInt16:
1513
- case TypeCode.UInt32:
1514
- case TypeCode.UInt64:
1515
- return "number";
1516
- case TypeCode.Char:
1517
- case TypeCode.String:
1518
- return "string";
1519
- case TypeCode.DateTime:
1520
- return "date";
1521
- default:
1522
- console.log("Unrecognized input type. Typecode:" + type);
1523
- return "string";
1524
- }
1525
- }
1526
- /**
1527
- * Effettua la clonazione profonda di un oggetto in maniera molto più performante che JSON.parse(JSON.stringify()).
1528
- *
1529
- * Usare solo per oggetti puri e quantomeno semplici per evitare complicazioni derivanti dalle semplificazioni che questo metodo assume
1530
- *
1531
- * @param {any} source Oggetto da clonare
1532
- *
1533
- * @return {any} Clone dell'oggetto passato
1534
- */
1535
- deepClone(source, type = null) {
1536
- // Valori semplici
1537
- if (source == null || typeof source !== 'object')
1538
- return source;
1539
- // Pseudo Struct
1540
- switch (toString.call(source)) {
1541
- case '[object Boolean]':
1542
- case '[object Number]':
1543
- case '[object String]':
1544
- case '[object Date]':
1545
- return new source.constructor(source.valueOf());
1546
- // Clonazione di un file -> Restituisco il riferimento al file stesso
1547
- case "[object File]":
1548
- return source;
1549
- default: break;
1550
- }
1551
- // Oggetti Complessi
1552
- return this.recursiveStep(source, Array.isArray(source) || source instanceof Array ? [] : (type == null ? Object.create(Object.getPrototypeOf(source)) : new type()));
1553
- }
1554
- /**
1555
- * @ignore
1556
- * Step ricorsivo per la clonatura degli oggetti. Vedere **deepClone**
1557
- */
1558
- recursiveStep(source, destination) {
1559
- if (Array.isArray(source) || source instanceof Array) {
1560
- for (var i = 0, ii = source.length; i < ii; i++)
1561
- destination.push(this.deepClone(source[i]));
1562
- }
1563
- else if (source && typeof source.hasOwnProperty === 'function') {
1564
- for (let key in source) {
1565
- if (source.hasOwnProperty(key))
1566
- destination[key] = this.deepClone(source[key]);
1567
- }
1568
- }
1569
- return destination;
1570
- }
1571
- cast(object, clss) {
1572
- let ret = Object.assign(Object.create(clss.prototype), object);
1573
- return ret;
1574
- }
1575
- /** @ignore */
1576
- throttla(id, func, throttleTime) {
1577
- //Se ho la funzione che vuole eseguire ripulisco quel timeout
1578
- if (this.executionTimers[id])
1579
- clearTimeout(this.executionTimers[id]);
1580
- //Ricreo il timeout per eseguire quella funzione dopo throttleTime millisecondi
1581
- this.executionTimers[id] = setTimeout(() => { func(); this.executionTimers[id] = null; }, throttleTime);
1582
- }
1583
- }
1584
- UtilityService.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.2.9", ngImport: i0, type: UtilityService, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
1585
- UtilityService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.2.9", ngImport: i0, type: UtilityService, providedIn: "root" });
1586
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.2.9", ngImport: i0, type: UtilityService, decorators: [{
1587
- type: Injectable,
1588
- args: [{ providedIn: "root" }]
1589
- }] });
1590
-
1591
- /**
1592
- * Decoratore che fornisce la classe di localizzazione per tutte le proprietà esportate con @Export e qualsiasi altro tag che richieda localizzazioni.
1593
- *
1594
- * Sostanzilamente aggiunge la proprietà **__loc__** all'oggetto creato dalla classe corrente assegnandogli come valore il tipo del LocalizationService da usare per la traduzione
1595
- *
1596
- * @param {Type<LocalizationService>} loc Tipo ereditato dal LocalizationService che può essere creato a runtime sotto contesto della DI di Angular
1597
- */
1598
- function ExportLocalization(loc) {
1599
- return function integrateLoc(constructor) {
1600
- return class extends constructor {
1601
- constructor() {
1602
- super(...arguments);
1603
- this.__loc__ = loc;
1604
- }
1605
- };
1606
- };
1607
- }
1608
- /**
1609
- * Decoratore di esportazione utilizzabile su una proprietà singola.
1610
- * Verranno generate 3 proprietà che gestiranno l'esportazione: (prop, prop_csvvis, prop_csvhdr).
1611
- *
1612
- * Ad esempio, da questa configurazione:
1613
- *
1614
- * @example
1615
- * ```
1616
- * @Export(true, "MyHeader")
1617
- * ciao: string;
1618
- * ```
1619
- *
1620
- * Nasceranno le seguenti proprietà nell'oggetto esportabile:
1621
- *
1622
- * @example
1623
- * ```
1624
- * ciao_csvvis: string; => true
1625
- * ciao: string;
1626
- * ciao_csvhdr: string => "MyHeader"
1627
- * ```
1628
- *
1629
- * @param {number} order Ordine di esportazione. Più piccolo è, prima appare il valore
1630
- * @param {string} header Titolo della colonna nel file CSV esportato
1631
- * @param {string} format Formato di esportazione. Può essere un formato data per i campi data o 'F' per i campi floating point
1632
- */
1633
- const Export = (order, header, format = null, tableid = null) => (target, propertyKey) => {
1634
- if (format)
1635
- Object.defineProperty(target, propertyKey + csvFormatPrefix, { value: format, writable: false });
1636
- Object.defineProperty(target, propertyKey + csvOrdPrefix, { value: order, writable: false });
1637
- Object.defineProperty(target, propertyKey + csvVisPrefix, { value: !!header, writable: false });
1638
- Object.defineProperty(target, propertyKey + csvHdrPrefix, { value: header, writable: false });
1639
- if (tableid)
1640
- Object.defineProperty(target, propertyKey + csvPropKey, { value: tableid, writable: false });
1641
- if (target[exportList])
1642
- target[exportList].push(propertyKey + csvVisPrefix);
1643
- else
1644
- target[exportList] = [propertyKey + csvVisPrefix];
1645
- };
1646
- /**
1647
- * Decoratore di esportazione utilizzabile su un oggetto.
1648
- * Per ogni proprietà dell'oggetto verranno generate 3 proprietà che gestiranno l'esportazione: (prop, prop_csvvis, prop_csvhdr).
1649
- * Per essere esportate, le proprietà dell'oggetto devono essere marcate con i Decoratori di esportazione
1650
- *
1651
- * Ad esempio, da questa configurazione:
1652
- *
1653
- * @example
1654
- * ```
1655
- * MyObj {
1656
- * @Export(true, "MyHeader")
1657
- * ciao: string;
1658
- * }
1659
- *
1660
- * @ExportObject(true, "MyHeader")
1661
- * test: MyObj;
1662
- * ```
1663
- *
1664
- * Nasceranno le seguenti proprietà nell'oggetto esportabile:
1665
- *
1666
- * @example
1667
- * ```
1668
- * testciao: string; => Valore di MyObj.ciao
1669
- * testciao_csvvis: string; => true
1670
- * testciao_csvhdr: string => "MyHeader"
1671
- * ```
1672
- *
1673
- * @param {number} order Ordine di esportazione. Più piccolo è, prima appare il valore
1674
- * @param {any} type Tipo da esportare
1675
- */
1676
- const ExportAs = (order, type, prefix) => (target, propertyKey) => {
1677
- var addedHere = {};
1678
- var t = new type();
1679
- var props = t[exportList];
1680
- for (let i = 0; i < props.length; i++) {
1681
- let prop = props[i].replace(csvVisPrefix, '');
1682
- if (addedHere[prop])
1683
- continue;
1684
- if (typeof t[prop + csvVisPrefix] !== "undefined") {
1685
- var toEmit = t[prop + csvVisPrefix];
1686
- var lbl = t[prop + csvHdrPrefix];
1687
- var format = t[prop + csvFormatPrefix];
1688
- var orderProp = t[prop + csvOrdPrefix];
1689
- if (format)
1690
- Object.defineProperty(target, propertyKey + prop + csvFormatPrefix, { value: format, writable: false });
1691
- let ppp = propertyKey + "$_$" + prop;
1692
- Object.defineProperty(target, ppp + csvOrdPrefix, { value: orderProp + order, writable: false });
1693
- Object.defineProperty(target, ppp, { value: null, writable: true, enumerable: true });
1694
- Object.defineProperty(target, ppp + csvValueNavigator, { value: propertyKey + "." + prop.replace(/\$_\$/g, '.'), writable: false });
1695
- Object.defineProperty(target, ppp + csvVisPrefix, { value: toEmit, writable: false });
1696
- Object.defineProperty(target, ppp + csvHdrPrefix, { value: (prefix ? prefix + ' ' : '') + lbl, writable: false });
1697
- Object.defineProperty(target, ppp + csvValueType, { value: type, writable: false });
1698
- if (target[exportList])
1699
- target[exportList].push(ppp + csvVisPrefix);
1700
- else
1701
- target[exportList] = [ppp + csvVisPrefix];
1702
- addedHere[ppp] = true;
1703
- }
1704
- }
1705
- };
1706
- /**
1707
- * Decoratore di esportazione utilizzabile su una lista,
1708
- * si utilizzano 2 navigator rispettivamente per la valorizzazione dell'Header e del Valore e
1709
- * per ogni elemento dell'array verranno generate 3 proprietà che gestiranno l'esportazione: (prop, prop_csvvis, prop_csvhdr)
1710
- *
1711
- * ATTENZIONE: Gli oggetti esportati in questa modalità non devono presentare altri tag di tipo @Export{...} all'interno. Fa tutto questo decoratore
1712
- *
1713
- * I navigator hanno questa convenzione:
1714
- *
1715
- * . --> divide due proprietà da richiamare consecutivamente: "a.b" richiamerà "obj.a.b";
1716
- *
1717
- * | --> divide più proprietà per le concatenazioni con uno spazio fra una e l'altra: "regdesc|slice.slicename" diventerà obj.regdesc + " " + obj.slice.slicename
1718
- *
1719
- * @param {number} order Ordine di esportazione. Più piccolo è, prima appare il valore
1720
- * @param {string} headernavigator Navigator col compito di selezionare il titolo per la colonna
1721
- * @param {string} valuenavigator Navigator col compito di selezionare il valore per la colonna
1722
- * @param {string} valueformat Formato di esportazione per i valori selezionati dal **valuenavigator**. Può essere un formato data per i campi data o 'F' per i campi floating point
1723
- */
1724
- const ExportList = (order, headernavigator, valuenavigator, valueformat = null) => (target, propertyKey) => {
1725
- Object.defineProperty(target, propertyKey + csvOrdPrefix, { value: order, writable: false });
1726
- Object.defineProperty(target, propertyKey + listCsvValPrefix, { value: valuenavigator, writable: false });
1727
- Object.defineProperty(target, propertyKey + listCsvHdrPrefix, { value: headernavigator, writable: false });
1728
- Object.defineProperty(target, propertyKey + listCsvValFormat, { value: valueformat, writable: false });
1729
- if (target[exportList])
1730
- target[exportList].push(propertyKey + listCsvHdrPrefix);
1731
- else
1732
- target[exportList] = [propertyKey + listCsvHdrPrefix];
1733
- };
1734
- /**
1735
- * Decoratore di esportazione utilizzabile su un dizionario. Se ad esempio si vogliono generare le colonne
1736
- *
1737
- * Valore A = 1
1738
- *
1739
- * Valore B = 2
1740
- *
1741
- * Valore C = 3
1742
- *
1743
- * partendo da un oggetto iniziale { Valore { A: 1, B: 2, C: 3 } }
1744
- *
1745
- * @param {number} order Ordine di esportazione. Più piccolo è, prima appare il valore
1746
- * @param {string} headerprefix Prefisso per l'header
1747
- * @param {string} valueprefix Prefisso per il valore
1748
- */
1749
- const ExportDictionary = (order, headerprefix, valueprefix) => (target, propertyKey) => {
1750
- Object.defineProperty(target, propertyKey + csvOrdPrefix, { value: order, writable: false });
1751
- Object.defineProperty(target, propertyKey + dictionaryCsvValPrefix, { value: valueprefix, writable: false });
1752
- Object.defineProperty(target, propertyKey + dictionaryCsvHdrPrefix, { value: headerprefix, writable: false });
1753
- if (target[exportList])
1754
- target[exportList].push(propertyKey + dictionaryCsvHdrPrefix);
1755
- else
1756
- target[exportList] = [propertyKey + dictionaryCsvHdrPrefix];
1757
- };
1758
- /**
1759
- * Service che si occupa dell'esportazione degli oggetti marcati dai Decoratori **ExportDictionary**, **ExportList**, **ExportAs** o **Export**
1760
- */
1761
- class ExportService {
1762
- /**
1763
- * Costruttore
1764
- *
1765
- * @ignore
1766
- */
1767
- constructor(dates, utiExts, lc) {
1768
- this.dates = dates;
1769
- this.utiExts = utiExts;
1770
- this.lc = lc;
1771
- }
1772
- /**
1773
- * Data una lista di oggetti genera gli header per l'esportazione e integra ogni oggetto con le proprietà esportabili dalla libreria **@ctrl/ngx-csv**
1774
- *
1775
- * @param {any[]} objs Oggetti da esportare
1776
- *
1777
- * @returns {CsvHeaders[]} Header di esportazione già ordinati correttamente
1778
- */
1779
- setupForExport(objs, columns = []) {
1780
- let headers = [];
1781
- let headersCache = {};
1782
- if (!objs || objs.length == 0)
1783
- return headers;
1784
- // Devo per forza farlo per tutti gli oggetti dato che devo esporre le proprietà che mi servono da esportare
1785
- // Gli header li raccolgo tutti poi faccio uan distinct in modo da esportare tutte le proprietà per bene
1786
- let columnSelectionDictionary = {};
1787
- if ((columns === null || columns === void 0 ? void 0 : columns.length) > 0)
1788
- for (let i = 0; i < (columns === null || columns === void 0 ? void 0 : columns.length); i++)
1789
- columnSelectionDictionary[columns[i]] = true;
1790
- for (let i = 0; i < objs.length; i++) {
1791
- let hds = this.parseAndGetHeaders(objs[i], columnSelectionDictionary);
1792
- // Aggiungo gli header facendo in modo di non aggiungerne mai due uguali per non dover fare una distinct dopo
1793
- // che costerebbe comunque risorse. Utilizzo un dizionario d'appoggio per lookup istantanei
1794
- for (let k = 0; k < hds.length; k++) {
1795
- if (!headersCache[hds[k].key]) {
1796
- headersCache[hds[k].key] = true;
1797
- headers.push(hds[k]);
1798
- }
1799
- }
1800
- }
1801
- if (!columns || columns.length == 0)
1802
- return headers.sort((a, b) => a.order - b.order);
1803
- else {
1804
- // Se mi arriva la lista di colonne non mi dà solo la visibilità, ma anche l'ordinamento
1805
- // le esporto di conseguenza
1806
- let orderedHeaders = [];
1807
- for (let i = 0; i < columns.length; i++) {
1808
- let thisId = columns[i];
1809
- for (let i = 0; i < headers.length; i++) {
1810
- if (headers[i].propKey == thisId) {
1811
- orderedHeaders.push(headers[i]);
1812
- break;
1813
- }
1814
- }
1815
- }
1816
- return orderedHeaders;
1817
- }
1818
- }
1819
- /**
1820
- * Data una lista di oggetti generici genera gli header per l'esportazione e integra ogni oggetto con le proprietà esportabili dalla libreria **@ctrl/ngx-csv**
1821
- *
1822
- * @param {GenericItem[]} objs Oggetti generici da esportare
1823
- * @param {CsvHeaders[]} columns Colonne richieste dall'esportazione
1824
- *
1825
- * @returns {CsvHeaders[]} Header di esportazione già ordinati correttamente
1826
- */
1827
- setupForGenericExport(objs, columns) {
1828
- let headers = [];
1829
- if (!objs || objs.length == 0)
1830
- return headers;
1831
- // Devo per forza farlo per tutti gli oggetti dato che devo esporre le proprietà che mi servono da esportare
1832
- objs.forEach((obj, index) => {
1833
- if (index == 0)
1834
- headers = this.parseAndGetGenericHeaders(obj, columns);
1835
- else
1836
- this.parseAndGetGenericHeaders(obj, columns);
1837
- });
1838
- return headers;
1839
- }
1840
- /**
1841
- * Dato un oggetto generico genera gli header per l'esportazione e lo integra con le proprietà esportabili dalla libreria **@ctrl/ngx-csv**
1842
- *
1843
- * Metodo interno richiamato da **setupForGenericExport**
1844
- *
1845
- * @param {GenericItem} obj Oggetto generico da esportare
1846
- * @param {CsvColumn[]} columns Colonne richieste dall'esportazione
1847
- *
1848
- * @returns {CsvHeaders[]} Header di esportazione già ordinati correttamente
1849
- */
1850
- parseAndGetGenericHeaders(obj, columns) {
1851
- if (!obj.properties)
1852
- return null;
1853
- var headers = [];
1854
- //Miracle incoming
1855
- columns.forEach(t => {
1856
- var propValue = obj.properties[t.key];
1857
- Object.defineProperty(obj, t.key + "_exp", { value: propValue, writable: false, enumerable: true });
1858
- headers.push({ label: t.label, key: t.key + "_exp", order: t.order, type: t.type, propKey: null });
1859
- });
1860
- //Tirati fuori tutti gli header faccio sort sull'ordinamento
1861
- return headers.sort((a, b) => { return a.order - b.order; });
1862
- }
1863
- /**
1864
- * Dato un oggetto genera gli header per l'esportazione e lo integra con le proprietà esportabili dalla libreria **@ctrl/ngx-csv**
1865
- *
1866
- * Metodo interno richiamato da **setupForExport**
1867
- *
1868
- * @param {any} obj Oggetto generico da esportare
1869
- *
1870
- * @returns {CsvHeaders[]} Header di esportazione già ordinati correttamente
1871
- */
1872
- parseAndGetHeaders(obj, columnsSelection) {
1873
- var headers = [];
1874
- // Miracle incoming
1875
- let exportProps = obj[exportList] || [];
1876
- let loc = obj[locProperty] ? this.lc.generateFromType(obj[locProperty]) : null;
1877
- if (exportProps.length == 0)
1878
- console.warn("[@esfaenza/extensions] Nessuna colonna configurata da esportare!");
1879
- for (let i = 0; i < exportProps.length; i++) {
1880
- let prop = exportProps[i];
1881
- let propBase = "";
1882
- let toCall;
1883
- if (prop.endsWith(listCsvHdrPrefix)) {
1884
- propBase = prop.replace(listCsvHdrPrefix, '');
1885
- toCall = this.parseList.bind(this);
1886
- }
1887
- else if (prop.endsWith(dictionaryCsvHdrPrefix)) {
1888
- propBase = prop.replace(dictionaryCsvHdrPrefix, '');
1889
- toCall = this.parseDictionary.bind(this);
1890
- }
1891
- else if (prop.endsWith(csvVisPrefix)) {
1892
- propBase = prop.replace(csvVisPrefix, '');
1893
- if (typeof obj[propBase + csvValueNavigator] !== "undefined")
1894
- toCall = this.parseObject.bind(this);
1895
- else
1896
- toCall = this.parseProperty.bind(this);
1897
- }
1898
- if (toCall)
1899
- toCall(obj, propBase, headers, columnsSelection, loc);
1900
- }
1901
- return headers;
1902
- }
1903
- /**
1904
- * Setup per l'esportazione di una singola proprietà.
1905
- * Viene generato l'header e la proprietà relativa al valore formattato o no
1906
- *
1907
- * @param {any} obj Oggetto di cui esportare la proprietà **prop**
1908
- * @param {string} prop Proprietà da esportare
1909
- * @param {CsvHeaders} headers Contenitore degli header, verrà riempito da questa funzione
1910
- * @param {LocalizationService} loc Servizio di localizzazione che traduce tutti i nomi che può
1911
- */
1912
- parseProperty(obj, prop, headers, columnsSelection, loc) {
1913
- let toEmit = obj[prop + csvVisPrefix];
1914
- let format = obj[prop + csvFormatPrefix];
1915
- let propKey = obj[prop + csvPropKey];
1916
- if (propKey && !columnsSelection[propKey] && Object.keys(columnsSelection).length > 0) {
1917
- console.log("[@esfaenza/extensions] Colonna da non esportare: " + propKey);
1918
- return;
1919
- }
1920
- let text = obj[prop + csvHdrPrefix];
1921
- let label = loc && text ? loc.loc(text) : text || "";
1922
- let order = obj[prop + csvOrdPrefix];
1923
- if (!toEmit)
1924
- return;
1925
- // Se non ho un formato esporto direttamente
1926
- if (!format) {
1927
- // Se è un formato data mi assicuro di non stampare mai una data 00:00:00 altrimenti in esportazione viene uno schifo
1928
- let val = obj[prop] ? this.dates.trimSeconds(obj[prop].toString()) : "";
1929
- let key = prop + "_nofmt";
1930
- Object.defineProperty(obj, key, { value: val, writable: false, enumerable: true });
1931
- headers.push({ label, key, order, type: "string", propKey });
1932
- }
1933
- else {
1934
- let key = prop + "_fmt";
1935
- // Caso formato numerico
1936
- if (format == "F") {
1937
- // Check considerando la possibilità di zeri
1938
- let val = obj[prop] != null ? obj[prop].toString() : "";
1939
- // Elimino tutte le virgole (indicatori di migliaia per la culture default en-US)
1940
- val = val.replace(/,/, "");
1941
- // Il singolo punto che c'è, se presente (separatore decimali) lo trasformo in virgola
1942
- let valConverted = val.replace(".", ",");
1943
- Object.defineProperty(obj, key, { value: valConverted, writable: false, enumerable: true });
1944
- headers.push({ label, key, order, type: "number", propKey });
1945
- }
1946
- else {
1947
- // Se ho un formato data trasformo in dayjs, formatto ed esporto
1948
- // Per la trasformazione in dayjs provo prima a passargli la stringa di netto, sperando la riconosca
1949
- // Se non funziona provo a definirgli la formattazione standard del metering per quel linguaggio
1950
- let val = this.dates.getFormatted(obj[prop], format.length <= 10, format.length > 16);
1951
- Object.defineProperty(obj, key, { value: val !== null && val !== void 0 ? val : "", writable: false, enumerable: true });
1952
- headers.push({ label, key, order, type: "date", propKey });
1953
- }
1954
- }
1955
- }
1956
- /**
1957
- * Setup per l'esportazione di una singola proprietà da un oggetto.
1958
- * Viene generato l'header e la proprietà relativa al valore formattato o no.
1959
- *
1960
- * Per ottenere il valore e l'header della proprietà vengono utilizzati i navigatori auto-generati nel decoratore **ExportAs**
1961
- *
1962
- * @param {any} obj Oggetto di cui esportare la proprietà **prop**
1963
- * @param {string} prop Proprietà da esportare
1964
- * @param {CsvHeaders} headers Contenitore degli header, verrà riempito da questa funzione
1965
- * @param {LocalizationService} loc Servizio di localizzazione che traduce tutti i nomi che può
1966
- */
1967
- parseObject(obj, prop, headers, columnsSelection, loc) {
1968
- //se questa proprietà ha un navigator significa che deriva da un oggetto interno, recupero il valore in questa fase dato che prima non ce l'ho
1969
- let valuenavigator = obj[prop + csvValueNavigator];
1970
- //Es. di valuenavigator obj.subobj.subsubobj.property
1971
- let jmps = valuenavigator.split(".");
1972
- // Localizzazione presa dalla classe base se c'è, altrimenti dalla classe interna (cioè dal primo saltino)
1973
- if (!loc) {
1974
- let type = obj[prop + csvValueType];
1975
- let proto = new type();
1976
- loc = proto[locProperty] ? this.lc.generateFromType(proto[locProperty]) : null;
1977
- }
1978
- //Mi clono l'oggetto originale per non uccidergli i riferimenti
1979
- let clone = JSON.parse(JSON.stringify(obj));
1980
- //Salto ricorsivamente su me stesso per arrivare alla proprietà
1981
- //Salto 1 > diventa obj
1982
- //Salto 2 > diventa obj.subobj
1983
- //ecc...
1984
- jmps.forEach(pp => { clone = clone === null || clone === void 0 ? void 0 : clone[pp]; });
1985
- //Valore finale :D
1986
- let value = clone;
1987
- let text = obj[prop + csvHdrPrefix];
1988
- let label = loc && text ? loc.loc(text) : text || "";
1989
- let order = obj[prop + csvOrdPrefix];
1990
- //Se per questa proprietà ho un formato lo applico
1991
- let format = obj[prop + csvFormatPrefix];
1992
- let type = "string";
1993
- if (format == "F") {
1994
- let val = value.toString();
1995
- val = val.replace(/,/, "");
1996
- value = val.replace(".", ",");
1997
- type = "number";
1998
- }
1999
- else if (format) {
2000
- value = this.dates.getFormatted(value, format.length <= 10, format.length > 16);
2001
- type = "date";
2002
- }
2003
- Object.defineProperty(obj, prop, { value: value !== null && value !== void 0 ? value : "", writable: false, enumerable: true });
2004
- headers.push({ label, key: prop, order, type, propKey: null });
2005
- }
2006
- /**
2007
- * Setup per l'esportazione di una lista di valori pivottati dinamicamente:
2008
- *
2009
- * => Recupero il valore utilizzando i navigatori
2010
- *
2011
- * => Recupero l'header utilizzando i navigatori
2012
- *
2013
- * => Con il valore ci creo la property
2014
- *
2015
- * => Con l'header e il riferimento alla property appena creata creo un record negli header da esportare
2016
- *
2017
- * @param {any} obj Oggetto di cui esportare la proprietà **prop**
2018
- * @param {string} prop Proprietà da esportare
2019
- * @param {CsvHeaders} headers Contenitore degli header, verrà riempito da questa funzione
2020
- * @param {LocalizationService} loc Servizio di localizzazione che traduce tutti i nomi che può
2021
- */
2022
- parseList(obj, prop, headers, columnsSelection, loc) {
2023
- let headernavigator = obj[prop + listCsvHdrPrefix];
2024
- let valuenavigator = obj[prop + listCsvValPrefix];
2025
- let valueformat = obj[prop + listCsvValFormat];
2026
- let order = obj[prop + csvOrdPrefix];
2027
- var jumps, tmpRes;
2028
- var objs = obj[prop];
2029
- for (let idx = 0; idx < objs.length; idx++) {
2030
- let listitem = objs[idx];
2031
- var headersplit = headernavigator.split(" ");
2032
- var label = "";
2033
- // Per l'header si considera a se stante ogni pezzo separato da spazio per fare le concatenazioni
2034
- headersplit.forEach(pr => {
2035
- jumps = pr.split(".");
2036
- tmpRes = JSON.parse(JSON.stringify(listitem));
2037
- jumps.forEach(pp => { tmpRes = tmpRes[pp]; });
2038
- let localized = !!loc ? loc.loc(tmpRes) : tmpRes;
2039
- if (!label)
2040
- label = localized;
2041
- else
2042
- label += " " + localized;
2043
- });
2044
- jumps = valuenavigator.split(".");
2045
- tmpRes = JSON.parse(JSON.stringify(listitem));
2046
- jumps.forEach(pp => { tmpRes = tmpRes[pp]; });
2047
- let value = tmpRes;
2048
- let type = "string";
2049
- if (valueformat == "F") {
2050
- let val = value != null ? value.toString() : "";
2051
- val = val.replace(/,/, "");
2052
- value = val.replace(".", ",");
2053
- type = "number";
2054
- }
2055
- else if (valueformat) {
2056
- value = this.dates.getFormatted(obj[prop], valueformat.length <= 10, valueformat.length > 16);
2057
- type = "date";
2058
- }
2059
- Object.defineProperty(obj, prop + idx, { value: value !== null && value !== void 0 ? value : "", writable: false });
2060
- headers.push({ label, key: prop + idx, order: order + idx, type, propKey: null });
2061
- }
2062
- }
2063
- /**
2064
- * Setup per l'esportazione di una lista di valori pivottati dinamicamente:
2065
- *
2066
- * => Recupero il valore utilizzando i navigatori
2067
- *
2068
- * => Recupero l'header utilizzando i navigatori
2069
- *
2070
- * => Con il valore ci creo la property
2071
- *
2072
- * => Con l'header e il riferimento alla property appena creata creo un record negli header da esportare
2073
- *
2074
- * @param {any} obj Oggetto di cui esportare la proprietà **prop**
2075
- * @param {string} prop Proprietà da esportare
2076
- * @param {CsvHeaders} headers Contenitore degli header, verrà riempito da questa funzione
2077
- */
2078
- parseDictionary(obj, prop, headers, columnsSelection) {
2079
- let headerprefix = obj[prop + dictionaryCsvHdrPrefix];
2080
- let valueprefix = obj[prop + dictionaryCsvValPrefix];
2081
- let order = obj[prop + csvOrdPrefix];
2082
- var object = obj[prop];
2083
- let idx = 0;
2084
- for (const [key, val] of Object.entries(object)) {
2085
- // Ignoro tutti i cmapi che non fanno parte della selezione delle colonne
2086
- if (key && !columnsSelection[key] && Object.keys(columnsSelection).length > 0) {
2087
- console.log("[@esfaenza/extensions] Colonna da non esportare: " + key);
2088
- return;
2089
- }
2090
- let propname = prop + "_" + key;
2091
- let value = valueprefix ? valueprefix + " " + val : val;
2092
- let label = headerprefix ? headerprefix + " " + key : key;
2093
- Object.defineProperty(obj, propname, { value: value !== null && value !== void 0 ? value : "", writable: false });
2094
- headers.push({ label: label, key: propname, order: order + idx++, type: 'string', propKey: null });
2095
- }
2096
- }
2097
- /**
2098
- * Effettua l'esportazione in file CSV
2099
- */
2100
- exportCSV(fn, headers, data) {
2101
- let csvData = '', row = '', sep = ';';
2102
- for (let i = 0; i < headers.length; i++) {
2103
- let h = headers[i];
2104
- row += `${row != '' ? sep : ''}"${h.label}"`;
2105
- }
2106
- csvData += row + '\r\n';
2107
- for (let i = 0; i < data.length; i++) {
2108
- row = '';
2109
- let item = data[i];
2110
- for (let j = 0; j < headers.length; j++) {
2111
- let val = item[headers[j].key];
2112
- row += `${row != '' ? sep : ''}"${val}"`;
2113
- }
2114
- csvData += row + '\r\n';
2115
- }
2116
- var BOM = new Uint8Array([0xEF, 0xBB, 0xBF]);
2117
- var blob = new Blob([BOM, csvData], { type: 'text/csv' });
2118
- var objectUrl = URL.createObjectURL(blob);
2119
- this.utiExts.fileDownload(objectUrl, fn.endsWith('.xlsx') ? fn.replace('.xlsx', '.csv') : fn.endsWith('.csv') ? fn : fn + ".csv");
2120
- }
2121
- /** Effettua l'esportazione del file Excel basandosi sul modulo **ExcelJS**, sugli header **headers** e sui dati **data** */
2122
- exportExcel(fn, headers, data) {
2123
- return __awaiter(this, void 0, void 0, function* () {
2124
- try {
2125
- this.ExcelJS = this.ExcelJS || (yield import('exceljs'));
2126
- }
2127
- catch (_a) {
2128
- throw "Impossibile caricare la libreria per l'esportazione in Excel";
2129
- }
2130
- let iFix = 1;
2131
- let workbook = new this.ExcelJS.Workbook();
2132
- workbook.creator = "Ema's big Es-Table";
2133
- workbook.created = new Date();
2134
- let sheet = workbook.addWorksheet('Data');
2135
- let header = sheet.getRow(1);
2136
- header.font = { bold: true };
2137
- headers = headers.sort((a, b) => a.order - b.order);
2138
- for (let i = 0; i < headers.length; i++) {
2139
- let h = headers[i];
2140
- header.getCell(i + iFix).value = h.label;
2141
- }
2142
- for (let i = 0; i < data.length; i++) {
2143
- let row = sheet.getRow(i + iFix + 1);
2144
- let item = data[i];
2145
- for (let i = 0; i < headers.length; i++) {
2146
- let h = headers[i];
2147
- let cell = row.getCell(i + 1);
2148
- let val = item[h.key];
2149
- if (!val) {
2150
- cell.value = "";
2151
- continue;
2152
- }
2153
- switch (h.type) {
2154
- case 'date':
2155
- // ExcelJS va di default in UTC quindi rischierebbe di tirare giù 2 ore ad ogni esportazione
2156
- // Bisogna aggiungere l'utc offset alla data attuale
2157
- let date = this.dates.getDateConvertion(val);
2158
- if (date) {
2159
- let correctedDate = date.add(date.utcOffset(), 'minute');
2160
- cell.value = correctedDate.toDate();
2161
- cell.numFmt = val.length > 10 ? 'dd/mm/yyyy h:m:s' : '';
2162
- }
2163
- break;
2164
- case 'number':
2165
- let converted = parseFloat(val.replace(',', '.'));
2166
- cell.value = isNaN(converted) ? "" : converted;
2167
- break;
2168
- default:
2169
- cell.value = val;
2170
- break;
2171
- }
2172
- }
2173
- }
2174
- let buffer = yield workbook.xlsx.writeBuffer();
2175
- let blob = new Blob([buffer], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;" });
2176
- let objectUrl = URL.createObjectURL(blob);
2177
- this.utiExts.fileDownload(objectUrl, fn.endsWith('.csv') ? fn.replace('.csv', '.xlsx') : fn.endsWith('.xlsx') ? fn : fn + ".xlsx");
2178
- });
2179
- }
2180
- /**
2181
- * Metodo che effettivamente genera gli header e i dati per l'esportazione con **ngx-csv**
2182
- *
2183
- * @param {any[]} items Oggetti da esportare
2184
- */
2185
- export(items, format, fileName, type, columnsFilter, genericHeaders) {
2186
- // Deepclone con assegnatura del tipo
2187
- var createdItems = items.map(t => this.utiExts.deepClone(t, type));
2188
- let headers = genericHeaders ? this.setupForGenericExport(createdItems, genericHeaders) : this.setupForExport(createdItems, columnsFilter);
2189
- (format == "CSV" ? this.exportCSV : this.exportExcel).bind(this)(fileName, headers, createdItems);
2190
- return headers;
2191
- }
2192
- }
2193
- ExportService.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.2.9", ngImport: i0, type: ExportService, deps: [{ token: DateService }, { token: UtilityService }, { token: i1.LocalizationService }], target: i0.ɵɵFactoryTarget.Injectable });
2194
- ExportService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.2.9", ngImport: i0, type: ExportService, providedIn: "root" });
2195
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.2.9", ngImport: i0, type: ExportService, decorators: [{
2196
- type: Injectable,
2197
- args: [{ providedIn: "root" }]
2198
- }], ctorParameters: function () { return [{ type: DateService }, { type: UtilityService }, { type: i1.LocalizationService }]; } });
2199
-
2200
- /**
2201
- * Service che fornisce un accesso base in lettura/scrittura sulla clipboard
2202
- */
2203
- class ClipboardService {
2204
- /**
2205
- * Costruttore
2206
- *
2207
- * @ignore
2208
- */
2209
- constructor(msgService, locProvider) {
2210
- this.msgService = msgService;
2211
- this.locProvider = locProvider;
2212
- /**
2213
- * Oggetto statico di localizzazione per i messaggi di questa Service
2214
- */
2215
- this.loc = {
2216
- "Unfortunately Firefox doesn't yet support direct Clipboard access if not via extensions, Please use Chrome to do this operation": {
2217
- 'en-US': "Unfortunately Firefox doesn't yet support direct Clipboard access if not via extensions, Please use Chrome to do this operation",
2218
- 'it-IT': "Mi dispiace ma Firefox non supporta l'accesso diretto alla Clipboard, se non attraverso le estensioni. Si prega di usare Chrome"
2219
- },
2220
- "Generic error during 'copy' command execution": {
2221
- 'en-US': "Generic error during 'copy' command execution",
2222
- 'it-IT': "Errore generico durante l'esecuzione del comando 'copy'"
2223
- },
2224
- "Error during Clipboard content read operation": {
2225
- 'en-US': "Error during Clipboard content read operation",
2226
- 'it-IT': "Errore nella lettura del contenuto della Clipboard"
2227
- },
2228
- "Error during Clipboard content copy operation": {
2229
- 'en-US': "Error during Clipboard content copy operation",
2230
- 'it-IT': "Errore nella scrittura del contenuto nella Clipboard"
2231
- },
2232
- "Please insert your clipboard content": {
2233
- 'en-US': "Please insert your clipboard content",
2234
- 'it-IT': "Si prega di incollare il contenuto della Clipboard"
2235
- },
2236
- "User input required": {
2237
- 'en-US': "User input required",
2238
- 'it-IT': "Richiesto Input utente"
2239
- },
2240
- "Your current browser does not support reading from the clipboard directly. Please paste your clipboard's content in this Input field and confirm the operation": {
2241
- 'en-US': "Your current browser does not support reading from the clipboard directly. Please paste your clipboard's content in this Input field and confirm the operation",
2242
- 'it-IT': "Il browser corrente non supporta la lettura diretta dei dati della Clipboard, si prega di effettuare un'incolla (CTRL + V) nella casella di testo e confermare l'operazione"
2243
- },
2244
- "Confirm": {
2245
- 'en-US': "Confirm",
2246
- 'it-IT': "Conferma"
2247
- },
2248
- "Cancel": {
2249
- 'en-US': "Cancel",
2250
- 'it-IT': "Annulla"
2251
- },
2252
- };
2253
- }
2254
- /**
2255
- * Prende il valore della clipboard.
2256
- * Si può specificare se ci si aspetta una lista o una matrice di valori in modo da ricevere già un risultato utilizzabile
2257
- *
2258
- * @param {'array' | 'matrix'} style Stile dell'output desiderato, se array o matrice
2259
- * @param {Function} valueFoundCallback Callback che questa funzione chiamerà una volta ottenuto i valori richiesti dalla clipboard
2260
- */
2261
- getClipboard(style, valueFoundCallback) {
2262
- return __awaiter(this, void 0, void 0, function* () {
2263
- let LOCALE = this.locProvider ? yield this.locProvider.Locale.pipe(first()).toPromise() : 'it-IT';
2264
- if (navigator.userAgent.indexOf("Firefox") != -1) {
2265
- swal.fire({
2266
- title: this.loc["User input required"][LOCALE],
2267
- text: this.loc["Your current browser does not support reading from the clipboard directly. Please paste your clipboard's content in this Input field and confirm the operation"][LOCALE],
2268
- input: 'textarea',
2269
- icon: "warning",
2270
- confirmButtonText: this.loc["Confirm"][LOCALE],
2271
- cancelButtonText: this.loc["Cancel"][LOCALE],
2272
- showCancelButton: true,
2273
- customClass: {
2274
- confirmButton: "btn btn-primary",
2275
- cancelButton: "btn btn-secondary app-margin-right-15",
2276
- container: "app-wrap",
2277
- },
2278
- reverseButtons: true,
2279
- allowOutsideClick: false,
2280
- inputValidator: (value) => {
2281
- if (!value)
2282
- return this.loc["Please insert your clipboard content"][LOCALE];
2283
- }
2284
- }).then(t => {
2285
- if (t.isConfirmed) {
2286
- console.log("[@esfaenza/extensions] Retrieving input data from user input");
2287
- this.doClipboardDataGet(t.value, style, valueFoundCallback);
2288
- }
2289
- });
2290
- return;
2291
- }
2292
- if (window.clipboardData) {
2293
- console.log("[@esfaenza/extensions] Found clipboardData");
2294
- let data = window.clipboardData.getData("Text");
2295
- this.doClipboardDataGet(data, style, valueFoundCallback);
2296
- }
2297
- else if (window.navigator.clipboard) {
2298
- console.log("[@esfaenza/extensions] Found navigator clipboard");
2299
- window.navigator.permissions.query({ name: 'clipboard-read' }).then(result => {
2300
- if (!(result.state === 'granted' || result.state === 'prompt')) {
2301
- console.error("[@esfaenza/extensions] Clipboard permission not granted");
2302
- if (valueFoundCallback)
2303
- valueFoundCallback([]);
2304
- return;
2305
- }
2306
- console.log("[@esfaenza/extensions] Clipboard permission granted, retrieving values");
2307
- window.navigator.clipboard.readText()
2308
- .then((t) => this.doClipboardDataGet(t, style, valueFoundCallback))
2309
- .catch((err) => this.msgService.simpleError(this.loc["Error during Clipboard content read operation"][LOCALE] + ": " + err));
2310
- });
2311
- }
2312
- });
2313
- }
2314
- /** @ignore */
2315
- doClipboardDataGet(clipboardText, style, valueFoundCallback) {
2316
- console.log("[@esfaenza/extensions] Retrieved clipboard values: " + clipboardText);
2317
- let value = style == "array" ? this.getClipboardLines(clipboardText) :
2318
- style == "matrix" ? this.getClipboardMatrix(clipboardText) : [];
2319
- console.log(`[@esfaenza/extensions] Adapted for ${style}: ${JSON.stringify(value)}`);
2320
- if (valueFoundCallback)
2321
- valueFoundCallback(value);
2322
- }
2323
- /**
2324
- * Ottiene il contenuto della clipboard diviso per righe (separate da newline)
2325
- *
2326
- * @param {string} data contenuto letto dalla clipboard
2327
- *
2328
- * @returns {string[]} Array contenente il testo preso dalla clipboard diviso per riga
2329
- */
2330
- getClipboardLines(data) {
2331
- let trimmedData = data.trim();
2332
- if (!trimmedData.includes("\r\n") && trimmedData.includes("\n"))
2333
- return trimmedData.split("\n");
2334
- return trimmedData.split("\r\n");
2335
- }
2336
- /**
2337
- * Ottiene il contenuto della clipboard diviso per righe (separate da newline) e colonne (separate da tab)
2338
- *
2339
- * @param {string} data contenuto letto dalla clipboard
2340
- *
2341
- * @returns {string[][]} Matrice contenente il testo preso dalla clipboard diviso per riga e colonna
2342
- */
2343
- getClipboardMatrix(data) {
2344
- var ret = [];
2345
- var rows = !data.includes("\r\n") && data.includes("\n") ? data.split("\n") : data.split("\r\n");
2346
- // A quanto pare ogni valore è separato da un \t... spero che sia uno standard di quando si copia da excel altrimenti ciao
2347
- for (let i = 0; i < rows.length; i++)
2348
- ret.push(rows[i].split('\t').map(t => t.trim()));
2349
- return ret;
2350
- }
2351
- /**
2352
- * Metodo che copia un testo all'interno della clipboard
2353
- *
2354
- * @param {string} text Testo da inserire nella clipboard
2355
- */
2356
- copyTextToClipboard(text) {
2357
- return __awaiter(this, void 0, void 0, function* () {
2358
- let LOCALE = this.locProvider ? yield this.locProvider.Locale.pipe(first()).toPromise() : 'it-IT';
2359
- var textArea = document.createElement("textarea");
2360
- //
2361
- // *** This styling is an extra step which is likely not required. ***
2362
- //
2363
- // Why is it here? To ensure:
2364
- // 1. the element is able to have focus and selection.
2365
- // 2. if element was to flash render it has minimal visual impact.
2366
- // 3. less flakyness with selection and copying which **might** occur if
2367
- // the textarea element is not visible.
2368
- //
2369
- // The likelihood is the element won't even render, not even a flash,
2370
- // so some of these are just precautions. However in IE the element
2371
- // is visible whilst the popup box asking the user for permission for
2372
- // the web page to copy to the clipboard.
2373
- //
2374
- // Place in top-left corner of screen regardless of scroll position.
2375
- textArea.style.position = "fixed";
2376
- textArea.style.top = "0";
2377
- textArea.style.left = "0";
2378
- // Ensure it has a small width and height. Setting to 1px / 1em
2379
- // doesn't work as this gives a negative w/h on some browsers.
2380
- textArea.style.width = "2em";
2381
- textArea.style.height = "2em";
2382
- // We don't need padding, reducing the size if it does flash render.
2383
- textArea.style.padding = "0";
2384
- // Clean up any borders.
2385
- textArea.style.border = "none";
2386
- textArea.style.outline = "none";
2387
- textArea.style.boxShadow = "none";
2388
- // Avoid flash of white box if rendered for any reason.
2389
- textArea.style.background = "transparent";
2390
- textArea.value = text;
2391
- document.body.appendChild(textArea);
2392
- textArea.focus();
2393
- textArea.select();
2394
- try {
2395
- var successful = document.execCommand("copy");
2396
- if (!successful)
2397
- this.msgService.simpleError(this.loc["Generic error during 'copy' command execution"][LOCALE]);
2398
- }
2399
- catch (err) {
2400
- this.msgService.simpleError(this.loc["Error during Clipboard content copy operation"][LOCALE] + ": " + err);
2401
- }
2402
- document.body.removeChild(textArea);
2403
- });
2404
- }
2405
- }
2406
- ClipboardService.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.2.9", ngImport: i0, type: ClipboardService, deps: [{ token: MessageService }, { token: i1.BaseLocalization, optional: true }], target: i0.ɵɵFactoryTarget.Injectable });
2407
- ClipboardService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.2.9", ngImport: i0, type: ClipboardService, providedIn: "root" });
2408
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.2.9", ngImport: i0, type: ClipboardService, decorators: [{
2409
- type: Injectable,
2410
- args: [{ providedIn: "root" }]
2411
- }], ctorParameters: function () {
2412
- return [{ type: MessageService }, { type: i1.BaseLocalization, decorators: [{
2413
- type: Optional
2414
- }] }];
2415
- } });
2416
-
2417
- /**
2418
- * Classe che rappresenta una risposta ricevuta da un Backend
2419
- */
2420
- class CallResult {
2421
- }
2422
-
2423
- /**
2424
- * Header per il file CSV che sta venendo generato
2425
- */
2426
- class CsvHeaders {
2427
- }
2428
-
2429
- /**
2430
- * Rappresentazione di un oggetto generico
2431
- */
2432
- class GenericItem {
2433
- }
2434
-
2435
- /** Enumeratore dei tipi di messaggio che i moduli esterni possono contattare sull'applicazione principale */
2436
- var InboundMessageTypes;
2437
- (function (InboundMessageTypes) {
2438
- /** Evento di navigazione */
2439
- InboundMessageTypes[InboundMessageTypes["Navigation"] = 0] = "Navigation";
2440
- })(InboundMessageTypes || (InboundMessageTypes = {}));
2441
-
2442
- /** Classe che rappresenta un generico messaggio scambiato fra applicazione e moduli */
2443
- class InterComMessage {
2444
- /**
2445
- * Costruttore
2446
- *
2447
- * @param type Tipo di messaggio
2448
- * @param message Contenuto del messaggio
2449
- */
2450
- constructor(type, message) {
2451
- this.type = type;
2452
- this.message = message;
2453
- }
2454
- }
2455
-
2456
- // Angular
2457
- /** Service che si occupa di gestire la comunicazione fra i moduli interni ed esterni dell'applicativo */
2458
- class InterComService {
2459
- constructor() {
2460
- /** Messaggi in uscita, uno per ogni recipient registratosi dall'entrypoint **register** */
2461
- this.outbounds = {};
2462
- /** Messaggi in entrata, unico per applicazione principale */
2463
- this.inbounds = new Subject();
2464
- }
2465
- /**
2466
- * Metodo che permette di inviare un messaggio dall'applicazione ad un modulo esterno o viceversa
2467
- *
2468
- * @param {any} messageType Tipologia di messaggio. Sarà di tipo **InboundMessageTypes** per tutti i messaggi inbound, dinamico per tutti i mesaggi outbound (il tipo dipenderà dagli enum dei messaggi dei moduli esterni)
2469
- * @param {any} message Messaggio da inviare che può essere un dto in casi complessi ma dovrà essere gestito a dovere lato implementativo
2470
- * @param {string} recipient Destinatario del messaggio. Per i messaggi inbound dev'essere lasciato vuoto, per i messaggi outbound sarà valorizzato alla chiave del modulo a cui si vuole inviare il messaggio
2471
- */
2472
- send(messageType, message, recipient) {
2473
- let msg = new InterComMessage(messageType, message);
2474
- // Se non c'è un recipient significa che è un modulo esterno che invia messaggi al modulo main (quindi messaggio in entrata - inbound)
2475
- // Altrimenti significa che è il modulo main ad inviare messaggi ai moduli esterni (messaggio in uscita - outbound)
2476
- if (!recipient) {
2477
- this.inbounds.next(msg);
2478
- }
2479
- else {
2480
- if (!this.outbounds[recipient])
2481
- console.warn("@esfaenza/extensions - InterComService: Impossibile inviare il messaggio al recipient " + recipient + " assicurarsi che il modulo sia caricato e che effettui la chiamata al metodo 'regisster'");
2482
- else
2483
- this.outbounds[recipient].next(msg);
2484
- }
2485
- }
2486
- /**
2487
- * Permette di registrare un modulo esterno alla lista dei moduli in listening sulla coda di messaggi
2488
- *
2489
- * @param {string} key Chiave del modulo da registrare. Tutti i messaggi inbound saranno inviati dall'applicazione principale su questa chiave
2490
- */
2491
- register(key) {
2492
- if (this.outbounds[key])
2493
- throw "@esfaenza/extensions - InterComService: Impossibile registrare più volte lo stesso modulo";
2494
- this.outbounds[key] = new Subject();
2495
- }
2496
- }
2497
- InterComService.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.2.9", ngImport: i0, type: InterComService, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
2498
- InterComService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.2.9", ngImport: i0, type: InterComService, providedIn: "root" });
2499
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.2.9", ngImport: i0, type: InterComService, decorators: [{
2500
- type: Injectable,
2501
- args: [{ providedIn: "root" }]
2502
- }] });
2503
-
2504
- /*
2505
- * Public API Surface of extensions
2506
- */
2507
-
2508
- /**
2509
- * Generated bundle index. Do not edit.
2510
- */
2511
-
2512
- export { APPSEARCH_PREFIX, AppEmbeddingExtensions, BaseExtensionsService, CallResult, ClipboardService, CsvHeaders, DateService, EXT_ALLOW_UTC, EXT_DEBUG_MODE, Export, ExportAs, ExportDictionary, ExportList, ExportLocalization, ExportService, ExtensionsModule, GenericItem, HashingService, InboundMessageTypes, InterComMessage, InterComService, LocDatePipe, MessageService, UtilityService };
2513
- //# sourceMappingURL=esfaenza-extensions.mjs.map