Repository navigation
Expand file tree
/
Copy pathapp.js
More file actions
1406 lines (1345 loc) · 62.4 KB
/
Copy pathapp.js
File metadata and controls
1406 lines (1345 loc) · 62.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Numero WhatsApp per "Invia diagnostica" — vuoto = bottone disabilitato.
// Configurato dall'utente; non commitare mai un numero reale qui.
const SUPPORT_WHATSAPP = '';
/** Genera un ID univoco breve */
function uid() { return Date.now().toString(36) + Math.random().toString(36).substr(2, 6); }
/** Formatta importo nella valuta indicata (EUR default, USD supportato) */
function formatValuta(n, currency = 'EUR') {
if (n == null || isNaN(n)) return currency === 'USD' ? '$0.00' : '0,00 \u20AC';
const locale = currency === 'USD' ? 'en-US' : 'it-IT';
return n.toLocaleString(locale, { style: 'currency', currency });
}
/** Formatta data ISO in gg/mm/aaaa */
function formatData(d) {
if (!d) return '\u2014';
const [y, m, g] = d.split('-');
return g + '/' + m + '/' + y;
}
/** Data odierna ISO */
function oggi() { return new Date().toISOString().split('T')[0]; }
/** Mese corrente YYYY-MM */
function meseCorrente() {
const d = new Date();
return d.getFullYear() + '-' + String(d.getMonth() + 1).padStart(2, '0');
}
/** Calcola data prevista per incasso */
function dataPrevist(mese, scadenza) {
const [y, m] = mese.split('-').map(Number);
if (scadenza === 'fine_mese') {
const ultimo = new Date(y, m, 0).getDate();
return y + '-' + String(m).padStart(2, '0') + '-' + String(ultimo).padStart(2, '0');
}
const g = parseInt(scadenza) || 1;
return y + '-' + String(m).padStart(2, '0') + '-' + String(g).padStart(2, '0');
}
/** Dati di esempio iniziali */
function datiEsempio() {
const bBPM = { id: uid(), nome: 'BPM', intestatario: 'Stefano Desio', currency: 'EUR' };
const bBPER = { id: uid(), nome: 'BPER', intestatario: 'Gina Desio', currency: 'EUR' };
const nomi = ['Via Guelfa','Via Dei Servi','Elba 508','Elba 626','Follonica Bicocchi','Franklin 214','Sweetzer 201','Ghibellina 101','Larrabee 116'];
const importi = [800,900,750,650,1000,1200,1100,850,950];
const proprieta = nomi.map((nome, i) => ({
id: uid(), nome, tipo: 'appartamento',
scadenzaAffitto: i % 3 === 0 ? '1' : (i % 3 === 1 ? '15' : 'fine_mese'),
importoAffittoMensile: importi[i],
bancaIncasso: i % 2 === 0 ? bBPM.id : bBPER.id,
intestatario: i % 2 === 0 ? 'Stefano Desio' : 'Gina Desio',
bancaDestinazione: i % 2 === 0 ? bBPER.id : bBPM.id,
currency: 'EUR',
deletedAt: null,
note: ''
}));
return { dataVersion: 3, proprieta, banche: [bBPM, bBPER], incassiAffitti: [], utenze: [] };
}
/** Migrazione schema dati: idempotente, applica cambiamenti incrementali per versione. */
function migraDati(dati) {
if (!dati || typeof dati !== 'object') return dati;
if (!dati.dataVersion || dati.dataVersion < 2) {
if (Array.isArray(dati.proprieta)) {
for (const p of dati.proprieta) { if (!p.currency) p.currency = 'EUR'; }
}
if (Array.isArray(dati.banche)) {
for (const b of dati.banche) { if (!b.currency) b.currency = 'EUR'; }
}
if (Array.isArray(dati.incassiAffitti)) {
for (const i of dati.incassiAffitti) { if (!i.currency) i.currency = 'EUR'; }
}
if (Array.isArray(dati.utenze)) {
for (const u of dati.utenze) { if (!u.currency) u.currency = 'EUR'; }
}
dati.dataVersion = 2;
}
if (!dati.dataVersion || dati.dataVersion < 3) {
if (Array.isArray(dati.proprieta)) {
for (const p of dati.proprieta) { if (!('deletedAt' in p)) p.deletedAt = null; }
}
if (Array.isArray(dati.incassiAffitti)) {
for (const i of dati.incassiAffitti) {
if (!('deletedAt' in i)) i.deletedAt = null;
if (!('modificatoManualmente' in i)) i.modificatoManualmente = false;
}
}
dati.dataVersion = 3;
}
return dati;
}
// ---------- Componente Alpine principale ----------
function app() {
return {
viste: [
{ id: 'dashboard', label: 'Dashboard' },
{ id: 'calendario', label: 'Calendario' },
{ id: 'proprieta', label: 'Propriet\u00E0' },
{ id: 'banche', label: 'Banche' },
{ id: 'utenze', label: 'Utenze' },
{ id: 'impostazioni', label: 'Impostazioni' }
],
vistaCorrente: 'dashboard',
mobileMenuOpen: false,
drawerOpen: false,
nomiMesi: ['Gennaio','Febbraio','Marzo','Aprile','Maggio','Giugno','Luglio','Agosto','Settembre','Ottobre','Novembre','Dicembre'],
dati: { dataVersion: 2, proprieta: [], banche: [], incassiAffitti: [], utenze: [] },
statoSalvataggio: 'salvato',
modalitaOffline: false,
// --- Stato autenticazione ---
utente: null,
caricamentoIniziale: true,
modalitaAuth: 'login',
authEmail: '',
authPassword: '',
authError: '',
authInfo: '',
authLoading: false,
debounceTimer: null,
_lastSnapshotData: null,
// Counter reattivo per Alpine: ogni pushSnapshot lo incrementa, snapshots()
// lo legge (void this._snapshotVersion) -> Alpine sa di dover ri-eseguire
// il template x-for quando localStorage cambia. Senza questo, snapshots()
// legge solo localStorage e Alpine non traccia alcun dep -> il template
// resta sullo stato iniziale "Nessuno snapshot disponibile" anche dopo
// pushSnapshot effettivo (SNAP-01 root cause, scoperto via CI debug PR2a).
_snapshotVersion: 0,
// PWA install prompt (PR2a REQ-PWA-03)
installPromptVisible: false,
_deferredInstallPrompt: null,
_isIosSafari: false,
storagePctValue: null,
proprietaSelezionata: null,
annoProprieta: new Date().getFullYear(),
meseCalendario: new Date().getMonth(),
annoCalendario: new Date().getFullYear(),
meseBanca: meseCorrente(),
incassoInModifica: null,
filtroUtenzeProprieta: '', filtroUtenzeTipo: '', filtroUtenzeStato: '',
filtroUtenzeAnno: new Date().getFullYear(),
mostraFormUtenza: false, nuovaUtenza: {},
mostraFormProprieta: false, editProprieta: {},
mostraFormBanca: false, editBanca: {},
async init() {
// Error capture globale: registrato per primo cosi cattura anche errori
// sollevati durante il setup di Supabase/Alpine.
window.addEventListener('error', (ev) => {
this.pushErrore({
ts: new Date().toISOString(),
message: (ev && ev.message) || 'error',
stack: ev && ev.error && ev.error.stack ? String(ev.error.stack).slice(0, 1000) : null,
url: ev && ev.filename ? ev.filename : null,
line: ev && ev.lineno ? ev.lineno : null,
severity: 'error',
});
});
window.addEventListener('unhandledrejection', (ev) => {
const reason = ev && ev.reason;
const msg = reason && reason.message ? reason.message : String(reason || 'unhandledrejection');
this.pushErrore({
ts: new Date().toISOString(),
message: msg,
stack: reason && reason.stack ? String(reason.stack).slice(0, 1000) : null,
severity: 'error',
});
});
// Pulizia: rimuove chiave localStorage obsoleta e service worker stale da versioni precedenti
try { localStorage.removeItem('gestione_affitti_dati'); } catch (e) {}
// Fire-and-forget: aggiorna la percentuale di storage usato dal browser.
this.aggiornaStoragePct();
// PWA shell (PR2a REQ-PWA-02 + CON-010 + CON-017 #3):
// unregistra SOLO i SW con scriptURL != sw.js corrente (es. registrazioni
// da versioni precedenti dell'app), poi registra sw.js scope './'.
// Filter-by-scriptURL preserva il SW attuale; il vecchio "unregister all"
// disinstallava anche se stesso ad ogni boot.
if ('serviceWorker' in navigator) {
try {
const SW_URL = 'sw.js';
const SW_ABS = new URL(SW_URL, location.href).href;
const regs = await navigator.serviceWorker.getRegistrations();
for (const r of regs) {
const active = r.active || r.installing || r.waiting;
const url = active && active.scriptURL ? active.scriptURL : '';
if (url !== SW_ABS) {
await r.unregister();
}
}
// fire-and-forget: non rallentare il boot
navigator.serviceWorker.register(SW_URL, { scope: './' }).catch((e) => {
console.warn('SW register failed:', e);
});
} catch (e) {
console.warn('SW boot error:', e);
}
}
// PWA install prompt detection (PR2a REQ-PWA-03)
// iOS Safari NON espone beforeinstallprompt; iPadOS 13+ si maschera come
// MacIntel quindi il check UA da solo non basta (OQ-6 del plan).
const ua = navigator.userAgent;
const isIosUA = /iPhone|iPad|iPod/.test(ua);
const isIpadOS = navigator.maxTouchPoints > 1 && navigator.platform === 'MacIntel';
const isStandalone = window.matchMedia('(display-mode: standalone)').matches
|| navigator.standalone === true;
this._isIosSafari = (isIosUA || isIpadOS) && !isStandalone;
window.addEventListener('beforeinstallprompt', (e) => {
e.preventDefault();
this._deferredInstallPrompt = e;
this.maybeShowInstallBanner();
});
window.addEventListener('appinstalled', () => {
this.installPromptVisible = false;
this._deferredInstallPrompt = null;
try { localStorage.setItem('gestione_affitti_installed', '1'); } catch (_) {}
});
this.recordSession();
this.maybeShowInstallBanner();
// Verifica se esiste una sessione attiva
const { data: { session } } = await sb.auth.getSession();
if (session) {
this.utente = session.user;
await this.caricaDatiUtente();
this.purgeOldSoftDeleted();
}
this.caricamentoIniziale = false;
// Ascolta cambiamenti di auth (login in altra tab, logout, refresh token)
sb.auth.onAuthStateChange(async (event, session) => {
if (event === 'SIGNED_IN' && session) {
this.utente = session.user;
await this.caricaDatiUtente();
} else if (event === 'SIGNED_OUT') {
this.utente = null;
this.dati = { dataVersion: 2, proprieta: [], banche: [], incassiAffitti: [], utenze: [] };
}
});
// Listener connettivita: quando torna online rilanciamo caricaDatiUtente
// che, grazie al confronto updated_at, ri-pushera la cache se piu recente.
window.addEventListener('online', () => {
if (this.utente && this.modalitaOffline) {
this.caricaDatiUtente();
}
});
window.addEventListener('offline', () => {
this.modalitaOffline = true;
});
// Flush salvataggio pendente prima di chiudere la scheda: evita perdita dati
// se l'utente refresha mentre il debounce di salva() e ancora in attesa.
window.addEventListener('beforeunload', (e) => {
if (this.debounceTimer) {
clearTimeout(this.debounceTimer);
this.debounceTimer = null;
// Cache eager gia scritta in salva(): qui tentiamo il push rete in modo
// best-effort. Se fallisce non blocchiamo la chiusura: al prossimo load
// il conflict resolution ripushera la cache piu recente.
try { this.salvaSubito(); } catch(_) {}
if (this.statoSalvataggio === 'salvataggio') {
e.preventDefault();
e.returnValue = '';
}
}
});
},
/** Filtra un array escludendo gli elementi soft-deleted (deletedAt valorizzato).
* Centralizza il filtro per i read site: tutti gli iteratori/find/filter su
* proprieta + incassiAffitti devono passare per qui. */
attivi(arr) {
if (!Array.isArray(arr)) return [];
return arr.filter(x => !x.deletedAt);
},
// --- Cestino ---
/** Lista unificata di item soft-deleted (proprieta + incassi) per il Cestino. */
cestinoItems() {
const out = [];
const props = Array.isArray(this.dati.proprieta) ? this.dati.proprieta : [];
const incs = Array.isArray(this.dati.incassiAffitti) ? this.dati.incassiAffitti : [];
for (const p of props) {
if (p.deletedAt) out.push({ id: p.id, tipo: 'Proprieta', nome: p.nome || '(senza nome)', deletedAt: p.deletedAt });
}
for (const i of incs) {
if (i.deletedAt) {
const propNome = this.nomeProprieta(i.proprietaId);
const label = (i.mese || '') + ' - ' + propNome;
out.push({ id: i.id, tipo: 'Incasso', nome: label, deletedAt: i.deletedAt });
}
}
return out.sort((a, b) => b.deletedAt.localeCompare(a.deletedAt));
},
relativeTime(iso) {
if (!iso) return '';
const diff = Date.now() - new Date(iso).getTime();
const m = Math.floor(diff / 60000);
if (m < 1) return 'pochi secondi fa';
if (m < 60) return m + (m === 1 ? ' minuto fa' : ' minuti fa');
const h = Math.floor(m / 60);
if (h < 24) return h + (h === 1 ? ' ora fa' : ' ore fa');
const g = Math.floor(h / 24);
return g + (g === 1 ? ' giorno fa' : ' giorni fa');
},
ripristina(item) {
if (item.tipo === 'Proprieta') {
const p = this.dati.proprieta.find(x => x.id === item.id);
if (!p) return;
const stamp = p.deletedAt;
p.deletedAt = null;
// Cascading: ripristina solo gli incassi cancellati nello STESSO burst
// (timestamp identico). Incassi cancellati separatamente restano in cestino.
for (const i of this.dati.incassiAffitti) {
if (i.proprietaId === item.id && i.deletedAt === stamp) i.deletedAt = null;
}
} else {
const i = this.dati.incassiAffitti.find(x => x.id === item.id);
if (i) i.deletedAt = null;
}
this.salva();
},
eliminaDefinitivamente(item) {
if (!confirm('Eliminare definitivamente "' + (item.nome || '') + '"? L\'azione non e reversibile.')) return;
if (item.tipo === 'Proprieta') {
// Cascading hard-delete sugli incassi figli (anche quelli soft-deleted
// separatamente). Orfani sono peggio della perdita.
this.dati.proprieta = this.dati.proprieta.filter(p => p.id !== item.id);
this.dati.incassiAffitti = this.dati.incassiAffitti.filter(i => i.proprietaId !== item.id);
} else {
this.dati.incassiAffitti = this.dati.incassiAffitti.filter(i => i.id !== item.id);
}
this.salva();
},
/** Hard-rimuove i soft-deleted con deletedAt < now-30gg.
* Idempotente: una seconda chiamata immediata non rimuove nulla.
* Log su console + entry in errori[] severity:info per visibilita. */
purgeOldSoftDeleted() {
try {
const cutoff = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000).toISOString();
let purged = 0;
if (Array.isArray(this.dati.proprieta)) {
const propsToPurge = this.dati.proprieta.filter(p => p.deletedAt && p.deletedAt < cutoff).map(p => p.id);
if (propsToPurge.length > 0) {
this.dati.proprieta = this.dati.proprieta.filter(p => !propsToPurge.includes(p.id));
// Cascading hard-delete sugli incassi figli (anche non-30gg, perche la proprieta non c'e piu).
if (Array.isArray(this.dati.incassiAffitti)) {
this.dati.incassiAffitti = this.dati.incassiAffitti.filter(i => !propsToPurge.includes(i.proprietaId));
}
purged += propsToPurge.length;
}
}
if (Array.isArray(this.dati.incassiAffitti)) {
const before = this.dati.incassiAffitti.length;
this.dati.incassiAffitti = this.dati.incassiAffitti.filter(i => !(i.deletedAt && i.deletedAt < cutoff));
purged += before - this.dati.incassiAffitti.length;
}
if (purged > 0) {
console.info('[purge] Auto-rimossi ' + purged + ' elementi soft-deleted >30 giorni');
this.pushErrore({ message: 'auto-purge: rimossi ' + purged + ' elementi soft-deleted >30gg', severity: 'info' });
this.salva();
}
} catch (e) {
this.pushErrore({ message: 'purgeOldSoftDeleted: ' + (e && e.message), severity: 'warn' });
}
},
// --- Snapshot ring buffer (10 stati pre-mutation) ---
pushSnapshot(preState) {
if (!preState) return;
try {
const raw = localStorage.getItem('gestione_affitti_snapshots');
const arr = raw ? JSON.parse(raw) : [];
const lista = Array.isArray(arr) ? arr : [];
lista.push({ ts: new Date().toISOString(), dati: preState });
while (lista.length > 10) lista.shift();
localStorage.setItem('gestione_affitti_snapshots', JSON.stringify(lista));
// Notifica Alpine: bump del version counter forza re-eval di snapshots()
// nei template (x-for, x-if). Senza questo, la UI ignora le scritture
// a localStorage.
this._snapshotVersion = (this._snapshotVersion || 0) + 1;
} catch (e) {
// QuotaExceededError o JSON troppo grande: log non-fatale.
this.pushErrore({ message: 'pushSnapshot: ' + (e && e.message), severity: 'warn' });
}
},
snapshots() {
// Touch reactive counter so Alpine ri-runs questo getter al bump in pushSnapshot.
void this._snapshotVersion;
try {
const raw = localStorage.getItem('gestione_affitti_snapshots');
const arr = raw ? JSON.parse(raw) : [];
return Array.isArray(arr) ? arr.slice().reverse() : [];
} catch (_) { return []; }
},
snapshotDiff(snap) {
const safeLen = (arr) => Array.isArray(arr) ? arr.filter(x => !x.deletedAt).length : 0;
const curr = {
proprieta: safeLen(this.dati.proprieta),
incassiAffitti: safeLen(this.dati.incassiAffitti),
utenze: safeLen(this.dati.utenze),
};
const past = snap && snap.dati ? {
proprieta: safeLen(snap.dati.proprieta),
incassiAffitti: safeLen(snap.dati.incassiAffitti),
utenze: safeLen(snap.dati.utenze),
} : { proprieta: 0, incassiAffitti: 0, utenze: 0 };
return {
proprieta: past.proprieta - curr.proprieta,
incassiAffitti: past.incassiAffitti - curr.incassiAffitti,
utenze: past.utenze - curr.utenze,
};
},
formatDiff(d) {
const parts = [];
for (const k of ['proprieta', 'incassiAffitti', 'utenze']) {
const v = d[k] || 0;
const sign = v > 0 ? '+' : '';
const lbl = k === 'incassiAffitti' ? 'Incassi' : (k === 'proprieta' ? 'Proprieta' : 'Utenze');
parts.push(lbl + ' ' + sign + v);
}
return parts.join(', ');
},
// --- Salute dati ---
saluteDati() {
const props = Array.isArray(this.dati.proprieta) ? this.dati.proprieta : [];
const incs = Array.isArray(this.dati.incassiAffitti) ? this.dati.incassiAffitti : [];
const utz = Array.isArray(this.dati.utenze) ? this.dati.utenze : [];
const propAttiveIds = new Set(props.filter(p => !p.deletedAt).map(p => p.id));
const incassiAttivi = incs.filter(i => !i.deletedAt);
let ultimoSync = null;
try {
const raw = localStorage.getItem('gestione_affitti_cache');
if (raw) {
const parsed = JSON.parse(raw);
if (parsed && parsed.updated_at) {
ultimoSync = new Date(parsed.updated_at).toLocaleString('it-IT');
}
}
} catch (_) {}
let dimensioneBlobKB = 0;
try {
dimensioneBlobKB = Math.round((JSON.stringify(this.dati).length / 1024) * 10) / 10;
} catch (_) {}
return {
proprietaAttive: props.filter(p => !p.deletedAt).length,
proprietaCestinate: props.filter(p => p.deletedAt).length,
incassiAttivi: incassiAttivi.length,
incassiCestinati: incs.filter(i => i.deletedAt).length,
incassiOrfani: incassiAttivi.filter(i => !propAttiveIds.has(i.proprietaId)).length,
incassiZero: incassiAttivi.filter(i => !(i.importo > 0)).length,
utenzeZero: utz.filter(u => !(u.importo > 0)).length,
ultimoSync,
dimensioneBlobKB,
};
},
async aggiornaStoragePct() {
try {
if (navigator.storage && navigator.storage.estimate) {
const est = await navigator.storage.estimate();
if (est && est.quota) {
this.storagePctValue = Math.round(((est.usage || 0) / est.quota) * 100);
return;
}
}
this.storagePctValue = null;
} catch (_) {
this.storagePctValue = null;
}
},
errori() {
try {
const raw = localStorage.getItem('errori');
const arr = raw ? JSON.parse(raw) : [];
return Array.isArray(arr) ? arr : [];
} catch (_) { return []; }
},
inviaDiagnostica() {
if (!this.supportWhatsapp) return;
const ultimi = this.errori().slice(-50);
const lines = ultimi.map(e => '[' + (e.ts || '') + '] ' + (e.message || ''));
let body = 'Diagnostica gestione-affitti\n\n' + lines.join('\n');
if (body.length > 3500) body = body.slice(-3500);
const url = 'https://wa.me/' + encodeURIComponent(this.supportWhatsapp) + '?text=' + encodeURIComponent(body);
window.open(url, '_blank', 'noopener,noreferrer');
},
ripristinaSnapshot(snap) {
if (!snap || !snap.dati) return;
if (!confirm('Ripristinare lo snapshot del ' + new Date(snap.ts).toLocaleString('it-IT') + '?\n\nLo stato attuale sara sovrascritto, INCLUSO il cestino.')) return;
this.dati = migraDati(JSON.parse(JSON.stringify(snap.dati)));
this._lastSnapshotData = JSON.parse(JSON.stringify(this.dati));
this.salva();
},
svuotaCestino() {
const items = this.cestinoItems();
if (items.length === 0) return;
if (!confirm('Svuotare il cestino? ' + items.length + ' elementi saranno eliminati definitivamente.')) return;
// Identifica le proprieta cestinate per fare cascading hard-delete dei loro incassi.
const propIdsCestinate = this.dati.proprieta.filter(p => p.deletedAt).map(p => p.id);
this.dati.proprieta = this.dati.proprieta.filter(p => !p.deletedAt);
this.dati.incassiAffitti = this.dati.incassiAffitti.filter(i => !i.deletedAt && !propIdsCestinate.includes(i.proprietaId));
this.salva();
},
// --- Soft-confirm modal Alpine (rimpiazza confirm() per importo=0) ---
softConfirm: { active: false, message: '', onConfirm: null, onCancel: null },
chiediConferma(message) {
return new Promise((resolve) => {
this.softConfirm.active = true;
this.softConfirm.message = message;
this.softConfirm.onConfirm = () => {
this.softConfirm.active = false;
this.softConfirm.onConfirm = null;
this.softConfirm.onCancel = null;
resolve(true);
};
this.softConfirm.onCancel = () => {
this.softConfirm.active = false;
this.softConfirm.onConfirm = null;
this.softConfirm.onCancel = null;
resolve(false);
};
});
},
// --- Toast generico (warn/info/success/error) — slot singolo, replace-on-new ---
toast: { active: false, type: 'info', message: '', timerId: null },
mostraToast(type, message, durata = 4000) {
if (this.toast.timerId) clearTimeout(this.toast.timerId);
this.toast.active = true;
this.toast.type = type;
this.toast.message = message;
this.toast.timerId = setTimeout(() => {
this.toast.active = false;
this.toast.timerId = null;
}, durata);
},
dismissGenericToast() {
if (this.toast.timerId) clearTimeout(this.toast.timerId);
this.toast.active = false;
this.toast.timerId = null;
},
supportWhatsapp: SUPPORT_WHATSAPP,
// --- Undo toast (5s, stack model: il nuovo rimpiazza il precedente) ---
undoToast: { active: false, message: '', undoFn: null, timerId: null, expiresAt: 0 },
mostraUndoToast(message, undoFn) {
if (this.undoToast.timerId) clearTimeout(this.undoToast.timerId);
this.undoToast.active = true;
this.undoToast.message = message;
this.undoToast.undoFn = typeof undoFn === 'function' ? undoFn : null;
this.undoToast.expiresAt = Date.now() + 5000;
this.undoToast.timerId = setTimeout(() => {
this.undoToast.active = false;
this.undoToast.undoFn = null;
this.undoToast.timerId = null;
}, 5000);
},
eseguiUndo() {
const fn = this.undoToast.undoFn;
if (this.undoToast.timerId) clearTimeout(this.undoToast.timerId);
this.undoToast.active = false;
this.undoToast.undoFn = null;
this.undoToast.timerId = null;
if (fn) try { fn(); } catch (e) { this.pushErrore({ message: 'undo: ' + (e && e.message), severity: 'error' }); }
},
dismissToast() {
if (this.undoToast.timerId) clearTimeout(this.undoToast.timerId);
this.undoToast.active = false;
this.undoToast.undoFn = null;
this.undoToast.timerId = null;
},
// --- PWA install prompt helpers (PR2a REQ-PWA-03) ---
// localStorage keys:
// gestione_affitti_session_log ISO[] (rolling 7d)
// gestione_affitti_install_dismissed_until ISO date (banner hidden until)
// gestione_affitti_installed "1" se appinstalled fired
recordSession() {
try {
const raw = localStorage.getItem('gestione_affitti_session_log');
const arr = raw ? JSON.parse(raw) : [];
const list = Array.isArray(arr) ? arr : [];
const now = new Date();
const cutoffIso = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000).toISOString();
const SESSION_GAP_MS = 30 * 60 * 1000;
const last = list.length ? new Date(list[list.length - 1]).getTime() : 0;
if (now.getTime() - last > SESSION_GAP_MS) list.push(now.toISOString());
const pruned = list.filter((iso) => iso >= cutoffIso);
localStorage.setItem('gestione_affitti_session_log', JSON.stringify(pruned));
} catch (_) {}
},
maybeShowInstallBanner() {
try {
if (localStorage.getItem('gestione_affitti_installed') === '1') return;
const dismissedUntil = localStorage.getItem('gestione_affitti_install_dismissed_until');
if (dismissedUntil && new Date().toISOString() < dismissedUntil) return;
const raw = localStorage.getItem('gestione_affitti_session_log');
const arr = raw ? JSON.parse(raw) : [];
if (!Array.isArray(arr) || arr.length < 3) return;
// Chrome/Android: serve beforeinstallprompt catturato.
// iOS Safari: nessun evento ma mostriamo comunque le istruzioni Condividi.
if (!this._isIosSafari && !this._deferredInstallPrompt) return;
this.installPromptVisible = true;
} catch (_) {}
},
async installApp() {
if (this._isIosSafari) return; // iOS: il banner mostra solo istruzioni
if (!this._deferredInstallPrompt) return;
try {
this._deferredInstallPrompt.prompt();
await this._deferredInstallPrompt.userChoice;
} catch (_) {}
this._deferredInstallPrompt = null;
this.installPromptVisible = false;
},
dismissInstallPrompt() {
try {
const INSTALL_DISMISS_DAYS = 14;
const until = new Date(Date.now() + INSTALL_DISMISS_DAYS * 24 * 60 * 60 * 1000).toISOString();
localStorage.setItem('gestione_affitti_install_dismissed_until', until);
} catch (_) {}
this.installPromptVisible = false;
},
/** Aggiunge un'entry al ring buffer FIFO di 50 errori in localStorage.errori.
* Mai re-throwa: solo log + storage. Filtra implicitamente i campi: niente PII. */
pushErrore(entry) {
try {
const raw = localStorage.getItem('errori');
const arr = raw ? JSON.parse(raw) : [];
const lista = Array.isArray(arr) ? arr : [];
lista.push({
ts: entry && entry.ts ? entry.ts : new Date().toISOString(),
message: entry && entry.message ? String(entry.message).slice(0, 500) : '',
stack: entry && entry.stack ? String(entry.stack).slice(0, 1000) : null,
url: entry && entry.url ? String(entry.url).slice(0, 300) : null,
line: entry && typeof entry.line === 'number' ? entry.line : null,
severity: entry && entry.severity ? entry.severity : 'error',
});
while (lista.length > 50) lista.shift();
localStorage.setItem('errori', JSON.stringify(lista));
} catch (_) {
// Quota piena o storage non disponibile: silenzioso (non vogliamo loop di errori).
}
},
// --- Autenticazione ---
async eseguiLogin() {
this.authLoading = true; this.authError = ''; this.authInfo = '';
try {
const { data, error } = await sb.auth.signInWithPassword({
email: this.authEmail.trim(),
password: this.authPassword
});
if (error) throw error;
this.utente = data.user;
this.authPassword = '';
await this.caricaDatiUtente();
} catch(e) {
this.authError = this.traduciErroreAuth(e.message);
} finally {
this.authLoading = false;
}
},
async eseguiSignup() {
this.authLoading = true; this.authError = ''; this.authInfo = '';
try {
const { data, error } = await sb.auth.signUp({
email: this.authEmail.trim(),
password: this.authPassword
});
if (error) throw error;
// Se Supabase richiede conferma email, session e null
if (!data.session) {
this.authInfo = 'Ti abbiamo inviato una email di conferma. Clicca il link per attivare l\'account, poi torna qui per accedere.';
this.modalitaAuth = 'login';
} else {
// Altrimenti login automatico
this.utente = data.user;
this.authPassword = '';
await this.caricaDatiUtente();
}
} catch(e) {
this.authError = this.traduciErroreAuth(e.message);
} finally {
this.authLoading = false;
}
},
async eseguiLogout() {
await sb.auth.signOut();
this.utente = null;
this.dati = { proprieta: [], banche: [], incassiAffitti: [], utenze: [] };
this.authEmail = ''; this.authPassword = '';
},
traduciErroreAuth(msg) {
if (/invalid login credentials/i.test(msg)) return 'Email o password errati.';
if (/email not confirmed/i.test(msg)) return 'Email non ancora confermata. Controlla la tua casella.';
if (/user already registered/i.test(msg)) return 'Esiste gia un account con questa email. Prova ad accedere.';
if (/password should be at least/i.test(msg)) return 'La password deve essere di almeno 6 caratteri.';
if (/invalid.*email/i.test(msg)) return 'Email non valida.';
return msg;
},
// --- Persistenza su Supabase ---
async caricaDatiUtente() {
this.statoSalvataggio = 'salvataggio';
let _primingDone = false;
try {
const { data, error } = await sb.from('user_data')
.select('data, updated_at').eq('user_id', this.utente.id).maybeSingle();
if (error) throw error;
// Conflict resolution: se la cache locale e piu recente del remoto, ri-pusha.
let cacheLocale = null;
try {
const raw = localStorage.getItem('gestione_affitti_cache');
if (raw) {
const parsed = JSON.parse(raw);
if (parsed && parsed.user_id === this.utente.id && parsed.data && parsed.updated_at) {
cacheLocale = parsed;
}
}
} catch(cacheErr) {
console.warn('Cache locale illeggibile:', cacheErr);
}
const remotoUpdatedAt = data && data.updated_at ? data.updated_at : null;
const cacheEPiuRecente = cacheLocale && (!remotoUpdatedAt || cacheLocale.updated_at > remotoUpdatedAt);
if (cacheEPiuRecente) {
// Cache locale vince: ripushiamo su Supabase senza sovrascriverla.
this.dati = migraDati(cacheLocale.data);
this._lastSnapshotData = JSON.parse(JSON.stringify(this.dati));
_primingDone = true;
this.modalitaOffline = false;
this.generaIncassiAttesi();
this.resetFormUtenza();
await this.salvaSubito();
return;
}
if (data && data.data && data.data.proprieta) {
// Dati esistenti trovati nel DB: applica migrazione se necessario
const versionePrima = data.data.dataVersion || 0;
const migrati = migraDati(data.data);
this.dati = migrati;
this.modalitaOffline = false;
if ((migrati.dataVersion || 0) !== versionePrima) {
await this.salvaSubito();
}
} else {
// Primo accesso: inizializza con dati di esempio e salva
this.dati = datiEsempio();
this.modalitaOffline = false;
await this.salvaSubito();
}
this._lastSnapshotData = JSON.parse(JSON.stringify(this.dati));
_primingDone = true;
this.generaIncassiAttesi();
this.resetFormUtenza();
this.statoSalvataggio = 'salvato';
} catch(e) {
console.error('Errore caricamento dati:', e);
// Fallback offline: tenta lettura da cache localStorage
try {
const raw = localStorage.getItem('gestione_affitti_cache');
if (raw) {
const cache = JSON.parse(raw);
if (cache && cache.user_id === this.utente.id && cache.data) {
this.dati = migraDati(cache.data);
this.modalitaOffline = true;
this.generaIncassiAttesi();
this.resetFormUtenza();
this.statoSalvataggio = 'errore';
return;
}
}
} catch(cacheErr) {
console.error('Errore lettura cache offline:', cacheErr);
}
this.statoSalvataggio = 'errore';
} finally {
// Boot/login priming per snapshot ring: garantisce che la PRIMA salva()
// successiva abbia un riferimento pre-mutation valido (vedi salva()
// commento). Idempotente: gia' impostato dai rami felici, ri-eseguito
// solo se il catch e' caduto senza primare.
if (!_primingDone && !this._lastSnapshotData) {
try {
this._lastSnapshotData = JSON.parse(JSON.stringify(this.dati));
} catch (_) {}
}
}
},
/** Salvataggio con debounce (300ms) per evitare richieste eccessive.
* La cache locale viene scritta SUBITO (non aspetta il debounce) per
* proteggere dai refresh mentre il timer e pending. */
salva() {
if (!this.utente) return;
this.statoSalvataggio = 'salvataggio';
// Snapshot pre-mutation: ogni chiamata a salva() corrisponde a UN'azione
// utente discreta (eliminaIncasso, salvaBanca, segnaIncassatoOggi, ...).
// Pushiamo qui (non in salvaSubito) perche' il debounce di 300ms coalescerebbe
// due azioni rapide consecutive in un solo salvaSubito → perderemmo lo
// snapshot intermedio (R-J: M-4 originale era directionally right ma
// posizionarlo nel debounced runner perde stati osservabili dall'utente).
// SNAP-01 fix (PR2a): defensive re-prime di _lastSnapshotData se ancora
// null al momento della prima salva() (race tra caricaDatiUtente paths o
// finally guard non eseguito). Garantisce >=1 setItem('gestione_affitti_snapshots')
// per ogni utente loggato — chiude il test snapshot.spec un-skipped.
if (!this._lastSnapshotData) {
try { this._lastSnapshotData = JSON.parse(JSON.stringify(this.dati)); } catch (_) {}
}
if (this._lastSnapshotData) {
this.pushSnapshot(this._lastSnapshotData);
}
// Aggiorna il riferimento "ultimo stato osservato" alla mutazione appena
// applicata: sara' il pre-state della prossima salva().
try {
this._lastSnapshotData = JSON.parse(JSON.stringify(this.dati));
} catch (_) {}
try {
localStorage.setItem('gestione_affitti_cache', JSON.stringify({
data: this.dati,
updated_at: new Date().toISOString(),
user_id: this.utente.id
}));
} catch(e) { console.warn('Cache eager fallita:', e); }
clearTimeout(this.debounceTimer);
this.debounceTimer = setTimeout(() => this.salvaSubito(), 300);
},
/** Salvataggio immediato su Supabase (upsert) */
async salvaSubito() {
if (!this.utente) return;
const ora = new Date().toISOString();
// Aggiorna sempre la cache locale PRIMA dell'upsert: cosi se la rete
// cade a meta operazione le modifiche non vanno perse.
const scriviCache = () => {
try {
localStorage.setItem('gestione_affitti_cache', JSON.stringify({
data: this.dati,
updated_at: ora,
user_id: this.utente.id
}));
} catch(cacheErr) {
console.warn('Impossibile aggiornare cache locale:', cacheErr);
}
};
if (this.modalitaOffline) {
// Gia offline: scrivi solo cache, non tentare la rete.
scriviCache();
this.statoSalvataggio = 'offline';
return;
}
// Bug 3 (DEC-020): catch chain a 4 branch invece di un unico mute-all.
// Ogni branch produce: cache persistente (no data loss) + classificazione
// visibile all'utente + entry in localStorage.errori per diagnostica.
const tentativoUpsert = async () => {
const { error } = await sb.from('user_data').upsert({
user_id: this.utente.id,
data: this.dati,
updated_at: ora,
});
if (error) throw error;
};
try {
await tentativoUpsert();
scriviCache();
// _lastSnapshotData NON viene aggiornato qui: la salva() chiamante
// l'ha gia' aggiornato sincronicamente. Aggiornarlo di nuovo qui
// post-await sovrascriverebbe lo stato di una mutazione utente che
// potrebbe essere arrivata nei 300ms+network successivi.
this.modalitaOffline = false;
this.statoSalvataggio = 'salvato';
} catch (e) {
const msg = (e && e.message) || '';
const code = (e && (e.code || e.status)) || '';
const isAuthExpired = /jwt expired|invalid jwt|token.*expired/i.test(msg) || code === 401 || code === '401';
const isRls = /pgrst301|42501|new row violates row-level security|row-level security/i.test(msg) || code === 403 || code === '403';
const isNetwork = !navigator.onLine || /failed to fetch|network|networkerror/i.test(msg) || (e && e.name === 'TypeError');
if (isAuthExpired) {
// Branch A: sessione scaduta → refresh + retry una volta.
try {
const { error: refreshErr } = await sb.auth.refreshSession();
if (refreshErr) throw refreshErr;
await tentativoUpsert();
scriviCache();
this.modalitaOffline = false;
this.statoSalvataggio = 'salvato';
return;
} catch (retryErr) {
scriviCache();
this.statoSalvataggio = 'errore';
this.mostraToast('warn', 'Sessione scaduta. Esegui di nuovo il login per sincronizzare.');
this.pushErrore({ message: 'auth-expired: ' + ((retryErr && retryErr.message) || msg), severity: 'error' });
return;
}
}
if (isRls) {
// Branch B: errore di permessi (RLS) → non riproponibile, log + toast.
scriviCache();
this.statoSalvataggio = 'errore';
this.mostraToast('error', 'Errore di permessi durante il salvataggio.');
this.pushErrore({ message: 'rls: ' + msg, severity: 'error' });
return;
}
if (isNetwork) {
// Branch C: rete giu → modalita offline, cache vale come source.
scriviCache();
this.modalitaOffline = true;
this.statoSalvataggio = 'offline';
this.mostraToast('warn', 'Connessione assente — modifiche salvate localmente.');
this.pushErrore({ message: 'network: ' + msg, severity: 'warn' });
return;
}
// Branch D: generico → cache + toast + log.
console.error('Errore salvataggio:', e);
scriviCache();
this.modalitaOffline = true;
this.statoSalvataggio = 'offline';
this.mostraToast('error', 'Errore inatteso durante il salvataggio.');
this.pushErrore({ message: 'save: ' + msg, severity: 'error' });
}
},
esportaJSON() {
const blob = new Blob([JSON.stringify(this.dati, null, 2)], { type: 'application/json' });
const a = document.createElement('a');
a.href = URL.createObjectURL(blob); a.download = 'dati.json'; a.click();
URL.revokeObjectURL(a.href);
},
async importaJSON(event) {
const file = event.target.files[0]; if (!file) return;
try {
const parsed = JSON.parse(await file.text());
// Bug 1 (DEC-020): import deve passare per migraDati altrimenti i JSON
// esportati con schemi v1/v2 mancano dei campi v3 (deletedAt, modificatoManualmente).
this.dati = migraDati(parsed);
this.generaIncassiAttesi();
await this.salva();
} catch(e) {
alert('Errore nel file JSON: ' + e.message);
if (typeof this.pushErrore === 'function') {
this.pushErrore({ ts: new Date().toISOString(), message: 'importaJSON: ' + (e && e.message), severity: 'error' });
}
}
},
// --- Generazione automatica incassi ---
generaIncassiAttesi() {
const adesso = new Date();
const mesi = [meseCorrente()];
if (adesso.getDate() >= 20) {
let mm = adesso.getMonth() + 2, yy = adesso.getFullYear();
if (mm > 12) { mm = 1; yy++; }
mesi.push(yy + '-' + String(mm).padStart(2, '0'));
}
for (const mese of mesi) {
for (const prop of this.attivi(this.dati.proprieta)) {
const esistente = this.attivi(this.dati.incassiAffitti).find(i => i.proprietaId === prop.id && i.mese === mese);
if (esistente) {
// Aggiorna incassi non ancora incassati con i nuovi dati della proprieta
// Bug 2 (DEC-020): rispettare modificatoManualmente, altrimenti l'edit
// utente viene sovrascritto a ogni ri-run di generaIncassiAttesi.
if (!esistente.dataIncasso && !esistente.modificatoManualmente) {
esistente.importo = prop.importoAffittoMensile;
esistente.bancaId = prop.bancaIncasso;
esistente.dataPrevista = dataPrevist(mese, prop.scadenzaAffitto);
}
continue;
}
if (prop.importoAffittoMensile > 0) {
this.dati.incassiAffitti.push({
id: uid(), proprietaId: prop.id, mese,
dataPrevista: dataPrevist(mese, prop.scadenzaAffitto),
dataIncasso: null, importo: prop.importoAffittoMensile,
bancaId: prop.bancaIncasso, girato: false,
dataGiro: null, bancaDestinazioneId: null,
currency: prop.currency || 'EUR',