Compare commits
8
Commits
f24e8595c1
...
a0474785d1
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a0474785d1 | ||
|
|
27c7634ff0 | ||
|
|
728215557d | ||
|
|
0fd9f95a1f | ||
|
|
bfc3895251 | ||
|
|
efbd87d9c3 | ||
|
|
c3fdb23d3a | ||
|
|
58c2d6d6e5 |
@@ -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()
|
||||
+2
-3
@@ -7,6 +7,7 @@ from pathlib import Path
|
||||
from typing import AsyncGenerator
|
||||
|
||||
from chat_context import history_recap
|
||||
from path_safety import safe_work_dir
|
||||
|
||||
DOCKER_IMAGE = os.environ.get("CLAUDE_DOCKER_IMAGE", "smeta-claude-sandbox")
|
||||
try:
|
||||
@@ -111,9 +112,7 @@ def _preprocess_xlsx(work_dir: Path):
|
||||
|
||||
|
||||
def get_work_dir(username: str, tab_id: str) -> Path:
|
||||
d = DATA_DIR / username / tab_id
|
||||
d.mkdir(parents=True, exist_ok=True)
|
||||
return d
|
||||
return safe_work_dir(username, tab_id) # блок path-traversal через client-controlled tab_id
|
||||
|
||||
|
||||
def get_session_id(username: str, tab_id: str) -> str | None:
|
||||
|
||||
@@ -14,6 +14,8 @@ from typing import AsyncGenerator
|
||||
|
||||
import httpx
|
||||
|
||||
from path_safety import safe_work_dir
|
||||
|
||||
SMETA_DIR = Path(os.environ.get("SMETA_PROJECT_DIR", os.path.expanduser("~/smeta-railway")))
|
||||
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")
|
||||
@@ -245,9 +247,7 @@ from search_engine import _normalize, _search_fssc, _search_resources, _search_g
|
||||
|
||||
|
||||
def get_work_dir(username: str, tab_id: str) -> Path:
|
||||
d = DATA_DIR / username / tab_id
|
||||
d.mkdir(parents=True, exist_ok=True)
|
||||
return d
|
||||
return safe_work_dir(username, tab_id) # блок path-traversal через client-controlled tab_id
|
||||
|
||||
|
||||
def get_session_id(username: str, tab_id: str) -> str | None:
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
# Ревизия «промахи не по бест-практикс» — 2026-07-18
|
||||
|
||||
Два read-only аудита Fable (фронтенд-UX + бэкенд/продукт) + моя верификация топ-находок.
|
||||
Мотив запроса: выбор даты был через `prompt()` — найти ВСЕ подобные «работает, но сделано лениво/не по бест-практикс», особенно то, что бьёт по пользователю или money/security. Код не менялся.
|
||||
|
||||
Системный вывод обоих аудиторов (независимо): **паттерн-правило в коде УЖЕ есть в части мест
|
||||
(маскирование ошибок, `_safe_tab`, `to_thread`, tus-проверка диска, `esc()`), но применён точечно —
|
||||
соседние пути живут по-старому.** Это и есть главный класс дефекта, зеркало `prompt()`-а.
|
||||
|
||||
Легенда: [V] = проверил лично в коде, подтверждено; [F] = находка Fable, не перепроверял.
|
||||
|
||||
---
|
||||
|
||||
## КРИТИЧНО (чинить первым — живой инструмент принимает файлы от контрагентов)
|
||||
|
||||
### 1. [V] Path traversal через заголовок `x-tab-id` → чтение и УДАЛЕНИЕ файлов вне своей папки
|
||||
- `claude_bridge.py:113-116`, `claude_bridge_glm.py:246-249` — `get_work_dir = DATA_DIR/username/tab_id`, БЕЗ санитизации.
|
||||
- `tab_id` = заголовок `x-tab-id` (не нормализуется браузером/сервером), течёт в `main.py:490, 676, 764, 832/836, 858, 888, 923`.
|
||||
- Вектор чтения: `GET /api/files/passwd` + `x-tab-id: ../../../../etc` → `FileResponse(/etc/passwd)` (`main.py:830-839`).
|
||||
- Вектор разрушения: `POST /api/clear-files` + `x-tab-id: ../..` → `work_dir` = родитель DATA_DIR, дальше `iterdir()`+`rmtree`/`unlink` (`main.py:921-930`) — сносит чужие каталоги.
|
||||
- Контраст (fix уже есть): `tus_upload.py:68-72` `_safe_tab`, `main.py:1420-1429` `admin_file_download` (`Path(...).name` + `resolve().relative_to(DATA_DIR)`).
|
||||
- Fix: единый `_safe_tab`-гард в `get_work_dir` обоих мостов + `relative_to`-проверка. `username`=email валидируется только по `@` (`auth.py:144`) — тоже прогнать через гард.
|
||||
|
||||
### 2. [V] `exec()` LLM-скрипта на ХОСТЕ, в процессе сервера
|
||||
- `batch_v3.py:439, 515, 764` — `exec(script, exec_globals)`, где `script` написал Claude по содержимому загруженного xlsx; `exec_globals` содержит `os`. Генерация — в Docker, исполнение — нет.
|
||||
- `batch.py:393` — то же в мёртвом модуле (не импортируется; V1-endpoints удалены).
|
||||
- Последствие: prompt-injection в смете контрагента → доступ к `.env` (SESSION_SECRET/SMTP_PASS/ZAI_API_KEY), БД, файлам всех, `~/.claude`.
|
||||
- Fix: исполнять в том же контейнере, что и генерация (том job_dir есть), либо изолированный subprocess без окружения сервера. `batch.py` — удалить.
|
||||
|
||||
### 3. [F] Stored XSS в админ-панели через email пользователя
|
||||
- `static/admin.html:268-273` — `tr.innerHTML = ...u.email...` без `esc()` (в соседних таблицах `esc()` применён). Email задаёт сам юзер по инвайту.
|
||||
- `static/admin.html:434-435` — то же в дропдаунах фильтра журнала.
|
||||
- Токены (access+refresh) в localStorage → XSS = полный увод админ-сессии.
|
||||
- Плюс inline-`onclick` строковой конкатенацией с email — ломается на легальном апострофе (`o'brien@…`) и это второй канал инъекции.
|
||||
- Fix: `esc()` на все ячейки из данных; `addEventListener`/data-атрибуты вместо строкового onclick.
|
||||
|
||||
---
|
||||
|
||||
## СЕРЬЁЗНО (money-safety / доступ к чужому / зависание всех)
|
||||
|
||||
### 4. [V] Дыры авторизации в пакетных/SSR/gen путях
|
||||
- `/api/gen/download/{job_id}` (`main.py:1921-1928`) — БЕЗ auth вообще; job_id угадываем.
|
||||
- `/api/check/yaml` (`main.py:1812-1843`) — без auth и возвращает сырой `str(exc)` наружу (`:1841`) — тот же класс, что инцидент 401.
|
||||
- Batch v2/v3, SSR (`main.py:1027-1125, 1530-1629, 1747-1762`) — проверяют только факт логина, НЕ владельца job (`_ssr_jobs[id]["user"]` пишется `:1702`, но не сверяется). job_id = `uuid4()[:8]` (32 бита). → скачивание/запуск чужих смет.
|
||||
- Смонтированные роутеры smeta-railway (`main.py:1786-1792`) — auth не виден, проверить.
|
||||
- Fix: `job["user"]==user` во всех job-эндпоинтах; `_get_user` на download/check; наружу — фикс-сообщение.
|
||||
|
||||
### 5. [V] Слабая крипта паролей + неработающая блокировка + fail-quiet секрет
|
||||
- `auth.py:53-56` — пароль = одиночный `sha256(salt+password)`. При утечке БД брутится на GPU. → PBKDF2/bcrypt/argon2.
|
||||
- `auth.py:176-185` (`verify_token`), `get_token_role`, refresh — декодят JWT, в БД НЕ смотрят: заблокированный/удалённый юзер работает до 24ч (access) и обновляется до 7 дней (refresh). Кнопка «заблокировать» фактически не блокирует.
|
||||
- `auth.py:19-21` — пустой `SESSION_SECRET` = только warning: логин молча ломается, download-ticket (`auth.py:200-217`) подписывается пустым ключом → подделка. → fail-loud на старте.
|
||||
- `main.py:444-454` — `/api/verify-email` без rate-limit: 6-значный код (1М, TTL 10мин) брутится.
|
||||
- `auth.py:149-155` — инвайт сжигается ДО проверки «email существует» → потеря приглашения на опечатке.
|
||||
- [F] lockout возвращает «Wrong credentials» вместо 429 «через N минут» (выдуманная причина).
|
||||
|
||||
### 6. [V/F] Синхронщина на event loop — «сервер завис у всех» (класс инцидента с сетью ФГИС)
|
||||
- [V] `db.py` весь синхронный, `busy_timeout=10s`; audit-middleware `log_action` (INSERT) на КАЖДОМ запросе (`main.py:236`), `save_message` в стриме (`main.py:487, 527`). `to_thread` применён только к `/health` и `/api/feedback` (`main.py:339, 613`) — 2 из ~30.
|
||||
- [F] `claude_bridge_glm.py:639-687` — весь сбор контекста (поиск по 24k ресурсов, парсинг 5-12МБ корпуса, faiss+embed) синхронно в `async`; в `to_thread` только `_read_work_dir_files`.
|
||||
- [F] `search_engine.py:121-150` — `_search_gesn_extra` на КАЖДЫЙ запрос заново `json.loads`-ит все `gesn_*.json` (181000+ норм) без кэша; триггер — почти любое сметное слово.
|
||||
- [F] `claude_bridge_sonnet.py:110,139` — тяжёлый openpyxl синхронно (в glm-близнеце обёрнут).
|
||||
- [F] `main.py:437` + `email_service.py:70-79` — SMTP (SSL+login, 10с) синхронно в регистрации.
|
||||
- [F] Batch/SSR: `extract_zip`/`convert_all_to_csv` (2000+ xlsx) синхронно (`main.py:991-1003, 1497-1506`); `await zip_file.read()` без лимита (`main.py:987, 1493, 1679`); распаковка без zip-bomb капа (`xlsx_utils.py:84-111`).
|
||||
- Fix: единообразный `to_thread` для db + сбора контекста; кэш gesn_extra по mtime; size-limit до чтения; обработку ZIP — в фон.
|
||||
|
||||
### 7. [F] Кнопка «✓ Утвердить» смету — косметика, ничего не сохраняет
|
||||
- `static/chat.html:1452-1462` — ставит бейдж/лочит инпуты только в DOM, ни одного запроса. Перезагрузка → утверждение исчезло. Функция врёт пользователю (сильнее, чем `prompt()`).
|
||||
- Fix: POST флага approved на бэкенд + рендер из данных.
|
||||
|
||||
### 8. [F] Плавающий CDN `marked` без версии и SRI
|
||||
- `static/chat.html:367` — `marked.min.js` без пина/`integrity` (соседние dompurify/tus закреплены+подписаны). Подмена CDN = чужой JS на странице с токенами; в корп-сетях РФ jsdelivr часто заблокирован → форматирование молча в plain-text.
|
||||
- Fix: пин версии + SRI, лучше self-host всех трёх.
|
||||
|
||||
---
|
||||
|
||||
## СТОИТ ПОЧИНИТЬ («класс prompt()» — ленивое/диалоговое/выдуманные причины)
|
||||
|
||||
- [F] `alert()`/`confirm()` в живом чате и админке: `chat.html:847,849` (ошибка даты — рядом ГОТОВ `#date-warn`!), `chat.html:1733` (удаление диалога), `admin.html:251,254,362`. → inline/свой мини-диалог (образец date-popover уже есть).
|
||||
- [F] Регистрация без `<form>` (`register.html:53-73`): Enter не работает, нет `autocomplete=new-password`/`one-time-code`, код `type=text` без `inputmode=numeric`. Первое, что видит новый юзер. Логин в `chat.html:278` сделан правильно — контраст.
|
||||
- [F] Сырые/выдуманные причины ошибок: `chat.html:752,759` любой сбой→«Неверный логин или пароль» (500/429 маскируются); `error_mask.py:29-33` «мы уже получили уведомление» — а активного алерта оператору нет (`send_operator_digest` не зовётся).
|
||||
- [F] Тихие проглоты сбоя: `main.py:485-530` разрыв соединения (GeneratorExit) → готовый ответ не сохранён в историю (сохранять в `finally`); `archive_host.py:140-177` битый том → юзеру ни слова, ждёт файлы; `main.py:540-556` битая панель молча выброшена; `main.py:685-686` DELETE диалога `except: pass` вокруг файлов, но `ok:true`.
|
||||
- [F] `chat.html:708,1010` — `atob()` на base64url JWT тихо бросает → «Админ»-кнопка и авто-refresh токена работают через раз. → нормализовать base64url.
|
||||
- [F] `chat.html:996-999` — удаление вложения кликабельным `<span>×` (не кнопка, нет клавиатуры/aria, таргет ~10px). → `<button aria-label>`.
|
||||
- [F] `chat.html:1106-1117` — legacy-фолбэк загрузки (когда tus-CDN недоступен = корп-сети) молча теряет неуспешные файлы. → показывать failed как в основном пути.
|
||||
- [F] `static/security.html:124,134` — «файлы не загружаются (справочный режим)», а чат берёт до 3 ГБ — текст противоречит продукту.
|
||||
- [F] `chat.html:1262-1266` — стрим ре-рендерит весь `innerHTML` на каждый чанк: O(n²), уничтожает выделение (нельзя копировать печатающийся ответ). → троттлинг/инкрементальный append.
|
||||
- [F] `chat.html:1253` — `JSON.parse` SSE без try/catch: одна битая строка роняет весь цикл в «Нет связи».
|
||||
|
||||
---
|
||||
|
||||
## МЕЛОЧИ / ДОЛГИ
|
||||
|
||||
- [F] Валидация → 500 вместо 400: `main.py:1667` `float(winter_pct)`, `main.py:1151-1162` `int(limit=abc)` без верхнего капа, `main.py:696,729` `assert isinstance` (исчезает под `-O`), `/api/recalc` лишний ключ → pydantic 500. Pydantic-модели не используются, везде ручной `body.get`.
|
||||
- [F] Копипаста разошедшихся близнецов: `main.py:59-126` inline-роутинг УЖЕ разошёлся с `routing.py:13-32` (нет .xlsm/фото/«извлеки»); мёртвый `batch.py` (свой `read_xlsx_xml` без cp866-фолбэка — а это был инцидент; + `exec`); дубли `get_work_dir`/`ALLOWED_EXTENSIONS`/`DATA_DIR` (×9) по мостам; `tools_glm.py` полумёртв; `claude_bridge._sessions/get_session_id` мёртв после отказа от `--resume`.
|
||||
- [F] Кэши без инвалидации: `main.py:305,359-367` `_DATA_PERIODS_CACHE` навсегда (data-version врёт до рестарта); `ADMIN_HTML_VERSION="20260602b"` (`main.py:1435`) не бампался с июня — правки admin.html не пробьют кэш (тот самый инцидент, ради которого схему строили).
|
||||
- [F] Таймзоны в трёх правдах: `main.py:1176` магический `'+10 hours'` в admin-stats; бизнес-дата `Europe/Moscow` (`claude_bridge_glm.py:80-87`); БД — unix UTC. → одна константа бизнес-TZ.
|
||||
- [F] In-memory состояние (`batch_v3.py:48`, `main.py:1635` `_ssr_jobs`, `_chat_rate`, `auth.py:35` `_login_attempts` — ключи не чистятся, утечка) теряется на рестарте/при >1 воркере → «Job not found» без объяснения.
|
||||
- [F] `claude_bridge.py:334-339` — `stderr=PIPE` докер-агента не дренируется: >64КБ в stderr → deadlock до дедлайна; в sonnet/batch stderr=DEVNULL → причина сбоя теряется.
|
||||
- [F] `claude_bridge.py:270-282` — докер-«песочница» с `--network=host` + rw-монт `~/.claude` (curl из Bash через host-network остаётся). → bridge-сеть + ro-креды.
|
||||
- [F] Доступность/адаптив: `<label>` нигде не связаны с полями (register/generate/wizard/ssr); `admin.html` без адаптива (сайдбар 220px, таблицы без overflow), тач-таргеты <40px, тема через `<a href=#>`; `chat.html:360` file-input без `accept`; date-popover без focus-trap/aria-modal; `reference.html:82` поиск без AbortController (гонка ответов); ссылка «О безопасности» opacity .4 ~8px (ниже AA).
|
||||
- [F] `main.py:192` deprecated `@app.on_event("startup")` → lifespan; `main.py:778-790` /api/upload собирает 100МБ в RAM → стримить в temp через `to_thread`.
|
||||
- [F] Депрекированные страницы (batch*/wizard/generate/reference/check) раздаются, но полуживые: двойной сабмит, blob-скачивания (запрещено памятью «большие файлы нативно»), часть без auth, без темы. Дешевле закрыть роуты заглушкой «переехало в чат», чем чинить 8 UI.
|
||||
|
||||
---
|
||||
|
||||
## Порядок работ (предложение)
|
||||
1. Traversal `tab_id` (fix ~10 строк, паттерн есть) + auth-дыры пакетом (ownership + auth на download/check + fail-loud SESSION_SECRET).
|
||||
2. `exec` batch_v3 → в контейнер; `batch.py` удалить.
|
||||
3. XSS admin (`esc()`) + пин `marked`+SRI.
|
||||
4. Синхронщина → `to_thread` (db-middleware, стрим, сбор контекста, SMTP) + кэш gesn_extra.
|
||||
5. «Утвердить» смету → на сервер; alert/confirm → inline; PBKDF2; blocked-проверка при refresh.
|
||||
Дальше — «стоит починить» и долги по мере сил.
|
||||
|
||||
NB: всё это ПРЕ-существующие вещи, не регресс этой сессии. Каждый фикс — surgical, отдельно, с прогоном тестов; после блока — Fable-верификация ([[feedback_final_fable_review]]).
|
||||
@@ -2,13 +2,16 @@
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi import FastAPI, HTTPException, Request, UploadFile
|
||||
logger = logging.getLogger("smeta_web")
|
||||
|
||||
from fastapi import Depends, FastAPI, HTTPException, Request, UploadFile
|
||||
from fastapi.responses import FileResponse, HTMLResponse, JSONResponse, StreamingResponse
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
|
||||
@@ -133,12 +136,20 @@ else:
|
||||
app = FastAPI(title="smeta-web")
|
||||
app.mount("/static", StaticFiles(directory="static"), name="static")
|
||||
|
||||
from path_safety import UnsafePath
|
||||
|
||||
|
||||
@app.exception_handler(UnsafePath)
|
||||
async def _unsafe_path_handler(request: Request, exc: UnsafePath):
|
||||
# client-controlled tab_id/username пытался выйти из папки → чистый 400 без утечки
|
||||
return JSONResponse({"detail": "Некорректный идентификатор сессии"}, status_code=400)
|
||||
|
||||
MAX_UPLOAD_SIZE = 100 * 1024 * 1024 # 100 MB
|
||||
MAX_MESSAGE_LEN = 10_000
|
||||
|
||||
# ⚠️ Версия UI — единый источник. БАМПАТЬ ПРИ КАЖДОМ ДЕПЛОЕ (формат: YYYY-MM-DD + буква).
|
||||
# Фронт берёт её через GET /api/version (chat.html + admin.html, элемент .app-version).
|
||||
APP_VERSION = "2026-07-18f"
|
||||
APP_VERSION = "2026-07-18h"
|
||||
|
||||
# Audit: path → action name mapping
|
||||
_AUDIT_MAP = [
|
||||
@@ -191,6 +202,11 @@ def _resolve_action(method: str, path: str) -> str | None:
|
||||
|
||||
@app.on_event("startup")
|
||||
async def startup():
|
||||
# fail-loud: без секрета JWT-логин молча ломается, а download-ticket подписывается
|
||||
# пустым ключом (подделываемо). Лучше не стартовать, чем работать «тихо небезопасно».
|
||||
import auth
|
||||
if not auth.SECRET:
|
||||
raise RuntimeError("SESSION_SECRET не задан — отказ запуска (см. .env)")
|
||||
init_db()
|
||||
# Прогрев справочника ФГИС в фоне: системный промпт агента берёт квартал/регионы из диск-кэша
|
||||
# БЕЗ сетевого вызова в async-пути (иначе первый чат заморозил бы весь сервер до таймаута сети).
|
||||
@@ -272,6 +288,20 @@ def _get_tab(request: Request, body: dict | None = None) -> str:
|
||||
return request.headers.get("x-tab-id", "default")
|
||||
|
||||
|
||||
def _auth_dep(request: Request):
|
||||
"""FastAPI-зависимость: требует валидный токен (для include_router-гейта)."""
|
||||
_get_user(request)
|
||||
|
||||
|
||||
def _require_job_owner(job: dict | None, user: str) -> dict:
|
||||
"""Job принадлежит этому юзеру? Иначе 404 (не 403 — не палим существование
|
||||
чужого job_id). Раньше batch/SSR-эндпоинты проверяли только факт логина, но не
|
||||
владельца → любой залогиненный по угаданному id тянул чужую смету (Fable audit)."""
|
||||
if not job or job.get("user") != user:
|
||||
raise HTTPException(404, "Job not found")
|
||||
return job
|
||||
|
||||
|
||||
@app.get("/", response_class=HTMLResponse)
|
||||
async def index(request: Request):
|
||||
# Кэш-бастинг главной (как /admin): без актуального ?v= → 302 на URL с v=APP_VERSION
|
||||
@@ -934,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
|
||||
@@ -953,178 +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["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."""
|
||||
_get_user(request)
|
||||
job = batch_v3.get_job(job_id)
|
||||
if not job:
|
||||
raise HTTPException(404, "Job not found")
|
||||
|
||||
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."""
|
||||
_get_user(request)
|
||||
job = batch_v3.get_job(job_id)
|
||||
if not job:
|
||||
raise HTTPException(404, "Job not found")
|
||||
|
||||
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):
|
||||
_get_user(request)
|
||||
job = batch_v3.get_job(job_id)
|
||||
if not job:
|
||||
raise HTTPException(404, "Job not found")
|
||||
|
||||
# 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):
|
||||
_get_user(request)
|
||||
job = batch_v3.get_job(job_id)
|
||||
if not job or 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 ===
|
||||
|
||||
|
||||
@@ -1432,7 +1282,7 @@ async def admin_download_file_endpoint(request: Request):
|
||||
return FileResponse(fpath, filename=safe_name, headers={"Referrer-Policy": "no-referrer"})
|
||||
|
||||
|
||||
ADMIN_HTML_VERSION = "20260602b"
|
||||
ADMIN_HTML_VERSION = "20260718a"
|
||||
|
||||
|
||||
@app.get("/admin", response_class=HTMLResponse)
|
||||
@@ -1459,174 +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["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."""
|
||||
_get_user(request)
|
||||
job = batch_v3.get_job(job_id)
|
||||
if not job:
|
||||
raise HTTPException(404, "Job not found")
|
||||
|
||||
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):
|
||||
_get_user(request)
|
||||
job = batch_v3.get_job(job_id)
|
||||
if not job:
|
||||
raise HTTPException(404, "Job not found")
|
||||
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):
|
||||
_get_user(request)
|
||||
job = batch_v3.get_job(job_id)
|
||||
if not job:
|
||||
raise HTTPException(404, "Job not found")
|
||||
|
||||
# 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):
|
||||
_get_user(request)
|
||||
job = batch_v3.get_job(job_id)
|
||||
if not job or not job.get("output_file"):
|
||||
raise HTTPException(404, "Result not ready")
|
||||
return FileResponse(job["output_file"], filename=Path(job["output_file"]).name)
|
||||
|
||||
|
||||
# ── SSR Generator ───────────────────────────────────────────────────────────
|
||||
@@ -1635,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
|
||||
@@ -1651,117 +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):
|
||||
_get_user(request)
|
||||
job = _ssr_jobs.get(job_id)
|
||||
if not job:
|
||||
raise HTTPException(404, "Job not found")
|
||||
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):
|
||||
_get_user(request)
|
||||
job = _ssr_jobs.get(job_id)
|
||||
if not job:
|
||||
raise HTTPException(404, "Job not found")
|
||||
return FileResponse(job["xlsx_path"], filename="ssr_generated.xlsx")
|
||||
|
||||
|
||||
# ── Wizard Aggregator ──────────────────────────────────────────────────────
|
||||
|
||||
def _import_smeta_railway():
|
||||
@@ -1777,158 +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
|
||||
|
||||
app.include_router(_wizard_router, prefix="/api/wizard")
|
||||
app.include_router(_gen_router, prefix="/api/gen")
|
||||
app.include_router(_chat_sr_router, prefix="/api/ref") # /api/ref/search, /api/ref/nr, /api/ref/sp
|
||||
|
||||
|
||||
@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")
|
||||
# Смонтированные роутеры не имели auth вообще → аноним жёг LLM/RAG-бюджет и грузил
|
||||
# файлы (Fable verify). Гейт на уровне монтирования — БЕЗ правки чужого пакета smeta_railway.
|
||||
# Живой чат их не использует (только депрекированные generate/reference/wizard).
|
||||
|
||||
|
||||
# ── 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
|
||||
|
||||
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:
|
||||
return {"error": str(exc), "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."""
|
||||
# ⛔ Путь 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):
|
||||
"""Download generated Excel estimate."""
|
||||
data_dir = Path(os.environ.get("DATA_DIR", "./smeta-web-data")) / "_estimates"
|
||||
xlsx_path = data_dir / f"estimate_{job_id}.xlsx"
|
||||
if not xlsx_path.exists():
|
||||
raise HTTPException(404, "Файл не найден")
|
||||
return FileResponse(str(xlsx_path), filename=f"smeta_{job_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")))
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
"""Единая защита work_dir от path-traversal.
|
||||
|
||||
username(email) и tab_id ОБА приходят от клиента (заголовок x-tab-id / path-param).
|
||||
Раньше get_work_dir в мостах клеил DATA_DIR/username/tab_id без проверки → заголовок
|
||||
`x-tab-id: ../..` читал (GET /api/files) и УДАЛЯЛ (POST /api/clear-files, rmtree)
|
||||
файлы вне папки пользователя. tus (`_safe_tab`) и admin-download уже защищены
|
||||
точечно — здесь единая точка для остального (Fable audit 2026-07-18).
|
||||
|
||||
Принцип: НЕ переписываем символы (иначе путь разойдётся с уже созданными каталогами
|
||||
существующих юзеров и их файлы «исчезнут») — а проверяем, что итог лежит СТРОГО внутри
|
||||
каталога данного пользователя. Легальные значения (email без '/', tab_id=UUID)
|
||||
проходят байт-в-байт; traversal и выход в чужую папку → UnsafePath (ValueError).
|
||||
"""
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
class UnsafePath(ValueError):
|
||||
"""Попытка выйти за пределы каталога пользователя (traversal / чужая папка)."""
|
||||
|
||||
|
||||
def _data_root() -> Path:
|
||||
return Path(os.environ.get("DATA_DIR", "./smeta-web-data")).resolve()
|
||||
|
||||
|
||||
def safe_work_dir(username: str, tab_id: str, *, create: bool = True) -> Path:
|
||||
"""DATA_DIR/username/tab_id с гарантией, что путь не вышел из папки пользователя."""
|
||||
root = _data_root()
|
||||
username = (username or "").strip()
|
||||
tab_id = (tab_id or "").strip() or "default"
|
||||
if "\x00" in username or "\x00" in tab_id: # null-byte → .resolve() бросил бы 500
|
||||
raise UnsafePath("null byte in component")
|
||||
try:
|
||||
user_dir = (root / username).resolve()
|
||||
d = (user_dir / tab_id).resolve()
|
||||
except ValueError as e: # прочие невалидные пути в .resolve() → 400
|
||||
raise UnsafePath(str(e))
|
||||
# username обязан быть ОДНИМ чистым компонентом: иначе 'zzz/../victim@x'
|
||||
# резолвится в чужую папку victim@x, у которой parent тоже == root (Fable).
|
||||
if user_dir.parent != root or user_dir.name != username:
|
||||
raise UnsafePath("bad username component")
|
||||
if d != user_dir and user_dir not in d.parents: # tab_id вышел из папки юзера
|
||||
raise UnsafePath("bad tab_id component")
|
||||
if create:
|
||||
d.mkdir(parents=True, exist_ok=True)
|
||||
return d
|
||||
+44
-17
@@ -118,34 +118,61 @@ def _search_fssc(query: str, top_k: int = 5) -> str:
|
||||
|
||||
# === ГЭСН extra (181K norms) ===
|
||||
|
||||
def _search_gesn_extra(query: str, top_k: int = 5) -> str:
|
||||
"""Search in full 181K GESN norms (gesn_extra JSON files)."""
|
||||
_gesn_extra_cache: list[tuple[str, str, str, str]] = [] # (code, name, name_lower, unit)
|
||||
_gesn_extra_sig: tuple = () # (имя, mtime_ns, size)* — инвалидация
|
||||
|
||||
|
||||
def _gesn_extra_index() -> list[tuple[str, str, str, str]]:
|
||||
"""Предпарсенный индекс полной базы ГЭСН с кэшем по mtime/size файлов.
|
||||
|
||||
Раньше _search_gesn_extra на КАЖДЫЙ запрос заново json.loads-ил все gesn_*.json
|
||||
(181K норм, секунды блокировки event loop на сообщение — Fable audit). Теперь
|
||||
диск читается только когда набор файлов изменился (напр. после pull-обновления)."""
|
||||
global _gesn_extra_cache, _gesn_extra_sig
|
||||
gesn_dir = SMETA_DIR / "data" / "gesn_extra"
|
||||
if not gesn_dir.exists():
|
||||
return ""
|
||||
|
||||
query_lower = query.lower()
|
||||
terms = [_normalize(t) for t in query_lower.split() if len(t) > 2]
|
||||
results = []
|
||||
|
||||
for f in gesn_dir.glob("gesn_*.json"):
|
||||
data = json.loads(f.read_text(encoding="utf-8"))
|
||||
return []
|
||||
files = sorted(gesn_dir.glob("gesn_*.json"))
|
||||
sig = tuple((f.name, f.stat().st_mtime_ns, f.stat().st_size) for f in files)
|
||||
if sig == _gesn_extra_sig and _gesn_extra_cache:
|
||||
return _gesn_extra_cache
|
||||
index: list[tuple[str, str, str, str]] = []
|
||||
for f in files:
|
||||
try:
|
||||
data = json.loads(f.read_text(encoding="utf-8"))
|
||||
except Exception: # noqa: BLE001 — битый файл не должен ронять весь поиск
|
||||
continue
|
||||
for code, info in data.items():
|
||||
if not isinstance(info, dict) or "error" in info:
|
||||
continue
|
||||
name = info.get("name", "").lower()
|
||||
score = sum(1 for t in terms if t in name)
|
||||
if score >= 2 or (score == 1 and len(terms) == 1):
|
||||
results.append((score, code, info))
|
||||
name = info.get("name", "")
|
||||
index.append((code, name, name.lower(), info.get("unit", "")))
|
||||
_gesn_extra_cache = index
|
||||
_gesn_extra_sig = sig
|
||||
return index
|
||||
|
||||
|
||||
def _search_gesn_extra(query: str, top_k: int = 5) -> str:
|
||||
"""Search in full 181K GESN norms (gesn_extra JSON files)."""
|
||||
index = _gesn_extra_index()
|
||||
if not index:
|
||||
return ""
|
||||
|
||||
terms = [_normalize(t) for t in query.lower().split() if len(t) > 2]
|
||||
if not terms:
|
||||
return ""
|
||||
results = []
|
||||
for code, name, name_lower, unit in index:
|
||||
score = sum(1 for t in terms if t in name_lower)
|
||||
if score >= 2 or (score == 1 and len(terms) == 1):
|
||||
results.append((score, code, name, unit))
|
||||
|
||||
results.sort(reverse=True, key=lambda x: x[0])
|
||||
if not results:
|
||||
return ""
|
||||
|
||||
lines = ["Расценки из полной базы ГЭСН (181 000+ норм):"]
|
||||
for score, code, info in results[:top_k]:
|
||||
name = info.get("name", "")
|
||||
unit = info.get("unit", "")
|
||||
for score, code, name, unit in results[:top_k]:
|
||||
lines.append(f"- ГЭСН {code}: {name} [{unit}]")
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
+13
-10
@@ -263,14 +263,17 @@ function loadUsers() {
|
||||
const tr = document.createElement('tr');
|
||||
const status = u.blocked ? '<span style="color:var(--accent)">Заблокирован</span>' : (u.verified ? '<span style="color:var(--green)">Активен</span>' : '<span style="color:var(--muted)">Не подтверждён</span>');
|
||||
const ts = d.toLocaleString('ru-RU',{day:'2-digit',month:'2-digit',hour:'2-digit',minute:'2-digit'});
|
||||
let actions = '';
|
||||
const btn = (label, fn) => '<button class="btn-sm" onclick="'+fn+'">'+label+'</button>';
|
||||
if (u.blocked) actions += btn('Разблокировать', "userAction('block','"+u.email+"',{blocked:false})");
|
||||
else actions += btn('Заблокировать', "userAction('block','"+u.email+"',{blocked:true})");
|
||||
if (!u.verified) actions += btn('Подтвердить', "userAction('verify','"+u.email+"')");
|
||||
actions += btn(u.role==='admin'?'Сделать user':'Сделать admin', "userAction('role','"+u.email+"',{role:'"+(u.role==='admin'?'user':'admin')+"'})");
|
||||
actions += btn('Удалить', "userAction('delete','"+u.email+"')");
|
||||
tr.innerHTML = '<td>'+u.email+'</td><td>'+u.role+'</td><td>'+status+'</td><td class="time">'+ts+'</td><td>'+actions+'</td>';
|
||||
// email/role экранируем (email задаёт сам юзер → был stored-XSS); status — из фикс-строк.
|
||||
tr.innerHTML = '<td>'+esc(u.email)+'</td><td>'+esc(u.role)+'</td><td>'+status+'</td><td class="time">'+ts+'</td>';
|
||||
const actionsTd = document.createElement('td');
|
||||
// обработчики — замыкания (email как ДАННЫЕ, не как код в inline-onclick: апостроф/тег ломал/инжектил)
|
||||
const addBtn = (label, fn) => { const b = document.createElement('button'); b.className='btn-sm'; b.textContent=label; b.onclick=fn; actionsTd.appendChild(b); };
|
||||
if (u.blocked) addBtn('Разблокировать', () => userAction('block', u.email, {blocked:false}));
|
||||
else addBtn('Заблокировать', () => userAction('block', u.email, {blocked:true}));
|
||||
if (!u.verified) addBtn('Подтвердить', () => userAction('verify', u.email));
|
||||
addBtn(u.role==='admin'?'Сделать user':'Сделать admin', () => userAction('role', u.email, {role: u.role==='admin'?'user':'admin'}));
|
||||
addBtn('Удалить', () => userAction('delete', u.email));
|
||||
tr.appendChild(actionsTd);
|
||||
t.appendChild(tr);
|
||||
}
|
||||
}).catch(()=>{});
|
||||
@@ -431,8 +434,8 @@ async function loadAudit(offset) {
|
||||
const uSel = document.getElementById('audit-user');
|
||||
const aSel = document.getElementById('audit-action');
|
||||
const curU = uSel.value, curA = aSel.value;
|
||||
uSel.innerHTML = '<option value="">Все пользователи</option>' + users.map(u=>`<option value="${u}">${u}</option>`).join('');
|
||||
aSel.innerHTML = '<option value="">Все действия</option>' + actions.map(a=>`<option value="${a}">${a}</option>`).join('');
|
||||
uSel.innerHTML = '<option value="">Все пользователи</option>' + users.map(u=>`<option value="${esc(u)}">${esc(u)}</option>`).join('');
|
||||
aSel.innerHTML = '<option value="">Все действия</option>' + actions.map(a=>`<option value="${esc(a)}">${esc(a)}</option>`).join('');
|
||||
uSel.value = curU; aSel.value = curA;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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>
|
||||
+21
-6
@@ -364,7 +364,7 @@ html { color-scheme: light; }
|
||||
</div><!-- /.app-layout -->
|
||||
</div>
|
||||
|
||||
<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
|
||||
<script src="https://cdn.jsdelivr.net/npm/marked@14.1.4/marked.min.js" integrity="sha384-lqPzN0kmFw9t2syAMwVPM4VbAyqsz/lPyYWbb2Xt6nSPM0WPNrpSWCUBgdcAdgnC" crossorigin="anonymous"></script>
|
||||
<script src="https://cdn.jsdelivr.net/npm/dompurify@3.1.7/dist/purify.min.js" integrity="sha384-XQqX/4yiUGu+oyr87jvWzRuqBUK/adrY0DunhL+tID9m/9dwSpV8h9Fk/Sg6ifVQ" crossorigin="anonymous"></script>
|
||||
<script src="https://cdn.jsdelivr.net/npm/tus-js-client@4.3.1/dist/tus.min.js" integrity="sha384-UlHjK3F7TCQCEUpnoa1ohMbP2oaWB3Aypv4gMo511vaZ86uUZ0Zv7UzZ0J1zRUT1" crossorigin="anonymous"></script>
|
||||
<script>
|
||||
@@ -863,17 +863,31 @@ async function authFetch(url, opts={}) {
|
||||
|
||||
// --- Messages ---
|
||||
const msgs = document.getElementById('messages');
|
||||
// Умный автоскролл: скроллим к низу только если пользователь уже «у дна» (иначе
|
||||
// он читает выше — не дёргаем). Кнопка «↓» возвращает вниз.
|
||||
// Умный автоскролл: «прилипаем» к низу, пока пользователь сам не прокрутит вверх.
|
||||
// Решение «следить за низом?» принимает ТОЛЬКО скролл пользователя (флаг stickToBottom),
|
||||
// а НЕ замер после вставки — иначе крупное сообщение/чанк ответа сразу «отклеивает»
|
||||
// (высота ушла за порог 80px) и приходится скроллить руками. Кнопка «↓» возвращает
|
||||
// вниз и снова включает прилипание.
|
||||
let stickToBottom = true;
|
||||
function isPinned() { return msgs.scrollHeight - msgs.scrollTop - msgs.clientHeight < 80; }
|
||||
function scrollIfPinned() { if (isPinned()) { msgs.scrollTop = msgs.scrollHeight; } else { jumpBtn.style.display = 'flex'; } }
|
||||
function scrollToBottom() { msgs.scrollTop = msgs.scrollHeight; }
|
||||
function scrollIfPinned() {
|
||||
if (stickToBottom) { scrollToBottom(); jumpBtn.style.display = 'none'; }
|
||||
else { jumpBtn.style.display = 'flex'; }
|
||||
}
|
||||
const jumpBtn = document.createElement('button');
|
||||
jumpBtn.className = 'jump-latest'; jumpBtn.textContent = '↓';
|
||||
jumpBtn.title = 'К последнему'; jumpBtn.setAttribute('aria-label', 'К последнему сообщению');
|
||||
jumpBtn.style.display = 'none';
|
||||
jumpBtn.onclick = () => { msgs.scrollTop = msgs.scrollHeight; jumpBtn.style.display = 'none'; };
|
||||
jumpBtn.onclick = () => { stickToBottom = true; scrollToBottom(); jumpBtn.style.display = 'none'; };
|
||||
document.body.appendChild(jumpBtn);
|
||||
msgs.addEventListener('scroll', () => { jumpBtn.style.display = isPinned() ? 'none' : 'flex'; });
|
||||
// Пользователь — хозяин прилипания: ушёл вверх читать → отлипаем и показываем «↓»,
|
||||
// вернулся к низу → снова прилипаем. Наш программный scrollToBottom тоже триггерит
|
||||
// это событие, но там isPinned()===true, так что флаг остаётся включённым.
|
||||
msgs.addEventListener('scroll', () => {
|
||||
stickToBottom = isPinned();
|
||||
jumpBtn.style.display = stickToBottom ? 'none' : 'flex';
|
||||
});
|
||||
|
||||
// Онбординг (срез 1.2): приветствие + примеры-подсказки на пустом чате.
|
||||
// Клик по подсказке подставляет её в поле ввода. Убирается при первом сообщении.
|
||||
@@ -1204,6 +1218,7 @@ async function sendMessage() {
|
||||
}
|
||||
}
|
||||
|
||||
stickToBottom = true; // явная отправка = хочу видеть своё сообщение и ответ — прилипаем к низу
|
||||
addMsg('user', text);
|
||||
input.value = '';
|
||||
input.style.height = 'auto';
|
||||
|
||||
@@ -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>
|
||||
@@ -0,0 +1,81 @@
|
||||
"""Block ① безопасности (Fable audit 2026-07-18): path-traversal через x-tab-id,
|
||||
анонимные compute/download-эндпоинты, владелец job'а.
|
||||
|
||||
Mutation-честность:
|
||||
- убери guard в get_work_dir → traversal-тесты пройдут МИМО (файл-часовой удалён / прочитан).
|
||||
- верни `_get_user` без ownership → foreign-job тест перестанет давать 404.
|
||||
"""
|
||||
import importlib
|
||||
import os
|
||||
import sys
|
||||
|
||||
import pytest
|
||||
|
||||
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
if ROOT not in sys.path:
|
||||
sys.path.insert(0, ROOT)
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def env(tmp_path, monkeypatch):
|
||||
monkeypatch.setenv("DB_PATH", str(tmp_path / "t.db"))
|
||||
monkeypatch.setenv("DATA_DIR", str(tmp_path / "data"))
|
||||
monkeypatch.setenv("AI_BACKEND", "claude")
|
||||
monkeypatch.setenv("SESSION_SECRET", "test-secret")
|
||||
monkeypatch.chdir(ROOT)
|
||||
import auth, claude_bridge, db, main, path_safety
|
||||
for m in (path_safety, db, auth, claude_bridge, main):
|
||||
importlib.reload(m)
|
||||
db.init_db()
|
||||
from fastapi.testclient import TestClient
|
||||
return auth, main, TestClient(main.app), tmp_path
|
||||
|
||||
|
||||
def _h(auth, user="mallory@x", role="user", tab="tab-1"):
|
||||
return {"Authorization": "Bearer " + auth._make_token(user, role), "X-Tab-Id": tab}
|
||||
|
||||
|
||||
# ---- path traversal через заголовок вкладки ----
|
||||
|
||||
def test_traversal_read_blocked(env):
|
||||
auth, main, client, tmp = env
|
||||
h = _h(auth, tab="../../../../etc")
|
||||
r = client.get("/api/files/passwd", headers=h)
|
||||
assert r.status_code == 400 # UnsafePath → чистый 400, не 200 с /etc/passwd
|
||||
|
||||
|
||||
def test_traversal_delete_does_not_wipe_outside(env):
|
||||
auth, main, client, tmp = env
|
||||
sentinel = tmp / "sentinel.txt" # лежит ВЫШЕ DATA_DIR (tmp/data)
|
||||
sentinel.write_text("keep me")
|
||||
r = client.post("/api/clear-files", headers=_h(auth, tab="../.."))
|
||||
assert r.status_code == 400
|
||||
assert sentinel.exists() # без guard clear-files снёс бы этот файл
|
||||
|
||||
|
||||
def test_legit_tab_still_works(env):
|
||||
auth, main, client, tmp = env
|
||||
# обычный tab_id (не traversal) — 200 и пустой список, не 400
|
||||
r = client.get("/api/files", headers=_h(auth, tab="normal-uuid-1234"))
|
||||
assert r.status_code == 200
|
||||
assert r.json() == []
|
||||
|
||||
|
||||
# ---- депрекированный пакетный путь убран целиком (exec на хосте + анонимные роуты) ----
|
||||
|
||||
def test_deprecated_pages_redirect(env):
|
||||
_auth, _main, client, _tmp = env
|
||||
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_deprecated_api_endpoints_gone(env):
|
||||
_auth, _main, client, _tmp = env
|
||||
# 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} всё ещё жив"
|
||||
@@ -0,0 +1,82 @@
|
||||
"""Path-traversal guard для work_dir (Fable audit 2026-07-18, P0 #1).
|
||||
|
||||
Легальные значения (email, tab_id=UUID) проходят байт-в-байт — иначе файлы
|
||||
существующих юзеров «исчезнут». Traversal и выход в чужую папку → UnsafePath.
|
||||
Mutation-честность: уберёшь containment-проверку → traversal-тесты станут зелёными
|
||||
на пути ВНЕ папки, то есть эти тесты реально падают без защиты.
|
||||
"""
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def _root(monkeypatch, tmp_path):
|
||||
monkeypatch.setenv("DATA_DIR", str(tmp_path))
|
||||
import importlib
|
||||
import path_safety as ps
|
||||
importlib.reload(ps)
|
||||
return ps, tmp_path.resolve()
|
||||
|
||||
|
||||
def test_legit_path_unchanged_and_created(_root):
|
||||
ps, root = _root
|
||||
d = ps.safe_work_dir("user@example.com", "550e8400-e29b-41d4-a716-446655440000")
|
||||
assert d == root / "user@example.com" / "550e8400-e29b-41d4-a716-446655440000"
|
||||
assert d.is_dir() # create=True
|
||||
|
||||
|
||||
def test_email_with_plus_preserved(_root):
|
||||
ps, root = _root
|
||||
d = ps.safe_work_dir("user+tag@x.com", "tab1", create=False)
|
||||
assert d == root / "user+tag@x.com" / "tab1" # символы НЕ переписаны
|
||||
|
||||
|
||||
def test_traversal_tab_id_rejected(_root):
|
||||
ps, _ = _root
|
||||
with pytest.raises(ps.UnsafePath):
|
||||
ps.safe_work_dir("user@x.com", "../..")
|
||||
|
||||
|
||||
def test_cross_user_tab_id_rejected(_root):
|
||||
ps, _ = _root
|
||||
with pytest.raises(ps.UnsafePath):
|
||||
ps.safe_work_dir("user@x.com", "../victim@x.com/tab")
|
||||
|
||||
|
||||
def test_absolute_tab_id_rejected(_root):
|
||||
ps, _ = _root
|
||||
with pytest.raises(ps.UnsafePath):
|
||||
ps.safe_work_dir("user@x.com", "/etc")
|
||||
|
||||
|
||||
def test_traversal_username_rejected(_root):
|
||||
ps, _ = _root
|
||||
with pytest.raises(ps.UnsafePath):
|
||||
ps.safe_work_dir("../../../etc", "passwd")
|
||||
|
||||
|
||||
def test_username_dotdot_collision_rejected(_root):
|
||||
"""Fable: 'zzz/../victim@x.com' резолвится в чужую папку victim@x.com
|
||||
(parent тоже == root) — должно отвергаться (username = один компонент)."""
|
||||
ps, _ = _root
|
||||
with pytest.raises(ps.UnsafePath):
|
||||
ps.safe_work_dir("zzz/../victim@x.com", "tab1")
|
||||
|
||||
|
||||
def test_null_byte_gives_unsafepath_not_500(_root):
|
||||
"""Fable: null-byte в tab_id из JSON-body → .resolve() бросал ValueError → 500.
|
||||
Теперь ловится как UnsafePath (обработчик → чистый 400)."""
|
||||
ps, _ = _root
|
||||
with pytest.raises(ps.UnsafePath):
|
||||
ps.safe_work_dir("user@x.com", "tab\x00evil")
|
||||
|
||||
|
||||
def test_nested_tab_stays_inside_user(_root):
|
||||
"""tab_id с одиночным '/' (без '..') остаётся внутри папки юзера — не reject."""
|
||||
ps, root = _root
|
||||
d = ps.safe_work_dir("user@x.com", "sub/inner", create=False)
|
||||
assert root / "user@x.com" in d.parents # всё ещё под своим каталогом
|
||||
Reference in New Issue
Block a user