"""Piezas comunes del piloto A (sin red, sin dependencias): lectura de importes en formato español, familias de reglas v3 (copiadas de sql/04b_reglas_v2.py y sql/04c_reglas_v3.py, sin cambios de lógica), control con el CODICE por lote y utilidades de citas. Control con el CODICE = §2.3 de prereg/PREREG_SCREENS.md (sellado 09:42), aplicado igual que lo escribe: * casa(v, ref): |v / (ref × factor) − 1| ≤ 0,5 %, factor ∈ {1; 1,21; 1,10; 1,04; 1,07; 1,03} (solo en ese sentido); * n: n_importes_válidos + n_sin_importe == num_ofertas (exacto); * minmax: si el CODICE trae mínimo y máximo: casa(mín extraído, mín) y casa(máx extraído, máx); * adj: si hay adjudicataria identificada e imp_adj_eur: casa(importe de la adjudicataria, imp_adj_eur). «Conciliado» = ninguna comprobación disponible falla (es lo que en screens_ref.py deja motivo_sensibilidad vacío). Para las REGLAS v3 (que no saben estados ni adjudicataria), `control_reglas`: nº de importes distintos == num_ofertas Y (minmax y/o «algún importe casa con algún adjudicado del lote») disponible y cumplido; sin min/máx ni adjudicado NO pasa (en la muestra el recuento solo dejó pasar un acta con importes erróneos: A22). """ import re import unicodedata FACTORES = (1.0, 1.21, 1.10, 1.04, 1.07, 1.03) # = RATIOS_IVA del pre-registro TOL_REL = 0.005 ESTADOS_VALIDOS = {'admitida', 'anormal', 'corregida'} ESTADOS_SIN_IMPORTE = {'excluida_sin_importe', 'no_abierta', 'retirada'} # --- de 04b_reglas_v2.py (sin cambios) --- IMP = r'(\d{1,3}(?:\.\d{3})+(?:,\d{1,2})?|\d{4,7},\d{2}|\d{1,3},\d{2})' SOC = re.compile(r'\b(S\.?\s?L\.?\s?U?\.?|S\.?\s?A\.?\s?U?\.?|SLU|SAU|SL|SA|UTE|S\.?\s?COOP|SLL|S\.?L\.?L\.?)\b|NIF|CIF|C\.I\.F|' r'\b[A-HJ-NP-SUVW]-?\d{2}\.?\d{3}\.?\d{3}-?[0-9A-J]?\b|\b\d{2}\.?\d{3}\.?\d{3}-?[A-Z]\b', re.I) def num(s): """Importe escrito → float (2 decimales) o None. Español: punto de miles y coma decimal («12.345,67»); también «12345,67», «72541.98» (punto decimal con 1-2 cifras), «12,345.67» (inglés), «12 345,67» y «1.234» (miles).""" if s is None: return None s = str(s).strip().replace(' ', ' ').replace('€', '').replace('EUR', '').strip() s = re.sub(r'(?<=\d)[  ](?=\d{3}\b)', '', s) s = s.rstrip('.').strip() if not re.fullmatch(r'-?[\d.,]+', s or 'x'): return None if ',' in s and '.' in s: if s.rfind(',') > s.rfind('.'): s = s.replace('.', '').replace(',', '.') else: s = s.replace(',', '') elif ',' in s: if s.count(',') > 1: s = s.replace(',', '') else: s = s.replace(',', '.') elif '.' in s: if re.fullmatch(r'-?\d{1,3}(?:\.\d{3})+', s): s = s.replace('.', '') elif re.fullmatch(r'-?\d+\.\d{1,2}', s): pass elif s.count('.') > 1: return None try: return round(float(s), 2) except ValueError: return None def familias(txt): """Familias de reglas v3 (04c_reglas_v3.py): R1 formato PLACSP, R2 «Oferta económica:», R34 filas de tabla.""" L = [re.sub(r'\s+', ' ', l).strip() for l in txt.splitlines()] t = re.sub(r'\s+', ' ', txt) f = {'R1': [], 'R2': [], 'R34': []} for m in re.finditer(r'(?:NIF|CIF): ?(\S+) (.{3,90}?):? ?- ?Precio Valor introducido por el licita ?d ?or: ?([\d.,]+)', t): f['R1'].append((m.group(2), num(m.group(3)), m.group(0))) for i, l in enumerate(L): m = re.search(r'(?:Oferta econ[oó]mica|Total oferta|Importe ofertado|Precio ofertado)[^0-9]{0,30}?' + IMP, l, re.I) if m: nombre = next((L[j] for j in range(i - 1, max(i - 4, -1), -1) if L[j] and SOC.search(L[j])), '') f['R2'].append((nombre, num(m.group(1)), l)) for i, l in enumerate(L): if not SOC.search(l): continue m = re.search(r'(?:^|\s)' + IMP + r'\s*(?:€|euros|EUR)?(?:\s|$)', l) p = re.search(r'(\d{1,2}(?:,\d{1,2})?)\s?%', l) if m and num(m.group(1)) and num(m.group(1)) >= 1000: f['R34'].append((l[:m.start()], num(m.group(1)), l)); continue if p: f['R34'].append((l[:p.start()], num(p.group(1)), l)); continue for j in (i + 1, i + 2): if j < len(L): m2 = re.match(IMP + r'\s*(?:€|euros)?', L[j]) if m2 and num(m2.group(1)) and num(m2.group(1)) >= 1000: f['R34'].append((l, num(m2.group(1)), l + ' ' + L[j])); break return f def casa(v, ref): """Igual que el pre-registro §2.3: ¿v = ref × factor (±0,5 %)? Devuelve el factor o None.""" if v is None or ref is None or ref <= 0: return None for f in FACTORES: if abs(v / (ref * f) - 1) <= TOL_REL: return f return None def control_codice(ofertas, lote): """ofertas: lista de dicts {importe (float|None), unidad, estado, adjudicataria (bool|None)} de UN lote. lote: dict del CODICE (num_ofertas, oferta_min_eur, oferta_max_eur, imp_adj_eur o listas imp_adj_*). Devuelve {'n','minmax','adj'} (True/False/None = no disponible), 'conciliado', n_validos, n_sin_importe.""" validas, sin_imp, adj_imp = [], 0, None for o in ofertas: e = o.get('estado') if e in ESTADOS_SIN_IMPORTE: sin_imp += 1 elif e in ESTADOS_VALIDOS and o.get('importe') is not None and o.get('unidad') in ('sin_iva', 'con_iva', 'pct_baja'): v = o['importe'] if o.get('unidad') == 'pct_baja': pbl = lote.get('imp_lic_eur') v = pbl * (1 - v / 100.0) if pbl else None if v is not None and v > 0: validas.append(v) if o.get('adjudicataria'): adj_imp = v nof = lote.get('num_ofertas') r = {'n_validos': len(validas), 'n_sin_importe': sin_imp, 'num_ofertas': nof} r['n'] = None if nof is None else (len(validas) + sin_imp == nof) mn, mx = lote.get('oferta_min_eur'), lote.get('oferta_max_eur') r['minmax'] = (casa(min(validas), mn) is not None and casa(max(validas), mx) is not None) \ if (validas and mn is not None and mx is not None and mn > 0) else None adj = lote.get('imp_adj_eur_unico') r['adj'] = (casa(adj_imp, adj) is not None) if (adj_imp is not None and adj is not None) else None r['conciliado'] = bool(validas) and all(r[k] is not False for k in ('n', 'minmax', 'adj')) and r['n'] is not None return r def control_reglas(importes, lote): """Control de las reglas v3 (sin estados): nº de importes distintos == num_ofertas y (minmax y/o adjudicado).""" imps = sorted(set(round(x, 2) for x in importes if x is not None and x > 0)) nof = lote.get('num_ofertas') r = {'n_importes': len(imps), 'num_ofertas': nof, 'n': (nof is not None and len(imps) == nof)} mn, mx = lote.get('oferta_min_eur'), lote.get('oferta_max_eur') r['minmax'] = (casa(imps[0], mn) is not None and casa(imps[-1], mx) is not None) \ if (imps and mn is not None and mx is not None and mn > 0) else None adjs = [x for k in ('imp_adj_sin_iva', 'imp_adj_con_iva', 'imp_adj_eur') for x in (lote.get(k) or []) if x] r['adj'] = any(casa(i, a) is not None for i in imps for a in adjs) if (imps and adjs) else None disp = [r[k] for k in ('minmax', 'adj') if r[k] is not None] r['pasa'] = bool(r['n'] and disp and all(disp)) return r def norm_espacios(s): return re.sub(r'\s+', ' ', unicodedata.normalize('NFC', s or '')).strip() def lista_float(v): """'[1.0, 2.5]' (DuckDB → TSV) o lista → lista de floats.""" if v is None: return [] if isinstance(v, (list, tuple)): return [float(x) for x in v if x is not None] v = str(v).strip() if not v or v in ('[]', 'NULL'): return [] return [float(x) for x in re.findall(r'-?\d+(?:\.\d+)?(?:[eE][-+]?\d+)?', v)] def leer_codice(ruta): import csv lotes = {} for r in csv.DictReader(open(ruta, encoding='utf-8'), delimiter='\t'): d = {'lote_id': r['lote_id'] or '', 'licitacion_id': r['licitacion_id']} d['num_ofertas'] = int(r['num_ofertas']) if r['num_ofertas'] not in ('', None) else None for k in ('oferta_min_eur', 'oferta_max_eur', 'imp_lic_eur'): d[k] = float(r[k]) if r.get(k) not in ('', None) else None for k in ('imp_adj_sin_iva', 'imp_adj_con_iva', 'imp_adj_eur'): d[k] = lista_float(r.get(k)) d['lote'] = d['lote_id'].split('|')[-1] if '|' in d['lote_id'] else '' u = sorted(set(d['imp_adj_eur'])) d['imp_adj_eur_unico'] = u[0] if len(u) == 1 else None # varios adjudicatarios (acuerdo marco): sin dato lotes.setdefault(r['licitacion_id'], []).append(d) return lotes