v1.0.28: один запрос на все файлы + ошибки блокируют ЛЛМ

This commit is contained in:
2026-06-18 20:43:21 +04:00
parent fb8b53eed1
commit 17517e0e60
2 changed files with 145 additions and 52 deletions
+75 -45
View File
@@ -64,7 +64,7 @@
<body>
<div class="topbar">
<img src="/nubes-logo.svg" alt="Nubes">
<span class="title">Сверка договоров <span style="font-weight:400;color:var(--muted);font-size:12px;">v1.0.27 — Lucee</span></span>
<span class="title">Сверка договоров <span style="font-weight:400;color:var(--muted);font-size:12px;">v1.0.28 — Lucee</span></span>
</div>
<div class="content">
@@ -221,68 +221,98 @@ fileInput.addEventListener('change', function() {
renderTable();
});
// ── Загрузка (FileReader → base64 → JSON POST) ────────
// ── Загрузка (FileReader → base64 → JSON POST все сразу)
uploadBtn.addEventListener('click', function() {
if (fileQueue.length === 0) return;
uploadBtn.disabled = true;
uploadStartTime = Date.now();
uploadTimer.style.display = 'block';
function uploadNext(i) {
if (i >= fileQueue.length) {
uploadTimer.style.display = 'none';
uploadBtn.disabled = false;
if (contractId) {
document.getElementById('actionsCard').style.display = 'block';
document.getElementById('chatCard').style.display = 'block';
}
return;
}
var f = fileQueue[i];
if (f.status === 'uploaded') { uploadNext(i + 1); return; }
// Читаем все файлы в base64
var pending = fileQueue.filter(function(f) { return !f.doc_id; });
var done = 0;
var payloads = [];
function readNext(i) {
if (i >= pending.length) { sendAll(); return; }
var f = pending[i];
f.status = 'читаю...';
renderTable();
uploadTimer.textContent = 'Загрузка ' + (i+1) + '/' + fileQueue.length + '...';
var reader = new FileReader();
reader.onload = function(e) {
var b64 = e.target.result.split(',')[1];
var payload = {filename: f.name, data: b64};
if (contractId) payload.contract_id = contractId;
fetch('/upload.cfm', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify(payload)
}).then(function(r) { return r.json(); })
.then(function(r) {
if (r.OK) {
contractId = r.CONTRACT_ID;
f.doc_id = r.DOC_ID;
f.status = 'uploaded';
var elapsed = ((Date.now() - uploadStartTime) / 1000).toFixed(1);
log('✅ ' + f.name + ' (' + formatSize(f.size) + ') — ' + elapsed + 'с');
} else {
f.status = 'error: ' + (r.ERROR || 'неизв.');
log('❌ ' + f.name + ': ' + (r.ERROR || ''));
}
renderTable();
setTimeout(function() { uploadNext(i + 1); }, 300);
}).catch(function(e) {
f.status = 'error: ' + e.message;
renderTable();
setTimeout(function() { uploadNext(i + 1); }, 300);
});
payloads.push({filename: f.name, data: e.target.result.split(',')[1]});
done++;
uploadTimer.textContent = 'Чтение ' + done + '/' + pending.length + '...';
readNext(i + 1);
};
reader.onerror = function() {
f.status = 'error: чтение';
renderTable();
uploadNext(i + 1);
readNext(i + 1);
};
reader.readAsDataURL(f.file);
}
uploadNext(0);
function sendAll() {
if (payloads.length === 0) {
uploadTimer.style.display = 'none';
uploadBtn.disabled = false;
return;
}
uploadTimer.textContent = 'Отправка ' + payloads.length + ' файлов...';
var body = {files: payloads};
if (contractId) body.contract_id = contractId;
fetch('/upload.cfm', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify(body)
}).then(function(r) { return r.json(); })
.then(function(data) {
uploadTimer.style.display = 'none';
uploadBtn.disabled = false;
if (data.OK && data.RESULTS) {
for (var i = 0; i < data.RESULTS.length; i++) {
var r = data.RESULTS[i];
// Найти файл в очереди по имени
for (var j = 0; j < fileQueue.length; j++) {
if (fileQueue[j].name === r.filename) {
if (r.OK) {
fileQueue[j].status = 'uploaded';
fileQueue[j].doc_id = r.DOC_ID;
contractId = r.CONTRACT_ID || contractId;
log('✅ ' + r.filename + ' (' + formatSize(fileQueue[j].size) + ')');
} else {
fileQueue[j].status = 'error: ' + (r.ERROR || '');
log('❌ ' + r.filename + ': ' + (r.ERROR || ''));
}
}
}
}
} else {
log('❌ ' + (data.ERROR || 'неизв. ошибка'));
for (var i = 0; i < pending.length; i++) {
pending[i].status = 'error';
}
}
renderTable();
var hasErrors = fileQueue.some(function(f) { return f.status && f.status.indexOf('error') === 0; });
if (contractId && !hasErrors) {
document.getElementById('actionsCard').style.display = 'block';
document.getElementById('chatCard').style.display = 'block';
}
}).catch(function(e) {
uploadTimer.style.display = 'none';
uploadBtn.disabled = false;
log('❌ Сеть: ' + e.message);
for (var i = 0; i < pending.length; i++) {
pending[i].status = 'error: ' + e.message;
}
renderTable();
});
}
readNext(0);
});
// ── Инфо ──────────────────────────────────────────────────
+70 -7
View File
@@ -13,21 +13,84 @@
<cfset result = {ok: false, error: "no file"}>
<cftry>
<!--- JSON-загрузка: {filename, data: base64, contract_id?} --->
<!--- JSON-загрузка: {files: [{filename, data}], contract_id?} или {filename, data} --->
<cfset ct = cgi.http_content_type>
<cfif ct CONTAINS "application/json">
<cfset body = toString(getHttpRequestData().content)>
<cfset data = deserializeJSON(body)>
<cfif structKeyExists(data, "filename") AND structKeyExists(data, "data")>
<cfset clientFile = data.filename>
<cfset originalBytes = data.data>
<cfset contractId = structKeyExists(data, "contract_id") ? data.contract_id : "">
<cfset fileSize = len(originalBytes)>
<!--- Один файл или массив --->
<cfif structKeyExists(data, "files") AND isArray(data.files)>
<cfset fileList = data.files>
<cfelseif structKeyExists(data, "filename")>
<cfset fileList = [data]>
<cfelse>
<cfset result = {ok: false, error: "JSON: filename and data required"}>
<cfset result = {ok: false, error: "JSON: files array or filename required"}>
<cfoutput>#serializeJSON(result)#</cfoutput>
<cfabort>
</cfif>
<cfset contractId = structKeyExists(data, "contract_id") ? data.contract_id : "">
<!--- Обработать каждый файл --->
<cfset results = []>
<cfloop array="#fileList#" index="fdata">
<cftry>
<cfset clientFile = fdata.filename>
<cfset originalBytes = fdata.data>
<cfset mime = "application/octet-stream">
<cfset ext = listLast(clientFile, ".")>
<cfif ext EQ "pdf"><cfset mime = "application/pdf">
<cfelseif ext EQ "docx"><cfset mime = "application/vnd.openxmlformats-officedocument.wordprocessingml.document">
<cfelseif ext EQ "doc"><cfset mime = "application/msword">
<cfelseif ext EQ "zip"><cfset mime = "application/zip">
</cfif>
<cftransaction>
<cfquery datasource="baza">
INSERT INTO documents (filename, mime_type, original_bytes, status)
VALUES (
<cfqueryparam value="#clientFile#" cfsqltype="cf_sql_varchar">,
<cfqueryparam value="#mime#" cfsqltype="cf_sql_varchar">,
<cfqueryparam value="#originalBytes#" cfsqltype="cf_sql_varchar">,
'uploaded'
)
</cfquery>
<cfquery name="doc" datasource="baza">
SELECT id FROM documents
WHERE filename = <cfqueryparam value="#clientFile#" cfsqltype="cf_sql_varchar">
AND status = 'uploaded' ORDER BY created_at DESC LIMIT 1
</cfquery>
<cfif len(contractId)>
<cfset cid = {id: contractId}>
<cfset suppType = "additional">
<cfelse>
<cfquery datasource="baza">
INSERT INTO contracts (number, client) VALUES (
<cfqueryparam value="б/н #dateFormat(now(), 'yyyymmdd')#-#timeFormat(now(), 'HHmm')#" cfsqltype="cf_sql_varchar">, ''
)
</cfquery>
<cfquery name="cid" datasource="baza">
SELECT id FROM contracts ORDER BY created_at DESC LIMIT 1
</cfquery>
<cfset contractId = cid.id>
<cfset suppType = "initial">
</cfif>
<cfquery datasource="baza">
INSERT INTO supplements (contract_id, document_id, type) VALUES (
<cfqueryparam value="#cid.id#" cfsqltype="cf_sql_varchar">,
<cfqueryparam value="#doc.id#" cfsqltype="cf_sql_varchar">,
<cfqueryparam value="#suppType#" cfsqltype="cf_sql_varchar">
)
</cfquery>
</cftransaction>
<cfset arrayAppend(results, {ok: true, doc_id: doc.id, contract_id: cid.id, filename: clientFile, size: len(originalBytes)})>
<cfcatch>
<cfset arrayAppend(results, {ok: false, filename: fdata.filename, error: cfcatch.message})>
</cfcatch>
</cftry>
</cfloop>
<cfset result = {ok: true, results: results, contract_id: contractId}>
<cfoutput>#serializeJSON(result)#</cfoutput>
<cfabort>
<!--- Multipart: curl/API --->
<cfelseif structKeyExists(form, "files") AND len(form.files)>
<cffile action="upload" fileField="files" destination="#getTempDirectory()#" nameConflict="makeUnique" result="upload">