diff --git a/backend/app/api/v1/parcels.py b/backend/app/api/v1/parcels.py index 173e1af8..047f10e0 100644 --- a/backend/app/api/v1/parcels.py +++ b/backend/app/api/v1/parcels.py @@ -140,7 +140,7 @@ def _fetch_seasonal_weather_sync(lat: float, lon: float) -> dict | None: "period": "1995-2024 (30 лет)", "model": "MRI-AGCM3-2-S", "source": "open-meteo-climate", - "note": ("Климатические нормали. " "Текущая погода — отдельный API."), + "note": ("Климатические нормали. Текущая погода — отдельный API."), } except Exception as e: logger.warning("seasonal weather fetch failed: %s", e) @@ -274,6 +274,95 @@ GEOTECH_BY_REGION: dict[int, dict[str, Any]] = { } +def _aggregate_pipeline(rows: list[Any]) -> dict[str, Any]: + """D4 (#36) — собрать pipeline_24mo aggregate из rows domrf_kn_objects. + + Метрики: + - objects_count, flats_total + - by_class: {economy: int, comfort: int, business: int, unknown: int} + - by_quarter: {"2026-Q1": {objects: N, flats: M}, ...} + - severity: low / medium / high (по flats_total) + - top_objects: первые 10 ближайших / крупнейших ЖК + + Используется для UI pipeline-bar и severity badge. + """ + if not rows: + return { + "objects_count": 0, + "flats_total": 0, + "by_class": {}, + "by_quarter": [], + "severity": "none", + "top_objects": [], + "note": "Нет ЖК в pipeline 24мес в радиусе 5км — низкая будущая конкуренция", + } + + by_class: dict[str, int] = {} + by_quarter: dict[str, dict[str, int]] = {} + flats_total = 0 + + for r in rows: + cls = (r["obj_class"] or "unknown").lower().strip() or "unknown" + flats = int(r["flat_count"]) if r["flat_count"] else 0 + flats_total += flats + by_class[cls] = by_class.get(cls, 0) + flats + + ready = r["ready_dt"] + if ready: + q = (ready.month - 1) // 3 + 1 + key = f"{ready.year}-Q{q}" + slot = by_quarter.setdefault(key, {"objects": 0, "flats": 0}) + slot["objects"] += 1 + slot["flats"] += flats + + # Severity (#36 acceptance — порог 500 / 3000): + if flats_total < 500: + severity = "low" + elif flats_total < 3000: + severity = "medium" + else: + severity = "high" + + severity_label = { + "low": "низкая", + "medium": "средняя", + "high": "высокая", + }[severity] + + # Sort quarters chronologically + quarters_sorted = [{"quarter": k, **v} for k, v in sorted(by_quarter.items())] + + # Top objects — по flat_count desc + top_objects = sorted( + [dict(r) for r in rows], + key=lambda r: r.get("flat_count") or 0, + reverse=True, + )[:10] + + # Serialize date for JSON + for obj in top_objects: + if obj.get("ready_dt"): + obj["ready_dt"] = obj["ready_dt"].isoformat() + if obj.get("distance_m"): + obj["distance_m"] = round(float(obj["distance_m"])) + + return { + "objects_count": len(rows), + "flats_total": flats_total, + "by_class": by_class, + "by_quarter": quarters_sorted, + "severity": severity, + "severity_label": severity_label, + "top_objects": top_objects, + "radius_km": 5, + "horizon_months": 24, + "note": ( + "Будущая конкуренция за покупателя: planned_commissioning от Росреестра " + "часто оптимистичен (сдвиги по факту). Pressure-балл — относительный." + ), + } + + def _geotech_risk(region_code: int, db: Session, geom_wkt: str) -> dict[str, Any]: """Геотехнические риски: сейсмика (ОСР-2016) + промышленная близость. @@ -516,6 +605,45 @@ def analyze_parcel( .all() ) + # 5b) D4 (#36): Pipeline 24mo — ЖК-конкуренты сдающиеся в горизонте 24 мес + # в радиусе 5км. ready_dt = planned commissioning. Группируем по obj_class + # + по кварталам сдачи. + pipeline_rows = ( + db.execute( + text(""" + WITH latest_obj AS ( + SELECT DISTINCT ON (obj_id) * + FROM domrf_kn_objects + WHERE latitude IS NOT NULL + AND ready_dt IS NOT NULL + ORDER BY obj_id, snapshot_date DESC NULLS LAST + ) + SELECT obj_id, + comm_name, + dev_name, + obj_class, + flat_count, + ready_dt, + ST_Distance( + ST_SetSRID(ST_MakePoint(o.longitude, o.latitude), 4326)::geography, + ST_Centroid(ST_GeomFromText(:wkt, 4326))::geography + ) AS distance_m + FROM latest_obj o + WHERE ST_DWithin( + ST_SetSRID(ST_MakePoint(o.longitude, o.latitude), 4326)::geography, + ST_Centroid(ST_GeomFromText(:wkt, 4326))::geography, + 5000 + ) + AND ready_dt >= CURRENT_DATE + AND ready_dt < CURRENT_DATE + INTERVAL '24 months' + ORDER BY ready_dt ASC + """), + {"wkt": geom_wkt}, + ) + .mappings() + .all() + ) + # 6) Centroid координаты для внешних API (air quality / wind) centroid_row = ( db.execute( @@ -906,6 +1034,9 @@ def analyze_parcel( score_final = score + center_bonus + # D4 (#36): aggregate pipeline_24mo + pipeline_24mo = _aggregate_pipeline(pipeline_rows) + return { "cad_num": cad_num, "source": source, @@ -928,6 +1059,8 @@ def analyze_parcel( "note": "Бонус к score: <5км +3.0, 5-10км +1.5, 10-15км +0.5, >15км 0", }, "competitors": [dict(c) for c in competitor_rows], + # D4 (#36): 24-month pipeline competition + "pipeline_24mo": pipeline_24mo, "noise": { "score": round(noise_score, 2), "estimated_db": round(noise_db_max, 1), diff --git a/frontend/src/components/site-finder/MarketTab.tsx b/frontend/src/components/site-finder/MarketTab.tsx index 727bfcec..b7215d3f 100644 --- a/frontend/src/components/site-finder/MarketTab.tsx +++ b/frontend/src/components/site-finder/MarketTab.tsx @@ -3,6 +3,7 @@ import type { ParcelAnalysis } from "@/types/site-finder"; import { MarketTrendBlock } from "./MarketTrendBlock"; import { CompetitorTable } from "./CompetitorTable"; +import { Pipeline24moBlock } from "./Pipeline24moBlock"; import { SuccessRecommendationBlock } from "./SuccessRecommendationBlock"; interface Props { @@ -12,10 +13,15 @@ interface Props { export function MarketTab({ data }: Props) { const hasTrend = "market_trend" in data; const hasRecommendation = "success_recommendation" in data; - const hasAny = hasTrend || hasRecommendation || data.competitors.length > 0; + const hasPipeline = data.pipeline_24mo !== undefined; + const hasAny = + hasTrend || hasRecommendation || hasPipeline || data.competitors.length > 0; return (
| + ЖК + | ++ Класс + | ++ Квартир + | ++ Сдача + | +
|---|---|---|---|
| + {obj.comm_name ?? obj.dev_name ?? "—"} + | ++ {obj.obj_class ? fmtClass(obj.obj_class) : "—"} + | ++ {obj.flat_count?.toLocaleString("ru-RU") ?? "—"} + | ++ {obj.ready_dt ? obj.ready_dt.substring(0, 7) : "—"} + | +