-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
966 lines (902 loc) · 39.1 KB
/
index.html
File metadata and controls
966 lines (902 loc) · 39.1 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
<!DOCTYPE html>
<html lang="it">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CheckappExcel — Confronto listini Excel/CSV</title>
<meta name="description" content="Confronta due o più file Excel/CSV di listini prodotti per codice e scarica un Excel con colonne colorate. Gratis, open source, funziona nel browser.">
<meta name="author" content="Alessandro Pezzali">
<meta name="theme-color" content="#1F77B4">
<!-- Favicon -->
<link rel="icon" type="image/svg+xml" href="assets/favicon.svg">
<link rel="alternate icon" type="image/png" href="assets/apple-touch-icon.png">
<link rel="apple-touch-icon" sizes="180x180" href="assets/apple-touch-icon.png">
<!-- PWA -->
<link rel="manifest" href="manifest.json">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="default">
<meta name="apple-mobile-web-app-title" content="CheckappExcel">
<!-- Open Graph (Facebook, WhatsApp, LinkedIn) -->
<meta property="og:type" content="website">
<meta property="og:site_name" content="CheckappExcel">
<meta property="og:title" content="CheckappExcel — Confronto listini Excel/CSV">
<meta property="og:description" content="Confronta due o più file Excel/CSV di listini prodotti per codice e scarica un Excel con colonne colorate. Gratis, funziona nel browser.">
<meta property="og:url" content="https://www.alessandropezzali.it/CheckappExcel/">
<meta property="og:image" content="https://www.alessandropezzali.it/CheckappExcel/assets/og-image.png">
<meta property="og:image:width" content="1200">
<meta property="og:image:height" content="630">
<meta property="og:image:alt" content="CheckappExcel - Confronta listini Excel/CSV">
<meta property="og:locale" content="it_IT">
<!-- Twitter Card -->
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:title" content="CheckappExcel — Confronto listini Excel/CSV">
<meta name="twitter:description" content="Confronta due o più file Excel/CSV di listini per codice prodotto e scarica un Excel con colonne colorate. Gratis, nel browser.">
<meta name="twitter:image" content="https://www.alessandropezzali.it/CheckappExcel/assets/og-image.png">
<script src="https://cdn.jsdelivr.net/npm/xlsx@0.18.5/dist/xlsx.full.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/exceljs@4.4.0/dist/exceljs.min.js"></script>
<style>
:root{
--bg:#f4f6fa; --card:#ffffff; --ink:#1a2332; --muted:#5a6776;
--border:#dde3eb; --accent:#1f77b4; --accent-dark:#155a88;
--ok:#2ca02c; --warn:#d97706; --err:#c0392b;
--missing:#fff2cc; --present:#c6efce; --diff:#fce4d6;
}
*{box-sizing:border-box}
body{
margin:0; font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Arial,sans-serif;
background:var(--bg); color:var(--ink); line-height:1.5;
}
header{
background:linear-gradient(135deg,#1f77b4,#2ca02c); color:#fff;
padding:28px 20px; text-align:center;
}
header h1{margin:0; font-size:28px; font-weight:700}
header p{margin:6px 0 0; opacity:.95; font-size:15px}
.install-btn{
margin-top:14px; padding:8px 18px; border-radius:20px;
background:rgba(255,255,255,.18); color:#fff; border:1px solid rgba(255,255,255,.4);
font:inherit; font-size:14px; font-weight:500; cursor:pointer;
backdrop-filter:blur(6px); transition:.15s;
}
.install-btn:hover{background:rgba(255,255,255,.28); border-color:rgba(255,255,255,.6)}
main{max-width:960px; margin:0 auto; padding:24px 16px 60px}
.card{
background:var(--card); border:1px solid var(--border); border-radius:12px;
padding:20px; margin-bottom:18px; box-shadow:0 1px 3px rgba(0,0,0,.04);
}
.card h2{margin:0 0 12px; font-size:18px}
.drop{
border:2px dashed var(--border); border-radius:12px; padding:32px 20px;
text-align:center; cursor:pointer; transition:.15s;
background:#fafbfd;
}
.drop:hover, .drop.hover{border-color:var(--accent); background:#eef5fb}
.drop:focus{outline:none}
.drop:focus-visible{border-color:var(--accent); box-shadow:0 0 0 3px rgba(31,119,180,.22)}
.drop .drop-icon{font-size:32px; display:block; margin-bottom:4px}
.drop .drop-title{font-size:15px; font-weight:500; margin-bottom:6px}
.drop .drop-hint{display:block; color:var(--muted); font-size:13px; margin-bottom:14px}
.drop .drop-btn{
display:inline-block; padding:9px 20px; border-radius:8px;
background:var(--accent); color:#fff; font-weight:500; font-size:14px;
border:none; cursor:pointer; transition:.15s;
}
.drop .drop-btn:hover{background:var(--accent-dark)}
/* File input nascosto in modo robusto (visually-hidden pattern) */
.visually-hidden{
position:absolute !important;
width:1px !important; height:1px !important;
padding:0 !important; margin:-1px !important;
overflow:hidden !important; clip:rect(0 0 0 0) !important;
white-space:nowrap !important; border:0 !important;
}
table.files{width:100%; border-collapse:collapse; margin-top:12px}
table.files th, table.files td{
padding:8px 10px; border-bottom:1px solid var(--border);
text-align:left; font-size:14px; vertical-align:middle;
}
table.files th{color:var(--muted); font-weight:600; font-size:12px; text-transform:uppercase; letter-spacing:.04em}
table.files input[type=text]{
width:100%; padding:6px 8px; border:1px solid var(--border); border-radius:6px;
font:inherit;
}
.swatch{display:inline-block; width:14px; height:14px; border-radius:3px; vertical-align:middle; margin-right:8px}
.btn{
display:inline-flex; align-items:center; gap:6px; padding:9px 16px; border-radius:8px;
border:1px solid var(--border); background:#fff; color:var(--ink); cursor:pointer;
font:inherit; font-weight:500; transition:.15s;
}
.btn:hover{border-color:var(--accent); color:var(--accent)}
.btn.primary{background:var(--accent); color:#fff; border-color:var(--accent)}
.btn.primary:hover{background:var(--accent-dark); border-color:var(--accent-dark); color:#fff}
.btn.danger{color:var(--err); border-color:#f0cfcc}
.btn.danger:hover{background:#fdecea}
.btn:disabled{opacity:.5; cursor:not-allowed}
a.btn{text-decoration:none}
a.btn.primary{color:#fff}
a.btn.primary:hover{color:#fff}
.download-card{background:linear-gradient(135deg, #f7f9fc 0%, #eef5fb 100%)}
.download-card h2{display:flex; align-items:center; gap:8px}
.btn-sm{padding:4px 10px; font-size:13px}
.options{display:flex; gap:20px; flex-wrap:wrap; margin-top:8px}
.options label{display:flex; align-items:center; gap:6px; font-size:14px; cursor:pointer}
.run-row{display:flex; justify-content:space-between; align-items:center; gap:12px; flex-wrap:wrap}
.status{color:var(--muted); font-size:14px}
.status.error{color:var(--err); font-weight:500}
.status.ok{color:var(--ok); font-weight:500}
.stats{display:grid; grid-template-columns:repeat(auto-fit,minmax(160px,1fr)); gap:12px; margin-top:12px}
.stat{background:#f7f9fc; border:1px solid var(--border); border-radius:8px; padding:12px}
.stat .k{font-size:12px; color:var(--muted); text-transform:uppercase; letter-spacing:.04em}
.stat .v{font-size:22px; font-weight:700; margin-top:2px}
.legend{display:flex; flex-wrap:wrap; gap:14px; margin-top:10px; font-size:13px; color:var(--muted)}
.legend span{display:inline-flex; align-items:center; gap:6px}
.legend i{display:inline-block; width:14px; height:14px; border-radius:3px; border:1px solid var(--border)}
.footer{text-align:center; color:var(--muted); font-size:13px; padding:20px 10px}
.footer a{color:var(--accent); text-decoration:none}
.footer a:hover{text-decoration:underline}
.hidden{display:none !important}
details{margin-top:10px; font-size:14px}
details summary{cursor:pointer; color:var(--accent); font-weight:500}
code{background:#eef2f7; padding:1px 5px; border-radius:4px; font-size:13px}
.progress{height:6px; background:var(--border); border-radius:3px; overflow:hidden; margin-top:8px}
.progress > div{height:100%; background:var(--accent); transition:width .2s; width:0%}
</style>
</head>
<body>
<header>
<h1>📊 CheckappExcel</h1>
<p>Confronta due o più file Excel/CSV di listini per codice prodotto</p>
<button type="button" id="install-btn" class="install-btn" hidden>⬇ Installa l'app</button>
</header>
<main>
<div class="card">
<h2>1. Carica i file</h2>
<div class="drop" id="drop-zone" role="button" tabindex="0" aria-label="Seleziona o trascina file Excel/CSV">
<span class="drop-icon">📁</span>
<div class="drop-title">Trascina qui i tuoi file Excel o CSV</div>
<small class="drop-hint">Formati supportati: .xlsx, .xlsm, .xls, .csv, .tsv — minimo 2 file</small>
<button type="button" class="drop-btn" id="pick-btn">Seleziona file dal computer</button>
</div>
<input type="file" id="file-input" class="visually-hidden" multiple accept=".xlsx,.xlsm,.xls,.csv,.tsv" tabindex="-1" aria-hidden="true">
<table class="files" id="file-table" style="display:none">
<thead>
<tr>
<th style="width:30px"></th>
<th>File</th>
<th>Etichetta nel report</th>
<th style="width:90px; text-align:right">Azione</th>
</tr>
</thead>
<tbody id="file-list"></tbody>
</table>
</div>
<div class="card">
<h2>2. Opzioni</h2>
<div class="options">
<label><input type="checkbox" id="opt-merge" checked> Unisci i fogli dello stesso file</label>
<label><input type="checkbox" id="opt-case"> Codici case-sensitive</label>
<label style="display:flex; align-items:center; gap:6px">
Evidenzia variazioni prezzo >
<input type="number" id="opt-threshold" value="5" min="0" max="500" step="1"
style="width:64px; padding:5px 8px; border:1px solid var(--border); border-radius:6px; font:inherit">
%
</label>
</div>
<details>
<summary>Quali colonne vengono riconosciute?</summary>
<div style="margin-top:8px; font-size:13px; color:var(--muted)">
L'app riconosce automaticamente queste intestazioni (italiano / inglese):<br>
• <strong>codice</strong>: <code>Codice</code>, <code>cod.</code>, <code>SKU</code>, <code>ID</code>, <code>Item Code</code><br>
• <strong>descrizione</strong>: <code>Descrizione</code>, <code>Desc</code>, <code>Nome</code>, <code>Description</code><br>
• <strong>prezzo</strong>: <code>Prezzo</code>, <code>Prezzo netto</code>, <code>Prezzo listino</code>, <code>Price</code><br>
• <strong>trasporto</strong>: <code>Trasporto</code>, <code>Spese trasporto</code>, <code>Spedizione</code>, <code>Shipping</code><br>
• <strong>installazione</strong>: <code>Installazione</code>, <code>Montaggio</code>, <code>Installation</code>, <code>Setup</code>
</div>
</details>
</div>
<div class="card">
<h2>3. Avvia il confronto</h2>
<div class="run-row">
<div class="status" id="status">In attesa di almeno 2 file…</div>
<button class="btn primary" id="run-btn" disabled>▶ Confronta e scarica Excel</button>
</div>
<div class="progress hidden" id="progress"><div></div></div>
<div id="results" class="hidden" style="margin-top:16px">
<div class="stats" id="stats"></div>
<div class="legend">
<span><i style="background:#fff2cc"></i> gialla = codice assente in quel file</span>
<span><i style="background:#c6efce"></i> verde = presente solo in un file</span>
<span><i style="background:#fce4d6"></i> arancio = prezzo diverso entro soglia</span>
<span><i style="background:#f08080"></i> rossa = variazione prezzo oltre soglia</span>
</div>
</div>
</div>
<div class="card download-card">
<h2>💻 Preferisci la versione desktop?</h2>
<p style="margin:0 0 14px; color:var(--muted); font-size:14px">
Se lavori spesso con molti file, la versione Python offre CLI + interfaccia Tkinter,
gira offline, e può essere integrata in script o automazioni.
Richiede Python 3.9+.
</p>
<div style="display:flex; gap:10px; flex-wrap:wrap">
<a class="btn primary" href="https://github.com/pezzaliapp/CheckappExcel/archive/refs/heads/main.zip">
⬇ Scarica ZIP progetto
</a>
<a class="btn" href="https://github.com/pezzaliapp/CheckappExcel" target="_blank" rel="noopener">
📖 Vedi su GitHub
</a>
</div>
<p style="margin:14px 0 0; color:var(--muted); font-size:13px">
💡 <strong>Su iPhone/iPad</strong>: apri questa pagina con Safari, tocca l'icona
Condividi → "Aggiungi alla schermata Home" per installare l'app.
</p>
</div>
<div class="footer">
Tutto il confronto avviene nel tuo browser, nessun file viene caricato su server.<br>
© 2026 <a href="https://github.com/pezzaliapp" target="_blank" rel="noopener">Alessandro Pezzali</a>
— rilasciato con licenza MIT
— <a href="https://github.com/pezzaliapp/CheckappExcel" target="_blank" rel="noopener">codice sorgente su GitHub</a>
</div>
</main>
<script>
/* ========================================================================
CheckappExcel — versione web (client-side)
======================================================================== */
const COLUMN_ALIASES = {
codice: ['codice','cod','cod.','cod prodotto','codice prodotto','codice articolo',
'articolo','sku','id','item code','code'],
descrizione: ['descrizione','desc','desc.','descrizione prodotto','denominazione',
'nome','description','prodotto','product',
'descrizione tecnica','descrizione commerciale','descrizione breve',
'nome breve','nome commerciale','nome prodotto','nome articolo',
'titolo','item description','product description'],
prezzo: ['prezzo','prezzo unitario','prezzo netto','prezzo listino','importo',
'costo','price','unit price',
'prezzo lordo','prezzolordo','prezzo netto listino',
'listino','list price','net price','gross price'],
trasporto: ['trasporto','spese trasporto','spedizione','costo trasporto',
'costotrasporto','spese di trasporto','shipping','transport',
'shipping cost','trasporto e spedizione','spese spedizione'],
installazione: ['installazione','montaggio','installazione/montaggio',
'costo installazione','costoinstallazione','costo montaggio',
'spese installazione','spese montaggio','setup',
'installation','installation cost','assembly'],
};
const COMPARISON_FIELDS = ['descrizione','prezzo','trasporto','installazione'];
const FILE_COLORS = ['1F77B4','2CA02C','FF7F0E','9467BD','17BECF','BCBD22','8C564B','E377C2'];
const COLOR_MISSING = 'FFF2CC';
const COLOR_PRESENT_ONLY = 'C6EFCE';
const COLOR_PRICE_DIFF = 'FCE4D6';
const COLOR_PRICE_VAR_HIGH = 'F08080';
const COLOR_KEY_FILL = 'D9E1F2';
const COLOR_STATUS_ALL = 'C6EFCE';
const COLOR_STATUS_PART = 'FFF2CC';
const COLOR_STATUS_UNIQ = 'F8CBAD';
// -------- lookup alias
const ALIAS_LOOKUP = (() => {
const map = {};
for (const [canon, list] of Object.entries(COLUMN_ALIASES)) {
for (const v of list) map[norm(v)] = canon;
map[norm(canon)] = canon;
}
return map;
})();
function norm(s){
let v = String(s ?? '').trim().toLowerCase();
v = v.replace(/[_\-\/]+/g, ' '); // underscore/trattino/slash → spazio
v = v.replace(/\s+/g, ' ').trim(); // spazi multipli
// rimuovi suffisso valuta finale: eur, euro, €, usd, $
v = v.replace(/\s*[\(\[]?\s*(eur|euro|€|usd|\$)\s*[\)\]]?\s*$/i, '').trim();
v = v.replace(/^[\.\,\:;]+|[\.\,\:;]+$/g, '').trim();
return v;
}
function normalizeCode(v, {caseSensitive, strip=true}){
if (v === null || v === undefined) return null;
let s = String(v);
if (strip) s = s.trim();
if (!s) return null;
// gestisci numerici tipo 12345.0 -> "12345"
if (/^-?\d+(\.\d+)?$/.test(s.replace(',', '.'))) {
const f = parseFloat(s.replace(',', '.'));
if (Number.isInteger(f)) s = String(f);
}
if (!caseSensitive) s = s.toUpperCase();
return s;
}
function toNumber(v){
if (v === null || v === undefined || v === '') return null;
if (typeof v === 'number') return isFinite(v) ? v : null;
let s = String(v).trim().replace(/[€$\s]/g,'');
// se c'è sia punto che virgola, il punto è separatore migliaia
if (s.includes(',') && s.includes('.')) s = s.replace(/\./g,'');
s = s.replace(',', '.');
const n = parseFloat(s);
return isFinite(n) ? n : null;
}
// -------- lettura file
async function readFile(file){
const buf = await file.arrayBuffer();
const ext = (file.name.split('.').pop() || '').toLowerCase();
const wb = XLSX.read(buf, {type:'array', cellDates:false, raw:false});
const sheets = {};
for (const name of wb.SheetNames){
// Leggi come array-of-arrays così possiamo fare auto-detect dell'header
const aoa = XLSX.utils.sheet_to_json(wb.Sheets[name], {
header:1, defval:null, raw:true, blankrows:false
});
if (aoa && aoa.length) sheets[name] = aoa;
}
return {name:file.name, ext, sheets};
}
function scoreHeaderRow(values){
// Conta quanti campi canonici distinti riconosciamo in una riga
const seen = new Set();
for (const v of values){
if (v === null || v === undefined) continue;
const canon = ALIAS_LOOKUP[norm(v)];
if (canon) seen.add(canon);
}
return seen.size;
}
function detectHeaderIndex(aoa, maxScan=10){
// Se la riga 0 non è un header buono, cerca fino a maxScan righe più in basso
let bestIdx = 0;
let bestScore = aoa[0] ? scoreHeaderRow(aoa[0]) : 0;
const limit = Math.min(maxScan, aoa.length);
for (let i = 1; i < limit; i++){
const s = scoreHeaderRow(aoa[i]);
if (s > bestScore){ bestScore = s; bestIdx = i; }
}
// richiede almeno 2 campi riconosciuti (codice + uno)
return bestScore >= 2 ? bestIdx : 0;
}
function aoaToObjects(aoa){
if (!aoa || !aoa.length) return [];
const headerIdx = detectHeaderIndex(aoa);
const headers = aoa[headerIdx].map(h => (h === null || h === undefined) ? '' : String(h));
const out = [];
for (let i = headerIdx + 1; i < aoa.length; i++){
const row = aoa[i];
if (!row || row.every(c => c === null || c === undefined || c === '')) continue;
const obj = {};
headers.forEach((h, j) => { if (h) obj[h] = row[j] ?? null; });
out.push(obj);
}
return out;
}
function guessColumns(rows){
if (!rows || !rows.length) return {};
const cols = Object.keys(rows[0]);
const map = {};
for (const col of cols){
const canon = ALIAS_LOOKUP[norm(col)];
if (canon && !map[canon]) map[canon] = col;
}
return map;
}
function normalizeSheet(aoa, opts){
// aoa = array-of-arrays (leggiamo con header:1)
const rows = aoaToObjects(aoa);
if (!rows.length) return null;
const colmap = guessColumns(rows);
if (!colmap.codice) return null;
const seen = new Set();
const out = [];
for (const r of rows){
const code = normalizeCode(r[colmap.codice], opts);
if (!code) continue;
if (seen.has(code)) continue;
seen.add(code);
const rec = {codice: code};
for (const f of COMPARISON_FIELDS){
rec[f] = colmap[f] !== undefined ? r[colmap[f]] : null;
}
out.push(rec);
}
return out;
}
function flattenSource(source, label, opts){
const result = [];
const sheetEntries = Object.entries(source.sheets)
.map(([name, rows]) => [name, normalizeSheet(rows, opts)])
.filter(([_, n]) => n && n.length);
if (!sheetEntries.length) return result;
if (opts.mergeSheets || sheetEntries.length === 1){
if (sheetEntries.length === 1){
result.push({label, rows: sheetEntries[0][1]});
return result;
}
// Merge intelligente: per ogni codice, riempi i campi vuoti
// con i valori trovati negli altri fogli.
const combined = new Map(); // codice -> record
const order = [];
const isEmpty = v => v === null || v === undefined
|| (typeof v === 'number' && isNaN(v))
|| (typeof v === 'string' && v.trim() === '');
for (const [, rows] of sheetEntries){
for (const r of rows){
if (!combined.has(r.codice)){
const rec = {codice: r.codice};
for (const f of COMPARISON_FIELDS) rec[f] = null;
combined.set(r.codice, rec);
order.push(r.codice);
}
const rec = combined.get(r.codice);
for (const f of COMPARISON_FIELDS){
if (isEmpty(rec[f]) && !isEmpty(r[f])) rec[f] = r[f];
}
}
}
const merged = order.map(c => combined.get(c));
result.push({label, rows: merged});
} else {
for (const [name, rows] of sheetEntries){
result.push({label:`${label} / ${name}`, rows});
}
}
return result;
}
// -------- confronto
function compare(flatList){
const labels = flatList.map(f => f.label);
const codes = [];
const seen = new Set();
for (const {rows} of flatList){
for (const r of rows){
if (!seen.has(r.codice)){ seen.add(r.codice); codes.push(r.codice); }
}
}
// index per label
const indexes = flatList.map(({rows}) => {
const m = new Map();
for (const r of rows) m.set(r.codice, r);
return m;
});
const wide = codes.map(code => {
const row = {codice: code, _present: []};
flatList.forEach(({label}, i) => {
const rec = indexes[i].get(code);
row._present.push(!!rec);
for (const f of COMPARISON_FIELDS){
row[`${label} | ${f}`] = rec ? rec[f] : null;
}
});
const nPresent = row._present.filter(Boolean).length;
if (nPresent === labels.length) row.stato = 'In tutti';
else if (nPresent === 1){
const idx = row._present.indexOf(true);
row.stato = `Solo in ${labels[idx]}`;
} else {
const missing = labels.filter((_,i)=>!row._present[i]);
row.stato = `Manca in: ${missing.join(', ')}`;
}
return row;
});
const stats = {
totale: wide.length,
inTutti: wide.filter(r => r.stato === 'In tutti').length,
soloUno: wide.filter(r => r.stato.startsWith('Solo in')).length,
parziali: wide.filter(r => r.stato.startsWith('Manca in')).length,
variazioniAlte: 0, // popolato in runCompare usando la soglia
perFile: {},
};
labels.forEach((l,i) => stats.perFile[l] = wide.filter(r => r._present[i]).length);
return {labels, table: wide, stats};
}
function countHighVariations(result, threshold){
const {labels, table} = result;
let n = 0;
table.forEach(row => {
const prices = [];
labels.forEach(l => {
const v = toNumber(row[`${l} | prezzo`]);
if (v !== null) prices.push(Math.round(v*100)/100);
});
if (new Set(prices).size <= 1) return;
const pmin = Math.min(...prices), pmax = Math.max(...prices);
if (pmin <= 0) { n++; return; }
const variation = ((pmax - pmin) / pmin) * 100;
if (variation > threshold) n++;
});
return n;
}
// -------- export Excel con ExcelJS
async function exportExcel(result){
const {labels, table, stats} = result;
const threshold = (typeof result.threshold === 'number' && result.threshold >= 0)
? result.threshold : 5;
const wb = new ExcelJS.Workbook();
wb.creator = 'CheckappExcel';
wb.created = new Date();
// foglio Riepilogo
const ws1 = wb.addWorksheet('Riepilogo');
ws1.getCell('A1').value = 'CheckappExcel — Riepilogo confronto';
ws1.getCell('A1').font = {bold:true, size:14};
const summaryRows = [
['Totale codici distinti', stats.totale],
['Presenti in tutti i file', stats.inTutti],
['Presenti solo in uno', stats.soloUno],
['Parzialmente presenti', stats.parziali],
];
summaryRows.forEach((r, i) => {
ws1.getCell(3+i, 1).value = r[0];
ws1.getCell(3+i, 1).font = {bold:true};
ws1.getCell(3+i, 2).value = r[1];
});
let r = 3 + summaryRows.length + 1;
ws1.getCell(r,1).value = 'Conteggio per file'; ws1.getCell(r,1).font = {bold:true}; r++;
ws1.getCell(r,1).value = 'File'; ws1.getCell(r,1).font = {bold:true};
ws1.getCell(r,2).value = 'N. codici'; ws1.getCell(r,2).font = {bold:true}; r++;
labels.forEach((label, i) => {
const color = FILE_COLORS[i % FILE_COLORS.length];
const c = ws1.getCell(r, 1);
c.value = label;
c.fill = {type:'pattern', pattern:'solid', fgColor:{argb:'FF'+color}};
c.font = {bold:true, color:{argb:'FFFFFFFF'}};
ws1.getCell(r, 2).value = stats.perFile[label];
r++;
});
r += 1;
ws1.getCell(r,1).value = 'Legenda'; ws1.getCell(r,1).font = {bold:true}; r++;
const legend = [
['Cella gialla = codice assente in quel file', COLOR_MISSING],
['Cella verde = codice presente solo in un file', COLOR_PRESENT_ONLY],
['Cella arancio = prezzo diverso (entro la soglia)', COLOR_PRICE_DIFF],
[`Cella rossa = variazione prezzo oltre ${threshold}%`, COLOR_PRICE_VAR_HIGH],
];
for (const [txt, col] of legend){
const c = ws1.getCell(r, 1);
c.value = txt;
c.fill = {type:'pattern', pattern:'solid', fgColor:{argb:'FF'+col}};
r++;
}
ws1.getColumn(1).width = 48;
ws1.getColumn(2).width = 20;
// foglio Confronto
const ws2 = wb.addWorksheet('Confronto');
// riga 1: titoli per file (merged)
ws2.getCell(1,1).value = 'Codice';
ws2.getCell(1,2).value = 'Stato';
let col = 3;
labels.forEach((label, i) => {
const color = FILE_COLORS[i % FILE_COLORS.length];
const start = col, end = col + COMPARISON_FIELDS.length - 1;
ws2.mergeCells(1, start, 1, end);
const c = ws2.getCell(1, start);
c.value = label;
c.font = {bold:true, color:{argb:'FFFFFFFF'}, size:12};
c.alignment = {horizontal:'center', vertical:'middle'};
c.fill = {type:'pattern', pattern:'solid', fgColor:{argb:'FF'+color}};
for (let k=start; k<=end; k++){
ws2.getCell(1,k).fill = {type:'pattern', pattern:'solid', fgColor:{argb:'FF'+color}};
}
col = end + 1;
});
// riga 2: nomi campi
const headers2 = ['Codice','Stato'];
labels.forEach(() => headers2.push('Descrizione','Prezzo','Trasporto','Installazione'));
headers2.forEach((h, i) => {
const c = ws2.getCell(2, i+1);
c.value = h;
c.font = {bold:true};
c.alignment = {horizontal:'center', vertical:'middle', wrapText:true};
c.border = {top:{style:'thin',color:{argb:'FFB7B7B7'}}, bottom:{style:'thin',color:{argb:'FFB7B7B7'}},
left:{style:'thin',color:{argb:'FFB7B7B7'}}, right:{style:'thin',color:{argb:'FFB7B7B7'}}};
if (i < 2){
c.fill = {type:'pattern', pattern:'solid', fgColor:{argb:'FF'+COLOR_KEY_FILL}};
} else {
const block = Math.floor((i - 2) / COMPARISON_FIELDS.length);
const color = FILE_COLORS[block % FILE_COLORS.length];
c.fill = {type:'pattern', pattern:'solid', fgColor:{argb:'FF'+color}};
c.font = {bold:true, color:{argb:'FFFFFFFF'}};
}
});
// dati
const border = {top:{style:'thin',color:{argb:'FFB7B7B7'}}, bottom:{style:'thin',color:{argb:'FFB7B7B7'}},
left:{style:'thin',color:{argb:'FFB7B7B7'}}, right:{style:'thin',color:{argb:'FFB7B7B7'}}};
table.forEach((row, idx) => {
const rowNum = 3 + idx;
// codice
const cCode = ws2.getCell(rowNum, 1);
cCode.value = row.codice;
cCode.fill = {type:'pattern', pattern:'solid', fgColor:{argb:'FF'+COLOR_KEY_FILL}};
// stato
const cStato = ws2.getCell(rowNum, 2);
cStato.value = row.stato;
if (row.stato === 'In tutti')
cStato.fill = {type:'pattern', pattern:'solid', fgColor:{argb:'FF'+COLOR_STATUS_ALL}};
else if (row.stato.startsWith('Solo in'))
cStato.fill = {type:'pattern', pattern:'solid', fgColor:{argb:'FF'+COLOR_STATUS_UNIQ}};
else
cStato.fill = {type:'pattern', pattern:'solid', fgColor:{argb:'FF'+COLOR_STATUS_PART}};
// classifica la variazione prezzo: 'same' | 'diff' | 'high'
const prices = [];
labels.forEach(l => {
const n = toNumber(row[`${l} | prezzo`]);
if (n !== null) prices.push(Math.round(n*100)/100);
});
let priceFlag = 'same';
if (new Set(prices).size > 1){
const pmin = Math.min(...prices), pmax = Math.max(...prices);
const variation = pmin > 0 ? ((pmax - pmin) / pmin) * 100 : Infinity;
priceFlag = variation > threshold ? 'high' : 'diff';
}
const nPresent = row._present.filter(Boolean).length;
let colCursor = 3;
labels.forEach((label, iLbl) => {
const isPresent = row._present[iLbl];
for (const field of COMPARISON_FIELDS){
const cell = ws2.getCell(rowNum, colCursor);
let v = row[`${label} | ${field}`];
if (v === null || v === undefined || (typeof v === 'number' && isNaN(v))) v = null;
if (['prezzo','trasporto','installazione'].includes(field)){
const n = toNumber(v);
if (n !== null){
cell.value = n;
cell.numFmt = '#,##0.00\\ "€"';
} else if (v !== null){
cell.value = v;
}
} else {
if (v !== null) cell.value = v;
}
cell.border = border;
cell.alignment = {vertical:'middle', wrapText:true};
if (!isPresent)
cell.fill = {type:'pattern', pattern:'solid', fgColor:{argb:'FF'+COLOR_MISSING}};
else if (nPresent === 1)
cell.fill = {type:'pattern', pattern:'solid', fgColor:{argb:'FF'+COLOR_PRESENT_ONLY}};
else if (field === 'prezzo'){
if (priceFlag === 'high'){
cell.fill = {type:'pattern', pattern:'solid', fgColor:{argb:'FF'+COLOR_PRICE_VAR_HIGH}};
cell.font = {bold:true, color:{argb:'FF7F0000'}};
} else if (priceFlag === 'diff'){
cell.fill = {type:'pattern', pattern:'solid', fgColor:{argb:'FF'+COLOR_PRICE_DIFF}};
}
}
colCursor++;
}
});
});
ws2.getColumn(1).width = 18;
ws2.getColumn(2).width = 28;
labels.forEach((_, iLbl) => {
const base = 3 + iLbl * COMPARISON_FIELDS.length;
ws2.getColumn(base).width = 40;
ws2.getColumn(base+1).width = 14;
ws2.getColumn(base+2).width = 14;
ws2.getColumn(base+3).width = 16;
});
ws2.views = [{state:'frozen', xSplit:2, ySplit:2}];
const lastCol = 2 + labels.length * COMPARISON_FIELDS.length;
ws2.autoFilter = {from:{row:2,column:1}, to:{row:ws2.rowCount, column:lastCol}};
// foglio Mancanti
const ws3 = wb.addWorksheet('Mancanti');
const missing = table.filter(r => r.stato !== 'In tutti');
const hdrs = ['Codice','Stato', ...labels.map(l => `In ${l}?`)];
hdrs.forEach((h,i) => {
const c = ws3.getCell(1, i+1);
c.value = h;
c.font = {bold:true, color:{argb:'FFFFFFFF'}};
c.fill = {type:'pattern', pattern:'solid', fgColor:{argb:'FF404040'}};
c.alignment = {horizontal:'center'};
});
missing.forEach((row, i) => {
const rn = i + 2;
const cCode = ws3.getCell(rn, 1);
cCode.value = row.codice;
cCode.fill = {type:'pattern', pattern:'solid', fgColor:{argb:'FF'+COLOR_KEY_FILL}};
const cSt = ws3.getCell(rn, 2);
cSt.value = row.stato;
cSt.fill = {type:'pattern', pattern:'solid',
fgColor:{argb:'FF' + (row.stato.startsWith('Solo in') ? COLOR_STATUS_UNIQ : COLOR_STATUS_PART)}};
labels.forEach((_, iLbl) => {
const has = row._present[iLbl];
const c = ws3.getCell(rn, 3 + iLbl);
c.value = has ? 'Sì' : 'No';
c.alignment = {horizontal:'center'};
c.fill = {type:'pattern', pattern:'solid',
fgColor:{argb:'FF' + (has ? COLOR_STATUS_ALL : COLOR_MISSING)}};
});
});
ws3.getColumn(1).width = 18;
ws3.getColumn(2).width = 32;
for (let i=0; i<labels.length; i++) ws3.getColumn(3+i).width = 22;
ws3.views = [{state:'frozen', ySplit:1}];
if (missing.length){
ws3.autoFilter = {from:{row:1,column:1}, to:{row:ws3.rowCount, column:2+labels.length}};
}
// download
const buf = await wb.xlsx.writeBuffer();
const blob = new Blob([buf], {type:'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'});
const ts = new Date().toISOString().replace(/[:.]/g,'-').slice(0,16);
const a = document.createElement('a');
a.href = URL.createObjectURL(blob);
a.download = `confronto_${ts}.xlsx`;
document.body.appendChild(a); a.click();
setTimeout(() => { URL.revokeObjectURL(a.href); a.remove(); }, 2000);
}
/* ========================================================================
UI
======================================================================== */
const FILES = []; // {file, label, color}
const fileInput = document.getElementById('file-input');
const fileList = document.getElementById('file-list');
const fileTable = document.getElementById('file-table');
const dropZone = document.getElementById('drop-zone');
const pickBtn = document.getElementById('pick-btn');
const runBtn = document.getElementById('run-btn');
const statusEl = document.getElementById('status');
const progressEl= document.getElementById('progress');
const resultsEl = document.getElementById('results');
const statsEl = document.getElementById('stats');
function openFileDialog(){ fileInput.click(); }
fileInput.addEventListener('change', e => addFiles(Array.from(e.target.files)));
pickBtn.addEventListener('click', e => { e.stopPropagation(); openFileDialog(); });
dropZone.addEventListener('click', e => { if (e.target === pickBtn) return; openFileDialog(); });
dropZone.addEventListener('keydown', e => {
if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); openFileDialog(); }
});
['dragenter','dragover'].forEach(ev => dropZone.addEventListener(ev, e => {e.preventDefault(); dropZone.classList.add('hover');}));
['dragleave','drop'].forEach(ev => dropZone.addEventListener(ev, e => {e.preventDefault(); dropZone.classList.remove('hover');}));
dropZone.addEventListener('drop', e => {
const files = Array.from(e.dataTransfer.files).filter(f => /\.(xlsx|xlsm|xls|csv|tsv)$/i.test(f.name));
addFiles(files);
});
function addFiles(list){
for (const f of list){
if (FILES.some(x => x.file.name === f.name && x.file.size === f.size)) continue;
FILES.push({
file: f,
label: f.name.replace(/\.(xlsx|xlsm|xls|csv|tsv)$/i,''),
color: FILE_COLORS[FILES.length % FILE_COLORS.length],
});
}
render();
fileInput.value = '';
}
function render(){
fileList.innerHTML = '';
fileTable.style.display = FILES.length ? '' : 'none';
FILES.forEach((entry, i) => {
const tr = document.createElement('tr');
tr.innerHTML = `
<td><span class="swatch" style="background:#${entry.color}"></span></td>
<td>${escapeHtml(entry.file.name)}<br><small style="color:var(--muted)">${formatSize(entry.file.size)}</small></td>
<td><input type="text" value="${escapeHtml(entry.label)}" data-i="${i}"></td>
<td style="text-align:right"><button class="btn btn-sm danger" data-rm="${i}">Rimuovi</button></td>
`;
fileList.appendChild(tr);
});
fileList.querySelectorAll('input[type=text]').forEach(inp => {
inp.addEventListener('input', e => FILES[+e.target.dataset.i].label = e.target.value);
});
fileList.querySelectorAll('button[data-rm]').forEach(btn => {
btn.addEventListener('click', e => {
FILES.splice(+e.target.dataset.rm, 1);
// ricolora
FILES.forEach((f, i) => f.color = FILE_COLORS[i % FILE_COLORS.length]);
render();
});
});
updateRunState();
}
function updateRunState(){
if (FILES.length < 2){
runBtn.disabled = true;
statusEl.className = 'status';
statusEl.textContent = `In attesa di almeno 2 file… (${FILES.length} caricato/i)`;
} else {
runBtn.disabled = false;
statusEl.className = 'status';
statusEl.textContent = `Pronto: ${FILES.length} file in confronto.`;
}
}
runBtn.addEventListener('click', runCompare);
async function runCompare(){
runBtn.disabled = true;
progressEl.classList.remove('hidden');
const bar = progressEl.firstElementChild;
bar.style.width = '10%';
resultsEl.classList.add('hidden');
statusEl.className = 'status';
statusEl.textContent = 'Lettura dei file…';
try {
const opts = {
caseSensitive: document.getElementById('opt-case').checked,
mergeSheets : document.getElementById('opt-merge').checked,
threshold : parseFloat(document.getElementById('opt-threshold').value) || 0,
};
const flat = [];
for (let i = 0; i < FILES.length; i++){
const entry = FILES[i];
statusEl.textContent = `Lettura: ${entry.file.name}…`;
const src = await readFile(entry.file);
flat.push(...flattenSource(src, entry.label || entry.file.name, opts));
bar.style.width = `${10 + 60 * (i+1) / FILES.length}%`;
}
if (flat.length < 2){
throw new Error('Non sono state trovate colonne "codice" valide in almeno 2 file/fogli. Controlla le intestazioni.');
}
statusEl.textContent = 'Confronto…';
bar.style.width = '80%';
const result = compare(flat);
result.threshold = opts.threshold;
result.stats.variazioniAlte = countHighVariations(result, opts.threshold);
statusEl.textContent = 'Generazione Excel…';
bar.style.width = '92%';
await exportExcel(result);
bar.style.width = '100%';
statusEl.className = 'status ok';
statusEl.textContent = `✓ Completato. File scaricato. ${result.stats.totale} codici totali.`;
showStats(result.stats, result.labels);
} catch (err) {
console.error(err);
statusEl.className = 'status error';
statusEl.textContent = `Errore: ${err.message || err}`;
} finally {
runBtn.disabled = FILES.length < 2;
setTimeout(() => {
progressEl.classList.add('hidden');
bar.style.width = '0%';
}, 1200);
}
}
function showStats(stats, labels){
resultsEl.classList.remove('hidden');
const cards = [
['Codici totali', stats.totale],
['In tutti i file', stats.inTutti],
['Parziali', stats.parziali],
['Solo in uno', stats.soloUno],
];
let html = '';
for (const [k,v] of cards) html += `<div class="stat"><div class="k">${k}</div><div class="v">${v}</div></div>`;
if (typeof stats.variazioniAlte === 'number'){
html += `<div class="stat" style="border-left:4px solid #e74c3c"><div class="k">Variazioni rilevanti</div><div class="v" style="color:#c0392b">${stats.variazioniAlte}</div></div>`;
}
labels.forEach((l,i) => {
const color = FILE_COLORS[i % FILE_COLORS.length];
html += `<div class="stat" style="border-left:4px solid #${color}"><div class="k">${escapeHtml(l)}</div><div class="v">${stats.perFile[l]}</div></div>`;
});
statsEl.innerHTML = html;
}
function escapeHtml(s){ return String(s ?? '').replace(/[&<>"']/g, c => ({'&':'&','<':'<','>':'>','"':'"',"'":'''})[c]); }
function formatSize(n){
if (n < 1024) return n + ' B';
if (n < 1024*1024) return (n/1024).toFixed(1) + ' KB';
return (n/1024/1024).toFixed(1) + ' MB';
}
/* ========================================================================
PWA — service worker + install prompt
======================================================================== */
if ('serviceWorker' in navigator) {
window.addEventListener('load', () => {
navigator.serviceWorker.register('sw.js').catch(err => {
console.warn('Service worker registration failed:', err);
});
});
}
let deferredPrompt = null;
const installBtn = document.getElementById('install-btn');
window.addEventListener('beforeinstallprompt', e => {
e.preventDefault();
deferredPrompt = e;
if (installBtn) installBtn.hidden = false;
});
if (installBtn) {
installBtn.addEventListener('click', async () => {
if (!deferredPrompt) return;
deferredPrompt.prompt();
const { outcome } = await deferredPrompt.userChoice;
deferredPrompt = null;
if (outcome === 'accepted') installBtn.hidden = true;
});
}
window.addEventListener('appinstalled', () => {
if (installBtn) installBtn.hidden = true;
deferredPrompt = null;
});
</script>
</body>
</html>