/* 안내문 발송(2026-10-27) — 리스트 화면: 붙여 넣기 → 미리보기(메일/DM/오류) → 추가, 걸러 보기, 이름 고치기, 메일 = 고른 줄 [고른 메일 보내기](서버가 본인 Gmail 로 한 통씩, 보내는 동안 2초마다 다시 읽음), DM = [DM 보내기](그 사람 이름이 들어간 문구를 클립보드에 + ig.me DM 창을 새 탭) → [보냄]. 설정 화면 = 세로 2단(메일 | DM) — 메일 본문 서식 편집기·DM 편집기(Quill), {이름} 빨강 굵게, [기본 문구로 되돌리기], DM 글자 수. */ (function () { "use strict"; function esc(s) { return String(s == null ? "" : s).replace(/[&<>"']/g, function (c) { return { "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[c]; }); } async function api(method, url, body) { const res = await fetch(url, { method: method, headers: body ? { "Content-Type": "application/json" } : {}, body: body ? JSON.stringify(body) : undefined, credentials: "same-origin" }); let data = {}; try { data = await res.json(); } catch (_) { data = {}; } if (!res.ok) { const e = new Error(data.message || data.detail || ("HTTP " + res.status)); e.status = res.status; e.data = data; throw e; } return data; } function toast(msg, bad) { let el = document.getElementById("otr-toast"); if (!el) { el = document.createElement("div"); el.id = "otr-toast"; el.className = "otr-toast"; document.body.appendChild(el); } el.textContent = msg; el.classList.toggle("is-bad", !!bad); el.hidden = false; clearTimeout(el._t); el._t = setTimeout(function () { el.hidden = true; }, 4000); } async function copyText(text) { try { await navigator.clipboard.writeText(text); return true; } catch (_) { /* 아래로 */ } const ta = document.createElement("textarea"); ta.value = text; ta.style.position = "fixed"; ta.style.top = "-1000px"; document.body.appendChild(ta); ta.select(); let ok = false; try { ok = document.execCommand("copy"); } catch (_) { ok = false; } ta.remove(); return ok; } // ── 설정 화면 ── const setForm = document.getElementById("otr-set-form"); if (setForm) { if (window.Quill) initSettings(window.Quill, setForm); else toast("편집기를 불러오지 못했습니다 — 새로 고침해 주세요.", true); } // 메일 본문 = 서식 편집기(글자 크기·굵게·기울임·밑줄·취소선·글자/배경 색·정렬·목록·링크·서식 지우기·되돌리기), // DM = 서식 없는 편집기. 두 편집기 모두 {이름} = 빨강 굵게(class 만 — 저장하면 서버가 class 를 지워 메일에는 안 남음). // 저장 = 메일 본문 getSemanticHTML() → body(fmt=html, 서버가 허용 태그만 남김), DM getText() → dm_body. function initSettings(Quill, form) { const TAG = "{이름}"; const SIZES = ["12px", "16px", "18px", "20px", "24px", "30px"]; // 없음(false) = 기본 14px const Parchment = Quill.import("parchment"); Quill.register(new Parchment.ClassAttributor("nametag", "otr-nametag", { scope: Parchment.Scope.INLINE }), true); const Size = Quill.import("attributors/style/size"); Size.whitelist = SIZES; Quill.register(Size, true); Quill.register(Quill.import("attributors/style/align"), true); function readJson(id) { try { return JSON.parse(document.getElementById(id).textContent) || {}; } catch (_) { return {}; } } const mail = new Quill("#otr-body-editor", { theme: "snow", placeholder: "메일 본문", modules: { history: { userOnly: true }, toolbar: { container: [ [{ size: [false].concat(SIZES) }], ["bold", "italic", "underline", "strike"], [{ color: [] }, { background: [] }], [{ align: [] }], [{ list: "ordered" }, { list: "bullet" }], ["link", "clean"], ["undo", "redo"], ], handlers: { undo: function () { mail.history.undo(); }, redo: function () { mail.history.redo(); } }, }, }, }); const dmEl = document.getElementById("otr-dm-editor"); const dm = new Quill(dmEl, { theme: "snow", placeholder: dmEl.dataset.placeholder || "", formats: ["nametag"], modules: { toolbar: false, history: { userOnly: true } } }); // 도구 막대 — 되돌리기 아이콘, 한글 도움말 const tb = mail.getModule("toolbar").container; tb.querySelector(".ql-undo").innerHTML = "↶"; tb.querySelector(".ql-redo").innerHTML = "↷"; const tips = { ".ql-size": "글자 크기", ".ql-bold": "굵게 (Ctrl+B)", ".ql-italic": "기울임 (Ctrl+I)", ".ql-underline": "밑줄 (Ctrl+U)", ".ql-strike": "취소선", ".ql-color": "글자 색", ".ql-background": "배경 색", ".ql-align": "정렬", '.ql-list[value="ordered"]': "번호 목록", '.ql-list[value="bullet"]': "글머리 목록", ".ql-link": "링크", ".ql-clean": "서식 지우기", ".ql-undo": "되돌리기 (Ctrl+Z)", ".ql-redo": "다시 하기 (Ctrl+Y)" }; Object.keys(tips).forEach(function (sel) { tb.querySelectorAll(sel).forEach(function (el) { el.title = tips[sel]; }); }); // {이름} 빨강 굵게 — 지금 칠한 곳과 있어야 할 곳이 다를 때만 고친다(글자 칠 때마다 DOM 을 건드리지 않게, 한글 조합 중엔 쉼) function markNames(q) { if (q.composition && q.composition.isComposing) return; const text = q.getText(), want = []; for (let i = text.indexOf(TAG); i >= 0; i = text.indexOf(TAG, i + TAG.length)) { const last = want[want.length - 1]; if (last && last[1] === i) last[1] = i + TAG.length; else want.push([i, i + TAG.length]); } const have = []; let pos = 0; q.getContents().ops.forEach(function (op) { const len = typeof op.insert === "string" ? op.insert.length : 1; if (op.attributes && op.attributes.nametag) { const last = have[have.length - 1]; if (last && last[1] === pos) last[1] = pos + len; else have.push([pos, pos + len]); } pos += len; }); if (JSON.stringify(want) === JSON.stringify(have)) return; have.forEach(function (r) { q.formatText(r[0], r[1] - r[0], "nametag", false, "silent"); }); want.forEach(function (r) { q.formatText(r[0], r[1] - r[0], "nametag", "on", "silent"); }); } function setMail(html) { mail.setContents(mail.clipboard.convert({ html: html || "" }), "silent"); markNames(mail); } function setDm(text) { dm.setText(text || "", "silent"); markNames(dm); dmCount(); } // DM 글자 수(인스타 DM 한 통 한도) const countEl = document.getElementById("otr-dm-count"), dmMax = Number(countEl.dataset.max) || 1000; function dmValue() { return dm.getText().replace(/\s+$/, ""); } function dmCount() { const n = dmValue().length; countEl.textContent = n ? n + " / " + dmMax + "자" : "비어 있음 — 메일 본문 글 + 끝 문구가 복사됩니다"; countEl.classList.toggle("is-over", n > dmMax); } let dirty = false; mail.on("text-change", function (d, o, source) { if (source !== "silent") { dirty = true; markNames(mail); } }); dm.on("text-change", function (d, o, source) { if (source !== "silent") { dirty = true; markNames(dm); dmCount(); } }); document.addEventListener("input", function (e) { if (e.target.form === form) dirty = true; }); window.addEventListener("beforeunload", function (e) { if (dirty) { e.preventDefault(); e.returnValue = ""; } }); const cur = readJson("otr-current-data"); setMail(cur.body); setDm(cur.dm_body); document.getElementById("otr-dm-from-mail").addEventListener("click", function () { if (dmValue() && !confirm("지금 DM 문구를 메일 본문 글로 바꿀까요?")) return; setDm(mail.getText().replace(/\s+$/, "")); dirty = true; }); document.getElementById("otr-default").addEventListener("click", function () { if (!confirm("제목·본문·보내는 이름·끝 문구·DM 문구를 기본 문구로 바꿀까요? ([저장]을 눌러야 적용)")) return; const d = readJson("otr-default-data"); form.elements.subject.value = d.subject || ""; form.elements.sender_name.value = d.sender_name || ""; form.elements.footer.value = d.footer || ""; form.elements.ad_label.checked = !!d.ad_label; setMail(d.body); setDm(d.dm_body); dirty = true; }); form.addEventListener("submit", function (e) { if (!mail.getText().trim()) { e.preventDefault(); toast("메일 본문을 쓰세요.", true); mail.focus(); return; } if (dmValue().length > dmMax) { e.preventDefault(); toast("DM 문구가 " + dmMax + "자를 넘습니다 — 줄여 주세요.", true); dm.focus(); return; } document.getElementById("otr-body-input").value = mail.getSemanticHTML(); document.getElementById("otr-dm-input").value = dmValue(); dirty = false; }); } // ── 리스트 화면 ── const root = document.getElementById("otr"); const tbody = document.getElementById("otr-tbody"); if (!root || !tbody) return; let rows = []; try { rows = JSON.parse(document.getElementById("otr-data").textContent).rows || []; } catch (_) { rows = []; } let filter = "all"; const picked = new Set(); let pollTimer = null; function visible(r) { if (filter === "all") return true; if (filter === "email" || filter === "instagram") return r.kind === filter; return r.status === filter; } function when(iso) { return iso ? iso.slice(5, 16).replace("T", " ") : ""; } function render() { const counts = { all: rows.length, email: 0, instagram: 0, "대기": 0, "보냄": 0, "실패": 0 }; rows.forEach(function (r) { counts[r.kind]++; if (counts[r.status] != null) counts[r.status]++; }); document.querySelectorAll("[data-cnt]").forEach(function (n) { n.textContent = counts[n.dataset.cnt] || 0; }); const shown = rows.filter(visible); tbody.innerHTML = shown.map(function (r) { const status = r.status === "실패" ? '실패' + (r.last_error ? '
' + esc(r.last_error) + "
" : "") : '' + esc(r.status) + ""; const acts = r.kind === "instagram" ? '' + (r.status !== "보냄" ? '' : "") : ''; const addr = r.kind === "instagram" ? '@' + esc(r.handle) + "" : esc(r.handle); return '' + '' + '' + esc(r.kind_label) + "" + '' + '' + addr + "" + "" + status + "" + '' + esc(when(r.sent_at)) + (r.sent_via ? ' ' + (r.sent_via === "dm" ? "DM" : "Gmail") + "" : "") + "" + '' + acts + ""; }).join(""); document.getElementById("otr-empty").hidden = rows.length > 0; const sel = rows.filter(function (r) { return picked.has(r.id); }); const mails = sel.filter(function (r) { return r.kind === "email" && (r.status === "대기" || r.status === "실패"); }).length; document.getElementById("otr-selected").textContent = "고른 줄 " + sel.length + " · 보낼 메일 " + mails; const all = document.getElementById("otr-check-all"); all.checked = shown.length > 0 && shown.every(function (r) { return picked.has(r.id); }); if (rows.some(function (r) { return r.status === "발송중"; })) startPoll(); else stopPoll(); } async function reload() { const d = await api("GET", "/outreach/api/recipients"); rows = d.rows || []; const ids = new Set(rows.map(function (r) { return r.id; })); Array.from(picked).forEach(function (id) { if (!ids.has(id)) picked.delete(id); }); render(); } function startPoll() { if (!pollTimer) pollTimer = setInterval(function () { reload().catch(function () {}); }, 2000); } function stopPoll() { if (pollTimer) { clearInterval(pollTimer); pollTimer = null; } } function rowOf(node) { const tr = node.closest("tr[data-id]"); return tr ? rows.find(function (r) { return r.id === +tr.dataset.id; }) : null; } document.querySelectorAll("[data-filter]").forEach(function (b) { b.addEventListener("click", function () { filter = b.dataset.filter; document.querySelectorAll("[data-filter]").forEach(function (x) { x.classList.toggle("is-active", x === b); }); render(); }); }); document.getElementById("otr-check-all").addEventListener("change", function (e) { rows.filter(visible).forEach(function (r) { if (e.target.checked) picked.add(r.id); else picked.delete(r.id); }); render(); }); tbody.addEventListener("change", function (e) { if (e.target.matches("[data-pick]")) { const r = rowOf(e.target); if (e.target.checked) picked.add(r.id); else picked.delete(r.id); render(); } }); // 이름 — 칸을 떠나면(또는 Enter) 저장 tbody.addEventListener("focusout", async function (e) { if (!e.target.matches(".otr-name")) return; const r = rowOf(e.target); const v = e.target.value.trim(); if (!r || v === (r.name || "")) return; try { const d = await api("PUT", "/outreach/api/recipients/" + r.id, { name: v }); Object.assign(r, d.row); render(); } catch (err) { toast("이름 저장 실패: " + err.message, true); e.target.value = r.name || ""; } }); tbody.addEventListener("keydown", function (e) { if (e.target.matches(".otr-name") && e.key === "Enter" && !e.isComposing) { e.preventDefault(); e.target.blur(); } }); tbody.addEventListener("click", async function (e) { const btn = e.target.closest("[data-act]"); if (!btn) return; const r = rowOf(btn); if (!r) return; if (btn.dataset.act === "dm") { if (r.needs_name) { toast("이름을 먼저 넣으세요 — DM 문구에 {이름}이 있습니다.", true); return; } // 누르는 순간 바로(브라우저가 막지 않게) — 문구 복사 + DM 창 새 탭. 문구는 화면 데이터에 미리 있다. const win = window.open(r.dm_link, "_blank", "noopener"); const ok = await copyText(r.dm_text || ""); toast(ok ? "@" + r.handle + " DM 문구를 복사했습니다 — 열린 인스타 DM 창에 붙여 넣어(Ctrl+V) 보낸 뒤 [보냄]을 누르세요." : "문구를 복사하지 못했습니다 — [미리보기]가 아니라 DM 창에 직접 적어 주세요.", !ok); if (!win) toast("인스타 창이 막혔습니다 — 브라우저 팝업 허용 뒤 다시 누르세요(문구는 복사됨).", true); } else if (btn.dataset.act === "dm-sent") { btn.disabled = true; try { const d = await api("POST", "/outreach/api/recipients/" + r.id + "/dm-sent"); Object.assign(r, d.row); render(); } catch (err) { btn.disabled = false; toast("기록 실패: " + err.message, true); } } else if (btn.dataset.act === "preview") { try { showPreview(await api("GET", "/outreach/api/recipients/" + r.id + "/preview"), r); } catch (err) { toast("미리보기 실패: " + err.message, true); } } }); // 미리보기 창 const pv = document.getElementById("otr-preview"); function showPreview(d, r) { document.getElementById("otr-pv-title").textContent = (d.kind === "email" ? "메일 미리보기 → " : "DM 미리보기 → ") + d.to; document.getElementById("otr-pv-subject").textContent = d.kind === "email" ? "제목: " + d.subject + " · 보내는 이름: " + (d.sender_name || "") : ""; document.getElementById("otr-pv-frame").srcdoc = d.kind === "email" ? d.html : '
' + esc(d.text) + "
"; pv.hidden = false; } pv.addEventListener("click", function (e) { if (e.target === pv || e.target.closest("[data-close]")) pv.hidden = true; }); document.addEventListener("keydown", function (e) { if (e.key === "Escape" && !pv.hidden) pv.hidden = true; }); // 보내기 · 다시 대기 · 지우기 const sendBtn = document.getElementById("otr-send"); sendBtn.addEventListener("click", async function () { const sel = rows.filter(function (r) { return picked.has(r.id) && r.kind === "email" && (r.status === "대기" || r.status === "실패"); }); if (!sel.length) { toast("보낼 메일 줄(대기·실패)을 고르세요.", true); return; } const noName = sel.filter(function (r) { return r.needs_name; }).length; if (!confirm(sel.length + "명에게 메일을 보낼까요?" + (noName ? "\n(이름 없는 " + noName + "명은 보내지 않고 '실패'로 남습니다)" : ""))) return; sendBtn.disabled = true; try { const d = await api("POST", "/outreach/api/send", { ids: sel.map(function (r) { return r.id; }) }); toast(d.queued + "통을 보내는 중입니다 — 상태가 '보냄'으로 바뀝니다."); await reload(); } catch (err) { toast(err.data && err.data.reconnect ? err.message : "보내기 실패: " + err.message, true); } finally { sendBtn.disabled = false; } }); document.getElementById("otr-reset").addEventListener("click", async function () { const sel = rows.filter(function (r) { return picked.has(r.id) && (r.status === "보냄" || r.status === "실패"); }); if (!sel.length) { toast("보냄·실패 줄을 고르세요.", true); return; } if (!confirm(sel.length + "줄을 다시 '대기'로 둘까요? (다시 보낼 수 있게)")) return; for (const r of sel) { try { const d = await api("PUT", "/outreach/api/recipients/" + r.id, { status: "대기" }); Object.assign(r, d.row); } catch (err) { toast("실패: " + err.message, true); break; } } render(); }); document.getElementById("otr-delete").addEventListener("click", async function () { const ids = Array.from(picked); if (!ids.length) { toast("지울 줄을 고르세요.", true); return; } if (!confirm(ids.length + "줄을 리스트에서 지울까요? (보낸 기록은 남습니다)")) return; try { await api("POST", "/outreach/api/recipients/delete", { ids: ids }); ids.forEach(function (i) { picked.delete(i); }); await reload(); } catch (err) { toast("지우기 실패: " + err.message, true); } }); // 리스트 추가 — 미리보기(판별) → 추가 const addBox = document.getElementById("otr-add"), addText = document.getElementById("otr-add-text"); const addSave = document.getElementById("otr-add-save"), addResult = document.getElementById("otr-add-result"); document.getElementById("otr-add-open").addEventListener("click", function () { addBox.hidden = false; addText.focus(); }); document.getElementById("otr-add-close").addEventListener("click", function () { addBox.hidden = true; }); addText.addEventListener("input", function () { addSave.disabled = true; }); document.getElementById("otr-add-preview").addEventListener("click", async function () { try { const d = await api("POST", "/outreach/api/recipients/parse", { text: addText.value }); const ok = d.rows.filter(function (r) { return r.kind && !r.dup && !r.exists; }); addResult.hidden = false; addResult.innerHTML = '' + d.rows.map(function (r) { const note = !r.kind ? '' + esc(r.error) + "" : r.dup ? "같은 주소가 위에 있음(건너뜀)" : r.exists ? "이미 리스트에 있음(이름이 비었으면 채움)" : r.name ? "" : '이름 없음'; return '"; }).join("") + "
줄구분이름주소
' + r.line + '' + esc(r.kind_label) + "" + esc(r.name) + "" + esc(r.kind === "instagram" ? "@" + r.handle : r.handle || r.address) + "" + note + "
"; const bad = d.rows.filter(function (r) { return !r.kind; }).length; document.getElementById("otr-add-sum").textContent = "새로 " + ok.length + "명 (메일 " + ok.filter(function (r) { return r.kind === "email"; }).length + " · DM " + ok.filter(function (r) { return r.kind === "instagram"; }).length + ")" + (bad ? " · 오류 " + bad + "줄(추가 안 됨)" : ""); addSave.disabled = !d.rows.some(function (r) { return r.kind && !r.dup; }); } catch (err) { toast("미리보기 실패: " + err.message, true); } }); addSave.addEventListener("click", async function () { addSave.disabled = true; try { const d = await api("POST", "/outreach/api/recipients", { text: addText.value }); toast("추가 " + d.added + "명" + (d.existed ? " · 이미 있던 " + d.existed + "명" : "") + (d.invalid ? " · 오류 " + d.invalid + "줄" : "")); addText.value = ""; addResult.hidden = true; document.getElementById("otr-add-sum").textContent = ""; addBox.hidden = true; await reload(); } catch (err) { addSave.disabled = false; toast("추가 실패: " + err.message, true); } }); render(); })();