Files
smeta-web/tests/test_tsn_price_book.py
anorandClaude Code 016a5ea9a5 fix(ТСН): перебазировку отличаем по заголовку раздела, а не по слову в содержании
Признак раздела включался со страницы содержания и перекрашивал весь справочник:
38 строк перебазировки и одна честно битая строка (в PDF «227,6S»). Теперь раздел
узнаётся по заголовку с шапкой «№№ позиций»/«Сметная стоимость».

Co-Authored-By: Claude Code <noreply@anthropic.com>
2026-11-18 04:42:02 +10:00

165 lines
7.5 KiB
Python

"""Разбор ценовых справочников ТСН-2001.1 (материалы) и .2 (машины).
Колонки измерены по настоящим PDF: позиция x≈57/62, код 99/101, наименование с 156,
единица 377, нетто 410, брутто 452, цена 499 (материалы); цена 359, оплата труда 420
(машины). Проверки идут на PDF, собранном тем же PyMuPDF с этими координатами: они
держат раскладку колонок, а не «примерные» числа.
Шифр ресурса — «книга.позиция»: позиция 1-1-44 в справочнике .1 — это ресурс
1.1-1-44 в сборниках расценок (сверено на «Ветошь»: позиция 1-1-115 = 1,61 руб.).
"""
import os
import sys
import fitz
import pytest
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
if ROOT not in sys.path:
sys.path.insert(0, ROOT)
import tsn_parse # noqa: E402
X_POS, X_CODE, X_NAME, X_UNIT = 57, 99, 156, 377
X_NET, X_GROSS, X_PRICE = 410, 452, 499
X_MPRICE, X_MOT = 359, 420
def _pdf(tmp_path, rows):
"""rows: [(y, [(x, text), ...]), ...]"""
doc = fitz.open()
page = doc.new_page(width=595, height=842)
for y, words in rows:
for x, text in words:
page.insert_text((x, y), text, fontsize=8)
path = tmp_path / "book.pdf"
doc.save(str(path))
doc.close()
return str(path)
def _material_row(y, pos, okp, name, unit, net, gross, price):
words = [(X_POS, pos), (X_CODE, okp), (X_NAME, name),
(X_UNIT, unit), (X_NET, net), (X_GROSS, gross)]
if price:
words.append((X_PRICE, price))
return (y, words)
def test_material_row_becomes_resource_with_price(tmp_path):
path = _pdf(tmp_path, [
_material_row(100, "1-1-44", "0256120001", "BN, road", "t", "1000,00", "1020,00", "3389,74"),
])
got = tsn_parse.parse_price_book(path, {"book": "ТСН-2001.1"})
assert got["stats"]["rows_seen"] == 1
item = got["items"][0]
assert item["code"] == "1.1-1-44"
assert item["unit"] == "t"
assert item["price"] == pytest.approx(3389.74)
def test_number_inside_name_is_not_a_price(tmp_path):
path = _pdf(tmp_path, [
_material_row(100, "1-1-313", "1250020001", "Ropes 1x3, diameter 3", "t", "1000,00", "1000,00", "16728,62"),
])
got = tsn_parse.parse_price_book(path, {"book": "ТСН-2001.1"})
assert got["items"][0]["price"] == pytest.approx(16728.62)
assert "diameter" in got["items"][0]["name"]
def test_wrapped_name_is_joined_and_price_from_number_line(tmp_path):
path = _pdf(tmp_path, [
(100, [(X_POS, "1-1-2076"), (X_CODE, "2484240004"), (X_NAME, "Vandex DPC")]),
(112, [(X_NAME, "silicone sealant for")]),
(124, [(X_NAME, "waterproofing"), (X_UNIT, "l"), (X_NET, "1,01"),
(X_GROSS, "1,02"), (X_PRICE, "95,13")]),
])
got = tsn_parse.parse_price_book(path, {"book": "ТСН-2001.1"})
item = got["items"][0]
assert item["price"] == pytest.approx(95.13)
assert item["unit"] == "l"
assert "Vandex" in item["name"] and "waterproofing" in item["name"]
def test_row_without_price_goes_to_quarantine(tmp_path):
path = _pdf(tmp_path, [
_material_row(100, "1-1-45", "0256120002", "BND, road", "t", "1000,00", "1020,00", None),
])
got = tsn_parse.parse_price_book(path, {"book": "ТСН-2001.1"})
assert got["items"] == []
assert got["quarantine"] and got["quarantine"][0]["code"] == "1-1-45"
assert "цена" in got["quarantine"][0]["reason"]
def test_section_heading_is_not_an_item(tmp_path):
path = _pdf(tmp_path, [
(90, [(X_NAME, "Bitumens, grade:")]),
_material_row(110, "1-1-44", "0256120001", "BN", "t", "1000,00", "1020,00", "3389,74"),
])
got = tsn_parse.parse_price_book(path, {"book": "ТСН-2001.1"})
assert len(got["items"]) == 1
def test_machine_row_takes_price_column_not_labour(tmp_path):
path = _pdf(tmp_path, [
(100, [(62, "1-1-60"), (101, "014001"), (137, "8,0"),
(X_MPRICE, "213,44"), (X_MOT, "40,20")]),
])
got = tsn_parse.parse_price_book(path, {"book": "ТСН-2001.2"})
item = got["items"][0]
assert item["code"] == "2.1-1-60"
assert item["price"] == pytest.approx(213.44), "оплата труда не должна стать ценой"
assert item["unit"] == "маш.-ч"
def test_negative_price_goes_to_quarantine(tmp_path):
path = _pdf(tmp_path, [
_material_row(100, "1-1-46", "0256110001", "MG", "t", "1000,00", "1000,00", "-5,00"),
])
got = tsn_parse.parse_price_book(path, {"book": "ТСН-2001.1"})
assert got["items"] == [] and got["quarantine"]
def test_unit_with_count_is_kept_whole(tmp_path):
"""«100 шт.» — единица целиком: число в окне единицы не отбрасывается, иначе
цена 69,01 приписывается одной штуке вместо сотни."""
path = _pdf(tmp_path, [
(100, [(X_POS, "7-1-43"), (X_CODE, "4596010010"), (X_NAME, "screw 5x20"),
(370, "100"), (390, "sht."), (425, "0,40"), (466, "0,40"), (506, "69,01")]),
])
got = tsn_parse.parse_price_book(path, {"book": "ТСН-2001.1"})
assert got["items"][0]["unit"] == "100 sht."
def test_name_tail_does_not_become_unit():
"""Хвост названия, заехавший в колонку единицы («м3 по»), не должен стать единицей."""
assert tsn_parse._unit_of_tokens(["м3", "по"]) == "м3"
assert tsn_parse._unit_of_tokens(["100", "шт."]) == "100 шт."
assert tsn_parse._unit_of_tokens(["компл,"]) == "компл."
assert tsn_parse._unit_of_tokens(["по"]) == ""
def test_name_keeps_numbers(tmp_path):
"""Числа в наименовании («Труба 100 мм») — часть названия, а не мусор."""
path = _pdf(tmp_path, [
(100, [(X_POS, "1-1-1"), (X_CODE, "5744150001"), (156, "Pipe"), (200, "100"),
(230, "mm"), (X_UNIT, "m"), (X_NET, "1,00"), (X_GROSS, "1,00"),
(X_PRICE, "10,00")]),
])
got = tsn_parse.parse_price_book(path, {"book": "ТСН-2001.1"})
assert got["items"][0]["name"] == "Pipe 100 mm", got["items"][0]["name"]
def test_relocation_section_rows_get_honest_reason():
"""Таблица «Стоимость перебазировки» — это не цена за маш.-ч: строка в карантин
с причиной, объясняющей отказ, а не «цена не найдена»."""
heading = "Раздел 2. Стоимость перебазировки машин. №№ позиций"
assert tsn_parse._price_missing_reason(heading) \
== "раздел перебазировки: это стоимость перебазировки, не цена за маш.-ч"
# упоминание в содержании — не раздел
assert tsn_parse._price_missing_reason(
"Раздел 2. Стоимость перебазировки машин ........ 30") == "цена не найдена"
assert tsn_parse._price_missing_reason("Сметные цены эксплуатации машин") == "цена не найдена"
# продолжение раздела на следующей странице без заголовка
assert "перебазиров" in tsn_parse._price_missing_reason("", in_relocation=True)