e7b1e17579
- 실적 설정 "광고 API 연동" 카드: 개발자 토큰·고객 ID·로그인 고객 ID(MCC)·서비스 계정 JSON·API 버전(기본 v26) → 쇼핑몰과 같은 마스터 키로 암호화(perf_ad_credentials, AAD perf:ad:…), 연결 테스트·상태(perf_ad_source_status) - ad_sources/(채널 하나 = 파일 하나) + google_ads.py: 서비스 계정 JWT 토큰(httpx) → REST searchStream GAQL, 비용(cost_micros 원 반올림, 부가세 별도)·ROAS(전환 가치÷비용)·노출·클릭·전환 항목, KRW 계정만, 오류 코드별 안내 - ad_sync.py: 기간 한 트랜잭션 저장(source='api', 안 준 날은 예전 API 값만 지움), 같은 채널 동시 실행 차단, 비밀값 가림 - 광고비 탭 [구글 광고 불러오기](보는 기간, 92일 넘으면 관리자) + 매출 자동 업데이트 회차에 함께, API 값 초록 숫자, 구글 머리글 = 일자별 항목 표 - 마이그레이션 007, 테스트 test_google_ads.py(가짜 구글 서버) — performance 테스트 83개 통과 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1442 lines
98 KiB
JavaScript
1442 lines
98 KiB
JavaScript
/* 실적(쇼핑몰 통합 매출) — 대시보드 / 설정 화면 동작.
|
||
*
|
||
* 쇼핑몰 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) : '<span class="perf-zero">–</span>'; }
|
||
// 축 눈금용 짧은 금액(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, opts) { return window.erpAlert ? window.erpAlert(msg, opts) : 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" : opts.wide ? " is-wide" : ""),
|
||
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 };
|
||
}
|
||
|
||
// ── 매출 업데이트 진행 창 — 서버가 백그라운드로 수집(POST /api/sync background)하는 동안
|
||
// GET /api/sync/jobs/{id} 를 0.8초마다 불러 쇼핑몰별·전체 진행 막대를 그린다.
|
||
// 창을 닫아도 수집은 서버에서 계속된다. 끝나면 resolve(마지막 상태), 호출 자체가 실패하면 reject.
|
||
const SHOP_STATE = { waiting: "대기", running: "수집 중", saving: "저장 중", done: "완료", error: "실패", skipped: "건너뜀",
|
||
cancelled: "취소됨" };
|
||
function fmtSec(sec) {
|
||
sec = Math.max(0, Math.round(sec || 0));
|
||
return Math.floor(sec / 60) + ":" + String(sec % 60).padStart(2, "0");
|
||
}
|
||
function progressRow(name, fraction, text, cls, action) {
|
||
const pct = Math.round((fraction || 0) * 100);
|
||
return '<div class="perf-prog-row' + (cls ? " " + cls : "") + '">' +
|
||
'<div class="perf-prog-name"><span>' + esc(name) + "</span>" + (action || "") + "</div>" +
|
||
'<div class="perf-prog-bar" role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="' + pct + '">' +
|
||
'<span style="width:' + pct + '%"></span></div>' +
|
||
'<div class="perf-prog-pct">' + pct + "%</div>" +
|
||
'<div class="perf-prog-text">' + text + "</div></div>";
|
||
}
|
||
function shopText(s) {
|
||
let t = SHOP_STATE[s.state] || s.state;
|
||
if (s.state === "running" && s.total) t += " " + fmt(s.done) + "/" + fmt(s.total) + s.unit;
|
||
if (s.items && s.state !== "done") t += " · 받은 자료 " + fmt(s.items) + "건";
|
||
if (s.state === "done") t += " · " + fmt(s.upserted) + "건 반영";
|
||
if (s.state === "error") t += " · " + (s.label ? s.label + " — " : "") + (s.message || "");
|
||
if (s.state === "skipped") t += " · " + (s.message || "");
|
||
if (s.state === "cancelled") t = (s.message === "중지됨" ? "중지됨" : t) + " · 저장하지 않음(기존 매출 그대로)";
|
||
if (s.state === "running" && s.cancel_pending) t += " · 취소하는 중…";
|
||
else if (s.state === "running" && s.stop_requested) t += " · 중지하는 중…";
|
||
if (s.state === "waiting" && s.stop_requested) t += " · 중지 — 차례가 오면 건너뜀";
|
||
let html = esc(t);
|
||
if (s.elapsed && s.state !== "waiting") html += ' <span class="perf-muted">(' + fmtSec(s.elapsed) + ")</span>";
|
||
return html;
|
||
}
|
||
function renderSyncJob(box, job, joined) {
|
||
const active = job.shops.filter(function (s) { return s.active; });
|
||
const passive = job.shops.filter(function (s) { return !s.active; });
|
||
const o = job.overall;
|
||
let html = joined ? '<p class="perf-notice">이미 진행 중인 업데이트를 보여 줍니다.</p>' : "";
|
||
html += '<p class="perf-muted" style="margin:0 0 10px">기간 ' + esc(job.from || "") + " ~ " + esc(job.to || "") +
|
||
" · 경과 " + fmtSec(job.elapsed) + (job.finished ? "" : " · 창을 닫아도 서버에서 계속 진행됩니다") + "</p>";
|
||
html += active.map(function (s) {
|
||
const cls = s.state === "error" ? "is-error" : s.state === "done" ? "is-done" :
|
||
(s.state === "skipped" || s.state === "cancelled") ? "is-skip" : "";
|
||
if (job.cancel_requested) s.cancel_pending = true;
|
||
// 쇼핑몰별 [중지] — 이 쇼핑몰만 멈추고 다음 쇼핑몰로(대기·수집 중일 때만, 저장 중엔 못 멈춤)
|
||
const stoppable = !job.finished && !job.cancel_requested && !s.stop_requested &&
|
||
(s.state === "waiting" || s.state === "running");
|
||
const stopBtn = stoppable ? '<button type="button" class="perf-prog-stop" data-stop="' + esc(s.code) + '" title="' +
|
||
esc(s.name) + ' 업데이트만 멈추고 다음 쇼핑몰로 넘어갑니다(이 쇼핑몰은 저장하지 않음)">중지</button>' : "";
|
||
return progressRow(s.name, s.fraction, shopText(s), cls, stopBtn);
|
||
}).join("");
|
||
html += progressRow("전체", o.fraction,
|
||
esc((job.cancel_requested ? (job.finished ? "업데이트 취소됨 · " : "취소하는 중 · ") : "") +
|
||
fmt(o.finished) + "/" + fmt(o.shops) + " 쇼핑몰 완료" +
|
||
(o.items ? " · 받은 자료 " + fmt(o.items) + "건" : "") + (job.finished ? " · " + fmt(o.upserted) + "건 반영" : "")),
|
||
"is-total" + (job.finished ? (job.cancel_requested ? " is-skip" : " is-done") : ""));
|
||
if (passive.length) {
|
||
html += '<p class="perf-muted" style="margin:10px 0 0">건너뜀: ' + esc(passive.map(function (s) {
|
||
return s.name + (s.label ? "(" + s.label + ")" : "");
|
||
}).join(", ")) + "</p>";
|
||
}
|
||
if (job.error) html += '<p class="perf-notice is-warn">' + esc(job.error) + "</p>";
|
||
box.innerHTML = html;
|
||
}
|
||
function runSyncWithProgress(payload, title) {
|
||
return new Promise(function (resolve, reject) {
|
||
let timer = null, closed = false, last = null;
|
||
const m = openModal(title || "매출 업데이트", { narrow: true, onClose: function () { closed = true; clearTimeout(timer); if (last) resolve(last); } });
|
||
m.card.classList.add("perf-prog-card");
|
||
m.body.innerHTML = '<p class="perf-muted">업데이트를 시작하는 중…</p>';
|
||
// [업데이트 취소] — 돌고 있는 쇼핑몰은 다음 API 호출 직전에 멈추고(저장 전이면 DB 그대로),
|
||
// 이미 저장이 끝난 쇼핑몰 결과는 남는다. 끝나면 숨긴다.
|
||
const cancelBtn = el("button", { type: "button", class: "erp-btn erp-btn-outline perf-prog-cancel", hidden: "hidden" }, "업데이트 취소");
|
||
const closeBtn = el("button", { type: "button", class: "erp-btn erp-btn-outline" }, "닫기");
|
||
closeBtn.addEventListener("click", m.close);
|
||
m.foot.appendChild(cancelBtn);
|
||
m.foot.appendChild(closeBtn);
|
||
let jobId = null;
|
||
// 쇼핑몰별 [중지] — 진행 창은 0.8초마다 다시 그려지므로 위임으로 받는다
|
||
m.body.addEventListener("click", async function (e) {
|
||
const b = e.target.closest("[data-stop]");
|
||
if (!b || !jobId) return;
|
||
b.disabled = true;
|
||
b.textContent = "중지하는 중…";
|
||
try {
|
||
const r = await api("POST", "/performance/api/sync/jobs/" + encodeURIComponent(jobId) + "/shops/" +
|
||
encodeURIComponent(b.dataset.stop) + "/stop");
|
||
last = r.job;
|
||
renderSyncJob(m.body, r.job, false);
|
||
} catch (err) {
|
||
b.disabled = false;
|
||
b.textContent = "중지";
|
||
alertMsg("중지 실패: " + err.message);
|
||
}
|
||
});
|
||
cancelBtn.addEventListener("click", async function () {
|
||
if (!jobId) return;
|
||
if (!(await confirmMsg("매출 업데이트를 취소할까요?\n수집 중인 쇼핑몰은 저장하지 않고 멈추고, 이미 끝난 쇼핑몰 결과는 그대로 남습니다."))) return;
|
||
cancelBtn.disabled = true;
|
||
cancelBtn.textContent = "취소하는 중…";
|
||
try {
|
||
const r = await api("POST", "/performance/api/sync/jobs/" + encodeURIComponent(jobId) + "/cancel");
|
||
last = r.job;
|
||
renderSyncJob(m.body, r.job, false);
|
||
} catch (err) {
|
||
cancelBtn.disabled = false;
|
||
cancelBtn.textContent = "업데이트 취소";
|
||
alertMsg("취소 실패: " + err.message);
|
||
}
|
||
});
|
||
api("POST", "/performance/api/sync", Object.assign({ background: true }, payload)).then(function (res) {
|
||
last = res.job;
|
||
jobId = res.job.id;
|
||
const joined = res.joined;
|
||
renderSyncJob(m.body, res.job, joined);
|
||
if (!res.job.finished) cancelBtn.hidden = false;
|
||
if (res.job.cancel_requested) { cancelBtn.disabled = true; cancelBtn.textContent = "취소하는 중…"; }
|
||
async function poll() {
|
||
if (closed) return;
|
||
try {
|
||
const r = await api("GET", "/performance/api/sync/jobs/" + encodeURIComponent(res.job.id));
|
||
last = r.job;
|
||
renderSyncJob(m.body, r.job, joined);
|
||
if (r.job.finished) {
|
||
cancelBtn.hidden = true;
|
||
closeBtn.textContent = "확인";
|
||
closeBtn.className = "erp-btn erp-btn-primary";
|
||
return;
|
||
}
|
||
} catch (err) {
|
||
m.body.insertAdjacentHTML("beforeend", '<p class="perf-notice is-warn">' + esc(err.message) + "</p>");
|
||
return;
|
||
}
|
||
timer = setTimeout(poll, 800);
|
||
}
|
||
timer = setTimeout(poll, 500);
|
||
}).catch(function (err) {
|
||
m.body.innerHTML = '<p class="perf-notice is-warn">' + esc(err.message) + "</p>";
|
||
closed = true;
|
||
reject(err);
|
||
});
|
||
});
|
||
}
|
||
// 끝난 작업 → 기존 결과 줄(반영/실패/건너뜀)에 쓰던 모양
|
||
function jobResults(job) {
|
||
return (job && job.shops || []).map(function (s) {
|
||
return { code: s.code, name: s.name, ok: s.state === "done", skipped: s.state === "skipped",
|
||
cancelled: s.state === "cancelled", stopped: s.state === "cancelled" && s.message === "중지됨",
|
||
upserted: s.upserted, status: s.status, label: s.label, message: s.message, finished: s.state !== "waiting" && s.state !== "running" && s.state !== "saving" };
|
||
});
|
||
}
|
||
|
||
// ════════════════════════════════════════════════════
|
||
// 대시보드
|
||
// ════════════════════════════════════════════════════
|
||
function initDashboard(root) {
|
||
const data = JSON.parse((document.getElementById("perf-data") || {}).textContent || "{}");
|
||
const METRIC_NAMES = { gross: "총매출", commission: "수수료", net: "수수료 차감 매출" };
|
||
const KEY = "perf_metric";
|
||
const FIXED_METRIC = root.dataset.fixedMetric || ""; // 광고비 화면 = 금액 하나(gross)뿐
|
||
const MANUAL_API = data.manual_api || "/performance/api/manual-sales/";
|
||
const MANUAL_WORD = data.manual_word || "총매출";
|
||
const EMPTY_TEXT = data.empty_text || "기간 내 매출이 없습니다.";
|
||
|
||
// 표시 기준 전환 — 서버가 세 값을 다 그려 두었고 CSS 가 하나만 보인다.
|
||
function setMetric(m) {
|
||
if (FIXED_METRIC) m = FIXED_METRIC;
|
||
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);
|
||
});
|
||
if (!FIXED_METRIC) { 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); });
|
||
});
|
||
|
||
// 수동 입력 엑셀 업로드 — 1열 날짜, 2열부터 쇼핑몰 이름 머리글. 값이 있는 칸만 반영(빈 칸은 기존 값 그대로).
|
||
// 잘못된 칸이 있으면 서버가 아무것도 저장하지 않고 칸 위치 목록을 돌려준다.
|
||
const uploadBtn = document.getElementById("perf-manual-upload");
|
||
if (uploadBtn) uploadBtn.addEventListener("click", function () {
|
||
let saved = false;
|
||
const m = openModal("수동 입력 엑셀 업로드", { narrow: true, onClose: function () { if (saved) location.reload(); } });
|
||
const shops = (data.manual_upload_names || []).map(esc).join(", ");
|
||
m.body.innerHTML =
|
||
'<p class="perf-muted" style="margin:0 0 8px">1열에 <b>날짜</b>, 2열부터 <b>쇼핑몰 이름</b>을 머리글로 적고 그날 <b>총매출</b>을 넣습니다. ' +
|
||
"값이 있는 칸만 반영되고(같은 날 값은 덮어씀) 빈 칸은 기존 값 그대로입니다.</p>" +
|
||
'<p class="perf-muted" style="margin:0 0 10px">입력 가능한 쇼핑몰: ' + (shops || "없음") + "</p>" +
|
||
'<p style="margin:0 0 12px"><a class="erp-btn erp-btn-outline erp-btn-sm" href="/performance/api/manual-sales/sample.xlsx" download>' +
|
||
"샘플 파일 받기</a></p>" +
|
||
'<input type="file" class="erp-input perf-upload-file" accept=".xlsx,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" aria-label="엑셀 파일" />' +
|
||
'<div class="perf-upload-result"></div>';
|
||
const fileInput = m.body.querySelector(".perf-upload-file");
|
||
const out = m.body.querySelector(".perf-upload-result");
|
||
const go = el("button", { type: "button", class: "erp-btn erp-btn-primary" }, "업로드");
|
||
const cancel = el("button", { type: "button", class: "erp-btn erp-btn-ghost" }, "닫기");
|
||
m.foot.appendChild(cancel);
|
||
m.foot.appendChild(go);
|
||
cancel.addEventListener("click", m.close);
|
||
go.addEventListener("click", async function () {
|
||
const f = fileInput.files && fileInput.files[0];
|
||
if (!f) { out.innerHTML = '<p class="perf-notice is-warn">엑셀 파일을 고르세요.</p>'; return; }
|
||
go.disabled = true;
|
||
out.innerHTML = '<p class="perf-muted">올리는 중…</p>';
|
||
const fd = new FormData();
|
||
fd.append("file", f);
|
||
let res, body = null;
|
||
try {
|
||
res = await fetch("/performance/api/manual-sales/upload", { method: "POST", credentials: "same-origin", body: fd });
|
||
try { body = await res.json(); } catch (_) { body = null; }
|
||
} catch (err) {
|
||
out.innerHTML = '<p class="perf-notice is-warn">업로드 실패: ' + esc(err.message) + "</p>";
|
||
go.disabled = false;
|
||
return;
|
||
}
|
||
go.disabled = false;
|
||
const ignored = body && body.ignored && body.ignored.length
|
||
? '<p class="perf-muted" style="margin:6px 0 0">건너뛴 열: ' + esc(body.ignored.join(", ")) + "</p>" : "";
|
||
if (!res.ok) {
|
||
const detail = body && typeof body.detail === "string" ? body.detail : "업로드 실패 (" + res.status + ")";
|
||
const errs = body && body.errors && body.errors.length
|
||
? '<ul class="perf-upload-errors">' + body.errors.map(function (e) { return "<li>" + esc(e) + "</li>"; }).join("") + "</ul>" : "";
|
||
out.innerHTML = '<p class="perf-notice is-warn">' + esc(detail) + "</p>" + errs + ignored;
|
||
return;
|
||
}
|
||
saved = body.saved > 0;
|
||
out.innerHTML = '<p class="perf-notice is-ok">' + (saved
|
||
? fmt(body.saved) + "칸 반영 (" + esc(body.from === body.to ? body.from : body.from + " ~ " + body.to) + ")<br>" +
|
||
esc(body.by_shop.map(function (s) { return s.name + " " + fmt(s.count) + "일"; }).join(" · "))
|
||
: "반영할 값이 없습니다(값이 있는 칸이 없음).") + "</p>" + ignored +
|
||
(saved ? '<p class="perf-muted" style="margin:6px 0 0">창을 닫으면 표·합계·그래프가 다시 계산됩니다.</p>' : "");
|
||
fileInput.value = "";
|
||
});
|
||
});
|
||
|
||
// 광고비 파일 업로드 — 채널(양식이 정해진 채널만)을 고르고 파일을 올리면 파일에 있는 날만 덮어쓴다.
|
||
// 잘못된 줄이 있으면 서버가 아무것도 저장하지 않고 줄 위치 목록을 돌려준다.
|
||
const adUploadBtn = document.getElementById("perf-ad-upload");
|
||
if (adUploadBtn) adUploadBtn.addEventListener("click", function () {
|
||
let saved = false;
|
||
const chans = data.upload_channels || [];
|
||
const m = openModal("광고비 파일 업로드", { narrow: true, onClose: function () { if (saved) location.reload(); } });
|
||
m.body.innerHTML =
|
||
'<label class="perf-muted" style="display:block;margin:0 0 4px">채널</label>' +
|
||
'<select class="erp-input perf-ad-channel" style="width:100%;margin:0 0 6px">' + chans.map(function (c) {
|
||
return '<option value="' + esc(c.code) + '">' + esc(c.name) + "</option>";
|
||
}).join("") + "</select>" +
|
||
'<p class="perf-muted perf-ad-help" style="margin:0 0 10px"></p>' +
|
||
'<input type="file" multiple class="erp-input perf-upload-file" accept=".csv,.xlsx,text/csv,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" aria-label="광고 보고서 파일(여러 개 가능)" />' +
|
||
'<p class="perf-muted" style="margin:6px 0 0">파일을 여러 개 고를 수 있습니다. 같은 날짜가 여러 파일에 있으면 파일 날짜(수정 시각)가 최신인 파일 값을 씁니다.</p>' +
|
||
'<div class="perf-upload-result"></div>';
|
||
const sel = m.body.querySelector(".perf-ad-channel");
|
||
const help = m.body.querySelector(".perf-ad-help");
|
||
function showHelp() {
|
||
const c = chans.filter(function (x) { return x.code === sel.value; })[0];
|
||
help.textContent = c ? c.help : "";
|
||
}
|
||
sel.addEventListener("change", showHelp);
|
||
showHelp();
|
||
const fileInput = m.body.querySelector(".perf-upload-file");
|
||
const out = m.body.querySelector(".perf-upload-result");
|
||
const go = el("button", { type: "button", class: "erp-btn erp-btn-primary" }, "업로드");
|
||
const cancel = el("button", { type: "button", class: "erp-btn erp-btn-ghost" }, "닫기");
|
||
m.foot.appendChild(cancel);
|
||
m.foot.appendChild(go);
|
||
cancel.addEventListener("click", m.close);
|
||
go.addEventListener("click", async function () {
|
||
const picked = Array.prototype.slice.call(fileInput.files || []);
|
||
if (!picked.length) { out.innerHTML = '<p class="perf-notice is-warn">파일을 고르세요.</p>'; return; }
|
||
go.disabled = true;
|
||
out.innerHTML = '<p class="perf-muted">올리는 중… (' + picked.length + "개 파일)</p>";
|
||
const fd = new FormData();
|
||
picked.forEach(function (f) {
|
||
fd.append("files", f);
|
||
fd.append("modified", String(f.lastModified || 0)); // 같은 날짜는 파일 날짜가 최신인 파일 값
|
||
});
|
||
let res, body = null;
|
||
try {
|
||
res = await fetch("/performance/api/ad-spend/upload?channel=" + encodeURIComponent(sel.value),
|
||
{ method: "POST", credentials: "same-origin", body: fd });
|
||
try { body = await res.json(); } catch (_) { body = null; }
|
||
} catch (err) {
|
||
out.innerHTML = '<p class="perf-notice is-warn">업로드 실패: ' + esc(err.message) + "</p>";
|
||
go.disabled = false;
|
||
return;
|
||
}
|
||
go.disabled = false;
|
||
if (!res.ok) {
|
||
const detail = body && typeof body.detail === "string" ? body.detail : "업로드 실패 (" + res.status + ")";
|
||
const errs = body && body.errors && body.errors.length
|
||
? '<ul class="perf-upload-errors">' + body.errors.map(function (e) { return "<li>" + esc(e) + "</li>"; }).join("") + "</ul>" : "";
|
||
out.innerHTML = '<p class="perf-notice is-warn">' + esc(detail) + "</p>" + errs;
|
||
return;
|
||
}
|
||
saved = body.saved > 0;
|
||
// 업로드가 끝나면 창을 닫고 표·합계·그래프를 다시 그린다(onClose 새로고침). 청구금액이 없는 날짜·파일은 그냥 넘어간다.
|
||
if (saved) { m.close(); return; }
|
||
out.innerHTML = '<p class="perf-notice is-ok">청구금액이 있는 날짜가 없어 반영한 날이 없습니다.</p>';
|
||
fileInput.value = "";
|
||
});
|
||
});
|
||
|
||
// [구글 광고 불러오기] — 광고 API 로 지금 보는 기간(오늘까지)을 가져와 저장(같은 날 덮어씀) → 새로고침.
|
||
root.addEventListener("click", async function (e) {
|
||
const btn = e.target.closest("[data-ad-sync]");
|
||
if (!btn || btn.disabled) return;
|
||
const label = btn.textContent;
|
||
btn.disabled = true;
|
||
btn.textContent = "불러오는 중…";
|
||
try {
|
||
const res = await api("POST", "/performance/api/ad-sources/" + encodeURIComponent(btn.dataset.adSync) + "/sync",
|
||
{ from: data.period_start, to: data.period_end });
|
||
await alertMsg(res.name + " — " + res.from + " ~ " + res.to + "\n" + (res.days ? res.days + "일, 광고비 ₩" + fmt(res.total) + " 반영" : "이 기간 광고비가 없습니다."),
|
||
{ tone: "ok" });
|
||
location.reload();
|
||
} catch (err) {
|
||
alertMsg(err.message);
|
||
btn.disabled = false;
|
||
btn.textContent = label;
|
||
}
|
||
});
|
||
|
||
// 광고 보고서 일자별 상세(네이버·구글 머리글) — 지금 보는 기간의 날마다 광고비·ROAS·보고서 항목, 맨 아래 합계.
|
||
root.addEventListener("click", async function (e) {
|
||
const btn = e.target.closest("[data-detail-channel]");
|
||
if (!btn) return;
|
||
const code = btn.dataset.detailChannel;
|
||
const name = (data.names || {})[code] || code;
|
||
const m = openModal(name + " 광고 보고서 · " + (data.period_label || ""), { wide: true });
|
||
m.body.innerHTML = '<p class="perf-muted">불러오는 중…</p>';
|
||
try {
|
||
const res = await api("GET", "/performance/api/ad-spend/" + encodeURIComponent(code) + "/details?from=" +
|
||
encodeURIComponent(data.period_start) + "&to=" + encodeURIComponent(data.period_end));
|
||
if (!res.rows || !res.rows.length) { m.body.innerHTML = '<p class="perf-muted">이 기간 보고서 자료가 없습니다(파일 업로드 또는 광고 API 불러오기).</p>'; return; }
|
||
const cols = res.columns || [];
|
||
const cell = function (v) {
|
||
if (v == null || v === "") return '<span class="perf-zero">–</span>';
|
||
return typeof v === "number" ? (Number.isInteger(v) ? fmt(v) : v.toLocaleString("ko-KR", { minimumFractionDigits: 2, maximumFractionDigits: 2 })) : esc(v);
|
||
};
|
||
const WD = ["일", "월", "화", "수", "목", "금", "토"];
|
||
const day = function (iso) {
|
||
const d = new Date(iso + "T00:00:00");
|
||
return iso.slice(5, 7) + "/" + iso.slice(8, 10) + "(" + WD[d.getDay()] + ")";
|
||
};
|
||
m.body.innerHTML = '<div class="perf-ev-wrap"><table class="perf-table perf-detail-table"><thead><tr><th class="perf-th-label">날짜</th>' +
|
||
cols.map(function (c) { return "<th>" + esc(c) + "</th>"; }).join("") + "</tr></thead><tbody>" +
|
||
res.rows.map(function (r) {
|
||
return '<tr><th class="perf-td-label" scope="row">' + esc(day(r.date)) + "</th>" +
|
||
cols.map(function (c) { return '<td class="perf-num">' + cell((r.values || {})[c]) + "</td>"; }).join("") + "</tr>";
|
||
}).join("") + '</tbody><tfoot><tr class="perf-row-total"><th class="perf-td-label" scope="row">합계</th>' +
|
||
cols.map(function (c) { return '<td class="perf-num">' + cell((res.total || {})[c]) + "</td>"; }).join("") +
|
||
"</tr></tfoot></table></div>" +
|
||
'<p class="perf-muted">합계: 숫자 항목은 더한 값, 클릭률 = 클릭수 ÷ 노출수, 광고수익률·ROAS = 날짜별 값을 광고비로 가중 평균.</p>';
|
||
} catch (err) {
|
||
m.body.innerHTML = '<p class="perf-notice is-warn">' + esc(err.message) + "</p>";
|
||
}
|
||
});
|
||
|
||
// 직접선택 / 쇼핑몰 필터
|
||
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 {
|
||
// 지금 보고 있는 기간(오늘까지)을 가져온다 — "이번달"이면 1일부터 오늘까지.
|
||
const from = data.period_start, to = data.period_end < data.today ? data.period_end : data.today;
|
||
if (from > data.today) throw new Error("앞으로의 기간은 가져올 수 없습니다.");
|
||
// 진행 창(쇼핑몰별·전체 막대) — 창을 닫아도 서버에서 계속된다.
|
||
const job = await runSyncWithProgress({ from: from, to: to }, "매출 업데이트 " + from + " ~ " + to);
|
||
const res = { results: jobResults(job).filter(function (r) { return r.finished; }), last_update_at: job && job.last_update_at };
|
||
const running = job && !job.finished;
|
||
// 실패(빨강)는 인증 실패·API 오류처럼 손봐야 하는 것만. 인증정보를 아직 안 넣은 쇼핑몰(미설정)과
|
||
// 수집을 아직 만들지 않은 쇼핑몰(연동 준비 중)은 회색 한 줄로 이름만.
|
||
const ok = [], bad = [], pending = [], unset = [], busy = [], cancelled = [], stopped = [];
|
||
let changed = 0;
|
||
(res.results || []).forEach(function (r) {
|
||
const name = (data.names || {})[r.code] || r.name || r.code;
|
||
if (r.stopped) stopped.push(name);
|
||
else if (r.cancelled) cancelled.push(name);
|
||
else 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("<b>반영</b> " + esc(ok.join(", ")));
|
||
if (bad.length) parts.push("<b>실패</b> " + esc(bad.join(", ")));
|
||
if (busy.length) parts.push("<b>이미 진행 중</b> " + esc(busy.join(", ")));
|
||
if (stopped.length) parts.push("<b>중지됨</b>(기존 매출 그대로) " + esc(stopped.join(", ")));
|
||
if (cancelled.length) parts.push("<b>취소됨</b>(기존 매출 그대로) " + esc(cancelled.join(", ")));
|
||
if (pending.length) parts.push('<span class="perf-muted">연동 준비 중: ' + esc(pending.join(", ")) + "</span>");
|
||
if (unset.length) parts.push('<span class="perf-muted">인증정보 미설정: ' + esc(unset.join(", ")) + "</span>");
|
||
if (running) parts.unshift("<b>업데이트가 아직 진행 중입니다</b> — 끝나면 다시 [매출 업데이트]를 눌러 결과를 보세요");
|
||
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 && !running) setTimeout(function () { location.reload(); }, 800);
|
||
} 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);
|
||
});
|
||
|
||
// ── 수동 입력(설정에서 켠 쇼핑몰) — 날짜 칸을 눌러 총매출 입력. Enter 저장 후 아래 칸 · Shift+Enter 위 칸 · Esc 취소.
|
||
// 비우고 저장하면 그날은 다시 API 값. 저장은 칸마다 차례로, 입력을 마치면(다른 칸으로 안 넘어가면) 새로고침해
|
||
// 합계·수수료·그래프를 서버 계산으로 다시 그린다.
|
||
let manualDirty = false;
|
||
let manualChain = Promise.resolve();
|
||
function manualCells(code) {
|
||
return Array.prototype.slice.call(root.querySelectorAll('td.is-manual-cell[data-manual-code="' + code + '"]'));
|
||
}
|
||
function digitsOf(td) { return td.dataset.manualValue || ""; }
|
||
function finishManual() {
|
||
setTimeout(function () {
|
||
if (root.querySelector(".perf-manual-input")) return; // 다른 칸으로 넘어감
|
||
manualChain.then(function () { if (manualDirty) location.reload(); });
|
||
}, 120);
|
||
}
|
||
function saveManual(td, text) {
|
||
const raw = String(text || "").replace(/[,\s원]/g, "");
|
||
const was = digitsOf(td);
|
||
if (raw !== "" && !/^-?\d+$/.test(raw)) return Promise.reject(new Error("숫자(원)만 입력하세요."));
|
||
if (raw === was) return Promise.resolve(false); // 바뀐 것 없음(빈 칸 그대로 포함)
|
||
const job = manualChain.then(function () {
|
||
return api("PUT", MANUAL_API + encodeURIComponent(td.dataset.manualCode) + "/" +
|
||
encodeURIComponent(td.dataset.date), { amount: raw === "" ? null : Number(raw) });
|
||
}).then(function (res) {
|
||
const manual = res.manual == null ? "" : String(res.manual);
|
||
td.dataset.manualValue = manual;
|
||
td.classList.toggle("is-manual", manual !== "");
|
||
td.classList.remove("is-upload");
|
||
const ro = td.querySelector(".perf-roas"); // 광고비가 바뀌면 ROAS 는 새로고침 때 다시 계산
|
||
if (ro) ro.remove();
|
||
td.title = manual !== "" ? "직접 입력값 — 눌러 고치기(비우고 저장하면 " + (FIXED_METRIC ? "지움" : "API 값") + ")"
|
||
: "눌러 " + MANUAL_WORD + " 직접 입력";
|
||
const g = td.querySelector(".v-gross");
|
||
if (g) g.innerHTML = won(res.amount);
|
||
td.classList.add("is-stale"); // 수수료·차감 매출은 새로고침 때 다시 계산
|
||
manualDirty = true;
|
||
return true;
|
||
});
|
||
manualChain = job.catch(function () {});
|
||
return job;
|
||
}
|
||
function editManual(td) {
|
||
if (td.querySelector(".perf-manual-input")) return;
|
||
const input = el("input", { type: "text", inputmode: "numeric", class: "perf-manual-input",
|
||
"aria-label": ((data.names || {})[td.dataset.manualCode] || "") + " " + td.dataset.date + " " + MANUAL_WORD });
|
||
input.value = digitsOf(td);
|
||
const g = td.querySelector(".v-gross");
|
||
input.placeholder = digitsOf(td) ? "" : (g ? g.textContent.trim().replace(/[–-]/, "") : "") || MANUAL_WORD;
|
||
td.classList.add("is-editing");
|
||
td.appendChild(input);
|
||
input.focus();
|
||
input.select();
|
||
let done = false;
|
||
function close() {
|
||
if (done) return;
|
||
done = true;
|
||
input.remove();
|
||
td.classList.remove("is-editing");
|
||
}
|
||
function commit(step) {
|
||
if (done) return;
|
||
const val = input.value;
|
||
close();
|
||
const cells = manualCells(td.dataset.manualCode);
|
||
const next = step ? cells[cells.indexOf(td) + step] : null;
|
||
if (next) editManual(next);
|
||
saveManual(td, val).catch(function (err) {
|
||
alertMsg("저장 실패(" + td.dataset.date + "): " + err.message);
|
||
}).then(finishManual);
|
||
}
|
||
input.addEventListener("keydown", function (e) {
|
||
if (e.isComposing) return;
|
||
if (e.key === "Enter" || e.key === "Tab") { e.preventDefault(); commit(e.shiftKey ? -1 : 1); }
|
||
else if (e.key === "ArrowDown" || e.key === "ArrowUp") { e.preventDefault(); commit(e.key === "ArrowUp" ? -1 : 1); }
|
||
else if (e.key === "Escape") { e.preventDefault(); close(); td.focus(); finishManual(); }
|
||
});
|
||
input.addEventListener("blur", function () { commit(0); });
|
||
}
|
||
root.addEventListener("click", function (e) {
|
||
const td = e.target.closest("td.is-manual-cell");
|
||
if (td && !e.target.closest(".perf-manual-input")) editManual(td);
|
||
});
|
||
root.addEventListener("keydown", function (e) {
|
||
const td = e.target.closest && e.target.closest("td.is-manual-cell");
|
||
if (td && e.target === td && (e.key === "Enter" || e.key === "F2")) { e.preventDefault(); editManual(td); }
|
||
});
|
||
async function openEvents(code, from, to) {
|
||
const name = (data.names || {})[code] || code;
|
||
const title = name + " · " + (from === to ? from : from + " ~ " + to) + " 주문 내역";
|
||
const m = openModal(title, { wide: true }); // 넓은 창 + 상품명 줄바꿈 → 가로 스크롤 없이
|
||
m.body.innerHTML = '<p class="perf-muted">불러오는 중…</p>';
|
||
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 = '<p class="perf-muted">내역이 없습니다.</p>'; 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 '<tr class="' + (r.event_type === "CANCEL" ? "is-cancel" : r.amount < 0 ? "perf-ev-cancel" : "") + '">' +
|
||
"<td>" + esc(r.sales_date) + "</td><td>" + esc(KIND[r.event_type] || r.event_type) +
|
||
(r.is_sample ? ' <span class="perf-pill">테스트</span>' : "") + "</td>" +
|
||
"<td>" + esc(r.external_order_id) + "</td>" +
|
||
'<td class="perf-ev-name">' + esc(r.product_name) + (r.option_name ? " <span class='perf-muted'>" + esc(r.option_name) + "</span>" : "") + "</td>" +
|
||
'<td class="perf-num">' + esc(r.quantity) + "</td>" +
|
||
'<td class="perf-num">' + fmt(r.amount) + "</td>" +
|
||
"<td>" + esc(r.order_date || "") + "</td><td>" + esc(r.payment_date || "") + "</td>" +
|
||
"<td>" + esc(r.order_status) + "</td></tr>";
|
||
}).join("");
|
||
m.body.innerHTML =
|
||
'<div class="perf-ev-wrap"><table class="perf-table perf-ev-table"><thead><tr>' +
|
||
'<th class="perf-th-label">매출일</th><th class="perf-th-label">구분</th><th class="perf-th-label">주문번호</th>' +
|
||
'<th class="perf-th-label perf-ev-name">상품명</th><th>수량</th><th>금액</th><th class="perf-th-label">주문일</th>' +
|
||
'<th class="perf-th-label">결제일</th><th class="perf-th-label">상태</th></tr></thead><tbody>' + body +
|
||
'</tbody><tfoot><tr class="perf-row-total"><th class="perf-td-label" colspan="5">결제 ' + fmt(sales) +
|
||
" / 취소·반품 " + fmt(minus) + '</th><td class="perf-num">' + fmt(sum) + '</td><td colspan="3"></td></tr></tfoot></table></div>' +
|
||
(res.truncated ? '<p class="perf-muted">처음 500건만 표시합니다.</p>' : "") +
|
||
'<p class="perf-muted">수수료는 일·쇼핑몰 단위로 계산되어 주문별로는 표시하지 않습니다.</p>';
|
||
} catch (err) {
|
||
m.body.innerHTML = '<p class="perf-notice is-warn">' + esc(err.message) + "</p>";
|
||
}
|
||
}
|
||
|
||
// ── 그래프(SVG) ──
|
||
function svg(w, h, inner) {
|
||
return '<svg viewBox="0 0 ' + w + " " + h + '" preserveAspectRatio="none" role="img">' + inner + "</svg>";
|
||
}
|
||
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 = '<div class="perf-chart-empty">' + esc(EMPTY_TEXT) + "</div>";
|
||
return;
|
||
}
|
||
const W = 640, H = 230, L = 48, R = 8, T = 10, B = 26;
|
||
const maxV = niceMax(Math.max.apply(null, vals.concat([0])));
|
||
const minV = Math.min.apply(null, vals.concat([0])) < 0 ? -niceMax(-Math.min.apply(null, vals)) : 0;
|
||
const y = function (v) { return T + (H - T - B) * (maxV - v) / (maxV - minV); };
|
||
const bw = (W - L - R) / pts.length;
|
||
let g = "";
|
||
for (let i = 0; i <= 4; i++) {
|
||
const v = minV + (maxV - minV) * i / 4;
|
||
g += '<line class="grid" x1="' + L + '" x2="' + (W - R) + '" y1="' + y(v) + '" y2="' + y(v) + '"/>' +
|
||
'<text x="' + (L - 6) + '" y="' + (y(v) + 3.5) + '" text-anchor="end">' + short(Math.round(v)) + "</text>";
|
||
}
|
||
const every = Math.ceil(pts.length / 16);
|
||
pts.forEach(function (p, i) {
|
||
const v = vals[i];
|
||
const x = L + i * bw + bw * 0.15, w = Math.max(1, bw * 0.7);
|
||
const y0 = y(0), y1 = y(v);
|
||
g += '<rect class="bar' + (v < 0 ? " is-neg" : "") + '" x="' + x + '" y="' + Math.min(y0, y1) +
|
||
'" width="' + w + '" height="' + Math.max(0.5, Math.abs(y1 - y0)) + '"><title>' + esc(p.label) + " " + fmt(v) + "원</title></rect>";
|
||
if (i % every === 0) g += '<text x="' + (L + i * bw + bw / 2) + '" y="' + (H - 8) + '" text-anchor="middle">' + esc(p.label) + "</text>";
|
||
});
|
||
g += '<line class="axis" x1="' + L + '" x2="' + (W - R) + '" y1="' + y(0) + '" y2="' + y(0) + '"/>';
|
||
box.innerHTML = svg(W, H, g);
|
||
}
|
||
function drawShare(metric) {
|
||
const box = document.getElementById("perf-chart-share");
|
||
if (!box) return;
|
||
const rows = (data.share || []).slice().sort(function (a, b) { return (b[metric] || 0) - (a[metric] || 0); });
|
||
const total = rows.reduce(function (s, r) { return s + Math.max(0, r[metric] || 0); }, 0);
|
||
if (!rows.length || total <= 0) { box.innerHTML = '<div class="perf-chart-empty">' + esc(EMPTY_TEXT) + "</div>"; return; }
|
||
const W = 640, rowH = 22, L = 120, R = 150, H = rows.length * rowH + 6;
|
||
const maxV = Math.max.apply(null, rows.map(function (r) { return Math.max(0, r[metric] || 0); })) || 1;
|
||
let g = "";
|
||
rows.forEach(function (r, i) {
|
||
const v = r[metric] || 0, y = 4 + i * rowH;
|
||
const w = Math.max(0, (W - L - R) * Math.max(0, v) / maxV);
|
||
const pct = total > 0 ? (Math.max(0, v) / total * 100).toFixed(1) : "0.0";
|
||
g += '<text x="' + (L - 8) + '" y="' + (y + 14) + '" text-anchor="end">' + esc(r.name) + "</text>" +
|
||
'<rect class="bar" x="' + L + '" y="' + (y + 4) + '" width="' + w + '" height="13"><title>' + esc(r.name) + " " + fmt(v) + "원</title></rect>" +
|
||
'<text x="' + (L + w + 6) + '" y="' + (y + 14) + '">' + fmt(v) + " (" + pct + "%)</text>";
|
||
});
|
||
box.innerHTML = svg(W, H, g);
|
||
}
|
||
|
||
let saved = null;
|
||
try { saved = localStorage.getItem(KEY); } catch (_) {}
|
||
setMetric(saved || root.dataset.metric || "gross");
|
||
}
|
||
|
||
// ════════════════════════════════════════════════════
|
||
// 설정
|
||
// ════════════════════════════════════════════════════
|
||
function initSettings(root) {
|
||
// 사용 / 매출 집계 토글 — 바로 저장, 실패하면 되돌림
|
||
root.querySelectorAll(".perf-switch input").forEach(function (box) {
|
||
box.addEventListener("change", async function () {
|
||
const tr = box.closest("tr");
|
||
const payload = {};
|
||
payload[box.dataset.field] = box.checked;
|
||
box.disabled = true;
|
||
try {
|
||
await api("PUT", "/performance/api/marketplaces/" + tr.dataset.code, payload);
|
||
} catch (err) {
|
||
box.checked = !box.checked;
|
||
alertMsg("저장 실패: " + err.message);
|
||
} finally { box.disabled = false; }
|
||
});
|
||
});
|
||
|
||
root.addEventListener("click", function (e) {
|
||
const btn = e.target.closest("button[data-act]");
|
||
if (!btn) return;
|
||
const tr = btn.closest("tr");
|
||
const code = tr.dataset.code, name = tr.dataset.name;
|
||
// 광고 API 연동 줄(data-api="ad-sources")은 /performance/api/ad-sources/…, 나머지는 쇼핑몰
|
||
const base = "/performance/api/" + (tr.dataset.api || "marketplaces") + "/";
|
||
if (btn.dataset.act === "rate") openRate(code, name, btn.dataset.hasHistory === "1");
|
||
else if (btn.dataset.act === "creds") openCreds(code, name, base);
|
||
else if (btn.dataset.act === "test") runTest(code, name, btn, base);
|
||
});
|
||
|
||
function today() {
|
||
const d = new Date();
|
||
return d.getFullYear() + "-" + String(d.getMonth() + 1).padStart(2, "0") + "-" + String(d.getDate()).padStart(2, "0");
|
||
}
|
||
|
||
// ── 수수료율 ──
|
||
async function openRate(code, name, hasHistory) {
|
||
const m = openModal(name + " 수수료율", { narrow: true, onClose: function () { if (m.changed) location.reload(); } });
|
||
m.body.innerHTML =
|
||
'<form class="perf-form" id="perf-rate-form">' +
|
||
'<div class="perf-form-row"><label for="perf-rate-in">수수료율(%)</label>' +
|
||
'<input class="erp-input" id="perf-rate-in" inputmode="decimal" placeholder="예: 5, 10.8, 15.35" required /></div>' +
|
||
'<div class="perf-form-row"><label for="perf-rate-from">적용 시작일</label>' +
|
||
'<div class="perf-inline"><input class="erp-input perf-date" type="date" id="perf-rate-from" value="' + today() + '" />' +
|
||
'<label class="perf-check"><input type="checkbox" id="perf-rate-all"' + (hasHistory ? "" : " checked") + " /> 처음부터(과거 전체)</label></div>" +
|
||
'<div class="perf-form-help">이 날짜부터 새 요율로 계산하고, 그 전 실적은 예전 요율을 유지합니다.</div></div>' +
|
||
'<div class="perf-form-row"><label for="perf-rate-memo">메모</label><input class="erp-input" id="perf-rate-memo" maxlength="200" /></div>' +
|
||
"</form>" +
|
||
'<h4 class="perf-h" style="margin:14px 0 6px">변경 이력</h4><div id="perf-rate-hist" class="perf-muted">불러오는 중…</div>';
|
||
const save = el("button", { type: "button", class: "erp-btn erp-btn-primary" }, "저장");
|
||
m.foot.appendChild(save);
|
||
const from = m.body.querySelector("#perf-rate-from"), all = m.body.querySelector("#perf-rate-all");
|
||
function syncAll() { from.disabled = all.checked; }
|
||
all.addEventListener("change", syncAll); syncAll();
|
||
|
||
function renderHist(rates) {
|
||
const box = m.body.querySelector("#perf-rate-hist");
|
||
if (!rates.length) { box.textContent = "이력이 없습니다(현재 0%)."; return; }
|
||
box.innerHTML = '<table class="perf-table"><thead><tr><th class="perf-th-label">적용 시작일</th><th>요율</th>' +
|
||
'<th class="perf-th-label">메모</th><th class="perf-th-label">변경자</th><th></th></tr></thead><tbody>' +
|
||
rates.map(function (r) {
|
||
const eff = r.effective_from === "2000-01-01" ? "처음부터" : r.effective_from;
|
||
return "<tr><td>" + esc(eff) + '</td><td class="perf-num">' + esc(String(r.rate_percent).replace(/\.?0+$/, "")) +
|
||
"%</td><td>" + esc(r.memo) + "</td><td>" + esc((r.created_by || "").split("@")[0]) +
|
||
'</td><td><button type="button" class="erp-btn erp-btn-ghost erp-btn-sm" data-del="' + r.id + '">삭제</button></td></tr>';
|
||
}).join("") + "</tbody></table>";
|
||
}
|
||
try { renderHist((await api("GET", "/performance/api/marketplaces/" + code + "/rates")).rates || []); }
|
||
catch (err) { m.body.querySelector("#perf-rate-hist").textContent = err.message; }
|
||
|
||
m.body.addEventListener("click", async function (e) {
|
||
const b = e.target.closest("button[data-del]");
|
||
if (!b) return;
|
||
if (!(await confirmMsg("이 수수료 이력을 삭제할까요? 해당 기간 실적의 수수료가 다시 계산됩니다."))) return;
|
||
try {
|
||
renderHist((await api("DELETE", "/performance/api/marketplaces/" + code + "/rates/" + b.dataset.del)).rates || []);
|
||
m.changed = true;
|
||
} catch (err) { alertMsg(err.message); }
|
||
});
|
||
async function submit() {
|
||
const rate = m.body.querySelector("#perf-rate-in").value.trim();
|
||
if (!rate) { m.body.querySelector("#perf-rate-in").focus(); return; }
|
||
try {
|
||
const res = await api("POST", "/performance/api/marketplaces/" + code + "/rates", {
|
||
rate_percent: rate, effective_from: all.checked ? "2000-01-01" : from.value,
|
||
memo: m.body.querySelector("#perf-rate-memo").value,
|
||
});
|
||
renderHist(res.rates || []);
|
||
m.changed = true;
|
||
m.body.querySelector("#perf-rate-in").value = "";
|
||
} catch (err) { alertMsg(err.message); }
|
||
}
|
||
save.addEventListener("click", submit);
|
||
m.body.querySelector("#perf-rate-form").addEventListener("submit", function (e) { e.preventDefault(); submit(); });
|
||
m.body.querySelector("#perf-rate-in").focus();
|
||
}
|
||
|
||
// ── API 인증정보 ──
|
||
async function openCreds(code, name, base) {
|
||
base = base || "/performance/api/marketplaces/";
|
||
const m = openModal(name + " API 설정", { narrow: true, onClose: function () { if (m.changed) location.reload(); } });
|
||
m.body.innerHTML = '<p class="perf-muted">불러오는 중…</p>';
|
||
let info;
|
||
try { info = await api("GET", base + code + "/credentials"); }
|
||
catch (err) { m.body.innerHTML = '<p class="perf-notice is-warn">' + esc(err.message) + "</p>"; 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 += '<p class="perf-muted">' + esc(info.note) + "</p>";
|
||
if (info.docs_url) html += '<p class="perf-muted">API 문서: <a href="' + esc(info.docs_url) + '" target="_blank" rel="noopener noreferrer">' + esc(info.docs_url) + "</a></p>";
|
||
if (info.shared) {
|
||
m.body.innerHTML = html + '<p class="perf-notice">이 쇼핑몰은 기존 공통 연동을 사용합니다. 연결 테스트로 상태만 확인할 수 있습니다.</p>';
|
||
} else {
|
||
if (!info.key || !info.key.ok) html += '<p class="perf-notice is-warn">' + esc((info.key && info.key.message) || "암호화 키가 없습니다.") + "</p>";
|
||
if (info.decrypt_error) html += '<p class="perf-notice is-warn">' + esc(info.decrypt_error) + "</p>";
|
||
html += '<form class="perf-form" id="perf-cred-form" autocomplete="off">' + info.fields.map(function (f) {
|
||
const id = "perf-cred-" + f.key;
|
||
let state = "";
|
||
if (f.secret) {
|
||
state = f.has_value
|
||
? '<span class="perf-secret-state">현재 값: •••••••• (저장됨' + (f.updated_at ? ", " + esc(f.updated_at.slice(0, 16).replace("T", " ")) : "") + ")</span>"
|
||
: '<span class="perf-secret-state is-empty">저장된 값 없음</span>';
|
||
}
|
||
// 여러 줄 항목(서비스 계정 JSON 키 등)은 textarea — 비밀값이면 저장 후 내용은 다시 보이지 않는다
|
||
const field = f.multiline
|
||
? '<textarea class="erp-input perf-cred-multi" id="' + id + '" data-key="' + esc(f.key) + '" rows="6" spellcheck="false" ' +
|
||
'autocomplete="off" placeholder="' + (f.secret && f.has_value ? "변경할 때만 새 값 붙여넣기" : esc(f.placeholder || "붙여넣기")) + '">' +
|
||
(f.secret ? "" : esc(f.value || "")) + "</textarea>"
|
||
: '<input class="erp-input" id="' + id + '" data-key="' + esc(f.key) + '" ' +
|
||
(f.secret ? 'type="password" autocomplete="new-password" placeholder="' + (f.has_value ? "변경할 때만 새 값 입력" : "입력") + '"'
|
||
: 'type="text" value="' + esc(f.value || "") + '" placeholder="' + esc(f.placeholder || "") + '"') + " />";
|
||
return '<div class="perf-form-row"><label for="' + id + '">' + esc(f.label) + (f.required ? " *" : "") + "</label>" + state +
|
||
field +
|
||
(f.help ? '<div class="perf-form-help">' + esc(f.help) + "</div>" : "") +
|
||
(f.secret && f.has_value && !f.required ? '<label class="perf-check"><input type="checkbox" data-clear="' + esc(f.key) + '" /> 저장된 값 지우기</label>' : "") +
|
||
"</div>";
|
||
}).join("") + "</form>" +
|
||
'<p class="perf-foot perf-muted">[연결 테스트]는 입력한 새 값으로 시험하며 저장하지 않습니다(빈 칸은 저장된 값 사용). ' +
|
||
"[저장]은 연결 테스트 결과와 관계없이 저장합니다 — 쇼핑몰의 일시 장애로 테스트가 실패할 수 있기 때문입니다. " +
|
||
"저장 후 자동으로 한 번 더 연결 테스트를 합니다.</p>";
|
||
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", base + code + "/credentials", { values: typed(), clear: cleared() });
|
||
m.changed = true;
|
||
m.body.querySelectorAll("input[type=password], textarea.perf-cred-multi").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], textarea[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", base + 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, base) {
|
||
btn.disabled = true;
|
||
const label = btn.textContent;
|
||
btn.textContent = "확인 중…";
|
||
try {
|
||
const res = await api("POST", (base || "/performance/api/marketplaces/") + code + "/test", {});
|
||
await alertMsg(name + " — " + (res.ok ? "정상 연결\n" : res.label + "\n") + res.message, res.ok ? { tone: "ok" } : undefined);
|
||
location.reload();
|
||
} catch (err) {
|
||
alertMsg(err.message);
|
||
} finally { btn.disabled = false; btn.textContent = label; }
|
||
}
|
||
|
||
// ── 카페24 매출 대조 — 카페24 "일별 매출내역" 열 순서대로 ──
|
||
let lastShop = {}; // 일별 비교에 붙여넣은 카페24 값(날짜 → 열) — 대조 표에 차이 열로 표시
|
||
const recon = document.getElementById("perf-recon");
|
||
if (recon) recon.addEventListener("click", async function () {
|
||
const day = document.getElementById("perf-recon-date").value;
|
||
const out = document.getElementById("perf-recon-result");
|
||
if (!day) return;
|
||
recon.disabled = true;
|
||
out.innerHTML = '<p class="perf-muted">카페24에서 불러오는 중…</p>';
|
||
try {
|
||
const r = await api("GET", "/performance/api/marketplaces/cafe24/reconcile?date=" + encodeURIComponent(day));
|
||
if (!r.ok) { out.innerHTML = '<p class="perf-notice is-warn">' + esc((r.label ? r.label + " — " : "") + r.message) + "</p>"; return; }
|
||
const s = r.orders.self, m = r.orders.market, rs = r.refunds.self, rm = r.refunds.market;
|
||
const dev = function (n, amt) { return n ? fmt(n) + '건 <span class="perf-muted">' + won(amt) + "</span>" : won(0); };
|
||
const MARKET_NAMES = {};
|
||
root.querySelectorAll("tr[data-code]").forEach(function (tr) { MARKET_NAMES[tr.dataset.code] = tr.dataset.name; });
|
||
const disc = ["membership_discount_amount", "set_product_discount_amount", "app_discount_amount",
|
||
"market_other_discount_amount", "shipping_fee_discount_amount"];
|
||
const coup = ["coupon_discount_price", "coupon_shipping_fee_amount"];
|
||
const LABEL = {
|
||
membership_discount_amount: "회원할인", set_product_discount_amount: "세트상품할인", app_discount_amount: "앱할인",
|
||
market_other_discount_amount: "마켓 기타할인", shipping_fee_discount_amount: "배송비할인",
|
||
coupon_discount_price: "상품쿠폰", coupon_shipping_fee_amount: "배송비쿠폰",
|
||
};
|
||
const sum = function (g, keys) { return keys.reduce(function (a, k) { return a + (g[k] || 0); }, 0); };
|
||
// x[4] = 붙여넣은 카페24 일별 매출내역 열 번호(일별 비교에서 이 날짜를 눌렀을 때 차이 표시)
|
||
const rows = [
|
||
["주문수", s.orders, m.orders, "cnt", 0], ["품목수(수량 합계)", s.items, m.items, "cnt", 1], ["품목수(품목 줄 수)", s.lines, m.lines, "cnt", 1],
|
||
["상품구매금액", s.order_price_amount, m.order_price_amount, "", 2],
|
||
["배송비", s.shipping_fee, m.shipping_fee, "", 3],
|
||
["할인 합계", sum(s, disc), sum(m, disc), "", 4],
|
||
].concat(disc.map(function (k) { return [" · " + LABEL[k], s[k], m[k], "sub"]; }))
|
||
.concat([["쿠폰 합계", sum(s, coup), sum(m, coup), "", 5]])
|
||
.concat(coup.map(function (k) { return [" · " + LABEL[k], s[k], m[k], "sub"]; }))
|
||
.concat([
|
||
[" 참고식: 상품구매금액 + 배송비 − 할인 − 쿠폰", s.goods_total, m.goods_total, "sub"],
|
||
["실결제금액", s.payment_amount, m.payment_amount, "", 6],
|
||
["적립금 사용", s.points_spent_amount, m.points_spent_amount, "", 7],
|
||
["예치금 사용", s.credits_spent_amount, m.credits_spent_amount, "", 8],
|
||
["네이버포인트", s.naver_point, m.naver_point, "", 9],
|
||
["결제합계(실결제 + 적립금 + 예치금 + 네이버포인트)", s.total, m.total, "key", 10],
|
||
["환불 건수(환불 목록)", rs.count, rm.count, "cnt"],
|
||
[" · 실제 환불액", rs.actual_refund_amount, rm.actual_refund_amount, "sub"],
|
||
[" · 적립금 환불", rs.used_points, rm.used_points, "sub"],
|
||
[" · 예치금 환불", rs.used_credits, rm.used_credits, "sub"],
|
||
["환불 목록 없는 네이버페이 취소·반품 품목 수", rs.no_record_count, rm.no_record_count, "cnt"],
|
||
[" · 취소·반품 금액", rs.no_record, rm.no_record, "sub"],
|
||
["환불합계", rs.total, rm.total, "key", 11],
|
||
["순매출(결제합계 − 환불합계)", s.total - rs.total, m.total - rm.total, "key", 12],
|
||
]);
|
||
const shopCols = (lastShop[r.date] || {}).cols || null;
|
||
out.innerHTML = '<table class="perf-table" style="margin-top:8px"><thead><tr><th class="perf-th-label">' + esc(r.date) +
|
||
"</th><th>카페24 열(자체몰 채널)</th><th>다른 쇼핑몰 열(외부 마켓)</th>" +
|
||
(shopCols ? "<th>합계</th><th>카페24 화면</th><th>차이</th>" : "") + "</tr></thead><tbody>" +
|
||
rows.map(function (x) {
|
||
const cls = x[3] === "key" ? ' class="perf-row-week"' : "";
|
||
const f = function (v) { return x[3] === "cnt" ? fmt(v) : won(v); };
|
||
let cmp = "";
|
||
if (shopCols) {
|
||
const both = (x[1] || 0) + (x[2] || 0), c = x[4] == null ? null : shopCols[x[4]];
|
||
cmp = '<td class="perf-num">' + f(both) + '</td><td class="perf-num">' + (c == null ? "" : f(c)) + '</td><td class="perf-num">' +
|
||
(c == null ? "" : both === c ? '<span class="perf-diff-ok">✓</span>' : '<span class="perf-diff-bad">' + (both > c ? "+" : "") + fmt(both - c) + "</span>") + "</td>";
|
||
}
|
||
return "<tr" + cls + '><th class="perf-td-label' + (x[3] === "sub" ? " perf-muted" : "") + '">' + esc(x[0]) +
|
||
'</th><td class="perf-num">' + f(x[1]) + '</td><td class="perf-num">' + f(x[2]) + "</td>" + cmp + "</tr>";
|
||
}).join("") + "</tbody></table>" +
|
||
(r.refund_basis
|
||
? (function () {
|
||
const b = r.refund_basis;
|
||
const row = function (label, x, cls) {
|
||
return "<tr" + (cls ? ' class="' + cls + '"' : "") + '><th class="perf-td-label">' + label + '</th><td class="perf-num">' +
|
||
fmt(x.count) + '</td><td class="perf-num">' + won(x.actual_refund_amount) + '</td><td class="perf-num">' +
|
||
won(x.used_points + x.used_credits) + '</td><td class="perf-num">' + won(x.with_points) + "</td></tr>";
|
||
};
|
||
return '<h4 class="perf-h" style="margin:14px 0 6px">환불 기준 비교 — 카페24 화면의 그날 "환불합계"와 같은 칸을 찾아 주세요</h4>' +
|
||
'<table class="perf-table"><thead><tr><th class="perf-th-label">기준</th><th>건수</th><th>실제 환불액</th>' +
|
||
"<th>적립금·예치금 환불</th><th>합계(포함)</th></tr></thead><tbody>" +
|
||
row("환불완료일 기준 · 완료 <span class='perf-pill is-ok'>적용(합계 포함 칸)</span>", b.completed, "perf-row-week") +
|
||
row("환불접수일 기준 · 전체 상태", b.accepted_all) +
|
||
(b.by_pay_date ? row("결제일 기준 · 그날 결제한 주문의 환불(오늘까지" +
|
||
(b.by_pay_date.refund_dates.length ? ", 환불일 " + esc(b.by_pay_date.refund_dates.join(", ")) : "") + ")", b.by_pay_date) : "") +
|
||
(b.accepted_by_status || []).map(function (s) {
|
||
return row(" · 접수일 기준 " + esc(s.label), s);
|
||
}).join("") + "</tbody></table>";
|
||
})()
|
||
: "") +
|
||
((r.refund_candidates || []).length
|
||
? '<h4 class="perf-h" style="margin:14px 0 6px">환불합계 후보 — 카페24 화면 값을 넣으면 같은 줄을 표시합니다</h4>' +
|
||
'<div class="perf-row-inline" style="margin-bottom:6px"><input class="erp-input perf-date" type="text" inputmode="numeric" ' +
|
||
'id="perf-recon-target" placeholder="카페24 환불합계" /></div>' +
|
||
'<table class="perf-table" id="perf-recon-cands"><thead><tr><th class="perf-th-label">후보</th><th>금액</th><th>차이</th></tr></thead><tbody>' +
|
||
r.refund_candidates.map(function (c) {
|
||
return '<tr data-amount="' + c.amount + '"><td class="perf-td-label">' + esc(c.label) + '</td><td class="perf-num">' +
|
||
won(c.amount) + '</td><td class="perf-num perf-cand-diff">–</td></tr>';
|
||
}).join("") + "</tbody></table>"
|
||
: "") +
|
||
((r.refund_list || []).length
|
||
? '<h4 class="perf-h" style="margin:14px 0 6px">환불 건별 (환불 API)</h4>' +
|
||
'<table class="perf-table"><thead><tr><th class="perf-th-label">환불코드</th><th class="perf-th-label">주문번호</th>' +
|
||
'<th class="perf-th-label">채널</th><th class="perf-th-label">상태</th><th class="perf-th-label">접수일</th><th class="perf-th-label">완료일</th>' +
|
||
"<th>수량</th><th>실제 환불액</th><th>적립금·예치금</th><th class=\"perf-th-label\">환불수단</th></tr></thead><tbody>" +
|
||
r.refund_list.map(function (x) {
|
||
const st = { T: "환불완료", F: "환불전", M: "환불보류" }[x.status] || x.status;
|
||
return '<tr><td class="perf-td-label">' + esc(x.refund_code) + "</td><td>" + esc(x.order_id) + "</td><td>" + esc(x.channel || "–") +
|
||
"</td><td>" + esc(st) + "</td><td>" + esc(x.accepted_date || "–") + "</td><td>" + esc(x.refund_date || "–") +
|
||
'</td><td class="perf-num">' + fmt(x.quantity) + '</td><td class="perf-num">' + won(x.actual_refund_amount) +
|
||
'</td><td class="perf-num">' + won(x.used_points + x.used_credits) + "</td><td>" + esc((x.methods || []).join(", ") || "–") + "</td></tr>";
|
||
}).join("") + "</tbody></table>"
|
||
: "") +
|
||
((r.no_record_claims || []).length
|
||
? '<h4 class="perf-h" style="margin:14px 0 6px">환불 목록에 없는 네이버페이 취소·반품 (환불합계에 넣은 건 — 주문 전체취소면 배송비 포함)</h4>' +
|
||
'<table class="perf-table"><thead><tr><th class="perf-th-label">주문번호</th><th class="perf-th-label">품목</th>' +
|
||
'<th class="perf-th-label">채널</th><th class="perf-th-label">상태</th><th class="perf-th-label">반영일</th><th class="perf-th-label">상품</th>' +
|
||
"<th>수량</th><th>뺀 금액</th><th>품목 결제금액</th><th>쿠폰</th><th class=\"perf-th-label\">주문 전체취소</th><th>주문 배송비</th></tr></thead><tbody>" +
|
||
r.no_record_claims.map(function (c) {
|
||
return '<tr><td class="perf-td-label">' + esc(c.order_id) + "</td><td>" + esc(c.item_code) + "</td><td>" + esc(c.place_name || c.market_id || "–") +
|
||
"</td><td>" + esc(c.status + (c.naver_pay_claim_status ? " / 네이버페이 " + c.naver_pay_claim_status : "")) + "</td><td>" + esc(c.day) +
|
||
"</td><td>" + esc(c.product_name) + '</td><td class="perf-num">' + fmt(c.quantity) + '</td><td class="perf-num">' + won(c.amount) +
|
||
(c.shipping_refund ? ' <span class="perf-muted">(배송비 ' + fmt(c.shipping_refund) + ")</span>" : "") +
|
||
'</td><td class="perf-num">' + won(c.item_payment_amount) + '</td><td class="perf-num">' + won(c.coupon) + "</td><td>" +
|
||
(c.order_all_claimed ? "<b>예</b>" : "아니오") + '</td><td class="perf-num">' + won(c.order_shipping_fee) + "</td></tr>";
|
||
}).join("") + "</tbody></table>"
|
||
: "") +
|
||
((r.reduced_orders || []).length
|
||
? '<h4 class="perf-h" style="margin:14px 0 6px">그날 결제한 주문 중 금액이 줄어든 주문 (취소·반품) — "환불 기록 없음"이 환불 API 에 안 잡힌 건</h4>' +
|
||
'<table class="perf-table"><thead><tr><th class="perf-th-label">주문번호</th><th class="perf-th-label">채널</th>' +
|
||
'<th class="perf-th-label">결제수단</th><th class="perf-th-label">품목 상태</th><th class="perf-th-label">취소·환불일</th>' +
|
||
"<th>결제 당시</th><th>현재</th><th>줄어든 금액</th><th>환불 기록</th></tr></thead><tbody>" +
|
||
r.reduced_orders.map(function (x) {
|
||
const miss = x.diff - x.refunded;
|
||
return "<tr" + (miss > 0 ? ' class="perf-row-match"' : "") + '><td class="perf-td-label">' + esc(x.order_id) + "</td><td>" +
|
||
esc(x.channel || "–") + "</td><td>" + esc(x.payment || "–") + "</td><td>" +
|
||
esc(x.statuses.join(", ") + (x.naver_pay.length ? " / 네이버페이 " + x.naver_pay.join(",") : "")) + "</td><td>" +
|
||
esc(x.claim_dates.join(", ") || "–") + '</td><td class="perf-num">' + won(x.initial) + '</td><td class="perf-num">' +
|
||
won(x.now) + '</td><td class="perf-num">' + won(x.diff) + '</td><td class="perf-num">' +
|
||
(x.refunded ? won(x.refunded) + ' <span class="perf-muted">' + esc(x.refund_dates.join(", ")) + "</span>" : "<b>없음</b>") + "</td></tr>";
|
||
}).join("") + "</tbody></table>"
|
||
: "") +
|
||
(r.claims
|
||
? '<h4 class="perf-h" style="margin:14px 0 6px">그날 취소·반품·교환 완료 품목 (주문 API)</h4>' +
|
||
((r.claims.errors || []).length ? '<p class="perf-notice is-warn">' + esc(r.claims.errors.join(" / ")) + "</p>" : "") +
|
||
((r.claims.items || []).length
|
||
? '<table class="perf-table"><thead><tr><th class="perf-th-label">조회</th><th class="perf-th-label">주문번호</th>' +
|
||
'<th class="perf-th-label">채널</th><th class="perf-th-label">상태</th><th class="perf-th-label">클레임</th><th class="perf-th-label">상품</th>' +
|
||
"<th>수량</th><th>판매가×수량</th><th>품목 결제금액</th><th>쿠폰</th><th class=\"perf-th-label\">환불 기록</th></tr></thead><tbody>" +
|
||
r.claims.items.map(function (c) {
|
||
return "<tr" + (c.done ? "" : ' class="perf-muted"') + '><td class="perf-td-label">' + esc(c.via) + "</td><td>" + esc(c.order_id) +
|
||
"</td><td>" + esc(c.channel || "–") + "</td><td>" + esc(c.status + (c.status_text ? " " + c.status_text : "")) +
|
||
"</td><td>" + esc(c.claim_code || "–") + "</td><td>" + esc(c.product_name) + '</td><td class="perf-num">' + fmt(c.quantity) +
|
||
'</td><td class="perf-num">' + won(c.product_amount) + '</td><td class="perf-num">' + won(c.payment_amount) +
|
||
'</td><td class="perf-num">' + won(c.coupon) + "</td><td>" + (c.has_refund ? "있음" : '<b>없음</b>') + "</td></tr>";
|
||
}).join("") + "</tbody></table>" +
|
||
'<p class="perf-foot perf-muted">전체취소 주문 배송비 ' + won(r.claims.full_cancel_shipping) +
|
||
'. 흐린 줄은 아직 완료되지 않은 클레임(후보 합계에서 제외).</p>'
|
||
: '<p class="perf-muted">없음</p>')
|
||
: "") +
|
||
((r.by_channel || []).length
|
||
? '<h4 class="perf-h" style="margin:14px 0 6px">주문 채널별</h4>' +
|
||
'<table class="perf-table"><thead><tr><th class="perf-th-label">market_id</th><th class="perf-th-label">주문경로</th>' +
|
||
'<th class="perf-th-label">구분</th><th class="perf-th-label">반영 열</th><th>주문수</th><th>결제합계</th>' +
|
||
"<th>PC 주문</th><th>모바일 주문</th><th>환불</th><th>순매출</th></tr></thead><tbody>" +
|
||
r.by_channel.map(function (b) {
|
||
const col = MARKET_NAMES[b.target] || b.target;
|
||
const kind = b.kind === "self" ? "자체몰 채널" + (b.label ? "(" + b.label + ")" : "")
|
||
: b.kind === "market" ? "외부 마켓" : '<span class="perf-err" style="display:inline">알 수 없는 채널</span>';
|
||
return '<tr><td class="perf-td-label">' + esc(b.market_id) + "</td><td>" + esc(b.place || "–") +
|
||
(b.place_id && b.place_id !== b.place ? ' <span class="perf-muted">' + esc(b.place_id) + "</span>" : "") +
|
||
"</td><td>" + (b.kind === "unknown" ? kind : esc(kind)) + "</td><td>" + esc(col) +
|
||
'</td><td class="perf-num">' + fmt(b.orders) + '</td><td class="perf-num">' + won(b.total) +
|
||
'</td><td class="perf-num">' + dev(b.pc_orders, b.pc_total) + '</td><td class="perf-num">' + dev(b.mobile_orders, b.mobile_total) +
|
||
'</td><td class="perf-num">' + won(-b.refund_amount) + '</td><td class="perf-num">' + won(b.total - b.refund_amount) + "</td></tr>";
|
||
}).join("") + "</tbody>" +
|
||
// 카페24 열(자체몰) 기기 합계
|
||
(function () {
|
||
const own = r.by_channel.filter(function (b) { return b.target === "cafe24"; });
|
||
const t = own.reduce(function (a, b) {
|
||
a.o += b.orders; a.t += b.total; a.po += b.pc_orders; a.pt += b.pc_total; a.mo += b.mobile_orders; a.mt += b.mobile_total;
|
||
a.ra += b.refund_amount; return a;
|
||
}, { o: 0, t: 0, po: 0, pt: 0, mo: 0, mt: 0, ra: 0 });
|
||
return '<tfoot><tr class="perf-row-week"><th class="perf-td-label" colspan="4">카페24 열(자체몰) 합계</th><td class="perf-num">' +
|
||
fmt(t.o) + '</td><td class="perf-num">' + won(t.t) + '</td><td class="perf-num">' + dev(t.po, t.pt) +
|
||
'</td><td class="perf-num">' + dev(t.mo, t.mt) + '</td><td class="perf-num">' + won(-t.ra) +
|
||
'</td><td class="perf-num">' + won(t.t - t.ra) + "</td></tr></tfoot>";
|
||
})() + "</table>" +
|
||
'<p class="perf-foot perf-muted">한 줄 = market_id × 주문경로. market_id "self"는 PC 전용이 아니라 자체몰 전체이며, 그 안에 PC쇼핑몰·모바일웹 경로가 섞여 있습니다. ' +
|
||
'PC/모바일 주문은 카페24가 주문마다 주는 모바일 주문 여부(order_from_mobile) 기준입니다.</p>'
|
||
: "") +
|
||
((r.by_payment || []).length
|
||
? '<h4 class="perf-h" style="margin:14px 0 6px">결제수단별 (카페24 열)</h4>' +
|
||
'<table class="perf-table"><thead><tr><th class="perf-th-label">결제수단</th><th>주문수</th><th>결제합계</th><th>비중</th></tr></thead><tbody>' +
|
||
(function () {
|
||
const tot = r.by_payment.reduce(function (a, p) { return a + p.total; }, 0);
|
||
return r.by_payment.map(function (p) {
|
||
return '<tr><td class="perf-td-label">' + esc(p.method) + '</td><td class="perf-num">' + fmt(p.orders) +
|
||
'</td><td class="perf-num">' + won(p.total) + '</td><td class="perf-num">' +
|
||
(tot > 0 ? (p.total / tot * 100).toFixed(1) + "%" : "–") + "</td></tr>";
|
||
}).join("");
|
||
})() + "</tbody></table>"
|
||
: "") +
|
||
(r.diag
|
||
? (function () {
|
||
// 판매가 합계 − 카페24 상품구매금액 = 찾는 금액(예: 9/23 → 62). 같은 값인 필드를 강조.
|
||
const gap = shopCols ? (s.order_price_amount + m.order_price_amount) - shopCols[2] : null;
|
||
const PART = { initial: "주문 금액(결제 당시 initial_order_amount)", actual: "주문 금액(현재 actual_order_amount)",
|
||
item: "품목(items) 합계", order: "주문 최상위 필드" };
|
||
const cells = ["initial", "actual", "item", "order"].map(function (p) {
|
||
const f = r.diag[p] || {};
|
||
const keys = Object.keys(f).filter(function (k) { return f[k]; });
|
||
return '<div><h5 class="perf-h" style="margin:6px 0">' + esc(PART[p]) + "</h5>" +
|
||
(keys.length ? '<table class="perf-table"><tbody>' + keys.map(function (k) {
|
||
return "<tr" + (gap && f[k] === gap ? ' class="perf-row-match"' : "") + '><td class="perf-td-label">' + esc(k) +
|
||
'</td><td class="perf-num">' + fmt(f[k]) + "</td></tr>";
|
||
}).join("") + "</tbody></table>" : '<p class="perf-muted">0 아닌 값 없음</p>') + "</div>";
|
||
}).join("");
|
||
const odd = (r.odd_orders || []).map(function (o) {
|
||
return '<tr><td class="perf-td-label">' + esc(o.order_id) + "</td><td>" + esc(o.channel || "–") + '</td><td class="perf-num">' +
|
||
fmt(o.items_gross) + '</td><td class="perf-num">' + fmt(o.order_price_amount) + '</td><td class="perf-num">' + fmt(o.total) +
|
||
'</td><td style="white-space:normal;font-size:11.5px">' + o.items.map(function (i) {
|
||
return esc(i.code + " " + i.status + " ×" + i.quantity + " — " +
|
||
Object.keys(i.fields).map(function (k) { return k + "=" + fmt(i.fields[k]); }).join(", "));
|
||
}).join("<br>") + "</td></tr>";
|
||
}).join("");
|
||
return '<h4 class="perf-h" style="margin:14px 0 6px">원본 금액 필드 합계 (진단 — 그날 결제 주문 전체)' +
|
||
(gap ? ' · 판매가 합계 − 카페24 상품구매금액 = <b>' + fmt(gap) + "</b> (같은 값 강조)" : "") + "</h4>" +
|
||
'<div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(240px,1fr));gap:10px">' + cells + "</div>" +
|
||
(odd ? '<h4 class="perf-h" style="margin:14px 0 6px">상품금액이 100원 단위가 아니거나 판매가×수량 합과 다른 주문</h4>' +
|
||
'<table class="perf-table"><thead><tr><th class="perf-th-label">주문번호</th><th class="perf-th-label">채널</th><th>판매가×수량</th>' +
|
||
'<th>주문 상품금액</th><th>결제합계(계산)</th><th class="perf-th-label">품목 금액 필드(0 제외)</th></tr></thead><tbody>' + odd + "</tbody></table>" : "");
|
||
})()
|
||
: "") +
|
||
'<p class="perf-foot perf-muted">' + esc(r.formula) + ". 미결제 주문 " + fmt(r.unpaid_orders) +
|
||
"건 제외. \"알 수 없는 채널\"은 카페24 열에 넣습니다 — 외부 마켓이면 어느 쇼핑몰인지 알려 주세요.</p>";
|
||
const target = document.getElementById("perf-recon-target");
|
||
if (target) target.addEventListener("input", function () {
|
||
const v = parseInt(target.value.replace(/[^0-9-]/g, ""), 10);
|
||
out.querySelectorAll("#perf-recon-cands tr[data-amount]").forEach(function (tr) {
|
||
const a = parseInt(tr.dataset.amount, 10);
|
||
const d = tr.querySelector(".perf-cand-diff");
|
||
if (isNaN(v)) { d.textContent = "–"; tr.classList.remove("perf-row-match"); return; }
|
||
d.textContent = a === v ? "일치" : fmt(a - v);
|
||
tr.classList.toggle("perf-row-match", a === v);
|
||
});
|
||
});
|
||
} catch (err) {
|
||
out.innerHTML = '<p class="perf-notice is-warn">' + esc(err.message) + "</p>";
|
||
} finally { recon.disabled = false; }
|
||
});
|
||
|
||
// ── 일별 한 번에 비교 — 카페24 일별 매출내역 붙여넣기 ↔ 저장값 ↔ 지금 API 값 ──
|
||
// 붙여넣은 한 줄: "2026-09-29(화) 주문수 품목수 … 결제합계 환불합계 순매출" — 뒤의 세 숫자와 첫 숫자(주문수)만 쓴다.
|
||
function parseDaily(text) {
|
||
const out = {};
|
||
String(text || "").split(/\r?\n/).forEach(function (line) {
|
||
const m = line.match(/(\d{4})[-./](\d{2})[-./](\d{2})/);
|
||
if (!m) return;
|
||
const nums = (line.slice(m.index + m[0].length).match(/-?\d[\d,]*/g) || [])
|
||
.map(function (x) { return parseInt(x.replace(/,/g, ""), 10); });
|
||
if (nums.length < 3) return;
|
||
const n = nums.length;
|
||
out[m[1] + "-" + m[2] + "-" + m[3]] = { orders: n >= 13 ? nums[0] : null, paid: nums[n - 3], refund: nums[n - 2], net: nums[n - 1],
|
||
cols: n >= 13 ? nums.slice(n - 13) : null };
|
||
});
|
||
return out;
|
||
}
|
||
const dailyBtn = document.getElementById("perf-daily-check");
|
||
if (dailyBtn) dailyBtn.addEventListener("click", async function () {
|
||
const out = document.getElementById("perf-daily-result");
|
||
const shop = lastShop = parseDaily(document.getElementById("perf-daily-paste").value);
|
||
const dates = Object.keys(shop).sort();
|
||
if (!dates.length) { out.innerHTML = '<p class="perf-notice is-warn">날짜가 있는 줄을 찾지 못했습니다. 카페24 일별 매출내역 표를 복사해 붙여 넣으세요.</p>'; return; }
|
||
const live = document.getElementById("perf-daily-live").checked;
|
||
dailyBtn.disabled = true;
|
||
out.innerHTML = '<p class="perf-muted">' + (live ? "저장값과 카페24 API 값을 계산하는 중… (기간이 길면 1~2분)" : "저장값을 불러오는 중…") + "</p>";
|
||
try {
|
||
const from = dates[0], to = dates[dates.length - 1];
|
||
const r = await api("GET", "/performance/api/marketplaces/cafe24/daily-check?from=" + from + "&to=" + to + (live ? "&live=1" : ""));
|
||
if (!r.ok) { out.innerHTML = '<p class="perf-notice is-warn">' + esc(r.message) + "</p>"; return; }
|
||
const byDate = function (rows) { const o = {}; (rows || []).forEach(function (x) { o[x.date] = x; }); return o; };
|
||
const db = byDate(r.db), lv = r.live ? byDate(r.live) : null;
|
||
const zero = { paid: 0, refund: 0, orders: 0 };
|
||
const diff = function (ours, theirs) {
|
||
const d = ours - theirs;
|
||
return d === 0 ? '<span class="perf-diff-ok">✓</span>' : '<span class="perf-diff-bad">' + (d > 0 ? "+" : "") + fmt(d) + "</span>";
|
||
};
|
||
const todayIso = today();
|
||
let bad = 0, stale = 0, rule = 0;
|
||
const sum = { cp: 0, cr: 0, dp: 0, dr: 0, lp: 0, lr: 0 };
|
||
const body = dates.slice().reverse().map(function (d) {
|
||
const c = shop[d], x = db[d] || zero, l = lv ? (lv[d] || zero) : null;
|
||
sum.cp += c.paid; sum.cr += c.refund; sum.dp += x.paid; sum.dr += x.refund;
|
||
if (l) { sum.lp += l.paid; sum.lr += l.refund; }
|
||
const dbOk = x.paid === c.paid && x.refund === c.refund;
|
||
const liveOk = l && l.paid === c.paid && l.refund === c.refund;
|
||
let verdict;
|
||
if (dbOk) verdict = '<span class="perf-pill is-ok">일치</span>';
|
||
else if (l && liveOk) { verdict = '<span class="perf-pill">다시 가져오면 해결</span>'; stale++; }
|
||
else if (l) {
|
||
const what = [l.paid !== c.paid ? "결제" : "", l.refund !== c.refund ? "환불" : ""].filter(Boolean).join("·");
|
||
verdict = '<span class="perf-pill is-bad">규칙 차이(' + what + ")</span>"; rule++;
|
||
} else verdict = '<span class="perf-pill is-bad">차이</span>';
|
||
if (!dbOk) bad++;
|
||
const wd = "일월화수목금토"[new Date(d + "T00:00:00").getDay()];
|
||
return "<tr" + (dbOk ? "" : ' class="perf-row-diff"') + '><td class="perf-td-label"><button type="button" class="perf-link" data-recon-day="' + d + '">' +
|
||
esc(d) + "(" + wd + ")</button>" + (d === todayIso ? ' <span class="perf-muted">오늘·집계 중</span>' : "") + "</td>" +
|
||
'<td class="perf-num">' + (c.orders == null ? "–" : fmt(c.orders)) + ' <span class="perf-muted">/ ' + fmt(x.orders) + (l ? " / " + fmt(l.orders) : "") + "</span></td>" +
|
||
'<td class="perf-num">' + won(c.paid) + '</td><td class="perf-num">' + diff(x.paid, c.paid) + "</td>" + (l ? '<td class="perf-num">' + diff(l.paid, c.paid) + "</td>" : "") +
|
||
'<td class="perf-num">' + won(c.refund) + '</td><td class="perf-num">' + diff(x.refund, c.refund) + "</td>" + (l ? '<td class="perf-num">' + diff(l.refund, c.refund) + "</td>" : "") +
|
||
"<td>" + verdict + (x.synced_at ? '<div class="perf-muted" style="font-size:11px">저장 ' + esc(String(x.synced_at).slice(5, 16).replace("T", " ")) + "</div>" : "") + "</td></tr>";
|
||
}).join("");
|
||
const head = '<tr><th class="perf-th-label">날짜</th><th>주문수 <span class="perf-muted">카페24 / 저장' + (lv ? " / API" : "") + "</span></th>" +
|
||
"<th>결제합계(카페24)</th><th>저장값 차이</th>" + (lv ? "<th>API 차이</th>" : "") +
|
||
"<th>환불합계(카페24)</th><th>저장값 차이</th>" + (lv ? "<th>API 차이</th>" : "") + '<th class="perf-th-label">판정</th></tr>';
|
||
const foot = '<tr class="perf-row-week"><th class="perf-td-label">합계</th><td></td><td class="perf-num">' + won(sum.cp) + '</td><td class="perf-num">' +
|
||
diff(sum.dp, sum.cp) + "</td>" + (lv ? '<td class="perf-num">' + diff(sum.lp, sum.cp) + "</td>" : "") + '<td class="perf-num">' + won(sum.cr) +
|
||
'</td><td class="perf-num">' + diff(sum.dr, sum.cr) + "</td>" + (lv ? '<td class="perf-num">' + diff(sum.lr, sum.cr) + "</td>" : "") + "<td></td></tr>";
|
||
const summary = bad
|
||
? "저장값이 다른 날 " + bad + "일" + (lv ? " — 다시 가져오면 해결 " + stale + "일, 규칙 차이 " + rule + "일" : " — [API 값도 계산]을 켜고 다시 비교하면 원인을 나눠 볼 수 있습니다")
|
||
: "모든 날짜가 일치합니다.";
|
||
out.innerHTML = '<p class="perf-notice ' + (bad ? "is-warn" : "is-ok") + '" style="margin-top:8px">' + esc(summary) +
|
||
(r.live_error ? "<br>API 계산 실패: " + esc(r.live_error) : "") + "</p>" +
|
||
(stale ? '<div class="perf-sample-form"><button type="button" class="erp-btn erp-btn-primary" id="perf-daily-resync" data-from="' + from +
|
||
'" data-to="' + to + '">' + esc(from + " ~ " + to) + " 카페24 다시 가져오기</button></div>" : "") +
|
||
'<table class="perf-table" style="margin-top:8px"><thead>' + head + "</thead><tbody>" + body + "</tbody><tfoot>" + foot + "</tfoot></table>" +
|
||
'<p class="perf-foot perf-muted">차이 = 우리 값 − 카페24 값. 저장값은 카페24 수집분 전체(카페24 화면과 같은 범위)입니다.</p>';
|
||
} catch (err) {
|
||
out.innerHTML = '<p class="perf-notice is-warn">' + esc(err.message) + "</p>";
|
||
} finally { dailyBtn.disabled = false; }
|
||
});
|
||
const dailyOut = document.getElementById("perf-daily-result");
|
||
if (dailyOut) dailyOut.addEventListener("click", async function (e) {
|
||
const dayBtn = e.target.closest("[data-recon-day]");
|
||
if (dayBtn && recon) {
|
||
document.getElementById("perf-recon-date").value = dayBtn.dataset.reconDay;
|
||
recon.click();
|
||
recon.scrollIntoView({ behavior: "smooth", block: "center" });
|
||
return;
|
||
}
|
||
const rs = e.target.closest("#perf-daily-resync");
|
||
if (!rs) return;
|
||
if (!(await confirmMsg(rs.dataset.from + " ~ " + rs.dataset.to + " 카페24 매출을 지금 규칙으로 다시 가져옵니다."))) return;
|
||
rs.disabled = true;
|
||
rs.textContent = "가져오는 중…";
|
||
try {
|
||
const res = await api("POST", "/performance/api/sync", { from: rs.dataset.from, to: rs.dataset.to, codes: ["cafe24"] });
|
||
const r0 = (res.results || [])[0];
|
||
if (r0 && !r0.ok) throw new Error((r0.label || r0.status) + ": " + (r0.message || ""));
|
||
dailyBtn.click();
|
||
} catch (err) {
|
||
alertMsg("다시 가져오기 실패: " + err.message);
|
||
rs.disabled = false;
|
||
}
|
||
});
|
||
|
||
// ── 쇼핑몰 원본 데이터 확인(네이버·11번가·GS샵·토스쇼핑·쿠팡) — 조회 주소별 동작 여부·항목 합계, 네이버는 날짜별 현재 규칙 매출 ──
|
||
const probe = document.getElementById("perf-probe");
|
||
if (probe) probe.addEventListener("click", async function () {
|
||
const day = document.getElementById("perf-probe-date").value;
|
||
const out = document.getElementById("perf-probe-result");
|
||
if (!day) return;
|
||
probe.disabled = true;
|
||
const codeSel = document.getElementById("perf-probe-code");
|
||
const code = codeSel ? codeSel.value : "elevenst";
|
||
const loading = { naver: "네이버에서 불러오는 중… (하루씩, 기간이 길면 수십 초)",
|
||
gsshop: "GS샵에서 불러오는 중… (10일 단위)", toss: "토스쇼핑에서 불러오는 중… (31일 단위)",
|
||
coupang: "쿠팡에서 불러오는 중… (판매자배송 상태 6개 + 로켓그로스, 수십 초)" }[code] || "11번가에서 불러오는 중… (주소 10개 × 7일 단위, 기간이 길면 1분 이상)";
|
||
out.innerHTML = '<p class="perf-muted">' + loading + "</p>";
|
||
try {
|
||
const to = document.getElementById("perf-probe-to").value || day;
|
||
const r = await api("GET", "/performance/api/marketplaces/" + code + "/reconcile?date=" + encodeURIComponent(day) +
|
||
"&to=" + encodeURIComponent(to));
|
||
if (!r.ok) { out.innerHTML = '<p class="perf-notice is-warn">' + esc((r.label ? r.label + " — " : "") + r.message) + "</p>"; return; }
|
||
// 원본 확인은 최대 31일 — 더 긴 기간을 넣으면 서버가 앞 31일만 본다. 실제 조회 기간을 꼭 보여 준다.
|
||
const shown = r.date ? (r.date === r.to ? r.date : r.date + " ~ " + r.to) : "";
|
||
const cut = r.to && r.to < to;
|
||
const range = shown ? '<p class="perf-notice' + (cut ? " is-warn" : "") + '" style="margin-top:8px">조회 기간 <b>' + esc(shown) + "</b>" +
|
||
(cut ? " — 원본 데이터 확인은 한 번에 31일까지라 " + esc(r.to) + " 뒤(~" + esc(to) + ")는 조회하지 않았습니다. " +
|
||
"1년치 매출은 위 [과거 매출 가져오기]로 받으세요(31일씩 나눠 불러 저장)." : "") + "</p>" : "";
|
||
const summary = range + '<table class="perf-table" style="margin-top:8px"><thead><tr><th class="perf-th-label">조회</th>' +
|
||
'<th class="perf-th-label">주소</th><th class="perf-th-label">결과</th><th>건수</th></tr></thead><tbody>' +
|
||
r.probes.map(function (p) {
|
||
return '<tr><td class="perf-td-label">' + esc(p.label) + '</td><td class="perf-muted">' + esc(p.path) + "</td><td>" +
|
||
(p.ok ? '<span class="perf-pill is-ok">동작</span>' : '<span class="perf-pill is-bad">실패</span> <span class="perf-muted" style="white-space:normal">' + esc(p.error) + "</span>") +
|
||
'</td><td class="perf-num">' + (p.ok ? fmt(p.count) : "") + "</td></tr>";
|
||
}).join("") + "</tbody></table>";
|
||
const details = r.probes.filter(function (p) { return p.ok && p.count; }).map(function (p) {
|
||
return '<h4 class="perf-h" style="margin:14px 0 6px">' + esc(p.label) + " — " + fmt(p.count) + "줄</h4>" +
|
||
'<table class="perf-table"><thead><tr><th class="perf-th-label">항목</th><th>채워진 줄</th><th>숫자 합계</th>' +
|
||
'<th class="perf-th-label">예시 값</th></tr></thead><tbody>' +
|
||
p.fields.map(function (f) {
|
||
return '<tr><td class="perf-td-label">' + esc(f.name) + '</td><td class="perf-num">' + fmt(f.filled) + '</td><td class="perf-num">' +
|
||
(f.sum == null ? "" : fmt(f.sum)) + "</td><td>" + (f.personal ? '<span class="perf-muted">개인정보(숨김)</span>' : esc(f.sample)) + "</td></tr>";
|
||
}).join("") + "</tbody></table>";
|
||
}).join("");
|
||
// 날짜별 현재 규칙 매출(네이버·토스쇼핑) — 쇼핑몰 관리자 화면 매출과 나란히 비교
|
||
const days = (r.days || []).length ? '<h4 class="perf-h" style="margin:14px 0 6px">날짜별 현재 규칙 매출</h4>' +
|
||
(r.rule ? '<p class="perf-muted">규칙: ' + esc(r.rule) + "</p>" : "") +
|
||
'<table class="perf-table"><thead><tr><th class="perf-th-label">날짜</th><th>주문 수</th><th>' +
|
||
esc((r.day_cols || {}).amount || "매출") + "</th>" +
|
||
"<th>" + esc((r.day_cols || {}).claimed || "그중 결제 뒤 취소·반품(참고)") + "</th><th>" +
|
||
esc((r.day_cols || {}).ship || "배송비(참고, 매출 제외)") + "</th></tr></thead><tbody>" +
|
||
r.days.map(function (d) {
|
||
return '<tr><td class="perf-td-label">' + esc(d.date) + '</td><td class="perf-num">' + fmt(d.orders) +
|
||
'</td><td class="perf-num">' + fmt(d.amount) + '</td><td class="perf-num">' + fmt(d.claimed || 0) +
|
||
'</td><td class="perf-num">' + fmt(d.ship || 0) + "</td></tr>";
|
||
}).join("") + '<tr><td class="perf-td-label"><b>합계</b></td>' +
|
||
["orders", "amount", "claimed", "ship"].map(function (k) {
|
||
return '<td class="perf-num"><b>' + fmt(r.days.reduce(function (a, d) { return a + (d[k] || 0); }, 0)) + "</b></td>";
|
||
}).join("") + "</tr></tbody></table>" : "";
|
||
// 환불 출처별(토스쇼핑) — 출처별 날짜 합계를 나란히, 아래에 건별 목록(주문번호·금액·메모)
|
||
const rc = r.refund_candidates || [];
|
||
const candDays = (r.days || []).map(function (d) { return d.date; });
|
||
const cands = rc.length ? '<h4 class="perf-h" style="margin:14px 0 6px">' + esc(r.candidates_title || "환불 출처별 비교 — 첫 열(적용 규칙)이 저장되는 환불") + "</h4>" +
|
||
'<table class="perf-table"><thead><tr><th class="perf-th-label">날짜</th>' +
|
||
rc.map(function (c) { return "<th>" + esc(c.label) + "</th>"; }).join("") + "</tr></thead><tbody>" +
|
||
candDays.map(function (dt) {
|
||
return '<tr><td class="perf-td-label">' + esc(dt) + "</td>" + rc.map(function (c) {
|
||
return '<td class="perf-num">' + (c.error ? "" : fmt((c.days || {})[dt] || 0)) + "</td>";
|
||
}).join("") + "</tr>";
|
||
}).join("") + '<tr><td class="perf-td-label"><b>합계</b></td>' + rc.map(function (c) {
|
||
if (c.error) return '<td><span class="perf-pill is-bad">실패</span> <span class="perf-muted" style="white-space:normal">' + esc(c.error) + "</span></td>";
|
||
const t = Object.keys(c.days || {}).reduce(function (a, k) { return a + c.days[k]; }, 0);
|
||
return '<td class="perf-num"><b>' + fmt(t) + "</b></td>";
|
||
}).join("") + "</tr></tbody></table>" +
|
||
rc.filter(function (c) { return !c.error && (c.rows || []).length; }).map(function (c) {
|
||
return '<p class="perf-muted" style="margin:10px 0 4px">' + esc(c.label) + " — " + fmt(c.rows.length) + "건</p>" +
|
||
'<table class="perf-table"><thead><tr><th class="perf-th-label">환불일</th><th class="perf-th-label">주문일</th>' +
|
||
'<th class="perf-th-label">주문번호</th>' +
|
||
'<th class="perf-th-label">주문상품</th><th>금액</th><th class="perf-th-label">메모</th></tr></thead><tbody>' +
|
||
c.rows.map(function (x) {
|
||
return '<tr><td class="perf-td-label">' + esc(x.date) + "</td><td>" + esc(x.orderDate || "") + "</td><td>" +
|
||
esc(x.orderId) + "</td><td>" + esc(x.orderProductId) +
|
||
'</td><td class="perf-num">' + fmt(x.amount) + '</td><td class="perf-muted">' + esc(x.note) + "</td></tr>";
|
||
}).join("") + "</tbody></table>";
|
||
}).join("") : "";
|
||
out.innerHTML = summary + days + cands + (details ||'<p class="perf-muted" style="margin-top:8px">그 기간에 조회된 주문이 없습니다. 쇼핑몰 관리자 화면에서 매출이 있던 날로 다시 해 보세요.</p>');
|
||
} catch (err) {
|
||
out.innerHTML = '<p class="perf-notice is-warn">' + esc(err.message) + "</p>";
|
||
} finally { probe.disabled = false; }
|
||
});
|
||
|
||
// ── 과거 매출 가져오기(기간 지정 수집, 관리자) ──
|
||
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 job = await runSyncWithProgress({ from: from, to: to }, "과거 매출 가져오기 " + from + " ~ " + to);
|
||
const res = { results: jobResults(job).filter(function (r) { return r.finished; }) };
|
||
const ok = [], bad = [], rest = [];
|
||
if (job && !job.finished) rest.push("(아직 진행 중 — 창을 닫았습니다. 끝나면 대시보드에 반영됩니다)");
|
||
(res.results || []).forEach(function (r) {
|
||
const name = names[r.code] || r.name || r.code;
|
||
if (r.cancelled) rest.push(name + (r.stopped ? "(중지됨)" : "(취소됨)"));
|
||
else 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 ? "<b>반영</b> " + esc(ok.join(", ")) : "",
|
||
bad.length ? "<b>실패</b> " + esc(bad.join(", ")) : "",
|
||
rest.length ? '<span class="perf-muted">건너뜀(미연동·미설정): ' + esc(rest.join(", ")) + "</span>" : "",
|
||
].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);
|
||
});
|
||
})();
|