140 lines
8.4 KiB
Python
140 lines
8.4 KiB
Python
"""Visible household assumptions for price proxies from normative catalogues.
|
||
|
||
This layer never declares a proxy suitable for installation. Catalogue codes are
|
||
queried exactly and the returned family, unit and quarter are checked again.
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import re
|
||
from decimal import Decimal
|
||
|
||
import fgis_ref
|
||
import tsn_ref
|
||
from stove_units import convert_qty
|
||
|
||
_ROMAN = {"I": 1, "II": 2, "III": 3, "IV": 4}
|
||
_SIZE = re.compile(r"(?<!\d)(\d{2,4})\s*[×хx]\s*(\d{2,4})", re.I)
|
||
_DIAMETER = re.compile(r"[Øø]?(\d(?:[,.]\d)?)\s*[–—-]\s*(\d(?:[,.]\d)?)\s*мм", re.I)
|
||
_PI = Decimal("3.141592653589793")
|
||
_STEEL_KG_M3 = Decimal("7850")
|
||
|
||
|
||
def _quarter(value: str) -> tuple[int, int] | None:
|
||
text = (value or "").upper().strip()
|
||
m = re.search(r"\b(I{1,3}|IV)\s*КВ\.?(?:АРТАЛ)?\s*(20\d\d)", text)
|
||
if m:
|
||
return int(m[2]), _ROMAN[m[1]]
|
||
m = re.search(r"\b([1-4])\s*(?:КВ|КВАРТАЛ)\.?\s*(20\d\d)", text)
|
||
return (int(m[2]), int(m[1])) if m else None
|
||
|
||
|
||
def _recipe(name: str, qty: Decimal, unit: str, bucket_l: Decimal):
|
||
text = fgis_ref.norm_text(name)
|
||
unit = unit.lower().strip().rstrip(".")
|
||
if ("кирпич" in text and "шамот" in text and unit == "шт"
|
||
and not re.search(r"\bша-?\d", text)):
|
||
mass = Decimal("3.4")
|
||
return ("fgis", "17.1.02.05-0022", "т", qty * mass / 1000,
|
||
("кирпич шамотный", "марка ша"),
|
||
["цена марки ША использована как ориентир для шамотного кирпича",
|
||
"масса принята 3,4 кг/шт для типового ШБ-5; уточните марку и массу"])
|
||
if unit == "ведро" and "глин" in text and "шамот" not in text:
|
||
return ("tsn", "1.1-1-150", "м3", qty * bucket_l / 1000,
|
||
("глина обыкновенная",), [f"ведро принято {bucket_l:g} л",
|
||
"обыкновенная глина взята как ценовой ориентир для раствора"])
|
||
if unit == "ведро" and "песок" in text:
|
||
return ("fgis", "02.3.01.02-1104", "м3", qty * bucket_l / 1000,
|
||
("песок природный", "средний"), [f"ведро принято {bucket_l:g} л",
|
||
"принят природный строительный песок средней фракции"])
|
||
if "дверк" in text and "поддув" in text and unit == "шт":
|
||
return ("tsn", "1.8-5-1", "шт", qty,
|
||
("дверка поддувальная",),
|
||
["цена другой поддувальной дверки; она не подходит по размеру для установки"])
|
||
if "задвиж" in text and ("дым" in text or "печ" in text) and unit == "шт":
|
||
return ("tsn", "1.8-5-8", "шт", qty,
|
||
("задвижка печная",),
|
||
["цена другой печной задвижки; она не подходит по размеру для установки"])
|
||
if "бетон" in text and re.search(r"[bв]20\b", text) and unit == "м3":
|
||
return ("fgis", "04.1.02.05-0136", "м3", qty,
|
||
("смеси бетонные тяжелого бетона", "класс в20"),
|
||
["принята готовая тяжёлая смесь В20 на гравийном щебне, F100 W4"])
|
||
if ("песок" in text and unit == "м3"
|
||
and any(word in text for word in ("строит", "подуш", "зазор", "раствор"))
|
||
and "метал" not in text):
|
||
return ("fgis", "02.3.01.02-1104", "м3", qty,
|
||
("песок природный", "средний"),
|
||
["принят природный строительный песок средней фракции"])
|
||
if ("гидроизоляц" in text and unit == "м2"
|
||
and ("рулон" in text or "слоя" in text or "слои" in text)):
|
||
return ("fgis", "12.1.02.15-0041", "м2", qty,
|
||
("материал рулонный гидроизоляционный изол",),
|
||
["принята рулонная резино-битумная гидроизоляция",
|
||
"площадь из ведомости считается расходом материала; число слоёв повторно не умножено"])
|
||
if "проволок" in text and "отож" in text and unit == "м":
|
||
m = _DIAMETER.search(text)
|
||
if not m:
|
||
return None
|
||
diameters = [Decimal(x.replace(",", ".")) for x in m.groups()]
|
||
if not (Decimal("1") <= diameters[0] <= diameters[1] <= Decimal("5")):
|
||
return None
|
||
diameter_mm = sum(diameters) / 2
|
||
kg_per_m = _PI / 4 * (diameter_mm / 1000) ** 2 * _STEEL_KG_M3
|
||
return ("fgis", "08.3.03.06-0012", "т", qty * kg_per_m / 1000,
|
||
("проволока стальная низкоуглеродистая вязальная",),
|
||
[f"для диапазона Ø{m[1]}–{m[2]} мм принят Ø{diameter_mm:g} мм",
|
||
"масса вычислена по круглому сечению и плотности стали 7850 кг/м³",
|
||
"вязальная проволока взята как ценовой ориентир для отожжённой"])
|
||
if ("лист" in text and "стал" in text and unit == "шт"
|
||
and not any(word in text for word in ("оцинк", "нержав", "алюмин"))):
|
||
m = _SIZE.search(text)
|
||
if not m:
|
||
return None
|
||
area_m2 = Decimal(m[1]) * Decimal(m[2]) / Decimal("1000000")
|
||
thickness_mm = Decimal("0.7")
|
||
tonnes = qty * area_m2 * thickness_mm / 1000 * _STEEL_KG_M3 / 1000
|
||
return ("fgis", "08.3.05.03-0001", "т", tonnes,
|
||
("сталь листовая кровельная", "толщина 0,7"),
|
||
[f"площадь одного листа {area_m2:g} м²; толщина принята 0,7 мм",
|
||
"масса вычислена по плотности стали 7850 кг/м³",
|
||
"цена кровельной стали — ориентир, не рекомендация материала для предтопочного листа"])
|
||
return None
|
||
|
||
|
||
def resolve(name: str, qty: float, unit: str, region: str, zone: str | None,
|
||
period: str, *, bucket_volume_l: float = 10) -> dict | None:
|
||
"""Return a verified catalogue row and visible catalogue quantity, or None."""
|
||
if not _quarter(period):
|
||
return None
|
||
bucket_l = Decimal(str(bucket_volume_l))
|
||
if not Decimal("1") <= bucket_l <= Decimal("30"):
|
||
return None
|
||
recipe = _recipe(name, Decimal(str(qty)), unit, bucket_l)
|
||
if recipe is None:
|
||
return None
|
||
source, code, expected_unit, resource_qty, family, assumptions = recipe
|
||
if source == "tsn":
|
||
if region.lower() not in ("москва", "город москва", "г. москва"):
|
||
return None
|
||
year, quarter = _quarter(period)
|
||
found = tsn_ref.find_item(code, as_of=f"{year}-Q{quarter}", limit=2)
|
||
rows = found.get("items", []) if found.get("status") == "ok" else []
|
||
rows = [row for row in rows if row.get("index") and
|
||
(row["index"].get("year"), row["index"].get("quarter")) == (year, quarter)
|
||
and row.get("book") == "ТСН-2001.1"]
|
||
else:
|
||
found = fgis_ref.find_resource_price(query=code, region=region, zone=zone, limit=2)
|
||
rows = found.get("results", []) if (found.get("status") == "ok" and
|
||
not found.get("multiple_zones")) else []
|
||
rows = [row for row in rows if _quarter(row.get("period")) == _quarter(period)]
|
||
rows = [row for row in rows if row.get("code") == code
|
||
and (row.get("price_calc") is not None or row.get("price_current") is not None)
|
||
and all(part in fgis_ref.norm_text(row.get("name") or "") for part in family)
|
||
and convert_qty(1, expected_unit, row.get("unit")) is not None]
|
||
if len(rows) != 1:
|
||
return None
|
||
converted = convert_qty(resource_qty, expected_unit, rows[0]["unit"])
|
||
if converted is None:
|
||
return None
|
||
return {"row": rows[0], "resource_qty": converted, "kind": "price_proxy",
|
||
"assumptions": assumptions}
|