Add inline norm and quantity choices with strict recalculation
This commit is contained in:
+57
-2
@@ -34,10 +34,20 @@ _VOLUME = re.compile(
|
|||||||
r"(?:извещател[А-ЯЁа-яё]*|шт\.?|штук)\b", re.IGNORECASE)
|
r"(?:извещател[А-ЯЁа-яё]*|шт\.?|штук)\b", re.IGNORECASE)
|
||||||
_EXPLICIT_VOLUME = re.compile(r"объ[её]м\s+работ\s*[=:—-]\s*(\d+(?:[.,]\d+)?)\s*шт\b",
|
_EXPLICIT_VOLUME = re.compile(r"объ[её]м\s+работ\s*[=:—-]\s*(\d+(?:[.,]\d+)?)\s*шт\b",
|
||||||
re.IGNORECASE)
|
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:
|
def extract_position(question: str, answer: str) -> tuple[str, float] | None:
|
||||||
"""Only one explicit norm and an explicit piece count; never infer a quantity."""
|
"""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))
|
codes = set(_CODE.findall(question + "\n" + answer))
|
||||||
if len(codes) != 1:
|
if len(codes) != 1:
|
||||||
return None
|
return None
|
||||||
@@ -51,13 +61,49 @@ def extract_position(question: str, answer: str) -> tuple[str, float] | None:
|
|||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def norm_choices(code: str) -> list[dict]:
|
||||||
|
"""Only neighbouring 2022 GESNm piece norms with an auditable composition."""
|
||||||
|
if not _CODE.fullmatch(code):
|
||||||
|
return []
|
||||||
|
import fsnb_ref
|
||||||
|
family = code.rsplit("-", 1)[0]
|
||||||
|
found = fsnb_ref.find_gesn_composition(query=family, base="2022", limit=80)
|
||||||
|
rows = found.get("results") or []
|
||||||
|
choices = []
|
||||||
|
for row in rows:
|
||||||
|
unit = re.sub(r"\s|\.", "", str(row.get("unit") or "").lower())
|
||||||
|
resources = row.get("resources") or []
|
||||||
|
supported = bool(resources) and sum(
|
||||||
|
str(r.get("code") or "").startswith("1-100-") for r in resources) <= 1
|
||||||
|
for resource in resources:
|
||||||
|
resource_code, quantity = str(resource.get("code") or ""), resource.get("quantity")
|
||||||
|
if (not isinstance(quantity, (int, float)) or isinstance(quantity, bool)
|
||||||
|
or not math.isfinite(quantity) or quantity < 0 or resource.get("quantity_note")
|
||||||
|
or not (re.fullmatch(r"1-100-\d{2}", resource_code)
|
||||||
|
or (not resource_code.startswith("91.")
|
||||||
|
and re.match(r"\d{2}\.", resource_code)))):
|
||||||
|
supported = False
|
||||||
|
break
|
||||||
|
if (row.get("base_type") == "ГЭСНм" and unit == "шт"
|
||||||
|
and re.fullmatch(re.escape(family) + r"-\d{2}", str(row.get("code") or ""))
|
||||||
|
and supported):
|
||||||
|
choices.append({"code": row["code"], "name": row.get("name") or row["code"]})
|
||||||
|
if code not in {row["code"] for row in choices}:
|
||||||
|
return []
|
||||||
|
return choices
|
||||||
|
|
||||||
|
|
||||||
def _money(value: float) -> str:
|
def _money(value: float) -> str:
|
||||||
return f"{value:,.2f}".replace(",", " ").replace(".", ",") + " ₽"
|
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:
|
def format_plain_result(result: dict, code: str, qty: float, zone: str, period: str) -> str:
|
||||||
lines = [f"Ценовая зона: {zone}. Период цен: {period}.", "",
|
lines = [f"Ценовая зона: {zone}. Период цен: {period}.", "",
|
||||||
f"Норма: {code}. Объём: {qty:g} шт."]
|
f"Норма: {code}. Объём: {_quantity(qty)} шт."]
|
||||||
if result.get("status") != "ok":
|
if result.get("status") != "ok":
|
||||||
lines.extend(["", "Расчёт стоимости не выполнен: "
|
lines.extend(["", "Расчёт стоимости не выполнен: "
|
||||||
+ str(result.get("message") or "ценовая форма недоступна")])
|
+ str(result.get("message") or "ценовая форма недоступна")])
|
||||||
@@ -83,12 +129,21 @@ def format_plain_result(result: dict, code: str, qty: float, zone: str, period:
|
|||||||
return "\n".join(lines)
|
return "\n".join(lines)
|
||||||
|
|
||||||
|
|
||||||
def calculate_plain(question: str, old_answer: str, zone: str, period: str) -> str:
|
def calculate_plain(question: str, old_answer: str, zone: str, period: str,
|
||||||
|
code_override: str | None = None, qty_override: float | None = None) -> str:
|
||||||
"""Calculate an explicit single GESN piece norm from audited resources and price form."""
|
"""Calculate an explicit single GESN piece norm from audited resources and price form."""
|
||||||
extracted = extract_position(question, old_answer)
|
extracted = extract_position(question, old_answer)
|
||||||
if extracted is None:
|
if extracted is None:
|
||||||
raise ValueError("В ответе нет одной нормы с подтверждённым объёмом в штуках")
|
raise ValueError("В ответе нет одной нормы с подтверждённым объёмом в штуках")
|
||||||
code, qty = extracted
|
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 engine_prices
|
||||||
import estimate_contract as ec
|
import estimate_contract as ec
|
||||||
import fsnb_ref
|
import fsnb_ref
|
||||||
|
|||||||
@@ -0,0 +1,46 @@
|
|||||||
|
# Подбор норм для Инфосметы
|
||||||
|
|
||||||
|
Образец пользовательского сценария: [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 с при согласованной нагрузке. Ссылка на доступный стенд обязательна при показе владельцу.
|
||||||
|
|
||||||
|
Оценка: 14–21 рабочих дней после инвентаризации, если текущая ФСНБ содержит нужные редакции и ресурсный состав; при пробелах данных отдельный этап загрузки и сверки. Это план функционала, реализация здесь ещё не начата.
|
||||||
|
|
||||||
|
## Риски и решение перед стартом
|
||||||
|
|
||||||
|
- Разные редакции одной нормы выглядят одинаково по шифру — ключ результата включает базу, редакцию, тип сборника и идентификатор источника.
|
||||||
|
- Поисковая близость может подменить предмет работы — показать обоснование совпадения, состав работ и пометку «проверьте»; расчёт только после выбора пользователя.
|
||||||
|
- Неполные ресурсы или цены создадут убедительную, но ложную сумму — блокировать готовый итог и перечислить пропуски.
|
||||||
|
- Полная ФСНБ может дать медленный запрос — индекс и профилирование на копии данных до открытия UI.
|
||||||
|
|
||||||
|
После A цикл плана повторяется: сравнить фактическую полноту и качество поиска с критериями, уточнить B–E и только затем брать реализацию. Для выбора предложений КА и соответствия ресурсов из загруженных документов нужен отдельный структурированный слой с источниками, единицами и ценой с/без НДС; это следующий сценарий выбора внутри ответа, а не часть поиска норм.
|
||||||
@@ -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) средняя/незначительный — длинный селектор сломал узкий экран; перенос строк и браузерный осмотр. Три действия: строгая серверная валидация, повторный выбор в тесте, осмотр узкой ширины.
|
||||||
|
|||||||
Binary file not shown.
|
After Width: | Height: | Size: 28 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 27 KiB |
@@ -2424,12 +2424,15 @@ async def estimate_basis_options(estimate_id: int, request: Request):
|
|||||||
|
|
||||||
|
|
||||||
async def _generate_freeform_basis_answer(user: str, tab_id: str, question: str,
|
async def _generate_freeform_basis_answer(user: str, tab_id: str, question: str,
|
||||||
old_answer: str, zone: str, period: str) -> dict:
|
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."""
|
"""Strict recalculation; never substitute an LLM's guessed price for a form."""
|
||||||
import answer_basis
|
import answer_basis
|
||||||
try:
|
try:
|
||||||
answer = await asyncio.to_thread(answer_basis.calculate_plain,
|
answer = await asyncio.to_thread(answer_basis.calculate_plain,
|
||||||
question, old_answer, zone, period)
|
question, old_answer, zone, period,
|
||||||
|
code_override, qty_override)
|
||||||
except ValueError as exc:
|
except ValueError as exc:
|
||||||
raise HTTPException(400, str(exc)) from exc
|
raise HTTPException(400, str(exc)) from exc
|
||||||
return {"answer": answer, "usage": {}, "provider": "estimate-engine", "model": ""}
|
return {"answer": answer, "usage": {}, "provider": "estimate-engine", "model": ""}
|
||||||
@@ -2446,7 +2449,11 @@ async def freeform_basis_options(message_id: int, request: Request, label: str =
|
|||||||
zones, _ = await asyncio.to_thread(answer_basis.options_for_label, saved["content"], label)
|
zones, _ = await asyncio.to_thread(answer_basis.options_for_label, saved["content"], label)
|
||||||
except ValueError as exc:
|
except ValueError as exc:
|
||||||
raise HTTPException(400, str(exc)) from exc
|
raise HTTPException(400, str(exc)) from exc
|
||||||
return {"zones": zones, "revision": answer_basis.revision(saved["content"])}
|
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")
|
@app.post("/api/messages/{message_id}/basis")
|
||||||
@@ -2456,6 +2463,7 @@ async def change_freeform_basis(message_id: int, request: Request):
|
|||||||
body = await _тело(request)
|
body = await _тело(request)
|
||||||
label, token = body.get("label"), body.get("revision")
|
label, token = body.get("label"), body.get("revision")
|
||||||
zone_id, period_id = body.get("zone_id"), body.get("period_id")
|
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)
|
if (not isinstance(label, str) or not isinstance(token, str)
|
||||||
or any(not isinstance(value, int) or isinstance(value, bool) or value < 0
|
or any(not isinstance(value, int) or isinstance(value, bool) or value < 0
|
||||||
for value in (zone_id, period_id))):
|
for value in (zone_id, period_id))):
|
||||||
@@ -2467,6 +2475,16 @@ async def change_freeform_basis(message_id: int, request: Request):
|
|||||||
import estimate_interactive
|
import estimate_interactive
|
||||||
if answer_basis.revision(saved["content"]) != token:
|
if answer_basis.revision(saved["content"]) != token:
|
||||||
raise HTTPException(409, "Ответ изменён в другой вкладке — обновите диалог")
|
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:
|
try:
|
||||||
zones, _ = await asyncio.to_thread(answer_basis.options_for_label, saved["content"], label)
|
zones, _ = await asyncio.to_thread(answer_basis.options_for_label, saved["content"], label)
|
||||||
except ValueError as exc:
|
except ValueError as exc:
|
||||||
@@ -2483,9 +2501,12 @@ async def change_freeform_basis(message_id: int, request: Request):
|
|||||||
log_action(user, "chat", "POST", f"/api/messages/{message_id}/basis",
|
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)
|
f"tab={tab_id}; zone={zone_id}; period={period_id}", _client_ip(request) or None, 200)
|
||||||
try:
|
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(
|
generated = await asyncio.wait_for(
|
||||||
_generate_freeform_basis_answer(user, tab_id, saved["question"], saved["content"],
|
_generate_freeform_basis_answer(*args, **kwargs), timeout=180)
|
||||||
zone["name"], period["name"]), timeout=180)
|
|
||||||
except TimeoutError as exc:
|
except TimeoutError as exc:
|
||||||
raise HTTPException(504, "Пересчёт не завершился — прежний ответ сохранён") from exc
|
raise HTTPException(504, "Пересчёт не завершился — прежний ответ сохранён") from exc
|
||||||
changed = await asyncio.to_thread(db.replace_scoped_assistant, user, tab_id, message_id,
|
changed = await asyncio.to_thread(db.replace_scoped_assistant, user, tab_id, message_id,
|
||||||
|
|||||||
+55
-4
@@ -365,7 +365,9 @@ button { font-family: inherit; }
|
|||||||
.inline-basis-trigger { border: 0; border-bottom: 1px dotted currentColor; padding: 0; background: transparent; color: var(--accent); font: inherit; cursor: pointer; }
|
.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-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 { 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 { 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-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-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 .inline-basis-apply { color: var(--accent); cursor: pointer; }
|
||||||
.inline-basis-picker .est-basis-error { flex-basis: 100%; }
|
.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; }
|
||||||
@@ -2265,6 +2267,36 @@ function bindFreeformBasis(host) {
|
|||||||
fragment.append(document.createTextNode(node.textContent.slice(start)));
|
fragment.append(document.createTextNode(node.textContent.slice(start)));
|
||||||
node.replaceWith(fragment);
|
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) {
|
async function openFreeformBasis(button, host, label) {
|
||||||
@@ -2296,18 +2328,36 @@ async function openFreeformBasis(button, host, label) {
|
|||||||
if (named) periodSelect.value = String(named.period_id);
|
if (named) periodSelect.value = String(named.period_id);
|
||||||
};
|
};
|
||||||
fillPeriods(); zoneSelect.onchange = fillPeriods;
|
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';
|
const apply = document.createElement('button'); apply.type = 'button';
|
||||||
apply.className = 'inline-basis-apply'; apply.textContent = 'Пересчитать';
|
apply.className = 'inline-basis-apply'; apply.textContent = 'Пересчитать';
|
||||||
const cancel = document.createElement('button'); cancel.type = 'button'; cancel.textContent = 'Отмена';
|
const cancel = document.createElement('button'); cancel.type = 'button'; cancel.textContent = 'Отмена';
|
||||||
cancel.onclick = () => picker.replaceWith(button);
|
cancel.onclick = () => picker.replaceWith(button);
|
||||||
apply.onclick = async () => {
|
apply.onclick = async () => {
|
||||||
if (!periodSelect.value) { periodSelect.focus(); return; }
|
if (!periodSelect.value) { periodSelect.focus(); return; }
|
||||||
picker.querySelectorAll('button, select').forEach(el => { el.disabled = true; });
|
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 = 'Пересчитываю…';
|
apply.textContent = 'Пересчитываю…';
|
||||||
try {
|
try {
|
||||||
const response = await authFetch(url, {method: 'POST', headers: {'Content-Type':'application/json'},
|
const response = await authFetch(url, {method: 'POST', headers: {'Content-Type':'application/json'},
|
||||||
body: JSON.stringify({label, zone_id:Number(zoneSelect.value),
|
body: JSON.stringify({label, zone_id:Number(zoneSelect.value),
|
||||||
period_id:Number(periodSelect.value), revision:options.revision})});
|
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));
|
if (!response.ok) throw new Error(await reasonOrText(response));
|
||||||
const updated = await response.json();
|
const updated = await response.json();
|
||||||
if (requestTab !== tabId || !picker.isConnected) return;
|
if (requestTab !== tabId || !picker.isConnected) return;
|
||||||
@@ -2321,10 +2371,11 @@ async function openFreeformBasis(button, host, label) {
|
|||||||
const err = document.createElement('span'); err.className = 'est-basis-error';
|
const err = document.createElement('span'); err.className = 'est-basis-error';
|
||||||
err.setAttribute('role', 'alert'); err.textContent = e.message || 'Не удалось пересчитать';
|
err.setAttribute('role', 'alert'); err.textContent = e.message || 'Не удалось пересчитать';
|
||||||
picker.appendChild(err);
|
picker.appendChild(err);
|
||||||
picker.querySelectorAll('button, select').forEach(el => { el.disabled = false; });
|
picker.querySelectorAll('button, select, input').forEach(el => { el.disabled = false; });
|
||||||
apply.textContent = 'Пересчитать';
|
apply.textContent = 'Пересчитать';
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
if (normRows.length) picker.append(normSelect, quantity);
|
||||||
picker.append(zoneSelect, periodSelect, apply, cancel);
|
picker.append(zoneSelect, periodSelect, apply, cancel);
|
||||||
button.replaceWith(picker); zoneSelect.focus();
|
button.replaceWith(picker); zoneSelect.focus();
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
|||||||
@@ -96,3 +96,70 @@ def test_incomplete_engine_result_is_never_presented_as_full_total():
|
|||||||
assert "156 066,82 ₽" in text
|
assert "156 066,82 ₽" in text
|
||||||
assert "НР/СП не определены" in text
|
assert "НР/СП не определены" in text
|
||||||
assert "итого по локальной смете" not in text.lower()
|
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)]
|
||||||
|
|||||||
Reference in New Issue
Block a user