gendesign/tradein-mvp/backend/app/services/cian_price_history.py
Light1YT 86e9ea2937 fix(week-review): автофиксы код-ревью — 169 issue (label «week ревью 1»)
Многоагентный аудит + имплементация: один воркер на файл, точечные правки.
Верификация: py_compile (47/47 .py) + tsc --noEmit (0 ошибок). Unit-тесты
не прогонялись (окружение не поднято: rollup native dep / нет pytest-venv).

Полностью исправлено (169): #1336, #1337, #1339, #1340, #1341, #1342, #1343, #1345, #1346, #1348, #1349, #1350, #1351, #1354, #1356, #1358, #1359, #1360, #1362, #1364, #1365, #1366, #1367, #1368, #1369, #1370, #1371, #1372, #1373, #1374, #1375, #1376, #1377, #1378, #1379, #1380, #1381, #1382, #1384, #1385, #1386, #1387, #1388, #1389, #1390, #1391, #1392, #1394, #1395, #1396, #1397, #1399, #1400, #1401, #1402, #1403, #1404, #1408, #1409, #1410, #1411, #1412, #1413, #1414, #1415, #1416, #1417, #1418, #1420, #1423, #1425, #1426, #1427, #1428, #1429, #1430, #1431, #1432, #1433, #1434, #1435, #1437, #1438, #1439, #1440, #1441, #1442, #1443, #1444, #1445, #1446, #1447, #1448, #1449, #1450, #1451, #1452, #1453, #1454, #1455, #1456, #1457, #1458, #1459, #1460, #1461, #1462, #1463, #1464, #1465, #1466, #1467, #1468, #1469, #1471, #1472, #1473, #1474, #1476, #1478, #1479, #1481, #1482, #1483, #1484, #1485, #1487, #1488, #1489, #1490, #1491, #1492, #1493, #1494, #1495, #1496, #1497, #1499, #1500, #1501, #1502, #1504, #1505, #1506, #1507, #1510, #1514, #1515, #1516, #1517, #1518, #1519, #1521, #1522, #1523, #1524, #1525, #1526, #1527, #1528, #1529, #1531, #1532, #1533, #1534, #1535, #1536, #1537, #1538

Частично (9, in-file часть, остаток cross-file): #1361, #1419, #1422, #1424, #1470, #1475, #1477, #1480, #1498
Требуют cross-file (3, не тронуты): #1338, #1363, #1421
Пропущено (1): #1539

Не входило в партию: 22 needs-Leha issue (нужны решения владельца).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-15 20:21:11 +05:00

171 lines
5.4 KiB
Python

"""T8a: Cian offer price-history backfill service.
Fetches Cian detail pages (curl_cffi, без Playwright) for listings that have
no rows in offer_price_history, extracts priceChanges from
_cianConfig['frontend-offer-card'] defaultState, writes to offer_price_history.
Deliberately NOT wired into scheduler — rate-limit risk with datacenter IPs.
Triggered manually via POST /api/v1/admin/scrape/cian-price-history.
"""
from __future__ import annotations
import asyncio
import logging
import time
from dataclasses import dataclass, field
from sqlalchemy import text
from sqlalchemy.orm import Session
from app.services.scraper_settings import get_scraper_delay
from app.services.scrapers.cian_detail import fetch_detail, save_detail_enrichment
logger = logging.getLogger(__name__)
@dataclass
class CianPriceHistoryResult:
checked: int = 0
saved: int = 0
skipped: int = 0
errors: int = 0
duration_sec: float = field(default=0.0)
async def backfill_cian_price_history(
db: Session,
*,
batch_size: int = 50,
listing_id: int | None = None,
) -> CianPriceHistoryResult:
"""Fetch Cian detail pages and write missing price-history rows.
Args:
db: SQLAlchemy session (caller-owned; commits internally per listing).
batch_size: max listings to process when listing_id is None.
listing_id: process a single specific listing (ignores batch_size).
Selection query picks cian listings with no existing offer_price_history rows.
Idempotent: re-run safe via ON CONFLICT DO NOTHING in save_detail_enrichment.
"""
result = CianPriceHistoryResult()
t0 = time.time()
delay = get_scraper_delay("cian") # default 5.0s
if listing_id is not None:
rows = (
db.execute(
text("""
SELECT l.id, l.source_url
FROM listings l
WHERE l.id = CAST(:lid AS bigint)
AND l.source = 'cian'
AND l.source_url IS NOT NULL
"""),
{"lid": listing_id},
)
.mappings()
.all()
)
else:
rows = (
db.execute(
text("""
SELECT l.id, l.source_url
FROM listings l
LEFT JOIN offer_price_history oph ON oph.listing_id = l.id
WHERE l.source = 'cian'
AND l.source_url IS NOT NULL
AND oph.listing_id IS NULL
ORDER BY l.id
LIMIT :lim
"""),
{"lim": batch_size},
)
.mappings()
.all()
)
result.checked = len(rows)
logger.info(
"cian_price_history backfill: checked=%d delay=%.1fs",
result.checked,
delay,
)
for i, row in enumerate(rows):
lid: int = row["id"]
url: str = row["source_url"]
try:
enrichment = await fetch_detail(url)
except Exception as exc:
logger.warning(
"cian_price_history: fetch failed listing_id=%s url=%s: %s",
lid,
url,
exc,
)
result.errors += 1
await asyncio.sleep(delay)
continue
if enrichment is None:
logger.warning(
"cian_price_history: fetch returned None listing_id=%s url=%s",
lid,
url,
)
result.errors += 1
await asyncio.sleep(delay)
continue
if not enrichment.price_changes:
logger.debug("cian_price_history: no price_changes listing_id=%s", lid)
result.skipped += 1
else:
try:
# Count rows actually inserted: save_detail_enrichment skips
# changes without change_time/price_rub and uses ON CONFLICT
# DO NOTHING, so len(price_changes) overcounts on invalid
# elements or idempotent re-runs. Diff the row count instead.
before = db.execute(
text(
"SELECT COUNT(*) FROM offer_price_history "
"WHERE listing_id = CAST(:lid AS bigint)"
),
{"lid": lid},
).scalar_one()
save_detail_enrichment(db, lid, enrichment)
after = db.execute(
text(
"SELECT COUNT(*) FROM offer_price_history "
"WHERE listing_id = CAST(:lid AS bigint)"
),
{"lid": lid},
).scalar_one()
result.saved += max(0, int(after) - int(before))
except Exception as exc:
logger.warning("cian_price_history: save failed listing_id=%s: %s", lid, exc)
result.errors += 1
try:
db.rollback()
except Exception:
pass
await asyncio.sleep(delay)
continue
if i < len(rows) - 1:
await asyncio.sleep(delay)
result.duration_sec = time.time() - t0
logger.info(
"cian_price_history done: checked=%d saved=%d skipped=%d errors=%d %.1fs",
result.checked,
result.saved,
result.skipped,
result.errors,
result.duration_sec,
)
return result