/* 입출고 관리(inout) 화면 스크립트 — 화면 전환·저장은 서버(폼)가 하고, 여기는 입력을 돕기만 한다. · 목록 줄 누르기 = 발주서로 · 발주서 폼: 제품 줄 추가·지우기·번호·합계, 코드표 단품 검색(GET /inout/api/items?q=) 드롭다운 · 발주서 화면: [남은 수량 모두 채우기], 이번 입고 합계 · 옵션 팝업(톱니): 담당자·공장 — 열 때 내용을 받고, 저장은 제자리 · 입고증 사진: 브라우저에서 줄여 올리기·미리보기·크게 보기, 입고 저장 전 초과 확인(사진이 사라지지 않게) · 발주 메일·입고 요청 메일: 미리보기 팝업 → [메일 발송](보내는 사람 본인 Gmail), 처음엔 [Gmail 연결] · 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"); const totalAmount = document.getElementById("io-total-amount"), noPrice = document.getElementById("io-total-noprice"); function renumber() { let q = 0, k = 0, amount = 0, missing = 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); const has = !!tr.querySelector('input[name="item_code"]').value; const price = tr.dataset.price === "" || tr.dataset.price === undefined ? null : parseFloat(tr.dataset.price); const cell = tr.querySelector(".io-amount"); // 금액 = 수량 × 단가(상품 정보 단가, 이미 있던 품목은 발주 당시 단가) — 표시만, 저장은 서버가 단가 사본으로 if (cell) cell.textContent = has && price !== null && n ? (Math.round(price * n * 100) / 100).toLocaleString("ko-KR") : "-"; if (has) { k++; q += n; if (price === null) missing++; else amount += price * n; } }); totalQty.textContent = fmt(q); totalLines.textContent = fmt(k); if (totalAmount) totalAmount.textContent = (Math.round(amount * 100) / 100).toLocaleString("ko-KR"); if (noPrice) noPrice.textContent = missing ? " (단가 없는 " + missing + "종 제외)" : ""; } 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)); if (it.unit_price) { const pr = document.createElement("span"); pr.className = "io-suggest-price"; pr.textContent = it.unit_price + "원"; opt.insertBefore(pr, c); // float:right 는 글자보다 앞에 둬야 같은 줄 오른쪽 } 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; const row = input.closest("tr"); if (row) { // 단가(상품 정보) — 금액 계산용 row.dataset.price = it.price === null || it.price === undefined ? "" : String(it.price); const pc = row.querySelector(".io-price"); if (pc) pc.textContent = it.unit_price || "-"; } 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 = ""; // 글을 고치면 고른 제품은 풀린다(다시 골라야 저장) const row0 = input.closest("tr"); if (row0 && row0.dataset.price !== undefined) { row0.dataset.price = ""; const pc0 = row0.querySelector(".io-price"); if (pc0) pc0.textContent = "-"; } 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); // [남은 수량 모두 채우기] — 한 번 더 누르면 채우기 전 값으로 되돌린다(2026-10-19). 채운 뒤 손으로 고친 칸도 되돌림. const fill = document.getElementById("io-fill-remaining"); if (fill) { const fillLabel = fill.textContent; let before = null; // 채우기 직전 칸 값들 — 있으면 다음 클릭은 되돌리기 const setMode = function (filled) { before = filled ? before : null; fill.textContent = filled ? "채운 수량 되돌리기" : fillLabel; fill.setAttribute("aria-pressed", filled ? "true" : "false"); fill.classList.toggle("is-filled", filled); }; fill.addEventListener("click", function () { if (before) { inputs.forEach(function (i, k) { i.value = before[k]; }); setMode(false); } else { const snap = inputs.map(function (i) { return i.value; }); let changed = false; inputs.forEach(function (i) { if (!i.value.trim() && num(i.dataset.remaining)) { i.value = i.dataset.remaining; changed = true; } }); if (changed) { before = snap; setMode(true); } } 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 = '

옵션을 불러오지 못했습니다. 잠시 뒤 다시 여세요.

'; } } 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; }); } }); // ── 상품 정보 탭(004) — 단가·무게·은 함유량, 바뀐 줄만 [변경 저장], 불러오기·지우기·되살리기 ── function dirtyRows() { return Array.from(body.querySelectorAll(".io-prod-table tbody tr")).filter(function (tr) { return Array.from(tr.querySelectorAll("input[data-key]")).some(function (i) { return i.value.trim() !== i.defaultValue.trim(); }); }); } function paintDirty() { const n = dirtyRows().length; const save = body.querySelector("#io-prod-save"), badge = body.querySelector("#io-prod-dirty"); if (save) save.disabled = !n; if (badge) badge.textContent = n ? "(" + n + ")" : ""; } function dec(v) { const n = parseFloat(String(v || "").replace(/[,%\s]/g, "")); return Number.isFinite(n) ? n : null; } async function postJSON(url, payload) { const res = await fetch(url, { method: "POST", headers: { "X-Inout-Options": "1", "Content-Type": "application/json" }, body: payload === undefined ? "{}" : JSON.stringify(payload) }); let out = {}; try { out = await res.json(); } catch (_) {} return { ok: res.ok && out.ok !== false, message: out.message || out.detail || (res.ok ? "" : "HTTP " + res.status) }; } async function act(url, payload) { const r = await postJSON(url, payload); if (r.ok) { changed = true; await load(); } say(r.message || (r.ok ? "저장했습니다." : "저장하지 못했습니다."), !r.ok); return r.ok; } body.addEventListener("input", function (e) { const inp = e.target; if (inp.id === "io-prod-search") { const q = inp.value.trim().toLowerCase(); let shown = 0; body.querySelectorAll(".io-prod-table tbody tr").forEach(function (tr) { const hit = !q || tr.dataset.search.indexOf(q) >= 0; tr.hidden = !hit; if (hit) shown++; }); const cnt = body.querySelector("#io-prod-count"); if (cnt) cnt.dataset.base = cnt.dataset.base || cnt.textContent; if (cnt) cnt.textContent = q ? shown + "개 찾음" : cnt.dataset.base; return; } if (!inp.dataset || !inp.dataset.key) return; const tr = inp.closest("tr"); const w = dec(tr.querySelector('[data-key="weight_g"]').value), pct = dec(tr.querySelector('[data-key="silver_pct"]').value); const ag = tr.querySelector(".io-ag"); if (ag) ag.textContent = w !== null && pct !== null ? (Math.round(w * pct / 100 * 10000) / 10000).toLocaleString("ko-KR", { maximumFractionDigits: 4 }) : "-"; tr.classList.toggle("is-dirty", Array.from(tr.querySelectorAll("input[data-key]")).some(function (i) { return i.value.trim() !== i.defaultValue.trim(); })); paintDirty(); }); body.addEventListener("click", async function (e) { const t = e.target; if (t.id === "io-prod-import") { if (dirtyRows().length && !(await confirmMsg("저장 안 한 변경이 있습니다. 버리고 불러올까요?"))) return; t.disabled = true; say("코드표에서 단품을 불러오는 중…"); try { await act("/inout/settings/products/import"); } finally { t.disabled = false; } } else if (t.closest("#io-prod-save")) { const rows = dirtyRows().map(function (tr) { const v = function (k) { return tr.querySelector('[data-key="' + k + '"]').value.trim(); }; return { code: tr.dataset.code, unit_price: v("unit_price"), weight_g: v("weight_g"), silver_pct: v("silver_pct") }; }); if (rows.length) await act("/inout/settings/products/save", { rows: rows }); } else if (t.dataset && t.dataset.exclude) { if (await confirmMsg(t.dataset.exclude + " 를 상품 정보에서 지울까요? 다음 불러오기에서도 빠집니다(지난 발주서는 그대로).")) await act("/inout/settings/products/" + encodeURIComponent(t.dataset.exclude) + "/exclude"); } else if (t.dataset && t.dataset.restore) { await act("/inout/settings/products/" + encodeURIComponent(t.dataset.restore) + "/restore"); } }); // 저장 안 한 상품 정보가 있으면 닫기 전에 묻는다(✕·취소·Esc) dlg.addEventListener("cancel", function (e) { if (dirtyRows().length) { e.preventDefault(); confirmMsg("저장 안 한 상품 정보 변경이 있습니다. 닫을까요?").then(function (ok) { if (ok) dlg.close(); }); } }); dlg.addEventListener("click", function (e) { if (e.target.closest("[data-close]") && dirtyRows().length) { e.stopImmediatePropagation(); confirmMsg("저장 안 한 상품 정보 변경이 있습니다. 닫을까요?").then(function (ok) { if (ok) dlg.close(); }); } }, true); if (btn.dataset.open === "1") open(); } // ── 입고증 사진(003) — 브라우저에서 줄여(긴 변 2000px JPEG) 올린다. 못 줄이는 형식(HEIC 등)은 원본 그대로 ── const PHOTO_MAX_SIDE = 2000; async function shrinkPhoto(file) { if (!/^image\/(jpeg|png|webp)$/i.test(file.type)) return file; // GIF(움직임)·HEIC 등은 그대로 try { const bmp = await createImageBitmap(file); const scale = Math.min(1, PHOTO_MAX_SIDE / Math.max(bmp.width, bmp.height)); if (scale === 1 && file.size < 1.5 * 1024 * 1024) { bmp.close && bmp.close(); return file; } const cv = document.createElement("canvas"); cv.width = Math.round(bmp.width * scale); cv.height = Math.round(bmp.height * scale); cv.getContext("2d").drawImage(bmp, 0, 0, cv.width, cv.height); bmp.close && bmp.close(); const blob = await new Promise(function (r) { cv.toBlob(r, "image/jpeg", 0.85); }); if (!blob || blob.size >= file.size) return file; return new File([blob], file.name.replace(/\.[^.]+$/, "") + ".jpg", { type: "image/jpeg", lastModified: file.lastModified }); } catch (_) { return file; } } async function prepare(input) { const max = parseInt(input.dataset.max || "10", 10); let files = Array.from(input._ioFiles || []).concat(Array.from(input.files || [])); if (files.length > max) { alertMsg("입고증 사진은 " + max + "장까지 올릴 수 있습니다 — 앞의 " + max + "장만 넣습니다."); files = files.slice(0, max); } input.disabled = true; const done = []; for (const f of files) done.push(f._ioShrunk ? f : Object.assign(await shrinkPhoto(f), { _ioShrunk: true })); input.disabled = false; setFiles(input, done); return done; } function setFiles(input, files) { input._ioFiles = files; try { const dt = new DataTransfer(); files.forEach(function (f) { dt.items.add(f); }); input.files = dt.files; } catch (_) { /* 아주 옛 브라우저 — 고른 원본 그대로 올라간다 */ } } function paintPreviews(input, box) { box.innerHTML = ""; (input._ioFiles || []).forEach(function (f, i) { const chip = document.createElement("span"); chip.className = "io-photo-chip"; const img = document.createElement("img"); img.alt = ""; if (/^image\/(jpeg|png|webp|gif)$/i.test(f.type)) img.src = URL.createObjectURL(f); chip.appendChild(img); const meta = document.createElement("span"); meta.textContent = f.name + " · " + Math.max(1, Math.round(f.size / 1024)) + "KB"; chip.appendChild(meta); const x = document.createElement("button"); x.type = "button"; x.textContent = "✕"; x.setAttribute("aria-label", f.name + " 빼기"); x.addEventListener("click", function () { const left = input._ioFiles.filter(function (_f, k) { return k !== i; }); input.value = ""; setFiles(input, left); paintPreviews(input, box); }); chip.appendChild(x); box.appendChild(chip); }); } document.addEventListener("change", async function (e) { const input = e.target; if (!input.classList || !input.classList.contains("io-photo-input")) return; if (input.classList.contains("io-photo-auto")) { // 입고 기록 [+] — 고르면 바로 올림 input._ioFiles = []; const files = await prepare(input); if (files.length) input.form.submit(); return; } const fresh = Array.from(input.files || []); input._ioFiles = (input._ioFiles || []).filter(function () { return true; }); input.value = ""; try { const dt = new DataTransfer(); fresh.forEach(function (f) { dt.items.add(f); }); input.files = dt.files; } catch (_) {} await prepare(input); const box = document.getElementById("io-photo-previews"); if (box) paintPreviews(input, box); }); // ── 입고 저장 전 초과 확인(브라우저) — 서버까지 갔다 오면 고른 사진이 사라지므로 여기서 먼저 묻는다 ── const recvForm2 = document.getElementById("io-receipt-form"); if (recvForm2) recvForm2.addEventListener("submit", function (e) { const flag = document.getElementById("io-confirm-over"); if (!flag || flag.value === "1" || (e.submitter && e.submitter.name === "confirm_over")) return; const overs = Array.from(recvForm2.querySelectorAll(".io-recv")).map(function (i) { const after = num(i.dataset.received) + num(i.value); return { code: i.dataset.code, name: i.dataset.name, ordered: num(i.dataset.ordered), after: after, add: num(i.value) }; }).filter(function (x) { return x.add && x.after > x.ordered; }); if (!overs.length) return; e.preventDefault(); const lines = overs.map(function (x) { return x.code + " " + x.name + " — 발주 " + fmt(x.ordered) + "개, 입고 후 " + fmt(x.after) + "개(+" + fmt(x.after - x.ordered) + ")"; }); confirmMsg("발주보다 많이 입고하려고 합니다.\n\n" + lines.join("\n") + "\n\n초과 입고로 저장할까요?").then(function (ok) { if (!ok) return; flag.value = "1"; if (recvForm2.requestSubmit) recvForm2.requestSubmit(); else recvForm2.submit(); }); }); // ── 입고증 사진 크게 보기 ── const viewer = document.getElementById("io-viewer"); if (viewer) { const img = document.getElementById("io-viewer-img"), heic = document.getElementById("io-viewer-heic"); const title = document.getElementById("io-viewer-title"), openA = document.getElementById("io-viewer-open"); const del = document.getElementById("io-viewer-del"); let list = [], at = 0; function show(i) { at = (i + list.length) % list.length; const b = list[at], id = b.dataset.photo, isHeic = b.dataset.type === "image/heic"; img.hidden = isHeic; heic.hidden = !isHeic; if (!isHeic) img.src = "/inout/photos/" + id; openA.href = "/inout/photos/" + id; title.textContent = (b.dataset.name || "입고증") + " (" + (at + 1) + "/" + list.length + ")"; if (del) del.action = "/inout/orders/" + viewer.dataset.order + "/photos/" + id + "/delete"; viewer.querySelectorAll(".io-viewer-nav").forEach(function (n) { n.hidden = list.length < 2; }); } document.addEventListener("click", function (e) { const b = e.target.closest(".io-thumb[data-photo]"); if (!b) return; list = Array.from(document.querySelectorAll('.io-thumb[data-receipt="' + b.dataset.receipt + '"][data-photo]')); show(list.indexOf(b)); viewer.showModal(); viewer.focus({ preventScroll: true }); // [원본]에 초점 테두리가 생기지 않게(←/→ 는 창에서 받음) }); viewer.addEventListener("click", function (e) { if (e.target === viewer || e.target.closest("[data-close]")) viewer.close(); const step = e.target.closest("[data-step]"); if (step) show(at + parseInt(step.dataset.step, 10)); }); viewer.addEventListener("keydown", function (e) { if (e.key === "ArrowLeft") show(at - 1); if (e.key === "ArrowRight") show(at + 1); }); } // ── 메일 창 — 발주 메일(003)·입고 요청 메일(005) 공용. 미리보기를 받아 보여 주고, [메일 발송]을 눌러야 보낸다 ── // 발주 메일: 머리 [발주 메일 보내기] → GET|POST /inout/orders/{id}/mail (발주 담당 본인 Gmail, 받는 사람 = 공장 이메일) // 입고 요청 메일: 입고 저장 뒤 바로(?rmail=입고 id) 또는 입고 기록 줄 [보내기] → GET|POST …/receipts/{rid}/mail // (입고 담당 본인 Gmail, 받는 사람 = 옵션 → 물류센터 이메일, 참조 기본 = 옵션 값, 본문에 입고증 사진) const mailBtn = document.getElementById("io-mail-btn"), mailDlg = document.getElementById("io-mail"); if (mailBtn && mailDlg) { const om = initMail(mailDlg, { param: "mail", what: "발주 메일" }); const url = "/inout/orders/" + mailBtn.dataset.order + "/mail"; mailBtn.addEventListener("click", function () { om.open(url); }); if (mailBtn.dataset.open === "1") om.open(url); } const rmailDlg = document.getElementById("io-rmail"); if (rmailDlg) { const rm = initMail(rmailDlg, { param: "rmail", what: "입고 요청 메일" }); document.querySelectorAll(".io-rmail-btn").forEach(function (b) { b.addEventListener("click", function () { rm.open(b.dataset.url, b.dataset.title); }); }); if (rmailDlg.dataset.openUrl) rm.open(rmailDlg.dataset.openUrl, rmailDlg.dataset.openTitle); } function initMail(dlg, cfg) { const body = dlg.querySelector("[data-mail-body]"), foot = dlg.querySelector("[data-mail-foot]"); const msgEl = dlg.querySelector(".io-dlg-msg"), sendBtn = dlg.querySelector("[data-mail-send]"); const titleEl = dlg.querySelector("[data-mail-title]"); let base = "", data = null, sent = false; function say(text, bad) { msgEl.textContent = text || ""; msgEl.hidden = !text; msgEl.classList.toggle("is-bad", !!bad); } function esc(s) { const d = document.createElement("div"); d.textContent = s == null ? "" : String(s); return d.innerHTML; } function field(name) { return body.querySelector('[data-mail-field="' + name + '"]'); } async function load() { const res = await fetch(base, { headers: { Accept: "application/json" } }); data = await res.json(); if (!res.ok) throw new Error(data.detail || "HTTP " + res.status); if (!data.connected) { foot.hidden = true; body.innerHTML = '
' + "

" + esc(cfg.what) + "은 내 Gmail(" + esc(data.from) + ")로 보냅니다. 처음 한 번만 Gmail 연결이 필요합니다.

" + "

구글 화면에서 같은 계정을 고르고 '메일 보내기' 권한을 허락하세요. 보내기 권한만 받으며, 메일함은 읽지 않습니다.

" + (data.configured ? "" : '

서버 설정(APP_ENCRYPTION_KEY·구글 OAuth)이 없어 연결할 수 없습니다 — 관리자에게 알려 주세요.

') + 'Gmail 연결' + // 구글이 redirect_uri_mismatch 로 막으면 ERP 로 돌아오지 않는다 — 등록할 주소를 미리 보여 준다 '
구글 화면에 400 오류: redirect_uri_mismatch 가 나오면, 관리자가 구글 클라우드 → API 및 서비스 → 사용자 인증 정보 → ' + '로그인용 OAuth 클라이언트 → 승인된 리디렉션 URI에 아래 주소를 추가해야 합니다(Gmail API 사용·gmail.send 범위도 함께).
' + '' + esc(data.callback_url) + '
'; return; } foot.hidden = false; const receipt = data.kind === "receipt"; const sentList = (data.sent || []).map(function (m) { return "
  • " + esc(m.at) + " · " + esc(m.by) + " → " + esc(m.to) + "
  • "; }).join(""); let hint = ""; if (!data.to) { hint = receipt ? "물류센터 담당자 이메일이 옵션에 없습니다 — 받는 사람을 직접 넣거나, 관리자가 옵션 → 물류센터에 넣어 두세요." : (data.factory || "공장") + " 이메일이 옵션에 없습니다 — 받는 사람을 직접 넣거나, 관리자가 옵션 → 공장에 넣어 두세요."; } if (receipt && data.ready === false) hint += (hint ? " " : "") + "(DB 마이그레이션 005 전이라 보낸 기록이 남지 않습니다.)"; // 발주 메일 — 보내면 입고 담당에게 발주 알림(발주번호·발주일·품목·수량)이 같은 제목으로 따로 자동 발송된다 const notice = !receipt && data.notice_to ? (data.notice_to.length ? "메일 발송 시 입고 담당(" + data.notice_to.join(", ") + ")에게 발주 알림 메일(발주번호·발주일·제품 코드·제품명·수량)이 따로 자동 발송됩니다." : "입고 담당이 옵션에 없어 발주 알림 메일은 가지 않습니다(옵션 → 담당자에서 지정).") : ""; body.innerHTML = '
    ' + "" + "" + "" + "
    " + (hint ? '

    ' + esc(hint) + "

    " : "") + (notice ? '

    ' + esc(notice) + "

    " : "") + (receipt && data.photos_skipped ? '

    HEIC 등 본문에 넣지 못하는 입고증 사진 ' + esc(data.photos_skipped) + "장은 빠집니다(입고 기록에는 그대로).

    " : "") + (sentList ? '
    보낸 기록
    " : "") + ''; body.querySelector(".io-mail-preview").srcdoc = data.html; sendBtn.textContent = (data.sent || []).length ? "다시 발송" : "메일 발송"; } async function open(url, title) { base = url; if (title && titleEl) titleEl.textContent = title; say(""); sent = false; if (!dlg.open) dlg.showModal(); dlg.focus({ preventScroll: true }); body.innerHTML = '

    불러오는 중…

    '; foot.hidden = true; try { await load(); } catch (err) { body.innerHTML = '

    ' + esc(err.message) + "

    "; foot.hidden = true; } } async function send(resend) { const to = field("to").value, cc = field("cc").value; sendBtn.disabled = true; say("보내는 중…"); try { const res = await fetch(base, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ to: to, cc: cc, resend: !!resend }) }); const out = await res.json(); if (out.resend_needed) { say(""); if (await confirmMsg(out.message)) return send(true); return; } if (out.reconnect) { say(out.message, true); await load(); return; } if (!res.ok || !out.ok) { say(out.message || out.detail || "보내지 못했습니다.", true); return; } sent = true; say(out.message); await load(); } catch (_) { say("보내지 못했습니다(연결 오류). 다시 눌러 주세요.", true); } finally { sendBtn.disabled = false; } } sendBtn.addEventListener("click", function () { send(false); }); dlg.querySelector("[data-gmail-disconnect]").addEventListener("click", async function () { if (!(await confirmMsg("Gmail 연결을 끊을까요? 다음에 보낼 때 다시 연결해야 합니다."))) return; await fetch("/inout/gmail/disconnect", { method: "POST" }); await load(); say("Gmail 연결을 끊었습니다."); }); dlg.addEventListener("click", function (e) { if (e.target.closest("[data-close]")) dlg.close(); }); dlg.addEventListener("close", function () { const url = new URL(location.href); const had = url.searchParams.has(cfg.param); url.searchParams.delete(cfg.param); url.searchParams.delete("msg"); if (sent) location.href = url.toString(); // 보낸 기록(머리·입고 기록 칸)이 바뀌었다 else if (had) history.replaceState(null, "", url.toString()); }); return { open: open }; } })();