argos-cli 0.3.1__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.
- argos/__init__.py +5 -0
- argos/__main__.py +4 -0
- argos/adapters/__init__.py +9 -0
- argos/adapters/_libreoffice_worker.py +111 -0
- argos/adapters/ai.py +1506 -0
- argos/adapters/ai_remote.py +654 -0
- argos/adapters/attachment_conversion.py +132 -0
- argos/adapters/capabilities.py +31 -0
- argos/adapters/chart_render.py +72 -0
- argos/adapters/docx_pdf.py +2953 -0
- argos/adapters/limesurvey.py +1079 -0
- argos/adapters/model_call.py +274 -0
- argos/adapters/report_publication.py +1530 -0
- argos/adapters/url_fetch.py +146 -0
- argos/adapters/xlsx.py +454 -0
- argos/analytics.py +731 -0
- argos/assets.py +257 -0
- argos/audit_result.py +369 -0
- argos/booleans.py +105 -0
- argos/catalog.py +1205 -0
- argos/cli.py +606 -0
- argos/contracts.py +532 -0
- argos/core.py +325 -0
- argos/default_skills/README.md +23 -0
- argos/default_skills/criar-matriz-planejamento/SKILL.md +200 -0
- argos/default_skills/elaborar-survey-limesurvey/SKILL.md +106 -0
- argos/default_skills/operar-argos/SKILL.md +74 -0
- argos/default_skills/verificar-diretrizes-fiscalizacao/SKILL.md +129 -0
- argos/default_skills/verificar-diretrizes-fiscalizacao/assets/relatorio-avaliacao.md +54 -0
- argos/default_skills/verificar-diretrizes-fiscalizacao/references/contrato-saidas.md +36 -0
- argos/default_skills/verificar-diretrizes-fiscalizacao/references/papeis-das-pastas.md +37 -0
- argos/default_skills/verificar-diretrizes-fiscalizacao/references/roteiro-verificacoes.md +27 -0
- argos/default_skills/verificar-diretrizes-fiscalizacao/scripts/avaliacao.py +253 -0
- argos/engines/__init__.py +3 -0
- argos/engines/adjustments.py +571 -0
- argos/engines/analytics.py +195 -0
- argos/engines/audit.py +2730 -0
- argos/engines/evaluation.py +6088 -0
- argos/engines/index.py +1683 -0
- argos/engines/matrix.py +5736 -0
- argos/engines/matrix_html.py +698 -0
- argos/engines/model_request.py +201 -0
- argos/engines/report_document.py +137 -0
- argos/engines/reports.py +1200 -0
- argos/engines/survey.py +4445 -0
- argos/envfile.py +53 -0
- argos/errors.py +29 -0
- argos/evidence_staging.py +293 -0
- argos/executions.py +565 -0
- argos/findings_matrix.py +2549 -0
- argos/fingerprints.py +487 -0
- argos/index_dsl.py +2100 -0
- argos/matrix_markdown.py +475 -0
- argos/matrix_widths.py +280 -0
- argos/pipeline.py +1745 -0
- argos/products.py +220 -0
- argos/progress.py +221 -0
- argos/project.py +608 -0
- argos/report_config.py +158 -0
- argos/resources/ESPECIFICACAO_MARKDOWN_MATRIZ_ACHADOS.md +539 -0
- argos/resources/ESPECIFICACAO_MARKDOWN_MATRIZ_PLANEJAMENTO.md +1000 -0
- argos/resources/ESPECIFICACAO_UNIFICADA_MATRIZES_V1_3.md +1142 -0
- argos/resources/anexo-evidencias-base.docx +0 -0
- argos/resources/argos-index-dsl-v1.schema.json +539 -0
- argos/resources/argos-report-config-v1.schema.json +113 -0
- argos/resources/diretrizes-projeto.md +476 -0
- argos/resources/env.example +37 -0
- argos/resources/exemplos/matriz_achados_boilerplate.md +61 -0
- argos/resources/exemplos/matriz_achados_draft.md +106 -0
- argos/resources/exemplos/matriz_achados_larguras_v1_3.md +114 -0
- argos/resources/exemplos/matriz_achados_v1_3.md +107 -0
- argos/resources/exemplos/matriz_planejamento_boilerplate.md +64 -0
- argos/resources/exemplos/matriz_planejamento_larguras_v1_3.md +115 -0
- argos/resources/exemplos/matriz_planejamento_v1_3.md +108 -0
- argos/resources/template-base-estilos-sigiloso.docx +0 -0
- argos/resources/template-base-estilos.docx +0 -0
- argos/resources/template-matriz-planejamento.docx +0 -0
- argos/resources/template-relatorio-consolidado-comum.docx +0 -0
- argos/resources/template-relatorio-consolidado-institucional.docx +0 -0
- argos/response_profiles.py +856 -0
- argos/scheduler.py +142 -0
- argos/status.py +367 -0
- argos/store.py +1228 -0
- argos/survey_collection.py +832 -0
- argos/telemetry.py +84 -0
- argos/tui.py +1262 -0
- argos/tui.tcss +827 -0
- argos/tui_models.py +466 -0
- argos/tui_path.py +155 -0
- argos/tui_widgets.py +482 -0
- argos/version.py +3 -0
- argos_cli-0.3.1.dist-info/METADATA +570 -0
- argos_cli-0.3.1.dist-info/RECORD +96 -0
- argos_cli-0.3.1.dist-info/WHEEL +5 -0
- argos_cli-0.3.1.dist-info/entry_points.txt +2 -0
- argos_cli-0.3.1.dist-info/top_level.txt +1 -0
argos/index_dsl.py
ADDED
|
@@ -0,0 +1,2100 @@
|
|
|
1
|
+
"""Compiler for the declarative Argos Index DSL v1."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from copy import deepcopy
|
|
6
|
+
from dataclasses import dataclass, field
|
|
7
|
+
from datetime import date, datetime, timezone
|
|
8
|
+
from decimal import Decimal, InvalidOperation
|
|
9
|
+
from functools import lru_cache
|
|
10
|
+
from importlib import resources
|
|
11
|
+
import json
|
|
12
|
+
import math
|
|
13
|
+
from numbers import Real
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
import re
|
|
16
|
+
from types import MappingProxyType
|
|
17
|
+
from typing import Any, Mapping
|
|
18
|
+
import unicodedata
|
|
19
|
+
|
|
20
|
+
import yaml
|
|
21
|
+
from jsonschema import Draft202012Validator
|
|
22
|
+
from yaml.constructor import ConstructorError
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
SCHEMA_RESOURCE = "argos-index-dsl-v1.schema.json"
|
|
26
|
+
INDEX_EVALUATOR_REVISION = "argos-index-evaluator-v1"
|
|
27
|
+
OPERATIONS = frozenset(
|
|
28
|
+
{"mapeamento", "media_ponderada", "media_binaria", "soma_ponderada", "desconto_proporcional"}
|
|
29
|
+
)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class IndexDslError(ValueError):
|
|
33
|
+
"""A configuration or input error with a stable DSL code and location."""
|
|
34
|
+
|
|
35
|
+
def __init__(self, code: str, message: str, *, path: str = "$") -> None:
|
|
36
|
+
self.code = code
|
|
37
|
+
self.path = path
|
|
38
|
+
self.message = message
|
|
39
|
+
super().__init__(f"{code} em {path}: {message}")
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@dataclass(frozen=True)
|
|
43
|
+
class SelectorItem:
|
|
44
|
+
name: str
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
@dataclass(frozen=True)
|
|
48
|
+
class SelectorNot:
|
|
49
|
+
operand: SelectorExpression
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
@dataclass(frozen=True)
|
|
53
|
+
class SelectorAnd:
|
|
54
|
+
left: SelectorExpression
|
|
55
|
+
right: SelectorExpression
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
@dataclass(frozen=True)
|
|
59
|
+
class SelectorOr:
|
|
60
|
+
left: SelectorExpression
|
|
61
|
+
right: SelectorExpression
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
@dataclass(frozen=True)
|
|
65
|
+
class SelectorGroup:
|
|
66
|
+
expression: SelectorExpression
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
SelectorExpression = SelectorItem | SelectorNot | SelectorAnd | SelectorOr | SelectorGroup
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
@dataclass(frozen=True)
|
|
73
|
+
class ParsedSelector:
|
|
74
|
+
source: str
|
|
75
|
+
criteria: tuple[SelectorExpression, ...]
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
@dataclass(frozen=True)
|
|
79
|
+
class ComponentReference:
|
|
80
|
+
raw_text: str
|
|
81
|
+
kind: str
|
|
82
|
+
target_node: str | None = None
|
|
83
|
+
question: str | None = None
|
|
84
|
+
selector: ParsedSelector | None = None
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
@dataclass(frozen=True)
|
|
88
|
+
class WeightedComponent:
|
|
89
|
+
reference: ComponentReference
|
|
90
|
+
weight: float
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
@dataclass(frozen=True)
|
|
94
|
+
class CompiledNode:
|
|
95
|
+
node_id: str
|
|
96
|
+
operation: str
|
|
97
|
+
parameters: Mapping[str, Any]
|
|
98
|
+
components: tuple[WeightedComponent, ...]
|
|
99
|
+
parameter_references: Mapping[str, ComponentReference]
|
|
100
|
+
component_rule: Mapping[str, Any] | None = None
|
|
101
|
+
rule_name: str | None = None
|
|
102
|
+
component_rule_name: str | None = None
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
@dataclass(frozen=True)
|
|
106
|
+
class ResolvedReference:
|
|
107
|
+
"""Input columns bound to one external reference in a compiled node."""
|
|
108
|
+
|
|
109
|
+
path: str
|
|
110
|
+
reference: ComponentReference
|
|
111
|
+
column: str | None = None
|
|
112
|
+
detail_columns: Mapping[str, str] = field(default_factory=lambda: MappingProxyType({}))
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
@dataclass(frozen=True)
|
|
116
|
+
class CompiledIndex:
|
|
117
|
+
"""Immutable, semantically checked index definition."""
|
|
118
|
+
|
|
119
|
+
document: Mapping[str, Any]
|
|
120
|
+
metadata: Mapping[str, Any]
|
|
121
|
+
entry: Mapping[str, Any]
|
|
122
|
+
converters: Mapping[str, Mapping[str, Any]]
|
|
123
|
+
converter_codes: Mapping[str, Mapping[str, str]]
|
|
124
|
+
converter_aliases: Mapping[str, Mapping[str, str]]
|
|
125
|
+
rules: Mapping[str, Mapping[str, Any]]
|
|
126
|
+
nodes: Mapping[str, CompiledNode]
|
|
127
|
+
evaluation_order: tuple[str, ...]
|
|
128
|
+
maturity: tuple[Mapping[str, Any], ...]
|
|
129
|
+
maturity_gaps: tuple[MaturityGap, ...]
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
@dataclass(frozen=True)
|
|
133
|
+
class PreparedRecord:
|
|
134
|
+
organization: str
|
|
135
|
+
row_number: int
|
|
136
|
+
values: Mapping[str, Any]
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
@dataclass(frozen=True)
|
|
140
|
+
class PreparedInput:
|
|
141
|
+
headers: tuple[str, ...]
|
|
142
|
+
records: tuple[PreparedRecord, ...]
|
|
143
|
+
statistics: Mapping[str, int]
|
|
144
|
+
resolved_references: Mapping[str, ResolvedReference] = field(default_factory=lambda: MappingProxyType({}))
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
@dataclass(frozen=True)
|
|
148
|
+
class ConvertedValue:
|
|
149
|
+
"""A converted cell retaining its declared code and physical origin."""
|
|
150
|
+
|
|
151
|
+
canonical_code: str | None
|
|
152
|
+
value: float
|
|
153
|
+
column: str | None
|
|
154
|
+
raw: Any
|
|
155
|
+
empty: bool
|
|
156
|
+
origin: str
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
@dataclass(frozen=True)
|
|
160
|
+
class OperationResult:
|
|
161
|
+
"""Numeric result before/after the configured range and trace fields."""
|
|
162
|
+
|
|
163
|
+
value: float
|
|
164
|
+
before_range: float
|
|
165
|
+
applied_range: tuple[float, float] | None
|
|
166
|
+
diagnostics: Mapping[str, Any] = field(default_factory=lambda: MappingProxyType({}))
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
@dataclass(frozen=True)
|
|
170
|
+
class ComponentTrace:
|
|
171
|
+
reference: ComponentReference
|
|
172
|
+
input_column: str | None
|
|
173
|
+
detail_columns: Mapping[str, str]
|
|
174
|
+
value: float
|
|
175
|
+
canonical_code: str | None
|
|
176
|
+
origin: str | None
|
|
177
|
+
weight: float
|
|
178
|
+
rule_result: OperationResult | None = None
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
@dataclass(frozen=True)
|
|
182
|
+
class NodeTrace:
|
|
183
|
+
node_id: str
|
|
184
|
+
operation: str
|
|
185
|
+
rule_name: str | None
|
|
186
|
+
component_rule_name: str | None
|
|
187
|
+
components: tuple[ComponentTrace, ...]
|
|
188
|
+
exclusive_negative: ComponentTrace | None
|
|
189
|
+
result: OperationResult
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
@dataclass(frozen=True)
|
|
193
|
+
class MaturityGap:
|
|
194
|
+
lower: float
|
|
195
|
+
upper: float
|
|
196
|
+
includes_lower: bool
|
|
197
|
+
includes_upper: bool
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
@dataclass(frozen=True)
|
|
201
|
+
class RowEvaluation:
|
|
202
|
+
"""All calculated node scores for one prepared organization row."""
|
|
203
|
+
|
|
204
|
+
organization: str
|
|
205
|
+
scores: Mapping[str, float]
|
|
206
|
+
operations: Mapping[str, OperationResult]
|
|
207
|
+
traces: Mapping[str, NodeTrace] = field(default_factory=lambda: MappingProxyType({}))
|
|
208
|
+
classification: str | None = None
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
class _UniqueKeyLoader(yaml.SafeLoader):
|
|
212
|
+
"""SafeLoader that rejects duplicate YAML mapping keys before dict creation."""
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def _construct_unique_mapping(loader: _UniqueKeyLoader, node: yaml.MappingNode, deep: bool = False) -> dict[Any, Any]:
|
|
216
|
+
loader.flatten_mapping(node)
|
|
217
|
+
mapping: dict[Any, Any] = {}
|
|
218
|
+
for key_node, value_node in node.value:
|
|
219
|
+
key = loader.construct_object(key_node, deep=deep)
|
|
220
|
+
try:
|
|
221
|
+
duplicate = key in mapping
|
|
222
|
+
except TypeError as exc:
|
|
223
|
+
raise ConstructorError("while constructing a mapping", node.start_mark, "unhashable key", key_node.start_mark) from exc
|
|
224
|
+
if duplicate:
|
|
225
|
+
raise ConstructorError(
|
|
226
|
+
"while constructing a mapping",
|
|
227
|
+
node.start_mark,
|
|
228
|
+
f"found duplicate key {key!r}",
|
|
229
|
+
key_node.start_mark,
|
|
230
|
+
)
|
|
231
|
+
mapping[key] = loader.construct_object(value_node, deep=deep)
|
|
232
|
+
return mapping
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
_UniqueKeyLoader.add_constructor(yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, _construct_unique_mapping)
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
def _load_unique_yaml(source: str) -> Any:
|
|
239
|
+
loader = _UniqueKeyLoader(source)
|
|
240
|
+
try:
|
|
241
|
+
return loader.get_single_data()
|
|
242
|
+
finally:
|
|
243
|
+
loader.dispose()
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
@lru_cache(maxsize=1)
|
|
247
|
+
def _schema() -> dict[str, Any]:
|
|
248
|
+
schema_path = resources.files("argos").joinpath("resources", SCHEMA_RESOURCE)
|
|
249
|
+
try:
|
|
250
|
+
schema = json.loads(schema_path.read_text(encoding="utf-8"))
|
|
251
|
+
Draft202012Validator.check_schema(schema)
|
|
252
|
+
except (OSError, ValueError) as exc:
|
|
253
|
+
raise RuntimeError(f"schema empacotado da DSL indisponível ou inválido: {exc}") from exc
|
|
254
|
+
return schema
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
def _path(parts: tuple[Any, ...] | list[Any]) -> str:
|
|
258
|
+
return "$" + "".join(f"[{part}]" if isinstance(part, int) else f".{part}" for part in parts)
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
def _find_nonfinite(value: Any, path: str = "$", active: set[int] | None = None) -> None:
|
|
262
|
+
if isinstance(value, bool):
|
|
263
|
+
return
|
|
264
|
+
if isinstance(value, Real):
|
|
265
|
+
try:
|
|
266
|
+
finite = math.isfinite(float(value))
|
|
267
|
+
except OverflowError:
|
|
268
|
+
finite = False
|
|
269
|
+
if not finite:
|
|
270
|
+
raise IndexDslError("E_NUMERIC_NONFINITE", "valores numéricos devem ser finitos", path=path)
|
|
271
|
+
if isinstance(value, Mapping) or isinstance(value, (list, tuple)):
|
|
272
|
+
active = active if active is not None else set()
|
|
273
|
+
identity = id(value)
|
|
274
|
+
if identity in active:
|
|
275
|
+
raise IndexDslError("E_YAML_ALIAS_CYCLE", "aliases YAML não podem formar ciclos", path=path)
|
|
276
|
+
active.add(identity)
|
|
277
|
+
try:
|
|
278
|
+
if isinstance(value, Mapping):
|
|
279
|
+
for key, child in value.items():
|
|
280
|
+
_find_nonfinite(child, f"{path}.{key}", active)
|
|
281
|
+
else:
|
|
282
|
+
for index, child in enumerate(value):
|
|
283
|
+
_find_nonfinite(child, f"{path}[{index}]", active)
|
|
284
|
+
finally:
|
|
285
|
+
active.remove(identity)
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
def _freeze(value: Any) -> Any:
|
|
289
|
+
if isinstance(value, Mapping):
|
|
290
|
+
return MappingProxyType({key: _freeze(item) for key, item in value.items()})
|
|
291
|
+
if isinstance(value, list):
|
|
292
|
+
return tuple(_freeze(item) for item in value)
|
|
293
|
+
if isinstance(value, tuple):
|
|
294
|
+
return tuple(_freeze(item) for item in value)
|
|
295
|
+
return value
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+
def _schema_error(error: Any) -> IndexDslError:
|
|
299
|
+
def nested_errors(current: Any) -> list[Any]:
|
|
300
|
+
return [current, *(child for context_error in current.context for child in nested_errors(context_error))]
|
|
301
|
+
|
|
302
|
+
errors = nested_errors(error)
|
|
303
|
+
invalid_weight = next(
|
|
304
|
+
(item for item in errors if item.validator == "minimum" and "componentes" in item.absolute_path),
|
|
305
|
+
None,
|
|
306
|
+
)
|
|
307
|
+
if invalid_weight is not None:
|
|
308
|
+
return IndexDslError("E_INVALID_WEIGHT", invalid_weight.message, path=_path(tuple(invalid_weight.absolute_path)))
|
|
309
|
+
path = _path(tuple(error.absolute_path))
|
|
310
|
+
if error.validator == "additionalProperties":
|
|
311
|
+
code = "E_UNKNOWN_ATTRIBUTE"
|
|
312
|
+
elif error.validator == "enum" and tuple(error.absolute_path)[-1:] == ("operacao",):
|
|
313
|
+
code = "E_UNKNOWN_OPERATION"
|
|
314
|
+
elif error.validator == "const" and tuple(error.absolute_path) == ("formato",):
|
|
315
|
+
code = "E_FORMAT_UNKNOWN"
|
|
316
|
+
else:
|
|
317
|
+
code = "E_SCHEMA_INVALID"
|
|
318
|
+
return IndexDslError(code, error.message, path=path)
|
|
319
|
+
|
|
320
|
+
|
|
321
|
+
def _normal(text: str) -> str:
|
|
322
|
+
return unicodedata.normalize("NFC", text.strip())
|
|
323
|
+
|
|
324
|
+
|
|
325
|
+
@dataclass(frozen=True)
|
|
326
|
+
class _SelectorToken:
|
|
327
|
+
kind: str
|
|
328
|
+
value: str
|
|
329
|
+
position: int
|
|
330
|
+
|
|
331
|
+
|
|
332
|
+
def _selector_error(source: str, position: int, message: str, path: str) -> IndexDslError:
|
|
333
|
+
excerpt_start = max(0, position - 8)
|
|
334
|
+
excerpt_end = min(len(source), position + 12)
|
|
335
|
+
excerpt = source[excerpt_start:excerpt_end]
|
|
336
|
+
return IndexDslError(
|
|
337
|
+
"E_SELECTOR_SYNTAX",
|
|
338
|
+
f"{message} na posição {position} próximo a {excerpt!r}",
|
|
339
|
+
path=path,
|
|
340
|
+
)
|
|
341
|
+
|
|
342
|
+
|
|
343
|
+
def _tokenize_selector(source: str, path: str) -> tuple[_SelectorToken, ...]:
|
|
344
|
+
tokens: list[_SelectorToken] = []
|
|
345
|
+
position = 0
|
|
346
|
+
while position < len(source):
|
|
347
|
+
char = source[position]
|
|
348
|
+
if char.isspace():
|
|
349
|
+
position += 1
|
|
350
|
+
continue
|
|
351
|
+
if char in "~&|(),":
|
|
352
|
+
tokens.append(_SelectorToken(char, char, position))
|
|
353
|
+
position += 1
|
|
354
|
+
continue
|
|
355
|
+
if char.isascii() and char.isalpha():
|
|
356
|
+
start = position
|
|
357
|
+
position += 1
|
|
358
|
+
while position < len(source):
|
|
359
|
+
following = source[position]
|
|
360
|
+
if following.isascii() and following.isalpha() or following.isascii() and following.isdigit() or following == "_":
|
|
361
|
+
position += 1
|
|
362
|
+
else:
|
|
363
|
+
break
|
|
364
|
+
tokens.append(_SelectorToken("item", source[start:position], start))
|
|
365
|
+
continue
|
|
366
|
+
raise _selector_error(source, position, f"token inválido {char!r}", path)
|
|
367
|
+
return tuple(tokens)
|
|
368
|
+
|
|
369
|
+
|
|
370
|
+
class _SelectorParser:
|
|
371
|
+
def __init__(self, source: str, tokens: tuple[_SelectorToken, ...], path: str) -> None:
|
|
372
|
+
self.source = source
|
|
373
|
+
self.tokens = tokens
|
|
374
|
+
self.path = path
|
|
375
|
+
self.position = 0
|
|
376
|
+
|
|
377
|
+
def _current(self) -> _SelectorToken | None:
|
|
378
|
+
return self.tokens[self.position] if self.position < len(self.tokens) else None
|
|
379
|
+
|
|
380
|
+
def _take(self, kind: str) -> _SelectorToken | None:
|
|
381
|
+
current = self._current()
|
|
382
|
+
if current is not None and current.kind == kind:
|
|
383
|
+
self.position += 1
|
|
384
|
+
return current
|
|
385
|
+
return None
|
|
386
|
+
|
|
387
|
+
def _expect(self, kind: str, message: str) -> _SelectorToken:
|
|
388
|
+
current = self._current()
|
|
389
|
+
if current is None or current.kind != kind:
|
|
390
|
+
position = len(self.source) if current is None else current.position
|
|
391
|
+
raise _selector_error(self.source, position, message, self.path)
|
|
392
|
+
self.position += 1
|
|
393
|
+
return current
|
|
394
|
+
|
|
395
|
+
def parse(self) -> ParsedSelector:
|
|
396
|
+
if not self.tokens:
|
|
397
|
+
raise _selector_error(self.source, 0, "a lista de critérios está vazia", self.path)
|
|
398
|
+
criteria: list[SelectorExpression] = []
|
|
399
|
+
while True:
|
|
400
|
+
criteria.append(self._parse_or())
|
|
401
|
+
current = self._current()
|
|
402
|
+
if current is None:
|
|
403
|
+
break
|
|
404
|
+
if self._take(",") is None:
|
|
405
|
+
raise _selector_error(self.source, current.position, "token inesperado", self.path)
|
|
406
|
+
current = self._current()
|
|
407
|
+
if current is None or current.kind in {",", ")"}:
|
|
408
|
+
position = len(self.source) if current is None else current.position
|
|
409
|
+
raise _selector_error(self.source, position, "critério vazio", self.path)
|
|
410
|
+
return ParsedSelector(self.source, tuple(criteria))
|
|
411
|
+
|
|
412
|
+
def _parse_or(self) -> SelectorExpression:
|
|
413
|
+
expression = self._parse_and()
|
|
414
|
+
while self._take("|") is not None:
|
|
415
|
+
expression = SelectorOr(expression, self._parse_and())
|
|
416
|
+
return expression
|
|
417
|
+
|
|
418
|
+
def _parse_and(self) -> SelectorExpression:
|
|
419
|
+
expression = self._parse_unary()
|
|
420
|
+
while self._take("&") is not None:
|
|
421
|
+
expression = SelectorAnd(expression, self._parse_unary())
|
|
422
|
+
return expression
|
|
423
|
+
|
|
424
|
+
def _parse_unary(self) -> SelectorExpression:
|
|
425
|
+
token = self._take("~")
|
|
426
|
+
if token is not None:
|
|
427
|
+
return SelectorNot(self._parse_unary())
|
|
428
|
+
return self._parse_primary()
|
|
429
|
+
|
|
430
|
+
def _parse_primary(self) -> SelectorExpression:
|
|
431
|
+
item = self._take("item")
|
|
432
|
+
if item is not None:
|
|
433
|
+
return SelectorItem(item.value)
|
|
434
|
+
opening = self._take("(")
|
|
435
|
+
if opening is not None:
|
|
436
|
+
current = self._current()
|
|
437
|
+
if current is None or current.kind == ")":
|
|
438
|
+
position = opening.position if current is None else current.position
|
|
439
|
+
raise _selector_error(self.source, position, "grupo vazio", self.path)
|
|
440
|
+
expression = self._parse_or()
|
|
441
|
+
self._expect(")", "faltou fechar o grupo")
|
|
442
|
+
return SelectorGroup(expression)
|
|
443
|
+
current = self._current()
|
|
444
|
+
position = len(self.source) if current is None else current.position
|
|
445
|
+
raise _selector_error(self.source, position, "era esperado um item, '~' ou '('", self.path)
|
|
446
|
+
|
|
447
|
+
|
|
448
|
+
def _parse_selector(source: str, path: str) -> ParsedSelector:
|
|
449
|
+
return _SelectorParser(source, _tokenize_selector(source, path), path).parse()
|
|
450
|
+
|
|
451
|
+
|
|
452
|
+
def _evaluate_selector_expression(expression: SelectorExpression, scores: Mapping[str, float], path: str) -> float:
|
|
453
|
+
if isinstance(expression, SelectorItem):
|
|
454
|
+
if expression.name not in scores:
|
|
455
|
+
raise IndexDslError("E_INPUT_COLUMN_MISSING", f"item selecionado {expression.name!r} não foi resolvido", path=path)
|
|
456
|
+
value = scores[expression.name]
|
|
457
|
+
try:
|
|
458
|
+
finite = math.isfinite(float(value))
|
|
459
|
+
except (OverflowError, TypeError, ValueError):
|
|
460
|
+
finite = False
|
|
461
|
+
if isinstance(value, bool) or not isinstance(value, Real) or not finite or not 0 <= value <= 1:
|
|
462
|
+
raise IndexDslError("E_NUMERIC_NONFINITE", f"pontuação inválida para item {expression.name!r}", path=path)
|
|
463
|
+
return float(value)
|
|
464
|
+
if isinstance(expression, SelectorGroup):
|
|
465
|
+
return _evaluate_selector_expression(expression.expression, scores, path)
|
|
466
|
+
if isinstance(expression, SelectorNot):
|
|
467
|
+
return 1.0 if _evaluate_selector_expression(expression.operand, scores, path) == 0 else 0.0
|
|
468
|
+
if isinstance(expression, SelectorAnd):
|
|
469
|
+
left = _evaluate_selector_expression(expression.left, scores, path)
|
|
470
|
+
right = _evaluate_selector_expression(expression.right, scores, path)
|
|
471
|
+
return 1.0 if left > 0 and right > 0 else 0.0
|
|
472
|
+
if isinstance(expression, SelectorOr):
|
|
473
|
+
left = _evaluate_selector_expression(expression.left, scores, path)
|
|
474
|
+
right = _evaluate_selector_expression(expression.right, scores, path)
|
|
475
|
+
return 1.0 if left > 0 or right > 0 else 0.0
|
|
476
|
+
raise TypeError(f"tipo de AST de seletor desconhecido: {type(expression).__name__}")
|
|
477
|
+
|
|
478
|
+
|
|
479
|
+
def score_selector(selector: ParsedSelector, item_scores: Mapping[str, float]) -> float:
|
|
480
|
+
"""Score a selector, preserving fractions for isolated items and booleans for logic."""
|
|
481
|
+
if not selector.criteria:
|
|
482
|
+
raise IndexDslError("E_SELECTOR_SYNTAX", "a lista de critérios está vazia", path=f"seletor:{selector.source}")
|
|
483
|
+
values: list[float] = []
|
|
484
|
+
for expression in selector.criteria:
|
|
485
|
+
values.append(_evaluate_selector_expression(expression, item_scores, f"seletor:{selector.source}"))
|
|
486
|
+
return math.fsum(values) / len(values)
|
|
487
|
+
|
|
488
|
+
|
|
489
|
+
def _resolve_reference(raw_text: str, node_ids: set[str], *, path: str) -> ComponentReference:
|
|
490
|
+
if raw_text in node_ids:
|
|
491
|
+
return ComponentReference(raw_text=raw_text, kind="node", target_node=raw_text)
|
|
492
|
+
if not isinstance(raw_text, str) or not raw_text.strip():
|
|
493
|
+
raise IndexDslError("E_COMPONENT_INVALID", "referência deve ser uma string não vazia", path=path)
|
|
494
|
+
|
|
495
|
+
if raw_text.endswith("}"):
|
|
496
|
+
opening = raw_text.rfind("{")
|
|
497
|
+
if opening <= 0 or "}" in raw_text[:opening] or "{" in raw_text[:opening]:
|
|
498
|
+
raise IndexDslError("E_SELECTOR_SYNTAX", "seletor final ou questão-base inválida", path=path)
|
|
499
|
+
question = raw_text[:opening]
|
|
500
|
+
selector_source = raw_text[opening + 1 : -1]
|
|
501
|
+
selector = _parse_selector(selector_source, path)
|
|
502
|
+
return ComponentReference(raw_text, "selected_question", question=question, selector=selector)
|
|
503
|
+
if "{" in raw_text or "}" in raw_text:
|
|
504
|
+
raise IndexDslError("E_SELECTOR_SYNTAX", "seletor deve aparecer no final da referência", path=path)
|
|
505
|
+
if re.search(r"\[[^\[\]]+\]$", raw_text):
|
|
506
|
+
return ComponentReference(raw_text, "detail")
|
|
507
|
+
return ComponentReference(raw_text, "input")
|
|
508
|
+
|
|
509
|
+
|
|
510
|
+
def _cell_empty(value: Any) -> bool:
|
|
511
|
+
return value is None or isinstance(value, str) and not value.strip()
|
|
512
|
+
|
|
513
|
+
|
|
514
|
+
def _key_text(value: Any) -> str:
|
|
515
|
+
if _cell_empty(value):
|
|
516
|
+
return ""
|
|
517
|
+
if isinstance(value, str):
|
|
518
|
+
return _normal(value)
|
|
519
|
+
if isinstance(value, Real) and not isinstance(value, bool):
|
|
520
|
+
try:
|
|
521
|
+
if not math.isfinite(float(value)):
|
|
522
|
+
return ""
|
|
523
|
+
except OverflowError:
|
|
524
|
+
return ""
|
|
525
|
+
return _normal(str(value))
|
|
526
|
+
|
|
527
|
+
|
|
528
|
+
def _dedup_order_key(value: Any, *, row_number: int, column: str) -> tuple[str, Any]:
|
|
529
|
+
path = f"entrada.desduplicacao.ordenar_por={column}, linha={row_number}"
|
|
530
|
+
if _cell_empty(value):
|
|
531
|
+
raise IndexDslError("E_DUPLICATE_ORDER_MISSING", "chave de ordenação ausente", path=path)
|
|
532
|
+
if isinstance(value, bool):
|
|
533
|
+
raise IndexDslError("E_DUPLICATE_ORDER_INVALID", "booleano não é chave de ordenação válida", path=path)
|
|
534
|
+
if isinstance(value, datetime):
|
|
535
|
+
normalized = value
|
|
536
|
+
if normalized.tzinfo is not None:
|
|
537
|
+
normalized = normalized.astimezone(timezone.utc).replace(tzinfo=None)
|
|
538
|
+
return "datetime", normalized.isoformat(timespec="microseconds")
|
|
539
|
+
if isinstance(value, date):
|
|
540
|
+
return "datetime", datetime.combine(value, datetime.min.time()).isoformat(timespec="microseconds")
|
|
541
|
+
if isinstance(value, Real):
|
|
542
|
+
try:
|
|
543
|
+
numeric = Decimal(str(value))
|
|
544
|
+
except (InvalidOperation, ValueError) as exc:
|
|
545
|
+
raise IndexDslError("E_DUPLICATE_ORDER_INVALID", "chave numérica inválida", path=path) from exc
|
|
546
|
+
if not numeric.is_finite():
|
|
547
|
+
raise IndexDslError("E_DUPLICATE_ORDER_INVALID", "chave numérica deve ser finita", path=path)
|
|
548
|
+
return "number", numeric
|
|
549
|
+
if isinstance(value, str):
|
|
550
|
+
text = _normal(value)
|
|
551
|
+
try:
|
|
552
|
+
parsed_datetime = datetime.fromisoformat(text.replace("Z", "+00:00"))
|
|
553
|
+
except ValueError:
|
|
554
|
+
try:
|
|
555
|
+
parsed_date = date.fromisoformat(text)
|
|
556
|
+
except ValueError:
|
|
557
|
+
try:
|
|
558
|
+
numeric = Decimal(text)
|
|
559
|
+
except InvalidOperation:
|
|
560
|
+
return "string", text
|
|
561
|
+
if not numeric.is_finite():
|
|
562
|
+
raise IndexDslError("E_DUPLICATE_ORDER_INVALID", "chave numérica deve ser finita", path=path)
|
|
563
|
+
return "number", numeric
|
|
564
|
+
return "datetime", datetime.combine(parsed_date, datetime.min.time()).isoformat(timespec="microseconds")
|
|
565
|
+
if parsed_datetime.tzinfo is not None:
|
|
566
|
+
parsed_datetime = parsed_datetime.astimezone(timezone.utc).replace(tzinfo=None)
|
|
567
|
+
return "datetime", parsed_datetime.isoformat(timespec="microseconds")
|
|
568
|
+
raise IndexDslError("E_DUPLICATE_ORDER_INVALID", "tipo de chave de ordenação não suportado", path=path)
|
|
569
|
+
|
|
570
|
+
|
|
571
|
+
@dataclass(frozen=True)
|
|
572
|
+
class _DetailPolicy:
|
|
573
|
+
locator: str
|
|
574
|
+
contract: str | None
|
|
575
|
+
|
|
576
|
+
|
|
577
|
+
@dataclass(frozen=True)
|
|
578
|
+
class _ReferenceUse:
|
|
579
|
+
path: str
|
|
580
|
+
reference: ComponentReference
|
|
581
|
+
policy: _DetailPolicy | None
|
|
582
|
+
base_question: bool = False
|
|
583
|
+
|
|
584
|
+
|
|
585
|
+
def _node_detail_policy(node: CompiledNode) -> _DetailPolicy | None:
|
|
586
|
+
source = node.component_rule if node.component_rule is not None else node.parameters
|
|
587
|
+
details = source.get("detalhes", {})
|
|
588
|
+
locator = details.get("localizador") or source.get("localizador")
|
|
589
|
+
if locator is None:
|
|
590
|
+
return None
|
|
591
|
+
return _DetailPolicy(locator, details.get("contrato"))
|
|
592
|
+
|
|
593
|
+
|
|
594
|
+
def _selector_items(expression: SelectorExpression) -> tuple[str, ...]:
|
|
595
|
+
if isinstance(expression, SelectorItem):
|
|
596
|
+
return (expression.name,)
|
|
597
|
+
if isinstance(expression, SelectorNot):
|
|
598
|
+
return _selector_items(expression.operand)
|
|
599
|
+
if isinstance(expression, (SelectorAnd, SelectorOr)):
|
|
600
|
+
return (*_selector_items(expression.left), *_selector_items(expression.right))
|
|
601
|
+
if isinstance(expression, SelectorGroup):
|
|
602
|
+
return _selector_items(expression.expression)
|
|
603
|
+
raise TypeError(f"tipo de AST de seletor desconhecido: {type(expression).__name__}")
|
|
604
|
+
|
|
605
|
+
|
|
606
|
+
def _locator_ignored(locator: Mapping[str, Any], header: str) -> bool:
|
|
607
|
+
return any(re.search(expression, header) is not None for expression in locator.get("ignorar_colunas_regex", ()))
|
|
608
|
+
|
|
609
|
+
|
|
610
|
+
def _locator_expression(pattern: str, *, question: str | None = None) -> re.Pattern[str]:
|
|
611
|
+
"""Compile one locator template as a full-header matcher."""
|
|
612
|
+
parts = re.split(r"(\{questao\}|\{item\})", pattern)
|
|
613
|
+
expression: list[str] = []
|
|
614
|
+
for part in parts:
|
|
615
|
+
if part == "{questao}":
|
|
616
|
+
expression.append(re.escape(_normal(question)) if question is not None else "(.+?)")
|
|
617
|
+
elif part == "{item}":
|
|
618
|
+
expression.append("(.+?)")
|
|
619
|
+
else:
|
|
620
|
+
expression.append(re.escape(part))
|
|
621
|
+
return re.compile("".join(expression))
|
|
622
|
+
|
|
623
|
+
|
|
624
|
+
def _locator_item_matches(locator: Mapping[str, Any], item: str) -> bool:
|
|
625
|
+
return re.fullmatch(locator["item_regex"], item) is not None
|
|
626
|
+
|
|
627
|
+
|
|
628
|
+
def _parse_locator_reference(
|
|
629
|
+
locator: Mapping[str, Any],
|
|
630
|
+
text: str,
|
|
631
|
+
known_questions: set[str],
|
|
632
|
+
*,
|
|
633
|
+
path: str,
|
|
634
|
+
) -> tuple[str, str]:
|
|
635
|
+
"""Resolve a direct detail reference against known questions before inferring its prefix."""
|
|
636
|
+
normalized = _normal(text)
|
|
637
|
+
candidates: set[tuple[str, str]] = set()
|
|
638
|
+
for question in known_questions:
|
|
639
|
+
for pattern in locator["padroes"]:
|
|
640
|
+
match = _locator_expression(pattern, question=question).fullmatch(normalized)
|
|
641
|
+
if match is None:
|
|
642
|
+
continue
|
|
643
|
+
item = match.groups()[-1]
|
|
644
|
+
if _locator_item_matches(locator, item):
|
|
645
|
+
candidates.add((question, item))
|
|
646
|
+
if not candidates:
|
|
647
|
+
for pattern in locator["padroes"]:
|
|
648
|
+
match = _locator_expression(pattern).fullmatch(normalized)
|
|
649
|
+
if match is None:
|
|
650
|
+
continue
|
|
651
|
+
question, item = match.groups()
|
|
652
|
+
if _locator_item_matches(locator, item):
|
|
653
|
+
candidates.add((_normal(question), item))
|
|
654
|
+
if len(candidates) != 1:
|
|
655
|
+
raise IndexDslError(
|
|
656
|
+
"E_LOCATOR_REFERENCE",
|
|
657
|
+
f"referência de detalhe {text!r} não identifica uma única questão e item",
|
|
658
|
+
path=path,
|
|
659
|
+
)
|
|
660
|
+
return next(iter(candidates))
|
|
661
|
+
|
|
662
|
+
|
|
663
|
+
def _inventory_details(
|
|
664
|
+
headers: tuple[str, ...],
|
|
665
|
+
locators: Mapping[str, Mapping[str, Any]],
|
|
666
|
+
questions_by_locator: Mapping[str, set[str]],
|
|
667
|
+
) -> dict[tuple[str, str], dict[str, str]]:
|
|
668
|
+
physical: dict[tuple[str, str, str], set[str]] = {}
|
|
669
|
+
for locator_name, questions in questions_by_locator.items():
|
|
670
|
+
locator = locators[locator_name]
|
|
671
|
+
for header in headers:
|
|
672
|
+
if _locator_ignored(locator, header):
|
|
673
|
+
continue
|
|
674
|
+
for question in questions:
|
|
675
|
+
for pattern in locator["padroes"]:
|
|
676
|
+
matcher = _locator_expression(pattern, question=question)
|
|
677
|
+
match = matcher.fullmatch(header)
|
|
678
|
+
if match is None:
|
|
679
|
+
continue
|
|
680
|
+
item = match.groups()[-1]
|
|
681
|
+
if _locator_item_matches(locator, item):
|
|
682
|
+
physical.setdefault((locator_name, question, item), set()).add(header)
|
|
683
|
+
|
|
684
|
+
inventory: dict[tuple[str, str], dict[str, str]] = {}
|
|
685
|
+
for (locator_name, question, item), columns in physical.items():
|
|
686
|
+
if len(columns) > 1:
|
|
687
|
+
ordered = sorted(columns)
|
|
688
|
+
raise IndexDslError(
|
|
689
|
+
"E_DETAIL_ALIAS_COLLISION",
|
|
690
|
+
f"colunas {ordered!r} são aliases simultâneos do item {item!r} da questão {question!r}",
|
|
691
|
+
path=f"cabeçalho.{locator_name}.{question}.{item}",
|
|
692
|
+
)
|
|
693
|
+
inventory.setdefault((locator_name, question), {})[item] = next(iter(columns))
|
|
694
|
+
return inventory
|
|
695
|
+
|
|
696
|
+
|
|
697
|
+
def _resolve_input_references(
|
|
698
|
+
compiled: CompiledIndex,
|
|
699
|
+
headers: tuple[str, ...],
|
|
700
|
+
) -> Mapping[str, ResolvedReference]:
|
|
701
|
+
positions = set(headers)
|
|
702
|
+
node_ids = set(compiled.nodes)
|
|
703
|
+
for node_id in node_ids & positions:
|
|
704
|
+
raise IndexDslError(
|
|
705
|
+
"E_NODE_INPUT_COLLISION",
|
|
706
|
+
f"a coluna física {node_id!r} também é identificador de nó calculado",
|
|
707
|
+
path="cabeçalho",
|
|
708
|
+
)
|
|
709
|
+
|
|
710
|
+
uses: list[_ReferenceUse] = []
|
|
711
|
+
questions_by_locator: dict[str, set[str]] = {}
|
|
712
|
+
policy_contracts: set[tuple[str, str]] = set()
|
|
713
|
+
contracts = compiled.entry.get("contratos_detalhes", {})
|
|
714
|
+
|
|
715
|
+
def register(use: _ReferenceUse) -> None:
|
|
716
|
+
uses.append(use)
|
|
717
|
+
reference = use.reference
|
|
718
|
+
policy = use.policy
|
|
719
|
+
if policy is None:
|
|
720
|
+
return
|
|
721
|
+
questions = questions_by_locator.setdefault(policy.locator, set())
|
|
722
|
+
if policy.contract is not None:
|
|
723
|
+
policy_contracts.add((policy.locator, policy.contract))
|
|
724
|
+
questions.update(contracts[policy.contract]["itens_por_questao"])
|
|
725
|
+
if reference.kind == "selected_question" and reference.question is not None:
|
|
726
|
+
questions.add(_normal(reference.question))
|
|
727
|
+
elif use.base_question:
|
|
728
|
+
questions.add(_normal(reference.raw_text))
|
|
729
|
+
|
|
730
|
+
for node in compiled.nodes.values():
|
|
731
|
+
policy = _node_detail_policy(node)
|
|
732
|
+
component_rule = node.component_rule
|
|
733
|
+
base_question_context = component_rule is not None and component_rule.get("operacao") == "desconto_proporcional"
|
|
734
|
+
if node.operation == "desconto_proporcional":
|
|
735
|
+
base_question_context = True
|
|
736
|
+
for index, component in enumerate(node.components):
|
|
737
|
+
reference = component.reference
|
|
738
|
+
register(
|
|
739
|
+
_ReferenceUse(
|
|
740
|
+
f"$.calculo.{node.node_id}.componentes[{index}]",
|
|
741
|
+
reference,
|
|
742
|
+
policy,
|
|
743
|
+
base_question=base_question_context and reference.kind == "input",
|
|
744
|
+
)
|
|
745
|
+
)
|
|
746
|
+
for name, reference in node.parameter_references.items():
|
|
747
|
+
register(_ReferenceUse(f"$.calculo.{node.node_id}.{name}", reference, None))
|
|
748
|
+
|
|
749
|
+
# A direct physical detail reference can contribute its own logical question
|
|
750
|
+
# when no contract or selector has supplied that question yet.
|
|
751
|
+
for use in uses:
|
|
752
|
+
if use.policy is None or use.reference.kind != "detail":
|
|
753
|
+
continue
|
|
754
|
+
locator = compiled.entry["localizadores"][use.policy.locator]
|
|
755
|
+
known_questions = questions_by_locator.setdefault(use.policy.locator, set())
|
|
756
|
+
question, _ = _parse_locator_reference(
|
|
757
|
+
locator,
|
|
758
|
+
use.reference.raw_text,
|
|
759
|
+
known_questions,
|
|
760
|
+
path=use.path,
|
|
761
|
+
)
|
|
762
|
+
known_questions.add(question)
|
|
763
|
+
|
|
764
|
+
locators = compiled.entry.get("localizadores", {})
|
|
765
|
+
inventory = _inventory_details(headers, locators, questions_by_locator)
|
|
766
|
+
|
|
767
|
+
for locator_name, contract_name in sorted(policy_contracts):
|
|
768
|
+
locator = locators[locator_name]
|
|
769
|
+
contract = contracts[contract_name]
|
|
770
|
+
for question, expected_items in contract["itens_por_questao"].items():
|
|
771
|
+
normalized_question = _normal(question)
|
|
772
|
+
if any(not _locator_item_matches(locator, item) for item in expected_items):
|
|
773
|
+
raise IndexDslError(
|
|
774
|
+
"E_DETAIL_CONTRACT_INVALID",
|
|
775
|
+
f"item fora do item_regex do localizador {locator_name!r} na questão {question!r}",
|
|
776
|
+
path=f"$.entrada.contratos_detalhes.{contract_name}.itens_por_questao.{question}",
|
|
777
|
+
)
|
|
778
|
+
actual_items = set(inventory.get((locator_name, normalized_question), {}))
|
|
779
|
+
expected_set = set(expected_items)
|
|
780
|
+
missing = [item for item in expected_items if item not in actual_items]
|
|
781
|
+
if missing:
|
|
782
|
+
raise IndexDslError(
|
|
783
|
+
"E_DETAIL_ITEM_MISSING",
|
|
784
|
+
f"itens esperados {missing!r} ausentes na questão {question!r}",
|
|
785
|
+
path=f"cabeçalho.{locator_name}.{question}",
|
|
786
|
+
)
|
|
787
|
+
extra = sorted(actual_items - expected_set)
|
|
788
|
+
if extra:
|
|
789
|
+
raise IndexDslError(
|
|
790
|
+
"E_DETAIL_ITEM_EXTRA",
|
|
791
|
+
f"itens extras {extra!r} no cabeçalho da questão {question!r}",
|
|
792
|
+
path=f"cabeçalho.{locator_name}.{question}",
|
|
793
|
+
)
|
|
794
|
+
|
|
795
|
+
resolved: dict[str, ResolvedReference] = {}
|
|
796
|
+
for use in uses:
|
|
797
|
+
reference = use.reference
|
|
798
|
+
policy = use.policy
|
|
799
|
+
if reference.kind == "node":
|
|
800
|
+
resolved[use.path] = ResolvedReference(use.path, reference)
|
|
801
|
+
continue
|
|
802
|
+
|
|
803
|
+
if reference.kind == "selected_question":
|
|
804
|
+
if policy is None:
|
|
805
|
+
raise IndexDslError(
|
|
806
|
+
"E_LOCATOR_REQUIRED",
|
|
807
|
+
"referência com seletor exige um localizador declarado pela operação ou regra de componentes",
|
|
808
|
+
path=use.path,
|
|
809
|
+
)
|
|
810
|
+
question = _normal(reference.question or "")
|
|
811
|
+
locator = locators[policy.locator]
|
|
812
|
+
selected_items = tuple(
|
|
813
|
+
dict.fromkeys(item for criterion in (reference.selector.criteria if reference.selector else ()) for item in _selector_items(criterion))
|
|
814
|
+
)
|
|
815
|
+
expected_items = None
|
|
816
|
+
if policy.contract is not None:
|
|
817
|
+
expected_items = contracts[policy.contract]["itens_por_questao"].get(question)
|
|
818
|
+
if expected_items is None:
|
|
819
|
+
raise IndexDslError(
|
|
820
|
+
"E_DETAIL_CONTRACT_QUESTION",
|
|
821
|
+
f"questão {question!r} não declarada no contrato {policy.contract!r}",
|
|
822
|
+
path=use.path,
|
|
823
|
+
)
|
|
824
|
+
unknown = [item for item in selected_items if item not in expected_items]
|
|
825
|
+
if unknown:
|
|
826
|
+
raise IndexDslError(
|
|
827
|
+
"E_DETAIL_CONTRACT_ITEM",
|
|
828
|
+
f"itens selecionados {unknown!r} não pertencem ao contrato da questão {question!r}",
|
|
829
|
+
path=use.path,
|
|
830
|
+
)
|
|
831
|
+
invalid = [item for item in selected_items if not _locator_item_matches(locator, item)]
|
|
832
|
+
if invalid:
|
|
833
|
+
raise IndexDslError("E_LOCATOR_ITEM_INVALID", f"itens inválidos para o localizador: {invalid!r}", path=use.path)
|
|
834
|
+
available = inventory.get((policy.locator, question), {})
|
|
835
|
+
missing = [item for item in selected_items if item not in available]
|
|
836
|
+
if missing:
|
|
837
|
+
raise IndexDslError(
|
|
838
|
+
"E_DETAIL_ITEM_MISSING",
|
|
839
|
+
f"itens selecionados {missing!r} ausentes na questão {question!r}",
|
|
840
|
+
path=use.path,
|
|
841
|
+
)
|
|
842
|
+
if question not in positions:
|
|
843
|
+
raise IndexDslError(
|
|
844
|
+
"E_INPUT_COLUMN_MISSING",
|
|
845
|
+
f"coluna-base obrigatória {question!r} ausente para o seletor",
|
|
846
|
+
path=use.path,
|
|
847
|
+
)
|
|
848
|
+
resolved[use.path] = ResolvedReference(
|
|
849
|
+
use.path,
|
|
850
|
+
reference,
|
|
851
|
+
column=question,
|
|
852
|
+
detail_columns=MappingProxyType({item: available[item] for item in selected_items}),
|
|
853
|
+
)
|
|
854
|
+
continue
|
|
855
|
+
|
|
856
|
+
if reference.kind == "detail" and policy is not None:
|
|
857
|
+
locator = locators[policy.locator]
|
|
858
|
+
known_questions = questions_by_locator.get(policy.locator, set())
|
|
859
|
+
question, item = _parse_locator_reference(locator, reference.raw_text, known_questions, path=use.path)
|
|
860
|
+
available = inventory.get((policy.locator, question), {})
|
|
861
|
+
column = available.get(item)
|
|
862
|
+
if column is None:
|
|
863
|
+
raise IndexDslError("E_DETAIL_ITEM_MISSING", f"item {item!r} ausente na questão {question!r}", path=use.path)
|
|
864
|
+
resolved[use.path] = ResolvedReference(
|
|
865
|
+
use.path,
|
|
866
|
+
reference,
|
|
867
|
+
column=column,
|
|
868
|
+
detail_columns=MappingProxyType({item: column}),
|
|
869
|
+
)
|
|
870
|
+
continue
|
|
871
|
+
|
|
872
|
+
column = _normal(reference.raw_text)
|
|
873
|
+
if column not in positions:
|
|
874
|
+
raise IndexDslError("E_INPUT_COLUMN_MISSING", f"coluna obrigatória {column!r} ausente", path=use.path)
|
|
875
|
+
detail_columns: Mapping[str, str] = MappingProxyType({})
|
|
876
|
+
if policy is not None and use.base_question:
|
|
877
|
+
question = _normal(reference.raw_text)
|
|
878
|
+
detail_columns = MappingProxyType(dict(inventory.get((policy.locator, question), {})))
|
|
879
|
+
resolved[use.path] = ResolvedReference(use.path, reference, column=column, detail_columns=detail_columns)
|
|
880
|
+
|
|
881
|
+
return MappingProxyType(resolved)
|
|
882
|
+
|
|
883
|
+
|
|
884
|
+
def prepare_input(compiled: CompiledIndex, table: Any) -> PreparedInput:
|
|
885
|
+
"""Validate headers and select rows according to the DSL input policy."""
|
|
886
|
+
physical_headers = tuple(table.headers)
|
|
887
|
+
if not physical_headers:
|
|
888
|
+
raise IndexDslError("E_INPUT_COLUMN_MISSING", "a tabela não possui cabeçalho")
|
|
889
|
+
|
|
890
|
+
headers = tuple(_normal(str(header)) for header in physical_headers)
|
|
891
|
+
if any(not header for header in headers):
|
|
892
|
+
raise IndexDslError("E_HEADER_INVALID", "cabeçalhos vazios não são permitidos")
|
|
893
|
+
positions: dict[str, int] = {}
|
|
894
|
+
for index, header in enumerate(headers):
|
|
895
|
+
if header in positions:
|
|
896
|
+
prior = physical_headers[positions[header]]
|
|
897
|
+
raise IndexDslError(
|
|
898
|
+
"E_COLUMN_ALIAS_COLLISION",
|
|
899
|
+
f"cabeçalhos {prior!r} e {physical_headers[index]!r} colidem após NFC/strip",
|
|
900
|
+
path=f"cabeçalho[{index + 1}]",
|
|
901
|
+
)
|
|
902
|
+
positions[header] = index
|
|
903
|
+
|
|
904
|
+
entry = compiled.entry
|
|
905
|
+
resolved_references = _resolve_input_references(compiled, headers)
|
|
906
|
+
id_column = _normal(entry["id_organizacao"])
|
|
907
|
+
required_columns = [id_column]
|
|
908
|
+
filters = entry.get("filtrar_validos")
|
|
909
|
+
if filters:
|
|
910
|
+
required_columns.extend(_normal(name) for name in filters["obrigatorio_preenchido"])
|
|
911
|
+
deduplication = entry.get("desduplicacao")
|
|
912
|
+
order_column: str | None = None
|
|
913
|
+
key_column: str | None = None
|
|
914
|
+
if deduplication:
|
|
915
|
+
key_name = deduplication["chave"]
|
|
916
|
+
key_column = id_column if key_name == "id_organizacao" else _normal(key_name)
|
|
917
|
+
order_column = _normal(deduplication["ordenar_por"])
|
|
918
|
+
required_columns.extend((key_column, order_column))
|
|
919
|
+
for column in required_columns:
|
|
920
|
+
if column not in positions:
|
|
921
|
+
raise IndexDslError("E_INPUT_COLUMN_MISSING", f"coluna obrigatória {column!r} ausente", path="cabeçalho")
|
|
922
|
+
|
|
923
|
+
source_records = tuple(table.rows)
|
|
924
|
+
records: list[PreparedRecord] = []
|
|
925
|
+
for source_record in source_records:
|
|
926
|
+
if len(source_record.values) != len(headers):
|
|
927
|
+
raise IndexDslError("E_TABLE_SHAPE", "número de valores difere do cabeçalho", path=f"linha {source_record.row_number}")
|
|
928
|
+
values = MappingProxyType({header: source_record.values[index] for index, header in enumerate(headers)})
|
|
929
|
+
if entry.get("linhas_vazias") == "erro" and all(_cell_empty(value) for value in values.values()):
|
|
930
|
+
raise IndexDslError("E_EMPTY_ROW", "linha de dados totalmente vazia", path=f"linha {source_record.row_number}")
|
|
931
|
+
records.append(PreparedRecord("", source_record.row_number, values))
|
|
932
|
+
|
|
933
|
+
rows_read = len(records)
|
|
934
|
+
rows_filtered = 0
|
|
935
|
+
if filters:
|
|
936
|
+
policy = filters["politica_incompletos"]
|
|
937
|
+
retained: list[PreparedRecord] = []
|
|
938
|
+
required = tuple(_normal(name) for name in filters["obrigatorio_preenchido"])
|
|
939
|
+
for record in records:
|
|
940
|
+
incomplete = [column for column in required if _cell_empty(record.values[column])]
|
|
941
|
+
if incomplete and policy == "erro":
|
|
942
|
+
raise IndexDslError(
|
|
943
|
+
"E_ROW_INCOMPLETE",
|
|
944
|
+
f"campos obrigatórios vazios: {', '.join(incomplete)}",
|
|
945
|
+
path=f"linha {record.row_number}",
|
|
946
|
+
)
|
|
947
|
+
if incomplete:
|
|
948
|
+
rows_filtered += 1
|
|
949
|
+
continue
|
|
950
|
+
retained.append(record)
|
|
951
|
+
records = retained
|
|
952
|
+
|
|
953
|
+
identified: list[PreparedRecord] = []
|
|
954
|
+
for record in records:
|
|
955
|
+
organization = _key_text(record.values[id_column])
|
|
956
|
+
if not organization:
|
|
957
|
+
raise IndexDslError("E_ORGANIZATION_ID", "identificador da organização vazio", path=f"linha {record.row_number}, coluna {id_column}")
|
|
958
|
+
identified.append(PreparedRecord(organization, record.row_number, record.values))
|
|
959
|
+
records = identified
|
|
960
|
+
|
|
961
|
+
duplicate_rows_removed = 0
|
|
962
|
+
if deduplication:
|
|
963
|
+
groups: dict[str, list[PreparedRecord]] = {}
|
|
964
|
+
assert key_column is not None and order_column is not None
|
|
965
|
+
for record in records:
|
|
966
|
+
key = _key_text(record.values[key_column])
|
|
967
|
+
if not key:
|
|
968
|
+
raise IndexDslError("E_DUPLICATE_KEY_MISSING", "chave de desduplicação vazia", path=f"linha {record.row_number}, coluna {key_column}")
|
|
969
|
+
groups.setdefault(key, []).append(record)
|
|
970
|
+
|
|
971
|
+
selected: list[PreparedRecord] = []
|
|
972
|
+
for key, group in groups.items():
|
|
973
|
+
if len(group) == 1:
|
|
974
|
+
selected.append(group[0])
|
|
975
|
+
continue
|
|
976
|
+
ordered = [
|
|
977
|
+
(record, _dedup_order_key(record.values[order_column], row_number=record.row_number, column=order_column))
|
|
978
|
+
for record in group
|
|
979
|
+
]
|
|
980
|
+
kinds = {order_key[0] for _, order_key in ordered}
|
|
981
|
+
if len(kinds) != 1:
|
|
982
|
+
raise IndexDslError("E_DUPLICATE_ORDER_INVALID", f"chaves de ordenação incomparáveis para {key!r}", path=f"coluna {order_column}")
|
|
983
|
+
maximum = max(order_key[1] for _, order_key in ordered)
|
|
984
|
+
tied = [record for record, order_key in ordered if order_key[1] == maximum]
|
|
985
|
+
first = tied[0]
|
|
986
|
+
if any(record.values != first.values for record in tied[1:]):
|
|
987
|
+
raise IndexDslError("E_DUPLICATE_ORDER_TIE", f"registros conflitantes empatam na maior chave para {key!r}", path=f"coluna {order_column}")
|
|
988
|
+
selected.append(first)
|
|
989
|
+
duplicate_rows_removed = len(records) - len(selected)
|
|
990
|
+
records = selected
|
|
991
|
+
else:
|
|
992
|
+
organizations: set[str] = set()
|
|
993
|
+
for record in records:
|
|
994
|
+
if record.organization in organizations:
|
|
995
|
+
raise IndexDslError("E_DUPLICATE_ORGANIZATION", f"organização repetida {record.organization!r} sem política de desduplicação", path=f"linha {record.row_number}")
|
|
996
|
+
organizations.add(record.organization)
|
|
997
|
+
|
|
998
|
+
statistics = MappingProxyType(
|
|
999
|
+
{
|
|
1000
|
+
"rows_read": rows_read,
|
|
1001
|
+
"rows_filtered": rows_filtered,
|
|
1002
|
+
"duplicate_rows_removed": duplicate_rows_removed,
|
|
1003
|
+
"rows_calculated": len(records),
|
|
1004
|
+
}
|
|
1005
|
+
)
|
|
1006
|
+
return PreparedInput(headers, tuple(records), statistics, resolved_references)
|
|
1007
|
+
|
|
1008
|
+
|
|
1009
|
+
def _validate_converter(name: str, converter: Mapping[str, Any]) -> None:
|
|
1010
|
+
path = f"$.conversores.{name}"
|
|
1011
|
+
values = converter.get("valores")
|
|
1012
|
+
if not isinstance(values, Mapping) or not values:
|
|
1013
|
+
raise IndexDslError("E_CONVERTER_INVALID", "valores deve ser um mapa não vazio", path=f"{path}.valores")
|
|
1014
|
+
canonical: dict[str, str] = {}
|
|
1015
|
+
for code, score in values.items():
|
|
1016
|
+
if not isinstance(code, str) or not code.strip():
|
|
1017
|
+
raise IndexDslError("E_CONVERTER_INVALID", "códigos canônicos devem ser strings não vazias", path=f"{path}.valores")
|
|
1018
|
+
normalized = _normal(code)
|
|
1019
|
+
if normalized in canonical:
|
|
1020
|
+
raise IndexDslError("E_CONVERTER_COLLISION", f"códigos colidem após normalização: {code!r}", path=f"{path}.valores")
|
|
1021
|
+
canonical[normalized] = code
|
|
1022
|
+
if isinstance(score, bool) or not isinstance(score, Real) or not math.isfinite(float(score)):
|
|
1023
|
+
raise IndexDslError("E_NUMERIC_NONFINITE", f"pontuação inválida para {code!r}", path=f"{path}.valores.{code}")
|
|
1024
|
+
if not 0 <= float(score) <= 1:
|
|
1025
|
+
raise IndexDslError("E_CONVERTER_RANGE", "pontuações de conversores devem estar em [0,1]", path=f"{path}.valores.{code}")
|
|
1026
|
+
|
|
1027
|
+
aliases = converter.get("aliases", {})
|
|
1028
|
+
seen_aliases: dict[str, tuple[str, str]] = {}
|
|
1029
|
+
for alias, code in aliases.items():
|
|
1030
|
+
alias_path = f"{path}.aliases.{alias}"
|
|
1031
|
+
if not isinstance(alias, str) or not alias.strip() or not isinstance(code, str):
|
|
1032
|
+
raise IndexDslError("E_CONVERTER_INVALID", "alias e código canônico devem ser strings não vazias", path=alias_path)
|
|
1033
|
+
if code not in values:
|
|
1034
|
+
raise IndexDslError("E_CONVERTER_UNKNOWN", f"alias referencia código canônico inexistente {code!r}", path=alias_path)
|
|
1035
|
+
normalized = _normal(alias)
|
|
1036
|
+
if normalized in seen_aliases:
|
|
1037
|
+
prior_alias, prior_code = seen_aliases[normalized]
|
|
1038
|
+
if prior_code != code or prior_alias != alias:
|
|
1039
|
+
raise IndexDslError("E_CONVERTER_COLLISION", f"aliases colidem após normalização: {prior_alias!r} e {alias!r}", path=alias_path)
|
|
1040
|
+
seen_aliases[normalized] = (alias, code)
|
|
1041
|
+
canonical_code = canonical.get(normalized)
|
|
1042
|
+
if canonical_code is not None and canonical_code != code:
|
|
1043
|
+
raise IndexDslError("E_CONVERTER_COLLISION", f"alias conflita com código canônico {canonical_code!r}", path=alias_path)
|
|
1044
|
+
|
|
1045
|
+
|
|
1046
|
+
def _numeric_input(value: Any, *, path: str, code: str, message: str) -> float:
|
|
1047
|
+
if isinstance(value, bool) or not isinstance(value, (Real, Decimal)):
|
|
1048
|
+
raise IndexDslError(code, message, path=path)
|
|
1049
|
+
try:
|
|
1050
|
+
numeric = float(value)
|
|
1051
|
+
except (OverflowError, TypeError, ValueError) as exc:
|
|
1052
|
+
raise IndexDslError("E_NUMERIC_NONFINITE", "valor numérico inválido ou não finito", path=path) from exc
|
|
1053
|
+
if not math.isfinite(numeric):
|
|
1054
|
+
raise IndexDslError("E_NUMERIC_NONFINITE", "valor numérico inválido ou não finito", path=path)
|
|
1055
|
+
return numeric
|
|
1056
|
+
|
|
1057
|
+
|
|
1058
|
+
def convert_value(
|
|
1059
|
+
compiled: CompiledIndex,
|
|
1060
|
+
converter_name: str,
|
|
1061
|
+
raw: Any,
|
|
1062
|
+
*,
|
|
1063
|
+
column: str | None = None,
|
|
1064
|
+
empty_policy: str | None = None,
|
|
1065
|
+
path: str = "$",
|
|
1066
|
+
) -> ConvertedValue:
|
|
1067
|
+
"""Convert one existing input cell without losing its canonical category."""
|
|
1068
|
+
converter = compiled.converters.get(converter_name)
|
|
1069
|
+
if converter is None:
|
|
1070
|
+
raise IndexDslError("E_CONVERTER_UNKNOWN", f"conversor inexistente {converter_name!r}", path=path)
|
|
1071
|
+
policy = empty_policy or converter["vazio"]
|
|
1072
|
+
if _cell_empty(raw):
|
|
1073
|
+
if policy == "zero":
|
|
1074
|
+
return ConvertedValue(None, 0.0, column, raw, True, "empty")
|
|
1075
|
+
raise IndexDslError("E_VALUE_EMPTY", f"célula vazia na coluna {column!r}", path=path)
|
|
1076
|
+
|
|
1077
|
+
if isinstance(raw, (Real, Decimal)) and not isinstance(raw, bool):
|
|
1078
|
+
try:
|
|
1079
|
+
finite = math.isfinite(float(raw))
|
|
1080
|
+
except (OverflowError, TypeError, ValueError):
|
|
1081
|
+
finite = False
|
|
1082
|
+
if not finite:
|
|
1083
|
+
raise IndexDslError("E_NUMERIC_NONFINITE", "valor numérico de entrada não finito", path=path)
|
|
1084
|
+
if not isinstance(raw, str):
|
|
1085
|
+
raise IndexDslError("E_CONVERSION_UNKNOWN", f"valor {raw!r} não corresponde a código ou alias textual", path=path)
|
|
1086
|
+
|
|
1087
|
+
normalized = _normal(raw)
|
|
1088
|
+
canonical = compiled.converter_codes[converter_name].get(normalized)
|
|
1089
|
+
origin = "canonical"
|
|
1090
|
+
if canonical is None:
|
|
1091
|
+
canonical = compiled.converter_aliases[converter_name].get(normalized)
|
|
1092
|
+
origin = "alias"
|
|
1093
|
+
if canonical is None:
|
|
1094
|
+
raise IndexDslError("E_CONVERSION_UNKNOWN", f"valor desconhecido {raw!r} para conversor {converter_name!r}", path=path)
|
|
1095
|
+
score = _numeric_input(
|
|
1096
|
+
converter["valores"][canonical],
|
|
1097
|
+
path=path,
|
|
1098
|
+
code="E_NUMERIC_NONFINITE",
|
|
1099
|
+
message=f"pontuação inválida para código {canonical!r}",
|
|
1100
|
+
)
|
|
1101
|
+
if not 0 <= score <= 1:
|
|
1102
|
+
raise IndexDslError("E_CONVERTER_RANGE", f"pontuação de {canonical!r} está fora de [0,1]", path=path)
|
|
1103
|
+
return ConvertedValue(canonical, score, column, raw, False, origin)
|
|
1104
|
+
|
|
1105
|
+
|
|
1106
|
+
def validate_external_score(value: Any, *, column: str, path: str = "$") -> float:
|
|
1107
|
+
"""Accept a precomputed numeric score only when it is an actual finite number."""
|
|
1108
|
+
score = _numeric_input(
|
|
1109
|
+
value,
|
|
1110
|
+
path=path,
|
|
1111
|
+
code="E_EXTERNAL_SCORE_INVALID",
|
|
1112
|
+
message=f"a coluna externa {column!r} deve conter escore numérico",
|
|
1113
|
+
)
|
|
1114
|
+
if not 0 <= score <= 1:
|
|
1115
|
+
raise IndexDslError("E_EXTERNAL_SCORE_INVALID", f"escore externo {score!r} fora de [0,1] na coluna {column!r}", path=path)
|
|
1116
|
+
return score
|
|
1117
|
+
|
|
1118
|
+
|
|
1119
|
+
def apply_range(value: Any, bounds: Any, *, path: str = "$") -> float:
|
|
1120
|
+
"""Apply a configured output interval; this is a helper, not a DSL operation."""
|
|
1121
|
+
numeric = _numeric_input(
|
|
1122
|
+
value,
|
|
1123
|
+
path=path,
|
|
1124
|
+
code="E_OPERATION_RESULT_INVALID",
|
|
1125
|
+
message="resultado da operação deve ser numérico",
|
|
1126
|
+
)
|
|
1127
|
+
if bounds is None:
|
|
1128
|
+
return numeric
|
|
1129
|
+
if (
|
|
1130
|
+
not isinstance(bounds, (tuple, list))
|
|
1131
|
+
or len(bounds) != 2
|
|
1132
|
+
or any(isinstance(bound, bool) or not isinstance(bound, (Real, Decimal)) for bound in bounds)
|
|
1133
|
+
):
|
|
1134
|
+
raise IndexDslError("E_INVALID_RANGE", "range deve conter dois limites numéricos", path=path)
|
|
1135
|
+
lower = _numeric_input(bounds[0], path=path, code="E_INVALID_RANGE", message="limite inferior inválido")
|
|
1136
|
+
upper = _numeric_input(bounds[1], path=path, code="E_INVALID_RANGE", message="limite superior inválido")
|
|
1137
|
+
if lower > upper:
|
|
1138
|
+
raise IndexDslError("E_INVALID_RANGE", "limite inferior excede o superior", path=path)
|
|
1139
|
+
result = min(upper, max(lower, numeric))
|
|
1140
|
+
if not math.isfinite(result):
|
|
1141
|
+
raise IndexDslError("E_NUMERIC_NONFINITE", "resultado não finito após range", path=path)
|
|
1142
|
+
return result
|
|
1143
|
+
|
|
1144
|
+
|
|
1145
|
+
def classify_maturity(value: Any, bands: Any, *, path: str = "$") -> str | None:
|
|
1146
|
+
"""Classify an unrounded root score using each band's explicit endpoints."""
|
|
1147
|
+
if not bands:
|
|
1148
|
+
return None
|
|
1149
|
+
score = _numeric_input(
|
|
1150
|
+
value,
|
|
1151
|
+
path=path,
|
|
1152
|
+
code="E_NUMERIC_NONFINITE",
|
|
1153
|
+
message="escore da raiz deve ser numérico e finito",
|
|
1154
|
+
)
|
|
1155
|
+
matches: list[str] = []
|
|
1156
|
+
for index, band in enumerate(bands):
|
|
1157
|
+
lower_ok = score >= band["min"] if band["inclui_min"] else score > band["min"]
|
|
1158
|
+
upper_ok = score <= band["max"] if band["inclui_max"] else score < band["max"]
|
|
1159
|
+
if lower_ok and upper_ok:
|
|
1160
|
+
matches.append(band["nome"])
|
|
1161
|
+
if not matches:
|
|
1162
|
+
raise IndexDslError("E_MATURITY_UNCLASSIFIED", f"escore {score!r} não pertence a nenhuma faixa de maturidade", path=path)
|
|
1163
|
+
if len(matches) > 1:
|
|
1164
|
+
raise IndexDslError("E_MATURITY_OVERLAP", f"escore {score!r} pertence a mais de uma faixa: {matches!r}", path=path)
|
|
1165
|
+
return matches[0]
|
|
1166
|
+
|
|
1167
|
+
|
|
1168
|
+
def _maturity_gaps(bands: tuple[Mapping[str, Any], ...] | list[Mapping[str, Any]]) -> tuple[MaturityGap, ...]:
|
|
1169
|
+
if not bands:
|
|
1170
|
+
return ()
|
|
1171
|
+
ordered = sorted(bands, key=lambda band: (band["min"], band["max"]))
|
|
1172
|
+
gaps: list[MaturityGap] = []
|
|
1173
|
+
first = ordered[0]
|
|
1174
|
+
if first["min"] > 0:
|
|
1175
|
+
gaps.append(MaturityGap(0.0, float(first["min"]), True, not first["inclui_min"]))
|
|
1176
|
+
elif not first["inclui_min"]:
|
|
1177
|
+
gaps.append(MaturityGap(0.0, 0.0, True, True))
|
|
1178
|
+
|
|
1179
|
+
for previous, following in zip(ordered, ordered[1:], strict=False):
|
|
1180
|
+
if previous["max"] < following["min"]:
|
|
1181
|
+
gaps.append(
|
|
1182
|
+
MaturityGap(
|
|
1183
|
+
float(previous["max"]),
|
|
1184
|
+
float(following["min"]),
|
|
1185
|
+
not previous["inclui_max"],
|
|
1186
|
+
not following["inclui_min"],
|
|
1187
|
+
)
|
|
1188
|
+
)
|
|
1189
|
+
elif previous["max"] == following["min"] and not previous["inclui_max"] and not following["inclui_min"]:
|
|
1190
|
+
boundary = float(previous["max"])
|
|
1191
|
+
gaps.append(MaturityGap(boundary, boundary, True, True))
|
|
1192
|
+
|
|
1193
|
+
last = ordered[-1]
|
|
1194
|
+
if last["max"] < 1:
|
|
1195
|
+
gaps.append(MaturityGap(float(last["max"]), 1.0, not last["inclui_max"], True))
|
|
1196
|
+
elif last["max"] == 1 and not last["inclui_max"]:
|
|
1197
|
+
gaps.append(MaturityGap(1.0, 1.0, True, True))
|
|
1198
|
+
return tuple(gaps)
|
|
1199
|
+
|
|
1200
|
+
|
|
1201
|
+
def _component_score(value: Any, *, path: str) -> float:
|
|
1202
|
+
if isinstance(value, ConvertedValue):
|
|
1203
|
+
score = _numeric_input(
|
|
1204
|
+
value.value,
|
|
1205
|
+
path=path,
|
|
1206
|
+
code="E_NUMERIC_NONFINITE",
|
|
1207
|
+
message="pontuação convertida deve ser finita",
|
|
1208
|
+
)
|
|
1209
|
+
if not 0 <= score <= 1:
|
|
1210
|
+
raise IndexDslError("E_SCORE_RANGE", f"pontuação {score!r} fora de [0,1]", path=path)
|
|
1211
|
+
return score
|
|
1212
|
+
return validate_external_score(value, column="componente numérico", path=path)
|
|
1213
|
+
|
|
1214
|
+
|
|
1215
|
+
def _weights_for(values: tuple[Any, ...], weights: Any, *, path: str) -> tuple[tuple[float, ...], tuple[Decimal, ...]]:
|
|
1216
|
+
raw_weights = (1.0,) * len(values) if weights is None else tuple(weights)
|
|
1217
|
+
if len(raw_weights) != len(values):
|
|
1218
|
+
raise IndexDslError("E_COMPONENT_COUNT", "quantidade de pesos difere da quantidade de componentes", path=path)
|
|
1219
|
+
converted: list[float] = []
|
|
1220
|
+
decimals: list[Decimal] = []
|
|
1221
|
+
for index, weight in enumerate(raw_weights):
|
|
1222
|
+
if isinstance(weight, bool) or not isinstance(weight, (Real, Decimal)):
|
|
1223
|
+
raise IndexDslError("E_INVALID_WEIGHT", f"peso {index} não é numérico", path=path)
|
|
1224
|
+
try:
|
|
1225
|
+
decimal_weight = Decimal(str(weight))
|
|
1226
|
+
numeric_weight = float(weight)
|
|
1227
|
+
except (InvalidOperation, OverflowError, TypeError, ValueError) as exc:
|
|
1228
|
+
raise IndexDslError("E_INVALID_WEIGHT", f"peso {index} é inválido", path=path) from exc
|
|
1229
|
+
if not decimal_weight.is_finite() or not math.isfinite(numeric_weight) or decimal_weight < 0:
|
|
1230
|
+
raise IndexDslError("E_INVALID_WEIGHT", f"peso {index} deve ser finito e não negativo", path=path)
|
|
1231
|
+
converted.append(numeric_weight)
|
|
1232
|
+
decimals.append(decimal_weight)
|
|
1233
|
+
return tuple(converted), tuple(decimals)
|
|
1234
|
+
|
|
1235
|
+
|
|
1236
|
+
def _operation_result(value: float, parameters: Mapping[str, Any], diagnostics: Mapping[str, Any], *, path: str) -> OperationResult:
|
|
1237
|
+
before_range = _numeric_input(
|
|
1238
|
+
value,
|
|
1239
|
+
path=path,
|
|
1240
|
+
code="E_NUMERIC_NONFINITE",
|
|
1241
|
+
message="resultado intermediário não finito",
|
|
1242
|
+
)
|
|
1243
|
+
raw_bounds = parameters.get("range")
|
|
1244
|
+
result = apply_range(before_range, raw_bounds, path=path)
|
|
1245
|
+
applied_range = None if raw_bounds is None else (float(raw_bounds[0]), float(raw_bounds[1]))
|
|
1246
|
+
return OperationResult(result, before_range, applied_range, MappingProxyType(dict(diagnostics)))
|
|
1247
|
+
|
|
1248
|
+
|
|
1249
|
+
def execute_operation(
|
|
1250
|
+
operation: str,
|
|
1251
|
+
values: Any,
|
|
1252
|
+
parameters: Mapping[str, Any],
|
|
1253
|
+
*,
|
|
1254
|
+
weights: Any = None,
|
|
1255
|
+
exclusive: Any = None,
|
|
1256
|
+
detail_factor: Any = None,
|
|
1257
|
+
path: str = "$",
|
|
1258
|
+
) -> OperationResult:
|
|
1259
|
+
"""Run one DSL arithmetic operation over already resolved component values."""
|
|
1260
|
+
if operation not in OPERATIONS:
|
|
1261
|
+
raise IndexDslError("E_UNKNOWN_OPERATION", f"operação desconhecida {operation!r}", path=path)
|
|
1262
|
+
components = tuple(values)
|
|
1263
|
+
if not components:
|
|
1264
|
+
raise IndexDslError("E_EMPTY_COMPONENTS", "a operação exige ao menos um componente", path=path)
|
|
1265
|
+
|
|
1266
|
+
if operation == "mapeamento":
|
|
1267
|
+
if len(components) != 1:
|
|
1268
|
+
raise IndexDslError("E_COMPONENT_COUNT", "mapeamento exige exatamente um componente", path=path)
|
|
1269
|
+
if not isinstance(components[0], ConvertedValue):
|
|
1270
|
+
raise IndexDslError("E_OPERATION_INPUT", "mapeamento exige uma célula categórica convertida", path=path)
|
|
1271
|
+
converted = components[0]
|
|
1272
|
+
return _operation_result(
|
|
1273
|
+
converted.value,
|
|
1274
|
+
parameters,
|
|
1275
|
+
{
|
|
1276
|
+
"code": converted.canonical_code,
|
|
1277
|
+
"value": converted.value,
|
|
1278
|
+
"column": converted.column,
|
|
1279
|
+
"origin": converted.origin,
|
|
1280
|
+
"empty": converted.empty,
|
|
1281
|
+
},
|
|
1282
|
+
path=path,
|
|
1283
|
+
)
|
|
1284
|
+
|
|
1285
|
+
if operation in {"media_ponderada", "soma_ponderada"}:
|
|
1286
|
+
scores = tuple(_component_score(value, path=f"{path}.componentes[{index}]") for index, value in enumerate(components))
|
|
1287
|
+
numeric_weights, decimal_weights = _weights_for(components, weights, path=f"{path}.componentes")
|
|
1288
|
+
decimal_total = sum(decimal_weights, Decimal(0))
|
|
1289
|
+
if decimal_total <= 0:
|
|
1290
|
+
raise IndexDslError("E_DIVISION_BY_ZERO", "a soma dos pesos deve ser positiva", path=path)
|
|
1291
|
+
try:
|
|
1292
|
+
weight_total = math.fsum(numeric_weights)
|
|
1293
|
+
numerator = math.fsum(weight * score for weight, score in zip(numeric_weights, scores, strict=True))
|
|
1294
|
+
except OverflowError as exc:
|
|
1295
|
+
raise IndexDslError("E_NUMERIC_NONFINITE", "resultado ponderado não finito", path=path) from exc
|
|
1296
|
+
if not math.isfinite(weight_total) or not math.isfinite(numerator):
|
|
1297
|
+
raise IndexDslError("E_NUMERIC_NONFINITE", "resultado ponderado não finito", path=path)
|
|
1298
|
+
if operation == "media_ponderada":
|
|
1299
|
+
if weight_total <= 0:
|
|
1300
|
+
raise IndexDslError("E_DIVISION_BY_ZERO", "a soma dos pesos deve ser positiva", path=path)
|
|
1301
|
+
result = numerator / weight_total
|
|
1302
|
+
else:
|
|
1303
|
+
tolerance = parameters.get("tolerancia_soma_pesos")
|
|
1304
|
+
if tolerance is not None:
|
|
1305
|
+
decimal_tolerance = Decimal(str(tolerance))
|
|
1306
|
+
if abs(decimal_total - Decimal(1)) > decimal_tolerance:
|
|
1307
|
+
raise IndexDslError("E_WEIGHT_SUM", "a soma dos pesos excede tolerancia_soma_pesos", path=path)
|
|
1308
|
+
result = numerator
|
|
1309
|
+
return _operation_result(
|
|
1310
|
+
result,
|
|
1311
|
+
parameters,
|
|
1312
|
+
{"weights": numeric_weights, "weight_total": weight_total, "components": scores},
|
|
1313
|
+
path=path,
|
|
1314
|
+
)
|
|
1315
|
+
|
|
1316
|
+
if operation == "media_binaria":
|
|
1317
|
+
scores = tuple(_component_score(value, path=f"{path}.componentes[{index}]") for index, value in enumerate(components))
|
|
1318
|
+
invalid = [score for score in scores if score not in (0.0, 1.0)]
|
|
1319
|
+
if invalid:
|
|
1320
|
+
raise IndexDslError("E_BINARY_SCORE_INVALID", f"media_binaria aceita apenas 0 ou 1; recebido {invalid!r}", path=path)
|
|
1321
|
+
negative: float | None = None
|
|
1322
|
+
if exclusive is not None:
|
|
1323
|
+
negative = _component_score(exclusive, path=f"{path}.exclusiva_negativa")
|
|
1324
|
+
if negative not in (0.0, 1.0):
|
|
1325
|
+
raise IndexDslError("E_BINARY_SCORE_INVALID", "opção negativa exclusiva deve valer 0 ou 1", path=path)
|
|
1326
|
+
if negative == 1.0 and any(score == 1.0 for score in scores):
|
|
1327
|
+
raise IndexDslError("E_EXCLUSIVE_CONTRADICTION", "opção exclusiva marcada junto a uma opção positiva", path=path)
|
|
1328
|
+
result = math.fsum(scores) / len(scores)
|
|
1329
|
+
return _operation_result(result, parameters, {"positive_count": math.fsum(scores), "exclusive": negative}, path=path)
|
|
1330
|
+
|
|
1331
|
+
if len(components) != 1 or not isinstance(components[0], ConvertedValue):
|
|
1332
|
+
raise IndexDslError("E_OPERATION_INPUT", "desconto_proporcional exige uma questão-base convertida", path=path)
|
|
1333
|
+
base = components[0]
|
|
1334
|
+
if detail_factor is None:
|
|
1335
|
+
if parameters.get("detalhes", {}).get("sem_itens_esperados") != "manter_base":
|
|
1336
|
+
raise IndexDslError("E_DETAIL_ITEMS_EMPTY", "desconto exige itens selecionados ou sem_itens_esperados: manter_base", path=path)
|
|
1337
|
+
factor: float | None = None
|
|
1338
|
+
discount = 0.0
|
|
1339
|
+
result = base.value
|
|
1340
|
+
else:
|
|
1341
|
+
factor = _component_score(detail_factor, path=f"{path}.detalhes")
|
|
1342
|
+
code_discounts = parameters["desconto_por_codigo"]
|
|
1343
|
+
if base.canonical_code in code_discounts:
|
|
1344
|
+
discount = _numeric_input(
|
|
1345
|
+
code_discounts[base.canonical_code],
|
|
1346
|
+
path=f"{path}.desconto_por_codigo.{base.canonical_code}",
|
|
1347
|
+
code="E_INVALID_DISCOUNT",
|
|
1348
|
+
message="desconto deve ser numérico",
|
|
1349
|
+
)
|
|
1350
|
+
elif parameters.get("outros_codigos") == "sem_desconto":
|
|
1351
|
+
discount = 0.0
|
|
1352
|
+
else:
|
|
1353
|
+
raise IndexDslError("E_INVALID_DISCOUNT", f"não há desconto configurado para {base.canonical_code!r}", path=path)
|
|
1354
|
+
if not 0 <= discount <= 1:
|
|
1355
|
+
raise IndexDslError("E_INVALID_DISCOUNT", "coeficiente deve estar em [0,1]", path=path)
|
|
1356
|
+
result = base.value - (1.0 - factor) * discount
|
|
1357
|
+
diagnostics = {
|
|
1358
|
+
"base_code": base.canonical_code,
|
|
1359
|
+
"base": base.value,
|
|
1360
|
+
"detail_factor": factor,
|
|
1361
|
+
"discount": discount,
|
|
1362
|
+
}
|
|
1363
|
+
return _operation_result(result, parameters, diagnostics, path=path)
|
|
1364
|
+
|
|
1365
|
+
|
|
1366
|
+
def _resolved_reference(prepared: PreparedInput, path: str) -> ResolvedReference:
|
|
1367
|
+
try:
|
|
1368
|
+
return prepared.resolved_references[path]
|
|
1369
|
+
except KeyError as exc:
|
|
1370
|
+
raise IndexDslError("E_INPUT_REFERENCE_UNRESOLVED", "referência de entrada não foi resolvida", path=path) from exc
|
|
1371
|
+
|
|
1372
|
+
|
|
1373
|
+
def _reference_numeric_value(
|
|
1374
|
+
compiled: CompiledIndex,
|
|
1375
|
+
prepared: PreparedInput,
|
|
1376
|
+
record: PreparedRecord,
|
|
1377
|
+
reference: ComponentReference,
|
|
1378
|
+
*,
|
|
1379
|
+
path: str,
|
|
1380
|
+
node_scores: Mapping[str, float],
|
|
1381
|
+
converter_name: str | None,
|
|
1382
|
+
empty_policy: str | None = None,
|
|
1383
|
+
) -> ConvertedValue | float:
|
|
1384
|
+
if reference.kind == "node":
|
|
1385
|
+
if reference.target_node not in node_scores:
|
|
1386
|
+
raise IndexDslError("E_GRAPH_ORDER", f"nó {reference.target_node!r} ainda não foi calculado", path=path)
|
|
1387
|
+
return node_scores[reference.target_node]
|
|
1388
|
+
if reference.kind == "selected_question":
|
|
1389
|
+
raise IndexDslError("E_OPERATION_INPUT", "seletor só pode ser consumido por uma regra de detalhes", path=path)
|
|
1390
|
+
resolved = _resolved_reference(prepared, path)
|
|
1391
|
+
if resolved.column is None:
|
|
1392
|
+
raise IndexDslError("E_INPUT_REFERENCE_UNRESOLVED", "referência não possui coluna física resolvida", path=path)
|
|
1393
|
+
raw = record.values[resolved.column]
|
|
1394
|
+
if converter_name is not None:
|
|
1395
|
+
return convert_value(
|
|
1396
|
+
compiled,
|
|
1397
|
+
converter_name,
|
|
1398
|
+
raw,
|
|
1399
|
+
column=resolved.column,
|
|
1400
|
+
empty_policy=empty_policy,
|
|
1401
|
+
path=path,
|
|
1402
|
+
)
|
|
1403
|
+
return validate_external_score(raw, column=resolved.column, path=path)
|
|
1404
|
+
|
|
1405
|
+
|
|
1406
|
+
def _discount_factor_for_reference(
|
|
1407
|
+
compiled: CompiledIndex,
|
|
1408
|
+
prepared: PreparedInput,
|
|
1409
|
+
record: PreparedRecord,
|
|
1410
|
+
reference: ComponentReference,
|
|
1411
|
+
*,
|
|
1412
|
+
path: str,
|
|
1413
|
+
details: Mapping[str, Any],
|
|
1414
|
+
) -> tuple[float | None, Mapping[str, ConvertedValue]]:
|
|
1415
|
+
resolved = _resolved_reference(prepared, path)
|
|
1416
|
+
if reference.kind == "selected_question":
|
|
1417
|
+
if reference.selector is None:
|
|
1418
|
+
raise IndexDslError("E_SELECTOR_SYNTAX", "seletor ausente na referência da questão", path=path)
|
|
1419
|
+
converted = {
|
|
1420
|
+
item: convert_value(
|
|
1421
|
+
compiled,
|
|
1422
|
+
details["conversor"],
|
|
1423
|
+
record.values[column],
|
|
1424
|
+
column=column,
|
|
1425
|
+
empty_policy=details.get("vazio"),
|
|
1426
|
+
path=f"{path}.detalhes.{item}",
|
|
1427
|
+
)
|
|
1428
|
+
for item, column in resolved.detail_columns.items()
|
|
1429
|
+
}
|
|
1430
|
+
item_scores = {item: value.value for item, value in converted.items()}
|
|
1431
|
+
return score_selector(reference.selector, item_scores), MappingProxyType(converted)
|
|
1432
|
+
|
|
1433
|
+
if reference.kind != "input":
|
|
1434
|
+
raise IndexDslError("E_OPERATION_INPUT", "desconto exige uma questão-base, com ou sem seletor", path=path)
|
|
1435
|
+
if not resolved.detail_columns:
|
|
1436
|
+
return None, MappingProxyType({})
|
|
1437
|
+
converted = {
|
|
1438
|
+
item: convert_value(
|
|
1439
|
+
compiled,
|
|
1440
|
+
details["conversor"],
|
|
1441
|
+
record.values[column],
|
|
1442
|
+
column=column,
|
|
1443
|
+
empty_policy=details.get("vazio"),
|
|
1444
|
+
path=f"{path}.detalhes.{item}",
|
|
1445
|
+
)
|
|
1446
|
+
for item, column in resolved.detail_columns.items()
|
|
1447
|
+
}
|
|
1448
|
+
return math.fsum(value.value for value in converted.values()) / len(converted), MappingProxyType(converted)
|
|
1449
|
+
|
|
1450
|
+
|
|
1451
|
+
def _converted_trace(value: ConvertedValue) -> Mapping[str, Any]:
|
|
1452
|
+
return MappingProxyType(
|
|
1453
|
+
{
|
|
1454
|
+
"column": value.column,
|
|
1455
|
+
"code": value.canonical_code,
|
|
1456
|
+
"value": value.value,
|
|
1457
|
+
"origin": value.origin,
|
|
1458
|
+
"empty": value.empty,
|
|
1459
|
+
}
|
|
1460
|
+
)
|
|
1461
|
+
|
|
1462
|
+
|
|
1463
|
+
def _evaluate_discount_reference(
|
|
1464
|
+
compiled: CompiledIndex,
|
|
1465
|
+
prepared: PreparedInput,
|
|
1466
|
+
record: PreparedRecord,
|
|
1467
|
+
reference: ComponentReference,
|
|
1468
|
+
parameters: Mapping[str, Any],
|
|
1469
|
+
*,
|
|
1470
|
+
path: str,
|
|
1471
|
+
) -> OperationResult:
|
|
1472
|
+
if reference.kind == "node":
|
|
1473
|
+
raise IndexDslError("E_OPERATION_INPUT", "desconto_proporcional exige uma questão-base bruta", path=path)
|
|
1474
|
+
resolved = _resolved_reference(prepared, path)
|
|
1475
|
+
if resolved.column is None:
|
|
1476
|
+
raise IndexDslError("E_INPUT_REFERENCE_UNRESOLVED", "questão-base sem coluna física", path=path)
|
|
1477
|
+
base = convert_value(
|
|
1478
|
+
compiled,
|
|
1479
|
+
parameters["conversor"],
|
|
1480
|
+
record.values[resolved.column],
|
|
1481
|
+
column=resolved.column,
|
|
1482
|
+
path=path,
|
|
1483
|
+
)
|
|
1484
|
+
details = parameters["detalhes"]
|
|
1485
|
+
factor, detail_values = _discount_factor_for_reference(
|
|
1486
|
+
compiled,
|
|
1487
|
+
prepared,
|
|
1488
|
+
record,
|
|
1489
|
+
reference,
|
|
1490
|
+
path=path,
|
|
1491
|
+
details=details,
|
|
1492
|
+
)
|
|
1493
|
+
result = execute_operation("desconto_proporcional", [base], parameters, detail_factor=factor, path=path)
|
|
1494
|
+
diagnostics = dict(result.diagnostics)
|
|
1495
|
+
diagnostics["base_column"] = base.column
|
|
1496
|
+
diagnostics["base_origin"] = base.origin
|
|
1497
|
+
diagnostics["detail_values"] = MappingProxyType(
|
|
1498
|
+
{item: _converted_trace(value) for item, value in detail_values.items()}
|
|
1499
|
+
)
|
|
1500
|
+
return OperationResult(
|
|
1501
|
+
result.value,
|
|
1502
|
+
result.before_range,
|
|
1503
|
+
result.applied_range,
|
|
1504
|
+
MappingProxyType(diagnostics),
|
|
1505
|
+
)
|
|
1506
|
+
|
|
1507
|
+
|
|
1508
|
+
def _evaluate_component_rule(
|
|
1509
|
+
compiled: CompiledIndex,
|
|
1510
|
+
prepared: PreparedInput,
|
|
1511
|
+
record: PreparedRecord,
|
|
1512
|
+
reference: ComponentReference,
|
|
1513
|
+
rule: Mapping[str, Any],
|
|
1514
|
+
*,
|
|
1515
|
+
path: str,
|
|
1516
|
+
node_scores: Mapping[str, float],
|
|
1517
|
+
) -> tuple[float, OperationResult | None]:
|
|
1518
|
+
if reference.kind == "node":
|
|
1519
|
+
if reference.target_node not in node_scores:
|
|
1520
|
+
raise IndexDslError("E_GRAPH_ORDER", f"nó {reference.target_node!r} ainda não foi calculado", path=path)
|
|
1521
|
+
return node_scores[reference.target_node], None
|
|
1522
|
+
if rule["operacao"] == "desconto_proporcional":
|
|
1523
|
+
result = _evaluate_discount_reference(
|
|
1524
|
+
compiled,
|
|
1525
|
+
prepared,
|
|
1526
|
+
record,
|
|
1527
|
+
reference,
|
|
1528
|
+
rule,
|
|
1529
|
+
path=path,
|
|
1530
|
+
)
|
|
1531
|
+
return result.value, result
|
|
1532
|
+
value = _reference_numeric_value(
|
|
1533
|
+
compiled,
|
|
1534
|
+
prepared,
|
|
1535
|
+
record,
|
|
1536
|
+
reference,
|
|
1537
|
+
path=path,
|
|
1538
|
+
node_scores=node_scores,
|
|
1539
|
+
converter_name=rule.get("conversor"),
|
|
1540
|
+
empty_policy=rule.get("vazio"),
|
|
1541
|
+
)
|
|
1542
|
+
result = execute_operation(rule["operacao"], [value], rule, weights=[1.0], path=path)
|
|
1543
|
+
return result.value, result
|
|
1544
|
+
|
|
1545
|
+
|
|
1546
|
+
def _component_trace(
|
|
1547
|
+
prepared: PreparedInput,
|
|
1548
|
+
reference: ComponentReference,
|
|
1549
|
+
*,
|
|
1550
|
+
path: str,
|
|
1551
|
+
value: Any,
|
|
1552
|
+
weight: float,
|
|
1553
|
+
rule_result: OperationResult | None = None,
|
|
1554
|
+
) -> ComponentTrace:
|
|
1555
|
+
resolved = _resolved_reference(prepared, path)
|
|
1556
|
+
if isinstance(value, ConvertedValue):
|
|
1557
|
+
score = value.value
|
|
1558
|
+
canonical_code = value.canonical_code
|
|
1559
|
+
origin = value.origin
|
|
1560
|
+
input_column = value.column
|
|
1561
|
+
else:
|
|
1562
|
+
score = float(value)
|
|
1563
|
+
diagnostics = rule_result.diagnostics if rule_result is not None else {}
|
|
1564
|
+
canonical_code = diagnostics.get("base_code", diagnostics.get("code"))
|
|
1565
|
+
origin = diagnostics.get("base_origin", diagnostics.get("origin"))
|
|
1566
|
+
input_column = diagnostics.get("base_column", resolved.column)
|
|
1567
|
+
return ComponentTrace(
|
|
1568
|
+
reference=reference,
|
|
1569
|
+
input_column=input_column,
|
|
1570
|
+
detail_columns=resolved.detail_columns,
|
|
1571
|
+
value=score,
|
|
1572
|
+
canonical_code=canonical_code,
|
|
1573
|
+
origin=origin,
|
|
1574
|
+
weight=weight,
|
|
1575
|
+
rule_result=rule_result,
|
|
1576
|
+
)
|
|
1577
|
+
|
|
1578
|
+
|
|
1579
|
+
def _evaluate_index_row(compiled: CompiledIndex, prepared: PreparedInput, record: PreparedRecord) -> RowEvaluation:
|
|
1580
|
+
"""Execute every compiled node for one already-filtered organization row."""
|
|
1581
|
+
scores: dict[str, float] = {}
|
|
1582
|
+
operations: dict[str, OperationResult] = {}
|
|
1583
|
+
traces: dict[str, NodeTrace] = {}
|
|
1584
|
+
for node_id in compiled.evaluation_order:
|
|
1585
|
+
node = compiled.nodes[node_id]
|
|
1586
|
+
node_path = f"$.calculo.{node_id}"
|
|
1587
|
+
if node.operation == "desconto_proporcional":
|
|
1588
|
+
reference = node.components[0].reference
|
|
1589
|
+
reference_path = f"{node_path}.componentes[0]"
|
|
1590
|
+
result = _evaluate_discount_reference(
|
|
1591
|
+
compiled,
|
|
1592
|
+
prepared,
|
|
1593
|
+
record,
|
|
1594
|
+
reference,
|
|
1595
|
+
node.parameters,
|
|
1596
|
+
path=reference_path,
|
|
1597
|
+
)
|
|
1598
|
+
component_traces = (
|
|
1599
|
+
_component_trace(
|
|
1600
|
+
prepared,
|
|
1601
|
+
reference,
|
|
1602
|
+
path=reference_path,
|
|
1603
|
+
value=result.value,
|
|
1604
|
+
weight=node.components[0].weight,
|
|
1605
|
+
rule_result=result,
|
|
1606
|
+
),
|
|
1607
|
+
)
|
|
1608
|
+
exclusive_trace = None
|
|
1609
|
+
elif node.operation == "mapeamento":
|
|
1610
|
+
reference = node.components[0].reference
|
|
1611
|
+
reference_path = f"{node_path}.componentes[0]"
|
|
1612
|
+
value = _reference_numeric_value(
|
|
1613
|
+
compiled,
|
|
1614
|
+
prepared,
|
|
1615
|
+
record,
|
|
1616
|
+
reference,
|
|
1617
|
+
path=reference_path,
|
|
1618
|
+
node_scores=scores,
|
|
1619
|
+
converter_name=node.parameters.get("conversor"),
|
|
1620
|
+
empty_policy=node.parameters.get("vazio"),
|
|
1621
|
+
)
|
|
1622
|
+
result = execute_operation("mapeamento", [value], node.parameters, path=node_path)
|
|
1623
|
+
component_traces = (
|
|
1624
|
+
_component_trace(
|
|
1625
|
+
prepared,
|
|
1626
|
+
reference,
|
|
1627
|
+
path=reference_path,
|
|
1628
|
+
value=value,
|
|
1629
|
+
weight=node.components[0].weight,
|
|
1630
|
+
),
|
|
1631
|
+
)
|
|
1632
|
+
exclusive_trace = None
|
|
1633
|
+
else:
|
|
1634
|
+
values: list[ConvertedValue | float] = []
|
|
1635
|
+
component_traces_list: list[ComponentTrace] = []
|
|
1636
|
+
for index, component in enumerate(node.components):
|
|
1637
|
+
reference = component.reference
|
|
1638
|
+
reference_path = f"{node_path}.componentes[{index}]"
|
|
1639
|
+
rule_result = None
|
|
1640
|
+
if reference.kind == "node":
|
|
1641
|
+
value = _reference_numeric_value(
|
|
1642
|
+
compiled,
|
|
1643
|
+
prepared,
|
|
1644
|
+
record,
|
|
1645
|
+
reference,
|
|
1646
|
+
path=reference_path,
|
|
1647
|
+
node_scores=scores,
|
|
1648
|
+
converter_name=None,
|
|
1649
|
+
)
|
|
1650
|
+
elif node.component_rule is not None:
|
|
1651
|
+
value, rule_result = _evaluate_component_rule(
|
|
1652
|
+
compiled,
|
|
1653
|
+
prepared,
|
|
1654
|
+
record,
|
|
1655
|
+
reference,
|
|
1656
|
+
node.component_rule,
|
|
1657
|
+
path=reference_path,
|
|
1658
|
+
node_scores=scores,
|
|
1659
|
+
)
|
|
1660
|
+
else:
|
|
1661
|
+
value = _reference_numeric_value(
|
|
1662
|
+
compiled,
|
|
1663
|
+
prepared,
|
|
1664
|
+
record,
|
|
1665
|
+
reference,
|
|
1666
|
+
path=reference_path,
|
|
1667
|
+
node_scores=scores,
|
|
1668
|
+
converter_name=node.parameters.get("conversor"),
|
|
1669
|
+
)
|
|
1670
|
+
values.append(value)
|
|
1671
|
+
component_traces_list.append(
|
|
1672
|
+
_component_trace(
|
|
1673
|
+
prepared,
|
|
1674
|
+
reference,
|
|
1675
|
+
path=reference_path,
|
|
1676
|
+
value=value,
|
|
1677
|
+
weight=component.weight,
|
|
1678
|
+
rule_result=rule_result,
|
|
1679
|
+
)
|
|
1680
|
+
)
|
|
1681
|
+
|
|
1682
|
+
exclusive = None
|
|
1683
|
+
exclusive_trace = None
|
|
1684
|
+
if "exclusiva_negativa" in node.parameter_references:
|
|
1685
|
+
negative_reference = node.parameter_references["exclusiva_negativa"]
|
|
1686
|
+
negative_path = f"{node_path}.exclusiva_negativa"
|
|
1687
|
+
exclusive = _reference_numeric_value(
|
|
1688
|
+
compiled,
|
|
1689
|
+
prepared,
|
|
1690
|
+
record,
|
|
1691
|
+
negative_reference,
|
|
1692
|
+
path=negative_path,
|
|
1693
|
+
node_scores=scores,
|
|
1694
|
+
converter_name=node.parameters.get("conversor"),
|
|
1695
|
+
)
|
|
1696
|
+
exclusive_trace = _component_trace(
|
|
1697
|
+
prepared,
|
|
1698
|
+
negative_reference,
|
|
1699
|
+
path=negative_path,
|
|
1700
|
+
value=exclusive,
|
|
1701
|
+
weight=0.0,
|
|
1702
|
+
)
|
|
1703
|
+
result = execute_operation(
|
|
1704
|
+
node.operation,
|
|
1705
|
+
values,
|
|
1706
|
+
node.parameters,
|
|
1707
|
+
weights=[component.weight for component in node.components],
|
|
1708
|
+
exclusive=exclusive,
|
|
1709
|
+
path=node_path,
|
|
1710
|
+
)
|
|
1711
|
+
component_traces = tuple(component_traces_list)
|
|
1712
|
+
scores[node_id] = result.value
|
|
1713
|
+
operations[node_id] = result
|
|
1714
|
+
traces[node_id] = NodeTrace(
|
|
1715
|
+
node_id=node_id,
|
|
1716
|
+
operation=node.operation,
|
|
1717
|
+
rule_name=node.rule_name,
|
|
1718
|
+
component_rule_name=node.component_rule_name,
|
|
1719
|
+
components=component_traces,
|
|
1720
|
+
exclusive_negative=exclusive_trace,
|
|
1721
|
+
result=result,
|
|
1722
|
+
)
|
|
1723
|
+
root_value = scores[compiled.metadata["raiz"]]
|
|
1724
|
+
classification = classify_maturity(root_value, compiled.maturity, path=f"$.calculo.{compiled.metadata['raiz']}")
|
|
1725
|
+
return RowEvaluation(
|
|
1726
|
+
record.organization,
|
|
1727
|
+
MappingProxyType(scores),
|
|
1728
|
+
MappingProxyType(operations),
|
|
1729
|
+
MappingProxyType(traces),
|
|
1730
|
+
classification,
|
|
1731
|
+
)
|
|
1732
|
+
|
|
1733
|
+
|
|
1734
|
+
def evaluate_index_row(compiled: CompiledIndex, prepared: PreparedInput, record: PreparedRecord) -> RowEvaluation:
|
|
1735
|
+
"""Execute an organization and attach its identity to any input/calculation error."""
|
|
1736
|
+
try:
|
|
1737
|
+
return _evaluate_index_row(compiled, prepared, record)
|
|
1738
|
+
except IndexDslError as exc:
|
|
1739
|
+
raise IndexDslError(
|
|
1740
|
+
exc.code,
|
|
1741
|
+
f"organização {record.organization!r}: {exc.message}",
|
|
1742
|
+
path=exc.path,
|
|
1743
|
+
) from exc
|
|
1744
|
+
|
|
1745
|
+
|
|
1746
|
+
def _validate_input_declarations(entry: Mapping[str, Any]) -> None:
|
|
1747
|
+
for key in ("localizadores", "contratos_detalhes"):
|
|
1748
|
+
declarations = entry.get(key, {})
|
|
1749
|
+
for name in declarations:
|
|
1750
|
+
if not isinstance(name, str) or not name.strip():
|
|
1751
|
+
raise IndexDslError("E_SCHEMA_INVALID", "nomes de declaração devem ser strings não vazias", path=f"$.entrada.{key}")
|
|
1752
|
+
for name, locator in entry.get("localizadores", {}).items():
|
|
1753
|
+
for index, pattern in enumerate(locator.get("padroes", [])):
|
|
1754
|
+
if pattern.count("{questao}") != 1 or pattern.count("{item}") != 1:
|
|
1755
|
+
raise IndexDslError(
|
|
1756
|
+
"E_LOCATOR_TEMPLATE",
|
|
1757
|
+
"cada padrão deve conter {questao} e {item} exatamente uma vez",
|
|
1758
|
+
path=f"$.entrada.localizadores.{name}.padroes[{index}]",
|
|
1759
|
+
)
|
|
1760
|
+
stripped = pattern.replace("{questao}", "").replace("{item}", "")
|
|
1761
|
+
if "{" in stripped or "}" in stripped:
|
|
1762
|
+
raise IndexDslError("E_LOCATOR_TEMPLATE", "placeholder desconhecido no padrão", path=f"$.entrada.localizadores.{name}.padroes[{index}]")
|
|
1763
|
+
try:
|
|
1764
|
+
re.compile(locator["item_regex"])
|
|
1765
|
+
for index, expression in enumerate(locator.get("ignorar_colunas_regex", [])):
|
|
1766
|
+
re.compile(expression)
|
|
1767
|
+
except re.error as exc:
|
|
1768
|
+
raise IndexDslError("E_LOCATOR_REGEX", str(exc), path=f"$.entrada.localizadores.{name}") from exc
|
|
1769
|
+
|
|
1770
|
+
for name, contract in entry.get("contratos_detalhes", {}).items():
|
|
1771
|
+
items_by_question = contract["itens_por_questao"]
|
|
1772
|
+
if not items_by_question:
|
|
1773
|
+
raise IndexDslError("E_DETAIL_CONTRACT_INVALID", "o contrato precisa declarar ao menos uma questão", path=f"$.entrada.contratos_detalhes.{name}")
|
|
1774
|
+
for question, items in items_by_question.items():
|
|
1775
|
+
if not isinstance(question, str) or not question:
|
|
1776
|
+
raise IndexDslError("E_DETAIL_CONTRACT_INVALID", "identificador de questão inválido", path=f"$.entrada.contratos_detalhes.{name}.itens_por_questao")
|
|
1777
|
+
if len(items) != len(set(items)):
|
|
1778
|
+
raise IndexDslError("E_DETAIL_CONTRACT_INVALID", f"itens repetidos em {question}", path=f"$.entrada.contratos_detalhes.{name}.itens_por_questao.{question}")
|
|
1779
|
+
|
|
1780
|
+
|
|
1781
|
+
def _validate_operation_parameters(operation: str, parameters: Mapping[str, Any], *, path: str) -> None:
|
|
1782
|
+
fields = {
|
|
1783
|
+
"mapeamento": {"componente", "conversor", "localizador", "range", "vazio"},
|
|
1784
|
+
"media_ponderada": {"conversor", "range", "componente_ausente"},
|
|
1785
|
+
"media_binaria": {"conversor", "range", "exclusiva_negativa", "contradicao_exclusiva", "coluna_ausente"},
|
|
1786
|
+
"soma_ponderada": {"range", "componente_ausente", "tolerancia_soma_pesos"},
|
|
1787
|
+
"desconto_proporcional": {"componente", "conversor", "detalhes", "desconto_por_codigo", "outros_codigos", "range"},
|
|
1788
|
+
}
|
|
1789
|
+
allowed = fields[operation] | ({"operacao"} if path.startswith("$.regras.") else set())
|
|
1790
|
+
inappropriate = set(parameters) - allowed
|
|
1791
|
+
if inappropriate:
|
|
1792
|
+
key = sorted(inappropriate)[0]
|
|
1793
|
+
raise IndexDslError("E_OPERATION_ATTRIBUTE", f"{key!r} não se aplica à operação {operation!r}", path=f"{path}.{key}")
|
|
1794
|
+
|
|
1795
|
+
if operation in {"mapeamento", "media_binaria", "desconto_proporcional"} and not parameters.get("conversor"):
|
|
1796
|
+
raise IndexDslError("E_CONVERTER_UNKNOWN", f"{operation} exige conversor", path=f"{path}.conversor")
|
|
1797
|
+
if operation == "desconto_proporcional":
|
|
1798
|
+
for key in ("componente", "detalhes", "desconto_por_codigo", "outros_codigos"):
|
|
1799
|
+
if key not in parameters:
|
|
1800
|
+
raise IndexDslError("E_OPERATION_PARAMETER", f"{operation} exige {key}", path=f"{path}.{key}")
|
|
1801
|
+
details = parameters["detalhes"]
|
|
1802
|
+
for key in ("localizador", "conversor"):
|
|
1803
|
+
if key not in details:
|
|
1804
|
+
raise IndexDslError("E_OPERATION_PARAMETER", f"detalhes exige {key}", path=f"{path}.detalhes.{key}")
|
|
1805
|
+
if operation == "soma_ponderada" and "tolerancia_soma_pesos" in parameters:
|
|
1806
|
+
tolerance = parameters["tolerancia_soma_pesos"]
|
|
1807
|
+
if isinstance(tolerance, bool) or not isinstance(tolerance, Real) or not math.isfinite(float(tolerance)) or tolerance < 0:
|
|
1808
|
+
raise IndexDslError("E_INVALID_WEIGHT", "tolerância deve ser finita e não negativa", path=f"{path}.tolerancia_soma_pesos")
|
|
1809
|
+
if operation == "media_binaria" and not parameters.get("contradicao_exclusiva"):
|
|
1810
|
+
raise IndexDslError("E_OPERATION_PARAMETER", "media_binaria exige contradicao_exclusiva", path=f"{path}.contradicao_exclusiva")
|
|
1811
|
+
if "range" in parameters:
|
|
1812
|
+
bounds = parameters["range"]
|
|
1813
|
+
if len(bounds) != 2 or bounds[0] > bounds[1] or bounds[0] < 0 or bounds[1] > 1:
|
|
1814
|
+
raise IndexDslError("E_INVALID_RANGE", "range deve satisfazer 0 <= mínimo <= máximo <= 1", path=f"{path}.range")
|
|
1815
|
+
|
|
1816
|
+
|
|
1817
|
+
def _effective_node(
|
|
1818
|
+
node_id: str,
|
|
1819
|
+
raw_node: Mapping[str, Any],
|
|
1820
|
+
rules: Mapping[str, Mapping[str, Any]],
|
|
1821
|
+
) -> tuple[str, dict[str, Any], tuple[tuple[str, float], ...]]:
|
|
1822
|
+
path = f"$.calculo.{node_id}"
|
|
1823
|
+
if ("regra" in raw_node) == ("operacao" in raw_node):
|
|
1824
|
+
raise IndexDslError("E_NODE_OPERATION", "declare exatamente uma das propriedades regra ou operacao", path=path)
|
|
1825
|
+
|
|
1826
|
+
if "regra" in raw_node:
|
|
1827
|
+
rule_name = raw_node["regra"]
|
|
1828
|
+
if rule_name not in rules:
|
|
1829
|
+
raise IndexDslError("E_RULE_UNKNOWN", f"regra inexistente {rule_name!r}", path=f"{path}.regra")
|
|
1830
|
+
rule = rules[rule_name]
|
|
1831
|
+
operation = rule["operacao"]
|
|
1832
|
+
parameters = {key: deepcopy(value) for key, value in rule.items() if key != "operacao"}
|
|
1833
|
+
for key, value in raw_node.items():
|
|
1834
|
+
if key in {"regra", "componentes", "regra_componentes"}:
|
|
1835
|
+
continue
|
|
1836
|
+
parameters[key] = deepcopy(value)
|
|
1837
|
+
else:
|
|
1838
|
+
operation = raw_node["operacao"]
|
|
1839
|
+
parameters = {key: deepcopy(value) for key, value in raw_node.items() if key not in {"operacao", "componentes", "regra_componentes"}}
|
|
1840
|
+
|
|
1841
|
+
_validate_operation_parameters(operation, parameters, path=path)
|
|
1842
|
+
raw_components = raw_node["componentes"]
|
|
1843
|
+
if isinstance(raw_components, list):
|
|
1844
|
+
components = tuple((reference, 1.0) for reference in raw_components)
|
|
1845
|
+
else:
|
|
1846
|
+
components = tuple((reference, float(weight)) for reference, weight in raw_components.items())
|
|
1847
|
+
if operation == "mapeamento" and len(components) != 1:
|
|
1848
|
+
raise IndexDslError("E_COMPONENT_COUNT", "mapeamento exige exatamente um componente", path=f"{path}.componentes")
|
|
1849
|
+
if operation == "desconto_proporcional" and len(components) != 1:
|
|
1850
|
+
raise IndexDslError("E_COMPONENT_COUNT", "desconto_proporcional exige uma questão-base por nó", path=f"{path}.componentes")
|
|
1851
|
+
return operation, parameters, components
|
|
1852
|
+
|
|
1853
|
+
|
|
1854
|
+
def _topological_order(nodes: Mapping[str, CompiledNode]) -> tuple[str, ...]:
|
|
1855
|
+
state: dict[str, int] = {}
|
|
1856
|
+
stack: list[str] = []
|
|
1857
|
+
ordered: list[str] = []
|
|
1858
|
+
|
|
1859
|
+
def visit(node_id: str) -> None:
|
|
1860
|
+
current_state = state.get(node_id, 0)
|
|
1861
|
+
if current_state == 2:
|
|
1862
|
+
return
|
|
1863
|
+
if current_state == 1:
|
|
1864
|
+
start = stack.index(node_id)
|
|
1865
|
+
cycle = (*stack[start:], node_id)
|
|
1866
|
+
raise IndexDslError("E_GRAPH_CYCLE", "ciclo no grafo: " + " -> ".join(cycle), path=f"$.calculo.{node_id}")
|
|
1867
|
+
state[node_id] = 1
|
|
1868
|
+
stack.append(node_id)
|
|
1869
|
+
node = nodes[node_id]
|
|
1870
|
+
dependencies = [
|
|
1871
|
+
component.reference.target_node
|
|
1872
|
+
for component in node.components
|
|
1873
|
+
if component.reference.kind == "node"
|
|
1874
|
+
]
|
|
1875
|
+
dependencies.extend(
|
|
1876
|
+
reference.target_node
|
|
1877
|
+
for reference in node.parameter_references.values()
|
|
1878
|
+
if reference.kind == "node"
|
|
1879
|
+
)
|
|
1880
|
+
for dependency in dependencies:
|
|
1881
|
+
if dependency is not None:
|
|
1882
|
+
visit(dependency)
|
|
1883
|
+
stack.pop()
|
|
1884
|
+
state[node_id] = 2
|
|
1885
|
+
ordered.append(node_id)
|
|
1886
|
+
|
|
1887
|
+
for node_id in nodes:
|
|
1888
|
+
visit(node_id)
|
|
1889
|
+
return tuple(ordered)
|
|
1890
|
+
|
|
1891
|
+
|
|
1892
|
+
def _validate_semantics(document: Mapping[str, Any]) -> CompiledIndex:
|
|
1893
|
+
metadata = document["metadata"]
|
|
1894
|
+
entry = document["entrada"]
|
|
1895
|
+
converters = document["conversores"]
|
|
1896
|
+
rules = document["regras"]
|
|
1897
|
+
raw_nodes = document["calculo"]
|
|
1898
|
+
|
|
1899
|
+
for section_name, section in (("conversores", converters), ("regras", rules), ("calculo", raw_nodes)):
|
|
1900
|
+
if any(not isinstance(name, str) or not name.strip() for name in section):
|
|
1901
|
+
raise IndexDslError("E_SCHEMA_INVALID", "identificadores devem ser strings não vazias", path=f"$.{section_name}")
|
|
1902
|
+
for node_id in raw_nodes:
|
|
1903
|
+
if "{" in node_id or "}" in node_id:
|
|
1904
|
+
raise IndexDslError("E_NODE_ID", "chaves são reservadas ao seletor de referência", path=f"$.calculo.{node_id}")
|
|
1905
|
+
|
|
1906
|
+
if metadata["raiz"] not in raw_nodes:
|
|
1907
|
+
raise IndexDslError("E_ROOT_UNKNOWN", f"nó raiz inexistente {metadata['raiz']!r}", path="$.metadata.raiz")
|
|
1908
|
+
_validate_input_declarations(entry)
|
|
1909
|
+
converter_codes: dict[str, Mapping[str, str]] = {}
|
|
1910
|
+
converter_aliases: dict[str, Mapping[str, str]] = {}
|
|
1911
|
+
for name, converter in converters.items():
|
|
1912
|
+
_validate_converter(name, converter)
|
|
1913
|
+
converter_codes[name] = MappingProxyType({_normal(code): code for code in converter["valores"]})
|
|
1914
|
+
converter_aliases[name] = MappingProxyType(
|
|
1915
|
+
{_normal(alias): code for alias, code in converter.get("aliases", {}).items()}
|
|
1916
|
+
)
|
|
1917
|
+
|
|
1918
|
+
for rule_name, rule in rules.items():
|
|
1919
|
+
operation = rule["operacao"]
|
|
1920
|
+
path = f"$.regras.{rule_name}"
|
|
1921
|
+
_validate_operation_parameters(operation, rule, path=path)
|
|
1922
|
+
converter_name = rule.get("conversor")
|
|
1923
|
+
if converter_name is not None and converter_name not in converters:
|
|
1924
|
+
raise IndexDslError("E_CONVERTER_UNKNOWN", f"conversor inexistente {converter_name!r}", path=f"{path}.conversor")
|
|
1925
|
+
if rule.get("localizador") not in (None, *entry.get("localizadores", {})):
|
|
1926
|
+
raise IndexDslError("E_LOCATOR_UNKNOWN", f"localizador inexistente {rule['localizador']!r}", path=f"{path}.localizador")
|
|
1927
|
+
details = rule.get("detalhes", {})
|
|
1928
|
+
if details:
|
|
1929
|
+
locator = details.get("localizador")
|
|
1930
|
+
if locator not in entry.get("localizadores", {}):
|
|
1931
|
+
raise IndexDslError("E_LOCATOR_UNKNOWN", f"localizador inexistente {locator!r}", path=f"{path}.detalhes.localizador")
|
|
1932
|
+
detail_converter = details.get("conversor")
|
|
1933
|
+
if detail_converter not in converters:
|
|
1934
|
+
raise IndexDslError("E_CONVERTER_UNKNOWN", f"conversor inexistente {detail_converter!r}", path=f"{path}.detalhes.conversor")
|
|
1935
|
+
contract = details.get("contrato")
|
|
1936
|
+
if contract is not None and contract not in entry.get("contratos_detalhes", {}):
|
|
1937
|
+
raise IndexDslError("E_DETAIL_CONTRACT_UNKNOWN", f"contrato inexistente {contract!r}", path=f"{path}.detalhes.contrato")
|
|
1938
|
+
if operation == "desconto_proporcional":
|
|
1939
|
+
converter = converters[rule["conversor"]]
|
|
1940
|
+
codes = converter["valores"]
|
|
1941
|
+
for code, discount in rule["desconto_por_codigo"].items():
|
|
1942
|
+
if code not in codes:
|
|
1943
|
+
raise IndexDslError("E_CONVERTER_UNKNOWN", f"desconto referencia código canônico inexistente {code!r}", path=f"{path}.desconto_por_codigo.{code}")
|
|
1944
|
+
if isinstance(discount, bool) or not isinstance(discount, Real) or not math.isfinite(float(discount)) or not 0 <= discount <= 1:
|
|
1945
|
+
raise IndexDslError("E_INVALID_DISCOUNT", "coeficiente deve ser finito e estar em [0,1]", path=f"{path}.desconto_por_codigo.{code}")
|
|
1946
|
+
|
|
1947
|
+
compiled_nodes: dict[str, CompiledNode] = {}
|
|
1948
|
+
node_ids = set(raw_nodes)
|
|
1949
|
+
for node_id, raw_node in raw_nodes.items():
|
|
1950
|
+
operation, parameters, raw_components = _effective_node(node_id, raw_node, rules)
|
|
1951
|
+
converter_name = parameters.get("conversor")
|
|
1952
|
+
if converter_name is not None and converter_name not in converters:
|
|
1953
|
+
raise IndexDslError("E_CONVERTER_UNKNOWN", f"conversor inexistente {converter_name!r}", path=f"$.calculo.{node_id}.conversor")
|
|
1954
|
+
locator = parameters.get("localizador")
|
|
1955
|
+
if locator is not None and locator not in entry.get("localizadores", {}):
|
|
1956
|
+
raise IndexDslError("E_LOCATOR_UNKNOWN", f"localizador inexistente {locator!r}", path=f"$.calculo.{node_id}.localizador")
|
|
1957
|
+
if "regra_componentes" in raw_node and raw_node["regra_componentes"] not in rules:
|
|
1958
|
+
raise IndexDslError("E_RULE_UNKNOWN", f"regra de componentes inexistente {raw_node['regra_componentes']!r}", path=f"$.calculo.{node_id}.regra_componentes")
|
|
1959
|
+
if operation == "desconto_proporcional":
|
|
1960
|
+
details = parameters["detalhes"]
|
|
1961
|
+
converter = converters[parameters["conversor"]]
|
|
1962
|
+
for code in parameters["desconto_por_codigo"]:
|
|
1963
|
+
if code not in converter["valores"]:
|
|
1964
|
+
raise IndexDslError("E_CONVERTER_UNKNOWN", f"desconto referencia código inexistente {code!r}", path=f"$.calculo.{node_id}.desconto_por_codigo.{code}")
|
|
1965
|
+
if details["localizador"] not in entry.get("localizadores", {}):
|
|
1966
|
+
raise IndexDslError("E_LOCATOR_UNKNOWN", f"localizador inexistente {details['localizador']!r}", path=f"$.calculo.{node_id}.detalhes.localizador")
|
|
1967
|
+
if details["conversor"] not in converters:
|
|
1968
|
+
raise IndexDslError("E_CONVERTER_UNKNOWN", f"conversor inexistente {details['conversor']!r}", path=f"$.calculo.{node_id}.detalhes.conversor")
|
|
1969
|
+
contract = details.get("contrato")
|
|
1970
|
+
if contract is not None and contract not in entry.get("contratos_detalhes", {}):
|
|
1971
|
+
raise IndexDslError("E_DETAIL_CONTRACT_UNKNOWN", f"contrato inexistente {contract!r}", path=f"$.calculo.{node_id}.detalhes.contrato")
|
|
1972
|
+
|
|
1973
|
+
components: list[WeightedComponent] = []
|
|
1974
|
+
for raw_reference, weight in raw_components:
|
|
1975
|
+
if not isinstance(raw_reference, str) or not raw_reference.strip():
|
|
1976
|
+
raise IndexDslError("E_COMPONENT_INVALID", "referências devem ser strings não vazias", path=f"$.calculo.{node_id}.componentes")
|
|
1977
|
+
if not math.isfinite(weight) or weight < 0:
|
|
1978
|
+
raise IndexDslError("E_INVALID_WEIGHT", "pesos devem ser finitos e não negativos", path=f"$.calculo.{node_id}.componentes.{raw_reference}")
|
|
1979
|
+
reference = _resolve_reference(raw_reference, node_ids, path=f"$.calculo.{node_id}.componentes.{raw_reference}")
|
|
1980
|
+
components.append(WeightedComponent(reference, weight))
|
|
1981
|
+
try:
|
|
1982
|
+
total_weight_decimal = sum((Decimal(str(component.weight)) for component in components), Decimal(0))
|
|
1983
|
+
total_weight = math.fsum(component.weight for component in components)
|
|
1984
|
+
except (InvalidOperation, OverflowError) as exc:
|
|
1985
|
+
raise IndexDslError("E_INVALID_WEIGHT", "soma dos pesos não é finita", path=f"$.calculo.{node_id}.componentes") from exc
|
|
1986
|
+
if not total_weight_decimal.is_finite() or not math.isfinite(total_weight):
|
|
1987
|
+
raise IndexDslError("E_INVALID_WEIGHT", "soma dos pesos não é finita", path=f"$.calculo.{node_id}.componentes")
|
|
1988
|
+
if operation in {"media_ponderada", "soma_ponderada"} and total_weight_decimal <= 0:
|
|
1989
|
+
raise IndexDslError("E_INVALID_WEIGHT", "a soma dos pesos deve ser positiva", path=f"$.calculo.{node_id}.componentes")
|
|
1990
|
+
tolerance = parameters.get("tolerancia_soma_pesos")
|
|
1991
|
+
if tolerance is not None and abs(total_weight_decimal - Decimal(1)) > Decimal(str(tolerance)):
|
|
1992
|
+
raise IndexDslError("E_WEIGHT_SUM", "a soma dos pesos excede tolerancia_soma_pesos", path=f"$.calculo.{node_id}.componentes")
|
|
1993
|
+
parameter_references: dict[str, ComponentReference] = {}
|
|
1994
|
+
if "exclusiva_negativa" in parameters:
|
|
1995
|
+
reference = _resolve_reference(
|
|
1996
|
+
parameters["exclusiva_negativa"],
|
|
1997
|
+
node_ids,
|
|
1998
|
+
path=f"$.calculo.{node_id}.exclusiva_negativa",
|
|
1999
|
+
)
|
|
2000
|
+
if reference.kind == "selected_question":
|
|
2001
|
+
raise IndexDslError("E_COMPONENT_INVALID", "exclusiva_negativa deve apontar para uma única opção", path=f"$.calculo.{node_id}.exclusiva_negativa")
|
|
2002
|
+
parameter_references["exclusiva_negativa"] = reference
|
|
2003
|
+
compiled_nodes[node_id] = CompiledNode(
|
|
2004
|
+
node_id,
|
|
2005
|
+
operation,
|
|
2006
|
+
_freeze(parameters),
|
|
2007
|
+
tuple(components),
|
|
2008
|
+
MappingProxyType(parameter_references),
|
|
2009
|
+
_freeze(rules[raw_node["regra_componentes"]]) if "regra_componentes" in raw_node else None,
|
|
2010
|
+
raw_node.get("regra"),
|
|
2011
|
+
raw_node.get("regra_componentes"),
|
|
2012
|
+
)
|
|
2013
|
+
|
|
2014
|
+
evaluation_order = _topological_order(compiled_nodes)
|
|
2015
|
+
|
|
2016
|
+
maturity = document.get("maturidade", [])
|
|
2017
|
+
names: set[str] = set()
|
|
2018
|
+
for index, band in enumerate(maturity):
|
|
2019
|
+
path = f"$.maturidade[{index}]"
|
|
2020
|
+
if band["nome"] in names:
|
|
2021
|
+
raise IndexDslError("E_MATURITY_INVALID", f"nome de faixa repetido {band['nome']!r}", path=f"{path}.nome")
|
|
2022
|
+
names.add(band["nome"])
|
|
2023
|
+
lower, upper = band["min"], band["max"]
|
|
2024
|
+
if not math.isfinite(float(lower)) or not math.isfinite(float(upper)) or not 0 <= lower < upper <= 1:
|
|
2025
|
+
raise IndexDslError("E_MATURITY_INVALID", "faixa deve satisfazer 0 <= min < max <= 1", path=path)
|
|
2026
|
+
for first_index, first in enumerate(maturity):
|
|
2027
|
+
for second_index in range(first_index + 1, len(maturity)):
|
|
2028
|
+
second = maturity[second_index]
|
|
2029
|
+
overlap_start = max(first["min"], second["min"])
|
|
2030
|
+
overlap_end = min(first["max"], second["max"])
|
|
2031
|
+
overlap = overlap_start < overlap_end
|
|
2032
|
+
if overlap_start == overlap_end:
|
|
2033
|
+
first_includes = (
|
|
2034
|
+
(overlap_start > first["min"] or first["inclui_min"])
|
|
2035
|
+
and (overlap_start < first["max"] or first["inclui_max"])
|
|
2036
|
+
)
|
|
2037
|
+
second_includes = (
|
|
2038
|
+
(overlap_start > second["min"] or second["inclui_min"])
|
|
2039
|
+
and (overlap_start < second["max"] or second["inclui_max"])
|
|
2040
|
+
)
|
|
2041
|
+
overlap = first_includes and second_includes
|
|
2042
|
+
if overlap:
|
|
2043
|
+
raise IndexDslError(
|
|
2044
|
+
"E_MATURITY_OVERLAP",
|
|
2045
|
+
f"faixas {first['nome']!r} e {second['nome']!r} se sobrepõem",
|
|
2046
|
+
path=f"$.maturidade[{second_index}]",
|
|
2047
|
+
)
|
|
2048
|
+
maturity_gaps = _maturity_gaps(maturity)
|
|
2049
|
+
|
|
2050
|
+
frozen_document = _freeze(deepcopy(dict(document)))
|
|
2051
|
+
return CompiledIndex(
|
|
2052
|
+
document=frozen_document,
|
|
2053
|
+
metadata=frozen_document["metadata"],
|
|
2054
|
+
entry=frozen_document["entrada"],
|
|
2055
|
+
converters=frozen_document["conversores"],
|
|
2056
|
+
converter_codes=MappingProxyType(converter_codes),
|
|
2057
|
+
converter_aliases=MappingProxyType(converter_aliases),
|
|
2058
|
+
rules=frozen_document["regras"],
|
|
2059
|
+
nodes=MappingProxyType(compiled_nodes),
|
|
2060
|
+
evaluation_order=evaluation_order,
|
|
2061
|
+
maturity=tuple(_freeze(item) for item in maturity),
|
|
2062
|
+
maturity_gaps=maturity_gaps,
|
|
2063
|
+
)
|
|
2064
|
+
|
|
2065
|
+
|
|
2066
|
+
def compile_index(document: Mapping[str, Any]) -> CompiledIndex:
|
|
2067
|
+
"""Validate structure and static references, then return an immutable index."""
|
|
2068
|
+
if not isinstance(document, Mapping):
|
|
2069
|
+
raise IndexDslError("E_SCHEMA_INVALID", "a definição deve ser um objeto YAML/JSON")
|
|
2070
|
+
_find_nonfinite(document)
|
|
2071
|
+
safe_document = deepcopy(dict(document))
|
|
2072
|
+
if "formato" not in safe_document:
|
|
2073
|
+
raise IndexDslError(
|
|
2074
|
+
"E_FORMAT_REQUIRED",
|
|
2075
|
+
"configuração antiga não é aceita; converta a definição para formato: argos-index-dsl/v1",
|
|
2076
|
+
)
|
|
2077
|
+
errors = sorted(
|
|
2078
|
+
Draft202012Validator(_schema()).iter_errors(safe_document),
|
|
2079
|
+
key=lambda error: (tuple(str(part) for part in error.absolute_path), error.message),
|
|
2080
|
+
)
|
|
2081
|
+
if errors:
|
|
2082
|
+
raise _schema_error(errors[0])
|
|
2083
|
+
return _validate_semantics(safe_document)
|
|
2084
|
+
|
|
2085
|
+
|
|
2086
|
+
def load_index_yaml(path: Path | str) -> CompiledIndex:
|
|
2087
|
+
"""Load UTF-8 YAML, reject duplicate keys and compile the definition."""
|
|
2088
|
+
source = Path(path)
|
|
2089
|
+
try:
|
|
2090
|
+
document = _load_unique_yaml(source.read_text(encoding="utf-8"))
|
|
2091
|
+
except ConstructorError as exc:
|
|
2092
|
+
message = str(exc.problem or exc)
|
|
2093
|
+
if "duplicate key" in message:
|
|
2094
|
+
raise IndexDslError("E_YAML_DUPLICATE_KEY", message, path=str(source)) from exc
|
|
2095
|
+
if "recursive node" in message:
|
|
2096
|
+
raise IndexDslError("E_YAML_ALIAS_CYCLE", message, path=str(source)) from exc
|
|
2097
|
+
raise IndexDslError("E_YAML_INVALID", message, path=str(source)) from exc
|
|
2098
|
+
except (OSError, yaml.YAMLError) as exc:
|
|
2099
|
+
raise IndexDslError("E_YAML_INVALID", str(exc), path=str(source)) from exc
|
|
2100
|
+
return compile_index(document)
|