{escape(review["title"])}
' f'' f'{escape(review["body"])}
' 'from __future__ import annotations import json from copy import deepcopy from functools import lru_cache from html import escape from pathlib import Path from typing import Any, Iterable, Mapping from urllib.parse import urlencode FIXTURE_PATH = Path(__file__).resolve().parent / "fixtures" / "review-evidence.json" SOURCE_AGGREGATE_PROVENANCE = "source_snapshot_aggregate" LOCAL_REVIEW_PROVENANCE = "local_user_review" REVIEW_SORTS = frozenset({"recent", "helpful"}) @lru_cache(maxsize=1) def _fixture() -> dict[str, Any]: payload = json.loads(FIXTURE_PATH.read_text(encoding="utf-8")) if payload.get("schema") != "amazon-clone.review-evidence.v1": raise ValueError("Unsupported review evidence schema") products = payload.get("products") if not isinstance(products, dict): raise ValueError("Review evidence products must be an object") return payload def supported_review_asins() -> tuple[str, ...]: """Return ASINs with source-observed review aggregates.""" return tuple(_fixture()["products"]) def get_review_evidence(asin: str) -> dict[str, Any] | None: """Return a caller-safe copy of an ASIN's immutable source evidence.""" product = _fixture()["products"].get(asin.upper()) return deepcopy(product) if product is not None else None def _bounded_text(value: object, field: str, *, maximum: int) -> str: if not isinstance(value, str): raise ValueError(f"{field} must be text") result = " ".join(value.split()) if not result: raise ValueError(f"{field} must not be empty") if len(result) > maximum: raise ValueError(f"{field} is too long") return result def _boolean(review: Mapping[str, Any], field: str, default: bool) -> bool: value = review.get(field, default) if not isinstance(value, bool): raise ValueError(f"{field} must be a boolean") return value def _normalize_local_review(review: Mapping[str, Any]) -> dict[str, Any]: if review.get("provenance") != LOCAL_REVIEW_PROVENANCE: raise ValueError("Local reviews must carry provenance=local_user_review") rating = review.get("rating") if isinstance(rating, bool) or not isinstance(rating, int) or not 1 <= rating <= 5: raise ValueError("rating must be an integer from 1 to 5") helpful_count = review.get("helpful_count", 0) if ( isinstance(helpful_count, bool) or not isinstance(helpful_count, int) or helpful_count < 0 ): raise ValueError("helpful_count must be a non-negative integer") created_at = review.get("created_at", "") updated_at = review.get("updated_at", created_at) if created_at and not isinstance(created_at, str): raise ValueError("created_at must be text") if updated_at and not isinstance(updated_at, str): raise ValueError("updated_at must be text") review_id = review.get("id", "") if review_id and not isinstance(review_id, (str, int)): raise ValueError("id must be text or an integer") verified_purchase = _boolean(review, "verified_purchase", False) viewer_found_helpful = _boolean(review, "viewer_found_helpful", False) owned_by_viewer = _boolean(review, "owned_by_viewer", False) can_mark_helpful = _boolean(review, "can_mark_helpful", not owned_by_viewer) if owned_by_viewer and can_mark_helpful: raise ValueError("review owners cannot mark their own review helpful") return { "id": str(review_id), "provenance": LOCAL_REVIEW_PROVENANCE, "author_display_name": _bounded_text( review.get("author_display_name"), "author_display_name", maximum=128 ), "rating": rating, "title": _bounded_text(review.get("title"), "title", maximum=200), "body": _bounded_text(review.get("body"), "body", maximum=10000), "created_at": created_at.strip(), "updated_at": updated_at.strip(), "verified_purchase": verified_purchase, "helpful_count": helpful_count, "viewer_found_helpful": viewer_found_helpful, "owned_by_viewer": owned_by_viewer, "can_mark_helpful": can_mark_helpful, } def normalize_local_reviews( reviews: Iterable[Mapping[str, Any]], *, star: int | None = None ) -> list[dict[str, Any]]: """Validate local rows without allowing them to masquerade as source reviews.""" if star is not None and (isinstance(star, bool) or star not in range(1, 6)): raise ValueError("star filter must be 1 through 5") normalized = [_normalize_local_review(review) for review in reviews] if star is not None: normalized = [review for review in normalized if review["rating"] == star] return normalized def build_review_view( asin: str, local_reviews: Iterable[Mapping[str, Any]] = (), *, star: int | None = None, product_label: str | None = None, source_rating_summary: Mapping[str, Any] | None = None, ) -> dict[str, Any] | None: """Build a UI view while keeping source aggregates and local rows separate.""" evidence = get_review_evidence(asin) known_product_label = None if product_label is not None: known_product_label = _bounded_text( product_label, "product_label", maximum=1000 ) if source_rating_summary is not None and not isinstance( source_rating_summary, Mapping ): raise ValueError("source_rating_summary must be a mapping") captured_summary = ( evidence["rating_summary"] if evidence is not None else (dict(source_rating_summary) if source_rating_summary is not None else None) ) if evidence is None and known_product_label is None and captured_summary is None: return None if star is not None and (isinstance(star, bool) or star not in range(1, 6)): raise ValueError("star filter must be 1 through 5") all_local = normalize_local_reviews(local_reviews) filtered_local = ( all_local if star is None else [review for review in all_local if review["rating"] == star] ) rating_total = sum(review["rating"] for review in all_local) local_average = round(rating_total / len(all_local), 1) if all_local else None local_by_star = { value: sum(review["rating"] == value for review in all_local) for value in range(5, 0, -1) } return { "asin": asin.upper(), "product_label": ( evidence["product_label"] if evidence is not None else known_product_label ), "source_aggregate_available": captured_summary is not None, "source_rating_summary": captured_summary, "source_histogram": evidence.get("histogram") if evidence is not None else None, "source_topics": evidence.get("source_topics", []) if evidence is not None else [], "source_topic_provenance": ( evidence.get("topic_provenance") if evidence is not None else None ), "source_excerpts": evidence.get("source_excerpts", []) if evidence is not None else [], "individual_review_evidence": ( evidence["individual_review_evidence"] if evidence is not None else { "available": False, "missing_fields": [ "aggregate_rating", "aggregate_count", "author", "title", "date", "rating", "helpful_count", ], } ), "local_summary": { "rating": local_average, "review_count": len(all_local), "provenance": LOCAL_REVIEW_PROVENANCE, "count_by_star": local_by_star, }, "owned_review": next( (review for review in all_local if review["owned_by_viewer"]), None ), "local_reviews": filtered_local, "active_star": star, } def _review_href( asin: str, *, star: int | None, sort: str, base_path: str, ) -> str: query: dict[str, str] = {} if star is not None: query["reviewStar"] = str(star) if sort != "recent": query["reviewSort"] = sort suffix = f"?{urlencode(query)}" if query else "" return f"{base_path}{suffix}#customerReviews" def _write_panel( view: Mapping[str, Any], account_name: str | None, form_error: str | None ) -> str: asin = str(view["asin"]) error_html = ( f'
Share your experience with other shoppers.
' 'Sign in to write a reviewPosting as {escape(account_name)}.
{error_html}{escape(review["body"])}
' 'No customer reviews match this filter yet.
' ) local_count = view["local_summary"]["review_count"] write_panel = _write_panel(view, account_name, form_error) rating_summary_html = ( f"""There are no customer ratings for this item yet.
' ) return f"""