| 1 |
#!/usr/bin/python3 |
| 2 |
from __future__ import annotations |
| 3 |
import argparse |
| 4 |
import contextlib |
| 5 |
import fnmatch |
| 6 |
import logging |
| 7 |
import os.path |
| 8 |
import re |
| 9 |
import shutil |
| 10 |
import sys |
| 11 |
from pathlib import Path |
| 12 |
from typing import TYPE_CHECKING, Optional, IO, Union |
| 13 |
|
| 14 |
from a38 import codec, models |
| 15 |
|
| 16 |
if TYPE_CHECKING: |
| 17 |
import fattura |
| 18 |
from .fattura import Fattura |
| 19 |
from .fattura_semplificata import FatturaElettronicaSemplificata |
| 20 |
|
| 21 |
log = logging.getLogger("a38tool") |
| 22 |
|
| 23 |
|
| 24 |
class Fail(Exception): |
| 25 |
pass |
| 26 |
|
| 27 |
|
| 28 |
class App: |
| 29 |
NAME = None |
| 30 |
|
| 31 |
def __init__(self, args): |
| 32 |
self.args = args |
| 33 |
|
| 34 |
def load_fattura(self, pathname) -> Union[Fattura, FatturaElettronicaSemplificata]: |
| 35 |
codecs = codec.Codecs() |
| 36 |
codec_cls = codecs.codec_from_filename(pathname) |
| 37 |
return codec_cls().load(pathname) |
| 38 |
|
| 39 |
@classmethod |
| 40 |
def add_subparser(cls, subparsers): |
| 41 |
name = getattr(cls, "NAME", None) |
| 42 |
if name is None: |
| 43 |
name = cls.__name__.lower() |
| 44 |
parser = subparsers.add_parser(name, help=cls.__doc__.strip()) |
| 45 |
parser.set_defaults(app=cls) |
| 46 |
return parser |
| 47 |
|
| 48 |
|
| 49 |
class Diff(App): |
| 50 |
""" |
| 51 |
show the difference between two fatture |
| 52 |
""" |
| 53 |
|
| 54 |
NAME = "diff" |
| 55 |
|
| 56 |
def __init__(self, args): |
| 57 |
super().__init__(args) |
| 58 |
self.first = args.first |
| 59 |
self.second = args.second |
| 60 |
|
| 61 |
@classmethod |
| 62 |
def add_subparser(cls, subparsers): |
| 63 |
parser = super().add_subparser(subparsers) |
| 64 |
parser.add_argument("first", help="first input file (.xml or .xml.p7m)") |
| 65 |
parser.add_argument("second", help="second input file (.xml or .xml.p7m)") |
| 66 |
return parser |
| 67 |
|
| 68 |
def run(self): |
| 69 |
first = self.load_fattura(self.first) |
| 70 |
second = self.load_fattura(self.second) |
| 71 |
from a38.diff import Diff |
| 72 |
|
| 73 |
res = Diff() |
| 74 |
first.diff(res, second) |
| 75 |
if res.differences: |
| 76 |
for d in res.differences: |
| 77 |
print(d) |
| 78 |
return 1 |
| 79 |
|
| 80 |
|
| 81 |
class Validate(App): |
| 82 |
""" |
| 83 |
validate the contents of a fattura |
| 84 |
""" |
| 85 |
|
| 86 |
NAME = "validate" |
| 87 |
|
| 88 |
def __init__(self, args): |
| 89 |
super().__init__(args) |
| 90 |
self.pathname = args.file |
| 91 |
|
| 92 |
@classmethod |
| 93 |
def add_subparser(cls, subparsers): |
| 94 |
parser = super().add_subparser(subparsers) |
| 95 |
parser.add_argument("file", help="input file (.xml or .xml.p7m)") |
| 96 |
return parser |
| 97 |
|
| 98 |
def run(self): |
| 99 |
f = self.load_fattura(self.pathname) |
| 100 |
from a38.validation import Validation |
| 101 |
|
| 102 |
res = Validation() |
| 103 |
f.validate(res) |
| 104 |
if res.warnings: |
| 105 |
for w in res.warnings: |
| 106 |
print(str(w), file=sys.stderr) |
| 107 |
if res.errors: |
| 108 |
for e in res.errors: |
| 109 |
print(str(e), file=sys.stderr) |
| 110 |
return 1 |
| 111 |
|
| 112 |
|
| 113 |
class Exporter(App): |
| 114 |
def __init__(self, args): |
| 115 |
super().__init__(args) |
| 116 |
self.files = args.files |
| 117 |
self.output = args.output |
| 118 |
self.codec = self.get_codec() |
| 119 |
|
| 120 |
def get_codec(self) -> codec.Codec: |
| 121 |
""" |
| 122 |
Instantiate the output codec to use for this exporter |
| 123 |
""" |
| 124 |
raise NotImplementedError( |
| 125 |
f"{self.__class__.__name__}.get_codec is not implemented" |
| 126 |
) |
| 127 |
|
| 128 |
def write(self, f: models.Model, file: Union[IO[str], IO[bytes]]): |
| 129 |
self.codec.write_file(f, file) |
| 130 |
|
| 131 |
@contextlib.contextmanager |
| 132 |
def open_output(self): |
| 133 |
if self.output is None: |
| 134 |
if self.codec.binary: |
| 135 |
yield sys.stdout.buffer |
| 136 |
else: |
| 137 |
yield sys.stdout |
| 138 |
else: |
| 139 |
with open(self.output, "wb" if self.codec.binary else "wt") as out: |
| 140 |
yield out |
| 141 |
|
| 142 |
def run(self): |
| 143 |
with self.open_output() as out: |
| 144 |
for pathname in self.files: |
| 145 |
f = self.load_fattura(pathname) |
| 146 |
self.write(f, out) |
| 147 |
|
| 148 |
@classmethod |
| 149 |
def add_subparser(cls, subparsers): |
| 150 |
parser = super().add_subparser(subparsers) |
| 151 |
parser.add_argument( |
| 152 |
"-o", "--output", help="output file (default: standard output)" |
| 153 |
) |
| 154 |
parser.add_argument("files", nargs="+", help="input files (.xml or .xml.p7m)") |
| 155 |
return parser |
| 156 |
|
| 157 |
|
| 158 |
class ExportJSON(Exporter): |
| 159 |
""" |
| 160 |
output a fattura in JSON |
| 161 |
""" |
| 162 |
|
| 163 |
NAME = "json" |
| 164 |
|
| 165 |
def get_codec(self) -> codec.Codec: |
| 166 |
if self.args.indent == "no": |
| 167 |
indent = None |
| 168 |
else: |
| 169 |
try: |
| 170 |
indent = int(self.args.indent) |
| 171 |
except ValueError: |
| 172 |
raise Fail("--indent argument must be an integer on 'no'") |
| 173 |
|
| 174 |
return codec.JSON(indent=indent) |
| 175 |
|
| 176 |
@classmethod |
| 177 |
def add_subparser(cls, subparsers): |
| 178 |
parser = super().add_subparser(subparsers) |
| 179 |
parser.add_argument( |
| 180 |
"--indent", |
| 181 |
default="1", |
| 182 |
help="indentation space (default: 1, use 'no' for all in one line)", |
| 183 |
) |
| 184 |
return parser |
| 185 |
|
| 186 |
|
| 187 |
class ExportYAML(Exporter): |
| 188 |
""" |
| 189 |
output a fattura in JSON |
| 190 |
""" |
| 191 |
|
| 192 |
NAME = "yaml" |
| 193 |
|
| 194 |
def get_codec(self) -> codec.Codec: |
| 195 |
return codec.YAML() |
| 196 |
|
| 197 |
|
| 198 |
class ExportXML(Exporter): |
| 199 |
""" |
| 200 |
output a fattura in XML |
| 201 |
""" |
| 202 |
|
| 203 |
NAME = "xml" |
| 204 |
|
| 205 |
def get_codec(self) -> codec.Codec: |
| 206 |
return codec.XML() |
| 207 |
|
| 208 |
|
| 209 |
class ExportPython(Exporter): |
| 210 |
""" |
| 211 |
output a fattura as Python code |
| 212 |
""" |
| 213 |
|
| 214 |
NAME = "python" |
| 215 |
|
| 216 |
def get_codec(self) -> codec.Codec: |
| 217 |
namespace = self.args.namespace |
| 218 |
if namespace == "": |
| 219 |
namespace = False |
| 220 |
|
| 221 |
return codec.Python(namespace=namespace, unformatted=self.args.unformatted) |
| 222 |
|
| 223 |
@classmethod |
| 224 |
def add_subparser(cls, subparsers): |
| 225 |
parser = super().add_subparser(subparsers) |
| 226 |
parser.add_argument( |
| 227 |
"--namespace", |
| 228 |
default=None, |
| 229 |
help="namespace to use for the model classes (default: the module fully qualified name)", |
| 230 |
) |
| 231 |
parser.add_argument( |
| 232 |
"--unformatted", |
| 233 |
action="store_true", |
| 234 |
help="disable code formatting, outputting a single-line statement", |
| 235 |
) |
| 236 |
return parser |
| 237 |
|
| 238 |
|
| 239 |
class Edit(App): |
| 240 |
""" |
| 241 |
Open a fattura for modification in a text editor |
| 242 |
""" |
| 243 |
|
| 244 |
def __init__(self, args): |
| 245 |
super().__init__(args) |
| 246 |
if self.args.style == "yaml": |
| 247 |
self.edit_codec = codec.YAML() |
| 248 |
elif self.args.style == "python": |
| 249 |
self.edit_codec = codec.Python(loadable=True) |
| 250 |
else: |
| 251 |
raise Fail(f"Unsupported edit style {self.args.style!r}") |
| 252 |
|
| 253 |
def write_out(self, f): |
| 254 |
""" |
| 255 |
Write a fattura, as much as possible over the file being edited |
| 256 |
""" |
| 257 |
codecs = codec.Codecs() |
| 258 |
codec_cls = codecs.codec_from_filename(self.args.file) |
| 259 |
if codec_cls == codec.P7M: |
| 260 |
with open(self.args.file[:-4], "wb") as fd: |
| 261 |
codec_cls().write_file(f, fd) |
| 262 |
elif codec_cls.binary: |
| 263 |
with open(self.args.file, "wb") as fd: |
| 264 |
codec_cls().write_file(f, fd) |
| 265 |
else: |
| 266 |
with open(self.args.file, "wt") as fd: |
| 267 |
codec_cls().write_file(f, fd) |
| 268 |
|
| 269 |
def run(self): |
| 270 |
f = self.load_fattura(self.args.file) |
| 271 |
f1 = self.edit_codec.interactive_edit(f) |
| 272 |
if f1 is not None and f != f1: |
| 273 |
self.write_out(f1) |
| 274 |
|
| 275 |
@classmethod |
| 276 |
def add_subparser(cls, subparsers): |
| 277 |
parser = super().add_subparser(subparsers) |
| 278 |
parser.add_argument( |
| 279 |
"-s", |
| 280 |
"--style", |
| 281 |
default="yaml", |
| 282 |
help="editable representation to use, one of 'yaml' or 'python'. Default: $(default)s", |
| 283 |
) |
| 284 |
parser.add_argument("file", help="file to edit") |
| 285 |
return parser |
| 286 |
|
| 287 |
|
| 288 |
class Renderer(App): |
| 289 |
""" |
| 290 |
Base class for CLI commands that render a Fattura |
| 291 |
""" |
| 292 |
|
| 293 |
def __init__(self, args): |
| 294 |
from a38.render import HAVE_LXML |
| 295 |
|
| 296 |
if not HAVE_LXML: |
| 297 |
raise Fail("python3-lxml is needed for XSLT based rendering") |
| 298 |
|
| 299 |
super().__init__(args) |
| 300 |
self.stylesheet = args.stylesheet |
| 301 |
self.files = args.files |
| 302 |
self.output = args.output |
| 303 |
self.force = args.force |
| 304 |
|
| 305 |
from a38.render import XSLTTransform |
| 306 |
|
| 307 |
self.transform = XSLTTransform(self.stylesheet) |
| 308 |
|
| 309 |
def render(self, f, output: str): |
| 310 |
""" |
| 311 |
Render the Fattura to the given destination file |
| 312 |
""" |
| 313 |
raise NotImplementedError( |
| 314 |
self.__class__.__name__ + ".render is not implemented" |
| 315 |
) |
| 316 |
|
| 317 |
def run(self): |
| 318 |
for pathname in self.files: |
| 319 |
dirname = os.path.normpath(os.path.dirname(pathname)) |
| 320 |
basename = os.path.basename(pathname) |
| 321 |
basename, ext = os.path.splitext(basename) |
| 322 |
output = self.output.format(dirname=dirname, basename=basename, ext=ext) |
| 323 |
if not self.force and os.path.exists(output): |
| 324 |
log.warning( |
| 325 |
"%s: output file %s already exists: skipped", pathname, output |
| 326 |
) |
| 327 |
else: |
| 328 |
log.info("%s: writing %s", pathname, output) |
| 329 |
f = self.load_fattura(pathname) |
| 330 |
self.render(f, output) |
| 331 |
|
| 332 |
@classmethod |
| 333 |
def add_subparser(cls, subparsers): |
| 334 |
parser = super().add_subparser(subparsers) |
| 335 |
parser.add_argument( |
| 336 |
"-f", "--force", action="store_true", help="overwrite existing output files" |
| 337 |
) |
| 338 |
default_output = "{dirname}/{basename}{ext}." + cls.NAME |
| 339 |
parser.add_argument( |
| 340 |
"-o", |
| 341 |
"--output", |
| 342 |
default=default_output, |
| 343 |
help="output file; use {dirname} for the source file path," |
| 344 |
" {basename} for the source file name" |
| 345 |
" (default: '" + default_output + "'", |
| 346 |
) |
| 347 |
parser.add_argument( |
| 348 |
"stylesheet", help=".xsl/.xslt stylesheet file to use for rendering" |
| 349 |
) |
| 350 |
parser.add_argument("files", nargs="+", help="input files (.xml or .xml.p7m)") |
| 351 |
return parser |
| 352 |
|
| 353 |
|
| 354 |
class RenderHTML(Renderer): |
| 355 |
""" |
| 356 |
render a Fattura as HTML using a .xslt stylesheet |
| 357 |
""" |
| 358 |
|
| 359 |
NAME = "html" |
| 360 |
|
| 361 |
def render(self, f, output): |
| 362 |
html = self.transform(f) |
| 363 |
html.write(output) |
| 364 |
|
| 365 |
|
| 366 |
class RenderPDF(Renderer): |
| 367 |
""" |
| 368 |
render a Fattura as PDF using a .xslt stylesheet |
| 369 |
""" |
| 370 |
|
| 371 |
NAME = "pdf" |
| 372 |
|
| 373 |
def __init__(self, args): |
| 374 |
super().__init__(args) |
| 375 |
self.wkhtmltopdf = shutil.which("wkhtmltopdf") |
| 376 |
if self.wkhtmltopdf is None: |
| 377 |
raise Fail("wkhtmltopdf is needed for PDF rendering") |
| 378 |
|
| 379 |
def render(self, f, output: str): |
| 380 |
self.transform.to_pdf(self.wkhtmltopdf, f, output) |
| 381 |
|
| 382 |
|
| 383 |
class UpdateCAPath(App): |
| 384 |
""" |
| 385 |
create/update an openssl CApath with CA certificates that can be used to |
| 386 |
validate digital signatures |
| 387 |
""" |
| 388 |
|
| 389 |
NAME = "update_capath" |
| 390 |
|
| 391 |
def __init__(self, args): |
| 392 |
super().__init__(args) |
| 393 |
self.destdir = Path(args.destdir) |
| 394 |
self.remove_old = args.remove_old |
| 395 |
|
| 396 |
@classmethod |
| 397 |
def add_subparser(cls, subparsers): |
| 398 |
parser = super().add_subparser(subparsers) |
| 399 |
parser.add_argument("destdir", help="CA certificate directory to update") |
| 400 |
parser.add_argument( |
| 401 |
"--remove-old", action="store_true", help="remove old certificates" |
| 402 |
) |
| 403 |
return parser |
| 404 |
|
| 405 |
def run(self): |
| 406 |
from a38 import trustedlist as tl |
| 407 |
|
| 408 |
tl.update_capath(self.destdir, remove_old=self.remove_old) |
| 409 |
|
| 410 |
|
| 411 |
class Allegati(App): |
| 412 |
""" |
| 413 |
Show the attachments in the fattura |
| 414 |
""" |
| 415 |
|
| 416 |
def __init__(self, args: argparse.Namespace) -> None: |
| 417 |
super().__init__(args) |
| 418 |
self.pathname = args.file |
| 419 |
self.ids: set[int] = set() |
| 420 |
self.globs: list[re.Pattern] = [] |
| 421 |
self.has_filter = False |
| 422 |
for pattern in self.args.attachments: |
| 423 |
self.has_filter = True |
| 424 |
if pattern.isdigit(): |
| 425 |
self.ids.add(int(pattern)) |
| 426 |
elif pattern.startswith("^"): |
| 427 |
self.globs.append(re.compile(pattern)) |
| 428 |
else: |
| 429 |
self.globs.append(re.compile(fnmatch.translate(pattern))) |
| 430 |
|
| 431 |
@classmethod |
| 432 |
def add_subparser(cls, subparsers): |
| 433 |
parser = super().add_subparser(subparsers) |
| 434 |
parser.add_argument( |
| 435 |
"--extract", "-x", action="store_true", help="extract selected attachments" |
| 436 |
) |
| 437 |
parser.add_argument( |
| 438 |
"--json", action="store_true", help="show attachments in json format" |
| 439 |
) |
| 440 |
parser.add_argument( |
| 441 |
"--yaml", action="store_true", help="show attachments in yaml format" |
| 442 |
) |
| 443 |
parser.add_argument( |
| 444 |
"--output", |
| 445 |
"-o", |
| 446 |
action="store", |
| 447 |
help="destination file name (-o file) or directory (-o dir/)", |
| 448 |
) |
| 449 |
parser.add_argument("file", help="input file (.xml or .xml.p7m)") |
| 450 |
parser.add_argument( |
| 451 |
"attachments", |
| 452 |
nargs="*", |
| 453 |
help="IDs or names of attachments to extract. Shell-like wildcards allowed, or regexps if starting with ^", |
| 454 |
) |
| 455 |
return parser |
| 456 |
|
| 457 |
def match_allegato(self, index: int, allegato: fattura.Allegati) -> bool: |
| 458 |
""" |
| 459 |
Check if the given allegato matches the attachments patterns |
| 460 |
""" |
| 461 |
if not self.has_filter: |
| 462 |
return True |
| 463 |
|
| 464 |
for id in self.ids: |
| 465 |
if index == id: |
| 466 |
return True |
| 467 |
|
| 468 |
for regex in self.globs: |
| 469 |
if regex.match(allegato.nome_attachment): |
| 470 |
return True |
| 471 |
|
| 472 |
return False |
| 473 |
|
| 474 |
def print_allegato(self, index: int, allegato: fattura.Allegati) -> None: |
| 475 |
formato = allegato.formato_attachment or "-" |
| 476 |
print(f"{index:02d}: {formato} {allegato.nome_attachment}") |
| 477 |
if allegato.descrizione_attachment: |
| 478 |
print(f" {allegato.descrizione_attachment}") |
| 479 |
|
| 480 |
def run(self): |
| 481 |
f = self.load_fattura(self.pathname) |
| 482 |
selected: list[tuple[int, fattura.Allegati]] = [] |
| 483 |
index = 1 |
| 484 |
for body in f.fattura_elettronica_body: |
| 485 |
for allegato in body.allegati: |
| 486 |
if self.match_allegato(index, allegato): |
| 487 |
selected.append((index, allegato)) |
| 488 |
index += 1 |
| 489 |
|
| 490 |
if self.args.json or self.args.yaml: |
| 491 |
output = [] |
| 492 |
for index, allegato in selected: |
| 493 |
jsonable = {"index": index} |
| 494 |
jsonable.update(allegato.to_jsonable()) |
| 495 |
jsonable.pop("attachment", None) |
| 496 |
output.append(jsonable) |
| 497 |
|
| 498 |
if self.args.json: |
| 499 |
import json |
| 500 |
|
| 501 |
json.dump(output, sys.stdout, indent=2) |
| 502 |
print() |
| 503 |
else: |
| 504 |
import yaml |
| 505 |
|
| 506 |
yaml.dump( |
| 507 |
output, |
| 508 |
stream=sys.stdout, |
| 509 |
default_flow_style=False, |
| 510 |
sort_keys=False, |
| 511 |
allow_unicode=True, |
| 512 |
explicit_start=True, |
| 513 |
Dumper=yaml.CDumper, |
| 514 |
) |
| 515 |
elif self.args.extract: |
| 516 |
destname: Optional[str] |
| 517 |
destdir: str |
| 518 |
|
| 519 |
if self.args.output: |
| 520 |
if os.path.isdir(self.args.output) or self.args.output.endswith(os.sep): |
| 521 |
destname = None |
| 522 |
destdir = self.args.output |
| 523 |
else: |
| 524 |
destname = self.args.output |
| 525 |
destdir = "." |
| 526 |
else: |
| 527 |
destname = None |
| 528 |
destdir = "." |
| 529 |
|
| 530 |
if destname is not None and len(selected) > 1: |
| 531 |
raise Fail( |
| 532 |
"there are multiple attachment to save, and--output points to a single file name" |
| 533 |
) |
| 534 |
|
| 535 |
os.makedirs(destdir, exist_ok=True) |
| 536 |
|
| 537 |
for index, allegato in selected: |
| 538 |
if destname is None: |
| 539 |
destname = os.path.basename(allegato.nome_attachment) |
| 540 |
dest = os.path.join(destdir, destname) |
| 541 |
log.info("Extracting %s to %s", allegato.nome_attachment, dest) |
| 542 |
with open(dest, "wb") as fd: |
| 543 |
fd.write(allegato.attachment) |
| 544 |
else: |
| 545 |
for index, allegato in selected: |
| 546 |
self.print_allegato(index, allegato) |
| 547 |
|
| 548 |
|
| 549 |
def main(): |
| 550 |
parser = argparse.ArgumentParser(description="Handle fattura elettronica files") |
| 551 |
parser.add_argument("--verbose", "-v", action="store_true", help="verbose output") |
| 552 |
parser.add_argument("--debug", action="store_true", help="debug output") |
| 553 |
|
| 554 |
subparsers = parser.add_subparsers(help="actions", required=True) |
| 555 |
subparsers.dest = "command" |
| 556 |
|
| 557 |
ExportJSON.add_subparser(subparsers) |
| 558 |
ExportYAML.add_subparser(subparsers) |
| 559 |
ExportXML.add_subparser(subparsers) |
| 560 |
ExportPython.add_subparser(subparsers) |
| 561 |
Edit.add_subparser(subparsers) |
| 562 |
Diff.add_subparser(subparsers) |
| 563 |
Validate.add_subparser(subparsers) |
| 564 |
RenderHTML.add_subparser(subparsers) |
| 565 |
RenderPDF.add_subparser(subparsers) |
| 566 |
UpdateCAPath.add_subparser(subparsers) |
| 567 |
Allegati.add_subparser(subparsers) |
| 568 |
|
| 569 |
args = parser.parse_args() |
| 570 |
|
| 571 |
log_format = "%(levelname)s %(message)s" |
| 572 |
level = logging.WARN |
| 573 |
if args.debug: |
| 574 |
level = logging.DEBUG |
| 575 |
elif args.verbose: |
| 576 |
level = logging.INFO |
| 577 |
logging.basicConfig(level=level, stream=sys.stderr, format=log_format) |
| 578 |
|
| 579 |
app = args.app(args) |
| 580 |
res = app.run() |
| 581 |
if isinstance(res, int): |
| 582 |
sys.exit(res) |
| 583 |
|
| 584 |
|
| 585 |
if __name__ == "__main__": |
| 586 |
try: |
| 587 |
main() |
| 588 |
except Fail as e: |
| 589 |
print(e, file=sys.stderr) |
| 590 |
sys.exit(1) |
| 591 |
except Exception: |
| 592 |
log.exception("uncaught exception") |