"""Cotejo A: clasificación final según el pre-registro §5.2 y aceptación A0-A4, con lo leído por 06_leer_A.py (A_anuncios_lectura.csv, A_parecidas_lectura.csv). Escribe cotejo/A_resultado.csv y salidas/08_cotejo_A.json.""" import csv, datetime as dt, json, collections, os, sys _src = open('/e1b/py/15_leer_A_r2.py').read().split("an = {int(a['anuncio'])")[0] _ns = {}; _argv = sys.argv; sys.argv = [_argv[0], '99']; exec(compile(_src, '06_leer_A', 'exec'), _ns); sys.argv = _argv xml_resultados = _ns['xml_resultados'] C = '/e1b/cotejo2/' an = list(csv.DictReader(open(C + 'A_anuncios_lectura.csv'))) ps = list(csv.DictReader(open(C + 'A_parecidas_lectura.csv'))) org_dir3 = {} try: for r in csv.DictReader(open(C + 'A_organo_dir3.csv')): org_dir3[(r['anuncio'], r['k'])] = r['veredicto'] except FileNotFoundError: pass RES_CONTABLE = ('Adjudicado', 'Formalizado', 'Desierto', 'Licitador mejor valorado') out = [] for p in ps: r = dict(p); err = [] if p.get('estado') != 'leida': r['clase'] = 'NL'; out.append(r); continue # b. órgano org = p.get('organo') if org == 'ERROR': err.append('E-ORG') if org == 'PENDIENTE_DIR3': v = org_dir3.get((p['anuncio'], p['k'])) if v == 'mismo_dir3': r['organo'] = 'mismo_dir3_nombre_distinto' else: # §5.2 b: ni perfil, ni nombre, ni DIR3 en los XML = ERROR DE ÓRGANO. El XML de los documentos del portal no # publica DIR3 (solo ID_PLATAFORMA y NIF): no se puede afirmar «mismo DIR3» con la fuente viva err.append('E-ORG') r['organo'] = 'perfil_y_nombre_distintos_' + ('dir3_distinto' if v == 'distinto' else 'sin_dir3_en_xml') # c. CPV (primer CPV del lote o de la licitación) if p.get('fuente_cpv_nota'): r['clase'] = 'NL'; r['nota_nl'] = 'CPV del lote no legible'; out.append(r); continue cpvs = [c for c in (p.get('fuente_cpvs') or '').split(';') if c] if not cpvs or any(c[:2] != p['nuestro_cpv'] for c in cpvs): err.append('E-CPV') # d. año. Con XML, AwardDate (§5.2 d). Una parecida leída en la ficha puede tener XML de la fase 4 (órgano): se usa fa = dt.date.fromisoformat(p['nuestro_fecha_adj']) if p['nuestro_fecha_adj'] else None lid = p['licitacion_id'].split('/')[-1] if not p.get('fuente_award') and os.path.exists(C + f'html/dir3_{lid}.xml'): x = xml_resultados(C + f'html/dir3_{lid}.xml') aw = [t['award'] for t in x.get('resultados', []) if t['award'] and (t['lote'] == p['lote'] if p['lote'] else True)] if aw: p['fuente_award'] = r['fuente_award'] = min(aw) r['nota_anio'] = 'AwardDate del XML de la fase 4; con solo la ficha: ' + (p.get('primer_doc_resultado') or '') if p.get('fuente_award'): if p['fuente_award'] != p['nuestro_fecha_adj']: err.append('E-AÑO') else: pd = (p.get('primer_doc_resultado') or '')[:10] if not (fa and pd and fa <= dt.date.fromisoformat(pd) <= fa + dt.timedelta(days=365)): err.append('E-AÑO') if not ('2023' <= p['nuestro_anio'] <= '2025'): err.append('E-AÑO') # e. resultado contable if p.get('fuente_res') == 'ficha': if not (p.get('fuente_resultado') or '').startswith(RES_CONTABLE): err.append('E-RES') elif p.get('fuente_resultado') != 'contable': err.append('E-RES') # f. ofertas fo = p.get('fuente_ofertas') fo = int(fo) if fo not in (None, '') and str(fo).isdigit() else None if fo != int(p['nuestro_ofertas']): err.append('E-OF1' if (fo == 1) != (int(p['nuestro_ofertas']) == 1) else 'E-OFN') r['errores'] = ' '.join(sorted(set(err))) r['clase'] = 'verificada' out.append(r) ver = [r for r in out if r['clase'] == 'verificada'] leg_an = [a for a in an if a['legible'] == 'True'] cnt = collections.Counter(e for r in ver for e in r['errores'].split()) an_ok = [a for a in leg_an if a['organo_ok'] == 'True' and a['cpv_ok'] == 'True' and a['fin_ok'] == 'True'] res = {'parecidas': len(out), 'verificadas': len(ver), 'no_legibles': len(out) - len(ver), 'anuncios_legibles': len(leg_an), 'errores': dict(cnt), 'ofertas_iguales': sum(1 for r in ver if 'E-OF' not in r['errores']), 'correctas_todo': sum(1 for r in ver if not r['errores']), 'organo_tipos': dict(collections.Counter(r.get('organo') for r in ver)), 'anuncios_ok': len(an_ok), 'anuncios_detalle': [{k: a.get(k) for k in ('anuncio', 'organo_ok', 'cpv_ok', 'fin_ok', 'fin_fuente', 'fin_nuestro', 'rectificaciones_posteriores')} for a in leg_an if a not in an_ok]} n = max(1, len(ver)) res['A0_legibilidad'] = len(ver) >= 54 and len(leg_an) >= 28 res['A1_ofertas'] = res['ofertas_iguales'] / n >= 0.95 res['A2_organo'] = cnt.get('E-ORG', 0) == 0 and all(a['organo_ok'] == 'True' for a in leg_an) res['A3_todo'] = res['correctas_todo'] / n >= 0.95 res['A4_anuncios'] = len(an_ok) / max(1, len(leg_an)) >= 0.95 res['PASA_A'] = all(res[k] for k in ('A0_legibilidad', 'A1_ofertas', 'A2_organo', 'A3_todo', 'A4_anuncios')) campos = [] for f in out: for c in f: if c not in campos: campos.append(c) with open(C + 'A_resultado.csv', 'w', newline='') as fh: w = csv.DictWriter(fh, fieldnames=campos); w.writeheader(); w.writerows(out) json.dump(res, open('/e1b/salidas/16_cotejo_A_r2.json', 'w'), indent=1, ensure_ascii=False) print(json.dumps(res, indent=1, ensure_ascii=False))