"""DOUE-PLAZO · cotejo contra el original. Uso: 30_cotejo.py DESDE HASTA. Toma, de los casos tarde con sara=TRUE de priv/medida_DESDE_HASTA.parquet, los 30 primeros
en orden md5(id + '|doue-plazo-8nov') y los compara con:
- el ATOM de la PLACSP en los ZIP (/h/nacional/zips/licitaciones, TODAS las versiones guardadas de la entrada): la fecha de envío al DOUE del anuncio de
formalización (DOC_FORM, medio DOUE; SendDate) y la de formalización (Contract/IssueDate); ninguna versión debe traer un envío anterior ≤ tope.
- el aviso de TED (ted_es_can por NIF+expediente; XML eForms local si existe): fecha de envío (BT-05) a ±1 día y, si la trae, fecha de conclusión igual.
Copia las versiones ATOM y el XML de TED a priv/ (700) para el paquete del lector. Sin red."""
import sys, json, re, os, time, glob, gzip, hashlib, zipfile, collections
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; SET preserve_insertion_order=false")
r = c.execute(f"SELECT id, expediente, nif_organo, anio, ff::VARCHAR, form_env::VARCHAR, tope::VARCHAR, d FROM read_parquet('/o/priv/medida_{D}_{Hh}.parquet') WHERE sara AND tarde").fetchall()
orden = sorted(r, key=lambda x: hashlib.md5((x[0] + '|doue-plazo-8nov').encode()).hexdigest())[:30]
M = [dict(id=x[0], expediente=x[1], nif=x[2], anio=x[3], ff=x[4], env=x[5], tope=x[6], d=x[7], clave='/'.join(x[0].split('/')[-2:])) for x in orden]
ids = [x['id'] for x in M]
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(?))", [ids]).fetchall()
por_zip = 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_zip[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_zip.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, f'{os.path.basename(zp)}:{n}'))
del data
print('zip', os.path.basename(zp), 'con versiones', sum(1 for k in ver), 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 todos(e, n): return [x.text.strip() for x in e.iter() if ln(x) == n and x.text]
# TED
c.execute("CREATE TEMP TABLE par (nif VARCHAR, ex VARCHAR)"); c.executemany("INSERT INTO par VALUES (?,?)", [(x['nif'], (x['expediente'] or '').strip().upper()) for x in M])
t = c.execute(f"""SELECT t.cae_nif_clean nif, upper(trim(t.expediente_sin_lote)) ex, t.ted_notice_id, t.dt_dispatch::DATE::VARCHAR, TRY_CAST(substr(t.contract_conclusion_date,1,10) AS DATE)::VARCHAR, t.year
FROM read_parquet('/h/ted/ted_es_can.parquet') t JOIN par p ON p.nif = t.cae_nif_clean AND p.ex = upper(trim(t.expediente_sin_lote)) WHERE t.year BETWEEN {D} AND {Hh + 1} AND coalesce(t.notice_type,'') NOT IN ('can-modif')""").fetchall()
tp = collections.defaultdict(list)
for nif, ex, nid, dp, cc, y in t: tp[(nif, ex)].append(dict(nid=nid, dispatch=dp, concl=cc, year=y))
def xml_ted(nid, year):
for y in (year, year + 1, 2024, 2025, 2026):
f = f'/h/ted/xml/{y}/{nid}.xml.gz'
if os.path.exists(f):
s = gzip.open(f).read(); root = ET.fromstring(s)
disp = next((ch.text.strip()[:10] for ch in root if ln(ch) == 'IssueDate' and ch.text), None)
concl = [x.text.strip()[:10] for sc in root.iter() if ln(sc) == 'SettledContract' for x in sc if ln(x) == 'IssueDate' and x.text]
return dict(fichero=f, dispatch_xml=disp, concl_xml=concl), s
return None, None
os.makedirs('/o/priv/orig', exist_ok=True); os.chmod('/o/priv/orig', 0o700)
R = []
for x in M:
a = dict(id=x['id'], clave=x['clave'], d=x['d'], ff=x['ff'], env=x['env'], tope=x['tope'])
h = hashlib.md5(x['clave'].encode()).hexdigest(); carpeta = f'/o/priv/orig/{h}'; os.makedirs(carpeta, exist_ok=True)
envs_doc = []; ffs = set(); envio_todas = []
vs = sorted(ver.get(x['clave'], {}).items())
for upd, (ent, origen) in vs:
nom = re.sub(r'[^0-9A-Za-z]', '', upd)[:20] or 'sin_fecha'
open(f'{carpeta}/{nom}.xml', 'wb').write(f'\n'.encode() + ent)
root = parse(ent)
ev = []
for v in root.iter():
if ln(v) != 'ValidNoticeInfo': continue
tipo = (todos(v, 'NoticeTypeCode') or [''])[0]
if tipo != 'DOC_FORM': continue
for st in v.iter():
if ln(st) != 'AdditionalPublicationStatus': continue
if (todos(st, 'PublicationMediaName') or [''])[0] != 'DOUE': continue
for e in todos(st, 'SendDate'): ev.append(e[:10])
fi = []
for tr in root.iter():
if ln(tr) != 'TenderResult': continue
ctr = [y for y in tr.iter() if ln(y) == 'Contract']
if ctr: fi += [d_[:10] for d_ in todos(ctr[0], 'IssueDate')]
envs_doc.append(dict(updated=upd, fichero=f'{nom}.xml', origen=origen, envios=sorted(set(ev)), formalizaciones=sorted(set(fi))))
a['n_versiones'] = len(envs_doc); a['versiones'] = envs_doc
ult = envs_doc[-1] if envs_doc else None
a['ok_atom_envio'] = bool(ult) and x['env'] in ult['envios']
a['ok_atom_ff'] = bool(ult) and x['ff'] in ult['formalizaciones']
a['envio_anterior_en_plazo'] = sorted({e for v in envs_doc for e in v['envios'] if e < x['env'] and e <= x['tope']})
a['ok_sin_envio_anterior'] = not a['envio_anterior_en_plazo']
# TED
cand = tp.get((x['nif'], (x['expediente'] or '').strip().upper()), [])
a['ted_candidatos'] = cand
ok_d = False; ted_ff = None; xml_info = None
for z_ in cand:
info, s = xml_ted(z_['nid'], z_['year'])
disp = (info or {}).get('dispatch_xml') or z_['dispatch']
import datetime as dt
if disp and abs((dt.date.fromisoformat(disp) - dt.date.fromisoformat(x['env'])).days) <= 1:
ok_d = True
concl = ((info or {}).get('concl_xml') or []) + ([z_['concl']] if z_['concl'] else [])
ted_ff = bool(concl) and x['ff'] in concl if concl else None
xml_info = info; xml_nid = z_['nid']
if s:
open(f'{carpeta}/ted_{xml_nid}.xml', 'wb').write(s)
break
a['ted_encontrado'] = bool(cand); a['ok_ted_envio'] = ok_d; a['ted_ff_coincide'] = ted_ff; a['xml_info'] = xml_info
a['ok_caso'] = a['ok_atom_envio'] and a['ok_atom_ff'] and a['ok_sin_envio_anterior'] and a['ok_ted_envio'] and (a['ted_ff_coincide'] is not False)
R.append(a)
res = dict(desde=D, hasta=Hh, n=len(R), ok_casos=sum(a['ok_caso'] for a in R), atom_envio=sum(a['ok_atom_envio'] for a in R), atom_ff=sum(a['ok_atom_ff'] for a in R),
sin_envio_anterior_en_plazo=sum(a['ok_sin_envio_anterior'] for a in R), ted_encontrado=sum(a['ted_encontrado'] for a in R), ted_envio=sum(a['ok_ted_envio'] for a in R),
ted_ff_coincide=sum(1 for a in R if a['ted_ff_coincide'] is True), ted_ff_sin_dato=sum(1 for a in R if a['ted_ff_coincide'] is None), ted_ff_distinta=sum(1 for a in R if a['ted_ff_coincide'] is False),
segundos=round(time.time() - T0))
json.dump(dict(resumen=res, muestra=M, casos=R), open(f'/o/priv/cotejo_{D}_{Hh}.json', 'w'), ensure_ascii=False, indent=1, default=str)
json.dump(res, open(f'/o/salidas/30_cotejo_{D}_{Hh}.json', 'w'), indent=1)
print(json.dumps(res, indent=1, ensure_ascii=False))
for a in R:
if not a['ok_caso']:
print('FALLA', a['clave'], 'env', a['env'], 'ff', a['ff'], 'tope', a['tope'], 'atom_env', a['ok_atom_envio'], 'atom_ff', a['ok_atom_ff'], 'prev', a['envio_anterior_en_plazo'], 'ted', a['ted_encontrado'], a['ok_ted_envio'], a['ted_ff_coincide'])