Files
GTI_GERENCIADOR_FISCAL/fiscal/scripts/profile_erp_operations.py
T
gti d21a9d1140 Add 'fiscal/' from commit '102ba84500dbd9655a0471288c3e278652593ca9'
git-subtree-dir: fiscal
git-subtree-mainline: d95165fc8f
git-subtree-split: 102ba84500
2026-09-29 14:43:23 -03:00

41 lines
4.0 KiB
Python

"""Read-only operational profile of emitted documents (trusted corpus + document keys). No writes."""
import json, os, sys
from collections import Counter
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "agent" / "src"))
from gti_fiscal_agent.firebird_reader import _connect
for l in (ROOT / ".env").read_text(encoding="utf-8").splitlines():
if "=" in l and not l.startswith("#"):
k, _, v = l.partition("="); os.environ.setdefault(k.strip(), v.strip())
s = lambda v: None if v is None else str(v).strip()
trusted = json.loads((ROOT / "docs" / "runs" / "trusted_historical_items.json").read_text(encoding="utf-8"))
cur = _connect(os.environ).cursor()
cur.execute("select CFOP, NATUREZA, TIPO from C000030"); nat = {}
for cfop, n, t in cur.fetchall(): nat.setdefault(s(cfop), []).append((s(n), t))
cur.execute("select CHAVE from NFCE where CHAVE is not null and trim(CHAVE) <> ''"); keys = [s(r[0]) for r in cur.fetchall()]
model = Counter(k[20:22] for k in keys if len(k) == 44); uf = Counter(k[:2] for k in keys if len(k) == 44)
cur.execute("select CFOP, count(*) from NFCE_ITENS group by CFOP"); all_cfop = {s(a): b for a, b in cur.fetchall()}
cur.execute("select CFOP, CST, CSOSN, count(*) from C000062 group by CFOP, CST, CSOSN"); nf_rows = [(s(a), s(b), s(c), n) for a, b, c, n in cur.fetchall()]
cf = Counter(t["cfop"] for t in trusted); cs = Counter(t["csosn"] for t in trusted); x = Counter((t["cfop"], t["csosn"], t["cst"]) for t in trusted)
cest_by_cfop = Counter((t["cfop"], bool((t["cest"] or "").strip())) for t in trusted)
def tipo(c):
ts = {t for _, t in nat.get(c, [])}; return {"in_C000030": c in nat, "tipo_values": sorted(str(t) for t in ts), "meaning": {"1": "entrada", "2": "saída"}.get(str(next(iter(ts))) if len(ts) == 1 else "", "ambiguous/absent")}
doc = {"artifact": "ERP_OPERATION_PROFILES_V1", "firebird_writes": 0, "trusted_items": len(trusted),
"nfce_document_keys": {"analyzed": len(keys), "model_positions_20_22": dict(model), "uf_code_positions_0_2": dict(uf),
"reading": "chave de acesso: cUF (29=BA) + modelo (65=NFC-e, official: consumidor final, operação interna) — proven for the keyed subset"},
"trusted_cfop": dict(cf), "trusted_csosn": dict(cs), "trusted_cfop_csosn_cst": {"|".join(map(str, k)): v for k, v in x.most_common()},
"trusted_cest_present_by_cfop": {f"{k[0]}|cest_present={k[1]}": v for k, v in cest_by_cfop.items()},
"cfop_natureza_C000030": {c: tipo(c) for c in sorted(x for x in (set(cf) | set(all_cfop) | {r[0] for r in nf_rows}) if x)},
"all_nfce_items_cfop": all_cfop, "C000062_cfop_cst_csosn": [{"cfop": a, "cst": b, "csosn": c, "n": n} for a, b, c, n in nf_rows],
"context_stability": {
"direction": {"value": "saída", "stable": True, "evidence": "100% of NFC-e item CFOPs start with 5/6/7 (saída); C000025.CFOP is a saída default", "available_to_agent": True},
"company_uf": {"value": "BA", "stable": True, "evidence": "C000004.UF + chave cUF=29", "available_to_agent": True},
"destination_uf_nfce": {"value": "BA", "stable": True, "evidence": "NFC-e (mod 65) is intra-state consumer sale", "available_to_agent": "derivable (document model), not per product"},
"consumer_final": {"value": True, "stable": True, "evidence": "NFC-e model 65", "available_to_agent": "derivable (document model)"},
"customer_taxpayer_status": {"stable": False, "evidence": "not present on NFC-e items; NF-e items (C000062) have no customer join in this analysis", "available_to_agent": False},
"st_retention_by_supplier": {"stable": False, "evidence": "no structured field", "available_to_agent": False}},
"note": "Frequency is descriptive only; no rule is derived from it."}
(ROOT / "docs" / "ERP_OPERATION_PROFILES_V1.json").write_text(json.dumps(doc, ensure_ascii=False, indent=1), encoding="utf-8")
print(json.dumps({"model": doc["nfce_document_keys"], "cfop": cf, "csosn": cs, "x": x.most_common(6)}, ensure_ascii=True))