"""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_household 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": "кирпич шамотный"} CERAMIC_STANDARD = "кирпич керамический рядовой полнотелый одинарный М150" _SIZE = re.compile(r"(? 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) if row.get("book"): out["source"] = row["book"] 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: 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": [], "search_results": {}} 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] if kind == "ceramic": 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) proxy = None if row else stove_household.resolve( query, qty, "шт", region, zone, out["valid_at"], bucket_volume_l=s.bucket_volume_l or 10) line = _line(query, qty, "шт", row or (proxy or {}).get("row"), bricks=True) if proxy: line.update(resource_qty=proxy["resource_qty"], match_kind=proxy["kind"], assumptions=proxy["assumptions"]) out["lines"].append(line) tsn_lookup: dict = {} for item in s.materials or []: name = item.name if re.search(r"\bкирпич(?:и|а|ей|ом|у)?\b", name.lower()): out["brick_lines_skipped"].append(name) continue got = fgis_ref.find_resource_price(query=name, region=region, zone=zone, limit=12) out["search_results"][len(out["lines"])] = got 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) proxy = None if row else stove_household.resolve( name, item.qty, item.unit, region, zone, out["valid_at"], bucket_volume_l=s.bucket_volume_l or 10) line = _line(name, item.qty, item.unit, row or (proxy or {}).get("row")) if proxy: line.update(resource_qty=proxy["resource_qty"], match_kind=proxy["kind"], assumptions=proxy["assumptions"]) out["lines"].append(line) return out