diff --git a/db.py b/db.py
index a30ed7a..8005fdd 100644
--- a/db.py
+++ b/db.py
@@ -364,6 +364,16 @@ def init_db():
"updated_at REAL, paid_at REAL, UNIQUE(provider, provider_id))")
conn.execute("CREATE INDEX IF NOT EXISTS idx_topups_user_ts ON topups(username, ts)")
conn.execute("CREATE INDEX IF NOT EXISTS idx_topups_status ON topups(status)")
+ # Рабочее место проверяющего (этап 0, план 21.11.2026): загруженная машиночитаемая
+ # смета и её позиции. Строки — снимком JSON: замечания (этап 1) будут ссылаться на
+ # ключ позиции, а не на номер строки, поэтому пересборка таблицы связи не ломает.
+ conn.execute(
+ "CREATE TABLE IF NOT EXISTS review_docs ("
+ "id INTEGER PRIMARY KEY AUTOINCREMENT, ts REAL NOT NULL, username TEXT NOT NULL, "
+ "filename TEXT NOT NULL, sha256 TEXT NOT NULL, title TEXT, code TEXT, "
+ "path TEXT NOT NULL, rows_json TEXT NOT NULL)")
+ conn.execute("CREATE INDEX IF NOT EXISTS idx_review_docs_user "
+ "ON review_docs(username, id)")
# Что просили у движка смет и что он ответил — пишет ОСНОВНОЙ процесс, а не агент.
# Всё, что лежит в рабочей папке вкладки, агенту доступно на запись: 14.09.2026 он
# переписал файл запрета и выгрузил неполную смету для экспертизы. База ему недоступна.
@@ -1362,6 +1372,31 @@ def get_topup_by_provider(provider: str, provider_id: str) -> dict | None:
return dict(row) if row else None
+def add_review_doc(username: str, filename: str, sha256: str, title: str,
+ code: str, path: str, rows_json: str) -> int:
+ with _conn() as conn:
+ cur = conn.execute(
+ "INSERT INTO review_docs (ts, username, filename, sha256, title, code, path, "
+ "rows_json) VALUES (?,?,?,?,?,?,?,?)",
+ (time.time(), username.lower().strip(), filename, sha256, title, code, path,
+ rows_json))
+ return int(cur.lastrowid)
+
+
+def get_review_doc(doc_id: int) -> dict | None:
+ with _conn() as conn:
+ row = conn.execute("SELECT * FROM review_docs WHERE id = ?", (doc_id,)).fetchone()
+ return dict(row) if row else None
+
+
+def list_review_docs(username: str) -> list[dict]:
+ with _conn() as conn:
+ rows = conn.execute(
+ "SELECT id, ts, filename, title, code FROM review_docs WHERE username = ? "
+ "ORDER BY id DESC", (username.lower().strip(),)).fetchall()
+ return [dict(r) for r in rows]
+
+
def recent_topup_statuses(limit: int) -> list[str]:
"""Статусы последних платежей, новые первыми — сторожу серии отказов платёжки."""
with _conn() as conn:
diff --git a/main.py b/main.py
index 2e3fcfe..ffc76e2 100644
--- a/main.py
+++ b/main.py
@@ -35,7 +35,7 @@ def _закрыть_задачу(job_id: str, статус: str) -> None:
JOBS = JobBoard(on_finish=_закрыть_задачу)
-from fastapi import BackgroundTasks, Depends, FastAPI, HTTPException, Query, Request, Response, UploadFile
+from fastapi import BackgroundTasks, Depends, FastAPI, File, HTTPException, Query, Request, Response, UploadFile
from fastapi.responses import (FileResponse, HTMLResponse, JSONResponse, PlainTextResponse,
StreamingResponse)
from fastapi.staticfiles import StaticFiles
@@ -545,7 +545,7 @@ MAX_MESSAGE_LEN = 10_000
# ⚠️ Версия UI — единый источник. БАМПАТЬ ПРИ КАЖДОМ ДЕПЛОЕ (формат: YYYY-MM-DD + буква).
# Фронт берёт её через GET /api/version (chat.html + admin.html, элемент .app-version).
-APP_VERSION = "2026-11-21m"
+APP_VERSION = "2026-11-21n"
# Audit: path → action name mapping
_AUDIT_MAP = [
@@ -3584,6 +3584,70 @@ async def reviews_report(review_id: int, request: Request):
f"attachment; filename*=UTF-8''{quote(filename)}"})
+# === Рабочее место проверяющего (этап 0, план docs/PLAN_2026-11-21_reviewer_workspace.md) ===
+
+REVIEW_DOC_MAX = 20 * 1024 * 1024 # машиночитаемая смета больше — почти наверняка ошибка
+
+
+@app.post("/api/review/docs")
+async def review_doc_upload(request: Request, file: UploadFile = File(...)):
+ """Машиночитаемая смета .gge → позиции таблицей. Excel и PDF научим позже; всё, что
+ не подошло, объясняем словами, а не пустым экраном."""
+ import gge_tools
+ import hashlib
+ user = _get_user(request)
+ name = (file.filename or "").strip() or "smeta.gge"
+ if not name.lower().endswith(".gge"):
+ raise HTTPException(400, "Пока принимаем машиночитаемые сметы .gge — Excel и PDF "
+ "научим позже")
+ data = await file.read()
+ if not data.strip():
+ raise HTTPException(400, "Файл пустой")
+ if len(data) > REVIEW_DOC_MAX:
+ raise HTTPException(413, f"Файл больше {REVIEW_DOC_MAX // 1024 // 1024} МБ")
+ sha = hashlib.sha256(data).hexdigest()
+ dest_dir = Path(os.environ.get("DATA_DIR", "./smeta-web-data")) / "review_docs" / user
+ dest = dest_dir / f"{sha[:16]}.gge"
+ try:
+ dest_dir.mkdir(parents=True, exist_ok=True)
+ dest.write_bytes(data)
+ parsed = await asyncio.to_thread(gge_tools.parse_gge_file, dest)
+ except Exception as e: # noqa: BLE001 — человеку наблюдаемый факт, подробности в журнал
+ logger.exception("review: файл %s не разобран", name)
+ raise HTTPException(400, f"Файл не разобран: {type(e).__name__}") from None
+ if parsed.get("error"):
+ raise HTTPException(400, "Файл не разобран: " + str(parsed["error"])[:200])
+ rows = parsed.get("positions") or []
+ if not rows:
+ raise HTTPException(400, "В файле не нашлось позиций сметы")
+ did = await asyncio.to_thread(
+ db.add_review_doc, user, name, sha, parsed.get("name") or name,
+ parsed.get("code") or "", str(dest), json.dumps(rows, ensure_ascii=False))
+ log_action(user, "review_upload", "POST", "/api/review/docs",
+ f"№{did} {name}", _client_ip(request), 200)
+ return {"id": did, "title": parsed.get("name") or name,
+ "code": parsed.get("code") or "", "positions": rows}
+
+
+@app.get("/api/review/docs")
+async def review_docs_list(request: Request):
+ """Свои сметы проверяющего — только его."""
+ user = _get_user(request)
+ return {"items": await asyncio.to_thread(db.list_review_docs, user)}
+
+
+@app.get("/api/review/docs/{doc_id}")
+async def review_doc_get(request: Request, doc_id: int):
+ """Смета по номеру: владелец или админ; чужой и несуществующий — одинаково 404."""
+ user = _get_user(request)
+ row = await asyncio.to_thread(db.get_review_doc, doc_id)
+ if not row or (row["username"] != user and not _is_admin(request, user)):
+ raise HTTPException(404, "Документ не найден")
+ return {"id": row["id"], "title": row["title"], "code": row["code"],
+ "filename": row["filename"], "ts": row["ts"],
+ "positions": json.loads(row["rows_json"])}
+
+
@app.get("/review")
async def review_list_page():
"""Заглушка проверяющего закрыта (Хозяин, 21.11.2026): пустая страница без действий.
@@ -3592,6 +3656,14 @@ async def review_list_page():
return RedirectResponse(url="/", status_code=302)
+@app.get("/review/workspace", response_class=HTMLResponse)
+async def review_workspace_page():
+ """Этап 0 рабочего места проверяющего: загрузка .gge и таблица позиций. В шапке ссылки
+ пока нет — страница откроется людям, когда пройдут этапы 1–4 (план в docs/)."""
+ return HTMLResponse(Path("static/review-workspace.html").read_text(encoding="utf-8"),
+ headers={"Cache-Control": "no-store"})
+
+
@app.get("/review/{review_id}")
async def review_page(review_id: int):
from fastapi.responses import RedirectResponse
diff --git a/static/changelog.json b/static/changelog.json
index 81411c1..d8ef9bd 100644
--- a/static/changelog.json
+++ b/static/changelog.json
@@ -1,4 +1,11 @@
[
+ {
+ "version": "2026-11-21n",
+ "date": "2026-11-21",
+ "changes": [
+ "Рабочее место проверяющего: загрузка машиночитаемой сметы .gge и таблица позиций с поиском (первая часть, вход пока скрыт)"
+ ]
+ },
{
"version": "2026-11-21m",
"date": "2026-11-21",
@@ -26,12 +33,5 @@
"changes": [
"После пополнения счёта пробный доступ снимается: значок показывает баланс, а не «4 из 5 вопросов»"
]
- },
- {
- "version": "2026-11-21h",
- "date": "2026-11-21",
- "changes": [
- "Кнопка-остаток в шапке стала зелёной — сразу видно, сколько осталось"
- ]
}
]
diff --git a/static/review-workspace.html b/static/review-workspace.html
new file mode 100644
index 0000000..138eb13
--- /dev/null
+++ b/static/review-workspace.html
@@ -0,0 +1,151 @@
+
+
+
+
+
+Рабочее место проверяющего
+
+
+
+
+
+
+
+
+
+
+
+
+ | № | Шифр | Наименование | Ед. |
+ Объём | Стоимость, ₽ |
+ | Загрузка… |
+
+
+
+
+
+
diff --git a/tests/fixtures/review_small.gge b/tests/fixtures/review_small.gge
new file mode 100644
index 0000000..36ac27a
--- /dev/null
+++ b/tests/fixtures/review_small.gge
@@ -0,0 +1,38 @@
+
+
+
+ ЛС-01
+ Смета для проверки замечаний
+ -
+
+ Разработка грунта с погрузкой
+
01-01-001-01
+ 100
+ м3
+ 15050.00
+ 15050.00
+
+
+ -
+
+ Устройство фундаментов
+
06-01-001-02
+ 20
+ м3
+ 100000.00
+ 100000.00
+
+
+ -
+
+ Монтаж каркаса
+
09-03-001-01
+ 5
+ т
+ 80000.00
+ 80000.00
+
+
+
+
diff --git a/tests/test_review_workspace_api.py b/tests/test_review_workspace_api.py
new file mode 100644
index 0000000..b2f8b7f
--- /dev/null
+++ b/tests/test_review_workspace_api.py
@@ -0,0 +1,101 @@
+"""Рабочее место проверяющего, этап 0: загрузка машиночитаемой сметы и её позиции.
+
+План — docs/PLAN_2026-11-21_reviewer_workspace.md. Приёмка этапа: файл .gge
+загружается, позиции возвращаются таблицей, чужой не видит документ, пустой и битый
+файл объясняются словами. Программа на компьютере эксперта не нужна.
+
+Mutation: не проверять владельца — падает «чужой не видит»; не проверять расширение —
+падает отказ битому файлу; не сохранять строки — падает выдача.
+"""
+import importlib
+import io
+import os
+import sys
+from pathlib import Path
+
+import pytest
+
+ROOT = Path(__file__).resolve().parent.parent
+sys.path.insert(0, str(ROOT))
+FIX = ROOT / "tests" / "fixtures" / "review_small.gge"
+
+
+@pytest.fixture()
+def env(tmp_path, monkeypatch):
+ monkeypatch.setenv("DB_PATH", str(tmp_path / "t.db"))
+ monkeypatch.setenv("DATA_DIR", str(tmp_path / "data"))
+ monkeypatch.setenv("SESSION_SECRET", "test-secret")
+ monkeypatch.setenv("AI_BACKEND", "claude")
+ monkeypatch.chdir(ROOT)
+ import auth
+ import db
+ import main
+ for m in (db, auth, main):
+ importlib.reload(m)
+ db.init_db()
+ for u in ("checker@x", "other@x"):
+ db.create_user(u, "h")
+ db.admin_verify_user(u)
+ from fastapi.testclient import TestClient
+ client = TestClient(main.app)
+ return db, auth, client
+
+
+def _h(auth, user="checker@x"):
+ return {"Authorization": "Bearer " + auth._make_token(user)}
+
+
+def _upload(client, auth, name="ЛС-01.gge", data=None, user="checker@x"):
+ body = data if data is not None else FIX.read_bytes()
+ return client.post("/api/review/docs", headers=_h(auth, user),
+ files={"file": (name, io.BytesIO(body),
+ "application/octet-stream")})
+
+
+def test_upload_returns_positions(env):
+ db, auth, client = env
+ r = _upload(client, auth)
+ assert r.status_code == 200, r.text
+ d = r.json()
+ assert d["title"] == "Смета для проверки замечаний" and d["code"] == "ЛС-01"
+ assert [p["code"] for p in d["positions"]] == ["01-01-001-01", "06-01-001-02",
+ "09-03-001-01"]
+ first = d["positions"][0]
+ assert first["unit"] == "м3" and first["quantity"] == 100
+ assert client.get(f"/api/review/docs/{d['id']}", headers=_h(auth)).json()["positions"]
+ assert [x["id"] for x in client.get("/api/review/docs", headers=_h(auth)).json()["items"]] == [d["id"]]
+
+
+def test_foreign_checker_cannot_see_document(env):
+ db, auth, client = env
+ did = _upload(client, auth).json()["id"]
+ assert client.get(f"/api/review/docs/{did}", headers=_h(auth, "other@x")).status_code == 404
+ assert client.get("/api/review/docs", headers=_h(auth, "other@x")).json()["items"] == []
+
+
+def test_wrong_and_broken_files_explained(env):
+ db, auth, client = env
+ r = _upload(client, auth, name="smeta.xlsx", data=b"PK\x03\x04")
+ assert r.status_code == 400 and ".gge" in r.text
+ r = _upload(client, auth, data=b"1x'
+ r = _upload(client, auth, data=empty)
+ assert r.status_code == 400 and "позиц" in r.text.lower()
+
+
+def test_upload_requires_login(env):
+ db, auth, client = env
+ r = client.post("/api/review/docs", files={"file": ("x.gge", io.BytesIO(FIX.read_bytes()))})
+ assert r.status_code == 401
+
+
+def test_workspace_page_has_real_actions_only(env):
+ """Страница этапа 0 — не заглушка: загрузка, поиск и таблица; никакой программы на
+ компьютере и кодов подключения (это и была «залепуха», Хозяин 21.11.2026)."""
+ html = (ROOT / "static" / "review-workspace.html").read_text(encoding="utf-8")
+ for text in ("Загрузить смету", 'accept=".gge"', 'id="search"', "Стоимость, ₽",
+ "/api/review/docs"):
+ assert text in html, text
+ for лишнее in ("Получить код", "программа", "Программа"):
+ assert лишнее not in html, лишнее