Add database-backed manual order grid with automatic cell saving
This commit is contained in:
@@ -0,0 +1,29 @@
|
||||
.manual-grid-panel { display:flex; flex-direction:column; width:100%; min-width:0; height:100%; padding:16px; gap:10px; box-sizing:border-box; background:#f8fafc; }
|
||||
.manual-grid-toolbar,.manual-grid-actions,.manual-grid-info { display:flex; align-items:center; gap:10px; flex-wrap:wrap; }
|
||||
.manual-grid-toolbar { justify-content:space-between; }
|
||||
.manual-grid-toolbar strong { font-size:18px; color:#1e293b; }
|
||||
.manual-grid-actions .btn { padding:7px 12px; font-size:13px; }
|
||||
.manual-muted,.manual-grid-info { color:#64748b; font-size:12px; }
|
||||
.manual-grid-info > :first-child { margin-right:auto; }
|
||||
#manual-save-status[data-state="error"] { color:#b91c1c; font-weight:600; }
|
||||
#manual-save-status[data-state="saving"] { color:#1d4ed8; }
|
||||
#manual-save-retry { border:1px solid #fecaca; background:#fff1f2; padding:3px 9px; border-radius:4px; cursor:pointer; }
|
||||
.manual-grid-scroll { flex:1; min-height:200px; overflow:auto; background:white; border:1px solid #cbd5e1; border-radius:8px; }
|
||||
table.manual-grid { border-collapse:separate; border-spacing:0; table-layout:fixed; width:max-content; min-width:100%; margin:0; font-size:13px; color:#1e293b; }
|
||||
.manual-grid th,.manual-grid td { box-sizing:border-box; min-width:150px; width:150px; max-width:150px; padding:7px 9px; border:0; border-right:1px solid #e2e8f0; border-bottom:1px solid #e2e8f0; text-align:left; vertical-align:top; white-space:pre-wrap; overflow-wrap:anywhere; line-height:20px; background:white; }
|
||||
.manual-grid th { position:sticky; z-index:2; top:24px; background:#f1f5f9; font-weight:600; height:35px; }
|
||||
.manual-grid thead tr:first-child th { top:0; height:24px; padding:1px 9px; text-align:center; color:#64748b; font-size:11px; background:#e9eef5; }
|
||||
.manual-grid td:first-child,.manual-grid th:first-child { position:sticky; left:0; min-width:65px; width:65px; max-width:65px; background:#f1f5f9; color:#64748b; text-align:center; z-index:1; white-space:nowrap; }
|
||||
.manual-grid th:first-child { z-index:3; }
|
||||
.manual-grid td:nth-child(9),.manual-grid th:nth-child(9),.manual-grid td:nth-child(16),.manual-grid th:nth-child(16) { min-width:280px; width:280px; max-width:280px; }
|
||||
.manual-grid td[contenteditable]:focus { outline:2px solid #2563eb; outline-offset:-2px; background:#eff6ff; }
|
||||
.manual-grid td[data-dirty="true"] { background:#fffbeb; }
|
||||
.manual-grid td[data-error="true"] { background:#fff1f2; box-shadow:inset 0 -2px #e11d48; }
|
||||
.manual-grid tbody tr:has(input:checked) td { background:#eff6ff; }
|
||||
#manual-grid-empty { color:#64748b; padding:36px; text-align:center; }
|
||||
#manual-exports { position:relative; font-size:13px; }
|
||||
#manual-exports summary { cursor:pointer; padding:7px; }
|
||||
#manual-export-list { position:absolute; right:0; top:25px; min-width:270px; max-height:300px; overflow:auto; background:white; box-shadow:0 8px 24px #0f172a26; border:1px solid #e2e8f0; border-radius:6px; padding:10px; list-style:none; z-index:5; }
|
||||
#manual-export-list li { padding:6px; }
|
||||
#manual-export-list a { color:#1d4ed8; text-decoration:none; }
|
||||
@media(max-width:800px) { .manual-grid-panel { padding:8px; } .manual-grid-actions { gap:5px; } }
|
||||
+6
-2
@@ -30,7 +30,7 @@ async function settingsErrorMessage(response) {
|
||||
async function readHistoryResponse(response) {
|
||||
const data = await response.json().catch(() => ({}));
|
||||
if (!response.ok) {
|
||||
throw new Error(typeof data.detail === 'string' ? data.detail : '내역 처리를 확인하지 못했습니다. 새로고침해주세요.');
|
||||
throw new Error(typeof data.detail === 'string' ? data.detail : data.detail?.message || '내역 처리를 확인하지 못했습니다. 새로고침해주세요.');
|
||||
}
|
||||
return data;
|
||||
}
|
||||
@@ -1750,7 +1750,7 @@ document.addEventListener('DOMContentLoaded', () => {
|
||||
if (data.status === 'success') {
|
||||
if (!url.includes('submit')) {
|
||||
alert(data.message);
|
||||
} else if (data.timestamp) {
|
||||
} else if (data.timestamp && !data.history_saved) {
|
||||
const histData = {
|
||||
timestamp: data.timestamp,
|
||||
customer_name: submitPayload.customer_name,
|
||||
@@ -1766,6 +1766,7 @@ document.addEventListener('DOMContentLoaded', () => {
|
||||
}
|
||||
}).catch(error => alert('발주는 완료됐지만 수동발주내역 저장을 확인하지 못했습니다. ' + error.message));
|
||||
}
|
||||
if (data.history_saved && typeof loadManualHistory === 'function') loadManualHistory();
|
||||
|
||||
// Copy the same text that is written to the sheet remarks/comparison field.
|
||||
if (data.clipboard_text) {
|
||||
@@ -1784,6 +1785,7 @@ document.addEventListener('DOMContentLoaded', () => {
|
||||
if (url.includes('submit')) {
|
||||
const iframe = document.querySelector('#manual-tab iframe');
|
||||
if (iframe) iframe.src = iframe.src;
|
||||
window.manualGrid?.refresh().catch(error => alert(error.message));
|
||||
}
|
||||
} else {
|
||||
alert("Error: " + data.detail);
|
||||
@@ -1803,6 +1805,7 @@ document.addEventListener('DOMContentLoaded', () => {
|
||||
document.getElementById('btn-submit-ellen').addEventListener('click', () => submitOrder('/api/order/submit', true));
|
||||
|
||||
document.getElementById('btn-download-sheet').addEventListener('click', () => {
|
||||
if (window.manualGrid) { window.manualGrid.download().catch(error => alert(error.message)); return; }
|
||||
if (!confirm("수동발주로 입력한 자료는 엑셀 파일로 저장되며, 입력된 수동발주 내용은 사라집니다.\n진행하시겠습니까?")) return;
|
||||
|
||||
const btn = document.getElementById('btn-download-sheet');
|
||||
@@ -2334,6 +2337,7 @@ document.addEventListener('DOMContentLoaded', () => {
|
||||
window.loadManualHistory();
|
||||
const iframe = document.querySelector('#manual-tab iframe');
|
||||
if (iframe) iframe.src = iframe.src;
|
||||
window.manualGrid?.refresh().catch(error => alert(error.message));
|
||||
})
|
||||
.catch(error => {
|
||||
alert(error.message || "삭제 중 오류가 발생했습니다.");
|
||||
|
||||
@@ -0,0 +1,193 @@
|
||||
(() => {
|
||||
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'));
|
||||
})();
|
||||
Reference in New Issue
Block a user