Files
dbx-main/app/static/inout.js
T
king 4c17158753 feat(inout): 옵션을 톱니 팝업으로, 겹치던 옵션 화면 정리, 공장 담당자·연락처 분리
- 옵션 탭 → 상단 오른쪽 톱니(관리자) → 팝업(탭: 담당자·공장). 내용은 /inout/settings?panel=1,
  저장은 팝업 안에서(X-Inout-Options: 1 → JSON, 같은 탭 그대로 다시 그림), 바뀌면 닫을 때 새로고침.
  예전 /inout/settings 주소는 목록으로 가서 팝업 열기(?options=1).
- 겹침 원인: 공용 .erp-input(min-width 240px + content-box)이 좁은 칸에서 옆 칸을 덮고,
  .erp-table-wrap(카드 그림자·둥근 모서리)이 카드 안에서 상자를 겹쳐 보이게 함 → .io/.io-dlg 안에서만 바로잡음.
  공장 표는 진짜 <table> + 입력칸 form 속성으로 열 맞춤(줄 선·배경 어긋남 없음).
- 공장 담당자·연락처 분리: inout_db 002(manager 열, 이름만 있던 연락처는 담당자로). 발주서 화면에 공장 담당자·연락처.
  002 미적용이어도 발주서 화면은 열리고 공장 저장만 안내.
- 테스트: 팝업·JSON 저장·예전 주소·권한, 담당자/연락처, 002 전후. 실제 브라우저로 겹침 0·줄 맞춤 확인.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 15:45:53 +09:00

311 lines
14 KiB
JavaScript

/* 입출고 관리(inout) 화면 스크립트 — 화면 전환·저장은 서버(폼)가 하고, 여기는 입력을 돕기만 한다.
· 목록 줄 누르기 = 발주서로
· 발주서 폼: 제품 줄 추가·지우기·번호·합계, 코드표 단품 검색(GET /inout/api/items?q=) 드롭다운
· 발주서 화면: [남은 수량 모두 채우기], 이번 입고 합계
· 옵션 팝업(톱니): 담당자·공장 — 열 때 내용을 받고, 저장은 제자리
· data-erp-confirm-btn: 버튼별 확인(formaction 이 있는 버튼 — 공용 data-erp-confirm 은 form.submit() 이라 누른 버튼이 사라짐) */
(function () {
"use strict";
function confirmMsg(msg) {
return window.erpConfirm ? window.erpConfirm(msg) : Promise.resolve(window.confirm(msg));
}
function alertMsg(msg) {
return window.erpAlert ? window.erpAlert(msg) : Promise.resolve(window.alert(msg));
}
function num(v) {
const n = parseInt(String(v || "").replace(/[,\s]/g, ""), 10);
return Number.isFinite(n) && n > 0 ? n : 0;
}
function fmt(n) { return n.toLocaleString("ko-KR"); }
// ── 목록 줄 누르기 → 발주서 ──
document.addEventListener("click", function (e) {
const row = e.target.closest(".io-row-link");
if (!row || e.target.closest("a, button, input, select, label")) return;
if (window.getSelection && String(window.getSelection())) return; // 글자 고르는 중
location.href = row.dataset.href;
});
// ── 버튼별 확인 ──
document.addEventListener("click", function (e) {
const btn = e.target.closest("[data-erp-confirm-btn]");
if (!btn || btn.dataset.confirmed === "1") return;
e.preventDefault();
confirmMsg(btn.dataset.erpConfirmBtn).then(function (ok) {
if (!ok) return;
btn.dataset.confirmed = "1";
if (btn.form.requestSubmit) btn.form.requestSubmit(btn); else btn.click();
});
});
// ── 발주서 폼 ──
const form = document.getElementById("io-order-form");
if (form) initOrderForm(form);
function initOrderForm(form) {
const body = form.querySelector("#io-lines tbody");
const tpl = document.getElementById("io-line-tpl");
const totalQty = document.getElementById("io-total-qty");
const totalLines = document.getElementById("io-total-lines");
function renumber() {
let q = 0, k = 0;
body.querySelectorAll(".io-line").forEach(function (tr, i) {
tr.querySelector(".io-col-no").textContent = String(i + 1);
const n = num(tr.querySelector(".io-qty").value);
if (tr.querySelector('input[name="item_code"]').value) { k++; q += n; }
});
totalQty.textContent = fmt(q);
totalLines.textContent = fmt(k);
}
function addLine(focus) {
const tr = tpl.content.firstElementChild.cloneNode(true);
body.appendChild(tr);
wireSearch(tr.querySelector(".io-item-search"));
renumber();
if (focus) tr.querySelector(".io-item-search").focus();
return tr;
}
form.querySelector("#io-add-line").addEventListener("click", function () { addLine(true); });
body.addEventListener("click", function (e) {
const del = e.target.closest(".io-del");
if (!del) return;
const tr = del.closest(".io-line");
const search = tr.querySelector(".io-item-search");
if (search && search._ioBox) search._ioBox.remove(); // body 에 붙은 드롭다운도 함께
tr.remove();
if (!body.querySelector(".io-line")) addLine(false);
renumber();
});
body.addEventListener("input", renumber); // 수량을 바꾸거나 제품 글을 고치면(고른 것 풀림) 다시 셈
body.addEventListener("io-chosen", renumber); // 검색 목록에서 제품을 고르면
body.querySelectorAll(".io-item-search").forEach(wireSearch);
if (!body.querySelector(".io-line")) { addLine(false); addLine(false); addLine(false); }
renumber();
form.addEventListener("submit", function (e) {
// 검색 글만 있고 목록에서 고르지 않은 줄, 같은 제품 두 줄 — 서버도 막지만 여기서 먼저 알려 준다
const codes = [];
let bad = null;
body.querySelectorAll(".io-line").forEach(function (tr) {
const code = tr.querySelector('input[name="item_code"]').value;
const text = tr.querySelector(".io-item-search").value.trim();
if (!code && text && !bad) bad = { tr: tr, msg: "'" + text + "' — 검색 목록에서 제품을 골라 주세요." };
if (code && codes.indexOf(code) >= 0 && !bad) bad = { tr: tr, msg: code + " — 같은 제품이 두 줄에 있습니다. 한 줄로 합쳐 주세요." };
if (code) codes.push(code);
});
if (bad) {
e.preventDefault();
bad.tr.querySelector(".io-item-search").classList.add("is-invalid");
alertMsg(bad.msg).then(function () { bad.tr.querySelector(".io-item-search").focus(); });
}
});
}
// 코드표 단품 검색 드롭다운 — 고르면 숨은 칸(코드·이름)을 채우고 수량 칸으로. 글을 다시 고치면 고른 것을 지운다.
function wireSearch(input) {
if (!input || input.readOnly || input.dataset.wired) return;
input.dataset.wired = "1";
const cell = input.closest(".io-item-cell");
const codeEl = cell.querySelector('input[name="item_code"]');
const nameEl = cell.querySelector('input[name="item_name"]');
const box = document.createElement("div");
box.className = "io-suggest";
box.setAttribute("role", "listbox");
box.hidden = true;
document.body.appendChild(box); // 표 가로 스크롤 상자 밖(fixed) — 아래 줄에서도 잘리지 않게
input._ioBox = box;
let timer = 0, seq = 0, items = [], active = -1;
function place() {
const r = input.getBoundingClientRect();
const below = window.innerHeight - r.bottom;
box.style.left = r.left + "px";
box.style.width = Math.max(r.width, 320) + "px";
if (below < 200 && r.top > below) { box.style.top = ""; box.style.bottom = (window.innerHeight - r.top + 2) + "px"; }
else { box.style.bottom = ""; box.style.top = (r.bottom + 2) + "px"; }
}
window.addEventListener("resize", function () { if (!box.hidden) place(); });
document.addEventListener("scroll", function () { if (!box.hidden) place(); }, true);
function close() { box.hidden = true; active = -1; input.setAttribute("aria-expanded", "false"); }
function paint() {
box.innerHTML = "";
if (!items.length) {
const empty = document.createElement("div");
empty.className = "io-suggest-empty";
empty.textContent = box.dataset.message || "맞는 단품이 없습니다.";
box.appendChild(empty);
}
items.forEach(function (it, i) {
const opt = document.createElement("div");
opt.className = "io-suggest-item" + (i === active ? " is-active" : "");
opt.setAttribute("role", "option");
const c = document.createElement("span");
c.className = "io-code";
c.textContent = it.code;
opt.appendChild(c);
opt.appendChild(document.createTextNode(" " + it.name));
opt.addEventListener("mousedown", function (e) { e.preventDefault(); choose(i); });
box.appendChild(opt);
});
box.hidden = false;
place();
input.setAttribute("aria-expanded", "true");
}
function choose(i) {
const it = items[i];
if (!it) return;
codeEl.value = it.code;
nameEl.value = it.name;
input.value = it.code + " · " + it.name;
input.classList.remove("is-invalid");
close();
const qty = input.closest("tr").querySelector(".io-qty");
if (qty) qty.focus();
input.dispatchEvent(new Event("io-chosen", { bubbles: true }));
}
async function search(q) {
const my = ++seq;
try {
const res = await fetch("/inout/api/items?q=" + encodeURIComponent(q), { headers: { Accept: "application/json" } });
const data = await res.json();
if (my !== seq) return;
items = data.items || [];
box.dataset.message = data.enabled === false ? (data.message || "코드표가 연결되지 않았습니다.") : "";
active = items.length ? 0 : -1;
paint();
} catch (_) {
if (my !== seq) return;
items = [];
box.dataset.message = "검색하지 못했습니다. 잠시 뒤 다시 입력하세요.";
paint();
}
}
input.setAttribute("aria-autocomplete", "list");
input.addEventListener("input", function () {
codeEl.value = ""; // 글을 고치면 고른 제품은 풀린다(다시 골라야 저장)
nameEl.value = "";
clearTimeout(timer);
const q = input.value.trim();
if (!q) { close(); return; }
timer = setTimeout(function () { search(q); }, 200);
});
input.addEventListener("keydown", function (e) {
if (box.hidden) return;
if (e.key === "ArrowDown" || e.key === "ArrowUp") {
e.preventDefault();
if (!items.length) return;
active = (active + (e.key === "ArrowDown" ? 1 : items.length - 1)) % items.length;
paint();
} else if (e.key === "Enter") {
e.preventDefault(); // 고르기만 — 폼 저장 아님
choose(active < 0 ? 0 : active);
} else if (e.key === "Escape") {
close();
}
});
input.addEventListener("blur", function () { setTimeout(close, 120); });
}
// ── 발주서 화면: 입고 입력 ──
const recvForm = document.getElementById("io-receipt-form");
if (recvForm) {
const total = document.getElementById("io-recv-total");
const inputs = Array.from(recvForm.querySelectorAll(".io-recv"));
const paintTotal = function () {
const t = inputs.reduce(function (s, i) { return s + num(i.value); }, 0);
if (total) total.textContent = t ? "(" + fmt(t) + "개)" : "";
};
recvForm.addEventListener("input", paintTotal);
const fill = document.getElementById("io-fill-remaining");
if (fill) fill.addEventListener("click", function () {
inputs.forEach(function (i) { if (!i.value.trim() && num(i.dataset.remaining)) i.value = i.dataset.remaining; });
paintTotal();
});
paintTotal();
}
// ── 옵션 팝업(톱니, 관리자) — 내용은 GET /inout/settings?panel=1, 저장은 제자리(X-Inout-Options: 1 → JSON) ──
const optBtn = document.getElementById("io-options-btn");
const optDlg = document.getElementById("io-options");
if (optBtn && optDlg) initOptions(optBtn, optDlg);
function initOptions(btn, dlg) {
const body = dlg.querySelector("#io-options-body");
const msgEl = dlg.querySelector(".io-dlg-msg");
let changed = false, pane = "roles";
function say(text, bad) {
msgEl.textContent = text || "";
msgEl.hidden = !text;
msgEl.classList.toggle("is-bad", !!bad);
}
function showPane(name) {
pane = name;
body.querySelectorAll(".io-dlg-tabs [data-pane]").forEach(function (t) {
const on = t.dataset.pane === name;
t.classList.toggle("is-active", on);
t.setAttribute("aria-selected", on ? "true" : "false");
t.tabIndex = on ? 0 : -1;
});
body.querySelectorAll(".io-dlg-pane").forEach(function (p) { p.hidden = p.dataset.pane !== name; });
}
async function load() {
const res = await fetch("/inout/settings?panel=1", { headers: { "X-Inout-Options": "1" } });
if (!res.ok) throw new Error("HTTP " + res.status);
body.innerHTML = await res.text();
showPane(pane);
}
async function open() {
say("");
if (!dlg.open) dlg.showModal();
try {
await load();
dlg.focus({ preventScroll: true }); // 닫기(✕)에 초점 테두리가 생기지 않게 창 자체에(Tab 으로 안으로 이동)
} catch (_) {
body.innerHTML = '<p class="io-error">옵션을 불러오지 못했습니다. 잠시 뒤 다시 여세요.</p>';
}
}
btn.addEventListener("click", open);
dlg.addEventListener("click", function (e) {
if (e.target.closest("[data-close]")) { dlg.close(); return; }
const tab = e.target.closest(".io-dlg-tabs [data-pane]");
if (tab) showPane(tab.dataset.pane);
});
dlg.addEventListener("close", function () {
const url = new URL(location.href);
const hadParam = url.searchParams.has("options");
url.searchParams.delete("options");
url.searchParams.delete("msg");
if (changed) location.href = url.toString(); // 담당 표시·공장 목록이 바뀌었을 수 있다
else if (hadParam) history.replaceState(null, "", url.toString());
});
dlg.addEventListener("submit", async function (e) {
const form = e.target;
if (!form.classList || !form.classList.contains("io-dlg-form")) return;
e.preventDefault();
const sub = e.submitter;
if (sub && sub.dataset.confirm && !(await confirmMsg(sub.dataset.confirm))) return;
const action = sub && sub.getAttribute("formaction") ? sub.getAttribute("formaction") : form.getAttribute("action");
const buttons = Array.from(dlg.querySelectorAll("button[type=submit]"));
buttons.forEach(function (b) { b.disabled = true; });
try {
const res = await fetch(action, { method: "POST", headers: { "X-Inout-Options": "1" },
body: new URLSearchParams(new FormData(form)) });
let data = {};
try { data = await res.json(); } catch (_) {}
if (!res.ok || data.ok === false) { say(data.message || data.detail || "저장하지 못했습니다.", true); return; }
changed = true;
await load();
say(data.message || "저장했습니다.");
} catch (_) {
say("저장하지 못했습니다(연결 오류). 다시 눌러 주세요.", true);
} finally {
buttons.forEach(function (b) { if (b.isConnected) b.disabled = false; });
}
});
if (btn.dataset.open === "1") open();
}
})();