Files
dbx-corm/static/js/manual_grid.js
T

194 lines
13 KiB
JavaScript

(() => {
const panel = document.getElementById('manual-grid-panel');
if (!panel) return;
const table = document.getElementById('manual-grid');
const status = document.getElementById('manual-save-status');
const retry = document.getElementById('manual-save-retry');
const pending = new Map();
let rows = new Map(), headers = [], saving = null, sentKeys = new Set(), timer, failure = null, locked = false, loadGeneration = 0;
const keyOf = (id, column) => `${id}:${column}`;
const cellAt = (id, column) => table.querySelector(`td[data-id="${id}"][data-column="${column}"]`);
function message(text, state = '') { status.textContent = text; status.dataset.state = state; }
async function request(url, options) {
const response = await fetch(url, options);
if (!response.ok) {
const data = await response.json().catch(() => ({}));
const error = new Error(typeof data.detail === 'string' ? data.detail : data.detail?.message || '처리를 확인하지 못했습니다. 다시 시도해주세요.');
error.conflicts = data.detail?.conflicts;
throw error;
}
return response;
}
const jsonOptions = (method, data) => ({method, headers: {'Content-Type': 'application/json'}, body: JSON.stringify(data)});
function queueCell(td) {
const id = Number(td.dataset.id), column = Number(td.dataset.column), key = keyOf(id, column);
const value = td.textContent.replace(/\r\n/g, '\n');
const previous = pending.get(key)?.previous_value ?? rows.get(id).cells[column];
if (value === rows.get(id).cells[column] && !sentKeys.has(key)) pending.delete(key);
else pending.set(key, {id, column, value, previous_value: previous});
td.dataset.dirty = String(pending.has(key));
delete td.dataset.error;
if (!failure) message('입력 중 · 자동 저장 대기', 'saving');
clearTimeout(timer);
timer = setTimeout(() => { if (!failure) flush().catch(() => {}); }, 450);
}
function applyRows(updated, keys) {
for (const row of updated) {
rows.set(row.id, row);
row.cells.forEach((value, column) => {
const key = keyOf(row.id, column), queued = pending.get(key), td = cellAt(row.id, column);
if (queued && keys.has(key)) queued.previous_value = value;
if (td && !queued) { if (td.textContent !== value) td.textContent = value; delete td.dataset.dirty; delete td.dataset.error; }
});
}
}
function flush() {
clearTimeout(timer);
if (saving) return saving;
if (failure) return Promise.reject(failure);
saving = (async () => {
while (pending.size) {
const batch = [...pending.values()].slice(0, 1000);
sentKeys = new Set(batch.map(c => keyOf(c.id, c.column)));
for (const key of sentKeys) pending.delete(key);
message('저장 중…', 'saving');
try {
const result = await (await request('/api/manual/orders/cells', jsonOptions('PATCH', {changes: batch}))).json();
applyRows(result.rows, sentKeys);
} catch (error) {
for (const change of batch) {
const key = keyOf(change.id, change.column), newer = pending.get(key);
pending.set(key, {...change, value: newer?.value ?? change.value});
const td = cellAt(change.id, change.column);
if (td) td.dataset.error = 'true';
}
failure = error;
retry.hidden = false;
message('저장하지 못한 입력이 있습니다 · ' + error.message, 'error');
throw error;
} finally { sentKeys = new Set(); }
}
message('모든 변경사항 저장됨');
retry.hidden = true;
})().finally(() => { saving = null; });
return saving;
}
retry.addEventListener('click', () => {
if (failure?.conflicts?.length) {
const preview = failure.conflicts.slice(0, 3).map(c => `${headers[c.column]}: 최신값 「${c.value}」 / 내 입력 「${pending.get(keyOf(c.id, c.column))?.value ?? ''}」`).join('\n');
const keepMine = confirm(preview + '\n\n확인: 내 입력으로 변경\n취소: 충돌한 셀은 최신값 사용');
for (const conflict of failure.conflicts) {
const key = keyOf(conflict.id, conflict.column), change = pending.get(key), td = cellAt(conflict.id, conflict.column);
rows.get(conflict.id).cells[conflict.column] = conflict.value;
if (keepMine && change) change.previous_value = conflict.value;
else { pending.delete(key); if (td) { td.textContent = conflict.value; delete td.dataset.dirty; delete td.dataset.error; } }
}
}
failure = null;
flush().catch(() => {});
});
function columnLetter(index) { let out = ''; for (let n = index + 1; n; n = Math.floor((n - 1) / 26)) out = String.fromCharCode(65 + (n - 1) % 26) + out; return out; }
function render(data) {
headers = data.headers;
rows = new Map(data.rows.map(row => [row.id, row]));
const head = table.tHead, body = table.tBodies[0];
head.replaceChildren(); body.replaceChildren();
const letters = head.insertRow(), titles = head.insertRow();
for (const [i, title] of ['', ...headers].entries()) {
const letter = document.createElement('th'), label = document.createElement('th');
letter.textContent = i ? columnLetter(i - 1) : '';
if (i) label.textContent = title;
else { const all = document.createElement('input'); all.type = 'checkbox'; all.setAttribute('aria-label', '모든 행 선택'); all.onchange = () => body.querySelectorAll('input').forEach(box => { box.checked = all.checked; }); label.append(all); }
letters.append(letter); titles.append(label);
}
data.rows.forEach((row, index) => {
const tr = body.insertRow(), number = tr.insertCell(), check = document.createElement('input');
check.type = 'checkbox'; check.dataset.rowId = row.id; check.setAttribute('aria-label', `${index + 1}행 선택`);
number.append(check, document.createTextNode(` ${index + 1}`));
row.cells.forEach((value, column) => {
const td = tr.insertCell(); td.textContent = value; td.contentEditable = 'plaintext-only'; td.tabIndex = 0;
td.dataset.id = row.id; td.dataset.column = column; td.setAttribute('aria-label', `${index + 1}행 ${headers[column] || columnLetter(column)}`);
td.addEventListener('input', event => { if (!event.isComposing) queueCell(td); });
td.addEventListener('compositionend', () => queueCell(td));
td.addEventListener('blur', () => { if (!failure) flush().catch(() => {}); });
td.addEventListener('keydown', event => {
if (event.isComposing) return;
if (event.key === 'Enter' && event.altKey) return;
if (event.key === 'Tab' || event.key === 'Enter') {
event.preventDefault();
const ids = [...rows.keys()], rowIndex = ids.indexOf(row.id);
let nextRow = rowIndex, nextColumn = column;
if (event.key === 'Enter') nextRow += event.shiftKey ? -1 : 1;
else nextColumn += event.shiftKey ? -1 : 1;
if (nextColumn >= headers.length) { nextColumn = 0; nextRow++; }
if (nextColumn < 0) { nextColumn = headers.length - 1; nextRow--; }
cellAt(ids[nextRow], nextColumn)?.focus();
}
if (event.key === 'Escape') { td.textContent = rows.get(row.id).cells[column]; queueCell(td); td.blur(); }
});
td.addEventListener('paste', event => {
event.preventDefault();
const text = event.clipboardData.getData('text/plain').replace(/\r\n/g, '\n').replace(/\n$/, '');
const matrix = text.split('\n').map(line => line.split('\t')), ids = [...rows.keys()], start = ids.indexOf(row.id);
if (matrix.length + start > ids.length || matrix.some(line => line.length + column > headers.length) || matrix.reduce((n, line) => n + line.length, 0) > 1000) {
alert('붙여넣을 범위를 확인해주세요. 필요한 행을 먼저 추가하고 한 번에 1,000셀 이내로 붙여넣으세요.'); return;
}
matrix.forEach((line, r) => line.forEach((text, c) => { const target = cellAt(ids[start + r], column + c); target.textContent = text; queueCell(target); }));
});
});
});
document.getElementById('manual-row-count').textContent = `${data.rows.length.toLocaleString()}행`;
document.getElementById('manual-grid-empty').hidden = data.rows.length !== 0;
}
async function load() {
if (pending.size || saving || locked) return;
const generation = ++loadGeneration;
const data = await (await request('/api/manual/orders')).json();
if (generation !== loadGeneration || pending.size || saving || locked || table.contains(document.activeElement)) return;
render(data); message('모든 변경사항 저장됨');
}
async function action(work) {
if (locked) return;
locked = true;
loadGeneration++;
table.querySelectorAll('[contenteditable]').forEach(td => { td.contentEditable = 'false'; });
try { await flush(); await work(); }
finally { locked = false; table.querySelectorAll('[contenteditable]').forEach(td => { td.contentEditable = 'plaintext-only'; }); }
await load();
}
async function download() {
if (!confirm('현재 발주를 엑셀로 내려받고 표를 비우시겠습니까? 내려받은 자료는 다운로드 기록에 보관됩니다.')) return;
await action(async () => {
const response = await request('/api/sheet/download_and_clear', {method: 'POST'});
const blob = await response.blob(), a = document.createElement('a');
a.href = URL.createObjectURL(blob);
a.download = decodeURIComponent(response.headers.get('Content-Disposition')?.split("UTF-8''")[1] || '수동발주.xlsx');
document.body.append(a); a.click(); a.remove(); setTimeout(() => URL.revokeObjectURL(a.href), 30000);
});
await loadExports();
}
async function loadExports() {
const list = document.getElementById('manual-export-list');
const exports = await (await request('/api/manual/orders/exports')).json(); list.replaceChildren();
for (const item of exports) { const li = document.createElement('li'), a = document.createElement('a'); a.textContent = item.filename; a.href = (window.APP_BASE_PATH || '') + '/api/manual/orders/exports/' + item.id; li.append(a); list.append(li); }
if (!exports.length) list.textContent = '아직 다운로드 기록이 없습니다.';
}
document.getElementById('manual-add-row').onclick = () => action(async () => { await request('/api/manual/orders', {method: 'POST'}); }).catch(error => message(error.message, 'error'));
document.getElementById('manual-delete-rows').onclick = () => {
const selected = [...table.querySelectorAll('input[data-row-id]:checked')].map(box => rows.get(Number(box.dataset.rowId)));
if (!selected.length || !confirm(`${selected.length}개 행을 표에서 삭제하시겠습니까?`)) return;
action(async () => { await request('/api/manual/orders/archive', jsonOptions('POST', {rows: selected.map(({id}) => ({id, version: rows.get(id).version}))})); }).catch(error => message(error.message, 'error'));
};
document.getElementById('manual-refresh').onclick = async () => {
try { if (failure && confirm('저장하지 못한 입력이 있습니다. 필요한 내용을 복사해 두셨나요? 확인하면 미저장 입력을 버리고 새로 불러옵니다.')) { pending.clear(); failure = null; retry.hidden = true; } else await flush(); document.activeElement?.blur(); await load(); }
catch (error) { message(error.message, 'error'); }
};
document.getElementById('manual-download').onclick = () => download().catch(error => message(error.message + ' · 다운로드 기록도 확인해주세요.', 'error'));
document.getElementById('manual-exports').ontoggle = event => { if (event.target.open) loadExports().catch(error => message(error.message, 'error')); };
window.manualGrid = {flush, refresh: async () => { await flush(); await load(); }, download};
window.addEventListener('beforeunload', event => { if (pending.size || saving) { event.preventDefault(); event.returnValue = ''; } });
document.querySelector('[data-tab="manual-tab"]')?.addEventListener('click', () => load().catch(error => message(error.message, 'error')));
setInterval(() => { if (document.getElementById('manual-tab').classList.contains('active')) load().catch(error => message(error.message, 'error')); }, 10000);
load().catch(error => message(error.message, 'error'));
})();