Files
smeta-web/tests/test_inline_compare.py

151 lines
8.5 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""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