@esfaenza/extensions 15.2.25 → 15.2.26

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