"""ETL-MENORES-CASA · clasificador mínimo sobre los ORIGINALES (pre-registro §3 y §6, cotejo): lee los XLSX del SMS, los CSV de la CARM y los XLS/XLSX de Palma tal como se descargaron (licitaciones-historico/.../raw/), con openpyxl, xlrd y csv, y la PLACSP de MC e IB de unified_20261108 con pyarrow (sin DuckDB ni las macros del ETL, sin la salida de py/regla.py). Escrito desde el texto del pre-registro §2. Imagen del scraper (licitaciones-scrapers:vps), sin red. python3 -I banco_orig.py entrada: {"casos": [...]} de p_banco_sel.py (o del cotejo) """ import csv import datetime as dt import glob import json import os import re import sys import unicodedata from collections import defaultdict import openpyxl import pyarrow.compute as pc import pyarrow.dataset as ds import xlrd H = "" U = "/unified_20261108/source=PLACSP" IMP_MIN = 1.5 def sin_tildes(s): return "".join(ch for ch in unicodedata.normalize("NFD", s) if unicodedata.category(ch) != "Mn") def cab(s): return re.sub(r"\s+", "", sin_tildes(str(s or "")).lower()) def texto(v): if v is None: return None if isinstance(v, float) and v.is_integer(): v = int(v) s = str(v).strip() return s or None def num(v): """Importe de una celda: número tal cual; texto con coma decimal ('1004,83', '1.234,56') o punto ('33.5').""" if v is None: return None if isinstance(v, (int, float)): return float(v) s = str(v).strip().replace("€", "").replace(" ", "") if not s: return None if s.startswith((",", ".")): s = "0" + s if "," in s and "." in s: s = s.replace(".", "").replace(",", ".") if s.rfind(",") > s.rfind(".") else s.replace(",", "") elif "," in s: s = s.replace(",", ".") try: return float(s) except ValueError: return None def fecha(v, mdy=False): if v is None: return None if isinstance(v, dt.datetime): return v.date().isoformat() if isinstance(v, dt.date): return v.isoformat() s = str(v).strip() if not s: return None s0 = s.split(" ")[0] m = re.match(r"^(\d{4})-(\d{2})-(\d{2})", s0) if m: return f"{m[1]}-{m[2]}-{m[3]}" m = re.match(r"^(\d{1,2})-(\d{1,2})-(\d{2})$", s0) if m: # mm-dd-aa (CARM 2023) return f"20{m[3]}-{int(m[1]):02d}-{int(m[2]):02d}" m = re.match(r"^(\d{1,2})/(\d{1,2})/(\d{2,4})$", s0) if m: a = m[3] if len(m[3]) == 4 else "20" + m[3] return f"{a}-{int(m[2]):02d}-{int(m[1]):02d}" return None def nif_clave(v): s = texto(v) if s is None: return None s = s.upper().replace(" ", "") if "*" in s: return s if re.match(r"^(\*{3}\d{4}\*{2}|\*{4}\d{4}\*)$", s) else None s = re.sub(r"[^A-Z0-9]", "", s) if re.match(r"^ES([0-9]{8}[A-Z]|[XYZ][0-9]{7}[A-Z]|[ABCDEFGHJKLMNPQRSUVW][0-9]{7}[A-Z0-9])$", s): s = s[2:] return s or None def mascara_de(nif_raw): s = (nif_raw or "").upper() return "***" + s[3:7] + "**" if re.match(r"^([0-9]{8}|[XYZ][0-9]{7})[A-Z]$", s) else None def norm_nombre(s): if s is None: return "" return re.sub(r"[^A-Z0-9]+", " ", sin_tildes(str(s)).upper()).strip() # --- PLACSP de MC e IB (unified_20261108) -------------------------------------------------------------------------------- def placsp(): d = ds.dataset(U, format="parquet", partitioning="hive") cols = ["id_canonical", "expediente", "unidad", "ccaa", "organo_ccaa", "adjudicatario_nif", "adjudicatario_nif_raw", "imp_adj_eur", "imp_adj_eur_sin_iva", "imp_adj_eur_con_iva", "anio", "fecha_adj", "year"] f = (pc.field("unidad") == "adjudicacion") & (pc.field("ccaa").isin(["MC", "IB"]) | pc.field("organo_ccaa").isin(["MC", "IB"])) t = d.to_table(columns=cols, filter=f).to_pylist() for r in t: r["com"] = "MC" if "MC" in (r["ccaa"], r["organo_ccaa"]) else "IB" r["u_anio"] = r["anio"] if r["anio"] is not None else r["year"] r["claves"] = {x for x in (texto(r["adjudicatario_nif"]) and r["adjudicatario_nif"].upper(), mascara_de(r["adjudicatario_nif_raw"])) if x} r["imps"] = {round(x, 2) for x in (r["imp_adj_eur"], r["imp_adj_eur_sin_iva"], r["imp_adj_eur_con_iva"]) if x is not None and x >= IMP_MIN} return t def d1_sms(P, pedido): return [r["id_canonical"] for r in P if r["com"] == "MC" and re.sub(r"[^0-9]", "", r["expediente"] or "") == pedido] def d1_carm(P, exp): rx = re.compile("^" + re.escape(exp) + r"(/[0-9]+)?$") return [r["id_canonical"] for r in P if r["com"] == "MC" and rx.match((r["expediente"] or "").strip())] def d2_candidatas(P, com, k, v, y): if k is None or v is None or y is None or v < IMP_MIN: return [] return [r["id_canonical"] for r in P if r["com"] == com and k in r["claves"] and round(v, 2) in r["imps"] and r["u_anio"] is not None and abs(int(r["u_anio"]) - y) <= 1] # --- SMS ------------------------------------------------------------------------------------------------------------------ SMS_PED = {"ref.contrato", "doc.compras", "doc.compr."} SMS_NIF = {"nifadj", "cif", "adjudicatarionif", "adjudicatariocodigoof", "adjudicatariocodigo"} SMS_IMP = {"valorneto", "importeadjudicacion", "importeadjudicacioneur"} SMS_FEC = {"f.formalizacion", "fechaformalizacion"} def sms_lineas(pedidos, filas_2019): """Todas las líneas de los XLSX del SMS de los pedidos pedidos; y, de los casos de 2019, la fila idx de su hoja.""" lineas, vistas_2019, cabeceras = defaultdict(list), {}, {} for f in sorted(glob.glob(f"{H}/murcia/raw/contratos_menores_sms/*.xlsx")): wb = openpyxl.load_workbook(f, read_only=True, data_only=True) for ws in wb.worksheets: hdr, idx = None, -1 for row in ws.iter_rows(values_only=True): if hdr is None: cs = [cab(x) for x in row] if any(c in SMS_PED | {"importe(ivaincluido)"} for c in cs): hdr = cs cabeceras[(os.path.basename(f), ws.title)] = [c for c in cs if c] continue if not any(x is not None and str(x).strip() for x in row): continue idx += 1 d = dict(zip(hdr, row)) clave_2019 = (os.path.basename(f), ws.title, idx) if clave_2019 in filas_2019: vistas_2019[clave_2019] = {"tiene_pedido": any(c in SMS_PED for c in hdr), "importe": num(d.get("importe(ivaincluido)"))} p = next((texto(d[c]) for c in SMS_PED if c in d and texto(d[c])), None) if p in pedidos: lineas[p].append({"nif": next((nif_clave(d[c]) for c in SMS_NIF if c in d and texto(d[c])), None), "importe": next((num(d[c]) for c in SMS_IMP if c in d and d[c] is not None), None), "fecha": next((fecha(d[c]) for c in SMS_FEC if c in d and d[c] is not None), None), "fichero": os.path.basename(f)}) wb.close() return lineas, vistas_2019, cabeceras # --- CARM ----------------------------------------------------------------------------------------------------------------- def carm_pagos(exps, filas_2022): pagos, vistas = defaultdict(list), {} for f in sorted(glob.glob(f"{H}/murcia/raw/contratos_menores_carm/CONTRA_ContratosMenores_20*.csv")): anio = re.search(r"(20\d\d)", os.path.basename(f))[1] with open(f, encoding="utf-8-sig", newline="") as fh: rd = csv.DictReader(fh) tiene_exp = "CODEXPEDIENTE" in (rd.fieldnames or []) idx = -1 for d in rd: if not any((v or "").strip() for v in d.values() if isinstance(v, str)): continue idx += 1 if (anio, idx) in filas_2022: vistas[(anio, idx)] = {"tiene_expediente": tiene_exp} e = texto(d.get("CODEXPEDIENTE")) if e in exps: imp = num(d.get("IMPORTECONTABPAGO") or d.get("VALORCONTABPAGO")) pagos[e].append({"nif": nif_clave(d.get("ADJUDICATARIOCODIGO") or d.get("ADJUDICATARIO_CIF")), "importe": imp, "fecha": fecha(d.get("FECHACONTABPAGO"), mdy=True), "fichero": anio}) return pagos, vistas def contrato(lineas, com, P, d1): ks = {x["nif"] for x in lineas} imps = [x["importe"] for x in lineas if x["importe"] is not None] fechas = sorted(x["fecha"] for x in lineas if x["fecha"]) suma = round(sum(imps), 2) if imps else None out = {"n": len(lineas), "suma": suma, "k": next(iter(ks)) if len(ks) == 1 else sorted(str(k) for k in ks), "fecha": fechas[0] if fechas else None, "d1": bool(d1), "d1_ids": d1[:3]} if len(ks) != 1 or None in ks or not imps or suma is None or suma <= 0: out["clase"] = "sin contrato" elif d1: out["clase"] = "ya contado" else: cands = d2_candidatas(P, com, out["k"], suma, int(fechas[0][:4]) if fechas else None) out["d2_candidatas"] = cands[:3] out["clase"] = "contrato" if not cands else "contrato o D2 (ver uno a uno)" return out # --- Palma ---------------------------------------------------------------------------------------------------------------- P_IMP = {"import", "importe"} P_EMP = {"empresaadjudicataria", "nombreter."} P_FEC = {"data", "fecha"} P_OBJ = {"objectecontracte", "textolibre"} P_CIF = {"cifempresaadjudicataria"} RX_ACTO = re.compile(r"^(ampliacio|complement|increment|augment|reajust|modificacio)") def trimestre(nombre): m = re.search(r"(?