Files
smeta-web/stove_pricing.py
T

158 lines
7.1 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Read-only adapter from stove estimates to the normative reference databases."""
from __future__ import annotations
import re
import fgis_ref
import fsnb_ref
import rim_calc
import tsn_calc
import tsn_ref
import stove_contract as c
from stove_units import convert_qty
RATES = {
"heating": ("08-08-003-01", "8-31-1"),
"heating_cooking": ("08-08-003-06", "8-31-6"),
"kitchen": ("08-08-003-05", "8-31-5"),
"bread": ("08-08-003-09", "8-31-9"),
}
BRICK_QUERY = {"ceramic": "кирпич керамический", "fireclay": "кирпич шамотный"}
_BRICK_WORDS = ("кирпич", "шамот", "огнеупор")
_ROMAN = ("I", "II", "III", "IV")
class ReferenceUnavailable(RuntimeError):
pass
class InvalidRegion(ValueError):
pass
def _period(label: str | None) -> str:
value = label or ""
m = re.search(r"([1-4])\s*(?:квартал|кв)\.?\s*(20\d\d)", value, re.I)
return f"{_ROMAN[int(m[1])-1]} кв. {m[2]}" if m else value
def _choose(result: dict, unit: str, query: str) -> dict | None:
"""Accept only an exact name and convertible unit; fuzzy search is for AI candidates."""
if result.get("status") != "ok" or result.get("multiple_zones"):
return None
normal = fgis_ref.norm_text(query)
same = [x for x in result.get("results", []) if fgis_ref.norm_text(x["name"]) == normal
and convert_qty(1, unit, x.get("unit")) is not None]
return same[0] if len(same) == 1 else None
def _price(row: dict) -> tuple[float | None, str | None]:
if row.get("price_calc") is not None:
return row["price_calc"], "calc"
if row.get("price_current") is not None:
return row["price_current"], "current"
return None, None
def _line(name: str, qty: float, unit: str, row: dict | None, *, bricks=False) -> dict:
out = {"name": name, "qty": qty, "unit": unit, "code": None, "bricks": bricks}
if row:
price, kind = _price(row)
out.update(code=row["code"], resource_name=row["name"], resource_unit=row["unit"],
price=price, price_kind=kind)
return out
def _norms(code: str) -> dict:
got = fsnb_ref.find_gesn_composition(query=code, base="2022")
if got.get("status") == "db_unavailable":
raise ReferenceUnavailable("составы ГЭСН не доступны")
works = [x for x in got.get("results", []) if x.get("code") == code and x.get("base_type") == "ГЭСН"]
if not works:
return {"ceramic": None, "fireclay": None}
out = {"ceramic": None, "fireclay": None}
for row in works[0].get("resources") or []:
name = (row.get("name") or "").lower()
if "кирпич" not in name or row.get("quantity") is None:
continue
kind = "fireclay" if "шамот" in name or "огнеупор" in name else "ceramic"
if convert_qty(1, row.get("unit"), "1000 шт") is None:
continue
out[kind] = (out[kind] or 0) + float(float(row["quantity"]) * float(convert_qty(1, row["unit"], "1000 шт")))
if out["ceramic"] and out["fireclay"] is None:
out["aggregate"] = out["ceramic"]
return out
def _tsn(kind: str, notes: list[str]) -> dict | None:
code = RATES[kind][1]
found = tsn_ref.find_work(code, limit=20)
rows = [r for r in found.get("items", []) if r.get("code") == code
and r.get("book") == "ТСН-2001.3" and r.get("chapter") == "3-8"]
if len(rows) != 1:
notes.append(f"ТСН {code}: точная строка книги/главы не найдена")
return None
row = rows[0]
if row.get("ot") is None or row.get("em") is None or row["ot"] + row["em"] <= 0:
notes.append(f"ТСН {code}: нет ОТ или ЭМ")
return None
index = tsn_calc.find_rate_index(row)
if index.get("status") != "ok":
notes.append(f"ТСН {code}: коэффициент выпуска не найден")
return None
return {"code": code, "labor": row["ot"] * index["value"],
"machines": row["em"] * index["value"]}
def load(stove: c.StoveRequest) -> dict:
s = stove.stove
notes: list[str] = []
probe = fgis_ref.find_resource_price(query=BRICK_QUERY["ceramic"], region=s.region, zone=s.zone, limit=12)
status = probe.get("status")
if status in ("region_not_found", "region_ambiguous", "zone_not_found"):
raise InvalidRegion(probe.get("message") or status)
if status in ("db_unavailable", "error"):
raise ReferenceUnavailable(probe.get("message") or status)
if probe.get("multiple_zones"):
return {"valid_at": "период не указан", "region": s.region, "zone_required": [z["zone_name"] for z in probe.get("zones", [])], "notes": []}
region = probe.get("region") or s.region
zones = probe.get("zones") or []
zone = zones[0]["zone_name"] if zones else s.zone
periods = [r.get("period") for r in probe.get("results", []) if r.get("period")]
out = {"valid_at": _period(periods[0]) if periods else "период не указан", "region": region,
"zone": s.zone and zone, "notes": notes, "lines": [], "brick_lines_skipped": []}
if s.kind in RATES:
code = RATES[s.kind][0]
rate = rim_calc.calc_rim_rate(code=code, region=region, zone=zone)
if rate.get("status") == "zone_required":
out["zone_required"] = [z["zone_name"] for z in rate.get("zones", [])]
return out
if rate.get("status") == "db_unavailable":
raise ReferenceUnavailable(rate.get("message") or "РИМ не доступен")
if rate.get("status") == "ok":
totals = rate["totals"]
if totals.get("labor") is not None and totals.get("machines") is not None:
out["federal"] = {"code": code, "labor": totals["labor"], "machines": totals["machines"],
"machinist_labor_excluded": totals.get("machinist_labor_excluded", False)}
if not totals.get("complete"):
notes.append("в составе ФЕР есть неоценённые ресурсы; для работ взяты только ОТ и ЭМ")
else:
notes.append(f"ФЕР {code}: {rate.get('status')}")
out["norms"] = _norms(code)
if region.lower() in ("москва", "город москва", "г. москва"):
out["tsn"] = _tsn(s.kind, notes)
for kind, qty in (("ceramic", s.bricks.ceramic), ("fireclay", s.bricks.fireclay)):
if not qty:
continue
query = BRICK_QUERY[kind]
got = probe if kind == "ceramic" else fgis_ref.find_resource_price(query=query, region=region, zone=zone, limit=12)
out["lines"].append(_line(query, qty, "шт", _choose(got, "шт", query), bricks=True))
for item in s.materials or []:
name = item.name
if any(word in name.lower() for word in _BRICK_WORDS):
out["brick_lines_skipped"].append(name)
continue
got = fgis_ref.find_resource_price(query=name, region=region, zone=zone, limit=12)
out["lines"].append(_line(name, item.qty, item.unit, _choose(got, item.unit, name)))
return out