// 긴급 공지 관리(/notice/, 수퍼관리자) — 만들기·고치기·취소·이미지·미리 보기·확인 현황. (function () { "use strict"; const root = document.getElementById("ntc-root"); if (!root) return; const $ = function (id) { return document.getElementById(id); }; const people = {}; (window.NTC_PEOPLE || []).forEach(function (p) { people[String(p.email).toLowerCase()] = p.name; }); const nameOf = function (e) { return people[String(e).toLowerCase()] || String(e).split("@")[0]; }; const esc = function (s) { return String(s == null ? "" : s).replace(/[&<>"']/g, function (c) { return { "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[c]; }); }; const shortWhen = function (iso) { const m = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})/.exec(iso || ""); return m ? m[1] + "-" + m[2] + "-" + m[3] + " " + m[4] + ":" + m[5] : ""; }; async function api(method, url, body, isForm) { const opts = { method: method, credentials: "same-origin", headers: {} }; if (body !== undefined) { if (isForm) opts.body = body; else { opts.headers["Content-Type"] = "application/json"; opts.body = JSON.stringify(body); } } const res = await fetch(url, opts); let data = null; try { data = await res.json(); } catch (_) {} if (!res.ok) { const d = data && data.detail; throw new Error(typeof d === "string" ? d : "HTTP " + res.status); } return data || {}; } const title = $("ntc-title"), body = $("ntc-body"), showAt = $("ntc-show-at"), idEl = $("ntc-id"); const peopleBox = $("ntc-people"), msg = $("ntc-msg"), save = $("ntc-save"); const say = function (text, ok) { msg.textContent = text || ""; msg.hidden = !text; msg.style.color = ok ? "#1f7a3a" : ""; }; function toAll() { return root.querySelector('input[name="ntc-to"]:checked').value === "all"; } root.querySelectorAll('input[name="ntc-to"]').forEach(function (r) { r.addEventListener("change", function () { peopleBox.hidden = toAll(); }); }); // ── 본문 편집 — 굵게, 이미지(버튼·붙여넣기·끌어 놓기 → 서버에 올리고 주소로 넣는다) ── root.querySelector('[data-cmd="bold"]').addEventListener("click", function () { body.focus(); document.execCommand("bold"); }); let savedRange = null; body.addEventListener("keyup", keepRange); body.addEventListener("mouseup", keepRange); body.addEventListener("blur", keepRange); function keepRange() { const s = window.getSelection(); if (s.rangeCount && body.contains(s.getRangeAt(0).commonAncestorContainer)) savedRange = s.getRangeAt(0).cloneRange(); } function insertNode(node) { body.focus(); const s = window.getSelection(); let r = savedRange && body.contains(savedRange.commonAncestorContainer) ? savedRange : null; if (!r) { r = document.createRange(); r.selectNodeContents(body); r.collapse(false); } r.deleteContents(); r.insertNode(node); r.setStartAfter(node); r.collapse(true); s.removeAllRanges(); s.addRange(r); savedRange = r.cloneRange(); } let uploading = 0; async function uploadImages(files) { for (const f of files) { if (!/^image\/(png|jpeg|gif|webp)$/.test(f.type)) { say("이미지(png·jpg·gif·webp)만 넣을 수 있습니다: " + f.name); continue; } uploading++; save.disabled = true; try { const fd = new FormData(); fd.append("file", f, f.name || "image"); const res = await api("POST", "/notice/api/images", fd, true); const img = document.createElement("img"); img.src = res.image.url; img.alt = f.name || ""; insertNode(img); say(""); } catch (e) { say("이미지를 올리지 못했습니다: " + e.message); } finally { uploading--; if (!uploading) save.disabled = false; } } } $("ntc-image-btn").addEventListener("click", function () { keepRange(); $("ntc-image-file").click(); }); $("ntc-image-file").addEventListener("change", function (e) { uploadImages(Array.from(e.target.files || [])); e.target.value = ""; }); body.addEventListener("paste", function (e) { const files = Array.from((e.clipboardData && e.clipboardData.files) || []).filter(function (f) { return /^image\//.test(f.type); }); if (files.length) { e.preventDefault(); keepRange(); uploadImages(files); } }); body.addEventListener("dragover", function (e) { e.preventDefault(); }); body.addEventListener("drop", function (e) { const files = Array.from((e.dataTransfer && e.dataTransfer.files) || []).filter(function (f) { return /^image\//.test(f.type); }); if (files.length) { e.preventDefault(); keepRange(); uploadImages(files); } }); // ── 저장(만들기·고치기) ── function payload() { return { title: title.value.trim(), body_html: body.innerHTML, show_at: showAt.value || "", to_all: toAll(), targets: Array.from(peopleBox.querySelectorAll("input:checked")).map(function (c) { return c.value; }), reshow: $("ntc-reshow").checked, }; } function resetForm() { idEl.value = ""; title.value = ""; body.innerHTML = ""; showAt.value = ""; root.querySelector('input[name="ntc-to"][value="all"]').checked = true; peopleBox.hidden = true; peopleBox.querySelectorAll("input").forEach(function (c) { c.checked = false; }); $("ntc-reshow").checked = false; $("ntc-reshow-row").hidden = true; $("ntc-form-title").textContent = "새 긴급 공지"; save.textContent = "공지 만들기"; savedRange = null; } $("ntc-reset").addEventListener("click", function () { resetForm(); say(""); }); let saving = false; save.addEventListener("click", async function () { if (saving || uploading) return; const p = payload(); if (!p.title) { say("제목을 입력하세요."); title.focus(); return; } if (!p.to_all && !p.targets.length) { say("받는 사람을 한 명 이상 고르거나 '전체'를 고르세요."); return; } saving = true; save.disabled = true; try { const id = idEl.value; if (id) await api("PUT", "/notice/api/notices/" + id, p); else await api("POST", "/notice/api/notices", p); resetForm(); say(id ? "공지를 고쳤습니다." : "공지를 만들었습니다. 띄울 시각이 되면 받는 사람 화면 가운데에 나타납니다.", true); await loadList(); } catch (e) { say("저장하지 못했습니다: " + e.message); } finally { saving = false; save.disabled = false; } }); // ── 미리 보기 — 받는 사람 화면과 같은 모양 ── $("ntc-preview").addEventListener("click", function () { preview(title.value.trim() || "(제목 없음)", body.innerHTML); }); function preview(t, html) { const box = document.createElement("div"); box.className = "erp-notice-backdrop"; box.innerHTML = ''; box.querySelector(".erp-notice-title").textContent = t; box.querySelector(".erp-notice-body").innerHTML = html; // 저장하면 서버가 다시 정리한다 document.body.appendChild(box); const ok = box.querySelector(".erp-notice-ok"); ok.addEventListener("click", function () { box.remove(); }); box.addEventListener("keydown", function (e) { if (e.key === "Escape") box.remove(); }); ok.focus(); } // ── 목록 ── let list = []; function stateOf(n) { if (n.cancelled_at) return ["is-cancelled", "취소됨"]; if (new Date(n.show_at) > new Date()) return ["is-scheduled", "예약 " + shortWhen(n.show_at)]; return ["is-live", "표시 중"]; } function render() { const box = $("ntc-list"); if (!list.length) { box.textContent = "아직 공지가 없습니다."; return; } box.innerHTML = list.map(function (n) { const st = stateOf(n); const acked = Object.keys(n.acks || {}); const who = n.to_all ? "전체" : n.targets.map(nameOf).join(", "); const ackLine = n.to_all ? "확인 " + acked.length + "명" : "확인 " + n.targets.filter(function (e) { return n.acks[e]; }).length + " / " + n.targets.length + "명"; const rows = (n.to_all ? acked : n.targets).map(function (e) { return n.acks[e] ? "
  • " + esc(nameOf(e)) + " — " + esc(shortWhen(n.acks[e])) + "
  • " : '
  • ' + esc(nameOf(e)) + " — 아직 확인 안 함
  • "; }).join(""); return '
    ' + '
    ' + esc(st[1]) + "" + '' + esc(n.title) + "" + '' + '' + '' + '" + "
    " + '
    띄울 시각 ' + esc(shortWhen(n.show_at)) + " · 받는 사람 " + esc(who) + " · 만든 사람 " + esc(nameOf(n.created_by)) + "
    " + '
    ' + esc(ackLine) + "
    " + "
    "; }).join(""); } async function loadList() { try { list = (await api("GET", "/notice/api/notices")).notices || []; render(); } catch (e) { $("ntc-list").textContent = "목록을 읽지 못했습니다: " + e.message; } } $("ntc-list").addEventListener("click", async function (e) { const b = e.target.closest("[data-act]"); if (!b) return; const n = list.find(function (x) { return String(x.id) === b.closest(".ntc-item").dataset.id; }); if (!n) return; if (b.dataset.act === "preview") { preview(n.title, n.body_html); return; } if (b.dataset.act === "edit") { idEl.value = n.id; title.value = n.title; body.innerHTML = n.body_html; showAt.value = (n.show_at || "").slice(0, 16); root.querySelector('input[name="ntc-to"][value="' + (n.to_all ? "all" : "some") + '"]').checked = true; peopleBox.hidden = n.to_all; peopleBox.querySelectorAll("input").forEach(function (c) { c.checked = n.targets.indexOf(c.value.toLowerCase()) >= 0; }); $("ntc-reshow-row").hidden = false; $("ntc-reshow").checked = false; $("ntc-form-title").textContent = "공지 고치기"; save.textContent = "고친 내용 저장"; say(""); title.focus(); return; } if (b.dataset.act === "cancel") { const cancel = !n.cancelled_at; if (cancel) { const q = "'" + n.title + "' 공지를 취소할까요? 아직 확인하지 않은 사람에게도 더 뜨지 않습니다."; const yes = window.erpConfirm ? await window.erpConfirm(q, { okText: "공지 취소", cancelText: "닫기" }) : window.confirm(q); if (!yes) return; } b.disabled = true; try { await api("POST", "/notice/api/notices/" + n.id + "/cancel", { cancel: cancel }); await loadList(); } catch (err) { say("처리하지 못했습니다: " + err.message); b.disabled = false; } } }); loadList(); })();