uni-manager 0.0.79 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,7 +1,7 @@
1
1
  import { BehaviorSubject } from 'rxjs/internal/BehaviorSubject';
2
2
  import { map } from 'rxjs/internal/operators/map';
3
3
  import { tap } from 'rxjs/internal/operators/tap';
4
- import { isHttpErrorBody, UniHttpError } from 'uni-error';
4
+ import { UniToastManager as UniToastManager$1 } from 'uni-manager/toast';
5
5
  import isEqual from 'lodash-es/isEqual';
6
6
  import { defer } from 'rxjs/internal/observable/defer';
7
7
  import { from } from 'rxjs/internal/observable/from';
@@ -9,6 +9,7 @@ import { timer } from 'rxjs/internal/observable/timer';
9
9
  import { catchError } from 'rxjs/internal/operators/catchError';
10
10
  import { distinctUntilChanged } from 'rxjs/internal/operators/distinctUntilChanged';
11
11
  import { finalize } from 'rxjs/internal/operators/finalize';
12
+ import { UniErrorManager as UniErrorManager$1 } from 'uni-manager/error';
12
13
  import { EMPTY } from 'rxjs/internal/observable/empty';
13
14
  import { of } from 'rxjs/internal/observable/of';
14
15
  import { throwError } from 'rxjs/internal/observable/throwError';
@@ -16,6 +17,9 @@ import { concatMap } from 'rxjs/internal/operators/concatMap';
16
17
  import { exhaustMap } from 'rxjs/internal/operators/exhaustMap';
17
18
  import { mergeMap } from 'rxjs/internal/operators/mergeMap';
18
19
  import { switchMap } from 'rxjs/internal/operators/switchMap';
20
+ import { UniHttpError, isHttpErrorBody } from 'uni-error/http';
21
+ import { UniTypeDateManager as UniTypeDateManager$1 } from 'uni-manager/type';
22
+ import { UniLocaleManager as UniLocaleManager$1 } from 'uni-manager/locale';
19
23
 
20
24
  class UniErrorManager {
21
25
  /* ------------------------------------------------------------------------------- */
@@ -184,401 +188,6 @@ var EmitValueMode;
184
188
  EmitValueMode[EmitValueMode["EVERY_TIME"] = 1] = "EVERY_TIME";
185
189
  })(EmitValueMode || (EmitValueMode = {}));
186
190
 
187
- class UniLocaleManager {
188
- /* ------------------------------------------------------------------------------- */
189
- /* ----------------------------------- Config ------------------------------------ */
190
- /* ------------------------------------------------------------------------------- */
191
- /** Codice lingua corrente (es. 'it-IT', 'en-US') usato per formattare date e numeri */
192
- static { this._locale = navigator.language ?? 'en-US'; }
193
- /** Elenco dei codici lingua supportati dall'applicazione (es. ['it-IT', 'en-US']) */
194
- static { this._localesSupported = []; }
195
- /** Prefisso globale applicato a tutte le chiavi di traduzione (es. 'APP_') */
196
- static { this._prefix = undefined; }
197
- /* ------------------------------------------------------------------------------- */
198
- /* --------------------------------- Metodi: get --------------------------------- */
199
- /* ------------------------------------------------------------------------------- */
200
- /** Restituisce il codice lingua corrente */
201
- static get locale() {
202
- return this._locale;
203
- }
204
- /** Restituisce l'array contenente tutti i codici locale supportati.*/
205
- static get localesSupported() {
206
- return this._localesSupported;
207
- }
208
- /** Restituisce solo la lingua (es. 'it') */
209
- static get language() {
210
- return this._locale.split('-')[0];
211
- }
212
- /** Restituisce solo il paese (es. 'IT') */
213
- static get region() {
214
- const parts = this._locale.split('-');
215
- return parts.length > 1 ? parts[1] : '';
216
- }
217
- /* ------------------------------------------------------------------------------- */
218
- /* ------------------------------------ Store ------------------------------------ */
219
- /* ------------------------------------------------------------------------------- */
220
- /** Store privato (Subject) */
221
- static { this.store = new BehaviorSubject({}); }
222
- /** Store pubblico (Observable) */
223
- static { this.store$ = this.store.asObservable(); }
224
- /** Ottiene il dizionario attuale senza sottoscrizione */
225
- static get currentValue() {
226
- return this.store.getValue();
227
- }
228
- /* ------------------------------------------------------------------------------- */
229
- /* -------------------------------- Metodi: setup -------------------------------- */
230
- /* ------------------------------------------------------------------------------- */
231
- /**
232
- * Inizializza la configurazione di rete del manager.
233
- * Deve essere chiamato prima di effettuare qualsiasi richiesta HTTP.
234
- */
235
- static setup(locale, prefix) {
236
- this._locale = locale ?? 'en-US';
237
- this._prefix = prefix;
238
- }
239
- /** Imposta l'elenco dei codici lingua supportati dall'applicazione */
240
- static setLocalesSupported(locales) {
241
- this._localesSupported = locales ?? [];
242
- }
243
- /**
244
- * Aggiorna lo store locale con il dizionario delle traduzioni fornito.
245
- * Se viene passato undefined, lo store viene inizializzato come oggetto vuoto.
246
- */
247
- static setTranslations(translations) {
248
- this.store.next(translations ?? {});
249
- }
250
- /* ------------------------------------------------------------------------------- */
251
- /* ----------------------------- Metodi: traduzioni ------------------------------ */
252
- /* ------------------------------------------------------------------------------- */
253
- /**
254
- * Traduce una label in base al dizionario caricato.
255
- * Gestisce la composizione della chiave, i parametri dinamici (interpolazione) e il fallback.
256
- */
257
- static translate(key, prefix = 'lbl', interpolationParams) {
258
- if (!key)
259
- return '-';
260
- // Costruzione chiave: prefissoGlobale + prefissoLocale + LabelConInizialeMaiuscola
261
- const keyParts = key.trim().split(/(?=[A-Z])/);
262
- const rootKeyParts = keyParts.filter((p) => p.toLowerCase() !== prefix.toLowerCase());
263
- const cleanKey = rootKeyParts.length > 0 ? rootKeyParts.join('') : undefined;
264
- const capitalizedKey = cleanKey ? cleanKey.charAt(0).toUpperCase() + cleanKey.slice(1) : '';
265
- const finalKey = `${this._prefix ?? ''}${prefix}${capitalizedKey}`;
266
- // Cerca la chiave in minuscolo (standardizzazione)
267
- let translation = this.currentValue?.[finalKey.toLowerCase()];
268
- // Log e fallback se la traduzione manca
269
- if (!translation) {
270
- console.warn(`Translation missing for key: ${finalKey}`);
271
- return `🔑 ${finalKey}`;
272
- }
273
- // Interpolazione variabili
274
- if (interpolationParams) {
275
- for (const [key, value] of Object.entries(interpolationParams)) {
276
- const displayValue = value instanceof Date ? value.toLocaleDateString(this._locale) : String(value);
277
- translation = translation.replaceAll(`{{${key}}}`, displayValue);
278
- }
279
- }
280
- return translation;
281
- }
282
- /**
283
- * Traduce una stringa che contiene parametri separati da un carattere specifico.
284
- * Supporta ora un numero arbitrario di parametri in formato "label/param1/param2"
285
- * o semplicemente "label".
286
- */
287
- static translateInlineParams(keyWithParams, splitChar) {
288
- if (!keyWithParams)
289
- return '-';
290
- const [label, ...params] = keyWithParams.split(splitChar);
291
- // Se non ci sono parametri, esegui una traduzione semplice
292
- if (params.length === 0) {
293
- return this.translate(label);
294
- }
295
- // Mappa i parametri in un oggetto di interpolazione: { inlineParam0: val, inlineParam1: val, ... }
296
- const interpolationParameters = {};
297
- for (const [index, val] of params.entries()) {
298
- interpolationParameters[`param${index}`] = val;
299
- }
300
- return this.translate(label, 'lbl', interpolationParameters);
301
- }
302
- /* ------------------------------------------------------------------------------- */
303
- /* ------------------------------- Metodi: numeri -------------------------------- */
304
- /* ------------------------------------------------------------------------------- */
305
- /**
306
- * Converte un valore numerico in una stringa formattata secondo il locale impostato.
307
- * Disabilita i separatori delle migliaia e forza un numero fisso di decimali.
308
- */
309
- static toStringNumber(value, decimal) {
310
- return new Intl.NumberFormat(this._locale, {
311
- useGrouping: true,
312
- minimumFractionDigits: decimal,
313
- maximumFractionDigits: decimal,
314
- numberingSystem: 'latn',
315
- }).format(value);
316
- }
317
- /* ------------------------------------------------------------------------------- */
318
- /* -------------------------------- Metodi: date --------------------------------- */
319
- /* ------------------------------------------------------------------------------- */
320
- /**
321
- * Formatta una data o una stringa in base al locale corrente.
322
- * Gestisce tre modalità predefinite (date, time, full) e accetta opzioni personalizzate Intl.
323
- */
324
- static toDate(date, mode = 'full', force) {
325
- const dt = new Date(date);
326
- // Controllo: validità data
327
- if (Number.isNaN(dt.getTime())) {
328
- console.error(`[UniLocaleManager] Data non valida fornita a formatDateTime:`, date);
329
- return '';
330
- }
331
- // Controllo: locale da forzare
332
- const locale = force && this._locale.startsWith(force.oldLang) ? force.newLocale : this._locale;
333
- switch (mode) {
334
- case 'date': {
335
- return dt.toLocaleDateString(locale);
336
- }
337
- case 'time': {
338
- return dt.toLocaleTimeString(locale);
339
- }
340
- case 'full': {
341
- return dt.toLocaleString(locale);
342
- }
343
- }
344
- }
345
- }
346
-
347
- /* eslint-disable @typescript-eslint/no-explicit-any */
348
- class UniToastManager {
349
- /* ------------------------------------------------------------------------------- */
350
- /* -------------------------------- Metodi: setup -------------------------------- */
351
- /* ------------------------------------------------------------------------------- */
352
- /**
353
- * Inizializza il manager con una serie di operazioni
354
- */
355
- static setup(operations) {
356
- this.manager = operations;
357
- }
358
- /* ------------------------------------------------------------------------------- */
359
- /* -------------------------------- Metodi: show --------------------------------- */
360
- /* ------------------------------------------------------------------------------- */
361
- /**
362
- * Mostra un toast di successo basato su una risposta HTTP e una label di traduzione.
363
- */
364
- static show(config) {
365
- /* Messaggio tradotto */
366
- const msg = UniLocaleManager.translate(config.label, 'toast', config.params);
367
- const msgFixed = `${config.prefix ?? ''}${msg}${config.suffix ?? ''}`;
368
- this.manager[config.type ?? 'info'](msgFixed, config);
369
- }
370
- /**
371
- * Mostra un toast di successo basato su una risposta HTTP e una label di traduzione.
372
- */
373
- static showHttp(config, res) {
374
- const { interpolationParams, resParams, resLengthParam, formatters } = config;
375
- /* Parametri statici di base */
376
- const allParams = { ...interpolationParams };
377
- /* Config parametri risposta: estrazione parametri dalla risposta (se esiste ed è un oggetto) */
378
- if (resParams?.length && res && typeof res === 'object') {
379
- for (const param of resParams ?? []) {
380
- if (param in res)
381
- continue;
382
- // Se esiste un formatter per questa chiave lo si usa, altrimenti valore grezzo
383
- const rawValue = res[param];
384
- allParams[param] = formatters?.[param] ? formatters[param](rawValue) : rawValue;
385
- }
386
- }
387
- /* Config parametro lunghezza risposta: conteggio array */
388
- if (resLengthParam && Array.isArray(res)) {
389
- allParams[resLengthParam] = res.length;
390
- }
391
- /* Messaggio tradotto */
392
- this.show({ ...config, params: allParams });
393
- }
394
- }
395
-
396
- async function execute(url, init) {
397
- try {
398
- /* Esegue chiamata http */
399
- const res = await fetch(url, init);
400
- /* Nessun contenuto cons status 204 */
401
- if (res.status === 204) {
402
- return undefined;
403
- }
404
- /* Recupero se è un json */
405
- const contentType = res.headers.get('content-type') ?? '';
406
- const isJson = contentType.startsWith('application/json');
407
- /* Errore HTTP (quindi risposta ricevuta ma non ok) */
408
- if (!res.ok) {
409
- let errorBody;
410
- try {
411
- /* Clona risposta solo se c'è errore, per leggerla senza consumare la originale */
412
- const resClone = res.clone();
413
- /* Aggiorna body con struttura errore */
414
- errorBody = isJson ? await resClone.json() : await resClone.text();
415
- }
416
- catch {
417
- errorBody = await res.text();
418
- }
419
- if (isHttpErrorBody(errorBody)) {
420
- const type = errorBody.exceptionType.includes('HttpRequestException') ? 'be' : 'ice';
421
- throw new UniHttpError(type, res.status, url, errorBody);
422
- }
423
- else {
424
- const error = new Error(`HTTP ${res.statusText}`);
425
- throw new UniHttpError('base', res.status, url, {
426
- exceptionMessage: error.message,
427
- exceptionType: 'ErrorBase',
428
- message: error.message,
429
- stackTrace: error.stack ?? '',
430
- });
431
- }
432
- }
433
- /* Risposta ok */
434
- return res;
435
- }
436
- catch (error) {
437
- if (error instanceof TypeError) {
438
- throw new UniHttpError('network', -1, url, {
439
- exceptionMessage: `${error.name}: ${error.message}\n${error.stack}`,
440
- exceptionType: error.name,
441
- message: error.message,
442
- stackTrace: error.stack ?? '',
443
- });
444
- }
445
- // Fallback
446
- throw error;
447
- }
448
- }
449
- async function executeHttp(url, init) {
450
- /* Esegue la chiamata HTTP e restituisce il corpo decodificato come JSON */
451
- const res = await execute(url, init);
452
- if (!res)
453
- return undefined;
454
- /* Estrae il contenuto come testo */
455
- const text = await res.text();
456
- /* Controllo: se il testo è vuoto (''), ritorna undefined */
457
- if (!text || text.trim().length === 0) {
458
- return undefined;
459
- }
460
- /* Parsa manualmente il testo, dato che lo stream è stato già letto */
461
- return JSON.parse(text);
462
- }
463
- async function executeBlob(url, init) {
464
- /* Esegue la chiamata HTTP */
465
- const res = await execute(url, init);
466
- if (!res)
467
- return undefined;
468
- /* Estrae il contenuto come Blob direttamente */
469
- const blob = await res.blob();
470
- /* Controllo: se il blob è vuoto (0 byte), ritorna undefined */
471
- if (blob.size === 0) {
472
- return undefined;
473
- }
474
- /* Estrae il nome del file dall'header */
475
- const disposition = res.headers.get('Content-Disposition');
476
- let fileName = 'download.pdf'; // Fallback di default
477
- if (disposition) {
478
- const matches = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/.exec(disposition);
479
- if (!!matches && matches[1]) {
480
- fileName = matches[1].replaceAll(/['"]/g, '');
481
- }
482
- }
483
- /* Genera l'URL temporaneo dal blob */
484
- const fileUrl = URL.createObjectURL(blob);
485
- return { url: fileUrl, name: fileName };
486
- }
487
-
488
- /**
489
- * Aggiunge una nuova ref nello store solo se non è già presente.
490
- * Se l'ID esiste già, l'operazione viene interrotta per preservare il dato originale.
491
- */
492
- function add(id, url, type) {
493
- // Recupera l'ultimo stato (Map)
494
- const oldMap = UniHttpManager.currentValue;
495
- // Controllo: se è presente l'item allora termina
496
- if (oldMap.get(id))
497
- return;
498
- // Crea il nuovo oggetto
499
- const newItemMap = {
500
- type,
501
- lineId: undefined,
502
- url,
503
- hasError: false,
504
- pendingCount: 0,
505
- };
506
- // Crea una nuova istanza della Map
507
- const newMap = new Map(oldMap);
508
- newMap.set(id, newItemMap);
509
- // Aggiorna il nuovo stato notificando l'observer
510
- UniHttpManager.store.next(newMap);
511
- }
512
- /**
513
- * Rimuove un http ref tramite ID
514
- */
515
- function remove(id) {
516
- // Recupera l'ultimo stato (Map)
517
- const oldMap = UniHttpManager.currentValue;
518
- // Controllo: se non è presente l'item allora termina
519
- if (!oldMap.has(id))
520
- return;
521
- // Aggiorna store
522
- const newMap = new Map(oldMap);
523
- newMap.delete(id);
524
- UniHttpManager.store.next(newMap);
525
- }
526
- /**
527
- * Aggiorna il contatore delle chiamate pendenti per una specifica ref.
528
- * Incrementa o decrementa 'pendingCount' garantendo che non scenda mai sotto lo zero.
529
- * Se la ref non esiste, l'operazione viene ignorata.
530
- */
531
- function updateIsLoading(id, delta) {
532
- // Recupera l'ultimo stato (Map)
533
- const oldMap = UniHttpManager.currentValue;
534
- // Controllo: se non è presente l'item allora termina
535
- const oldItem = oldMap.get(id);
536
- if (!oldItem)
537
- return;
538
- // Aggiorna l'oggetto
539
- const newItemMap = {
540
- ...oldItem,
541
- pendingCount: Math.max(0, oldItem.pendingCount + delta),
542
- };
543
- // Crea una nuova istanza della Map
544
- const newMap = new Map(oldMap);
545
- newMap.set(id, newItemMap);
546
- // Aggiorna il nuovo stato notificando l'observer
547
- UniHttpManager.store.next(newMap);
548
- }
549
- /**
550
- * Aggiorna lo stato di errore per una specifica ref.
551
- * Se il valore di 'hasError' è identico a quello attuale o se la ref non esiste,
552
- * l'operazione viene interrotta per evitare aggiornamenti inutili.
553
- */
554
- function updateHasError(id, hasError) {
555
- // Recupera l'ultimo stato (Map)
556
- const oldMap = UniHttpManager.currentValue;
557
- // Controllo: se non è presente l'item allora termina
558
- const oldItem = oldMap.get(id);
559
- if (!oldItem)
560
- return;
561
- // Controllo: se con lo stesso valore, salta
562
- if (oldItem.hasError === hasError)
563
- return;
564
- // Aggiorna l'oggetto
565
- const newItemMap = { ...oldItem, hasError };
566
- // Crea una nuova istanza della Map
567
- const newMap = new Map(oldMap);
568
- newMap.set(id, newItemMap);
569
- // Aggiorna il nuovo stato notificando l'observer
570
- UniHttpManager.store.next(newMap);
571
- }
572
- /**
573
- * Svuota completamente la lista delle refs
574
- */
575
- function removeAll() {
576
- // Crea una nuova istanza della Map
577
- const newMap = new Map();
578
- // Aggiorna il nuovo stato notificando l'observer
579
- UniHttpManager.store.next(newMap);
580
- }
581
-
582
191
  function operatorHandler(operator) {
583
192
  // Gestione della concorrenza in base al parametro
584
193
  switch (operator) {
@@ -612,18 +221,23 @@ function errorHandler(err, errorMode, ref) {
612
221
  return EMPTY;
613
222
  }
614
223
  case PollingErrorMode.IGNORE_WITH_ERROR: {
615
- {
616
- UniErrorManager.add(ref, err);
617
- return of();
618
- }
224
+ UniErrorManager$1.add(ref, err);
225
+ return of();
619
226
  }
620
227
  case PollingErrorMode.STOP: {
621
- UniErrorManager.add(ref, err);
228
+ UniErrorManager$1.add(ref, err);
622
229
  return throwError(() => err);
623
230
  }
624
231
  }
625
232
  }
626
233
 
234
+ /* ------------------------------------------------------------------------------- */
235
+ /* -------------------------------- Funzioni Core RxJS -------------------------- */
236
+ /* ------------------------------------------------------------------------------- */
237
+ /**
238
+ * Gestisce l'esecuzione e il ciclo di vita di una singola richiesta HTTP.
239
+ * Si occupa della registrazione della reference, della gestione dei loader, dei toast di successo e dell'intercettazione degli errori.
240
+ */
627
241
  function http$(url, refType, config, promiseFactory) {
628
242
  /* Recupero configurazione */
629
243
  const { ref, toast, hasLoader } = config;
@@ -645,7 +259,7 @@ function http$(url, refType, config, promiseFactory) {
645
259
  next: (res) => {
646
260
  /* Mostra toast (se presente) */
647
261
  if (toast) {
648
- UniToastManager.showHttp(toast, res);
262
+ UniToastManager$1.showHttp(toast, res);
649
263
  }
650
264
  },
651
265
  }), catchError((err) => {
@@ -659,6 +273,10 @@ function http$(url, refType, config, promiseFactory) {
659
273
  }));
660
274
  });
661
275
  }
276
+ /**
277
+ * Avvia e coordina un ciclo di polling a intervalli regolari.
278
+ * Gestisce la concorrenza tramite operatori RxJS configurabili, la rimozione dei popup, di errore nelle iterazioni successive e i comportamenti custom al primo avvio.
279
+ */
662
280
  function httpPolling$(url, config, promiseFactory) {
663
281
  /* Recupero configurazione */
664
282
  const { interval, ref, operator = MapOperator.SWITCH_MAP, errorMode = PollingErrorMode.STOP, emitValueMode = EmitValueMode.ON_NEW_DATA, firstIteration, } = config;
@@ -680,14 +298,14 @@ function httpPolling$(url, config, promiseFactory) {
680
298
  return defer(() => {
681
299
  const http$ = from(promiseFactory());
682
300
  return http$.pipe(tap((res) => {
683
- /* Rimozione popup di errore nel caso di errorMode = 'IGNORE_WITH_ERROR' */
301
+ /* Meccanismo di ripristino automatico: se il polling torna in salute, cancella l'errore dallo store e nasconde i relativi messaggi a schermo */
684
302
  if (errorMode === PollingErrorMode.IGNORE_WITH_ERROR) {
685
303
  updateHasError(ref, false);
686
- UniErrorManager.remove(ref);
304
+ UniErrorManager$1.remove(ref);
687
305
  }
688
306
  /* Prima risposta */
689
307
  if (index === 0 && firstIteration?.toast) {
690
- UniToastManager.showHttp(firstIteration.toast, res);
308
+ UniToastManager$1.showHttp(firstIteration.toast, res);
691
309
  }
692
310
  }), catchError((err) => {
693
311
  /* Gestione errore */
@@ -704,148 +322,193 @@ function httpPolling$(url, config, promiseFactory) {
704
322
  ? source$.pipe(distinctUntilChanged((prev, cur) => isEqual(prev, cur)))
705
323
  : source$;
706
324
  }
707
-
325
+ /* ------------------------------------------------------------------------------- */
326
+ /* ------------------------------------ Utils ------------------------------------ */
327
+ /* ------------------------------------------------------------------------------- */
328
+ /**
329
+ * Aggiunge una nuova ref nello store solo se non è già presente.
330
+ * Se l'ID esiste già, l'operazione viene interrotta per preservare il dato originale.
331
+ */
332
+ function add(id, url, type) {
333
+ // Recupera l'ultimo stato (Map)
334
+ const oldMap = UniHttpManager.currentValue;
335
+ // Controllo: se è presente l'item allora termina
336
+ if (oldMap.get(id))
337
+ return;
338
+ // Crea il nuovo oggetto
339
+ const newItemMap = {
340
+ type,
341
+ lineId: undefined,
342
+ url,
343
+ hasError: false,
344
+ pendingCount: 0,
345
+ };
346
+ // Crea una nuova istanza della Map
347
+ const newMap = new Map(oldMap);
348
+ newMap.set(id, newItemMap);
349
+ // Aggiorna il nuovo stato notificando l'observer
350
+ UniHttpManager.store.next(newMap);
351
+ }
352
+ /**
353
+ * Rimuove un http ref tramite ID
354
+ */
355
+ function remove(id) {
356
+ // Recupera l'ultimo stato (Map)
357
+ const oldMap = UniHttpManager.currentValue;
358
+ // Controllo: se non è presente l'item allora termina
359
+ if (!oldMap.has(id))
360
+ return;
361
+ // Aggiorna store
362
+ const newMap = new Map(oldMap);
363
+ newMap.delete(id);
364
+ UniHttpManager.store.next(newMap);
365
+ }
708
366
  /**
709
- * Classe di utilità per la gestione e formattazione delle date.
710
- * Fornisce metodi per convertire in modo sicuro valori di tipo Date, stringa o null in formati standardizzati.
367
+ * Aggiorna il contatore delle chiamate pendenti per una specifica ref.
368
+ * Incrementa o decrementa 'pendingCount' garantendo che non scenda mai sotto lo zero.
369
+ * Se la ref non esiste, l'operazione viene ignorata.
711
370
  */
712
- class UniTypeDateManager {
713
- static toYYYYMMDD(date) {
714
- if (!date)
715
- return '';
716
- const d = new Date(date);
717
- if (Number.isNaN(d.getTime()))
718
- return '';
719
- const year = d.getFullYear();
720
- const month = String(d.getMonth() + 1).padStart(2, '0');
721
- const day = String(d.getDate()).padStart(2, '0');
722
- return `${year}-${month}-${day}`;
723
- }
371
+ function updateIsLoading(id, delta) {
372
+ // Recupera l'ultimo stato (Map)
373
+ const oldMap = UniHttpManager.currentValue;
374
+ // Controllo: se non è presente l'item allora termina
375
+ const oldItem = oldMap.get(id);
376
+ if (!oldItem)
377
+ return;
378
+ // Aggiorna l'oggetto
379
+ const newItemMap = {
380
+ ...oldItem,
381
+ pendingCount: Math.max(0, oldItem.pendingCount + delta),
382
+ };
383
+ // Crea una nuova istanza della Map
384
+ const newMap = new Map(oldMap);
385
+ newMap.set(id, newItemMap);
386
+ // Aggiorna il nuovo stato notificando l'observer
387
+ UniHttpManager.store.next(newMap);
724
388
  }
725
-
726
389
  /**
727
- * Utility per la gestione e formattazione di valori numerici.
390
+ * Aggiorna lo stato di errore per una specifica ref.
391
+ * Se il valore di 'hasError' è identico a quello attuale o se la ref non esiste,
392
+ * l'operazione viene interrotta per evitare aggiornamenti inutili.
728
393
  */
729
- class UniTypeNumberManager {
730
- /** Applica il padding a un numero o una stringa */
731
- static toPad(value, count, character = '0') {
732
- // Se il valore è null/undefined, riempiamo l'intero campo con il carattere scelto
733
- if (value === null || value === undefined) {
734
- return ''.padStart(count, character);
735
- }
736
- // Convertiamo in stringa e applichiamo il padding
737
- return value.toString().padStart(count, character);
738
- }
739
- /** Formatta un numero in una versione leggibile (es: 1000 -> 1K, 1000000 -> 1M) */
740
- static toTruncateAndAdUdm(value, decimalDigits = 0, maxIntegerDigits = 3) {
741
- // Nessun limite impostato o numero inferiore alla soglia definita
742
- if (Math.abs(value) < Math.pow(10, maxIntegerDigits)) {
743
- return value.toFixed(decimalDigits);
744
- }
745
- // Definizione delle scale di riduzione per grandi numeri
746
- const scales = [
747
- { threshold: 1e12, suffix: 'T' }, // Trilioni
748
- { threshold: 1e9, suffix: 'B' }, // Miliardi
749
- { threshold: 1e6, suffix: 'M' }, // Milioni
750
- { threshold: 1e3, suffix: 'K' }, // Migliaia
751
- ];
752
- // Itera dalla scala più grande alla più piccola per trovare la soglia corretta
753
- for (const { threshold, suffix } of scales) {
754
- if (Math.abs(value) >= threshold) {
755
- const reduced = value / threshold;
756
- // parseFloat(toFixed()) rimuove gli zeri decimali superflui (es: 1.50 -> 1.5)
757
- // aggiungendo poi il relativo suffisso (K, M, B, T)
758
- return Number.parseFloat(reduced.toFixed(decimalDigits)).toString() + suffix;
759
- }
760
- }
761
- // Fallback: se il numero è grande ma non rientra nelle scale (caso raro con la logica attuale)
762
- return value.toFixed(decimalDigits);
763
- }
394
+ function updateHasError(id, hasError) {
395
+ // Recupera l'ultimo stato (Map)
396
+ const oldMap = UniHttpManager.currentValue;
397
+ // Controllo: se non è presente l'item allora termina
398
+ const oldItem = oldMap.get(id);
399
+ if (!oldItem)
400
+ return;
401
+ // Controllo: se con lo stesso valore, salta
402
+ if (oldItem.hasError === hasError)
403
+ return;
404
+ // Aggiorna l'oggetto
405
+ const newItemMap = { ...oldItem, hasError };
406
+ // Crea una nuova istanza della Map
407
+ const newMap = new Map(oldMap);
408
+ newMap.set(id, newItemMap);
409
+ // Aggiorna il nuovo stato notificando l'observer
410
+ UniHttpManager.store.next(newMap);
764
411
  }
765
-
766
412
  /**
767
- * Utility per la manipolazione di stringhe
413
+ * Svuota completamente la lista delle refs
768
414
  */
769
- class UniTypeStringManager {
770
- /** Converte una stringa in formato lblPascalCase (es. "user_id" -> "lblUserId") */
771
- static toLabelize(key, prefix = 'lbl') {
772
- // Se vuoto restituisce vuoto
773
- if (!key)
774
- return '';
775
- // Pulizia chiave
776
- const fixedKey = key.trim();
777
- // Unisce il prefisso
778
- return prefix + this.toPascalCase(fixedKey);
779
- }
780
- /** Converte una stringa in PascalCase (es. "user_id" -> "UserId") */
781
- static toPascalCase(key) {
782
- // Se vuoto restituisce vuoto
783
- if (!key)
784
- return '';
785
- // Pulizia chiave
786
- const fixedKey = key.trim();
787
- // Normalizza e pulisce
788
- const parts = this.splitString(fixedKey);
789
- if (parts.length === 0)
790
- return '';
791
- // Converte in PascalCase
792
- const pascalCased = this.toPascalCaseParts(parts);
793
- return pascalCased;
794
- }
795
- /** Converte una stringa in camelCase (es. "user_id" -> "userId") */
796
- static toCamelCase(key) {
797
- // Se vuoto restituisce vuoto
798
- if (!key)
799
- return '';
800
- // Pulizia chiave
801
- const fixedKey = key.trim();
802
- // Normalizza e pulisce
803
- const parts = this.splitString(fixedKey);
804
- if (parts.length === 0)
805
- return '';
806
- // La prima parola resta minuscola, le successive PascalCase
807
- const first = parts[0].toLowerCase();
808
- const rest = parts.slice(1);
809
- return first + this.toPascalCaseParts(rest);
810
- }
811
- /** Capitalizza solo la prima lettera della stringa */
812
- static toCapitalize(key) {
813
- // Se vuoto restituisce vuoto
814
- if (!key)
815
- return '';
816
- // Pulizia chiave
817
- const fixedKey = key.trim();
818
- return fixedKey.charAt(0).toUpperCase() + fixedKey.slice(1);
415
+ function removeAll() {
416
+ // Crea una nuova istanza della Map
417
+ const newMap = new Map();
418
+ // Aggiorna il nuovo stato notificando l'observer
419
+ UniHttpManager.store.next(newMap);
420
+ }
421
+
422
+ async function execute(url, init) {
423
+ try {
424
+ /* Esegue chiamata http */
425
+ const res = await fetch(url, init);
426
+ /* Nessun contenuto cons status 204 */
427
+ if (res.status === 204) {
428
+ return undefined;
429
+ }
430
+ /* Recupero se è un json */
431
+ const contentType = res.headers.get('content-type') ?? '';
432
+ const isJson = contentType.startsWith('application/json');
433
+ /* Errore HTTP (quindi risposta ricevuta ma non ok) */
434
+ if (!res.ok) {
435
+ let errorBody;
436
+ try {
437
+ /* Clona risposta solo se c'è errore, per leggerla senza consumare la originale */
438
+ const resClone = res.clone();
439
+ /* Aggiorna body con struttura errore */
440
+ errorBody = isJson ? await resClone.json() : await resClone.text();
441
+ }
442
+ catch {
443
+ errorBody = await res.text();
444
+ }
445
+ if (isHttpErrorBody(errorBody)) {
446
+ const type = errorBody.exceptionType.includes('HttpRequestException') ? 'be' : 'ice';
447
+ throw new UniHttpError(type, res.status, url, errorBody);
448
+ }
449
+ else {
450
+ const error = new Error(`HTTP ${res.statusText}`);
451
+ throw new UniHttpError('base', res.status, url, {
452
+ exceptionMessage: error.message,
453
+ exceptionType: 'ErrorBase',
454
+ message: error.message,
455
+ stackTrace: error.stack ?? '',
456
+ });
457
+ }
458
+ }
459
+ /* Risposta ok */
460
+ return res;
819
461
  }
820
- /** Sostituisce sotto-stringhe all'interno della stringa */
821
- static toReplace(key, values) {
822
- // Se vuoto restituisce vuoto
823
- if (!key)
824
- return '';
825
- // Pulizia chiave
826
- let fixedKey = key.trim();
827
- for (const value of values) {
828
- fixedKey = fixedKey.replaceAll(value.searchValue, value.replaceValue);
462
+ catch (error) {
463
+ if (error instanceof TypeError) {
464
+ throw new UniHttpError('network', -1, url, {
465
+ exceptionMessage: `${error.name}: ${error.message}\n${error.stack}`,
466
+ exceptionType: error.name,
467
+ message: error.message,
468
+ stackTrace: error.stack ?? '',
469
+ });
829
470
  }
830
- return fixedKey;
471
+ // Fallback
472
+ throw error;
831
473
  }
832
- /* ----------------- Utils ----------------- */
833
- static splitString(key) {
834
- return (key
835
- // Pulisce eventuali caratteri di separazione rimasti in testa (es. "_tab_name" -> "tab_name")
836
- .replace(/^[-_\s]+/, '')
837
- // Isola il CamelCase inserendo un underscore tra minuscole e maiuscole (es. "userId" -> "user_Id")
838
- .replaceAll(/([a-z])([A-Z])/g, '$1_$2')
839
- // Isola gli acronimi attaccati a parole Normali (es. "VARAna" -> "VAR_Ana" grazie alla minuscola "na")
840
- .replaceAll(/([A-Z]+)([A-Z][a-z])/g, '$1_$2')
841
- // Applica il taglio definitivo usando come riferimento i trattini, gli underscore e gli spazi
842
- .split(/[-_\s]+/)
843
- // Rimuove dall'array finale eventuali stringhe vuote generate da separatori consecutivi
844
- .filter(Boolean));
474
+ }
475
+ async function executeHttp(url, init) {
476
+ /* Esegue la chiamata HTTP e restituisce il corpo decodificato come JSON */
477
+ const res = await execute(url, init);
478
+ if (!res)
479
+ return undefined;
480
+ /* Estrae il contenuto come testo */
481
+ const text = await res.text();
482
+ /* Controllo: se il testo è vuoto (''), ritorna undefined */
483
+ if (!text || text.trim().length === 0) {
484
+ return undefined;
845
485
  }
846
- static toPascalCaseParts(parts) {
847
- return parts.map((part) => part.charAt(0).toUpperCase() + part.slice(1).toLowerCase()).join('');
486
+ /* Parsa manualmente il testo, dato che lo stream è stato già letto */
487
+ return JSON.parse(text);
488
+ }
489
+ async function executeBlob(url, init) {
490
+ /* Esegue la chiamata HTTP */
491
+ const res = await execute(url, init);
492
+ if (!res)
493
+ return undefined;
494
+ /* Estrae il contenuto come Blob direttamente */
495
+ const blob = await res.blob();
496
+ /* Controllo: se il blob è vuoto (0 byte), ritorna undefined */
497
+ if (blob.size === 0) {
498
+ return undefined;
499
+ }
500
+ /* Estrae il nome del file dall'header */
501
+ const disposition = res.headers.get('Content-Disposition');
502
+ let fileName = 'download.pdf'; // Fallback di default
503
+ if (disposition) {
504
+ const matches = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/.exec(disposition);
505
+ if (!!matches && matches[1]) {
506
+ fileName = matches[1].replaceAll(/['"]/g, '');
507
+ }
848
508
  }
509
+ /* Genera l'URL temporaneo dal blob */
510
+ const fileUrl = URL.createObjectURL(blob);
511
+ return { url: fileUrl, name: fileName };
849
512
  }
850
513
 
851
514
  /**
@@ -874,14 +537,14 @@ function getUrl(hostname, port, config) {
874
537
  let formattedValue;
875
538
  // Caso: Date nativo
876
539
  if (item instanceof Date) {
877
- formattedValue = UniTypeDateManager.toYYYYMMDD(item);
540
+ formattedValue = UniTypeDateManager$1.toYYYYMMDD(item);
878
541
  }
879
542
  // Caso: Date formato ISO string
880
543
  else if (typeof item === 'string' && isoDateRegex.test(item)) {
881
544
  const parsedDate = new Date(item);
882
545
  formattedValue = Number.isNaN(parsedDate.getTime())
883
546
  ? item
884
- : UniTypeDateManager.toYYYYMMDD(parsedDate);
547
+ : UniTypeDateManager$1.toYYYYMMDD(parsedDate);
885
548
  }
886
549
  // Default
887
550
  else {
@@ -931,7 +594,10 @@ function normalizeHttpBody(body, isRoot = true) {
931
594
  return Object.fromEntries(entries);
932
595
  }
933
596
 
934
- const CONFIG_TOAST_DEFAULT = { type: 'success', label: 'OperationCompleted' };
597
+ const CONFIG_TOAST_DEFAULT = {
598
+ type: 'success',
599
+ label: 'OperationCompleted',
600
+ };
935
601
  class UniHttpManager {
936
602
  /* ------------------------------------------------------------------------------- */
937
603
  /* --------------------------------- Metodi: get --------------------------------- */
@@ -962,12 +628,6 @@ class UniHttpManager {
962
628
  this.hostname = hostname;
963
629
  this.port = port;
964
630
  }
965
- /**
966
- * Imposta o resetta lo stato di errore per una specifica reference.
967
- */
968
- static updateHasError(id, hasError) {
969
- updateHasError(id, hasError);
970
- }
971
631
  /* ------------------------------------------------------------------------------- */
972
632
  /* -------------------------------- Metodi: CRUD --------------------------------- */
973
633
  /* ------------------------------------------------------------------------------- */
@@ -985,7 +645,7 @@ class UniHttpManager {
985
645
  const url = getUrl(this.hostname, this.port, config);
986
646
  return http$(url, 'one', config, () => executeHttp(url, initCustom)).pipe(tap((res) => {
987
647
  if (Array.isArray(res) && config.toast === undefined) {
988
- UniToastManager.show({
648
+ UniToastManager$1.show({
989
649
  label: 'ItemsFound',
990
650
  params: { count: res.length },
991
651
  });
@@ -1058,97 +718,447 @@ class UniHttpManager {
1058
718
  return http$(url, 'one', configCustom, () => executeHttp(url, initCustom));
1059
719
  }
1060
720
  /* ------------------------------------------------------------------------------- */
1061
- /* -------------------------- Metodi: CRUD file/image ---------------------------- */
721
+ /* -------------------------- Metodi: CRUD file/image ---------------------------- */
722
+ /* ------------------------------------------------------------------------------- */
723
+ /**
724
+ * Recupera un'immagine tramite una richiesta GET e la trasforma in un formato gestibile (es. Blob o Base64).
725
+ * Delega la logica di conversione alla funzione executeImage.
726
+ */
727
+ static readImage$(config) {
728
+ /* Config */
729
+ const initCustom = {
730
+ ...config.init,
731
+ method: 'GET',
732
+ };
733
+ /* Chiama API */
734
+ const url = getUrl(this.hostname, this.port, config);
735
+ return http$(url, 'one', config, () => executeBlob(url, initCustom));
736
+ }
737
+ /**
738
+ * Recupera un file (es. PDF) tramite una richiesta GET e restituisce un Object URL temporaneo.
739
+ * Delega la logica di conversione alla funzione executeFile.
740
+ */
741
+ static readFile$(config) {
742
+ /* Config */
743
+ const initCustom = {
744
+ ...config.init,
745
+ method: 'GET',
746
+ };
747
+ /* Toast di default */
748
+ const configCustom = {
749
+ ...config,
750
+ toast: config.toast === null ? undefined : (config.toast ?? CONFIG_TOAST_DEFAULT),
751
+ };
752
+ /* Chiama API */
753
+ const url = getUrl(this.hostname, this.port, config);
754
+ return http$(url, 'file', configCustom, () => executeBlob(url, initCustom));
755
+ }
756
+ /* ------------------------------------------------------------------------------- */
757
+ /* ---------------------------- Metodi: CRUD polling ----------------------------- */
758
+ /* ------------------------------------------------------------------------------- */
759
+ /**
760
+ * Avvia un ciclo di polling basato su richieste GET.
761
+ * Continua a emettere valori in base alla configurazione di intervallo definita in HttpConfigPolling.
762
+ */
763
+ static readPolling$(config) {
764
+ /* Config */
765
+ const initCustom = {
766
+ ...config.init,
767
+ method: 'GET',
768
+ };
769
+ /* Chiama API */
770
+ const url = getUrl(this.hostname, this.port, config);
771
+ return httpPolling$(url, config, () => executeHttp(url, initCustom));
772
+ }
773
+ /**
774
+ * Avvia un ciclo di polling basato su richieste POST.
775
+ * Invia il body specificato a ogni iterazione del ciclo.
776
+ */
777
+ static createPolling$(config, body) {
778
+ /* Config */
779
+ const initCustom = {
780
+ ...config.init,
781
+ method: 'POST',
782
+ headers: { 'Content-Type': 'application/json' },
783
+ body: JSON.stringify(body),
784
+ };
785
+ /* Chiama API */
786
+ const url = getUrl(this.hostname, this.port, config);
787
+ return httpPolling$(url, config, () => executeHttp(url, initCustom));
788
+ }
789
+ /**
790
+ * Avvia un ciclo di polling basato su richieste PUT.
791
+ */
792
+ static updatePolling$(config, body) {
793
+ /* Config */
794
+ const initCustom = {
795
+ ...config.init,
796
+ method: 'PUT',
797
+ };
798
+ if (body !== undefined) {
799
+ initCustom.headers = {
800
+ ...initCustom.headers,
801
+ 'Content-Type': 'application/json',
802
+ };
803
+ initCustom.body = JSON.stringify(body);
804
+ }
805
+ /* Chiama API */
806
+ const url = getUrl(this.hostname, this.port, config);
807
+ return httpPolling$(url, config, () => executeHttp(url, initCustom));
808
+ }
809
+ }
810
+
811
+ class UniLocaleManager {
812
+ /* ------------------------------------------------------------------------------- */
813
+ /* ----------------------------------- Config ------------------------------------ */
814
+ /* ------------------------------------------------------------------------------- */
815
+ /** Codice lingua corrente (es. 'it-IT', 'en-US') usato per formattare date e numeri */
816
+ static { this._locale = navigator.language ?? 'en-US'; }
817
+ /** Elenco dei codici lingua supportati dall'applicazione (es. ['it-IT', 'en-US']) */
818
+ static { this._localesSupported = []; }
819
+ /** Prefisso globale applicato a tutte le chiavi di traduzione (es. 'APP_') */
820
+ static { this._prefix = undefined; }
821
+ /* ------------------------------------------------------------------------------- */
822
+ /* --------------------------------- Metodi: get --------------------------------- */
823
+ /* ------------------------------------------------------------------------------- */
824
+ /** Restituisce il codice lingua corrente */
825
+ static get locale() {
826
+ return this._locale;
827
+ }
828
+ /** Restituisce l'array contenente tutti i codici locale supportati.*/
829
+ static get localesSupported() {
830
+ return this._localesSupported;
831
+ }
832
+ /** Restituisce solo la lingua (es. 'it') */
833
+ static get language() {
834
+ return this._locale.split('-')[0];
835
+ }
836
+ /** Restituisce solo il paese (es. 'IT') */
837
+ static get region() {
838
+ const parts = this._locale.split('-');
839
+ return parts.length > 1 ? parts[1] : '';
840
+ }
841
+ /* ------------------------------------------------------------------------------- */
842
+ /* ------------------------------------ Store ------------------------------------ */
843
+ /* ------------------------------------------------------------------------------- */
844
+ /** Store privato (Subject) */
845
+ static { this.store = new BehaviorSubject({}); }
846
+ /** Store pubblico (Observable) */
847
+ static { this.store$ = this.store.asObservable(); }
848
+ /** Ottiene il dizionario attuale senza sottoscrizione */
849
+ static get currentValue() {
850
+ return this.store.getValue();
851
+ }
852
+ /* ------------------------------------------------------------------------------- */
853
+ /* -------------------------------- Metodi: setup -------------------------------- */
854
+ /* ------------------------------------------------------------------------------- */
855
+ /**
856
+ * Inizializza la configurazione di rete del manager.
857
+ * Deve essere chiamato prima di effettuare qualsiasi richiesta HTTP.
858
+ */
859
+ static setup(locale, prefix) {
860
+ this._locale = locale ?? 'en-US';
861
+ this._prefix = prefix;
862
+ }
863
+ /** Imposta l'elenco dei codici lingua supportati dall'applicazione */
864
+ static setLocalesSupported(locales) {
865
+ this._localesSupported = locales ?? [];
866
+ }
867
+ /**
868
+ * Aggiorna lo store locale con il dizionario delle traduzioni fornito.
869
+ * Se viene passato undefined, lo store viene inizializzato come oggetto vuoto.
870
+ */
871
+ static setTranslations(translations) {
872
+ this.store.next(translations ?? {});
873
+ }
874
+ /* ------------------------------------------------------------------------------- */
875
+ /* ----------------------------- Metodi: traduzioni ------------------------------ */
876
+ /* ------------------------------------------------------------------------------- */
877
+ /**
878
+ * Traduce una label in base al dizionario caricato.
879
+ * Gestisce la composizione della chiave, i parametri dinamici (interpolazione) e il fallback.
880
+ */
881
+ static translate(key, prefix = 'lbl', interpolationParams) {
882
+ if (!key)
883
+ return '-';
884
+ // Costruzione chiave: prefissoGlobale + prefissoLocale + LabelConInizialeMaiuscola
885
+ const keyParts = key.trim().split(/(?=[A-Z])/);
886
+ const rootKeyParts = keyParts.filter((p) => p.toLowerCase() !== prefix.toLowerCase());
887
+ const cleanKey = rootKeyParts.length > 0 ? rootKeyParts.join('') : undefined;
888
+ const capitalizedKey = cleanKey ? cleanKey.charAt(0).toUpperCase() + cleanKey.slice(1) : '';
889
+ const finalKey = `${this._prefix ?? ''}${prefix}${capitalizedKey}`;
890
+ // Cerca la chiave in minuscolo (standardizzazione)
891
+ let translation = this.currentValue?.[finalKey.toLowerCase()];
892
+ // Log e fallback se la traduzione manca
893
+ if (!translation) {
894
+ console.warn(`Translation missing for key: ${finalKey}`);
895
+ return `🔑 ${finalKey}`;
896
+ }
897
+ // Interpolazione variabili
898
+ if (interpolationParams) {
899
+ for (const [key, value] of Object.entries(interpolationParams)) {
900
+ const displayValue = value instanceof Date ? value.toLocaleDateString(this._locale) : String(value);
901
+ translation = translation.replaceAll(`{{${key}}}`, displayValue);
902
+ }
903
+ }
904
+ return translation;
905
+ }
906
+ /**
907
+ * Traduce una stringa che contiene parametri separati da un carattere specifico.
908
+ * Supporta ora un numero arbitrario di parametri in formato "label/param1/param2"
909
+ * o semplicemente "label".
910
+ */
911
+ static translateInlineParams(keyWithParams, splitChar) {
912
+ if (!keyWithParams)
913
+ return '-';
914
+ const [label, ...params] = keyWithParams.split(splitChar);
915
+ // Se non ci sono parametri, esegui una traduzione semplice
916
+ if (params.length === 0) {
917
+ return this.translate(label);
918
+ }
919
+ // Mappa i parametri in un oggetto di interpolazione: { inlineParam0: val, inlineParam1: val, ... }
920
+ const interpolationParameters = {};
921
+ for (const [index, val] of params.entries()) {
922
+ interpolationParameters[`param${index}`] = val;
923
+ }
924
+ return this.translate(label, 'lbl', interpolationParameters);
925
+ }
926
+ /* ------------------------------------------------------------------------------- */
927
+ /* ------------------------------- Metodi: numeri -------------------------------- */
928
+ /* ------------------------------------------------------------------------------- */
929
+ /**
930
+ * Converte un valore numerico in una stringa formattata secondo il locale impostato.
931
+ * Disabilita i separatori delle migliaia e forza un numero fisso di decimali.
932
+ */
933
+ static toStringNumber(value, decimal) {
934
+ return new Intl.NumberFormat(this._locale, {
935
+ useGrouping: true,
936
+ minimumFractionDigits: decimal,
937
+ maximumFractionDigits: decimal,
938
+ numberingSystem: 'latn',
939
+ }).format(value);
940
+ }
941
+ /* ------------------------------------------------------------------------------- */
942
+ /* -------------------------------- Metodi: date --------------------------------- */
943
+ /* ------------------------------------------------------------------------------- */
944
+ /**
945
+ * Formatta una data o una stringa in base al locale corrente.
946
+ * Gestisce tre modalità predefinite (date, time, full) e accetta opzioni personalizzate Intl.
947
+ */
948
+ static toDate(date, mode = 'full', force) {
949
+ const dt = new Date(date);
950
+ // Controllo: validità data
951
+ if (Number.isNaN(dt.getTime())) {
952
+ console.error(`[UniLocaleManager] Data non valida fornita a formatDateTime:`, date);
953
+ return '';
954
+ }
955
+ // Controllo: locale da forzare
956
+ const locale = force && this._locale.startsWith(force.oldLang) ? force.newLocale : this._locale;
957
+ switch (mode) {
958
+ case 'date': {
959
+ return dt.toLocaleDateString(locale);
960
+ }
961
+ case 'time': {
962
+ return dt.toLocaleTimeString(locale);
963
+ }
964
+ case 'full': {
965
+ return dt.toLocaleString(locale);
966
+ }
967
+ }
968
+ }
969
+ }
970
+
971
+ /* eslint-disable @typescript-eslint/no-explicit-any */
972
+ class UniToastManager {
973
+ /* ------------------------------------------------------------------------------- */
974
+ /* -------------------------------- Metodi: setup -------------------------------- */
1062
975
  /* ------------------------------------------------------------------------------- */
1063
976
  /**
1064
- * Recupera un'immagine tramite una richiesta GET e la trasforma in un formato gestibile (es. Blob o Base64).
1065
- * Delega la logica di conversione alla funzione executeImage.
1066
- */
1067
- static readImage$(config) {
1068
- /* Config */
1069
- const initCustom = {
1070
- ...config.init,
1071
- method: 'GET',
1072
- };
1073
- /* Chiama API */
1074
- const url = getUrl(this.hostname, this.port, config);
1075
- return http$(url, 'one', config, () => executeBlob(url, initCustom));
1076
- }
1077
- /**
1078
- * Recupera un file (es. PDF) tramite una richiesta GET e restituisce un Object URL temporaneo.
1079
- * Delega la logica di conversione alla funzione executeFile.
977
+ * Inizializza il manager con una serie di operazioni
1080
978
  */
1081
- static readFile$(config) {
1082
- /* Config */
1083
- const initCustom = {
1084
- ...config.init,
1085
- method: 'GET',
1086
- };
1087
- /* Toast di default */
1088
- const configCustom = {
1089
- ...config,
1090
- toast: config.toast === null ? undefined : (config.toast ?? CONFIG_TOAST_DEFAULT),
1091
- };
1092
- /* Chiama API */
1093
- const url = getUrl(this.hostname, this.port, config);
1094
- return http$(url, 'file', configCustom, () => executeBlob(url, initCustom));
979
+ static setup(operations) {
980
+ this.manager = operations;
1095
981
  }
1096
982
  /* ------------------------------------------------------------------------------- */
1097
- /* ---------------------------- Metodi: CRUD polling ----------------------------- */
983
+ /* -------------------------------- Metodi: show --------------------------------- */
1098
984
  /* ------------------------------------------------------------------------------- */
1099
985
  /**
1100
- * Avvia un ciclo di polling basato su richieste GET.
1101
- * Continua a emettere valori in base alla configurazione di intervallo definita in HttpConfigPolling.
986
+ * Mostra un toast di successo basato su una risposta HTTP e una label di traduzione.
1102
987
  */
1103
- static readPolling$(config) {
1104
- /* Config */
1105
- const initCustom = {
1106
- ...config.init,
1107
- method: 'GET',
1108
- };
1109
- /* Chiama API */
1110
- const url = getUrl(this.hostname, this.port, config);
1111
- return httpPolling$(url, config, () => executeHttp(url, initCustom));
988
+ static show(config) {
989
+ /* Messaggio tradotto */
990
+ const msg = UniLocaleManager$1.translate(config.label, 'toast', config.params);
991
+ const msgFixed = `${config.prefix ?? ''}${msg}${config.suffix ?? ''}`;
992
+ this.manager[config.type ?? 'info'](msgFixed, config);
1112
993
  }
1113
994
  /**
1114
- * Avvia un ciclo di polling basato su richieste POST.
1115
- * Invia il body specificato a ogni iterazione del ciclo.
995
+ * Mostra un toast di successo basato su una risposta HTTP e una label di traduzione.
1116
996
  */
1117
- static createPolling$(config, body) {
1118
- /* Config */
1119
- const initCustom = {
1120
- ...config.init,
1121
- method: 'POST',
1122
- headers: { 'Content-Type': 'application/json' },
1123
- body: JSON.stringify(body),
1124
- };
1125
- /* Chiama API */
1126
- const url = getUrl(this.hostname, this.port, config);
1127
- return httpPolling$(url, config, () => executeHttp(url, initCustom));
997
+ static showHttp(config, res) {
998
+ const { interpolationParams, resParams, resLengthParam, formatters } = config;
999
+ /* Parametri statici di base */
1000
+ const allParams = { ...interpolationParams };
1001
+ /* Config parametri risposta: estrazione parametri dalla risposta (se esiste ed è un oggetto) */
1002
+ if (resParams?.length && res && typeof res === 'object') {
1003
+ for (const param of resParams ?? []) {
1004
+ if (param in res)
1005
+ continue;
1006
+ // Se esiste un formatter per questa chiave lo si usa, altrimenti valore grezzo
1007
+ const rawValue = res[param];
1008
+ allParams[param] = formatters?.[param] ? formatters[param](rawValue) : rawValue;
1009
+ }
1010
+ }
1011
+ /* Config parametro lunghezza risposta: conteggio array */
1012
+ if (resLengthParam && Array.isArray(res)) {
1013
+ allParams[resLengthParam] = res.length;
1014
+ }
1015
+ /* Messaggio tradotto */
1016
+ this.show({ ...config, params: allParams });
1128
1017
  }
1129
- /**
1130
- * Avvia un ciclo di polling basato su richieste PUT.
1131
- */
1132
- static updatePolling$(config, body) {
1133
- /* Config */
1134
- const initCustom = {
1135
- ...config.init,
1136
- method: 'PUT',
1137
- };
1138
- if (body !== undefined) {
1139
- initCustom.headers = {
1140
- ...initCustom.headers,
1141
- 'Content-Type': 'application/json',
1142
- };
1143
- initCustom.body = JSON.stringify(body);
1018
+ }
1019
+
1020
+ /**
1021
+ * Classe di utilità per la gestione e formattazione delle date.
1022
+ * Fornisce metodi per convertire in modo sicuro valori di tipo Date, stringa o null in formati standardizzati.
1023
+ */
1024
+ class UniTypeDateManager {
1025
+ static toYYYYMMDD(date) {
1026
+ if (!date)
1027
+ return '';
1028
+ const d = new Date(date);
1029
+ if (Number.isNaN(d.getTime()))
1030
+ return '';
1031
+ const year = d.getFullYear();
1032
+ const month = String(d.getMonth() + 1).padStart(2, '0');
1033
+ const day = String(d.getDate()).padStart(2, '0');
1034
+ return `${year}-${month}-${day}`;
1035
+ }
1036
+ }
1037
+
1038
+ /**
1039
+ * Utility per la gestione e formattazione di valori numerici.
1040
+ */
1041
+ class UniTypeNumberManager {
1042
+ /** Applica il padding a un numero o una stringa */
1043
+ static toPad(value, count, character = '0') {
1044
+ // Se il valore è null/undefined, riempiamo l'intero campo con il carattere scelto
1045
+ if (value === null || value === undefined) {
1046
+ return ''.padStart(count, character);
1144
1047
  }
1145
- /* Chiama API */
1146
- const url = getUrl(this.hostname, this.port, config);
1147
- return httpPolling$(url, config, () => executeHttp(url, initCustom));
1048
+ // Convertiamo in stringa e applichiamo il padding
1049
+ return value.toString().padStart(count, character);
1050
+ }
1051
+ /** Formatta un numero in una versione leggibile (es: 1000 -> 1K, 1000000 -> 1M) */
1052
+ static toTruncateAndAdUdm(value, decimalDigits = 0, maxIntegerDigits = 3) {
1053
+ // Nessun limite impostato o numero inferiore alla soglia definita
1054
+ if (Math.abs(value) < Math.pow(10, maxIntegerDigits)) {
1055
+ return value.toFixed(decimalDigits);
1056
+ }
1057
+ // Definizione delle scale di riduzione per grandi numeri
1058
+ const scales = [
1059
+ { threshold: 1e12, suffix: 'T' }, // Trilioni
1060
+ { threshold: 1e9, suffix: 'B' }, // Miliardi
1061
+ { threshold: 1e6, suffix: 'M' }, // Milioni
1062
+ { threshold: 1e3, suffix: 'K' }, // Migliaia
1063
+ ];
1064
+ // Itera dalla scala più grande alla più piccola per trovare la soglia corretta
1065
+ for (const { threshold, suffix } of scales) {
1066
+ if (Math.abs(value) >= threshold) {
1067
+ const reduced = value / threshold;
1068
+ // parseFloat(toFixed()) rimuove gli zeri decimali superflui (es: 1.50 -> 1.5)
1069
+ // aggiungendo poi il relativo suffisso (K, M, B, T)
1070
+ return Number.parseFloat(reduced.toFixed(decimalDigits)).toString() + suffix;
1071
+ }
1072
+ }
1073
+ // Fallback: se il numero è grande ma non rientra nelle scale (caso raro con la logica attuale)
1074
+ return value.toFixed(decimalDigits);
1148
1075
  }
1149
1076
  }
1150
1077
 
1151
- /* eslint-disable @typescript-eslint/no-explicit-any */
1078
+ /**
1079
+ * Utility per la manipolazione di stringhe
1080
+ */
1081
+ class UniTypeStringManager {
1082
+ /** Converte una stringa in formato lblPascalCase (es. "user_id" -> "lblUserId") */
1083
+ static toLabelize(key, prefix = 'lbl') {
1084
+ // Se vuoto restituisce vuoto
1085
+ if (!key)
1086
+ return '';
1087
+ // Pulizia chiave
1088
+ const fixedKey = key.trim();
1089
+ // Unisce il prefisso
1090
+ return prefix + this.toPascalCase(fixedKey);
1091
+ }
1092
+ /** Converte una stringa in PascalCase (es. "user_id" -> "UserId") */
1093
+ static toPascalCase(key) {
1094
+ // Se vuoto restituisce vuoto
1095
+ if (!key)
1096
+ return '';
1097
+ // Pulizia chiave
1098
+ const fixedKey = key.trim();
1099
+ // Normalizza e pulisce
1100
+ const parts = this.splitString(fixedKey);
1101
+ if (parts.length === 0)
1102
+ return '';
1103
+ // Converte in PascalCase
1104
+ const pascalCased = this.toPascalCaseParts(parts);
1105
+ return pascalCased;
1106
+ }
1107
+ /** Converte una stringa in camelCase (es. "user_id" -> "userId") */
1108
+ static toCamelCase(key) {
1109
+ // Se vuoto restituisce vuoto
1110
+ if (!key)
1111
+ return '';
1112
+ // Pulizia chiave
1113
+ const fixedKey = key.trim();
1114
+ // Normalizza e pulisce
1115
+ const parts = this.splitString(fixedKey);
1116
+ if (parts.length === 0)
1117
+ return '';
1118
+ // La prima parola resta minuscola, le successive PascalCase
1119
+ const first = parts[0].toLowerCase();
1120
+ const rest = parts.slice(1);
1121
+ return first + this.toPascalCaseParts(rest);
1122
+ }
1123
+ /** Capitalizza solo la prima lettera della stringa */
1124
+ static toCapitalize(key) {
1125
+ // Se vuoto restituisce vuoto
1126
+ if (!key)
1127
+ return '';
1128
+ // Pulizia chiave
1129
+ const fixedKey = key.trim();
1130
+ return fixedKey.charAt(0).toUpperCase() + fixedKey.slice(1);
1131
+ }
1132
+ /** Sostituisce sotto-stringhe all'interno della stringa */
1133
+ static toReplace(key, values) {
1134
+ // Se vuoto restituisce vuoto
1135
+ if (!key)
1136
+ return '';
1137
+ // Pulizia chiave
1138
+ let fixedKey = key.trim();
1139
+ for (const value of values) {
1140
+ fixedKey = fixedKey.replaceAll(value.searchValue, value.replaceValue);
1141
+ }
1142
+ return fixedKey;
1143
+ }
1144
+ /* ----------------- Utils ----------------- */
1145
+ static splitString(key) {
1146
+ return (key
1147
+ // Pulisce eventuali caratteri di separazione rimasti in testa (es. "_tab_name" -> "tab_name")
1148
+ .replace(/^[-_\s]+/, '')
1149
+ // Isola il CamelCase inserendo un underscore tra minuscole e maiuscole (es. "userId" -> "user_Id")
1150
+ .replaceAll(/([a-z])([A-Z])/g, '$1_$2')
1151
+ // Isola gli acronimi attaccati a parole Normali (es. "VARAna" -> "VAR_Ana" grazie alla minuscola "na")
1152
+ .replaceAll(/([A-Z]+)([A-Z][a-z])/g, '$1_$2')
1153
+ // Applica il taglio definitivo usando come riferimento i trattini, gli underscore e gli spazi
1154
+ .split(/[-_\s]+/)
1155
+ // Rimuove dall'array finale eventuali stringhe vuote generate da separatori consecutivi
1156
+ .filter(Boolean));
1157
+ }
1158
+ static toPascalCaseParts(parts) {
1159
+ return parts.map((part) => part.charAt(0).toUpperCase() + part.slice(1).toLowerCase()).join('');
1160
+ }
1161
+ }
1152
1162
 
1153
1163
  /*
1154
1164
  * Public API Surface of uni-manager