fix(security): блок ② — убран депрекированный пакетный путь (exec на хосте)
По решению пользователя вместо песочницы — retire всего депрекированного пакетного пути (страницы давно заменены чатом). Устраняет P0: batch v2/v3 исполняли СГЕНЕРИРОВАННЫЙ ИИ по загруженной смете скрипт через exec() прямо в процессе сервера (prompt-injection в смете контрагента → доступ к .env/БД/файлам всех). - Удалены роуты: /api/batch-v2/*, /api/batch-v3/*, /api/ssr/*, /api/check/yaml, /api/gen/calculate, /api/gen/download + смонтированные /api/gen|ref|wizard. - Страницы /batch|batch2|batch3|ssr|wizard|generate|reference|check → 302 на /. - Удалены мёртвые модули batch.py (exec:393 + code-injection через имя листа) и batch_v3.py (три exec-точки), их HTML-страницы (заодно ушёл их XSS-surface). - get_work_dir/ownership-хелперы для batch больше не нужны, но оставлены (dead, безвредны) — точечная зачистка отдельно. Живой чат путь не затронут (batch_v3/extract_zip импортились только депрекированными эндпоинтами). Тесты: pages→302, api→404. 297 passed. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -1,157 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Пакетная обработка смет</title>
|
||||
<style>
|
||||
:root { --bg: #f5f0eb; --card: #fff; --text: #3a3a3a; --muted: #6b6b6b; --accent: #c4463a; --border: #d4c5b2; --radius: 10px; }
|
||||
* { box-sizing: border-box; margin: 0; padding: 0; }
|
||||
body { font-family: 'Inter', -apple-system, sans-serif; background: var(--bg); color: var(--text); min-height: 100vh; padding: 2rem; }
|
||||
.container { max-width: 700px; margin: 0 auto; }
|
||||
h1 { font-size: 1.3rem; margin-bottom: .3rem; }
|
||||
.subtitle { color: var(--muted); font-size: .9rem; margin-bottom: 1.5rem; }
|
||||
.card { background: var(--card); border-radius: var(--radius); padding: 1.5rem; margin-bottom: 1rem; box-shadow: 0 1px 4px rgba(0,0,0,.06); }
|
||||
label { display: block; font-weight: 600; margin-bottom: .4rem; font-size: .9rem; }
|
||||
.hint { color: var(--muted); font-size: .8rem; margin-bottom: .6rem; }
|
||||
input[type=file] { width: 100%; padding: .5rem; border: 1.5px dashed var(--border); border-radius: var(--radius); margin-bottom: 1rem; }
|
||||
textarea { width: 100%; padding: .6rem; border: 1.5px solid var(--border); border-radius: var(--radius); font-family: inherit; font-size: .9rem; resize: vertical; min-height: 60px; }
|
||||
button { padding: .7rem 1.5rem; background: var(--accent); color: #fff; border: none; border-radius: var(--radius); font-size: .95rem; font-weight: 600; cursor: pointer; }
|
||||
button:hover { background: #a83830; }
|
||||
button:disabled { background: var(--border); cursor: not-allowed; }
|
||||
.back { display: inline-block; margin-bottom: 1rem; color: var(--accent); text-decoration: none; font-size: .85rem; }
|
||||
#status { display: none; }
|
||||
#analysis { display: none; }
|
||||
.progress { background: #ede5db; border-radius: 6px; height: 8px; margin: .5rem 0; }
|
||||
.progress-bar { background: var(--accent); height: 100%; border-radius: 6px; transition: width .3s; }
|
||||
.error-list { color: #c4463a; font-size: .8rem; margin-top: .5rem; }
|
||||
pre { background: #2c2c2c; color: #f5f0eb; padding: .8rem; border-radius: 6px; overflow-x: auto; font-size: .8rem; margin: .5rem 0; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<a class="back" href="/">← Вернуться в чат</a>
|
||||
<h1>Пакетная обработка смет</h1>
|
||||
<p class="subtitle">Загрузите архив со сметами и сводный файл — ИИ проанализирует структуру и перенесёт данные</p>
|
||||
|
||||
<div class="card" id="upload-form">
|
||||
<label>Архив со сметами (.zip)</label>
|
||||
<p class="hint">Все файлы локальных смет в одном архиве</p>
|
||||
<input type="file" id="zip-file" accept=".zip">
|
||||
|
||||
<label>Сводный файл (.xlsx)</label>
|
||||
<p class="hint">Файл, в который нужно внести данные (ССР, ведомость и т.д.)</p>
|
||||
<input type="file" id="target-file" accept=".xlsx,.xls">
|
||||
|
||||
<label>Описание задачи</label>
|
||||
<textarea id="task-desc" placeholder="Например: Из каждой сметы взять итого строительных работ (тыс.руб.) и внести в соответствующую строку ССР"></textarea>
|
||||
<br><br>
|
||||
<button onclick="startBatch()">Анализировать</button>
|
||||
</div>
|
||||
|
||||
<div class="card" id="analysis">
|
||||
<h3>Результат анализа</h3>
|
||||
<p id="analysis-desc"></p>
|
||||
<details>
|
||||
<summary>Сгенерированный скрипт</summary>
|
||||
<pre id="analysis-script"></pre>
|
||||
</details>
|
||||
<p id="analysis-files" style="margin:.5rem 0;color:var(--muted);font-size:.85rem"></p>
|
||||
<button onclick="runBatch()">Запустить обработку</button>
|
||||
</div>
|
||||
|
||||
<div class="card" id="status">
|
||||
<h3>Обработка</h3>
|
||||
<p id="status-text"></p>
|
||||
<div class="progress"><div class="progress-bar" id="progress-bar" style="width:0%"></div></div>
|
||||
<p id="status-count" style="font-size:.85rem;color:var(--muted)"></p>
|
||||
<div class="error-list" id="error-list"></div>
|
||||
<button id="download-btn" style="display:none" onclick="downloadResult()">Скачать результат</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
const API = '';
|
||||
let token = localStorage.getItem('token');
|
||||
let jobId = null;
|
||||
|
||||
if (!token) { window.location.href = '/'; }
|
||||
|
||||
function authHeaders() { return {'Authorization': 'Bearer ' + token}; }
|
||||
|
||||
async function startBatch() {
|
||||
const zipFile = document.getElementById('zip-file').files[0];
|
||||
const targetFile = document.getElementById('target-file').files[0];
|
||||
const taskDesc = document.getElementById('task-desc').value;
|
||||
if (!zipFile || !targetFile) { alert('Загрузите оба файла'); return; }
|
||||
|
||||
const fd = new FormData();
|
||||
fd.append('zip_file', zipFile);
|
||||
fd.append('target_file', targetFile);
|
||||
fd.append('task_description', taskDesc || 'Перенести итоги из смет в сводный файл');
|
||||
|
||||
document.querySelector('#upload-form button').disabled = true;
|
||||
document.querySelector('#upload-form button').textContent = 'Анализирую...';
|
||||
|
||||
try {
|
||||
const r = await fetch(API + '/api/batch/upload', {method: 'POST', headers: authHeaders(), body: fd});
|
||||
if (r.status === 401) { window.location.href = '/'; return; }
|
||||
const data = await r.json();
|
||||
if (data.analysis?.error) { alert('Ошибка: ' + data.analysis.error); return; }
|
||||
|
||||
jobId = data.job_id;
|
||||
document.getElementById('analysis-desc').textContent = data.analysis.description || 'Анализ завершён';
|
||||
document.getElementById('analysis-script').textContent = data.analysis.python_script || '(нет скрипта)';
|
||||
document.getElementById('analysis-files').textContent = 'Файлов: ' + data.total_files;
|
||||
document.getElementById('analysis').style.display = 'block';
|
||||
} catch(e) { alert('Ошибка: ' + e.message); }
|
||||
finally {
|
||||
document.querySelector('#upload-form button').disabled = false;
|
||||
document.querySelector('#upload-form button').textContent = 'Анализировать';
|
||||
}
|
||||
}
|
||||
|
||||
async function runBatch() {
|
||||
if (!jobId) return;
|
||||
document.querySelector('#analysis button').disabled = true;
|
||||
const r = await fetch(API + '/api/batch/run/' + jobId, {method: 'POST', headers: authHeaders()});
|
||||
if (!r.ok) { alert('Ошибка запуска'); return; }
|
||||
|
||||
document.getElementById('status').style.display = 'block';
|
||||
pollStatus();
|
||||
}
|
||||
|
||||
async function pollStatus() {
|
||||
const r = await fetch(API + '/api/batch/status/' + jobId, {headers: authHeaders()});
|
||||
const data = await r.json();
|
||||
|
||||
const pct = data.total > 0 ? (data.processed / data.total * 100) : 0;
|
||||
document.getElementById('progress-bar').style.width = pct + '%';
|
||||
document.getElementById('status-count').textContent = data.processed + ' / ' + data.total + ' файлов';
|
||||
|
||||
if (data.status === 'running') {
|
||||
document.getElementById('status-text').textContent = 'Обработка...';
|
||||
setTimeout(pollStatus, 2000);
|
||||
} else if (data.status === 'completed') {
|
||||
document.getElementById('status-text').textContent = 'Готово!';
|
||||
document.getElementById('download-btn').style.display = 'inline-block';
|
||||
} else if (data.status === 'failed') {
|
||||
document.getElementById('status-text').textContent = 'Ошибка: ' + (data.errors[0] || 'неизвестная');
|
||||
}
|
||||
|
||||
if (data.errors.length > 0) {
|
||||
document.getElementById('error-list').innerHTML = '<b>Ошибки:</b><br>' + data.errors.map(e => '• ' + e).join('<br>');
|
||||
}
|
||||
}
|
||||
|
||||
function downloadResult() {
|
||||
const a = document.createElement('a');
|
||||
a.href = API + '/api/batch/download/' + jobId;
|
||||
fetch(a.href, {headers: authHeaders()}).then(r => r.blob()).then(b => {
|
||||
const u = URL.createObjectURL(b);
|
||||
const l = document.createElement('a'); l.href = u; l.download = 'result.xlsx'; l.click();
|
||||
});
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,348 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Пакетная обработка V2 — Claude Code</title>
|
||||
<style>
|
||||
:root { --bg: #f5f0eb; --card: #fff; --text: #3a3a3a; --muted: #6b6b6b; --accent: #c4463a; --border: #d4c5b2; --radius: 10px; --green: #2d8a56; }
|
||||
* { box-sizing: border-box; margin: 0; padding: 0; }
|
||||
body { font-family: 'Inter', -apple-system, sans-serif; background: var(--bg); color: var(--text); min-height: 100vh; padding: 2rem; }
|
||||
.container { max-width: 750px; margin: 0 auto; }
|
||||
h1 { font-size: 1.3rem; margin-bottom: .3rem; }
|
||||
.subtitle { color: var(--muted); font-size: .9rem; margin-bottom: 1.5rem; }
|
||||
.badge { display: inline-block; background: var(--green); color: #fff; font-size: .7rem; padding: 2px 8px; border-radius: 12px; vertical-align: middle; margin-left: .5rem; }
|
||||
.card { background: var(--card); border-radius: var(--radius); padding: 1.5rem; margin-bottom: 1rem; box-shadow: 0 1px 4px rgba(0,0,0,.06); }
|
||||
.card.hidden { display: none; }
|
||||
label { display: block; font-weight: 600; margin-bottom: .4rem; font-size: .9rem; }
|
||||
.hint { color: var(--muted); font-size: .8rem; margin-bottom: .6rem; }
|
||||
input[type=file] { width: 100%; padding: .5rem; border: 1.5px dashed var(--border); border-radius: var(--radius); margin-bottom: 1rem; }
|
||||
textarea { width: 100%; padding: .6rem; border: 1.5px solid var(--border); border-radius: var(--radius); font-family: inherit; font-size: .9rem; resize: vertical; min-height: 80px; }
|
||||
button { padding: .7rem 1.5rem; background: var(--accent); color: #fff; border: none; border-radius: var(--radius); font-size: .95rem; font-weight: 600; cursor: pointer; }
|
||||
button:hover { background: #a83830; }
|
||||
button:disabled { background: var(--border); cursor: not-allowed; }
|
||||
.back { display: inline-block; margin-bottom: 1rem; color: var(--accent); text-decoration: none; font-size: .85rem; }
|
||||
.progress { background: #ede5db; border-radius: 6px; height: 8px; margin: .5rem 0; }
|
||||
.progress-bar { background: var(--accent); height: 100%; border-radius: 6px; transition: width .3s; }
|
||||
.error-list { color: #c4463a; font-size: .8rem; margin-top: .5rem; max-height: 200px; overflow-y: auto; }
|
||||
pre { background: #2c2c2c; color: #f5f0eb; padding: .8rem; border-radius: 6px; overflow-x: auto; font-size: .78rem; margin: .5rem 0; max-height: 400px; overflow-y: auto; white-space: pre-wrap; word-break: break-word; }
|
||||
.log { background: #1a1a2e; color: #a0d2db; padding: .8rem; border-radius: 6px; font-size: .78rem; margin: .5rem 0; max-height: 300px; overflow-y: auto; font-family: monospace; white-space: pre-wrap; word-break: break-word; }
|
||||
.info-row { display: flex; gap: 1rem; margin: .5rem 0; font-size: .85rem; color: var(--muted); }
|
||||
.info-row span { background: #ede5db; padding: 3px 10px; border-radius: 6px; }
|
||||
.spinner { display: inline-block; width: 16px; height: 16px; border: 2px solid var(--border); border-top-color: var(--accent); border-radius: 50%; animation: spin .8s linear infinite; vertical-align: middle; margin-right: 6px; }
|
||||
@keyframes spin { to { transform: rotate(360deg); } }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<a class="back" href="/">← Вернуться в чат</a>
|
||||
<h1>Пакетная обработка смет <span class="badge">V2 Claude</span></h1>
|
||||
<p class="subtitle">Claude Code читает ВСЕ файлы, понимает структуру, генерирует скрипт обработки</p>
|
||||
|
||||
<!-- Step 1: Upload -->
|
||||
<div class="card" id="step-upload">
|
||||
<label>1. Архив со сметами (.zip)</label>
|
||||
<p class="hint">Все файлы локальных смет в одном архиве (до 2000 файлов)</p>
|
||||
<input type="file" id="zip-file" accept=".zip">
|
||||
|
||||
<label>Сводный файл (.xlsx)</label>
|
||||
<p class="hint">Файл, в который нужно внести данные (ССР, ведомость и т.д.)</p>
|
||||
<input type="file" id="target-file" accept=".xlsx,.xls">
|
||||
|
||||
<label>Описание задачи</label>
|
||||
<p class="hint">Опишите что именно нужно сделать — Claude прочитает файлы и разберётся</p>
|
||||
<textarea id="task-desc" placeholder="Из каждого файла взять итоговые суммы по типам работ (строительные, монтажные, оборудование, прочие) и внести в соответствующие строки и колонки сводного файла. Значения в исходных файлах в рублях, в сводном — тыс.руб."></textarea>
|
||||
<br><br>
|
||||
<button id="btn-upload" onclick="uploadFiles()">Загрузить и конвертировать</button>
|
||||
</div>
|
||||
|
||||
<!-- Step 2: Analysis -->
|
||||
<div class="card hidden" id="step-analyze">
|
||||
<label>2. Анализ Claude Code</label>
|
||||
<div class="info-row" id="csv-info"></div>
|
||||
<p style="margin:.5rem 0;font-size:.9rem"><span class="spinner" id="analyze-spinner"></span> <span id="analyze-status">Claude анализирует файлы...</span> <span id="analyze-timer" style="color:var(--muted);font-size:.8rem"></span></p>
|
||||
<div class="log" id="analyze-log"></div>
|
||||
</div>
|
||||
|
||||
<!-- Step 3: Confirm -->
|
||||
<div class="card hidden" id="step-confirm">
|
||||
<label>3. Проверьте найденные параметры</label>
|
||||
<div id="summary-view" style="font-size:.9rem;line-height:1.6"></div>
|
||||
<details style="margin-top:.8rem">
|
||||
<summary style="cursor:pointer;color:var(--muted);font-size:.8rem">Показать скрипт (для разработчиков)</summary>
|
||||
<pre id="script-code"></pre>
|
||||
</details>
|
||||
<div style="display:flex;gap:.5rem;margin-top:.8rem">
|
||||
<button onclick="runScript()">Запустить обработку</button>
|
||||
<button onclick="reanalyze()" style="background:var(--border);color:var(--text)">Переанализировать</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Step 4: Execution -->
|
||||
<div class="card hidden" id="step-run">
|
||||
<label>4. Выполнение</label>
|
||||
<p id="run-status"></p>
|
||||
<div class="progress"><div class="progress-bar" id="run-progress" style="width:0%"></div></div>
|
||||
<p id="run-count" style="font-size:.85rem;color:var(--muted)"></p>
|
||||
<div class="error-list" id="run-errors"></div>
|
||||
<button id="btn-download" style="display:none" onclick="downloadResult()">Скачать результат</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
const token = localStorage.getItem('token');
|
||||
if (!token) window.location.href = '/';
|
||||
|
||||
const H = {'Authorization': 'Bearer ' + token};
|
||||
let jobId = null;
|
||||
let timerInterval = null;
|
||||
let timerStart = 0;
|
||||
|
||||
function show(id) { document.getElementById(id).classList.remove('hidden'); }
|
||||
function hide(id) { document.getElementById(id).classList.add('hidden'); }
|
||||
|
||||
function startTimer() {
|
||||
timerStart = Date.now();
|
||||
timerInterval = setInterval(() => {
|
||||
const s = Math.floor((Date.now() - timerStart) / 1000);
|
||||
const m = Math.floor(s / 60);
|
||||
const sec = s % 60;
|
||||
document.getElementById('analyze-timer').textContent = m > 0 ? m + 'м ' + sec + 'с' : sec + 'с';
|
||||
}, 1000);
|
||||
}
|
||||
function stopTimer() { if (timerInterval) { clearInterval(timerInterval); timerInterval = null; } }
|
||||
|
||||
async function uploadFiles() {
|
||||
const zipFile = document.getElementById('zip-file').files[0];
|
||||
const targetFile = document.getElementById('target-file').files[0];
|
||||
const taskDesc = document.getElementById('task-desc').value;
|
||||
if (!zipFile || !targetFile) { alert('Загрузите оба файла'); return; }
|
||||
|
||||
const btn = document.getElementById('btn-upload');
|
||||
btn.disabled = true; btn.textContent = 'Загружаю...';
|
||||
|
||||
const fd = new FormData();
|
||||
fd.append('zip_file', zipFile);
|
||||
fd.append('target_file', targetFile);
|
||||
fd.append('task_description', taskDesc || 'Перенести итоги из смет в сводный файл');
|
||||
|
||||
try {
|
||||
const r = await fetch('/api/batch-v2/upload', {method: 'POST', headers: H, body: fd});
|
||||
if (r.status === 401) { window.location.href = '/'; return; }
|
||||
const data = await r.json();
|
||||
jobId = data.job_id;
|
||||
|
||||
const info = data.csv_info;
|
||||
document.getElementById('csv-info').innerHTML =
|
||||
`<span>${data.total_files} xlsx всего</span>` +
|
||||
`<span>${info.sample_count} CSV сэмплов</span>` +
|
||||
`<span>~${Math.round(info.estimated_tokens/1000)}K токенов</span>`;
|
||||
|
||||
show('step-analyze');
|
||||
startAnalysis();
|
||||
} catch(e) { alert('Ошибка: ' + e.message); }
|
||||
finally { btn.disabled = false; btn.textContent = 'Загрузить и конвертировать'; }
|
||||
}
|
||||
|
||||
async function startAnalysis() {
|
||||
const log = document.getElementById('analyze-log');
|
||||
log.textContent = '';
|
||||
startTimer();
|
||||
|
||||
try {
|
||||
const r = await fetch('/api/batch-v2/analyze/' + jobId, {method: 'POST', headers: H});
|
||||
const reader = r.body.getReader();
|
||||
const decoder = new TextDecoder();
|
||||
let buffer = '';
|
||||
|
||||
while (true) {
|
||||
const {done, value} = await reader.read();
|
||||
if (done) break;
|
||||
buffer += decoder.decode(value, {stream: true});
|
||||
|
||||
const lines = buffer.split('\n');
|
||||
buffer = lines.pop(); // keep incomplete line
|
||||
|
||||
let eventType = '';
|
||||
for (const line of lines) {
|
||||
if (line.startsWith('event: ')) { eventType = line.slice(7); continue; }
|
||||
if (!line.startsWith('data: ')) continue;
|
||||
try {
|
||||
const d = JSON.parse(line.slice(6));
|
||||
if (eventType === 'text') {
|
||||
log.textContent += d.text;
|
||||
log.scrollTop = log.scrollHeight;
|
||||
} else if (eventType === 'tool') {
|
||||
log.textContent += '\n[tool: ' + d.tool + ']\n';
|
||||
log.scrollTop = log.scrollHeight;
|
||||
} else if (eventType === 'done') {
|
||||
document.getElementById('analyze-spinner').style.display = 'none';
|
||||
stopTimer();
|
||||
if (d.script) {
|
||||
document.getElementById('analyze-status').textContent = 'Анализ завершён';
|
||||
document.getElementById('script-code').textContent = d.script;
|
||||
renderSummary(d.summary);
|
||||
show('step-confirm');
|
||||
} else {
|
||||
document.getElementById('analyze-status').textContent = 'Claude не сгенерировал скрипт';
|
||||
document.getElementById('analyze-status').style.color = 'var(--accent)';
|
||||
}
|
||||
}
|
||||
} catch(e) {}
|
||||
}
|
||||
}
|
||||
} catch(e) {
|
||||
// Network error or stream closed — ignore, fall through to polling
|
||||
}
|
||||
|
||||
// Fallback: if SSE ended without 'done' event, poll status
|
||||
if (!document.getElementById('step-confirm').classList.contains('hidden')) return; // already shown
|
||||
stopTimer();
|
||||
document.getElementById('analyze-status').textContent = 'Проверяю результат...';
|
||||
for (let i = 0; i < 10; i++) {
|
||||
await new Promise(r => setTimeout(r, 2000));
|
||||
try {
|
||||
const sr = await fetch('/api/batch-v2/status/' + jobId, {headers: H});
|
||||
const sd = await sr.json();
|
||||
if (sd.status === 'analyzed' && sd.script) {
|
||||
document.getElementById('analyze-spinner').style.display = 'none';
|
||||
document.getElementById('analyze-status').textContent = 'Анализ завершён';
|
||||
document.getElementById('script-code').textContent = sd.script;
|
||||
// Fetch summary from status if available
|
||||
renderSummary(sd.summary || {});
|
||||
show('step-confirm');
|
||||
return;
|
||||
} else if (sd.status === 'analysis_failed') {
|
||||
document.getElementById('analyze-spinner').style.display = 'none';
|
||||
document.getElementById('analyze-status').textContent = 'Ошибка анализа';
|
||||
document.getElementById('analyze-status').style.color = 'var(--accent)';
|
||||
return;
|
||||
}
|
||||
} catch(e2) {}
|
||||
}
|
||||
document.getElementById('analyze-spinner').style.display = 'none';
|
||||
document.getElementById('analyze-status').textContent = 'Таймаут — попробуйте ещё раз';
|
||||
document.getElementById('analyze-status').style.color = 'var(--accent)';
|
||||
}
|
||||
|
||||
async function reanalyze() {
|
||||
hide('step-confirm');
|
||||
document.getElementById('analyze-spinner').style.display = 'inline-block';
|
||||
document.getElementById('analyze-status').textContent = 'Claude анализирует файлы...';
|
||||
document.getElementById('analyze-status').style.color = '';
|
||||
startAnalysis();
|
||||
}
|
||||
|
||||
async function runScript() {
|
||||
try {
|
||||
const r = await fetch('/api/batch-v2/run/' + jobId, {method: 'POST', headers: H});
|
||||
if (!r.ok) { alert('Ошибка запуска'); return; }
|
||||
show('step-run');
|
||||
pollStatus();
|
||||
} catch(e) { alert('Ошибка: ' + e.message); }
|
||||
}
|
||||
|
||||
async function pollStatus() {
|
||||
const r = await fetch('/api/batch-v2/status/' + jobId, {headers: H});
|
||||
const d = await r.json();
|
||||
|
||||
const pct = d.total > 0 ? (d.processed / d.total * 100) : 0;
|
||||
document.getElementById('run-progress').style.width = pct + '%';
|
||||
document.getElementById('run-count').textContent = d.processed + ' / ' + d.total + ' файлов';
|
||||
|
||||
if (d.status === 'running') {
|
||||
document.getElementById('run-status').textContent = 'Обработка...';
|
||||
setTimeout(pollStatus, 1500);
|
||||
} else if (d.status === 'completed') {
|
||||
document.getElementById('run-status').textContent = 'Готово! Обработано: ' + d.processed + ' из ' + d.total;
|
||||
document.getElementById('run-status').style.color = 'var(--green)';
|
||||
document.getElementById('btn-download').style.display = 'inline-block';
|
||||
} else if (d.status === 'failed') {
|
||||
document.getElementById('run-status').textContent = 'Ошибка выполнения';
|
||||
document.getElementById('run-status').style.color = 'var(--accent)';
|
||||
}
|
||||
|
||||
if (d.errors && d.errors.length > 0) {
|
||||
document.getElementById('run-errors').innerHTML = '<b>Ошибки:</b><br>' + d.errors.map(e => '• ' + e).join('<br>');
|
||||
}
|
||||
}
|
||||
|
||||
function renderSummary(s) {
|
||||
const el = document.getElementById('summary-view');
|
||||
if (!s || !s.source_patterns) {
|
||||
el.innerHTML = '<p style="color:var(--muted)">Параметры не распознаны — проверьте скрипт вручную</p>';
|
||||
return;
|
||||
}
|
||||
const src = s.source_patterns || {};
|
||||
const tgt = s.target_mapping || {};
|
||||
let html = '';
|
||||
if (s.description) html += `<p><b>${s.description}</b></p>`;
|
||||
|
||||
html += '<table style="width:100%;border-collapse:collapse;margin:.5rem 0;font-size:.85rem">';
|
||||
html += '<tr style="background:#ede5db"><td colspan="2" style="padding:6px;font-weight:600">Исходные файлы</td></tr>';
|
||||
if (src.sheet) html += row('Лист', src.sheet);
|
||||
if (src.id_field) html += row('Шифр/название', src.id_field);
|
||||
if (src.value_column) html += row('Столбец значений', src.value_column);
|
||||
if (src.units) html += row('Единицы', src.units);
|
||||
|
||||
if (src.totals) {
|
||||
html += '<tr style="background:#ede5db"><td colspan="2" style="padding:6px;font-weight:600">Паттерны поиска итогов</td></tr>';
|
||||
for (const [k, v] of Object.entries(src.totals)) {
|
||||
html += row(k, '<code>' + v + '</code>');
|
||||
}
|
||||
}
|
||||
|
||||
html += '<tr style="background:#ede5db"><td colspan="2" style="padding:6px;font-weight:600">Сводный файл</td></tr>';
|
||||
if (tgt.sheet) html += row('Лист', tgt.sheet);
|
||||
if (tgt.match_column) html += row('Столбец сопоставления', tgt.match_column);
|
||||
if (tgt.value_columns) {
|
||||
for (const [k, v] of Object.entries(tgt.value_columns)) {
|
||||
html += row(k + ' →', 'столбец ' + v);
|
||||
}
|
||||
}
|
||||
if (tgt.units) html += row('Единицы', tgt.units);
|
||||
if (s.conversion) html += row('Конвертация', s.conversion);
|
||||
html += '</table>';
|
||||
|
||||
// Preview table: source → target mapping with actual values
|
||||
if (s.preview && s.preview.length > 0) {
|
||||
html += '<div style="margin-top:.8rem"><b>Превью маппинга (по сэмплам):</b></div>';
|
||||
html += '<table style="width:100%;border-collapse:collapse;margin:.3rem 0;font-size:.8rem">';
|
||||
html += '<tr style="background:#ede5db">' +
|
||||
'<td style="padding:5px">Исходный файл</td>' +
|
||||
'<td style="padding:5px">Извлечённые значения</td>' +
|
||||
'<td style="padding:5px">→ Куда</td>' +
|
||||
'<td style="padding:5px">Записываемые значения</td></tr>';
|
||||
for (const p of s.preview) {
|
||||
const srcVals = p.source_values ? Object.entries(p.source_values).map(([k,v]) => k + ': ' + v).join('<br>') : '-';
|
||||
const tgtVals = p.target_values ? Object.entries(p.target_values).map(([k,v]) => k + '=' + v).join(', ') : '-';
|
||||
const tgtWhere = (p.target_sheet || '') + '<br>' + (p.target_row || '');
|
||||
html += '<tr>' +
|
||||
'<td style="padding:4px 5px;border-bottom:1px solid #eee;word-break:break-all">' + (p.source_file || '') + '</td>' +
|
||||
'<td style="padding:4px 5px;border-bottom:1px solid #eee;font-size:.75rem">' + srcVals + '</td>' +
|
||||
'<td style="padding:4px 5px;border-bottom:1px solid #eee;font-size:.75rem">' + tgtWhere + '</td>' +
|
||||
'<td style="padding:4px 5px;border-bottom:1px solid #eee"><code>' + tgtVals + '</code></td></tr>';
|
||||
}
|
||||
html += '</table>';
|
||||
}
|
||||
|
||||
el.innerHTML = html;
|
||||
|
||||
function row(label, value) {
|
||||
return `<tr><td style="padding:4px 6px;border-bottom:1px solid #eee;color:var(--muted);width:40%">${label}</td><td style="padding:4px 6px;border-bottom:1px solid #eee">${value}</td></tr>`;
|
||||
}
|
||||
}
|
||||
|
||||
function downloadResult() {
|
||||
fetch('/api/batch-v2/download/' + jobId, {headers: H})
|
||||
.then(r => r.blob())
|
||||
.then(b => {
|
||||
const u = URL.createObjectURL(b);
|
||||
const a = document.createElement('a');
|
||||
a.href = u; a.download = 'result.xlsx'; a.click();
|
||||
URL.revokeObjectURL(u);
|
||||
});
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,389 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Пакетная обработка V3 — Verify</title>
|
||||
<style>
|
||||
:root { --bg: #f5f0eb; --card: #fff; --text: #3a3a3a; --muted: #6b6b6b; --accent: #c4463a; --border: #d4c5b2; --radius: 10px; --green: #2d8a56; }
|
||||
* { box-sizing: border-box; margin: 0; padding: 0; }
|
||||
body { font-family: 'Inter', -apple-system, sans-serif; background: var(--bg); color: var(--text); min-height: 100vh; padding: 2rem; }
|
||||
.container { max-width: 750px; margin: 0 auto; }
|
||||
h1 { font-size: 1.3rem; margin-bottom: .3rem; }
|
||||
.subtitle { color: var(--muted); font-size: .9rem; margin-bottom: 1.5rem; }
|
||||
.badge { display: inline-block; background: var(--green); color: #fff; font-size: .7rem; padding: 2px 8px; border-radius: 12px; vertical-align: middle; margin-left: .5rem; }
|
||||
.badge-warn { background: #d4a017; }
|
||||
.card { background: var(--card); border-radius: var(--radius); padding: 1.5rem; margin-bottom: 1rem; box-shadow: 0 1px 4px rgba(0,0,0,.06); }
|
||||
.card.hidden { display: none; }
|
||||
label { display: block; font-weight: 600; margin-bottom: .4rem; font-size: .9rem; }
|
||||
.hint { color: var(--muted); font-size: .8rem; margin-bottom: .6rem; }
|
||||
input[type=file] { width: 100%; padding: .5rem; border: 1.5px dashed var(--border); border-radius: var(--radius); margin-bottom: 1rem; }
|
||||
textarea { width: 100%; padding: .6rem; border: 1.5px solid var(--border); border-radius: var(--radius); font-family: inherit; font-size: .9rem; resize: vertical; min-height: 80px; }
|
||||
button { padding: .7rem 1.5rem; background: var(--accent); color: #fff; border: none; border-radius: var(--radius); font-size: .95rem; font-weight: 600; cursor: pointer; }
|
||||
button:hover { background: #a83830; }
|
||||
button:disabled { background: var(--border); cursor: not-allowed; }
|
||||
.back { display: inline-block; margin-bottom: 1rem; color: var(--accent); text-decoration: none; font-size: .85rem; }
|
||||
.progress { background: #ede5db; border-radius: 6px; height: 8px; margin: .5rem 0; }
|
||||
.progress-bar { background: var(--accent); height: 100%; border-radius: 6px; transition: width .3s; }
|
||||
.error-list { color: #c4463a; font-size: .8rem; margin-top: .5rem; max-height: 200px; overflow-y: auto; }
|
||||
pre { background: #2c2c2c; color: #f5f0eb; padding: .8rem; border-radius: 6px; overflow-x: auto; font-size: .78rem; margin: .5rem 0; max-height: 400px; overflow-y: auto; white-space: pre-wrap; word-break: break-word; }
|
||||
.log { background: #1a1a2e; color: #a0d2db; padding: .8rem; border-radius: 6px; font-size: .78rem; margin: .5rem 0; max-height: 300px; overflow-y: auto; font-family: monospace; white-space: pre-wrap; word-break: break-word; }
|
||||
.info-row { display: flex; gap: 1rem; margin: .5rem 0; font-size: .85rem; color: var(--muted); }
|
||||
.info-row span { background: #ede5db; padding: 3px 10px; border-radius: 6px; }
|
||||
.spinner { display: inline-block; width: 16px; height: 16px; border: 2px solid var(--border); border-top-color: var(--accent); border-radius: 50%; animation: spin .8s linear infinite; vertical-align: middle; margin-right: 6px; }
|
||||
@keyframes spin { to { transform: rotate(360deg); } }
|
||||
.copy-btn { position: absolute; top: 4px; right: 4px; padding: 4px 12px; font-size: .75rem; background: var(--card); color: var(--accent); border: 1.5px solid var(--accent); border-radius: 4px; cursor: pointer; z-index: 1; font-weight: 600; }
|
||||
.copy-btn:hover { background: var(--accent); color: #fff; }
|
||||
.copy-btn-inline { display: inline-block; padding: 4px 14px; font-size: .75rem; background: var(--card); color: var(--accent); border: 1.5px solid var(--accent); border-radius: 4px; cursor: pointer; font-weight: 600; margin-top: .5rem; }
|
||||
.copy-btn-inline:hover { background: var(--accent); color: #fff; }
|
||||
.verify-ok { background: #e8f5e9; border: 1px solid var(--green); border-radius: 6px; padding: .5rem .8rem; margin: .5rem 0; font-size: .85rem; color: var(--green); }
|
||||
.verify-fail { background: #fce4ec; border: 1px solid var(--accent); border-radius: 6px; padding: .5rem .8rem; margin: .5rem 0; font-size: .85rem; color: var(--accent); }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<a class="back" href="/">← Вернуться в чат</a>
|
||||
<h1>Пакетная обработка смет <span class="badge">V3 Verify</span></h1>
|
||||
<p class="subtitle">Claude генерирует скрипт + автоматическая проверка на 2 файлах + auto-retry</p>
|
||||
|
||||
<!-- Step 1: Upload -->
|
||||
<div class="card" id="step-upload">
|
||||
<label>1. Архив со сметами (.zip)</label>
|
||||
<p class="hint">Все файлы локальных смет в одном архиве (до 2000 файлов)</p>
|
||||
<input type="file" id="zip-file" accept=".zip">
|
||||
<label>Сводный файл (.xlsx)</label>
|
||||
<p class="hint">Файл, в который нужно внести данные (ССР, ведомость и т.д.)</p>
|
||||
<input type="file" id="target-file" accept=".xlsx,.xls">
|
||||
<label>Описание задачи</label>
|
||||
<p class="hint">Опишите что именно нужно сделать — Claude прочитает файлы и разберётся</p>
|
||||
<textarea id="task-desc" placeholder="Из каждого файла взять итоговые суммы по типам работ (строительные, монтажные, оборудование, прочие) и внести в соответствующие строки и колонки сводного файла. Значения в исходных файлах в рублях, в сводном — тыс.руб."></textarea>
|
||||
<br><br>
|
||||
<button id="btn-upload" onclick="uploadFiles()">Загрузить и конвертировать</button>
|
||||
</div>
|
||||
|
||||
<!-- Step 2: Analysis + Verification -->
|
||||
<div class="card hidden" id="step-analyze">
|
||||
<label>2. Генерация + верификация</label>
|
||||
<div class="info-row" id="csv-info"></div>
|
||||
<p style="margin:.5rem 0;font-size:.9rem"><span class="spinner" id="analyze-spinner"></span> <span id="analyze-status">Claude генерирует скрипт...</span> <span id="analyze-timer" style="color:var(--muted);font-size:.8rem"></span></p>
|
||||
<div id="verify-status"></div>
|
||||
<div style="position:relative">
|
||||
<div class="log" id="analyze-log"></div>
|
||||
<button class="copy-btn" onclick="copyText('analyze-log')" title="Копировать">Копировать</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Step 3: Confirm -->
|
||||
<div class="card hidden" id="step-confirm">
|
||||
<label>3. Проверьте найденные параметры</label>
|
||||
<div id="verify-badge"></div>
|
||||
<div id="summary-view" style="font-size:.9rem;line-height:1.6"></div>
|
||||
<button class="copy-btn-inline" onclick="copyText('summary-view')" title="Копировать параметры">Копировать параметры</button>
|
||||
<details style="margin-top:.8rem">
|
||||
<summary style="cursor:pointer;color:var(--muted);font-size:.8rem">Показать скрипт (для разработчиков)</summary>
|
||||
<div style="position:relative">
|
||||
<pre id="script-code"></pre>
|
||||
<button class="copy-btn" onclick="copyText('script-code')" title="Копировать">Копировать</button>
|
||||
</div>
|
||||
</details>
|
||||
<div style="display:flex;gap:.5rem;margin-top:.8rem">
|
||||
<button id="btn-run" onclick="runScript()">Запустить обработку</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Step 4: Execution -->
|
||||
<div class="card hidden" id="step-run">
|
||||
<label>4. Выполнение</label>
|
||||
<p id="run-status"></p>
|
||||
<div class="progress"><div class="progress-bar" id="run-progress" style="width:0%"></div></div>
|
||||
<p id="run-count" style="font-size:.85rem;color:var(--muted)"></p>
|
||||
<div class="error-list" id="run-errors"></div>
|
||||
<button id="btn-download" style="display:none" onclick="downloadResult()">Скачать результат</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
let token = localStorage.getItem('token');
|
||||
// Validate token on load (don't trust localStorage blindly)
|
||||
(async () => {
|
||||
if (!token) { window.location.href = '/'; return; }
|
||||
try {
|
||||
const r = await fetch('/api/history?limit=1', {headers:{'Authorization':'Bearer '+token}});
|
||||
if (r.ok) return; // token valid
|
||||
} catch {}
|
||||
// Try refresh
|
||||
const rt = localStorage.getItem('refresh_token');
|
||||
if (rt) {
|
||||
try {
|
||||
const r = await fetch('/api/refresh', {method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify({refresh_token:rt})});
|
||||
if (r.ok) { const d = await r.json(); token = d.token; localStorage.setItem('token', token); return; }
|
||||
} catch {}
|
||||
}
|
||||
localStorage.removeItem('token'); localStorage.removeItem('refresh_token');
|
||||
window.location.href = '/';
|
||||
})();
|
||||
|
||||
const API = '/api/batch-v3';
|
||||
const H = {'Authorization': 'Bearer ' + token};
|
||||
let jobId = null;
|
||||
let verified = false;
|
||||
let timerInterval = null;
|
||||
let timerStart = 0;
|
||||
|
||||
function show(id) { document.getElementById(id).classList.remove('hidden'); }
|
||||
function hide(id) { document.getElementById(id).classList.add('hidden'); }
|
||||
function copyText(elId) {
|
||||
const el = document.getElementById(elId);
|
||||
const text = el.innerText || el.textContent;
|
||||
navigator.clipboard.writeText(text).then(() => {
|
||||
const btn = el.parentElement.querySelector('.copy-btn');
|
||||
if (btn) { const orig = btn.textContent; btn.textContent = 'Скопировано'; setTimeout(() => btn.textContent = orig, 1500); }
|
||||
});
|
||||
}
|
||||
|
||||
function startTimer() {
|
||||
timerStart = Date.now();
|
||||
timerInterval = setInterval(() => {
|
||||
const s = Math.floor((Date.now() - timerStart) / 1000);
|
||||
const m = Math.floor(s / 60);
|
||||
const sec = s % 60;
|
||||
document.getElementById('analyze-timer').textContent = m > 0 ? m + 'м ' + sec + 'с' : sec + 'с';
|
||||
}, 1000);
|
||||
}
|
||||
function stopTimer() { if (timerInterval) { clearInterval(timerInterval); timerInterval = null; } }
|
||||
|
||||
async function uploadFiles() {
|
||||
const zipFile = document.getElementById('zip-file').files[0];
|
||||
const targetFile = document.getElementById('target-file').files[0];
|
||||
const taskDesc = document.getElementById('task-desc').value;
|
||||
if (!zipFile || !targetFile) { alert('Загрузите оба файла'); return; }
|
||||
|
||||
const btn = document.getElementById('btn-upload');
|
||||
btn.disabled = true; btn.textContent = 'Загружаю...';
|
||||
|
||||
const fd = new FormData();
|
||||
fd.append('zip_file', zipFile);
|
||||
fd.append('target_file', targetFile);
|
||||
fd.append('task_description', taskDesc || 'Перенести итоги из смет в сводный файл');
|
||||
|
||||
try {
|
||||
const r = await fetch(API + '/upload', {method: 'POST', headers: H, body: fd});
|
||||
if (r.status === 401) { window.location.href = '/'; return; }
|
||||
const data = await r.json();
|
||||
jobId = data.job_id;
|
||||
const info = data.csv_info;
|
||||
document.getElementById('csv-info').innerHTML =
|
||||
`<span>${data.total_files} xlsx</span><span>${info.sample_count} CSV сэмплов</span><span>~${Math.round(info.estimated_tokens/1000)}K токенов</span>`;
|
||||
btn.textContent = 'Загружено';
|
||||
show('step-analyze');
|
||||
startAnalysis();
|
||||
} catch(e) { alert('Ошибка: ' + e.message); btn.disabled = false; btn.textContent = 'Загрузить и конвертировать'; }
|
||||
}
|
||||
|
||||
async function startAnalysis() {
|
||||
const log = document.getElementById('analyze-log');
|
||||
const vstat = document.getElementById('verify-status');
|
||||
log.textContent = '';
|
||||
vstat.innerHTML = '';
|
||||
verified = false;
|
||||
startTimer();
|
||||
|
||||
try {
|
||||
const r = await fetch(API + '/analyze/' + jobId, {method: 'POST', headers: H});
|
||||
const reader = r.body.getReader();
|
||||
const decoder = new TextDecoder();
|
||||
let buffer = '';
|
||||
|
||||
while (true) {
|
||||
const {done, value} = await reader.read();
|
||||
if (done) break;
|
||||
buffer += decoder.decode(value, {stream: true});
|
||||
const lines = buffer.split('\n');
|
||||
buffer = lines.pop();
|
||||
|
||||
let eventType = '';
|
||||
for (const line of lines) {
|
||||
if (line.startsWith('event: ')) { eventType = line.slice(7); continue; }
|
||||
if (!line.startsWith('data: ')) continue;
|
||||
try {
|
||||
const d = JSON.parse(line.slice(6));
|
||||
|
||||
if (eventType === 'text') {
|
||||
log.textContent += d.text;
|
||||
log.scrollTop = log.scrollHeight;
|
||||
} else if (eventType === 'tool') {
|
||||
log.textContent += '\n[tool: ' + d.tool + ']\n';
|
||||
log.scrollTop = log.scrollHeight;
|
||||
} else if (eventType === 'generation_start') {
|
||||
const att = d.attempt || 1;
|
||||
document.getElementById('analyze-status').textContent = att > 1
|
||||
? 'Попытка ' + att + '/3: Claude перегенерирует скрипт...'
|
||||
: 'Claude генерирует скрипт...';
|
||||
if (att > 1) log.textContent += '\n--- Попытка ' + att + ' ---\n';
|
||||
} else if (eventType === 'verify_start') {
|
||||
document.getElementById('analyze-status').textContent = 'Проверяю скрипт на 2 файлах...';
|
||||
vstat.innerHTML = '<p style="font-size:.85rem;color:var(--muted)">Выполняю скрипт на 2 сэмплах...</p>';
|
||||
} else if (eventType === 'verify_ok') {
|
||||
vstat.innerHTML = '<div class="verify-ok">Скрипт проверен: обработано ' + d.processed + ' файлов без ошибок</div>';
|
||||
} else if (eventType === 'verify_fail') {
|
||||
vstat.innerHTML = '<div class="verify-fail">Попытка ' + d.attempt + '/3: ошибка — ' + (d.error || '').slice(0, 200) + '</div>';
|
||||
} else if (eventType === 'retry') {
|
||||
log.textContent += '\n[retry: attempt ' + d.attempt + ']\n';
|
||||
} else if (eventType === 'done') {
|
||||
document.getElementById('analyze-spinner').style.display = 'none';
|
||||
stopTimer();
|
||||
verified = d.verified || false;
|
||||
if (d.script) {
|
||||
document.getElementById('analyze-status').textContent = 'Анализ завершён' + (d.attempts > 1 ? ' (попытка ' + d.attempts + ')' : '');
|
||||
document.getElementById('script-code').textContent = d.script;
|
||||
renderSummary(d.summary);
|
||||
// Verify badge
|
||||
const vb = document.getElementById('verify-badge');
|
||||
if (verified) {
|
||||
vb.innerHTML = '<div class="verify-ok">Скрипт прошёл автоматическую проверку</div>';
|
||||
} else {
|
||||
vb.innerHTML = '<div class="verify-fail">Скрипт НЕ прошёл проверку после 3 попыток. Запуск на ваш риск.</div>';
|
||||
}
|
||||
show('step-confirm');
|
||||
} else {
|
||||
document.getElementById('analyze-status').textContent = 'Claude не сгенерировал скрипт';
|
||||
document.getElementById('analyze-status').style.color = 'var(--accent)';
|
||||
}
|
||||
}
|
||||
} catch(e) {}
|
||||
}
|
||||
}
|
||||
} catch(e) {
|
||||
// Stream closed — fall through to polling
|
||||
}
|
||||
|
||||
// Polling fallback
|
||||
if (document.getElementById('step-confirm').classList.contains('hidden')) {
|
||||
stopTimer();
|
||||
document.getElementById('analyze-status').textContent = 'Проверяю результат...';
|
||||
for (let i = 0; i < 15; i++) {
|
||||
await new Promise(r => setTimeout(r, 3000));
|
||||
try {
|
||||
const sr = await fetch(API + '/status/' + jobId, {headers: H});
|
||||
const sd = await sr.json();
|
||||
if (sd.status === 'analyzed' && sd.script) {
|
||||
document.getElementById('analyze-spinner').style.display = 'none';
|
||||
document.getElementById('analyze-status').textContent = 'Анализ завершён';
|
||||
document.getElementById('script-code').textContent = sd.script;
|
||||
verified = sd.verified || false;
|
||||
renderSummary(sd.summary || {});
|
||||
const vb = document.getElementById('verify-badge');
|
||||
vb.innerHTML = verified
|
||||
? '<div class="verify-ok">Скрипт прошёл автоматическую проверку</div>'
|
||||
: '<div class="verify-fail">Скрипт НЕ прошёл проверку. Запуск на ваш риск.</div>';
|
||||
show('step-confirm');
|
||||
return;
|
||||
}
|
||||
} catch(e2) {}
|
||||
}
|
||||
document.getElementById('analyze-spinner').style.display = 'none';
|
||||
document.getElementById('analyze-status').textContent = 'Таймаут — попробуйте ещё раз';
|
||||
document.getElementById('analyze-status').style.color = 'var(--accent)';
|
||||
}
|
||||
}
|
||||
|
||||
async function runScript() {
|
||||
if (!verified) {
|
||||
if (!confirm('Скрипт НЕ прошёл автоматическую проверку. Запустить на свой риск?')) return;
|
||||
}
|
||||
const btn = document.getElementById('btn-run');
|
||||
btn.disabled = true; btn.textContent = 'Запускаю...';
|
||||
try {
|
||||
const r = await fetch(API + '/run/' + jobId, {method: 'POST', headers: H});
|
||||
if (!r.ok) { alert('Ошибка запуска'); btn.disabled = false; btn.textContent = 'Запустить обработку'; return; }
|
||||
btn.textContent = 'Запущено';
|
||||
show('step-run');
|
||||
pollStatus();
|
||||
} catch(e) { alert('Ошибка: ' + e.message); btn.disabled = false; btn.textContent = 'Запустить обработку'; }
|
||||
}
|
||||
|
||||
async function pollStatus() {
|
||||
const r = await fetch(API + '/status/' + jobId, {headers: H});
|
||||
const d = await r.json();
|
||||
const pct = d.total > 0 ? (d.processed / d.total * 100) : 0;
|
||||
document.getElementById('run-progress').style.width = pct + '%';
|
||||
document.getElementById('run-count').textContent = d.processed + ' / ' + d.total + ' файлов';
|
||||
|
||||
if (d.status === 'running') {
|
||||
document.getElementById('run-status').textContent = 'Обработка...';
|
||||
setTimeout(pollStatus, 1500);
|
||||
} else if (d.status === 'completed') {
|
||||
document.getElementById('run-status').textContent = 'Готово! Обработано: ' + d.processed + ' из ' + d.total;
|
||||
document.getElementById('run-status').style.color = 'var(--green)';
|
||||
document.getElementById('btn-download').style.display = 'inline-block';
|
||||
} else if (d.status === 'failed') {
|
||||
document.getElementById('run-status').textContent = 'Ошибка выполнения';
|
||||
document.getElementById('run-status').style.color = 'var(--accent)';
|
||||
}
|
||||
if (d.errors && d.errors.length > 0) {
|
||||
document.getElementById('run-errors').innerHTML = '<b>Ошибки:</b><br>' + d.errors.map(e => '• ' + e).join('<br>');
|
||||
}
|
||||
}
|
||||
|
||||
function renderSummary(s) {
|
||||
const el = document.getElementById('summary-view');
|
||||
if (!s || !s.source_patterns) {
|
||||
el.innerHTML = '<p style="color:var(--muted)">Параметры не распознаны — проверьте скрипт вручную</p>';
|
||||
return;
|
||||
}
|
||||
const src = s.source_patterns || {};
|
||||
const tgt = s.target_mapping || {};
|
||||
let html = '';
|
||||
if (s.description) html += `<p><b>${s.description}</b></p>`;
|
||||
|
||||
html += '<table style="width:100%;border-collapse:collapse;margin:.5rem 0;font-size:.85rem">';
|
||||
html += '<tr style="background:#ede5db"><td colspan="2" style="padding:6px;font-weight:600">Исходные файлы</td></tr>';
|
||||
if (src.sheet) html += row('Лист', src.sheet);
|
||||
if (src.id_field) html += row('Шифр/название', src.id_field);
|
||||
if (src.value_column) html += row('Столбец значений', src.value_column);
|
||||
if (src.units) html += row('Единицы', src.units);
|
||||
if (src.totals) {
|
||||
html += '<tr style="background:#ede5db"><td colspan="2" style="padding:6px;font-weight:600">Паттерны поиска итогов</td></tr>';
|
||||
for (const [k, v] of Object.entries(src.totals)) html += row(k, '<code>' + v + '</code>');
|
||||
}
|
||||
html += '<tr style="background:#ede5db"><td colspan="2" style="padding:6px;font-weight:600">Сводный файл</td></tr>';
|
||||
if (tgt.sheet) html += row('Лист', tgt.sheet);
|
||||
if (tgt.match_column) html += row('Столбец сопоставления', tgt.match_column);
|
||||
if (tgt.value_columns) {
|
||||
for (const [k, v] of Object.entries(tgt.value_columns)) html += row(k + ' →', 'столбец ' + v);
|
||||
}
|
||||
if (tgt.units) html += row('Единицы', tgt.units);
|
||||
if (s.conversion) html += row('Конвертация', s.conversion);
|
||||
html += '</table>';
|
||||
|
||||
if (s.preview && s.preview.length > 0) {
|
||||
html += '<div style="margin-top:.8rem"><b>Превью маппинга (по сэмплам):</b></div>';
|
||||
html += '<table style="width:100%;border-collapse:collapse;margin:.3rem 0;font-size:.8rem">';
|
||||
html += '<tr style="background:#ede5db"><td style="padding:5px">Исходный файл</td><td style="padding:5px">Извлечённые значения</td><td style="padding:5px">→ Куда</td><td style="padding:5px">Записываемые значения</td></tr>';
|
||||
for (const p of s.preview) {
|
||||
const srcVals = p.source_values ? Object.entries(p.source_values).map(([k,v]) => k + ': ' + v).join('<br>') : '-';
|
||||
const tgtVals = p.target_values ? Object.entries(p.target_values).map(([k,v]) => k + '=' + v).join(', ') : '-';
|
||||
const tgtWhere = (p.target_sheet || '') + '<br>' + (p.target_row || '');
|
||||
html += '<tr><td style="padding:4px 5px;border-bottom:1px solid #eee;word-break:break-all">' + (p.source_file || '') + '</td><td style="padding:4px 5px;border-bottom:1px solid #eee;font-size:.75rem">' + srcVals + '</td><td style="padding:4px 5px;border-bottom:1px solid #eee;font-size:.75rem">' + tgtWhere + '</td><td style="padding:4px 5px;border-bottom:1px solid #eee"><code>' + tgtVals + '</code></td></tr>';
|
||||
}
|
||||
html += '</table>';
|
||||
}
|
||||
el.innerHTML = html;
|
||||
function row(label, value) {
|
||||
return `<tr><td style="padding:4px 6px;border-bottom:1px solid #eee;color:var(--muted);width:40%">${label}</td><td style="padding:4px 6px;border-bottom:1px solid #eee">${value}</td></tr>`;
|
||||
}
|
||||
}
|
||||
|
||||
function downloadResult() {
|
||||
fetch(API + '/download/' + jobId, {headers: H})
|
||||
.then(r => r.blob())
|
||||
.then(b => {
|
||||
const u = URL.createObjectURL(b);
|
||||
const a = document.createElement('a');
|
||||
a.href = u; a.download = 'result.xlsx'; a.click();
|
||||
URL.revokeObjectURL(u);
|
||||
});
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,137 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Проверка сметы</title>
|
||||
<style>
|
||||
:root {
|
||||
--bg: #f5f0eb; --bg-card: #ffffff;
|
||||
--text: #3a3a3a; --text-muted: #6b6b6b;
|
||||
--border: #d4c5b2; --border-light: #ede5db;
|
||||
--accent: #c4463a; --accent-hover: #a83830;
|
||||
--success: #2b8a3e; --warn: #e8590c; --danger: #e03131; --info: #1971c2;
|
||||
--shadow-md: 0 4px 16px rgba(0,0,0,.07);
|
||||
--radius: 10px; --radius-lg: 16px;
|
||||
}
|
||||
* { box-sizing: border-box; margin: 0; padding: 0; }
|
||||
body { font-family: 'Inter', -apple-system, sans-serif; background: var(--bg); color: var(--text); }
|
||||
.container { max-width: 860px; margin: 24px auto; padding: 0 16px; }
|
||||
.header { display: flex; align-items: center; justify-content: space-between; margin-bottom: 20px; }
|
||||
.header h1 { font-size: 1.2rem; font-weight: 700; }
|
||||
.header a { color: var(--accent); text-decoration: none; font-size: .85rem; font-weight: 500; }
|
||||
.card { background: var(--bg-card); border-radius: var(--radius-lg); box-shadow: var(--shadow-md); padding: 24px; margin-bottom: 16px; }
|
||||
label { display: block; font-size: .85rem; font-weight: 500; color: var(--text-muted); margin-bottom: 4px; }
|
||||
textarea { width: 100%; padding: .6rem; border: 1.5px solid var(--border); border-radius: var(--radius); font-size: .82rem; font-family: 'SF Mono', Menlo, monospace; background: var(--bg); outline: none; resize: vertical; min-height: 200px; }
|
||||
textarea:focus { border-color: var(--accent); background: var(--bg-card); }
|
||||
.btn { padding: .55rem 1.2rem; border: none; border-radius: var(--radius); font-size: .85rem; font-weight: 600; cursor: pointer; background: var(--accent); color: #fff; }
|
||||
.btn:hover { background: var(--accent-hover); }
|
||||
.btn-outline { background: transparent; border: 1.5px solid var(--border); color: var(--text-muted); }
|
||||
.result-item { padding: 8px 12px; border-radius: var(--radius); margin-bottom: 6px; font-size: .88rem; display: flex; align-items: flex-start; gap: 8px; }
|
||||
.result-item.error { background: #fff1f2; border-left: 3px solid var(--danger); }
|
||||
.result-item.warning { background: #fff9db; border-left: 3px solid var(--warn); }
|
||||
.result-item.info { background: #e7f5ff; border-left: 3px solid var(--info); }
|
||||
.icon { font-size: 1rem; flex-shrink: 0; }
|
||||
.summary { display: flex; gap: 12px; margin-bottom: 16px; }
|
||||
.badge { padding: 4px 12px; border-radius: 10px; font-size: .8rem; font-weight: 600; }
|
||||
.badge-err { background: #ffe3e3; color: var(--danger); }
|
||||
.badge-warn { background: #fff3bf; color: var(--warn); }
|
||||
.badge-info { background: #dbeafe; color: var(--info); }
|
||||
.mt-2 { margin-top: 8px; }
|
||||
.mt-3 { margin-top: 12px; }
|
||||
.spinner { width: 1rem; height: 1rem; border: 2px solid var(--border); border-top-color: var(--accent); border-radius: 50%; animation: spin .6s linear infinite; display: inline-block; }
|
||||
@keyframes spin { to { transform: rotate(360deg); } }
|
||||
.d-none { display: none !important; }
|
||||
.or { text-align: center; color: var(--text-muted); font-size: .85rem; margin: 8px 0; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<div class="header">
|
||||
<h1>Проверка сметы</h1>
|
||||
<a href="/">← Назад к чату</a>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<label>Загрузите YAML-файл проекта:</label>
|
||||
<input type="file" id="yamlFile" accept=".yaml,.yml" style="padding:.4rem;border:1.5px solid var(--border);border-radius:var(--radius);width:100%;font-size:.9rem;background:var(--bg)">
|
||||
<div class="or">или вставьте YAML вручную:</div>
|
||||
<textarea id="yamlInput" placeholder="sections:
|
||||
- name: Глава 1
|
||||
subsections:
|
||||
- items:
|
||||
- code: 28-01-037-02
|
||||
name: Замена шпал
|
||||
unit: шт
|
||||
qty: 100
|
||||
coefficients:
|
||||
definitions:
|
||||
- key: dvizhenie
|
||||
value: 1.40"></textarea>
|
||||
<button class="btn mt-2" onclick="check()" id="checkBtn">
|
||||
<span id="checkSpin" class="spinner d-none"></span> Проверить
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div id="reportCard" class="card d-none">
|
||||
<div class="summary" id="summary"></div>
|
||||
<div id="report"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
function $(id){return document.getElementById(id);}
|
||||
|
||||
$('yamlFile').addEventListener('change', function(e) {
|
||||
const file = e.target.files[0];
|
||||
if (file) {
|
||||
const reader = new FileReader();
|
||||
reader.onload = (ev) => $('yamlInput').value = ev.target.result;
|
||||
reader.readAsText(file);
|
||||
}
|
||||
});
|
||||
|
||||
async function check() {
|
||||
const yaml = $('yamlInput').value.trim();
|
||||
if (!yaml) return;
|
||||
$('checkSpin').classList.remove('d-none'); $('checkBtn').disabled = true;
|
||||
$('reportCard').classList.add('d-none');
|
||||
|
||||
try {
|
||||
const r = await fetch('/api/check/yaml', {
|
||||
method: 'POST', headers: {'Content-Type': 'application/json'},
|
||||
body: JSON.stringify({yaml})
|
||||
});
|
||||
const d = await r.json();
|
||||
|
||||
if (d.error) {
|
||||
$('summary').innerHTML = `<span class="badge badge-err">Ошибка парсинга</span>`;
|
||||
$('report').innerHTML = `<div class="result-item error"><span class="icon">❌</span>${esc(d.error)}</div>`;
|
||||
} else {
|
||||
let sum = '';
|
||||
if (d.errors) sum += `<span class="badge badge-err">${d.errors} ошибок</span>`;
|
||||
if (d.warnings) sum += `<span class="badge badge-warn">${d.warnings} предупреждений</span>`;
|
||||
if (!d.errors && !d.warnings) sum += `<span class="badge badge-info">Всё в порядке</span>`;
|
||||
$('summary').innerHTML = sum;
|
||||
|
||||
let h = '';
|
||||
for (const r of d.results) {
|
||||
const cls = r.level;
|
||||
const icon = r.level === 'error' ? '❌' : r.level === 'warning' ? '⚠️' : 'ℹ️';
|
||||
const pos = r.position ? ` <span style="color:var(--text-muted)">[${esc(r.position)}]</span>` : '';
|
||||
h += `<div class="result-item ${cls}"><span class="icon">${icon}</span><span>${esc(r.message)}${pos}</span></div>`;
|
||||
}
|
||||
$('report').innerHTML = h;
|
||||
}
|
||||
$('reportCard').classList.remove('d-none');
|
||||
} catch(e) {
|
||||
alert(e.message);
|
||||
} finally {
|
||||
$('checkSpin').classList.add('d-none'); $('checkBtn').disabled = false;
|
||||
}
|
||||
}
|
||||
|
||||
function esc(s) { return String(s).replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>'); }
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,219 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Генерация сметы</title>
|
||||
<style>
|
||||
:root {
|
||||
--bg: #f5f0eb; --bg-card: #ffffff; --bg-input: #ffffff;
|
||||
--text: #3a3a3a; --text-muted: #6b6b6b; --text-light: #8b7355;
|
||||
--border: #d4c5b2; --border-light: #ede5db;
|
||||
--accent: #c4463a; --accent-hover: #a83830;
|
||||
--success: #2b8a3e; --warn: #e8590c; --danger: #e03131; --info: #1971c2;
|
||||
--shadow-sm: 0 1px 3px rgba(0,0,0,.05);
|
||||
--shadow-md: 0 4px 16px rgba(0,0,0,.07);
|
||||
--radius: 10px; --radius-lg: 16px;
|
||||
}
|
||||
* { box-sizing: border-box; margin: 0; padding: 0; }
|
||||
body { font-family: 'Inter', -apple-system, sans-serif; background: var(--bg); color: var(--text); -webkit-font-smoothing: antialiased; }
|
||||
.container { max-width: 860px; margin: 24px auto; padding: 0 16px; }
|
||||
.header { display: flex; align-items: center; justify-content: space-between; margin-bottom: 20px; }
|
||||
.header h1 { font-size: 1.2rem; font-weight: 700; }
|
||||
.header a { color: var(--accent); text-decoration: none; font-size: .85rem; font-weight: 500; }
|
||||
.card { background: var(--bg-card); border-radius: var(--radius-lg); box-shadow: var(--shadow-md); padding: 24px; margin-bottom: 16px; }
|
||||
.card h2 { font-size: 1rem; font-weight: 600; margin-bottom: 12px; }
|
||||
label { display: block; font-size: .85rem; font-weight: 500; color: var(--text-muted); margin-bottom: 4px; }
|
||||
input[type="text"], textarea, select { width: 100%; padding: .55rem .75rem; border: 1.5px solid var(--border); border-radius: var(--radius); font-size: .9rem; background: var(--bg); outline: none; transition: border-color .2s; font-family: inherit; }
|
||||
input:focus, textarea:focus, select:focus { border-color: var(--accent); background: var(--bg-card); }
|
||||
textarea { resize: vertical; min-height: 100px; }
|
||||
.row { display: flex; gap: 12px; flex-wrap: wrap; }
|
||||
.row > * { flex: 1; min-width: 140px; }
|
||||
.btn { padding: .55rem 1.2rem; border: none; border-radius: var(--radius); font-size: .85rem; font-weight: 600; cursor: pointer; transition: all .15s; }
|
||||
.btn-primary { background: var(--accent); color: #fff; }
|
||||
.btn-primary:hover { background: var(--accent-hover); }
|
||||
.btn-outline { background: transparent; border: 1.5px solid var(--border); color: var(--text-muted); }
|
||||
.btn-outline:hover { border-color: var(--accent); color: var(--accent); }
|
||||
.btn-success { background: var(--success); color: #fff; }
|
||||
.btn:disabled { opacity: .5; cursor: not-allowed; }
|
||||
.gen-step { display: none; }
|
||||
.gen-step.active { display: block; }
|
||||
.step-badge { display: inline-block; background: var(--accent); color: #fff; padding: 2px 10px; border-radius: 10px; font-size: .78rem; font-weight: 600; }
|
||||
.item { padding: 10px 14px; border: 1.5px solid var(--border-light); border-radius: var(--radius); margin-bottom: 8px; }
|
||||
.item.ok { border-left: 4px solid var(--success); }
|
||||
.item.bad { border-left: 4px solid var(--danger); }
|
||||
.item-head { display: flex; justify-content: space-between; align-items: center; }
|
||||
.item-head strong { font-size: .9rem; }
|
||||
.item-meta { font-size: .82rem; margin-top: 4px; }
|
||||
.score { display: inline-block; padding: 1px 6px; border-radius: 8px; font-size: .72rem; font-weight: 700; }
|
||||
.score-hi { background: #d3f9d8; color: var(--success); }
|
||||
.score-md { background: #fff3bf; color: var(--warn); }
|
||||
.score-lo { background: #ffe3e3; color: var(--danger); }
|
||||
.alt { font-size: .78rem; color: var(--info); cursor: pointer; margin-right: 8px; }
|
||||
.yaml-box { font-family: 'SF Mono', Menlo, monospace; font-size: .8rem; white-space: pre-wrap; background: #2c2c2c; color: #f5f0eb; padding: 16px; border-radius: var(--radius); max-height: 400px; overflow-y: auto; line-height: 1.5; }
|
||||
.error { color: var(--danger); font-size: .85rem; margin-top: 8px; }
|
||||
.spinner { width: 1rem; height: 1rem; border: 2px solid var(--border); border-top-color: var(--accent); border-radius: 50%; animation: spin .6s linear infinite; display: inline-block; }
|
||||
@keyframes spin { to { transform: rotate(360deg); } }
|
||||
.d-none { display: none !important; }
|
||||
.mt-2 { margin-top: 8px; }
|
||||
.mt-3 { margin-top: 12px; }
|
||||
.mb-2 { margin-bottom: 8px; }
|
||||
.chk { display: flex; align-items: center; gap: 6px; margin-top: 16px; }
|
||||
.chk input { width: auto; }
|
||||
.chk label { margin: 0; font-size: .9rem; color: var(--text); }
|
||||
.gap-2 { display: flex; gap: 8px; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<div class="header">
|
||||
<h1>Генерация сметы</h1>
|
||||
<a href="/">← Назад к чату</a>
|
||||
</div>
|
||||
|
||||
<div class="mb-2">
|
||||
<span class="step-badge" id="stepBadge">Шаг 1 из 3</span>
|
||||
<span style="color:var(--text-muted);font-size:.85rem;margin-left:8px" id="stepLabel">Описание работ</span>
|
||||
</div>
|
||||
|
||||
<!-- Step 1 -->
|
||||
<div class="gen-step active card" id="g1">
|
||||
<h2>Опишите работы</h2>
|
||||
<textarea id="desc" placeholder="Замена 500 шпал на перегоне ст. Свиягино — ст. Ружино, очистка щебня 2 км, замена 3 пар рельсовых плетей по 800м..."></textarea>
|
||||
<div class="row mt-3">
|
||||
<div><label>Регион</label><input type="text" id="region" value="Приморский край"></div>
|
||||
<div><label>Поездов/сут</label><input type="text" id="trains" value="91-108"></div>
|
||||
</div>
|
||||
<div class="row mt-2">
|
||||
<div class="chk"><input type="checkbox" id="vl" checked><label for="vl">Зона ВЛ</label></div>
|
||||
<div class="chk"><input type="checkbox" id="okno" checked><label for="okno">В "окно"</label></div>
|
||||
</div>
|
||||
<button class="btn btn-primary mt-3" onclick="parse()" id="parseBtn">
|
||||
<span id="parseSpin" class="spinner d-none"></span> Разобрать на позиции
|
||||
</button>
|
||||
<div id="parseErr" class="error"></div>
|
||||
</div>
|
||||
|
||||
<!-- Step 2 -->
|
||||
<div class="gen-step card" id="g2">
|
||||
<h2>Проверьте позиции и расценки</h2>
|
||||
<div id="items"></div>
|
||||
<div class="gap-2 mt-3">
|
||||
<button class="btn btn-outline" onclick="show(1)">Назад</button>
|
||||
<button class="btn btn-primary" onclick="genYaml()" id="yamlBtn">
|
||||
<span id="yamlSpin" class="spinner d-none"></span> Сформировать смету
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Step 3 -->
|
||||
<div class="gen-step card" id="g3">
|
||||
<h2>Конфигурация сметы</h2>
|
||||
<div id="yamlOut" class="yaml-box"></div>
|
||||
<div class="gap-2 mt-3">
|
||||
<button class="btn btn-outline" onclick="show(2)">Назад</button>
|
||||
<button class="btn btn-success" onclick="calcExcel()" id="calcBtn">
|
||||
<span id="calcSpin" class="spinner d-none"></span> Рассчитать и скачать Excel
|
||||
</button>
|
||||
<button class="btn btn-outline" onclick="copy()">Скопировать YAML</button>
|
||||
</div>
|
||||
<div id="calcResult" class="mt-2"></div>
|
||||
</div>
|
||||
|
||||
<!-- Step 4 -->
|
||||
<div class="gen-step card" id="g4">
|
||||
<h2>Смета готова</h2>
|
||||
<p>Расчёт выполнен. Скачайте файл Excel.</p>
|
||||
<div id="downloadInfo" class="mt-2"></div>
|
||||
<div class="gap-2 mt-3">
|
||||
<button class="btn btn-outline" onclick="show(3)">Назад к YAML</button>
|
||||
<a id="downloadLink" class="btn btn-success" href="#" style="text-decoration:none">Скачать Excel</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
let matched=[], yamlStr='';
|
||||
function $(id){return document.getElementById(id);}
|
||||
function esc(s){return s.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>');}
|
||||
|
||||
function show(n){
|
||||
for(let i=1;i<=4;i++) $('g'+i).classList.toggle('active',i===n);
|
||||
$('stepBadge').textContent=`Шаг ${n} из 4`;
|
||||
const L={1:'Описание работ',2:'Проверка позиций',3:'Конфигурация',4:'Скачать Excel'};
|
||||
$('stepLabel').textContent=L[n];
|
||||
}
|
||||
|
||||
async function parse(){
|
||||
const desc=$('desc').value.trim();
|
||||
if(!desc){$('parseErr').textContent='Введите описание работ';return;}
|
||||
$('parseSpin').classList.remove('d-none'); $('parseBtn').disabled=true; $('parseErr').textContent='';
|
||||
try{
|
||||
const r1=await fetch('/api/gen/parse',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({description:desc})});
|
||||
const d1=await r1.json();
|
||||
if(d1.error){$('parseErr').textContent=d1.error;return;}
|
||||
if(!d1.items.length){$('parseErr').textContent='Не удалось разобрать описание';return;}
|
||||
|
||||
const r2=await fetch('/api/gen/match',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({items:d1.items})});
|
||||
const d2=await r2.json();
|
||||
if(d2.error){$('parseErr').textContent=d2.error;return;}
|
||||
matched=d2.matched;
|
||||
|
||||
let h='';
|
||||
for(const m of matched){
|
||||
const ok=m.score>0.3;
|
||||
const sc=m.score>0.6?'score-hi':m.score>0.3?'score-md':'score-lo';
|
||||
h+=`<div class="item ${ok?'ok':'bad'}">
|
||||
<div class="item-head"><strong>${esc(m.description)}</strong><span>${esc(m.unit||'')} x ${m.qty||'?'}</span></div>
|
||||
<div class="item-meta"><span class="score ${sc}">${(m.score*100).toFixed(0)}%</span> <strong>${esc(m.gesn_code)}</strong> ${esc(m.gesn_name||'')}</div>`;
|
||||
if(m.alternatives&&m.alternatives.length){h+='<div class="mt-2">';for(const a of m.alternatives)h+=`<span class="alt">${a.code} (${(a.score*100).toFixed(0)}%)</span>`;h+='</div>';}
|
||||
if(m.note)h+=`<div style="font-size:.82rem;color:var(--text-muted);margin-top:4px">${esc(m.note)}</div>`;
|
||||
h+='</div>';
|
||||
}
|
||||
$('items').innerHTML=h;
|
||||
show(2);
|
||||
}catch(e){$('parseErr').textContent=e.message;}
|
||||
finally{$('parseSpin').classList.add('d-none');$('parseBtn').disabled=false;}
|
||||
}
|
||||
|
||||
async function genYaml(){
|
||||
$('yamlSpin').classList.remove('d-none'); $('yamlBtn').disabled=true;
|
||||
try{
|
||||
const r=await fetch('/api/gen/yaml',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({matched_items:matched,region:$('region').value,trains_per_day:$('trains').value,vl_zone:$('vl').checked,okno:$('okno').checked})});
|
||||
const d=await r.json();
|
||||
if(d.error){alert(d.error);return;}
|
||||
yamlStr=d.yaml;
|
||||
$('yamlOut').textContent=yamlStr;
|
||||
show(3);
|
||||
}catch(e){alert(e.message);}
|
||||
finally{$('yamlSpin').classList.add('d-none');$('yamlBtn').disabled=false;}
|
||||
}
|
||||
|
||||
async function calcExcel(){
|
||||
$('calcSpin').classList.remove('d-none'); $('calcBtn').disabled=true; $('calcResult').innerHTML='';
|
||||
try{
|
||||
const r=await fetch('/api/gen/calculate',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({yaml:yamlStr})});
|
||||
const d=await r.json();
|
||||
if(d.error){
|
||||
$('calcResult').innerHTML=`<div style="color:var(--danger);font-size:.85rem">${esc(d.error)}</div>`;
|
||||
return;
|
||||
}
|
||||
$('downloadLink').href=d.download_url;
|
||||
$('downloadInfo').innerHTML=`<p>Позиций: ${d.positions}</p>`;
|
||||
show(4);
|
||||
}catch(e){$('calcResult').innerHTML=`<div style="color:var(--danger)">${e.message}</div>`;}
|
||||
finally{$('calcSpin').classList.add('d-none');$('calcBtn').disabled=false;}
|
||||
}
|
||||
|
||||
function copy(){
|
||||
navigator.clipboard.writeText(yamlStr).then(()=>{
|
||||
const b=event.target; b.textContent='Скопировано!'; setTimeout(()=>b.textContent='Скопировать',2000);
|
||||
});
|
||||
}
|
||||
function dl(){
|
||||
const b=new Blob([yamlStr],{type:'text/yaml'}), u=URL.createObjectURL(b), a=document.createElement('a');
|
||||
a.href=u; a.download='estimate.yaml'; a.click(); URL.revokeObjectURL(u);
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,115 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Справочники</title>
|
||||
<style>
|
||||
:root {
|
||||
--bg: #f5f0eb; --bg-card: #ffffff;
|
||||
--text: #3a3a3a; --text-muted: #6b6b6b; --text-light: #8b7355;
|
||||
--border: #d4c5b2; --border-light: #ede5db;
|
||||
--accent: #c4463a; --accent-hover: #a83830;
|
||||
--success: #2b8a3e; --warn: #e8590c; --danger: #e03131; --info: #1971c2;
|
||||
--shadow-sm: 0 1px 3px rgba(0,0,0,.05);
|
||||
--shadow-md: 0 4px 16px rgba(0,0,0,.07);
|
||||
--radius: 10px; --radius-lg: 16px;
|
||||
}
|
||||
* { box-sizing: border-box; margin: 0; padding: 0; }
|
||||
body { font-family: 'Inter', -apple-system, sans-serif; background: var(--bg); color: var(--text); }
|
||||
.container { max-width: 860px; margin: 24px auto; padding: 0 16px; }
|
||||
.header { display: flex; align-items: center; justify-content: space-between; margin-bottom: 20px; }
|
||||
.header h1 { font-size: 1.2rem; font-weight: 700; }
|
||||
.header a { color: var(--accent); text-decoration: none; font-size: .85rem; font-weight: 500; }
|
||||
.card { background: var(--bg-card); border-radius: var(--radius-lg); box-shadow: var(--shadow-md); padding: 24px; margin-bottom: 16px; }
|
||||
label { display: block; font-size: .85rem; font-weight: 500; color: var(--text-muted); margin-bottom: 4px; }
|
||||
input, select { width: 100%; padding: .55rem .75rem; border: 1.5px solid var(--border); border-radius: var(--radius); font-size: .9rem; background: var(--bg); outline: none; }
|
||||
input:focus { border-color: var(--accent); background: var(--bg-card); }
|
||||
.tabs { display: flex; gap: 4px; margin-bottom: 16px; }
|
||||
.tab { padding: .5rem 1rem; border: 1.5px solid var(--border); border-radius: var(--radius); cursor: pointer; font-size: .85rem; font-weight: 500; color: var(--text-muted); background: transparent; transition: all .15s; }
|
||||
.tab.active { background: var(--accent); color: #fff; border-color: var(--accent); }
|
||||
.tab:hover:not(.active) { border-color: var(--accent); color: var(--accent); }
|
||||
.btn { padding: .55rem 1.2rem; border: none; border-radius: var(--radius); font-size: .85rem; font-weight: 600; cursor: pointer; background: var(--accent); color: #fff; }
|
||||
.btn:hover { background: var(--accent-hover); }
|
||||
.result { padding: 10px 14px; border-left: 3px solid var(--info); background: var(--bg); border-radius: 0 var(--radius) var(--radius) 0; margin-bottom: 6px; font-size: .88rem; }
|
||||
.result strong { font-weight: 700; }
|
||||
.score { display: inline-block; padding: 1px 6px; border-radius: 8px; font-size: .72rem; font-weight: 700; }
|
||||
.score-hi { background: #d3f9d8; color: var(--success); }
|
||||
.score-md { background: #fff3bf; color: var(--warn); }
|
||||
.score-lo { background: #ffe3e3; color: var(--danger); }
|
||||
.pct { font-size: 1.1rem; font-weight: 700; color: var(--accent); }
|
||||
.muted { color: var(--text-muted); font-size: .82rem; }
|
||||
.mt-2 { margin-top: 8px; }
|
||||
.mt-3 { margin-top: 12px; }
|
||||
.input-row { display: flex; gap: 8px; }
|
||||
.input-row input { flex: 1; }
|
||||
#results { min-height: 100px; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<div class="header">
|
||||
<h1>Справочники</h1>
|
||||
<a href="/">← Назад к чату</a>
|
||||
</div>
|
||||
|
||||
<div class="tabs">
|
||||
<button class="tab active" onclick="setTab('gesn')">Поиск ГЭСН</button>
|
||||
<button class="tab" onclick="setTab('nr')">НР</button>
|
||||
<button class="tab" onclick="setTab('sp')">СП</button>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<div class="input-row">
|
||||
<input type="text" id="q" placeholder="Введите запрос..." onkeydown="if(event.key==='Enter')search()">
|
||||
<button class="btn" onclick="search()">Найти</button>
|
||||
</div>
|
||||
<div id="results" class="mt-3"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
let mode = 'gesn';
|
||||
|
||||
function setTab(m) {
|
||||
mode = m;
|
||||
document.querySelectorAll('.tab').forEach((t, i) => t.classList.toggle('active', ['gesn','nr','sp'][i] === m));
|
||||
document.getElementById('q').placeholder = mode === 'gesn' ? 'Описание работ...' : 'Вид работ...';
|
||||
document.getElementById('results').innerHTML = '';
|
||||
document.getElementById('q').focus();
|
||||
}
|
||||
|
||||
async function search() {
|
||||
const q = document.getElementById('q').value.trim();
|
||||
if (!q) return;
|
||||
const url = mode === 'gesn' ? '/api/ref/search' : `/api/ref/${mode}`;
|
||||
const body = mode === 'gesn' ? {query: q, top_k: 10} : {query: q};
|
||||
const r = await fetch(url, {method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify(body)});
|
||||
const d = await r.json();
|
||||
|
||||
let h = '';
|
||||
if (mode === 'gesn') {
|
||||
if (!d.results || !d.results.length) { h = '<p class="muted">Ничего не найдено</p>'; }
|
||||
else {
|
||||
for (const r of d.results) {
|
||||
const sc = r.score > 0.6 ? 'score-hi' : r.score > 0.3 ? 'score-md' : 'score-lo';
|
||||
h += `<div class="result"><strong>ГЭСН ${esc(r.code)}</strong> <span class="score ${sc}">${(r.score*100).toFixed(0)}%</span><br>${esc(r.name)}<br><span class="muted">Ед: ${esc(r.unit)} | сб.${esc(r.collection)}</span></div>`;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if (!d.results || !d.results.length) { h = `<p class="muted">${d.label}: ничего не найдено</p>`; }
|
||||
else {
|
||||
h = `<p class="muted">${d.label} — найдено: ${d.count}</p>`;
|
||||
for (const r of d.results) {
|
||||
h += `<div class="result">п.${esc(r.key)}. ${esc(r.name)} — <span class="pct">${r.percent}%</span> от ФОТ</div>`;
|
||||
}
|
||||
}
|
||||
}
|
||||
document.getElementById('results').innerHTML = h;
|
||||
}
|
||||
|
||||
function esc(s) { return String(s).replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>'); }
|
||||
document.getElementById('q').focus();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
-204
@@ -1,204 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Генератор ССР</title>
|
||||
<style>
|
||||
:root { --bg: #f5f0eb; --card: #fff; --text: #3a3a3a; --muted: #6b6b6b; --accent: #c4463a; --border: #d4c5b2; --radius: 10px; --green: #2d8a56; }
|
||||
* { box-sizing: border-box; margin: 0; padding: 0; }
|
||||
body { font-family: 'Inter', -apple-system, sans-serif; background: var(--bg); color: var(--text); min-height: 100vh; padding: 2rem; }
|
||||
.container { max-width: 900px; margin: 0 auto; }
|
||||
h1 { font-size: 1.3rem; margin-bottom: .3rem; }
|
||||
.subtitle { color: var(--muted); font-size: .9rem; margin-bottom: 1.5rem; }
|
||||
.badge { display: inline-block; background: var(--green); color: #fff; font-size: .7rem; padding: 2px 8px; border-radius: 12px; vertical-align: middle; margin-left: .5rem; }
|
||||
.card { background: var(--card); border-radius: var(--radius); padding: 1.5rem; margin-bottom: 1rem; box-shadow: 0 1px 4px rgba(0,0,0,.06); }
|
||||
.card.hidden { display: none; }
|
||||
label { display: block; font-weight: 600; margin-bottom: .4rem; font-size: .9rem; }
|
||||
.hint { color: var(--muted); font-size: .8rem; margin-bottom: .6rem; }
|
||||
input[type=file] { width: 100%; padding: .5rem; border: 1.5px dashed var(--border); border-radius: var(--radius); margin-bottom: 1rem; }
|
||||
input[type=number] { width: 80px; padding: .4rem; border: 1.5px solid var(--border); border-radius: 6px; font-size: .9rem; }
|
||||
.params-row { display: flex; flex-wrap: wrap; gap: 1rem; margin: .8rem 0; }
|
||||
.param { display: flex; flex-direction: column; }
|
||||
.param label { font-size: .8rem; font-weight: 500; }
|
||||
button { padding: .7rem 1.5rem; background: var(--accent); color: #fff; border: none; border-radius: var(--radius); font-size: .95rem; font-weight: 600; cursor: pointer; }
|
||||
button:hover { background: #a83830; }
|
||||
button:disabled { background: var(--border); cursor: not-allowed; }
|
||||
.back { display: inline-block; margin-bottom: 1rem; color: var(--accent); text-decoration: none; font-size: .85rem; }
|
||||
.spinner { display: inline-block; width: 16px; height: 16px; border: 2px solid var(--border); border-top-color: var(--accent); border-radius: 50%; animation: spin .8s linear infinite; vertical-align: middle; margin-right: 6px; }
|
||||
@keyframes spin { to { transform: rotate(360deg); } }
|
||||
.error { color: var(--accent); margin-top: .5rem; font-size: .85rem; }
|
||||
.stats { display: flex; gap: 1rem; margin: .5rem 0; font-size: .85rem; color: var(--muted); flex-wrap: wrap; }
|
||||
.stats span { background: #ede5db; padding: 3px 10px; border-radius: 6px; }
|
||||
.btn-download { background: var(--green); margin-top: 1rem; font-size: 1rem; padding: .8rem 2rem; }
|
||||
.btn-download:hover { background: #246e45; }
|
||||
#preview-frame { width: 100%; border: 1px solid var(--border); border-radius: var(--radius); min-height: 400px; background: #fff; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<a class="back" href="/">← Вернуться в чат</a>
|
||||
<h1>Генератор ССР <span class="badge">из GGE</span></h1>
|
||||
<p class="subtitle">Загрузите ZIP с GGE-файлами — получите сводный сметный расчёт (9 листов) с превью</p>
|
||||
|
||||
<!-- Step 1: Upload -->
|
||||
<div class="card" id="step-upload">
|
||||
<label>1. Архив с GGE-файлами (.zip) <span style="color:var(--accent)">*</span></label>
|
||||
<p class="hint">ZIP со всеми локальными сметами в формате GGE (до 2000 файлов)</p>
|
||||
<input type="file" id="zip-file" accept=".zip">
|
||||
|
||||
<label>2. Сводный файл (.xlsx) — <em>необязательно</em></label>
|
||||
<p class="hint">Ваш существующий ССР/РАСПРЕДЕЛЕНИЕ. Скрипт заполнит GGE-данные в лист РАСПРЕДЕЛЕНИЕ, остальные листы не тронет.<br>
|
||||
Если не указан — будет сгенерирован новый файл с нуля (9 листов).</p>
|
||||
<input type="file" id="xlsx-file" accept=".xlsx,.xls">
|
||||
|
||||
<label>Параметры расчёта <span class="hint" style="display:inline">(для генерации с нуля)</span></label>
|
||||
<div class="params-row" id="params-row">
|
||||
<div class="param">
|
||||
<label>Зимнее, %</label>
|
||||
<input type="number" id="p-winter" value="3.2" step="0.1" min="0" max="20">
|
||||
</div>
|
||||
<div class="param">
|
||||
<label>Стройконтроль, %</label>
|
||||
<input type="number" id="p-control" value="0.55" step="0.01" min="0" max="5">
|
||||
</div>
|
||||
<div class="param">
|
||||
<label>Резерв, %</label>
|
||||
<input type="number" id="p-reserve" value="1.0" step="0.5" min="0" max="10">
|
||||
</div>
|
||||
<div class="param">
|
||||
<label>НДС, %</label>
|
||||
<input type="number" id="p-vat" value="22" step="1" min="0" max="30">
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<button id="btn-upload" onclick="doUpload()">Заполнить / Генерировать ССР</button>
|
||||
<div id="upload-error" class="error"></div>
|
||||
</div>
|
||||
|
||||
<!-- Step 2: Processing -->
|
||||
<div class="card hidden" id="step-processing">
|
||||
<span class="spinner"></span> Парсинг GGE-файлов и генерация ССР...
|
||||
<p class="hint" style="margin-top:.5rem">Это может занять 10-30 секунд для крупных архивов</p>
|
||||
</div>
|
||||
|
||||
<!-- Step 3: Preview + Download -->
|
||||
<div class="card hidden" id="step-result">
|
||||
<h2 style="margin-bottom:.5rem">Результат</h2>
|
||||
<div id="stats" class="stats"></div>
|
||||
<button class="btn-download" id="btn-download" onclick="doDownload()">Скачать XLSX (9 листов)</button>
|
||||
<hr style="margin:1rem 0;border:none;border-top:1px solid var(--border)">
|
||||
<h2 style="margin-bottom:.5rem">Превью</h2>
|
||||
<iframe id="preview-frame" sandbox="allow-same-origin"></iframe>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
let token = localStorage.getItem('token');
|
||||
// Validate token on load
|
||||
(async () => {
|
||||
if (!token) { location.href = '/'; return; }
|
||||
try {
|
||||
const r = await fetch('/api/history?limit=1', {headers:{'Authorization':'Bearer '+token}});
|
||||
if (r.ok) return;
|
||||
} catch {}
|
||||
const rt = localStorage.getItem('refresh_token');
|
||||
if (rt) {
|
||||
try {
|
||||
const r = await fetch('/api/refresh', {method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify({refresh_token:rt})});
|
||||
if (r.ok) { const d = await r.json(); token = d.token; localStorage.setItem('token', token); return; }
|
||||
} catch {}
|
||||
}
|
||||
localStorage.removeItem('token'); localStorage.removeItem('refresh_token');
|
||||
location.href = '/';
|
||||
})();
|
||||
|
||||
let currentJobId = null;
|
||||
|
||||
async function doUpload() {
|
||||
const zipInput = document.getElementById('zip-file');
|
||||
const errorEl = document.getElementById('upload-error');
|
||||
errorEl.textContent = '';
|
||||
|
||||
if (!zipInput.files.length) {
|
||||
errorEl.textContent = 'Выберите ZIP-файл';
|
||||
return;
|
||||
}
|
||||
|
||||
const xlsxInput = document.getElementById('xlsx-file');
|
||||
const hasXlsx = xlsxInput.files.length > 0;
|
||||
|
||||
const fd = new FormData();
|
||||
fd.append('zip_file', zipInput.files[0]);
|
||||
if (hasXlsx) {
|
||||
fd.append('xlsx_file', xlsxInput.files[0]);
|
||||
fd.append('mode', 'fill'); // fill existing file
|
||||
} else {
|
||||
fd.append('mode', 'generate'); // generate from scratch
|
||||
}
|
||||
fd.append('winter_pct', document.getElementById('p-winter').value);
|
||||
fd.append('control_pct', document.getElementById('p-control').value);
|
||||
fd.append('reserve_pct', document.getElementById('p-reserve').value);
|
||||
fd.append('vat_pct', document.getElementById('p-vat').value);
|
||||
|
||||
document.getElementById('btn-upload').disabled = true;
|
||||
document.getElementById('step-processing').classList.remove('hidden');
|
||||
|
||||
try {
|
||||
const resp = await fetch('/api/ssr/upload', {
|
||||
method: 'POST',
|
||||
headers: { 'Authorization': 'Bearer ' + token },
|
||||
body: fd,
|
||||
});
|
||||
|
||||
if (!resp.ok) {
|
||||
const err = await resp.json();
|
||||
throw new Error(err.detail || 'Upload failed');
|
||||
}
|
||||
|
||||
const data = await resp.json();
|
||||
currentJobId = data.job_id;
|
||||
|
||||
// Show stats
|
||||
const s = data.stats;
|
||||
document.getElementById('stats').innerHTML =
|
||||
`<span>Смет: ${s.estimates}</span>` +
|
||||
`<span>Глав: ${s.chapters}</span>` +
|
||||
`<span>Листов: ${s.sheets}</span>` +
|
||||
`<span>СР-10: ${s.sr10_eff_pct.toFixed(3)}%</span>` +
|
||||
`<span>Итого с НДС: ${Number(s.total_vat).toLocaleString('ru-RU', {minimumFractionDigits:2})} тыс.руб.</span>`;
|
||||
|
||||
// Show preview in iframe
|
||||
const frame = document.getElementById('preview-frame');
|
||||
frame.srcdoc = data.preview_html;
|
||||
frame.style.height = '600px';
|
||||
|
||||
document.getElementById('step-processing').classList.add('hidden');
|
||||
document.getElementById('step-result').classList.remove('hidden');
|
||||
|
||||
} catch (e) {
|
||||
errorEl.textContent = e.message;
|
||||
document.getElementById('step-processing').classList.add('hidden');
|
||||
document.getElementById('btn-upload').disabled = false;
|
||||
}
|
||||
}
|
||||
|
||||
function doDownload() {
|
||||
if (!currentJobId) return;
|
||||
const a = document.createElement('a');
|
||||
a.href = `/api/ssr/download/${currentJobId}`;
|
||||
// Add auth header via fetch+blob
|
||||
fetch(a.href, { headers: { 'Authorization': 'Bearer ' + token } })
|
||||
.then(r => r.blob())
|
||||
.then(blob => {
|
||||
const url = URL.createObjectURL(blob);
|
||||
const link = document.createElement('a');
|
||||
link.href = url;
|
||||
link.download = 'ssr_generated.xlsx';
|
||||
link.click();
|
||||
URL.revokeObjectURL(url);
|
||||
});
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,235 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Агрегатор xlsx</title>
|
||||
<style>
|
||||
:root {
|
||||
--bg: #f5f0eb; --bg-card: #ffffff; --bg-input: #ffffff;
|
||||
--text: #3a3a3a; --text-muted: #6b6b6b; --text-light: #8b7355;
|
||||
--border: #d4c5b2; --border-light: #ede5db;
|
||||
--accent: #c4463a; --accent-hover: #a83830;
|
||||
--success: #2b8a3e; --info: #1971c2;
|
||||
--shadow-sm: 0 1px 3px rgba(0,0,0,.05);
|
||||
--shadow-md: 0 4px 16px rgba(0,0,0,.07);
|
||||
--radius: 10px; --radius-lg: 16px;
|
||||
}
|
||||
* { box-sizing: border-box; margin: 0; padding: 0; }
|
||||
body { font-family: 'Inter', -apple-system, sans-serif; background: var(--bg); color: var(--text); -webkit-font-smoothing: antialiased; }
|
||||
.container { max-width: 860px; margin: 24px auto; padding: 0 16px; }
|
||||
.header { display: flex; align-items: center; justify-content: space-between; margin-bottom: 20px; }
|
||||
.header h1 { font-size: 1.2rem; font-weight: 700; }
|
||||
.header a { color: var(--accent); text-decoration: none; font-size: .85rem; font-weight: 500; }
|
||||
.card { background: var(--bg-card); border-radius: var(--radius-lg); box-shadow: var(--shadow-md); padding: 24px; margin-bottom: 16px; }
|
||||
.card h2 { font-size: 1rem; font-weight: 600; margin-bottom: 12px; color: var(--text); }
|
||||
label { display: block; font-size: .85rem; font-weight: 500; color: var(--text-muted); margin-bottom: 4px; }
|
||||
input[type="text"], input[type="file"], select { width: 100%; padding: .55rem .75rem; border: 1.5px solid var(--border); border-radius: var(--radius); font-size: .9rem; background: var(--bg); outline: none; transition: border-color .2s; }
|
||||
input:focus, select:focus { border-color: var(--accent); background: var(--bg-card); }
|
||||
.row { display: flex; gap: 12px; }
|
||||
.row > * { flex: 1; }
|
||||
.btn { padding: .55rem 1.2rem; border: none; border-radius: var(--radius); font-size: .85rem; font-weight: 600; cursor: pointer; transition: all .15s; }
|
||||
.btn-primary { background: var(--accent); color: #fff; }
|
||||
.btn-primary:hover { background: var(--accent-hover); }
|
||||
.btn-outline { background: transparent; border: 1.5px solid var(--border); color: var(--text-muted); }
|
||||
.btn-outline:hover { border-color: var(--accent); color: var(--accent); }
|
||||
.btn-success { background: var(--success); color: #fff; }
|
||||
.btn:disabled { opacity: .5; cursor: not-allowed; }
|
||||
.step-bar { display: flex; gap: 4px; margin-bottom: 20px; }
|
||||
.step-dot { flex: 1; height: 5px; border-radius: 3px; background: var(--border-light); transition: background .3s; }
|
||||
.step-dot.done { background: var(--success); }
|
||||
.step-dot.current { background: var(--accent); }
|
||||
.wiz-step { display: none; }
|
||||
.wiz-step.active { display: block; }
|
||||
.preview-table { max-height: 280px; overflow-y: auto; font-size: .82rem; border: 1px solid var(--border-light); border-radius: var(--radius); }
|
||||
.preview-table table { width: 100%; border-collapse: collapse; }
|
||||
.preview-table th { background: var(--bg); font-weight: 600; position: sticky; top: 0; }
|
||||
.preview-table td, .preview-table th { padding: 6px 10px; border-bottom: 1px solid var(--border-light); white-space: nowrap; }
|
||||
.status-add { color: var(--success); font-weight: 600; }
|
||||
.status-update { color: var(--info); }
|
||||
.badge { display: inline-block; padding: 2px 8px; border-radius: 10px; font-size: .75rem; font-weight: 600; }
|
||||
.badge-info { background: #dbeafe; color: var(--info); }
|
||||
.badge-success { background: #d3f9d8; color: var(--success); }
|
||||
.badge-muted { background: var(--border-light); color: var(--text-muted); }
|
||||
.error { color: #e03131; font-size: .85rem; margin-top: 8px; }
|
||||
.file-list { font-size: .85rem; color: var(--text-muted); }
|
||||
.spinner { width: 1rem; height: 1rem; border: 2px solid var(--border); border-top-color: var(--accent); border-radius: 50%; animation: spin .6s linear infinite; display: inline-block; }
|
||||
@keyframes spin { to { transform: rotate(360deg); } }
|
||||
.d-none { display: none !important; }
|
||||
.mt-2 { margin-top: 8px; }
|
||||
.mt-3 { margin-top: 12px; }
|
||||
.mb-2 { margin-bottom: 8px; }
|
||||
.nav-bottom { display: flex; justify-content: space-between; margin-top: 16px; }
|
||||
.alert-success { background: #d3f9d8; border: 1px solid #69db7c; border-radius: var(--radius); padding: 12px; color: var(--success); }
|
||||
.alert-success a { color: var(--success); font-weight: 600; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<div class="header">
|
||||
<h1>Агрегатор xlsx</h1>
|
||||
<a href="/">← Назад к чату</a>
|
||||
</div>
|
||||
|
||||
<div class="step-bar" id="stepBar"></div>
|
||||
|
||||
<!-- Step 1 -->
|
||||
<div class="wiz-step active card" id="s1">
|
||||
<h2>Загрузка файлов</h2>
|
||||
<div class="mb-2"><label>ZIP-архив с источниками</label><input type="file" id="fZip" accept=".zip"></div>
|
||||
<div class="mb-2"><label>Целевой файл (.xlsx)</label><input type="file" id="fTarget" accept=".xlsx"></div>
|
||||
<button class="btn btn-primary" onclick="upload()"><span id="upSpin" class="spinner d-none"></span> Загрузить</button>
|
||||
<div id="upErr" class="error"></div>
|
||||
<div id="upInfo" class="file-list mt-2"></div>
|
||||
</div>
|
||||
|
||||
<!-- Step 2 -->
|
||||
<div class="wiz-step card" id="s2">
|
||||
<h2>Критерий поиска</h2>
|
||||
<div class="row mb-2">
|
||||
<div><label>Лист</label><select id="srcSheet"></select></div>
|
||||
<div><label>Колонка</label><select id="srcCol"></select></div>
|
||||
<div><label>Ключевое слово</label><input type="text" id="srcKw" value="разряд"></div>
|
||||
</div>
|
||||
<button class="btn btn-outline" onclick="analyze()">Найти</button>
|
||||
<div id="searchPrev" class="mt-2"></div>
|
||||
</div>
|
||||
|
||||
<!-- Step 3 -->
|
||||
<div class="wiz-step card" id="s3">
|
||||
<h2>Колонка значений</h2>
|
||||
<div class="mb-2"><label>Из какой колонки брать числа?</label><select id="valCol"></select></div>
|
||||
<button class="btn btn-outline" onclick="analyzeVal()">Превью</button>
|
||||
<div id="valPrev" class="mt-2"></div>
|
||||
</div>
|
||||
|
||||
<!-- Step 4 -->
|
||||
<div class="wiz-step card" id="s4">
|
||||
<h2>Сопоставление с целевым</h2>
|
||||
<div class="row"><div><label>Лист</label><select id="tgtSheet"></select></div><div><label>Колонка</label><select id="matchCol"></select></div></div>
|
||||
</div>
|
||||
|
||||
<!-- Step 5 -->
|
||||
<div class="wiz-step card" id="s5">
|
||||
<h2>Действие</h2>
|
||||
<div class="row">
|
||||
<div><label>Операция</label><select id="action"><option value="sum">Суммировать</option><option value="replace">Заменить</option><option value="max">Максимум</option><option value="min">Минимум</option></select></div>
|
||||
<div><label>Записать в колонку</label><select id="writeCol"></select></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Step 6 -->
|
||||
<div class="wiz-step card" id="s6">
|
||||
<h2>Ненайденные строки</h2>
|
||||
<select id="unmatched" style="max-width:300px"><option value="add">Добавить новые строки</option><option value="skip">Пропустить</option></select>
|
||||
</div>
|
||||
|
||||
<!-- Step 7 -->
|
||||
<div class="wiz-step card" id="s7">
|
||||
<h2>Превью и подтверждение</h2>
|
||||
<div id="prevLoad" class="d-none" style="text-align:center;padding:20px"><div class="spinner"></div><p class="mt-2" style="color:var(--text-muted)">Вычисляю...</p></div>
|
||||
<div id="prevResult"></div>
|
||||
<div id="prevSummary" class="mt-2"></div>
|
||||
<button class="btn btn-success mt-3 d-none" id="runBtn" onclick="run()"><span id="runSpin" class="spinner d-none"></span> Применить и скачать</button>
|
||||
<div id="runResult" class="mt-2"></div>
|
||||
</div>
|
||||
|
||||
<div class="nav-bottom">
|
||||
<button class="btn btn-outline" id="prevBtn" onclick="prev()" disabled>Назад</button>
|
||||
<button class="btn btn-primary" id="nextBtn" onclick="next()" disabled>Далее</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
const N=7; let step=1,sid=null,src=null,tgt=null;
|
||||
|
||||
function ui(){
|
||||
for(let i=1;i<=N;i++) document.getElementById('s'+i).classList.toggle('active',i===step);
|
||||
document.getElementById('prevBtn').disabled=step===1;
|
||||
document.getElementById('nextBtn').disabled=!ok();
|
||||
const b=document.getElementById('stepBar'); b.innerHTML='';
|
||||
for(let i=1;i<=N;i++){const c=i<step?'done':i===step?'current':''; b.innerHTML+=`<div class="step-dot ${c}"></div>`;}
|
||||
if(step===7) loadPreview();
|
||||
}
|
||||
function ok(){
|
||||
if(step===1)return!!sid; if(step===2)return!!$('srcCol').value;
|
||||
if(step===3)return!!$('valCol').value; if(step===4)return!!$('matchCol').value;
|
||||
return step===5||step===6;
|
||||
}
|
||||
function next(){if(step<N){step++;ui();}} function prev(){if(step>1){step--;ui();}}
|
||||
function $(id){return document.getElementById(id);}
|
||||
|
||||
async function upload(){
|
||||
const z=$('fZip').files[0], t=$('fTarget').files[0];
|
||||
if(!z||!t){$('upErr').textContent='Выберите оба файла';return;}
|
||||
$('upSpin').classList.remove('d-none'); $('upErr').textContent='';
|
||||
const fd=new FormData(); fd.append('zip_file',z); fd.append('target_file',t);
|
||||
try{
|
||||
const r=await fetch('/api/wizard/upload',{method:'POST',body:fd});
|
||||
if(!r.ok){const e=await r.json();throw new Error(e.detail||'Ошибка загрузки');}
|
||||
const d=await r.json(); sid=d.session_id; src=d.sources; tgt=d.target;
|
||||
let h=`<p><strong>Источники:</strong> ${src.length} файл(ов)</p><ul>`;
|
||||
for(const s of src) h+=`<li>${s.filename} — ${s.sheets.map(sh=>sh.name+' ('+sh.row_count+')').join(', ')}</li>`;
|
||||
h+=`</ul><p><strong>Целевой:</strong> ${tgt.filename}</p>`;
|
||||
$('upInfo').innerHTML=h; popSrc(); popTgt(); ui();
|
||||
}catch(e){$('upErr').textContent=e.message;}
|
||||
finally{$('upSpin').classList.add('d-none');}
|
||||
}
|
||||
|
||||
function popSrc(){
|
||||
const ss=$('srcSheet'),sc=$('srcCol'),vc=$('valCol'); ss.innerHTML='';sc.innerHTML='';vc.innerHTML='';
|
||||
const sheets=new Set(); for(const s of src) for(const sh of s.sheets) sheets.add(sh.name);
|
||||
for(const n of sheets) ss.innerHTML+=`<option>${n}</option>`;
|
||||
const cols=src[0].sheets[0].columns;
|
||||
for(const c of cols){const l=`${c.letter}: ${c.header} (${c.type})`;sc.innerHTML+=`<option value="${c.letter}">${l}</option>`;vc.innerHTML+=`<option value="${c.letter}">${l}</option>`;}
|
||||
const tc=cols.filter(c=>c.type==='text'),nc=cols.filter(c=>c.type==='number');
|
||||
const nl=tc.find(c=>/наименован/i.test(c.header)); if(nl)sc.value=nl.letter; else if(tc.length)sc.value=tc[0].letter;
|
||||
const ql=nc.find(c=>/количеств|кол/i.test(c.header)); if(ql)vc.value=ql.letter; else if(nc.length)vc.value=nc[0].letter;
|
||||
}
|
||||
function popTgt(){
|
||||
const ts=$('tgtSheet'),mc=$('matchCol'),wc=$('writeCol'); ts.innerHTML='';mc.innerHTML='';wc.innerHTML='';
|
||||
for(const sh of tgt.sheets) ts.innerHTML+=`<option>${sh.name}</option>`;
|
||||
const cols=tgt.sheets[0].columns;
|
||||
for(const c of cols){const l=`${c.letter}: ${c.header} (${c.type})`;mc.innerHTML+=`<option value="${c.letter}">${l}</option>`;wc.innerHTML+=`<option value="${c.letter}">${l}</option>`;}
|
||||
const tc=cols.filter(c=>c.type==='text'),nc=cols.filter(c=>c.type==='number');
|
||||
const nl=tc.find(c=>/наименован/i.test(c.header)); if(nl)mc.value=nl.letter; else if(tc.length)mc.value=tc[0].letter;
|
||||
const ql=nc.find(c=>/количеств|кол/i.test(c.header)); if(ql)wc.value=ql.letter; else if(nc.length)wc.value=nc[0].letter;
|
||||
}
|
||||
|
||||
async function analyze(){
|
||||
const r=await fetch('/api/wizard/analyze',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({session_id:sid,search_column:$('srcCol').value,search_keyword:$('srcKw').value,source_sheet:$('srcSheet').value})});
|
||||
const d=await r.json();
|
||||
let h=`<p>Найдено: <strong>${d.found_count}</strong>, ключей: <strong>${(d.unique_keys||[]).length}</strong></p>`;
|
||||
if(d.sample_rows&&d.sample_rows.length){h+='<div class="preview-table"><table><thead><tr><th>Файл</th><th>Строка</th><th>Текст</th><th>Ключ</th></tr></thead><tbody>';for(const r of d.sample_rows.slice(0,15))h+=`<tr><td>${r.file}</td><td>${r.row}</td><td>${r.search_value}</td><td>${r.key||'-'}</td></tr>`;h+='</tbody></table></div>';}
|
||||
$('searchPrev').innerHTML=h; ui();
|
||||
}
|
||||
async function analyzeVal(){
|
||||
const r=await fetch('/api/wizard/analyze',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({session_id:sid,search_column:$('srcCol').value,search_keyword:$('srcKw').value,source_sheet:$('srcSheet').value,value_column:$('valCol').value})});
|
||||
const d=await r.json(); let h='';
|
||||
if(d.sample_rows&&d.sample_rows.length){h+='<div class="preview-table"><table><thead><tr><th>Файл</th><th>Ключ</th><th>Значение</th></tr></thead><tbody>';for(const r of d.sample_rows.slice(0,10))h+=`<tr><td>${r.file}</td><td>${r.key||'-'}</td><td>${r.number_value!=null?r.number_value.toFixed(2):'-'}</td></tr>`;h+='</tbody></table></div>';}
|
||||
$('valPrev').innerHTML=h;
|
||||
}
|
||||
|
||||
function cfg(){return{session_id:sid,search_keyword:$('srcKw').value,search_column:$('srcCol').value,value_column:$('valCol').value,source_sheet:$('srcSheet').value||null,target_sheet:$('tgtSheet').value||null,match_column:$('matchCol').value,target_write_column:$('writeCol').value,action:$('action').value,unmatched:$('unmatched').value};}
|
||||
|
||||
async function loadPreview(){
|
||||
$('prevLoad').classList.remove('d-none');$('prevResult').innerHTML='';$('prevSummary').innerHTML='';$('runBtn').classList.add('d-none');
|
||||
try{const r=await fetch('/api/wizard/preview',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(cfg())});const d=await r.json();
|
||||
let h='<div class="preview-table"><table><thead><tr><th>Статус</th><th>Строка</th><th>Название</th><th>Было</th><th>Станет</th></tr></thead><tbody>';
|
||||
for(const m of d.matches){const c=m.status==='add'?'status-add':'status-update',l=m.status==='add'?'НОВЫЙ':'обновл.';h+=`<tr><td class="${c}">${l}</td><td>${m.target_row||'—'}</td><td>${m.target_label}</td><td>${m.current_value!=null?m.current_value.toFixed(2):'—'}</td><td>${m.new_value.toFixed(2)}</td></tr>`;}
|
||||
h+='</tbody></table></div>';$('prevResult').innerHTML=h;
|
||||
const s=d.summary;$('prevSummary').innerHTML=`<span class="badge badge-info">${s.updates} обновлений</span> <span class="badge badge-success">${s.adds} новых</span> <span class="badge badge-muted">Итого: ${s.total_new_value.toFixed(2)}</span>`;
|
||||
if(d.matches.length)$('runBtn').classList.remove('d-none');
|
||||
}finally{$('prevLoad').classList.add('d-none');}
|
||||
}
|
||||
|
||||
async function run(){
|
||||
$('runSpin').classList.remove('d-none');
|
||||
try{const r=await fetch('/api/wizard/run',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(cfg())});const d=await r.json();
|
||||
if(d.success)$('runResult').innerHTML=`<div class="alert-success">Готово! Обновлено: ${d.stats.updated}, добавлено: ${d.stats.added}<br><a href="${d.download_url}">Скачать результат</a></div>`;
|
||||
}finally{$('runSpin').classList.add('d-none');}
|
||||
}
|
||||
ui();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
Reference in New Issue
Block a user