feat(cupang): 밀크런 출고리스트 작성 팝업 — 구글 시트 출고일 시트 아래에 덧붙임

- 첫 화면 "+ 신규 등록" 옆 엑셀색 버튼 → 작성일·출고일·센터입고일(프로젝트 날짜 팝업),
  입고센터(시트 F열 + 등록 센터, 직접 입력), 출고방식(파렛트/택배), 코드표 검색 제품·수량, 출고, 작업자(기본 핫프렌즈)
- POST /cupang/api/outbound-sheet: 출고일 시트 YYYYMMDD(요일) 맨 아래에 기존 양식으로 추가
  (순번 이어짐·파렛트 배경색), 시트가 없으면 5행 양식째 생성. cupang_db 에는 저장하지 않음
- GET /cupang/api/outbound-sheet/centers: 입고센터 후보(10분 캐시)
- export.build_block 분리(기존 build_table 결과 동일), google_sheets 에 sheet_titles·read_ranges·append_block 추가
- 테스트: pytest(양식·입력 검사·덧붙일 위치·Sheets 요청·실제 앱), Playwright 화면 테스트

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-23 14:57:43 +09:00
parent 9883971beb
commit e63734c984
11 changed files with 1411 additions and 63 deletions
+316
View File
@@ -0,0 +1,316 @@
/* 쿠팡 밀크런 — 밀크런 출고리스트 작성 팝업(cupang/index.html).
- 날짜 칸: 프로젝트 화면의 날짜 팝업(window.PJLib.enhanceDateInput)을 그대로 쓴다.
- 입고센터: 출고리스트 구글 시트에 적힌 센터 + 설정에 등록된 센터(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 = "완료";
});
});
})();
+43
View File
@@ -1602,3 +1602,46 @@ a.cpg-boxno-dl:hover { background: #1a5c38; border-color: #1a5c38; font-weight:
@media (max-width: 640px) {
.cpg-sales-form { grid-template-columns: minmax(0, 1fr); }
}
/* ── 밀크런 출고리스트 작성 (index.html 팝업 · cupang-outbound.js) ── */
/* 엑셀 초록 버튼 */
.cpg-btn-excel { background: #217346; color: #fff; padding: 8px 16px; }
.cpg-btn-excel:hover { background: #185c37; }
.cpg-btn-excel:disabled { opacity: .6; cursor: default; }
.cpg-ol-box { width: min(760px, calc(100vw - 32px)); max-height: calc(100vh - 48px); overflow-y: auto; gap: 12px; }
.cpg-ol-grid { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 10px; }
.cpg-ol-grid-2 { grid-template-columns: repeat(2, minmax(0, 1fr)); }
.cpg-ol-box .erp-input { box-sizing: border-box; }
/* 날짜 칸 = 프로젝트 날짜 버튼. 칸 너비에 맞추고, 지난 날짜도 빨강(마감 지남)으로 칠하지 않는다 */
.cpg-ol-box .pj-date-btn { width: 100%; margin-top: 0; height: 34px; justify-content: flex-start; }
.cpg-ol-box .pj-date-btn.is-overdue { color: var(--color-rich-black); }
.cpg-ol-search { position: relative; }
.cpg-ol-results {
position: absolute; z-index: 5; left: 0; right: 0; top: calc(100% + 4px);
margin: 0; padding: 4px; list-style: none; max-height: 260px; overflow-y: auto;
background: var(--color-canvas-white); border: 1px solid var(--color-subtle-ash);
border-radius: 8px; box-shadow: 0 8px 24px rgba(0, 0, 0, .14);
}
.cpg-ol-results[hidden] { display: none; }
.cpg-ol-hit { display: flex; gap: 10px; padding: 6px 8px; border-radius: 6px; cursor: pointer; font-size: 13px; color: var(--color-rich-black); }
.cpg-ol-hit b { flex: 0 0 auto; min-width: 96px; }
.cpg-ol-hit.is-active, .cpg-ol-hit:hover { background: #e8f3ec; }
.cpg-ol-noresult { padding: 8px; font-size: 13px; color: var(--color-midtone-gray); }
.cpg-ol-lines { width: 100%; border-collapse: collapse; font-size: 13px; }
.cpg-ol-lines th { text-align: center; font-weight: 600; background: #dbe9f7; padding: 6px 8px; border: 1px solid var(--color-subtle-ash); }
.cpg-ol-lines td { padding: 4px 8px; border: 1px solid var(--color-subtle-ash); text-align: center; }
.cpg-ol-lines td:nth-child(2) { text-align: left; }
.cpg-ol-lines[hidden] { display: none; }
.cpg-ol-box .cpg-ol-qty { width: 110px; min-width: 0; text-align: right; }
.cpg-ol-lines th:nth-child(1) { width: 120px; }
.cpg-ol-lines th:nth-child(3) { width: 130px; }
.cpg-ol-lines th:nth-child(4) { width: 56px; }
.cpg-ol-center-custom[hidden] { display: none; }
.cpg-ol-empty { margin: 0; }
.cpg-ol-empty[hidden] { display: none; }
.cpg-ol-target { margin: 0; font-size: 12px; }
.cpg-ol-error { margin: 0; font-size: 13px; color: #c22b10; }
.cpg-ol-actions { display: flex; gap: 6px; justify-content: flex-end; }
@media (max-width: 640px) {
.cpg-ol-grid, .cpg-ol-grid-2 { grid-template-columns: minmax(0, 1fr); }
}