Price stove estimates with marked close analogues and TSN items

This commit is contained in:
anor
2026-11-27 01:34:20 +10:00
parent 68bd0378fe
commit 3c66d7771e
7 changed files with 196 additions and 10 deletions
+1 -1
View File
@@ -210,7 +210,7 @@ async def estimate(request: Request):
return response return response
PROTOCOL = """# API оценки кладки печи v1\n\nPOST `/api/v1/stove-estimate` с заголовками `X-API-Key: ism_...` и `Content-Type: application/json`. Тело: `{"stove":{"kind":"heating","bricks":{"ceramic":210,"fireclay":76},"region":"Москва","mass_kg":1320,"materials":[{"name":"Глина шамотная","qty":0.5,"unit":"т"}]}}`.\n\nВиды: `heating`, `heating_cooking`, `kitchen`, `bread`, `bath`, `fireplace`. `zone` указывайте для субъекта с несколькими ценовыми зонами. `context` служит только подсказкой и не сохраняется.\n\nОтвет содержит вилку прямых затрат в рублях: `works`, `materials`, `total`, способы в `basis.ways`, неоценённые строки в `missing`, нехватку данных в `missing_data`. `null` означает отсутствие проверенной суммы. НР и СП не начислены. Расчёт не является проектом или договором.\n\nКлюч выдаёт оператор и может отключить или отозвать. Лимиты по умолчанию: 1000 ответов за скользящие сутки, 30 обращений в минуту, 256 КБ тела. При 429 ориентируйтесь на `Retry-After`. История запросов без поля `context` хранится до 12 месяцев. Инфосмета должна быть указана как источник расчёта при показе результата человеку.\n\nОшибки: `detail`, `code`, `request_id`, `documentation_url`. Схема: `/api/v1/stove-estimate/openapi.json`.\n""" PROTOCOL = """# API оценки кладки печи v1\n\nPOST `/api/v1/stove-estimate` с заголовками `X-API-Key: ism_...` и `Content-Type: application/json`. Тело: `{"stove":{"kind":"heating","bricks":{"ceramic":210,"fireclay":76},"region":"Москва","mass_kg":1320,"materials":[{"name":"Глина шамотная","qty":0.5,"unit":"т"}]}}`.\n\nВиды: `heating`, `heating_cooking`, `kitchen`, `bread`, `bath`, `fireplace`. `zone` указывайте для субъекта с несколькими ценовыми зонами. `context` служит только подсказкой и не сохраняется.\n\nОтвет содержит вилку прямых затрат в рублях: `works`, `materials`, `total`, способы в `basis.ways`, подобранные аналоги в `basis.analogues` (исходная и выбранная позиции, код, отличие и источник), неоценённые строки в `missing`, нехватку данных в `missing_data`. Близкие аналоги допускаются при совместимой единице и расхождении размеров не более 20% по каждому измерению; цена ТСН используется только за тот же квартал, что и ФГИС. `null` означает отсутствие проверенной суммы. НР и СП не начислены. Расчёт не является проектом или договором.\n\nКлюч выдаёт оператор и может отключить или отозвать. Лимиты по умолчанию: 1000 ответов за скользящие сутки, 30 обращений в минуту, 256 КБ тела. При 429 ориентируйтесь на `Retry-After`. История запросов без поля `context` хранится до 12 месяцев. Инфосмета должна быть указана как источник расчёта при показе результата человеку.\n\nОшибки: `detail`, `code`, `request_id`, `documentation_url`. Схема: `/api/v1/stove-estimate/openapi.json`.\n"""
@public.get(c.PROTOCOL_PATH) @public.get(c.PROTOCOL_PATH)
+28 -2
View File
@@ -29,6 +29,7 @@
from __future__ import annotations from __future__ import annotations
import math import math
import re
from decimal import ROUND_HALF_UP, Decimal from decimal import ROUND_HALF_UP, Decimal
from fractions import Fraction from fractions import Fraction
@@ -47,8 +48,9 @@ _KOP = Decimal("0.01")
def build_answer(stove: c.StoveRequest, prices: dict) -> dict: def build_answer(stove: c.StoveRequest, prices: dict) -> dict:
kind = stove.stove.kind kind = stove.stove.kind
notes = list(prices.get("notes") or []) notes = list(prices.get("notes") or [])
basis = {"ways": [], "volume_m3": None, "notes": notes, "region": prices.get("region", ""), sources = {line.get("source") for line in prices.get("lines") or [] if line.get("source")}
"price_source": c.PRICE_SOURCE} basis = {"ways": [], "volume_m3": None, "notes": notes, "analogues": _analogues(prices), "region": prices.get("region", ""),
"price_source": c.PRICE_SOURCE + ("; ТСН-2001 с индексом текущего квартала" if sources else "")}
if prices.get("zone"): if prices.get("zone"):
basis["zone"] = prices["zone"] basis["zone"] = prices["zone"]
answer = {"currency": c.CURRENCY, "valid_at": prices.get("valid_at", ""), "works": None, answer = {"currency": c.CURRENCY, "valid_at": prices.get("valid_at", ""), "works": None,
@@ -110,6 +112,30 @@ def build_answer(stove: c.StoveRequest, prices: dict) -> dict:
return answer return answer
_SIZE = re.compile(r"(?<!\d)(\d{2,4})\s*[×хx]\s*(\d{2,4})(?:\s*[×хx]\s*(\d{1,4}))?", re.I)
def _analogues(prices: dict) -> list[dict]:
result = []
for line in prices.get("lines") or []:
if not line.get("code"):
continue
asked, picked = line["name"], line["resource_name"]
if asked.casefold() == picked.casefold():
continue
wanted, offered = _SIZE.search(asked), _SIZE.search(picked)
if wanted and offered:
n = len([part for part in wanted.groups() if part])
size = f"размер {'×'.join(wanted.groups()[:n])} → {'×'.join(offered.groups()[:n])} мм"
elif line.get("bricks"):
size = "принят рядовой полнотелый кирпич М150 250×120×65 мм"
else:
size = "близкий ресурс; характеристики нужно сверить перед покупкой"
result.append({"requested": asked, "selected": picked, "code": line["code"],
"difference": size, "source": line.get("source") or "ФГИС ЦС"})
return result
def _materials(prices: dict, missing: list, gaps: list): def _materials(prices: dict, missing: list, gaps: list):
"""Сумма материалов (дробь) или None, если ни одна строка не оценена; счёт оценённых строк.""" """Сумма материалов (дробь) или None, если ни одна строка не оценена; счёт оценённых строк."""
total, bill_n, brick_n = None, 0, 0 total, bill_n, brick_n = None, 0, 0
+9
View File
@@ -137,10 +137,19 @@ class Volume(_Model):
return self return self
class Analogue(_Model):
requested: str
selected: str
code: str
difference: str
source: str
class Basis(_Model): class Basis(_Model):
ways: Annotated[list[str], Field(max_length=4)] ways: Annotated[list[str], Field(max_length=4)]
volume_m3: Volume | None volume_m3: Volume | None
notes: list[str] notes: list[str]
analogues: list[Analogue] = Field(default_factory=list)
region: str region: str
zone: str | None = None zone: str | None = None
price_source: str price_source: str
+18 -2
View File
@@ -86,12 +86,24 @@ def _candidate_rows(found: dict, unit: str, name: str = "") -> list[dict]:
rows = [] rows = []
wanted_size = _dimensions(name) wanted_size = _dimensions(name)
for row in found.get("results", []): for row in found.get("results", []):
offered_size = _dimensions(row.get("name") or "") offered_name = row.get("name") or ""
if wanted_size and offered_size and offered_size[:len(wanted_size)] != wanted_size: purposes = ("поддув", "прочист", "топоч")
purpose = next((part for part in purposes if part in name.lower()), None)
if purpose and any(part in offered_name.lower() for part in purposes if part != purpose):
continue continue
offered_size = _dimensions(offered_name)
if wanted_size:
if len(offered_size) < len(wanted_size):
continue
if any(abs(actual - wanted) / wanted > 0.20
for wanted, actual in zip(wanted_size, offered_size)):
continue
if (row.get("code") and convert_qty(1, unit, row.get("unit")) is not None if (row.get("code") and convert_qty(1, unit, row.get("unit")) is not None
and stove_pricing._price(row)[0] is not None): and stove_pricing._price(row)[0] is not None):
rows.append(row) rows.append(row)
if wanted_size:
rows.sort(key=lambda row: sum(abs(actual - wanted) / wanted
for wanted, actual in zip(wanted_size, _dimensions(row["name"]))))
return rows[:12] return rows[:12]
@@ -127,6 +139,10 @@ async def _ask(batch: list[dict], key_id: int, budget: float, deadline: float, r
if not chain: if not chain:
raise MatchingUnavailable() raise MatchingUnavailable()
prompt = {"task": "Выбери для каждой строки один код из её списка candidates или null. " prompt = {"task": "Выбери для каждой строки один код из её списка candidates или null. "
"Допустим близкий аналог того же назначения с совместимой единицей; "
"размеры могут отличаться не более чем на 20% по каждому измерению. "
"Не заменяй целое изделие его частью, бетонную смесь готовым изделием, "
"а материал другим типом. Если аналог сомнителен — null. "
"Верни только JSON массив объектов {index,code}. Не придумывай коды.", "Верни только JSON массив объектов {index,code}. Не придумывай коды.",
"lines": [{"index": x["index"], "name": x["line"]["name"], "lines": [{"index": x["index"], "name": x["line"]["name"],
"unit": x["line"]["unit"], "unit": x["line"]["unit"],
+57 -3
View File
@@ -18,6 +18,8 @@ RATES = {
"bread": ("08-08-003-09", "8-31-9"), "bread": ("08-08-003-09", "8-31-9"),
} }
BRICK_QUERY = {"ceramic": "кирпич керамический", "fireclay": "кирпич шамотный"} BRICK_QUERY = {"ceramic": "кирпич керамический", "fireclay": "кирпич шамотный"}
CERAMIC_STANDARD = "кирпич керамический рядовой полнотелый одинарный М150"
_SIZE = re.compile(r"(?<!\d)(\d{2,4})\s*[×хx]\s*(\d{2,4})(?:\s*[×хx]\s*(\d{1,4}))?", re.I)
_ROMAN = ("I", "II", "III", "IV") _ROMAN = ("I", "II", "III", "IV")
@@ -59,9 +61,48 @@ def _line(name: str, qty: float, unit: str, row: dict | None, *, bricks=False) -
price, kind = _price(row) price, kind = _price(row)
out.update(code=row["code"], resource_name=row["name"], resource_unit=row["unit"], out.update(code=row["code"], resource_name=row["name"], resource_unit=row["unit"],
price=price, price_kind=kind) price=price, price_kind=kind)
if row.get("book"):
out["source"] = row["book"]
return out return out
def _tsn_candidate(name: str, unit: str, period: str, lookup: dict) -> dict | None:
lower = name.lower()
if "дверк" in lower:
family, query = next(((word, "дверка") for word in ("поддув", "прочист", "топоч")
if word in lower), (None, None))
elif "колосник" in lower:
family, query = "колосник", "колосник"
else:
return None
if not family:
return None
wanted = _SIZE.search(name)
if not wanted:
return None
if query not in lookup:
lookup[query] = tsn_ref.find_item(query, limit=100)
found = lookup[query]
if found.get("status") != "ok":
return None
matches = []
for row in found.get("items", []):
offered = _SIZE.search(row["name"])
idx = row.get("index") or {}
row_period = _period(f"{idx.get('quarter', 0)} квартал {idx.get('year', 0)}")
if (family not in row["name"].lower() or not offered or row_period != period
or row.get("price_calc") is None
or convert_qty(1, unit, row.get("unit")) is None):
continue
want = [int(x) for x in wanted.groups() if x]
got = [int(x) for x in offered.groups() if x]
if len(got) < len(want) or any(abs(a-b)/a > 0.20 for a, b in zip(want, got)):
continue
matches.append((sum(abs(a-b)/a for a, b in zip(want, got)), row))
matches.sort(key=lambda x: x[0])
return matches[0][1] if matches else None
def _norms(code: str) -> dict: def _norms(code: str) -> dict:
got = fsnb_ref.find_gesn_composition(query=code, base="2022") got = fsnb_ref.find_gesn_composition(query=code, base="2022")
if got.get("status") == "db_unavailable": if got.get("status") == "db_unavailable":
@@ -145,8 +186,18 @@ def load(stove: c.StoveRequest) -> dict:
if not qty: if not qty:
continue continue
query = BRICK_QUERY[kind] query = BRICK_QUERY[kind]
got = probe if kind == "ceramic" else fgis_ref.find_resource_price(query=query, region=region, zone=zone, limit=12) if kind == "ceramic":
out["lines"].append(_line(query, qty, "шт", _choose(got, "шт", query), bricks=True)) got = fgis_ref.find_resource_price(query=CERAMIC_STANDARD, region=region, zone=zone, limit=30)
matches = [r for r in got.get("results", [])
if "рядовой" in r["name"].lower() and "полнотелый" in r["name"].lower()
and "м150" in r["name"].lower() and "250х120х65" in r["name"].lower()
and convert_qty(1, "шт", r.get("unit")) is not None and _price(r)[0] is not None]
row = matches[0] if len(matches) == 1 else None
else:
got = fgis_ref.find_resource_price(query=query, region=region, zone=zone, limit=12)
row = _choose(got, "шт", query)
out["lines"].append(_line(query, qty, "шт", row, bricks=True))
tsn_lookup: dict = {}
for item in s.materials or []: for item in s.materials or []:
name = item.name name = item.name
if re.search(r"\bкирпич(?:и|а|ей|ом|у)?\b", name.lower()): if re.search(r"\bкирпич(?:и|а|ей|ом|у)?\b", name.lower()):
@@ -154,5 +205,8 @@ def load(stove: c.StoveRequest) -> dict:
continue continue
got = fgis_ref.find_resource_price(query=name, region=region, zone=zone, limit=12) got = fgis_ref.find_resource_price(query=name, region=region, zone=zone, limit=12)
out["search_results"][len(out["lines"])] = got out["search_results"][len(out["lines"])] = got
out["lines"].append(_line(name, item.qty, item.unit, _choose(got, item.unit, name))) row = _choose(got, item.unit, name)
if row is None and region.lower() in ("москва", "город москва", "г. москва"):
row = _tsn_candidate(name, item.unit, out["valid_at"], tsn_lookup)
out["lines"].append(_line(name, item.qty, item.unit, row))
return out return out
+17
View File
@@ -36,6 +36,23 @@ BRICKS = [CERAMIC, FIRECLAY]
UNMATCHED = {"name": "Дверка банная 140×240", "qty": 1, "unit": "шт", "code": None} UNMATCHED = {"name": "Дверка банная 140×240", "qty": 1, "unit": "шт", "code": None}
def test_approximate_resource_is_visible_in_answer():
req = _stove()
price_data = _prices(lines=[dict(DOOR, name="Дверка топочная 250×205",
resource_name="Дверка чугунная для печи, топочная, размеры 291х230х67 мм",
code="08.1.02.12-0061")])
out = calc.build_answer(req, price_data)
assert out["basis"]["analogues"] == [{
"requested": "Дверка топочная 250×205",
"selected": "Дверка чугунная для печи, топочная, размеры 291х230х67 мм",
"code": "08.1.02.12-0061",
"difference": "размер 250×205 → 291×230 мм",
"source": "ФГИС ЦС",
}]
checked = c.StoveAnswer.model_validate(dict(out, request_id=RID)).model_dump()
assert checked["basis"]["analogues"] == out["basis"]["analogues"]
def _prices(**over): def _prices(**over):
prices = {"valid_at": "III кв. 2026", "region": "Москва", "norms": dict(NORMS), prices = {"valid_at": "III кв. 2026", "region": "Москва", "norms": dict(NORMS),
"federal": dict(FEDERAL), "tsn": dict(TSN), "notes": ["ТСН: строка 8-31-6 без ОТ"], "federal": dict(FEDERAL), "tsn": dict(TSN), "notes": ["ТСН: строка 8-31-6 без ОТ"],
+66 -2
View File
@@ -151,15 +151,79 @@ def test_explicit_door_dimensions_exclude_wrong_catalog_size():
"unit": "шт", "price_calc": 1400} "unit": "шт", "price_calc": 1400}
found = {"status": "ok", "results": [wrong, right]} found = {"status": "ok", "results": [wrong, right]}
assert [row["code"] for row in stove_match._candidate_rows( assert [row["code"] for row in stove_match._candidate_rows(
found, "шт", "Дверка топочная 250×205")] == ["right"] found, "шт", "Дверка топочная 250×205")] == ["right", "wrong"]
assert len(stove_match._candidate_rows(found, "шт", "Дверка топочная")) == 2 assert len(stove_match._candidate_rows(found, "шт", "Дверка топочная")) == 2
def test_large_door_size_difference_is_not_an_analogue():
row = {"code": "big", "name": "Дверка поддувальная 291х160х67 мм",
"unit": "шт", "price_calc": 1200}
assert stove_match._candidate_rows({"status": "ok", "results": [row]}, "шт",
"Дверка поддувальная 130×140") == []
def test_different_door_purpose_is_not_an_analogue_even_at_same_size():
row = {"code": "fire", "name": "Дверка топочная 130х140 мм", "unit": "шт",
"price_calc": 900}
assert stove_match._candidate_rows({"status": "ok", "results": [row]}, "шт",
"Дверка поддувальная 130×140") == []
def test_ceramic_brick_uses_marked_standard_m150_price(monkeypatch):
calls = []
brick = {"code": "06.1.01.05-0037", "name": "Кирпич керамический рядовой полнотелый одинарный, размеры 250х120х65 мм, марка М150",
"unit": "1000 шт", "price_calc": 18167.45}
def search(**kw):
calls.append(kw["query"])
rows = [brick] if "М150" in kw["query"] else []
return {"status": "ok", "region": "Москва", "results": rows}
monkeypatch.setattr(stove_pricing.fgis_ref, "find_resource_price", search)
req = c.StoveRequest.model_validate({"stove": {"kind": "bath", "bricks": {
"ceramic": 244, "fireclay": 0}, "region": "Москва"}})
priced = stove_pricing.load(req)
assert priced["lines"][0]["code"] == brick["code"]
assert priced["lines"][0]["resource_name"] == brick["name"]
assert any("М150" in query for query in calls)
def test_tsn_prices_exact_cleanout_door_but_not_oversized_ash_door(monkeypatch):
monkeypatch.setattr(stove_pricing.fgis_ref, "find_resource_price", lambda **kw: {
"status": "ok", "region": "Москва", "results": [
{"period": "3 квартал 2026 г.", "name": "неизвестный ресурс", "unit": "кг"}]})
items = [
{"code": "1.8-5-1", "name": "дверка поддувальная ДП-2, размер 250×140", "unit": "шт.",
"price_calc": 763.03, "book": "ТСН-2001.1", "index": {"quarter": 3, "year": 2026}},
{"code": "1.8-5-2", "name": "дверка прочистная ДП-1, размер 130×140 мм", "unit": "шт.",
"price_calc": 787.72, "book": "ТСН-2001.1", "index": {"quarter": 3, "year": 2026}},
]
monkeypatch.setattr(stove_pricing.tsn_ref, "find_item", lambda *a, **kw: {
"status": "ok", "items": items})
req = c.StoveRequest.model_validate({"stove": {"kind": "bath", "bricks": {
"ceramic": 0, "fireclay": 1}, "region": "Москва", "materials": [
{"name": "Дверка поддувальная 130×140", "qty": 1, "unit": "шт"},
{"name": "Дверка прочистная 130×140", "qty": 1, "unit": "шт"}]}})
priced = stove_pricing.load(req)
assert priced["lines"][1]["code"] is None
assert priced["lines"][2]["code"] == "1.8-5-2"
assert priced["lines"][2]["source"] == "ТСН-2001.1"
def test_tsn_requires_same_price_quarter(monkeypatch):
monkeypatch.setattr(stove_pricing.tsn_ref, "find_item", lambda *a, **kw: {
"status": "ok", "items": [{"code": "1.8-5-2", "name": "дверка прочистная 130×140 мм",
"unit": "шт.", "price_calc": 787.72,
"index": {"quarter": 2, "year": 2026}}]})
assert stove_pricing._tsn_candidate("Дверка прочистная 130×140", "шт",
"III кв. 2026", {}) is None
def test_cached_door_code_with_wrong_size_is_rejected(monkeypatch): def test_cached_door_code_with_wrong_size_is_rejected(monkeypatch):
deleted = [] deleted = []
prices = {"region": "Москва", "zone": None, "valid_at": "III кв. 2026", prices = {"region": "Москва", "zone": None, "valid_at": "III кв. 2026",
"lines": [{"name": "Дверка топочная 250×205", "qty": 1, "unit": "шт", "code": None}]} "lines": [{"name": "Дверка топочная 250×205", "qty": 1, "unit": "шт", "code": None}]}
wrong = {"code": "wrong", "name": "Дверка топочная, размеры 291х230х67 мм", wrong = {"code": "wrong", "name": "Дверка топочная, размеры 391х330х67 мм",
"unit": "шт", "price_calc": 1200} "unit": "шт", "price_calc": 1200}
monkeypatch.setattr(stove_match.stove_cache, "match_get", lambda key: {"code": "wrong"}) 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_delete", lambda key: deleted.append(key))