feat(lps): 최저가 이력(price_history) — 트리거 기반 시계열 그래프

같은 상품 반복 검색 시 최저가를 스냅샷으로 적재 → 네이버/쿠팡/최종 3개 선 그래프.
배치 아님(조회된 상품만, 실제 검색 시각에 기록) — 트래픽/리소스 절약.

- price_history 테이블: product_code·triggered_at(X축)·naver/coupang/final 최저가+상세·outcome
- crud/price_history: record() + list_by_product(시각 오름차순)
- handler: AI 매칭 후 소스별 min + 전체 min 스냅샷 기록(_price_snapshot).
  found/not_found 기록, 네거티브 캐시 히트·기술실패는 미기록
- API: GET /v1/lps/products/{product_code}/history → 그래프 데이터(시각 오름차순)
- tests: 스냅샷 계산/기록·조회/핸들러 기록규칙/API → 전체 54/54

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
민헌andClaude Opus 4.8 committed 2026-07-09 11:13:28 +09:00
1 parent bca8032b79
commit 5906acc48a
9 files changed
+299 -5

No files matched your search

+32 -2
View File
@@ -17,11 +17,28 @@ import asyncio
from common.enums import JobType
from common.logger import LOG
from services.search.contract import SearchAdapter
from services.search.contract import SearchAdapter, NormalizedProduct
from services.search.util import parse_price
from services.pipeline.core import apply_filters, rank_result
def _price_snapshot(matched: list[NormalizedProduct]) -> dict:
"""매칭 목록에서 소스별 최저가 + 전체 최저가 스냅샷을 만든다(price_history 기록용)."""
def lowest(src):
items = [p for p in matched if p.source == src]
return min(items, key=lambda p: p.price) if items else None
n, c = lowest("naver"), lowest("coupang")
finals = [x for x in (n, c) if x]
f = min(finals, key=lambda p: p.price) if finals else None
return {
"matched_count": len(matched),
"naver_lowest": n.price if n else None, "naver_name": n.name if n else None, "naver_url": n.detail_url if n else None,
"coupang_lowest": c.price if c else None, "coupang_name": c.name if c else None, "coupang_url": c.detail_url if c else None,
"final_lowest": f.price if f else None, "final_source": f.source if f else None,
}
def build_search_handler(
adapters: dict[str, SearchAdapter],
sources: list[str] | None = None,
@@ -31,12 +48,23 @@ def build_search_handler(
keyword_gen=None,
max_rounds: int = 3,
neg_cache=None,
history=None,
):
"""검색 핸들러 생성.
judge: SimilarityJudge(같은 상품 판정) / keyword_gen: KeywordGenerator(정밀·광역 재검색어) /
neg_cache: NegativeCache(TTL not_found 캐시). 모두 선택 — 없으면 해당 단계 생략."""
neg_cache: NegativeCache(TTL not_found 캐시) / history: PriceHistory(최저가 스냅샷).
모두 선택 — 없으면 해당 단계 생략."""
use = list(sources) if sources else list(adapters.keys())
async def _record_history(product_code: str, job_id, outcome: str, matched: list):
if history is None:
return
event = {"product_code": product_code, "job_id": job_id, "outcome": outcome, **_price_snapshot(matched)}
try:
await history.record(event)
except Exception as ex:
LOG.e_no_callstack(f"[history] 스냅샷 기록 실패(무시): {ex}")
async def _search_round(query: str):
"""한 라운드: 모든 소스 동시 검색 → (products, per_source, tech_failed)."""
results = await asyncio.gather(*[adapters[s].search(query, limit=limit) for s in use], return_exceptions=True)
@@ -99,6 +127,7 @@ def build_search_handler(
if candidates: # 찾음 → 조기 종료
result = rank_result(candidates, len(products), stages, top_n)
result.update(outcome="found", query=query, round=label, rounds_tried=rounds_done, sources=per_source)
await _record_history(cache_key, job.get("job_id"), "found", candidates)
return result
if tech_failed: # 0매칭인데 소스가 죽어 있었음 → '없음'이라 단정 불가 → 기술 재시도
@@ -109,6 +138,7 @@ def build_search_handler(
await neg_cache.put(cache_key, reason=f"not_found after {rounds_done} rounds")
result = rank_result([], 0, last_stages, top_n)
result.update(outcome="not_found", query=base_query, rounds_tried=rounds_done, sources=last_sources)
await _record_history(cache_key, job.get("job_id"), "not_found", [])
return result
return handler