Files
anorandClaude Opus 4.6 6b98045184 fix: polling fallback когда SSE done event не доходит до клиента
Проблема: Claude Code Docker завершается, файлы на диске есть,
но SSE event 'done' не доходит до браузера через nginx.
UI зависает навечно.

Решение: двойная страховка
1. JS: после завершения SSE stream поллит /api/batch-v2/status каждые 2с
2. API status: проверяет файлы на диске, если job.status ещё "uploaded"
   но batch_script.py уже существует → переводит в "analyzed"

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-26 03:34:35 +10:00

349 lines
18 KiB
HTML
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<!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="/">&#8592; Вернуться в чат</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 => '&bull; ' + 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>