feat(движок): смета считается по ценовой зоне места стройки, а не по одной вшитой форме
Цены ресурсов берутся из разобранной формы ФГИС той зоны, что названа в запросе (engine_prices: каталог по зонам и периодам, JSON). Без региона или при нескольких зонах — отказ без чисел и уточнение; без квартала — последний период с пометкой; ресурсы без цены в форме зоны — список и неполный итог. Панель показывает основу цен, пересчёт повторяет ту же зону. Чекер и панель состояния вместо «выбери регион и примени» следят за собранностью цен по зонам. Версия 2026-09-14c. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01ADvViaqN9hgCWVNH3HVQ6r
This commit is contained in:
+71
-121
@@ -42,41 +42,64 @@ def _mock_pravo(monkeypatch, new_docs):
|
||||
monkeypatch.setattr(pc, "new_since", lambda seen, max_pages=8, client=None: new_docs)
|
||||
|
||||
|
||||
def _set_engine(subject=323, zone=191, period=426):
|
||||
"""Обозначить движковую зону + применённый период (st['active']). База денежного сигнала."""
|
||||
with es.update_state() as st:
|
||||
st.setdefault("active", {})["fgis_split_form"] = {
|
||||
"subject": subject, "zone": zone, "period_id": period}
|
||||
def _snapshot(root, key, sha):
|
||||
s, z, p = key.split("/")
|
||||
d = root / "snapshots" / "fgis" / "split_form" / s / z / p
|
||||
d.mkdir(parents=True, exist_ok=True)
|
||||
(d / "meta.json").write_text(json.dumps({"sha256": sha, "file": "fgis_split_form.xlsx"}),
|
||||
encoding="utf-8")
|
||||
|
||||
|
||||
def test_new_period_produces_finding_with_action(_tmp, monkeypatch):
|
||||
def _catalog(root, zones):
|
||||
d = root / "derived" / "engine_prices"
|
||||
d.mkdir(parents=True, exist_ok=True)
|
||||
(d / "catalog.json").write_text(json.dumps({"built_at": "2026-09-14T00:00:00Z", "zones": [
|
||||
{"subject_id": int(k.split("/")[0]), "zone_id": int(k.split("/")[1]),
|
||||
"period_id": int(k.split("/")[2]), "sha256": sha, "period_label": "3 квартал 2026",
|
||||
"zone_name": "город Москва", "subject_name": "Москва", "file": f"{k}.json"}
|
||||
for k, sha in zones.items()]}), encoding="utf-8")
|
||||
|
||||
|
||||
def _engine_synced(root):
|
||||
"""Цены движка собраны по всем скачанным формам — чекер о движке молчит."""
|
||||
_snapshot(root, "323/191/426", "a")
|
||||
_catalog(root, {"323/191/426": "a"})
|
||||
|
||||
|
||||
def _engine_findings(rep):
|
||||
return [f for f in rep["findings"] if f["source"] == "engine_prices"]
|
||||
|
||||
|
||||
def test_движку_больше_не_предлагается_применить_регион(_tmp, monkeypatch):
|
||||
"""С 14.09.2026 движок считает по зоне из запроса: «выбери регион и примени» — ложный совет."""
|
||||
_mock_fgis(monkeypatch, latest=426)
|
||||
_mock_pravo(monkeypatch, [])
|
||||
_set_engine(period=425) # движку применён 425 → latest 426 новее → сигнал «примени»
|
||||
_snapshot(_tmp, "323/191/426", "a")
|
||||
_catalog(_tmp, {"323/191/426": "a"})
|
||||
rep = ec.run_check(regions=[323], notify=False)
|
||||
ups = [f for f in rep["findings"] if f["source"] == "fgis_split_form"]
|
||||
assert len(ups) == 1 and "426" in ups[0]["message"] and "ext_apply.py" in ups[0]["action"]
|
||||
assert not [f for f in rep["findings"] if "примен" in f["message"]], rep["findings"]
|
||||
assert not _engine_findings(rep)
|
||||
|
||||
|
||||
def test_no_finding_when_period_is_active(_tmp, monkeypatch):
|
||||
def test_несобранные_цены_движка_проблема_каждый_прогон(_tmp, monkeypatch):
|
||||
"""Каталога нет — движок откажет в любом расчёте; сигнал не одноразовый."""
|
||||
_mock_fgis(monkeypatch, latest=426)
|
||||
_mock_pravo(monkeypatch, [])
|
||||
_set_engine(period=426) # движок уже на latest → тишина
|
||||
rep = ec.run_check(regions=[323], notify=False)
|
||||
assert not [f for f in rep["findings"] if f["source"] == "fgis_split_form"]
|
||||
_snapshot(_tmp, "323/191/426", "a")
|
||||
for _ in range(2):
|
||||
f = _engine_findings(ec.run_check(regions=[323], notify=False))
|
||||
assert f and f[0]["level"] == "problem", f
|
||||
|
||||
|
||||
def test_autopull_does_not_silence_apply_signal(_tmp, monkeypatch):
|
||||
"""КЛЮЧ money-safety: авто-закачка обновила ПУЛЛ (sources) до latest, но движок применён на
|
||||
старом периоде → сигнал «пора применить» ДОЛЖЕН остаться (иначе движок молча по старым ценам)."""
|
||||
_mock_fgis(monkeypatch, latest=430)
|
||||
def test_перезалитая_или_новая_форма_требует_сборки(_tmp, monkeypatch):
|
||||
_mock_fgis(monkeypatch, latest=426)
|
||||
_mock_pravo(monkeypatch, [])
|
||||
_set_engine(period=426) # движок на 426
|
||||
with es.update_state() as st:
|
||||
st["sources"]["fgis_split_form"] = {"323/191": {"period_id": 430}} # авто-pull подтянул 430
|
||||
rep = ec.run_check(regions=[323], notify=False)
|
||||
ups = [f for f in rep["findings"] if f["source"] == "fgis_split_form" and f["level"] == "update"]
|
||||
assert len(ups) == 1 and "430" in ups[0]["message"] # не заглушено скачанным 430
|
||||
_snapshot(_tmp, "323/191/426", "новая-сумма")
|
||||
_snapshot(_tmp, "264/118/427", "b")
|
||||
_catalog(_tmp, {"323/191/426": "старая-сумма"})
|
||||
f = _engine_findings(ec.run_check(regions=[323], notify=False))
|
||||
assert f and f[0]["level"] == "update" and "2 зон" in f[0]["message"], f
|
||||
assert "build_engine_prices.py" in f[0]["action"]
|
||||
|
||||
|
||||
def test_checker_does_not_mutate_state_json(_tmp, monkeypatch):
|
||||
@@ -142,77 +165,16 @@ def test_one_zone_period_failure_does_not_kill_run(_tmp, monkeypatch):
|
||||
|
||||
def test_notify_failure_keeps_findings_for_retry(_tmp, monkeypatch):
|
||||
"""HIGH-фикс: важная находка + письмо НЕ ушло → watch_seen НЕ сохраняется → повтор (не потеря)."""
|
||||
_mock_fgis(monkeypatch, latest=430)
|
||||
_mock_pravo(monkeypatch, [])
|
||||
_mock_fgis(monkeypatch, latest=426)
|
||||
_engine_synced(_tmp)
|
||||
_mock_pravo(monkeypatch, [{"eoNumber": "E9", "number": "9/пр", "name": "Об индексах сметной стоимости",
|
||||
"documentDate": "2026-07-01", "relevant": True, "pdf_url": "u"}])
|
||||
monkeypatch.setenv("OPERATOR_EMAIL", "") # адреса нет → _notify вернёт False при updates
|
||||
_set_engine(period=425) # движок на 425, latest 430 → сигнал «примени»
|
||||
rep = ec.run_check(regions=[323], notify=True)
|
||||
assert rep["notify_ok"] is False
|
||||
# дедуп НЕ сохранён → на следующем прогоне находка повторится
|
||||
assert es.load_watch_seen().get("fgis_periods_reported", {}).get("323/191") != 430
|
||||
assert "E9" not in es.load_watch_seen().get("pravo_eo", []) # метка «доложено» не осела
|
||||
rep2 = ec.run_check(regions=[323], notify=True)
|
||||
assert any(f["source"] == "fgis_split_form" for f in rep2["findings"])
|
||||
|
||||
|
||||
def test_rollback_reports_again(_tmp, monkeypatch):
|
||||
"""Исполняет ветку reported.pop (Fable: старый тест её не проверял — мутация «убрать pop»
|
||||
выживала). Последовательность: gap+доклад (метка ВЫСТАВЛЕНА) → применили latest (pop, метка снята)
|
||||
→ откат применения → снова доклад. Мутант без pop даст тишину на 3-м шаге."""
|
||||
_mock_fgis(monkeypatch, latest=426)
|
||||
_mock_pravo(monkeypatch, [])
|
||||
_set_engine(period=425) # движок на 425
|
||||
rep1 = ec.run_check(regions=[323], notify=False) # gap → доклад, метка=426
|
||||
assert any(f["source"] == "fgis_split_form" and "426" in f["message"] for f in rep1["findings"])
|
||||
assert es.load_watch_seen()["fgis_periods_reported"].get("323/191") == 426
|
||||
_set_engine(period=426) # применили latest → синхронно
|
||||
ec.run_check(regions=[323], notify=False) # pop снимает метку
|
||||
assert not es.load_watch_seen().get("fgis_periods_reported", {}).get("323/191")
|
||||
_set_engine(period=425) # откат применения → 425
|
||||
rep3 = ec.run_check(regions=[323], notify=False)
|
||||
assert any(f["source"] == "fgis_split_form" and "426" in f["message"] for f in rep3["findings"])
|
||||
|
||||
|
||||
def test_engine_unset_signal_repeats(_tmp, monkeypatch):
|
||||
"""Движку ничего не применено → сигнал ПОВТОРЯЕТСЯ каждый прогон (Fable: раньше был one-shot
|
||||
навсегда — пропустил письмо, тишина). Денежный риск не рассасывается сам."""
|
||||
_mock_fgis(monkeypatch, latest=426)
|
||||
_mock_pravo(monkeypatch, []) # engine не задаём → unset
|
||||
r1 = ec.run_check(regions=[323], notify=False)
|
||||
r2 = ec.run_check(regions=[323], notify=False)
|
||||
def sig(rep):
|
||||
return [f for f in rep["findings"] if f["source"] == "fgis_split_form"
|
||||
and "не применён ни один регион" in f["message"]]
|
||||
assert sig(r1) and sig(r2)
|
||||
|
||||
|
||||
def test_legacy_active_without_period_is_reapply_not_silent(_tmp, monkeypatch):
|
||||
"""Дефект Fable: active есть, но БЕЗ метаданных (legacy/без --period) → сигнал «перепримени с
|
||||
--period» КАЖДЫЙ прогон, а не ложное «ничего не применяли» и не тишина о реальном устаревании."""
|
||||
_mock_fgis(monkeypatch, latest=430)
|
||||
_mock_pravo(monkeypatch, [])
|
||||
with es.update_state() as st: # legacy: только target/sha, без subject/zone/period
|
||||
st.setdefault("active", {})["fgis_split_form"] = {"target": "/x.xlsx", "sha256": "ab"}
|
||||
r1 = ec.run_check(regions=[323], notify=False)
|
||||
r2 = ec.run_check(regions=[323], notify=False)
|
||||
def unk(rep):
|
||||
return [f for f in rep["findings"] if f["source"] == "fgis_split_form"
|
||||
and "период неизвестен" in f["message"]]
|
||||
assert unk(r1) and unk(r2) # повторяется, не one-shot
|
||||
assert not any("не применён ни один регион" in f["message"] for f in r1["findings"]) # НЕ ложное
|
||||
|
||||
|
||||
def test_engine_gap_signalled_even_if_zone_not_monitored(_tmp, monkeypatch):
|
||||
"""Движковая зона вне EXT_REGIONS → apply-gap всё равно проверяется отдельным запросом
|
||||
(Fable: ветка была не покрыта). Иначе узкий EXT_REGIONS потерял бы денежный сигнал."""
|
||||
monkeypatch.setattr(fc, "alive", lambda client=None: True)
|
||||
monkeypatch.setattr(fc, "price_zones", lambda s, client=None: [{"id": 500, "name": "зона корпуса"}])
|
||||
monkeypatch.setattr(fc, "latest_period",
|
||||
lambda z, client=None: {"id": 430, "name": "п430"} if z == 191 else {"id": 410, "name": "п410"})
|
||||
_mock_pravo(monkeypatch, [])
|
||||
_set_engine(subject=323, zone=191, period=426) # движок 323/191@426, но мониторим регион 77
|
||||
rep = ec.run_check(regions=[77], notify=False)
|
||||
assert any(f["source"] == "fgis_split_form" and f["level"] == "update" and "430" in f["message"]
|
||||
for f in rep["findings"])
|
||||
assert any(f["source"] == "pravo" for f in rep2["findings"])
|
||||
|
||||
|
||||
def test_new_sources_seed_then_update_then_dedup(_tmp, monkeypatch):
|
||||
@@ -264,32 +226,18 @@ def test_checker_bug_becomes_problem_not_crash(_tmp, monkeypatch):
|
||||
|
||||
|
||||
def test_crash_midcheck_does_not_mark_undelivered_finding(_tmp, monkeypatch):
|
||||
"""КРИТ (репро Fable): чекер падает не-FetchError ПОСЛЕ того как зона A дала находку «новый
|
||||
период» и пометила её 'доложено' in-place. Метка не должна осесть в seen — иначе на следующем
|
||||
прогоне (когда сбой ушёл) находка потеряется НАВСЕГДА, регион будет считаться по старым
|
||||
индексам. Проверяем: сбой ушёл → находка доходит. Падает на старом _safe_check (без deep-copy)."""
|
||||
monkeypatch.setattr(fc, "alive", lambda client=None: True)
|
||||
monkeypatch.setattr(fc, "price_zones", lambda s, client=None:
|
||||
[{"id": 191, "name": "зона A"}, {"id": 999, "name": "зона B"}])
|
||||
_mock_pravo(monkeypatch, [])
|
||||
_set_engine(subject=323, zone=191, period=426) # 191 — движковая зона, применён 426
|
||||
# ключ fgis_periods_reported УЖЕ есть (метка другой зоны) → reported = ссылка ВНУТРЬ seen,
|
||||
# значит reported[323/191]=430 мутирует seen in-place ДО краха (иначе баг не воспроизводится).
|
||||
es.save_watch_seen({"fgis_periods_reported": {"999/000": 1}})
|
||||
flag = {"boom": True}
|
||||
def latest(z, client=None):
|
||||
if z == 999 and flag["boom"]:
|
||||
raise TypeError("нежданный баг в зоне B") # НЕ FetchError — эмулируем баг чекера
|
||||
return {"id": 430, "name": "период 430"} if z == 191 else {"id": 300, "name": "стар"}
|
||||
monkeypatch.setattr(fc, "latest_period", latest)
|
||||
"""КРИТ (репро Fable): чекер пометил находку «доложено» прямо в seen и упал до конца цикла.
|
||||
Метка не должна осесть — иначе после ухода сбоя находка потеряется навсегда. Защищает копия
|
||||
seen в _safe_check; падает на _safe_check без deep-copy."""
|
||||
seen = {"pravo_eo": ["E1"]}
|
||||
|
||||
rep1 = ec.run_check(regions=[323], notify=False) # ПРОГОН 1 — краш в зоне B
|
||||
assert any(f["source"] == "check_fgis" and f["level"] == "problem" for f in rep1["findings"])
|
||||
assert not [f for f in rep1["findings"] if f["source"] == "fgis_split_form"] # A не доставлена
|
||||
def падающий(work):
|
||||
work["pravo_eo"].append("E2") # пометил «доложено» in-place
|
||||
raise TypeError("нежданный баг посреди цикла") # НЕ FetchError — баг чекера
|
||||
|
||||
flag["boom"] = False # сбой ушёл
|
||||
rep2 = ec.run_check(regions=[323], notify=False) # ПРОГОН 2 — находка A ДОЛЖНА дойти
|
||||
assert any(f["source"] == "fgis_split_form" and "430" in f["message"] for f in rep2["findings"])
|
||||
findings, after = ec._safe_check("check_pravo", падающий, seen)
|
||||
assert any(f["source"] == "check_pravo" and f["level"] == "problem" for f in findings)
|
||||
assert after == {"pravo_eo": ["E1"]} and seen == {"pravo_eo": ["E1"]}
|
||||
|
||||
|
||||
def test_regions_all_but_unreachable_is_problem(_tmp, monkeypatch):
|
||||
@@ -352,7 +300,7 @@ def test_bim_index_absent_recurrent_info_not_update(_tmp, monkeypatch):
|
||||
(видно в отчёте/панели), но НЕ update: ежедневное письмо не должно продавливать гейт."""
|
||||
_mock_fgis(monkeypatch, latest=426)
|
||||
_mock_pravo(monkeypatch, [])
|
||||
_set_engine(period=426)
|
||||
_engine_synced(_tmp)
|
||||
_seed_bim_letters(_tmp, {"g1": "2026-07-18T03:00:00Z", "g2": "2026-07-18T03:00:00Z",
|
||||
"g3": "2026-07-18T03:00:00Z"})
|
||||
r1 = ec.run_check(regions=[323], notify=False)
|
||||
@@ -369,7 +317,7 @@ def test_bim_new_letter_after_build_update_recurrent_until_rebuild(_tmp, monkeyp
|
||||
ТОЛЬКО пересборкой индекса (built_at новее). Авто-apply чекер НЕ делает."""
|
||||
_mock_fgis(monkeypatch, latest=426)
|
||||
_mock_pravo(monkeypatch, [])
|
||||
_set_engine(period=426)
|
||||
_engine_synced(_tmp)
|
||||
_seed_bim_letters(_tmp, {"g-old": "2026-07-18T03:00:00Z"})
|
||||
_seed_bim_index(_tmp, "2026-07-23T12:00:00Z", guids=("g-old",))
|
||||
|
||||
@@ -394,7 +342,7 @@ def test_bim_index_without_built_at_is_problem(_tmp, monkeypatch):
|
||||
"""Индекс без built_at → свежесть не отследить → problem (fail-loud), не тихий ноль."""
|
||||
_mock_fgis(monkeypatch, latest=426)
|
||||
_mock_pravo(monkeypatch, [])
|
||||
_set_engine(period=426)
|
||||
_engine_synced(_tmp)
|
||||
_seed_bim_letters(_tmp, {"g-old": "2026-07-18T03:00:00Z"})
|
||||
_seed_bim_index(_tmp, None, guids=("g-old",))
|
||||
rep = ec.run_check(regions=[323], notify=False)
|
||||
@@ -409,7 +357,7 @@ def test_bim_parsed_but_tool_unwired_is_problem(_tmp, monkeypatch):
|
||||
monkeypatch.setattr(smeta_mcp, "TOOLS", {})
|
||||
_mock_fgis(monkeypatch, latest=426)
|
||||
_mock_pravo(monkeypatch, [])
|
||||
_set_engine(period=426)
|
||||
_engine_synced(_tmp)
|
||||
_seed_bim_letters(_tmp, {"g-old": "2026-07-18T03:00:00Z"})
|
||||
_seed_bim_index(_tmp, "2026-07-23T12:00:00Z", guids=("g-old",))
|
||||
rep = ec.run_check(regions=[323], notify=False)
|
||||
@@ -422,9 +370,11 @@ def test_bim_gap_does_not_mutate_state_or_seen(_tmp, monkeypatch):
|
||||
(иначе сигнал стал бы one-shot и протухание замолчало бы)."""
|
||||
_mock_fgis(monkeypatch, latest=426)
|
||||
_mock_pravo(monkeypatch, [])
|
||||
_set_engine(period=426)
|
||||
_engine_synced(_tmp)
|
||||
_seed_bim_letters(_tmp, {"g-new": "2026-07-24T09:00:00Z"})
|
||||
_seed_bim_index(_tmp, "2026-07-23T12:00:00Z", guids=())
|
||||
with es.update_state():
|
||||
pass # state.json существует до прогона
|
||||
before = (_tmp / "state.json").read_bytes()
|
||||
ec.run_check(regions=[323], notify=False)
|
||||
assert (_tmp / "state.json").read_bytes() == before
|
||||
@@ -440,9 +390,9 @@ def test_notify_called_only_with_findings(_tmp, monkeypatch):
|
||||
import email_service
|
||||
monkeypatch.setattr(email_service, "send_operator_digest",
|
||||
lambda to, subj, html: calls.append((to, subj)) or True)
|
||||
_set_engine(period=426) # движок синхронен с latest → нет новостей
|
||||
_engine_synced(_tmp) # цены движка собраны → нет новостей
|
||||
ec.run_check(regions=[323], notify=True)
|
||||
assert calls == []
|
||||
_mock_fgis(monkeypatch, latest=430) # latest вырос, движок всё на 426 → «примени»
|
||||
_snapshot(_tmp, "323/191/427", "b") # скачана новая форма → «собери цены»
|
||||
ec.run_check(regions=[323], notify=True)
|
||||
assert len(calls) == 1 and calls[0][0] == "op@test" # письмо ушло с новостью
|
||||
|
||||
Reference in New Issue
Block a user