"""Price basis choices for a plain, saved assistant answer.""" from __future__ import annotations import hashlib import math import re def revision(content: str) -> str: return hashlib.sha256(content.encode("utf-8")).hexdigest() def options_for_label(content: str, label: str) -> tuple[list[dict], int]: """Only a catalog zone visibly named in this answer can open the selector.""" if not label or len(label) > 160 or len(content) > 30000 or label not in content: raise ValueError("Ценовая зона не найдена в этом ответе") import engine_prices catalog = engine_prices.load_catalog() or {} subject_ids = {row.get("subject_id") for row in catalog.get("zones") or [] if row.get("zone_name") == label and isinstance(row.get("subject_id"), int)} if len(subject_ids) != 1: raise ValueError("Такой ценовой зоны нет в каталоге") subject_id = subject_ids.pop() zones = engine_prices.basis_options(subject_id) if not zones: raise ValueError("Для этой зоны нет доступных ценовых форм") return zones, subject_id _CODE = re.compile(r"(? tuple[str, float] | None: """Only one explicit norm and an explicit piece count; never infer a quantity.""" current = (_CURRENT_POSITION.search(answer) if answer.startswith("Ценовая зона: ") and "Период цен: " in answer else None) if current: qty = float(current.group(2).replace(",", ".")) if math.isfinite(qty) and 0 < qty <= 1_000_000: return current.group(1), qty return None codes = set(_CODE.findall(question + "\n" + answer)) if len(codes) != 1: return None for source, pattern in ((question, _EXPLICIT_VOLUME), (answer, _EXPLICIT_VOLUME), (question, _VOLUME), (answer, _VOLUME)): matches = pattern.findall(source) if matches: qty = float(matches[0].replace(",", ".")) if math.isfinite(qty) and 0 < qty <= 1_000_000: return codes.pop(), qty return None def norm_choices(code: str) -> list[dict]: """Only neighbouring 2022 GESNm piece norms with an auditable composition.""" if not _CODE.fullmatch(code): return [] import fsnb_ref family = code.rsplit("-", 1)[0] found = fsnb_ref.find_gesn_composition(query=family, base="2022", limit=80) rows = found.get("results") or [] choices = [] for row in rows: unit = re.sub(r"\s|\.", "", str(row.get("unit") or "").lower()) resources = row.get("resources") or [] supported = bool(resources) and sum( str(r.get("code") or "").startswith("1-100-") for r in resources) <= 1 for resource in resources: resource_code, quantity = str(resource.get("code") or ""), resource.get("quantity") if (not isinstance(quantity, (int, float)) or isinstance(quantity, bool) or not math.isfinite(quantity) or quantity < 0 or resource.get("quantity_note") or not (re.fullmatch(r"1-100-\d{2}", resource_code) or (not resource_code.startswith("91.") and re.match(r"\d{2}\.", resource_code)))): supported = False break if (row.get("base_type") == "ГЭСНм" and unit == "шт" and re.fullmatch(re.escape(family) + r"-\d{2}", str(row.get("code") or "")) and supported): choices.append({"code": row["code"], "name": row.get("name") or row["code"]}) if code not in {row["code"] for row in choices}: return [] return choices def _money(value: float) -> str: return f"{value:,.2f}".replace(",", " ").replace(".", ",") + " ₽" def _quantity(value: float) -> str: return f"{value:.6f}".rstrip("0").rstrip(".") def format_plain_result(result: dict, code: str, qty: float, zone: str, period: str) -> str: lines = [f"Ценовая зона: {zone}. Период цен: {period}.", "", f"Норма: {code}. Объём: {_quantity(qty)} шт."] if result.get("status") != "ok": lines.extend(["", "Расчёт стоимости не выполнен: " + str(result.get("message") or "ценовая форма недоступна")]) return "\n".join(lines) missing, unpriced = result.get("missing") or [], result.get("unpriced") or [] total = result.get("grand_total") complete = result.get("ok") and not missing and not unpriced lines.append("") if complete and isinstance(total, (int, float)) and math.isfinite(total): lines.append("Итого по локальной смете: " + _money(total)) else: lines.append("Расчёт неполный — готовую смету по этим данным получить нельзя.") if (result.get("positions") and isinstance(total, (int, float)) and math.isfinite(total) and total > 0): lines.append("Стоимость учтённой части: " + _money(total) + ". Она не включает перечисленные ниже затраты.") for item in missing: lines.append("Не рассчитано: " + str(item.get("reason") or item.get("code") or "позиция")) if unpriced: lines.append("Часть ресурсов без цены в выбранной форме; их стоимость не включена.") if result.get("limits_note"): lines.extend(["", str(result["limits_note"])]) return "\n".join(lines) def calculate_plain(question: str, old_answer: str, zone: str, period: str, code_override: str | None = None, qty_override: float | None = None) -> str: """Calculate an explicit single GESN piece norm from audited resources and price form.""" extracted = extract_position(question, old_answer) if extracted is None: raise ValueError("В ответе нет одной нормы с подтверждённым объёмом в штуках") code, qty = extracted if code_override is not None or qty_override is not None: if (code_override is None or qty_override is None or code_override not in {row["code"] for row in norm_choices(code)} or not isinstance(qty_override, (int, float)) or isinstance(qty_override, bool) or not 0.000001 <= qty_override <= 1_000_000 or not math.isfinite(qty_override) or round(qty_override, 6) != qty_override): raise ValueError("Выбранная норма или объём недоступны для пересчёта") code, qty = code_override, float(qty_override) import engine_prices import estimate_contract as ec import fsnb_ref from smeta_railway.models import LaborResource, MaterialResource, NormResources found = fsnb_ref.find_gesn_composition(query=code, base="2022", limit=10) candidates = [row for row in found.get("results") or [] if row.get("code") == code and row.get("base_type") in ("ГЭСН", "ГЭСНм")] if len(candidates) != 1: raise ValueError("Ресурсный состав этой нормы не найден однозначно") work = candidates[0] if not work.get("unit") or "шт" not in work["unit"].lower() or not work.get("resources"): raise ValueError("Ресурсный состав или измеритель этой нормы не позволяет пересчёт") labor = None materials = [] for row in work["resources"]: code_row, quantity = str(row.get("code") or ""), row.get("quantity") if (not code_row or not isinstance(quantity, (int, float)) or not math.isfinite(quantity) or quantity < 0 or row.get("quantity_note")): raise ValueError("В норме есть ресурс с неопределённым расходом") if code_row.startswith("1-100-"): if labor is not None or not re.fullmatch(r"1-100-\d{2}", code_row): raise ValueError("Разряд труда в норме не определён однозначно") labor = LaborResource(razryad=int(code_row[-2:]) / 10, chel_hours=quantity) elif code_row.startswith("91."): raise ValueError("Норма содержит машины; их оплату нельзя пропустить при пересчёте") elif code_row.startswith("4-100-"): raise ValueError("Труд машинистов этой нормы требует отдельного расчёта") elif re.match(r"\d{2}\.", code_row): materials.append(MaterialResource(code=code_row, name=row.get("name") or code_row, unit=row.get("unit") or "", qty=quantity)) else: raise ValueError("В норме есть ресурс неизвестного вида — пересчёт остановлен") norm_code = work["base_type"] + " " + code norm = NormResources(norm_code=norm_code, norm_name=work.get("name"), unit=work["unit"], ozp=labor, materials=materials) resources = {norm_code: norm} meta = {"region": zone, "zone": zone, "price_level": period} basis = engine_prices.resolve(meta) if basis.get("status") != "ok": return format_plain_result(basis, code, qty, zone, period) try: lookup = engine_prices.load_lookup(basis["entry"]) except (OSError, ValueError): return format_plain_result({"status": "catalog_unavailable", "message": "ценовая форма не читается"}, code, qty, zone, period) positions, refusal = ec._positions_in_measures( [{"code": norm_code, "name": work.get("name") or code, "qty": qty, "unit": "шт"}], resources) if refusal: return format_plain_result(refusal, code, qty, zone, period) draft = ec.EstimateDraft(meta=ec.DraftMeta(**meta), positions=[ec.DraftPosition(**item) for item in positions]) result = ec.build_and_calc(draft, resources, lookup, basis) # Этот узкий путь допускает только труд и материалы: перевозки здесь нет. result["limits_note"] = ec.LIMITS_NOTE return format_plain_result(result, code, qty, zone, period)