Files
GTI_GERENCIADOR_FISCAL/central/app/reference_registry.py
T
gtiandClaude Sonnet 5 21e8282224 feat: Reference Data Registry (Fase 1) + P1 NCM validated + feasibility studies (Fase 5)
Missão 5:

Fase 1 (Reference Data Registry): migration 0034 adds licence_terms, valid_from/
valid_to, file_size_bytes, raw_file_path, parse_errors, submitted_by/approved_by/
approved_at to the existing `datasets` table (additive only - the 9 pre-existing
dataset kinds keep their current auto-activate behavior in
central/app/datasets/service.py, completely untouched, so this changes nothing
about the currently-running engine). New central/app/reference_registry.py is a
separate, NEW ingestion workflow: register_draft() always lands as DRAFT (never
auto-activates), diff_against_vigente() summarizes a draft against the current
VIGENTE of the same kind for admin review, approve_draft()/reject_draft() are
the only way to promote a DRAFT (refuses non-DRAFT rows and refuses a draft
with recorded parse_errors). New admin screen "Tabelas oficiais"
(/admin/reference-datasets, ADMIN only, CSRF, every decision audited as
REFERENCE_DATASET_APPROVE/REJECT) lists the registry with a diff view and
approve/reject buttons. New CLI (scripts/ingest_reference_dataset.py) downloads
an official source (currently: NCM/Siscomex, no login/captcha), validates
(minimum row count, a known-sample spot check), and registers a DRAFT - --dry-run
never writes anything.

P1 (NCM) validated for real: downloaded the live official Siscomex NCM JSON
(2026-09-28, sha256 8a3bf89a..., 15,156 entries) with an identifiable User-Agent,
one request. Its hash is IDENTICAL to the NCM dataset already ACTIVE in the Hub -
confirms the currently loaded table is already current against the official
source today. Raw file kept out of git (.gitignore:
sources/raw/reference_registry/); manifest (URL, date, hash, size) recorded in
docs/REFERENCE_DATASET_MANIFEST_V1.md, including P2-P6 sources still pending URL
confirmation.

Fase 5 (feasibility studies, no code): docs/VIABILIDADE_CCG_DFE_V1.md - CCG/SEFAZ
GTIN lookup and Distribuição DF-e both require the client's own ICP-Brasil
certificate; recommendation is NOT to implement now (would require either the
Hub holding a client certificate - breaks the project's core security model - or
the Agent making new outbound internet calls, against this mission's fixed
rules). Reading the already-authorized purchase-NFe XML from disk via the Agent
(path already stored in XML_MES) is recommended as the next concrete step
instead: no certificate, no new internet call, opt-in per installation, result
always tagged DECLARADO (never auto-promoted - consensus across purchase
invoices is not fiscal truth). Open Food Facts stays identity-only, unchanged.

21 new tests, all passing. Full suite: 1147 passed, 1 skipped.

No write to any Firebird database anywhere. No Agent code touched.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-28 15:24:55 -03:00

93 lines
5.2 KiB
Python

"""Reference Data Registry (Missão 5, Fase 1): the NEW admin-approved ingestion workflow, separate
from central/app/datasets/service.py's existing auto-activate methods (untouched, still used by the
9 pre-existing dataset kinds). A dataset registered here lands as DRAFT and only becomes VIGENTE
(superseding the previous VIGENTE of the same kind) after an explicit ADMIN approval of the diff -
"Nenhuma versão de dataset vira 'vigente' sem aprovação ADMIN do diff" (mission rule).
"""
from __future__ import annotations
from datetime import datetime, timezone
from sqlalchemy import select, update
from .models import Dataset
STATUSES = ("DRAFT", "APPROVED", "VIGENTE", "OBSOLETO", "REJECTED")
class RegistryError(Exception):
pass
def register_draft(session, *, kind: str, provider: str, source_url: str, sha256: str, version_label: str,
act: str = "", valid_from: str | None = None, valid_to: str | None = None, record_count: int = 0,
parse_errors: dict | None = None, licence_terms: str | None = None, raw_file_path: str | None = None,
file_size_bytes: int | None = None, submitted_by: str | None = None) -> Dataset:
"""Registers a new dataset submission as DRAFT. If this exact (provider, sha256) already exists
under ANY status, returns it unchanged (idempotent re-submission of an unchanged official file -
e.g. re-downloading the same official NCM table produces byte-identical content) instead of
creating a duplicate row (the (provider, sha256) constraint would refuse it anyway)."""
existing = session.scalar(select(Dataset).where(Dataset.provider == provider, Dataset.sha256 == sha256))
if existing:
return existing
dataset = Dataset(kind=kind, provider=provider, sha256=sha256, version_label=version_label, act=act, source_url=source_url,
downloaded_at=datetime.now(timezone.utc), status="DRAFT", record_count=record_count, licence_terms=licence_terms,
valid_from=valid_from, valid_to=valid_to, file_size_bytes=file_size_bytes, raw_file_path=raw_file_path,
parse_errors=parse_errors or {}, submitted_by=submitted_by)
session.add(dataset)
session.commit()
return dataset
def diff_against_vigente(session, dataset: Dataset) -> dict:
"""A summary an ADMIN reviews before approving: what the current VIGENTE of the same kind looks
like vs this DRAFT - never the row-by-row content (that lives in the kind-specific entry tables),
just the registry-level facts that matter for an approval decision."""
current = session.scalar(select(Dataset).where(Dataset.kind == dataset.kind, Dataset.status == "VIGENTE"))
return {
"kind": dataset.kind,
"draft": {"id": dataset.id, "version_label": dataset.version_label, "sha256": dataset.sha256, "record_count": dataset.record_count,
"valid_from": dataset.valid_from, "valid_to": dataset.valid_to, "parse_errors": dataset.parse_errors},
"current_vigente": None if current is None else {"id": current.id, "version_label": current.version_label, "sha256": current.sha256,
"record_count": current.record_count, "valid_from": current.valid_from, "valid_to": current.valid_to},
"record_count_delta": None if current is None else dataset.record_count - current.record_count,
"is_first_version": current is None,
"sha256_unchanged": current is not None and current.sha256 == dataset.sha256,
}
def approve_draft(session, dataset_id: int, *, admin_name: str) -> Dataset:
"""DRAFT -> VIGENTE, superseding the previous VIGENTE of the same kind (OBSOLETO, never deleted).
Refuses a dataset that isn't DRAFT, and refuses a dataset with recorded parse errors (must be
re-submitted clean - an ADMIN cannot approve past a known parsing problem)."""
dataset = session.get(Dataset, dataset_id)
if dataset is None:
raise RegistryError("dataset not found")
if dataset.status != "DRAFT":
raise RegistryError(f"only a DRAFT dataset can be approved (current status: {dataset.status})")
if dataset.parse_errors:
raise RegistryError("dataset has recorded parse errors - re-submit a clean version")
session.execute(update(Dataset).where(Dataset.kind == dataset.kind, Dataset.status == "VIGENTE").values(status="OBSOLETO"))
dataset.status = "VIGENTE"
dataset.approved_by = admin_name
dataset.approved_at = datetime.now(timezone.utc)
session.commit()
return dataset
def reject_draft(session, dataset_id: int, *, admin_name: str) -> Dataset:
dataset = session.get(Dataset, dataset_id)
if dataset is None:
raise RegistryError("dataset not found")
if dataset.status != "DRAFT":
raise RegistryError(f"only a DRAFT dataset can be rejected (current status: {dataset.status})")
dataset.status = "REJECTED"
dataset.approved_by = admin_name
dataset.approved_at = datetime.now(timezone.utc)
session.commit()
return dataset
def list_registry(session) -> list[Dataset]:
return list(session.scalars(select(Dataset).where(Dataset.status.in_(STATUSES)).order_by(Dataset.kind, Dataset.downloaded_at.desc())))