47 lines
1.2 KiB
Python
47 lines
1.2 KiB
Python
def _limpiar(rut: str) -> str:
|
|||
|
|
return rut.upper().replace(".", "").replace("-", "").strip()
|
||
|
|
|
||
|
|
|
||
|
|
def _calcular_dv(numero: str) -> str:
|
||
|
|
suma = 0
|
||
|
|
multiplicador = 2
|
||
|
|
for digito in reversed(numero):
|
||
|
|
suma += int(digito) * multiplicador
|
||
|
|
multiplicador = multiplicador + 1 if multiplicador < 7 else 2
|
||
|
|
|
||
|
|
resto = 11 - (suma % 11)
|
||
|
|
if resto == 11:
|
||
|
|
return "0"
|
||
|
|
if resto == 10:
|
||
|
|
return "K"
|
||
|
|
return str(resto)
|
||
|
|
|
||
|
|
|
||
|
|
def validar_rut(rut: str) -> bool:
|
||
|
|
"""
|
||
|
|
Valida un RUT chileno usando el dígito verificador módulo 11.
|
||
|
|
Acepta con o sin puntos/guión: "12345678-5", "12.345.678-5", "123456785".
|
||
|
|
"""
|
||
|
|
limpio = _limpiar(rut)
|
||
|
|
if len(limpio) < 2:
|
||
|
|
return False
|
||
|
|
|
||
|
|
numero, dv = limpio[:-1], limpio[-1]
|
||
|
|
if not numero.isdigit():
|
||
|
|
return False
|
||
|
|
|
||
|
|
return _calcular_dv(numero) == dv
|
||
|
|
|
||
|
|
|
||
|
|
def normalizar_rut(rut: str) -> str:
|
||
|
|
"""Devuelve el RUT sin puntos ni guión, en mayúsculas (ej. "123456785")."""
|
||
|
|
return _limpiar(rut)
|
||
|
|
|
||
|
|
|
||
|
|
def formatear_rut(rut: str) -> str:
|
||
|
|
"""
|
||
|
|
Devuelve el RUT en el formato que usa SAP para FederalTaxID:
|
||
|
|
"NNNNNNNN-D" (sin puntos, con guión antes del dígito verificador).
|
||
|
|
"""
|
||
|
|
limpio = _limpiar(rut)
|
||
|
|
return f"{limpio[:-1]}-{limpio[-1]}"
|