/* 실적(쇼핑몰 통합 매출) — 대시보드 / 설정 화면 동작. * * 쇼핑몰 API 는 브라우저에서 직접 부르지 않는다. 모든 요청은 우리 서버(/performance/api/…)로만. * 인증정보 창은 저장된 비밀값을 받지 않는다(서버가 "저장됨" 여부만 준다). */ (function () { "use strict"; // ── 공통 ───────────────────────────────────────────── function el(tag, attrs, html) { const n = document.createElement(tag); Object.keys(attrs || {}).forEach(function (k) { if (k === "class") n.className = attrs[k]; else if (k === "text") n.textContent = attrs[k]; else n.setAttribute(k, attrs[k]); }); if (html != null) n.innerHTML = html; return n; } function esc(s) { return String(s == null ? "" : s).replace(/[&<>"']/g, function (c) { return { "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[c]; }); } function fmt(n) { return Number(n || 0).toLocaleString("ko-KR"); } function won(n) { return n ? fmt(n) : '–'; } // 축 눈금용 짧은 금액(1.2억 / 350만) function short(n) { const a = Math.abs(n), s = n < 0 ? "-" : ""; if (a >= 100000000) return s + (a / 100000000).toFixed(a >= 1000000000 ? 0 : 1).replace(/\.0$/, "") + "억"; if (a >= 10000) return s + Math.round(a / 10000).toLocaleString("ko-KR") + "만"; return s + fmt(a); } function alertMsg(msg) { return window.erpAlert ? window.erpAlert(msg) : Promise.resolve(window.alert(msg)); } function confirmMsg(msg) { return window.erpConfirm ? window.erpConfirm(msg) : Promise.resolve(window.confirm(msg)); } async function api(method, url, body) { const res = await fetch(url, { method: method, credentials: "same-origin", headers: body ? { "Content-Type": "application/json" } : {}, body: body ? JSON.stringify(body) : undefined, }); let data = null; try { data = await res.json(); } catch (_) { data = null; } if (!res.ok) { const detail = data && data.detail; throw new Error(typeof detail === "string" ? detail : "요청 실패 (" + res.status + ")"); } return data || {}; } // 간단한 창. 반환: { card, body, foot, close } function openModal(title, opts) { opts = opts || {}; const back = el("div", { class: "perf-modal" }); const card = el("div", { class: "perf-modal-card" + (opts.narrow ? " is-narrow" : ""), role: "dialog", "aria-modal": "true" }); const head = el("div", { class: "perf-modal-head" }); head.appendChild(el("h3", { text: title })); const x = el("button", { type: "button", class: "perf-modal-x", "aria-label": "닫기" }, "×"); head.appendChild(x); const body = el("div", { class: "perf-modal-body" }); const foot = el("div", { class: "perf-modal-foot" }); card.appendChild(head); card.appendChild(body); card.appendChild(foot); back.appendChild(card); document.body.appendChild(back); function onKey(e) { if (e.key === "Escape") close(); } function close() { document.removeEventListener("keydown", onKey, true); back.remove(); if (opts.onClose) opts.onClose(); } x.addEventListener("click", close); back.addEventListener("mousedown", function (e) { if (e.target === back) close(); }); document.addEventListener("keydown", onKey, true); return { card: card, body: body, foot: foot, close: close }; } // ════════════════════════════════════════════════════ // 대시보드 // ════════════════════════════════════════════════════ function initDashboard(root) { const data = JSON.parse((document.getElementById("perf-data") || {}).textContent || "{}"); const METRIC_NAMES = { gross: "총매출", commission: "수수료", net: "수수료 차감 매출" }; const KEY = "perf_metric"; // 표시 기준 전환 — 서버가 세 값을 다 그려 두었고 CSS 가 하나만 보인다. function setMetric(m) { if (!METRIC_NAMES[m]) m = "gross"; root.dataset.metric = m; root.querySelectorAll(".perf-metric .perf-seg").forEach(function (b) { b.classList.toggle("is-active", b.dataset.metric === m); }); try { localStorage.setItem(KEY, m); } catch (_) {} drawDaily(m); drawShare(m); root.querySelectorAll(".perf-metric-name").forEach(function (n) { n.textContent = METRIC_NAMES[m]; }); } root.querySelectorAll(".perf-metric .perf-seg").forEach(function (b) { b.addEventListener("click", function () { setMetric(b.dataset.metric); }); }); // 직접선택 / 쇼핑몰 필터 const customBtn = document.getElementById("perf-custom-btn"); const customForm = document.getElementById("perf-custom"); if (customBtn && customForm) customBtn.addEventListener("click", function () { customForm.hidden = !customForm.hidden; if (!customForm.hidden) customForm.querySelector("input[type=date]").focus(); }); const checkAll = root.querySelector("[data-perf-check-all]"); if (checkAll) checkAll.addEventListener("click", function () { const boxes = root.querySelectorAll(".perf-filter-pop input[type=checkbox]"); const allOn = Array.prototype.every.call(boxes, function (b) { return b.checked; }); boxes.forEach(function (b) { b.checked = !allOn; }); }); document.addEventListener("click", function (e) { const f = document.getElementById("perf-filter"); if (f && f.open && !f.contains(e.target)) f.open = false; }); // 매출 업데이트 — 서버가 쇼핑몰별로 따로 수집(한 곳 실패해도 나머지 반영) const syncBtn = document.getElementById("perf-sync-btn"); const resultBox = document.getElementById("perf-sync-result"); if (syncBtn) syncBtn.addEventListener("click", async function () { syncBtn.disabled = true; const label = syncBtn.textContent; syncBtn.textContent = "업데이트 중…"; try { const res = await api("POST", "/performance/api/sync", {}); // 실패(빨강)는 인증 실패·API 오류처럼 손봐야 하는 것만. 인증정보를 아직 안 넣은 쇼핑몰(미설정)과 // 수집을 아직 만들지 않은 쇼핑몰(연동 준비 중)은 회색 한 줄로 이름만. const ok = [], bad = [], pending = [], unset = [], busy = []; let changed = 0; (res.results || []).forEach(function (r) { const name = (data.names || {})[r.code] || r.code; if (r.skipped) busy.push(name); else if (r.ok) { ok.push(name + " " + fmt(r.upserted) + "건"); changed += r.upserted; } else if (r.status === "not_implemented") pending.push(name); else if (r.status === "not_configured") unset.push(name); else bad.push(name + "(" + (r.label || r.status) + (r.message ? ": " + r.message : "") + ")"); }); const parts = []; if (ok.length) parts.push("반영 " + esc(ok.join(", "))); if (bad.length) parts.push("실패 " + esc(bad.join(", "))); if (busy.length) parts.push("이미 진행 중 " + esc(busy.join(", "))); if (pending.length) parts.push('연동 준비 중: ' + esc(pending.join(", ")) + ""); if (unset.length) parts.push('인증정보 미설정: ' + esc(unset.join(", ")) + ""); resultBox.innerHTML = parts.join(" · ") || "업데이트할 쇼핑몰이 없습니다."; resultBox.className = "perf-notice" + (bad.length ? " is-warn" : " is-ok"); resultBox.hidden = false; if (res.last_update_at) { const lu = document.querySelector("#perf-last-update b"); if (lu) lu.textContent = res.last_update_at.slice(0, 16).replace("T", " "); } if (changed > 0) setTimeout(function () { location.reload(); }, 1200); } catch (err) { resultBox.textContent = "업데이트 실패: " + err.message; resultBox.className = "perf-notice is-warn"; resultBox.hidden = false; } finally { syncBtn.disabled = false; syncBtn.textContent = label === "업데이트 중…" ? "매출 업데이트" : label; } }); // 금액 클릭 → 주문 상세 root.addEventListener("click", function (e) { const td = e.target.closest("td.is-link"); if (!td) return; openEvents(td.dataset.code, td.dataset.from, td.dataset.to); }); async function openEvents(code, from, to) { const name = (data.names || {})[code] || code; const title = name + " · " + (from === to ? from : from + " ~ " + to) + " 주문 내역"; const m = openModal(title); m.body.innerHTML = '
불러오는 중…
'; try { const res = await api("GET", "/performance/api/events?code=" + encodeURIComponent(code) + "&from=" + encodeURIComponent(from) + "&to=" + encodeURIComponent(to)); const rows = res.rows || []; if (!rows.length) { m.body.innerHTML = '내역이 없습니다.
'; return; } const KIND = { SALE: "결제", CANCEL: "취소", RETURN: "반품", ADJUST: "조정" }; let sum = 0, sales = 0, minus = 0; const body = rows.map(function (r) { sum += r.amount; if (r.amount >= 0) sales += r.amount; else minus += r.amount; return '| 매출일 | 구분 | 주문번호 | ' + '상품명 | 수량 | 금액 | 주문일 | ' + '결제일 | 상태 |
|---|---|---|---|---|---|---|---|---|
| 결제 ' + fmt(sales) + " / 취소·반품 " + fmt(minus) + ' | ' + fmt(sum) + ' | |||||||
처음 500건만 표시합니다.
' : "") + '수수료는 일·쇼핑몰 단위로 계산되어 주문별로는 표시하지 않습니다.
'; } catch (err) { m.body.innerHTML = '' + esc(err.message) + "
"; } } // ── 그래프(SVG) ── function svg(w, h, inner) { return '"; } function niceMax(v) { if (v <= 0) return 1; const p = Math.pow(10, Math.floor(Math.log10(v))); const n = v / p; return (n <= 1 ? 1 : n <= 2 ? 2 : n <= 5 ? 5 : 10) * p; } function drawDaily(metric) { const box = document.getElementById("perf-chart-daily"); if (!box) return; const pts = data.daily || []; const vals = pts.map(function (p) { return p[metric] || 0; }); if (!pts.length || vals.every(function (v) { return !v; })) { box.innerHTML = '| 적용 시작일 | 요율 | ' + '메모 | 변경자 | |
|---|---|---|---|---|
| " + esc(eff) + ' | ' + esc(String(r.rate_percent).replace(/\.?0+$/, "")) + "% | " + esc(r.memo) + " | " + esc((r.created_by || "").split("@")[0]) + ' |
불러오는 중…
'; let info; try { info = await api("GET", "/performance/api/marketplaces/" + code + "/credentials"); } catch (err) { m.body.innerHTML = '' + esc(err.message) + "
"; return; } const result = el("span", { class: "perf-test-result" }); m.foot.appendChild(result); const testBtn = el("button", { type: "button", class: "erp-btn erp-btn-outline" }, "연결 테스트"); m.foot.appendChild(testBtn); let html = ""; if (info.note) html += '' + esc(info.note) + "
"; if (info.docs_url) html += 'API 문서: ' + esc(info.docs_url) + "
"; if (info.shared) { m.body.innerHTML = html + '이 쇼핑몰은 기존 공통 연동을 사용합니다. 연결 테스트로 상태만 확인할 수 있습니다.
'; } else { if (!info.key || !info.key.ok) html += '' + esc((info.key && info.key.message) || "암호화 키가 없습니다.") + "
"; if (info.decrypt_error) html += '' + esc(info.decrypt_error) + "
"; html += '" + '[연결 테스트]는 입력한 새 값으로 시험하며 저장하지 않습니다(빈 칸은 저장된 값 사용). ' + "[저장]은 연결 테스트 결과와 관계없이 저장합니다 — 쇼핑몰의 일시 장애로 테스트가 실패할 수 있기 때문입니다. " + "저장 후 자동으로 한 번 더 연결 테스트를 합니다.
"; m.body.innerHTML = html; const saveBtn = el("button", { type: "button", class: "erp-btn erp-btn-primary" }, "저장"); m.foot.appendChild(saveBtn); saveBtn.addEventListener("click", async function () { saveBtn.disabled = true; try { await api("PUT", "/performance/api/marketplaces/" + code + "/credentials", { values: typed(), clear: cleared() }); m.changed = true; m.body.querySelectorAll("input[type=password]").forEach(function (i) { i.value = ""; }); result.className = "perf-test-result"; result.textContent = "저장했습니다. 연결 확인 중…"; await test(false); } catch (err) { result.className = "perf-test-result is-bad"; result.textContent = "저장 실패: " + err.message; } finally { saveBtn.disabled = false; } }); } function typed() { const out = {}; m.body.querySelectorAll("input[data-key]").forEach(function (i) { if (i.value.trim()) out[i.dataset.key] = i.value.trim(); }); return out; } function cleared() { return Array.prototype.filter.call(m.body.querySelectorAll("input[data-clear]"), function (c) { return c.checked; }) .map(function (c) { return c.dataset.clear; }); } async function test(withTyped) { testBtn.disabled = true; result.className = "perf-test-result"; result.textContent = "연결 확인 중…"; try { const res = await api("POST", "/performance/api/marketplaces/" + code + "/test", withTyped ? { values: typed() } : {}); result.className = "perf-test-result " + (res.ok ? "is-ok" : "is-bad"); result.textContent = (res.ok ? "● " : "● " + res.label + " — ") + res.message + (res.unsaved ? " (저장 안 한 값으로 시험)" : ""); if (!res.unsaved) m.changed = true; } catch (err) { result.className = "perf-test-result is-bad"; result.textContent = err.message; } finally { testBtn.disabled = false; } } testBtn.addEventListener("click", function () { test(true); }); } async function runTest(code, name, btn) { btn.disabled = true; const label = btn.textContent; btn.textContent = "확인 중…"; try { const res = await api("POST", "/performance/api/marketplaces/" + code + "/test", {}); await alertMsg(name + " — " + (res.ok ? "정상 연결\n" : res.label + "\n") + res.message); location.reload(); } catch (err) { alertMsg(err.message); } finally { btn.disabled = false; btn.textContent = label; } } // ── 과거 매출 가져오기(기간 지정 수집, 관리자) ── const backfill = document.getElementById("perf-backfill"); if (backfill) backfill.addEventListener("click", async function () { const from = document.getElementById("perf-backfill-from").value; const to = document.getElementById("perf-backfill-to").value; const box = document.getElementById("perf-backfill-result"); if (!from || !to) return; if (!(await confirmMsg(from + " ~ " + to + " 매출을 연동된 쇼핑몰에서 가져옵니다. 기간이 길면 몇 분 걸릴 수 있습니다."))) return; const names = {}; root.querySelectorAll("tr[data-code]").forEach(function (tr) { names[tr.dataset.code] = tr.dataset.name; }); backfill.disabled = true; backfill.textContent = "가져오는 중…"; box.hidden = true; try { const res = await api("POST", "/performance/api/sync", { from: from, to: to }); const ok = [], bad = [], rest = []; (res.results || []).forEach(function (r) { const name = names[r.code] || r.code; if (r.ok) ok.push(name + " " + fmt(r.upserted) + "건"); else if (r.skipped) rest.push(name + "(이미 진행 중)"); else if (r.status === "not_implemented" || r.status === "not_configured") rest.push(name); else bad.push(name + "(" + (r.label || r.status) + ": " + (r.message || "") + ")"); }); box.innerHTML = [ ok.length ? "반영 " + esc(ok.join(", ")) : "", bad.length ? "실패 " + esc(bad.join(", ")) : "", rest.length ? '건너뜀(미연동·미설정): ' + esc(rest.join(", ")) + "" : "", ].filter(Boolean).join(" · ") || "가져올 쇼핑몰이 없습니다."; box.className = "perf-notice" + (bad.length ? " is-warn" : " is-ok"); box.hidden = false; } catch (err) { box.textContent = "가져오기 실패: " + err.message; box.className = "perf-notice is-warn"; box.hidden = false; } finally { backfill.disabled = false; backfill.textContent = "가져오기"; } }); // ── 테스트 데이터 / 재암호화 ── const gen = document.getElementById("perf-sample-gen"); if (gen) gen.addEventListener("click", async function () { gen.disabled = true; try { const res = await api("POST", "/performance/api/sample-data", { action: "generate", from: document.getElementById("perf-sample-from").value, to: document.getElementById("perf-sample-to").value, }); await alertMsg("테스트 데이터 " + fmt(res.generated) + "건을 만들었습니다(같은 기간을 다시 만들면 덮어씀)."); location.reload(); } catch (err) { alertMsg(err.message); } finally { gen.disabled = false; } }); const del = document.getElementById("perf-sample-del"); if (del) del.addEventListener("click", async function () { if (!(await confirmMsg("테스트 데이터만 모두 삭제합니다. 실제 수집한 매출은 지우지 않습니다. 계속할까요?"))) return; try { const res = await api("POST", "/performance/api/sample-data", { action: "delete" }); await alertMsg("테스트 데이터 " + fmt(res.deleted) + "건을 삭제했습니다."); location.reload(); } catch (err) { alertMsg(err.message); } }); const rekey = document.getElementById("perf-rekey"); if (rekey) rekey.addEventListener("click", async function () { if (!(await confirmMsg("예전 키로 암호화된 인증정보를 현재 키로 다시 암호화합니다. 계속할까요?"))) return; try { const res = await api("POST", "/performance/api/rekey"); await alertMsg("다시 암호화 " + res.reencrypted + "건" + (res.failed ? ", 실패 " + res.failed + "건(다시 입력 필요)" : "")); location.reload(); } catch (err) { alertMsg(err.message); } }); } document.addEventListener("DOMContentLoaded", function () { const dash = document.getElementById("perf-dash"); if (dash) initDashboard(dash); const set = document.getElementById("perf-settings"); if (set) initSettings(set); }); })();