fix(security): блок ② — убран депрекированный пакетный путь (exec на хосте)
По решению пользователя вместо песочницы — retire всего депрекированного пакетного пути (страницы давно заменены чатом). Устраняет P0: batch v2/v3 исполняли СГЕНЕРИРОВАННЫЙ ИИ по загруженной смете скрипт через exec() прямо в процессе сервера (prompt-injection в смете контрагента → доступ к .env/БД/файлам всех). - Удалены роуты: /api/batch-v2/*, /api/batch-v3/*, /api/ssr/*, /api/check/yaml, /api/gen/calculate, /api/gen/download + смонтированные /api/gen|ref|wizard. - Страницы /batch|batch2|batch3|ssr|wizard|generate|reference|check → 302 на /. - Удалены мёртвые модули batch.py (exec:393 + code-injection через имя листа) и batch_v3.py (три exec-точки), их HTML-страницы (заодно ушёл их XSS-surface). - get_work_dir/ownership-хелперы для batch больше не нужны, но оставлены (dead, безвредны) — точечная зачистка отдельно. Живой чат путь не затронут (batch_v3/extract_zip импортились только депрекированными эндпоинтами). Тесты: pages→302, api→404. 297 passed. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -1,416 +0,0 @@
|
||||
"""Batch processor: LLM analyzes structure, generates script, runs on all files.
|
||||
|
||||
Flow:
|
||||
1. User uploads zip (smetas) + target xlsx (summary)
|
||||
2. Server extracts, reads 3 sample files via XML
|
||||
3. GLM analyzes structure → generates Python processing script
|
||||
4. User confirms (or corrects)
|
||||
5. Script runs on ALL files without LLM
|
||||
6. Result: updated target xlsx + error log
|
||||
"""
|
||||
|
||||
import csv
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import tempfile
|
||||
import time
|
||||
import traceback
|
||||
import zipfile
|
||||
import xml.etree.ElementTree as ET
|
||||
from pathlib import Path
|
||||
|
||||
import httpx
|
||||
|
||||
ZAI_API_KEY = os.environ.get("ZAI_API_KEY", "")
|
||||
ZAI_BASE_URL = os.environ.get("ZAI_BASE_URL", "https://open.bigmodel.cn/api/coding/paas/v4")
|
||||
try:
|
||||
import model_registry
|
||||
ZAI_MODEL = model_registry.model_id("batch") # единый реестр (env ZAI_MODEL override)
|
||||
except Exception: # noqa: BLE001 — fail-soft
|
||||
ZAI_MODEL = os.environ.get("ZAI_MODEL", "glm-5.1")
|
||||
|
||||
# Batch jobs storage
|
||||
_jobs: dict[str, dict] = {}
|
||||
|
||||
|
||||
def read_xlsx_xml(path: str, max_rows: int = 50) -> dict:
|
||||
"""Read xlsx via XML (handles broken styles). Returns {sheet_name: [[row], ...]}."""
|
||||
result = {}
|
||||
try:
|
||||
z = zipfile.ZipFile(path)
|
||||
ns = {'s': 'http://schemas.openxmlformats.org/spreadsheetml/2006/main'}
|
||||
# Shared strings
|
||||
strings = []
|
||||
try:
|
||||
ss = ET.parse(z.open('xl/sharedStrings.xml')).getroot()
|
||||
for si in ss.findall('.//s:si', ns):
|
||||
strings.append(''.join(t.text or '' for t in si.findall('.//s:t', ns)))
|
||||
except KeyError:
|
||||
pass
|
||||
# Sheet names and rels
|
||||
wb = ET.parse(z.open('xl/workbook.xml')).getroot()
|
||||
rels = ET.parse(z.open('xl/_rels/workbook.xml.rels')).getroot()
|
||||
# Parse rels regardless of namespace
|
||||
rid_map = {}
|
||||
for r in rels.iter():
|
||||
rid = r.get('Id', '')
|
||||
tgt = r.get('Target', '')
|
||||
if rid and tgt:
|
||||
rid_map[rid] = tgt
|
||||
|
||||
for sheet in wb.findall('.//s:sheet', ns):
|
||||
name = sheet.get('name', '')
|
||||
rid = sheet.attrib.get('{http://schemas.openxmlformats.org/officeDocument/2006/relationships}id', '')
|
||||
target = rid_map.get(rid, '')
|
||||
if not target:
|
||||
continue
|
||||
# Normalize path (handle leading / or relative)
|
||||
if target.startswith('/'):
|
||||
sheet_path = target.lstrip('/')
|
||||
elif target.startswith('xl/'):
|
||||
sheet_path = target
|
||||
else:
|
||||
sheet_path = f'xl/{target}'
|
||||
try:
|
||||
sheet_xml = ET.parse(z.open(sheet_path)).getroot()
|
||||
except KeyError:
|
||||
continue
|
||||
rows = []
|
||||
for row_el in sheet_xml.findall('.//s:row', ns):
|
||||
row_num = int(row_el.get('r', len(rows) + 1))
|
||||
# Pad with empty rows if needed
|
||||
while len(rows) < row_num - 1:
|
||||
rows.append([])
|
||||
if len(rows) >= max_rows:
|
||||
break
|
||||
# Parse cells with proper column positions
|
||||
row_data = [''] * 26 # A-Z
|
||||
for c in row_el.findall('s:c', ns):
|
||||
ref = c.get('r', '') # e.g. "B5", "H29"
|
||||
cell_type = c.get('t', '')
|
||||
v = c.find('s:v', ns)
|
||||
val = v.text if v is not None else ''
|
||||
if cell_type == 's' and val.isdigit():
|
||||
idx = int(val)
|
||||
val = strings[idx] if idx < len(strings) else val
|
||||
elif cell_type == 'inlineStr':
|
||||
# Inline string: <is><t>text</t></is>
|
||||
is_el = c.find('s:is', ns)
|
||||
if is_el is not None:
|
||||
val = ''.join(t.text or '' for t in is_el.findall('.//s:t', ns))
|
||||
# Extract column index from ref (A=0, B=1, ..., H=7)
|
||||
col_letters = ''.join(ch for ch in ref if ch.isalpha())
|
||||
col_idx = 0
|
||||
for ch in col_letters.upper():
|
||||
col_idx = col_idx * 26 + (ord(ch) - ord('A'))
|
||||
if col_idx < len(row_data):
|
||||
row_data[col_idx] = val
|
||||
# Trim trailing empty cells
|
||||
while row_data and row_data[-1] == '':
|
||||
row_data.pop()
|
||||
rows.append(row_data)
|
||||
result[name] = rows
|
||||
z.close()
|
||||
except Exception as e:
|
||||
result['_error'] = str(e)
|
||||
return result
|
||||
|
||||
|
||||
def extract_zip(zip_path: str, dest_dir: str) -> list[str]:
|
||||
"""Extract zip and return list of xlsx files.
|
||||
|
||||
Handles Cyrillic filenames: Python's zipfile decodes names as CP437
|
||||
when the UTF-8 flag is not set. We detect and fix this.
|
||||
"""
|
||||
with zipfile.ZipFile(zip_path) as z:
|
||||
for info in z.infolist():
|
||||
# Fix Cyrillic filenames: if flag bit 11 is not set,
|
||||
# Python decodes as CP437 — re-encode and decode as UTF-8
|
||||
if not (info.flag_bits & 0x800):
|
||||
try:
|
||||
fixed = info.filename.encode('cp437').decode('utf-8')
|
||||
info.filename = fixed
|
||||
except (UnicodeDecodeError, UnicodeEncodeError):
|
||||
pass # keep original if re-decode fails
|
||||
# Skip macOS resource fork files and __MACOSX directory
|
||||
basename = Path(info.filename).name
|
||||
if basename.startswith('._') or '__MACOSX' in info.filename:
|
||||
continue
|
||||
z.extract(info, dest_dir)
|
||||
# Collect all supported smeta file types
|
||||
SMETA_EXTENSIONS = {'.xlsx', '.xls', '.gge', '.esw', '.xml'}
|
||||
files = []
|
||||
for f in Path(dest_dir).rglob('*'):
|
||||
if f.is_file() and f.suffix.lower() in SMETA_EXTENSIONS \
|
||||
and not f.name.startswith('~$') and not f.name.startswith('._'):
|
||||
files.append(str(f))
|
||||
return sorted(files)
|
||||
|
||||
|
||||
async def analyze_structure(sample_files: list[str], target_file: str, task_description: str) -> dict:
|
||||
"""Use LLM to analyze file structure and generate processing script."""
|
||||
# Read samples — head + tail to see structure AND totals
|
||||
samples = []
|
||||
for f in sample_files[:3]:
|
||||
data = read_xlsx_xml(f, max_rows=999)
|
||||
sample = {'filename': Path(f).name, 'sheets': {}}
|
||||
for k, v in data.items():
|
||||
if k == '_error':
|
||||
continue
|
||||
head = v[:15]
|
||||
tail = v[-50:] if len(v) > 50 else v[15:]
|
||||
# Compact: only non-empty rows
|
||||
head_compact = [[j, row[j]] for row in head for j in range(len(row)) if row[j]]
|
||||
tail_compact = []
|
||||
for i, row in enumerate(tail):
|
||||
row_idx = len(v) - len(tail) + i
|
||||
cells = [[j, row[j]] for j in range(len(row)) if row[j]]
|
||||
if cells:
|
||||
tail_compact.append({'row': row_idx, 'cells': cells[:6]})
|
||||
sample['sheets'][k] = {
|
||||
'total_rows': len(v),
|
||||
'head': head_compact[:30],
|
||||
'tail': tail_compact[:30],
|
||||
}
|
||||
samples.append(sample)
|
||||
|
||||
# Read target structure
|
||||
target_data = read_xlsx_xml(target_file, max_rows=50)
|
||||
target_info = {'filename': Path(target_file).name, 'sheets': {}}
|
||||
for k, v in target_data.items():
|
||||
if k == '_error':
|
||||
continue
|
||||
compact = []
|
||||
for i, row in enumerate(v[:30]):
|
||||
cells = [[j, row[j]] for j in range(len(row)) if row[j]]
|
||||
if cells:
|
||||
compact.append({'row': i, 'cells': cells[:8]})
|
||||
target_info['sheets'][k] = {'total_rows': len(v), 'rows': compact}
|
||||
|
||||
prompt = f"""Ты — эксперт по автоматизации сметного дела.
|
||||
|
||||
Задача: {task_description}
|
||||
|
||||
## Примеры исходных файлов (3 штуки):
|
||||
{json.dumps(samples, ensure_ascii=False, indent=2)[:6000]}
|
||||
|
||||
## Сводный файл:
|
||||
{json.dumps(target_info, ensure_ascii=False, indent=2)[:3000]}
|
||||
|
||||
## Определи:
|
||||
1. Где в исходном файле шифр сметы (лист, строка, столбец)
|
||||
2. Где итоговые суммы (строительные, монтажные, оборудование, прочие)
|
||||
3. Где в сводном файле строки для записи (лист, столбец с шифрами, столбцы для значений)
|
||||
|
||||
## ВАЖНО: В скрипте используй ТОЛЬКО эти переменные:
|
||||
- `source_files` — list[str] путей ко всем xlsx файлам
|
||||
- `target_file` — str путь к сводному файлу (уже скопирован, пиши в него)
|
||||
- `job` — dict: job["processed"] += 1 (int счётчик), job["errors"].append("описание") (list строк)
|
||||
- `read_xlsx_xml(path, max_rows=999)` — функция чтения xlsx через XML, возвращает dict[sheet_name, list[list[str]]]
|
||||
- `openpyxl` — для записи в target_file
|
||||
|
||||
Ответь ТОЛЬКО JSON (без markdown, без ```):
|
||||
{{
|
||||
"description": "описание алгоритма на русском",
|
||||
"source_code_cell": "B5",
|
||||
"source_totals": {{"строительные": "H29", "монтажные": "H30", "оборудование": "H31", "прочие": "H32"}},
|
||||
"target_sheet": "ССРСС-1 ТУЦ",
|
||||
"target_match_col": "B",
|
||||
"target_value_cols": {{"строительные": "D", "монтажные": "E", "оборудование": "F", "прочие": "G"}}
|
||||
}}"""
|
||||
|
||||
proxy = os.environ.get("HTTPS_PROXY") or os.environ.get("HTTP_PROXY")
|
||||
async with httpx.AsyncClient(timeout=300, proxy=proxy) as client:
|
||||
resp = await client.post(
|
||||
f"{ZAI_BASE_URL}/chat/completions",
|
||||
headers={"Authorization": f"Bearer {ZAI_API_KEY}"},
|
||||
json={
|
||||
"model": ZAI_MODEL,
|
||||
"messages": [
|
||||
{"role": "system", "content": "Ты генерируешь ТОЛЬКО валидный JSON. Никакого текста вне JSON."},
|
||||
{"role": "user", "content": prompt},
|
||||
],
|
||||
"temperature": 0.1,
|
||||
"max_tokens": 4000,
|
||||
"response_format": {"type": "json_object"},
|
||||
"thinking": {"type": "disabled"},
|
||||
},
|
||||
)
|
||||
resp.raise_for_status()
|
||||
msg = resp.json()["choices"][0]["message"]
|
||||
content = msg.get("content") or msg.get("reasoning_content") or ""
|
||||
|
||||
# Parse JSON from response
|
||||
try:
|
||||
if "```json" in content:
|
||||
content = content.split("```json")[1].split("```")[0]
|
||||
elif "```" in content:
|
||||
content = content.split("```")[1].split("```")[0]
|
||||
params = json.loads(content)
|
||||
except (json.JSONDecodeError, IndexError):
|
||||
return {"error": "Failed to parse LLM response", "raw": content[:2000]}
|
||||
|
||||
# Generate deterministic script from params
|
||||
params["python_script"] = _build_batch_script(params)
|
||||
return params
|
||||
|
||||
|
||||
def _col_to_idx(col: str) -> int:
|
||||
"""A→0, B→1, H→7"""
|
||||
result = 0
|
||||
for ch in col.upper():
|
||||
result = result * 26 + (ord(ch) - ord('A'))
|
||||
return result
|
||||
|
||||
|
||||
def _build_batch_script(params: dict) -> str:
|
||||
"""Build deterministic Python script from LLM-extracted params."""
|
||||
code_cell = params.get("source_code_cell", "B5")
|
||||
totals = params.get("source_totals", {})
|
||||
target_sheet = params.get("target_sheet", "")
|
||||
match_col = params.get("target_match_col", "B")
|
||||
value_cols = params.get("target_value_cols", {})
|
||||
|
||||
# Parse code cell → row, col indices
|
||||
code_col = ''.join(c for c in code_cell if c.isalpha())
|
||||
code_row = ''.join(c for c in code_cell if c.isdigit())
|
||||
code_col_idx = _col_to_idx(code_col)
|
||||
code_row_idx = int(code_row) - 1 if code_row else 4
|
||||
|
||||
# Parse total cells
|
||||
total_cells = []
|
||||
for name, cell in totals.items():
|
||||
col = ''.join(c for c in cell if c.isalpha())
|
||||
row = ''.join(c for c in cell if c.isdigit())
|
||||
total_cells.append((name, _col_to_idx(col), int(row) - 1 if row else 0))
|
||||
|
||||
# Parse target columns
|
||||
target_cols = {}
|
||||
for name, col in value_cols.items():
|
||||
target_cols[name] = _col_to_idx(col) + 1 # openpyxl is 1-indexed
|
||||
|
||||
match_col_idx = _col_to_idx(match_col) + 1
|
||||
|
||||
# Build value extraction lines
|
||||
value_lines = []
|
||||
for name, ci, ri in total_cells:
|
||||
tcol = target_cols.get(name, ci + 4)
|
||||
value_lines.append(
|
||||
f" v=0\n"
|
||||
f" if len(sheet)>{ri} and len(sheet[{ri}])>{ci}:\n"
|
||||
f" try: v=float(str(sheet[{ri}][{ci}] or 0).replace(',','.').replace(' ','') or 0)\n"
|
||||
f" except: v=0\n"
|
||||
f" ws.cell(row, {tcol}).value = v"
|
||||
)
|
||||
values_code = "\n".join(value_lines)
|
||||
|
||||
return (
|
||||
"import openpyxl\n"
|
||||
"wb = openpyxl.load_workbook(target_file)\n"
|
||||
f"ws = wb['{target_sheet}'] if '{target_sheet}' in wb.sheetnames else wb.active\n"
|
||||
"code_to_row = {}\n"
|
||||
f"for r in range(1, ws.max_row + 1):\n"
|
||||
f" v = ws.cell(r, {match_col_idx}).value\n"
|
||||
" if v:\n"
|
||||
" code_to_row[str(v).strip()] = r\n"
|
||||
"for f in source_files:\n"
|
||||
" try:\n"
|
||||
" data = read_xlsx_xml(f, max_rows=100)\n"
|
||||
" if not data:\n"
|
||||
" job['errors'].append(f + ': empty'); continue\n"
|
||||
" sheet = list(data.values())[0]\n"
|
||||
f" if len(sheet) <= {code_row_idx} or len(sheet[{code_row_idx}]) <= {code_col_idx}:\n"
|
||||
" job['errors'].append(f + ': no code'); continue\n"
|
||||
f" code = str(sheet[{code_row_idx}][{code_col_idx}]).strip()\n"
|
||||
" if not code or code not in code_to_row:\n"
|
||||
" job['errors'].append(f + ': ' + code + ' not found'); continue\n"
|
||||
" row = code_to_row[code]\n"
|
||||
f"{values_code}\n"
|
||||
" job['processed'] += 1\n"
|
||||
" except Exception as e:\n"
|
||||
" job['errors'].append(f + ': ' + str(e))\n"
|
||||
"wb.save(target_file)\n"
|
||||
)
|
||||
|
||||
|
||||
def run_batch(job_id: str, script: str, source_dir: str, target_file: str):
|
||||
"""Execute generated script on all files. Updates job status."""
|
||||
job = _jobs[job_id]
|
||||
job["status"] = "running"
|
||||
job["started_at"] = time.time()
|
||||
|
||||
source_files = [str(f) for f in Path(source_dir).rglob("*.xlsx") if not f.name.startswith("~$")]
|
||||
job["total_files"] = len(source_files)
|
||||
job["processed"] = 0
|
||||
job["errors"] = []
|
||||
job["error_count"] = 0 # int counter for scripts that do += 1
|
||||
|
||||
# Create a safe execution environment
|
||||
output_file = str(Path(target_file).parent / f"result_{Path(target_file).name}")
|
||||
shutil.copy2(target_file, output_file)
|
||||
|
||||
# Fix common LLM mistakes in generated scripts
|
||||
import re
|
||||
script = script.replace("job['errors'] += 1", "job['errors'].append('error')")
|
||||
script = script.replace('job["errors"] += 1', 'job["errors"].append("error")')
|
||||
# Fix sheet name access — add fallback to active sheet
|
||||
script = re.sub(
|
||||
r"wb_target\['([^']+)'\]",
|
||||
r"(wb_target['\1'] if '\1' in wb_target.sheetnames else wb_target.active)",
|
||||
script
|
||||
)
|
||||
script = re.sub(
|
||||
r'wb_target\["([^"]+)"\]',
|
||||
r'(wb_target["\1"] if "\1" in wb_target.sheetnames else wb_target.active)',
|
||||
script
|
||||
)
|
||||
# If LLM wrapped in def main() / if __name__, call main() at the end
|
||||
if "def main()" in script and "if __name__" in script:
|
||||
script = re.sub(r"if __name__\s*==\s*['\"]__main__['\"]\s*:\s*\n\s*main\(\)", "", script)
|
||||
script += "\nmain()\n"
|
||||
|
||||
try:
|
||||
exec_globals = {
|
||||
"__builtins__": __builtins__,
|
||||
"source_files": source_files,
|
||||
"target_file": output_file,
|
||||
"job": job,
|
||||
"read_xlsx_xml": read_xlsx_xml,
|
||||
"Path": Path,
|
||||
"csv": csv,
|
||||
"json": json,
|
||||
"zipfile": zipfile,
|
||||
"ET": ET,
|
||||
}
|
||||
try:
|
||||
import openpyxl
|
||||
exec_globals["openpyxl"] = openpyxl
|
||||
except ImportError:
|
||||
pass
|
||||
|
||||
exec(script, exec_globals)
|
||||
job["status"] = "completed"
|
||||
job["output_file"] = output_file
|
||||
|
||||
except Exception as e:
|
||||
job["status"] = "failed"
|
||||
job["error"] = f"{type(e).__name__}: {e}\n{traceback.format_exc()}"
|
||||
|
||||
job["finished_at"] = time.time()
|
||||
|
||||
|
||||
def get_job(job_id: str) -> dict | None:
|
||||
return _jobs.get(job_id)
|
||||
|
||||
|
||||
def create_job(job_id: str):
|
||||
_jobs[job_id] = {
|
||||
"id": job_id,
|
||||
"status": "created",
|
||||
"total_files": 0,
|
||||
"processed": 0,
|
||||
"errors": [],
|
||||
}
|
||||
return _jobs[job_id]
|
||||
-771
@@ -1,771 +0,0 @@
|
||||
"""Batch V3: Generate + Verify + Auto-Retry.
|
||||
|
||||
Extends V2 with automatic verification: after Claude generates a script,
|
||||
it is exec'd on 2 sample files. If it fails, Claude retries with error feedback.
|
||||
|
||||
Flow:
|
||||
1. Upload zip + target + task description (same as V2)
|
||||
2. Claude Code (sonnet) generates script
|
||||
3. Script is exec'd on 2 samples → verify
|
||||
4. If fail → retry with error feedback (up to 3 times)
|
||||
5. User confirms → script runs on all files
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import csv
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import time
|
||||
import traceback
|
||||
import zipfile
|
||||
import xml.etree.ElementTree as ET
|
||||
from pathlib import Path
|
||||
from typing import AsyncGenerator
|
||||
|
||||
from xlsx_utils import read_xlsx_xml, extract_zip
|
||||
|
||||
DOCKER_IMAGE = os.environ.get("CLAUDE_DOCKER_IMAGE", "smeta-claude-sandbox")
|
||||
try:
|
||||
import model_registry
|
||||
CLAUDE_MODEL = model_registry.model_id("sonnet_cli") # единый реестр (env CLAUDE_MODEL override)
|
||||
except Exception: # noqa: BLE001 — fail-soft
|
||||
CLAUDE_MODEL = os.environ.get("CLAUDE_MODEL", "sonnet")
|
||||
CLAUDE_CONFIG_DIR = os.environ.get(
|
||||
"CLAUDE_CONFIG_DIR", os.path.expanduser("~/.claude")
|
||||
)
|
||||
DOCKER_HOST_GW = os.environ.get("DOCKER_HOST_GW", "172.17.0.1")
|
||||
XRAY_PORT = os.environ.get("XRAY_PORT", "10809")
|
||||
|
||||
# Token estimation: ~0.3 tokens per byte for CSV text
|
||||
TOKENS_PER_BYTE = 0.3
|
||||
MAX_CONTEXT_TOKENS = 800_000 # leave headroom from 1M
|
||||
MAX_SAMPLE_FILES = 15 # sample xlsx for Claude to read
|
||||
MAX_SAMPLE_BYTES = 500_000 # max total bytes of sample CSVs
|
||||
|
||||
# V3 job storage (separate from V2)
|
||||
_jobs: dict[str, dict] = {}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Functions merged from batch_v2.py
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def convert_xlsx_to_csv(xlsx_path: str, output_dir: str) -> list[str]:
|
||||
"""Convert xlsx to CSV files via XML parser (handles broken styles).
|
||||
|
||||
Returns list of created CSV file paths.
|
||||
"""
|
||||
data = read_xlsx_xml(xlsx_path, max_rows=9999)
|
||||
if "_error" in data and len(data) == 1:
|
||||
return []
|
||||
|
||||
created = []
|
||||
stem = Path(xlsx_path).stem
|
||||
for sheet_name, rows in data.items():
|
||||
if sheet_name == "_error":
|
||||
continue
|
||||
# Skip empty sheets
|
||||
if not rows or all(not any(cell for cell in row) for row in rows):
|
||||
continue
|
||||
safe_name = "".join(c if c.isalnum() or c in " _-" else "_" for c in sheet_name)
|
||||
csv_path = Path(output_dir) / f"{stem}__{safe_name}.csv"
|
||||
with open(csv_path, "w", newline="", encoding="utf-8") as f:
|
||||
writer = csv.writer(f)
|
||||
for row in rows:
|
||||
writer.writerow(row)
|
||||
created.append(str(csv_path))
|
||||
return created
|
||||
|
||||
|
||||
def convert_all_to_csv(source_dir: str, csv_dir: str) -> dict:
|
||||
"""Convert all xlsx files in source_dir to CSV in csv_dir.
|
||||
|
||||
Returns {"files": [...], "total_bytes": int, "estimated_tokens": int}.
|
||||
"""
|
||||
Path(csv_dir).mkdir(parents=True, exist_ok=True)
|
||||
all_csv = []
|
||||
total_bytes = 0
|
||||
|
||||
SMETA_EXT = {'.xlsx', '.xls', '.gge', '.esw', '.xml'}
|
||||
xlsx_files = sorted(
|
||||
f for f in Path(source_dir).rglob("*")
|
||||
if f.is_file() and f.suffix.lower() in SMETA_EXT
|
||||
and not f.name.startswith("~$") and not f.name.startswith("._")
|
||||
)
|
||||
|
||||
for xlsx in xlsx_files:
|
||||
# .gge/.esw are XML — copy as-is (no xlsx conversion needed)
|
||||
if xlsx.suffix.lower() in ('.gge', '.esw', '.xml'):
|
||||
dst = Path(csv_dir) / f"{xlsx.stem}.xml"
|
||||
shutil.copy2(str(xlsx), str(dst))
|
||||
size = dst.stat().st_size
|
||||
all_csv.append({"path": str(dst), "name": dst.name, "bytes": size})
|
||||
total_bytes += size
|
||||
continue
|
||||
csvs = convert_xlsx_to_csv(str(xlsx), csv_dir)
|
||||
for c in csvs:
|
||||
size = Path(c).stat().st_size
|
||||
all_csv.append({"path": c, "name": Path(c).name, "bytes": size})
|
||||
total_bytes += size
|
||||
|
||||
return {
|
||||
"files": all_csv,
|
||||
"total_bytes": total_bytes,
|
||||
"estimated_tokens": int(total_bytes * TOKENS_PER_BYTE),
|
||||
"xlsx_count": len(xlsx_files),
|
||||
}
|
||||
|
||||
|
||||
def select_samples(source_dir: str, csv_info: dict) -> list[str]:
|
||||
"""Select a diverse sample of xlsx files for Claude to analyze.
|
||||
|
||||
Strategy: pick files of different sizes and from different subdirs.
|
||||
Returns list of xlsx file paths (originals, not CSV).
|
||||
"""
|
||||
SMETA_EXT = {'.xlsx', '.xls', '.gge', '.esw', '.xml'}
|
||||
xlsx_files = sorted(
|
||||
[f for f in Path(source_dir).rglob("*")
|
||||
if f.is_file() and f.suffix.lower() in SMETA_EXT
|
||||
and not f.name.startswith("~$") and not f.name.startswith("._")],
|
||||
key=lambda f: f.stat().st_size,
|
||||
)
|
||||
if len(xlsx_files) <= MAX_SAMPLE_FILES:
|
||||
return [str(f) for f in xlsx_files]
|
||||
|
||||
# Pick diverse: smallest, largest, and evenly spaced
|
||||
n = len(xlsx_files)
|
||||
indices = set()
|
||||
indices.add(0) # smallest
|
||||
indices.add(n - 1) # largest
|
||||
# Evenly spaced
|
||||
step = max(1, n // (MAX_SAMPLE_FILES - 2))
|
||||
for i in range(0, n, step):
|
||||
indices.add(i)
|
||||
if len(indices) >= MAX_SAMPLE_FILES:
|
||||
break
|
||||
# If still room, add from different directories
|
||||
if len(indices) < MAX_SAMPLE_FILES:
|
||||
dirs_seen = set()
|
||||
for i, f in enumerate(xlsx_files):
|
||||
d = str(f.parent)
|
||||
if d not in dirs_seen:
|
||||
dirs_seen.add(d)
|
||||
indices.add(i)
|
||||
if len(indices) >= MAX_SAMPLE_FILES:
|
||||
break
|
||||
|
||||
return [str(xlsx_files[i]) for i in sorted(indices)][:MAX_SAMPLE_FILES]
|
||||
|
||||
|
||||
def prepare_samples(source_dir: str, job_dir: Path, csv_info: dict) -> dict:
|
||||
"""Convert only sample files to CSV in /data/sample_csv/ for Claude.
|
||||
|
||||
Returns {"sample_files": [...], "sample_csv_dir": str}.
|
||||
"""
|
||||
sample_xlsx = select_samples(source_dir, csv_info)
|
||||
sample_csv_dir = job_dir / "sample_csv"
|
||||
sample_csv_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
converted_xlsx = []
|
||||
sample_csvs = []
|
||||
total_bytes = 0
|
||||
for xlsx in sample_xlsx:
|
||||
# .gge/.esw/.xml — copy as-is, no xlsx conversion
|
||||
if Path(xlsx).suffix.lower() in ('.gge', '.esw', '.xml'):
|
||||
dst = sample_csv_dir / f"{Path(xlsx).stem}.xml"
|
||||
shutil.copy2(xlsx, str(dst))
|
||||
converted_xlsx.append(xlsx)
|
||||
sample_csvs.append(str(dst))
|
||||
total_bytes += dst.stat().st_size
|
||||
continue
|
||||
csvs = convert_xlsx_to_csv(xlsx, str(sample_csv_dir))
|
||||
converted_xlsx.append(xlsx)
|
||||
for c in csvs:
|
||||
size = Path(c).stat().st_size
|
||||
sample_csvs.append(c)
|
||||
total_bytes += size
|
||||
if total_bytes > MAX_SAMPLE_BYTES:
|
||||
break
|
||||
|
||||
return {
|
||||
"sample_files": converted_xlsx,
|
||||
"sample_csv_dir": str(sample_csv_dir),
|
||||
"sample_csv_count": len(sample_csvs),
|
||||
"sample_bytes": total_bytes,
|
||||
}
|
||||
|
||||
|
||||
def build_claude_prompt(
|
||||
task_description: str,
|
||||
sample_csv_dir: str,
|
||||
target_csv_dir: str,
|
||||
target_filename: str,
|
||||
total_xlsx_count: int,
|
||||
sample_xlsx_names: list[str],
|
||||
) -> str:
|
||||
"""Build the prompt for Claude Code to analyze sample files and generate script."""
|
||||
sample_names = "\n".join(f"- {Path(f).name}" for f in sample_xlsx_names)
|
||||
return f"""You are an expert in Russian construction cost estimation (smeta).
|
||||
|
||||
## Task
|
||||
{task_description}
|
||||
|
||||
## Source files
|
||||
There are {total_xlsx_count} xlsx source files total. You have {len(sample_xlsx_names)} SAMPLE files
|
||||
converted to CSV in /data/sample_csv/ for analysis.
|
||||
CSV naming: {{original_xlsx_stem}}__{{sheet_name}}.csv
|
||||
|
||||
Sample files:
|
||||
{sample_names}
|
||||
|
||||
## Target file
|
||||
The target summary file is converted to CSV in /data/target_csv/.
|
||||
Original filename: {target_filename}
|
||||
NOTE: In the script, use the `target_file` variable (not a hardcoded path).
|
||||
|
||||
## Your job
|
||||
1. Read the sample CSV files in /data/sample_csv/ — understand their structure
|
||||
2. Read the target CSV files in /data/target_csv/ — understand where data goes
|
||||
3. Figure out: what to extract from each source, how to match to target rows
|
||||
4. FIRST write /data/batch_summary.json, THEN write /data/batch_script.py
|
||||
|
||||
## MANDATORY: /data/batch_summary.json — write this FIRST!
|
||||
The user is a construction estimator, not a programmer. This summary is shown to them for review.
|
||||
JSON with these fields (in Russian):
|
||||
```json
|
||||
{{
|
||||
"description": "Краткое описание что будет сделано",
|
||||
"source_patterns": {{
|
||||
"sheet": "на каком листе искать данные",
|
||||
"id_field": "где шифр/название сметы (например: имя файла, ячейка B5)",
|
||||
"totals": {{
|
||||
"строительные работы": "паттерн поиска (например: ВСЕГО строительные работы)",
|
||||
"монтажные работы": "паттерн поиска",
|
||||
"оборудование": "паттерн поиска",
|
||||
"прочие затраты": "паттерн поиска"
|
||||
}},
|
||||
"value_column": "в каком столбце значения (например: A или H)",
|
||||
"units": "рубли или тыс.руб"
|
||||
}},
|
||||
"target_mapping": {{
|
||||
"sheet": "на какой лист сводного файла записывать",
|
||||
"match_column": "столбец с шифрами для сопоставления (например: B)",
|
||||
"value_columns": {{
|
||||
"строительные работы": "столбец (например: D)",
|
||||
"монтажные работы": "столбец (например: E)",
|
||||
"оборудование": "столбец (например: F)",
|
||||
"прочие затраты": "столбец (например: G)"
|
||||
}},
|
||||
"units": "тыс.руб"
|
||||
}},
|
||||
"conversion": "делить на 1000 (руб → тыс.руб)" или "без конвертации",
|
||||
"preview": [
|
||||
{{
|
||||
"source_file": "имя файла источника",
|
||||
"source_values": {{"строительные работы": 15460805.77, "монтажные работы": 0}},
|
||||
"target_sheet": "ССРСС ТУЦ",
|
||||
"target_row": "строка 17 (ЛС-01-02-2-00-01 Устройство насыпи)",
|
||||
"target_values": {{"D": 15460.81, "E": 0, "F": 0, "G": 0}}
|
||||
}}
|
||||
]
|
||||
}}
|
||||
```
|
||||
The "preview" array must contain entries for ALL sample files — show the actual extracted values
|
||||
and where they will go in the target. This is the most important part for the user to verify!
|
||||
|
||||
### File 2: /data/batch_script.py — Python script
|
||||
|
||||
## CRITICAL: The script will run on ALL {total_xlsx_count} files, not just samples!
|
||||
The script must handle any file with the same general structure as the samples.
|
||||
|
||||
## Script execution context (these variables will be available):
|
||||
- `source_files`: list[str] — paths to ALL {total_xlsx_count} original xlsx files
|
||||
- `target_file`: str — path to target xlsx (a copy, safe to modify)
|
||||
- `job`: dict — job["processed"] += 1 per file, job["errors"].append("msg") for errors
|
||||
- `read_xlsx_xml(path, max_rows=9999)`: dict[sheet_name, list[list[str]]]
|
||||
IMPORTANT: ALWAYS pass max_rows=9999! Default is only 50 rows — totals are at the END of files!
|
||||
Column indices: A=0, B=1, C=2, ..., H=7, etc. Values are strings.
|
||||
- `openpyxl`: for writing to target xlsx
|
||||
- `Path`, `csv`, `json`, `re`, `os`
|
||||
|
||||
## Script requirements
|
||||
- Self-contained, using ONLY the variables above
|
||||
- NO `if __name__` or `def main()` wrappers — top-level code
|
||||
- Robust: skip files with unexpected structure, log to job["errors"]
|
||||
- Track progress: job["processed"] += 1 after each successful file
|
||||
- Save at the end: wb.save(target_file)
|
||||
"""
|
||||
|
||||
|
||||
def _read_result_files(job_dir: Path) -> dict:
|
||||
"""Read batch_script.py and batch_summary.json from job dir."""
|
||||
script_path = job_dir / "batch_script.py"
|
||||
summary_path = job_dir / "batch_summary.json"
|
||||
summary = {}
|
||||
if summary_path.exists():
|
||||
try:
|
||||
summary = json.loads(summary_path.read_text(encoding="utf-8"))
|
||||
except (json.JSONDecodeError, OSError):
|
||||
pass
|
||||
if script_path.exists():
|
||||
return {"script": script_path.read_text(encoding="utf-8"), "summary": summary}
|
||||
return {"script": "", "result": "Script not generated", "summary": summary}
|
||||
|
||||
|
||||
async def run_claude_analysis(
|
||||
job_dir: Path,
|
||||
task_description: str,
|
||||
target_filename: str,
|
||||
total_xlsx_count: int,
|
||||
sample_info: dict,
|
||||
) -> AsyncGenerator[dict, None]:
|
||||
"""Run Claude Code in Docker to analyze files and generate script (V2 style, no verify)."""
|
||||
target_csv_dir = str(job_dir / "target_csv")
|
||||
prompt = build_claude_prompt(
|
||||
task_description,
|
||||
sample_info["sample_csv_dir"],
|
||||
target_csv_dir,
|
||||
target_filename,
|
||||
total_xlsx_count,
|
||||
sample_info["sample_files"],
|
||||
)
|
||||
|
||||
cmd = [
|
||||
"docker", "run", "--rm",
|
||||
"--memory=1g", "--cpus=2", "--network=host",
|
||||
"-v", f"{job_dir.resolve()}:/data",
|
||||
"-v", f"{CLAUDE_CONFIG_DIR}:/home/worker/.claude",
|
||||
"-v", f"{os.path.expanduser('~')}/.claude.json:/home/worker/.claude.json",
|
||||
"-e", f"HTTPS_PROXY=http://{DOCKER_HOST_GW}:{XRAY_PORT}",
|
||||
"-e", f"HTTP_PROXY=http://{DOCKER_HOST_GW}:{XRAY_PORT}",
|
||||
"-e", "HOME=/home/worker",
|
||||
"-w", "/data",
|
||||
DOCKER_IMAGE,
|
||||
"-p", prompt,
|
||||
"--output-format", "stream-json",
|
||||
"--verbose",
|
||||
"--allowedTools", "Bash,Read,Write,Edit,Glob,Grep",
|
||||
"--max-turns", "30",
|
||||
]
|
||||
|
||||
try:
|
||||
proc = await asyncio.create_subprocess_exec(
|
||||
*cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.DEVNULL,
|
||||
)
|
||||
except FileNotFoundError:
|
||||
yield {"type": "done", "script": "", "result": "Docker not found"}
|
||||
return
|
||||
|
||||
got_result = False
|
||||
try:
|
||||
while True:
|
||||
raw_line = await proc.stdout.readline()
|
||||
if not raw_line:
|
||||
break
|
||||
line = raw_line.decode().strip()
|
||||
if not line:
|
||||
continue
|
||||
try:
|
||||
event = json.loads(line)
|
||||
except json.JSONDecodeError:
|
||||
continue
|
||||
etype = event.get("type", "")
|
||||
if etype == "assistant":
|
||||
msg = event.get("message", {})
|
||||
for block in msg.get("content", []):
|
||||
if block.get("type") == "text":
|
||||
yield {"type": "text", "text": block["text"]}
|
||||
elif block.get("type") == "tool_use":
|
||||
yield {"type": "tool", "tool": block.get("name", "")}
|
||||
elif etype == "result":
|
||||
got_result = True
|
||||
result_data = _read_result_files(job_dir)
|
||||
yield {"type": "done", **result_data}
|
||||
finally:
|
||||
if proc.returncode is None:
|
||||
proc.terminate()
|
||||
try:
|
||||
await asyncio.wait_for(proc.wait(), timeout=5)
|
||||
except asyncio.TimeoutError:
|
||||
proc.kill()
|
||||
|
||||
if not got_result:
|
||||
result_data = _read_result_files(job_dir)
|
||||
yield {"type": "done", **result_data}
|
||||
|
||||
|
||||
def run_batch_v2(job_id: str, script: str, source_dir: str, target_file: str):
|
||||
"""Execute the Claude-generated script on all files."""
|
||||
job = _jobs[job_id]
|
||||
job["status"] = "running"
|
||||
job["started_at"] = time.time()
|
||||
|
||||
SMETA_EXT = {'.xlsx', '.xls', '.gge', '.esw', '.xml'}
|
||||
source_files = [
|
||||
str(f) for f in Path(source_dir).rglob("*")
|
||||
if f.is_file() and f.suffix.lower() in SMETA_EXT
|
||||
and not f.name.startswith("~$") and not f.name.startswith("._")
|
||||
]
|
||||
job["total_files"] = len(source_files)
|
||||
job["processed"] = 0
|
||||
job["errors"] = []
|
||||
|
||||
output_file = str(Path(target_file).parent / f"result_{Path(target_file).name}")
|
||||
shutil.copy2(target_file, output_file)
|
||||
|
||||
try:
|
||||
exec_globals = {
|
||||
"__builtins__": __builtins__,
|
||||
"source_files": source_files,
|
||||
"target_file": output_file,
|
||||
"job": job,
|
||||
"read_xlsx_xml": read_xlsx_xml,
|
||||
"Path": Path,
|
||||
"csv": csv,
|
||||
"json": json,
|
||||
"zipfile": zipfile,
|
||||
"ET": ET,
|
||||
"os": os,
|
||||
"re": re,
|
||||
}
|
||||
try:
|
||||
import openpyxl
|
||||
exec_globals["openpyxl"] = openpyxl
|
||||
except ImportError:
|
||||
pass
|
||||
exec(script, exec_globals)
|
||||
job["status"] = "completed"
|
||||
job["output_file"] = output_file
|
||||
except Exception as e:
|
||||
job["status"] = "failed"
|
||||
job["error"] = f"{type(e).__name__}: {e}\n{traceback.format_exc()}"
|
||||
|
||||
job["finished_at"] = time.time()
|
||||
|
||||
|
||||
def create_job(job_id: str) -> dict:
|
||||
_jobs[job_id] = {
|
||||
"id": job_id,
|
||||
"status": "created",
|
||||
"total_files": 0,
|
||||
"processed": 0,
|
||||
"errors": [],
|
||||
"verified": False,
|
||||
"verify_attempts": 0,
|
||||
"verify_errors": [],
|
||||
}
|
||||
return _jobs[job_id]
|
||||
|
||||
|
||||
def get_job(job_id: str) -> dict | None:
|
||||
return _jobs.get(job_id)
|
||||
|
||||
|
||||
def verify_script(
|
||||
script: str,
|
||||
source_dir: str,
|
||||
target_file: str,
|
||||
job_dir: str | Path,
|
||||
) -> dict:
|
||||
"""Execute script on 2 sample files to verify correctness.
|
||||
|
||||
Returns {"ok": True/False, "processed": int, "errors": [...], "error": str}.
|
||||
"""
|
||||
job_dir = Path(job_dir)
|
||||
SMETA_EXT = {'.xlsx', '.xls', '.gge', '.esw', '.xml'}
|
||||
# Select 2 sample files
|
||||
all_files = sorted(
|
||||
f for f in Path(source_dir).rglob("*")
|
||||
if f.is_file() and f.suffix.lower() in SMETA_EXT
|
||||
and not f.name.startswith("~$") and not f.name.startswith("._")
|
||||
)
|
||||
samples = [str(f) for f in all_files[:2]]
|
||||
if not samples:
|
||||
return {"ok": False, "error": "No xlsx files found in source", "processed": 0, "errors": []}
|
||||
|
||||
# Copy target to temp file
|
||||
verify_target = job_dir / "verify_target.xlsx"
|
||||
shutil.copy2(target_file, str(verify_target))
|
||||
|
||||
mini_job = {"processed": 0, "errors": []}
|
||||
exec_globals = {
|
||||
"__builtins__": __builtins__,
|
||||
"source_files": samples,
|
||||
"target_file": str(verify_target),
|
||||
"job": mini_job,
|
||||
"read_xlsx_xml": read_xlsx_xml,
|
||||
"Path": Path,
|
||||
"csv": csv,
|
||||
"json": json,
|
||||
"zipfile": zipfile,
|
||||
"ET": ET,
|
||||
"os": os,
|
||||
"re": re,
|
||||
}
|
||||
try:
|
||||
import openpyxl
|
||||
exec_globals["openpyxl"] = openpyxl
|
||||
except ImportError:
|
||||
pass
|
||||
|
||||
try:
|
||||
exec(script, exec_globals)
|
||||
except Exception as e:
|
||||
return {
|
||||
"ok": False,
|
||||
"error": f"{type(e).__name__}: {e}\n{traceback.format_exc()}",
|
||||
"processed": mini_job["processed"],
|
||||
"errors": mini_job["errors"],
|
||||
}
|
||||
finally:
|
||||
if verify_target.exists():
|
||||
verify_target.unlink()
|
||||
|
||||
if mini_job["processed"] > 0 and len(mini_job["errors"]) == 0:
|
||||
return {"ok": True, "processed": mini_job["processed"], "errors": []}
|
||||
|
||||
error_msg = f"processed={mini_job['processed']}/{len(samples)}, errors={mini_job['errors']}"
|
||||
return {
|
||||
"ok": False,
|
||||
"error": error_msg,
|
||||
"processed": mini_job["processed"],
|
||||
"errors": mini_job["errors"],
|
||||
}
|
||||
|
||||
|
||||
def build_retry_prompt(original_prompt: str, script: str, error: str, attempt: int) -> str:
|
||||
"""Build prompt for retry after verification failure."""
|
||||
return f"""{original_prompt}
|
||||
|
||||
## PREVIOUS ATTEMPT FAILED (attempt {attempt}/3)
|
||||
|
||||
Your previously generated script was tested on 2 sample xlsx files and FAILED.
|
||||
|
||||
### The script that failed:
|
||||
```python
|
||||
{script}
|
||||
```
|
||||
|
||||
### Error:
|
||||
{error}
|
||||
|
||||
## Fix the bugs. Common issues:
|
||||
- ALWAYS use read_xlsx_xml(path, max_rows=9999) — default is only 50 rows!
|
||||
- Column indices: A=0, B=1, ..., H=7 (0-based in read_xlsx_xml)
|
||||
- openpyxl uses 1-based row/col numbering
|
||||
- Handle missing sheets/values gracefully (skip, don't crash)
|
||||
- Don't forget to handle files with encoding issues in filenames
|
||||
|
||||
Write corrected /data/batch_script.py and /data/batch_summary.json.
|
||||
"""
|
||||
|
||||
|
||||
async def run_claude_v3(
|
||||
job_dir: Path,
|
||||
prompt: str,
|
||||
) -> AsyncGenerator[dict, None]:
|
||||
"""Run Claude Code in Docker (--model из CLAUDE_MODEL). Yields SSE events."""
|
||||
cmd = [
|
||||
"docker", "run", "--rm",
|
||||
"--memory=1g",
|
||||
"--cpus=2",
|
||||
"--network=host",
|
||||
"-v", f"{job_dir.resolve()}:/data",
|
||||
"-v", f"{CLAUDE_CONFIG_DIR}:/home/worker/.claude",
|
||||
"-v", f"{os.path.expanduser('~')}/.claude.json:/home/worker/.claude.json",
|
||||
"-e", f"HTTPS_PROXY=http://{DOCKER_HOST_GW}:{XRAY_PORT}",
|
||||
"-e", f"HTTP_PROXY=http://{DOCKER_HOST_GW}:{XRAY_PORT}",
|
||||
"-e", "HOME=/home/worker",
|
||||
"-w", "/data",
|
||||
DOCKER_IMAGE,
|
||||
"-p", prompt,
|
||||
"--model", CLAUDE_MODEL,
|
||||
"--output-format", "stream-json",
|
||||
"--verbose",
|
||||
"--allowedTools", "Bash,Read,Write,Edit,Glob,Grep",
|
||||
"--max-turns", "30",
|
||||
]
|
||||
|
||||
try:
|
||||
proc = await asyncio.create_subprocess_exec(
|
||||
*cmd,
|
||||
stdout=asyncio.subprocess.PIPE,
|
||||
stderr=asyncio.subprocess.DEVNULL,
|
||||
)
|
||||
except FileNotFoundError:
|
||||
yield {"type": "done", "script": "", "result": "Docker not found"}
|
||||
return
|
||||
|
||||
got_result = False
|
||||
try:
|
||||
while True:
|
||||
raw_line = await proc.stdout.readline()
|
||||
if not raw_line:
|
||||
break
|
||||
line = raw_line.decode().strip()
|
||||
if not line:
|
||||
continue
|
||||
try:
|
||||
event = json.loads(line)
|
||||
except json.JSONDecodeError:
|
||||
continue
|
||||
|
||||
etype = event.get("type", "")
|
||||
if etype == "assistant":
|
||||
msg = event.get("message", {})
|
||||
for block in msg.get("content", []):
|
||||
if block.get("type") == "text":
|
||||
yield {"type": "text", "text": block["text"]}
|
||||
elif block.get("type") == "tool_use":
|
||||
yield {"type": "tool", "tool": block.get("name", "")}
|
||||
elif etype == "result":
|
||||
got_result = True
|
||||
yield {"type": "done", **_read_result_files(job_dir)}
|
||||
finally:
|
||||
if proc.returncode is None:
|
||||
proc.terminate()
|
||||
try:
|
||||
await asyncio.wait_for(proc.wait(), timeout=5)
|
||||
except asyncio.TimeoutError:
|
||||
proc.kill()
|
||||
|
||||
if not got_result:
|
||||
yield {"type": "done", **_read_result_files(job_dir)}
|
||||
|
||||
|
||||
async def run_generate_and_verify(
|
||||
job_dir: Path,
|
||||
task_description: str,
|
||||
target_filename: str,
|
||||
total_xlsx_count: int,
|
||||
sample_info: dict,
|
||||
source_dir: str,
|
||||
target_file: str,
|
||||
) -> AsyncGenerator[dict, None]:
|
||||
"""Orchestrator: generate script → verify → retry if needed."""
|
||||
original_prompt = build_claude_prompt(
|
||||
task_description,
|
||||
sample_info["sample_csv_dir"],
|
||||
str(job_dir / "target_csv"),
|
||||
target_filename,
|
||||
total_xlsx_count,
|
||||
sample_info["sample_files"],
|
||||
)
|
||||
prompt = original_prompt
|
||||
|
||||
for attempt in range(1, 4):
|
||||
# Phase 1: Generate
|
||||
yield {"type": "generation_start", "attempt": attempt}
|
||||
|
||||
script = ""
|
||||
summary = {}
|
||||
async for event in run_claude_v3(job_dir, prompt):
|
||||
if event["type"] in ("text", "tool"):
|
||||
yield event
|
||||
elif event["type"] == "done":
|
||||
script = event.get("script", "")
|
||||
summary = event.get("summary", {})
|
||||
|
||||
if not script:
|
||||
yield {"type": "error", "error": "Script not generated", "attempt": attempt}
|
||||
return
|
||||
|
||||
# Phase 2: Verify (run in thread to avoid blocking event loop)
|
||||
yield {"type": "verify_start", "attempt": attempt}
|
||||
loop = asyncio.get_event_loop()
|
||||
result = await loop.run_in_executor(
|
||||
None, verify_script, script, source_dir, target_file, str(job_dir)
|
||||
)
|
||||
|
||||
if result["ok"]:
|
||||
yield {
|
||||
"type": "verify_ok",
|
||||
"attempt": attempt,
|
||||
"processed": result["processed"],
|
||||
}
|
||||
yield {
|
||||
"type": "done",
|
||||
"script": script,
|
||||
"summary": summary,
|
||||
"verified": True,
|
||||
"attempts": attempt,
|
||||
}
|
||||
return
|
||||
|
||||
# Phase 3: Failed
|
||||
yield {
|
||||
"type": "verify_fail",
|
||||
"attempt": attempt,
|
||||
"error": result["error"],
|
||||
"processed": result["processed"],
|
||||
}
|
||||
|
||||
if attempt < 3:
|
||||
yield {"type": "retry", "attempt": attempt + 1}
|
||||
prompt = build_retry_prompt(original_prompt, script, result["error"], attempt)
|
||||
# Clean up for next attempt
|
||||
(job_dir / "batch_script.py").unlink(missing_ok=True)
|
||||
(job_dir / "batch_summary.json").unlink(missing_ok=True)
|
||||
|
||||
# All 3 attempts failed — still return the last script
|
||||
yield {
|
||||
"type": "done",
|
||||
"script": script,
|
||||
"summary": summary,
|
||||
"verified": False,
|
||||
"attempts": 3,
|
||||
"last_error": result["error"],
|
||||
}
|
||||
|
||||
|
||||
def run_batch_v3(job_id: str, script: str, source_dir: str, target_file: str):
|
||||
"""Execute script on all files (same as V2)."""
|
||||
job = _jobs[job_id]
|
||||
job["status"] = "running"
|
||||
job["started_at"] = time.time()
|
||||
|
||||
SMETA_EXT = {'.xlsx', '.xls', '.gge', '.esw', '.xml'}
|
||||
source_files = [
|
||||
str(f) for f in Path(source_dir).rglob("*")
|
||||
if f.is_file() and f.suffix.lower() in SMETA_EXT
|
||||
and not f.name.startswith("~$") and not f.name.startswith("._")
|
||||
]
|
||||
job["total_files"] = len(source_files)
|
||||
job["processed"] = 0
|
||||
job["errors"] = []
|
||||
|
||||
output_file = str(Path(target_file).parent / f"result_{Path(target_file).name}")
|
||||
shutil.copy2(target_file, output_file)
|
||||
|
||||
try:
|
||||
exec_globals = {
|
||||
"__builtins__": __builtins__,
|
||||
"source_files": source_files,
|
||||
"target_file": output_file,
|
||||
"job": job,
|
||||
"read_xlsx_xml": read_xlsx_xml,
|
||||
"Path": Path,
|
||||
"csv": csv,
|
||||
"json": json,
|
||||
"zipfile": zipfile,
|
||||
"ET": ET,
|
||||
"os": os,
|
||||
"re": re,
|
||||
}
|
||||
try:
|
||||
import openpyxl
|
||||
exec_globals["openpyxl"] = openpyxl
|
||||
except ImportError:
|
||||
pass
|
||||
|
||||
exec(script, exec_globals)
|
||||
job["status"] = "completed"
|
||||
job["output_file"] = output_file
|
||||
except Exception as e:
|
||||
job["status"] = "failed"
|
||||
job["error"] = f"{type(e).__name__}: {e}\n{traceback.format_exc()}"
|
||||
|
||||
job["finished_at"] = time.time()
|
||||
@@ -964,17 +964,9 @@ async def clear_files(request: Request):
|
||||
|
||||
|
||||
# === Batch processing ===
|
||||
from xlsx_utils import extract_zip
|
||||
import batch_v3
|
||||
import threading
|
||||
import uuid
|
||||
|
||||
BATCH_DIR = Path(os.environ.get("DATA_DIR", "./smeta-web-data")) / "_batch"
|
||||
|
||||
|
||||
@app.get("/batch", response_class=HTMLResponse)
|
||||
async def batch_page():
|
||||
return Path("static/batch.html").read_text(encoding="utf-8")
|
||||
|
||||
|
||||
# V1 batch endpoints removed — use /api/batch-v3/* instead
|
||||
@@ -983,173 +975,6 @@ async def batch_page():
|
||||
# === Batch V2: Claude Code analysis ===
|
||||
|
||||
|
||||
@app.get("/batch2", response_class=HTMLResponse)
|
||||
async def batch2_page():
|
||||
return Path("static/batch2.html").read_text(encoding="utf-8")
|
||||
|
||||
|
||||
@app.post("/api/batch-v2/upload")
|
||||
async def batch_v2_upload(request: Request):
|
||||
"""Upload zip + target, convert xlsx→CSV, start Claude analysis (SSE stream)."""
|
||||
user = _get_user(request)
|
||||
form = await request.form()
|
||||
zip_file = form.get("zip_file")
|
||||
target_file = form.get("target_file")
|
||||
task_desc = form.get("task_description", "Перенести итоги из смет в сводный файл")
|
||||
|
||||
if not zip_file or not target_file:
|
||||
raise HTTPException(400, "Need zip_file and target_file")
|
||||
|
||||
job_id = str(uuid.uuid4())[:8]
|
||||
job_dir = Path(os.environ.get("DATA_DIR", "./smeta-web-data")) / "_batch_v2" / user / job_id
|
||||
job_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# Save target
|
||||
target_name = Path(target_file.filename).name
|
||||
target_path = job_dir / target_name
|
||||
target_content = await target_file.read()
|
||||
target_path.write_bytes(target_content)
|
||||
# Also save as target.xlsx for Claude
|
||||
(job_dir / "target.xlsx").write_bytes(target_content)
|
||||
|
||||
# Save and extract zip
|
||||
zip_path = job_dir / "source.zip"
|
||||
zip_content = await zip_file.read()
|
||||
zip_path.write_bytes(zip_content)
|
||||
source_dir = job_dir / "source"
|
||||
source_dir.mkdir(exist_ok=True)
|
||||
source_files = extract_zip(str(zip_path), str(source_dir))
|
||||
|
||||
# Convert target → CSV for Claude to read (only the target file)
|
||||
target_only_dir = job_dir / "_target_only"
|
||||
target_only_dir.mkdir(exist_ok=True)
|
||||
shutil.copy2(str(target_path), str(target_only_dir / target_name))
|
||||
target_csv_dir = str(job_dir / "target_csv")
|
||||
batch_v3.convert_all_to_csv(str(target_only_dir), target_csv_dir)
|
||||
shutil.rmtree(str(target_only_dir))
|
||||
|
||||
# Select and convert SAMPLE files (not all — could be 2000+)
|
||||
sample_info = batch_v3.prepare_samples(str(source_dir), job_dir, {})
|
||||
|
||||
# Create job
|
||||
job = batch_v3.create_job(job_id)
|
||||
job["user"] = user # владелец — для проверки доступа в analyze/run/status/download
|
||||
job["source_dir"] = str(source_dir)
|
||||
job["target_file"] = str(target_path)
|
||||
job["target_name"] = target_name
|
||||
job["job_dir"] = str(job_dir)
|
||||
job["total_files"] = len(source_files)
|
||||
job["task_description"] = task_desc
|
||||
job["sample_info"] = sample_info
|
||||
job["status"] = "uploaded"
|
||||
|
||||
return {
|
||||
"job_id": job_id,
|
||||
"total_files": len(source_files),
|
||||
"csv_info": {
|
||||
"sample_count": sample_info["sample_csv_count"],
|
||||
"sample_bytes": sample_info["sample_bytes"],
|
||||
"estimated_tokens": int(sample_info["sample_bytes"] * 0.3),
|
||||
"xlsx_count": len(source_files),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@app.post("/api/batch-v2/analyze/{job_id}")
|
||||
async def batch_v2_analyze(job_id: str, request: Request):
|
||||
"""Start Claude Code analysis — returns SSE stream."""
|
||||
user = _get_user(request)
|
||||
job = _require_job_owner(batch_v3.get_job(job_id), user)
|
||||
|
||||
job_dir = Path(job["job_dir"])
|
||||
task_desc = job["task_description"]
|
||||
target_name = job["target_name"]
|
||||
total_files = job["total_files"]
|
||||
sample_info = job["sample_info"]
|
||||
|
||||
async def event_stream():
|
||||
async for event in batch_v3.run_claude_analysis(
|
||||
job_dir, task_desc, target_name, total_files, sample_info
|
||||
):
|
||||
etype = event.get("type", "")
|
||||
if etype == "text":
|
||||
yield f"event: text\ndata: {json.dumps({'text': event['text']}, ensure_ascii=False)}\n\n"
|
||||
elif etype == "tool":
|
||||
yield f"event: tool\ndata: {json.dumps({'tool': event['tool']}, ensure_ascii=False)}\n\n"
|
||||
elif etype == "done":
|
||||
script = event.get("script", "")
|
||||
summary = event.get("summary", {})
|
||||
if script:
|
||||
job["analysis"] = {"python_script": script, "summary": summary}
|
||||
job["status"] = "analyzed"
|
||||
else:
|
||||
job["analysis"] = {"error": "Claude did not generate script", "result": event.get("result", "")}
|
||||
job["status"] = "analysis_failed"
|
||||
yield f"event: done\ndata: {json.dumps({'script': script, 'summary': summary, 'status': job['status']}, ensure_ascii=False)}\n\n"
|
||||
|
||||
return StreamingResponse(
|
||||
event_stream(),
|
||||
media_type="text/event-stream",
|
||||
headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"},
|
||||
)
|
||||
|
||||
|
||||
@app.post("/api/batch-v2/run/{job_id}")
|
||||
async def batch_v2_run(job_id: str, request: Request):
|
||||
"""Confirm and run the Claude-generated script."""
|
||||
user = _get_user(request)
|
||||
job = _require_job_owner(batch_v3.get_job(job_id), user)
|
||||
|
||||
script = job.get("analysis", {}).get("python_script", "")
|
||||
if not script:
|
||||
raise HTTPException(400, "No script generated")
|
||||
|
||||
threading.Thread(
|
||||
target=batch_v3.run_batch_v2,
|
||||
args=(job_id, script, job["source_dir"], job["target_file"]),
|
||||
daemon=True,
|
||||
).start()
|
||||
|
||||
return {"status": "started", "job_id": job_id}
|
||||
|
||||
|
||||
@app.get("/api/batch-v2/status/{job_id}")
|
||||
async def batch_v2_status(job_id: str, request: Request):
|
||||
user = _get_user(request)
|
||||
job = _require_job_owner(batch_v3.get_job(job_id), user)
|
||||
|
||||
# If status is still "uploaded" but files exist on disk — Claude finished
|
||||
# but SSE didn't deliver the done event
|
||||
if job["status"] == "uploaded" and job.get("job_dir"):
|
||||
job_dir = Path(job["job_dir"])
|
||||
result_data = batch_v3._read_result_files(job_dir)
|
||||
if result_data.get("script"):
|
||||
job["analysis"] = {
|
||||
"python_script": result_data["script"],
|
||||
"summary": result_data.get("summary", {}),
|
||||
}
|
||||
job["status"] = "analyzed"
|
||||
|
||||
analysis = job.get("analysis", {})
|
||||
return {
|
||||
"status": job["status"],
|
||||
"total": job.get("total_files", 0),
|
||||
"processed": job.get("processed", 0),
|
||||
"errors": job.get("errors", [])[:20],
|
||||
"script": analysis.get("python_script", ""),
|
||||
"summary": analysis.get("summary", {}),
|
||||
}
|
||||
|
||||
|
||||
@app.get("/api/batch-v2/download/{job_id}")
|
||||
async def batch_v2_download(job_id: str, request: Request):
|
||||
user = _get_user(request)
|
||||
job = _require_job_owner(batch_v3.get_job(job_id), user)
|
||||
if not job.get("output_file"):
|
||||
raise HTTPException(404, "Result not ready")
|
||||
return FileResponse(job["output_file"], filename=Path(job["output_file"]).name)
|
||||
|
||||
|
||||
# === Admin: view user sessions ===
|
||||
|
||||
|
||||
@@ -1484,169 +1309,6 @@ async def admin_page(request: Request):
|
||||
|
||||
|
||||
# === Batch V3: Generate + Verify + Auto-Retry ===
|
||||
import batch_v3
|
||||
|
||||
|
||||
@app.get("/batch3", response_class=HTMLResponse)
|
||||
async def batch3_page():
|
||||
return Path("static/batch3.html").read_text(encoding="utf-8")
|
||||
|
||||
|
||||
@app.post("/api/batch-v3/upload")
|
||||
async def batch_v3_upload(request: Request):
|
||||
"""Upload zip + target — same as V2 but separate storage."""
|
||||
user = _get_user(request)
|
||||
form = await request.form()
|
||||
zip_file = form.get("zip_file")
|
||||
target_file = form.get("target_file")
|
||||
task_desc = form.get("task_description", "Перенести итоги из смет в сводный файл")
|
||||
|
||||
if not zip_file or not target_file:
|
||||
raise HTTPException(400, "Need zip_file and target_file")
|
||||
|
||||
job_id = str(uuid.uuid4())[:8]
|
||||
job_dir = Path(os.environ.get("DATA_DIR", "./smeta-web-data")) / "_batch_v3" / user / job_id
|
||||
job_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
target_name = Path(target_file.filename).name
|
||||
target_path = job_dir / target_name
|
||||
target_content = await target_file.read()
|
||||
target_path.write_bytes(target_content)
|
||||
(job_dir / "target.xlsx").write_bytes(target_content)
|
||||
|
||||
zip_path = job_dir / "source.zip"
|
||||
zip_content = await zip_file.read()
|
||||
zip_path.write_bytes(zip_content)
|
||||
source_dir = job_dir / "source"
|
||||
source_dir.mkdir(exist_ok=True)
|
||||
source_files = extract_zip(str(zip_path), str(source_dir))
|
||||
|
||||
target_only_dir = job_dir / "_target_only"
|
||||
target_only_dir.mkdir(exist_ok=True)
|
||||
shutil.copy2(str(target_path), str(target_only_dir / target_name))
|
||||
target_csv_dir = str(job_dir / "target_csv")
|
||||
batch_v3.convert_all_to_csv(str(target_only_dir), target_csv_dir)
|
||||
shutil.rmtree(str(target_only_dir))
|
||||
|
||||
sample_info = batch_v3.prepare_samples(str(source_dir), job_dir, {})
|
||||
|
||||
job = batch_v3.create_job(job_id)
|
||||
job["user"] = user # владелец — для проверки доступа в analyze/run/status/download
|
||||
job["source_dir"] = str(source_dir)
|
||||
job["target_file"] = str(target_path)
|
||||
job["target_name"] = target_name
|
||||
job["job_dir"] = str(job_dir)
|
||||
job["total_files"] = len(source_files)
|
||||
job["task_description"] = task_desc
|
||||
job["sample_info"] = sample_info
|
||||
job["status"] = "uploaded"
|
||||
|
||||
return {
|
||||
"job_id": job_id,
|
||||
"total_files": len(source_files),
|
||||
"csv_info": {
|
||||
"sample_count": sample_info["sample_csv_count"],
|
||||
"sample_bytes": sample_info["sample_bytes"],
|
||||
"estimated_tokens": int(sample_info["sample_bytes"] * 0.3),
|
||||
"xlsx_count": len(source_files),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@app.post("/api/batch-v3/analyze/{job_id}")
|
||||
async def batch_v3_analyze(job_id: str, request: Request):
|
||||
"""Generate + verify + auto-retry — SSE stream."""
|
||||
user = _get_user(request)
|
||||
job = _require_job_owner(batch_v3.get_job(job_id), user)
|
||||
|
||||
job_dir = Path(job["job_dir"])
|
||||
|
||||
async def event_stream():
|
||||
async for event in batch_v3.run_generate_and_verify(
|
||||
job_dir,
|
||||
job["task_description"],
|
||||
job["target_name"],
|
||||
job["total_files"],
|
||||
job["sample_info"],
|
||||
job["source_dir"],
|
||||
job["target_file"],
|
||||
):
|
||||
etype = event.get("type", "")
|
||||
if etype in ("text", "tool", "generation_start", "verify_start",
|
||||
"verify_ok", "verify_fail", "retry", "error"):
|
||||
yield f"event: {etype}\ndata: {json.dumps(event, ensure_ascii=False)}\n\n"
|
||||
elif etype == "done":
|
||||
script = event.get("script", "")
|
||||
summary = event.get("summary", {})
|
||||
verified = event.get("verified", False)
|
||||
attempts = event.get("attempts", 0)
|
||||
if script:
|
||||
job["analysis"] = {"python_script": script, "summary": summary}
|
||||
job["status"] = "analyzed"
|
||||
job["verified"] = verified
|
||||
job["verify_attempts"] = attempts
|
||||
else:
|
||||
job["status"] = "analysis_failed"
|
||||
yield f"event: done\ndata: {json.dumps({'script': script, 'summary': summary, 'verified': verified, 'attempts': attempts, 'status': job['status']}, ensure_ascii=False)}\n\n"
|
||||
|
||||
return StreamingResponse(
|
||||
event_stream(),
|
||||
media_type="text/event-stream",
|
||||
headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"},
|
||||
)
|
||||
|
||||
|
||||
@app.post("/api/batch-v3/run/{job_id}")
|
||||
async def batch_v3_run(job_id: str, request: Request):
|
||||
user = _get_user(request)
|
||||
job = _require_job_owner(batch_v3.get_job(job_id), user)
|
||||
script = job.get("analysis", {}).get("python_script", "")
|
||||
if not script:
|
||||
raise HTTPException(400, "No script")
|
||||
threading.Thread(
|
||||
target=batch_v3.run_batch_v3,
|
||||
args=(job_id, script, job["source_dir"], job["target_file"]),
|
||||
daemon=True,
|
||||
).start()
|
||||
return {"status": "started", "job_id": job_id}
|
||||
|
||||
|
||||
@app.get("/api/batch-v3/status/{job_id}")
|
||||
async def batch_v3_status(job_id: str, request: Request):
|
||||
user = _get_user(request)
|
||||
job = _require_job_owner(batch_v3.get_job(job_id), user)
|
||||
|
||||
# Fallback: check disk if SSE didn't deliver
|
||||
if job["status"] == "uploaded" and job.get("job_dir"):
|
||||
result_data = batch_v3._read_result_files(Path(job["job_dir"]))
|
||||
if result_data.get("script"):
|
||||
job["analysis"] = {
|
||||
"python_script": result_data["script"],
|
||||
"summary": result_data.get("summary", {}),
|
||||
}
|
||||
job["status"] = "analyzed"
|
||||
|
||||
analysis = job.get("analysis", {})
|
||||
return {
|
||||
"status": job["status"],
|
||||
"total": job.get("total_files", 0),
|
||||
"processed": job.get("processed", 0),
|
||||
"errors": job.get("errors", [])[:20],
|
||||
"script": analysis.get("python_script", ""),
|
||||
"summary": analysis.get("summary", {}),
|
||||
"verified": job.get("verified", False),
|
||||
"verify_attempts": job.get("verify_attempts", 0),
|
||||
"verify_errors": job.get("verify_errors", []),
|
||||
}
|
||||
|
||||
|
||||
@app.get("/api/batch-v3/download/{job_id}")
|
||||
async def batch_v3_download(job_id: str, request: Request):
|
||||
user = _get_user(request)
|
||||
job = _require_job_owner(batch_v3.get_job(job_id), user)
|
||||
if not job.get("output_file"):
|
||||
raise HTTPException(404, "Result not ready")
|
||||
return FileResponse(job["output_file"], filename=Path(job["output_file"]).name)
|
||||
|
||||
|
||||
# ── SSR Generator ───────────────────────────────────────────────────────────
|
||||
@@ -1655,11 +1317,6 @@ async def batch_v3_download(job_id: str, request: Request):
|
||||
_ssr_jobs: dict[str, dict] = {}
|
||||
|
||||
|
||||
@app.get("/ssr", response_class=HTMLResponse)
|
||||
async def ssr_page():
|
||||
return Path("static/ssr.html").read_text(encoding="utf-8")
|
||||
|
||||
|
||||
def _import_ssr_scripts():
|
||||
"""Import smeta-railway scripts (installed via pip install -e)."""
|
||||
import sys
|
||||
@@ -1671,113 +1328,6 @@ def _import_ssr_scripts():
|
||||
sys.path.insert(0, scripts_dir)
|
||||
|
||||
|
||||
@app.post("/api/ssr/upload")
|
||||
async def ssr_upload(request: Request):
|
||||
"""Upload ZIP (+ optional xlsx) → fill or generate SSR → return preview."""
|
||||
user = _get_user(request)
|
||||
form = await request.form()
|
||||
zip_file: UploadFile = form.get("zip_file")
|
||||
if not zip_file or not zip_file.filename.lower().endswith(".zip"):
|
||||
raise HTTPException(400, "ZIP file required")
|
||||
|
||||
xlsx_file: UploadFile = form.get("xlsx_file")
|
||||
mode = form.get("mode", "generate") # "fill" or "generate"
|
||||
|
||||
# Params (for generate mode)
|
||||
winter_pct = float(form.get("winter_pct", 3.2))
|
||||
control_pct = float(form.get("control_pct", 0.55))
|
||||
reserve_pct = float(form.get("reserve_pct", 1.0))
|
||||
vat_pct = float(form.get("vat_pct", 22.0))
|
||||
|
||||
job_id = str(uuid.uuid4())[:8]
|
||||
data_dir = Path(os.environ.get("DATA_DIR", "./smeta-web-data"))
|
||||
job_dir = data_dir / "_ssr" / user / job_id
|
||||
job_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# Save ZIP
|
||||
zip_path = job_dir / "source.zip"
|
||||
zip_path.write_bytes(await zip_file.read())
|
||||
|
||||
_import_ssr_scripts()
|
||||
|
||||
if mode == "fill" and xlsx_file:
|
||||
# Mode: fill existing xlsx with GGE data
|
||||
try:
|
||||
from fill_raspredelenie import fill_raspredelenie_from_zip
|
||||
except ImportError:
|
||||
raise HTTPException(500, "smeta-railway scripts not found")
|
||||
|
||||
xlsx_path = job_dir / xlsx_file.filename
|
||||
xlsx_path.write_bytes(await xlsx_file.read())
|
||||
|
||||
output_path = str(job_dir / f"filled_{xlsx_file.filename}")
|
||||
result = fill_raspredelenie_from_zip(str(zip_path), str(xlsx_path), output_path)
|
||||
|
||||
if "error" in result:
|
||||
raise HTTPException(400, result["error"])
|
||||
|
||||
html_path = str(job_dir / "protocol.html")
|
||||
Path(html_path).write_text(result["html"], encoding="utf-8")
|
||||
|
||||
_ssr_jobs[job_id] = {
|
||||
"user": user, "job_dir": str(job_dir),
|
||||
"xlsx_path": output_path, "html_path": html_path,
|
||||
"result": result["stats"],
|
||||
}
|
||||
|
||||
return {
|
||||
"job_id": job_id,
|
||||
"preview_html": result["html"],
|
||||
"stats": result["stats"],
|
||||
"mode": "fill",
|
||||
}
|
||||
|
||||
else:
|
||||
# Mode: generate new SSR from scratch
|
||||
try:
|
||||
from parse_gge_structure import parse_gge_from_zip
|
||||
from generate_ssr import generate_ssr_from_data
|
||||
except ImportError:
|
||||
raise HTTPException(500, "smeta-railway scripts not found")
|
||||
|
||||
data = parse_gge_from_zip(str(zip_path))
|
||||
xlsx_path = str(job_dir / "ssr.xlsx")
|
||||
html_path = str(job_dir / "ssr.html")
|
||||
result = generate_ssr_from_data(
|
||||
data, xlsx_path, html_path,
|
||||
winter_pct=winter_pct, control_pct=control_pct,
|
||||
reserve_pct=reserve_pct, vat_pct=vat_pct,
|
||||
)
|
||||
|
||||
_ssr_jobs[job_id] = {
|
||||
"user": user, "job_dir": str(job_dir),
|
||||
"xlsx_path": xlsx_path, "html_path": html_path,
|
||||
"result": result,
|
||||
}
|
||||
|
||||
preview_html = Path(html_path).read_text(encoding="utf-8")
|
||||
return {
|
||||
"job_id": job_id,
|
||||
"preview_html": preview_html,
|
||||
"stats": result,
|
||||
"mode": "generate",
|
||||
}
|
||||
|
||||
|
||||
@app.get("/api/ssr/preview/{job_id}")
|
||||
async def ssr_preview(job_id: str, request: Request):
|
||||
user = _get_user(request)
|
||||
job = _require_job_owner(_ssr_jobs.get(job_id), user)
|
||||
return HTMLResponse(Path(job["html_path"]).read_text(encoding="utf-8"))
|
||||
|
||||
|
||||
@app.get("/api/ssr/download/{job_id}")
|
||||
async def ssr_download(job_id: str, request: Request):
|
||||
user = _get_user(request)
|
||||
job = _require_job_owner(_ssr_jobs.get(job_id), user)
|
||||
return FileResponse(job["xlsx_path"], filename="ssr_generated.xlsx")
|
||||
|
||||
|
||||
# ── Wizard Aggregator ──────────────────────────────────────────────────────
|
||||
|
||||
def _import_smeta_railway():
|
||||
@@ -1793,166 +1343,32 @@ def _import_smeta_railway():
|
||||
_import_smeta_railway()
|
||||
|
||||
|
||||
@app.get("/wizard", response_class=HTMLResponse)
|
||||
async def wizard_page():
|
||||
return Path("static/wizard.html").read_text(encoding="utf-8")
|
||||
|
||||
|
||||
# Import and mount smeta-railway routers
|
||||
from smeta_railway.web.wizard_api import router as _wizard_router
|
||||
from smeta_railway.web.generator_api import router as _gen_router
|
||||
from smeta_railway.web.chat_api import router as _chat_sr_router
|
||||
|
||||
# Смонтированные роутеры не имели auth вообще → аноним жёг LLM/RAG-бюджет и грузил
|
||||
# файлы (Fable verify). Гейт на уровне монтирования — БЕЗ правки чужого пакета smeta_railway.
|
||||
# Живой чат их не использует (только депрекированные generate/reference/wizard).
|
||||
app.include_router(_wizard_router, prefix="/api/wizard", dependencies=[Depends(_auth_dep)])
|
||||
app.include_router(_gen_router, prefix="/api/gen", dependencies=[Depends(_auth_dep)])
|
||||
app.include_router(_chat_sr_router, prefix="/api/ref", dependencies=[Depends(_auth_dep)])
|
||||
|
||||
|
||||
@app.get("/generate", response_class=HTMLResponse)
|
||||
async def generate_page():
|
||||
return Path("static/generate.html").read_text(encoding="utf-8")
|
||||
|
||||
|
||||
@app.get("/reference", response_class=HTMLResponse)
|
||||
async def reference_page():
|
||||
return Path("static/reference.html").read_text(encoding="utf-8")
|
||||
|
||||
|
||||
# ── Estimate Checker ──────────────────────────────────────────────────────
|
||||
|
||||
@app.get("/check", response_class=HTMLResponse)
|
||||
async def check_page():
|
||||
return Path("static/check.html").read_text(encoding="utf-8")
|
||||
|
||||
|
||||
@app.post("/api/check/yaml")
|
||||
async def check_yaml_endpoint(request: Request):
|
||||
"""Validate YAML config and return check report."""
|
||||
import tempfile
|
||||
from smeta_railway.ai.checker import check_yaml_config, format_report
|
||||
|
||||
_get_user(request) # закрыт от анонима (был публичный compute-эндпоинт)
|
||||
body = await request.json()
|
||||
yaml_content = body.get("yaml", "")
|
||||
if not yaml_content.strip():
|
||||
raise HTTPException(400, "Empty YAML")
|
||||
|
||||
# Write to temp file for checker
|
||||
with tempfile.NamedTemporaryFile(mode="w", suffix=".yaml", delete=False) as f:
|
||||
f.write(yaml_content)
|
||||
tmp_path = f.name
|
||||
|
||||
try:
|
||||
report = check_yaml_config(tmp_path)
|
||||
return {
|
||||
"errors": report.errors,
|
||||
"warnings": report.warnings,
|
||||
"info": report.info,
|
||||
"results": [
|
||||
{"level": r.level, "code": r.code, "message": r.message, "position": r.position}
|
||||
for r in report.results
|
||||
],
|
||||
"formatted": format_report(report),
|
||||
}
|
||||
except Exception as exc:
|
||||
logger.exception("check_yaml failed") # детали — в лог оператору, не клиенту
|
||||
return {"error": "Не удалось проверить конфигурацию", "results": []}
|
||||
finally:
|
||||
Path(tmp_path).unlink(missing_ok=True)
|
||||
|
||||
|
||||
# ── Full Pipeline: YAML → Calculate → Excel ───────────────────────────────
|
||||
|
||||
@app.post("/api/gen/calculate")
|
||||
async def calculate_estimate(request: Request):
|
||||
"""Take YAML config, run calculation, generate Excel, return download link."""
|
||||
_get_user(request) # был аноним; ниже мёртвый код с сырым traceback — закрыть до ревайва
|
||||
# ⛔ Путь LLM→движок пока НЕ оживлён: код ниже зовёт несуществующие методы
|
||||
# (ProjectConfig.from_yaml_string / NormResources.from_dict / FGISLookup(region=))
|
||||
# и отдавал сырой traceback пользователю. Кнопка «Генерация» депрекирована
|
||||
# (chat.html, 2026-05-07), путь достижим лишь прямым URL. До keystone-ревайва
|
||||
# (роадмап: оживить контракт с fail-loud цен + проверенным маппингом НР/СП по
|
||||
# 812/774/пр) — честный ответ вместо сырой ошибки. Логика ниже сохранена как
|
||||
# стартовая точка ревайва.
|
||||
return {
|
||||
"error": "Автоматический расчёт сметы пока в разработке — функция скоро появится.",
|
||||
"download_url": None,
|
||||
}
|
||||
import tempfile
|
||||
import yaml as pyyaml
|
||||
|
||||
body = await request.json()
|
||||
yaml_str = body.get("yaml", "")
|
||||
if not yaml_str.strip():
|
||||
raise HTTPException(400, "Empty YAML")
|
||||
|
||||
try:
|
||||
from smeta_railway.config import ProjectConfig
|
||||
from smeta_railway.calc.estimate import EstimateCalculator
|
||||
from smeta_railway.data.fgis import FGISLookup
|
||||
from smeta_railway.output.excel_se import write_excel
|
||||
from smeta_railway.models import NormResources
|
||||
|
||||
# Parse config
|
||||
config = ProjectConfig.from_yaml_string(yaml_str)
|
||||
|
||||
# Load resources
|
||||
resources_path = Path(__file__).resolve().parent / ".." / "smeta-railway" / "resources.json"
|
||||
if not resources_path.exists():
|
||||
resources_path = Path.home() / "smeta-railway" / "resources.json"
|
||||
if not resources_path.exists():
|
||||
return {"error": "resources.json не найден — расчёт невозможен", "download_url": None}
|
||||
|
||||
import json as _json
|
||||
raw = _json.loads(resources_path.read_text(encoding="utf-8"))
|
||||
resources = {k: NormResources.from_dict(v) for k, v in raw.items()}
|
||||
|
||||
# FGIS lookup
|
||||
fgis = FGISLookup(region=config.region)
|
||||
|
||||
# Calculate
|
||||
calc = EstimateCalculator(
|
||||
fgis=fgis,
|
||||
resources=resources,
|
||||
coeff_config=config.coefficients,
|
||||
overhead_config=config.overhead,
|
||||
limited_costs_config=config.limited_costs,
|
||||
)
|
||||
result = calc.calculate(config.sections)
|
||||
|
||||
# Write Excel
|
||||
data_dir = Path(os.environ.get("DATA_DIR", "./smeta-web-data")) / "_estimates"
|
||||
data_dir.mkdir(parents=True, exist_ok=True)
|
||||
job_id = str(uuid.uuid4())[:8]
|
||||
xlsx_path = data_dir / f"estimate_{job_id}.xlsx"
|
||||
write_excel(result, str(xlsx_path), config)
|
||||
|
||||
return {
|
||||
"download_url": f"/api/gen/download/{job_id}",
|
||||
"positions": len(result.positions),
|
||||
"total": result.total if hasattr(result, "total") else None,
|
||||
"error": None,
|
||||
}
|
||||
except Exception as exc:
|
||||
import traceback
|
||||
return {"error": str(exc), "detail": traceback.format_exc()[-500:], "download_url": None}
|
||||
# ── Депрекированные страницы → всё переехало в чат (Fable retire 2026-07-18) ──
|
||||
# Пакетная обработка/SSR/генерация: там ИИ-скрипт исполнялся на хосте (риск RCE
|
||||
# через смету-с-начинкой) + анонимные роуты. Функционал давно заменён чатом.
|
||||
from fastapi.responses import RedirectResponse as _DepRedirect
|
||||
|
||||
|
||||
@app.get("/api/gen/download/{job_id}")
|
||||
async def download_estimate(job_id: str, request: Request):
|
||||
"""Download generated Excel estimate."""
|
||||
_get_user(request) # был публичный доступ к файлам по угадываемому id
|
||||
safe_id = Path(job_id).name # без traversal в имени файла
|
||||
data_dir = Path(os.environ.get("DATA_DIR", "./smeta-web-data")) / "_estimates"
|
||||
xlsx_path = data_dir / f"estimate_{safe_id}.xlsx"
|
||||
if not xlsx_path.exists():
|
||||
raise HTTPException(404, "Файл не найден")
|
||||
return FileResponse(str(xlsx_path), filename=f"smeta_{safe_id}.xlsx")
|
||||
async def _deprecated_moved():
|
||||
return _DepRedirect("/", status_code=302)
|
||||
|
||||
|
||||
for _dep_url in ("/batch", "/batch2", "/batch3", "/ssr", "/wizard",
|
||||
"/generate", "/reference", "/check"):
|
||||
app.add_api_route(_dep_url, _deprecated_moved, methods=["GET"], include_in_schema=False)
|
||||
|
||||
if __name__ == "__main__":
|
||||
import uvicorn
|
||||
uvicorn.run(app, host="0.0.0.0", port=int(os.environ.get("PORT", "8000")))
|
||||
|
||||
@@ -1,157 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Пакетная обработка смет</title>
|
||||
<style>
|
||||
:root { --bg: #f5f0eb; --card: #fff; --text: #3a3a3a; --muted: #6b6b6b; --accent: #c4463a; --border: #d4c5b2; --radius: 10px; }
|
||||
* { box-sizing: border-box; margin: 0; padding: 0; }
|
||||
body { font-family: 'Inter', -apple-system, sans-serif; background: var(--bg); color: var(--text); min-height: 100vh; padding: 2rem; }
|
||||
.container { max-width: 700px; margin: 0 auto; }
|
||||
h1 { font-size: 1.3rem; margin-bottom: .3rem; }
|
||||
.subtitle { color: var(--muted); font-size: .9rem; margin-bottom: 1.5rem; }
|
||||
.card { background: var(--card); border-radius: var(--radius); padding: 1.5rem; margin-bottom: 1rem; box-shadow: 0 1px 4px rgba(0,0,0,.06); }
|
||||
label { display: block; font-weight: 600; margin-bottom: .4rem; font-size: .9rem; }
|
||||
.hint { color: var(--muted); font-size: .8rem; margin-bottom: .6rem; }
|
||||
input[type=file] { width: 100%; padding: .5rem; border: 1.5px dashed var(--border); border-radius: var(--radius); margin-bottom: 1rem; }
|
||||
textarea { width: 100%; padding: .6rem; border: 1.5px solid var(--border); border-radius: var(--radius); font-family: inherit; font-size: .9rem; resize: vertical; min-height: 60px; }
|
||||
button { padding: .7rem 1.5rem; background: var(--accent); color: #fff; border: none; border-radius: var(--radius); font-size: .95rem; font-weight: 600; cursor: pointer; }
|
||||
button:hover { background: #a83830; }
|
||||
button:disabled { background: var(--border); cursor: not-allowed; }
|
||||
.back { display: inline-block; margin-bottom: 1rem; color: var(--accent); text-decoration: none; font-size: .85rem; }
|
||||
#status { display: none; }
|
||||
#analysis { display: none; }
|
||||
.progress { background: #ede5db; border-radius: 6px; height: 8px; margin: .5rem 0; }
|
||||
.progress-bar { background: var(--accent); height: 100%; border-radius: 6px; transition: width .3s; }
|
||||
.error-list { color: #c4463a; font-size: .8rem; margin-top: .5rem; }
|
||||
pre { background: #2c2c2c; color: #f5f0eb; padding: .8rem; border-radius: 6px; overflow-x: auto; font-size: .8rem; margin: .5rem 0; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<a class="back" href="/">← Вернуться в чат</a>
|
||||
<h1>Пакетная обработка смет</h1>
|
||||
<p class="subtitle">Загрузите архив со сметами и сводный файл — ИИ проанализирует структуру и перенесёт данные</p>
|
||||
|
||||
<div class="card" id="upload-form">
|
||||
<label>Архив со сметами (.zip)</label>
|
||||
<p class="hint">Все файлы локальных смет в одном архиве</p>
|
||||
<input type="file" id="zip-file" accept=".zip">
|
||||
|
||||
<label>Сводный файл (.xlsx)</label>
|
||||
<p class="hint">Файл, в который нужно внести данные (ССР, ведомость и т.д.)</p>
|
||||
<input type="file" id="target-file" accept=".xlsx,.xls">
|
||||
|
||||
<label>Описание задачи</label>
|
||||
<textarea id="task-desc" placeholder="Например: Из каждой сметы взять итого строительных работ (тыс.руб.) и внести в соответствующую строку ССР"></textarea>
|
||||
<br><br>
|
||||
<button onclick="startBatch()">Анализировать</button>
|
||||
</div>
|
||||
|
||||
<div class="card" id="analysis">
|
||||
<h3>Результат анализа</h3>
|
||||
<p id="analysis-desc"></p>
|
||||
<details>
|
||||
<summary>Сгенерированный скрипт</summary>
|
||||
<pre id="analysis-script"></pre>
|
||||
</details>
|
||||
<p id="analysis-files" style="margin:.5rem 0;color:var(--muted);font-size:.85rem"></p>
|
||||
<button onclick="runBatch()">Запустить обработку</button>
|
||||
</div>
|
||||
|
||||
<div class="card" id="status">
|
||||
<h3>Обработка</h3>
|
||||
<p id="status-text"></p>
|
||||
<div class="progress"><div class="progress-bar" id="progress-bar" style="width:0%"></div></div>
|
||||
<p id="status-count" style="font-size:.85rem;color:var(--muted)"></p>
|
||||
<div class="error-list" id="error-list"></div>
|
||||
<button id="download-btn" style="display:none" onclick="downloadResult()">Скачать результат</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
const API = '';
|
||||
let token = localStorage.getItem('token');
|
||||
let jobId = null;
|
||||
|
||||
if (!token) { window.location.href = '/'; }
|
||||
|
||||
function authHeaders() { return {'Authorization': 'Bearer ' + token}; }
|
||||
|
||||
async function startBatch() {
|
||||
const zipFile = document.getElementById('zip-file').files[0];
|
||||
const targetFile = document.getElementById('target-file').files[0];
|
||||
const taskDesc = document.getElementById('task-desc').value;
|
||||
if (!zipFile || !targetFile) { alert('Загрузите оба файла'); return; }
|
||||
|
||||
const fd = new FormData();
|
||||
fd.append('zip_file', zipFile);
|
||||
fd.append('target_file', targetFile);
|
||||
fd.append('task_description', taskDesc || 'Перенести итоги из смет в сводный файл');
|
||||
|
||||
document.querySelector('#upload-form button').disabled = true;
|
||||
document.querySelector('#upload-form button').textContent = 'Анализирую...';
|
||||
|
||||
try {
|
||||
const r = await fetch(API + '/api/batch/upload', {method: 'POST', headers: authHeaders(), body: fd});
|
||||
if (r.status === 401) { window.location.href = '/'; return; }
|
||||
const data = await r.json();
|
||||
if (data.analysis?.error) { alert('Ошибка: ' + data.analysis.error); return; }
|
||||
|
||||
jobId = data.job_id;
|
||||
document.getElementById('analysis-desc').textContent = data.analysis.description || 'Анализ завершён';
|
||||
document.getElementById('analysis-script').textContent = data.analysis.python_script || '(нет скрипта)';
|
||||
document.getElementById('analysis-files').textContent = 'Файлов: ' + data.total_files;
|
||||
document.getElementById('analysis').style.display = 'block';
|
||||
} catch(e) { alert('Ошибка: ' + e.message); }
|
||||
finally {
|
||||
document.querySelector('#upload-form button').disabled = false;
|
||||
document.querySelector('#upload-form button').textContent = 'Анализировать';
|
||||
}
|
||||
}
|
||||
|
||||
async function runBatch() {
|
||||
if (!jobId) return;
|
||||
document.querySelector('#analysis button').disabled = true;
|
||||
const r = await fetch(API + '/api/batch/run/' + jobId, {method: 'POST', headers: authHeaders()});
|
||||
if (!r.ok) { alert('Ошибка запуска'); return; }
|
||||
|
||||
document.getElementById('status').style.display = 'block';
|
||||
pollStatus();
|
||||
}
|
||||
|
||||
async function pollStatus() {
|
||||
const r = await fetch(API + '/api/batch/status/' + jobId, {headers: authHeaders()});
|
||||
const data = await r.json();
|
||||
|
||||
const pct = data.total > 0 ? (data.processed / data.total * 100) : 0;
|
||||
document.getElementById('progress-bar').style.width = pct + '%';
|
||||
document.getElementById('status-count').textContent = data.processed + ' / ' + data.total + ' файлов';
|
||||
|
||||
if (data.status === 'running') {
|
||||
document.getElementById('status-text').textContent = 'Обработка...';
|
||||
setTimeout(pollStatus, 2000);
|
||||
} else if (data.status === 'completed') {
|
||||
document.getElementById('status-text').textContent = 'Готово!';
|
||||
document.getElementById('download-btn').style.display = 'inline-block';
|
||||
} else if (data.status === 'failed') {
|
||||
document.getElementById('status-text').textContent = 'Ошибка: ' + (data.errors[0] || 'неизвестная');
|
||||
}
|
||||
|
||||
if (data.errors.length > 0) {
|
||||
document.getElementById('error-list').innerHTML = '<b>Ошибки:</b><br>' + data.errors.map(e => '• ' + e).join('<br>');
|
||||
}
|
||||
}
|
||||
|
||||
function downloadResult() {
|
||||
const a = document.createElement('a');
|
||||
a.href = API + '/api/batch/download/' + jobId;
|
||||
fetch(a.href, {headers: authHeaders()}).then(r => r.blob()).then(b => {
|
||||
const u = URL.createObjectURL(b);
|
||||
const l = document.createElement('a'); l.href = u; l.download = 'result.xlsx'; l.click();
|
||||
});
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,348 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Пакетная обработка V2 — Claude Code</title>
|
||||
<style>
|
||||
:root { --bg: #f5f0eb; --card: #fff; --text: #3a3a3a; --muted: #6b6b6b; --accent: #c4463a; --border: #d4c5b2; --radius: 10px; --green: #2d8a56; }
|
||||
* { box-sizing: border-box; margin: 0; padding: 0; }
|
||||
body { font-family: 'Inter', -apple-system, sans-serif; background: var(--bg); color: var(--text); min-height: 100vh; padding: 2rem; }
|
||||
.container { max-width: 750px; margin: 0 auto; }
|
||||
h1 { font-size: 1.3rem; margin-bottom: .3rem; }
|
||||
.subtitle { color: var(--muted); font-size: .9rem; margin-bottom: 1.5rem; }
|
||||
.badge { display: inline-block; background: var(--green); color: #fff; font-size: .7rem; padding: 2px 8px; border-radius: 12px; vertical-align: middle; margin-left: .5rem; }
|
||||
.card { background: var(--card); border-radius: var(--radius); padding: 1.5rem; margin-bottom: 1rem; box-shadow: 0 1px 4px rgba(0,0,0,.06); }
|
||||
.card.hidden { display: none; }
|
||||
label { display: block; font-weight: 600; margin-bottom: .4rem; font-size: .9rem; }
|
||||
.hint { color: var(--muted); font-size: .8rem; margin-bottom: .6rem; }
|
||||
input[type=file] { width: 100%; padding: .5rem; border: 1.5px dashed var(--border); border-radius: var(--radius); margin-bottom: 1rem; }
|
||||
textarea { width: 100%; padding: .6rem; border: 1.5px solid var(--border); border-radius: var(--radius); font-family: inherit; font-size: .9rem; resize: vertical; min-height: 80px; }
|
||||
button { padding: .7rem 1.5rem; background: var(--accent); color: #fff; border: none; border-radius: var(--radius); font-size: .95rem; font-weight: 600; cursor: pointer; }
|
||||
button:hover { background: #a83830; }
|
||||
button:disabled { background: var(--border); cursor: not-allowed; }
|
||||
.back { display: inline-block; margin-bottom: 1rem; color: var(--accent); text-decoration: none; font-size: .85rem; }
|
||||
.progress { background: #ede5db; border-radius: 6px; height: 8px; margin: .5rem 0; }
|
||||
.progress-bar { background: var(--accent); height: 100%; border-radius: 6px; transition: width .3s; }
|
||||
.error-list { color: #c4463a; font-size: .8rem; margin-top: .5rem; max-height: 200px; overflow-y: auto; }
|
||||
pre { background: #2c2c2c; color: #f5f0eb; padding: .8rem; border-radius: 6px; overflow-x: auto; font-size: .78rem; margin: .5rem 0; max-height: 400px; overflow-y: auto; white-space: pre-wrap; word-break: break-word; }
|
||||
.log { background: #1a1a2e; color: #a0d2db; padding: .8rem; border-radius: 6px; font-size: .78rem; margin: .5rem 0; max-height: 300px; overflow-y: auto; font-family: monospace; white-space: pre-wrap; word-break: break-word; }
|
||||
.info-row { display: flex; gap: 1rem; margin: .5rem 0; font-size: .85rem; color: var(--muted); }
|
||||
.info-row span { background: #ede5db; padding: 3px 10px; border-radius: 6px; }
|
||||
.spinner { display: inline-block; width: 16px; height: 16px; border: 2px solid var(--border); border-top-color: var(--accent); border-radius: 50%; animation: spin .8s linear infinite; vertical-align: middle; margin-right: 6px; }
|
||||
@keyframes spin { to { transform: rotate(360deg); } }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<a class="back" href="/">← Вернуться в чат</a>
|
||||
<h1>Пакетная обработка смет <span class="badge">V2 Claude</span></h1>
|
||||
<p class="subtitle">Claude Code читает ВСЕ файлы, понимает структуру, генерирует скрипт обработки</p>
|
||||
|
||||
<!-- Step 1: Upload -->
|
||||
<div class="card" id="step-upload">
|
||||
<label>1. Архив со сметами (.zip)</label>
|
||||
<p class="hint">Все файлы локальных смет в одном архиве (до 2000 файлов)</p>
|
||||
<input type="file" id="zip-file" accept=".zip">
|
||||
|
||||
<label>Сводный файл (.xlsx)</label>
|
||||
<p class="hint">Файл, в который нужно внести данные (ССР, ведомость и т.д.)</p>
|
||||
<input type="file" id="target-file" accept=".xlsx,.xls">
|
||||
|
||||
<label>Описание задачи</label>
|
||||
<p class="hint">Опишите что именно нужно сделать — Claude прочитает файлы и разберётся</p>
|
||||
<textarea id="task-desc" placeholder="Из каждого файла взять итоговые суммы по типам работ (строительные, монтажные, оборудование, прочие) и внести в соответствующие строки и колонки сводного файла. Значения в исходных файлах в рублях, в сводном — тыс.руб."></textarea>
|
||||
<br><br>
|
||||
<button id="btn-upload" onclick="uploadFiles()">Загрузить и конвертировать</button>
|
||||
</div>
|
||||
|
||||
<!-- Step 2: Analysis -->
|
||||
<div class="card hidden" id="step-analyze">
|
||||
<label>2. Анализ Claude Code</label>
|
||||
<div class="info-row" id="csv-info"></div>
|
||||
<p style="margin:.5rem 0;font-size:.9rem"><span class="spinner" id="analyze-spinner"></span> <span id="analyze-status">Claude анализирует файлы...</span> <span id="analyze-timer" style="color:var(--muted);font-size:.8rem"></span></p>
|
||||
<div class="log" id="analyze-log"></div>
|
||||
</div>
|
||||
|
||||
<!-- Step 3: Confirm -->
|
||||
<div class="card hidden" id="step-confirm">
|
||||
<label>3. Проверьте найденные параметры</label>
|
||||
<div id="summary-view" style="font-size:.9rem;line-height:1.6"></div>
|
||||
<details style="margin-top:.8rem">
|
||||
<summary style="cursor:pointer;color:var(--muted);font-size:.8rem">Показать скрипт (для разработчиков)</summary>
|
||||
<pre id="script-code"></pre>
|
||||
</details>
|
||||
<div style="display:flex;gap:.5rem;margin-top:.8rem">
|
||||
<button onclick="runScript()">Запустить обработку</button>
|
||||
<button onclick="reanalyze()" style="background:var(--border);color:var(--text)">Переанализировать</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Step 4: Execution -->
|
||||
<div class="card hidden" id="step-run">
|
||||
<label>4. Выполнение</label>
|
||||
<p id="run-status"></p>
|
||||
<div class="progress"><div class="progress-bar" id="run-progress" style="width:0%"></div></div>
|
||||
<p id="run-count" style="font-size:.85rem;color:var(--muted)"></p>
|
||||
<div class="error-list" id="run-errors"></div>
|
||||
<button id="btn-download" style="display:none" onclick="downloadResult()">Скачать результат</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
const token = localStorage.getItem('token');
|
||||
if (!token) window.location.href = '/';
|
||||
|
||||
const H = {'Authorization': 'Bearer ' + token};
|
||||
let jobId = null;
|
||||
let timerInterval = null;
|
||||
let timerStart = 0;
|
||||
|
||||
function show(id) { document.getElementById(id).classList.remove('hidden'); }
|
||||
function hide(id) { document.getElementById(id).classList.add('hidden'); }
|
||||
|
||||
function startTimer() {
|
||||
timerStart = Date.now();
|
||||
timerInterval = setInterval(() => {
|
||||
const s = Math.floor((Date.now() - timerStart) / 1000);
|
||||
const m = Math.floor(s / 60);
|
||||
const sec = s % 60;
|
||||
document.getElementById('analyze-timer').textContent = m > 0 ? m + 'м ' + sec + 'с' : sec + 'с';
|
||||
}, 1000);
|
||||
}
|
||||
function stopTimer() { if (timerInterval) { clearInterval(timerInterval); timerInterval = null; } }
|
||||
|
||||
async function uploadFiles() {
|
||||
const zipFile = document.getElementById('zip-file').files[0];
|
||||
const targetFile = document.getElementById('target-file').files[0];
|
||||
const taskDesc = document.getElementById('task-desc').value;
|
||||
if (!zipFile || !targetFile) { alert('Загрузите оба файла'); return; }
|
||||
|
||||
const btn = document.getElementById('btn-upload');
|
||||
btn.disabled = true; btn.textContent = 'Загружаю...';
|
||||
|
||||
const fd = new FormData();
|
||||
fd.append('zip_file', zipFile);
|
||||
fd.append('target_file', targetFile);
|
||||
fd.append('task_description', taskDesc || 'Перенести итоги из смет в сводный файл');
|
||||
|
||||
try {
|
||||
const r = await fetch('/api/batch-v2/upload', {method: 'POST', headers: H, body: fd});
|
||||
if (r.status === 401) { window.location.href = '/'; return; }
|
||||
const data = await r.json();
|
||||
jobId = data.job_id;
|
||||
|
||||
const info = data.csv_info;
|
||||
document.getElementById('csv-info').innerHTML =
|
||||
`<span>${data.total_files} xlsx всего</span>` +
|
||||
`<span>${info.sample_count} CSV сэмплов</span>` +
|
||||
`<span>~${Math.round(info.estimated_tokens/1000)}K токенов</span>`;
|
||||
|
||||
show('step-analyze');
|
||||
startAnalysis();
|
||||
} catch(e) { alert('Ошибка: ' + e.message); }
|
||||
finally { btn.disabled = false; btn.textContent = 'Загрузить и конвертировать'; }
|
||||
}
|
||||
|
||||
async function startAnalysis() {
|
||||
const log = document.getElementById('analyze-log');
|
||||
log.textContent = '';
|
||||
startTimer();
|
||||
|
||||
try {
|
||||
const r = await fetch('/api/batch-v2/analyze/' + jobId, {method: 'POST', headers: H});
|
||||
const reader = r.body.getReader();
|
||||
const decoder = new TextDecoder();
|
||||
let buffer = '';
|
||||
|
||||
while (true) {
|
||||
const {done, value} = await reader.read();
|
||||
if (done) break;
|
||||
buffer += decoder.decode(value, {stream: true});
|
||||
|
||||
const lines = buffer.split('\n');
|
||||
buffer = lines.pop(); // keep incomplete line
|
||||
|
||||
let eventType = '';
|
||||
for (const line of lines) {
|
||||
if (line.startsWith('event: ')) { eventType = line.slice(7); continue; }
|
||||
if (!line.startsWith('data: ')) continue;
|
||||
try {
|
||||
const d = JSON.parse(line.slice(6));
|
||||
if (eventType === 'text') {
|
||||
log.textContent += d.text;
|
||||
log.scrollTop = log.scrollHeight;
|
||||
} else if (eventType === 'tool') {
|
||||
log.textContent += '\n[tool: ' + d.tool + ']\n';
|
||||
log.scrollTop = log.scrollHeight;
|
||||
} else if (eventType === 'done') {
|
||||
document.getElementById('analyze-spinner').style.display = 'none';
|
||||
stopTimer();
|
||||
if (d.script) {
|
||||
document.getElementById('analyze-status').textContent = 'Анализ завершён';
|
||||
document.getElementById('script-code').textContent = d.script;
|
||||
renderSummary(d.summary);
|
||||
show('step-confirm');
|
||||
} else {
|
||||
document.getElementById('analyze-status').textContent = 'Claude не сгенерировал скрипт';
|
||||
document.getElementById('analyze-status').style.color = 'var(--accent)';
|
||||
}
|
||||
}
|
||||
} catch(e) {}
|
||||
}
|
||||
}
|
||||
} catch(e) {
|
||||
// Network error or stream closed — ignore, fall through to polling
|
||||
}
|
||||
|
||||
// Fallback: if SSE ended without 'done' event, poll status
|
||||
if (!document.getElementById('step-confirm').classList.contains('hidden')) return; // already shown
|
||||
stopTimer();
|
||||
document.getElementById('analyze-status').textContent = 'Проверяю результат...';
|
||||
for (let i = 0; i < 10; i++) {
|
||||
await new Promise(r => setTimeout(r, 2000));
|
||||
try {
|
||||
const sr = await fetch('/api/batch-v2/status/' + jobId, {headers: H});
|
||||
const sd = await sr.json();
|
||||
if (sd.status === 'analyzed' && sd.script) {
|
||||
document.getElementById('analyze-spinner').style.display = 'none';
|
||||
document.getElementById('analyze-status').textContent = 'Анализ завершён';
|
||||
document.getElementById('script-code').textContent = sd.script;
|
||||
// Fetch summary from status if available
|
||||
renderSummary(sd.summary || {});
|
||||
show('step-confirm');
|
||||
return;
|
||||
} else if (sd.status === 'analysis_failed') {
|
||||
document.getElementById('analyze-spinner').style.display = 'none';
|
||||
document.getElementById('analyze-status').textContent = 'Ошибка анализа';
|
||||
document.getElementById('analyze-status').style.color = 'var(--accent)';
|
||||
return;
|
||||
}
|
||||
} catch(e2) {}
|
||||
}
|
||||
document.getElementById('analyze-spinner').style.display = 'none';
|
||||
document.getElementById('analyze-status').textContent = 'Таймаут — попробуйте ещё раз';
|
||||
document.getElementById('analyze-status').style.color = 'var(--accent)';
|
||||
}
|
||||
|
||||
async function reanalyze() {
|
||||
hide('step-confirm');
|
||||
document.getElementById('analyze-spinner').style.display = 'inline-block';
|
||||
document.getElementById('analyze-status').textContent = 'Claude анализирует файлы...';
|
||||
document.getElementById('analyze-status').style.color = '';
|
||||
startAnalysis();
|
||||
}
|
||||
|
||||
async function runScript() {
|
||||
try {
|
||||
const r = await fetch('/api/batch-v2/run/' + jobId, {method: 'POST', headers: H});
|
||||
if (!r.ok) { alert('Ошибка запуска'); return; }
|
||||
show('step-run');
|
||||
pollStatus();
|
||||
} catch(e) { alert('Ошибка: ' + e.message); }
|
||||
}
|
||||
|
||||
async function pollStatus() {
|
||||
const r = await fetch('/api/batch-v2/status/' + jobId, {headers: H});
|
||||
const d = await r.json();
|
||||
|
||||
const pct = d.total > 0 ? (d.processed / d.total * 100) : 0;
|
||||
document.getElementById('run-progress').style.width = pct + '%';
|
||||
document.getElementById('run-count').textContent = d.processed + ' / ' + d.total + ' файлов';
|
||||
|
||||
if (d.status === 'running') {
|
||||
document.getElementById('run-status').textContent = 'Обработка...';
|
||||
setTimeout(pollStatus, 1500);
|
||||
} else if (d.status === 'completed') {
|
||||
document.getElementById('run-status').textContent = 'Готово! Обработано: ' + d.processed + ' из ' + d.total;
|
||||
document.getElementById('run-status').style.color = 'var(--green)';
|
||||
document.getElementById('btn-download').style.display = 'inline-block';
|
||||
} else if (d.status === 'failed') {
|
||||
document.getElementById('run-status').textContent = 'Ошибка выполнения';
|
||||
document.getElementById('run-status').style.color = 'var(--accent)';
|
||||
}
|
||||
|
||||
if (d.errors && d.errors.length > 0) {
|
||||
document.getElementById('run-errors').innerHTML = '<b>Ошибки:</b><br>' + d.errors.map(e => '• ' + e).join('<br>');
|
||||
}
|
||||
}
|
||||
|
||||
function renderSummary(s) {
|
||||
const el = document.getElementById('summary-view');
|
||||
if (!s || !s.source_patterns) {
|
||||
el.innerHTML = '<p style="color:var(--muted)">Параметры не распознаны — проверьте скрипт вручную</p>';
|
||||
return;
|
||||
}
|
||||
const src = s.source_patterns || {};
|
||||
const tgt = s.target_mapping || {};
|
||||
let html = '';
|
||||
if (s.description) html += `<p><b>${s.description}</b></p>`;
|
||||
|
||||
html += '<table style="width:100%;border-collapse:collapse;margin:.5rem 0;font-size:.85rem">';
|
||||
html += '<tr style="background:#ede5db"><td colspan="2" style="padding:6px;font-weight:600">Исходные файлы</td></tr>';
|
||||
if (src.sheet) html += row('Лист', src.sheet);
|
||||
if (src.id_field) html += row('Шифр/название', src.id_field);
|
||||
if (src.value_column) html += row('Столбец значений', src.value_column);
|
||||
if (src.units) html += row('Единицы', src.units);
|
||||
|
||||
if (src.totals) {
|
||||
html += '<tr style="background:#ede5db"><td colspan="2" style="padding:6px;font-weight:600">Паттерны поиска итогов</td></tr>';
|
||||
for (const [k, v] of Object.entries(src.totals)) {
|
||||
html += row(k, '<code>' + v + '</code>');
|
||||
}
|
||||
}
|
||||
|
||||
html += '<tr style="background:#ede5db"><td colspan="2" style="padding:6px;font-weight:600">Сводный файл</td></tr>';
|
||||
if (tgt.sheet) html += row('Лист', tgt.sheet);
|
||||
if (tgt.match_column) html += row('Столбец сопоставления', tgt.match_column);
|
||||
if (tgt.value_columns) {
|
||||
for (const [k, v] of Object.entries(tgt.value_columns)) {
|
||||
html += row(k + ' →', 'столбец ' + v);
|
||||
}
|
||||
}
|
||||
if (tgt.units) html += row('Единицы', tgt.units);
|
||||
if (s.conversion) html += row('Конвертация', s.conversion);
|
||||
html += '</table>';
|
||||
|
||||
// Preview table: source → target mapping with actual values
|
||||
if (s.preview && s.preview.length > 0) {
|
||||
html += '<div style="margin-top:.8rem"><b>Превью маппинга (по сэмплам):</b></div>';
|
||||
html += '<table style="width:100%;border-collapse:collapse;margin:.3rem 0;font-size:.8rem">';
|
||||
html += '<tr style="background:#ede5db">' +
|
||||
'<td style="padding:5px">Исходный файл</td>' +
|
||||
'<td style="padding:5px">Извлечённые значения</td>' +
|
||||
'<td style="padding:5px">→ Куда</td>' +
|
||||
'<td style="padding:5px">Записываемые значения</td></tr>';
|
||||
for (const p of s.preview) {
|
||||
const srcVals = p.source_values ? Object.entries(p.source_values).map(([k,v]) => k + ': ' + v).join('<br>') : '-';
|
||||
const tgtVals = p.target_values ? Object.entries(p.target_values).map(([k,v]) => k + '=' + v).join(', ') : '-';
|
||||
const tgtWhere = (p.target_sheet || '') + '<br>' + (p.target_row || '');
|
||||
html += '<tr>' +
|
||||
'<td style="padding:4px 5px;border-bottom:1px solid #eee;word-break:break-all">' + (p.source_file || '') + '</td>' +
|
||||
'<td style="padding:4px 5px;border-bottom:1px solid #eee;font-size:.75rem">' + srcVals + '</td>' +
|
||||
'<td style="padding:4px 5px;border-bottom:1px solid #eee;font-size:.75rem">' + tgtWhere + '</td>' +
|
||||
'<td style="padding:4px 5px;border-bottom:1px solid #eee"><code>' + tgtVals + '</code></td></tr>';
|
||||
}
|
||||
html += '</table>';
|
||||
}
|
||||
|
||||
el.innerHTML = html;
|
||||
|
||||
function row(label, value) {
|
||||
return `<tr><td style="padding:4px 6px;border-bottom:1px solid #eee;color:var(--muted);width:40%">${label}</td><td style="padding:4px 6px;border-bottom:1px solid #eee">${value}</td></tr>`;
|
||||
}
|
||||
}
|
||||
|
||||
function downloadResult() {
|
||||
fetch('/api/batch-v2/download/' + jobId, {headers: H})
|
||||
.then(r => r.blob())
|
||||
.then(b => {
|
||||
const u = URL.createObjectURL(b);
|
||||
const a = document.createElement('a');
|
||||
a.href = u; a.download = 'result.xlsx'; a.click();
|
||||
URL.revokeObjectURL(u);
|
||||
});
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,389 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Пакетная обработка V3 — Verify</title>
|
||||
<style>
|
||||
:root { --bg: #f5f0eb; --card: #fff; --text: #3a3a3a; --muted: #6b6b6b; --accent: #c4463a; --border: #d4c5b2; --radius: 10px; --green: #2d8a56; }
|
||||
* { box-sizing: border-box; margin: 0; padding: 0; }
|
||||
body { font-family: 'Inter', -apple-system, sans-serif; background: var(--bg); color: var(--text); min-height: 100vh; padding: 2rem; }
|
||||
.container { max-width: 750px; margin: 0 auto; }
|
||||
h1 { font-size: 1.3rem; margin-bottom: .3rem; }
|
||||
.subtitle { color: var(--muted); font-size: .9rem; margin-bottom: 1.5rem; }
|
||||
.badge { display: inline-block; background: var(--green); color: #fff; font-size: .7rem; padding: 2px 8px; border-radius: 12px; vertical-align: middle; margin-left: .5rem; }
|
||||
.badge-warn { background: #d4a017; }
|
||||
.card { background: var(--card); border-radius: var(--radius); padding: 1.5rem; margin-bottom: 1rem; box-shadow: 0 1px 4px rgba(0,0,0,.06); }
|
||||
.card.hidden { display: none; }
|
||||
label { display: block; font-weight: 600; margin-bottom: .4rem; font-size: .9rem; }
|
||||
.hint { color: var(--muted); font-size: .8rem; margin-bottom: .6rem; }
|
||||
input[type=file] { width: 100%; padding: .5rem; border: 1.5px dashed var(--border); border-radius: var(--radius); margin-bottom: 1rem; }
|
||||
textarea { width: 100%; padding: .6rem; border: 1.5px solid var(--border); border-radius: var(--radius); font-family: inherit; font-size: .9rem; resize: vertical; min-height: 80px; }
|
||||
button { padding: .7rem 1.5rem; background: var(--accent); color: #fff; border: none; border-radius: var(--radius); font-size: .95rem; font-weight: 600; cursor: pointer; }
|
||||
button:hover { background: #a83830; }
|
||||
button:disabled { background: var(--border); cursor: not-allowed; }
|
||||
.back { display: inline-block; margin-bottom: 1rem; color: var(--accent); text-decoration: none; font-size: .85rem; }
|
||||
.progress { background: #ede5db; border-radius: 6px; height: 8px; margin: .5rem 0; }
|
||||
.progress-bar { background: var(--accent); height: 100%; border-radius: 6px; transition: width .3s; }
|
||||
.error-list { color: #c4463a; font-size: .8rem; margin-top: .5rem; max-height: 200px; overflow-y: auto; }
|
||||
pre { background: #2c2c2c; color: #f5f0eb; padding: .8rem; border-radius: 6px; overflow-x: auto; font-size: .78rem; margin: .5rem 0; max-height: 400px; overflow-y: auto; white-space: pre-wrap; word-break: break-word; }
|
||||
.log { background: #1a1a2e; color: #a0d2db; padding: .8rem; border-radius: 6px; font-size: .78rem; margin: .5rem 0; max-height: 300px; overflow-y: auto; font-family: monospace; white-space: pre-wrap; word-break: break-word; }
|
||||
.info-row { display: flex; gap: 1rem; margin: .5rem 0; font-size: .85rem; color: var(--muted); }
|
||||
.info-row span { background: #ede5db; padding: 3px 10px; border-radius: 6px; }
|
||||
.spinner { display: inline-block; width: 16px; height: 16px; border: 2px solid var(--border); border-top-color: var(--accent); border-radius: 50%; animation: spin .8s linear infinite; vertical-align: middle; margin-right: 6px; }
|
||||
@keyframes spin { to { transform: rotate(360deg); } }
|
||||
.copy-btn { position: absolute; top: 4px; right: 4px; padding: 4px 12px; font-size: .75rem; background: var(--card); color: var(--accent); border: 1.5px solid var(--accent); border-radius: 4px; cursor: pointer; z-index: 1; font-weight: 600; }
|
||||
.copy-btn:hover { background: var(--accent); color: #fff; }
|
||||
.copy-btn-inline { display: inline-block; padding: 4px 14px; font-size: .75rem; background: var(--card); color: var(--accent); border: 1.5px solid var(--accent); border-radius: 4px; cursor: pointer; font-weight: 600; margin-top: .5rem; }
|
||||
.copy-btn-inline:hover { background: var(--accent); color: #fff; }
|
||||
.verify-ok { background: #e8f5e9; border: 1px solid var(--green); border-radius: 6px; padding: .5rem .8rem; margin: .5rem 0; font-size: .85rem; color: var(--green); }
|
||||
.verify-fail { background: #fce4ec; border: 1px solid var(--accent); border-radius: 6px; padding: .5rem .8rem; margin: .5rem 0; font-size: .85rem; color: var(--accent); }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<a class="back" href="/">← Вернуться в чат</a>
|
||||
<h1>Пакетная обработка смет <span class="badge">V3 Verify</span></h1>
|
||||
<p class="subtitle">Claude генерирует скрипт + автоматическая проверка на 2 файлах + auto-retry</p>
|
||||
|
||||
<!-- Step 1: Upload -->
|
||||
<div class="card" id="step-upload">
|
||||
<label>1. Архив со сметами (.zip)</label>
|
||||
<p class="hint">Все файлы локальных смет в одном архиве (до 2000 файлов)</p>
|
||||
<input type="file" id="zip-file" accept=".zip">
|
||||
<label>Сводный файл (.xlsx)</label>
|
||||
<p class="hint">Файл, в который нужно внести данные (ССР, ведомость и т.д.)</p>
|
||||
<input type="file" id="target-file" accept=".xlsx,.xls">
|
||||
<label>Описание задачи</label>
|
||||
<p class="hint">Опишите что именно нужно сделать — Claude прочитает файлы и разберётся</p>
|
||||
<textarea id="task-desc" placeholder="Из каждого файла взять итоговые суммы по типам работ (строительные, монтажные, оборудование, прочие) и внести в соответствующие строки и колонки сводного файла. Значения в исходных файлах в рублях, в сводном — тыс.руб."></textarea>
|
||||
<br><br>
|
||||
<button id="btn-upload" onclick="uploadFiles()">Загрузить и конвертировать</button>
|
||||
</div>
|
||||
|
||||
<!-- Step 2: Analysis + Verification -->
|
||||
<div class="card hidden" id="step-analyze">
|
||||
<label>2. Генерация + верификация</label>
|
||||
<div class="info-row" id="csv-info"></div>
|
||||
<p style="margin:.5rem 0;font-size:.9rem"><span class="spinner" id="analyze-spinner"></span> <span id="analyze-status">Claude генерирует скрипт...</span> <span id="analyze-timer" style="color:var(--muted);font-size:.8rem"></span></p>
|
||||
<div id="verify-status"></div>
|
||||
<div style="position:relative">
|
||||
<div class="log" id="analyze-log"></div>
|
||||
<button class="copy-btn" onclick="copyText('analyze-log')" title="Копировать">Копировать</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Step 3: Confirm -->
|
||||
<div class="card hidden" id="step-confirm">
|
||||
<label>3. Проверьте найденные параметры</label>
|
||||
<div id="verify-badge"></div>
|
||||
<div id="summary-view" style="font-size:.9rem;line-height:1.6"></div>
|
||||
<button class="copy-btn-inline" onclick="copyText('summary-view')" title="Копировать параметры">Копировать параметры</button>
|
||||
<details style="margin-top:.8rem">
|
||||
<summary style="cursor:pointer;color:var(--muted);font-size:.8rem">Показать скрипт (для разработчиков)</summary>
|
||||
<div style="position:relative">
|
||||
<pre id="script-code"></pre>
|
||||
<button class="copy-btn" onclick="copyText('script-code')" title="Копировать">Копировать</button>
|
||||
</div>
|
||||
</details>
|
||||
<div style="display:flex;gap:.5rem;margin-top:.8rem">
|
||||
<button id="btn-run" onclick="runScript()">Запустить обработку</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Step 4: Execution -->
|
||||
<div class="card hidden" id="step-run">
|
||||
<label>4. Выполнение</label>
|
||||
<p id="run-status"></p>
|
||||
<div class="progress"><div class="progress-bar" id="run-progress" style="width:0%"></div></div>
|
||||
<p id="run-count" style="font-size:.85rem;color:var(--muted)"></p>
|
||||
<div class="error-list" id="run-errors"></div>
|
||||
<button id="btn-download" style="display:none" onclick="downloadResult()">Скачать результат</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
let token = localStorage.getItem('token');
|
||||
// Validate token on load (don't trust localStorage blindly)
|
||||
(async () => {
|
||||
if (!token) { window.location.href = '/'; return; }
|
||||
try {
|
||||
const r = await fetch('/api/history?limit=1', {headers:{'Authorization':'Bearer '+token}});
|
||||
if (r.ok) return; // token valid
|
||||
} catch {}
|
||||
// Try refresh
|
||||
const rt = localStorage.getItem('refresh_token');
|
||||
if (rt) {
|
||||
try {
|
||||
const r = await fetch('/api/refresh', {method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify({refresh_token:rt})});
|
||||
if (r.ok) { const d = await r.json(); token = d.token; localStorage.setItem('token', token); return; }
|
||||
} catch {}
|
||||
}
|
||||
localStorage.removeItem('token'); localStorage.removeItem('refresh_token');
|
||||
window.location.href = '/';
|
||||
})();
|
||||
|
||||
const API = '/api/batch-v3';
|
||||
const H = {'Authorization': 'Bearer ' + token};
|
||||
let jobId = null;
|
||||
let verified = false;
|
||||
let timerInterval = null;
|
||||
let timerStart = 0;
|
||||
|
||||
function show(id) { document.getElementById(id).classList.remove('hidden'); }
|
||||
function hide(id) { document.getElementById(id).classList.add('hidden'); }
|
||||
function copyText(elId) {
|
||||
const el = document.getElementById(elId);
|
||||
const text = el.innerText || el.textContent;
|
||||
navigator.clipboard.writeText(text).then(() => {
|
||||
const btn = el.parentElement.querySelector('.copy-btn');
|
||||
if (btn) { const orig = btn.textContent; btn.textContent = 'Скопировано'; setTimeout(() => btn.textContent = orig, 1500); }
|
||||
});
|
||||
}
|
||||
|
||||
function startTimer() {
|
||||
timerStart = Date.now();
|
||||
timerInterval = setInterval(() => {
|
||||
const s = Math.floor((Date.now() - timerStart) / 1000);
|
||||
const m = Math.floor(s / 60);
|
||||
const sec = s % 60;
|
||||
document.getElementById('analyze-timer').textContent = m > 0 ? m + 'м ' + sec + 'с' : sec + 'с';
|
||||
}, 1000);
|
||||
}
|
||||
function stopTimer() { if (timerInterval) { clearInterval(timerInterval); timerInterval = null; } }
|
||||
|
||||
async function uploadFiles() {
|
||||
const zipFile = document.getElementById('zip-file').files[0];
|
||||
const targetFile = document.getElementById('target-file').files[0];
|
||||
const taskDesc = document.getElementById('task-desc').value;
|
||||
if (!zipFile || !targetFile) { alert('Загрузите оба файла'); return; }
|
||||
|
||||
const btn = document.getElementById('btn-upload');
|
||||
btn.disabled = true; btn.textContent = 'Загружаю...';
|
||||
|
||||
const fd = new FormData();
|
||||
fd.append('zip_file', zipFile);
|
||||
fd.append('target_file', targetFile);
|
||||
fd.append('task_description', taskDesc || 'Перенести итоги из смет в сводный файл');
|
||||
|
||||
try {
|
||||
const r = await fetch(API + '/upload', {method: 'POST', headers: H, body: fd});
|
||||
if (r.status === 401) { window.location.href = '/'; return; }
|
||||
const data = await r.json();
|
||||
jobId = data.job_id;
|
||||
const info = data.csv_info;
|
||||
document.getElementById('csv-info').innerHTML =
|
||||
`<span>${data.total_files} xlsx</span><span>${info.sample_count} CSV сэмплов</span><span>~${Math.round(info.estimated_tokens/1000)}K токенов</span>`;
|
||||
btn.textContent = 'Загружено';
|
||||
show('step-analyze');
|
||||
startAnalysis();
|
||||
} catch(e) { alert('Ошибка: ' + e.message); btn.disabled = false; btn.textContent = 'Загрузить и конвертировать'; }
|
||||
}
|
||||
|
||||
async function startAnalysis() {
|
||||
const log = document.getElementById('analyze-log');
|
||||
const vstat = document.getElementById('verify-status');
|
||||
log.textContent = '';
|
||||
vstat.innerHTML = '';
|
||||
verified = false;
|
||||
startTimer();
|
||||
|
||||
try {
|
||||
const r = await fetch(API + '/analyze/' + jobId, {method: 'POST', headers: H});
|
||||
const reader = r.body.getReader();
|
||||
const decoder = new TextDecoder();
|
||||
let buffer = '';
|
||||
|
||||
while (true) {
|
||||
const {done, value} = await reader.read();
|
||||
if (done) break;
|
||||
buffer += decoder.decode(value, {stream: true});
|
||||
const lines = buffer.split('\n');
|
||||
buffer = lines.pop();
|
||||
|
||||
let eventType = '';
|
||||
for (const line of lines) {
|
||||
if (line.startsWith('event: ')) { eventType = line.slice(7); continue; }
|
||||
if (!line.startsWith('data: ')) continue;
|
||||
try {
|
||||
const d = JSON.parse(line.slice(6));
|
||||
|
||||
if (eventType === 'text') {
|
||||
log.textContent += d.text;
|
||||
log.scrollTop = log.scrollHeight;
|
||||
} else if (eventType === 'tool') {
|
||||
log.textContent += '\n[tool: ' + d.tool + ']\n';
|
||||
log.scrollTop = log.scrollHeight;
|
||||
} else if (eventType === 'generation_start') {
|
||||
const att = d.attempt || 1;
|
||||
document.getElementById('analyze-status').textContent = att > 1
|
||||
? 'Попытка ' + att + '/3: Claude перегенерирует скрипт...'
|
||||
: 'Claude генерирует скрипт...';
|
||||
if (att > 1) log.textContent += '\n--- Попытка ' + att + ' ---\n';
|
||||
} else if (eventType === 'verify_start') {
|
||||
document.getElementById('analyze-status').textContent = 'Проверяю скрипт на 2 файлах...';
|
||||
vstat.innerHTML = '<p style="font-size:.85rem;color:var(--muted)">Выполняю скрипт на 2 сэмплах...</p>';
|
||||
} else if (eventType === 'verify_ok') {
|
||||
vstat.innerHTML = '<div class="verify-ok">Скрипт проверен: обработано ' + d.processed + ' файлов без ошибок</div>';
|
||||
} else if (eventType === 'verify_fail') {
|
||||
vstat.innerHTML = '<div class="verify-fail">Попытка ' + d.attempt + '/3: ошибка — ' + (d.error || '').slice(0, 200) + '</div>';
|
||||
} else if (eventType === 'retry') {
|
||||
log.textContent += '\n[retry: attempt ' + d.attempt + ']\n';
|
||||
} else if (eventType === 'done') {
|
||||
document.getElementById('analyze-spinner').style.display = 'none';
|
||||
stopTimer();
|
||||
verified = d.verified || false;
|
||||
if (d.script) {
|
||||
document.getElementById('analyze-status').textContent = 'Анализ завершён' + (d.attempts > 1 ? ' (попытка ' + d.attempts + ')' : '');
|
||||
document.getElementById('script-code').textContent = d.script;
|
||||
renderSummary(d.summary);
|
||||
// Verify badge
|
||||
const vb = document.getElementById('verify-badge');
|
||||
if (verified) {
|
||||
vb.innerHTML = '<div class="verify-ok">Скрипт прошёл автоматическую проверку</div>';
|
||||
} else {
|
||||
vb.innerHTML = '<div class="verify-fail">Скрипт НЕ прошёл проверку после 3 попыток. Запуск на ваш риск.</div>';
|
||||
}
|
||||
show('step-confirm');
|
||||
} else {
|
||||
document.getElementById('analyze-status').textContent = 'Claude не сгенерировал скрипт';
|
||||
document.getElementById('analyze-status').style.color = 'var(--accent)';
|
||||
}
|
||||
}
|
||||
} catch(e) {}
|
||||
}
|
||||
}
|
||||
} catch(e) {
|
||||
// Stream closed — fall through to polling
|
||||
}
|
||||
|
||||
// Polling fallback
|
||||
if (document.getElementById('step-confirm').classList.contains('hidden')) {
|
||||
stopTimer();
|
||||
document.getElementById('analyze-status').textContent = 'Проверяю результат...';
|
||||
for (let i = 0; i < 15; i++) {
|
||||
await new Promise(r => setTimeout(r, 3000));
|
||||
try {
|
||||
const sr = await fetch(API + '/status/' + jobId, {headers: H});
|
||||
const sd = await sr.json();
|
||||
if (sd.status === 'analyzed' && sd.script) {
|
||||
document.getElementById('analyze-spinner').style.display = 'none';
|
||||
document.getElementById('analyze-status').textContent = 'Анализ завершён';
|
||||
document.getElementById('script-code').textContent = sd.script;
|
||||
verified = sd.verified || false;
|
||||
renderSummary(sd.summary || {});
|
||||
const vb = document.getElementById('verify-badge');
|
||||
vb.innerHTML = verified
|
||||
? '<div class="verify-ok">Скрипт прошёл автоматическую проверку</div>'
|
||||
: '<div class="verify-fail">Скрипт НЕ прошёл проверку. Запуск на ваш риск.</div>';
|
||||
show('step-confirm');
|
||||
return;
|
||||
}
|
||||
} catch(e2) {}
|
||||
}
|
||||
document.getElementById('analyze-spinner').style.display = 'none';
|
||||
document.getElementById('analyze-status').textContent = 'Таймаут — попробуйте ещё раз';
|
||||
document.getElementById('analyze-status').style.color = 'var(--accent)';
|
||||
}
|
||||
}
|
||||
|
||||
async function runScript() {
|
||||
if (!verified) {
|
||||
if (!confirm('Скрипт НЕ прошёл автоматическую проверку. Запустить на свой риск?')) return;
|
||||
}
|
||||
const btn = document.getElementById('btn-run');
|
||||
btn.disabled = true; btn.textContent = 'Запускаю...';
|
||||
try {
|
||||
const r = await fetch(API + '/run/' + jobId, {method: 'POST', headers: H});
|
||||
if (!r.ok) { alert('Ошибка запуска'); btn.disabled = false; btn.textContent = 'Запустить обработку'; return; }
|
||||
btn.textContent = 'Запущено';
|
||||
show('step-run');
|
||||
pollStatus();
|
||||
} catch(e) { alert('Ошибка: ' + e.message); btn.disabled = false; btn.textContent = 'Запустить обработку'; }
|
||||
}
|
||||
|
||||
async function pollStatus() {
|
||||
const r = await fetch(API + '/status/' + jobId, {headers: H});
|
||||
const d = await r.json();
|
||||
const pct = d.total > 0 ? (d.processed / d.total * 100) : 0;
|
||||
document.getElementById('run-progress').style.width = pct + '%';
|
||||
document.getElementById('run-count').textContent = d.processed + ' / ' + d.total + ' файлов';
|
||||
|
||||
if (d.status === 'running') {
|
||||
document.getElementById('run-status').textContent = 'Обработка...';
|
||||
setTimeout(pollStatus, 1500);
|
||||
} else if (d.status === 'completed') {
|
||||
document.getElementById('run-status').textContent = 'Готово! Обработано: ' + d.processed + ' из ' + d.total;
|
||||
document.getElementById('run-status').style.color = 'var(--green)';
|
||||
document.getElementById('btn-download').style.display = 'inline-block';
|
||||
} else if (d.status === 'failed') {
|
||||
document.getElementById('run-status').textContent = 'Ошибка выполнения';
|
||||
document.getElementById('run-status').style.color = 'var(--accent)';
|
||||
}
|
||||
if (d.errors && d.errors.length > 0) {
|
||||
document.getElementById('run-errors').innerHTML = '<b>Ошибки:</b><br>' + d.errors.map(e => '• ' + e).join('<br>');
|
||||
}
|
||||
}
|
||||
|
||||
function renderSummary(s) {
|
||||
const el = document.getElementById('summary-view');
|
||||
if (!s || !s.source_patterns) {
|
||||
el.innerHTML = '<p style="color:var(--muted)">Параметры не распознаны — проверьте скрипт вручную</p>';
|
||||
return;
|
||||
}
|
||||
const src = s.source_patterns || {};
|
||||
const tgt = s.target_mapping || {};
|
||||
let html = '';
|
||||
if (s.description) html += `<p><b>${s.description}</b></p>`;
|
||||
|
||||
html += '<table style="width:100%;border-collapse:collapse;margin:.5rem 0;font-size:.85rem">';
|
||||
html += '<tr style="background:#ede5db"><td colspan="2" style="padding:6px;font-weight:600">Исходные файлы</td></tr>';
|
||||
if (src.sheet) html += row('Лист', src.sheet);
|
||||
if (src.id_field) html += row('Шифр/название', src.id_field);
|
||||
if (src.value_column) html += row('Столбец значений', src.value_column);
|
||||
if (src.units) html += row('Единицы', src.units);
|
||||
if (src.totals) {
|
||||
html += '<tr style="background:#ede5db"><td colspan="2" style="padding:6px;font-weight:600">Паттерны поиска итогов</td></tr>';
|
||||
for (const [k, v] of Object.entries(src.totals)) html += row(k, '<code>' + v + '</code>');
|
||||
}
|
||||
html += '<tr style="background:#ede5db"><td colspan="2" style="padding:6px;font-weight:600">Сводный файл</td></tr>';
|
||||
if (tgt.sheet) html += row('Лист', tgt.sheet);
|
||||
if (tgt.match_column) html += row('Столбец сопоставления', tgt.match_column);
|
||||
if (tgt.value_columns) {
|
||||
for (const [k, v] of Object.entries(tgt.value_columns)) html += row(k + ' →', 'столбец ' + v);
|
||||
}
|
||||
if (tgt.units) html += row('Единицы', tgt.units);
|
||||
if (s.conversion) html += row('Конвертация', s.conversion);
|
||||
html += '</table>';
|
||||
|
||||
if (s.preview && s.preview.length > 0) {
|
||||
html += '<div style="margin-top:.8rem"><b>Превью маппинга (по сэмплам):</b></div>';
|
||||
html += '<table style="width:100%;border-collapse:collapse;margin:.3rem 0;font-size:.8rem">';
|
||||
html += '<tr style="background:#ede5db"><td style="padding:5px">Исходный файл</td><td style="padding:5px">Извлечённые значения</td><td style="padding:5px">→ Куда</td><td style="padding:5px">Записываемые значения</td></tr>';
|
||||
for (const p of s.preview) {
|
||||
const srcVals = p.source_values ? Object.entries(p.source_values).map(([k,v]) => k + ': ' + v).join('<br>') : '-';
|
||||
const tgtVals = p.target_values ? Object.entries(p.target_values).map(([k,v]) => k + '=' + v).join(', ') : '-';
|
||||
const tgtWhere = (p.target_sheet || '') + '<br>' + (p.target_row || '');
|
||||
html += '<tr><td style="padding:4px 5px;border-bottom:1px solid #eee;word-break:break-all">' + (p.source_file || '') + '</td><td style="padding:4px 5px;border-bottom:1px solid #eee;font-size:.75rem">' + srcVals + '</td><td style="padding:4px 5px;border-bottom:1px solid #eee;font-size:.75rem">' + tgtWhere + '</td><td style="padding:4px 5px;border-bottom:1px solid #eee"><code>' + tgtVals + '</code></td></tr>';
|
||||
}
|
||||
html += '</table>';
|
||||
}
|
||||
el.innerHTML = html;
|
||||
function row(label, value) {
|
||||
return `<tr><td style="padding:4px 6px;border-bottom:1px solid #eee;color:var(--muted);width:40%">${label}</td><td style="padding:4px 6px;border-bottom:1px solid #eee">${value}</td></tr>`;
|
||||
}
|
||||
}
|
||||
|
||||
function downloadResult() {
|
||||
fetch(API + '/download/' + jobId, {headers: H})
|
||||
.then(r => r.blob())
|
||||
.then(b => {
|
||||
const u = URL.createObjectURL(b);
|
||||
const a = document.createElement('a');
|
||||
a.href = u; a.download = 'result.xlsx'; a.click();
|
||||
URL.revokeObjectURL(u);
|
||||
});
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,137 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Проверка сметы</title>
|
||||
<style>
|
||||
:root {
|
||||
--bg: #f5f0eb; --bg-card: #ffffff;
|
||||
--text: #3a3a3a; --text-muted: #6b6b6b;
|
||||
--border: #d4c5b2; --border-light: #ede5db;
|
||||
--accent: #c4463a; --accent-hover: #a83830;
|
||||
--success: #2b8a3e; --warn: #e8590c; --danger: #e03131; --info: #1971c2;
|
||||
--shadow-md: 0 4px 16px rgba(0,0,0,.07);
|
||||
--radius: 10px; --radius-lg: 16px;
|
||||
}
|
||||
* { box-sizing: border-box; margin: 0; padding: 0; }
|
||||
body { font-family: 'Inter', -apple-system, sans-serif; background: var(--bg); color: var(--text); }
|
||||
.container { max-width: 860px; margin: 24px auto; padding: 0 16px; }
|
||||
.header { display: flex; align-items: center; justify-content: space-between; margin-bottom: 20px; }
|
||||
.header h1 { font-size: 1.2rem; font-weight: 700; }
|
||||
.header a { color: var(--accent); text-decoration: none; font-size: .85rem; font-weight: 500; }
|
||||
.card { background: var(--bg-card); border-radius: var(--radius-lg); box-shadow: var(--shadow-md); padding: 24px; margin-bottom: 16px; }
|
||||
label { display: block; font-size: .85rem; font-weight: 500; color: var(--text-muted); margin-bottom: 4px; }
|
||||
textarea { width: 100%; padding: .6rem; border: 1.5px solid var(--border); border-radius: var(--radius); font-size: .82rem; font-family: 'SF Mono', Menlo, monospace; background: var(--bg); outline: none; resize: vertical; min-height: 200px; }
|
||||
textarea:focus { border-color: var(--accent); background: var(--bg-card); }
|
||||
.btn { padding: .55rem 1.2rem; border: none; border-radius: var(--radius); font-size: .85rem; font-weight: 600; cursor: pointer; background: var(--accent); color: #fff; }
|
||||
.btn:hover { background: var(--accent-hover); }
|
||||
.btn-outline { background: transparent; border: 1.5px solid var(--border); color: var(--text-muted); }
|
||||
.result-item { padding: 8px 12px; border-radius: var(--radius); margin-bottom: 6px; font-size: .88rem; display: flex; align-items: flex-start; gap: 8px; }
|
||||
.result-item.error { background: #fff1f2; border-left: 3px solid var(--danger); }
|
||||
.result-item.warning { background: #fff9db; border-left: 3px solid var(--warn); }
|
||||
.result-item.info { background: #e7f5ff; border-left: 3px solid var(--info); }
|
||||
.icon { font-size: 1rem; flex-shrink: 0; }
|
||||
.summary { display: flex; gap: 12px; margin-bottom: 16px; }
|
||||
.badge { padding: 4px 12px; border-radius: 10px; font-size: .8rem; font-weight: 600; }
|
||||
.badge-err { background: #ffe3e3; color: var(--danger); }
|
||||
.badge-warn { background: #fff3bf; color: var(--warn); }
|
||||
.badge-info { background: #dbeafe; color: var(--info); }
|
||||
.mt-2 { margin-top: 8px; }
|
||||
.mt-3 { margin-top: 12px; }
|
||||
.spinner { width: 1rem; height: 1rem; border: 2px solid var(--border); border-top-color: var(--accent); border-radius: 50%; animation: spin .6s linear infinite; display: inline-block; }
|
||||
@keyframes spin { to { transform: rotate(360deg); } }
|
||||
.d-none { display: none !important; }
|
||||
.or { text-align: center; color: var(--text-muted); font-size: .85rem; margin: 8px 0; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<div class="header">
|
||||
<h1>Проверка сметы</h1>
|
||||
<a href="/">← Назад к чату</a>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<label>Загрузите YAML-файл проекта:</label>
|
||||
<input type="file" id="yamlFile" accept=".yaml,.yml" style="padding:.4rem;border:1.5px solid var(--border);border-radius:var(--radius);width:100%;font-size:.9rem;background:var(--bg)">
|
||||
<div class="or">или вставьте YAML вручную:</div>
|
||||
<textarea id="yamlInput" placeholder="sections:
|
||||
- name: Глава 1
|
||||
subsections:
|
||||
- items:
|
||||
- code: 28-01-037-02
|
||||
name: Замена шпал
|
||||
unit: шт
|
||||
qty: 100
|
||||
coefficients:
|
||||
definitions:
|
||||
- key: dvizhenie
|
||||
value: 1.40"></textarea>
|
||||
<button class="btn mt-2" onclick="check()" id="checkBtn">
|
||||
<span id="checkSpin" class="spinner d-none"></span> Проверить
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div id="reportCard" class="card d-none">
|
||||
<div class="summary" id="summary"></div>
|
||||
<div id="report"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
function $(id){return document.getElementById(id);}
|
||||
|
||||
$('yamlFile').addEventListener('change', function(e) {
|
||||
const file = e.target.files[0];
|
||||
if (file) {
|
||||
const reader = new FileReader();
|
||||
reader.onload = (ev) => $('yamlInput').value = ev.target.result;
|
||||
reader.readAsText(file);
|
||||
}
|
||||
});
|
||||
|
||||
async function check() {
|
||||
const yaml = $('yamlInput').value.trim();
|
||||
if (!yaml) return;
|
||||
$('checkSpin').classList.remove('d-none'); $('checkBtn').disabled = true;
|
||||
$('reportCard').classList.add('d-none');
|
||||
|
||||
try {
|
||||
const r = await fetch('/api/check/yaml', {
|
||||
method: 'POST', headers: {'Content-Type': 'application/json'},
|
||||
body: JSON.stringify({yaml})
|
||||
});
|
||||
const d = await r.json();
|
||||
|
||||
if (d.error) {
|
||||
$('summary').innerHTML = `<span class="badge badge-err">Ошибка парсинга</span>`;
|
||||
$('report').innerHTML = `<div class="result-item error"><span class="icon">❌</span>${esc(d.error)}</div>`;
|
||||
} else {
|
||||
let sum = '';
|
||||
if (d.errors) sum += `<span class="badge badge-err">${d.errors} ошибок</span>`;
|
||||
if (d.warnings) sum += `<span class="badge badge-warn">${d.warnings} предупреждений</span>`;
|
||||
if (!d.errors && !d.warnings) sum += `<span class="badge badge-info">Всё в порядке</span>`;
|
||||
$('summary').innerHTML = sum;
|
||||
|
||||
let h = '';
|
||||
for (const r of d.results) {
|
||||
const cls = r.level;
|
||||
const icon = r.level === 'error' ? '❌' : r.level === 'warning' ? '⚠️' : 'ℹ️';
|
||||
const pos = r.position ? ` <span style="color:var(--text-muted)">[${esc(r.position)}]</span>` : '';
|
||||
h += `<div class="result-item ${cls}"><span class="icon">${icon}</span><span>${esc(r.message)}${pos}</span></div>`;
|
||||
}
|
||||
$('report').innerHTML = h;
|
||||
}
|
||||
$('reportCard').classList.remove('d-none');
|
||||
} catch(e) {
|
||||
alert(e.message);
|
||||
} finally {
|
||||
$('checkSpin').classList.add('d-none'); $('checkBtn').disabled = false;
|
||||
}
|
||||
}
|
||||
|
||||
function esc(s) { return String(s).replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>'); }
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,219 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Генерация сметы</title>
|
||||
<style>
|
||||
:root {
|
||||
--bg: #f5f0eb; --bg-card: #ffffff; --bg-input: #ffffff;
|
||||
--text: #3a3a3a; --text-muted: #6b6b6b; --text-light: #8b7355;
|
||||
--border: #d4c5b2; --border-light: #ede5db;
|
||||
--accent: #c4463a; --accent-hover: #a83830;
|
||||
--success: #2b8a3e; --warn: #e8590c; --danger: #e03131; --info: #1971c2;
|
||||
--shadow-sm: 0 1px 3px rgba(0,0,0,.05);
|
||||
--shadow-md: 0 4px 16px rgba(0,0,0,.07);
|
||||
--radius: 10px; --radius-lg: 16px;
|
||||
}
|
||||
* { box-sizing: border-box; margin: 0; padding: 0; }
|
||||
body { font-family: 'Inter', -apple-system, sans-serif; background: var(--bg); color: var(--text); -webkit-font-smoothing: antialiased; }
|
||||
.container { max-width: 860px; margin: 24px auto; padding: 0 16px; }
|
||||
.header { display: flex; align-items: center; justify-content: space-between; margin-bottom: 20px; }
|
||||
.header h1 { font-size: 1.2rem; font-weight: 700; }
|
||||
.header a { color: var(--accent); text-decoration: none; font-size: .85rem; font-weight: 500; }
|
||||
.card { background: var(--bg-card); border-radius: var(--radius-lg); box-shadow: var(--shadow-md); padding: 24px; margin-bottom: 16px; }
|
||||
.card h2 { font-size: 1rem; font-weight: 600; margin-bottom: 12px; }
|
||||
label { display: block; font-size: .85rem; font-weight: 500; color: var(--text-muted); margin-bottom: 4px; }
|
||||
input[type="text"], textarea, select { width: 100%; padding: .55rem .75rem; border: 1.5px solid var(--border); border-radius: var(--radius); font-size: .9rem; background: var(--bg); outline: none; transition: border-color .2s; font-family: inherit; }
|
||||
input:focus, textarea:focus, select:focus { border-color: var(--accent); background: var(--bg-card); }
|
||||
textarea { resize: vertical; min-height: 100px; }
|
||||
.row { display: flex; gap: 12px; flex-wrap: wrap; }
|
||||
.row > * { flex: 1; min-width: 140px; }
|
||||
.btn { padding: .55rem 1.2rem; border: none; border-radius: var(--radius); font-size: .85rem; font-weight: 600; cursor: pointer; transition: all .15s; }
|
||||
.btn-primary { background: var(--accent); color: #fff; }
|
||||
.btn-primary:hover { background: var(--accent-hover); }
|
||||
.btn-outline { background: transparent; border: 1.5px solid var(--border); color: var(--text-muted); }
|
||||
.btn-outline:hover { border-color: var(--accent); color: var(--accent); }
|
||||
.btn-success { background: var(--success); color: #fff; }
|
||||
.btn:disabled { opacity: .5; cursor: not-allowed; }
|
||||
.gen-step { display: none; }
|
||||
.gen-step.active { display: block; }
|
||||
.step-badge { display: inline-block; background: var(--accent); color: #fff; padding: 2px 10px; border-radius: 10px; font-size: .78rem; font-weight: 600; }
|
||||
.item { padding: 10px 14px; border: 1.5px solid var(--border-light); border-radius: var(--radius); margin-bottom: 8px; }
|
||||
.item.ok { border-left: 4px solid var(--success); }
|
||||
.item.bad { border-left: 4px solid var(--danger); }
|
||||
.item-head { display: flex; justify-content: space-between; align-items: center; }
|
||||
.item-head strong { font-size: .9rem; }
|
||||
.item-meta { font-size: .82rem; margin-top: 4px; }
|
||||
.score { display: inline-block; padding: 1px 6px; border-radius: 8px; font-size: .72rem; font-weight: 700; }
|
||||
.score-hi { background: #d3f9d8; color: var(--success); }
|
||||
.score-md { background: #fff3bf; color: var(--warn); }
|
||||
.score-lo { background: #ffe3e3; color: var(--danger); }
|
||||
.alt { font-size: .78rem; color: var(--info); cursor: pointer; margin-right: 8px; }
|
||||
.yaml-box { font-family: 'SF Mono', Menlo, monospace; font-size: .8rem; white-space: pre-wrap; background: #2c2c2c; color: #f5f0eb; padding: 16px; border-radius: var(--radius); max-height: 400px; overflow-y: auto; line-height: 1.5; }
|
||||
.error { color: var(--danger); font-size: .85rem; margin-top: 8px; }
|
||||
.spinner { width: 1rem; height: 1rem; border: 2px solid var(--border); border-top-color: var(--accent); border-radius: 50%; animation: spin .6s linear infinite; display: inline-block; }
|
||||
@keyframes spin { to { transform: rotate(360deg); } }
|
||||
.d-none { display: none !important; }
|
||||
.mt-2 { margin-top: 8px; }
|
||||
.mt-3 { margin-top: 12px; }
|
||||
.mb-2 { margin-bottom: 8px; }
|
||||
.chk { display: flex; align-items: center; gap: 6px; margin-top: 16px; }
|
||||
.chk input { width: auto; }
|
||||
.chk label { margin: 0; font-size: .9rem; color: var(--text); }
|
||||
.gap-2 { display: flex; gap: 8px; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<div class="header">
|
||||
<h1>Генерация сметы</h1>
|
||||
<a href="/">← Назад к чату</a>
|
||||
</div>
|
||||
|
||||
<div class="mb-2">
|
||||
<span class="step-badge" id="stepBadge">Шаг 1 из 3</span>
|
||||
<span style="color:var(--text-muted);font-size:.85rem;margin-left:8px" id="stepLabel">Описание работ</span>
|
||||
</div>
|
||||
|
||||
<!-- Step 1 -->
|
||||
<div class="gen-step active card" id="g1">
|
||||
<h2>Опишите работы</h2>
|
||||
<textarea id="desc" placeholder="Замена 500 шпал на перегоне ст. Свиягино — ст. Ружино, очистка щебня 2 км, замена 3 пар рельсовых плетей по 800м..."></textarea>
|
||||
<div class="row mt-3">
|
||||
<div><label>Регион</label><input type="text" id="region" value="Приморский край"></div>
|
||||
<div><label>Поездов/сут</label><input type="text" id="trains" value="91-108"></div>
|
||||
</div>
|
||||
<div class="row mt-2">
|
||||
<div class="chk"><input type="checkbox" id="vl" checked><label for="vl">Зона ВЛ</label></div>
|
||||
<div class="chk"><input type="checkbox" id="okno" checked><label for="okno">В "окно"</label></div>
|
||||
</div>
|
||||
<button class="btn btn-primary mt-3" onclick="parse()" id="parseBtn">
|
||||
<span id="parseSpin" class="spinner d-none"></span> Разобрать на позиции
|
||||
</button>
|
||||
<div id="parseErr" class="error"></div>
|
||||
</div>
|
||||
|
||||
<!-- Step 2 -->
|
||||
<div class="gen-step card" id="g2">
|
||||
<h2>Проверьте позиции и расценки</h2>
|
||||
<div id="items"></div>
|
||||
<div class="gap-2 mt-3">
|
||||
<button class="btn btn-outline" onclick="show(1)">Назад</button>
|
||||
<button class="btn btn-primary" onclick="genYaml()" id="yamlBtn">
|
||||
<span id="yamlSpin" class="spinner d-none"></span> Сформировать смету
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Step 3 -->
|
||||
<div class="gen-step card" id="g3">
|
||||
<h2>Конфигурация сметы</h2>
|
||||
<div id="yamlOut" class="yaml-box"></div>
|
||||
<div class="gap-2 mt-3">
|
||||
<button class="btn btn-outline" onclick="show(2)">Назад</button>
|
||||
<button class="btn btn-success" onclick="calcExcel()" id="calcBtn">
|
||||
<span id="calcSpin" class="spinner d-none"></span> Рассчитать и скачать Excel
|
||||
</button>
|
||||
<button class="btn btn-outline" onclick="copy()">Скопировать YAML</button>
|
||||
</div>
|
||||
<div id="calcResult" class="mt-2"></div>
|
||||
</div>
|
||||
|
||||
<!-- Step 4 -->
|
||||
<div class="gen-step card" id="g4">
|
||||
<h2>Смета готова</h2>
|
||||
<p>Расчёт выполнен. Скачайте файл Excel.</p>
|
||||
<div id="downloadInfo" class="mt-2"></div>
|
||||
<div class="gap-2 mt-3">
|
||||
<button class="btn btn-outline" onclick="show(3)">Назад к YAML</button>
|
||||
<a id="downloadLink" class="btn btn-success" href="#" style="text-decoration:none">Скачать Excel</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
let matched=[], yamlStr='';
|
||||
function $(id){return document.getElementById(id);}
|
||||
function esc(s){return s.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>');}
|
||||
|
||||
function show(n){
|
||||
for(let i=1;i<=4;i++) $('g'+i).classList.toggle('active',i===n);
|
||||
$('stepBadge').textContent=`Шаг ${n} из 4`;
|
||||
const L={1:'Описание работ',2:'Проверка позиций',3:'Конфигурация',4:'Скачать Excel'};
|
||||
$('stepLabel').textContent=L[n];
|
||||
}
|
||||
|
||||
async function parse(){
|
||||
const desc=$('desc').value.trim();
|
||||
if(!desc){$('parseErr').textContent='Введите описание работ';return;}
|
||||
$('parseSpin').classList.remove('d-none'); $('parseBtn').disabled=true; $('parseErr').textContent='';
|
||||
try{
|
||||
const r1=await fetch('/api/gen/parse',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({description:desc})});
|
||||
const d1=await r1.json();
|
||||
if(d1.error){$('parseErr').textContent=d1.error;return;}
|
||||
if(!d1.items.length){$('parseErr').textContent='Не удалось разобрать описание';return;}
|
||||
|
||||
const r2=await fetch('/api/gen/match',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({items:d1.items})});
|
||||
const d2=await r2.json();
|
||||
if(d2.error){$('parseErr').textContent=d2.error;return;}
|
||||
matched=d2.matched;
|
||||
|
||||
let h='';
|
||||
for(const m of matched){
|
||||
const ok=m.score>0.3;
|
||||
const sc=m.score>0.6?'score-hi':m.score>0.3?'score-md':'score-lo';
|
||||
h+=`<div class="item ${ok?'ok':'bad'}">
|
||||
<div class="item-head"><strong>${esc(m.description)}</strong><span>${esc(m.unit||'')} x ${m.qty||'?'}</span></div>
|
||||
<div class="item-meta"><span class="score ${sc}">${(m.score*100).toFixed(0)}%</span> <strong>${esc(m.gesn_code)}</strong> ${esc(m.gesn_name||'')}</div>`;
|
||||
if(m.alternatives&&m.alternatives.length){h+='<div class="mt-2">';for(const a of m.alternatives)h+=`<span class="alt">${a.code} (${(a.score*100).toFixed(0)}%)</span>`;h+='</div>';}
|
||||
if(m.note)h+=`<div style="font-size:.82rem;color:var(--text-muted);margin-top:4px">${esc(m.note)}</div>`;
|
||||
h+='</div>';
|
||||
}
|
||||
$('items').innerHTML=h;
|
||||
show(2);
|
||||
}catch(e){$('parseErr').textContent=e.message;}
|
||||
finally{$('parseSpin').classList.add('d-none');$('parseBtn').disabled=false;}
|
||||
}
|
||||
|
||||
async function genYaml(){
|
||||
$('yamlSpin').classList.remove('d-none'); $('yamlBtn').disabled=true;
|
||||
try{
|
||||
const r=await fetch('/api/gen/yaml',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({matched_items:matched,region:$('region').value,trains_per_day:$('trains').value,vl_zone:$('vl').checked,okno:$('okno').checked})});
|
||||
const d=await r.json();
|
||||
if(d.error){alert(d.error);return;}
|
||||
yamlStr=d.yaml;
|
||||
$('yamlOut').textContent=yamlStr;
|
||||
show(3);
|
||||
}catch(e){alert(e.message);}
|
||||
finally{$('yamlSpin').classList.add('d-none');$('yamlBtn').disabled=false;}
|
||||
}
|
||||
|
||||
async function calcExcel(){
|
||||
$('calcSpin').classList.remove('d-none'); $('calcBtn').disabled=true; $('calcResult').innerHTML='';
|
||||
try{
|
||||
const r=await fetch('/api/gen/calculate',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({yaml:yamlStr})});
|
||||
const d=await r.json();
|
||||
if(d.error){
|
||||
$('calcResult').innerHTML=`<div style="color:var(--danger);font-size:.85rem">${esc(d.error)}</div>`;
|
||||
return;
|
||||
}
|
||||
$('downloadLink').href=d.download_url;
|
||||
$('downloadInfo').innerHTML=`<p>Позиций: ${d.positions}</p>`;
|
||||
show(4);
|
||||
}catch(e){$('calcResult').innerHTML=`<div style="color:var(--danger)">${e.message}</div>`;}
|
||||
finally{$('calcSpin').classList.add('d-none');$('calcBtn').disabled=false;}
|
||||
}
|
||||
|
||||
function copy(){
|
||||
navigator.clipboard.writeText(yamlStr).then(()=>{
|
||||
const b=event.target; b.textContent='Скопировано!'; setTimeout(()=>b.textContent='Скопировать',2000);
|
||||
});
|
||||
}
|
||||
function dl(){
|
||||
const b=new Blob([yamlStr],{type:'text/yaml'}), u=URL.createObjectURL(b), a=document.createElement('a');
|
||||
a.href=u; a.download='estimate.yaml'; a.click(); URL.revokeObjectURL(u);
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,115 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Справочники</title>
|
||||
<style>
|
||||
:root {
|
||||
--bg: #f5f0eb; --bg-card: #ffffff;
|
||||
--text: #3a3a3a; --text-muted: #6b6b6b; --text-light: #8b7355;
|
||||
--border: #d4c5b2; --border-light: #ede5db;
|
||||
--accent: #c4463a; --accent-hover: #a83830;
|
||||
--success: #2b8a3e; --warn: #e8590c; --danger: #e03131; --info: #1971c2;
|
||||
--shadow-sm: 0 1px 3px rgba(0,0,0,.05);
|
||||
--shadow-md: 0 4px 16px rgba(0,0,0,.07);
|
||||
--radius: 10px; --radius-lg: 16px;
|
||||
}
|
||||
* { box-sizing: border-box; margin: 0; padding: 0; }
|
||||
body { font-family: 'Inter', -apple-system, sans-serif; background: var(--bg); color: var(--text); }
|
||||
.container { max-width: 860px; margin: 24px auto; padding: 0 16px; }
|
||||
.header { display: flex; align-items: center; justify-content: space-between; margin-bottom: 20px; }
|
||||
.header h1 { font-size: 1.2rem; font-weight: 700; }
|
||||
.header a { color: var(--accent); text-decoration: none; font-size: .85rem; font-weight: 500; }
|
||||
.card { background: var(--bg-card); border-radius: var(--radius-lg); box-shadow: var(--shadow-md); padding: 24px; margin-bottom: 16px; }
|
||||
label { display: block; font-size: .85rem; font-weight: 500; color: var(--text-muted); margin-bottom: 4px; }
|
||||
input, select { width: 100%; padding: .55rem .75rem; border: 1.5px solid var(--border); border-radius: var(--radius); font-size: .9rem; background: var(--bg); outline: none; }
|
||||
input:focus { border-color: var(--accent); background: var(--bg-card); }
|
||||
.tabs { display: flex; gap: 4px; margin-bottom: 16px; }
|
||||
.tab { padding: .5rem 1rem; border: 1.5px solid var(--border); border-radius: var(--radius); cursor: pointer; font-size: .85rem; font-weight: 500; color: var(--text-muted); background: transparent; transition: all .15s; }
|
||||
.tab.active { background: var(--accent); color: #fff; border-color: var(--accent); }
|
||||
.tab:hover:not(.active) { border-color: var(--accent); color: var(--accent); }
|
||||
.btn { padding: .55rem 1.2rem; border: none; border-radius: var(--radius); font-size: .85rem; font-weight: 600; cursor: pointer; background: var(--accent); color: #fff; }
|
||||
.btn:hover { background: var(--accent-hover); }
|
||||
.result { padding: 10px 14px; border-left: 3px solid var(--info); background: var(--bg); border-radius: 0 var(--radius) var(--radius) 0; margin-bottom: 6px; font-size: .88rem; }
|
||||
.result strong { font-weight: 700; }
|
||||
.score { display: inline-block; padding: 1px 6px; border-radius: 8px; font-size: .72rem; font-weight: 700; }
|
||||
.score-hi { background: #d3f9d8; color: var(--success); }
|
||||
.score-md { background: #fff3bf; color: var(--warn); }
|
||||
.score-lo { background: #ffe3e3; color: var(--danger); }
|
||||
.pct { font-size: 1.1rem; font-weight: 700; color: var(--accent); }
|
||||
.muted { color: var(--text-muted); font-size: .82rem; }
|
||||
.mt-2 { margin-top: 8px; }
|
||||
.mt-3 { margin-top: 12px; }
|
||||
.input-row { display: flex; gap: 8px; }
|
||||
.input-row input { flex: 1; }
|
||||
#results { min-height: 100px; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<div class="header">
|
||||
<h1>Справочники</h1>
|
||||
<a href="/">← Назад к чату</a>
|
||||
</div>
|
||||
|
||||
<div class="tabs">
|
||||
<button class="tab active" onclick="setTab('gesn')">Поиск ГЭСН</button>
|
||||
<button class="tab" onclick="setTab('nr')">НР</button>
|
||||
<button class="tab" onclick="setTab('sp')">СП</button>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<div class="input-row">
|
||||
<input type="text" id="q" placeholder="Введите запрос..." onkeydown="if(event.key==='Enter')search()">
|
||||
<button class="btn" onclick="search()">Найти</button>
|
||||
</div>
|
||||
<div id="results" class="mt-3"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
let mode = 'gesn';
|
||||
|
||||
function setTab(m) {
|
||||
mode = m;
|
||||
document.querySelectorAll('.tab').forEach((t, i) => t.classList.toggle('active', ['gesn','nr','sp'][i] === m));
|
||||
document.getElementById('q').placeholder = mode === 'gesn' ? 'Описание работ...' : 'Вид работ...';
|
||||
document.getElementById('results').innerHTML = '';
|
||||
document.getElementById('q').focus();
|
||||
}
|
||||
|
||||
async function search() {
|
||||
const q = document.getElementById('q').value.trim();
|
||||
if (!q) return;
|
||||
const url = mode === 'gesn' ? '/api/ref/search' : `/api/ref/${mode}`;
|
||||
const body = mode === 'gesn' ? {query: q, top_k: 10} : {query: q};
|
||||
const r = await fetch(url, {method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify(body)});
|
||||
const d = await r.json();
|
||||
|
||||
let h = '';
|
||||
if (mode === 'gesn') {
|
||||
if (!d.results || !d.results.length) { h = '<p class="muted">Ничего не найдено</p>'; }
|
||||
else {
|
||||
for (const r of d.results) {
|
||||
const sc = r.score > 0.6 ? 'score-hi' : r.score > 0.3 ? 'score-md' : 'score-lo';
|
||||
h += `<div class="result"><strong>ГЭСН ${esc(r.code)}</strong> <span class="score ${sc}">${(r.score*100).toFixed(0)}%</span><br>${esc(r.name)}<br><span class="muted">Ед: ${esc(r.unit)} | сб.${esc(r.collection)}</span></div>`;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if (!d.results || !d.results.length) { h = `<p class="muted">${d.label}: ничего не найдено</p>`; }
|
||||
else {
|
||||
h = `<p class="muted">${d.label} — найдено: ${d.count}</p>`;
|
||||
for (const r of d.results) {
|
||||
h += `<div class="result">п.${esc(r.key)}. ${esc(r.name)} — <span class="pct">${r.percent}%</span> от ФОТ</div>`;
|
||||
}
|
||||
}
|
||||
}
|
||||
document.getElementById('results').innerHTML = h;
|
||||
}
|
||||
|
||||
function esc(s) { return String(s).replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>'); }
|
||||
document.getElementById('q').focus();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
-204
@@ -1,204 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Генератор ССР</title>
|
||||
<style>
|
||||
:root { --bg: #f5f0eb; --card: #fff; --text: #3a3a3a; --muted: #6b6b6b; --accent: #c4463a; --border: #d4c5b2; --radius: 10px; --green: #2d8a56; }
|
||||
* { box-sizing: border-box; margin: 0; padding: 0; }
|
||||
body { font-family: 'Inter', -apple-system, sans-serif; background: var(--bg); color: var(--text); min-height: 100vh; padding: 2rem; }
|
||||
.container { max-width: 900px; margin: 0 auto; }
|
||||
h1 { font-size: 1.3rem; margin-bottom: .3rem; }
|
||||
.subtitle { color: var(--muted); font-size: .9rem; margin-bottom: 1.5rem; }
|
||||
.badge { display: inline-block; background: var(--green); color: #fff; font-size: .7rem; padding: 2px 8px; border-radius: 12px; vertical-align: middle; margin-left: .5rem; }
|
||||
.card { background: var(--card); border-radius: var(--radius); padding: 1.5rem; margin-bottom: 1rem; box-shadow: 0 1px 4px rgba(0,0,0,.06); }
|
||||
.card.hidden { display: none; }
|
||||
label { display: block; font-weight: 600; margin-bottom: .4rem; font-size: .9rem; }
|
||||
.hint { color: var(--muted); font-size: .8rem; margin-bottom: .6rem; }
|
||||
input[type=file] { width: 100%; padding: .5rem; border: 1.5px dashed var(--border); border-radius: var(--radius); margin-bottom: 1rem; }
|
||||
input[type=number] { width: 80px; padding: .4rem; border: 1.5px solid var(--border); border-radius: 6px; font-size: .9rem; }
|
||||
.params-row { display: flex; flex-wrap: wrap; gap: 1rem; margin: .8rem 0; }
|
||||
.param { display: flex; flex-direction: column; }
|
||||
.param label { font-size: .8rem; font-weight: 500; }
|
||||
button { padding: .7rem 1.5rem; background: var(--accent); color: #fff; border: none; border-radius: var(--radius); font-size: .95rem; font-weight: 600; cursor: pointer; }
|
||||
button:hover { background: #a83830; }
|
||||
button:disabled { background: var(--border); cursor: not-allowed; }
|
||||
.back { display: inline-block; margin-bottom: 1rem; color: var(--accent); text-decoration: none; font-size: .85rem; }
|
||||
.spinner { display: inline-block; width: 16px; height: 16px; border: 2px solid var(--border); border-top-color: var(--accent); border-radius: 50%; animation: spin .8s linear infinite; vertical-align: middle; margin-right: 6px; }
|
||||
@keyframes spin { to { transform: rotate(360deg); } }
|
||||
.error { color: var(--accent); margin-top: .5rem; font-size: .85rem; }
|
||||
.stats { display: flex; gap: 1rem; margin: .5rem 0; font-size: .85rem; color: var(--muted); flex-wrap: wrap; }
|
||||
.stats span { background: #ede5db; padding: 3px 10px; border-radius: 6px; }
|
||||
.btn-download { background: var(--green); margin-top: 1rem; font-size: 1rem; padding: .8rem 2rem; }
|
||||
.btn-download:hover { background: #246e45; }
|
||||
#preview-frame { width: 100%; border: 1px solid var(--border); border-radius: var(--radius); min-height: 400px; background: #fff; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<a class="back" href="/">← Вернуться в чат</a>
|
||||
<h1>Генератор ССР <span class="badge">из GGE</span></h1>
|
||||
<p class="subtitle">Загрузите ZIP с GGE-файлами — получите сводный сметный расчёт (9 листов) с превью</p>
|
||||
|
||||
<!-- Step 1: Upload -->
|
||||
<div class="card" id="step-upload">
|
||||
<label>1. Архив с GGE-файлами (.zip) <span style="color:var(--accent)">*</span></label>
|
||||
<p class="hint">ZIP со всеми локальными сметами в формате GGE (до 2000 файлов)</p>
|
||||
<input type="file" id="zip-file" accept=".zip">
|
||||
|
||||
<label>2. Сводный файл (.xlsx) — <em>необязательно</em></label>
|
||||
<p class="hint">Ваш существующий ССР/РАСПРЕДЕЛЕНИЕ. Скрипт заполнит GGE-данные в лист РАСПРЕДЕЛЕНИЕ, остальные листы не тронет.<br>
|
||||
Если не указан — будет сгенерирован новый файл с нуля (9 листов).</p>
|
||||
<input type="file" id="xlsx-file" accept=".xlsx,.xls">
|
||||
|
||||
<label>Параметры расчёта <span class="hint" style="display:inline">(для генерации с нуля)</span></label>
|
||||
<div class="params-row" id="params-row">
|
||||
<div class="param">
|
||||
<label>Зимнее, %</label>
|
||||
<input type="number" id="p-winter" value="3.2" step="0.1" min="0" max="20">
|
||||
</div>
|
||||
<div class="param">
|
||||
<label>Стройконтроль, %</label>
|
||||
<input type="number" id="p-control" value="0.55" step="0.01" min="0" max="5">
|
||||
</div>
|
||||
<div class="param">
|
||||
<label>Резерв, %</label>
|
||||
<input type="number" id="p-reserve" value="1.0" step="0.5" min="0" max="10">
|
||||
</div>
|
||||
<div class="param">
|
||||
<label>НДС, %</label>
|
||||
<input type="number" id="p-vat" value="22" step="1" min="0" max="30">
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<button id="btn-upload" onclick="doUpload()">Заполнить / Генерировать ССР</button>
|
||||
<div id="upload-error" class="error"></div>
|
||||
</div>
|
||||
|
||||
<!-- Step 2: Processing -->
|
||||
<div class="card hidden" id="step-processing">
|
||||
<span class="spinner"></span> Парсинг GGE-файлов и генерация ССР...
|
||||
<p class="hint" style="margin-top:.5rem">Это может занять 10-30 секунд для крупных архивов</p>
|
||||
</div>
|
||||
|
||||
<!-- Step 3: Preview + Download -->
|
||||
<div class="card hidden" id="step-result">
|
||||
<h2 style="margin-bottom:.5rem">Результат</h2>
|
||||
<div id="stats" class="stats"></div>
|
||||
<button class="btn-download" id="btn-download" onclick="doDownload()">Скачать XLSX (9 листов)</button>
|
||||
<hr style="margin:1rem 0;border:none;border-top:1px solid var(--border)">
|
||||
<h2 style="margin-bottom:.5rem">Превью</h2>
|
||||
<iframe id="preview-frame" sandbox="allow-same-origin"></iframe>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
let token = localStorage.getItem('token');
|
||||
// Validate token on load
|
||||
(async () => {
|
||||
if (!token) { location.href = '/'; return; }
|
||||
try {
|
||||
const r = await fetch('/api/history?limit=1', {headers:{'Authorization':'Bearer '+token}});
|
||||
if (r.ok) return;
|
||||
} catch {}
|
||||
const rt = localStorage.getItem('refresh_token');
|
||||
if (rt) {
|
||||
try {
|
||||
const r = await fetch('/api/refresh', {method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify({refresh_token:rt})});
|
||||
if (r.ok) { const d = await r.json(); token = d.token; localStorage.setItem('token', token); return; }
|
||||
} catch {}
|
||||
}
|
||||
localStorage.removeItem('token'); localStorage.removeItem('refresh_token');
|
||||
location.href = '/';
|
||||
})();
|
||||
|
||||
let currentJobId = null;
|
||||
|
||||
async function doUpload() {
|
||||
const zipInput = document.getElementById('zip-file');
|
||||
const errorEl = document.getElementById('upload-error');
|
||||
errorEl.textContent = '';
|
||||
|
||||
if (!zipInput.files.length) {
|
||||
errorEl.textContent = 'Выберите ZIP-файл';
|
||||
return;
|
||||
}
|
||||
|
||||
const xlsxInput = document.getElementById('xlsx-file');
|
||||
const hasXlsx = xlsxInput.files.length > 0;
|
||||
|
||||
const fd = new FormData();
|
||||
fd.append('zip_file', zipInput.files[0]);
|
||||
if (hasXlsx) {
|
||||
fd.append('xlsx_file', xlsxInput.files[0]);
|
||||
fd.append('mode', 'fill'); // fill existing file
|
||||
} else {
|
||||
fd.append('mode', 'generate'); // generate from scratch
|
||||
}
|
||||
fd.append('winter_pct', document.getElementById('p-winter').value);
|
||||
fd.append('control_pct', document.getElementById('p-control').value);
|
||||
fd.append('reserve_pct', document.getElementById('p-reserve').value);
|
||||
fd.append('vat_pct', document.getElementById('p-vat').value);
|
||||
|
||||
document.getElementById('btn-upload').disabled = true;
|
||||
document.getElementById('step-processing').classList.remove('hidden');
|
||||
|
||||
try {
|
||||
const resp = await fetch('/api/ssr/upload', {
|
||||
method: 'POST',
|
||||
headers: { 'Authorization': 'Bearer ' + token },
|
||||
body: fd,
|
||||
});
|
||||
|
||||
if (!resp.ok) {
|
||||
const err = await resp.json();
|
||||
throw new Error(err.detail || 'Upload failed');
|
||||
}
|
||||
|
||||
const data = await resp.json();
|
||||
currentJobId = data.job_id;
|
||||
|
||||
// Show stats
|
||||
const s = data.stats;
|
||||
document.getElementById('stats').innerHTML =
|
||||
`<span>Смет: ${s.estimates}</span>` +
|
||||
`<span>Глав: ${s.chapters}</span>` +
|
||||
`<span>Листов: ${s.sheets}</span>` +
|
||||
`<span>СР-10: ${s.sr10_eff_pct.toFixed(3)}%</span>` +
|
||||
`<span>Итого с НДС: ${Number(s.total_vat).toLocaleString('ru-RU', {minimumFractionDigits:2})} тыс.руб.</span>`;
|
||||
|
||||
// Show preview in iframe
|
||||
const frame = document.getElementById('preview-frame');
|
||||
frame.srcdoc = data.preview_html;
|
||||
frame.style.height = '600px';
|
||||
|
||||
document.getElementById('step-processing').classList.add('hidden');
|
||||
document.getElementById('step-result').classList.remove('hidden');
|
||||
|
||||
} catch (e) {
|
||||
errorEl.textContent = e.message;
|
||||
document.getElementById('step-processing').classList.add('hidden');
|
||||
document.getElementById('btn-upload').disabled = false;
|
||||
}
|
||||
}
|
||||
|
||||
function doDownload() {
|
||||
if (!currentJobId) return;
|
||||
const a = document.createElement('a');
|
||||
a.href = `/api/ssr/download/${currentJobId}`;
|
||||
// Add auth header via fetch+blob
|
||||
fetch(a.href, { headers: { 'Authorization': 'Bearer ' + token } })
|
||||
.then(r => r.blob())
|
||||
.then(blob => {
|
||||
const url = URL.createObjectURL(blob);
|
||||
const link = document.createElement('a');
|
||||
link.href = url;
|
||||
link.download = 'ssr_generated.xlsx';
|
||||
link.click();
|
||||
URL.revokeObjectURL(url);
|
||||
});
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,235 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Агрегатор xlsx</title>
|
||||
<style>
|
||||
:root {
|
||||
--bg: #f5f0eb; --bg-card: #ffffff; --bg-input: #ffffff;
|
||||
--text: #3a3a3a; --text-muted: #6b6b6b; --text-light: #8b7355;
|
||||
--border: #d4c5b2; --border-light: #ede5db;
|
||||
--accent: #c4463a; --accent-hover: #a83830;
|
||||
--success: #2b8a3e; --info: #1971c2;
|
||||
--shadow-sm: 0 1px 3px rgba(0,0,0,.05);
|
||||
--shadow-md: 0 4px 16px rgba(0,0,0,.07);
|
||||
--radius: 10px; --radius-lg: 16px;
|
||||
}
|
||||
* { box-sizing: border-box; margin: 0; padding: 0; }
|
||||
body { font-family: 'Inter', -apple-system, sans-serif; background: var(--bg); color: var(--text); -webkit-font-smoothing: antialiased; }
|
||||
.container { max-width: 860px; margin: 24px auto; padding: 0 16px; }
|
||||
.header { display: flex; align-items: center; justify-content: space-between; margin-bottom: 20px; }
|
||||
.header h1 { font-size: 1.2rem; font-weight: 700; }
|
||||
.header a { color: var(--accent); text-decoration: none; font-size: .85rem; font-weight: 500; }
|
||||
.card { background: var(--bg-card); border-radius: var(--radius-lg); box-shadow: var(--shadow-md); padding: 24px; margin-bottom: 16px; }
|
||||
.card h2 { font-size: 1rem; font-weight: 600; margin-bottom: 12px; color: var(--text); }
|
||||
label { display: block; font-size: .85rem; font-weight: 500; color: var(--text-muted); margin-bottom: 4px; }
|
||||
input[type="text"], input[type="file"], select { width: 100%; padding: .55rem .75rem; border: 1.5px solid var(--border); border-radius: var(--radius); font-size: .9rem; background: var(--bg); outline: none; transition: border-color .2s; }
|
||||
input:focus, select:focus { border-color: var(--accent); background: var(--bg-card); }
|
||||
.row { display: flex; gap: 12px; }
|
||||
.row > * { flex: 1; }
|
||||
.btn { padding: .55rem 1.2rem; border: none; border-radius: var(--radius); font-size: .85rem; font-weight: 600; cursor: pointer; transition: all .15s; }
|
||||
.btn-primary { background: var(--accent); color: #fff; }
|
||||
.btn-primary:hover { background: var(--accent-hover); }
|
||||
.btn-outline { background: transparent; border: 1.5px solid var(--border); color: var(--text-muted); }
|
||||
.btn-outline:hover { border-color: var(--accent); color: var(--accent); }
|
||||
.btn-success { background: var(--success); color: #fff; }
|
||||
.btn:disabled { opacity: .5; cursor: not-allowed; }
|
||||
.step-bar { display: flex; gap: 4px; margin-bottom: 20px; }
|
||||
.step-dot { flex: 1; height: 5px; border-radius: 3px; background: var(--border-light); transition: background .3s; }
|
||||
.step-dot.done { background: var(--success); }
|
||||
.step-dot.current { background: var(--accent); }
|
||||
.wiz-step { display: none; }
|
||||
.wiz-step.active { display: block; }
|
||||
.preview-table { max-height: 280px; overflow-y: auto; font-size: .82rem; border: 1px solid var(--border-light); border-radius: var(--radius); }
|
||||
.preview-table table { width: 100%; border-collapse: collapse; }
|
||||
.preview-table th { background: var(--bg); font-weight: 600; position: sticky; top: 0; }
|
||||
.preview-table td, .preview-table th { padding: 6px 10px; border-bottom: 1px solid var(--border-light); white-space: nowrap; }
|
||||
.status-add { color: var(--success); font-weight: 600; }
|
||||
.status-update { color: var(--info); }
|
||||
.badge { display: inline-block; padding: 2px 8px; border-radius: 10px; font-size: .75rem; font-weight: 600; }
|
||||
.badge-info { background: #dbeafe; color: var(--info); }
|
||||
.badge-success { background: #d3f9d8; color: var(--success); }
|
||||
.badge-muted { background: var(--border-light); color: var(--text-muted); }
|
||||
.error { color: #e03131; font-size: .85rem; margin-top: 8px; }
|
||||
.file-list { font-size: .85rem; color: var(--text-muted); }
|
||||
.spinner { width: 1rem; height: 1rem; border: 2px solid var(--border); border-top-color: var(--accent); border-radius: 50%; animation: spin .6s linear infinite; display: inline-block; }
|
||||
@keyframes spin { to { transform: rotate(360deg); } }
|
||||
.d-none { display: none !important; }
|
||||
.mt-2 { margin-top: 8px; }
|
||||
.mt-3 { margin-top: 12px; }
|
||||
.mb-2 { margin-bottom: 8px; }
|
||||
.nav-bottom { display: flex; justify-content: space-between; margin-top: 16px; }
|
||||
.alert-success { background: #d3f9d8; border: 1px solid #69db7c; border-radius: var(--radius); padding: 12px; color: var(--success); }
|
||||
.alert-success a { color: var(--success); font-weight: 600; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<div class="header">
|
||||
<h1>Агрегатор xlsx</h1>
|
||||
<a href="/">← Назад к чату</a>
|
||||
</div>
|
||||
|
||||
<div class="step-bar" id="stepBar"></div>
|
||||
|
||||
<!-- Step 1 -->
|
||||
<div class="wiz-step active card" id="s1">
|
||||
<h2>Загрузка файлов</h2>
|
||||
<div class="mb-2"><label>ZIP-архив с источниками</label><input type="file" id="fZip" accept=".zip"></div>
|
||||
<div class="mb-2"><label>Целевой файл (.xlsx)</label><input type="file" id="fTarget" accept=".xlsx"></div>
|
||||
<button class="btn btn-primary" onclick="upload()"><span id="upSpin" class="spinner d-none"></span> Загрузить</button>
|
||||
<div id="upErr" class="error"></div>
|
||||
<div id="upInfo" class="file-list mt-2"></div>
|
||||
</div>
|
||||
|
||||
<!-- Step 2 -->
|
||||
<div class="wiz-step card" id="s2">
|
||||
<h2>Критерий поиска</h2>
|
||||
<div class="row mb-2">
|
||||
<div><label>Лист</label><select id="srcSheet"></select></div>
|
||||
<div><label>Колонка</label><select id="srcCol"></select></div>
|
||||
<div><label>Ключевое слово</label><input type="text" id="srcKw" value="разряд"></div>
|
||||
</div>
|
||||
<button class="btn btn-outline" onclick="analyze()">Найти</button>
|
||||
<div id="searchPrev" class="mt-2"></div>
|
||||
</div>
|
||||
|
||||
<!-- Step 3 -->
|
||||
<div class="wiz-step card" id="s3">
|
||||
<h2>Колонка значений</h2>
|
||||
<div class="mb-2"><label>Из какой колонки брать числа?</label><select id="valCol"></select></div>
|
||||
<button class="btn btn-outline" onclick="analyzeVal()">Превью</button>
|
||||
<div id="valPrev" class="mt-2"></div>
|
||||
</div>
|
||||
|
||||
<!-- Step 4 -->
|
||||
<div class="wiz-step card" id="s4">
|
||||
<h2>Сопоставление с целевым</h2>
|
||||
<div class="row"><div><label>Лист</label><select id="tgtSheet"></select></div><div><label>Колонка</label><select id="matchCol"></select></div></div>
|
||||
</div>
|
||||
|
||||
<!-- Step 5 -->
|
||||
<div class="wiz-step card" id="s5">
|
||||
<h2>Действие</h2>
|
||||
<div class="row">
|
||||
<div><label>Операция</label><select id="action"><option value="sum">Суммировать</option><option value="replace">Заменить</option><option value="max">Максимум</option><option value="min">Минимум</option></select></div>
|
||||
<div><label>Записать в колонку</label><select id="writeCol"></select></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Step 6 -->
|
||||
<div class="wiz-step card" id="s6">
|
||||
<h2>Ненайденные строки</h2>
|
||||
<select id="unmatched" style="max-width:300px"><option value="add">Добавить новые строки</option><option value="skip">Пропустить</option></select>
|
||||
</div>
|
||||
|
||||
<!-- Step 7 -->
|
||||
<div class="wiz-step card" id="s7">
|
||||
<h2>Превью и подтверждение</h2>
|
||||
<div id="prevLoad" class="d-none" style="text-align:center;padding:20px"><div class="spinner"></div><p class="mt-2" style="color:var(--text-muted)">Вычисляю...</p></div>
|
||||
<div id="prevResult"></div>
|
||||
<div id="prevSummary" class="mt-2"></div>
|
||||
<button class="btn btn-success mt-3 d-none" id="runBtn" onclick="run()"><span id="runSpin" class="spinner d-none"></span> Применить и скачать</button>
|
||||
<div id="runResult" class="mt-2"></div>
|
||||
</div>
|
||||
|
||||
<div class="nav-bottom">
|
||||
<button class="btn btn-outline" id="prevBtn" onclick="prev()" disabled>Назад</button>
|
||||
<button class="btn btn-primary" id="nextBtn" onclick="next()" disabled>Далее</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
const N=7; let step=1,sid=null,src=null,tgt=null;
|
||||
|
||||
function ui(){
|
||||
for(let i=1;i<=N;i++) document.getElementById('s'+i).classList.toggle('active',i===step);
|
||||
document.getElementById('prevBtn').disabled=step===1;
|
||||
document.getElementById('nextBtn').disabled=!ok();
|
||||
const b=document.getElementById('stepBar'); b.innerHTML='';
|
||||
for(let i=1;i<=N;i++){const c=i<step?'done':i===step?'current':''; b.innerHTML+=`<div class="step-dot ${c}"></div>`;}
|
||||
if(step===7) loadPreview();
|
||||
}
|
||||
function ok(){
|
||||
if(step===1)return!!sid; if(step===2)return!!$('srcCol').value;
|
||||
if(step===3)return!!$('valCol').value; if(step===4)return!!$('matchCol').value;
|
||||
return step===5||step===6;
|
||||
}
|
||||
function next(){if(step<N){step++;ui();}} function prev(){if(step>1){step--;ui();}}
|
||||
function $(id){return document.getElementById(id);}
|
||||
|
||||
async function upload(){
|
||||
const z=$('fZip').files[0], t=$('fTarget').files[0];
|
||||
if(!z||!t){$('upErr').textContent='Выберите оба файла';return;}
|
||||
$('upSpin').classList.remove('d-none'); $('upErr').textContent='';
|
||||
const fd=new FormData(); fd.append('zip_file',z); fd.append('target_file',t);
|
||||
try{
|
||||
const r=await fetch('/api/wizard/upload',{method:'POST',body:fd});
|
||||
if(!r.ok){const e=await r.json();throw new Error(e.detail||'Ошибка загрузки');}
|
||||
const d=await r.json(); sid=d.session_id; src=d.sources; tgt=d.target;
|
||||
let h=`<p><strong>Источники:</strong> ${src.length} файл(ов)</p><ul>`;
|
||||
for(const s of src) h+=`<li>${s.filename} — ${s.sheets.map(sh=>sh.name+' ('+sh.row_count+')').join(', ')}</li>`;
|
||||
h+=`</ul><p><strong>Целевой:</strong> ${tgt.filename}</p>`;
|
||||
$('upInfo').innerHTML=h; popSrc(); popTgt(); ui();
|
||||
}catch(e){$('upErr').textContent=e.message;}
|
||||
finally{$('upSpin').classList.add('d-none');}
|
||||
}
|
||||
|
||||
function popSrc(){
|
||||
const ss=$('srcSheet'),sc=$('srcCol'),vc=$('valCol'); ss.innerHTML='';sc.innerHTML='';vc.innerHTML='';
|
||||
const sheets=new Set(); for(const s of src) for(const sh of s.sheets) sheets.add(sh.name);
|
||||
for(const n of sheets) ss.innerHTML+=`<option>${n}</option>`;
|
||||
const cols=src[0].sheets[0].columns;
|
||||
for(const c of cols){const l=`${c.letter}: ${c.header} (${c.type})`;sc.innerHTML+=`<option value="${c.letter}">${l}</option>`;vc.innerHTML+=`<option value="${c.letter}">${l}</option>`;}
|
||||
const tc=cols.filter(c=>c.type==='text'),nc=cols.filter(c=>c.type==='number');
|
||||
const nl=tc.find(c=>/наименован/i.test(c.header)); if(nl)sc.value=nl.letter; else if(tc.length)sc.value=tc[0].letter;
|
||||
const ql=nc.find(c=>/количеств|кол/i.test(c.header)); if(ql)vc.value=ql.letter; else if(nc.length)vc.value=nc[0].letter;
|
||||
}
|
||||
function popTgt(){
|
||||
const ts=$('tgtSheet'),mc=$('matchCol'),wc=$('writeCol'); ts.innerHTML='';mc.innerHTML='';wc.innerHTML='';
|
||||
for(const sh of tgt.sheets) ts.innerHTML+=`<option>${sh.name}</option>`;
|
||||
const cols=tgt.sheets[0].columns;
|
||||
for(const c of cols){const l=`${c.letter}: ${c.header} (${c.type})`;mc.innerHTML+=`<option value="${c.letter}">${l}</option>`;wc.innerHTML+=`<option value="${c.letter}">${l}</option>`;}
|
||||
const tc=cols.filter(c=>c.type==='text'),nc=cols.filter(c=>c.type==='number');
|
||||
const nl=tc.find(c=>/наименован/i.test(c.header)); if(nl)mc.value=nl.letter; else if(tc.length)mc.value=tc[0].letter;
|
||||
const ql=nc.find(c=>/количеств|кол/i.test(c.header)); if(ql)wc.value=ql.letter; else if(nc.length)wc.value=nc[0].letter;
|
||||
}
|
||||
|
||||
async function analyze(){
|
||||
const r=await fetch('/api/wizard/analyze',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({session_id:sid,search_column:$('srcCol').value,search_keyword:$('srcKw').value,source_sheet:$('srcSheet').value})});
|
||||
const d=await r.json();
|
||||
let h=`<p>Найдено: <strong>${d.found_count}</strong>, ключей: <strong>${(d.unique_keys||[]).length}</strong></p>`;
|
||||
if(d.sample_rows&&d.sample_rows.length){h+='<div class="preview-table"><table><thead><tr><th>Файл</th><th>Строка</th><th>Текст</th><th>Ключ</th></tr></thead><tbody>';for(const r of d.sample_rows.slice(0,15))h+=`<tr><td>${r.file}</td><td>${r.row}</td><td>${r.search_value}</td><td>${r.key||'-'}</td></tr>`;h+='</tbody></table></div>';}
|
||||
$('searchPrev').innerHTML=h; ui();
|
||||
}
|
||||
async function analyzeVal(){
|
||||
const r=await fetch('/api/wizard/analyze',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({session_id:sid,search_column:$('srcCol').value,search_keyword:$('srcKw').value,source_sheet:$('srcSheet').value,value_column:$('valCol').value})});
|
||||
const d=await r.json(); let h='';
|
||||
if(d.sample_rows&&d.sample_rows.length){h+='<div class="preview-table"><table><thead><tr><th>Файл</th><th>Ключ</th><th>Значение</th></tr></thead><tbody>';for(const r of d.sample_rows.slice(0,10))h+=`<tr><td>${r.file}</td><td>${r.key||'-'}</td><td>${r.number_value!=null?r.number_value.toFixed(2):'-'}</td></tr>`;h+='</tbody></table></div>';}
|
||||
$('valPrev').innerHTML=h;
|
||||
}
|
||||
|
||||
function cfg(){return{session_id:sid,search_keyword:$('srcKw').value,search_column:$('srcCol').value,value_column:$('valCol').value,source_sheet:$('srcSheet').value||null,target_sheet:$('tgtSheet').value||null,match_column:$('matchCol').value,target_write_column:$('writeCol').value,action:$('action').value,unmatched:$('unmatched').value};}
|
||||
|
||||
async function loadPreview(){
|
||||
$('prevLoad').classList.remove('d-none');$('prevResult').innerHTML='';$('prevSummary').innerHTML='';$('runBtn').classList.add('d-none');
|
||||
try{const r=await fetch('/api/wizard/preview',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(cfg())});const d=await r.json();
|
||||
let h='<div class="preview-table"><table><thead><tr><th>Статус</th><th>Строка</th><th>Название</th><th>Было</th><th>Станет</th></tr></thead><tbody>';
|
||||
for(const m of d.matches){const c=m.status==='add'?'status-add':'status-update',l=m.status==='add'?'НОВЫЙ':'обновл.';h+=`<tr><td class="${c}">${l}</td><td>${m.target_row||'—'}</td><td>${m.target_label}</td><td>${m.current_value!=null?m.current_value.toFixed(2):'—'}</td><td>${m.new_value.toFixed(2)}</td></tr>`;}
|
||||
h+='</tbody></table></div>';$('prevResult').innerHTML=h;
|
||||
const s=d.summary;$('prevSummary').innerHTML=`<span class="badge badge-info">${s.updates} обновлений</span> <span class="badge badge-success">${s.adds} новых</span> <span class="badge badge-muted">Итого: ${s.total_new_value.toFixed(2)}</span>`;
|
||||
if(d.matches.length)$('runBtn').classList.remove('d-none');
|
||||
}finally{$('prevLoad').classList.add('d-none');}
|
||||
}
|
||||
|
||||
async function run(){
|
||||
$('runSpin').classList.remove('d-none');
|
||||
try{const r=await fetch('/api/wizard/run',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(cfg())});const d=await r.json();
|
||||
if(d.success)$('runResult').innerHTML=`<div class="alert-success">Готово! Обновлено: ${d.stats.updated}, добавлено: ${d.stats.added}<br><a href="${d.download_url}">Скачать результат</a></div>`;
|
||||
}finally{$('runSpin').classList.add('d-none');}
|
||||
}
|
||||
ui();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
+13
-49
@@ -61,57 +61,21 @@ def test_legit_tab_still_works(env):
|
||||
assert r.json() == []
|
||||
|
||||
|
||||
# ---- анонимные эндпоинты закрыты ----
|
||||
# ---- депрекированный пакетный путь убран целиком (exec на хосте + анонимные роуты) ----
|
||||
|
||||
def test_gen_download_requires_auth(env):
|
||||
def test_deprecated_pages_redirect(env):
|
||||
_auth, _main, client, _tmp = env
|
||||
r = client.get("/api/gen/download/anything") # без Authorization
|
||||
assert r.status_code == 401
|
||||
for url in ("/batch2", "/batch3", "/ssr", "/generate", "/wizard", "/reference", "/check"):
|
||||
r = client.get(url, follow_redirects=False)
|
||||
assert r.status_code == 302, f"{url} → {r.status_code}"
|
||||
assert r.headers.get("location", "").endswith("/"), f"{url} → {r.headers.get('location')}"
|
||||
|
||||
|
||||
def test_check_yaml_requires_auth(env):
|
||||
def test_deprecated_api_endpoints_gone(env):
|
||||
_auth, _main, client, _tmp = env
|
||||
r = client.post("/api/check/yaml", json={"yaml": "x: 1"})
|
||||
assert r.status_code == 401
|
||||
|
||||
|
||||
def test_mounted_routers_and_gen_reject_anon(env):
|
||||
"""Fable verify #1/#4: /api/gen|ref|wizard/* были полностью анонимны (жгли LLM/RAG,
|
||||
грузили файлы). Ни один маршрут под этими префиксами не должен пускать без токена."""
|
||||
import re as _re
|
||||
_auth, main, client, _tmp = env
|
||||
targets = []
|
||||
for r in main.app.routes:
|
||||
p = getattr(r, "path", "")
|
||||
if p.startswith(("/api/ref/", "/api/wizard/", "/api/gen/")): # с '/' — не ловить /api/refresh
|
||||
methods = getattr(r, "methods", None) or {"GET"}
|
||||
m = "POST" if "POST" in methods else ("GET" if "GET" in methods else next(iter(methods)))
|
||||
targets.append((m, _re.sub(r"\{[^}]+\}", "x", p)))
|
||||
assert targets, "нет смонтированных маршрутов — тест бесполезен"
|
||||
for m, url in targets:
|
||||
resp = client.request(m, url) # без Authorization
|
||||
assert resp.status_code == 401, f"{m} {url} → {resp.status_code}, ждали 401"
|
||||
|
||||
|
||||
# ---- владелец job'а ----
|
||||
|
||||
def test_require_job_owner_helper(env):
|
||||
_auth, main, _client, _tmp = env
|
||||
from fastapi import HTTPException
|
||||
assert main._require_job_owner({"user": "a@x"}, "a@x")["user"] == "a@x"
|
||||
with pytest.raises(HTTPException):
|
||||
main._require_job_owner({"user": "a@x"}, "b@x") # чужой → 404
|
||||
with pytest.raises(HTTPException):
|
||||
main._require_job_owner(None, "a@x") # нет job → 404
|
||||
|
||||
|
||||
def test_batch_v3_status_foreign_is_404(env):
|
||||
_auth, main, client, _tmp = env
|
||||
auth = _auth
|
||||
# заводим job вручную от имени owner@x, спрашиваем от mallory@x
|
||||
import batch_v3
|
||||
job = batch_v3.create_job("deadbeef")
|
||||
job["user"] = "owner@x"
|
||||
job["job_dir"] = "/tmp/nope"
|
||||
r = client.get("/api/batch-v3/status/deadbeef", headers=_h(auth, user="mallory@x"))
|
||||
assert r.status_code == 404
|
||||
# exec-путь (batch v2/v3) + SSR + анонимные gen/check/ref/wizard удалены → маршрута нет
|
||||
for m, url in [("POST", "/api/batch-v3/upload"), ("POST", "/api/batch-v2/upload"),
|
||||
("POST", "/api/ssr/upload"), ("POST", "/api/check/yaml"),
|
||||
("GET", "/api/gen/download/x"), ("POST", "/api/gen/parse"),
|
||||
("POST", "/api/ref/search"), ("POST", "/api/wizard/upload")]:
|
||||
assert client.request(m, url).status_code == 404, f"{m} {url} всё ещё жив"
|
||||
|
||||
Reference in New Issue
Block a user