Move CORM settings and histories to dedicated PostgreSQL database

This commit is contained in:
2026-10-22 17:48:50 +09:00
parent 92986eb1cc
commit 399e91518c
20 changed files with 2058 additions and 84 deletions
+52 -30
View File
@@ -19,6 +19,22 @@
};
})();
async function settingsErrorMessage(response) {
const fallback = response.status === 409
? '다른 요청이 설정을 변경했습니다. 새로고침 후 다시 저장해주세요.'
: '설정을 저장하지 못했습니다. 새로고침하여 저장 여부를 확인해주세요.';
const data = await response.json().catch(() => ({}));
return typeof data.detail === 'string' ? data.detail : fallback;
}
async function readHistoryResponse(response) {
const data = await response.json().catch(() => ({}));
if (!response.ok) {
throw new Error(typeof data.detail === 'string' ? data.detail : '내역 처리를 확인하지 못했습니다. 새로고침해주세요.');
}
return data;
}
function showToast(message) {
const toast = document.createElement('div');
toast.textContent = message;
@@ -1744,11 +1760,11 @@ document.addEventListener('DOMContentLoaded', () => {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(histData)
}).then(() => {
}).then(readHistoryResponse).then(() => {
if (typeof loadManualHistory === 'function') {
loadManualHistory();
}
});
}).catch(error => alert('발주는 완료됐지만 수동발주내역 저장을 확인하지 못했습니다. ' + error.message));
}
// Copy the same text that is written to the sheet remarks/comparison field.
@@ -2176,14 +2192,14 @@ document.addEventListener('DOMContentLoaded', () => {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(histData)
}).then(() => {
}).then(readHistoryResponse).then(() => {
writeSmsCustomerCache(stamp, {
custName: custName,
custPhone: custPhone,
custAddress: custAddress
});
loadSmsHistory();
});
}).catch(error => alert('문자내역 저장을 확인하지 못했습니다. ' + error.message));
});
@@ -2194,14 +2210,14 @@ document.addEventListener('DOMContentLoaded', () => {
function loadSmsHistory() {
const u = document.getElementById('sms-history-list');
u.innerHTML = '';
fetch('/api/sms/history').then(r => r.json()).then(data => {
fetch('/api/sms/history').then(readHistoryResponse).then(data => {
data.slice().reverse().forEach((d, idx) => {
const actualIdx = data.length - 1 - idx;
const li = document.createElement('li');
li.style.cursor = 'pointer';
li.style.padding = '4px 0';
li.style.borderBottom = '1px solid #eee';
li.onclick = () => window.loadHistoryItem(actualIdx);
li.onclick = () => window.loadHistoryItem(actualIdx, d.id);
const cachedCustomer = readSmsCustomerCache()[d.timestamp] || {};
const name = firstNonEmpty(d.custName, d.customer_name, cachedCustomer.custName, cachedCustomer.customer_name);
@@ -2226,7 +2242,7 @@ document.addEventListener('DOMContentLoaded', () => {
spanDel.style.marginLeft = '8px';
spanDel.title = '삭제';
spanDel.textContent = '❌';
spanDel.onclick = (e) => window.deleteHistory(actualIdx, e);
spanDel.onclick = (e) => window.deleteHistory(actualIdx, e, d.id);
li.appendChild(spanDel);
u.appendChild(li);
@@ -2235,7 +2251,7 @@ document.addEventListener('DOMContentLoaded', () => {
});
});
}).catch(error => { u.textContent = error.message; });
}
const SMS_CUSTOMER_CACHE_KEY = 'smsCustomerHistoryByTimestamp';
@@ -2268,7 +2284,7 @@ document.addEventListener('DOMContentLoaded', () => {
const u = document.getElementById('manual-history-list');
if (!u) return;
u.innerHTML = '';
fetch('/api/manual/history').then(r => r.json()).then(data => {
fetch('/api/manual/history').then(readHistoryResponse).then(data => {
let totalCount = data.length;
let totalAmount = 0;
data.forEach((d) => {
@@ -2306,18 +2322,21 @@ document.addEventListener('DOMContentLoaded', () => {
spanDel.textContent = '❌';
spanDel.onclick = (e) => {
e.stopPropagation();
if (confirm("🚨 [경고] 이 수동발주 기록을 삭제하시겠습니까?\n\n(구글 시트에서도 함께 삭제됩니다!)")) {
if (confirm("이 수동발주 기록을 삭제하시겠습니까?\n\n연결된 발주 시트의 주문도 함께 삭제됩니다.")) {
const btn = e.target;
btn.textContent = '⏳';
btn.style.pointerEvents = 'none';
fetch(`/api/manual/history/${encodeURIComponent(d.timestamp)}`, { method: 'DELETE' })
.then(() => {
const deleteUrl = d.id !== undefined
? `/api/manual/history/records/${d.id}`
: `/api/manual/history/${encodeURIComponent(d.timestamp)}`;
fetch(deleteUrl, { method: 'DELETE' })
.then(readHistoryResponse).then(() => {
window.loadManualHistory();
const iframe = document.querySelector('#manual-tab iframe');
if (iframe) iframe.src = iframe.src;
})
.catch(() => {
alert("삭제 중 오류가 발생했습니다.");
.catch(error => {
alert(error.message || "삭제 중 오류가 발생했습니다.");
btn.textContent = '❌';
btn.style.pointerEvents = 'auto';
});
@@ -2327,13 +2346,13 @@ document.addEventListener('DOMContentLoaded', () => {
u.appendChild(li);
});
}).catch(err => console.error("Error loading manual history", err));
}).catch(error => { u.textContent = error.message; });
}
window.loadHistoryItem = function (idx) {
fetch('/api/sms/history').then(r => r.json()).then(data => {
if (idx < 0 || idx >= data.length) return;
const d = data[idx];
window.loadHistoryItem = function (idx, recordId) {
fetch('/api/sms/history').then(readHistoryResponse).then(data => {
const d = recordId !== undefined ? data.find(record => record.id === recordId) : data[idx];
if (!d) { loadSmsHistory(); return; }
document.getElementById('btn-reset').click();
@@ -2428,19 +2447,22 @@ document.addEventListener('DOMContentLoaded', () => {
updateSelectedOrderItemsSummary();
});
}).catch(error => alert(error.message));
}
window.deleteHistory = function (idx, e) {
window.deleteHistory = function (idx, e, recordId) {
e.stopPropagation();
if (confirm("이 기록을 삭제하시겠습니까?")) {
fetch(`/api/sms/history/${idx}`, { method: 'DELETE' }).then(() => loadSmsHistory());
const url = recordId !== undefined ? `/api/sms/history/records/${recordId}` : `/api/sms/history/${idx}`;
fetch(url, { method: 'DELETE' }).then(readHistoryResponse)
.then(() => loadSmsHistory()).catch(error => alert(error.message));
}
}
document.getElementById('btn-sms-clear-all').addEventListener('click', () => {
if (confirm("정말로 모든 기록을 삭제하시겠습니까?")) {
fetch('/api/sms/history', { method: 'DELETE' }).then(() => loadSmsHistory());
fetch('/api/sms/history', { method: 'DELETE' }).then(readHistoryResponse)
.then(() => loadSmsHistory()).catch(error => alert(error.message));
}
@@ -2620,7 +2642,7 @@ document.addEventListener('DOMContentLoaded', () => {
buildProductTab(configData);
});
} else {
alert('저장 실패');
alert(await settingsErrorMessage(res));
}
} catch (e) {
alert('오류 발생');
@@ -2717,7 +2739,7 @@ document.addEventListener('DOMContentLoaded', () => {
body: JSON.stringify({ [BULK_TRACKING_PREFIX_SETTING]: prefix })
});
if (!res.ok) throw new Error('Failed to save bulk tracking prefix');
if (!res.ok) throw new Error(await settingsErrorMessage(res));
if (!configData.APP_SETTINGS) configData.APP_SETTINGS = {};
configData.APP_SETTINGS[BULK_TRACKING_PREFIX_SETTING] = prefix;
if (btnBulkPrefixSave) btnBulkPrefixSave.style.backgroundColor = '#4a5568';
@@ -2755,7 +2777,7 @@ document.addEventListener('DOMContentLoaded', () => {
await saveBulkTrackingPrefix();
} catch (err) {
console.error('Bulk prefix save failed:', err);
alert('송장 앞 숫자 저장에 실패했습니다.');
alert(err.message || '송장 앞 숫자 저장에 실패했습니다.');
}
});
}
@@ -2788,7 +2810,7 @@ document.addEventListener('DOMContentLoaded', () => {
savedPrefix = await saveBulkTrackingPrefix({ silent: true });
} catch (err) {
console.error('Bulk prefix save failed:', err);
alert('송장 앞 숫자 저장에 실패했습니다.');
alert(err.message || '송장 앞 숫자 저장에 실패했습니다.');
return;
}
@@ -3518,8 +3540,8 @@ document.addEventListener('DOMContentLoaded', () => {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload)
}).then(r => {
if (!r.ok) throw new Error("Network response was not ok (status " + r.status + ")");
}).then(async r => {
if (!r.ok) throw new Error(await settingsErrorMessage(r));
return r.json();
}).then(res => {
alert("상품 설정이 저장되었습니다.");
@@ -3538,7 +3560,7 @@ document.addEventListener('DOMContentLoaded', () => {
});
}).catch(err => {
console.error(err);
alert("저장 실패!");
alert(err.message || "저장 실패!");
document.getElementById('btn-product-save').innerText = '상품 설정 저장';
});
});