Stelle den Frontend-MVP und die v0.3-API auf develop bereit, damit Dev API und PWA zusammen deployen.
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
827e6a2a11
commit
b276758ee1
152 files changed
+25846
-34
No files matched your search
Whitespace-only changes.
@@ -0,0 +1,45 @@
|
||||
from datetime import datetime
|
||||
from decimal import Decimal
|
||||
from typing import Iterable
|
||||
|
||||
from app.domain.enums import NormalizationStatus
|
||||
from app.domain.models import AttributeStatement
|
||||
|
||||
|
||||
def statement_is_usable(statement: AttributeStatement | None, minimum_confidence: Decimal) -> bool:
|
||||
if statement is None:
|
||||
return False
|
||||
if statement.normalization_status != NormalizationStatus.NORMALIZED:
|
||||
return False
|
||||
if statement.normalized_value is None:
|
||||
return False
|
||||
return statement.confidence >= minimum_confidence
|
||||
|
||||
|
||||
def select_attribute_snapshot(
|
||||
statements: Iterable[AttributeStatement],
|
||||
*,
|
||||
as_of: datetime,
|
||||
snapshot_cutoff: datetime,
|
||||
) -> dict[str, AttributeStatement]:
|
||||
"""Pick the newest statement per key at or before the evaluation cutoff."""
|
||||
chosen: dict[str, AttributeStatement] = {}
|
||||
for statement in statements:
|
||||
if statement.observed_at > as_of or statement.ingested_at > snapshot_cutoff:
|
||||
continue
|
||||
current = chosen.get(statement.attribute)
|
||||
if current is None or _is_newer(statement, current):
|
||||
chosen[statement.attribute] = statement
|
||||
return chosen
|
||||
|
||||
|
||||
def _is_newer(candidate: AttributeStatement, current: AttributeStatement) -> bool:
|
||||
return (
|
||||
candidate.observed_at,
|
||||
candidate.ingested_at,
|
||||
candidate.id,
|
||||
) > (
|
||||
current.observed_at,
|
||||
current.ingested_at,
|
||||
current.id,
|
||||
)
|
||||
@@ -0,0 +1,148 @@
|
||||
from decimal import Decimal
|
||||
from typing import Any
|
||||
|
||||
from app.domain.attributes import statement_is_usable
|
||||
from app.domain.enums import ConstraintOperator, ConstraintStatus, ValueType
|
||||
from app.domain.models import AttributeDefinition, AttributeStatement, Constraint, ConstraintResult
|
||||
|
||||
_NUMBER_OPS = {
|
||||
ConstraintOperator.GE,
|
||||
ConstraintOperator.LE,
|
||||
ConstraintOperator.GT,
|
||||
ConstraintOperator.LT,
|
||||
}
|
||||
_EQUALITY_OPS = {ConstraintOperator.EQ, ConstraintOperator.NE}
|
||||
_SCALAR_TYPES = {ValueType.NUMBER, ValueType.STRING, ValueType.BOOLEAN}
|
||||
|
||||
|
||||
def operator_allowed_for(value_type: ValueType, operator: ConstraintOperator) -> bool:
|
||||
if operator == ConstraintOperator.EXISTS:
|
||||
return True
|
||||
if operator in _NUMBER_OPS:
|
||||
return value_type == ValueType.NUMBER
|
||||
if operator in _EQUALITY_OPS:
|
||||
return value_type in _SCALAR_TYPES
|
||||
if operator == ConstraintOperator.IN:
|
||||
return value_type in _SCALAR_TYPES
|
||||
if operator == ConstraintOperator.CONTAINS:
|
||||
return value_type == ValueType.STRING_LIST
|
||||
return False
|
||||
|
||||
|
||||
def evaluate_constraint(
|
||||
constraint: Constraint,
|
||||
statement: AttributeStatement | None,
|
||||
definition: AttributeDefinition,
|
||||
minimum_confidence: Decimal,
|
||||
) -> ConstraintResult:
|
||||
usable = statement_is_usable(statement, minimum_confidence)
|
||||
actual = statement.normalized_value if usable else None
|
||||
attribute_row_id = statement.id if statement is not None else None
|
||||
|
||||
if not usable:
|
||||
return ConstraintResult(
|
||||
constraint_id=constraint.id,
|
||||
attribute=constraint.attribute,
|
||||
operator=constraint.operator.value,
|
||||
expected=constraint.value,
|
||||
actual=None,
|
||||
status=ConstraintStatus.UNKNOWN.value,
|
||||
mandatory=constraint.mandatory,
|
||||
attribute_row_id=attribute_row_id,
|
||||
reason_code="ATTRIBUTE_UNUSABLE",
|
||||
)
|
||||
|
||||
passed = _compare(constraint.operator, actual, constraint.value, definition.value_type)
|
||||
if passed is None:
|
||||
status = ConstraintStatus.UNKNOWN
|
||||
reason = "TYPE_MISMATCH"
|
||||
elif passed:
|
||||
status = ConstraintStatus.PASS
|
||||
reason = "CONSTRAINT_PASS"
|
||||
else:
|
||||
status = ConstraintStatus.FAIL
|
||||
reason = "CONSTRAINT_FAIL"
|
||||
return ConstraintResult(
|
||||
constraint_id=constraint.id,
|
||||
attribute=constraint.attribute,
|
||||
operator=constraint.operator.value,
|
||||
expected=constraint.value,
|
||||
actual=actual,
|
||||
status=status.value,
|
||||
mandatory=constraint.mandatory,
|
||||
attribute_row_id=attribute_row_id,
|
||||
reason_code=reason,
|
||||
)
|
||||
|
||||
|
||||
def _as_number(value: Any) -> Decimal | None:
|
||||
if isinstance(value, bool) or value is None:
|
||||
return None
|
||||
if isinstance(value, Decimal):
|
||||
return value
|
||||
if isinstance(value, int):
|
||||
return Decimal(value)
|
||||
if isinstance(value, float):
|
||||
return Decimal(str(value))
|
||||
if isinstance(value, str):
|
||||
return None
|
||||
return None
|
||||
|
||||
|
||||
def _same_scalar(left: Any, right: Any, value_type: ValueType) -> bool | None:
|
||||
if value_type == ValueType.NUMBER:
|
||||
left_n = _as_number(left)
|
||||
right_n = _as_number(right)
|
||||
if left_n is None or right_n is None:
|
||||
return None
|
||||
return left_n == right_n
|
||||
if value_type == ValueType.STRING:
|
||||
if not isinstance(left, str) or not isinstance(right, str):
|
||||
return None
|
||||
return left == right
|
||||
if value_type == ValueType.BOOLEAN:
|
||||
if not isinstance(left, bool) or not isinstance(right, bool):
|
||||
return None
|
||||
return left == right
|
||||
return None
|
||||
|
||||
|
||||
def _compare(
|
||||
operator: ConstraintOperator,
|
||||
actual: Any,
|
||||
expected: Any,
|
||||
value_type: ValueType,
|
||||
) -> bool | None:
|
||||
if operator == ConstraintOperator.EXISTS:
|
||||
return True
|
||||
if operator in _NUMBER_OPS:
|
||||
actual_n = _as_number(actual)
|
||||
expected_n = _as_number(expected)
|
||||
if actual_n is None or expected_n is None:
|
||||
return None
|
||||
if operator == ConstraintOperator.GE:
|
||||
return actual_n >= expected_n
|
||||
if operator == ConstraintOperator.LE:
|
||||
return actual_n <= expected_n
|
||||
if operator == ConstraintOperator.GT:
|
||||
return actual_n > expected_n
|
||||
return actual_n < expected_n
|
||||
if operator == ConstraintOperator.EQ:
|
||||
return _same_scalar(actual, expected, value_type)
|
||||
if operator == ConstraintOperator.NE:
|
||||
equal = _same_scalar(actual, expected, value_type)
|
||||
return None if equal is None else (not equal)
|
||||
if operator == ConstraintOperator.IN:
|
||||
if not isinstance(expected, list) or not expected:
|
||||
return None
|
||||
matches = [_same_scalar(actual, item, value_type) for item in expected]
|
||||
if any(item is None for item in matches):
|
||||
return None
|
||||
return any(matches)
|
||||
if operator == ConstraintOperator.CONTAINS:
|
||||
if not isinstance(actual, list) or not isinstance(expected, str):
|
||||
return None
|
||||
if any(not isinstance(item, str) for item in actual):
|
||||
return None
|
||||
return expected in actual
|
||||
return None
|
||||
@@ -0,0 +1,81 @@
|
||||
from enum import StrEnum
|
||||
|
||||
|
||||
class ValueType(StrEnum):
|
||||
NUMBER = "number"
|
||||
STRING = "string"
|
||||
BOOLEAN = "boolean"
|
||||
STRING_LIST = "string_list"
|
||||
|
||||
|
||||
class OfferCondition(StrEnum):
|
||||
NEW = "new"
|
||||
REFURBISHED = "refurbished"
|
||||
USED = "used"
|
||||
|
||||
|
||||
class Availability(StrEnum):
|
||||
IN_STOCK = "in_stock"
|
||||
OUT_OF_STOCK = "out_of_stock"
|
||||
UNKNOWN = "unknown"
|
||||
|
||||
|
||||
class NormalizationStatus(StrEnum):
|
||||
NORMALIZED = "normalized"
|
||||
UNKNOWN = "unknown"
|
||||
|
||||
|
||||
class ConstraintStatus(StrEnum):
|
||||
PASS = "PASS"
|
||||
FAIL = "FAIL"
|
||||
UNKNOWN = "UNKNOWN"
|
||||
|
||||
|
||||
class Eligibility(StrEnum):
|
||||
ELIGIBLE = "ELIGIBLE"
|
||||
INELIGIBLE = "INELIGIBLE"
|
||||
UNKNOWN = "UNKNOWN"
|
||||
|
||||
|
||||
class PreferenceStrategy(StrEnum):
|
||||
NUMERIC_LINEAR = "numeric_linear"
|
||||
|
||||
|
||||
class PreferenceDirection(StrEnum):
|
||||
HIGHER = "higher"
|
||||
LOWER = "lower"
|
||||
|
||||
|
||||
class ConstraintOperator(StrEnum):
|
||||
GE = ">="
|
||||
LE = "<="
|
||||
GT = ">"
|
||||
LT = "<"
|
||||
EQ = "=="
|
||||
NE = "!="
|
||||
IN = "in"
|
||||
CONTAINS = "contains"
|
||||
EXISTS = "exists"
|
||||
|
||||
|
||||
class Classification(StrEnum):
|
||||
IGNORE = "IGNORE"
|
||||
WATCH = "WATCH"
|
||||
GOOD = "GOOD"
|
||||
VERY_GOOD = "VERY_GOOD"
|
||||
EXCEPTIONAL = "EXCEPTIONAL"
|
||||
INELIGIBLE = "INELIGIBLE"
|
||||
INSUFFICIENT_DATA = "INSUFFICIENT_DATA"
|
||||
|
||||
|
||||
class PriceBasis(StrEnum):
|
||||
BUDGET_ONLY = "BUDGET_ONLY"
|
||||
BUDGET_AND_HISTORY = "BUDGET_AND_HISTORY"
|
||||
|
||||
|
||||
class PriceReferenceScope(StrEnum):
|
||||
OFFER = "offer"
|
||||
|
||||
|
||||
class AdapterType(StrEnum):
|
||||
MANUAL = "manual"
|
||||
@@ -0,0 +1,275 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime
|
||||
from decimal import Decimal
|
||||
from typing import Any
|
||||
from uuid import UUID
|
||||
|
||||
from app.domain.enums import (
|
||||
Availability,
|
||||
ConstraintOperator,
|
||||
Eligibility,
|
||||
NormalizationStatus,
|
||||
OfferCondition,
|
||||
PreferenceDirection,
|
||||
PreferenceStrategy,
|
||||
PriceBasis,
|
||||
PriceReferenceScope,
|
||||
ValueType,
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Budget:
|
||||
target: Decimal
|
||||
maximum: Decimal
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Constraint:
|
||||
id: str
|
||||
attribute: str
|
||||
operator: ConstraintOperator
|
||||
value: Any = None
|
||||
mandatory: bool = True
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Preference:
|
||||
id: str
|
||||
attribute: str
|
||||
strategy: PreferenceStrategy
|
||||
direction: PreferenceDirection
|
||||
acceptable: Decimal
|
||||
ideal: Decimal
|
||||
weight: Decimal
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ClassificationBound:
|
||||
upper: Decimal
|
||||
inclusive: bool
|
||||
label: str
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ScoringModel:
|
||||
version: str
|
||||
algorithm_id: str
|
||||
supported_preference_strategies: tuple[str, ...]
|
||||
minimum_confidence: Decimal
|
||||
maximum_price_age_hours: int
|
||||
optional_constraint_penalty_points: Decimal
|
||||
missing_preference_score: Decimal
|
||||
product_weight: Decimal
|
||||
price_weight: Decimal
|
||||
budget_weight: Decimal
|
||||
history_weight: Decimal
|
||||
history_window_days: int
|
||||
minimum_history_days: int
|
||||
history_discount_for_max_score: Decimal
|
||||
classification_upper_bounds: tuple[ClassificationBound, ...]
|
||||
definition: dict[str, Any]
|
||||
definition_hash: str
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Profile:
|
||||
id: str
|
||||
version: int
|
||||
name: str
|
||||
category: str
|
||||
currency: str
|
||||
market: str
|
||||
allowed_conditions: tuple[OfferCondition, ...]
|
||||
budget: Budget
|
||||
scoring_version: str
|
||||
constraints: tuple[Constraint, ...]
|
||||
preferences: tuple[Preference, ...]
|
||||
definition: dict[str, Any]
|
||||
definition_hash: str
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class AttributeDefinition:
|
||||
key: str
|
||||
value_type: ValueType
|
||||
canonical_unit: str | None
|
||||
minimum: Decimal | None
|
||||
maximum: Decimal | None
|
||||
description: str | None
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Product:
|
||||
id: UUID
|
||||
category: str
|
||||
brand: str
|
||||
name: str
|
||||
model: str | None
|
||||
created_at: datetime
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ProductVariant:
|
||||
id: UUID
|
||||
product_id: UUID
|
||||
name: str
|
||||
manufacturer_sku: str | None
|
||||
identifiers: dict[str, Any]
|
||||
created_at: datetime
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class AttributeStatement:
|
||||
id: UUID
|
||||
variant_id: UUID
|
||||
attribute: str
|
||||
raw_value: Any
|
||||
normalized_value: Any
|
||||
unit: str | None
|
||||
normalization_status: NormalizationStatus
|
||||
normalizer_version: str
|
||||
confidence: Decimal
|
||||
source_id: str
|
||||
source_reference: str
|
||||
observed_at: datetime
|
||||
ingested_at: datetime
|
||||
normalization_error: str | None = None
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Offer:
|
||||
id: UUID
|
||||
variant_id: UUID
|
||||
source_id: str
|
||||
external_id: str
|
||||
seller: str
|
||||
url: str | None
|
||||
market: str
|
||||
currency: str
|
||||
condition: OfferCondition
|
||||
created_at: datetime
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class PriceObservation:
|
||||
id: UUID
|
||||
offer_id: UUID
|
||||
source_id: str
|
||||
external_observation_id: str
|
||||
observed_at: datetime
|
||||
ingested_at: datetime
|
||||
item_price: Decimal
|
||||
shipping_price: Decimal | None
|
||||
currency: str
|
||||
availability: Availability
|
||||
raw_payload: Any
|
||||
confidence: Decimal
|
||||
|
||||
@property
|
||||
def total_price(self) -> Decimal | None:
|
||||
if self.shipping_price is None:
|
||||
return None
|
||||
return self.item_price + self.shipping_price
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ConstraintResult:
|
||||
constraint_id: str
|
||||
attribute: str
|
||||
operator: str
|
||||
expected: Any
|
||||
actual: Any
|
||||
status: str
|
||||
mandatory: bool
|
||||
attribute_row_id: UUID | None
|
||||
reason_code: str
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class GateResult:
|
||||
key: str
|
||||
status: str
|
||||
reason_code: str
|
||||
details: dict[str, Any] = field(default_factory=dict)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ScoreComponent:
|
||||
kind: str
|
||||
component_key: str
|
||||
raw_score: Decimal | None
|
||||
weight: Decimal | None
|
||||
contribution: Decimal | None
|
||||
details: dict[str, Any]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class HistoryWindow:
|
||||
days: int
|
||||
values: tuple[Decimal, ...]
|
||||
observation_ids: tuple[UUID, ...]
|
||||
|
||||
@property
|
||||
def day_count(self) -> int:
|
||||
return len(self.values)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class PriceStatistics:
|
||||
current_total: Decimal | None
|
||||
median_30d: Decimal | None
|
||||
median_30d_days: int
|
||||
median_90d: Decimal | None
|
||||
median_90d_days: int
|
||||
lowest_365d: Decimal | None
|
||||
lowest_365d_days: int
|
||||
lowest_365d_is_full_year: bool
|
||||
used_observation_ids: tuple[UUID, ...]
|
||||
current_observation_id: UUID | None
|
||||
price_reference_scope: PriceReferenceScope = PriceReferenceScope.OFFER
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Reason:
|
||||
code: str
|
||||
message: str
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class EvaluationResult:
|
||||
profile_id: str
|
||||
profile_version: int
|
||||
scoring_version: str
|
||||
scoring_hash: str
|
||||
engine_build: str
|
||||
variant_id: UUID
|
||||
offer_id: UUID
|
||||
as_of: datetime
|
||||
snapshot_cutoff: datetime
|
||||
product_eligibility: Eligibility
|
||||
offer_eligibility: Eligibility
|
||||
overall_eligibility: Eligibility
|
||||
eligible: bool | None
|
||||
product_score: Decimal | None
|
||||
product_score_raw: Decimal | None
|
||||
price_score: Decimal | None
|
||||
price_score_raw: Decimal | None
|
||||
deal_score: Decimal | None
|
||||
deal_score_raw: Decimal | None
|
||||
classification: str
|
||||
price_basis: PriceBasis | None
|
||||
product_coverage: Decimal
|
||||
constraint_results: tuple[ConstraintResult, ...]
|
||||
product_gates: tuple[GateResult, ...]
|
||||
offer_gates: tuple[GateResult, ...]
|
||||
components: tuple[ScoreComponent, ...]
|
||||
price_statistics: PriceStatistics
|
||||
price_reference_scope: PriceReferenceScope
|
||||
reasons: tuple[Reason, ...]
|
||||
warnings: tuple[str, ...]
|
||||
input_snapshot: dict[str, Any]
|
||||
failed_constraints: tuple[ConstraintResult, ...]
|
||||
unknown_constraints: tuple[ConstraintResult, ...]
|
||||
@@ -0,0 +1,26 @@
|
||||
from datetime import date, datetime
|
||||
from decimal import Decimal
|
||||
from typing import Any
|
||||
from uuid import UUID
|
||||
|
||||
from app.domain.timeutil import to_iso_z
|
||||
|
||||
|
||||
def jsonable(value: Any) -> Any:
|
||||
if value is None or isinstance(value, (str, int, bool)):
|
||||
return value
|
||||
if isinstance(value, Decimal):
|
||||
return format(value, "f")
|
||||
if isinstance(value, UUID):
|
||||
return str(value)
|
||||
if isinstance(value, datetime):
|
||||
return to_iso_z(value)
|
||||
if isinstance(value, date):
|
||||
return value.isoformat()
|
||||
if isinstance(value, dict):
|
||||
return {str(key): jsonable(item) for key, item in value.items()}
|
||||
if isinstance(value, (list, tuple)):
|
||||
return [jsonable(item) for item in value]
|
||||
if hasattr(value, "value"):
|
||||
return jsonable(value.value)
|
||||
return value
|
||||
@@ -0,0 +1,11 @@
|
||||
from datetime import datetime, timezone
|
||||
|
||||
|
||||
def require_utc(value: datetime, field_name: str) -> datetime:
|
||||
if value.tzinfo is None:
|
||||
raise ValueError(f"{field_name} must include a timezone")
|
||||
return value.astimezone(timezone.utc)
|
||||
|
||||
|
||||
def to_iso_z(value: datetime) -> str:
|
||||
return require_utc(value, "datetime").strftime("%Y-%m-%dT%H:%M:%SZ")
|
||||
@@ -0,0 +1,307 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
from decimal import Decimal
|
||||
from typing import Any
|
||||
|
||||
from app.domain.constraints import operator_allowed_for
|
||||
from app.domain.enums import (
|
||||
ConstraintOperator,
|
||||
OfferCondition,
|
||||
PreferenceDirection,
|
||||
PreferenceStrategy,
|
||||
ValueType,
|
||||
)
|
||||
from app.domain.models import (
|
||||
AttributeDefinition,
|
||||
Budget,
|
||||
ClassificationBound,
|
||||
Constraint,
|
||||
Preference,
|
||||
Profile,
|
||||
ScoringModel,
|
||||
)
|
||||
|
||||
SNAKE_CASE = r"^[a-z][a-z0-9]*(?:_[a-z0-9]+)*$"
|
||||
CURRENCY = r"^[A-Z]{3}$"
|
||||
SUPPORTED_ALGORITHM = "linear-budget-history-v1"
|
||||
|
||||
|
||||
class DomainValidationError(ValueError):
|
||||
def __init__(self, message: str, details: dict[str, Any] | None = None) -> None:
|
||||
super().__init__(message)
|
||||
self.details = details or {}
|
||||
|
||||
|
||||
def canonical_json(data: Any) -> str:
|
||||
return json.dumps(data, sort_keys=True, separators=(",", ":"), ensure_ascii=False)
|
||||
|
||||
|
||||
def sha256_text(text: str) -> str:
|
||||
return hashlib.sha256(text.encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
def _decimal(value: Any, field: str) -> Decimal:
|
||||
if isinstance(value, bool) or value is None:
|
||||
raise DomainValidationError(f"{field} must be a decimal", {"field": field})
|
||||
try:
|
||||
return Decimal(str(value))
|
||||
except Exception as exc:
|
||||
raise DomainValidationError(f"{field} must be a decimal", {"field": field}) from exc
|
||||
|
||||
|
||||
def _require(mapping: dict[str, Any], key: str) -> Any:
|
||||
if key not in mapping:
|
||||
raise DomainValidationError(f"missing field {key}", {"field": key})
|
||||
return mapping[key]
|
||||
|
||||
|
||||
def validate_attribute_key(key: str) -> None:
|
||||
import re
|
||||
|
||||
if not re.fullmatch(SNAKE_CASE, key):
|
||||
raise DomainValidationError("attribute key must be snake_case", {"key": key})
|
||||
|
||||
|
||||
def validate_currency(value: str) -> str:
|
||||
import re
|
||||
|
||||
if not re.fullmatch(CURRENCY, value):
|
||||
raise DomainValidationError("currency must be a 3-letter uppercase code", {"currency": value})
|
||||
return value
|
||||
|
||||
|
||||
def parse_scoring_model(definition: dict[str, Any]) -> ScoringModel:
|
||||
version = str(_require(definition, "version"))
|
||||
algorithm_id = str(_require(definition, "algorithm_id"))
|
||||
if algorithm_id != SUPPORTED_ALGORITHM:
|
||||
raise DomainValidationError("unsupported algorithm_id", {"algorithm_id": algorithm_id})
|
||||
strategies = tuple(str(item) for item in _require(definition, "supported_preference_strategies"))
|
||||
if not strategies:
|
||||
raise DomainValidationError("supported_preference_strategies must not be empty")
|
||||
if PreferenceStrategy.NUMERIC_LINEAR.value not in strategies:
|
||||
raise DomainValidationError("generic-v1 must support numeric_linear")
|
||||
|
||||
min_conf = _decimal(_require(definition, "minimum_confidence"), "minimum_confidence")
|
||||
if not Decimal("0") <= min_conf <= Decimal("1"):
|
||||
raise DomainValidationError("minimum_confidence must be between 0 and 1")
|
||||
|
||||
max_age = int(_require(definition, "maximum_price_age_hours"))
|
||||
history_window = int(_require(definition, "history_window_days"))
|
||||
min_history = int(_require(definition, "minimum_history_days"))
|
||||
if max_age <= 0 or history_window <= 0 or min_history <= 0:
|
||||
raise DomainValidationError("time windows must be positive")
|
||||
|
||||
product_weight = _decimal(_require(definition, "product_weight"), "product_weight")
|
||||
price_weight = _decimal(_require(definition, "price_weight"), "price_weight")
|
||||
budget_weight = _decimal(_require(definition, "budget_weight"), "budget_weight")
|
||||
history_weight = _decimal(_require(definition, "history_weight"), "history_weight")
|
||||
for name, weight in (
|
||||
("product_weight", product_weight),
|
||||
("price_weight", price_weight),
|
||||
("budget_weight", budget_weight),
|
||||
("history_weight", history_weight),
|
||||
):
|
||||
if weight < 0:
|
||||
raise DomainValidationError(f"{name} must be non-negative")
|
||||
if product_weight + price_weight != Decimal("1"):
|
||||
raise DomainValidationError("product_weight + price_weight must equal 1")
|
||||
if budget_weight + history_weight != Decimal("1"):
|
||||
raise DomainValidationError("budget_weight + history_weight must equal 1")
|
||||
|
||||
bounds_raw = _require(definition, "classification_upper_bounds")
|
||||
bounds: list[ClassificationBound] = []
|
||||
previous = Decimal("0")
|
||||
for index, raw in enumerate(bounds_raw):
|
||||
upper = _decimal(raw["upper"], f"classification_upper_bounds[{index}].upper")
|
||||
inclusive = bool(raw["inclusive"])
|
||||
label = str(raw["label"])
|
||||
if upper < previous or (index and upper == previous):
|
||||
raise DomainValidationError("classification bounds must be strictly ascending")
|
||||
if index == 0 and upper <= 0:
|
||||
raise DomainValidationError("classification bounds must start above 0")
|
||||
bounds.append(ClassificationBound(upper=upper, inclusive=inclusive, label=label))
|
||||
previous = upper
|
||||
if not bounds or bounds[-1].upper != Decimal("100"):
|
||||
raise DomainValidationError("classification bounds must end at 100")
|
||||
|
||||
canonical = json.loads(canonical_json(definition))
|
||||
return ScoringModel(
|
||||
version=version,
|
||||
algorithm_id=algorithm_id,
|
||||
supported_preference_strategies=strategies,
|
||||
minimum_confidence=min_conf,
|
||||
maximum_price_age_hours=max_age,
|
||||
optional_constraint_penalty_points=_decimal(
|
||||
_require(definition, "optional_constraint_penalty_points"),
|
||||
"optional_constraint_penalty_points",
|
||||
),
|
||||
missing_preference_score=_decimal(
|
||||
_require(definition, "missing_preference_score"),
|
||||
"missing_preference_score",
|
||||
),
|
||||
product_weight=product_weight,
|
||||
price_weight=price_weight,
|
||||
budget_weight=budget_weight,
|
||||
history_weight=history_weight,
|
||||
history_window_days=history_window,
|
||||
minimum_history_days=min_history,
|
||||
history_discount_for_max_score=_decimal(
|
||||
_require(definition, "history_discount_for_max_score"),
|
||||
"history_discount_for_max_score",
|
||||
),
|
||||
classification_upper_bounds=tuple(bounds),
|
||||
definition=canonical,
|
||||
definition_hash=sha256_text(canonical_json(canonical)),
|
||||
)
|
||||
|
||||
|
||||
def parse_profile(
|
||||
definition: dict[str, Any],
|
||||
*,
|
||||
attribute_definitions: dict[str, AttributeDefinition],
|
||||
scoring_versions: set[str],
|
||||
supported_strategies: set[str],
|
||||
) -> Profile:
|
||||
profile_id = str(_require(definition, "id"))
|
||||
version = int(_require(definition, "version"))
|
||||
if version <= 0:
|
||||
raise DomainValidationError("profile version must be > 0")
|
||||
name = str(_require(definition, "name"))
|
||||
category = str(_require(definition, "category"))
|
||||
if not category:
|
||||
raise DomainValidationError("category is required")
|
||||
currency = validate_currency(str(_require(definition, "currency")))
|
||||
market = str(_require(definition, "market"))
|
||||
if not market:
|
||||
raise DomainValidationError("market is required")
|
||||
raw_conditions = _require(definition, "allowed_conditions")
|
||||
if not raw_conditions:
|
||||
raise DomainValidationError("allowed_conditions is required")
|
||||
conditions = tuple(OfferCondition(item) for item in raw_conditions)
|
||||
scoring_version = str(_require(definition, "scoring_version"))
|
||||
if scoring_version not in scoring_versions:
|
||||
raise DomainValidationError("unknown scoring_version", {"scoring_version": scoring_version})
|
||||
|
||||
budget_raw = _require(definition, "budget")
|
||||
target = _decimal(_require(budget_raw, "target"), "budget.target")
|
||||
maximum = _decimal(_require(budget_raw, "maximum"), "budget.maximum")
|
||||
if not (Decimal("0") < target < maximum):
|
||||
raise DomainValidationError("budget must satisfy 0 < target < maximum")
|
||||
|
||||
constraints = _parse_constraints(_require(definition, "constraints"), attribute_definitions)
|
||||
preferences = _parse_preferences(
|
||||
_require(definition, "preferences"),
|
||||
attribute_definitions,
|
||||
supported_strategies,
|
||||
)
|
||||
canonical = json.loads(canonical_json(definition))
|
||||
return Profile(
|
||||
id=profile_id,
|
||||
version=version,
|
||||
name=name,
|
||||
category=category,
|
||||
currency=currency,
|
||||
market=market,
|
||||
allowed_conditions=conditions,
|
||||
budget=Budget(target=target, maximum=maximum),
|
||||
scoring_version=scoring_version,
|
||||
constraints=constraints,
|
||||
preferences=preferences,
|
||||
definition=canonical,
|
||||
definition_hash=sha256_text(canonical_json(canonical)),
|
||||
)
|
||||
|
||||
|
||||
def _parse_constraints(
|
||||
raw_items: list[dict[str, Any]],
|
||||
attribute_definitions: dict[str, AttributeDefinition],
|
||||
) -> tuple[Constraint, ...]:
|
||||
seen: set[str] = set()
|
||||
items: list[Constraint] = []
|
||||
for raw in raw_items:
|
||||
constraint_id = str(_require(raw, "id"))
|
||||
if constraint_id in seen:
|
||||
raise DomainValidationError("duplicate constraint id", {"id": constraint_id})
|
||||
seen.add(constraint_id)
|
||||
attribute = str(_require(raw, "attribute"))
|
||||
definition = attribute_definitions.get(attribute)
|
||||
if definition is None:
|
||||
raise DomainValidationError("unknown attribute key", {"attribute": attribute})
|
||||
operator = ConstraintOperator(str(_require(raw, "operator")))
|
||||
if not operator_allowed_for(definition.value_type, operator):
|
||||
raise DomainValidationError(
|
||||
"operator is not valid for attribute type",
|
||||
{"attribute": attribute, "operator": operator.value, "value_type": definition.value_type.value},
|
||||
)
|
||||
value = raw.get("value")
|
||||
if operator == ConstraintOperator.EXISTS:
|
||||
if "value" in raw and raw["value"] is not None:
|
||||
raise DomainValidationError("exists must not have a value", {"id": constraint_id})
|
||||
value = None
|
||||
elif operator == ConstraintOperator.IN:
|
||||
if not isinstance(value, list) or not value:
|
||||
raise DomainValidationError("in requires a non-empty list", {"id": constraint_id})
|
||||
elif operator == ConstraintOperator.CONTAINS:
|
||||
if not isinstance(value, str):
|
||||
raise DomainValidationError("contains requires a string", {"id": constraint_id})
|
||||
items.append(
|
||||
Constraint(
|
||||
id=constraint_id,
|
||||
attribute=attribute,
|
||||
operator=operator,
|
||||
value=value,
|
||||
mandatory=bool(raw.get("mandatory", True)),
|
||||
)
|
||||
)
|
||||
return tuple(items)
|
||||
|
||||
|
||||
def _parse_preferences(
|
||||
raw_items: list[dict[str, Any]],
|
||||
attribute_definitions: dict[str, AttributeDefinition],
|
||||
supported_strategies: set[str],
|
||||
) -> tuple[Preference, ...]:
|
||||
if not raw_items:
|
||||
raise DomainValidationError("at least one preference is required")
|
||||
seen: set[str] = set()
|
||||
items: list[Preference] = []
|
||||
for raw in raw_items:
|
||||
preference_id = str(_require(raw, "id"))
|
||||
if preference_id in seen:
|
||||
raise DomainValidationError("duplicate preference id", {"id": preference_id})
|
||||
seen.add(preference_id)
|
||||
attribute = str(_require(raw, "attribute"))
|
||||
definition = attribute_definitions.get(attribute)
|
||||
if definition is None:
|
||||
raise DomainValidationError("unknown attribute key", {"attribute": attribute})
|
||||
strategy = str(_require(raw, "strategy"))
|
||||
if strategy not in supported_strategies:
|
||||
raise DomainValidationError("unsupported preference strategy", {"strategy": strategy})
|
||||
if strategy != PreferenceStrategy.NUMERIC_LINEAR.value:
|
||||
raise DomainValidationError("v0.1 only supports numeric_linear", {"strategy": strategy})
|
||||
if definition.value_type != ValueType.NUMBER:
|
||||
raise DomainValidationError("numeric_linear requires a number attribute", {"attribute": attribute})
|
||||
direction = PreferenceDirection(str(_require(raw, "direction")))
|
||||
acceptable = _decimal(_require(raw, "acceptable"), "acceptable")
|
||||
ideal = _decimal(_require(raw, "ideal"), "ideal")
|
||||
weight = _decimal(_require(raw, "weight"), "weight")
|
||||
if weight <= 0:
|
||||
raise DomainValidationError("preference weight must be positive", {"id": preference_id})
|
||||
if direction == PreferenceDirection.HIGHER and not ideal > acceptable:
|
||||
raise DomainValidationError("higher requires ideal > acceptable", {"id": preference_id})
|
||||
if direction == PreferenceDirection.LOWER and not ideal < acceptable:
|
||||
raise DomainValidationError("lower requires ideal < acceptable", {"id": preference_id})
|
||||
items.append(
|
||||
Preference(
|
||||
id=preference_id,
|
||||
attribute=attribute,
|
||||
strategy=PreferenceStrategy.NUMERIC_LINEAR,
|
||||
direction=direction,
|
||||
acceptable=acceptable,
|
||||
ideal=ideal,
|
||||
weight=weight,
|
||||
)
|
||||
)
|
||||
return tuple(items)
|
||||
Reference in new issue
Block a user