diff --git a/claude_bridge.py b/claude_bridge.py index ef0267e..3832527 100644 --- a/claude_bridge.py +++ b/claude_bridge.py @@ -127,7 +127,7 @@ def clear_session(username: str, tab_id: str): ALLOWED_EXTENSIONS = { ".xlsx", ".xlsm", ".xlsb", ".xls", ".ods", ".docx", ".doc", ".pdf", ".csv", ".txt", ".xml", ".json", ".yaml", ".yml", - ".gge", ".gsfx", ".esw", ".ges", ".smr", ".smt", # smeta programs: ГРАНД-Смета, Smeta.RU + ".gge", ".gsfx", ".arp", ".arps", ".esw", ".ges", ".smr", ".smt", # smeta programs: ГРАНД-Смета, Smeta.RU ".zip", ".rar", ".7z", } diff --git a/claude_bridge_glm.py b/claude_bridge_glm.py index 97461aa..b3ae491 100644 --- a/claude_bridge_glm.py +++ b/claude_bridge_glm.py @@ -190,7 +190,7 @@ def clear_session(username: str, tab_id: str): ALLOWED_EXTENSIONS = { ".xlsx", ".xlsm", ".xlsb", ".xls", ".ods", ".docx", ".doc", ".pdf", ".csv", ".txt", ".xml", ".json", ".yaml", ".yml", - ".gge", ".gsfx", ".esw", ".ges", ".smr", ".smt", + ".gge", ".gsfx", ".arp", ".arps", ".esw", ".ges", ".smr", ".smt", ".zip", ".rar", ".7z", } @@ -373,6 +373,15 @@ def _read_work_dir_files(work_dir: Path, max_chars: int = 150000) -> str: f"Регион: {g['region']} | Итог: {g['total']} руб | позиций: {g['positions_count']}\n{poss}") parts.append(chunk) total += len(chunk) + elif ext in (".arp", ".arps"): + from gge_tools import parse_arp_file + a = parse_arp_file(f) + poss = "\n".join(f" {p['code']} | {p['name'][:80]} | {p['unit']} | {p['total']} руб" + for p in a["positions"][:40]) + chunk = (f"\n### Смета .arp: {f.name}\nШифр: {a['code']} | {a['name']}\n" + f"Итог: {a['total']} руб | позиций: {a['positions_count']}\n{poss}") + parts.append(chunk) + total += len(chunk) elif ext in _UNSUPPORTED_SMETA: parts.append(f"\n### Файл: {f.name} (формат {ext} проприетарный, " f"автоматически не читается — экспортируйте смету в АРПС (.arp) или Excel)") diff --git a/gge_tools.py b/gge_tools.py index 4a3ada1..4b844c6 100644 --- a/gge_tools.py +++ b/gge_tools.py @@ -249,6 +249,53 @@ def parse_gsfx_file(path: Path) -> dict: } +def parse_arp_file(path: Path) -> dict: + """Разобрать .arp/.arps (АРПС 1.10 — открытый текстовый формат обмена смет, + Smeta.RU / ПК АВС). Кодировка cp866, поля через '#', первое поле = тип записи. + + Тип 3 — шапка сметы: [4]=шифр, [5]=название, [14]=итог. + Тип 20 — позиция: [2]=обоснование (первый токен = шифр расценки), [3]=ед.изм, + [4]=наименование, [15]=стоимость позиции. Объём НЕ извлекаем — его поле в АРПС + неоднозначно, лучше не давать выдуманное число. + """ + try: + raw = Path(path).read_bytes() + except OSError as e: + return {'error': f'{type(e).__name__}: {e}', 'path': str(path)} + text = raw.decode('cp866', 'replace') + code = name = '' + total = 0.0 + positions: list[dict] = [] + for line in text.splitlines(): + if not line or '#' not in line: + continue + f = line.split('#') + rec = f[0] + if rec == '3' and len(f) > 5: + code = f[4].strip() + name = f[5].strip() + if len(f) > 14: + total = _ru_float(f[14]) + elif rec == '20' and len(f) > 4: + just = f[2].strip() + pcode = just.split(' ')[0] if just else '' + unit = f[3].strip() + pname = f[4].strip() + ptotal = _ru_float(f[15]) if len(f) > 15 else 0.0 + if pname or pcode: + positions.append({'code': pcode, 'name': pname, + 'unit': unit, 'total': ptotal}) + return { + 'path': str(path), + 'format': 'arp', + 'code': code, + 'name': name, + 'total': total, + 'positions_count': len(positions), + 'positions': positions, + } + + def index_gge_directory(dir_path: Path, save_index_to: Path | None = None) -> dict: """Пройти все .gge в dir_path рекурсивно, распарсить. diff --git a/main.py b/main.py index ad2d96c..8e3e679 100644 --- a/main.py +++ b/main.py @@ -138,7 +138,7 @@ MAX_MESSAGE_LEN = 10_000 # ⚠️ Версия UI — единый источник. БАМПАТЬ ПРИ КАЖДОМ ДЕПЛОЕ (формат: YYYY-MM-DD + буква). # Фронт берёт её через GET /api/version (chat.html + admin.html, элемент .app-version). -APP_VERSION = "2026-07-15e" +APP_VERSION = "2026-07-15f" # Audit: path → action name mapping _AUDIT_MAP = [ diff --git a/smeta_mcp.py b/smeta_mcp.py index 5fcb8dd..1258fcb 100644 --- a/smeta_mcp.py +++ b/smeta_mcp.py @@ -294,6 +294,30 @@ def tool_parse_gsfx_file(*, filename: str, max_positions: int = 30) -> dict: return data +def tool_parse_arp_file(*, filename: str, max_positions: int = 30) -> dict: + """Распарсить одну .arp/.arps смету (АРПС 1.10 — Smeta.RU / ПК АВС, текстовый). + Возвращает: code, name, total (итог сметы), позиции (code=шифр, name, unit, + total=стоимость позиции). Родной формат обмена Smeta.RU — раньше не читался. + """ + user, tab = _user_tab() + work_dir = _work_dir(user, tab) + candidate = work_dir / filename + if not candidate.exists(): + matches = list(work_dir.rglob(Path(filename).name)) + if not matches: + return {"error": f"«{filename}» не найден в {user}/{tab}"} + candidate = matches[0] + from gge_tools import parse_arp_file + data = parse_arp_file(candidate) + if 'error' in data: + return data + if len(data['positions']) > max_positions: + data['positions_total'] = len(data['positions']) + data['positions'] = data['positions'][:max_positions] + data['positions_truncated'] = True + return data + + def tool_update_xlsx_cells(*, filename: str, sheet: str, updates: list, out_filename: str | None = None) -> dict: """Массовая запись ячеек в xlsx. Универсальный tool — годится для @@ -514,6 +538,23 @@ TOOLS: dict[str, dict] = { "required": ["filename"], }, }, + "parse_arp_file": { + "fn": tool_parse_arp_file, + "description": ( + "Распарсить одну .arp/.arps смету (АРПС 1.10 — формат обмена Smeta.RU / " + "ПК АВС, текстовый). Возвращает: code (шифр), name, total (итог сметы, руб), " + "positions (code=шифр расценки, name, unit, total=стоимость позиции). " + "ИСПОЛЬЗУЙ для файлов .arp/.arps — родной формат Smeta.RU." + ), + "inputSchema": { + "type": "object", + "properties": { + "filename": {"type": "string", "description": "Путь к .arp относительно work_dir (или basename)"}, + "max_positions": {"type": "integer", "description": "Лимит позиций (default 30)"}, + }, + "required": ["filename"], + }, + }, "update_xlsx_cells": { "fn": tool_update_xlsx_cells, "description": ( diff --git a/tests/test_arp.py b/tests/test_arp.py new file mode 100644 index 0000000..4459d03 --- /dev/null +++ b/tests/test_arp.py @@ -0,0 +1,65 @@ +"""Юнит-тест parse_arp_file на синтетическом АРПС 1.10 (cp866, поля через '#'). +Реальный .arp — на сервере. Mutation-safe: сломай индекс поля кода → assert упадёт.""" +import os +import sys +import tempfile +from pathlib import Path + +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) +from gge_tools import parse_arp_file + +ARP = "\r\n".join([ + "1#АРПС 1.10#Программный комплекс АВС#2022.2.1", + "0#Метод расчета#базисный#", + "3####00-02-7-00-01Р#Контактная сеть станции Находка#######Иванов#Петров#6105760,71#0", + "10#0#1# Строительные работы ", + "20#1#01-02-058-03 ОЕРЖ-2001 от 25.04.2015#100 м3 грунта#Копание ям вручную без креплений#4167,54#4167,54#0#0#0#0###411,0##43559,13#43559,13", + "25#4#0#0#1,3#Кзп#", + "20#2#28-02-013-01 ОЕРЖ-2001#1 опора#Установка опор с пути#100#100#0#0#0#0###5##2500,00#2500,00", +]) + "\r\n" + + +def _make_arp(d: Path) -> Path: + p = d / "смета.arp" + p.write_bytes(ARP.encode("cp866")) + return p + + +def test_header(): + r = parse_arp_file(_make_arp(Path(tempfile.mkdtemp()))) + assert "error" not in r, r + assert r["code"] == "00-02-7-00-01Р", r + assert r["name"] == "Контактная сеть станции Находка", r + assert abs(r["total"] - 6105760.71) < 0.01, r + + +def test_positions(): + r = parse_arp_file(_make_arp(Path(tempfile.mkdtemp()))) + assert r["positions_count"] == 2, r + p0 = r["positions"][0] + assert p0["code"] == "01-02-058-03", p0 # первый токен обоснования + assert p0["unit"] == "100 м3 грунта", p0 + assert "Копание ям" in p0["name"], p0 + assert abs(p0["total"] - 43559.13) < 0.01, p0 + + +def test_bad_file(): + d = Path(tempfile.mkdtemp()) + p = d / "x.arp" + p.write_bytes(b"\xff\xfe not arps") + r = parse_arp_file(p) + # не падает; просто нет позиций/шапки + assert r["positions_count"] == 0, r + + +if __name__ == "__main__": + import traceback + fns = [v for k, v in sorted(globals().items()) if k.startswith("test_") and callable(v)] + failed = 0 + for fn in fns: + try: + fn(); print(f" ok: {fn.__name__}") + except Exception: + failed += 1; print(f" FAIL: {fn.__name__}"); traceback.print_exc() + print("ALL PASS" if not failed else f"{failed} FAILED") + sys.exit(failed) diff --git a/tests/test_arp_server.py b/tests/test_arp_server.py new file mode 100644 index 0000000..56b787e --- /dev/null +++ b/tests/test_arp_server.py @@ -0,0 +1,27 @@ +"""Real-тест parse_arp_file на настоящем .arp (гонять на dev2).""" +import shutil +import sys +import tempfile +import zipfile +from pathlib import Path + +from gge_tools import parse_arp_file + +SRC = Path("/home/mcp-user/smeta-web-data/smeta/b1f47437-2254-4267-a584-4d2ea050e100/11900.zip") + +tmp = Path(tempfile.mkdtemp()) +with zipfile.ZipFile(SRC) as z: + name = next(n for n in z.namelist() if n.lower().endswith(".arp")) + p = tmp / "s.arp" + p.write_bytes(z.read(name)) + +r = parse_arp_file(p) +assert "error" not in r, r +print(f" code={r['code']} | total={r['total']} | positions={r['positions_count']}") +assert r["code"], "нет шифра сметы" +assert r["positions_count"] > 0, r +p0 = r["positions"][0] +assert p0["code"] and p0["name"] and p0["unit"], p0 +print(f" пример: {p0}") +shutil.rmtree(tmp, ignore_errors=True) +print("ALL PASS")