Add inline price basis switching to saved estimate answers
This commit is contained in:
@@ -0,0 +1,62 @@
|
||||
"""Validated inputs and deterministic answer text for inline estimate revisions."""
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
|
||||
|
||||
def selected_form(options: list[dict], zone_id: int, period_id: int) -> tuple[dict, dict] | None:
|
||||
for zone in options:
|
||||
if zone["zone_id"] == zone_id:
|
||||
for period in zone["periods"]:
|
||||
if period["period_id"] == period_id:
|
||||
return zone, period
|
||||
return None
|
||||
|
||||
|
||||
def positions_for_revision(saved: dict, edited: object = None) -> list[dict]:
|
||||
"""The browser may change quantities, never estimate codes or measuring units."""
|
||||
source = saved.get("positions") or []
|
||||
if not isinstance(source, list) or not 1 <= len(source) <= 1000:
|
||||
raise ValueError("В смете нет позиций для пересчёта")
|
||||
if edited is not None and (not isinstance(edited, list) or len(edited) != len(source)):
|
||||
raise ValueError("Состав позиций изменился; обновите диалог")
|
||||
result = []
|
||||
for index, row in enumerate(source):
|
||||
if not isinstance(row, dict) or not row.get("code"):
|
||||
raise ValueError("Позиция не содержит шифр для пересчёта")
|
||||
incoming = edited[index] if edited is not None else row
|
||||
if not isinstance(incoming, dict) or incoming.get("code") != row["code"]:
|
||||
raise ValueError("Шифры позиций нельзя менять этим выбором")
|
||||
if edited is not None and (incoming.get("unit") or "") != (row.get("unit") or ""):
|
||||
raise ValueError("Единицы измерения нельзя менять этим выбором")
|
||||
try:
|
||||
qty = float(incoming["qty"])
|
||||
except (KeyError, TypeError, ValueError):
|
||||
raise ValueError("Укажите числовой объём для каждой позиции") from None
|
||||
if not math.isfinite(qty) or qty < 0:
|
||||
raise ValueError("Объём каждой позиции не может быть отрицательным")
|
||||
result.append({"code": row["code"], "unit": row.get("unit", ""), "qty": qty})
|
||||
return result
|
||||
|
||||
|
||||
def revised_answer(result: dict) -> str:
|
||||
"""Replace stale AI prose with values from the same calculation as the panel."""
|
||||
applied = result["applied"]
|
||||
total = result.get("grand_total")
|
||||
if not isinstance(total, (int, float)) or not math.isfinite(total):
|
||||
raise ValueError("Движок не вернул итог")
|
||||
zone = str(applied.get("zone") or "").replace("\n", " ")
|
||||
period = str(applied.get("period") or "").replace("\n", " ")
|
||||
lines = ["Смета пересчитана по выбранным ценам.", "",
|
||||
f"Ценовая зона: {zone}. Период цен: {period}.", "",
|
||||
("Предварительный итог: " if not result.get("ok") or result.get("unpriced")
|
||||
else "Итого по локальной смете: ")
|
||||
+ f"{total:,.2f} ₽".replace(",", " "),
|
||||
"Позиции и их стоимости приведены в таблице ниже."]
|
||||
if result.get("unpriced"):
|
||||
lines.append("⚠ Часть ресурсов не оценена; итог неполный.")
|
||||
if result.get("missing"):
|
||||
lines.append("⚠ Часть позиций не рассчитана; итог неполный.")
|
||||
if result.get("limits_note"):
|
||||
lines.extend(["", str(result["limits_note"])])
|
||||
return "\n".join(lines)
|
||||
Reference in New Issue
Block a user