Stage isolated engine price catalog for inline zone choices
This commit is contained in:
@@ -62,6 +62,21 @@ prod_ext=${prod_ext:-$prod_data/_external}
|
||||
stage_ext=${stage_ext:-$stage_data/_external}
|
||||
test "${prod_ext#/}" != "$prod_ext" && test "${stage_ext#/}" != "$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])' \
|
||||
"$prod_ext" "$stage_ext/landing_documents.json"
|
||||
export SMETA_PROJECT_DIR="$stage-norms"
|
||||
|
||||
@@ -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}")
|
||||
+12
-2
@@ -376,6 +376,7 @@ button { font-family: inherit; }
|
||||
.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; }
|
||||
@@ -2338,6 +2339,13 @@ async function openFreeformBasis(button, host, label) {
|
||||
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 = '';
|
||||
@@ -2345,8 +2353,10 @@ async function openFreeformBasis(button, host, label) {
|
||||
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 => (host._rawText || '').includes(p.name));
|
||||
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 || [];
|
||||
@@ -2397,7 +2407,7 @@ async function openFreeformBasis(button, host, label) {
|
||||
}
|
||||
};
|
||||
if (normRows.length) picker.append(normSelect, quantity);
|
||||
picker.append(zoneSelect, periodSelect, apply, cancel);
|
||||
picker.append(zoneSelect, periodSelect, apply, cancel, periodNote);
|
||||
button.replaceWith(picker); zoneSelect.focus();
|
||||
} catch (e) {
|
||||
button.disabled = false;
|
||||
|
||||
@@ -144,11 +144,13 @@ def test_plain_answer_zone_changes_inside_its_bubble(browser, site):
|
||||
}
|
||||
return oldFetch(url,opts);
|
||||
};
|
||||
const answer = addMsg('ai','Норма ГЭСНм 10-08-002-02, объём работ = 100 шт.\\nВыберите ценовую зону:\\n1. Хабаровский край (1 зона)\\n2. Хабаровский край (2 зона)');
|
||||
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"))
|
||||
|
||||
@@ -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)
|
||||
Reference in New Issue
Block a user