|
| 1 | +"""Market price lookup on eBay France (public Browse API).""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import logging |
| 6 | +from typing import Annotated |
| 7 | + |
| 8 | +from fastapi import APIRouter, Depends, HTTPException, Query, status |
| 9 | + |
| 10 | +from app_types.ebay_browse import ( |
| 11 | + ConditionFilter, |
| 12 | + GradedFilter, |
| 13 | + MarketSearchResponse, |
| 14 | + SortOrder, |
| 15 | +) |
| 16 | +from config import get_settings |
| 17 | +from core.deps import get_current_user |
| 18 | +from models.user import User |
| 19 | +from services.ebay_app_oauth_service import ebay_app_oauth_configured |
| 20 | +from services.ebay_browse_service import DEFAULT_LIMIT, MAX_LIMIT, browse_search |
| 21 | +from services.ebay_price_aggregator_service import aggregate_prices, partition_outliers |
| 22 | + |
| 23 | +logger = logging.getLogger(__name__) |
| 24 | + |
| 25 | +router = APIRouter(prefix="/ebay/market", tags=["ebay-market"]) |
| 26 | + |
| 27 | +#: Hardcoded noise-word list appended to every Browse query. These tokens |
| 28 | +#: describe **accessories** ("sleeve", "classeur", …) and are unlikely to |
| 29 | +#: appear in a user's legitimate sealed-product or card search. |
| 30 | +#: |
| 31 | +#: Negative tokens are forwarded to eBay as ``-"sleeve"`` so no matching |
| 32 | +#: listing is ever returned — this keeps noise out at the source without |
| 33 | +#: relying only on statistical outlier filtering. |
| 34 | +_DEFAULT_EXCLUDES: tuple[str, ...] = ( |
| 35 | + "sleeve", |
| 36 | + "sleeves", |
| 37 | + "protège-cartes", |
| 38 | + "protege-cartes", |
| 39 | + "protège carte", |
| 40 | + "protege carte", |
| 41 | + "étui", |
| 42 | + "etui", |
| 43 | + "classeur", |
| 44 | + "portfolio", |
| 45 | + "binder", |
| 46 | + "album", |
| 47 | + "intercalaire", |
| 48 | + "divider", |
| 49 | + "toploader", |
| 50 | + "top loader", |
| 51 | + "penny sleeve", |
| 52 | + "playmat", |
| 53 | + "tapis de jeu", |
| 54 | + "boîte rangement", |
| 55 | + "boite rangement", |
| 56 | + "storage box", |
| 57 | + "pin's", |
| 58 | + "pin ", |
| 59 | + "badge", |
| 60 | + "sticker", |
| 61 | + "autocollant", |
| 62 | + "poster", |
| 63 | + "affiche", |
| 64 | + "plush", |
| 65 | + "peluche", |
| 66 | + "figurine", |
| 67 | +) |
| 68 | + |
| 69 | + |
| 70 | +@router.get("/search", response_model=None) |
| 71 | +async def search_market( |
| 72 | + _user: Annotated[User, Depends(get_current_user)], |
| 73 | + q: Annotated[str, Query(min_length=2, max_length=256)], |
| 74 | + period_days: Annotated[int, Query(ge=0, le=365)] = 30, |
| 75 | + condition: Annotated[ConditionFilter, Query()] = "new", |
| 76 | + graded: Annotated[GradedFilter, Query()] = "all", |
| 77 | + sort: Annotated[SortOrder, Query()] = "relevance", |
| 78 | + fr_only: Annotated[bool, Query()] = False, |
| 79 | + min_price: Annotated[float | None, Query(ge=0)] = None, |
| 80 | + max_price: Annotated[float | None, Query(ge=0)] = None, |
| 81 | + limit: Annotated[int, Query(ge=1, le=MAX_LIMIT)] = DEFAULT_LIMIT, |
| 82 | +) -> MarketSearchResponse: |
| 83 | + """ |
| 84 | + Search **active** eBay France listings matching ``q`` and return aggregated stats. |
| 85 | +
|
| 86 | + Authentication uses the OAuth Client Credentials flow (application token): |
| 87 | + no user eBay connection required. |
| 88 | +
|
| 89 | + Noise-word exclusions (sleeves, étuis, classeurs, …) and statistical |
| 90 | + outlier filtering are applied **server-side** by default — both are |
| 91 | + relative to the median price, so legitimate low-value cards remain visible. |
| 92 | + """ |
| 93 | + app = get_settings() |
| 94 | + if not ebay_app_oauth_configured(app): |
| 95 | + raise HTTPException( |
| 96 | + status_code=status.HTTP_503_SERVICE_UNAVAILABLE, |
| 97 | + detail="eBay app credentials not configured on the server (EBAY_CLIENT_ID, EBAY_CLIENT_SECRET).", |
| 98 | + ) |
| 99 | + exclude_list = list(_DEFAULT_EXCLUDES) |
| 100 | + try: |
| 101 | + raw_listings, total, warnings, effective_q = await browse_search( |
| 102 | + q=q.strip(), |
| 103 | + period_days=period_days, |
| 104 | + condition=condition, |
| 105 | + graded=graded, |
| 106 | + sort=sort, |
| 107 | + min_price=min_price, |
| 108 | + max_price=max_price, |
| 109 | + fr_only=fr_only, |
| 110 | + limit=limit, |
| 111 | + exclude_keywords=exclude_list, |
| 112 | + app=app, |
| 113 | + ) |
| 114 | + except RuntimeError as exc: |
| 115 | + raise HTTPException(status_code=500, detail=str(exc)) from exc |
| 116 | + except Exception as exc: # httpx raises HTTPStatusError etc. |
| 117 | + logger.warning("eBay Browse search failed: %s", exc) |
| 118 | + raise HTTPException( |
| 119 | + status_code=status.HTTP_502_BAD_GATEWAY, |
| 120 | + detail=f"eBay Browse API error: {exc}", |
| 121 | + ) from exc |
| 122 | + |
| 123 | + kept, outliers = partition_outliers(raw_listings) |
| 124 | + stats = aggregate_prices(kept) |
| 125 | + return { |
| 126 | + "query": q.strip(), |
| 127 | + "effective_query": effective_q, |
| 128 | + "marketplace_id": "EBAY_FR", |
| 129 | + "period_days": period_days, |
| 130 | + "filters_applied": { |
| 131 | + "condition": condition, |
| 132 | + "graded": graded, |
| 133 | + "sort": sort, |
| 134 | + "fr_only": fr_only, |
| 135 | + "min_price": min_price, |
| 136 | + "max_price": max_price, |
| 137 | + "limit": limit, |
| 138 | + "exclude_keywords": exclude_list, |
| 139 | + "exclude_outliers": True, |
| 140 | + }, |
| 141 | + "stats": stats, |
| 142 | + "items": kept, |
| 143 | + "outliers": outliers, |
| 144 | + "outliers_excluded": len(outliers), |
| 145 | + "total_matches": total, |
| 146 | + "warnings": warnings, |
| 147 | + } |
0 commit comments