tiss 0.4.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- tiss/__init__.py +81 -0
- tiss/__main__.py +467 -0
- tiss/_audit.py +324 -0
- tiss/_audit_rules.py +85 -0
- tiss/_audit_schema.py +29 -0
- tiss/_autorizacao.py +319 -0
- tiss/_autorizacao_xml.py +418 -0
- tiss/_check.py +254 -0
- tiss/_completeness.py +84 -0
- tiss/_data/examples/lote-exemplo.json +12 -0
- tiss/_data/glosas.json +6612 -0
- tiss/_data/sadt/fields.json +958 -0
- tiss/_data/sadt/template.css +171 -0
- tiss/_data/sadt/template.html +251 -0
- tiss/_data/schemas/4.02.00/provenance.json +16 -0
- tiss/_data/schemas/4.02.00/tissAssinaturaDigital_v1.01.xsd +16 -0
- tiss/_data/schemas/4.02.00/tissComplexTypesV4_02_00.xsd +1512 -0
- tiss/_data/schemas/4.02.00/tissGuiasV4_02_00.xsd +1469 -0
- tiss/_data/schemas/4.02.00/tissSimpleTypesV4_02_00.xsd +4505 -0
- tiss/_data/schemas/4.02.00/tissV4_02_00.xsd +130 -0
- tiss/_data/schemas/4.02.00/tissWebServicesV4_02_00.xsd +361 -0
- tiss/_data/schemas/4.02.00/xmldsig-core-schema.xsd +309 -0
- tiss/_data/schemas/4.03.00/provenance.json +17 -0
- tiss/_data/schemas/4.03.00/tissAssinaturaDigital_v1.01.xsd +16 -0
- tiss/_data/schemas/4.03.00/tissComplexTypesV4_03_00.xsd +1524 -0
- tiss/_data/schemas/4.03.00/tissGuiasV4_03_00.xsd +1472 -0
- tiss/_data/schemas/4.03.00/tissSimpleTypesV4_03_00.xsd +4832 -0
- tiss/_data/schemas/4.03.00/tissV4_03_00.xsd +130 -0
- tiss/_data/schemas/4.03.00/tissWebServicesV4_03_00.xsd +361 -0
- tiss/_data/schemas/4.03.00/xmldsig-core-schema.xsd +309 -0
- tiss/_glosa.py +36 -0
- tiss/_line_total.py +77 -0
- tiss/_lote.py +209 -0
- tiss/_lote_codec.py +336 -0
- tiss/_lote_xml.py +192 -0
- tiss/_mapa.py +339 -0
- tiss/_mapa_html.py +125 -0
- tiss/_mapa_schema.py +70 -0
- tiss/_patch.py +122 -0
- tiss/_report.py +195 -0
- tiss/_retorno.py +307 -0
- tiss/_rules.py +251 -0
- tiss/_rules_schema.py +99 -0
- tiss/_sadt.py +335 -0
- tiss/_sadt_builders.py +49 -0
- tiss/_sadt_bundle.py +70 -0
- tiss/_sadt_types.py +23 -0
- tiss/_sadt_values.py +103 -0
- tiss/_schema.py +85 -0
- tiss/_text.py +31 -0
- tiss/_validate.py +364 -0
- tiss/_validate_xsd.py +211 -0
- tiss/_xml.py +10 -0
- tiss/codes.py +94 -0
- tiss/dominio/__init__.py +146 -0
- tiss/dominio/_data/domain.json +6488 -0
- tiss/examples/__init__.py +26 -0
- tiss/examples/autorizacao-resposta.xml +2 -0
- tiss/examples/autorizacao-solicitacao.xml +2 -0
- tiss/examples/demonstrativo.xml +20 -0
- tiss/examples/lote-com-erros.xml +63 -0
- tiss/examples/lote-valido.xml +64 -0
- tiss/operadoras/__init__.py +110 -0
- tiss/operadoras/_data/healthplans.json +13863 -0
- tiss/operadoras/_data/indicadores.json +895 -0
- tiss/py.typed +0 -0
- tiss/rede/__init__.py +352 -0
- tiss/rede/__main__.py +5 -0
- tiss/rede/_data/manifesto.json +15 -0
- tiss/rules/000000.json +43 -0
- tiss/sandbox.py +462 -0
- tiss/server/__init__.py +1 -0
- tiss/server/__main__.py +22 -0
- tiss/server/_context.py +22 -0
- tiss/server/_docs.py +170 -0
- tiss/server/_http.py +277 -0
- tiss/server/_keys.py +152 -0
- tiss/server/_mcp.py +314 -0
- tiss/server/_mcp_data.py +82 -0
- tiss/server/_ops.py +598 -0
- tiss/server/_ops_autorizacao.py +97 -0
- tiss/server/_ops_consulta.py +142 -0
- tiss/server/_ops_lote.py +176 -0
- tiss/server/_ops_schemas.py +134 -0
- tiss/server/_prompts.py +64 -0
- tiss/server/_published_rules.py +70 -0
- tiss/server/_quota.py +109 -0
- tiss/server/_rejection_map.py +109 -0
- tiss/server/_rejection_map_http.py +68 -0
- tiss/server/_service.py +56 -0
- tiss/server/_stdio.py +29 -0
- tiss/server/_telemetry.py +164 -0
- tiss/server/_usage.py +84 -0
- tiss/server/_waitlist.py +163 -0
- tiss/tuss/__init__.py +72 -0
- tiss/tuss/_data/tuss.json +544189 -0
- tiss/tuss/_index.py +357 -0
- tiss-0.4.0.dist-info/METADATA +436 -0
- tiss-0.4.0.dist-info/RECORD +102 -0
- tiss-0.4.0.dist-info/WHEEL +4 -0
- tiss-0.4.0.dist-info/entry_points.txt +2 -0
- tiss-0.4.0.dist-info/licenses/LICENSE +201 -0
tiss/__init__.py
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
"""Validação TISS e geração local de documentos."""
|
|
2
|
+
|
|
3
|
+
from copy import deepcopy
|
|
4
|
+
from typing import Any
|
|
5
|
+
|
|
6
|
+
from . import dominio, examples, operadoras
|
|
7
|
+
from ._audit import AuditContext, audit
|
|
8
|
+
from ._autorizacao import check_autorizacao
|
|
9
|
+
from ._autorizacao_xml import AutorizacaoError, build_autorizacao, parse_autorizacao
|
|
10
|
+
from ._check import check
|
|
11
|
+
from ._completeness import missing_mandatory
|
|
12
|
+
from ._glosa import glosa
|
|
13
|
+
from ._lote import Lote, LoteError
|
|
14
|
+
from ._lote_codec import build_lote, hash_epilogo, parse_lote
|
|
15
|
+
from ._mapa import rejection_map
|
|
16
|
+
from ._patch import PatchError, apply_fixes
|
|
17
|
+
from ._report import Finding, Report, json_schema
|
|
18
|
+
from ._retorno import (
|
|
19
|
+
Decisao,
|
|
20
|
+
Decision,
|
|
21
|
+
Proposta,
|
|
22
|
+
Reconciliacao,
|
|
23
|
+
RetornoError,
|
|
24
|
+
parse_demonstrativo,
|
|
25
|
+
plan_reconciliation,
|
|
26
|
+
)
|
|
27
|
+
from ._rules import validate_package
|
|
28
|
+
from ._sadt import BundleError, MissingExtraError, load_bundle, render_sadt
|
|
29
|
+
from ._validate import validate
|
|
30
|
+
|
|
31
|
+
__version__ = "0.4.0"
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def sadt_catalog() -> dict[str, Any]:
|
|
35
|
+
"""Retorna uma cópia independente do catálogo SP/SADT."""
|
|
36
|
+
return deepcopy(load_bundle().catalog)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def sadt_missing(values: dict[str, Any]) -> list[str]:
|
|
40
|
+
"""Retorna os campos SP/SADT obrigatórios ainda ausentes."""
|
|
41
|
+
return missing_mandatory(values, sadt_catalog())
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
__all__ = [
|
|
45
|
+
"AuditContext",
|
|
46
|
+
"AutorizacaoError",
|
|
47
|
+
"BundleError",
|
|
48
|
+
"Decisao",
|
|
49
|
+
"Decision",
|
|
50
|
+
"Finding",
|
|
51
|
+
"Lote",
|
|
52
|
+
"LoteError",
|
|
53
|
+
"MissingExtraError",
|
|
54
|
+
"PatchError",
|
|
55
|
+
"Proposta",
|
|
56
|
+
"Reconciliacao",
|
|
57
|
+
"Report",
|
|
58
|
+
"RetornoError",
|
|
59
|
+
"apply_fixes",
|
|
60
|
+
"audit",
|
|
61
|
+
"build_autorizacao",
|
|
62
|
+
"build_lote",
|
|
63
|
+
"check",
|
|
64
|
+
"check_autorizacao",
|
|
65
|
+
"dominio",
|
|
66
|
+
"examples",
|
|
67
|
+
"glosa",
|
|
68
|
+
"hash_epilogo",
|
|
69
|
+
"json_schema",
|
|
70
|
+
"operadoras",
|
|
71
|
+
"parse_autorizacao",
|
|
72
|
+
"parse_demonstrativo",
|
|
73
|
+
"parse_lote",
|
|
74
|
+
"plan_reconciliation",
|
|
75
|
+
"rejection_map",
|
|
76
|
+
"render_sadt",
|
|
77
|
+
"sadt_catalog",
|
|
78
|
+
"sadt_missing",
|
|
79
|
+
"validate",
|
|
80
|
+
"validate_package",
|
|
81
|
+
]
|
tiss/__main__.py
ADDED
|
@@ -0,0 +1,467 @@
|
|
|
1
|
+
"""Interface de linha de comando do tiss."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import difflib
|
|
7
|
+
import json
|
|
8
|
+
import os
|
|
9
|
+
import re
|
|
10
|
+
import sys
|
|
11
|
+
import urllib.error
|
|
12
|
+
import urllib.request
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
from typing import Any, cast
|
|
15
|
+
|
|
16
|
+
from lxml import etree
|
|
17
|
+
|
|
18
|
+
import tiss
|
|
19
|
+
from tiss import tuss
|
|
20
|
+
|
|
21
|
+
from ._audit import AuditContext
|
|
22
|
+
from ._lote import Lote
|
|
23
|
+
from ._mapa import rejection_map
|
|
24
|
+
from ._mapa_html import render_rejection_map_html
|
|
25
|
+
from ._rules import validate_package
|
|
26
|
+
from ._schema import parser as xml_parser
|
|
27
|
+
|
|
28
|
+
_MAP_URL = "https://tiss-api.voa.health/v1/rejection-map/submit"
|
|
29
|
+
_ANS = {"ans": "http://www.ans.gov.br/padroes/tiss/schemas"}
|
|
30
|
+
_USAGE_ERROR = 2
|
|
31
|
+
_ERROR = 1
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _org_secret(url: str, key: str) -> str | None:
|
|
35
|
+
request = urllib.request.Request(
|
|
36
|
+
url.rsplit("/", 1)[0] + "/config",
|
|
37
|
+
headers={"Authorization": f"Bearer {key}"},
|
|
38
|
+
)
|
|
39
|
+
try:
|
|
40
|
+
with urllib.request.urlopen(request, timeout=10) as response:
|
|
41
|
+
value = json.load(response)
|
|
42
|
+
if isinstance(value, dict) and value.get("enabled") is True:
|
|
43
|
+
secret = value.get("secret")
|
|
44
|
+
if isinstance(secret, str) and re.fullmatch(r"[0-9a-f]{64}", secret):
|
|
45
|
+
return secret
|
|
46
|
+
except (OSError, ValueError, TypeError):
|
|
47
|
+
pass
|
|
48
|
+
sys.stderr.write("Coleta indisponível para esta chave.\n")
|
|
49
|
+
return None
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _json_file(path: Path) -> Any:
|
|
53
|
+
return json.loads(path.read_text(encoding="utf-8"))
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _inputs(folder: Path) -> tuple[list[str | bytes | dict[str, Any]], list[Path]]:
|
|
57
|
+
paths = sorted(
|
|
58
|
+
(
|
|
59
|
+
path
|
|
60
|
+
for path in folder.rglob("*")
|
|
61
|
+
if path.is_file() and path.suffix.lower() in {".xml", ".json"}
|
|
62
|
+
),
|
|
63
|
+
key=lambda path: path.as_posix(),
|
|
64
|
+
)
|
|
65
|
+
lotes: list[str | bytes | dict[str, Any]] = []
|
|
66
|
+
for path in paths:
|
|
67
|
+
if path.suffix.lower() == ".xml":
|
|
68
|
+
lotes.append(path.read_bytes())
|
|
69
|
+
else:
|
|
70
|
+
value = _json_file(path)
|
|
71
|
+
if not isinstance(value, dict):
|
|
72
|
+
raise ValueError(f"Arquivo JSON não contém um lote: {path}")
|
|
73
|
+
lotes.append(value)
|
|
74
|
+
return lotes, paths
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _arguments(argv: list[str] | None) -> argparse.Namespace:
|
|
78
|
+
parser = argparse.ArgumentParser(description="Valida, corrige e consulta documentos TISS.")
|
|
79
|
+
parser.add_argument("--version", action="version", version=f"tiss {tiss.__version__}")
|
|
80
|
+
commands = parser.add_subparsers(dest="command", required=True)
|
|
81
|
+
|
|
82
|
+
validate = commands.add_parser("validate", help="valida arquivos ou pastas")
|
|
83
|
+
validate.add_argument("paths", nargs="+", type=Path)
|
|
84
|
+
validate.add_argument("--operadora")
|
|
85
|
+
validate.add_argument("--format", choices=("text", "json", "github"), default="text")
|
|
86
|
+
|
|
87
|
+
fix = commands.add_parser("fix", help="aplica correções determinísticas")
|
|
88
|
+
fix.add_argument("arquivo", type=Path)
|
|
89
|
+
output = fix.add_mutually_exclusive_group()
|
|
90
|
+
output.add_argument("--write", action="store_true")
|
|
91
|
+
output.add_argument("-o", "--output", type=Path)
|
|
92
|
+
fix.add_argument("--operadora")
|
|
93
|
+
|
|
94
|
+
hash_command = commands.add_parser("hash", help="calcula o hash do epílogo")
|
|
95
|
+
hash_command.add_argument("arquivo", type=Path)
|
|
96
|
+
hash_command.add_argument("--check", action="store_true")
|
|
97
|
+
|
|
98
|
+
glosa = commands.add_parser("glosa", help="consulta um código de glosa")
|
|
99
|
+
glosa.add_argument("codigo")
|
|
100
|
+
tuss_parser = commands.add_parser("tuss", help="consulta um código ou termo TUSS")
|
|
101
|
+
tuss_parser.add_argument("consulta")
|
|
102
|
+
operadora = commands.add_parser("operadora", help="consulta o perfil de uma operadora")
|
|
103
|
+
operadora.add_argument("registro")
|
|
104
|
+
|
|
105
|
+
mapa = commands.add_parser("mapa", help="agrega achados por prestador")
|
|
106
|
+
mapa.add_argument("pasta", type=Path)
|
|
107
|
+
mapa.add_argument("--regras", type=Path)
|
|
108
|
+
mapa.add_argument("--contexto", type=Path)
|
|
109
|
+
mapa.add_argument("--html", type=Path)
|
|
110
|
+
mapa.add_argument("--json", type=Path)
|
|
111
|
+
mapa.add_argument("--enviar", action="store_true")
|
|
112
|
+
|
|
113
|
+
commands.add_parser("mcp", help="inicia o servidor MCP local em stdio")
|
|
114
|
+
serve = commands.add_parser("serve", help="inicia a API HTTP local")
|
|
115
|
+
serve.add_argument("--host", default="127.0.0.1")
|
|
116
|
+
serve.add_argument("--port", default=8000, type=int)
|
|
117
|
+
return parser.parse_args(argv)
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def _send_map(url: str, key: str, body: bytes) -> bool:
|
|
121
|
+
request = urllib.request.Request(
|
|
122
|
+
url,
|
|
123
|
+
data=body,
|
|
124
|
+
headers={
|
|
125
|
+
"Content-Type": "application/json",
|
|
126
|
+
"Authorization": f"Bearer {key}",
|
|
127
|
+
},
|
|
128
|
+
method="POST",
|
|
129
|
+
)
|
|
130
|
+
try:
|
|
131
|
+
with urllib.request.urlopen(request, timeout=10):
|
|
132
|
+
pass
|
|
133
|
+
except (urllib.error.HTTPError, urllib.error.URLError, TimeoutError, OSError):
|
|
134
|
+
sys.stderr.write("Falha ao enviar o mapa.\n")
|
|
135
|
+
return False
|
|
136
|
+
return True
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def _mapa(args: argparse.Namespace) -> int:
|
|
140
|
+
url: str | None
|
|
141
|
+
key: str | None
|
|
142
|
+
if args.enviar:
|
|
143
|
+
url = os.environ.get("TISS_MAPA_URL", _MAP_URL)
|
|
144
|
+
key = os.environ.get("TISS_KEY")
|
|
145
|
+
if not url or not key:
|
|
146
|
+
sys.stderr.write("Defina TISS_KEY para enviar o mapa.\n")
|
|
147
|
+
return _USAGE_ERROR
|
|
148
|
+
else:
|
|
149
|
+
url = key = None
|
|
150
|
+
|
|
151
|
+
secret = os.environ.get("TISS_SEGREDO_PSEUDONIMO")
|
|
152
|
+
if args.enviar and not secret:
|
|
153
|
+
secret = _org_secret(url or _MAP_URL, key or "")
|
|
154
|
+
if secret is None:
|
|
155
|
+
return _USAGE_ERROR
|
|
156
|
+
|
|
157
|
+
if not args.pasta.is_dir():
|
|
158
|
+
sys.stderr.write("A pasta informada não existe ou não é um diretório.\n")
|
|
159
|
+
return _USAGE_ERROR
|
|
160
|
+
try:
|
|
161
|
+
rules = _json_file(args.regras) if args.regras else None
|
|
162
|
+
if rules is not None:
|
|
163
|
+
errors = validate_package(rules)
|
|
164
|
+
if errors:
|
|
165
|
+
sys.stderr.write(f"Pacote de regras inválido: {' '.join(errors)}\n")
|
|
166
|
+
return _USAGE_ERROR
|
|
167
|
+
contexto = cast(AuditContext | None, _json_file(args.contexto)) if args.contexto else None
|
|
168
|
+
if contexto is not None and not isinstance(contexto, dict):
|
|
169
|
+
sys.stderr.write("O contexto deve ser um objeto JSON.\n")
|
|
170
|
+
return _USAGE_ERROR
|
|
171
|
+
lotes, paths = _inputs(args.pasta)
|
|
172
|
+
result = rejection_map(
|
|
173
|
+
lotes,
|
|
174
|
+
contexto=contexto,
|
|
175
|
+
operadora=rules,
|
|
176
|
+
segredo_pseudonimo=secret,
|
|
177
|
+
)
|
|
178
|
+
except ValueError as exc:
|
|
179
|
+
message = str(exc)
|
|
180
|
+
if message != ("Informe segredo_pseudonimo para lotes com prestador identificado por CPF."):
|
|
181
|
+
message = "Não foi possível gerar o mapa com os dados informados."
|
|
182
|
+
sys.stderr.write(message + "\n")
|
|
183
|
+
return _USAGE_ERROR
|
|
184
|
+
except (OSError, json.JSONDecodeError, TypeError):
|
|
185
|
+
sys.stderr.write("Não foi possível ler as entradas do mapa.\n")
|
|
186
|
+
return _USAGE_ERROR
|
|
187
|
+
|
|
188
|
+
for index in result["ignorados"]:
|
|
189
|
+
if index < len(paths):
|
|
190
|
+
sys.stderr.write(f"Lote ignorado: {paths[index]}\n")
|
|
191
|
+
serialized = json.dumps(result, ensure_ascii=False, indent=2, sort_keys=True)
|
|
192
|
+
if args.json:
|
|
193
|
+
args.json.parent.mkdir(parents=True, exist_ok=True)
|
|
194
|
+
args.json.write_text(serialized + "\n", encoding="utf-8")
|
|
195
|
+
if args.html:
|
|
196
|
+
args.html.parent.mkdir(parents=True, exist_ok=True)
|
|
197
|
+
args.html.write_text(render_rejection_map_html(result), encoding="utf-8")
|
|
198
|
+
if not args.json and not args.html:
|
|
199
|
+
sys.stdout.write(serialized + "\n")
|
|
200
|
+
if args.enviar and not _send_map(url or "", key or "", serialized.encode("utf-8")):
|
|
201
|
+
return _ERROR
|
|
202
|
+
return 0
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def _report(path: Path, operadora: str | None) -> tuple[tiss.Report, bytes | None]:
|
|
206
|
+
if not path.exists():
|
|
207
|
+
raise FileNotFoundError(path)
|
|
208
|
+
if not path.is_file():
|
|
209
|
+
raise IsADirectoryError(path)
|
|
210
|
+
content = path.read_bytes()
|
|
211
|
+
if path.suffix.lower() == ".xml":
|
|
212
|
+
return tiss.validate(content, operadora=operadora), content
|
|
213
|
+
if path.suffix.lower() == ".json":
|
|
214
|
+
value = json.loads(content.decode("utf-8"))
|
|
215
|
+
if not isinstance(value, dict):
|
|
216
|
+
raise ValueError(f"Arquivo JSON não contém um lote: {path}")
|
|
217
|
+
return tiss.check(value, operadora=operadora), None
|
|
218
|
+
raise ValueError(f"Formato de arquivo não suportado: {path}")
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def _expand_paths(paths: list[Path]) -> list[Path]:
|
|
222
|
+
expanded: list[Path] = []
|
|
223
|
+
for path in paths:
|
|
224
|
+
if not path.exists():
|
|
225
|
+
raise FileNotFoundError(path)
|
|
226
|
+
if path.is_dir():
|
|
227
|
+
expanded.extend(
|
|
228
|
+
candidate
|
|
229
|
+
for candidate in path.rglob("*")
|
|
230
|
+
if candidate.is_file() and candidate.suffix.lower() in {".xml", ".json"}
|
|
231
|
+
)
|
|
232
|
+
elif path.is_file():
|
|
233
|
+
expanded.append(path)
|
|
234
|
+
else:
|
|
235
|
+
raise ValueError(f"Caminho não é um arquivo ou pasta: {path}")
|
|
236
|
+
return sorted(set(expanded), key=lambda item: item.as_posix())
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
def _line(root: etree._Element | None, xpath: str | None) -> int | None:
|
|
240
|
+
if root is None or not xpath:
|
|
241
|
+
return None
|
|
242
|
+
try:
|
|
243
|
+
matches = root.xpath(xpath, namespaces=_ANS)
|
|
244
|
+
return matches[0].sourceline if matches and isinstance(matches[0], etree._Element) else None
|
|
245
|
+
except (etree.LxmlError, TypeError, ValueError):
|
|
246
|
+
return None
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
def _escape_data(value: str) -> str:
|
|
250
|
+
return value.replace("%", "%25").replace("\r", "%0D").replace("\n", "%0A")
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
def _escape_property(value: str) -> str:
|
|
254
|
+
return _escape_data(value).replace(":", "%3A").replace(",", "%2C")
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
def _format_validation(
|
|
258
|
+
reports: dict[str, tuple[tiss.Report, bytes | None]], output_format: str
|
|
259
|
+
) -> int:
|
|
260
|
+
if output_format == "json":
|
|
261
|
+
serialized: Any
|
|
262
|
+
if len(reports) == 1:
|
|
263
|
+
serialized = next(iter(reports.values()))[0].to_dict()
|
|
264
|
+
else:
|
|
265
|
+
serialized = {path: report.to_dict() for path, (report, _) in reports.items()}
|
|
266
|
+
sys.stdout.write(
|
|
267
|
+
json.dumps(serialized, ensure_ascii=False, sort_keys=True, indent=2) + "\n"
|
|
268
|
+
)
|
|
269
|
+
else:
|
|
270
|
+
errors = warnings = 0
|
|
271
|
+
for path, (report, content) in reports.items():
|
|
272
|
+
root: etree._Element | None = None
|
|
273
|
+
if content is not None and report.findings:
|
|
274
|
+
try:
|
|
275
|
+
root = etree.fromstring(content, xml_parser())
|
|
276
|
+
except (etree.LxmlError, ValueError):
|
|
277
|
+
root = None
|
|
278
|
+
for finding in report.findings:
|
|
279
|
+
line = _line(root, finding.xpath)
|
|
280
|
+
if finding.severity == "error":
|
|
281
|
+
errors += 1
|
|
282
|
+
else:
|
|
283
|
+
warnings += 1
|
|
284
|
+
if output_format == "github":
|
|
285
|
+
command = "warning" if finding.severity == "warning" else "error"
|
|
286
|
+
properties = f"file={_escape_property(path)}"
|
|
287
|
+
if line is not None:
|
|
288
|
+
properties += f",line={line}"
|
|
289
|
+
properties += f",title={_escape_property(finding.code)}"
|
|
290
|
+
sys.stdout.write(f"::{command} {properties}::{_escape_data(finding.message)}\n")
|
|
291
|
+
continue
|
|
292
|
+
location = f"{path}:{line}" if line is not None else path
|
|
293
|
+
suffix = finding.pointer or finding.xpath
|
|
294
|
+
details = f" ({suffix})" if suffix else ""
|
|
295
|
+
sys.stdout.write(
|
|
296
|
+
f"{location}: {finding.severity} {finding.code}: {finding.message}{details}\n"
|
|
297
|
+
)
|
|
298
|
+
if finding.needs:
|
|
299
|
+
sys.stdout.write(f" needs: {', '.join(finding.needs)}\n")
|
|
300
|
+
if output_format == "text":
|
|
301
|
+
sys.stdout.write(
|
|
302
|
+
f"{errors} erro(s), {warnings} aviso(s) em {len(reports)} arquivo(s)\n"
|
|
303
|
+
)
|
|
304
|
+
return _ERROR if any(not report.valid for report, _ in reports.values()) else 0
|
|
305
|
+
|
|
306
|
+
|
|
307
|
+
def _validate(args: argparse.Namespace) -> int:
|
|
308
|
+
try:
|
|
309
|
+
paths = _expand_paths(args.paths)
|
|
310
|
+
if not paths:
|
|
311
|
+
locations = ", ".join(path.as_posix() for path in args.paths)
|
|
312
|
+
sys.stderr.write(f"Nenhum arquivo .xml ou .json encontrado em: {locations}\n")
|
|
313
|
+
return _USAGE_ERROR
|
|
314
|
+
reports = {path.as_posix(): _report(path, args.operadora) for path in paths}
|
|
315
|
+
except (OSError, ValueError, UnicodeError, json.JSONDecodeError) as exc:
|
|
316
|
+
sys.stderr.write(f"Não foi possível ler a entrada: {exc}\n")
|
|
317
|
+
return _USAGE_ERROR
|
|
318
|
+
return _format_validation(reports, args.format)
|
|
319
|
+
|
|
320
|
+
|
|
321
|
+
def _load_lote(path: Path) -> tuple[dict[str, Any], bytes | None]:
|
|
322
|
+
if not path.exists() or not path.is_file():
|
|
323
|
+
raise FileNotFoundError(path)
|
|
324
|
+
content = path.read_bytes()
|
|
325
|
+
if path.suffix.lower() == ".xml":
|
|
326
|
+
return cast(dict[str, Any], tiss.parse_lote(content)), content
|
|
327
|
+
if path.suffix.lower() == ".json":
|
|
328
|
+
value = json.loads(content.decode("utf-8"))
|
|
329
|
+
if isinstance(value, dict):
|
|
330
|
+
return cast(dict[str, Any], value), None
|
|
331
|
+
raise ValueError("Arquivo JSON não contém um lote.")
|
|
332
|
+
raise ValueError(f"Formato de arquivo não suportado: {path}")
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
def _serialize_lote(lote: dict[str, Any], path: Path) -> bytes:
|
|
336
|
+
if path.suffix.lower() == ".xml":
|
|
337
|
+
return tiss.build_lote(cast(Lote, lote))
|
|
338
|
+
return (json.dumps(lote, indent=2, ensure_ascii=False) + "\n").encode("utf-8")
|
|
339
|
+
|
|
340
|
+
|
|
341
|
+
def _fix(args: argparse.Namespace) -> int:
|
|
342
|
+
try:
|
|
343
|
+
lote, original = _load_lote(args.arquivo)
|
|
344
|
+
for _ in range(3):
|
|
345
|
+
report = tiss.check(lote, operadora=args.operadora)
|
|
346
|
+
if not any(finding.fix for finding in report.findings):
|
|
347
|
+
break
|
|
348
|
+
lote = tiss.apply_fixes(lote, report)
|
|
349
|
+
report = tiss.check(lote, operadora=args.operadora)
|
|
350
|
+
output = _serialize_lote(lote, args.arquivo)
|
|
351
|
+
except (OSError, ValueError, UnicodeError, json.JSONDecodeError) as exc:
|
|
352
|
+
sys.stderr.write(f"Não foi possível corrigir a entrada: {exc}\n")
|
|
353
|
+
return _USAGE_ERROR
|
|
354
|
+
if args.write or args.output:
|
|
355
|
+
destination = args.arquivo if args.write else args.output
|
|
356
|
+
try:
|
|
357
|
+
destination.write_bytes(output)
|
|
358
|
+
except OSError as exc:
|
|
359
|
+
sys.stderr.write(f"Não foi possível gravar a saída: {exc}\n")
|
|
360
|
+
return _USAGE_ERROR
|
|
361
|
+
else:
|
|
362
|
+
encoding = "ISO-8859-1" if args.arquivo.suffix.lower() == ".xml" else "utf-8"
|
|
363
|
+
old_text = (original or b"").decode(encoding)
|
|
364
|
+
new_text = output.decode(encoding)
|
|
365
|
+
sys.stdout.writelines(
|
|
366
|
+
difflib.unified_diff(
|
|
367
|
+
old_text.splitlines(keepends=True),
|
|
368
|
+
new_text.splitlines(keepends=True),
|
|
369
|
+
fromfile=args.arquivo.as_posix(),
|
|
370
|
+
tofile=args.arquivo.as_posix() + " (corrigido)",
|
|
371
|
+
)
|
|
372
|
+
)
|
|
373
|
+
for finding in report.findings:
|
|
374
|
+
if finding.needs:
|
|
375
|
+
sys.stderr.write(f"needs: {', '.join(finding.needs)}\n")
|
|
376
|
+
if finding.severity == "error":
|
|
377
|
+
sys.stderr.write(f"erro {finding.code}: {finding.message}\n")
|
|
378
|
+
return 0 if report.valid else _ERROR
|
|
379
|
+
|
|
380
|
+
|
|
381
|
+
def _hash(args: argparse.Namespace) -> int:
|
|
382
|
+
try:
|
|
383
|
+
content = args.arquivo.read_bytes()
|
|
384
|
+
calculated = tiss.hash_epilogo(content)
|
|
385
|
+
except (OSError, ValueError, UnicodeError) as exc:
|
|
386
|
+
sys.stderr.write(f"Não foi possível calcular o hash: {exc}\n")
|
|
387
|
+
return _USAGE_ERROR
|
|
388
|
+
if not args.check:
|
|
389
|
+
sys.stdout.write(calculated + "\n")
|
|
390
|
+
return 0
|
|
391
|
+
try:
|
|
392
|
+
root = etree.fromstring(content, xml_parser())
|
|
393
|
+
elements = root.xpath(".//ans:epilogo/ans:hash", namespaces=_ANS)
|
|
394
|
+
actual = (elements[0].text or "") if elements else "(ausente)"
|
|
395
|
+
except (etree.LxmlError, ValueError):
|
|
396
|
+
sys.stderr.write("XML inválido.\n")
|
|
397
|
+
return _USAGE_ERROR
|
|
398
|
+
if actual == calculated:
|
|
399
|
+
sys.stdout.write(calculated + "\n")
|
|
400
|
+
return 0
|
|
401
|
+
sys.stderr.write(f"Hash divergente: calculado {calculated}; encontrado {actual}.\n")
|
|
402
|
+
return _ERROR
|
|
403
|
+
|
|
404
|
+
|
|
405
|
+
def _lookup(args: argparse.Namespace) -> int:
|
|
406
|
+
if args.command == "glosa":
|
|
407
|
+
result = tiss.glosa(args.codigo)
|
|
408
|
+
if result is None:
|
|
409
|
+
sys.stderr.write(f"Glosa não encontrada: {args.codigo}\n")
|
|
410
|
+
return _ERROR
|
|
411
|
+
elif args.command == "tuss":
|
|
412
|
+
results = (
|
|
413
|
+
tuss.lookup(args.consulta, include_expired=True)
|
|
414
|
+
if args.consulta.isdigit()
|
|
415
|
+
else tuss.search(args.consulta, include_expired=False)[:20]
|
|
416
|
+
)
|
|
417
|
+
if not results:
|
|
418
|
+
sys.stderr.write(f"Resultado não encontrado: {args.consulta}\n")
|
|
419
|
+
return _ERROR
|
|
420
|
+
result = {"resultados": results}
|
|
421
|
+
else:
|
|
422
|
+
result = tiss.operadoras.perfil(args.registro)
|
|
423
|
+
if result is None:
|
|
424
|
+
sys.stderr.write(f"Operadora não encontrada: {args.registro}\n")
|
|
425
|
+
return _ERROR
|
|
426
|
+
sys.stdout.write(json.dumps(result, ensure_ascii=False, sort_keys=True, indent=2) + "\n")
|
|
427
|
+
return 0
|
|
428
|
+
|
|
429
|
+
|
|
430
|
+
def _optional_server(args: argparse.Namespace) -> int:
|
|
431
|
+
try:
|
|
432
|
+
if args.command == "mcp":
|
|
433
|
+
from tiss.server._stdio import main as serve_stdio
|
|
434
|
+
|
|
435
|
+
serve_stdio()
|
|
436
|
+
else:
|
|
437
|
+
from tiss.server.__main__ import main as serve_http
|
|
438
|
+
|
|
439
|
+
serve_http(["--host", args.host, "--port", str(args.port)])
|
|
440
|
+
except ImportError:
|
|
441
|
+
extra = "mcp" if args.command == "mcp" else "server"
|
|
442
|
+
sys.stderr.write(f'Instale o extra: pip install "tiss[{extra}]"\n')
|
|
443
|
+
return _USAGE_ERROR
|
|
444
|
+
return 0
|
|
445
|
+
|
|
446
|
+
|
|
447
|
+
def main(argv: list[str] | None = None) -> int:
|
|
448
|
+
"""Execute a CLI e retorne seu código de saída."""
|
|
449
|
+
try:
|
|
450
|
+
args = _arguments(argv)
|
|
451
|
+
except SystemExit as exc:
|
|
452
|
+
return exc.code if isinstance(exc.code, int) else 0
|
|
453
|
+
if args.command == "validate":
|
|
454
|
+
return _validate(args)
|
|
455
|
+
if args.command == "fix":
|
|
456
|
+
return _fix(args)
|
|
457
|
+
if args.command == "hash":
|
|
458
|
+
return _hash(args)
|
|
459
|
+
if args.command in {"glosa", "tuss", "operadora"}:
|
|
460
|
+
return _lookup(args)
|
|
461
|
+
if args.command == "mapa":
|
|
462
|
+
return _mapa(args)
|
|
463
|
+
return _optional_server(args)
|
|
464
|
+
|
|
465
|
+
|
|
466
|
+
if __name__ == "__main__":
|
|
467
|
+
raise SystemExit(main())
|