Add inline norm and quantity choices with strict recalculation

This commit is contained in:
anor
2026-12-03 21:56:16 +10:00
parent d908d183d5
commit a13cdaf902
8 changed files with 269 additions and 11 deletions
+57 -2
View File
@@ -34,10 +34,20 @@ _VOLUME = re.compile(
r"(?:извещател[А-ЯЁа-яё]*|шт\.?|штук)\b", re.IGNORECASE)
_EXPLICIT_VOLUME = re.compile(r"объ[её]м\s+работ\s*[=:—-]\s*(\d+(?:[.,]\d+)?)\s*шт\b",
re.IGNORECASE)
_CURRENT_POSITION = re.compile(
r"Норма:\s*(\d{2}-\d{2}-\d{3}-\d{2})\.\s*Объ[её]м:\s*"
r"(\d+(?:[.,]\d+)?)\s*шт\.", re.IGNORECASE)
def extract_position(question: str, answer: str) -> 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
@@ -51,13 +61,49 @@ def extract_position(question: str, answer: str) -> tuple[str, float] | None:
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}. Объём: {qty:g} шт."]
f"Норма: {code}. Объём: {_quantity(qty)} шт."]
if result.get("status") != "ok":
lines.extend(["", "Расчёт стоимости не выполнен: "
+ str(result.get("message") or "ценовая форма недоступна")])
@@ -83,12 +129,21 @@ def format_plain_result(result: dict, code: str, qty: float, zone: str, period:
return "\n".join(lines)
def calculate_plain(question: str, old_answer: str, zone: str, period: str) -> str:
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