Passed
Push — main ( 89ce93...d5cc6d )
by Sat CFDI
01:51
created

satdigitalinvoice.utils.estado_to_estatus()   A

Complexity

Conditions 3

Size

Total Lines 6
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

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