tiss 0.4.0a1__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.
Files changed (100) hide show
  1. tiss/__init__.py +81 -0
  2. tiss/__main__.py +167 -0
  3. tiss/_audit.py +324 -0
  4. tiss/_audit_rules.py +85 -0
  5. tiss/_audit_schema.py +29 -0
  6. tiss/_autorizacao.py +319 -0
  7. tiss/_autorizacao_xml.py +418 -0
  8. tiss/_check.py +254 -0
  9. tiss/_completeness.py +84 -0
  10. tiss/_data/examples/lote-exemplo.json +12 -0
  11. tiss/_data/glosas.json +6612 -0
  12. tiss/_data/sadt/fields.json +958 -0
  13. tiss/_data/sadt/template.css +171 -0
  14. tiss/_data/sadt/template.html +251 -0
  15. tiss/_data/schemas/4.02.00/provenance.json +16 -0
  16. tiss/_data/schemas/4.02.00/tissAssinaturaDigital_v1.01.xsd +16 -0
  17. tiss/_data/schemas/4.02.00/tissComplexTypesV4_02_00.xsd +1512 -0
  18. tiss/_data/schemas/4.02.00/tissGuiasV4_02_00.xsd +1469 -0
  19. tiss/_data/schemas/4.02.00/tissSimpleTypesV4_02_00.xsd +4505 -0
  20. tiss/_data/schemas/4.02.00/tissV4_02_00.xsd +130 -0
  21. tiss/_data/schemas/4.02.00/tissWebServicesV4_02_00.xsd +361 -0
  22. tiss/_data/schemas/4.02.00/xmldsig-core-schema.xsd +309 -0
  23. tiss/_data/schemas/4.03.00/provenance.json +17 -0
  24. tiss/_data/schemas/4.03.00/tissAssinaturaDigital_v1.01.xsd +16 -0
  25. tiss/_data/schemas/4.03.00/tissComplexTypesV4_03_00.xsd +1524 -0
  26. tiss/_data/schemas/4.03.00/tissGuiasV4_03_00.xsd +1472 -0
  27. tiss/_data/schemas/4.03.00/tissSimpleTypesV4_03_00.xsd +4832 -0
  28. tiss/_data/schemas/4.03.00/tissV4_03_00.xsd +130 -0
  29. tiss/_data/schemas/4.03.00/tissWebServicesV4_03_00.xsd +361 -0
  30. tiss/_data/schemas/4.03.00/xmldsig-core-schema.xsd +309 -0
  31. tiss/_glosa.py +36 -0
  32. tiss/_line_total.py +77 -0
  33. tiss/_lote.py +209 -0
  34. tiss/_lote_codec.py +336 -0
  35. tiss/_lote_xml.py +192 -0
  36. tiss/_mapa.py +339 -0
  37. tiss/_mapa_html.py +125 -0
  38. tiss/_mapa_schema.py +70 -0
  39. tiss/_patch.py +122 -0
  40. tiss/_report.py +195 -0
  41. tiss/_retorno.py +307 -0
  42. tiss/_rules.py +251 -0
  43. tiss/_rules_schema.py +99 -0
  44. tiss/_sadt.py +335 -0
  45. tiss/_sadt_builders.py +49 -0
  46. tiss/_sadt_bundle.py +70 -0
  47. tiss/_sadt_types.py +23 -0
  48. tiss/_sadt_values.py +103 -0
  49. tiss/_schema.py +85 -0
  50. tiss/_text.py +31 -0
  51. tiss/_validate.py +364 -0
  52. tiss/_validate_xsd.py +211 -0
  53. tiss/_xml.py +10 -0
  54. tiss/codes.py +94 -0
  55. tiss/dominio/__init__.py +146 -0
  56. tiss/dominio/_data/domain.json +6488 -0
  57. tiss/examples/__init__.py +26 -0
  58. tiss/examples/autorizacao-resposta.xml +2 -0
  59. tiss/examples/autorizacao-solicitacao.xml +2 -0
  60. tiss/examples/demonstrativo.xml +20 -0
  61. tiss/examples/lote-com-erros.xml +63 -0
  62. tiss/examples/lote-valido.xml +64 -0
  63. tiss/operadoras/__init__.py +110 -0
  64. tiss/operadoras/_data/healthplans.json +13863 -0
  65. tiss/operadoras/_data/indicadores.json +895 -0
  66. tiss/py.typed +0 -0
  67. tiss/rede/__init__.py +352 -0
  68. tiss/rede/__main__.py +5 -0
  69. tiss/rede/_data/manifesto.json +15 -0
  70. tiss/rules/000000.json +43 -0
  71. tiss/sandbox.py +462 -0
  72. tiss/server/__init__.py +7 -0
  73. tiss/server/__main__.py +22 -0
  74. tiss/server/_context.py +21 -0
  75. tiss/server/_docs.py +170 -0
  76. tiss/server/_http.py +277 -0
  77. tiss/server/_keys.py +152 -0
  78. tiss/server/_mcp.py +307 -0
  79. tiss/server/_mcp_data.py +82 -0
  80. tiss/server/_ops.py +598 -0
  81. tiss/server/_ops_autorizacao.py +97 -0
  82. tiss/server/_ops_consulta.py +142 -0
  83. tiss/server/_ops_lote.py +176 -0
  84. tiss/server/_ops_schemas.py +134 -0
  85. tiss/server/_prompts.py +64 -0
  86. tiss/server/_published_rules.py +70 -0
  87. tiss/server/_quota.py +109 -0
  88. tiss/server/_rejection_map.py +109 -0
  89. tiss/server/_rejection_map_http.py +68 -0
  90. tiss/server/_service.py +56 -0
  91. tiss/server/_telemetry.py +164 -0
  92. tiss/server/_usage.py +84 -0
  93. tiss/server/_waitlist.py +163 -0
  94. tiss/tuss/__init__.py +72 -0
  95. tiss/tuss/_data/tuss.json +544189 -0
  96. tiss/tuss/_index.py +357 -0
  97. tiss-0.4.0a1.dist-info/METADATA +345 -0
  98. tiss-0.4.0a1.dist-info/RECORD +100 -0
  99. tiss-0.4.0a1.dist-info/WHEEL +4 -0
  100. tiss-0.4.0a1.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.0a1"
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,167 @@
1
+ """CLI para operações locais do tiss."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import os
8
+ import re
9
+ import sys
10
+ import urllib.error
11
+ import urllib.request
12
+ from pathlib import Path
13
+ from typing import Any, cast
14
+
15
+ from ._audit import AuditContext
16
+ from ._mapa import rejection_map
17
+ from ._mapa_html import render_rejection_map_html
18
+ from ._rules import validate_package
19
+
20
+ _MAP_URL = "https://tiss-api.voa.health/v1/rejection-map/submit"
21
+
22
+
23
+ def _org_secret(url: str, key: str) -> str | None:
24
+ request = urllib.request.Request(
25
+ url.rsplit("/", 1)[0] + "/config",
26
+ headers={"Authorization": f"Bearer {key}"},
27
+ )
28
+ try:
29
+ with urllib.request.urlopen(request, timeout=10) as response:
30
+ value = json.load(response)
31
+ if isinstance(value, dict) and value.get("enabled") is True:
32
+ secret = value.get("secret")
33
+ if isinstance(secret, str) and re.fullmatch(r"[0-9a-f]{64}", secret):
34
+ return secret
35
+ except (OSError, ValueError, TypeError):
36
+ pass
37
+ sys.stderr.write("Coleta indisponível para esta chave.\n")
38
+ return None
39
+
40
+
41
+ def _json_file(path: Path) -> Any:
42
+ return json.loads(path.read_text(encoding="utf-8"))
43
+
44
+
45
+ def _inputs(folder: Path) -> tuple[list[str | bytes | dict[str, Any]], list[Path]]:
46
+ paths = sorted(
47
+ (
48
+ path
49
+ for path in folder.rglob("*")
50
+ if path.is_file() and path.suffix.lower() in {".xml", ".json"}
51
+ ),
52
+ key=lambda path: path.as_posix(),
53
+ )
54
+ lotes: list[str | bytes | dict[str, Any]] = []
55
+ for path in paths:
56
+ if path.suffix.lower() == ".xml":
57
+ lotes.append(path.read_bytes())
58
+ else:
59
+ value = _json_file(path)
60
+ if not isinstance(value, dict):
61
+ raise ValueError(f"Arquivo JSON não contém um lote: {path}")
62
+ lotes.append(value)
63
+ return lotes, paths
64
+
65
+
66
+ def _arguments(argv: list[str] | None) -> argparse.Namespace:
67
+ parser = argparse.ArgumentParser(description="Gera um mapa agregado de rejeição.")
68
+ commands = parser.add_subparsers(dest="command", required=True)
69
+ mapa = commands.add_parser("mapa", help="agrega achados por prestador")
70
+ mapa.add_argument("pasta", type=Path)
71
+ mapa.add_argument("--regras", type=Path)
72
+ mapa.add_argument("--contexto", type=Path)
73
+ mapa.add_argument("--html", type=Path)
74
+ mapa.add_argument("--json", type=Path)
75
+ mapa.add_argument("--enviar", action="store_true")
76
+ return parser.parse_args(argv)
77
+
78
+
79
+ def _send_map(url: str, key: str, body: bytes) -> bool:
80
+ request = urllib.request.Request(
81
+ url,
82
+ data=body,
83
+ headers={
84
+ "Content-Type": "application/json",
85
+ "Authorization": f"Bearer {key}",
86
+ },
87
+ method="POST",
88
+ )
89
+ try:
90
+ with urllib.request.urlopen(request, timeout=10):
91
+ pass
92
+ except (urllib.error.HTTPError, urllib.error.URLError, TimeoutError, OSError):
93
+ sys.stderr.write("Falha ao enviar o mapa.\n")
94
+ return False
95
+ return True
96
+
97
+
98
+ def main(argv: list[str] | None = None) -> int:
99
+ """Executa a CLI e retorna seu código de saída."""
100
+ args = _arguments(argv)
101
+ url: str | None
102
+ if args.enviar:
103
+ url = os.environ.get("TISS_MAPA_URL", _MAP_URL)
104
+ key = os.environ.get("TISS_KEY")
105
+ if not url or not key:
106
+ sys.stderr.write("Defina TISS_KEY para enviar o mapa.\n")
107
+ return 2
108
+ else:
109
+ url = key = None
110
+
111
+ secret = os.environ.get("TISS_SEGREDO_PSEUDONIMO")
112
+ if args.enviar and not secret:
113
+ secret = _org_secret(url or _MAP_URL, key or "")
114
+ if secret is None:
115
+ return 2
116
+
117
+ if not args.pasta.is_dir():
118
+ sys.stderr.write("A pasta informada não existe ou não é um diretório.\n")
119
+ return 2
120
+ try:
121
+ rules = _json_file(args.regras) if args.regras else None
122
+ if rules is not None:
123
+ errors = validate_package(rules)
124
+ if errors:
125
+ sys.stderr.write(f"Pacote de regras inválido: {' '.join(errors)}\n")
126
+ return 2
127
+ contexto = cast(AuditContext | None, _json_file(args.contexto)) if args.contexto else None
128
+ if contexto is not None and not isinstance(contexto, dict):
129
+ sys.stderr.write("O contexto deve ser um objeto JSON.\n")
130
+ return 2
131
+ lotes, paths = _inputs(args.pasta)
132
+ result = rejection_map(
133
+ lotes,
134
+ contexto=contexto,
135
+ operadora=rules,
136
+ segredo_pseudonimo=secret,
137
+ )
138
+ except ValueError as exc:
139
+ message = str(exc)
140
+ if message != ("Informe segredo_pseudonimo para lotes com prestador identificado por CPF."):
141
+ message = "Não foi possível gerar o mapa com os dados informados."
142
+ sys.stderr.write(message + "\n")
143
+ return 2
144
+ except (OSError, json.JSONDecodeError, TypeError) as exc:
145
+ del exc
146
+ sys.stderr.write("Não foi possível ler as entradas do mapa.\n")
147
+ return 2
148
+
149
+ for index in result["ignorados"]:
150
+ if index < len(paths):
151
+ sys.stderr.write(f"Lote ignorado: {paths[index]}\n")
152
+ serialized = json.dumps(result, ensure_ascii=False, indent=2, sort_keys=True)
153
+ if args.json:
154
+ args.json.parent.mkdir(parents=True, exist_ok=True)
155
+ args.json.write_text(serialized + "\n", encoding="utf-8")
156
+ if args.html:
157
+ args.html.parent.mkdir(parents=True, exist_ok=True)
158
+ args.html.write_text(render_rejection_map_html(result), encoding="utf-8")
159
+ if not args.json and not args.html:
160
+ sys.stdout.write(serialized + "\n")
161
+ if args.enviar and not _send_map(url or "", key or "", serialized.encode("utf-8")):
162
+ return 1
163
+ return 0
164
+
165
+
166
+ if __name__ == "__main__":
167
+ raise SystemExit(main())
tiss/_audit.py ADDED
@@ -0,0 +1,324 @@
1
+ """Auditorias determinísticas de lotes TISS com contexto versionado."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import datetime
6
+ from typing import Any, TypedDict
7
+
8
+ from ._audit_rules import _day, _matches, _money
9
+ from ._audit_schema import audit_context_schema
10
+ from ._lote import _procedure_records
11
+ from ._report import Finding, Report
12
+ from ._rules import rule_findings
13
+ from .codes import CODE_CATALOG
14
+ from .tuss import lookup
15
+
16
+
17
+ class AuditContext(TypedDict, total=False):
18
+ tabela_operadora: dict[str, Any]
19
+ carteirinhas: dict[str, Any]
20
+ autorizacoes: dict[str, Any]
21
+
22
+
23
+ def _lookup_context(
24
+ values: Any, *, guide_index: int, guide: dict[str, Any], field: str
25
+ ) -> dict[str, Any] | None:
26
+ if not isinstance(values, dict):
27
+ return None
28
+ number = str(
29
+ guide.get("cabecalho_guia", {}).get("numero_guia_prestador")
30
+ or guide.get("cabecalho_consulta", {}).get("numero_guia_prestador")
31
+ or guide_index
32
+ )
33
+ result = values.get(number, values.get(str(guide_index)))
34
+ if isinstance(result, dict):
35
+ return result
36
+ return None
37
+
38
+
39
+ def _finding(
40
+ code: str,
41
+ pointer: str | None,
42
+ message: str,
43
+ *,
44
+ severity: str | None = None,
45
+ needs: list[str] | None = None,
46
+ glosa: str | None = None,
47
+ ) -> Finding:
48
+ spec = CODE_CATALOG[code]
49
+ severity = severity or spec["severity"]
50
+ glosa = glosa or spec["glosa"]
51
+ if needs is None and spec["needs"] == "pointer":
52
+ needs = [pointer or "/contexto"]
53
+ return Finding(
54
+ code=code,
55
+ severity=severity, # type: ignore[arg-type]
56
+ guia=None,
57
+ xpath=None,
58
+ pointer=pointer,
59
+ message=message,
60
+ fix=None,
61
+ needs=needs,
62
+ glosa=glosa,
63
+ )
64
+
65
+
66
+ def audit(
67
+ lote: dict[str, Any],
68
+ *,
69
+ contexto: AuditContext | None = None,
70
+ at: datetime.date | str | None = None,
71
+ operadora: Any = None,
72
+ ) -> Report:
73
+ """Verifica regras locais e regras do contexto informado."""
74
+ context = contexto or {}
75
+ table = context.get("tabela_operadora", {})
76
+ findings: list[Finding] = []
77
+ guides = lote.get("guias", [])
78
+ if _matches("lote.vazio", guides):
79
+ findings.append(_finding("lote.vazio", "/guias", "O lote não contém guias."))
80
+ max_guides = table.get("max_guias")
81
+ if isinstance(max_guides, int) and _matches("lote.acima_do_teto", len(guides), max_guides):
82
+ findings.append(
83
+ _finding(
84
+ "lote.acima_do_teto",
85
+ "/guias",
86
+ f"O lote contém {len(guides)} guias; o limite é {max_guides}.",
87
+ )
88
+ )
89
+ procedures = table.get("procedimentos")
90
+ if isinstance(procedures, list) and _matches("audit.tabela_sem_procedimentos", procedures):
91
+ findings.append(
92
+ _finding(
93
+ "audit.tabela_sem_procedimentos", "/guias", "Tabela da operadora sem procedimentos."
94
+ )
95
+ )
96
+ registry = table.get("registro_ans")
97
+ if _matches(
98
+ "audit.operadora_divergente",
99
+ (registry, lote.get("operadora", {}).get("registro_ans")),
100
+ ):
101
+ findings.append(
102
+ _finding(
103
+ "audit.operadora_divergente",
104
+ "/operadora/registro_ans",
105
+ "Registro ANS diverge do contexto.",
106
+ )
107
+ )
108
+ for index, guide in enumerate(guides):
109
+ pointer = f"/guias/{index}"
110
+ service_date = _day(guide.get("dados_atendimento", {}).get("data_atendimento"))
111
+ if service_date is None:
112
+ first_item: dict[str, Any] = next(iter(guide.get("procedimentos_executados", [])), {})
113
+ if isinstance(first_item, dict):
114
+ service_date = _day(first_item.get("data_execucao"))
115
+ service_date = service_date or _day(
116
+ guide.get("cabecalho_guia", {}).get("data_atendimento")
117
+ or guide.get("cabecalho_consulta", {}).get("data_atendimento")
118
+ )
119
+ reference = service_date or _day(at)
120
+ if table:
121
+ inicio = _day(table.get("vigencia_inicio"))
122
+ fim = _day(table.get("vigencia_fim"))
123
+ if inicio or fim:
124
+ if _matches("audit.data_ausente", reference):
125
+ findings.append(
126
+ _finding(
127
+ "audit.data_ausente",
128
+ f"{pointer}/dados_atendimento/data_atendimento",
129
+ "Data de atendimento necessária para verificar vigência da tabela.",
130
+ severity="warning",
131
+ needs=[f"{pointer}/dados_atendimento/data_atendimento"],
132
+ )
133
+ )
134
+ elif _matches("audit.tabela_fora_de_vigencia", (reference, inicio, fim)):
135
+ findings.append(
136
+ _finding(
137
+ "audit.tabela_fora_de_vigencia",
138
+ f"{pointer}/dados_atendimento/data_atendimento",
139
+ "Data do atendimento fora da vigência da tabela.",
140
+ )
141
+ )
142
+ guide_registry = guide.get("cabecalho_guia", {}).get("registro_ans") or guide.get(
143
+ "cabecalho_consulta", {}
144
+ ).get("registro_ans")
145
+ lot_registry = lote.get("operadora", {}).get("registro_ans")
146
+ if _matches("audit.operadora_divergente", (guide_registry, lot_registry)):
147
+ findings.append(
148
+ _finding(
149
+ "audit.operadora_divergente",
150
+ f"{pointer}/cabecalho_guia/registro_ans",
151
+ "Registro ANS da guia diverge do cabeçalho do lote.",
152
+ )
153
+ )
154
+ for relative, procedure, amount_value, item_date in _procedure_records(guide):
155
+ code = str(procedure.get("codigo_procedimento", ""))
156
+ table_code = str(procedure.get("codigo_tabela", ""))
157
+ procedure_pointer = pointer + relative
158
+ reference = _day(item_date) or service_date or _day(at)
159
+ if _matches("audit.procedimento_ausente", code):
160
+ findings.append(
161
+ _finding(
162
+ "audit.procedimento_ausente",
163
+ procedure_pointer + "/codigo_procedimento",
164
+ "Código do procedimento ausente.",
165
+ )
166
+ )
167
+ continue
168
+ records = (
169
+ lookup(code, tabela=table_code, include_expired=True)
170
+ if table_code in {"18", "19", "20", "22"}
171
+ else []
172
+ )
173
+ if (
174
+ not records
175
+ and table_code in {"18", "19", "20", "22"}
176
+ and _matches("tuss.inexistente", records)
177
+ ):
178
+ findings.append(
179
+ _finding(
180
+ "tuss.inexistente",
181
+ procedure_pointer + "/codigo_procedimento",
182
+ f"Código TUSS {code} inexistente na tabela {table_code}.",
183
+ )
184
+ )
185
+ elif records:
186
+ if _matches("audit.data_ausente", reference) and any(
187
+ row.get("vigencia_inicio") or row.get("vigencia_fim") for row in records
188
+ ):
189
+ findings.append(
190
+ _finding(
191
+ "audit.data_ausente",
192
+ pointer + "/dados_atendimento/data_atendimento",
193
+ "Data necessária para verificar vigência do código TUSS.",
194
+ severity="warning",
195
+ needs=[pointer + "/dados_atendimento/data_atendimento"],
196
+ )
197
+ )
198
+ elif _matches("tuss.fora_de_vigencia", (records, reference)):
199
+ findings.append(
200
+ _finding(
201
+ "tuss.fora_de_vigencia",
202
+ procedure_pointer + "/codigo_procedimento",
203
+ f"Código TUSS {code} fora de vigência na data do atendimento.",
204
+ )
205
+ )
206
+ if isinstance(procedures, list) and _matches(
207
+ "audit.procedimento_fora_da_tabela",
208
+ code,
209
+ {str(item) for item in procedures},
210
+ ):
211
+ findings.append(
212
+ _finding(
213
+ "audit.procedimento_fora_da_tabela",
214
+ procedure_pointer + "/codigo_procedimento",
215
+ f"Procedimento {code} não consta na tabela da operadora.",
216
+ )
217
+ )
218
+ required = table.get("exige_autorizacao", [])
219
+ if _matches("autorizacao_requerida", code, required):
220
+ authorization = _lookup_context(
221
+ context.get("autorizacoes"),
222
+ guide_index=index,
223
+ guide=guide,
224
+ field="autorizacoes",
225
+ )
226
+ if _matches("audit.autorizacao_ausente", authorization):
227
+ findings.append(
228
+ _finding(
229
+ "audit.autorizacao_ausente",
230
+ pointer + "/dados_autorizacao",
231
+ "Autorização necessária não informada.",
232
+ )
233
+ )
234
+ else:
235
+ assert authorization is not None
236
+ expiry = _day(authorization.get("validade"))
237
+ if _matches("audit.autorizacao_vencida", (expiry, reference)):
238
+ findings.append(
239
+ _finding(
240
+ "audit.autorizacao_vencida",
241
+ pointer + "/dados_autorizacao",
242
+ "Autorização vencida na data do atendimento.",
243
+ )
244
+ )
245
+ elif expiry and _matches("audit.data_ausente", reference):
246
+ findings.append(
247
+ _finding(
248
+ "audit.data_ausente",
249
+ pointer + "/dados_atendimento/data_atendimento",
250
+ "Data necessária para verificar validade da autorização.",
251
+ severity="warning",
252
+ needs=[pointer + "/dados_atendimento/data_atendimento"],
253
+ )
254
+ )
255
+ amount = _money(amount_value)
256
+ if _matches("audit.valor_nao_positivo", amount):
257
+ findings.append(
258
+ _finding(
259
+ "audit.valor_nao_positivo",
260
+ procedure_pointer
261
+ + (
262
+ "/valor_total"
263
+ if guide.get("tipo") == "sp_sadt"
264
+ else "/valor_procedimento"
265
+ ),
266
+ "O valor do procedimento deve ser positivo.",
267
+ )
268
+ )
269
+ card_context = _lookup_context(
270
+ context.get("carteirinhas"), guide_index=index, guide=guide, field="carteirinhas"
271
+ )
272
+ if context.get("carteirinhas") is not None:
273
+ if _matches("audit.carteirinha_ausente", card_context):
274
+ findings.append(
275
+ _finding(
276
+ "audit.carteirinha_ausente",
277
+ pointer + "/dados_beneficiario/numero_carteira",
278
+ "Carteirinha não localizada no contexto da operadora.",
279
+ )
280
+ )
281
+ else:
282
+ assert card_context is not None
283
+ if _matches("audit.carteirinha_inativa", card_context.get("ativa")):
284
+ findings.append(
285
+ _finding(
286
+ "audit.carteirinha_inativa",
287
+ pointer + "/dados_beneficiario/numero_carteira",
288
+ "Carteirinha inativa.",
289
+ )
290
+ )
291
+ expiry = _day(card_context.get("validade") or card_context.get("fim"))
292
+ if expiry and _matches("audit.data_ausente", reference):
293
+ findings.append(
294
+ _finding(
295
+ "audit.data_ausente",
296
+ pointer + "/dados_atendimento/data_atendimento",
297
+ "Data necessária para verificar validade da carteirinha.",
298
+ severity="warning",
299
+ needs=[pointer + "/dados_atendimento/data_atendimento"],
300
+ )
301
+ )
302
+ elif _matches("audit.carteirinha_vencida", (expiry, reference)):
303
+ findings.append(
304
+ _finding(
305
+ "audit.carteirinha_vencida",
306
+ pointer + "/dados_beneficiario/numero_carteira",
307
+ "Carteirinha vencida na data do atendimento.",
308
+ )
309
+ )
310
+ if operadora is not None:
311
+ findings.extend(rule_findings(lote, operadora))
312
+ unique: dict[tuple[Any, ...], Finding] = {}
313
+ for finding in findings:
314
+ unique[(finding.code, finding.guia, finding.pointer)] = finding
315
+ result = tuple(
316
+ sorted(
317
+ unique.values(),
318
+ key=lambda item: (item.pointer is None, item.pointer or "", item.code, item.message),
319
+ )
320
+ )
321
+ return Report(not any(item.severity == "error" for item in result), "4.03.00", result)
322
+
323
+
324
+ __all__ = ["AuditContext", "audit", "audit_context_schema"]
tiss/_audit_rules.py ADDED
@@ -0,0 +1,85 @@
1
+ """Primitivas reutilizáveis para regras de auditoria."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import datetime
6
+ from typing import Any
7
+
8
+ AUDIT_RULES = {
9
+ "lote.vazio": "empty",
10
+ "lote.acima_do_teto": "greater",
11
+ "audit.tabela_sem_procedimentos": "empty",
12
+ "audit.operadora_divergente": "different_if_both",
13
+ "audit.tabela_fora_de_vigencia": "outside_window",
14
+ "audit.procedimento_ausente": "empty",
15
+ "tuss.inexistente": "empty",
16
+ "tuss.fora_de_vigencia": "no_valid_record",
17
+ "audit.procedimento_fora_da_tabela": "not_in",
18
+ "autorizacao_requerida": "in",
19
+ "audit.autorizacao_ausente": "empty",
20
+ "audit.autorizacao_vencida": "expired",
21
+ "audit.valor_nao_positivo": "nonpositive",
22
+ "audit.carteirinha_ausente": "empty",
23
+ "audit.carteirinha_inativa": "inactive",
24
+ "audit.carteirinha_vencida": "expired",
25
+ "audit.data_ausente": "missing",
26
+ }
27
+
28
+
29
+ def _day(value: Any) -> datetime.date | None:
30
+ if isinstance(value, datetime.datetime):
31
+ return value.date()
32
+ if isinstance(value, datetime.date):
33
+ return value
34
+ if isinstance(value, str):
35
+ try:
36
+ return datetime.date.fromisoformat(value[:10])
37
+ except ValueError:
38
+ return None
39
+ return None
40
+
41
+
42
+ def _money(value: Any) -> int | None:
43
+ if isinstance(value, bool):
44
+ return None
45
+ if isinstance(value, int):
46
+ return value
47
+ return None
48
+
49
+
50
+ def _matches(rule: str, value: Any, expected: Any = None) -> bool:
51
+ match AUDIT_RULES[rule]:
52
+ case "empty":
53
+ return not value
54
+ case "greater":
55
+ return bool(value > expected)
56
+ case "different_if_both":
57
+ left, right = value
58
+ return bool(left and right and left != right)
59
+ case "outside_window":
60
+ reference, start, end = value
61
+ return reference is not None and (
62
+ (start is not None and reference < start) or (end is not None and reference >= end)
63
+ )
64
+ case "no_valid_record":
65
+ records, reference = value
66
+ return reference is not None and not any(
67
+ (not row.get("vigencia_inicio") or reference.isoformat() >= row["vigencia_inicio"])
68
+ and (not row.get("vigencia_fim") or reference.isoformat() < row["vigencia_fim"])
69
+ for row in records
70
+ )
71
+ case "not_in":
72
+ return value not in expected
73
+ case "in":
74
+ return value in expected
75
+ case "expired":
76
+ expiry, reference = value
77
+ return expiry is not None and reference is not None and reference >= expiry
78
+ case "nonpositive":
79
+ return value is not None and value <= 0
80
+ case "inactive":
81
+ return value is False
82
+ case "missing":
83
+ return value is None
84
+ case _:
85
+ raise ValueError(f"Regra de auditoria desconhecida: {rule}")
tiss/_audit_schema.py ADDED
@@ -0,0 +1,29 @@
1
+ """Esquema JSON do contexto de auditoria."""
2
+
3
+ from typing import Any
4
+
5
+
6
+ def audit_context_schema() -> dict[str, Any]:
7
+ """Retorna o esquema JSON do contexto de auditoria."""
8
+ return {
9
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
10
+ "title": "Contexto de auditoria TISS",
11
+ "type": "object",
12
+ "additionalProperties": False,
13
+ "properties": {
14
+ "tabela_operadora": {
15
+ "type": "object",
16
+ "additionalProperties": False,
17
+ "properties": {
18
+ "registro_ans": {"type": "string"},
19
+ "procedimentos": {"type": "array", "items": {"type": "string"}},
20
+ "exige_autorizacao": {"type": "array", "items": {"type": "string"}},
21
+ "vigencia_inicio": {"type": "string", "format": "date"},
22
+ "vigencia_fim": {"type": ["string", "null"], "format": "date"},
23
+ "max_guias": {"type": "integer", "minimum": 1},
24
+ },
25
+ },
26
+ "carteirinhas": {"type": "object"},
27
+ "autorizacoes": {"type": "object"},
28
+ },
29
+ }