11 Commits
37 changed files with 3403 additions and 52 deletions
+202
View File
@@ -0,0 +1,202 @@
"""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"(?<!\d)(\d{2}-\d{2}-\d{3}-\d{2})(?![\d-])")
_VOLUME = re.compile(
r"(?<!\d)(\d+(?:[.,]\d+)?)\s+(?:(?:[А-ЯЁа-яё-]+\s+){0,3})?"
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
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)
+164 -2
View File
@@ -579,11 +579,12 @@ def init_db():
def save_message(username: str, tab_id: str, role: str, content: str): def save_message(username: str, tab_id: str, role: str, content: str):
"""Save a user or assistant message.""" """Save a user or assistant message."""
with _conn() as conn: with _conn() as conn:
conn.execute( cursor = conn.execute(
"INSERT INTO messages (session_id, username, tab_id, role, content, timestamp) " "INSERT INTO messages (session_id, username, tab_id, role, content, timestamp) "
"VALUES (?, ?, ?, ?, ?, ?)", "VALUES (?, ?, ?, ?, ?, ?)",
(f"{username}/{tab_id}", username, tab_id, role, content, time.time()), (f"{username}/{tab_id}", username, tab_id, role, content, time.time()),
) )
return cursor.lastrowid
HISTORY_LIMIT = 2000 # потолок выдачи истории: длинные переписки нужны целиком HISTORY_LIMIT = 2000 # потолок выдачи истории: длинные переписки нужны целиком
@@ -601,7 +602,7 @@ def get_history(username: str, tab_id: str, limit: int = HISTORY_LIMIT,
(проверено на всех 1299 диалогах боевой базы 09.09.2026), но записи, добавленные задним (проверено на всех 1299 диалогах боевой базы 09.09.2026), но записи, добавленные задним
числом — цена под старым ответом, — обязаны вставать на своё место, а не в конец числом — цена под старым ответом, — обязаны вставать на своё место, а не в конец
диалога.""" диалога."""
sql = "SELECT role, content, timestamp FROM messages WHERE username = ? AND tab_id = ?" sql = "SELECT id, role, content, timestamp FROM messages WHERE username = ? AND tab_id = ?"
args: list = [username, tab_id] args: list = [username, tab_id]
if roles: if roles:
sql += " AND role IN (" + ",".join("?" * len(roles)) + ")" sql += " AND role IN (" + ",".join("?" * len(roles)) + ")"
@@ -613,6 +614,167 @@ def get_history(username: str, tab_id: str, limit: int = HISTORY_LIMIT,
return [dict(r) for r in reversed(rows)] return [dict(r) for r in reversed(rows)]
def get_linked_estimate(username: str, tab_id: str, estimate_id: int) -> dict | None:
"""Return an estimate only when its answer belongs to the same user's dialog."""
import json
with _conn() as conn:
row = conn.execute(
"SELECT content FROM messages WHERE id=? AND username=? AND tab_id=? AND role='estimate'",
(estimate_id, username, tab_id),
).fetchone()
if not row:
return None
try:
data = json.loads(row["content"])
assistant_id = data.get("_assistant_id")
except (ValueError, AttributeError, TypeError):
return None
if not isinstance(assistant_id, int) or isinstance(assistant_id, bool):
return None
answer = conn.execute(
"SELECT id FROM messages WHERE id=? AND username=? AND tab_id=? AND role='assistant'",
(assistant_id, username, tab_id),
).fetchone()
return data if answer else None
def get_scoped_assistant(username: str, tab_id: str, message_id: int) -> dict | None:
"""Plain answer and the question it answered, scoped to one user's dialog."""
with _conn() as conn:
answer = conn.execute(
"SELECT id, content, timestamp FROM messages "
"WHERE id=? AND username=? AND tab_id=? AND role='assistant'",
(message_id, username, tab_id),
).fetchone()
if not answer:
return None
question = conn.execute(
"SELECT content FROM messages WHERE username=? AND tab_id=? AND role='user' "
"AND (timestamp < ? OR (timestamp = ? AND id < ?)) "
"ORDER BY timestamp DESC, id DESC LIMIT 1",
(username, tab_id, answer["timestamp"], answer["timestamp"], message_id),
).fetchone()
return {"content": answer["content"], "question": question["content"] if question else ""}
def replace_scoped_assistant(username: str, tab_id: str, message_id: int,
old_content: str, new_content: str) -> bool:
"""Atomically reject another tab's edit instead of overwriting it."""
with _conn() as conn:
conn.execute("BEGIN IMMEDIATE")
cursor = conn.execute(
"UPDATE messages SET content=? WHERE id=? AND username=? AND tab_id=? "
"AND role='assistant' AND content=?",
(new_content, message_id, username, tab_id, old_content),
)
return cursor.rowcount == 1
def get_scoped_norm_quote(username: str, tab_id: str, quote_id: int) -> dict | None:
"""One saved finder result, never a quote from another user or dialog."""
import json
with _conn() as conn:
row = conn.execute(
"SELECT content FROM messages WHERE id=? AND username=? AND tab_id=? "
"AND role='norm_quote'", (quote_id, username, tab_id),
).fetchone()
if row is None:
return None
try:
data = json.loads(row["content"])
except (ValueError, TypeError):
return None
return {"raw": row["content"], "data": data}
def replace_scoped_norm_quote(username: str, tab_id: str, quote_id: int,
old_content: str, new_content: str) -> bool:
"""Compare and swap one finder result in the current dialog."""
with _conn() as conn:
conn.execute("BEGIN IMMEDIATE")
cursor = conn.execute(
"UPDATE messages SET content=? WHERE id=? AND username=? AND tab_id=? "
"AND role='norm_quote' AND content=?",
(new_content, quote_id, username, tab_id, old_content),
)
return cursor.rowcount == 1
def get_linked_file_compare(username: str, tab_id: str, compare_id: int) -> dict | None:
"""Return a saved file comparison only with its answer in the same dialog."""
import json
with _conn() as conn:
row = conn.execute(
"SELECT content FROM messages WHERE id=? AND username=? AND tab_id=? "
"AND role='file_compare'", (compare_id, username, tab_id),
).fetchone()
if row is None:
return None
try:
data = json.loads(row["content"])
assistant_id = data["_assistant_id"]
except (ValueError, KeyError, TypeError):
return None
answer = conn.execute(
"SELECT 1 FROM messages WHERE id=? AND username=? AND tab_id=? AND role='assistant'",
(assistant_id, username, tab_id),
).fetchone()
return {"raw": row["content"], "data": data} if answer else None
def replace_linked_file_compare(username: str, tab_id: str, compare_id: int,
old_content: str, new_content: str) -> bool:
"""Atomically reject concurrent edits to a comparison in the current dialog."""
with _conn() as conn:
conn.execute("BEGIN IMMEDIATE")
cursor = conn.execute(
"UPDATE messages SET content=? WHERE id=? AND username=? AND tab_id=? "
"AND role='file_compare' AND content=?",
(new_content, compare_id, username, tab_id, old_content),
)
return cursor.rowcount == 1
def replace_linked_estimate(username: str, tab_id: str, estimate_id: int,
expected_revision: int, data: dict, answer: str) -> str:
"""Compare-and-swap answer and estimate in one SQLite transaction."""
import json
with _conn() as conn:
conn.execute("BEGIN IMMEDIATE")
row = conn.execute(
"SELECT content FROM messages WHERE id=? AND username=? AND tab_id=? AND role='estimate'",
(estimate_id, username, tab_id),
).fetchone()
if not row:
return "missing"
try:
current = json.loads(row["content"])
assistant_id = current.get("_assistant_id")
revision = current.get("_revision", 0)
except (ValueError, AttributeError, TypeError):
return "missing"
if not isinstance(assistant_id, int) or isinstance(assistant_id, bool):
return "missing"
if revision != expected_revision:
return "stale"
answer_row = conn.execute(
"SELECT id FROM messages WHERE id=? AND username=? AND tab_id=? AND role='assistant'",
(assistant_id, username, tab_id),
).fetchone()
if not answer_row:
return "missing"
data["_assistant_id"] = assistant_id
data["_revision"] = expected_revision + 1
conn.execute("UPDATE messages SET content=? WHERE id=?", (answer, assistant_id))
conn.execute("UPDATE messages SET content=? WHERE id=?",
(json.dumps(data, ensure_ascii=False), estimate_id))
return "ok"
def clear_history(username: str, tab_id: str): def clear_history(username: str, tab_id: str):
"""Delete chat messages for one tab — backs the explicit reset action. """Delete chat messages for one tab — backs the explicit reset action.
+23
View File
@@ -0,0 +1,23 @@
# Выбор параметров прямо в ответе: этапы
Основа: разбор агрегированных тем диалогов сметчиков и существующий интерфейс. Не переносить тексты и файлы пользователей в спецификацию. Каждый выбор должен менять тот же сохранённый ответ или связанную с ним панель; новое сообщение в чате не создаётся.
## Контракт для каждого выбора
Сервер отдаёт тип параметра, текущий вариант, допустимые варианты, измеритель, источник, ревизию ответа и перечень зависимых чисел. Клиент отправляет только ID выбранного варианта и ревизию. Сервер повторно проверяет принадлежность диалогу, актуальность варианта, наличие исходных данных и пересчитывает зависимые числа. Неполные данные приводят к явному предупреждению, а не к готовой сумме. Два окна не должны перетирать выбор друг друга.
## Очерёдность
1. **Норма, объём, зона и квартал** — локальный коммит `a13cdaf`. ГЭСНм с измерителем «шт.», составом, который поддерживает строгий движок, и собранной ценовой формой. Проверены повторный выбор, чужой диалог, мобильная ширина и реальная ФСНБ. Остальные измерители и типы норм требуют расширения движка.
2. **Сопоставление ресурса между исходными документами** — следующий этап. Для каждой строки ВОР/ЛСР/КА хранить ID файла, листа/раздела, строки, исходное название, код, единицу, количество, тип цены и кандидатов сопоставления. В ответе показывать «выбрано из…» с 2–5 кандидатами и причиной сходства. Выбор без совпадения единиц требует явного коэффициента и подтверждения пользователя. После выбора пересчитать все строки и итоги, зависящие от ресурса. Проверить на паре реальных обезличенных документов с неверным первым кандидатом.
3. **Вид цены и НДС** — после структурирования источника из этапа 2. Показывать только реально присутствующие в источнике «с НДС», «без НДС», «с перевозкой» и период цены; не превращать одно в другое без подтверждённой ставки и методики. Поменять цену в том же ответе, пересчитать итог и показать, какие строки затронуты. Проверить случаи отсутствующего НДС и перевозки, смешанных периодов и валют.
4. **Выбор файла, версии и раздела** — после ID источников из этапа 2. В сообщении должен быть виден документ, дата/версия, лист/раздел. Смена источника инвалидирует старые сопоставления и итог до повторного расчёта. Проверить два одноимённых файла и новую версию старой сметы.
5. **Альтернативные нормы и статус замечаний** — расширить текущий выбор нормы на измерители и типы, которые умеет считать движок; для проверки сметы дать выбор «принять/отклонить/нужны данные» с сохранением причины и аудита. Это разные доменные операции, их не смешивать одним универсальным селектором.
## Гейты
- Для этапов 2–4 сначала измерить долю диалогов, где структурированные данные действительно доступны. Без привязки к строке источника не показывать псевдовыбор из текста ИИ.
- Перед каждым этапом: red-тест на неверного кандидата и конфликт ревизии, затем реализация, серверный расчёт на реальных данных, визуальный тест на 375 px и desktop, регрессия связанных сценариев.
- Показывать владельцу ссылку на доступный серверный стенд до решения о публикации. Продакшен выкладывать только по явной команде и после rollback-плана.
Оценка после этапа 1: этап 2 — 8–12 рабочих дней, этап 3 — 4–6, этап 4 — 3–5, этап 5 — отдельно после инвентаризации данных. Оценки пересмотреть после проверки доступности структурированных строк и ценовых полей.
+48
View File
@@ -0,0 +1,48 @@
# Подбор норм для Инфосметы
Образец пользовательского сценария: [Smetrix — подбор расценок](https://smetrix.ru/podbor/). На странице образца есть поиск по названию или шифру, выбор базы, карточки найденных норм, состав ресурсов, ценовой срез по региону/зоне/кварталу и сравнение. Реализуем собственный интерфейс поверх проверенных баз Инфосметы, без копирования текста, кода и дизайна образца.
## Результат для пользователя
Сметчик вводит работу обычными словами или шифром, видит подходящие нормы с измерителем и составом, сравнивает до трёх вариантов, выбирает подтверждённую норму и при наличии ценовой формы получает предварительный расчёт. Выбранную норму можно перенести в текущий ответ/черновик сметы с явным объёмом.
## Проверяемые критерии
1. По точному шифру выдаётся точная норма, по словесному запросу — ранжированный список с названием, базой, измерителем, составом работ, ресурсами и ссылкой на происхождение записи. Неподтверждённое совпадение помечается.
2. Фильтры показывают только реально загруженные базы/редакции; выбор субъекта, зоны и квартала берётся из каталога собранных форм. Отсутствие формы или неполный набор цен не выдаёт итог как готовую смету.
3. До трёх норм можно сравнить рядом: одинаковые поля, различия в составе работ/ресурсов/измерителе, ограничения по применимости. Разные измерители нельзя механически сравнить по сумме без приведения объёма.
4. Расчёт с объёмом выполняется только серверным движком и сохраняет выбранную норму, объём, основу цен и версию данных. Изменение основы пересчитывает тот же результат, а не добавляет новый ответ.
5. Есть проверка реальными данными для ГЭСНм и ГЭСН, узкого экрана, клавиатуры и неавторизованного доступа. Поиск без результата честно сообщает, какой базы/редакции не хватает.
## Данные и границы
- Источник норм: существующая ФСНБ SQLite и `fsnb_ref.find_works`/`find_gesn_composition`; состав и provenance сохраняются без пересказа ИИ.
- Цены: `engine_prices` и `estimate_contract`; варианты только из `basis_options`. ГЭСН без ценовой формы остаётся нормой с ресурсным составом, а не «нулевой ценой».
- ФЕР и ГЭСН, редакции 2020/2022, региональные базы и отдельные типы норм отображаются лишь там, где реально загружены и разрешены для поиска. Нет автоматического смешивания разных баз.
- Сравнение цен: уровень цен, НР/СП, НДС, доставка и неоценённые ресурсы показываются раздельно. Не додумывать отсутствующие ставки и коэффициенты.
- Публичный каталог и расчёты пользователей — разные права доступа, лимиты и аудит. Поиск не раскрывает чужие диалоги и файлы.
## План и зависимости
**A. Инвентаризация данных и качество поиска (3–5 дней).** Снять по каждой базе число норм и долю записей с составом/измерителем/provenance; подготовить корпус из реальных обезличенных запросов сметчиков и эталонных шифров. Проверить точный код, морфологию, синонимы, опечатки и похожие работы. Зафиксировать порог: точный код 100% на эталоне, top‑5 не ниже 90% на размеченных запросах. Если порог не достигнут, улучшать ранжирование до UI.
**B. Поисковый API (3–4 дня; после A).** Отдельный endpoint с `q`, `base`, `limit`, курсором. Валидация, rate limit, тайм-аут, безопасные SQL-параметры, стабильные IDs и provenance. Результат содержит score и причину совпадения, но слабое совпадение не объявляется точным.
**C. Сравнение норм (2–3 дня; после B).** API деталей и UI до трёх норм. Отдельно показывать измеритель, состав работ, ресурсы и условные позиции «П». Контракт запрещает сравнение сумм при разных единицах без явного объёма.
**D. Ценовой срез и перенос в смету (4–6 дней; после B и C).** Зона/квартал из каталога, расчёт серверным движком, неполные итоги и отсутствие НР/СП выделены. Перенос в существующий структурированный черновик/ответ требует ревизии и пересчёта; клиент не присылает цены.
**E. Приёмка на серверном стенде (2–3 дня; после D).** Проверить реальные ГЭСНм/ГЭСН, пустые цены, разные единицы, mobile 360 px, клавиатуру, повторный выбор и сохранение после reload. Сравнить производительность поиска на полной БД: p95 ≤ 2 с при согласованной нагрузке. Ссылка на доступный стенд обязательна при показе владельцу.
Первый рабочий срез реализован в коммите `09d092d`: `/podbor`, авторизованный поиск, детали с происхождением и составом ресурсов, сравнение до трёх норм, выбор доступной зоны и квартала, серверный предварительный расчёт и пересчёт сохранённого результата. На реальной ФСНБ проверены ГЭСНм `10-08-002-02` и ГЭСН `11-01-049-01`; отсутствие цены ресурса оставляет итог неполным. Десктоп и мобильный экран проверены в Chromium, скриншоты в `docs/verification/`.
До полной приёмки по критериям выше остаются размеченный benchmark top‑5, измерение p95 на полной БД, курсор поиска, публичный режим каталога с отдельным лимитом и структурированный перенос выбранной нормы в черновик сметы. Эти пункты нельзя подменять формой «вставить текст запроса в чат».
## Риски и решение перед стартом
- Разные редакции одной нормы выглядят одинаково по шифру — ключ результата включает базу, редакцию, тип сборника и идентификатор источника.
- Поисковая близость может подменить предмет работы — показать обоснование совпадения, состав работ и пометку «проверьте»; расчёт только после выбора пользователя.
- Неполные ресурсы или цены создадут убедительную, но ложную сумму — блокировать готовый итог и перечислить пропуски.
- Полная ФСНБ может дать медленный запрос — индекс и профилирование на копии данных до открытия UI.
После A цикл плана повторяется: сравнить фактическую полноту и качество поиска с критериями, уточнить B–E и только затем брать реализацию. Для выбора предложений КА и соответствия ресурсов из загруженных документов нужен отдельный структурированный слой с источниками, единицами и ценой с/без НДС; это следующий сценарий выбора внутри ответа, а не часть поиска норм.
+18
View File
@@ -2612,3 +2612,21 @@ GPT отдельно прочитал `regional_ref.py` и выписку `_regi
профильный набор — 128 зелёных; 14 мутаций из 14 пойманы своими проверками, профильный набор — 128 зелёных; 14 мутаций из 14 пойманы своими проверками,
исходники после прогона восстановлены побайтово. Рецензии DeepSeek и z.ai исходники после прогона восстановлены побайтово. Рецензии DeepSeek и z.ai
финального состояния, полный гейт и стенд — дальше. финального состояния, полный гейт и стенд — дальше.
# 2026-12-03 — выбор нормы и объёма внутри ответа
Готово, когда:
1. В обычном ответе с одной однозначной нормой и объёмом пользователь может нажать на код нормы или объём и выбрать другую норму того же сборника и измерителя либо изменить объём; результат заменяет тот же сохранённый ответ.
2. Варианты норм приходят из ФСНБ; сервер принимает только один из них, проверяет положительный конечный объём и доступную ценовую форму. Клиент не передаёт цены.
3. После повторного изменения и перезагрузки истории сохраняются последние выбранные норма, объём, зона и квартал; чужой диалог и устаревшая ревизия отклоняются.
4. Норма без определённого состава/измерителя и неполная цена не превращаются в готовый итог; существующий выбор зоны/квартала продолжает работать.
5. Отдельный документ содержит план самостоятельного подбора норм по образцу публичной страницы Smetrix с критериями приёмки, источниками и границами данных.
План реализации (зависимости: A → B → C → D):
- A. Серверный контракт: извлечение текущей позиции из сохранённого ответа, поиск соседних норм в ФСНБ, валидация выбора. Риск: неверная норма с другим измерителем. Проверка: unit и семейство нормы совпадают.
- B. Пересчёт и атомарная замена ответа с ревизией. Риск: повторный выбор берёт объём исходного вопроса. Проверка: две последовательные замены с разными объёмами.
- C. Кнопки на коде и объёме внутри пузыря, доступный селектор, состояние ошибки. Риск: markdown и асинхронная перерисовка снимают обработчики. Проверка: браузерный сценарий с reload и мобильной шириной.
- D. Регрессия API и реальный расчёт на стендовых данных, затем ревью. Риск: UI показывает цену при неполном наборе ресурсов. Проверка: неполный итог явно помечен.
Премортем: (1) высокая/серьёзный — поиск по похожему коду подставил иной измеритель; фильтр unit и серверный перечень вариантов. (2) средняя/серьёзный — вопрос и новый ответ разошлись; парсить текущую позицию из сохранённого пересчёта. (3) средняя/серьёзный — выбор перетёр соседнюю вкладку; CAS по ревизии. (4) средняя/незначительный — длинный селектор сломал узкий экран; перенос строк и браузерный осмотр. Три действия: строгая серверная валидация, повторный выбор в тесте, осмотр узкой ширины.
@@ -0,0 +1,15 @@
# Интерактивная ценовая основа сметы
Проверяемые критерии:
1. В новом структурированном ответе сметы выбор зоны и квартала находится внутри того же пузыря ответа; при выборе сервер пересчитывает зависимые числа и заменяет содержимое этого пузыря без нового сообщения.
2. Доступны только реально собранные формы выбранного субъекта. Пустая/недоступная форма, чужой диалог и устаревшая ревизия не меняют сохранённый ответ.
3. Изменённый ответ и основа расчёта сохраняются вместе и правильно восстанавливаются после перезагрузки истории. Старые ответы без привязки остаются читаемыми.
4. Никакой клиентский пересчёт сумм: числа берутся из `estimate_contract.calc_estimate`. Продукт не показывает неполный итог как готовую смету.
5. Гейт release и ручной осмотр десктопа и узкого экрана проходят до предложения выкладки на прод.
6. Обычный ответ ИИ с одной явной нормой и объёмом в штуках также показывает выбор на названиях ценовых зон. После выбора зоны и квартала строгий расчёт заменяет этот же ответ и переживает обновление страницы; ответ без расчётной позиции не получает ложную кнопку.
7. Ресурсы монтажной нормы берутся из ФСНБ, цены — из формы зоны. Если НР/СП или ресурс не определены, показана только учтённая часть с явным предупреждением; числа другого периода и ответ ИИ не подставляются.
План: (A) связать сохранённые assistant/estimate записи и допустимые формы → (B) scoped API пересчёта и атомарного сохранения → (C) селекторы и замена внутри пузыря → (D) интеграционные и UI проверки → (E) release стенд и визуальный осмотр.
Риски: поток перерисует кнопки; выбор устаревшего периода даст чужие цены; два окна одновременно перетрут друг друга; после reload текст и панель разойдутся; длинная таблица сломает мобильную ширину; свободный текст ИИ может назвать цену чужого квартала. Меры: монтировать после сохранения ответа, стабильные ID каталога, ревизия, транзакция, браузерный осмотр, для свободного ответа считать только подтверждённую норму и объём без обращения к ИИ.
+11
View File
@@ -0,0 +1,11 @@
# Сверка строк файлов внутри ответа
## Критерии приёмки
1. После ответа на запрос КА↔ЛСР или ВОР↔ЛСР в том же пузыре есть панель выбора исходных файлов и листов. Никакого отдельного ответа на изменение параметра.
2. Каждая показанная строка содержит файл, лист, номер строки, исходный код, название, единицу и цену/объём. Система автоматически принимает только точный код с совместимой единицей; похожее название предлагает кандидатов, но не объявляет их совпадением.
3. Пользователь может выбрать другую строку-сопоставление, доступный столбец цены (с НДС/без НДС/сметная цена) или другой исходный файл. После выбора зависимые разницы пересчитывает сервер. НДС и единицы без известного коэффициента не пересчитываются из догадки.
4. Результат и выбранные параметры сохраняются; reload показывает тот же выбор. Чужой диалог, устаревшая ревизия и изменившийся на диске файл отвергаются без изменения ответа.
5. Неоднозначные заголовки, пустые ячейки, формулы без кешированного значения, отсутствие второй книги и неполные строки помечаются; сервис не показывает неполную сверку как завершённую.
Порядок: A. Безопасный разбор файлов и схемы колонок → B. Источники и кандидаты с серверной арифметикой → C. scoped сохранение и CAS → D. панель в текущем ответе → E. тест на серверном стенде с доступной ссылкой. После каждого шага тестировать уже существующие расчёты и историю чата.
Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 37 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 61 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 62 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 34 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 40 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 86 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 42 KiB

+21
View File
@@ -232,6 +232,27 @@ def load_catalog() -> dict | None:
return None return None
def basis_options(subject_id: int) -> list[dict]:
"""Only built price forms for one subject, grouped for an inline selector."""
catalog = load_catalog() or {}
zones: dict[int, dict] = {}
for entry in catalog.get("zones") or []:
if entry.get("subject_id") != subject_id:
continue
zone_id = entry.get("zone_id")
period_id = entry.get("period_id")
if not isinstance(zone_id, int) or not isinstance(period_id, int):
continue
zone = zones.setdefault(zone_id, {"zone_id": zone_id,
"name": entry.get("zone_name") or "",
"periods": []})
zone["periods"].append({"period_id": period_id,
"name": entry.get("period_label") or ""})
for zone in zones.values():
zone["periods"].sort(key=lambda period: period["period_id"])
return sorted(zones.values(), key=lambda zone: zone["name"])
@functools.lru_cache(maxsize=4) @functools.lru_cache(maxsize=4)
def _load_form(path: str, sha256: str | None, builder: int | None): def _load_form(path: str, sha256: str | None, builder: int | None):
# Контрольная сумма и версия — в ключе кеша: перезалитая форма той же зоны и периода лежит по # Контрольная сумма и версия — в ключе кеша: перезалитая форма той же зоны и периода лежит по
+62
View File
@@ -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(",", " ").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)
+3 -1
View File
@@ -398,12 +398,14 @@ def find_works(*, query: str, base: str | None = None,
"не найдено. Код и норму бери только из данных — уточни " "не найдено. Код и норму бери только из данных — уточни "
"наименование или шифр.")} "наименование или шифр.")}
diverse = _diverse_works(rows, limit) diverse = _diverse_works(rows, limit)
srcs = _sources_map(con)
out = [{"code": r["code"], "name": r["name"], "unit": r["unit"], out = [{"code": r["code"], "name": r["name"], "unit": r["unit"],
"base": r["base"], "base_type": r["base_type"], "base": r["base"], "base_type": r["base_type"],
"price_level": r["price_level"], "section_path": r["section_path"], "price_level": r["price_level"], "section_path": r["section_path"],
"content": r["content"], "content": r["content"],
"cost": r["cost"], "salary": r["salary"], "cost": r["cost"], "salary": r["salary"],
"machines": r["machines"], "materials": r["materials"]} "machines": r["machines"], "materials": r["materials"],
"provenance": _provenance(srcs.get(r["source_id"]))}
for r in diverse] for r in diverse]
return {"status": "ok", "works": out, "total": len(rows)} return {"status": "ok", "works": out, "total": len(rows)}
except sqlite3.Error as e: except sqlite3.Error as e:
+284
View File
@@ -0,0 +1,284 @@
"""Conservative, source-linked comparison of uploaded estimate workbooks."""
from __future__ import annotations
from decimal import Decimal, InvalidOperation
from difflib import SequenceMatcher
from hashlib import sha256
from pathlib import Path
import re
MAX_ROWS = 5000
MAX_COLUMNS = 80
MAX_FILE_BYTES = 30 * 1024 * 1024
def _norm(value: object) -> str:
return re.sub(r"\s+", " ", str(value or "").casefold().replace("ё", "е")).strip()
def _field(header: object) -> str | None:
h = _norm(header)
if not h:
return None
if "наименован" in h or h in {"ресурс", "работа", "вид работ"}:
return "name"
if "ед. изм" in h or "единица измерения" in h or h == "единица":
return "unit"
if "код" in h or "шифр" in h:
return "code"
if "количеств" in h or "объем" in h or "объём" in h:
return "quantity"
if "отпускная" in h and "ндс" in h and "без" not in h:
return "price_with_vat"
if "цена" in h and "ндс" in h and "без" not in h:
return "price_with_vat"
if "сметная цена" in h and "без" in h and "ндс" in h:
return "price_no_vat"
if ("стоимость" in h or "цена" in h) and ("на единицу" in h or "единицу измерения" in h):
return "unit_price"
return None
def _number(value: object) -> str | None:
if value is None or isinstance(value, bool):
return None
s = str(value).strip().replace("\u00a0", "").replace(" ", "")
if not s:
return None
if "," in s and "." in s:
return None # ambiguous decimal notation
try:
amount = Decimal(s.replace(",", "."))
except InvalidOperation:
return None
if not amount.is_finite():
return None
if abs(amount) > Decimal("1000000000000"):
return None
try:
return str(amount.quantize(Decimal("0.01")))
except InvalidOperation:
return None
def _safe_file(work_dir: Path, filename: str) -> Path:
if not filename or filename in {".", ".."} or Path(filename).name != filename or "\\" in filename:
raise ValueError("Недопустимое имя файла")
root = Path(work_dir).resolve()
path = root / filename
if path.is_symlink() or path.resolve().parent != root:
raise ValueError("Файл вне рабочей папки")
if path.suffix.lower() not in {".xlsx", ".xlsm"}:
raise ValueError("Поддерживаются только xlsx/xlsm")
if not path.is_file() or path.stat().st_size > MAX_FILE_BYTES:
raise ValueError("Файл не найден или превышает 30 МБ")
return path
def file_fingerprint(work_dir: Path, filename: str) -> str:
path = _safe_file(work_dir, filename)
digest = sha256()
with path.open("rb") as stream:
for chunk in iter(lambda: stream.read(1024 * 1024), b""):
digest.update(chunk)
return digest.hexdigest()
def list_workbooks(work_dir: Path) -> list[dict]:
"""List eligible uploaded files and sheets without reading document rows."""
import openpyxl
from xlsx_utils import assert_xlsx_not_bomb
root = Path(work_dir)
if not root.is_dir():
return []
found = []
for path in sorted(root.iterdir(), key=lambda p: p.name.casefold()):
if path.suffix.lower() not in {".xlsx", ".xlsm"} or path.name.startswith("~$"):
continue
try:
safe = _safe_file(root, path.name)
assert_xlsx_not_bomb(safe)
book = openpyxl.load_workbook(safe, read_only=True, data_only=True)
try:
found.append({"filename": path.name, "sheets": list(book.sheetnames)})
finally:
book.close()
except Exception:
# A corrupt workbook is never offered as a source.
continue
return found
def read_table(work_dir: Path, filename: str, sheet: str, role: str) -> dict:
import openpyxl
from xlsx_utils import assert_xlsx_not_bomb
if role not in {"ka", "lsr", "vor", "kp"}:
raise ValueError("Неизвестный тип документа")
path = _safe_file(work_dir, filename)
assert_xlsx_not_bomb(path)
fingerprint = file_fingerprint(work_dir, filename)
book = openpyxl.load_workbook(path, read_only=True, data_only=True)
try:
if sheet not in book.sheetnames:
raise ValueError("Лист не найден")
ws = book[sheet]
header_row = None
columns = {}
for row_idx, cells in enumerate(ws.iter_rows(min_row=1, max_row=30, max_col=MAX_COLUMNS,
values_only=True), 1):
mapping = {}
duplicates = set()
for col_idx, cell in enumerate(cells):
field = _field(cell)
if field in mapping:
duplicates.add(field)
elif field:
mapping[field] = col_idx
needed = {"name", "unit"}
metric = ({"price_no_vat", "price_with_vat"} if role == "ka" else
{"unit_price", "quantity"} if role == "lsr" else
{"quantity"} if role == "vor" else
{"price_with_vat", "unit_price"})
if needed <= mapping.keys() and metric & mapping.keys():
if duplicates:
raise ValueError("Неоднозначные заголовки: " + ", ".join(sorted(duplicates)))
header_row, columns = row_idx, mapping
break
if header_row is None:
raise ValueError("Не найдены однозначные заголовки имени, единицы и цены/объёма")
rows = []
for row_idx, cells in enumerate(ws.iter_rows(min_row=header_row + 1,
max_row=header_row + MAX_ROWS + 1,
max_col=MAX_COLUMNS, values_only=True), header_row + 1):
if len(rows) >= MAX_ROWS:
break
name = str(cells[columns["name"]] or "").strip()
if not name:
continue
values = {}
for field in ("price_no_vat", "price_with_vat", "unit_price", "quantity"):
if field in columns:
parsed = _number(cells[columns[field]])
if parsed is not None:
values[field] = parsed
rows.append({"file": filename, "sheet": sheet, "row": row_idx,
"code": str(cells[columns["code"]] or "").strip() if "code" in columns else "",
"name": name,
"unit": str(cells[columns["unit"]] or "").strip(),
"values": values})
return {"file": filename, "sheet": sheet, "role": role,
"fields": list(columns),
"fingerprint": fingerprint, "rows": rows,
"truncated": (ws.max_row or 0) > header_row + MAX_ROWS}
finally:
book.close()
def _unit(value: str) -> str:
u = _norm(value).replace(".", "").replace("²", "2").replace("³", "3")
return {"штука": "шт", "штук": "шт", "м кв": "м2", "кв м": "м2",
"м куб": "м3", "куб м": "м3"}.get(u, u)
def _candidate(left: dict, right: dict) -> tuple[float, bool, str]:
same_code = bool(left["code"] and right["code"] and _norm(left["code"]) == _norm(right["code"]))
same_name = _norm(left["name"]) == _norm(right["name"])
unit_ok = bool(_unit(left["unit"]) and _unit(left["unit"]) == _unit(right["unit"]))
ratio = SequenceMatcher(None, _norm(left["name"]), _norm(right["name"])).ratio()
score = (2 if same_code else 0) + (1 if same_name else ratio) + (0.25 if unit_ok else 0)
auto = unit_ok and (same_code or (not left["code"] and same_name))
return score, auto, ("Точный код" if same_code else "Точное название" if same_name else "Похожее название")
def detect_mode(question: str) -> str | None:
q = _norm(question)
if not any(term in q for term in ("сравн", "свер", "сопостав")):
return None
ka = bool(re.search(r"\bка\b", q) or "конъюнктур" in q)
lsr = bool(re.search(r"\bлср\b", q) or "локальн" in q or "смет" in q)
vor = bool(re.search(r"\bвор\b", q) or "ведомост" in q)
kp = bool(re.search(r"\bкп\b", q) or "коммерческ" in q)
if ka and lsr:
return "ka_lsr"
if vor and lsr:
return "vor_lsr"
if ka and kp:
return "ka_kp"
return None
def compare(left: dict, right: dict, mode: str, *, choices: dict | None = None,
price_fields: dict | None = None) -> dict:
roles = {"ka_lsr": ("ka", "lsr"), "vor_lsr": ("vor", "lsr"), "ka_kp": ("ka", "kp")}
if mode not in roles or (left["role"], right["role"]) != roles[mode]:
raise ValueError("Несовместимые типы документов")
choices, price_fields = choices or {}, price_fields or {}
result = []
by_code: dict[str, set[int]] = {}
by_name: dict[str, set[int]] = {}
by_token: dict[str, set[int]] = {}
for other_index, other in enumerate(right["rows"]):
if other["code"]:
by_code.setdefault(_norm(other["code"]), set()).add(other_index)
by_name.setdefault(_norm(other["name"]), set()).add(other_index)
for token in set(re.findall(r"[\w-]{4,}", _norm(other["name"]))):
by_token.setdefault(token, set()).add(other_index)
for index, row in enumerate(left["rows"]):
ranked = []
exact = set(by_code.get(_norm(row["code"]), ())) if row["code"] else set()
exact.update(by_name.get(_norm(row["name"]), ()))
relevant = set(exact)
for token in set(re.findall(r"[\w-]{4,}", _norm(row["name"]))):
relevant.update(by_token.get(token, ()))
candidate_indices = sorted(exact)[:100] + sorted(relevant - exact)[:100]
for other_index in candidate_indices:
other = right["rows"][other_index]
score, auto, reason = _candidate(row, other)
if score >= 0.45:
ranked.append((score, other_index, auto, reason))
ranked.sort(key=lambda hit: (-hit[0], hit[1]))
candidates = [{"index": idx, "reason": reason, "code": right["rows"][idx]["code"],
"name": right["rows"][idx]["name"], "unit": right["rows"][idx]["unit"],
"file": right["file"], "sheet": right["sheet"], "row": right["rows"][idx]["row"]}
for _, idx, _, reason in ranked[:5]]
selected = choices.get(index)
if selected == -1:
selected = None
elif selected is not None:
if not isinstance(selected, int) or selected < 0 or selected >= len(right["rows"]):
raise ValueError("Выбранной строки нет в исходном файле")
elif ranked and ranked[0][2] and (len(ranked) == 1 or ranked[0][0] > ranked[1][0]):
selected = ranked[0][1]
left_field = price_fields.get(index, "price_no_vat" if mode == "ka_lsr" else
"quantity" if mode == "vor_lsr" else "price_with_vat")
allowed = {"ka_lsr": {"price_no_vat", "price_with_vat"},
"vor_lsr": {"quantity"}, "ka_kp": {"price_with_vat", "price_no_vat"}}[mode]
if left_field not in allowed or left_field not in left.get("fields", row["values"]):
raise ValueError("Выбранного столбца нет в исходном файле")
right_field = "quantity" if mode == "vor_lsr" else "unit_price" if mode == "ka_lsr" else "price_with_vat"
warning = ""
difference = None
right_row = right["rows"][selected] if selected is not None else None
if right_row is None:
warning = "Совпадение не подтверждено"
elif _unit(row["unit"]) != _unit(right_row["unit"]) or not _unit(row["unit"]):
warning = "Несовместимые единицы измерения"
elif mode == "ka_lsr" and left_field == "price_with_vat":
warning = "Цена с НДС и сметная стоимость: база НДС не совпадает"
elif left_field not in row["values"] or right_field not in right_row["values"]:
warning = "В исходной строке нет числового значения"
else:
difference = str((Decimal(right_row["values"][right_field]) -
Decimal(row["values"][left_field])).quantize(Decimal("0.01")))
result.append({"index": index, "left": row, "match_index": selected,
"right": right_row, "left_field": left_field, "right_field": right_field,
"difference": difference, "warning": warning, "candidates": candidates})
matched = {r["match_index"] for r in result if r["match_index"] is not None}
unmatched_right = len(right["rows"]) - len(matched) if mode == "vor_lsr" else 0
return {"mode": mode, "left": left, "right": right, "rows": result,
"unmatched_right": unmatched_right,
"complete": bool(result) and not left["truncated"] and not right["truncated"] and
unmatched_right == 0 and all(r["difference"] is not None for r in result)}
+446 -4
View File
@@ -555,7 +555,7 @@ MAX_MESSAGE_LEN = 10_000
# ⚠️ Версия UI — единый источник. БАМПАТЬ ПРИ КАЖДОМ ДЕПЛОЕ (формат: YYYY-MM-DD + буква). # ⚠️ Версия UI — единый источник. БАМПАТЬ ПРИ КАЖДОМ ДЕПЛОЕ (формат: YYYY-MM-DD + буква).
# Фронт берёт её через GET /api/version (chat.html + admin.html, элемент .app-version). # Фронт берёт её через GET /api/version (chat.html + admin.html, элемент .app-version).
APP_VERSION = "2026-12-02c" APP_VERSION = "2026-12-02e"
# Audit: path → action name mapping # Audit: path → action name mapping
_AUDIT_MAP = [ _AUDIT_MAP = [
@@ -1079,6 +1079,12 @@ async def index(request: Request):
) )
@app.get("/podbor", response_class=HTMLResponse)
async def norm_finder_page():
return FileResponse("static/norm-finder.html", media_type="text/html",
headers={"Cache-Control": "no-store"})
@app.get("/api/version") @app.get("/api/version")
async def version(): async def version():
"""Public — single source of UI version (stamped into .app-version on the front).""" """Public — single source of UI version (stamped into .app-version on the front)."""
@@ -1995,8 +2001,11 @@ async def _stream_and_save(message: str, user: str, tab_id: str):
# был бы уже вторым и диалог остался бы без стабильного имени. # был бы уже вторым и диалог остался бы без стабильного имени.
_maybe_autotitle(user, tab_id, message) _maybe_autotitle(user, tab_id, message)
return return
assistant_message_id = None
if full_response: if full_response:
save_message(user, tab_id, "assistant", full_response) assistant_message_id = save_message(user, tab_id, "assistant", full_response)
yield ("event: assistant_id\ndata: "
+ json.dumps({"id": assistant_message_id}) + "\n\n")
# Цена ответа — отдельной записью СРАЗУ за ответом: так она переживает # Цена ответа — отдельной записью СРАЗУ за ответом: так она переживает
# обновление страницы. В память диалога эта роль не попадает (chat_context # обновление страницы. В память диалога эта роль не попадает (chat_context
# берёт только реплики), иначе модель начала бы отвечать на цену. # берёт только реплики), иначе модель начала бы отвечать на цену.
@@ -2004,6 +2013,19 @@ async def _stream_and_save(message: str, user: str, tab_id: str):
save_message(user, tab_id, "spend", save_message(user, tab_id, "spend",
json.dumps(_spend_payload["answer"], ensure_ascii=False)) json.dumps(_spend_payload["answer"], ensure_ascii=False))
_maybe_autotitle(user, tab_id, message) _maybe_autotitle(user, tab_id, message)
# A file comparison belongs to the answer that requested it. Store only
# source selections; rows are reread from the user's current work folder.
if assistant_message_id and not errored:
import inline_compare
compare_mode = inline_compare.detect_mode(message)
if compare_mode:
compare_data = {"_assistant_id": assistant_message_id, "_revision": 0,
"mode": compare_mode, "left": None, "right": None,
"choices": {}, "price_fields": {}}
compare_id = save_message(user, tab_id, "file_compare",
json.dumps(compare_data, ensure_ascii=False))
compare_data["_message_id"] = compare_id
yield f"event: file_compare\ndata: {json.dumps(compare_data, ensure_ascii=False)}\n\n"
# Структурированная смета от агента (tool show_estimate пишет _estimate_panel.json) → # Структурированная смета от агента (tool show_estimate пишет _estimate_panel.json) →
# событие estimate + панель. Файл читаем, эмитим, удаляем (не в кнопки, не повторно). # событие estimate + панель. Файл читаем, эмитим, удаляем (не в кнопки, не повторно).
est_file = work_dir / "_estimate_panel.json" est_file = work_dir / "_estimate_panel.json"
@@ -2011,8 +2033,13 @@ async def _stream_and_save(message: str, user: str, tab_id: str):
try: try:
est_data = json.loads(est_file.read_text(encoding="utf-8")) est_data = json.loads(est_file.read_text(encoding="utf-8"))
if isinstance(est_data, dict) and est_data.get("positions"): if isinstance(est_data, dict) and est_data.get("positions"):
save_message(user, tab_id, "estimate", json.dumps(est_data, ensure_ascii=False)) if assistant_message_id:
yield f"event: estimate\ndata: {json.dumps(est_data, ensure_ascii=False)}\n\n" est_data["_assistant_id"] = assistant_message_id
est_data["_revision"] = 0
estimate_message_id = save_message(
user, tab_id, "estimate", json.dumps(est_data, ensure_ascii=False))
event_data = {**est_data, "_message_id": estimate_message_id}
yield f"event: estimate\ndata: {json.dumps(event_data, ensure_ascii=False)}\n\n"
except Exception: except Exception:
pass pass
finally: finally:
@@ -2360,6 +2387,247 @@ async def sessions(request: Request):
return list_sessions(user) return list_sessions(user)
@app.get("/api/norm-finder/catalog")
async def norm_finder_catalog(request: Request):
_get_user(request)
import norm_finder
import engine_prices
bases = await asyncio.to_thread(norm_finder.catalog)
price_catalog = await asyncio.to_thread(engine_prices.load_catalog) or {}
subjects = {}
for row in price_catalog.get("zones") or []:
sid = row.get("subject_id")
if isinstance(sid, int) and not isinstance(sid, bool):
subjects[sid] = row.get("subject_name") or f"Субъект {sid}"
return {"bases": bases, "subjects": [{"id": sid, "name": name}
for sid, name in sorted(subjects.items(), key=lambda x: x[1])]}
@app.get("/api/norm-finder/search")
async def norm_finder_search(request: Request, q: str = "", base: str = "2022", limit: int = 12):
_get_user(request)
import norm_finder
try:
found = await asyncio.to_thread(norm_finder.search, q, base, limit)
except ValueError as exc:
raise HTTPException(400, str(exc)) from exc
if found.get("status") == "db_unavailable":
raise HTTPException(503, found.get("message"))
return found
@app.get("/api/norm-finder/detail")
async def norm_finder_detail(request: Request, base: str = "", base_type: str = "",
code: str = ""):
_get_user(request)
import norm_finder
try:
return await asyncio.to_thread(norm_finder.detail, base, base_type, code)
except ValueError as exc:
raise HTTPException(400, str(exc)) from exc
@app.get("/api/norm-finder/prices")
async def norm_finder_prices(request: Request, subject_id: int):
_get_user(request)
import engine_prices
if subject_id < 1:
raise HTTPException(400, "Укажите субъект")
return {"zones": await asyncio.to_thread(engine_prices.basis_options, subject_id)}
async def _finder_calculation(body: dict, base: str, base_type: str, code: str) -> dict:
import engine_prices
import estimate_interactive
import norm_finder
sid, zid, pid = (body.get(key) for key in ("subject_id", "zone_id", "period_id"))
qty, unit = body.get("quantity"), body.get("unit")
if (any(not isinstance(v, int) or isinstance(v, bool) or v < 1 for v in (sid, zid, pid))
or not isinstance(qty, (int, float)) or isinstance(qty, bool)
or not 0.000001 <= qty <= 1_000_000 or not math.isfinite(qty)
or not isinstance(unit, str) or not 1 <= len(unit) <= 60):
raise HTTPException(400, "Укажите доступную зону, квартал, объём и его единицу")
zones = await asyncio.to_thread(engine_prices.basis_options, sid)
selected = estimate_interactive.selected_form(zones, zid, pid)
if selected is None:
raise HTTPException(400, "Выбранной ценовой формы нет в каталоге")
zone, period = selected
try:
result = await asyncio.to_thread(norm_finder.calculate, base, base_type, code,
qty, unit, zone["name"], period["name"])
except ValueError as exc:
raise HTTPException(400, str(exc)) from exc
return {"selection": {"base": base, "base_type": base_type, "code": code,
"quantity": qty, "unit": unit, "subject_id": sid,
"zone_id": zid, "period_id": pid}, "result": result}
@app.post("/api/norm-finder/calculate")
async def norm_finder_calculate(request: Request):
user, tab_id = _get_user(request), _get_tab(request)
body = await _тело(request)
base, base_type, code = (body.get(key) for key in ("base", "base_type", "code"))
if not all(isinstance(value, str) for value in (base, base_type, code)):
raise HTTPException(400, "Укажите норму из каталога")
_check_rate_limit(user)
data = await _finder_calculation(body, base, base_type, code)
data["revision"] = 0
quote_id = await asyncio.to_thread(save_message, user, tab_id, "norm_quote",
json.dumps(data, ensure_ascii=False))
log_action(user, "norm_finder", "POST", "/api/norm-finder/calculate",
f"quote={quote_id}; code={code}", _client_ip(request) or None, 200)
return {"id": quote_id, **data}
@app.get("/api/norm-finder/quotes/{quote_id}")
async def norm_finder_quote(quote_id: int, request: Request):
user, tab_id = _get_user(request), _get_tab(request)
saved = await asyncio.to_thread(db.get_scoped_norm_quote, user, tab_id, quote_id)
if saved is None:
raise HTTPException(404, "Расчёт этого диалога не найден")
return {"id": quote_id, **saved["data"]}
@app.post("/api/norm-finder/quotes/{quote_id}")
async def norm_finder_recalculate(quote_id: int, request: Request):
user, tab_id = _get_user(request), _get_tab(request)
body = await _тело(request)
saved = await asyncio.to_thread(db.get_scoped_norm_quote, user, tab_id, quote_id)
if saved is None:
raise HTTPException(404, "Расчёт этого диалога не найден")
current = saved["data"]
revision = body.get("revision")
if not isinstance(revision, int) or isinstance(revision, bool) or revision != current.get("revision"):
raise HTTPException(409, "Расчёт изменён в другой вкладке — обновите страницу")
selection = current.get("selection") or {}
_check_rate_limit(user)
updated = await _finder_calculation(body, selection.get("base"),
selection.get("base_type"), selection.get("code"))
updated["revision"] = revision + 1
changed = await asyncio.to_thread(db.replace_scoped_norm_quote, user, tab_id, quote_id,
saved["raw"], json.dumps(updated, ensure_ascii=False))
if not changed:
raise HTTPException(409, "Расчёт изменён в другой вкладке — обновите страницу")
log_action(user, "norm_finder", "POST", f"/api/norm-finder/quotes/{quote_id}",
f"quote={quote_id}; revision={updated['revision']}", _client_ip(request) or None, 200)
return {"id": quote_id, **updated}
@app.get("/api/file-compare/workbooks")
async def file_compare_workbooks(request: Request):
user, tab_id = _get_user(request), _get_tab(request)
from path_safety import safe_work_dir
import inline_compare
folder = safe_work_dir(user, tab_id, create=False)
return {"workbooks": await asyncio.to_thread(inline_compare.list_workbooks, folder)}
def _file_compare_state(folder: Path, data: dict, page: int = 0) -> dict:
import inline_compare
left, right = data.get("left"), data.get("right")
if not left or not right:
return {"comparison": None, "page": 0}
for selected in (left, right):
if inline_compare.file_fingerprint(folder, selected["file"]) != selected["fingerprint"]:
raise HTTPException(409, "Исходный файл изменился — выберите файлы заново")
mode = data["mode"]
roles = {"ka_lsr": ("ka", "lsr"), "vor_lsr": ("vor", "lsr"), "ka_kp": ("ka", "kp")}
left_table = inline_compare.read_table(folder, left["file"], left["sheet"], roles[mode][0])
right_table = inline_compare.read_table(folder, right["file"], right["sheet"], roles[mode][1])
if (left_table["fingerprint"] != left["fingerprint"] or
right_table["fingerprint"] != right["fingerprint"]):
raise HTTPException(409, "Исходный файл изменился во время чтения")
choices = {int(k): v for k, v in data.get("choices", {}).items()}
fields = {int(k): v for k, v in data.get("price_fields", {}).items()}
compared = inline_compare.compare(left_table, right_table, mode,
choices=choices, price_fields=fields)
all_rows = compared["rows"]
compared["rows"] = all_rows[page * 50:(page + 1) * 50]
compared["total_rows"] = len(all_rows)
compared["unmatched"] = sum(row["difference"] is None for row in all_rows)
compared["left"].pop("rows")
compared["right"].pop("rows")
return {"comparison": compared, "page": page}
@app.get("/api/file-compare/{compare_id}")
async def file_compare_get(compare_id: int, request: Request, page: int = 0):
user, tab_id = _get_user(request), _get_tab(request)
from path_safety import safe_work_dir
saved = await asyncio.to_thread(db.get_linked_file_compare, user, tab_id, compare_id)
if saved is None:
raise HTTPException(404, "Сверка этого диалога не найдена")
if not 0 <= page <= 99:
raise HTTPException(400, "Недопустимая страница")
try:
state = await asyncio.to_thread(_file_compare_state,
safe_work_dir(user, tab_id, create=False),
saved["data"], page)
except ValueError as exc:
raise HTTPException(400, str(exc)) from exc
return {"id": compare_id, **saved["data"], **state}
@app.post("/api/file-compare/{compare_id}")
async def file_compare_update(compare_id: int, request: Request):
user, tab_id = _get_user(request), _get_tab(request)
from path_safety import safe_work_dir
import inline_compare
body = await _тело(request)
saved = await asyncio.to_thread(db.get_linked_file_compare, user, tab_id, compare_id)
if saved is None:
raise HTTPException(404, "Сверка этого диалога не найдена")
current = saved["data"]
revision = body.get("revision")
if not isinstance(revision, int) or isinstance(revision, bool) or revision != current.get("_revision"):
raise HTTPException(409, "Сверка изменена в другой вкладке — обновите страницу")
folder = safe_work_dir(user, tab_id, create=False)
updated = dict(current)
source_changed = False
try:
for side in ("left", "right"):
if side in body:
src = body[side]
if not isinstance(src, dict) or not all(isinstance(src.get(k), str)
for k in ("file", "sheet")):
raise ValueError("Выберите файл и лист")
available = inline_compare.list_workbooks(folder)
if not any(w["filename"] == src["file"] and src["sheet"] in w["sheets"]
for w in available):
raise ValueError("Файл или лист отсутствует в рабочей папке")
selected = {"file": src["file"], "sheet": src["sheet"],
"fingerprint": inline_compare.file_fingerprint(folder, src["file"])}
source_changed |= selected != current.get(side)
updated[side] = selected
if source_changed:
updated["choices"], updated["price_fields"] = {}, {}
else:
for key in ("choices", "price_fields"):
if key in body:
raw = body[key]
if not isinstance(raw, dict) or len(raw) > inline_compare.MAX_ROWS:
raise ValueError("Недопустимый выбор строк")
parsed = {}
for index, value in raw.items():
if not str(index).isdigit() or int(index) >= inline_compare.MAX_ROWS:
raise ValueError("Недопустимый номер строки")
if key == "choices" and (not isinstance(value, int) or isinstance(value, bool)):
raise ValueError("Недопустимое сопоставление")
if key == "price_fields" and not isinstance(value, str):
raise ValueError("Недопустимый столбец")
parsed[str(index)] = value
updated[key] = parsed
state = await asyncio.to_thread(_file_compare_state, folder, updated)
except ValueError as exc:
raise HTTPException(400, str(exc)) from exc
updated["_revision"] = revision + 1
changed = await asyncio.to_thread(db.replace_linked_file_compare, user, tab_id, compare_id,
saved["raw"], json.dumps(updated, ensure_ascii=False))
if not changed:
raise HTTPException(409, "Сверка изменена в другой вкладке — обновите страницу")
return {"id": compare_id, **updated, **state}
@app.post("/api/recalc") @app.post("/api/recalc")
async def recalc(request: Request): async def recalc(request: Request):
"""Пересчитать смету движком по правкам объёмов (срез 6.2). Числа — из движка, не из JS. """Пересчитать смету движком по правкам объёмов (срез 6.2). Числа — из движка, не из JS.
@@ -2398,6 +2666,180 @@ async def recalc(request: Request):
} }
@app.get("/api/estimates/{estimate_id}/basis")
async def estimate_basis_options(estimate_id: int, request: Request):
user = _get_user(request)
tab_id = _get_tab(request)
saved = await asyncio.to_thread(db.get_linked_estimate, user, tab_id, estimate_id)
if saved is None:
raise HTTPException(404, "Смета этого диалога не найдена")
import engine_prices
subject_id = (saved.get("applied") or {}).get("subject_id")
if not isinstance(subject_id, int) or isinstance(subject_id, bool):
raise HTTPException(400, "У этой сметы не указана ценовая база")
zones = await asyncio.to_thread(engine_prices.basis_options, subject_id)
if not zones:
raise HTTPException(400, "Для этой сметы нет доступных ценовых форм")
return {"zones": zones, "revision": saved.get("_revision", 0)}
async def _generate_freeform_basis_answer(user: str, tab_id: str, question: str,
old_answer: str, zone: str, period: str,
code_override: str | None = None,
qty_override: float | None = None) -> dict:
"""Strict recalculation; never substitute an LLM's guessed price for a form."""
import answer_basis
try:
answer = await asyncio.to_thread(answer_basis.calculate_plain,
question, old_answer, zone, period,
code_override, qty_override)
except ValueError as exc:
raise HTTPException(400, str(exc)) from exc
return {"answer": answer, "usage": {}, "provider": "estimate-engine", "model": ""}
@app.get("/api/messages/{message_id}/basis")
async def freeform_basis_options(message_id: int, request: Request, label: str = ""):
user, tab_id = _get_user(request), _get_tab(request)
saved = await asyncio.to_thread(db.get_scoped_assistant, user, tab_id, message_id)
if saved is None:
raise HTTPException(404, "Ответ этого диалога не найден")
import answer_basis
try:
zones, _ = await asyncio.to_thread(answer_basis.options_for_label, saved["content"], label)
except ValueError as exc:
raise HTTPException(400, str(exc)) from exc
position = answer_basis.extract_position(saved["question"], saved["content"])
norms = (await asyncio.to_thread(answer_basis.norm_choices, position[0])) if position else []
return {"zones": zones, "revision": answer_basis.revision(saved["content"]),
"position": {"code": position[0], "quantity": position[1]} if position else None,
"norms": norms}
@app.post("/api/messages/{message_id}/basis")
async def change_freeform_basis(message_id: int, request: Request):
"""Regenerate one plain answer in place after an explicit price basis choice."""
user, tab_id = _get_user(request), _get_tab(request)
body = await _тело(request)
label, token = body.get("label"), body.get("revision")
zone_id, period_id = body.get("zone_id"), body.get("period_id")
code_override, qty_override = body.get("norm_code"), body.get("quantity")
if (not isinstance(label, str) or not isinstance(token, str)
or any(not isinstance(value, int) or isinstance(value, bool) or value < 0
for value in (zone_id, period_id))):
raise HTTPException(400, "Укажите ценовую зону, квартал и версию ответа")
saved = await asyncio.to_thread(db.get_scoped_assistant, user, tab_id, message_id)
if saved is None:
raise HTTPException(404, "Ответ этого диалога не найден")
import answer_basis
import estimate_interactive
if answer_basis.revision(saved["content"]) != token:
raise HTTPException(409, "Ответ изменён в другой вкладке — обновите диалог")
if code_override is not None or qty_override is not None:
position = answer_basis.extract_position(saved["question"], saved["content"])
if (position is None or not isinstance(code_override, str)
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 HTTPException(400, "Укажите допустимую норму и положительный объём")
allowed = await asyncio.to_thread(answer_basis.norm_choices, position[0])
if code_override not in {row["code"] for row in allowed}:
raise HTTPException(400, "Выбранной нормы нет среди доступных вариантов")
try:
zones, _ = await asyncio.to_thread(answer_basis.options_for_label, saved["content"], label)
except ValueError as exc:
raise HTTPException(400, str(exc)) from exc
selected = estimate_interactive.selected_form(zones, zone_id, period_id)
if selected is None:
raise HTTPException(400, "Выбранной ценовой формы нет в каталоге")
zone, period = selected
safe_work_dir(user, tab_id, create=False)
_check_rate_limit(user)
_refuse_if_read_only(user)
_refuse_if_trial_over(user)
await _check_limits(user, tab_id)
log_action(user, "chat", "POST", f"/api/messages/{message_id}/basis",
f"tab={tab_id}; zone={zone_id}; period={period_id}", _client_ip(request) or None, 200)
try:
args = (user, tab_id, saved["question"], saved["content"],
zone["name"], period["name"])
kwargs = ({"code_override": code_override, "qty_override": float(qty_override)}
if code_override is not None else {})
generated = await asyncio.wait_for(
_generate_freeform_basis_answer(*args, **kwargs), timeout=180)
except TimeoutError as exc:
raise HTTPException(504, "Пересчёт не завершился — прежний ответ сохранён") from exc
changed = await asyncio.to_thread(db.replace_scoped_assistant, user, tab_id, message_id,
saved["content"], generated["answer"])
if not changed:
raise HTTPException(409, "Ответ изменён в другой вкладке — обновите диалог")
return {"answer": generated["answer"]}
@app.post("/api/estimates/{estimate_id}/basis")
async def change_estimate_basis(estimate_id: int, request: Request):
"""Recalculate and replace the same answer; never accept prices from the browser."""
user = _get_user(request)
tab_id = _get_tab(request)
body = await _тело(request)
zone_id, period_id, revision = (body.get(key) for key in
("zone_id", "period_id", "revision"))
if any(not isinstance(value, int) or isinstance(value, bool) or value < 0
for value in (zone_id, period_id, revision)):
raise HTTPException(400, "Укажите зону, квартал и версию ответа")
saved = await asyncio.to_thread(db.get_linked_estimate, user, tab_id, estimate_id)
if saved is None:
raise HTTPException(404, "Смета этого диалога не найдена")
if saved.get("_revision", 0) != revision:
raise HTTPException(409, "Ответ изменён в другой вкладке — обновите диалог")
import engine_prices
import estimate_contract as ec
import estimate_interactive as ei
if not ec.engine_enabled():
raise HTTPException(400, "Расчётный движок выключен")
subject_id = (saved.get("applied") or {}).get("subject_id")
if not isinstance(subject_id, int) or isinstance(subject_id, bool):
raise HTTPException(400, "У этой сметы не указана ценовая база")
zones = await asyncio.to_thread(engine_prices.basis_options, subject_id)
selected = ei.selected_form(zones, zone_id, period_id)
if selected is None:
raise HTTPException(400, "Выбранной ценовой формы нет в каталоге")
zone, period = selected
try:
positions = ei.positions_for_revision(saved, body.get("positions"))
except ValueError as exc:
raise HTTPException(400, str(exc)) from exc
subject = (saved.get("applied") or {}).get("subject")
meta = {"region": subject, "zone": zone["name"], "price_level": period["name"]}
result = await asyncio.to_thread(ec.calc_estimate, positions, meta)
if result.get("status") != "ok":
raise HTTPException(400, result.get("message") or "Не удалось пересчитать смету")
applied = result.get("applied") or {}
if applied.get("zone_id") != zone_id or applied.get("period_id") != period_id:
raise HTTPException(409, "Ценовая база изменилась — обновите диалог")
try:
answer = ei.revised_answer(result)
except ValueError as exc:
raise HTTPException(409, str(exc)) from exc
updated = {
"title": saved.get("title") or "Смета (пересчёт)",
"positions": [{"code": p.get("code"), "name": p.get("name"), "unit": p.get("unit"),
"qty": p.get("qty"), "total": p.get("total")}
for p in result.get("positions", [])],
"totals": {"grand_total": result["grand_total"]},
"ok": result.get("ok"), "missing": result.get("missing"),
"applied": applied, "unpriced": result.get("unpriced"),
"limits_note": result.get("limits_note"), "meta": ec.recalc_meta(applied),
}
outcome = await asyncio.to_thread(db.replace_linked_estimate, user, tab_id,
estimate_id, revision, updated, answer)
if outcome == "stale":
raise HTTPException(409, "Ответ изменён в другой вкладке — обновите диалог")
if outcome != "ok":
raise HTTPException(404, "Смета этого диалога не найдена")
return {"answer": answer, "estimate": {**updated, "_message_id": estimate_id}}
@app.delete("/api/sessions/{tab_id}") @app.delete("/api/sessions/{tab_id}")
async def delete_session_ep(tab_id: str, request: Request): async def delete_session_ep(tab_id: str, request: Request):
"""Удалить свой диалог ЦЕЛИКОМ (история в БД + загруженные файлы на диске). """Удалить свой диалог ЦЕЛИКОМ (история в БД + загруженные файлы на диске).
+183
View File
@@ -0,0 +1,183 @@
"""Source-backed norm finder and conservative current-price preview."""
from __future__ import annotations
import math
import re
import fsnb_ref
BASES = {"2022": "ГЭСН-2022", "2020": "ФЕР-2020"}
TYPES = {"ГЭСН", "ГЭСНм", "ГЭСНмр", "ГЭСНп", "ГЭСНр",
"ФЕР", "ФЕРм", "ФЕРмр", "ФЕРп", "ФЕРр"}
def catalog() -> list[dict]:
"""List only norm families actually present in the deployed read-only index."""
con = fsnb_ref._connect()
if con is None:
return []
try:
rows = con.execute("SELECT base, base_type, COUNT(*) AS n FROM works "
"GROUP BY base, base_type ORDER BY base, base_type").fetchall()
return [{"base": row["base"], "base_type": row["base_type"], "count": row["n"]}
for row in rows if row["base"] in BASES.values()]
finally:
con.close()
def search(query: str, base: str, limit: int = 12) -> dict:
query = query.strip() if isinstance(query, str) else ""
if not 2 <= len(query) <= 160 or base not in BASES or not isinstance(limit, int) or not 1 <= limit <= 30:
raise ValueError("Укажите запрос 2–160 символов, доступную базу и число результатов до 30")
result = fsnb_ref.find_works(query=query, base=base, limit=limit)
if result.get("status") == "not_found" and not fsnb_ref._extract_code(query):
terms = [term for term in re.findall(r"[а-яa-z0-9]+", fsnb_ref.norm_text(query))
if len(term) >= 4 and not fsnb_ref._is_generic_term(term)]
counts = [(fsnb_ref.count_works(term), term) for term in terms]
usable = [(count, term) for count, term in counts if count > 0]
if usable:
anchor = min(usable)[1]
fallback = fsnb_ref.find_works(query=anchor, base=base, limit=max(60, limit * 5))
if fallback.get("status") == "ok":
def rank(row):
name = re.findall(r"[а-яa-z0-9]+", fsnb_ref.norm_text(str(row.get("name") or "")))
section = re.findall(r"[а-яa-z0-9]+", fsnb_ref.norm_text(str(row.get("section_path") or "")))
score = 0
for term in re.findall(r"[а-яa-z0-9]+", fsnb_ref.norm_text(query)):
if len(term) < 3:
continue
stem = fsnb_ref._stem(term)
root = stem[:4] if len(stem) >= 5 else stem[:3]
score += (3 if any(word.startswith(root) for word in name) else 0)
score += (2 if any(word.startswith(root) for word in section) else 0)
return score
rows = sorted(fallback.get("works") or [], key=rank, reverse=True)
result = {"status": "ok", "works": rows[:limit]}
if result.get("status") == "ok":
terms = [term for term in re.findall(r"[а-яa-z0-9]+", fsnb_ref.norm_text(query))
if len(term) >= 3 and not fsnb_ref._is_generic_term(term)]
items = []
for original in result.get("works") or []:
row = dict(original)
if query == row.get("code"):
row["match_reason"] = "Точный шифр"
row["match_score"] = 100
else:
words = re.findall(r"[а-яa-z0-9]+", fsnb_ref.norm_text(
str(row.get("name") or "") + " " + str(row.get("section_path") or "")))
matched = []
for term in terms:
stem = fsnb_ref._stem(term)
root = stem[:4] if len(stem) >= 5 else stem[:3]
if any(word.startswith(root) for word in words):
matched.append(term)
row["match_score"] = round(100 * len(matched) / len(terms)) if terms else 0
row["match_reason"] = ("Совпали слова: " + ", ".join(matched)
if matched else "Похожее название — проверьте состав")
items.append(row)
return {"status": "ok", "items": items,
"shown": len(items), "query": query, "base": BASES[base]}
return {"status": result.get("status") or "unavailable", "items": [],
"message": result.get("message") or "Поиск не выполнен", "query": query,
"base": BASES[base]}
def detail(base: str, base_type: str, code: str) -> dict:
if (base not in BASES or base_type not in TYPES or not isinstance(code, str)
or not fsnb_ref.WORK_CODE_RE.fullmatch(code) or len(code) > 24):
raise ValueError("Укажите существующий шифр, тип сборника и базу")
found = fsnb_ref.find_gesn_composition(query=code, base=base, limit=30)
rows = [row for row in found.get("results") or []
if row.get("base") == BASES[base] and row.get("base_type") == base_type
and row.get("code") == code]
if len(rows) != 1:
raise ValueError("Норма в выбранной базе не найдена однозначно")
work = dict(rows[0])
limitation = ""
if base != "2022" or not base_type.startswith("ГЭСН"):
limitation = "Для этой базы доступна базисная цена; текущие цены по зоне не рассчитываются"
else:
try:
_norm_from_work(work)
except ValueError as exc:
limitation = str(exc)
work["current_price_supported"] = not limitation
work["calculation_limitation"] = limitation
return work
def _norm_from_work(work: dict):
"""Build only compositions supported without guessing machine payroll or project consumption."""
import estimate_contract # noqa: F401 — registers the sibling smeta_railway package path
from smeta_railway.models import LaborResource, MaterialResource, NormResources
if not work.get("unit") or not work.get("resources"):
raise ValueError("Измеритель или ресурсный состав нормы отсутствует")
labor = None
materials = []
for row in work["resources"]:
code = str(row.get("code") or "")
quantity = row.get("quantity")
if (not isinstance(quantity, (int, float)) or isinstance(quantity, bool)
or not math.isfinite(quantity) or quantity < 0 or row.get("quantity_note")):
raise ValueError("Расход одного из ресурсов не задан числом")
if re.fullmatch(r"1-100-\d{2}", code):
if labor is not None:
raise ValueError("Оплата труда в норме не определяется однозначно")
labor = LaborResource(razryad=int(code[-2:]) / 10, chel_hours=quantity)
elif re.fullmatch(r"\d{2}\.\S+", code) and not code.startswith("91."):
materials.append(MaterialResource(code=code, name=row.get("name") or code,
unit=row.get("unit") or "", qty=quantity))
else:
raise ValueError("Расчёт этой нормы пока не поддерживается: машины, машинисты или неизвестный ресурс")
norm_code = work["base_type"] + " " + work["code"]
return NormResources(norm_code=norm_code, norm_name=work.get("name"),
unit=work["unit"], ozp=labor, materials=materials)
def calculate(base: str, base_type: str, code: str, quantity: float, unit: str,
zone: str, period: str) -> dict:
if (not isinstance(quantity, (int, float)) or isinstance(quantity, bool)
or not 0.000001 <= quantity <= 1_000_000 or not math.isfinite(quantity)
or not isinstance(unit, str) or not 1 <= len(unit) <= 60):
raise ValueError("Укажите положительный объём и его единицу измерения")
work = detail(base, base_type, code)
if base != "2022" or not base_type.startswith("ГЭСН"):
raise ValueError("Расчёт текущих цен для этой базы не поддерживается")
norm = _norm_from_work(work)
import engine_prices
import estimate_contract as ec
meta = {"region": zone, "zone": zone, "price_level": period}
basis = engine_prices.resolve(meta)
if basis.get("status") != "ok":
return {"status": "unavailable", "complete": False,
"message": basis.get("message") or "Ценовая форма недоступна"}
resource_key = ec._code_key(norm.norm_code)
resources = {resource_key: norm}
positions, refusal = ec._positions_in_measures(
[{"code": norm.norm_code, "name": work.get("name") or code,
"qty": quantity, "unit": unit}], resources)
if refusal:
raise ValueError(refusal.get("message") or "Единица объёма не совпадает с измерителем")
try:
prices = engine_prices.load_lookup(basis["entry"])
except (OSError, ValueError):
return {"status": "unavailable", "complete": False,
"message": "Форма цен зоны не читается"}
draft = ec.EstimateDraft(meta=ec.DraftMeta(**meta),
positions=[ec.DraftPosition(**position) for position in positions])
result = ec.build_and_calc(draft, resources, prices, basis)
amount = result.get("grand_total")
complete = (result.get("status") == "ok" and bool(result.get("ok"))
and not result.get("missing") and not result.get("unpriced")
and isinstance(amount, (int, float)) and math.isfinite(amount))
return {"status": result.get("status"), "complete": complete,
"total": amount if complete else None,
"accounted": amount if result.get("status") == "ok" and not complete and isinstance(amount, (int, float))
and math.isfinite(amount) and amount > 0 else None,
"missing": result.get("missing") or [], "unpriced": result.get("unpriced") or [],
"message": result.get("message") or "", "limits_note": ec.LIMITS_NOTE,
"base": work["base"], "base_type": base_type, "code": code,
"name": work.get("name"), "quantity": quantity, "unit": unit,
"zone": zone, "period": period}
+15
View File
@@ -62,6 +62,21 @@ prod_ext=${prod_ext:-$prod_data/_external}
stage_ext=${stage_ext:-$stage_data/_external} stage_ext=${stage_ext:-$stage_data/_external}
test "${prod_ext#/}" != "$prod_ext" && test "${stage_ext#/}" != "$stage_ext" test "${prod_ext#/}" != "$prod_ext" && test "${stage_ext#/}" != "$stage_ext"
test "$(readlink -f "$prod_ext")" != "$(readlink -f "$stage_ext")" test "$(readlink -f "$prod_ext")" != "$(readlink -f "$stage_ext")"
# Инлайн-выбор ценовой зоны и /podbor читают собранные формы из derived.
# Без их изолированной копии dev показывает зоны в ответе ИИ, но на каждое
# нажатие отвечает «нет в каталоге». Синхронизируем только производные цены,
# не личные файлы и не исходные письма ФГИС. rsync повторно копирует лишь дельту.
price_src="$prod_ext/derived/engine_prices"
price_dst="$stage_ext/derived/engine_prices"
test ! -L "$price_src" && test ! -L "$price_dst"
test "$(readlink -f "$price_src")" != "$(readlink -f "$price_dst")"
"$python_bin" "$stage/scripts/shadow/verify_engine_prices.py" "$price_src"
mkdir -p "$price_dst"
price_catalog_sha=$(sha256sum "$price_src/catalog.json" | cut -d' ' -f1)
rsync -a --delete "$price_src/" "$price_dst/"
test "$price_catalog_sha" = "$(sha256sum "$price_src/catalog.json" | cut -d' ' -f1)"
test "$price_catalog_sha" = "$(sha256sum "$price_dst/catalog.json" | cut -d' ' -f1)"
"$python_bin" "$stage/scripts/shadow/verify_engine_prices.py" "$price_dst"
"$python_bin" -c 'import sys, public_documents; public_documents.export_summary(sys.argv[1], sys.argv[2])' \ "$python_bin" -c 'import sys, public_documents; public_documents.export_summary(sys.argv[1], sys.argv[2])' \
"$prod_ext" "$stage_ext/landing_documents.json" "$prod_ext" "$stage_ext/landing_documents.json"
export SMETA_PROJECT_DIR="$stage-norms" export SMETA_PROJECT_DIR="$stage-norms"
+57
View File
@@ -0,0 +1,57 @@
"""Check that an isolated price snapshot can serve every listed zone and period."""
from __future__ import annotations
import json
from pathlib import Path
import sys
def validate(root: Path) -> int:
root = Path(root)
if root.is_symlink() or not root.is_dir():
raise ValueError("Каталог ценовых форм отсутствует или является ссылкой")
base = root.resolve()
catalog = root / "catalog.json"
if catalog.is_symlink() or not catalog.is_file():
raise ValueError("Каталог ценовых зон не найден")
try:
zones = json.loads(catalog.read_text(encoding="utf-8"))["zones"]
except (OSError, ValueError, KeyError, TypeError) as exc:
raise ValueError("Каталог ценовых зон не читается") from exc
if not isinstance(zones, list) or not zones:
raise ValueError("Каталог ценовых зон пуст")
seen = set()
for entry in zones:
if not isinstance(entry, dict):
raise ValueError("Некорректная запись ценовой зоны")
ids = tuple(entry.get(key) for key in ("subject_id", "zone_id", "period_id"))
if any(not isinstance(value, int) or isinstance(value, bool) or value < 1 for value in ids):
raise ValueError("Некорректный код ценовой зоны или квартала")
if ids in seen:
raise ValueError("Повтор ценовой зоны и квартала")
seen.add(ids)
if not all(isinstance(entry.get(key), str) and entry[key].strip()
for key in ("zone_name", "period_label")):
raise ValueError("Нет названия зоны или квартала")
name = entry.get("file")
if not isinstance(name, str) or not name:
raise ValueError("Нет файла ценовой формы")
relative = Path(name)
if (relative.is_absolute() or ".." in relative.parts or relative.suffix != ".json"
or len(relative.parts) != 3):
raise ValueError("Путь ценовой формы вне снимка")
path = root / relative
if path.is_symlink() or base not in path.resolve().parents:
raise ValueError("Путь ценовой формы вне снимка")
if not path.is_file() or path.stat().st_size == 0:
raise ValueError(f"Ценовая форма не найдена: {name}")
return len(zones)
if __name__ == "__main__":
try:
count = validate(Path(sys.argv[1]))
except (IndexError, ValueError) as error:
raise SystemExit(str(error)) from error
print(f"Ценовых форм в изолированном снимке: {count}")
+14 -33
View File
@@ -1,4 +1,18 @@
[ [
{
"version": "2026-12-02e",
"date": "2026-12-02",
"changes": [
"Ценовую зону в обычном ответе можно выбрать прямо в тексте; после выбора квартала ответ пересчитывается и заменяется в том же сообщении"
]
},
{
"version": "2026-12-02d",
"date": "2026-12-02",
"changes": [
"В готовой смете можно выбрать другую доступную ценовую зону или квартал прямо в ответе: итог пересчитывается и сохраняется в этом же диалоге"
]
},
{ {
"version": "2026-12-02c", "version": "2026-12-02c",
"date": "2026-12-02", "date": "2026-12-02",
@@ -20,38 +34,5 @@
"changes": [ "changes": [
"Обычные файлы можно загружать до 30 МБ; общий предел обычных файлов в диалоге тоже 30 МБ" "Обычные файлы можно загружать до 30 МБ; общий предел обычных файлов в диалоге тоже 30 МБ"
] ]
},
{
"version": "2026-11-25b",
"date": "2026-11-25",
"changes": [
"Вопрос с отрицанием региона («для Москвы, не Московской области») получает расценку названного региона, а не отрицательного; слова вроде «областной» рядом с «районом» больше не выглядят регионом; «для Татарстана» и «для Дагестана» снова распознаются",
"Починка сопоставления региона в вопросе: «в Республике Татарстан» больше не подкладывает факт о другой республике, «в Северной Осетии» находит регион по второму слову имени, вопрос с кодом без региона не получает чужого факта",
"Отрицание в вопросе учитывается и через общие слова названия региона («для Москвы, не в Республике Татарстан»); слова «народный», «автономный», «республиканский» без названия региона рядом больше не принимаются за регион («северного народного хора», «республиканского суда»)",
"Отрицание региона распознаётся и после знака препинания, и с предлогами: «в Рязанской области (не Московской области)», «не из Московской области, а из Рязанской области», «вопрос не о Московской области, а о Рязанской» — помощник получает расценку названного региона, а не отрицательного",
"Слова «северный», «северная» и «республиканец» без названия региона больше не принимаются за регион: «по северному краю участка», «в северном округе», «приморского республиканца» раньше подкладывали расценку Северной Осетии или Приморского края",
"Регион узнаётся и в падежных формах имени: «под Москвой», «на границе с Татарстаном», «рядом со Севастополем», «рядом с Петербургом», «в Адыгее» — раньше регион в них не узнавался",
"Вопрос «не ТЕР, а ТЕРм» или «не 01-01-001-01, а 01-01-001-02» доставляет помощнику названный вид расценок и названный код, а не отвергнутые",
"Отказ от кода или вида учитывается и после них, и до них с глаголом: «01-01-001-01 не использовать, нужен 01-01-001-02», «не применять 01-01-001-01, брать 01-01-001-02», «ТЕР не нужен, нужна ТЕРм», «нельзя ТЕР, можно ТЕРм» — помощник получает названный код и вид, а не отвергнутые; вопрос («не подходит ли ТЕР?») отказом не считается",
"Отрицание региона узнаётся в новых формах: «не на территории Московской области», «не про Московскую область», «не через Московскую область» — помощник получает расценку названного региона, а не отвергнутого; «не областного значения Московской области» больше не скрывает названную область",
"Более длинный номер в вопросе больше не превращается в код расценки: «02-01-01-001-01», «01-01-001-01-02», «01-01-001-01.5» раньше давали цену кода 01-01-001-01; слова через дефис («ханты-мансийский банк», «на москве-реке») больше не принимаются за регион",
"Отказ от кода или вида расценок узнаётся во всех формах известных глаголов отказа: «01-01-001-01 не применяются», «не использованы», «не берите», «не возьмите», «не считаются»; вопрос («не применяются ли 01-…») отказом не считается; «не от Московской области, а от Рязанской» и «не к Московской области» узнаются как отказ от Московской области",
"Если в вопросе вид отвергнут и другой не назван («ТЕР не нужен»), помощник не получает цену отвергнутого вида",
"Нарицательные «областного» и «республиканского» в составных оборотах («автономного областного совета», «народного республиканского суда») больше не узнаются как регион",
"В Ямало-Ненецком автономном округе помощник больше не подставляет цену Ненецкого округа; формы «Красноярским краём» и «Ненецким округом» распознаются",
"Упоминание жителя («квартира осетина», «квартира бурята») больше не принимается за название региона",
"Поздний отказ от уже названного кода или вида расценок убирает отвергнутую цену; распознаются формы «не берут» и «не взяли»",
"Код после обозначения вида («ТЕР-01-01-001-01») распознаётся как расценка и не теряется",
"Фраза «ТЕР не требуется, нужна ТЕРм» больше не подставляет цену отвергнутого ТЕР",
"Нумерованная строка «1.ТЕР-01-01-001-01» сохраняет код расценки; фрагмент чужого числа «2.01-01-001-01» по-прежнему не принимается за код"
]
},
{
"version": "2026-11-25a",
"date": "2026-11-25",
"changes": [
"Вопрос с кодом расценки региона (например, 31-01-014-02): помощник подкладывает себе факт из региональной базы с пометкой о провенансе — федеральную расценку вместо региональной не подставляет",
"У помощника новый инструмент «regional_rate»: расценка или цена из региональной базы (ТЕР/ТССЦ) с указанием региона, редакции и акта"
]
} }
] ]
+549 -12
View File
@@ -356,6 +356,31 @@ button { font-family: inherit; }
.est-tot-row .num { font-variant-numeric: tabular-nums; } .est-tot-row .num { font-variant-numeric: tabular-nums; }
.est-tot-strong { font-weight: 700; color: var(--text); font-size: .95rem; } .est-tot-strong { font-weight: 700; color: var(--text); font-size: .95rem; }
.est-basis { padding: .35rem .9rem; font-size: .78rem; color: var(--text-muted); border-bottom: 1px solid var(--border); overflow-wrap: anywhere; } .est-basis { padding: .35rem .9rem; font-size: .78rem; color: var(--text-muted); border-bottom: 1px solid var(--border); overflow-wrap: anywhere; }
.msg-ai.has-estimate { width: 100%; max-width: 100%; }
.msg-ai .est-panel { width: 100%; box-sizing: border-box; }
.file-compare-controls { display: flex; flex-wrap: wrap; gap: .6rem; padding: .7rem .9rem; }
.file-compare-controls label { display: grid; gap: .25rem; min-width: min(100%, 220px); font-size: .8rem; }
.file-compare-controls select, .file-compare-panel select { max-width: 100%; padding: .35rem; border: 1px solid var(--border); border-radius: 6px; background: var(--bg-card); color: var(--text); }
.file-compare-status { padding: .4rem .9rem; color: var(--text-muted); font-size: .82rem; }
.file-compare-status[role="alert"] { color: var(--error, #ad3434); }
.file-compare-pages { display: flex; gap: .5rem; align-items: center; padding: .5rem .9rem; }
.file-compare-panel .est-scroll { overflow-x: auto; }
.file-compare-panel .est-table { min-width: 850px; table-layout: auto; }
.file-compare-panel .est-table th, .file-compare-panel .est-table td { min-width: 80px; word-break: normal; overflow-wrap: normal; }
.file-compare-panel .est-table th:nth-child(2), .file-compare-panel .est-table td:nth-child(2) { min-width: 150px; }
.est-basis-picker { display: inline-flex; gap: .35rem; align-items: center; flex-wrap: wrap; }
.est-basis-picker button, .est-basis-picker select { max-width: 100%; font: inherit; color: var(--text); background: var(--bg-card); border: 1px solid var(--border); border-radius: 6px; padding: .25rem .4rem; cursor: pointer; }
.est-basis-picker button:hover, .est-basis-picker select:focus-visible { border-color: var(--accent); }
.est-basis-error { color: var(--danger); display: block; margin-top: .3rem; }
.inline-basis-trigger { border: 0; border-bottom: 1px dotted currentColor; padding: 0; background: transparent; color: var(--accent); font: inherit; cursor: pointer; }
.inline-basis-trigger:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
.inline-basis-picker { display: inline-flex; flex-wrap: wrap; align-items: center; gap: .35rem; padding: .2rem; border: 1px solid var(--border); border-radius: 6px; background: var(--bg-card); max-width: 100%; }
.inline-basis-picker select, .inline-basis-picker button, .inline-basis-picker input { max-width: 100%; min-width: 0; padding: .2rem .35rem; font: inherit; color: var(--text); background: var(--bg-card); border: 1px solid var(--border); border-radius: 5px; }
.inline-basis-note { flex-basis: 100%; font-size: .78rem; color: var(--text-muted); }
.inline-basis-picker .inline-norm-select { max-width: min(28rem, 100%); }
.inline-basis-picker .inline-quantity { width: 6rem; }
.inline-basis-picker .inline-basis-apply { color: var(--accent); cursor: pointer; }
.inline-basis-picker .est-basis-error { flex-basis: 100%; }
.est-input { color: var(--text-muted); font-size: .85em; } .est-input { color: var(--text-muted); font-size: .85em; }
.est-warn { padding: .5rem .9rem; border-top: 1px solid var(--border); background: var(--error-bg); color: var(--error-text, var(--text)); font-size: .8rem; display: flex; flex-direction: column; gap: .25rem; } .est-warn { padding: .5rem .9rem; border-top: 1px solid var(--border); background: var(--error-bg); color: var(--error-text, var(--text)); font-size: .8rem; display: flex; flex-direction: column; gap: .25rem; }
.ka-sub { padding: .3rem .9rem; font-size: .72rem; color: var(--text-muted); font-family: monospace; border-bottom: 1px solid var(--border-light, var(--border)); word-break: break-all; } .ka-sub { padding: .3rem .9rem; font-size: .72rem; color: var(--text-muted); font-family: monospace; border-bottom: 1px solid var(--border-light, var(--border)); word-break: break-all; }
@@ -499,6 +524,38 @@ button { font-family: inherit; }
.msg { max-width: 92%; } .msg { max-width: 92%; }
.onboarding { margin: 1.2rem auto; padding: 1rem; } .onboarding { margin: 1.2rem auto; padding: 1rem; }
} }
@media (max-width: 600px) {
.msg-ai.has-estimate .est-table, .msg-ai.has-estimate .est-table tbody,
.msg-ai.has-estimate .est-table tr { display: block; width: 100%; }
.msg-ai.has-estimate .est-table .est-header-row { display: none; }
.msg-ai.has-estimate .est-table tr { padding: .45rem; border-bottom: 1px solid var(--border); }
.msg-ai.has-estimate .est-table td {
display: grid; grid-template-columns: minmax(7.3rem, 42%) minmax(0, 1fr);
gap: .35rem; width: 100%; max-width: none; box-sizing: border-box;
border: 0; padding: .2rem .35rem; white-space: normal; overflow-wrap: anywhere;
}
.msg-ai.has-estimate .est-table td::before {
content: attr(data-label); color: var(--text-muted); font-weight: 600;
}
.msg-ai.has-estimate .est-table td.num { text-align: left; white-space: normal; }
.msg-ai.has-estimate .est-table td input { min-width: 0; max-width: 100%; box-sizing: border-box; }
.msg-ai.has-estimate .est-actions {
display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: .4rem;
}
.msg-ai.has-estimate .est-actions .est-dl {
width: 100%; min-height: 2.5rem; word-break: normal; overflow-wrap: normal;
}
/* Сверка файлов остаётся таблицей с горизонтальной прокруткой. Карточная
раскладка сметы выше растягивает её строки и ломает селекторы. */
.msg-ai.has-estimate .file-compare-panel .est-table { display: table; width: 100%; }
.msg-ai.has-estimate .file-compare-panel .est-table tbody { display: table-row-group; width: auto; }
.msg-ai.has-estimate .file-compare-panel .est-table tr { display: table-row; width: auto; padding: 0; }
.msg-ai.has-estimate .file-compare-panel .est-table td {
display: table-cell; width: auto; max-width: 360px; border: 1px solid var(--border-light);
padding: .35rem .55rem; white-space: normal; overflow-wrap: normal;
}
.msg-ai.has-estimate .file-compare-panel .est-table td::before { content: none; }
}
/* Меряем колонку переписки, а не окно: при открытой панели диалогов колонка узкая и на /* Меряем колонку переписки, а не окно: при открытой панели диалогов колонка узкая и на
широком экране. От названия в узкой колонке остаётся «Сметн…» — место нужнее дате сметы широком экране. От названия в узкой колонке остаётся «Сметн…» — место нужнее дате сметы
и остатку. Подписи значков прячем, сами дата и сумма остаются: иначе многоточие съедало и остатку. Подписи значков прячем, сами дата и сумма остаются: иначе многоточие съедало
@@ -769,6 +826,7 @@ html { color-scheme: light; }
<div class="account-menu-email" id="account-menu-email"></div> <div class="account-menu-email" id="account-menu-email"></div>
<button type="button" role="menuitem" onclick="closeAccountMenu(); location.href='/stats'">Статистика</button> <button type="button" role="menuitem" onclick="closeAccountMenu(); location.href='/stats'">Статистика</button>
<button type="button" role="menuitem" onclick="closeAccountMenu(); listFiles()">Файлы</button> <button type="button" role="menuitem" onclick="closeAccountMenu(); listFiles()">Файлы</button>
<button type="button" role="menuitem" onclick="closeAccountMenu(); location.href='/podbor'">Подбор норм</button>
<button type="button" role="menuitem" id="btn-invite" aria-expanded="false" aria-controls="invite-panel" <button type="button" role="menuitem" id="btn-invite" aria-expanded="false" aria-controls="invite-panel"
onclick="closeAccountMenu(); toggleInvitePanel()">Пригласить коллегу</button> onclick="closeAccountMenu(); toggleInvitePanel()">Пригласить коллегу</button>
<button type="button" role="menuitem" id="btn-device" <button type="button" role="menuitem" id="btn-device"
@@ -2175,6 +2233,189 @@ function addMsg(type, text, ts) {
scrollIfPinned(); scrollIfPinned();
return div; return div;
} }
// Структурированная смета приходит после done. Отделяем текст ответа от кнопок,
// стоимости и панели, чтобы пересчёт заменял содержимое ЭТОГО пузыря.
function estimateAnswerBody(host) {
let body = host.querySelector(':scope > .ai-body');
if (body) return body;
body = document.createElement('div'); body.className = 'ai-body';
for (const child of Array.from(host.childNodes)) {
if (child.nodeType === 1 && child.matches('.msg-time, .copy-btn, .msg-cost, .est-panel, .fb-form')) continue;
body.appendChild(child);
}
const time = host.querySelector(':scope > .msg-time');
if (time) time.after(body); else host.prepend(body);
return body;
}
function replaceEstimateAnswer(host, text) {
const body = estimateAnswerBody(host);
body.innerHTML = renderMarkdown(text);
host._rawText = text;
enhanceTables(body); typografAI(body); externalizeLinks(body);
}
// В обычном ответе названия ценовых зон остаются частью текста. Нажатие открывает
// допустимые формы, а пересчёт заменяет этот же ответ, без нового пузыря.
function bindFreeformBasis(host) {
if (!host || !host._messageId || viewOwner || host.classList.contains('has-estimate')) return;
const raw = host._rawText || '';
if (!/\d{2}-\d{2}-\d{3}-\d{2}/.test(raw)
|| !/\d+(?:[.,]\d+)?\s+(?:(?:[а-яё-]+\s+){0,3})?(?:извещател[а-яё]*|шт\.?|штук)(?=$|[^а-яё])/i.test(raw)) return;
const body = estimateAnswerBody(host);
const pattern = /[А-ЯЁ][А-ЯЁа-яё-]*(?:\s+[А-ЯЁа-яё-]+){0,5}\s*\(\d+\s+зона\)/g;
const walker = document.createTreeWalker(body, NodeFilter.SHOW_TEXT);
const nodes = [];
while (walker.nextNode()) {
const node = walker.currentNode;
if (node.parentElement && !node.parentElement.closest('button, a, select, .inline-basis-picker')
&& pattern.test(node.textContent)) nodes.push(node);
pattern.lastIndex = 0;
}
nodes.forEach(node => {
const fragment = document.createDocumentFragment();
let start = 0;
for (const match of node.textContent.matchAll(pattern)) {
fragment.append(document.createTextNode(node.textContent.slice(start, match.index)));
const button = document.createElement('button');
button.type = 'button'; button.className = 'inline-basis-trigger';
button.textContent = match[0];
button.title = 'Выбрать ценовую зону и квартал для этого ответа';
button.onclick = () => openFreeformBasis(button, host, match[0]);
fragment.append(button);
start = match.index + match[0].length;
}
fragment.append(document.createTextNode(node.textContent.slice(start)));
node.replaceWith(fragment);
});
const firstZone = raw.match(pattern);
if (!firstZone) return;
const wrapChoice = (regex, title) => {
const textWalker = document.createTreeWalker(body, NodeFilter.SHOW_TEXT);
const matches = [];
while (textWalker.nextNode()) {
const node = textWalker.currentNode;
if (node.parentElement && !node.parentElement.closest('button, a, select, .inline-basis-picker')
&& regex.test(node.textContent)) matches.push(node);
regex.lastIndex = 0;
}
matches.forEach(node => {
const fragment = document.createDocumentFragment();
let start = 0;
for (const match of node.textContent.matchAll(regex)) {
fragment.append(document.createTextNode(node.textContent.slice(start, match.index)));
const trigger = document.createElement('button');
trigger.type = 'button'; trigger.className = 'inline-basis-trigger';
trigger.textContent = match[0]; trigger.title = title;
trigger.onclick = () => openFreeformBasis(trigger, host, firstZone[0]);
fragment.append(trigger);
start = match.index + match[0].length;
}
fragment.append(document.createTextNode(node.textContent.slice(start)));
node.replaceWith(fragment);
});
};
wrapChoice(/\b\d{2}-\d{2}-\d{3}-\d{2}\b/g, 'Выбрать норму для этого расчёта');
wrapChoice(/Объ[её]м(?:\s+работ)?\s*[=:—-]\s*\d+(?:[.,]\d+)?\s*шт\.?/gi,
'Изменить объём для этого расчёта');
}
async function openFreeformBasis(button, host, label) {
if (!host._messageId || viewOwner) return;
const requestTab = tabId;
button.disabled = true;
try {
const url = API + '/api/messages/' + host._messageId + '/basis';
const r = await authFetch(url + '?label=' + encodeURIComponent(label));
if (!r.ok) throw new Error(await reasonOrText(r));
const options = await r.json();
if (requestTab !== tabId || !button.isConnected) return;
const zones = options.zones || [];
const picker = document.createElement('span'); picker.className = 'inline-basis-picker';
const zoneSelect = document.createElement('select'); zoneSelect.setAttribute('aria-label', 'Ценовая зона');
zones.forEach(z => { const o = document.createElement('option'); o.value = String(z.zone_id);
o.textContent = z.name; zoneSelect.appendChild(o); });
const currentZone = zones.find(z => z.name === label);
if (currentZone) zoneSelect.value = String(currentZone.zone_id);
const periodSelect = document.createElement('select'); periodSelect.setAttribute('aria-label', 'Квартал цен');
const periodNote = document.createElement('span'); periodNote.className = 'inline-basis-note';
periodNote.textContent = 'Квартал из ответа не загружен. Выберите доступный квартал для нового расчёта.';
const quarterMention = (host._rawText || '').match(/\b(IV|III|II|I|[1-4])\s*квартал[а-яё]*\s+(20\d{2})/i);
const roman = {I:1, II:2, III:3, IV:4};
const mentionedPeriod = quarterMention
? String(roman[quarterMention[1].toUpperCase()] || Number(quarterMention[1])) + ' квартал ' + quarterMention[2]
: '';
const fillPeriods = () => {
periodSelect.replaceChildren();
const placeholder = document.createElement('option'); placeholder.value = '';
placeholder.textContent = 'Выберите квартал'; periodSelect.appendChild(placeholder);
const zone = zones.find(z => String(z.zone_id) === zoneSelect.value);
(zone ? zone.periods : []).forEach(p => { const o = document.createElement('option');
o.value = String(p.period_id); o.textContent = p.name; periodSelect.appendChild(o); });
const named = (zone ? zone.periods : []).find(p => p.name === mentionedPeriod)
|| (zone ? zone.periods : []).find(p => (host._rawText || '').includes(p.name));
if (named) periodSelect.value = String(named.period_id);
periodNote.hidden = !quarterMention || !!named;
};
fillPeriods(); zoneSelect.onchange = fillPeriods;
const normRows = options.norms || [];
const position = options.position;
const normSelect = document.createElement('select');
normSelect.className = 'inline-norm-select';
normSelect.setAttribute('aria-label', 'Норма');
normRows.forEach(n => { const o = document.createElement('option'); o.value = n.code;
o.textContent = n.code + ' — ' + n.name; normSelect.appendChild(o); });
if (position) normSelect.value = position.code;
const quantity = document.createElement('input');
quantity.className = 'inline-quantity'; quantity.type = 'number';
quantity.min = '0.000001'; quantity.max = '1000000'; quantity.step = 'any';
quantity.setAttribute('aria-label', 'Объём, шт.');
if (position) quantity.value = String(position.quantity);
const apply = document.createElement('button'); apply.type = 'button';
apply.className = 'inline-basis-apply'; apply.textContent = 'Пересчитать';
const cancel = document.createElement('button'); cancel.type = 'button'; cancel.textContent = 'Отмена';
cancel.onclick = () => picker.replaceWith(button);
apply.onclick = async () => {
if (!periodSelect.value) { periodSelect.focus(); return; }
if (normRows.length && (!quantity.value || !quantity.checkValidity()
|| !Number.isFinite(Number(quantity.value)) || Number(quantity.value) <= 0)) {
quantity.focus(); return;
}
picker.querySelectorAll('button, select, input').forEach(el => { el.disabled = true; });
apply.textContent = 'Пересчитываю…';
try {
const response = await authFetch(url, {method: 'POST', headers: {'Content-Type':'application/json'},
body: JSON.stringify({label, zone_id:Number(zoneSelect.value),
period_id:Number(periodSelect.value), revision:options.revision,
...(normRows.length ? {norm_code:normSelect.value, quantity:Number(quantity.value)} : {})})});
if (!response.ok) throw new Error(await reasonOrText(response));
const updated = await response.json();
if (requestTab !== tabId || !picker.isConnected) return;
replaceEstimateAnswer(host, updated.answer);
bindFreeformBasis(host);
if (updated.spend) attachCost(host, updated.spend);
if (updated.balance) renderBalance(updated.balance);
srAnnounce('Ответ пересчитан в текущем сообщении');
} catch (e) {
if (!picker.isConnected) return;
const err = document.createElement('span'); err.className = 'est-basis-error';
err.setAttribute('role', 'alert'); err.textContent = e.message || 'Не удалось пересчитать';
picker.appendChild(err);
picker.querySelectorAll('button, select, input').forEach(el => { el.disabled = false; });
apply.textContent = 'Пересчитать';
}
};
if (normRows.length) picker.append(normSelect, quantity);
picker.append(zoneSelect, periodSelect, apply, cancel, periodNote);
button.replaceWith(picker); zoneSelect.focus();
} catch (e) {
button.disabled = false;
const err = document.createElement('span'); err.className = 'est-basis-error';
err.setAttribute('role', 'alert'); err.textContent = e.message || 'Нет доступных цен';
button.after(err);
}
}
function addTyping() { function addTyping() {
const div = document.createElement('div'); const div = document.createElement('div');
div.className = 'typing'; div.className = 'typing';
@@ -3009,12 +3250,16 @@ async function runChat(text, retried, готовыйПоток, внешнийCt
// Цена ответа и остаток — без перезагрузки страницы. // Цена ответа и остаток — без перезагрузки страницы.
if (aiDiv && data.answer) attachCost(aiDiv, data.answer); if (aiDiv && data.answer) attachCost(aiDiv, data.answer);
if (data.balance) renderBalance(data.balance); if (data.balance) renderBalance(data.balance);
} else if (eventType === 'assistant_id') {
if (aiDiv && data.id) { aiDiv._messageId = data.id; bindFreeformBasis(aiDiv); }
} else if (eventType === 'files') { } else if (eventType === 'files') {
// Агент подготовил файлы — кнопки скачивания прямо в чате // Агент подготовил файлы — кнопки скачивания прямо в чате
if (data.files && data.files.length) addFilesMsg(data.files); if (data.files && data.files.length) addFilesMsg(data.files);
} else if (eventType === 'estimate') { } else if (eventType === 'estimate') {
// Структурированная смета — панель с таблицей (срез 6.1, JS НЕ считает) // Смета живёт в том же ответе, который её породил.
if (data && data.positions) addEstimatePanel(data); if (data && data.positions) addEstimatePanel(data, null, aiDiv);
} else if (eventType === 'file_compare') {
if (data && data._message_id && aiDiv) addFileComparePanel(data, aiDiv);
} else if (eventType === 'ka_form') { } else if (eventType === 'ka_form') {
// Конъюнктурный анализ — панель офферов (срез 7) // Конъюнктурный анализ — панель офферов (срез 7)
if (data && data.rows) addKaPanel(data); if (data && data.rows) addKaPanel(data);
@@ -3058,7 +3303,7 @@ function fmtMoney(v) {
if (typeof v !== 'number' || !isFinite(v)) return v == null ? '' : String(v); if (typeof v !== 'number' || !isFinite(v)) return v == null ? '' : String(v);
return v.toLocaleString('ru-RU', {minimumFractionDigits: 2, maximumFractionDigits: 2}); return v.toLocaleString('ru-RU', {minimumFractionDigits: 2, maximumFractionDigits: 2});
} }
function addEstimatePanel(data, prevData) { function addEstimatePanel(data, prevData, host) {
const panel = document.createElement('div'); const panel = document.createElement('div');
panel.className = 'est-panel'; panel.className = 'est-panel';
panel.setAttribute('role', 'region'); panel.setAttribute('role', 'region');
@@ -3076,12 +3321,93 @@ function addEstimatePanel(data, prevData) {
// По какой форме посчитано: зона места стройки и уровень цен — подпись итога не должна // По какой форме посчитано: зона места стройки и уровень цен — подпись итога не должна
// приписать числа чужому региону (инцидент 01.08.2026). // приписать числа чужому региону (инцидент 01.08.2026).
const ap = data.applied; const ap = data.applied;
async function applyLinked(zoneId, periodId, positions) {
if (!data._message_id || !host) return;
const requestTab = tabId;
panel.querySelectorAll('button, select, input').forEach(el => { el.disabled = true; });
let error = panel.querySelector('.est-basis-error');
if (error) error.remove();
try {
const r = await authFetch('/api/estimates/' + data._message_id + '/basis', {
method: 'POST', headers: {'Content-Type': 'application/json'},
body: JSON.stringify({zone_id: zoneId, period_id: periodId,
revision: data._revision || 0, positions})});
if (!r.ok) throw new Error(await reasonOrText(r));
const updated = await r.json();
if (requestTab !== tabId || !panel.isConnected) return;
replaceEstimateAnswer(host, updated.answer);
addEstimatePanel(updated.estimate, data, host);
panel.remove();
srAnnounce('Смета пересчитана в текущем ответе');
} catch (e) {
if (!panel.isConnected) return;
error = document.createElement('span'); error.className = 'est-basis-error';
error.setAttribute('role', 'alert');
error.textContent = e.message || 'Не удалось пересчитать';
(panel.querySelector('.est-basis') || panel.querySelector('.est-head')).appendChild(error);
panel.querySelectorAll('button, select, input').forEach(el => { el.disabled = false; });
}
}
if (ap && ap.zone) { if (ap && ap.zone) {
const basis = document.createElement('div'); const basis = document.createElement('div');
basis.className = 'est-basis'; basis.className = 'est-basis';
basis.textContent = 'Цены: ' + ap.zone + ', ' + (ap.period || '') if (data._message_id && data._assistant_id && host && !viewOwner && ap.subject_id != null) {
+ (ap.period_default ? ' (последний доступный период)' : '') const picker = document.createElement('span'); picker.className = 'est-basis-picker';
+ (ap.letter ? ' · ' + ap.letter : ''); const open = document.createElement('button'); open.type = 'button';
open.textContent = 'Цены: ' + ap.zone + ', ' + (ap.period || '') + ' ▾';
open.setAttribute('aria-label', 'Изменить ценовую зону или квартал');
open.onclick = async () => {
open.disabled = true; open.textContent = 'Загружаю доступные цены…';
try {
const r = await authFetch('/api/estimates/' + data._message_id + '/basis');
if (!r.ok) throw new Error(await reasonOrText(r));
const options = await r.json();
if (!panel.isConnected) return;
const zones = options.zones || [];
const zoneSelect = document.createElement('select');
zoneSelect.setAttribute('aria-label', 'Ценовая зона');
zones.forEach(z => { const o = document.createElement('option');
o.value = String(z.zone_id); o.textContent = z.name; zoneSelect.appendChild(o); });
zoneSelect.value = String(ap.zone_id);
const periodSelect = document.createElement('select');
periodSelect.setAttribute('aria-label', 'Квартал цен');
const fillPeriods = () => {
periodSelect.replaceChildren();
const selected = zones.find(z => String(z.zone_id) === zoneSelect.value);
const periods = selected ? selected.periods : [];
periods.forEach(p => { const o = document.createElement('option');
o.value = String(p.period_id); o.textContent = p.name; periodSelect.appendChild(o); });
if ([...periodSelect.options].some(o => o.value === String(ap.period_id)))
periodSelect.value = String(ap.period_id);
else if (periods.length) periodSelect.value = String(periods[periods.length - 1].period_id);
};
fillPeriods();
const submit = () => {
if (Number(zoneSelect.value) === ap.zone_id && Number(periodSelect.value) === ap.period_id) return;
const inputs = Array.from(panel.querySelectorAll('.est-qty'));
const positions = inputs.map(inp => ({code: inp.dataset.code, unit: inp.dataset.unit || '',
qty: parseFloat(inp.value)}));
applyLinked(Number(zoneSelect.value), Number(periodSelect.value), positions);
};
zoneSelect.onchange = () => { fillPeriods(); submit(); };
periodSelect.onchange = submit;
picker.replaceChildren(zoneSelect, periodSelect);
zoneSelect.focus();
} catch (e) {
open.disabled = false; open.textContent = 'Цены: ' + ap.zone + ', ' + (ap.period || '') + ' ▾';
const err = document.createElement('span'); err.className = 'est-basis-error';
err.setAttribute('role', 'alert'); err.textContent = e.message || 'Нет связи';
basis.appendChild(err);
}
};
picker.appendChild(open); basis.appendChild(picker);
if (ap.letter) { const letter = document.createElement('span');
letter.textContent = ' · ' + ap.letter; basis.appendChild(letter); }
} else {
basis.textContent = 'Цены: ' + ap.zone + ', ' + (ap.period || '')
+ (ap.period_default ? ' (последний доступный период)' : '')
+ (ap.letter ? ' · ' + ap.letter : '');
}
panel.appendChild(basis); panel.appendChild(basis);
} }
@@ -3090,6 +3416,7 @@ function addEstimatePanel(data, prevData) {
const table = document.createElement('table'); const table = document.createElement('table');
table.className = 'est-table'; table.className = 'est-table';
const thead = document.createElement('tr'); const thead = document.createElement('tr');
thead.className = 'est-header-row';
['№', 'Код', 'Наименование', 'Ед.', 'Кол-во', 'Цена/ед', 'Стоимость'].forEach(h => { ['№', 'Код', 'Наименование', 'Ед.', 'Кол-во', 'Цена/ед', 'Стоимость'].forEach(h => {
const th = document.createElement('th'); th.textContent = h; thead.appendChild(th); const th = document.createElement('th'); th.textContent = h; thead.appendChild(th);
}); });
@@ -3097,10 +3424,15 @@ function addEstimatePanel(data, prevData) {
const editable = !!(data.positions || []).some(p => p.code); // движок сможет пересчитать const editable = !!(data.positions || []).some(p => p.code); // движок сможет пересчитать
(data.positions || []).forEach((p, i) => { (data.positions || []).forEach((p, i) => {
const tr = document.createElement('tr'); const tr = document.createElement('tr');
// Движок отдаёт стоимость позиции и объём, но не всегда отдельную цену за единицу.
const unitPrice = typeof p.unit_cost === 'number' ? p.unit_cost
: typeof p.total === 'number' && typeof p.qty === 'number' && p.qty > 0
? p.total / p.qty : null;
const cells = [i + 1, p.code || '', p.name || '', p.unit || '', const cells = [i + 1, p.code || '', p.name || '', p.unit || '',
p.qty != null ? p.qty : '', fmtMoney(p.unit_cost), fmtMoney(p.total)]; p.qty != null ? p.qty : '', fmtMoney(unitPrice), fmtMoney(p.total)];
cells.forEach((c, ci) => { cells.forEach((c, ci) => {
const td = document.createElement('td'); const td = document.createElement('td');
td.dataset.label = ['№', 'Код', 'Наименование', 'Ед.', 'Кол-во', 'Цена/ед', 'Стоимость'][ci];
if (ci === 4 && editable && p.code) { if (ci === 4 && editable && p.code) {
// объём — редактируемый; правка пересчитывается ДВИЖКОМ (не JS) // объём — редактируемый; правка пересчитывается ДВИЖКОМ (не JS)
const inp = document.createElement('input'); const inp = document.createElement('input');
@@ -3196,6 +3528,10 @@ function addEstimatePanel(data, prevData) {
return; return;
} }
if (!positions.length) return; if (!positions.length) return;
if (data._message_id && host && ap && ap.zone_id != null && ap.period_id != null) {
await applyLinked(ap.zone_id, ap.period_id, positions);
return;
}
rc.disabled = true; rc.textContent = '↻ Считаю...'; rc.disabled = true; rc.textContent = '↻ Считаю...';
try { try {
const r = await authFetch('/api/recalc', {method: 'POST', const r = await authFetch('/api/recalc', {method: 'POST',
@@ -3221,7 +3557,14 @@ function addEstimatePanel(data, prevData) {
if (prevData) { if (prevData) {
const un = document.createElement('button'); const un = document.createElement('button');
un.className = 'est-dl'; un.type = 'button'; un.textContent = '↩ Отменить пересчёт'; un.className = 'est-dl'; un.type = 'button'; un.textContent = '↩ Отменить пересчёт';
un.onclick = () => { const back = addEstimatePanel(prevData); panel.replaceWith(back); }; un.onclick = () => {
if (data._message_id && host && prevData.applied) {
applyLinked(prevData.applied.zone_id, prevData.applied.period_id,
(prevData.positions || []).map(p => ({code: p.code, unit: p.unit || '', qty: p.qty})));
} else {
const back = addEstimatePanel(prevData); panel.replaceWith(back);
}
};
acts.appendChild(un); acts.appendChild(un);
} }
// Утвердить смету (срез 6.4): человек фиксирует смету — блокируем правки, метка // Утвердить смету (срез 6.4): человек фиксирует смету — блокируем правки, метка
@@ -3230,6 +3573,8 @@ function addEstimatePanel(data, prevData) {
appr.onclick = () => { appr.onclick = () => {
panel.classList.add('est-approved'); panel.classList.add('est-approved');
panel.querySelectorAll('.est-qty').forEach(i => { i.readOnly = true; i.tabIndex = -1; }); panel.querySelectorAll('.est-qty').forEach(i => { i.readOnly = true; i.tabIndex = -1; });
panel.querySelectorAll('.est-basis-picker button, .est-basis-picker select')
.forEach(el => { el.disabled = true; });
acts.querySelectorAll('button').forEach(b => { if (b !== dl) b.disabled = true; }); acts.querySelectorAll('button').forEach(b => { if (b !== dl) b.disabled = true; });
const badge = document.createElement('span'); const badge = document.createElement('span');
badge.className = 'est-badge'; badge.textContent = '✓ Утверждено'; badge.className = 'est-badge'; badge.textContent = '✓ Утверждено';
@@ -3240,11 +3585,184 @@ function addEstimatePanel(data, prevData) {
panel.appendChild(acts); panel.appendChild(acts);
const ob = document.getElementById('onboarding'); if (ob) ob.remove(); const ob = document.getElementById('onboarding'); if (ob) ob.remove();
msgs.appendChild(panel); if (host) {
host.querySelectorAll('.inline-basis-trigger').forEach(button => {
button.replaceWith(document.createTextNode(button.textContent));
});
estimateAnswerBody(host);
host.classList.add('has-estimate');
host.appendChild(panel);
} else msgs.appendChild(panel);
scrollIfPinned(); scrollIfPinned();
return panel; return panel;
} }
// --- Сверка собственных файлов внутри того же ответа ---
function addFileComparePanel(initial, host) {
if (!host) return;
const panel = document.createElement('section');
panel.className = 'est-panel file-compare-panel';
panel.setAttribute('role', 'region');
panel.setAttribute('aria-label', 'Сверка файлов');
host.classList.add('has-estimate');
host.appendChild(panel);
let state = initial, workbooks = [], page = 0;
let pending = Promise.resolve();
const modeNames = {ka_lsr: 'КА ↔ ЛСР: цены', vor_lsr: 'ВОР ↔ ЛСР: объёмы', ka_kp: 'КА ↔ КП: цены'};
const sideNames = {ka_lsr: ['Конъюнктурный анализ', 'Локальная смета'],
vor_lsr: ['Ведомость объёмов', 'Локальная смета'],
ka_kp: ['Конъюнктурный анализ', 'Коммерческое предложение']};
const id = initial._message_id;
const endpoint = '/api/file-compare/' + encodeURIComponent(id);
const node = (tag, cls, value) => {
const el = document.createElement(tag);
if (cls) el.className = cls;
if (value != null) el.textContent = String(value);
return el;
};
async function load(nextPage=0) {
const r = await authFetch(endpoint + '?page=' + nextPage);
const data = await r.json().catch(() => ({}));
if (!r.ok) throw new Error(data.detail || 'Не удалось прочитать сверку');
state = data; page = nextPage;
render();
}
function update(change) {
// Быстрые изменения двух селекторов идут последовательно: каждый POST
// получает ревизию после предыдущего, иначе второй законно вернёт 409.
const operation = pending.catch(() => {}).then(async () => {
const r = await authFetch(endpoint, {method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({revision: state._revision, ...change})});
const data = await r.json().catch(() => ({}));
if (!r.ok) throw new Error(data.detail || 'Не удалось пересчитать сверку');
state = data; page = 0;
render();
});
pending = operation;
return operation;
}
function showError(message) {
let status = panel.querySelector('.file-compare-status');
if (!status) { status = node('div', 'file-compare-status'); panel.appendChild(status); }
status.setAttribute('role', 'alert');
status.textContent = message;
}
function fileChoice(side, title, controls) {
const label = node('label', '', title);
const file = node('select');
file.setAttribute('aria-label', title + ': файл');
file.add(new Option('Выберите файл', ''));
workbooks.forEach(w => file.add(new Option(w.filename, w.filename)));
file.value = state[side]?.file || '';
const sheet = node('select');
sheet.setAttribute('aria-label', title + ': лист');
function sheets(selected) {
sheet.replaceChildren();
const selectedBook = workbooks.find(w => w.filename === file.value);
(selectedBook?.sheets || []).forEach(name => sheet.add(new Option(name, name)));
sheet.value = selected || selectedBook?.sheets?.[0] || '';
}
sheets(state[side]?.sheet);
async function apply() {
if (!file.value || !sheet.value) return;
try { await update({[side]: {file: file.value, sheet: sheet.value}}); }
catch (e) { showError(e.message); }
}
file.onchange = () => { sheets(); apply(); };
sheet.onchange = apply;
if (viewOwner) { file.disabled = true; sheet.disabled = true; }
label.append(file, sheet); controls.appendChild(label);
}
function render() {
if (!panel.isConnected) return;
panel.replaceChildren(node('div', 'est-head', modeNames[state.mode] || 'Сверка файлов'));
const controls = node('div', 'file-compare-controls');
const titles = sideNames[state.mode] || ['Первый файл', 'Второй файл'];
fileChoice('left', titles[0], controls);
fileChoice('right', titles[1], controls);
panel.appendChild(controls);
const comparison = state.comparison;
if (!workbooks.length) {
panel.appendChild(node('div', 'file-compare-status', 'Загрузите книги xlsx в этот диалог.'));
return;
}
if (!comparison) {
panel.appendChild(node('div', 'file-compare-status', 'Выберите исходные файлы и листы для сверки.'));
return;
}
panel.appendChild(node('div', 'file-compare-status',
`Строк: ${comparison.total_rows}; требуют проверки: ${comparison.unmatched}; ` +
`только во втором файле: ${comparison.unmatched_right || 0}. ` +
(comparison.complete ? 'Сверка завершена.' : 'Сверка неполная; проверьте строки и исходные файлы.')));
panel.appendChild(node('div', 'file-compare-status', 'Таблицу можно прокручивать по горизонтали.'));
const scroll = node('div', 'est-scroll');
const table = node('table', 'est-table');
const header = node('tr');
['Источник', 'Код / наименование', 'Ед.', 'Значение', 'Соответствие', 'Разница'].forEach(text =>
header.appendChild(node('th', '', text)));
table.appendChild(header);
(comparison.rows || []).forEach(row => {
const tr = node('tr', row.warning ? 'est-unresolved' : '');
const left = row.left;
tr.appendChild(node('td', '', `${left.file} · ${left.sheet} · строка ${left.row}`));
tr.appendChild(node('td', '', [left.code, left.name].filter(Boolean).join(' · ')));
tr.appendChild(node('td', '', left.unit));
const valueCell = node('td');
if (state.mode !== 'vor_lsr' && comparison.left.fields?.length) {
const price = node('select');
const names = {price_no_vat: 'Без НДС', price_with_vat: 'С НДС'};
comparison.left.fields.filter(f => names[f]).forEach(f =>
price.add(new Option(`${names[f]}: ${left.values[f] ?? '—'}`, f)));
price.value = row.left_field;
price.disabled = !!viewOwner;
price.onchange = async () => {
const fields = {...state.price_fields, [row.index]: price.value};
try { await update({price_fields: fields}); } catch (e) { showError(e.message); }
};
valueCell.appendChild(price);
} else valueCell.textContent = left.values[row.left_field] ?? '—';
tr.appendChild(valueCell);
const matchCell = node('td');
const match = node('select');
match.setAttribute('aria-label', `Соответствие для строки ${left.row}`);
match.add(new Option('Нет подтверждённого совпадения', '-1'));
(row.candidates || []).forEach(c => match.add(new Option(
`${c.file} · ${c.sheet} · ${c.row}: ${c.code} ${c.name} (${c.unit})`, String(c.index))));
match.value = row.match_index == null ? '-1' : String(row.match_index);
match.disabled = !!viewOwner;
match.onchange = async () => {
const choices = {...state.choices, [row.index]: Number(match.value)};
try { await update({choices}); } catch (e) { showError(e.message); }
};
matchCell.appendChild(match);
if (row.right) matchCell.appendChild(node('small', '',
` ${row.right.file} · ${row.right.sheet} · строка ${row.right.row}; ${row.right.values[row.right_field] ?? '—'}`));
tr.appendChild(matchCell);
tr.appendChild(node('td', '', row.difference ?? row.warning ?? '—'));
table.appendChild(tr);
});
scroll.appendChild(table); panel.appendChild(scroll);
const pages = node('div', 'file-compare-pages');
const prev = node('button', '', 'Назад'), next = node('button', '', 'Далее');
prev.disabled = page === 0; next.disabled = (page + 1) * 50 >= comparison.total_rows;
prev.onclick = () => load(page - 1).catch(e => showError(e.message));
next.onclick = () => load(page + 1).catch(e => showError(e.message));
pages.append(prev, node('span', '', `Страница ${page + 1}`), next);
panel.appendChild(pages);
}
(async () => {
try {
const r = await authFetch('/api/file-compare/workbooks');
const data = await r.json().catch(() => ({}));
if (!r.ok) throw new Error(data.detail || 'Не удалось получить список файлов');
workbooks = data.workbooks || [];
await load();
} catch (e) { showError(e.message); }
})();
return panel;
}
// --- Панель конъюнктурного анализа (срез 7): офферы таблицей + принятая цена --- // --- Панель конъюнктурного анализа (срез 7): офферы таблицей + принятая цена ---
function addKaPanel(form) { function addKaPanel(form) {
const panel = document.createElement('div'); const panel = document.createElement('div');
@@ -3491,18 +4009,37 @@ async function loadHistory() {
if (history.length === 0) { showOnboarding(); updateQuickActions(); return; } if (history.length === 0) { showOnboarding(); updateQuickActions(); return; }
msgs.innerHTML = ''; msgs.innerHTML = '';
let lastAi = null; let lastAi = null;
const aiById = new Map();
for (const m of history) { for (const m of history) {
if (m.role === 'user') addMsg('user', m.content, m.timestamp); if (m.role === 'user') addMsg('user', m.content, m.timestamp);
else if (m.role === 'assistant') lastAi = addMsg('ai', m.content, m.timestamp); else if (m.role === 'assistant') {
lastAi = addMsg('ai', m.content, m.timestamp);
lastAi._messageId = m.id;
aiById.set(m.id, lastAi);
bindFreeformBasis(lastAi);
}
else if (m.role === 'spend') { else if (m.role === 'spend') {
try { attachCost(lastAi, JSON.parse(m.content)); } catch {} try { const cost = JSON.parse(m.content);
attachCost(cost._assistant_id ? aiById.get(cost._assistant_id) : lastAi, cost); } catch {}
} }
else if (m.role === 'system') addMsg('system', m.content, m.timestamp); else if (m.role === 'system') addMsg('system', m.content, m.timestamp);
else if (m.role === 'files') { else if (m.role === 'files') {
try { addFilesMsg(JSON.parse(m.content), m.timestamp); } catch {} try { addFilesMsg(JSON.parse(m.content), m.timestamp); } catch {}
} }
else if (m.role === 'estimate') { else if (m.role === 'estimate') {
try { addEstimatePanel(JSON.parse(m.content)); } catch {} try {
const estimate = JSON.parse(m.content);
const host = !estimate._assistant_id || lastAi && lastAi._messageId === estimate._assistant_id
? lastAi : null;
addEstimatePanel({...estimate, _message_id: m.id}, null, host);
} catch {}
}
else if (m.role === 'file_compare') {
try {
const data = JSON.parse(m.content);
const host = aiById.get(data._assistant_id);
if (host) addFileComparePanel({...data, _message_id: m.id}, host);
} catch {}
} }
else if (m.role === 'ka_form') { else if (m.role === 'ka_form') {
try { addKaPanel(JSON.parse(m.content)); } catch {} try { addKaPanel(JSON.parse(m.content)); } catch {}
+105
View File
@@ -0,0 +1,105 @@
<!doctype html>
<html lang="ru">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Подбор норм — Инфосмета</title>
<style>
:root { color-scheme: light; --bg:#f4f2ee; --card:#fff; --text:#272824; --muted:#626760;
--line:#d8d9d2; --accent:#176c63; --bad:#a83c31; --warn:#fff5da; }
* { box-sizing:border-box; }
body { margin:0; background:var(--bg); color:var(--text); font:16px/1.48 system-ui,-apple-system,Arial,sans-serif; }
button,input,select { font:inherit; }
button { cursor:pointer; }
:focus-visible { outline:3px solid #65aba4; outline-offset:2px; }
a { color:var(--accent); }
.wrap { max-width:1240px; margin:auto; padding:24px clamp(16px,3vw,40px) 64px; }
header { display:flex; align-items:center; justify-content:space-between; gap:16px; margin-bottom:32px; }
.brand { font-weight:750; font-size:1.15rem; text-decoration:none; color:var(--text); }
h1 { font-size:clamp(2rem,4vw,3rem); line-height:1.1; margin:0 0 12px; }
h2 { font-size:1.35rem; margin:0 0 12px; }
h3 { font-size:1.05rem; margin:0 0 8px; }
p { margin:0 0 12px; }
.intro { max-width:760px; color:var(--muted); margin-bottom:22px; }
.panel,.card { background:var(--card); border:1px solid var(--line); border-radius:14px; padding:20px; }
.search-row,.controls,.actions { display:flex; gap:10px; align-items:end; flex-wrap:wrap; }
label { display:grid; gap:5px; font-size:.84rem; color:var(--muted); font-weight:600; }
input,select { min-height:42px; padding:8px 11px; color:var(--text); background:var(--card);
border:1px solid var(--line); border-radius:8px; max-width:100%; }
#query { flex:1 1 330px; }
.search-row label:has(#query) { flex:1 1 330px; }
.primary,.secondary { min-height:42px; padding:8px 16px; border-radius:8px; font-weight:650; }
.primary { background:var(--accent); border:1px solid var(--accent); color:#fff; }
.secondary { background:var(--card); border:1px solid var(--line); color:var(--text); }
.small { min-height:34px; padding:5px 10px; font-size:.84rem; }
.examples { display:flex; gap:8px; flex-wrap:wrap; align-items:center; margin-top:14px; color:var(--muted); font-size:.85rem; }
.examples button { border:0; border-bottom:1px dotted var(--accent); background:transparent; color:var(--accent); padding:0; }
.status { min-height:24px; margin:14px 0; color:var(--muted); }
.status.error { color:var(--bad); }
.results { display:grid; grid-template-columns:repeat(auto-fit,minmax(min(100%,340px),1fr)); gap:14px; }
.card { display:flex; flex-direction:column; gap:7px; }
.card-head { display:flex; align-items:start; justify-content:space-between; gap:12px; }
.code { color:var(--accent); font-weight:750; font-variant-numeric:tabular-nums; }
.badge { background:#e9f4f1; color:#155f56; padding:3px 8px; border-radius:999px; font-size:.72rem; white-space:nowrap; }
.meta,.hint { font-size:.82rem; color:var(--muted); }
.card .actions { margin-top:auto; padding-top:7px; }
.section { margin-top:28px; }
.detail-grid { display:grid; grid-template-columns:minmax(0,1.4fr) minmax(270px,.8fr); gap:18px; }
.list { margin:0; padding-left:20px; }
.scroll { max-width:100%; overflow:auto; }
table { border-collapse:collapse; width:100%; font-size:.86rem; }
th,td { border-bottom:1px solid var(--line); text-align:left; padding:8px; vertical-align:top; }
th { color:var(--muted); font-weight:650; }
.num { text-align:right; font-variant-numeric:tabular-nums; white-space:nowrap; }
.comparison { display:grid; grid-template-columns:repeat(3,minmax(0,1fr)); gap:12px; }
.comparison .card { overflow-wrap:anywhere; }
.notice { background:var(--warn); border-radius:9px; padding:10px 12px; font-size:.86rem; }
.result-amount { font-size:1.5rem; font-weight:750; font-variant-numeric:tabular-nums; }
.quote-controls label { min-width:140px; }
.quote-controls #qty { width:125px; }
[hidden] { display:none !important; }
@media (max-width:760px) { .wrap { padding:18px 14px 40px; } header { margin-bottom:24px; }
.detail-grid,.comparison { grid-template-columns:1fr; } .panel,.card { padding:15px; }
.search-row > *, .controls > label { flex:1 1 100%; } .search-row button { width:100%; }
.quote-controls label { min-width:0; } }
</style>
</head>
<body>
<main class="wrap">
<header><a class="brand" href="/">ИНФОСМЕТА</a><a href="/">Вернуться в чат</a></header>
<h1>Подбор норм</h1>
<p class="intro">Найдите работу по названию или шифру, проверьте состав и измеритель, сравните варианты. Цены считаются только по доступной форме выбранной зоны и квартала.</p>
<div id="auth-notice" class="notice" hidden>Чтобы искать нормы, <a href="/">войдите в Инфосмету</a>.</div>
<form id="search-form" class="panel">
<div class="search-row">
<label for="query">Работа или шифр<input id="query" type="search" maxlength="160" placeholder="Например, монтаж пожарного извещателя" required></label>
<label for="base">Нормативная база<select id="base" aria-label="Нормативная база"></select></label>
<button class="primary" type="submit">Найти нормы</button>
</div>
<div class="examples">Примеры: <button type="button" data-query="монтаж извещателя">монтаж извещателя</button>
<button type="button" data-query="устройство стяжки пола">устройство стяжки пола</button>
<button type="button" data-query="10-08-002-02">10-08-002-02</button></div>
</form>
<div id="status" class="status" role="status" aria-live="polite"></div>
<section id="results-section" class="section" hidden><h2>Подходящие нормы</h2><div id="results" class="results"></div></section>
<section id="detail-section" class="section" hidden><div class="detail-grid">
<div class="panel"><h2 id="detail-title">Состав нормы</h2><div id="detail"></div></div>
<div class="panel"><h2>Предварительный расчёт</h2><p class="hint">Объём вводится в выбранной единице. Недостающие цены и затраты будут отмечены.</p>
<div class="controls quote-controls">
<label for="subject">Регион<select id="subject"></select></label>
<label for="zone">Ценовая зона<select id="zone"></select></label>
<label for="period">Квартал<select id="period"></select></label>
<label for="qty">Объём<input id="qty" type="number" min="0.000001" max="1000000" step="any" value="1"></label>
<label for="unit">Единица<select id="unit"></select></label>
</div>
<div class="actions" style="margin-top:16px"><button id="calc" type="button" class="primary">Рассчитать</button>
<button id="to-chat" type="button" class="secondary">Перенести в чат</button></div>
<div id="quote" style="margin-top:16px" aria-live="polite"></div>
</div>
</div></section>
<section id="compare-section" class="section" hidden><h2>Сравнение норм</h2><p id="compare-warning" class="notice" hidden></p>
<div id="comparison" class="comparison"></div></section>
</main>
<script src="/static/norm-finder.js" defer></script>
</body>
</html>
+285
View File
@@ -0,0 +1,285 @@
(() => {
'use strict';
const $ = id => document.getElementById(id);
const token = (() => { try { return localStorage.getItem('token') || ''; } catch { return ''; } })();
const subject = (() => {
try { return JSON.parse(atob(token.split('.')[1].replace(/-/g, '+').replace(/_/g, '/'))).sub || ''; }
catch { return ''; }
})();
const tabKey = 'tabId:' + subject;
const tabId = (() => {
try {
let id = localStorage.getItem(tabKey);
if (!id) { id = crypto.randomUUID(); localStorage.setItem(tabKey, id); }
return id;
} catch { return crypto.randomUUID(); }
})();
let active = null;
let savedQuote = null;
let subjects = [];
let priceZones = [];
const compared = new Map();
const money = n => new Intl.NumberFormat('ru-RU', {minimumFractionDigits:2, maximumFractionDigits:2}).format(n) + ' ₽';
function node(tag, value, className) {
const el = document.createElement(tag);
if (value != null) el.textContent = String(value);
if (className) el.className = className;
return el;
}
function status(message, error=false) {
$('status').textContent = message;
$('status').classList.toggle('error', error);
}
async function api(path, options={}) {
const response = await fetch(path, { ...options, headers: {
Authorization: 'Bearer ' + token, 'X-Tab-Id': tabId,
...(options.body ? {'Content-Type':'application/json'} : {}), ...(options.headers || {})
}});
const data = await response.json().catch(() => ({}));
if (!response.ok) throw new Error(typeof data.detail === 'string' ? data.detail : 'Запрос не выполнен');
return data;
}
function fillSelect(select, rows, valueKey, nameKey, placeholder) {
select.replaceChildren();
select.append(node('option', placeholder));
select.options[0].value = '';
for (const row of rows) {
const option = node('option', row[nameKey]);
option.value = String(row[valueKey]); select.append(option);
}
}
function selectedZone() { return priceZones.find(z => String(z.zone_id) === $('zone').value); }
function setUnits(normUnit) {
const unit = String(normUnit || '').trim();
const match = unit.match(/^(\d+)\s*(.+)$/);
const units = match && Number(match[1]) > 1 ? [match[2], unit] : [unit];
fillSelect($('unit'), units.filter(Boolean).map(value => ({value, name:value})),
'value', 'name', 'Выберите единицу');
if (units[0]) $('unit').value = units[0];
}
function fillPeriods() {
fillSelect($('period'), selectedZone()?.periods || [], 'period_id', 'name', 'Выберите квартал');
if ($('period').options.length === 2) $('period').selectedIndex = 1;
}
async function loadPrices() {
priceZones = [];
fillSelect($('zone'), [], 'zone_id', 'name', 'Выберите зону'); fillPeriods();
if (!$('subject').value) return;
const data = await api('/api/norm-finder/prices?subject_id=' + encodeURIComponent($('subject').value));
priceZones = data.zones || [];
fillSelect($('zone'), priceZones, 'zone_id', 'name', 'Выберите зону');
if (priceZones.length === 1) { $('zone').selectedIndex = 1; fillPeriods(); }
}
function key(item) { return [item.base, item.base_type, item.code].join('|'); }
function baseAlias(item) { return item.base === 'ФЕР-2020' ? '2020' : '2022'; }
function detailUrl(item) {
return '/api/norm-finder/detail?' + new URLSearchParams({base:baseAlias(item),
base_type:item.base_type, code:item.code});
}
async function detailFor(item) { return api(detailUrl(item)); }
function renderSearchItem(item) {
const card = node('article', null, 'card');
const head = node('div', null, 'card-head');
head.append(node('span', item.code, 'code'), node('span', item.base_type, 'badge'));
card.append(head, node('h3', item.name || 'Без наименования'),
node('p', (item.base || '') + ' · измеритель: ' + (item.unit || 'не указан'), 'meta'));
if (item.section_path) card.append(node('p', item.section_path, 'hint'));
if (item.match_reason) card.append(node('p', item.match_reason, 'hint'));
if (item.provenance?.decree) card.append(node('p', 'Источник: ' + item.provenance.decree, 'hint'));
const actions = node('div', null, 'actions');
const open = node('button', 'Открыть состав', 'primary small');
open.type = 'button'; open.addEventListener('click', () => openDetail(item));
const compare = node('button', compared.has(key(item)) ? 'Убрать из сравнения' : 'Сравнить', 'secondary small');
compare.type = 'button';
compare.addEventListener('click', async () => {
try {
if (compared.has(key(item))) compared.delete(key(item));
else {
if (compared.size >= 3) { status('Сравнить можно не более трёх норм', true); return; }
compared.set(key(item), await detailFor(item));
}
compare.textContent = compared.has(key(item)) ? 'Убрать из сравнения' : 'Сравнить';
renderComparison();
} catch (e) { status(e.message, true); }
});
actions.append(open, compare); card.append(actions);
return card;
}
async function search(event) {
event?.preventDefault();
const q = $('query').value.trim(), base = $('base').value;
if (q.length < 2) { status('Введите хотя бы два символа', true); return; }
status('Ищу нормы…');
$('results-section').hidden = true; $('detail-section').hidden = true;
try {
const data = await api('/api/norm-finder/search?' + new URLSearchParams({q,base,limit:'12'}));
const items = data.items || [];
$('results').replaceChildren(...items.map(renderSearchItem));
$('results-section').hidden = !items.length;
status(items.length ? 'Показано ' + items.length + ' подходящих норм. Проверьте состав работ перед расчётом.'
: (data.message || 'Нормы не найдены. Уточните работу или шифр.'));
} catch (e) { status(e.message, true); }
}
function renderDetail(item) {
$('detail-title').textContent = item.code + ' — ' + (item.name || 'Норма');
const root = $('detail'); root.replaceChildren();
root.append(node('p', item.base + ' · ' + item.base_type + ' · измеритель: ' + (item.unit || '—'), 'meta'));
if (item.section_path) root.append(node('p', item.section_path, 'hint'));
if (item.content?.length) {
root.append(node('h3', 'Состав работ'));
const list = node('ol', null, 'list');
for (const line of item.content) list.append(node('li', line));
root.append(list);
}
root.append(node('h3', 'Ресурсы'));
const scroll = node('div', null, 'scroll');
const table = node('table');
const thead = node('thead'); const tr = node('tr');
for (const label of ['Код','Ресурс','Единица','Расход на измеритель']) tr.append(node('th', label));
thead.append(tr); table.append(thead);
const tbody = node('tbody');
for (const r of item.resources || []) {
const row = node('tr');
row.append(node('td', r.code || '—'), node('td', r.name || '—'), node('td', r.unit || '—'),
node('td', r.quantity_note || (r.quantity ?? 'не задан'), 'num'));
tbody.append(row);
}
table.append(tbody); scroll.append(table); root.append(scroll);
const provenance = item.provenance || {};
const source = [provenance.decree, provenance.file].filter(Boolean).join(' · ');
root.append(node('p', source ? 'Источник: ' + source : 'Источник в индексе не указан', 'hint'));
if (item.prices?.cost != null) root.append(node('p', 'Базисная стоимость: ' + money(item.prices.cost) +
' (уровень ' + (item.price_level || 'не указан') + '). Это не цена выбранного квартала.', 'notice'));
}
async function openDetail(item) {
status('Загружаю состав нормы…');
try {
active = await detailFor(item); savedQuote = null;
$('quote').replaceChildren(); renderDetail(active);
setUnits(active.unit);
$('calc').disabled = !active.current_price_supported;
if (active.calculation_limitation) $('quote').append(node('p', active.calculation_limitation, 'notice'));
$('detail-section').hidden = false;
$('detail-section').scrollIntoView({behavior:'smooth', block:'start'});
status('Состав нормы загружен. Сверьте измеритель и ресурсы.');
} catch (e) { status(e.message, true); }
}
function renderComparison() {
$('compare-section').hidden = compared.size === 0;
const items = [...compared.values()];
const units = new Set(items.map(i => i.unit || ''));
$('compare-warning').hidden = units.size < 2;
$('compare-warning').textContent = 'Измерители различаются. Сравнение стоимости без явного приведения объёма некорректно.';
const cards = items.map(item => {
const card = node('article', null, 'card');
card.append(node('div', item.code, 'code'), node('h3', item.name),
node('p', item.base + ' · ' + item.base_type + ' · ' + (item.unit || 'без измерителя'), 'meta'));
if (item.content?.length) card.append(node('p', 'Состав: ' + item.content.join('; '), 'hint'));
card.append(node('p', 'Ресурсов: ' + (item.resources || []).length, 'hint'));
for (const row of item.resources || []) card.append(node('p', (row.code || '—') + ' · ' +
(row.name || '—') + ' · ' + (row.quantity_note || (row.quantity ?? '—')), 'hint'));
return card;
});
$('comparison').replaceChildren(...cards);
}
function renderQuote(data) {
savedQuote = data;
const result = data.result || {};
const root = $('quote'); root.replaceChildren();
root.append(node('p', [result.code, result.quantity != null ? result.quantity + ' ' + (result.unit || '') : '',
result.zone, result.period].filter(Boolean).join(' · '), 'meta'));
if (result.complete && result.total != null) {
root.append(node('p', 'Предварительный итог', 'meta'), node('div', money(result.total), 'result-amount'));
} else {
root.append(node('p', 'Расчёт неполный — готовую смету по этим данным получить нельзя.', 'notice'));
if (result.accounted != null) root.append(node('p', 'Учтённая часть', 'meta'),
node('div', money(result.accounted), 'result-amount'));
}
if (result.message) root.append(node('p', result.message, 'notice'));
for (const missing of result.missing || []) root.append(node('p', 'Не рассчитано: ' +
(missing.reason || missing.code || 'позиция'), 'hint'));
if (result.unpriced?.length) root.append(node('p', 'Часть ресурсов без цены в выбранной форме.', 'hint'));
if (result.limits_note) root.append(node('p', result.limits_note, 'hint'));
const link = node('a', 'Ссылка на этот расчёт');
link.href = '/podbor?quote=' + encodeURIComponent(data.id);
root.append(link);
}
async function calculate() {
if (!active) return;
const quantity = Number($('qty').value);
if (!Number.isFinite(quantity) || quantity <= 0 || !$('qty').checkValidity()
|| !$('subject').value || !$('zone').value || !$('period').value) {
status('Укажите регион, зону, квартал и положительный объём', true); return;
}
const selection = {base:baseAlias(active),base_type:active.base_type,code:active.code,
quantity,unit:$('unit').value,subject_id:Number($('subject').value),
zone_id:Number($('zone').value),period_id:Number($('period').value)};
$('calc').disabled = true; status('Считаю по выбранной форме…');
try {
const path = savedQuote ? '/api/norm-finder/quotes/' + savedQuote.id : '/api/norm-finder/calculate';
const body = {...selection, ...(savedQuote ? {revision:savedQuote.revision} : {})};
const data = await api(path, {method:'POST', body:JSON.stringify(body)});
renderQuote(data);
history.replaceState(null, '', '/podbor?quote=' + encodeURIComponent(data.id));
status('Расчёт обновлён в этой карточке.');
} catch (e) { status(e.message, true); }
finally { $('calc').disabled = false; }
}
function toChat() {
if (!active) return;
const prompt = 'Посчитай ' + ($('qty').value || '1') + ' ' + ($('unit').value || active.unit || '') +
' по норме ' + active.base_type + ' ' + active.code +
(selectedZone() && $('period').value ? ', ' + selectedZone().name + ', ' +
$('period').selectedOptions[0].textContent : '') + '. Проверь состав ресурсов.';
try { localStorage.setItem('draft_' + tabId, prompt); }
catch { status('Не удалось сохранить черновик для чата', true); return; }
location.href = '/';
}
async function restoreQuote() {
const id = Number(new URLSearchParams(location.search).get('quote'));
if (!Number.isSafeInteger(id) || id < 1) return;
try {
const data = await api('/api/norm-finder/quotes/' + id);
const selection = data.selection || {};
active = await detailFor({base:selection.base === '2020' ? 'ФЕР-2020' : 'ГЭСН-2022',
base_type:selection.base_type, code:selection.code});
renderDetail(active); $('detail-section').hidden = false;
$('calc').disabled = !active.current_price_supported;
$('qty').value = String(selection.quantity); setUnits(active.unit); $('unit').value = selection.unit;
$('subject').value = String(selection.subject_id);
await loadPrices(); $('zone').value = String(selection.zone_id); fillPeriods();
$('period').value = String(selection.period_id); renderQuote(data);
status('Сохранённый расчёт загружен.');
} catch (e) { status(e.message, true); }
}
async function init() {
if (!token || !subject) { $('auth-notice').hidden = false; $('search-form').hidden = true; return; }
try {
const data = await api('/api/norm-finder/catalog');
const bases = [...new Set((data.bases || []).map(x => x.base))];
fillSelect($('base'), bases.map(b => ({id:b === 'ФЕР-2020' ? '2020' : '2022',name:b})),
'id', 'name', 'Выберите базу');
if (bases.length) $('base').selectedIndex = 1;
subjects = data.subjects || [];
fillSelect($('subject'), subjects, 'id', 'name', 'Выберите регион');
if (!bases.length) status('Нормативная база пока недоступна', true);
await restoreQuote();
} catch (e) { status(e.message, true); }
}
$('search-form').addEventListener('submit', search);
document.querySelectorAll('[data-query]').forEach(button => button.addEventListener('click', () => {
$('query').value = button.dataset.query; $('search-form').requestSubmit();
}));
$('subject').addEventListener('change', () => loadPrices().catch(e => status(e.message, true)));
$('zone').addEventListener('change', fillPeriods);
for (const id of ['subject', 'zone', 'period', 'qty', 'unit']) {
$(id).addEventListener('change', () => {
if (savedQuote) status('Параметры изменены. Нажмите «Рассчитать», чтобы обновить сумму.');
});
}
$('calc').addEventListener('click', calculate);
$('to-chat').addEventListener('click', toChat);
init();
})();
+1
View File
@@ -98,6 +98,7 @@ def test_generic_words_not_required(works_db):
assert w["base_type"] == "ГЭСНм" assert w["base_type"] == "ГЭСНм"
assert w["unit"] == "шт" assert w["unit"] == "шт"
assert w["price_level"] == "01.01.2022" assert w["price_level"] == "01.01.2022"
assert w["provenance"]["decree"] == "приказ (тест)"
def test_all_generic_is_empty(works_db): def test_all_generic_is_empty(works_db):
+150
View File
@@ -0,0 +1,150 @@
"""Deterministic, source-linked comparison of uploaded estimate spreadsheets."""
from decimal import Decimal
import importlib
import json
import openpyxl
import pytest
from fastapi.testclient import TestClient
def workbook(path, headers, rows):
wb = openpyxl.Workbook()
ws = wb.active
ws.title = "Данные"
ws.append(["Объект: синтетический"])
ws.append(headers)
for row in rows:
ws.append(row)
wb.save(path)
wb.close()
def test_ka_lsr_rows_keep_source_and_price_fields(tmp_path):
import inline_compare as ic
workbook(tmp_path / "КА.xlsx",
["Код строительного ресурса", "Наименование", "Ед. изм.",
"Текущая отпускная цена с НДС", "Сметная цена без НДС"],
[["01.1.01.01-0002", "Материал А", "шт.", "120,00", "100,00"]])
workbook(tmp_path / "ЛСР.xlsx",
["Код ресурса", "Наименование ресурса", "Ед. изм.",
"Сметная стоимость на единицу измерения в текущем уровне цен", "Количество"],
[["01.1.01.01-0002", "Материал А", "шт.", "105,00", 3]])
ka = ic.read_table(tmp_path, "КА.xlsx", "Данные", "ka")
lsr = ic.read_table(tmp_path, "ЛСР.xlsx", "Данные", "lsr")
assert ka["rows"][0]["row"] == 3
assert ka["rows"][0]["values"] == {"price_with_vat": "120.00", "price_no_vat": "100.00"}
assert lsr["rows"][0]["values"]["unit_price"] == "105.00"
assert ka["fingerprint"] and lsr["fingerprint"]
compared = ic.compare(ka, lsr, "ka_lsr")
assert compared["rows"][0]["match_index"] == 0
assert compared["rows"][0]["difference"] == "5.00"
assert compared["rows"][0]["left_field"] == "price_no_vat"
def test_fuzzy_candidate_is_not_accepted_and_unit_mismatch_blocks_delta(tmp_path):
import inline_compare as ic
workbook(tmp_path / "КА.xlsx",
["Код ресурса", "Наименование", "Ед. изм.", "Сметная цена без НДС"],
[["01.1.01.01-0002", "Дверка поддувальная", "шт", 100]])
workbook(tmp_path / "ЛСР.xlsx",
["Код ресурса", "Наименование", "Ед. изм.", "Сметная стоимость на единицу"],
[["01.1.01.01-0003", "Дверка поддувальная чугунная", "м2", 110]])
compared = ic.compare(ic.read_table(tmp_path, "КА.xlsx", "Данные", "ka"),
ic.read_table(tmp_path, "ЛСР.xlsx", "Данные", "lsr"), "ka_lsr")
row = compared["rows"][0]
assert row["match_index"] is None
assert row["candidates"][0]["index"] == 0
revised = ic.compare(compared["left"], compared["right"], "ka_lsr", choices={0: 0})
assert revised["rows"][0]["difference"] is None
assert "единиц" in revised["rows"][0]["warning"]
def test_vor_lsr_compares_volume_only_for_compatible_units(tmp_path):
import inline_compare as ic
workbook(tmp_path / "ВОР.xlsx", ["Наименование работ", "Ед. изм.", "Количество"],
[["Монтаж извещателя", "шт", 100]])
workbook(tmp_path / "ЛСР.xlsx", ["Код работы", "Наименование", "Ед. изм.", "Количество"],
[["10-08-002-02", "Монтаж извещателя", "шт", 95]])
result = ic.compare(ic.read_table(tmp_path, "ВОР.xlsx", "Данные", "vor"),
ic.read_table(tmp_path, "ЛСР.xlsx", "Данные", "lsr"), "vor_lsr")
assert result["rows"][0]["match_index"] == 0
assert Decimal(result["rows"][0]["difference"]) == Decimal("-5")
def test_path_traversal_and_ambiguous_headers_are_rejected(tmp_path):
import inline_compare as ic
with pytest.raises(ValueError):
ic.read_table(tmp_path, "../secret.xlsx", "Данные", "ka")
workbook(tmp_path / "Пусто.xlsx", ["Колонка 1", "Колонка 2"], [["x", "y"]])
with pytest.raises(ValueError, match="заголов"):
ic.read_table(tmp_path, "Пусто.xlsx", "Данные", "ka")
def test_detection_requires_explicit_comparison_intent():
import inline_compare as ic
assert ic.detect_mode("Сравни цены КА с ЛСР") == "ka_lsr"
assert ic.detect_mode("Сверь объёмы ВОР и ЛСР") == "vor_lsr"
assert ic.detect_mode("Сопоставь КА с коммерческими предложениями") == "ka_kp"
assert ic.detect_mode("Расскажи о КА и ЛСР") is None
def test_ka_kp_uses_vat_price_without_guessing_a_missing_value(tmp_path):
import inline_compare as ic
workbook(tmp_path / "КА.xlsx",
["Код ресурса", "Наименование", "Ед. изм.", "Текущая отпускная цена с НДС"],
[["R-01", "Кабель", "м", 120], ["R-02", "Провод", "м", None]])
workbook(tmp_path / "КП.xlsx",
["Код ресурса", "Наименование", "Ед. изм.", "Цена с НДС"],
[["R-01", "Кабель", "м", 125], ["R-02", "Провод", "м", 130]])
result = ic.compare(ic.read_table(tmp_path, "КА.xlsx", "Данные", "ka"),
ic.read_table(tmp_path, "КП.xlsx", "Данные", "kp"), "ka_kp")
assert result["rows"][0]["difference"] == "5.00"
assert result["rows"][1]["difference"] is None
assert result["complete"] is False
def test_comparison_api_stays_in_dialog_and_rejects_stale_file(tmp_path, monkeypatch):
monkeypatch.setenv("DB_PATH", str(tmp_path / "compare.db"))
monkeypatch.setenv("DATA_DIR", str(tmp_path / "data"))
monkeypatch.setenv("SESSION_SECRET", "compare-test-secret")
import auth
import db
import main
for module in (db, auth, main):
importlib.reload(module)
db.init_db()
db.create_user("compare@x", auth.hash_password("Passw0rd!ok"))
db.admin_verify_user("compare@x")
db.create_user("other@x", auth.hash_password("Passw0rd!ok"))
db.admin_verify_user("other@x")
headers = {"Authorization": "Bearer " + auth._make_token("compare@x"), "X-Tab-Id": "tab"}
other = {"Authorization": "Bearer " + auth._make_token("other@x"), "X-Tab-Id": "tab"}
folder = tmp_path / "data" / "compare@x" / "tab"
folder.mkdir(parents=True)
workbook(folder / "КА.xlsx", ["Код ресурса", "Наименование", "Ед. изм.", "Сметная цена без НДС"],
[["01.1.01.01-0002", "Материал А", "шт", 100]])
workbook(folder / "ЛСР.xlsx", ["Код ресурса", "Наименование", "Ед. изм.", "Сметная стоимость на единицу"],
[["01.1.01.01-0002", "Материал А", "шт", 105]])
assistant_id = db.save_message("compare@x", "tab", "assistant", "Сверка файлов")
compare_id = db.save_message("compare@x", "tab", "file_compare", json.dumps({
"_assistant_id": assistant_id, "_revision": 0, "mode": "ka_lsr", "left": None,
"right": None, "choices": {}, "price_fields": {}}))
client = TestClient(main.app)
url = f"/api/file-compare/{compare_id}"
assert client.get(url).status_code == 401
assert client.get(url, headers=other).status_code == 404
assert len(client.get("/api/file-compare/workbooks", headers=headers).json()["workbooks"]) == 2
first = client.post(url, headers=headers,
json={"revision": 0, "left": {"file": "КА.xlsx", "sheet": "Данные"}})
assert first.status_code == 200, first.text
second = client.post(url, headers=headers,
json={"revision": 1, "right": {"file": "ЛСР.xlsx", "sheet": "Данные"}})
assert second.status_code == 200, second.text
assert second.json()["comparison"]["rows"][0]["difference"] == "5.00"
assert client.post(url, headers=headers, json={"revision": 1, "choices": {"0": -1}}).status_code == 409
assert client.post(url, headers=other, json={"revision": 2}).status_code == 404
workbook(folder / "ЛСР.xlsx", ["Код ресурса", "Наименование", "Ед. изм.", "Сметная стоимость на единицу"],
[["01.1.01.01-0002", "Материал А", "шт", 110]])
assert client.get(url, headers=headers).status_code == 409
assert client.post(url, headers=headers, json={"revision": 2, "choices": {"0": -1}}).status_code == 409
+172
View File
@@ -0,0 +1,172 @@
"""Switching a price form changes the saved answer and estimate as one revision."""
import importlib
import json
import asyncio
import pytest
from fastapi.testclient import TestClient
@pytest.fixture()
def case(tmp_path, monkeypatch):
monkeypatch.setenv("DB_PATH", str(tmp_path / "chat.db"))
monkeypatch.setenv("SESSION_SECRET", "inline-estimate-test")
monkeypatch.setenv("ESTIMATE_ENGINE", "on")
import auth
import db
import main
import engine_prices
import estimate_contract
for module in (db, auth, main):
importlib.reload(module)
db.init_db()
for email in ("alice@x", "bob@x"):
db.create_user(email, auth.hash_password("Passw0rd!ok"))
db.admin_verify_user(email)
old = {
"title": "Смета", "positions": [{"code": "ГЭСН 01-01-001-01", "name": "Работа",
"unit": "м3", "qty": 2, "total": 100}],
"totals": {"grand_total": 100}, "ok": True,
"applied": {"subject": "Тестовый край", "subject_id": 1,
"zone": "Тестовый край (1 зона)", "zone_id": 11,
"period": "3 квартал 2026", "period_id": 403},
"meta": {"region": "Тестовый край (1 зона)", "price_level": "3 квартал 2026"},
}
assistant_id = db.save_message("alice@x", "tab", "assistant", "Исходный ответ: 100 руб.")
estimate_id = db.save_message("alice@x", "tab", "estimate",
json.dumps({**old, "_assistant_id": assistant_id}, ensure_ascii=False))
catalog = {"zones": [
{"subject_id": 1, "subject_name": "Тестовый край", "zone_id": 11,
"zone_name": "Тестовый край (1 зона)", "period_id": 403,
"period_label": "3 квартал 2026"},
{"subject_id": 1, "subject_name": "Тестовый край", "zone_id": 12,
"zone_name": "Тестовый край (2 зона)", "period_id": 404,
"period_label": "4 квартал 2026"},
{"subject_id": 2, "subject_name": "Чужой край", "zone_id": 21,
"zone_name": "Чужой край", "period_id": 404,
"period_label": "4 квартал 2026"},
]}
monkeypatch.setattr(engine_prices, "load_catalog", lambda: catalog)
seen = []
def calculate(positions, meta):
seen.append((positions, meta))
return {"status": "ok", "ok": True, "grand_total": 240,
"positions": [{"code": "ГЭСН 01-01-001-01", "name": "Работа",
"unit": "м3", "qty": 2, "total": 240}],
"missing": [], "unpriced": [], "limits_note": "Без дополнительных затрат и НДС.",
"applied": {"subject": "Тестовый край", "subject_id": 1,
"zone": "Тестовый край (2 зона)", "zone_id": 12,
"period": "4 квартал 2026", "period_id": 404}}
monkeypatch.setattr(estimate_contract, "calc_estimate", calculate)
client = TestClient(main.app)
alice = {"Authorization": "Bearer " + auth._make_token("alice@x"), "X-Tab-Id": "tab"}
bob = {"Authorization": "Bearer " + auth._make_token("bob@x"), "X-Tab-Id": "tab"}
return db, client, alice, bob, estimate_id, assistant_id, seen
def _request(client, estimate_id, headers, **values):
return client.post(f"/api/estimates/{estimate_id}/basis", headers=headers,
json={"zone_id": 12, "period_id": 404, "revision": 0, **values})
def test_basis_switch_is_saved_in_same_answer(case):
db, client, alice, _, eid, aid, seen = case
r = _request(client, eid, alice)
assert r.status_code == 200, r.text
body = r.json()
assert body["estimate"]["applied"]["zone_id"] == 12
assert body["estimate"]["_revision"] == 1
assert "240,00 ₽" in body["answer"] and "4 квартал 2026" in body["answer"]
assert "**" not in body["answer"]
assert seen == [([{"code": "ГЭСН 01-01-001-01", "unit": "м3", "qty": 2}],
{"region": "Тестовый край", "zone": "Тестовый край (2 зона)",
"price_level": "4 квартал 2026"})]
rows = db.get_history("alice@x", "tab")
assert len(rows) == 2 and [row["id"] for row in rows] == [aid, eid]
assert rows[0]["content"] == body["answer"]
assert json.loads(rows[1]["content"])["_revision"] == 1
def test_basis_switch_requires_owner_and_current_revision(case):
db, client, alice, bob, eid, _, seen = case
assert _request(client, eid, {}).status_code == 401
assert _request(client, eid, bob).status_code == 404
assert _request(client, eid, alice, zone_id=21).status_code == 400
assert seen == []
assert _request(client, eid, alice).status_code == 200
assert _request(client, eid, alice).status_code == 409
assert len(db.get_history("alice@x", "tab")) == 2
def test_basis_options_only_contain_current_subject(case):
_, client, alice, _, eid, _, _ = case
r = client.get(f"/api/estimates/{eid}/basis", headers=alice)
assert r.status_code == 200
assert [(z["zone_id"], [p["period_id"] for p in z["periods"]])
for z in r.json()["zones"]] == [(11, [403]), (12, [404])]
def test_stream_links_estimate_to_answer_before_sending_event(tmp_path, monkeypatch):
import main
saved = []
def save(_user, _tab, role, content):
saved.append((role, content))
return len(saved)
monkeypatch.setattr(main, "save_message", save)
monkeypatch.setattr(main, "get_work_dir", lambda _u, _t: tmp_path)
monkeypatch.setattr(main, "_work_dir_snapshot", lambda _path: {})
monkeypatch.setattr(main, "_maybe_autotitle", lambda *_: None)
(tmp_path / "_estimate_panel.json").write_text(json.dumps({
"positions": [{"code": "ГЭСН 01-01-001-01", "qty": 2}],
"applied": {"subject_id": 1}}), encoding="utf-8")
async def stream(*_):
yield 'event: text\ndata: {"text":"Смета посчитана"}\n\n'
yield 'event: done\ndata: {"result":"Смета посчитана","usage":{}}\n\n'
monkeypatch.setattr(main, "stream_claude", stream)
chunks = asyncio.run(_collect(main._stream_and_save("Посчитай смету", "alice@x", "tab")))
event = next(json.loads(chunk.split("data: ", 1)[1]) for chunk in chunks
if chunk.startswith("event: estimate"))
assistant_id = next(i for i, (role, _) in enumerate(saved, 1) if role == "assistant")
estimate_id = next(i for i, (role, _) in enumerate(saved, 1) if role == "estimate")
assert event["_assistant_id"] == assistant_id
assert event["_message_id"] == estimate_id
assert json.loads(saved[estimate_id - 1][1])["_assistant_id"] == assistant_id
def test_stream_attaches_file_comparison_to_same_answer(tmp_path, monkeypatch):
import main
saved = []
def save(_user, _tab, role, content):
saved.append((role, content))
return len(saved)
monkeypatch.setattr(main, "save_message", save)
monkeypatch.setattr(main, "get_work_dir", lambda _u, _t: tmp_path)
monkeypatch.setattr(main, "_work_dir_snapshot", lambda _path: {})
monkeypatch.setattr(main, "_maybe_autotitle", lambda *_: None)
async def stream(*_):
yield 'event: text\ndata: {"text":"Сверка файлов"}\n\n'
yield 'event: done\ndata: {"result":"Сверка файлов","usage":{}}\n\n'
monkeypatch.setattr(main, "stream_claude", stream)
chunks = asyncio.run(_collect(main._stream_and_save("Сравни цены КА с ЛСР", "alice@x", "tab")))
event = next(json.loads(chunk.split("data: ", 1)[1]) for chunk in chunks
if chunk.startswith("event: file_compare"))
assistant_id = next(i for i, (role, _) in enumerate(saved, 1) if role == "assistant")
compare_id = next(i for i, (role, _) in enumerate(saved, 1) if role == "file_compare")
assert event["_assistant_id"] == assistant_id
assert event["_message_id"] == compare_id
assert event["mode"] == "ka_lsr"
async def _collect(stream):
return [chunk async for chunk in stream]
+181
View File
@@ -0,0 +1,181 @@
"""The price selector edits the current answer bubble in a real browser."""
import functools
import http.server
import os
import socketserver
import sys
import threading
from pathlib import Path
import pytest
sys.path.insert(0, str(Path(__file__).resolve().parent))
pytest.importorskip("playwright.sync_api")
import ui_smoke_harness # noqa: E402
from test_password_reset_ui import browser # noqa: E402,F401
@pytest.fixture(scope="module")
def site(tmp_path_factory):
directory = tmp_path_factory.mktemp("inline-estimate")
ui_smoke_harness.build_stub(directory / "index.html", logged_in=True)
handler = functools.partial(http.server.SimpleHTTPRequestHandler, directory=str(directory))
class Quiet(socketserver.ThreadingTCPServer):
allow_reuse_address = True
daemon_threads = True
server = Quiet(("127.0.0.1", 0), handler)
threading.Thread(target=server.serve_forever, daemon=True).start()
yield f"http://127.0.0.1:{server.server_address[1]}/index.html"
server.shutdown()
def test_choice_replaces_current_answer_without_new_bubble(browser, site):
page = browser.new_page(viewport={"width": 390, "height": 844})
page.goto(site)
page.wait_for_timeout(500)
page.evaluate("""() => {
const oldFetch = window.fetch;
window._basisPosts = [];
const old = {title:'Смета', _message_id:31, _assistant_id:30, _revision:0, ok:true,
positions:[{code:'ГЭСН 01-01-001-01',name:'Работа',unit:'м3',qty:2,total:100}],
totals:{grand_total:100}, applied:{subject:'Тестовый край',subject_id:1,
zone:'Тестовый край (1 зона)',zone_id:11,period:'3 квартал 2026',period_id:403}};
window.fetch = async (url, opts={}) => {
if (String(url).includes('/api/estimates/31/basis')) {
if (opts.method === 'POST') {
window._basisPosts.push(JSON.parse(opts.body));
return new Response(JSON.stringify({answer:'Итого: 240 ₽ · 4 квартал 2026',
estimate:{...old,_revision:1,
positions:[{...old.positions[0],total:240}],totals:{grand_total:240},
applied:{...old.applied,zone:'Тестовый край (2 зона)',zone_id:12,
period:'4 квартал 2026',period_id:404}}}),
{status:200,headers:{'Content-Type':'application/json'}});
}
return new Response(JSON.stringify({revision:0,zones:[
{zone_id:11,name:'Тестовый край (1 зона)',periods:[{period_id:403,name:'3 квартал 2026'}]},
{zone_id:12,name:'Тестовый край (2 зона)',periods:[
{period_id:402,name:'2 квартал 2026'},
{period_id:404,name:'4 квартал 2026'}]}]}),
{status:200,headers:{'Content-Type':'application/json'}});
}
return oldFetch(url,opts);
};
const answer = addMsg('ai','Исходный ответ: 100 ₽');
addEstimatePanel(old,null,answer);
window._answer = answer;
}""")
page.locator(".est-basis-picker button").click()
page.locator('select[aria-label="Ценовая зона"]').select_option("12")
page.wait_for_function("window._basisPosts.length === 1 && window._answer.innerText.includes('240')")
state = page.evaluate("""() => ({
bubbles: document.querySelectorAll('#messages .msg-ai').length,
within: !!window._answer.querySelector('.est-panel'),
text: window._answer.innerText,
posts: window._basisPosts,
cssWidth: window.innerWidth,
headDisplay: getComputedStyle(window._answer.querySelector('.est-header-row')).display,
hostClass: window._answer.className,
unitPrice: window._answer.querySelector('.est-table tr:not(.est-header-row) td:nth-child(6)')?.textContent,
horizontalOverflow: document.documentElement.scrollWidth > window.innerWidth
})""")
screenshot_dir = os.environ.get("INLINE_ESTIMATE_SCREENSHOTS")
if screenshot_dir:
page.evaluate("document.querySelector('#messages').scrollTop = 0")
page.screenshot(path=str(Path(screenshot_dir) / "inline-estimate-mobile.png"))
page.evaluate("document.querySelector('#messages').scrollTop = document.querySelector('#messages').scrollHeight")
page.screenshot(path=str(Path(screenshot_dir) / "inline-estimate-mobile-bottom.png"))
page.set_viewport_size({"width": 1280, "height": 800})
page.screenshot(path=str(Path(screenshot_dir) / "inline-estimate-desktop.png"))
page.close()
assert state["bubbles"] == 1 and state["within"]
assert "Исходный ответ: 100" not in state["text"]
assert "240" in state["text"] and "4 квартал 2026" in state["text"]
assert state["posts"][0]["zone_id"] == 12
assert state["posts"][0]["period_id"] == 404
assert state["unitPrice"] == "120,00"
assert state["headDisplay"] == "none", state
assert not state["horizontalOverflow"]
def test_saved_revision_reopens_inside_same_bubble(browser, site):
page = browser.new_page(viewport={"width": 390, "height": 844})
page.goto(site)
page.wait_for_timeout(500)
state = page.evaluate("""async () => {
const oldFetch = window.fetch;
window.fetch = async (url, opts={}) => {
if (String(url).includes('/api/history')) return new Response(JSON.stringify([
{id:30,role:'assistant',content:'Итого по локальной смете: 240 ₽',timestamp:1},
{id:31,role:'estimate',timestamp:2,content:JSON.stringify({
_assistant_id:30,_revision:1,title:'Смета',ok:true,
positions:[{code:'ГЭСН 01-01-001-01',name:'Работа',unit:'м3',qty:2,total:240}],
totals:{grand_total:240},applied:{subject:'Тестовый край',subject_id:1,
zone:'Тестовый край (2 зона)',zone_id:12,period:'4 квартал 2026',period_id:404}})}
]),{status:200,headers:{'Content-Type':'application/json'}});
return oldFetch(url,opts);
};
await loadHistory();
return {bubbles:document.querySelectorAll('#messages .msg-ai').length,
inside:!!document.querySelector('#messages .msg-ai .est-panel'),
text:document.querySelector('#messages .msg-ai')?.innerText || ''};
}""")
page.close()
assert state["bubbles"] == 1 and state["inside"]
assert "240" in state["text"] and "4 квартал 2026" in state["text"]
def test_plain_answer_zone_changes_inside_its_bubble(browser, site):
page = browser.new_page(viewport={"width": 390, "height": 844})
page.goto(site)
page.wait_for_timeout(500)
page.evaluate("""() => {
const oldFetch = window.fetch;
window.fetch = async (url, opts={}) => {
if (String(url).includes('/api/messages/30/basis')) {
if (opts.method === 'POST') return new Response(JSON.stringify({
answer:'Норма 10-08-002-02. Объём 100 шт. Ценовая зона: Хабаровский край (2 зона), 4 квартал 2026. Стоимость учтённой части: 280 ₽.'
}), {status:200,headers:{'Content-Type':'application/json'}});
return new Response(JSON.stringify({revision:'old-hash',zones:[
{zone_id:118,name:'Хабаровский край (1 зона)',periods:[{period_id:428,name:'4 квартал 2026'}]},
{zone_id:179,name:'Хабаровский край (2 зона)',periods:[{period_id:428,name:'4 квартал 2026'}]}
]}), {status:200,headers:{'Content-Type':'application/json'}});
}
return oldFetch(url,opts);
};
const answer = addMsg('ai','Норма ГЭСНм 10-08-002-02, объём работ = 100 шт.\\nУровень цен: III квартал 2025.\\nВыберите ценовую зону:\\n1. Хабаровский край (1 зона)\\n2. Хабаровский край (2 зона)');
answer._messageId = 30;
bindFreeformBasis(answer);
}""")
page.locator(".inline-basis-trigger").first.click()
assert page.locator('select[aria-label="Квартал цен"]').input_value() == ""
assert "не загружен" in page.locator('.inline-basis-picker').inner_text()
screenshot_dir = os.environ.get("INLINE_FREEFORM_SCREENSHOTS")
if screenshot_dir:
page.screenshot(path=str(Path(screenshot_dir) / "inline-freeform-picker.png"))
page.locator('select[aria-label="Ценовая зона"]').select_option("179")
page.locator('select[aria-label="Квартал цен"]').select_option("428")
page.locator(".inline-basis-apply").click()
page.locator(".msg-ai .ai-body", has_text="280 ₽").wait_for(timeout=10000)
assert page.locator("#messages .msg-ai").count() == 1
assert "Выберите ценовую зону" not in page.locator(".msg-ai").inner_text()
assert page.locator(".inline-basis-trigger").count() >= 1
assert page.evaluate("document.documentElement.scrollWidth <= window.innerWidth")
if screenshot_dir:
page.screenshot(path=str(Path(screenshot_dir) / "inline-freeform-updated.png"))
page.close()
def test_plain_zone_without_calculable_position_has_no_dead_selector(browser, site):
page = browser.new_page()
page.goto(site)
page.wait_for_timeout(500)
count = page.evaluate("""() => {
const answer = addMsg('ai','Выберите ценовую зону: Хабаровский край (1 зона).');
answer._messageId = 40;
bindFreeformBasis(answer);
return answer.querySelectorAll('.inline-basis-trigger').length;
}""")
page.close()
assert count == 0
+165
View File
@@ -0,0 +1,165 @@
"""A price zone chosen in a plain AI answer revises that answer in place."""
import importlib
import pytest
from fastapi.testclient import TestClient
@pytest.fixture()
def case(tmp_path, monkeypatch):
monkeypatch.setenv("DB_PATH", str(tmp_path / "chat.db"))
monkeypatch.setenv("SESSION_SECRET", "inline-freeform-test")
import auth
import db
import engine_prices
import main
for module in (db, auth, main):
importlib.reload(module)
db.init_db()
for email in ("alice@x", "bob@x"):
db.create_user(email, auth.hash_password("Passw0rd!ok"))
db.admin_verify_user(email)
db.save_message("alice@x", "tab", "user", "Посчитай 100 извещателей в Хабаровском крае")
original = ("Выберите ценовую зону:\n"
"1. Хабаровский край (1 зона)\n"
"2. Хабаровский край (2 зона)")
answer_id = db.save_message("alice@x", "tab", "assistant", original)
monkeypatch.setattr(engine_prices, "load_catalog", lambda: {"zones": [
{"subject_id": 264, "zone_id": 118, "zone_name": "Хабаровский край (1 зона)",
"period_id": 428, "period_label": "4 квартал 2026"},
{"subject_id": 264, "zone_id": 179, "zone_name": "Хабаровский край (2 зона)",
"period_id": 428, "period_label": "4 квартал 2026"},
{"subject_id": 265, "zone_id": 300, "zone_name": "Другой край (1 зона)",
"period_id": 428, "period_label": "4 квартал 2026"},
]})
seen = []
async def generate(user, tab, question, old_answer, zone, period):
seen.append((user, tab, question, old_answer, zone, period))
return {"answer": "Расчёт для Хабаровский край (2 зона), 4 квартал 2026: 280 ₽.",
"usage": {}, "provider": "test", "model": "test"}
monkeypatch.setattr(main, "_generate_freeform_basis_answer", generate, raising=False)
client = TestClient(main.app)
alice = {"Authorization": "Bearer " + auth._make_token("alice@x"), "X-Tab-Id": "tab"}
bob = {"Authorization": "Bearer " + auth._make_token("bob@x"), "X-Tab-Id": "tab"}
return db, client, alice, bob, answer_id, original, seen
def test_plain_answer_switches_in_place_and_rejects_stale_or_foreign(case):
db, client, alice, bob, answer_id, original, seen = case
url = f"/api/messages/{answer_id}/basis"
params = {"label": "Хабаровский край (1 зона)"}
assert client.get(url, params=params).status_code == 401
assert client.get(url, params=params, headers=bob).status_code == 404
options = client.get(url, params=params, headers=alice)
assert options.status_code == 200, options.text
assert [z["zone_id"] for z in options.json()["zones"]] == [118, 179]
payload = {"label": params["label"], "zone_id": 179, "period_id": 428,
"revision": options.json()["revision"]}
assert client.post(url, json={**payload, "zone_id": 300}, headers=alice).status_code == 400
assert client.post(url, json=payload, headers=bob).status_code == 404
result = client.post(url, json=payload, headers=alice)
assert result.status_code == 200, result.text
assert "280 ₽" in result.json()["answer"]
rows = db.get_history("alice@x", "tab")
assert len(rows) == 2 and rows[1]["id"] == answer_id
assert rows[1]["content"] == result.json()["answer"]
assert client.post(url, json=payload, headers=alice).status_code == 409
assert len(seen) == 1 and seen[0][3] == original
def test_label_must_exist_in_saved_answer(case):
_, client, alice, _, answer_id, _, seen = case
url = f"/api/messages/{answer_id}/basis"
assert client.get(url, params={"label": "Другой край (1 зона)"}, headers=alice).status_code == 400
assert seen == []
def test_plain_answer_extracts_explicit_norm_and_volume_without_guessing():
import answer_basis
question = "Посчитай монтаж 100 пожарных извещателей в Хабаровском крае"
answer = "Норма ГЭСНм 10-08-002-02. Измеритель 1 шт. На 100 извещателей объём работ = 100 шт."
assert answer_basis.extract_position(question, answer) == ("10-08-002-02", 100.0)
assert answer_basis.extract_position("Какая цена?", "ГЭСНм 10-08-002-02") is None
def test_incomplete_engine_result_is_never_presented_as_full_total():
import answer_basis
result = {"status": "ok", "ok": False, "grand_total": 156066.82,
"missing": [{"code": "ГЭСНм 10-08-002-02", "reason": "НР/СП не определены"}],
"unpriced": [], "positions": [{"code": "ГЭСНм 10-08-002-02", "qty": 100,
"unit": "шт", "total": 156066.82}]}
text = answer_basis.format_plain_result(result, "10-08-002-02", 100,
"Хабаровский край (2 зона)", "4 квартал 2026")
assert "156 066,82 ₽" in text
assert "НР/СП не определены" in text
assert "итого по локальной смете" not in text.lower()
def test_recalculated_answer_is_source_of_current_norm_and_volume():
import answer_basis
question = "Посчитай 100 шт. по 10-08-002-02"
saved_answer = "Ценовая зона: Хабаровский край (1 зона). Период цен: 4 квартал 2026.\nНорма: 10-08-002-03. Объём: 75 шт."
assert answer_basis.extract_position(question, saved_answer) == ("10-08-002-03", 75.0)
unverified = "Норма: 10-08-002-03. Объём: 75 шт."
assert answer_basis.extract_position(question, unverified) is None
def test_norm_choices_exclude_other_family_and_measure(monkeypatch):
import answer_basis
import fsnb_ref
def fake_find(*, query, base, limit):
assert query == "10-08-002" and base == "2022"
return {"status": "ok", "results": [
{"code": "10-08-002-02", "name": "Извещатель дымовой", "base_type": "ГЭСНм", "unit": "шт.", "resources": [{"code": "1-100-40", "quantity": 1}]},
{"code": "10-08-002-03", "name": "Извещатель тепловой", "base_type": "ГЭСНм", "unit": "шт.", "resources": [{"code": "1-100-40", "quantity": 1}]},
{"code": "10-08-002-04", "name": "Другая единица", "base_type": "ГЭСНм", "unit": "100 шт.", "resources": [{"code": "1-100-40", "quantity": 1}]},
{"code": "10-08-002-05", "name": "Другой сборник", "base_type": "ГЭСН", "unit": "шт.", "resources": [{"code": "1-100-40", "quantity": 1}]},
{"code": "10-08-002-06", "name": "Машинная норма", "base_type": "ГЭСНм", "unit": "шт.", "resources": [{"code": "91.01.01-001", "quantity": 1}]},
]}
monkeypatch.setattr(fsnb_ref, "find_gesn_composition", fake_find)
assert [r["code"] for r in answer_basis.norm_choices("10-08-002-02")] == [
"10-08-002-02", "10-08-002-03"]
def test_norm_and_quantity_change_is_scoped_and_revisioned(case, monkeypatch):
import answer_basis
import main
db, client, alice, bob, answer_id, original, _ = case
current = original + "\nНорма: 10-08-002-02. Объём: 100 шт."
assert db.replace_scoped_assistant("alice@x", "tab", answer_id, original, current)
monkeypatch.setattr(answer_basis, "norm_choices", lambda code: [
{"code": "10-08-002-02", "name": "Дымовой"},
{"code": "10-08-002-03", "name": "Тепловой"}])
seen = []
async def generate(user, tab, question, old_answer, zone, period, code_override=None,
qty_override=None):
seen.append((code_override, qty_override))
return {"answer": f"Ценовая зона: {zone}. Период цен: {period}.\n"
f"Норма: {code_override}. Объём: {qty_override:g} шт."}
monkeypatch.setattr(main, "_generate_freeform_basis_answer", generate)
url = f"/api/messages/{answer_id}/basis"
options = client.get(url, params={"label": "Хабаровский край (1 зона)"}, headers=alice)
assert options.status_code == 200
assert options.json()["position"]["code"] == "10-08-002-02"
assert len(options.json()["norms"]) == 2
payload = {"label": "Хабаровский край (1 зона)", "zone_id": 118,
"period_id": 428, "revision": options.json()["revision"],
"norm_code": "10-08-002-03", "quantity": 75}
assert client.post(url, json=payload, headers=bob).status_code == 404
assert client.post(url, json={**payload, "norm_code": "10-08-002-99"}, headers=alice).status_code == 400
assert client.post(url, json={**payload, "quantity": -1}, headers=alice).status_code == 400
result = client.post(url, json=payload, headers=alice)
assert result.status_code == 200, result.text
assert "10-08-002-03. Объём: 75 шт." in result.json()["answer"]
assert db.get_history("alice@x", "tab")[1]["content"] == result.json()["answer"]
assert client.post(url, json=payload, headers=alice).status_code == 409
second_options = client.get(url, params={"label": "Хабаровский край (1 зона)"}, headers=alice).json()
assert second_options["position"] == {"code": "10-08-002-03", "quantity": 75.0}
second = client.post(url, json={**payload, "revision": second_options["revision"],
"quantity": 25}, headers=alice)
assert second.status_code == 200, second.text
assert "Объём: 25 шт." in db.get_history("alice@x", "tab")[1]["content"]
assert seen == [("10-08-002-03", 75.0), ("10-08-002-03", 25.0)]
+185
View File
@@ -0,0 +1,185 @@
"""Source-backed norm search and price preview."""
import pytest
import importlib
from fastapi.testclient import TestClient
def test_search_rejects_empty_query_and_uses_existing_fsnb(monkeypatch):
import fsnb_ref
import norm_finder
seen = []
def find(*, query, base, limit):
seen.append((query, base, limit))
return {"status": "ok", "works": [{"code": "10-08-002-02", "name": "Извещатель",
"unit": "шт.", "base": "ГЭСН-2022", "base_type": "ГЭСНм"}]}
monkeypatch.setattr(fsnb_ref, "find_works", find)
with pytest.raises(ValueError):
norm_finder.search(" ", "2022", 12)
found = norm_finder.search("извещатель", "2022", 12)
assert found["items"][0]["code"] == "10-08-002-02"
assert found["items"][0]["match_reason"].startswith("Совпали слова")
assert seen == [("извещатель", "2022", 12)]
def test_search_falls_back_to_subject_term_and_ranks_relevant_work(monkeypatch):
import fsnb_ref
import norm_finder
def find(*, query, base, limit):
if query == "устройство стяжки пола":
return {"status": "not_found"}
assert query == "стяжки"
return {"status": "ok", "works": [
{"code": "06-12-001-04", "name": "Заполнение откосов со стяжкой",
"section_path": "Элеваторы", "base": "ГЭСН-2022", "base_type": "ГЭСН", "unit": "м3"},
{"code": "11-01-011-02", "name": "Устройство стяжек пола",
"section_path": "Полы", "base": "ГЭСН-2022", "base_type": "ГЭСН", "unit": "100 м2"},
]}
monkeypatch.setattr(fsnb_ref, "find_works", find)
monkeypatch.setattr(fsnb_ref, "count_works", lambda word: {"стяжки": 30, "пола": 200}.get(word, 1000))
rows = norm_finder.search("устройство стяжки пола", "2022", 12)["items"]
assert rows[0]["code"] == "11-01-011-02"
def test_detail_requires_exact_base_type_and_code(monkeypatch):
import fsnb_ref
import norm_finder
def composition(*, query, base, limit):
return {"status": "ok", "results": [
{"base": "ГЭСН-2022", "base_type": "ГЭСН", "code": query,
"name": "Другая норма", "unit": "м2", "resources": []},
{"base": "ГЭСН-2022", "base_type": "ГЭСНм", "code": query,
"name": "Извещатель", "unit": "шт.", "resources": [{"code": "1-100-40", "quantity": 1}],
"provenance": {"decree": "Приказ"}},
]}
monkeypatch.setattr(fsnb_ref, "find_gesn_composition", composition)
item = norm_finder.detail("2022", "ГЭСНм", "10-08-002-02")
assert item["name"] == "Извещатель"
assert item["provenance"]["decree"] == "Приказ"
assert item["current_price_supported"] is True
with pytest.raises(ValueError):
norm_finder.detail("2022", "ГЭСНр", "10-08-002-02")
def test_calculation_refuses_unpriced_norm_instead_of_fabricating_total(monkeypatch):
import norm_finder
monkeypatch.setattr(norm_finder, "detail", lambda *args: {
"base": "ГЭСН-2022", "base_type": "ГЭСНм", "code": "10-08-002-02",
"name": "Извещатель", "unit": "шт.", "resources": [
{"code": "91.01.01-001", "name": "Машина", "unit": "маш.-ч", "quantity": 1}],
})
with pytest.raises(ValueError, match="не поддерживается"):
norm_finder.calculate("2022", "ГЭСНм", "10-08-002-02", 100, "шт.",
"Хабаровский край (1 зона)", "4 квартал 2026")
def test_gesn_quantity_uses_base_unit_and_engine_resource_key(monkeypatch):
import norm_finder
import engine_prices
import estimate_contract as ec
monkeypatch.setattr(norm_finder, "detail", lambda *args: {
"base": "ГЭСН-2022", "base_type": "ГЭСН", "code": "11-01-049-01",
"name": "Порог", "unit": "100 м", "resources": [
{"code": "1-100-40", "name": "Рабочий", "unit": "чел.-ч", "quantity": 1}],
})
monkeypatch.setattr(engine_prices, "resolve", lambda meta: {"status": "ok", "entry": {}})
monkeypatch.setattr(engine_prices, "load_lookup", lambda entry: object())
seen = []
def fake_calc(draft, resources, prices, basis):
seen.append((draft.positions[0].qty, sorted(resources)))
return {"status": "ok", "ok": False, "grand_total": 10.0,
"missing": [{"reason": "НР/СП"}], "unpriced": []}
monkeypatch.setattr(ec, "build_and_calc", fake_calc)
result = norm_finder.calculate("2022", "ГЭСН", "11-01-049-01", 50, "м",
"Хабаровский край (1 зона)", "4 квартал 2026")
assert seen == [(0.5, ["11-01-049-01"])]
assert result["total"] is None and result["accounted"] == 10.0
@pytest.fixture()
def api(tmp_path, monkeypatch):
monkeypatch.setenv("DB_PATH", str(tmp_path / "finder.db"))
monkeypatch.setenv("SESSION_SECRET", "finder-test-secret")
import auth
import db
import main
for module in (db, auth, main):
importlib.reload(module)
db.init_db()
db.create_user("finder@x", auth.hash_password("Passw0rd!ok"))
db.admin_verify_user("finder@x")
headers = {"Authorization": "Bearer " + auth._make_token("finder@x"), "X-Tab-Id": "tab"}
return TestClient(main.app), headers, db
@pytest.mark.parametrize("method,path", [
("get", "/api/norm-finder/catalog"),
("get", "/api/norm-finder/search?q=извещатель&base=2022"),
("get", "/api/norm-finder/detail?base=2022&base_type=ГЭСНм&code=10-08-002-02"),
("get", "/api/norm-finder/prices?subject_id=264"),
("post", "/api/norm-finder/calculate"),
("get", "/api/norm-finder/quotes/1"),
("post", "/api/norm-finder/quotes/1"),
])
def test_finder_requires_login(api, method, path):
client, _, _ = api
assert getattr(client, method)(path).status_code == 401
def test_finder_api_search_detail_and_catalog(api, monkeypatch):
import norm_finder
client, headers, _ = api
monkeypatch.setattr(norm_finder, "catalog", lambda: [{"base": "ГЭСН-2022", "base_type": "ГЭСНм", "count": 100}])
monkeypatch.setattr(norm_finder, "search", lambda q, b, limit: {"status": "ok", "items": [
{"base": "ГЭСН-2022", "base_type": "ГЭСНм", "code": "10-08-002-02", "name": "Извещатель", "unit": "шт."}]})
monkeypatch.setattr(norm_finder, "detail", lambda b, t, c: {"base": "ГЭСН-2022", "base_type": t,
"code": c, "name": "Извещатель", "unit": "шт.", "resources": [], "provenance": {"decree": "Приказ"}})
assert client.get("/api/norm-finder/catalog", headers=headers).json()["bases"][0]["count"] == 100
found = client.get("/api/norm-finder/search?q=извещатель&base=2022", headers=headers)
assert found.status_code == 200 and found.json()["items"][0]["code"] == "10-08-002-02"
detail = client.get("/api/norm-finder/detail?base=2022&base_type=ГЭСНм&code=10-08-002-02", headers=headers)
assert detail.status_code == 200 and detail.json()["provenance"]["decree"] == "Приказ"
def test_finder_quote_is_saved_and_revised_in_place(api, monkeypatch):
import norm_finder
import engine_prices
client, headers, db = api
monkeypatch.setattr(engine_prices, "basis_options", lambda sid: [
{"zone_id": 118, "name": "Хабаровский край (1 зона)",
"periods": [{"period_id": 428, "name": "4 квартал 2026"}]}] if sid == 264 else [])
monkeypatch.setattr(norm_finder, "calculate", lambda b, t, c, q, u, z, p: {
"status": "ok", "complete": False, "accounted": q * 100,
"base": "ГЭСН-2022", "base_type": t, "code": c, "quantity": q,
"unit": u, "zone": z, "period": p, "missing": [{"reason": "НР/СП"}]})
body = {"base": "2022", "base_type": "ГЭСНм", "code": "10-08-002-02",
"quantity": 100, "unit": "шт.", "subject_id": 264, "zone_id": 118, "period_id": 428}
assert client.post("/api/norm-finder/calculate", json={**body, "period_id": 999}, headers=headers).status_code == 400
created = client.post("/api/norm-finder/calculate", json=body, headers=headers)
assert created.status_code == 200, created.text
quote = created.json()
assert quote["result"]["accounted"] == 10000
assert db.get_history("finder@x", "tab")[-1]["role"] == "norm_quote"
url = f"/api/norm-finder/quotes/{quote['id']}"
import auth
db.create_user("other@x", auth.hash_password("Passw0rd!ok"))
db.admin_verify_user("other@x")
other = {"Authorization": "Bearer " + auth._make_token("other@x"), "X-Tab-Id": "tab"}
assert client.get(url, headers=other).status_code == 404
assert client.post(url, json={**body, "revision": 0}, headers=other).status_code == 404
assert client.get(url, headers=headers).json()["result"]["accounted"] == 10000
updated = client.post(url, json={**body, "quantity": 75, "revision": quote["revision"]}, headers=headers)
assert updated.status_code == 200 and updated.json()["id"] == quote["id"]
assert updated.json()["result"]["accounted"] == 7500
assert client.post(url, json={**body, "quantity": 50, "revision": quote["revision"]}, headers=headers).status_code == 409
def test_finder_page_is_reachable_from_site(api):
client, _, _ = api
page = client.get("/podbor")
assert page.status_code == 200
assert "Подбор норм" in page.text
assert 'src="/static/norm-finder.js"' in page.text
assert "/podbor" in client.get("/").text
+44
View File
@@ -0,0 +1,44 @@
"""An isolated dev price snapshot must contain every catalogued form."""
import json
import pytest
def _catalog(root, name="264/118/428.json"):
root.mkdir(parents=True, exist_ok=True)
(root / "catalog.json").write_text(json.dumps({"zones": [{
"subject_id": 264, "zone_id": 118, "period_id": 428,
"zone_name": "Хабаровский край (1 зона)",
"period_label": "4 квартал 2026", "file": name}]}), encoding="utf-8")
def test_snapshot_validation_accepts_complete_catalog(tmp_path):
from scripts.shadow.verify_engine_prices import validate
_catalog(tmp_path)
form = tmp_path / "264" / "118" / "428.json"
form.parent.mkdir(parents=True)
form.write_text("{}", encoding="utf-8")
assert validate(tmp_path) == 1
def test_snapshot_validation_rejects_missing_or_escaping_form(tmp_path):
from scripts.shadow.verify_engine_prices import validate
_catalog(tmp_path)
with pytest.raises(ValueError, match="не найдена"):
validate(tmp_path)
_catalog(tmp_path, "../outside.json")
with pytest.raises(ValueError, match="вне"):
validate(tmp_path)
def test_snapshot_validation_rejects_symlink_outside_snapshot(tmp_path):
from scripts.shadow.verify_engine_prices import validate
root = tmp_path / "snapshot"
_catalog(root, "264/118/428.json")
outside = tmp_path / "outside.json"
outside.write_text("{}", encoding="utf-8")
link = root / "264" / "118" / "428.json"
link.parent.mkdir(parents=True)
link.symlink_to(outside)
with pytest.raises(ValueError, match="вне"):
validate(root)