Passed
Push — main ( 97b175...ba1019 )
by Sat CFDI
05:01
created

utils.verify_result()   D

Complexity

Conditions 12

Size

Total Lines 26
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 12
eloc 22
nop 2
dl 0
loc 26
rs 4.8
c 0
b 0
f 0

How to fix   Complexity   

Complexity

Complex classes like utils.verify_result() often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

1
import inspect
2
import os
3
import uuid
4
from collections import defaultdict
5
from datetime import datetime
6
from pprint import PrettyPrinter
7
8
from satcfdi.xelement import XElement
9
10
from satcfdi.models import Signer
11
from satcfdi.cfdi import CFDI
12
from satcfdi.models.certificate_store import CertificateStore
13
from satcfdi.create.cfd.tfd11 import TimbreFiscalDigital
14
15
module = 'satcfdi'
16
current_dir = os.path.dirname(__file__)
17
18
19
def stamp_v11(cfdi: CFDI, signer: Signer, date: datetime = None):
20
    timbre = TimbreFiscalDigital(
21
        proveedor=signer,
22
        uuid=str(uuid.uuid4()),
23
        sello_cfd=cfdi["Sello"],
24
        fecha_timbrado=date,
25
        leyenda=None,
26
    )
27
    if not cfdi.get("Complemento"):
28
        cfdi["Complemento"] = {}
29
30
    cfdi["Complemento"]["TimbreFiscalDigital"] = timbre
31
32
33
SAT_Certificate_Store_Pruebas = CertificateStore.create(os.path.join(current_dir, "SATCertsPruebas.zip"))
34
35
36
def get_signer(rfc: str, get_csd=False):
37
    if len(rfc) == 13:
38
        tp = "Personas Fisicas"
39
    elif len(rfc) == 12:
40
        tp = "Personas Morales"
41
    else:
42
        tp = ""
43
44
    if get_csd:
45
        app = "_csd"
46
    else:
47
        app = ""
48
49
    rfc = rfc.lower()
50
51
    return Signer.load(
52
        certificate=open(os.path.join(current_dir, f'csd/{tp}/{rfc}{app}.cer'), 'rb').read(),
53
        key=open(os.path.join(current_dir, f'csd/{tp}/{rfc}{app}.key'), 'rb').read(),
54
        password=open(os.path.join(current_dir, f'csd/{tp}/{rfc}{app}.txt'), 'rb').read()
55
    )
56
57
58
def get_rfc_pac(self):
59
    return "SAT970701NN3"
60
61
62
def _uuid():
63
    return uuid.UUID("6d7434a6-e3f2-47ad-9e4c-08849946afa0")
64
65
66
def verify_result(data, filename):
67
    calle_frame = inspect.stack()[1]
68
    caller_file = inspect.getmodule(calle_frame[0]).__file__
69
    caller_file = os.path.splitext(os.path.basename(caller_file))[0]
70
71
    if isinstance(data, bytes):
72
        ap = 'b'
73
    else:
74
        ap = ''
75
    filename_base, filename_ext = os.path.splitext(filename)
76
77
    full_path = os.path.join(current_dir, caller_file, filename_base)
78
    os.makedirs(os.path.dirname(full_path), exist_ok=True)
79
80
    try:
81
        with open(full_path + filename_ext, 'r' + ap, encoding=None if ap else 'utf-8') as f:
82
            if f.read() == data:
83
                os.remove(full_path + ".diff" + filename_ext)
84
                return True
85
        with open(full_path + ".diff" + filename_ext, 'w' + ap, encoding=None if ap else 'utf-8', newline=None if ap else '\n') as f:
86
            f.write(data)
87
        return False
88
    except FileNotFoundError:
89
        with open(full_path + filename_ext, 'w' + ap, encoding=None if ap else 'utf-8', newline=None if ap else '\n') as f:
90
            f.write(data)
91
        return True
92
93
94
class XElementPrettyPrinter(PrettyPrinter):
95
    _dispatch = PrettyPrinter._dispatch.copy()
96
    _dispatch[XElement.__repr__] = PrettyPrinter._pprint_dict
97
    _dispatch[defaultdict.__repr__] = PrettyPrinter._pprint_dict
98
99
100
if __name__ == "__main__":
101
    import os
102
103
    for f in os.listdir("cfdi//cfdv32"):
104
        print(repr('cfdv32//' + f) + ",")
105