BuyingAgent/backend/app/discovery/mapping.py

35 lines
1.2 KiB
Python
Raw Normal View History

from __future__ import annotations
from typing import Any
from urllib.parse import parse_qsl, urlsplit
from app.discovery.enums import MappingStatus
from app.discovery.urlgen import decode_xf_roundtrip, generate_search_url
def verify_roundtrip(
*,
category_url: str,
criterion: dict[str, Any],
mapping: dict[str, Any],
) -> bool:
"""True when encoding a single mapping round-trips to the same source parameter."""
probe = {**mapping, "status": MappingStatus.VERIFIED.value}
url, internal = generate_search_url(
category_url=category_url,
criteria_items=[criterion],
mappings=[probe],
)
if internal:
return False
encoding = mapping.get("encoding") or {}
param = str(encoding.get("url_param") or "xf")
if param == "xf":
expected_key = str(mapping["external_filter_key"])
expected_value = str(mapping.get("source_value") or "")
decoded = decode_xf_roundtrip(url)
return any(key == expected_key and value == expected_value.replace("+", " ") for key, value in decoded)
expected = str(criterion.get("value"))
query = parse_qsl(urlsplit(url).query, keep_blank_values=True)
return any(name == param and value == expected for name, value in query)