Passed
Push — main ( 731a55...984305 )
by Sat CFDI
01:46
created

satdigitalinvoice.utils.cert_info()   A

Complexity

Conditions 2

Size

Total Lines 14
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 6
dl 0
loc 14
rs 10
c 0
b 0
f 0
cc 2
nop 1
1
import os
2
import random
3
import shutil
4
from datetime import datetime
5
from uuid import UUID
6
7
from satcfdi import Signer, DatePeriod
8
9
10
def parse_date_period(periodo):
11
    fmt, period = try_parsing_date(periodo)
12
    if fmt == '%Y':
13
        return DatePeriod(period.year)
14
    if fmt == '%Y-%m':
15
        return DatePeriod(period.year, period.month)
16
    if fmt == '%Y-%m-%d':
17
        return DatePeriod(period.year, period.month, period.day)
18
19
20
def try_parsing_date(text):
21
    for fmt in ('%Y', '%Y-%m', '%Y-%m-%d'):
22
        try:
23
            return fmt, datetime.strptime(text, fmt)
24
        except ValueError:
25
            pass
26
    raise ValueError('no valid date format found')
27
28
29
def parse_ym_date(periodo):
30
    return try_parsing_date(periodo)[1]
31
32
33
def to_uuid(s):
34
    try:
35
        return UUID(s)
36
    except ValueError:
37
        return None
38
39
40
def to_int(s):
41
    try:
42
        return int(s)
43
    except ValueError:
44
        return None
45
46
47
def random_string():
48
    chars = "0123456789abcdefghijklmnopqrstuvwxzyABCDEFGHIJKLMNOPQRSTUVWXZY"
49
    return "".join(random.choice(chars) for _ in range(32))
50
51
52
def convert_ans1_date(ans1_date):
53
    return datetime.strptime(ans1_date.decode('utf-8'), '%Y%m%d%H%M%SZ')
54
55
56
def cert_info(signer: Signer):
57
    if signer:
58
        return {
59
            "NoCertificado": signer.certificate_number,
60
            # "Tipo": str(signer.type),
61
            #
62
            # "organizationName": signer.certificate.get_subject().O,
63
            # "x500UniqueIdentifier": signer.certificate.get_subject().x500UniqueIdentifier,
64
            # "serialNumber": signer.certificate.get_subject().serialNumber,
65
            # "organizationUnitName": signer.certificate.get_subject().OU,
66
            # "emailAddress": signer.certificate.get_subject().emailAddress,
67
            #
68
            "Expira": convert_ans1_date(signer.certificate.get_notAfter()),
69
            "Creado": convert_ans1_date(signer.certificate.get_notBefore()),
70
        }
71
72
73
def find_best_match(cases, emission_date):
74
    fk, fv = (None, None)
75
    for k, v in cases.items():
76
        k = parse_ym_date(k)
77
        if k <= emission_date:
78
            if fk is None or k > fk:
79
                fk, fv = k, v
80
    return fk, fv
81
82
83
def clear_directory(directory):
84
    shutil.rmtree(directory, ignore_errors=True)
85
    os.makedirs(directory, exist_ok=True)
86
87
88
# calculate the number of months between two dates
89
def months_between(d1, d2):
90
    return (d1.year - d2.year) * 12 + d1.month - d2.month
91
92
93
def add_month(d):
94
    m = d.month % 12 + 1
95
    y = d.year + d.month // 12
96
    return d.replace(year=y, month=m)
97
98
99
def load_certificate(data):
100
    if 'data' in data:
101
        return Signer.load_pkcs12(
102
            **data,
103
        )
104
    else:
105
        return Signer.load(
106
            **data,
107
        )
108
109
110
def first_duplicate(seq):
111
    seen = set()
112
    for x in seq:
113
        if x in seen:
114
            return x
115
        seen.add(x)
116
    return None
117
118
119
def parse_rango(rango):
120
    if rango == "":
121
        return 1, None
122
    if rango.isdigit():
123
        return int(rango), int(rango)
124
    if "-" in rango:
125
        start, end = rango.split("-")
126
        return int(start), int(end)
127