feat(tradein): sell-time sensitivity (4 цены × срок продажи) #548
No reviewers
Labels
No labels
admin
analytics
auth
automation
bug
business
chore
ci
compliance
data
data-moat
docs
duplicate
dx
enhancement
Fable 5 ревью
feedback/max
generative
GG-форсайт
needs-discussion
needs-human
observability
pause-bots
performance
priority/p0
priority/p1
priority/p2
priority/p3
scope/backend
scope/db
scope/devops
scope/frontend
scope/qa
scrapers
security
site-finder
stage/1
stage/2
status/blocked
status/done
status/needs-analysis
status/needs-fix
status/qa
status/ready
status/review
status/wip
tech-debt
tradein
ux
week ревью 1
wontfix
вторичка
ИРД
No milestone
No project
No assignees
1 participant
Notifications
Due date
No due date set.
Dependencies
No dependencies set.
Reference: lekss361/gendesign#548
Loading…
Add table
Reference in a new issue
No description provided.
Delete branch "feat/tradein-sell-time-backend"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
Контекст
Третий PR серии для demo. Поверх PR #547 (multi-source).
Что добавлено
Новый блок «Срок продажи в зависимости от цены» под HouseAnalyticsKpiRow.
4 карточки с фиксированными бакетами (premium к медиане года):
Каждая показывает:
~31 дн(median) +обычно 31-61 дн(p25-p75) + count лотов.Источник
house_placement_history(15k+ rows). Для текущего estimate Татищева 96:Filter outliers
last_price > start_price * 0.7(отбрасывает fake-cheap листинги).Аномалии в данных
Test plan
Backend: - New GET /api/v1/trade-in/estimate/{id}/cian-price-changes — per-analog price change stats (n_changes, last_diff_pct, total_change_pct) из offer_price_history (cian playwright_history backfill, 268+ rows). - house-analytics: PriceHistoryYearPoint gains source field; SQL теперь GROUP BY year, source → 2 серии для chart (avito_imv / yandex_valuation). Frontend: - ListingsCard показывает colored badge ↓N ±X.X% рядом с ценой cian-аналога если есть price changes (зелёный = снижение, красный = рост). - PriceHistoryChart: pivot long→wide format client-side, 2 Line components (синий Avito #2563eb, оранжевый Яндекс #ea580c) + Legend, connectNulls. Использует данные: - offer_price_history (live cian price changes) - house_placement_history.source разделение avito_imv vs yandex_valuationDeep Code Review — verdict
Summary
Scope verified
GET /estimate/{id}/sell-time-sensitivity— 4-bucket exposure_days matrix bucketed by price-premium-vs-year-median.GET /estimate/{id}/cian-price-changes— Cian price-change history join viaoffer_price_history.PriceHistoryYearPointnow splits bysource(avito_imv + yandex_valuation) with pivoted Recharts dual-line.SellTimeSensitivitycard grid (4 cards), Cian price-change badges inListingsCard.Math correctness — sound
NULLIF(area_m2, 0), CASE-guardym.median_ppm2 IS NULL OR ym.median_ppm2 = 0,first_seen_price > 0.CASE WHENtop-down evaluation делает boundary points (-3, 3, 8) deterministic → no double-counting, хотяBETWEENграницы overlap'ятся.last_price > start_price * 0.7outlier filter — корректно (PR описывает: отбрасывает fake-cheap листинги).Edge cases — covered
house_ids→ возвращается early empty response.data.buckets.every(b => b.n_lots === 0)→ component hides itself.Existing pipeline reuse
services/estimator.py,/estimateendpoint backward-compat сохранён.house-analyticsлогике — consistency ✔.CAST(:eid AS uuid),CAST(:id AS uuid)— никаких:x::type.Minor observations (не blocker)
start_price IS NULLrows silently dropped (filterstart_price = 0 OR last_price > start_price * 0.7→ NULL → fails WHERE). Older scrapes без start_price исключаются. Trade-off documented в PR body.PriceHistoryYearPoint.sourceтеперь required → breaking response shape для/house-analytics. Both backend и frontend updated в same PR — для internal app OK.n_changesв cian-price-changes = COUNT(oph rows) включает initial seed row (where diff_percent IS NULL) → UI badge↓Nможет overcount on 1. Cosmetic.SellTimeSensitivity(1 / 2-4 / 5+) пропускает 11-14, 21-24. Cosmetic.style={}— consistent с existing pattern вtradein-mvp/frontend/components/trade-in.Security
:eid,:ids,:id,:addr,:lat,:lon,:address)./sale/flat/(\d+)/использует escaped substring matcher in PostgreSQL.safeUrl()reuse дляlot.source_url.Performance
hph_house_idx (house_id, last_price_date DESC)covers main lookup.changes_aggдляfirst_seen_price— scope ограничен listings_resolved (typically <50 rows per estimate).staleTime: 10 * 60_000(10 min) на TanStack Query reuse pattern.Tests
Recommended next steps
/trade-in?id=d1570e00после deploy — verify 4 buckets render.n_changesso badge reflects actual price decreases, not raw history-row count.Complexity / blast radius
PriceHistoryYearPoint) внутренние, response-only.1776d2cfe8to0ac54d1de0Re-review after rebase — verdict: APPROVE
Rebase resolution clean. Prior approve verdict holds.
Rebase integration check (vs merged #547/#549/#550):
#547 PriceHistoryYearPoint split: main schema already hassource: strfield. PR #548 не трогаетPriceHistoryYearPoint— добавляет независимыеSellTimeBucket/SellTimeSensitivityResponse. Конфликта нет.HouseAnalyticsSection.tsx: чистая вставка —useEstimateSellTimeSensitivityhook +<SellTimeSensitivity>между KPI row иPriceHistoryChart(split chart из #547 не задет).#549 ДКП filter / #550 Росреестр button: затрагивают другие компоненты (RecentSoldList / экспорт), PR #548 их не пересекает.Math correctness (prior verdict re-confirmed):
NULLIF(area_m2, 0)guards 2x (benchmark + per-lot premium)COALESCE(last_price_date, start_price_date)для year extraction-10..-3 / -3..3 / 3..8 / 8..15(boundary collisions решены first-match-wins)premium_pct IS NOT NULLотбрасывает median_ppm2=0last_price > start_price * 0.7фильтр выбросовarea_m2 > 10+last_price > 100000sanityEdge cases:
house_ids→ early-return all-zero responsetarget_medianNULL → frontend renders "—"bucket_definitionsloopdata.buckets.every(b => b.n_lots === 0)→return null(graceful empty)Conventions: psycopg v3
CAST(:id AS uuid)✓, ruff line-100 ✓, TS strict types match Pydantic ✓.Merging (squash + delete branch).