"""TL-T1-151-E1 · cotejo de V1 (ENM1) contra el ATOM original (ZIP en disco, todas las versiones; sin red). Uso: 30_cotejo.py DESDE HASTA. Muestra: 30 primeros tarde en orden md5(id + '|tl-t1-151-10nov') y 10 de control (en plazo) en orden md5(id + '|tl-t1-151-10nov-control'). Pasa si: (a) en la última versión los resultados adjudicados (ResultCode 1/2/8/9) tienen una sola AwardDate, igual a fa; (b) la primera IssueDate del DOC_CAN_ADJ en un AdditionalPublicationStatus «Perfil…», de cualquier versión, igual o posterior a fa, es p; (c) tarde: p > tope; control: p <= tope; (d) TypeCode 1/2/3, ProcedureCode incluido, UrgencyCode distinto de 3, ContractingPartyTypeCode 1/2/3, ContractingSystemCode distinto de 2/3/4 y NIF del órgano igual; (e) la primera versión con esa fecha tiene updated >= p - 1 día. (f) AwardDate distinta entre versiones: se dice, no falla. Copia las versiones a /o/priv/orig/ (700) para el paquete.""" import sys, json, re, os, time, hashlib, zipfile, collections, datetime as dt import xml.etree.ElementTree as ET import duckdb sys.path.insert(0, '/o/py') import patrones151 as PT D, Hh = int(sys.argv[1]), int(sys.argv[2]); T0 = time.time() c = duckdb.connect(); c.execute("SET memory_limit='1500MB'; SET threads=2; SET enable_progress_bar=false") r = c.execute(f"SELECT id, nif, anio, fa::VARCHAR, p4p::VARCHAR, tope::VARCHAR, tarde, d, n_fa_todas, ca, ca_fuente, p4::VARCHAR, tope_loc::VARCHAR FROM read_parquet('/o/priv/medida_e1_{D}_{Hh}.parquet') WHERE base_v1").fetchall() o1 = sorted([x for x in r if x[6]], key=lambda x: hashlib.md5((x[0] + '|tl-t1-151-e1-10nov').encode()).hexdigest())[:30] o2 = sorted([x for x in r if not x[6]], key=lambda x: hashlib.md5((x[0] + '|tl-t1-151-e1-10nov-control').encode()).hexdigest())[:10] M = [dict(id=x[0], nif=x[1], anio=x[2], fa=x[3], p=x[4], tope=x[5], tarde=x[6], d=x[7], n_fa_todas=x[8], ca=x[9], ca_fuente=x[10], p4=x[11], tope_loc=x[12], grupo='tarde' if x[6] else 'control', clave='/'.join(x[0].split('/')[-2:])) for x in o1 + o2] PA = '/h/nacional/salida/licitaciones_completo_2012_2026' por = collections.defaultdict(set) for i, z, con in c.execute(f"SELECT DISTINCT id, archivo_origen, conjunto FROM read_parquet('{PA}.parquet') WHERE id IN (SELECT unnest(?))", [[m['id'] for m in M]]).fetchall(): p = f'/h/nacional/zips/{con}/{z}' if not os.path.exists(p): p = f'/h/nacional/zips/{con}/_historico/{z}' if os.path.exists(p): por[p].add('/'.join(i.split('/')[-2:])) else: print('falta zip', z, flush=True) RE_ID = re.compile(rb'https?://contratacion(?:delestado\.es|delsectorpublico\.gob\.es)/sindicacion/([^<]+)') RE_UPD = re.compile(rb'([^<]+)') ver = collections.defaultdict(dict) for zp, cl in por.items(): with zipfile.ZipFile(zp) as z: for nm in z.namelist(): if not nm.endswith('.atom'): continue data = z.read(nm) for mm in RE_ID.finditer(data): k = '/'.join(mm.group(1).decode().split('/')[-2:]) if k not in cl: continue i0 = data.rfind(b'', mm.end()) if i0 < 0 or i1 < 0: continue ent = data[i0:i1 + 8]; u = RE_UPD.search(ent) ver[k].setdefault(u.group(1).decode() if u else '', ent) del data print('zip', os.path.basename(zp), round(time.time() - T0), flush=True) def ln(e): return e.tag.split('}')[-1] def parse(ent): e2 = re.sub(r'\sxmlns(:[\w\-]+)?="[^"]*"', '', ent.decode('utf-8', 'replace')); e2 = re.sub(r'\s[\w\-]+:[\w\-]+="[^"]*"', '', e2); e2 = re.sub(r'<(/?)[A-Za-z\-]+:', r'<\1', e2) return ET.fromstring(e2) def fechas_adj(root): out = [] for v in root.iter(): if ln(v) != 'ValidNoticeInfo' or next((x.text for x in v if ln(x) == 'NoticeTypeCode'), None) != 'DOC_CAN_ADJ': continue for s in v: if ln(s) == 'AdditionalPublicationStatus' and (next((t.text for t in s if ln(t) == 'PublicationMediaName'), '') or '').lower().startswith('perfil'): out += [t.text.strip()[:10] for t2 in s for t in t2.iter() if ln(t) == 'IssueDate' and t.text] return out def award(root): return {next((x.text.strip()[:10] for x in tr if ln(x) == 'AwardDate' and x.text), None) for tr in root.iter() if ln(tr) == 'TenderResult' and next((x.text.strip() for x in tr if ln(x) == 'ResultCode' and x.text), '') in ('1', '2', '8', '9')} - {None} def uno(root, nombre): return next((x.text.strip() for x in root.iter() if ln(x) == nombre and x.text), None) res = [] for m in M: vs = sorted(ver.get(m['clave'], {}).items()) ori = f"/o/priv/orig/{hashlib.md5(m['clave'].encode()).hexdigest()}"; os.makedirs(ori, exist_ok=True) for u, ent in vs: open(f"{ori}/v_{re.sub(r'[^0-9T]', '', u)[:20]}.xml", 'wb').write(ent) fallos, notas = [], [] if not vs: fallos.append('sin versiones en los ZIP') else: R = [(u, parse(e)) for u, e in vs]; ult = R[-1][1] aw = award(ult) if aw != {m['fa']}: fallos.append(f"a: AwardDate {sorted(aw)} != {m['fa']}") todas = {u: fechas_adj(x) for u, x in R} ps = sorted({f for fs in todas.values() for f in fs if f >= m['fa']}) if not ps or ps[0] != m['p']: fallos.append(f"b: perfil {ps[:1]} != {m['p']}") if ps: if m['tarde'] and not ps[0] > m['tope']: fallos.append('c: dentro de plazo en el ATOM') if not m['tarde'] and not ps[0] <= m['tope']: fallos.append('c: control fuera de plazo') pri = next((u for u in sorted(todas) if ps[0] in todas[u]), None) if pri and pri[:10] < (dt.date.fromisoformat(ps[0]) - dt.timedelta(days=1)).isoformat(): fallos.append(f'e: aparece antes de la fecha: {pri[:10]}') tc, pcod, urg, toc, sis = (uno(ult, k) for k in ('TypeCode', 'ProcedureCode', 'UrgencyCode', 'ContractingPartyTypeCode', 'ContractingSystemCode')) if tc not in ('1', '2', '3'): fallos.append(f'd: tipo {tc}') if pcod not in ('1', '2', '3', '4', '5', '9', '10', '13'): fallos.append(f'd: proc {pcod}') if urg == '3': fallos.append('d: emergencia') if toc not in ('1', '2', '3'): fallos.append(f'd: tipo organo {toc}') if sis in ('2', '3', '4'): fallos.append(f'd: sistema {sis}') pp = next((x for x in ult.iter() if ln(x) == 'ProcurementProject'), None) nom = ((next((y.text for y in pp if ln(y) == 'Name' and y.text), '') if pp is not None else '') or '').upper()[:600] if (re.search(PT.PR_SI, nom, re.A) and not re.search(PT.PR_NO, nom, re.A)) or (re.search(PT.EM_SI, nom, re.A) and not re.search(PT.EM_NO, nom, re.A)): fallos.append('d: prorroga o emergencia en el objeto') lcp = next((x for x in ult.iter() if ln(x) == 'LocatedContractingParty'), None) if (m['nif'] or '') not in {x.text.strip() for x in (lcp.iter() if lcp is not None else []) if ln(x) == 'ID' and x.text}: fallos.append('d: NIF del organo no coincide') awv = set().union(*(award(x) for u, x in R)) if len(awv) > 1: notas.append(f'f: AwardDate entre versiones {sorted(awv)}') res.append(dict(grupo=m['grupo'], pasa=not fallos, fallos=fallos, notas=notas, n_versiones=len(vs), ref=hashlib.md5(m['clave'].encode()).hexdigest()[:8], **{k: m[k] for k in ('fa', 'p', 'tope', 'd', 'clave', 'id', 'n_fa_todas', 'ca', 'ca_fuente', 'p4', 'tope_loc')})) tarde = [x for x in res if x['grupo'] == 'tarde']; ctrl = [x for x in res if x['grupo'] == 'control'] sal = dict(desde=D, hasta=Hh, tarde_pasan=sum(x['pasa'] for x in tarde), tarde_n=len(tarde), control_pasan=sum(x['pasa'] for x in ctrl), control_n=len(ctrl), fallos=collections.Counter(f.split(':')[0] for x in res for f in x['fallos']), notas_f=sum(1 for x in res if x['notas']), segundos=round(time.time() - T0)) sal['pasa'] = sal['tarde_pasan'] >= 27 and sal['control_pasan'] >= 8 json.dump(res, open(f'/o/priv/cotejo_e1_{D}_{Hh}.json', 'w'), ensure_ascii=False, indent=0) json.dump(sal, open(f"/o/salidas/{'ensayo/' if Hh < 2024 else ''}32_cotejo_e1_{D}_{Hh}.json", 'w'), ensure_ascii=False, indent=1) print(json.dumps(sal, ensure_ascii=False)); print(json.dumps([dict(ref=x['ref'], f=x['fallos'], n=x['notas']) for x in res if not x['pasa'] or x['notas']], ensure_ascii=False)[:2000])