/* 쿠팡 밀크런 — 밀크런 출고리스트 작성 팝업(cupang/index.html). - 날짜 칸: 프로젝트 화면의 날짜 팝업(window.PJLib.enhanceDateInput)을 그대로 쓴다. - 입고센터: 출고리스트 엑셀(구글 드라이브 .xlsx)에 적힌 센터 + 설정에 등록된 센터(GET /cupang/api/outbound-sheet/centers). - 제품: 코드표(itemcode_db) 전체 목록(GET /cupang/api/products/all)에서 코드·이름으로 찾아 추가. - [완료] → POST /cupang/api/outbound-sheet → 출고일 시트(YYYYMMDD(요일)) 맨 아래에 덧붙임. */ (function () { "use strict"; var dlg = document.getElementById("cpg-ol-dlg"); var openBtn = document.getElementById("cpg-ol-open"); if (!dlg || !openBtn) return; // project.js 가 대화상자 제목을 프로젝트 화면 것으로 바꿔 두므로 이 화면은 기본 제목으로 되돌린다. if (window.ERP_DIALOG_TITLE === "KSN 프로그램") delete window.ERP_DIALOG_TITLE; var NEW_CENTER = "__new__"; var DOW = ["일", "월", "화", "수", "목", "금", "토"]; function $(id) { return document.getElementById(id); } var docDate = $("cpg-ol-doc-date"), shipDate = $("cpg-ol-ship-date"), arrivalDate = $("cpg-ol-arrival-date"); var centerSel = $("cpg-ol-center"), centerNew = $("cpg-ol-center-new"); var centerCustom = dlg.querySelector(".cpg-ol-center-custom"); var method = $("cpg-ol-method"), outbound = $("cpg-ol-outbound"), worker = $("cpg-ol-worker"); var search = $("cpg-ol-search"), results = $("cpg-ol-results"); var linesBody = $("cpg-ol-lines"), emptyMsg = $("cpg-ol-empty"); var target = $("cpg-ol-target"), errorBox = $("cpg-ol-error"), submitBtn = $("cpg-ol-submit"); var defaultWorker = worker.value; var products = null; // 코드표 [{code, name, type}] — 처음 열 때 한 번 읽는다 var productsReason = ""; var arrivalAuto = true; // 센터입고일을 직접 고르기 전까지는 출고일 + 1일로 따라간다 var busy = false; // 한국 날짜(브라우저 시간대와 무관) — 서버 today_kst 와 같은 날 function kstToday() { return new Date(Date.now() + 9 * 3600000).toISOString().slice(0, 10); } function addDays(iso, n) { var d = new Date(iso + "T00:00:00"); d.setDate(d.getDate() + n); return d.getFullYear() + "-" + String(d.getMonth() + 1).padStart(2, "0") + "-" + String(d.getDate()).padStart(2, "0"); } function sheetTitle(iso) { var d = new Date(iso + "T00:00:00"); return iso.replace(/-/g, "") + "(" + DOW[d.getDay()] + ")"; } if (window.PJLib && window.PJLib.enhanceDateInput) { [docDate, shipDate, arrivalDate].forEach(function (inp) { window.PJLib.enhanceDateInput(inp, { placeholder: "날짜 선택" }); }); } function showError(msg) { errorBox.textContent = msg || ""; errorBox.hidden = !msg; } // 고치기 시작하면 지난 안내는 지운다 dlg.addEventListener("input", function () { if (!busy) showError(""); }); dlg.addEventListener("change", function () { if (!busy) showError(""); }); function updateTarget() { target.textContent = shipDate.value ? "완료하면 출고리스트 엑셀 '" + sheetTitle(shipDate.value) + "' 시트 맨 아래에 추가합니다. (시트가 없으면 양식째 새로 만듭니다)" : "출고일을 고르면 그 날짜 시트(YYYYMMDD(요일))에 추가합니다."; } shipDate.addEventListener("change", function () { if (shipDate.value && (arrivalAuto || !arrivalDate.value)) { arrivalDate.value = addDays(shipDate.value, 1); arrivalAuto = true; } updateTarget(); }); arrivalDate.addEventListener("change", function () { arrivalAuto = !arrivalDate.value; }); // ── 입고센터 ───────────────────────────────────── function fillCenters(names, reason) { var keep = centerSel.value; centerSel.innerHTML = ""; function add(value, label) { var o = document.createElement("option"); o.value = value; o.textContent = label; centerSel.appendChild(o); } add("", names.length ? "센터 선택" : "센터 목록 없음"); names.forEach(function (n) { add(n, n); }); add(NEW_CENTER, "+ 직접 입력"); if (keep && (keep === NEW_CENTER || names.indexOf(keep) >= 0)) centerSel.value = keep; centerCustom.hidden = centerSel.value !== NEW_CENTER; if (reason) showError("입고센터 목록 일부를 불러오지 못했습니다: " + reason); } function loadCenters() { return fetch("/cupang/api/outbound-sheet/centers", { headers: { Accept: "application/json" } }) .then(function (res) { return res.ok ? res.json() : Promise.reject(new Error(res.status)); }) .then(function (data) { fillCenters(data.centers || [], data.reason || ""); }) .catch(function () { fillCenters([], "서버 응답 없음"); }); } centerSel.addEventListener("change", function () { centerCustom.hidden = centerSel.value !== NEW_CENTER; if (!centerCustom.hidden) centerNew.focus(); }); // ── 제품 검색(코드표) ───────────────────────────── function loadProducts() { if (products) return Promise.resolve(); return fetch("/cupang/api/products/all", { headers: { Accept: "application/json" } }) .then(function (res) { return res.ok ? res.json() : Promise.reject(new Error(res.status)); }) .then(function (data) { products = data.results || []; productsReason = data.enabled ? (data.error || "") : (data.reason || "코드표 미설정"); }) .catch(function () { products = []; productsReason = "서버 응답 없음"; }); } var hits = [], activeHit = -1; function renderResults() { results.innerHTML = ""; var q = search.value.trim().toLowerCase(); if (!q) { results.hidden = true; return; } hits = (products || []).filter(function (p) { return p.code.toLowerCase().indexOf(q) >= 0 || p.name.toLowerCase().indexOf(q) >= 0; }).slice(0, 30); activeHit = hits.length ? 0 : -1; if (!hits.length) { var li = document.createElement("li"); li.className = "cpg-ol-noresult"; li.textContent = productsReason ? "코드표를 불러오지 못했습니다: " + productsReason : "검색 결과가 없습니다."; results.appendChild(li); } hits.forEach(function (p, i) { var li = document.createElement("li"); li.className = "cpg-ol-hit" + (i === activeHit ? " is-active" : ""); li.dataset.index = String(i); var code = document.createElement("b"); code.textContent = p.code; var name = document.createElement("span"); name.textContent = p.name; li.appendChild(code); li.appendChild(name); results.appendChild(li); }); results.hidden = false; } function moveActive(step) { if (!hits.length) return; activeHit = (activeHit + step + hits.length) % hits.length; Array.prototype.forEach.call(results.querySelectorAll(".cpg-ol-hit"), function (li, i) { li.classList.toggle("is-active", i === activeHit); if (i === activeHit) li.scrollIntoView({ block: "nearest" }); }); } function pickHit(i) { var p = hits[i]; if (!p) return; addLine(p.code, p.name); search.value = ""; results.hidden = true; } search.addEventListener("input", renderResults); search.addEventListener("keydown", function (e) { if (e.isComposing || e.keyCode === 229) return; // 한글 조합 중 Enter 는 조합 확정 if (e.key === "ArrowDown") { e.preventDefault(); moveActive(1); } else if (e.key === "ArrowUp") { e.preventDefault(); moveActive(-1); } else if (e.key === "Enter") { e.preventDefault(); pickHit(activeHit); } else if (e.key === "Escape" && !results.hidden) { e.stopPropagation(); results.hidden = true; } }); // mousedown — 검색창 blur 로 목록이 닫히기 전에 고른다 results.addEventListener("mousedown", function (e) { var li = e.target.closest(".cpg-ol-hit"); if (!li) return; e.preventDefault(); pickHit(+li.dataset.index); }); search.addEventListener("blur", function () { results.hidden = true; }); // ── 제품 줄 ───────────────────────────────────── var linesTable = linesBody.closest("table"); function syncEmpty() { var has = linesBody.children.length > 0; emptyMsg.hidden = has; linesTable.hidden = !has; } function addLine(code, name) { var existing = Array.prototype.find.call(linesBody.children, function (tr) { return tr.dataset.code === code; }); if (existing) { existing.querySelector(".cpg-ol-qty").focus(); return; } var tr = document.createElement("tr"); tr.dataset.code = code; tr.dataset.name = name; var tdCode = document.createElement("td"); tdCode.textContent = code; var tdName = document.createElement("td"); tdName.textContent = name; var tdQty = document.createElement("td"); var qty = document.createElement("input"); qty.type = "number"; qty.min = "1"; qty.step = "1"; qty.className = "erp-input cpg-ol-qty"; qty.setAttribute("aria-label", name + " 수량"); tdQty.appendChild(qty); var tdDel = document.createElement("td"); var del = document.createElement("button"); del.type = "button"; del.className = "cpg-icon-btn is-danger"; del.textContent = "삭제"; del.addEventListener("click", function () { tr.remove(); syncEmpty(); }); tdDel.appendChild(del); tr.appendChild(tdCode); tr.appendChild(tdName); tr.appendChild(tdQty); tr.appendChild(tdDel); linesBody.appendChild(tr); syncEmpty(); qty.focus(); } // ── 열기 / 닫기 ───────────────────────────────── function reset() { docDate.value = kstToday(); shipDate.value = ""; arrivalDate.value = ""; arrivalAuto = true; centerSel.value = ""; centerNew.value = ""; centerCustom.hidden = true; method.value = "파렛트"; outbound.value = ""; worker.value = defaultWorker; search.value = ""; results.hidden = true; linesBody.innerHTML = ""; syncEmpty(); showError(""); updateTarget(); } function open() { reset(); dlg.hidden = false; loadCenters(); loadProducts(); } function close() { if (busy) return; dlg.hidden = true; } openBtn.addEventListener("click", open); Array.prototype.forEach.call(dlg.querySelectorAll("[data-ol-close]"), function (el) { el.addEventListener("click", close); }); document.addEventListener("keydown", function (e) { // 날짜 팝업이 떠 있으면 그 팝업이 먼저 닫힌다(그쪽이 Esc 를 가져간다) if (e.key === "Escape" && !dlg.hidden && !document.querySelector(".pj-datepop")) close(); }); // ── 완료 ──────────────────────────────────────── function collect() { var center = centerSel.value === NEW_CENTER ? centerNew.value.trim() : centerSel.value; var lines = Array.prototype.map.call(linesBody.children, function (tr) { return { code: tr.dataset.code, name: tr.dataset.name, quantity: tr.querySelector(".cpg-ol-qty").value }; }); if (!docDate.value) return { error: "작성일을 선택해 주세요." }; if (!shipDate.value) return { error: "출고일을 선택해 주세요." }; if (!arrivalDate.value) return { error: "센터입고일을 선택해 주세요." }; if (!center) return { error: "입고센터를 선택해 주세요." }; if (!lines.length) return { error: "제품을 1개 이상 추가해 주세요." }; for (var i = 0; i < lines.length; i++) { if (!(parseInt(lines[i].quantity, 10) > 0)) return { error: lines[i].name + "의 수량을 입력해 주세요." }; } return { body: { document_date: docDate.value, ship_date: shipDate.value, center_arrival_date: arrivalDate.value, center: center, ship_method: method.value, outbound: outbound.value.trim(), worker: worker.value.trim(), lines: lines, }, }; } submitBtn.addEventListener("click", function () { if (busy) return; var got = collect(); if (got.error) { showError(got.error); return; } showError(""); busy = true; submitBtn.disabled = true; submitBtn.textContent = "기록 중…"; fetch("/cupang/api/outbound-sheet", { method: "POST", headers: { "Content-Type": "application/json", Accept: "application/json" }, body: JSON.stringify(got.body), }) .then(function (res) { return res.json().catch(function () { return {}; }).then(function (data) { if (!res.ok) throw new Error(typeof data.detail === "string" ? data.detail : "출고리스트 파일에 기록하지 못했습니다."); return data; }); }) .then(function (data) { busy = false; close(); var msg = "'" + data.title + "' 시트 " + data.first_row + "~" + data.last_row + "행에 " + data.line_count + "개 제품을 추가했습니다."; if (window.erpConfirm && data.url) { window.erpConfirm(msg + "\n출고리스트 엑셀을 열어 볼까요?", { tone: "ok", okText: "파일 열기", cancelText: "닫기" }) .then(function (ok) { if (ok) window.open(data.url, "_blank", "noopener"); }); } else { window.alert(msg); } }) .catch(function (err) { showError(err.message); }) .finally(function () { busy = false; submitBtn.disabled = false; submitBtn.textContent = "완료"; }); }); })();