2026-09-15 16:54:29 -03:00
|
|
|
import logging
|
|
|
|
|
import os
|
|
|
|
|
|
|
|
|
|
from config import BASE_DIR
|
|
|
|
|
|
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
|
|
|
|
CAMPOS_ESPERADOS = 5 # ruc, razon_social, dv, codigo, estado
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _parsear_linea(linea, archivo_origen):
|
|
|
|
|
linea = linea.rstrip("\n").rstrip("\r")
|
|
|
|
|
if not linea.strip():
|
|
|
|
|
return None
|
|
|
|
|
|
|
|
|
|
partes = linea.split("|")
|
|
|
|
|
|
|
|
|
|
# El formato trae un pipe final -> el último elemento queda vacío, se descarta.
|
|
|
|
|
# Ojo: el campo "codigo" puede venir vacío legítimamente (doble pipe "||"),
|
|
|
|
|
# así que NO se filtran strings vacíos en el medio, solo se saca el último.
|
|
|
|
|
if partes and partes[-1] == "":
|
|
|
|
|
partes = partes[:-1]
|
|
|
|
|
|
|
|
|
|
if len(partes) != CAMPOS_ESPERADOS:
|
|
|
|
|
logger.warning("Línea con formato inesperado en %s: %r", archivo_origen, linea)
|
|
|
|
|
return None
|
|
|
|
|
|
|
|
|
|
ruc, razon_social, dv, codigo, estado = (p.strip() for p in partes)
|
|
|
|
|
return (ruc, razon_social, dv, codigo, estado, archivo_origen)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def recorrer_y_parsear(directorio_raiz=BASE_DIR):
|
|
|
|
|
"""
|
|
|
|
|
Recorre recursivamente directorio_raiz, encuentra todos los .txt
|
|
|
|
|
y devuelve una lista de tuplas listas para insertar en la base.
|
|
|
|
|
"""
|
|
|
|
|
registros = []
|
|
|
|
|
|
2026-09-16 14:24:35 -03:00
|
|
|
for carpeta_actual, _subcarpetas, archivos in sorted(os.walk(directorio_raiz)):
|
|
|
|
|
for nombre in sorted(archivos):
|
2026-09-15 16:54:29 -03:00
|
|
|
if not nombre.lower().endswith(".txt"):
|
|
|
|
|
continue
|
|
|
|
|
|
|
|
|
|
ruta_txt = os.path.join(carpeta_actual, nombre)
|
|
|
|
|
try:
|
2026-09-16 14:24:35 -03:00
|
|
|
with open(ruta_txt, "r", encoding="utf-8") as f:
|
2026-09-15 16:54:29 -03:00
|
|
|
for linea in f:
|
|
|
|
|
registro = _parsear_linea(linea, nombre)
|
|
|
|
|
if registro:
|
|
|
|
|
registros.append(registro)
|
2026-09-16 14:24:35 -03:00
|
|
|
except (OSError, UnicodeDecodeError) as e:
|
2026-09-15 16:54:29 -03:00
|
|
|
logger.error("No se pudo leer %s: %s", ruta_txt, e)
|
|
|
|
|
|
|
|
|
|
logger.info("Total de registros parseados: %d", len(registros))
|
|
|
|
|
return registros
|