"""TL-T1-154-E2 · ENM2 · cotejo (población E2) contra el ATOM original (ZIP en disco, todas las versiones). Uso: 30_cotejo.py DESDE HASTA.
Muestra: los 30 primeros tarde (V1) en orden md5(id + '|tl-t1-154-e2-9nov') y los 10 primeros de control (V1, en plazo) en orden md5(id + '|tl-t1-154-e2-9nov-control').
Un caso pasa si: (a) en la última versión la fecha de formalización (Contract/IssueDate) es una sola e igual a ff; (b) la fecha de publicación del DOC_FORM en el perfil más antigua entre todas las versiones es p_min;
(c) tarde: p_min > tope; control: p_min <= tope; (d) tipo 1/2/3, procedimiento incluido, no emergencia, tipo de órgano 1/2/3 y NIF del órgano igual al de la medida (última versión);
(e) la primera versión guardada con ese DOC_FORM tiene updated >= p_min - 1 día (la fecha no es anterior a la aparición del anuncio en el fichero).
Copia las versiones a priv/orig/ (700) para el paquete de lectura. Sin red."""
import sys, json, re, os, time, hashlib, zipfile, collections, datetime as dt
import xml.etree.ElementTree as ET
import duckdb
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, expediente, nif, anio, ff::VARCHAR, p_min::VARCHAR, tope::VARCHAR, tarde, d FROM read_parquet('/o/priv/medida_e2_{D}_{Hh}.parquet') WHERE base_v1").fetchall()
o1 = sorted([x for x in r if x[7]], key=lambda x: hashlib.md5((x[0] + '|tl-t1-154-e2-9nov').encode()).hexdigest())[:30]
o2 = sorted([x for x in r if not x[7]], key=lambda x: hashlib.md5((x[0] + '|tl-t1-154-e2-9nov-control').encode()).hexdigest())[:10]
M = [dict(id=x[0], expediente=x[1], nif=x[2], anio=x[3], ff=x[4], p=x[5], tope=x[6], tarde=x[7], d=x[8], grupo='tarde' if x[7] else 'control', clave='/'.join(x[0].split('/')[-2:])) for x in o1 + o2]
PA = '/h/nacional/salida/licitaciones_completo_2012_2026'
arch = 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()
por = collections.defaultdict(set)
for i, z, con in arch:
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 n in z.namelist():
if not n.endswith('.atom'): continue
data = z.read(n)
for m in RE_ID.finditer(data):
k = '/'.join(m.group(1).decode().split('/')[-2:])
if k not in cl: continue
i0 = data.rfind(b'', m.end())
if i0 < 0 or i1 < 0: continue
ent = data[i0:i1 + 8]; u = RE_UPD.search(ent); upd = u.group(1).decode() if u else ''
ver[k].setdefault(upd, 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_form(root):
out = []
for v in root.iter():
if ln(v) != 'ValidNoticeInfo' or next((c_.text for c_ in v if ln(c_) == 'NoticeTypeCode'), None) != 'DOC_FORM': continue
for s in v:
if ln(s) != 'AdditionalPublicationStatus': continue
medio = next((t.text for t in s if ln(t) == 'PublicationMediaName'), '') or ''
if medio.lower().startswith('perfil'):
out += [t.text[:10] for t2 in s for t in t2.iter() if ln(t) == 'IssueDate' and t.text]
return out
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 = []
if not vs: fallos.append('sin versiones en los ZIP')
else:
ult = parse(vs[-1][1])
cts = {x.text.strip()[:10] for ct in ult.iter() if ln(ct) == 'Contract' for x in ct if ln(x) == 'IssueDate' and x.text}
if cts != {m['ff']}: fallos.append(f"a: formalizacion {sorted(cts)} != {m['ff']}")
todas = {u: fechas_form(parse(e)) for u, e in vs}
ps = sorted({f for fs in todas.values() for f in fs})
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 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 = uno(ult, 'TypeCode'); pcod = uno(ult, 'ProcedureCode'); urg = uno(ult, 'UrgencyCode'); toc = uno(ult, 'ContractingPartyTypeCode')
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}')
sis = uno(ult, 'ContractingSystemCode')
if sis in ('1', '3', '4'): fallos.append(f'd: sistema {sis}')
lcp = next((x for x in ult.iter() if ln(x) == 'LocatedContractingParty'), None)
nifs = {x.text.strip() for x in (lcp.iter() if lcp is not None else []) if ln(x) == 'ID' and x.text}
if (m['nif'] or '') not in nifs: fallos.append('d: NIF del organo no coincide')
res.append(dict(grupo=m['grupo'], pasa=not fallos, fallos=fallos, n_versiones=len(vs), ref=hashlib.md5(m['clave'].encode()).hexdigest()[:8], **{k: m[k] for k in ('ff', 'p', 'tope', 'd', 'clave', 'id')}))
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']), segundos=round(time.time() - T0))
json.dump(res, open(f'/o/priv/cotejo_e2_{D}_{Hh}.json', 'w'), ensure_ascii=False, indent=0)
json.dump(sal, open(f'/o/salidas/32_cotejo_e2_{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']) for x in res if not x['pasa']], ensure_ascii=False)[:2500])