From 68bd0378fe21d7605c47117c064f609de051f381 Mon Sep 17 00:00:00 2001 From: anor Date: Fri, 27 Nov 2026 00:29:44 +1000 Subject: [PATCH] Reject mismatched stove part sizes and label partial totals --- stove_calc.py | 3 +++ stove_match.py | 22 +++++++++++++++++----- tests/test_stove_calc.py | 2 ++ tests/test_stove_match.py | 28 ++++++++++++++++++++++++++++ 4 files changed, 50 insertions(+), 5 deletions(-) diff --git a/stove_calc.py b/stove_calc.py index 9d53be8..09ee9ad 100644 --- a/stove_calc.py +++ b/stove_calc.py @@ -87,6 +87,9 @@ def build_answer(stove: c.StoveRequest, prices: dict) -> dict: names = ", ".join(f"«{name}»" for name in skipped) notes.append(f"строки ведомости {names} — это кирпич: отдельно не считаются, " "кирпич посчитан один раз по полю bricks") + if answer["missing"] or line_gaps or c.MISSING_BILL in gaps: + notes.append("итог неполный: учтены только позиции с найденной ценой; " + "остальные перечислены в missing и missing_data") if not ways and amount is not None: ways.append((_bill_label(bill_n, brick_priced, stove.stove.bricks), None)) diff --git a/stove_match.py b/stove_match.py index b37a65c..64cae74 100644 --- a/stove_match.py +++ b/stove_match.py @@ -3,6 +3,7 @@ from __future__ import annotations import asyncio import json +import re import threading import time @@ -24,6 +25,7 @@ RESERVE_RUB = 5.0 GLOBAL_RUB_DAY = 600.0 _lock = threading.Lock() _semaphore = asyncio.Semaphore(3) +_SIZE = re.compile(r"(? int: def _candidates(name: str, unit: str, region: str, zone: str | None) -> list[dict]: found = fgis_ref.find_resource_price(query=name, region=region, zone=zone, limit=12) - return _candidate_rows(found, unit) + return _candidate_rows(found, unit, name) -def _candidate_rows(found: dict, unit: str) -> list[dict]: +def _dimensions(name: str) -> tuple[int, ...]: + match = _SIZE.search(name) + return tuple(int(part) for part in match.groups() if part) if match else () + + +def _candidate_rows(found: dict, unit: str, name: str = "") -> list[dict]: if found.get("status") == "db_unavailable": raise MatchingUnavailable(30) if found.get("status") != "ok" or found.get("multiple_zones"): return [] rows = [] + wanted_size = _dimensions(name) for row in found.get("results", []): + offered_size = _dimensions(row.get("name") or "") + if wanted_size and offered_size and offered_size[:len(wanted_size)] != wanted_size: + continue if (row.get("code") and convert_qty(1, unit, row.get("unit")) is not None and stove_pricing._price(row)[0] is not None): rows.append(row) @@ -184,8 +195,9 @@ async def fill(prices: dict, *, key_id: int, budget: float, deadline: float, req if cached.get("code"): got = await asyncio.to_thread(fgis_ref.find_resource_price, query=cached["code"], region=prices["region"], zone=prices.get("zone"), limit=2) - rows = [r for r in got.get("results", []) if r.get("code") == cached["code"]] - if rows and stove_pricing._price(rows[0])[0] is not None: + rows = [r for r in _candidate_rows(got, line["unit"], line["name"]) + if r.get("code") == cached["code"]] + if rows: prices["lines"][index] = stove_pricing._line(line["name"], line["qty"], line["unit"], rows[0]) continue await asyncio.to_thread(stove_cache.match_delete, ck) @@ -193,7 +205,7 @@ async def fill(prices: dict, *, key_id: int, budget: float, deadline: float, req continue found = prices.get("search_results", {}).get(index) if found is not None: - candidates = _candidate_rows(found, line["unit"]) + candidates = _candidate_rows(found, line["unit"], line["name"]) else: candidates = await asyncio.to_thread(_candidates, line["name"], line["unit"], prices["region"], prices.get("zone")) diff --git a/tests/test_stove_calc.py b/tests/test_stove_calc.py index 6b0aa02..14a767d 100644 --- a/tests/test_stove_calc.py +++ b/tests/test_stove_calc.py @@ -265,3 +265,5 @@ def test_works_only_are_a_valid_partial_total_when_material_prices_are_missing() assert out["materials"] is None assert out["total"] == out["works"] assert out["missing"] == [UNMATCHED["name"]] + assert any("итог неполный" in note and "missing" in note + for note in out["basis"]["notes"]) diff --git a/tests/test_stove_match.py b/tests/test_stove_match.py index 5c06fdb..76c333b 100644 --- a/tests/test_stove_match.py +++ b/tests/test_stove_match.py @@ -142,3 +142,31 @@ def test_match_prefers_deepseek_without_thinking_and_keeps_glm_fallback(monkeypa picked = asyncio.run(stove_match._ask(batch, 1, 300, time.monotonic()+10, "rid")) assert picked == [None] assert calls == [("deepseek", {"type": "disabled"}), ("glm", None)] + + +def test_explicit_door_dimensions_exclude_wrong_catalog_size(): + wrong = {"code": "wrong", "name": "Дверка топочная, размеры 291х230х67 мм", + "unit": "шт", "price_calc": 1200} + right = {"code": "right", "name": "Дверка топочная, размеры 250х205х67 мм", + "unit": "шт", "price_calc": 1400} + found = {"status": "ok", "results": [wrong, right]} + assert [row["code"] for row in stove_match._candidate_rows( + found, "шт", "Дверка топочная 250×205")] == ["right"] + assert len(stove_match._candidate_rows(found, "шт", "Дверка топочная")) == 2 + + +def test_cached_door_code_with_wrong_size_is_rejected(monkeypatch): + deleted = [] + prices = {"region": "Москва", "zone": None, "valid_at": "III кв. 2026", + "lines": [{"name": "Дверка топочная 250×205", "qty": 1, "unit": "шт", "code": None}]} + wrong = {"code": "wrong", "name": "Дверка топочная, размеры 291х230х67 мм", + "unit": "шт", "price_calc": 1200} + monkeypatch.setattr(stove_match.stove_cache, "match_get", lambda key: {"code": "wrong"}) + monkeypatch.setattr(stove_match.stove_cache, "match_delete", lambda key: deleted.append(key)) + monkeypatch.setattr(stove_match.stove_cache, "match_put", lambda *args, **kw: None) + monkeypatch.setattr(stove_match.fgis_ref, "find_resource_price", lambda **kw: { + "status": "ok", "results": [wrong]}) + result = asyncio.run(stove_match.fill( + prices, key_id=1, budget=300, deadline=time.monotonic()+10, request_id="rid")) + assert result["lines"][0]["code"] is None + assert len(deleted) == 1