Commit graph

66 commits

Author SHA1 Message Date
lekss361
17ad0e18f5 feat(geo): ЖК → district mapping через PostGIS-полигоны OSM (Limit_District_Geometry closed)
- 56_fetch_ekb_districts.py: Overpass query (admin_level=9 в bbox ЕКБ),
  shapely-ассемблинг рваных OSM-веев в MultiPolygon, кэш в data/raw/.
- 56_schema_ekb_districts_geom.sql: CREATE TABLE с GIST.
- 57_kn_objects_district.sql: ALTER + backfill UPDATE через ST_Contains.
  3032 ЖК Свердл проставили district_name (208 в Академическом, 158 в Чкаловском,
  и т.д.), 454 за bbox ЕКБ остались NULL.
- domrf_kn.py: _backfill_district_names() после Phase A — каждый sweep
  автоматически проставляет district_name свежезаписанным ЖК.
- analytics_queries.py: 4 места addr ILIKE → district_name = :dn
  (_velocity_baseline, _elasticity_coef, _active_competitors_count, comparable).
- analytics_queries.py: graceful obj_class-degrade — если в районе все
  obj_class=NULL (kn-API quirk), фильтр по target_class опускается на уровне
  geo-запросов с warning. class_multiplier на ценах продолжает работать.

Smoke (Академический, Comfort, 50K м²): velocity_source=sale_graph (104 ЖК /
1872 точек), competitors=208 в районе, headline «3400 млн ₽ · 112 мес ·
ликвидность 21/100», 5 comparable ЖК района — все реалистичные.
2026-04-29 08:03:38 +03:00
lekss361
195d942ca7 feat: Tier α velocity overhaul + scraper FK fixes
Velocity model:
- _active_competitors_count() с каскадным fallback (район+класс → район → регион)
- Per-bucket velocity = bucket_market_v / sqrt(N_competitors) — sqrt-нормировка
  как proxy для эффективных конкурентов (power-law)
- Per-bucket market velocities из rosreestr (свой темп каждому сегменту,
  поэтому mix-слайдеры теперь двигают total)
- Headline format: f"{months:.1f}" вместо int() (закрывает «за 0 мес»)
- competitors_count + competitors_scope в scope, warning-badge в UI
  при rosreestr_fallback, methodology note показывает competitors

Scraper FK violations:
- _ensure_snapshot() ON CONFLICT DO NOTHING — закрыть FK на domrf_snapshots
  для domrf_raw_endpoints (Phase A insert до создания snapshot row)
- _ensure_developers() pre-upsert уникальных (dev_id, dev_name) перед
  upsert_objects, ON CONFLICT (developer_id) DO NOTHING — закрыть FK
  fk_kn_obj_developer
- SAVEPOINT (db.begin_nested) во всех 5 upsert helpers + _log_failure
  заменяет db.rollback() — теперь сбой одного row не сносит транзакцию

Bug Bug_Velocity_Mix_Static_OPEN, Bug_Velocity_Unrealistic_OPEN — закрыты
(numbers conservative до полного 442-sweep + sale_graph data fill).
2026-04-29 00:25:41 +03:00
lekss361
b74c7db438 fix(scraper): closing FK violations + transactional poisoning in upsert_objects
ForeignKeyViolation на dev_id='4777_0' / '5377_0' / etc — developer'ов нет
в domrf_developers (FK fk_kn_obj_developer). Plus, старый except: db.rollback()
откатывал ВСЮ транзакцию вместо текущего row → один FK-сбой убивал весь
Phase A.

- _ensure_developers(db, raw) — pre-upsert unique (dev_id, dev_name) перед
  upsert_objects, ON CONFLICT (developer_id) DO NOTHING. Fallback name
  'Developer #<companyGroup>' если все имена None.
- SAVEPOINT (db.begin_nested) во всех 5 upsert helper'ах + _log_failure
  заменяет db.rollback() — теперь сбой одного row не сносит транзакцию.
- Smoke verified против прод-БД: 4777_0/5377_0 закреплены, 6208_0 уже
  существовал — ON CONFLICT отработал.
2026-04-28 23:56:27 +03:00
lekss361
d1f2380f32 fix(sqlalchemy): убрать :name::type — psycopg3 их не парсит, ломает Phase A INSERT в kn_scrape_runs (run_region_sweep крашится сразу с ProgrammingError, task_received записан, но run_id никогда не создаётся). 4 места: domrf_kn.py (resume INSERT, new run INSERT, snapshot UPDATE) + admin_leads.py (date_to filter). Заменено на CAST(:name AS type). 2026-04-28 23:37:03 +03:00
lekss361
c3bc96535d fix(scraper): диагностируем «кнопка не работает» — Redis lock + task_received log
Симптом: POST /admin/scrape/kn возвращает task_id, но run_id не появляется
в kn_scrape_runs. Причина: зомби-worker оставил Redis-lock с TTL=2h, новые
задачи скипаются с reason='lock_held' молча.

Backend:
- _LOCK_TTL_SECONDS 7200 → 1800 (full sweep ~25-30 мин — потолок).
- force_release_lock() helper + новый POST /api/v1/admin/scrape/release-lock.
- TriggerKnRequest +force: bool — при true перед apply_async удалить lock.
- _log_task_received() / _log_task_skipped() — kn_scrape_log пишет «task
  подхвачен/skip» с run_id=NULL до основного flow. Теперь UI показывает
  whether worker реально получил задачу.

Frontend:
- Чекбокс  Force в форме запуска.
- Кнопка 🔓 Снять Redis-lock (отдельный endpoint).
- Уведомление о результате release.
2026-04-28 23:17:42 +03:00
lekss361
7a23aa9edc fix: heartbeat-based zombie autoclean (10min) + Phase A heartbeats; ship recommend velocity calculator
Scraper resume:
- /admin/scrape/queue autoclean уменьшен с 60min started_at до 10min
  COALESCE(heartbeat_at, started_at). Не режет валидные long sweeps.
- Phase A пишет heartbeat после каждого objStatus fetch (3min Phase A
  больше не рискует быть отмеченной как zombie при новом 10min threshold).

Recommend (Уровень 1 калькулятор):
- POST /api/v1/analytics/recommend/mix с velocity baseline (sale_graph),
  price elasticity (regr_slope/r2 на sale_graph, fallback -1.5),
  inverse mode (target_months → required price_factor), liquidity score
  24mo, headline.
- /analytics/recommend: RecommendVelocityPanel (price slider 0.85..1.15
  + 4 KPI Чек/Срок/Темп/Ликвидность + методология эластичности),
  RecommendLiquidityChart (cumulative 0..36 mo с пунктиром на 24).
- BucketsTable: +колонки Темп и Срок, цены/выручка масштабируются по
  priceFactor live.
- Все слайдеры и target_months считаются клиентски — никаких round-trip.

Fix: SQLAlchemy не парсит :cls::text — заменено на CAST(:cls AS TEXT).
2026-04-28 22:54:03 +03:00
lekss361
1507575698 fix alch 2026-04-27 22:03:48 +03:00
lekss361
8dda3903e5 add log scrapper 2026-04-27 21:50:44 +03:00
lekss361
62659887e9 add rec ui 2026-04-27 21:38:37 +03:00
lekss361
ecc0dbafd5 add predict 2026-04-27 21:28:02 +03:00
lekss361
12b1eb8169 add logs 2026-04-27 20:51:44 +03:00
lekss361
a56216aeb9 fix ui 2026-04-27 20:42:18 +03:00
lekss361
b3c15bb8ea fix ui lag 2026-04-27 20:26:55 +03:00
lekss361
c079ac2a77 fix photo 2026-04-27 20:06:18 +03:00
lekss361
5056438fcf add anal4 2026-04-27 19:45:47 +03:00
lekss361
522ecca5c4 ship #13-16: multi-target Dockerfile, per-object drill-in, CRM pipeline,
442-sweep instructions
#16 Dockerfile: runner (lean, 1.6 GB) + runner-with-chromium (2.9 GB).
   Compose + deploy.yml pushes 2 GHCR images. Backend saves 1.3 GB.
#15 5 backend object endpoints + /analytics/objects/[id] page (gallery,
   POI table, sale chart) + sparkline-driven PrinzipObjectsTable.
#14 prinzip_leads/deals + 2 MVs. Import script with PII-hashing &
   --inspect-only mode. 3 funnel endpoints + Sankey/Monthly charts.
#13 README section with UI/CLI/SQL for 442-object sweep.
2026-04-27 19:32:37 +03:00
lekss361
7c4197000f add monitor scrappers 2026-04-27 19:04:01 +03:00
lekss361
bfee5ea916 fix 2026-04-27 18:59:56 +03:00
lekss361
692a4fc5eb add log 2026-04-27 18:52:21 +03:00
lekss361
75c2025ba0 redme 2026-04-27 18:40:44 +03:00
lekss361
6d3fa8cbd2 add domrf extras parser (sale_graph + sales_agg + infra + photos) +
fix Docker build for playwright

- Regenerate uv.lock with playwright + tenacity (was missing → uv sync
  --frozen skipped them, hence playwright not in /app/.venv/bin/).
- Dockerfile: explicit Chromium runtime libs in apt (libnss3 + 14 more)
  + `playwright install chromium` BEFORE apt-lists cleanup.
- Schema 51_schema_kn_extras.sql: 5 new tables for time-series sales,
  current aggregates, POI infrastructure, photo metadata, failure log.
- Scraper: 4 new fetch helpers + upserts; photo binary download via
  Playwright APIRequest; failure-logging with full_url to kn_scrape_failures.
- CLI: --no-extras / --download-photos / --no-flats / --probe URL.
- Admin UI: extras checkboxes + failures table with copy-URL button.
- PRINZIP smoke: 28 objs, 5409 POI, 5150 photos metadata, sales_agg
  matches probe (Парк Победы 145/291 = 49%).
2026-04-27 18:35:46 +03:00
lekss361
621d56c064 fix 2026-04-27 18:12:57 +03:00
lekss361
1ae4c9522d fix 2026-04-27 18:04:00 +03:00
lekss361
79070bfe99 add interactive parser of наш.дом.рф ЖК+flats with stealth Playwright
- Discovered real endpoints via chrome-devtools: /сервисы/api/kn/object
  (offset/limit/place/objStatus) + /portal-kn/api/sales/portal/table.
  Server-side filter ignored — local filter by developer.companyGroup.
- Pure Playwright in-context fetch (httpx blocked by ServicePipe TLS-fp).
- Saved fingerprint state in data/playwright_state.json for server reuse.
- Celery beat (configurable cron + jitter) + admin trigger endpoint
  + /admin/scrape UI page.
- Schema migration: UNIQUE(id, snapshot_date) for versioned snapshots,
  kn_scrape_runs journal.
- Smoke-tested on PRINZIP: 28 ЖК / 826 квартир as expected.
2026-04-27 17:58:40 +03:00
lekss361
8d3a0874ef add interactive analytics dashboard for Sverdlovsk market and PRINZIP
3 pages (market, PRINZIP drilldown, developers leaderboard) on top of
existing v_developer_full_metrics + domrf_realization views. ECharts on
the frontend, FastAPI router /api/v1/analytics on the backend.
2026-04-27 16:55:30 +03:00
lekss361
16481868a6 add anal 2 2026-04-27 13:05:36 +03:00
lekss361
c13cbaef2e add data 2026-04-26 22:30:52 +03:00
lekss361
a2dcd9844a add link 2026-04-26 18:35:55 +03:00
lekss361
e84115a185 add nspd 2026-04-26 18:20:59 +03:00
lekss361
a5e5ad31e6 add rosreestr 2026-04-26 17:40:05 +03:00
lekss361
6c90c79859 anal.. 2026-04-26 17:14:44 +03:00
lekss361
a2728637ad anal 3 2026-04-26 16:04:11 +03:00
lekss361
0569ccdcf3 anal2 2026-04-26 15:30:02 +03:00
lekss361
ae8abf9f15 domrf api 2026-04-26 15:21:53 +03:00
lekss361
14a9b1415e add anal 2026-04-26 15:18:31 +03:00
lekss361
b132091fe7 docs+memory: HTTPS live, Apr26 catch-up
- README: status table reflects HTTPS-live state
- memory: +HTTPS_Live_Apr26 entity (the chain ESIA→DNS→cert,
  caddy_data wipe needed to clear staging-fallback retry queue)
2026-04-26 14:50:17 +03:00
lekss361
b7230f1bc8 deploy.yml: sync compose+Caddyfile from git, reload caddy after up 2026-04-26 14:26:57 +03:00
lekss361
1f9dde2bf3 backend: pin setuptools package to app/
CI build broke after adding `alembic/` and `db/` directories — flat-layout
auto-discovery saw three top-level dirs and refused to pick. Make it
explicit: only `app/` is a Python package, the rest are ops/migration data.
2026-04-26 13:59:54 +03:00
lekss361
a1633bf6db docs+memory: catch up — domain, Sentry, ops bundle, prod wipe Apr26
- README: status table updated to 2026-04-26 (gendsgn.ru pending DNS,
  Sentry live, healthchecks all green, multi-stage images deployed),
  added ops/ and backend/db/init/ to repo layout, "operational gotchas"
  section (restart vs --force-recreate; reset --hard clobbers manual edits).
- memory/memory-gendesign.jsonl: +5 entities (Domain_Setup_Apr26,
  Sentry_Setup_Apr26, OpsBundle_Apr26, Production_Wipe_Apr26, DockerOps_Apr26)
  + 8 relations linking them into the graph. 34 lines → 47.
2026-04-26 13:42:55 +03:00
lekss361
6c4ba1777a deploy.yml: sync compose+Caddyfile from git, reload caddy after up 2026-04-26 13:31:26 +03:00
lekss361
4f034bd86b ops: alembic baseline, pre-commit, TIGER cleanup, pg_dump scripts
- backend/alembic/* — alembic infra (env.py, script.py.mako). versions/ empty
  for now; first migration goes in Stage 2a when models are finalized.
- backend/Dockerfile: bake alembic.ini + alembic/ into the image so
  `docker compose exec backend alembic upgrade head` works in prod.
- backend/db/init/99_drop_unused_extensions.sql + bind-mount in both compose
  files: drops postgis-image's TIGER/topology/fuzzystrmatch on fresh volumes.
- .pre-commit-config.yaml + pre-commit in dev deps: ruff/prettier on commit
  to stop CI failures like UP035 from leaking out.
- ops/backup.sh, ops/restore.sh: pg_dump cron script with optional Selectel S3
  upload. 7-day local retention. Restore guard: requires RESTORE_CONFIRM=yes.
- Makefile: new targets `make migration NAME=...`, `make pre-commit-install`.
- backend/.env.example: SENTRY_DSN comment with sentry.io reference.
2026-04-26 13:08:51 +03:00
lekss361
68e95aa1ce ops: real domain in Caddyfile + ignore egg-info 2026-04-26 12:49:20 +03:00
lekss361
08a63f611d backend: fix mypy errors in geometry stub
- empty_buildings: dict → dict[str, Any] (mypy strict needs type args)
- drop unused `# type: ignore[arg-type]` on strategy= (mypy now narrows
  the loop variable to Literal[...] from a tuple of literals)
2026-04-26 11:02:22 +03:00
lekss361
d0909e6200 backend: ruff lint fixes
- main.py: AsyncIterator from collections.abc (typing.AsyncIterator deprecated, UP035)
- geometry.py: TEAP first in import (isort: ALL_CAPS before MixedCase, I001)
- pyproject.toml: ignore RUF001/002/003 — Russian-language project legitimately
  uses Cyrillic lookalikes in comments/docstrings (МСК-66 etc).

Verified: ruff check . — All checks passed!

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-26 10:53:50 +03:00
lekss361
e22aeb9b5a Docker: multi-stage backend, npm ci, healthcheck fix, same-origin API
- backend/Dockerfile: split builder/runner, runtime libs only, non-root app user, curl for healthcheck, --frozen via new uv.lock
- frontend/Dockerfile: npm ci instead of npm install (deterministic), USER node
- docker-compose.prod.yml: working backend healthcheck (curl now in image), redis healthcheck, drop dead NEXT_PUBLIC_API_BASE_URL env (Next.js bakes NEXT_PUBLIC_* at build time, runtime override is no-op)
- docker-compose.yml: same redis healthcheck, BACKEND_URL for next.config rewrites, drop uv from CMD (not in new image)
- Caddyfile: handle (not handle_path) so /api prefix is preserved into FastAPI router
- next.config.ts: rewrite /api/* and /health to BACKEND_URL in dev (no Caddy locally)
- frontend/src/lib/api.ts: empty default = same-origin relative URLs
- Makefile: drop uv run from migrate target
- Add backend/uv.lock and frontend/package-lock.json for reproducible builds

Verified: docker build succeeds for both, backend container starts, /health responds, curl healthcheck works inside image, container runs as non-root.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-26 10:47:35 +03:00
lekss361
c8b2cc8152 fix 2026-04-25 20:59:26 +03:00
lekss361
9d95b80b54 test 2026-04-25 20:33:13 +03:00
lekss361
4bd70cde06 Memory: catch up — hosting research, sales tracking, plan A, runbook, hardening 2026-04-25 20:29:07 +03:00
lekss361
09b9f18d3f Add empty frontend/public/ for Next.js standalone Docker build 2026-04-25 20:04:04 +03:00
lekss361
93c5f3f4a9 Fix frontend build: react-leaflet v5 + npm legacy-peer-deps 2026-04-25 20:00:55 +03:00