forked from claudiopizzillo/FeCscraper
-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathxml_fatture_processor_v9.py
More file actions
3077 lines (2575 loc) · 133 KB
/
xml_fatture_processor_v9.py
File metadata and controls
3077 lines (2575 loc) · 133 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
#!/usr/bin/env python3
"""
SISTEMA INTEGRATO FATTURE ELETTRONICHE AdE - VERSIONE 4.1 CORRETTA
Integrazione completa dei sistemi di decodifica multi-strategia
Sviluppato da Salvatore Crapanzano
Caratteristiche principali:
- Download completo da portale AdE
- Decodifica P7M multi-algoritmo avanzata (ASN1, Windows API, OpenSSL)
- Organizzazione COGNOME_NOME_PARTITAIVA_CF personalizzata
- Supporto completo ricevute SDI e metadati
- Gestione avanzata duplicati e hash
- Sistema di logging professionale
- JSON fattura con versione e dati fiscali completi
"""
import requests
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
import json
import os
import sys
import re
import time
import shutil
import subprocess
import hashlib
import xml.etree.ElementTree as ET
import io
import uuid
import tempfile
import platform
from datetime import datetime, timedelta, timezone
from pathlib import Path
from typing import Dict, List, Optional, Tuple, Set, Any
import logging
from dataclasses import dataclass, asdict
import pytz
from tqdm import tqdm
from urllib.parse import unquote
import argparse
# Dipendenze avanzate per decodifica P7M
try:
from asn1crypto import cms
ASN1_AVAILABLE = True
except ImportError:
ASN1_AVAILABLE = False
print("AVVISO: asn1crypto non installata. Alcune funzionalità di decodifica P7M ridotte.")
win32crypt = None
if platform.system() == "Windows":
try:
import win32crypt
WIN32_AVAILABLE = True
except ImportError:
WIN32_AVAILABLE = False
print("AVVISO: pywin32 non disponibile su Windows.")
else:
WIN32_AVAILABLE = False
# --- CONFIGURAZIONE ---
SCRIPT_VERSION = "SISTEMA_INTEGRATO_ADE_v4.1_CORRECTED"
CONFIG_FILE = "config_ade_system.json"
DEFAULT_USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'
JSON_SCHEMA_VERSION = "1.0"
# Pattern ottimizzati per riconoscimento file
METADATA_PATTERN = r'(_MT_|[Mm][Ee][Tt][Aa][Dd][Aa][Tt][Oo])'
NOTIFICATION_PATTERN = r'_(?:NS|RC|MC|NE|DT|AT|SE)_'
SUPPORTED_EXTENSIONS = {'.xml', '.p7m'}
# --- DATACLASSES POTENZIATE ---
@dataclass
class AdvancedProcessingResult:
"""Risultato elaborazione con informazioni dettagliate su decodifica."""
file_name: str
status: str # OK, KO, SKIPPED
method_used: str
error_message: Optional[str] = None
company_name: Optional[str] = None
invoice_year: Optional[str] = None
hash_md5: Optional[str] = None
hash_sha256: Optional[str] = None
is_duplicate: bool = False
has_ritenuta: bool = False
importo_ritenuta: float = 0.0
has_cassa_previdenza: bool = False
importo_cassa_previdenza: float = 0.0
file_type: Optional[str] = None # INVOICE, METADATA, NOTIFICATION
decoding_attempts: List[str] = None
original_size: int = 0
decoded_size: int = 0
execution_time: float = 0.0
def __post_init__(self):
if self.decoding_attempts is None:
self.decoding_attempts = []
@dataclass
class FatturaMetadata:
nome_file_originale: str
id_file: str
hash_sha256: str
tipo_fattura: str
data_emissione: Optional[str] = None
data_ricezione: Optional[str] = None
anno_riferimento: Optional[int] = None
partita_iva_cedente: Optional[str] = None
partita_iva_cessionario: Optional[str] = None
codice_fiscale_cedente: Optional[str] = None
codice_fiscale_cessionario: Optional[str] = None
ha_ritenuta: bool = False
ha_cassa_previdenza: bool = False
importo_ritenuta: float = 0.0
importo_cassa_previdenza: float = 0.0
tipo_ritenuta: Optional[str] = None
ricevute_sdi: List[str] = None
stato_decodifica: str = "non_processato"
errori_decodifica: List[str] = None
timestamp_elaborazione: str = None
metodo_decodifica: Optional[str] = None
tentativi_decodifica: List[str] = None
def __post_init__(self):
if self.ricevute_sdi is None:
self.ricevute_sdi = []
if self.errori_decodifica is None:
self.errori_decodifica = []
if self.tentativi_decodifica is None:
self.tentativi_decodifica = []
if self.timestamp_elaborazione is None:
self.timestamp_elaborazione = datetime.now().isoformat()
@dataclass
class DownloadResult:
success: bool
file_path: Optional[Path] = None
metadata_path: Optional[Path] = None
ricevute_sdi_paths: List[Path] = None
error_message: Optional[str] = None
error_code: Optional[str] = None
http_status: Optional[int] = None
attempts: int = 1
url: Optional[str] = None
content_disposition_present: bool = False
last_exception: Optional[str] = None
file_type: Optional[str] = None
client_id: Optional[str] = None
def __post_init__(self):
if self.ricevute_sdi_paths is None:
self.ricevute_sdi_paths = []
@dataclass
class DecodingResult:
"""Risultato decodifica con telemetria completa."""
success: bool
method_used: str
xml_content: Optional[str] = None
execution_time: float = 0.0
input_size: int = 0
output_size: int = 0
error_details: List[str] = None
attempt_chain: List[Dict] = None
def __post_init__(self):
if self.error_details is None:
self.error_details = []
if self.attempt_chain is None:
self.attempt_chain = []
@dataclass
class OrganizationResult:
success: bool
organized_files: int = 0
decoded_files: int = 0
errors: List[str] = None
client_folders_created: Dict[str, List[str]] = None
decoding_stats: Dict[str, int] = None
def __post_init__(self):
if self.errors is None:
self.errors = []
if self.client_folders_created is None:
self.client_folders_created = {}
if self.decoding_stats is None:
self.decoding_stats = {}
@dataclass
class AliquotaIVA:
"""Singola aliquota IVA con imponibile e imposta."""
aliquota: float
imponibile: float
imposta: float
natura: Optional[str] = None
detraibile: bool = True
@dataclass
class DatiPagamento:
"""Dati di pagamento della fattura."""
condizioni_pagamento: Optional[str] = None
dettaglio_pagamento: List[Dict] = None
importo_pagamento: float = 0.0
iban: Optional[str] = None
bic: Optional[str] = None
istituto_finanziario: Optional[str] = None
def __post_init__(self):
if self.dettaglio_pagamento is None:
self.dettaglio_pagamento = []
# --- UTILITY FUNCTIONS POTENZIATE ---
def unix_timestamp():
return str(int(datetime.now(tz=pytz.utc).timestamp() * 1000))
def calculate_file_hash(file_path: Path, algorithm: str = 'sha256') -> str:
"""Calcola hash del file con algoritmo specificato."""
if algorithm == 'md5':
hash_algo = hashlib.md5()
elif algorithm == 'sha256':
hash_algo = hashlib.sha256()
else:
raise ValueError(f"Algoritmo hash non supportato: {algorithm}")
try:
with open(file_path, "rb") as f:
for chunk in iter(lambda: f.read(4096), b""):
hash_algo.update(chunk)
return hash_algo.hexdigest()
except Exception:
return ""
def calculate_content_hash(content: str) -> str:
"""Calcola hash del contenuto normalizzato."""
normalized = re.sub(r'\s+', '', content)
return hashlib.sha256(normalized.encode()).hexdigest()[:16]
def is_metadata(file_path: Path) -> bool:
"""Verifica se il file è un metadato."""
return bool(re.search(METADATA_PATTERN, file_path.name))
def is_notification(file_path: Path) -> bool:
"""Verifica se il file è una ricevuta/notifica."""
return bool(re.search(NOTIFICATION_PATTERN, file_path.name))
def is_supported_file(file_path: Path) -> bool:
"""Verifica se il file è supportato."""
return file_path.suffix.lower() in SUPPORTED_EXTENSIONS
def determine_file_type(file_path: Path) -> str:
"""Determina il tipo di file."""
if is_metadata(file_path):
return "METADATA"
elif is_notification(file_path):
return "NOTIFICATION"
elif is_supported_file(file_path):
return "INVOICE"
else:
return "UNSUPPORTED"
def safe_filename(name: str) -> str:
"""Crea nome file sicuro."""
return re.sub(r'[<>:"/\\|?*]', '_', name)[:200]
def create_personalized_directory_name(nome_azienda: str, partita_iva: str, codice_fiscale: str) -> str:
"""Crea nome directory personalizzato nel formato COGNOME_NOME_PARTITAIVA_CF"""
# Pulisce i parametri da caratteri non validi
nome_azienda_clean = safe_filename(nome_azienda.upper().strip()) if nome_azienda else "SCONOSCIUTO"
piva_clean = re.sub(r'[^0-9A-Z]', '', partita_iva.upper()) if partita_iva else "NOPIVA"
cf_clean = re.sub(r'[^0-9A-Z]', '', codice_fiscale.upper()) if codice_fiscale else "NOCF"
return f"{nome_azienda_clean}_{piva_clean}_{cf_clean}"
def extract_date_from_xml(xml_file_path: Path, file_type: str) -> Tuple[Optional[str], Optional[int]]:
try:
tree = ET.parse(xml_file_path)
root = tree.getroot()
for elem in root.iter():
if '}' in elem.tag:
elem.tag = elem.tag.split('}')[1]
data_emissione = None
anno_riferimento = None
for data_elem in root.iter('Data'):
if data_elem.text:
data_emissione = data_elem.text
try:
anno_riferimento = int(data_emissione[:4])
except:
pass
break
if not anno_riferimento:
anno_riferimento = datetime.now().year
return data_emissione, anno_riferimento
except Exception:
return None, datetime.now().year
def extract_partita_iva_from_xml(xml_file_path: Path) -> Tuple[Optional[str], Optional[str], Optional[str], Optional[str]]:
try:
tree = ET.parse(xml_file_path)
root = tree.getroot()
for elem in root.iter():
if '}' in elem.tag:
elem.tag = elem.tag.split('}')[1]
piva_cedente = None
piva_cessionario = None
cf_cedente = None
cf_cessionario = None
for cedente in root.iter('CedentePrestatore'):
for dati in cedente.iter('DatiAnagrafici'):
for piva in dati.iter('IdFiscaleIVA'):
for codice in piva.iter('IdCodice'):
piva_cedente = codice.text
break
for cf in dati.iter('CodiceFiscale'):
cf_cedente = cf.text
break
for cessionario in root.iter('CessionarioCommittente'):
for dati in cessionario.iter('DatiAnagrafici'):
for piva in dati.iter('IdFiscaleIVA'):
for codice in piva.iter('IdCodice'):
piva_cessionario = codice.text
break
for cf in dati.iter('CodiceFiscale'):
cf_cessionario = cf.text
break
return piva_cedente, piva_cessionario, cf_cedente, cf_cessionario
except Exception:
return None, None, None, None
def check_ritenuta_cassa_from_xml(xml_file_path: Path) -> Tuple[bool, bool, float, str, float]:
"""Verifica presenza ritenute e cassa previdenziale con importi."""
try:
tree = ET.parse(xml_file_path)
root = tree.getroot()
for elem in root.iter():
if '}' in elem.tag:
elem.tag = elem.tag.split('}')[1]
ha_ritenuta = False
ha_cassa = False
importo_ritenuta = 0.0
importo_cassa = 0.0
tipo_ritenuta = "N/D"
# Cerca ritenute
for elem in root.iter():
if 'ritenuta' in elem.tag.lower() or 'Ritenuta' in elem.tag:
ha_ritenuta = True
break
# Cerca cassa previdenziale
for elem in root.iter():
if 'cassa' in elem.tag.lower() or 'Cassa' in elem.tag or 'previdenza' in elem.tag.lower():
ha_cassa = True
break
# Estrae importo ritenuta
if ha_ritenuta:
for elem in root.iter('ImportoRitenuta'):
if elem.text:
try:
importo_ritenuta = float(elem.text.replace(',', '.'))
break
except:
pass
for elem in root.iter('TipoRitenuta'):
if elem.text:
tipo_ritenuta = elem.text
break
# Estrae importo cassa previdenziale
if ha_cassa:
for elem in root.iter('ImportoContributoCassa'):
if elem.text:
try:
importo_cassa = float(elem.text.replace(',', '.'))
break
except:
pass
return ha_ritenuta, ha_cassa, importo_ritenuta, tipo_ritenuta, importo_cassa
except Exception:
return False, False, 0.0, "N/D", 0.0
def divide_in_trimestri(data_iniziale: str, data_finale: str) -> List[Tuple[str, str]]:
def aggiusta_fine_trimestre(d: datetime) -> datetime:
if d.month < 4:
return datetime(d.year, 3, 31)
elif d.month < 7:
return datetime(d.year, 6, 30)
elif d.month < 10:
return datetime(d.year, 9, 30)
else:
return datetime(d.year, 12, 31)
d1 = datetime.strptime(data_iniziale, "%d%m%Y")
d2 = datetime.strptime(data_finale, "%d%m%Y")
trimestri = []
while d1 <= d2:
fine_trimestre = aggiusta_fine_trimestre(d1)
if fine_trimestre >= d2:
trimestri.append((d1.strftime("%d%m%Y"), d2.strftime("%d%m%Y")))
break
else:
trimestri.append((d1.strftime("%d%m%Y"), fine_trimestre.strftime("%d%m%Y")))
d1 = fine_trimestre + timedelta(days=1)
return trimestri
def _parse_filename_from_content_disposition(header_val: str) -> Optional[str]:
if not header_val:
return None
m_star = re.search(r"filename\*\s*=\s*([^']*)'[^']*'([^;]+)", header_val, flags=re.IGNORECASE)
if m_star:
try:
raw = m_star.group(2)
decoded = unquote(raw)
return decoded.strip('"')
except Exception:
pass
m = re.search(r'filename\s*=\s*"([^"]+)"', header_val, flags=re.IGNORECASE)
if m:
return m.group(1)
m2 = re.search(r'filename\s*=\s*([^;]+)', header_val, flags=re.IGNORECASE)
if m2:
return m2.group(1).strip().strip('"')
return None
def determine_file_type_from_path(file_path: Path) -> str:
path_str = str(file_path).lower()
if 'emesse' in path_str:
if 'transfrontalier' in path_str:
return 'transfrontaliere_emesse'
return 'emesse'
elif 'ricevute' in path_str:
if 'transfrontalier' in path_str:
return 'transfrontaliere_ricevute'
return 'ricevute'
elif 'passive' in path_str:
return 'ricevute'
elif 'transfrontalier' in path_str:
return 'transfrontaliere_ricevute'
else:
return 'ricevute'
def strip_all_suffixes(p: Path) -> str:
name = p.name
for s in p.suffixes:
if name.endswith(s):
name = name[:-len(s)]
return name
def looks_like_xml(p: Path) -> bool:
try:
head = p.read_bytes()[:256].lstrip()
return head.startswith(b'<?xml') or b'<FatturaElettronica' in head
except Exception:
return False
def canonical_targets(p: Path):
# Ritorna (src, dst) dove dst è il nome corretto se serve rinominare, altrimenti None
base = strip_all_suffixes(p)
# Caso firmato: .xml.p7m oppure solo .p7m
if p.suffixes[-2:] == ['.xml', '.p7m'] or p.suffix == '.p7m':
# Mantieni l'originale; se hai già estratto l'XML, assicurati che esista BASE.xml
return p, p.with_name(base + '.xml')
# Caso anomalo: senza estensione ma contenuto XML → aggiungi .xml
if p.suffix == '' and looks_like_xml(p):
return p, p.with_name(base + '.xml')
return p, None # nessuna azione necessaria
# Bonifica batch: aggiunge .xml ai file XML senza estensione e garantisce l'accoppiata BASE.xml per i p7m
def fix_names(root: Path):
for f in root.rglob('*'):
if not f.is_file():
continue
src, dst = canonical_targets(f)
if dst and not dst.exists():
try:
src.rename(dst)
except FileExistsError:
# Evita sovrascritture creando un nome univoco
i, candidate = 1, dst
while candidate.exists():
candidate = candidate.with_name(f"{candidate.stem}_{i}{''.join(candidate.suffixes)}")
i += 1
src.rename(candidate)
# --- SISTEMA DECODIFICA P7M AVANZATO ---
class AdvancedP7MDecoder:
"""Decodificatore P7M multi-strategia con supporto ASN1, Windows API e OpenSSL."""
def __init__(self, logger: logging.Logger):
self.logger = logger
self.stats = {
'ASN1_SUCCESS': 0,
'WINDOWS_API_SUCCESS': 0,
'OPENSSL_SUCCESS': 0,
'FAILED': 0
}
def extract_xml_from_p7m_asn1(self, p7m_content: bytes) -> Tuple[Optional[str], List[str]]:
"""Decodifica P7M usando ASN1Crypto."""
errors = []
if not ASN1_AVAILABLE:
errors.append("ASN1Crypto non disponibile")
return None, errors
try:
content_info = cms.ContentInfo.load(p7m_content)
# Metodo 1: estrazione diretta contenuto
try:
content = content_info['content']['encap_content_info']['content'].native
if isinstance(content, bytes):
xml_content = content.decode('utf-8', errors='ignore')
else:
xml_content = str(content)
if xml_content and '<?xml' in xml_content:
self.stats['ASN1_SUCCESS'] += 1
return xml_content, errors
except Exception as e:
errors.append(f"ASN1 metodo 1: {str(e)}")
# Metodo 2: estrazione ricorsiva
try:
def extract_content_recursive(obj):
if hasattr(obj, 'native') and obj.native:
content = obj.native
if isinstance(content, bytes):
try:
decoded = content.decode('utf-8', errors='ignore')
if '<?xml' in decoded:
return decoded
except:
pass
elif isinstance(content, str) and '<?xml' in content:
return content
if hasattr(obj, '__iter__') and not isinstance(obj, (str, bytes)):
try:
for item in obj:
result = extract_content_recursive(item)
if result:
return result
except:
pass
if hasattr(obj, '__dict__'):
for attr_name in dir(obj):
if not attr_name.startswith('_'):
try:
attr_value = getattr(obj, attr_name)
result = extract_content_recursive(attr_value)
if result:
return result
except:
pass
return None
xml_content = extract_content_recursive(content_info)
if xml_content:
self.stats['ASN1_SUCCESS'] += 1
return xml_content, errors
except Exception as e:
errors.append(f"ASN1 metodo 2: {str(e)}")
except Exception as e:
errors.append(f"ASN1 generale: {str(e)}")
return None, errors
def extract_xml_from_p7m_windows(self, p7m_content: bytes) -> Tuple[Optional[str], List[str]]:
"""Decodifica P7M usando Windows Crypto API."""
errors = []
if not WIN32_AVAILABLE:
errors.append("Windows Crypto API non disponibile")
return None, errors
try:
# Metodo 1: decodifica standard
try:
decoded_bytes, cert_info = win32crypt.CryptDecodeMessage(
win32crypt.PKCS_7_ASN_ENCODING | win32crypt.X509_ASN_ENCODING,
None,
win32crypt.CMSG_SIGNED,
p7m_content,
len(p7m_content)
)
xml_content = decoded_bytes.decode('utf-8', errors='ignore')
if xml_content and '<?xml' in xml_content:
self.stats['WINDOWS_API_SUCCESS'] += 1
return xml_content, errors
except Exception as e:
errors.append(f"Windows API metodo 1: {str(e)}")
# Metodo 2: verifica senza controlli
try:
decoded_bytes = win32crypt.CryptDecodeMessage(
win32crypt.PKCS_7_ASN_ENCODING,
None,
0, # Nessun controllo specifico
p7m_content,
len(p7m_content)
)[0]
xml_content = decoded_bytes.decode('utf-8', errors='ignore')
if xml_content and '<?xml' in xml_content:
self.stats['WINDOWS_API_SUCCESS'] += 1
return xml_content, errors
except Exception as e:
errors.append(f"Windows API metodo 2: {str(e)}")
except Exception as e:
errors.append(f"Windows API generale: {str(e)}")
return None, errors
def extract_xml_from_p7m_openssl(self, p7m_path: Path) -> Tuple[Optional[str], List[str]]:
"""Decodifica P7M usando OpenSSL."""
errors = []
# Lista di comandi OpenSSL da provare
commands = [
['openssl', 'cms', '-verify', '-noverify', '-inform', 'DER', '-in', str(p7m_path)],
['openssl', 'cms', '-decrypt', '-verify', '-inform', 'DER', '-in', str(p7m_path), '-noverify'],
['openssl', 'smime', '-verify', '-noverify', '-inform', 'DER', '-in', str(p7m_path)],
['openssl', 'smime', '-decrypt', '-inform', 'DER', '-in', str(p7m_path), '-noverify'],
['openssl', 'cms', '-verify', '-inform', 'PEM', '-in', str(p7m_path), '-noverify'],
['openssl', 'cms', '-decrypt', '-inform', 'PEM', '-in', str(p7m_path), '-noverify']
]
for i, command in enumerate(commands):
try:
result = subprocess.run(
command,
capture_output=True,
text=True,
timeout=60,
check=False
)
if result.returncode == 0 and result.stdout:
xml_start = result.stdout.find('<?xml')
if xml_start != -1:
xml_content = result.stdout[xml_start:]
if xml_content:
self.stats['OPENSSL_SUCCESS'] += 1
return xml_content, errors
# Prova anche stderr in caso di output misto
if result.stderr:
xml_start = result.stderr.find('<?xml')
if xml_start != -1:
xml_content = result.stderr[xml_start:]
if xml_content:
self.stats['OPENSSL_SUCCESS'] += 1
return xml_content, errors
except subprocess.TimeoutExpired:
errors.append(f"OpenSSL comando {i+1}: timeout")
except Exception as e:
errors.append(f"OpenSSL comando {i+1}: {str(e)}")
return None, errors
def decrypt_p7m_file_enhanced(self, input_file: Path, output_dir: Path) -> DecodingResult:
"""Decodifica file P7M con telemetria completa."""
if not input_file.name.lower().endswith('.p7m'):
return DecodingResult(
success=False,
method_used="NONE",
error_details=["Non è un file P7M"]
)
result = DecodingResult(success=False, method_used="NONE")
result.input_size = input_file.stat().st_size
output_dir.mkdir(parents=True, exist_ok=True)
output_name = input_file.name[:-4] if input_file.name.endswith('.p7m') else input_file.stem
output_file = output_dir / output_name
try:
p7m_content = input_file.read_bytes()
# Strategia 1: ASN1Crypto
start_time = time.time()
xml_content, asn1_errors = self.extract_xml_from_p7m_asn1(p7m_content)
execution_time = time.time() - start_time
attempt_info = {
"method": "ASN1",
"success": bool(xml_content),
"execution_time": execution_time,
"errors": asn1_errors[:2]
}
result.attempt_chain.append(attempt_info)
if xml_content:
with open(output_file, 'w', encoding='utf-8') as f:
f.write(xml_content)
result.success = True
result.method_used = "ASN1"
result.xml_content = xml_content
result.execution_time = execution_time
result.output_size = len(xml_content.encode('utf-8'))
self.logger.debug(f"Decodifica ASN1 riuscita per {input_file.name}")
return result
result.error_details.extend(asn1_errors)
# Strategia 2: Windows API (solo su Windows)
if platform.system() == "Windows":
start_time = time.time()
xml_content, win_errors = self.extract_xml_from_p7m_windows(p7m_content)
execution_time = time.time() - start_time
attempt_info = {
"method": "WINDOWS_API",
"success": bool(xml_content),
"execution_time": execution_time,
"errors": win_errors[:2]
}
result.attempt_chain.append(attempt_info)
if xml_content:
with open(output_file, 'w', encoding='utf-8') as f:
f.write(xml_content)
result.success = True
result.method_used = "WINDOWS_API"
result.xml_content = xml_content
result.execution_time = execution_time
result.output_size = len(xml_content.encode('utf-8'))
self.logger.debug(f"Decodifica Windows API riuscita per {input_file.name}")
return result
result.error_details.extend(win_errors)
# Strategia 3: OpenSSL
start_time = time.time()
xml_content, openssl_errors = self.extract_xml_from_p7m_openssl(input_file)
execution_time = time.time() - start_time
attempt_info = {
"method": "OPENSSL",
"success": bool(xml_content),
"execution_time": execution_time,
"errors": openssl_errors[:2]
}
result.attempt_chain.append(attempt_info)
if xml_content:
with open(output_file, 'w', encoding='utf-8') as f:
f.write(xml_content)
result.success = True
result.method_used = "OPENSSL"
result.xml_content = xml_content
result.execution_time = execution_time
result.output_size = len(xml_content.encode('utf-8'))
self.logger.debug(f"Decodifica OpenSSL riuscita per {input_file.name}")
return result
result.error_details.extend(openssl_errors)
except Exception as e:
result.error_details.append(f"Errore lettura file: {str(e)}")
self.stats['FAILED'] += 1
result.method_used = "FAILED"
self.logger.warning(f"Decodifica fallita per {input_file.name}")
return result
def get_statistics(self) -> Dict[str, int]:
"""Restituisce statistiche di decodifica."""
return self.stats.copy()
# --- ANALISI XML AVANZATA ---
def parse_notification_xml(xml_content: str, filename: str) -> Optional[Dict]:
"""Parser per ricevute SDI e notifiche - CORRETTO."""
try:
clean_xml = xml_content[xml_content.find('<?xml'):]
it = ET.iterparse(io.StringIO(clean_xml))
for _, el in it:
if '}' in el.tag:
el.tag = el.tag.split('}', 1)[1]
root = it.root
def get_text(path):
elem = root.find(path)
return elem.text.strip() if elem is not None and elem.text else None
# CORREZIONE: Mappatura corretta secondo standard SDI
if root.tag in ['RicevutaConsegna', 'RC']:
tipo = "Ricevuta di Consegna"
elif root.tag in ['NotificaEsito', 'NE']:
tipo = "Notifica Esito"
elif root.tag in ['NotificaMancataConsegna', 'MC']:
tipo = "Notifica Mancata Consegna"
elif root.tag in ['RicevutaScarto', 'NS']: # CORRETTO: NS solo per scarto
tipo = "Ricevuta Scarto"
elif root.tag in ['NotificaDecorrenzaTermini', 'DT']:
tipo = "Notifica Decorrenza Termini"
elif root.tag in ['AttestazioneTrasmissioneFattura', 'AT']:
tipo = "Attestazione Trasmissione"
else:
tipo = f"Ricevuta Generica ({root.tag})"
return {
"status": "OK",
"tipo_notifica": tipo,
"identificativo_sdi": get_text(".//IdentificativoSdI"),
"nome_file": get_text(".//NomeFile"),
"hash_file": get_text(".//Hash"),
"data_ora_ricezione": get_text(".//DataOraRicezione"),
"data_ora_consegna": get_text(".//DataOraConsegna"),
"riferimento_fattura": get_text(".//RiferimentoFattura"),
"posizione_nella_fattura": get_text(".//PosizioneNellaFattura"),
"raw_content": xml_content[:500] # Prime 500 caratteri per debug
}
except Exception as e:
return {
"status": "ERROR",
"error": str(e),
"tipo_notifica": "Errore parsing",
"raw_content": xml_content[:200]
}
def get_denominazione_or_nome_cognome(node) -> Tuple[str, str, str]:
"""Estrae denominazione o nome+cognome da nodo XML restituendo denominazione, nome, cognome."""
if node is None:
return "Dati anagrafici mancanti", "", ""
denominazione = node.find('Denominazione')
if denominazione is not None and denominazione.text:
return denominazione.text.strip(), "", ""
nome = node.find('Nome')
cognome = node.find('Cognome')
if nome is not None and cognome is not None:
nome_text = nome.text.strip() if nome.text else ""
cognome_text = cognome.text.strip() if cognome.text else ""
if nome_text and cognome_text:
return f"{nome_text} {cognome_text}", nome_text, cognome_text
return "Dati anagrafici mancanti", "", ""
def extract_aliquote_iva_from_xml(root) -> List[AliquotaIVA]:
"""Estrae tutte le aliquote IVA dalla fattura."""
aliquote = []
try:
for riepilogo in root.iter('DatiRiepilogo'):
aliquota_elem = riepilogo.find('AliquotaIVA')
imponibile_elem = riepilogo.find('ImponibileImporto')
imposta_elem = riepilogo.find('Imposta')
natura_elem = riepilogo.find('Natura')
if aliquota_elem is not None and imponibile_elem is not None:
try:
aliquota = float(aliquota_elem.text.replace(',', '.')) if aliquota_elem.text else 0.0
imponibile = float(imponibile_elem.text.replace(',', '.')) if imponibile_elem.text else 0.0
imposta = float(imposta_elem.text.replace(',', '.')) if imposta_elem is not None and imposta_elem.text else 0.0
natura = natura_elem.text if natura_elem is not None else None
aliquote.append(AliquotaIVA(
aliquota=aliquota,
imponibile=imponibile,
imposta=imposta,
natura=natura,
detraibile=natura is None # Se non c'è natura, è generalmente detraibile
))
except (ValueError, AttributeError):
continue
except Exception:
pass
return aliquote
def extract_dati_pagamento_from_xml(root) -> DatiPagamento:
"""Estrae i dati di pagamento dalla fattura."""
dati_pagamento = DatiPagamento()
try:
# Cerca DatiPagamento
for dati_pag in root.iter('DatiPagamento'):
# Condizioni di pagamento
cond_pag = dati_pag.find('CondizioniPagamento')
if cond_pag is not None and cond_pag.text:
dati_pagamento.condizioni_pagamento = cond_pag.text
# Dettaglio pagamento
for dettaglio in dati_pag.iter('DettaglioPagamento'):
modalita = dettaglio.find('ModalitaPagamento')
importo = dettaglio.find('ImportoPagamento')
iban = dettaglio.find('IBAN')
bic = dettaglio.find('BIC')
istituto = dettaglio.find('IstitutoFinanziario')
dettaglio_dict = {}
if modalita is not None and modalita.text:
dettaglio_dict['modalita'] = modalita.text
if importo is not None and importo.text:
try:
importo_val = float(importo.text.replace(',', '.'))
dettaglio_dict['importo'] = importo_val
dati_pagamento.importo_pagamento += importo_val
except:
pass
if iban is not None and iban.text:
dettaglio_dict['iban'] = iban.text
dati_pagamento.iban = iban.text # Prende l'ultimo IBAN trovato
if bic is not None and bic.text:
dettaglio_dict['bic'] = bic.text
dati_pagamento.bic = bic.text
if istituto is not None and istituto.text:
dettaglio_dict['istituto'] = istituto.text
dati_pagamento.istituto_finanziario = istituto.text
if dettaglio_dict:
dati_pagamento.dettaglio_pagamento.append(dettaglio_dict)
except Exception:
pass
return dati_pagamento
def parse_invoice_xml_advanced(xml_content: str) -> Optional[Dict]:
"""Parser XML fattura con estrazione completa dati fiscali."""
try:
clean_xml = xml_content[xml_content.find('<?xml'):]
it = ET.iterparse(io.StringIO(clean_xml))
for _, el in it:
if '}' in el.tag:
el.tag = el.tag.split('}', 1)[1]
root = it.root
def get_text(path):
elem = root.find(path)
return elem.text.strip() if elem is not None and elem.text else None
def get_float(path):
text = get_text(path)
if text:
try:
return float(text.replace(',', '.'))
except:
return 0.0
return 0.0
# Estrae dati anagrafici
header = root.find('FatturaElettronicaHeader')
if not header:
return None
cedente = header.find('CedentePrestatore')
cessionario = header.find('CessionarioCommittente')
body = root.find('FatturaElettronicaBody')
if not all([cedente, cessionario, body]):
return None
dati_generali = body.find('DatiGenerali')
dati_generali_documento = dati_generali.find('DatiGeneraliDocumento') if dati_generali else None
if not dati_generali_documento:
return None