feat: sociedades page with CNPJs and CPFs cited in the case files, crossed with the Receita registry

This commit is contained in:
2026-11-08 21:16:34 +01:00
parent 9508a3ae34
commit f074568cf2
5 changed files with 955 additions and 1 deletions
+1
View File
@@ -1 +1,2 @@
.DS_Store
pipeline/_cache/
+292
View File
@@ -0,0 +1,292 @@
#!/usr/bin/env python3
"""CNPJs e CPFs citados nos autos -> web/sociedades.json (página Sociedades).
python3 pipeline/sociedades.py # extrai, consulta o beelink, monta o JSON
python3 pipeline/sociedades.py --cache # reaproveita as consultas salvas em pipeline/_cache/
1. Varre originals/**.md atrás de CNPJ (com barra) e CPF (com pontos e hífen) e descarta o que
não passa no dígito verificador — o OCR troca dígitos, e um número inválido não é de ninguém.
2. Cruza com o cadastro de CNPJ da Receita no espelho rodado (br_me_cnpj, no beelink, -readonly):
estabelecimento citado, razão social, situação, CNAE, município, e o quadro de sócios
(socios_historico: inclui quem já saiu).
3. Monta um grafo: empresa citada — sócio; pessoa citada (CPF que é sócio de alguma empresa) —
empresa. Sócio não citado e empresa não citada só viram nó quando ligam dois nós citados;
os demais aparecem só na lista do painel.
Privacidade: CPF nunca sai inteiro — só no formato mascarado que a própria Receita publica
(***.456.789-**). CPF citado que não é sócio de empresa nenhuma não tem nome em fonte pública:
entra só na contagem.
"""
import json, re, subprocess, sys
from collections import Counter, defaultdict
from pathlib import Path
RAIZ = Path(__file__).resolve().parent.parent
ORIG = RAIZ / "originals"
CACHE = RAIZ / "pipeline" / "_cache"
SAIDA = RAIZ / "web" / "sociedades.json"
BEELINK = "beelink"
CNPJ_RE = re.compile(r"(?<![\d.])(\d{2})\.?(\d{3})\.?(\d{3})/(\d{4})-?(\d{2})(?!\d)")
CPF_RE = re.compile(r"(?<![\d./])(\d{3})\.(\d{3})\.(\d{3})-(\d{2})(?![\d/])")
def dv_cnpj(d):
def c(s, w):
r = sum(int(a) * b for a, b in zip(s, w)) % 11
return 0 if r < 2 else 11 - r
w1 = [5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2]
return len(set(d)) > 1 and c(d[:12], w1) == int(d[12]) and c(d[:13], [6] + w1) == int(d[13])
def dv_cpf(d):
if len(set(d)) == 1:
return False
for n in (9, 10):
s = sum(int(d[i]) * (n + 1 - i) for i in range(n))
if (s * 10) % 11 % 10 != int(d[n]):
return False
return True
def extrai():
cnpj, cpf = defaultdict(set), defaultdict(set)
invalidos = Counter()
arquivos = sorted(ORIG.rglob("*.md"))
for f in arquivos:
t = f.read_text(errors="ignore")
rel = str(f.relative_to(ORIG))
for m in CNPJ_RE.finditer(t):
d = "".join(m.groups())
if dv_cnpj(d):
cnpj[d].add(rel)
else:
invalidos["cnpj"] += 1
for m in CPF_RE.finditer(t):
d = "".join(m.groups())
if dv_cpf(d):
cpf[d].add(rel)
else:
invalidos["cpf"] += 1
return cnpj, cpf, invalidos, len(arquivos)
def sql(nome, consulta):
"""Roda no beelink em -readonly; guarda o resultado em _cache/<nome>.json."""
arq = CACHE / f"{nome}.json"
if "--cache" in sys.argv and arq.exists():
return json.loads(arq.read_text())
r = subprocess.run(["ssh", BEELINK, "~/bin/duckdb -readonly -json ~/rodado/basedosdados.duckdb"],
input="SET enable_progress_bar=false;\n" + consulta, capture_output=True, text=True, check=True)
linhas = json.loads(r.stdout[r.stdout.index("["):]) if "[" in r.stdout else []
CACHE.mkdir(exist_ok=True)
arq.write_text(json.dumps(linhas, ensure_ascii=False))
return linhas
def envia(nome, cab, valores):
CACHE.mkdir(exist_ok=True)
loc = CACHE / f"{nome}.csv"
loc.write_text(cab + "\n" + "\n".join(sorted(valores)) + "\n")
subprocess.run(["scp", "-q", str(loc), f"{BEELINK}:duckdb_tmp/pet16704_{nome}.csv"], check=True)
return f"read_csv('~/duckdb_tmp/pet16704_{nome}.csv', columns={{'{cab}':'VARCHAR'}}, header=true)"
CPF_NO_NOME = re.compile(r"\s*\b(\d{3})(\d{3})(\d{3})(\d{2})\b")
def limpa(nome):
"""Razão social de empresário individual/MEI termina com o CPF inteiro: mascara."""
return CPF_NO_NOME.sub(lambda m: f" ***.{m[2]}.{m[3]}-**", nome) if nome else nome
def mascara(cpf):
return f"***.{cpf[3:6]}.{cpf[6:9]}-**" if cpf and len(cpf) == 11 and cpf.isdigit() else (cpf or "")
def main():
cnpj, cpf, invalidos, n_arq = extrai()
print(f"{n_arq} arquivos · {len(cnpj)} CNPJs e {len(cpf)} CPFs válidos · inválidos {dict(invalidos)}", file=sys.stderr)
cache_ok = "--cache" in sys.argv and (CACHE / "socios.json").exists()
if not cache_ok:
t_cnpj = envia("cnpj", "cnpj", cnpj)
t_cpf = envia("cpf", "cpf", cpf)
else:
t_cnpj = t_cpf = None
socios = sql("socios", f"""
SELECT s.cnpj_basico b, s.tipo, s.documento doc, s.nome, s.qualificacao q,
s.data_entrada_sociedade::VARCHAR entrada, s.no_ultimo_retrato atual
FROM br_me_cnpj.socios_historico s
WHERE s.cnpj_basico IN (SELECT substr(cnpj,1,8) FROM {t_cnpj})
OR s.documento IN (SELECT cpf FROM {t_cpf});""")
basicos = {k[:8] for k in cnpj} | {s["b"] for s in socios} | {
s["doc"][:8] for s in socios if s["tipo"] == "1" and s["doc"] and s["doc"].isdigit()}
if not cache_ok:
t_b = envia("basicos", "b", basicos)
else:
t_b = None
estab = sql("estabelecimentos", f"""
SELECT e.cnpj, e.cnpj_basico b, e.identificador_matriz_filial mf, e.nome_fantasia fantasia,
e.situacao_cadastral sit, e.data_situacao_cadastral::VARCHAR data_sit,
e.data_inicio_atividade::VARCHAR inicio, e.cnae_fiscal_principal cnae, e.sigla_uf uf, m.nome mun
FROM br_me_cnpj.estabelecimentos e
LEFT JOIN br_bd_diretorios_brasil.municipio m ON m.id_municipio = e.id_municipio
WHERE e.cnpj_basico IN (SELECT b FROM {t_b})
AND (e.identificador_matriz_filial = '1' OR e.cnpj IN (SELECT cnpj FROM {t_cnpj}));""")
empresas = sql("empresas", f"""
SELECT cnpj_basico b, razao_social razao, natureza_juridica nat, capital_social cap
FROM br_me_cnpj.empresas WHERE cnpj_basico IN (SELECT b FROM {t_b});""")
dic = sql("dicionario", """
SELECT id_tabela t, nome_coluna c, chave k, valor v FROM br_me_cnpj.dicionario
WHERE nome_coluna IN ('qualificacao', 'situacao_cadastral');""")
cnaes = sql("cnae", """
SELECT subclasse k, descricao_subclasse d, secao s, descricao_secao ds FROM br_bd_diretorios_brasil.cnae_2;""")
# --- documentos: um índice por arquivo, com o id da linha do tempo quando ele está lá
linha = {d["file"]: d["id"] for d in json.loads((RAIZ / "web" / "docs.json").read_text())}
arquivos = sorted(set().union(*cnpj.values(), *cpf.values()))
idx_doc = {f: i for i, f in enumerate(arquivos)}
# o link vai para o arquivo no git.rodado.xyz: se a cópia local mudou de pasta e não foi
# commitada, aponta para o caminho versionado de mesmo nome
git = subprocess.run(["git", "-C", str(RAIZ), "ls-files", "-z", "originals"], capture_output=True, text=True).stdout
versionados = {p[len("originals/"):] for p in git.split("\0") if p}
por_nome = {Path(p).name: p for p in versionados}
docs = []
for f in arquivos:
g = f if f in versionados else por_nome.get(Path(f).name, f)
parte, _, resto = g.partition("/")
docs.append([g, linha.get(resto) if parte == "Parte2" else None])
razao = {e["b"]: e for e in empresas}
matriz, estab_por_cnpj = {}, {}
for e in estab:
estab_por_cnpj[e["cnpj"]] = e
if e["mf"] == "1":
matriz[e["b"]] = e
# --- nós: empresa por cnpj_basico; pessoa por CPF (citada) ou por documento+nome (não citada)
nos, arestas = {}, []
def empresa(b):
k = "e" + b
if k not in nos:
r, m = razao.get(b, {}), matriz.get(b) or {}
cap = r.get("cap")
nos[k] = {"id": k, "t": "e", "b": b, "nome": limpa(r.get("razao")) or f"CNPJ {b}",
"fant": m.get("fantasia"), "sit": m.get("sit"), "uf": m.get("uf"), "mun": m.get("mun"),
"cnae": m.get("cnae"), "ini": m.get("inicio"), "nat": r.get("nat"),
"cap": cap if cap and cap < 999999999999 else None, "cit": [], "docs": set()}
return nos[k]
for c, arqs in cnpj.items():
if c not in estab_por_cnpj:
continue
n = empresa(c[:8])
e = estab_por_cnpj[c]
n["cit"].append({"cnpj": c, "mf": e["mf"], "uf": e["uf"], "mun": e["mun"], "sit": e["sit"], "n": len(arqs)})
n["docs"] |= {idx_doc[a] for a in arqs}
nomes_cpf = defaultdict(Counter)
for s in socios:
if s["tipo"] == "2" and s["doc"] in cpf:
nomes_cpf[s["doc"]][s["nome"]] += 1
for c, ns in nomes_cpf.items():
k = "p" + c
nos[k] = {"id": k, "t": "p", "nome": ns.most_common(1)[0][0], "cpf": mascara(c), "cit": True,
"docs": {idx_doc[a] for a in cpf[c]}}
# vínculos
vinc = []
for s in socios:
alvo = None
if s["tipo"] == "2":
alvo = "p" + s["doc"] if s["doc"] in cpf else "x" + (s["doc"] or "") + "|" + (s["nome"] or "")
elif s["tipo"] == "1" and s["doc"] and s["doc"].isdigit():
alvo = "e" + s["doc"][:8]
else:
alvo = "x|" + (s["nome"] or "")
vinc.append((s["b"], alvo, s))
def citado(k):
return k in nos and (nos[k]["t"] == "p" or nos[k]["cit"])
# grau de cada nó não citado em relação a nós citados
toca = defaultdict(set)
for b, alvo, s in vinc:
eb = "e" + b
if citado(eb):
toca[alvo].add(eb)
if citado(alvo):
toca[eb].add(alvo)
ponte = {k for k, v in toca.items() if len(v) >= 2 and not citado(k)}
extras = defaultdict(list) # vínculos com nó que fica só no painel
vistos = set()
for b, alvo, s in vinc:
eb = "e" + b
q = s["q"]
rel = (eb, alvo, q)
if rel in vistos:
continue
vistos.add(rel)
a_ok = citado(eb) or eb in ponte
b_ok = citado(alvo) or alvo in ponte
if a_ok and b_ok:
if alvo.startswith("e"):
empresa(alvo[1:])
elif alvo.startswith("x") and alvo not in nos:
nos[alvo] = {"id": alvo, "t": "p", "nome": limpa(s["nome"]), "cpf": mascara(s["doc"]), "cit": False, "docs": set()}
empresa(b)
arestas.append([eb, alvo, q, 1 if s["atual"] else 0, s["entrada"]])
elif a_ok:
extras[eb].append([limpa(s["nome"]), "e" if alvo.startswith("e") else "p", q, 1 if s["atual"] else 0])
elif b_ok:
r = razao.get(b, {})
m = matriz.get(b) or {}
extras[alvo].append([limpa(r.get("razao")) or f"CNPJ {b}", "e", q, 1 if s["atual"] else 0, b, m.get("sit")])
for k, n in nos.items():
n["docs"] = sorted(n.get("docs", ()))
if extras.get(k):
n["mais"] = extras[k]
if n["t"] == "e" and not n["cit"]:
n["cit"] = False
qual = {d["k"]: d["v"] for d in dic if d["c"] == "qualificacao"}
sit = {d["k"]: d["v"] for d in dic if d["c"] == "situacao_cadastral"}
cnae_usados = {n.get("cnae") for n in nos.values() if n.get("cnae")}
cn = {c["k"]: [c["d"], c["s"]] for c in cnaes if c["k"] in cnae_usados}
secoes = {c["s"]: c["ds"] for c in cnaes}
cpf_socio = set(nomes_cpf)
resumo = {
"arquivos": n_arq,
"cnpj_validos": len(cnpj), "cnpj_no_cadastro": sum(1 for c in cnpj if c in estab_por_cnpj),
"empresas_citadas": sum(1 for n in nos.values() if n["t"] == "e" and n["cit"]),
"cpf_validos": len(cpf), "cpf_socios": len(cpf_socio), "cpf_sem_empresa": len(cpf) - len(cpf_socio),
"invalidos": dict(invalidos),
"retrato": "2026-10",
}
# ids públicos: sequenciais. A chave interna de pessoa carrega o CPF inteiro e não pode sair
# no JSON (nem como hash: 10^9 CPFs se recalculam num laptop).
novo = {k: f"{n['t']}{i}" for i, (k, n) in enumerate(nos.items())}
for k, n in nos.items():
n["id"] = novo[k]
if n["t"] == "e":
n["id"] = "e" + n["b"]
novo = {k: n["id"] for k, n in nos.items()}
arestas = [[novo[a], novo[b], *r] for a, b, *r in arestas]
texto = json.dumps(list(nos.values()), ensure_ascii=False)
assert not any(c in texto for c in cpf), "CPF inteiro no JSON"
out = {"resumo": resumo, "qual": qual, "sit": sit, "cnae": cn, "secoes": secoes, "docs": docs,
"nos": list(nos.values()), "arestas": arestas}
SAIDA.write_text(json.dumps(out, ensure_ascii=False, separators=(",", ":")))
print(json.dumps(resumo, ensure_ascii=False), file=sys.stderr)
print(f"{len(nos)} nós ({sum(1 for n in nos.values() if n['t']=='e')} empresas), {len(arestas)} arestas, "
f"{SAIDA.stat().st_size/1e6:.1f} MB", file=sys.stderr)
if __name__ == "__main__":
main()
+1 -1
View File
@@ -432,7 +432,7 @@
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M14 3v5h5"/><path d="M6 3h8l5 5v13a1 1 0 0 1-1 1H6a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1z"/></svg>
Dossiê
</a>
<a class="page-link" href="https://rafapolo.github.io/vorcaros/" target="_blank" rel="noopener noreferrer">
<a class="page-link" href="sociedades.html" target="_blank" rel="noopener noreferrer">
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="5" cy="6" r="2.5"/><circle cx="19" cy="6" r="2.5"/><circle cx="12" cy="18" r="2.5"/><path d="M7 7.3 10 16"/><path d="M17 7.3 14 16"/><path d="M7.4 6h9.2"/></svg>
Sociedades
</a>
+660
View File
@@ -0,0 +1,660 @@
<!DOCTYPE html>
<html lang="pt-BR">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Sociedades nos autos da Pet16704</title>
<meta name="description" content="Os CNPJs e CPFs citados nos autos da Pet16704 cruzados com o cadastro de CNPJ da Receita Federal: empresas, sócios e quem liga quem.">
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Source+Serif+4:opsz,wght@8..60,500;8..60,600;8..60,700&family=Public+Sans:wght@400;500;600;700&family=IBM+Plex+Mono:wght@400;500&display=swap">
<style>
[hidden]{ display:none !important; }
:root{
color-scheme: light;
--page:#f9f9f7; --surface:#fcfcfb; --surface-2:#f1f0ea;
--ink:#0b0b0b; --ink-2:#52514e; --ink-3:#898781;
--grid:#e1e0d9; --border:rgba(11,11,11,0.10);
--s1:#2a78d6; --s2:#eb6834; --s3:#1baf7a; --s4:#a09d94;
--accent:var(--s1); --accent-wash:rgba(42,120,214,0.10); --danger:#a8271f;
--edge:rgba(11,11,11,0.16); --edge-hot:rgba(42,120,214,0.75);
}
@media (prefers-color-scheme: dark){
:root:not([data-theme="light"]){
color-scheme: dark;
--page:#0d0d0d; --surface:#1a1a19; --surface-2:#232322;
--ink:#ffffff; --ink-2:#c3c2b7; --ink-3:#898781;
--grid:#2c2c2a; --border:rgba(255,255,255,0.10);
--s1:#3987e5; --s2:#d95926; --s3:#199e70; --s4:#77746c;
--accent-wash:rgba(57,135,229,0.16); --danger:#f0847a;
--edge:rgba(255,255,255,0.13); --edge-hot:rgba(57,135,229,0.85);
}
}
:root[data-theme="dark"]{
color-scheme: dark;
--page:#0d0d0d; --surface:#1a1a19; --surface-2:#232322;
--ink:#ffffff; --ink-2:#c3c2b7; --ink-3:#898781;
--grid:#2c2c2a; --border:rgba(255,255,255,0.10);
--s1:#3987e5; --s2:#d95926; --s3:#199e70; --s4:#77746c;
--accent-wash:rgba(57,135,229,0.16); --danger:#f0847a;
--edge:rgba(255,255,255,0.13); --edge-hot:rgba(57,135,229,0.85);
}
*{ box-sizing:border-box; }
html,body{ margin:0; }
body{
background:var(--page); color:var(--ink); min-width:360px;
font-family:"Public Sans", system-ui, -apple-system, "Segoe UI", sans-serif;
padding-inline:max(16px, calc((100vw - 1400px)/2)); padding-block:28px 40px;
}
header{ display:flex; flex-direction:column; gap:12px; margin-bottom:18px; }
.page-top-row{ display:flex; flex-wrap:wrap; justify-content:space-between; align-items:center; gap:10px; }
.page-top-links{ display:flex; flex-wrap:wrap; gap:10px; }
.page-link{
display:inline-flex; align-items:center; gap:6px;
font-family:"IBM Plex Mono",monospace; font-size:11px; letter-spacing:.06em; text-transform:uppercase;
color:var(--ink-2); border:1px solid var(--border); background:var(--surface); border-radius:999px;
padding:5px 11px; text-decoration:none; cursor:pointer;
}
.page-link svg{ flex:none; opacity:.7; }
.page-link:hover{ border-color:var(--accent); color:var(--ink); }
.stamp{
font-family:"IBM Plex Mono",monospace; font-size:10.5px; letter-spacing:.09em; text-transform:uppercase;
color:var(--danger); border:1.4px solid var(--danger); border-radius:2px;
padding:4px 8px; transform:rotate(-2deg); white-space:nowrap; flex-shrink:0;
}
h1{ font-family:"Source Serif 4",Georgia,serif; font-size:clamp(24px,3.2vw,32px); font-weight:600; letter-spacing:-0.01em; margin:0; }
.lede{ max-width:78ch; color:var(--ink-2); font-size:14.5px; line-height:1.55; margin:0; }
.lede strong{ color:var(--ink); }
.mono{ font-family:"IBM Plex Mono",monospace; }
.stage{
display:grid; grid-template-columns:260px minmax(0,1fr) 340px; gap:0;
border:1px solid var(--border); border-radius:10px; background:var(--surface); overflow:hidden;
height:min(78vh, 860px); min-height:520px;
}
.side{ padding:14px; overflow:auto; border-right:1px solid var(--border); font-size:13px; }
.info{ padding:14px 16px; overflow:auto; border-left:1px solid var(--border); font-size:13px; }
.canvas-wrap{ position:relative; min-width:0; background:var(--page); }
canvas{ position:absolute; inset:0; width:100%; height:100%; display:block; touch-action:none; cursor:grab; }
canvas.dragging{ cursor:grabbing; }
.loading{
position:absolute; inset:0; display:flex; align-items:center; justify-content:center;
font-family:"IBM Plex Mono",monospace; font-size:12px; color:var(--ink-3); pointer-events:none;
}
.zoom-btns{ position:absolute; right:10px; bottom:10px; display:flex; flex-direction:column; gap:6px; }
.zoom-btns button{
width:30px; height:30px; border-radius:6px; border:1px solid var(--border); background:var(--surface);
color:var(--ink); font-size:16px; cursor:pointer;
}
.hint{ position:absolute; left:10px; bottom:10px; font-size:11px; color:var(--ink-3); font-family:"IBM Plex Mono",monospace; }
.sec-title{
font-family:"IBM Plex Mono",monospace; font-size:10.5px; letter-spacing:.08em; text-transform:uppercase;
color:var(--ink-3); margin:16px 0 8px;
}
.sec-title:first-child{ margin-top:0; }
.search{ position:relative; }
.search input{
width:100%; padding:8px 30px 8px 10px; border-radius:7px; border:1px solid var(--border);
background:var(--page); color:var(--ink); font:inherit; font-size:13px;
}
.search input:focus{ outline:2px solid var(--accent); outline-offset:-1px; }
.search .clear{
position:absolute; right:6px; top:50%; transform:translateY(-50%); border:0; background:none;
color:var(--ink-3); font-size:16px; cursor:pointer; padding:2px 4px;
}
.results{ margin-top:6px; display:flex; flex-direction:column; gap:1px; max-height:260px; overflow:auto; }
.results button, .lst button{
text-align:left; border:0; background:none; color:var(--ink); font:inherit; font-size:12.5px;
padding:5px 6px; border-radius:5px; cursor:pointer; display:flex; gap:7px; align-items:baseline; width:100%;
}
.results button:hover, .lst button:hover{ background:var(--accent-wash); }
.results .meta, .lst .meta{ color:var(--ink-3); font-size:11px; margin-left:auto; white-space:nowrap; }
.dot{ width:9px; height:9px; border-radius:50%; flex:none; display:inline-block; transform:translateY(1px); }
.legend label, .filters label{
display:flex; align-items:center; gap:8px; padding:4px 0; cursor:pointer; color:var(--ink-2);
}
.legend .n, .filters .n{ margin-left:auto; color:var(--ink-3); font-family:"IBM Plex Mono",monospace; font-size:11px; }
.legend input, .filters input{ margin:0; accent-color:var(--accent); }
.cnae-list{ max-height:220px; overflow:auto; }
.cnae-list label{ font-size:12px; line-height:1.3; }
.info h2{ font-family:"Source Serif 4",Georgia,serif; font-size:19px; line-height:1.25; margin:0 0 4px; font-weight:600; }
.info .kind{ font-family:"IBM Plex Mono",monospace; font-size:10.5px; letter-spacing:.07em; text-transform:uppercase; color:var(--ink-3); }
.info dl{ display:grid; grid-template-columns:auto 1fr; gap:4px 10px; margin:12px 0 0; }
.info dt{ color:var(--ink-3); font-size:12px; }
.info dd{ margin:0; font-size:12.5px; }
.badge{
display:inline-block; font-family:"IBM Plex Mono",monospace; font-size:10.5px; padding:1px 6px; border-radius:4px;
background:var(--surface-2); color:var(--ink-2);
}
.badge.off{ color:var(--danger); }
.lst{ display:flex; flex-direction:column; gap:1px; }
.lst .ex{ opacity:.6; }
.lst .txt{ min-width:0; overflow:hidden; text-overflow:ellipsis; }
.docs a{ display:block; color:var(--ink-2); font-size:11.5px; padding:3px 0; text-decoration:none; word-break:break-word; }
.docs a:hover{ color:var(--accent); text-decoration:underline; }
.empty{ color:var(--ink-3); font-size:13px; line-height:1.5; }
.nav{ display:flex; gap:6px; margin-bottom:10px; }
.nav button{
border:1px solid var(--border); background:var(--page); color:var(--ink-2); border-radius:6px;
padding:3px 9px; cursor:pointer; font-size:13px;
}
.nav button:disabled{ opacity:.35; cursor:default; }
.more-btn{ border:0; background:none; color:var(--accent); cursor:pointer; font:inherit; font-size:12px; padding:4px 6px; }
footer{ margin-top:22px; color:var(--ink-3); font-size:12.5px; line-height:1.6; max-width:90ch; }
footer p{ margin:0 0 10px; }
footer a{ color:var(--ink-2); }
@media (max-width: 1100px){
.stage{ grid-template-columns:240px minmax(0,1fr); }
.info{ grid-column:1 / -1; border-left:0; border-top:1px solid var(--border); max-height:none; }
.stage{ height:auto; }
.canvas-wrap{ height:68vh; min-height:440px; }
}
@media (max-width: 720px){
.stage{ grid-template-columns:minmax(0,1fr); }
.side{ border-right:0; border-bottom:1px solid var(--border); }
.canvas-wrap{ height:62vh; min-height:380px; }
.cnae-list{ max-height:160px; }
}
</style>
</head>
<body>
<header>
<div class="page-top-row">
<div class="stamp">Sob sigilo nos autos originais</div>
<div class="page-top-links">
<a class="page-link" href="./">
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 12h18"/><circle cx="7" cy="12" r="2"/><circle cx="14" cy="12" r="2"/><circle cx="19" cy="12" r="1.5"/></svg>
Linha do tempo
</a>
<a class="page-link" href="revelacoes.html" target="_blank" rel="noopener noreferrer">
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M14 3v5h5"/><path d="M6 3h8l5 5v13a1 1 0 0 1-1 1H6a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1z"/></svg>
Dossiê
</a>
<a class="page-link" href="https://git.rodado.xyz/rodado/pet16704/src/branch/main/pipeline/sociedades.py" target="_blank" rel="noopener noreferrer">
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M6 3v12"/><circle cx="6" cy="18" r="3"/><circle cx="18" cy="6" r="3"/><path d="M18 9a9 9 0 0 1-9 9"/></svg>
Fontes
</a>
</div>
</div>
<h1>Sociedades citadas nos autos</h1>
<p class="lede" id="lede">Carregando…</p>
</header>
<div class="stage">
<aside class="side">
<div class="sec-title">Buscar</div>
<div class="search">
<input id="q" type="search" placeholder="Nome, razão social ou CNPJ" aria-label="Buscar empresa, pessoa ou CNPJ" autocomplete="off">
<button class="clear" id="qClear" aria-label="Limpar busca" hidden>&times;</button>
</div>
<div class="results" id="results" role="list"></div>
<div class="sec-title">No grafo</div>
<div class="legend" id="legend"></div>
<div class="sec-title">Situação da empresa</div>
<div class="filters" id="sitFilters"></div>
<div class="sec-title">Atividade (CNAE)</div>
<div class="filters cnae-list" id="cnaeFilters"></div>
</aside>
<div class="canvas-wrap" id="wrap">
<canvas id="cv" aria-label="Grafo de empresas e sócios citados nos autos"></canvas>
<div class="loading" id="loading">Carregando a rede…</div>
<div class="hint" id="hint">arraste · role para zoom · clique num nó</div>
<div class="zoom-btns">
<button id="zin" aria-label="Aproximar">+</button>
<button id="zout" aria-label="Afastar">−</button>
<button id="zfit" aria-label="Enquadrar tudo">⤢</button>
</div>
</div>
<section class="info" id="info" aria-live="polite">
<div class="nav">
<button id="back" disabled aria-label="Anterior">&#8592;</button>
<button id="fwd" disabled aria-label="Próximo">&#8594;</button>
</div>
<div id="infoBody"><p class="empty">Clique num nó do grafo ou busque um nome. Cada empresa e cada pessoa
mostra quem está ligado a ela no cadastro da Receita e em quais documentos dos autos ela aparece.</p></div>
</section>
</div>
<footer id="foot"></footer>
<script>
(function(){
"use strict";
var D, nodes, byId = {}, links, adj = {};
var SIT_ATIVA = "2";
var state = { tipos:{ec:1, pc:1, el:1, pl:1}, sit:{}, cnae:{}, sel:null, hist:[], hi:-1 };
var fmt = new Intl.NumberFormat("pt-BR");
var BRL = new Intl.NumberFormat("pt-BR", {style:"currency", currency:"BRL", maximumFractionDigits:0});
var cv = document.getElementById("cv"), ctx = cv.getContext("2d");
var wrap = document.getElementById("wrap");
var W = 0, H = 0, DPR = 1;
var T = { x:0, y:0, k:0.3 };
var pos = null; // Float32Array x,y por índice de nó do grafo
var gnodes = [], gidx = {}; // nós que estão no grafo (têm aresta)
var colors = {};
function css(v){ return getComputedStyle(document.documentElement).getPropertyValue(v).trim(); }
function readColors(){
colors = { ec:css("--s1"), pc:css("--s2"), el:css("--s3"), pl:css("--s4"),
edge:css("--edge"), hot:css("--edge-hot"), ink:css("--ink"), ink3:css("--ink-3"), page:css("--page") };
}
function cls(n){ return n.t === "e" ? (n.cit ? "ec" : "el") : (n.cit ? "pc" : "pl"); }
var NOMES = { ec:"Empresa citada (CNPJ nos autos)", pc:"Pessoa citada (CPF nos autos, sócia de empresa)",
el:"Empresa ligada (não citada)", pl:"Sócio ligado (não citado)" };
function esc(s){ return String(s == null ? "" : s).replace(/[&<>"]/g, function(c){ return {"&":"&amp;","<":"&lt;",">":"&gt;","\"":"&quot;"}[c]; }); }
function fmtCnpj(c){ return c.replace(/^(\d{2})(\d{3})(\d{3})(\d{4})(\d{2})$/, "$1.$2.$3/$4-$5"); }
function fmtData(s){ return s ? s.split("-").reverse().join("/") : "—"; }
function norm(s){ return (s||"").normalize("NFD").replace(/[̀-ͯ]/g,"").toUpperCase(); }
fetch("sociedades.json").then(function(r){ return r.json(); }).then(init).catch(function(e){
document.getElementById("loading").textContent = "Não foi possível carregar os dados (" + e.message + ").";
});
function init(data){
D = data; nodes = D.nos; links = D.arestas;
nodes.forEach(function(n, i){ n.i = i; byId[n.id] = n; n.deg = 0; n.key = norm(n.nome + " " + (n.fant||"") + " " + (n.b||"") + " " + (n.cit && n.cit.map ? n.cit.map(function(c){return c.cnpj;}).join(" ") : "")); });
links.forEach(function(l){
var a = byId[l[0]], b = byId[l[1]];
if (!a || !b) return;
a.deg++; b.deg++;
(adj[a.id] = adj[a.id] || []).push(l);
(adj[b.id] = adj[b.id] || []).push(l);
});
nodes.forEach(function(n){ if (n.deg > 0){ gidx[n.id] = gnodes.length; gnodes.push(n); } });
nodes.forEach(function(n){ n.r = n.t === "e" ? 2.2 + Math.sqrt(n.docs.length) * 0.9 + Math.sqrt(n.deg) * 0.5
: 2 + Math.sqrt(n.docs.length) * 0.9 + Math.sqrt(n.deg) * 0.5; });
var R = D.resumo;
document.getElementById("lede").innerHTML =
"Os " + fmt.format(R.arquivos) + " arquivos dos autos (texto extraído por OCR) citam <strong>" + fmt.format(R.cnpj_validos) +
" CNPJs</strong> e <strong>" + fmt.format(R.cpf_validos) + " CPFs</strong> válidos. Cruzados com o cadastro de CNPJ da Receita Federal (retrato de " +
R.retrato.split("-").reverse().join("/") + "), " + fmt.format(R.cnpj_no_cadastro) + " CNPJs viraram <strong>" + fmt.format(R.empresas_citadas) +
" empresas</strong>, e <strong>" + fmt.format(R.cpf_socios) + " dos CPFs</strong> são sócios ou administradores de alguma empresa. " +
"O grafo liga as duas pontas pelo quadro de sócios — inclusive quem já saiu — e mostra também quem não foi citado mas liga dois nomes citados.";
buildLegend(); buildFilters(); buildFooter();
readColors(); resize();
startLayout();
var q = new URLSearchParams(location.search).get("n");
if (q && byId[q]) select(byId[q], true);
}
function buildLegend(){
var c = {ec:0, pc:0, el:0, pl:0};
gnodes.forEach(function(n){ c[cls(n)]++; });
var el = document.getElementById("legend");
el.innerHTML = ["ec","pc","el","pl"].map(function(k){
return '<label><input type="checkbox" data-k="'+k+'" checked><span class="dot" style="background:var(--s'+({ec:1,pc:2,el:3,pl:4})[k]+')"></span>'+
NOMES[k] + '<span class="n">'+fmt.format(c[k])+'</span></label>';
}).join("");
el.addEventListener("change", function(e){ state.tipos[e.target.dataset.k] = e.target.checked ? 1 : 0; draw(); });
}
function buildFilters(){
var sc = {}, cc = {};
gnodes.forEach(function(n){
if (n.t !== "e") return;
var s = n.sit || "?"; sc[s] = (sc[s]||0) + 1;
var sec = n.cnae && D.cnae[n.cnae] ? D.cnae[n.cnae][1] : "?"; cc[sec] = (cc[sec]||0) + 1;
});
var sitNome = Object.assign({"?":"Sem estabelecimento matriz no cadastro"}, D.sit);
var sitEl = document.getElementById("sitFilters");
sitEl.innerHTML = Object.keys(sc).sort(function(a,b){ return sc[b]-sc[a]; }).map(function(k){
state.sit[k] = 1;
return '<label><input type="checkbox" data-k="'+esc(k)+'" checked>'+esc(sitNome[k]||k)+'<span class="n">'+fmt.format(sc[k])+'</span></label>';
}).join("");
sitEl.addEventListener("change", function(e){ state.sit[e.target.dataset.k] = e.target.checked ? 1 : 0; draw(); });
var secNome = Object.assign({"?":"Sem CNAE"}, D.secoes);
var cEl = document.getElementById("cnaeFilters");
cEl.innerHTML = Object.keys(cc).sort(function(a,b){ return cc[b]-cc[a]; }).map(function(k){
state.cnae[k] = 1;
return '<label><input type="checkbox" data-k="'+esc(k)+'" checked>'+esc(secNome[k]||k)+'<span class="n">'+fmt.format(cc[k])+'</span></label>';
}).join("");
cEl.addEventListener("change", function(e){ state.cnae[e.target.dataset.k] = e.target.checked ? 1 : 0; draw(); });
}
function buildFooter(){
var R = D.resumo;
document.getElementById("foot").innerHTML =
"<p><strong>Como foi feito.</strong> Todo número no formato de CNPJ (com a barra) ou de CPF (com pontos e hífen) nos textos dos autos " +
"foi conferido pelo dígito verificador; " + fmt.format(R.invalidos.cnpj||0) + " ocorrências de CNPJ e " + fmt.format(R.invalidos.cpf||0) +
" de CPF não passaram — em geral erro de OCR — e ficaram de fora. Os válidos foram cruzados com o cadastro de CNPJ da Receita Federal " +
"(empresas, estabelecimentos e o histórico do quadro de sócios desde 2021) no espelho <a href=\"https://rodado.xyz\" target=\"_blank\" rel=\"noopener\">rodado</a>. " +
"Ligações tracejadas são vínculos que já não aparecem no cadastro mais recente.</p>" +
"<p><strong>Privacidade.</strong> CPF nunca aparece inteiro: só no formato mascarado que a própria Receita publica. " +
fmt.format(R.cpf_sem_empresa) + " CPFs citados não são sócios de nenhuma empresa — sem nome em fonte pública, entram só nesta contagem. " +
"Nome de sócio vem do cadastro público da Receita, não do texto dos autos.</p>" +
"<p><strong>Leia com cuidado.</strong> Estar citado nos autos não quer dizer estar sob investigação: muitos CNPJs aparecem como banco, " +
"contraparte de transação, empregador ou endereço de diligência. O cruzamento é automático — um CNPJ citado de passagem e uma empresa no centro " +
"do caso aparecem do mesmo jeito; o tamanho do nó é o número de documentos que citam o número. Confira sempre no documento original (link no painel).</p>";
}
// ------------------------------------------------------------ layout (d3-force num worker)
var worker = null;
function startLayout(){
var src = [
"importScripts('https://cdn.jsdelivr.net/npm/d3-dispatch@3.0.1/dist/d3-dispatch.min.js',",
"'https://cdn.jsdelivr.net/npm/d3-quadtree@3.0.1/dist/d3-quadtree.min.js',",
"'https://cdn.jsdelivr.net/npm/d3-timer@3.0.1/dist/d3-timer.min.js',",
"'https://cdn.jsdelivr.net/npm/d3-force@3.0.0/dist/d3-force.min.js');",
"onmessage=function(e){var N=e.data.n,L=e.data.l,R=e.data.r;",
"var ns=[];for(var i=0;i<N;i++){var a=i*2.399963,rad=12*Math.sqrt(i);ns.push({index:i,x:rad*Math.cos(a),y:rad*Math.sin(a),r:R[i]});}",
"var ls=[];for(var j=0;j<L.length;j+=2)ls.push({source:L[j],target:L[j+1]});",
"var sim=d3.forceSimulation(ns).stop()",
".force('link',d3.forceLink(ls).distance(18).strength(0.7))",
".force('charge',d3.forceManyBody().strength(-22).distanceMax(420).theta(1.1))",
".force('x',d3.forceX(0).strength(0.035)).force('y',d3.forceY(0).strength(0.035))",
".force('col',d3.forceCollide(function(d){return d.r+1.2;}).iterations(1));",
"var total=320;for(var t=0;t<total;t++){sim.tick();if(t%8===0||t===total-1){var b=new Float32Array(N*2);",
"for(var k=0;k<N;k++){b[k*2]=ns[k].x;b[k*2+1]=ns[k].y;}postMessage({p:b,done:t===total-1,t:t/total},[b.buffer]);}}};"
].join("\n");
worker = new Worker(URL.createObjectURL(new Blob([src], {type:"application/javascript"})));
var L = new Int32Array(links.length * 2), R = new Float32Array(gnodes.length);
links.forEach(function(l, i){ L[i*2] = gidx[l[0]]; L[i*2+1] = gidx[l[1]]; });
gnodes.forEach(function(n, i){ R[i] = n.r; });
var first = true;
worker.onmessage = function(e){
pos = e.data.p;
if (first){ first = false; fit(); }
var ld = document.getElementById("loading");
if (e.data.done){ ld.hidden = true; fit(); if (state.sel) centerOn(state.sel); }
else ld.textContent = "Arrumando a rede… " + Math.round(e.data.t*100) + "%";
draw();
};
worker.postMessage({ n:gnodes.length, l:Array.from(L), r:Array.from(R) });
}
// ------------------------------------------------------------ desenho
function resize(){
var r = wrap.getBoundingClientRect();
DPR = window.devicePixelRatio || 1; W = r.width; H = r.height;
cv.width = Math.round(W * DPR); cv.height = Math.round(H * DPR);
draw();
}
window.addEventListener("resize", resize);
if (window.matchMedia) window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change", function(){ readColors(); draw(); });
function visible(n){
if (!state.tipos[cls(n)]) return false;
if (n.t === "e"){
if (!state.sit[n.sit || "?"]) return false;
var sec = n.cnae && D.cnae[n.cnae] ? D.cnae[n.cnae][1] : "?";
if (!state.cnae[sec]) return false;
}
return true;
}
function px(i){ return pos[i*2] * T.k + T.x; }
function py(i){ return pos[i*2+1] * T.k + T.y; }
var raf = 0;
function draw(){ if (!raf) raf = requestAnimationFrame(paint); }
function paint(){
raf = 0;
ctx.setTransform(DPR,0,0,DPR,0,0);
ctx.clearRect(0,0,W,H);
if (!pos) return;
var sel = state.sel, nb = null;
if (sel){ nb = {}; nb[sel.id] = 1; (adj[sel.id]||[]).forEach(function(l){ nb[l[0]] = 1; nb[l[1]] = 1; }); }
var vis = new Uint8Array(gnodes.length);
for (var i = 0; i < gnodes.length; i++) vis[i] = visible(gnodes[i]) ? 1 : 0;
// arestas
ctx.lineWidth = Math.max(0.4, Math.min(1.2, T.k * 1.2));
ctx.strokeStyle = colors.edge;
var hot = [];
ctx.beginPath();
for (var j = 0; j < links.length; j++){
var l = links[j], a = gidx[l[0]], b = gidx[l[1]];
if (!vis[a] || !vis[b]) continue;
if (nb && (l[0] === sel.id || l[1] === sel.id)){ hot.push(l); continue; }
var x1 = px(a), y1 = py(a), x2 = px(b), y2 = py(b);
if ((x1 < 0 && x2 < 0) || (x1 > W && x2 > W) || (y1 < 0 && y2 < 0) || (y1 > H && y2 > H)) continue;
ctx.moveTo(x1, y1); ctx.lineTo(x2, y2);
}
ctx.globalAlpha = nb ? 0.35 : 1;
ctx.stroke();
ctx.globalAlpha = 1;
if (hot.length){
ctx.strokeStyle = colors.hot; ctx.lineWidth = 1.6;
hot.forEach(function(l){
var a = gidx[l[0]], b = gidx[l[1]];
ctx.setLineDash(l[3] ? [] : [4,3]);
ctx.beginPath(); ctx.moveTo(px(a), py(a)); ctx.lineTo(px(b), py(b)); ctx.stroke();
});
ctx.setLineDash([]);
}
// nós
var kk = Math.max(0.55, Math.min(2.2, Math.sqrt(T.k) * 1.4));
for (var t = 0; t < gnodes.length; t++){
if (!vis[t]) continue;
var n = gnodes[t], x = px(t), y = py(t), r = n.r * kk;
if (x < -r || x > W + r || y < -r || y > H + r) continue;
ctx.globalAlpha = nb && !nb[n.id] ? 0.18 : 1;
ctx.beginPath(); ctx.arc(x, y, r, 0, 6.2832);
if (n.t === "e" && n.sit && n.sit !== SIT_ATIVA){
ctx.fillStyle = colors.page; ctx.fill();
ctx.lineWidth = Math.max(1, r * 0.45); ctx.strokeStyle = colors[cls(n)]; ctx.stroke();
} else { ctx.fillStyle = colors[cls(n)]; ctx.fill(); }
}
ctx.globalAlpha = 1;
// rótulos
ctx.font = "500 11px 'Public Sans', system-ui, sans-serif";
ctx.textBaseline = "middle";
var lab = [];
if (nb){ Object.keys(nb).forEach(function(id){ if (gidx[id] != null && vis[gidx[id]]) lab.push(byId[id]); }); }
else {
var lim = T.k > 1.6 ? 9999 : T.k > 0.8 ? 260 : T.k > 0.45 ? 70 : 25;
lab = gnodes.filter(function(n, i){ return vis[i] && n.cit; })
.sort(function(a,b){ return (b.docs.length + b.deg) - (a.docs.length + a.deg); }).slice(0, lim);
}
lab.forEach(function(n){
var i = gidx[n.id], x = px(i), y = py(i);
if (x < -50 || x > W + 50 || y < -10 || y > H + 10) return;
var s = n.nome.length > 38 ? n.nome.slice(0, 36) + "…" : n.nome;
var ox = x + n.r * kk + 4;
ctx.lineWidth = 3; ctx.strokeStyle = colors.page; ctx.strokeText(s, ox, y);
ctx.fillStyle = n === sel ? colors.ink : colors.ink3; ctx.fillText(s, ox, y);
});
if (sel && gidx[sel.id] != null){
var si = gidx[sel.id];
ctx.beginPath(); ctx.arc(px(si), py(si), sel.r * kk + 4, 0, 6.2832);
ctx.lineWidth = 2; ctx.strokeStyle = colors.ink; ctx.stroke();
}
}
function fit(){
if (!pos) return;
var x0 = Infinity, y0 = Infinity, x1 = -Infinity, y1 = -Infinity;
for (var i = 0; i < gnodes.length; i++){
var x = pos[i*2], y = pos[i*2+1];
if (x < x0) x0 = x; if (x > x1) x1 = x; if (y < y0) y0 = y; if (y > y1) y1 = y;
}
var k = Math.min(W / (x1 - x0 + 40), H / (y1 - y0 + 40));
T.k = k; T.x = W/2 - (x0 + x1)/2 * k; T.y = H/2 - (y0 + y1)/2 * k;
draw();
}
function centerOn(n){
var i = gidx[n.id]; if (i == null || !pos) return;
T.k = Math.max(T.k, 1.4);
T.x = W/2 - pos[i*2] * T.k; T.y = H/2 - pos[i*2+1] * T.k; draw();
}
function zoomAt(f, cx, cy){
var k = Math.max(0.03, Math.min(12, T.k * f));
T.x = cx - (cx - T.x) * k / T.k; T.y = cy - (cy - T.y) * k / T.k; T.k = k; draw();
}
document.getElementById("zin").onclick = function(){ zoomAt(1.5, W/2, H/2); };
document.getElementById("zout").onclick = function(){ zoomAt(1/1.5, W/2, H/2); };
document.getElementById("zfit").onclick = fit;
// ------------------------------------------------------------ interação
cv.addEventListener("wheel", function(e){
e.preventDefault();
var r = cv.getBoundingClientRect();
zoomAt(Math.exp(-e.deltaY * 0.0015), e.clientX - r.left, e.clientY - r.top);
}, {passive:false});
var pts = {}, drag = null, moved = 0, pinch = null;
cv.addEventListener("pointerdown", function(e){
cv.setPointerCapture(e.pointerId);
pts[e.pointerId] = {x:e.clientX, y:e.clientY};
var ids = Object.keys(pts);
if (ids.length === 2){
var a = pts[ids[0]], b = pts[ids[1]];
pinch = { d:Math.hypot(a.x-b.x, a.y-b.y) }; drag = null;
} else { drag = {x:e.clientX, y:e.clientY}; moved = 0; cv.classList.add("dragging"); }
});
cv.addEventListener("pointermove", function(e){
if (!pts[e.pointerId]){ hover(e); return; }
pts[e.pointerId] = {x:e.clientX, y:e.clientY};
var ids = Object.keys(pts);
if (pinch && ids.length === 2){
var a = pts[ids[0]], b = pts[ids[1]], d = Math.hypot(a.x-b.x, a.y-b.y);
var r = cv.getBoundingClientRect();
zoomAt(d / pinch.d, (a.x+b.x)/2 - r.left, (a.y+b.y)/2 - r.top); pinch.d = d; moved = 99; return;
}
if (drag){
var dx = e.clientX - drag.x, dy = e.clientY - drag.y;
moved += Math.abs(dx) + Math.abs(dy);
T.x += dx; T.y += dy; drag = {x:e.clientX, y:e.clientY}; draw();
}
});
function up(e){
var wasDrag = drag && moved > 4;
delete pts[e.pointerId];
if (Object.keys(pts).length < 2) pinch = null;
cv.classList.remove("dragging");
if (drag && !wasDrag && e.type === "pointerup"){
var n = pick(e);
if (n) select(n); else if (state.sel){ state.sel = null; draw(); }
}
drag = null;
}
cv.addEventListener("pointerup", up);
cv.addEventListener("pointercancel", up);
function pick(e){
if (!pos) return null;
var r = cv.getBoundingClientRect(), x = e.clientX - r.left, y = e.clientY - r.top, best = null, bd = 1e9;
var kk = Math.max(0.55, Math.min(2.2, Math.sqrt(T.k) * 1.4));
for (var i = 0; i < gnodes.length; i++){
var n = gnodes[i]; if (!visible(n)) continue;
var d = Math.hypot(px(i) - x, py(i) - y);
if (d < Math.max(6, n.r * kk + 3) && d < bd){ bd = d; best = n; }
}
return best;
}
function hover(e){ cv.title = (function(n){ return n ? n.nome : ""; })(pick(e)); }
// ------------------------------------------------------------ busca
var qEl = document.getElementById("q"), resEl = document.getElementById("results"), qClr = document.getElementById("qClear");
qEl.addEventListener("input", search);
qClr.onclick = function(){ qEl.value = ""; search(); qEl.focus(); };
function search(){
var q = norm(qEl.value.trim()), qd = q.replace(/\D/g, "");
qClr.hidden = !q;
if (q.length < 2){ resEl.innerHTML = ""; return; }
var out = [];
for (var i = 0; i < nodes.length && out.length < 400; i++){
var n = nodes[i];
if (n.key.indexOf(q) >= 0 || (qd.length >= 8 && n.key.indexOf(qd) >= 0)) out.push(n);
}
out.sort(function(a,b){ return (b.cit?1:0) - (a.cit?1:0) || b.docs.length - a.docs.length || b.deg - a.deg; });
resEl.innerHTML = out.slice(0, 40).map(function(n){
return '<button data-id="'+esc(n.id)+'"><span class="dot" style="background:var(--s'+({ec:1,pc:2,el:3,pl:4})[cls(n)]+')"></span>'+
'<span class="txt">'+esc(n.nome)+'</span><span class="meta">'+(n.docs.length ? n.docs.length+" doc" : "")+'</span></button>';
}).join("") + (out.length > 40 ? '<p class="empty">… e mais '+fmt.format(out.length - 40)+'. Refine a busca.</p>' : "") +
(out.length ? "" : '<p class="empty">Nada encontrado.</p>');
}
resEl.addEventListener("click", function(e){ var b = e.target.closest("button"); if (b) select(byId[b.dataset.id]); });
// ------------------------------------------------------------ painel
function select(n, fromUrl){
if (!n) return;
state.sel = n;
if (state.hist[state.hi] !== n){ state.hist = state.hist.slice(0, state.hi + 1); state.hist.push(n); state.hi = state.hist.length - 1; }
navBtns();
renderInfo(n);
if (!fromUrl) history.replaceState(null, "", "?n=" + encodeURIComponent(n.id));
centerOn(n); draw();
}
var back = document.getElementById("back"), fwd = document.getElementById("fwd");
back.onclick = function(){ if (state.hi > 0){ state.hi--; var n = state.hist[state.hi]; state.sel = n; renderInfo(n); centerOn(n); navBtns(); draw(); } };
fwd.onclick = function(){ if (state.hi < state.hist.length - 1){ state.hi++; var n = state.hist[state.hi]; state.sel = n; renderInfo(n); centerOn(n); navBtns(); draw(); } };
function navBtns(){ back.disabled = state.hi <= 0; fwd.disabled = state.hi >= state.hist.length - 1; }
function sitBadge(s){ return s ? '<span class="badge'+(s === SIT_ATIVA ? "" : " off")+'">'+esc(D.sit[s] || s)+'</span>' : ""; }
function qual(q){ return D.qual[q] || ("qualificação " + q); }
function renderInfo(n){
var h = '<div class="kind">' + esc(NOMES[cls(n)]) + '</div><h2>' + esc(n.nome) + '</h2>';
if (n.t === "e"){
if (n.fant) h += '<div class="empty">' + esc(n.fant) + '</div>';
var cn = n.cnae && D.cnae[n.cnae];
h += '<dl>' +
'<dt>CNPJ base</dt><dd class="mono">' + esc(n.b.replace(/^(\d{2})(\d{3})(\d{3})$/, "$1.$2.$3")) + '</dd>' +
'<dt>Situação</dt><dd>' + (sitBadge(n.sit) || "—") + '</dd>' +
'<dt>Sede</dt><dd>' + esc([n.mun, n.uf].filter(Boolean).join(" · ") || "—") + '</dd>' +
'<dt>Atividade</dt><dd>' + esc(cn ? cn[0] : (n.cnae || "—")) + '</dd>' +
'<dt>Abertura</dt><dd>' + fmtData(n.ini) + '</dd>' +
(n.cap ? '<dt>Capital</dt><dd>' + BRL.format(n.cap) + '</dd>' : "") +
'</dl>';
if (n.cit && n.cit.length){
h += '<div class="sec-title">CNPJs citados nos autos</div><div class="lst">' + n.cit.map(function(c){
return '<div style="font-size:12px;padding:3px 0"><span class="mono">' + fmtCnpj(c.cnpj) + '</span> ' +
(c.mf === "1" ? "matriz" : "filial") + ' · ' + esc([c.mun, c.uf].filter(Boolean).join("/")) + ' ' + sitBadge(c.sit) +
' <span class="meta" style="color:var(--ink-3)">' + c.n + ' doc</span></div>';
}).join("") + '</div>';
}
} else {
h += '<dl><dt>CPF</dt><dd class="mono">' + esc(n.cpf || "—") + '</dd></dl>';
if (!n.cit) h += '<p class="empty" style="margin-top:8px">Não aparece nos autos pelo CPF; está no grafo porque é sócio de mais de uma empresa ou pessoa citada.</p>';
}
// conexões no grafo
var con = (adj[n.id] || []).map(function(l){ var o = byId[l[0] === n.id ? l[1] : l[0]]; return {o:o, l:l}; });
con.sort(function(a,b){ return b.l[3] - a.l[3] || (b.o.cit?1:0) - (a.o.cit?1:0) || b.o.docs.length - a.o.docs.length; });
if (con.length){
h += '<div class="sec-title">' + (n.t === "e" ? "Sócios e participações no grafo" : "Empresas no grafo") + ' · ' + con.length + '</div><div class="lst">' +
con.map(function(c){
return '<button data-id="' + esc(c.o.id) + '" class="' + (c.l[3] ? "" : "ex") + '"><span class="dot" style="background:var(--s' + ({ec:1,pc:2,el:3,pl:4})[cls(c.o)] + ')"></span>' +
'<span class="txt">' + esc(c.o.nome) + '</span><span class="meta">' + esc(qual(c.l[2])) + (c.l[3] ? "" : " · saiu") + '</span></button>';
}).join("") + '</div>';
} else if (n.t === "e") {
h += '<p class="empty" style="margin-top:12px">Sem vínculo societário com outro nome citado nos autos — por isso não está no grafo.</p>';
}
// vínculos fora do grafo
if (n.mais && n.mais.length){
var M = n.mais.slice().sort(function(a,b){ return b[3] - a[3]; });
h += '<div class="sec-title">' + (n.t === "e" ? "Outros sócios (não citados)" : "Outras empresas (não citadas)") + ' · ' + M.length + '</div><div class="lst" id="mais">' +
M.slice(0, 25).map(maisRow).join("") + '</div>' +
(M.length > 25 ? '<button class="more-btn" id="maisBtn">mostrar todos os ' + M.length + '</button>' : "");
}
// documentos
if (n.docs.length){
h += '<div class="sec-title">Citado em ' + n.docs.length + ' documento' + (n.docs.length > 1 ? "s" : "") + '</div><div class="docs">' +
n.docs.slice(0, 60).map(function(i){
var d = D.docs[i];
var url = "https://git.rodado.xyz/rodado/pet16704/src/branch/main/originals/" + d[0].split("/").map(encodeURIComponent).join("/");
return '<a href="' + url + '" target="_blank" rel="noopener noreferrer">' + esc(d[0].replace(/^Parte\d\//, "").replace(/_[0-9a-f]{8}\.md$/, "")) + '</a>';
}).join("") + (n.docs.length > 60 ? '<p class="empty">… e mais ' + (n.docs.length - 60) + '.</p>' : "") + '</div>';
}
var body = document.getElementById("infoBody");
body.innerHTML = h;
body.querySelectorAll(".lst button[data-id]").forEach(function(b){ b.onclick = function(){ select(byId[b.dataset.id]); }; });
var mb = document.getElementById("maisBtn");
if (mb) mb.onclick = function(){
document.getElementById("mais").innerHTML = n.mais.slice().sort(function(a,b){ return b[3] - a[3]; }).map(maisRow).join(""); mb.remove();
};
document.getElementById("info").scrollTop = 0;
}
function maisRow(m){
// [nome, tipo, qualificação, atual, cnpj_basico?, situação?]
var extra = m[4] ? ' <span class="mono">' + m[4].replace(/^(\d{2})(\d{3})(\d{3})$/, "$1.$2.$3") + '</span>' : "";
return '<div class="' + (m[3] ? "" : "ex") + '" style="font-size:12px;padding:3px 0;display:flex;gap:6px;align-items:baseline">' +
'<span class="txt">' + esc(m[0]) + extra + ' ' + (m[5] ? sitBadge(m[5]) : "") + '</span><span class="meta" style="margin-left:auto;color:var(--ink-3);white-space:nowrap">' +
esc(qual(m[2])) + (m[3] ? "" : " · saiu") + '</span></div>';
}
})();
</script>
</body>
</html>
File diff suppressed because one or more lines are too long