Passed
Push — main ( b508f6...84f6d4 )
by Sat CFDI
05:19
created

satcfdi.csf._request_constancia()   A

Complexity

Conditions 3

Size

Total Lines 13
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 3.0261

Importance

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