Passed
Push — main ( 6260f5...86e777 )
by Sat CFDI
05:29
created

satcfdi.csf._find_regimen()   A

Complexity

Conditions 3

Size

Total Lines 6
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 3.0416

Importance

Changes 0
Metric Value
cc 3
eloc 6
nop 1
dl 0
loc 6
ccs 5
cts 6
cp 0.8333
crap 3.0416
rs 10
c 0
b 0
f 0
1 1
from datetime import datetime
2 1
import requests
3 1
import urllib3
4 1
from bs4 import BeautifulSoup
5 1
from .. import __version__
6 1
from ..models import Code
7 1
from ..exceptions import ResponseError
8 1
from ..catalogs import select_all
9
10 1
try:
11 1
    urllib3.util.ssl_.DEFAULT_CIPHERS += ':HIGH:!DH'
12 1
except:
13 1
    pass
14
15
16 1
def retrieve(rfc: str, id_cif: str):
17 1
    data = _request_constancia(rfc, id_cif)
18 1
    return _parse_response(data)
19
20
21 1
def url(rfc: str, id_cif: str):
22 1
    return f"https://siat.sat.gob.mx/app/qr/faces/pages/mobile/validadorqr.jsf?D1=10&D2=1&D3={id_cif}_{rfc}"
23
24
25 1
def _request_constancia(rfc: str, id_cif: str):
26 1
    res = requests.get(
27
        url=url(rfc, id_cif),
28
        headers={
29
            "User-Agent": __version__.__user_agent__,
30
        }
31
    )
32 1
    if res.ok:
33 1
        return res.content
34
    else:
35
        raise ResponseError(res)
36
37
38 1
def _find_regimen(regimen):
39 1
    regimen = regimen.rstrip('.')
40 1
    for k, v in select_all('C756_c_RegimenFiscal').items():
41 1
        if regimen.endswith(v):
42 1
            return Code(k, v)
43
    return Code(None, regimen)
44
45
46 1
def _parse_response(data):
47 1
    _REGIMENES = "Regimenes"
48 1
    html = BeautifulSoup(data, 'html.parser')
49 1
    gc_v = html.find_all(name="td", attrs={"role": "gridcell", "style": "text-align:left;"})
50 1
    if not gc_v:
51 1
        raise ValueError("'rfc' or 'id_cif' is invalid")
52 1
    gc_k = html.find_all(name="span", attrs={"style": "font-weight: bold;"})
53 1
    result = {_REGIMENES: []}
54
55 1
    for k, v in zip(gc_k, gc_v):
56 1
        k = k.text.rstrip(":")
57 1
        v = v.text
58 1
        if k.startswith("Fecha ") and v:
59 1
            v = datetime.strptime(v, "%d-%m-%Y").date()
60
61 1
        if k == 'Régimen':
62 1
            result[_REGIMENES].append({
63
                'RegimenFiscal': _find_regimen(v),
64
            })
65 1
        elif k == 'Fecha de alta':
66 1
            result[_REGIMENES][-1][k] = v
67
        else:
68 1
            result[k] = v
69
70
    return result
71