feat(performance): 실적(쇼핑몰 통합 매출) 모듈 1단계 — 대시보드·설정·보안·어댑터 구조

- 네 영역 분리: ① 수집(adapters/ 쇼핑몰 10곳 + sync.py) ② 보안(security/ + credentials.py)
  ③ 계산·저장(calc.py + db.py) ④ 화면(dashboard.py, router.py, templates, performance.css/js)
- 대시보드: 기간(오늘/이번주/이번달/올해/직접선택, 이전·다음), 쇼핑몰 필터, KPI 5개(진행 중 기간은
  직전 기간 같은 경과일 대비), 일자×쇼핑몰 표(주간합계, 총매출/수수료/차감매출 전환), 일별 추이·
  쇼핑몰 비중(SVG), 월 누적(비중)·연간 누적, 금액 클릭 → 주문 상세
- 설정(관리자): 사용/매출 집계, 수수료율 이력(적용 시작일), 쇼핑몰별 API 인증정보 입력·연결 테스트·
  연결 상태, 마스터 키 상태·재암호화, 테스트(모의) 데이터 생성/삭제
- 인증정보: 설정 화면 입력 → AES-256-GCM(키 버전, AAD=쇼핑몰+항목) 암호화 저장, secret 원문은
  화면으로 다시 보내지 않음, 오류·로그·raw 는 비밀값 가린 뒤 저장. 마스터 키는 APP_ENCRYPTION_KEY(.env)
- 매출 기준일: 결제=결제일, 취소·반품=발생일. 금액 원 단위 정수, 수수료 반올림은 calc.commission 한 곳
- 동기화: 같은 쇼핑몰 동시 실행 차단(running 부분 유니크), 쇼핑몰별 실패 격리, 중복 방지 UNIQUE+UPSERT
- 카페24 어댑터는 기존 app/integrations/cafe24 OAuth 토큰 재사용, 나머지는 입력칸만(수집은 다음 단계)
- performance_db 초기화 스크립트, 권한키 performance(설정은 is_admin), 문서·.env.example

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-09-29 16:07:46 +09:00
parent b95206dcf4
commit aa669553db
41 changed files with 4326 additions and 1 deletions
+209
View File
@@ -0,0 +1,209 @@
/* ════════════════════════════════════════════════════
실적(쇼핑몰 통합 매출) — 정보 밀도 높은 관리자 대시보드.
기존 ERP 토큰(erp.css :root) 위에서만 쓴다. 색은 증감·상태·주말에만.
════════════════════════════════════════════════════ */
.perf {
--perf-line: var(--color-subtle-ash);
--perf-soft: #fafafa;
--perf-up: #0f8a3a;
--perf-down: var(--color-callout-red);
--perf-sat: #1d4ed8;
--perf-sun: var(--color-callout-red);
display: flex; flex-direction: column; gap: 12px;
font-variant-numeric: tabular-nums;
}
/* 공통 .erp-page 는 width:100% + padding 이라 부모보다 48px 넓어져 오른쪽이 잘린다.
전역 규칙은 다른 모듈에 영향이 있어, 실적 화면이 들어 있을 때만 border-box 로 맞춘다. */
.erp-page:has(> .perf) { box-sizing: border-box; }
.perf, .perf > * { min-width: 0; }
.perf-muted { color: var(--color-midtone-gray); font-size: 12px; }
.perf-nowrap { white-space: nowrap; }
.perf-center { text-align: center; }
/* 탭 */
.perf-tabs { display: flex; gap: 4px; border-bottom: 1px solid var(--perf-line); }
.perf-tab {
padding: 8px 14px; font-size: 13px; font-weight: 500; color: var(--color-midtone-gray);
border-bottom: 2px solid transparent; margin-bottom: -1px;
}
.perf-tab:hover { color: var(--color-rich-black); }
.perf-tab.is-active { color: var(--color-rich-black); border-bottom-color: var(--color-rich-black); }
/* 도구 막대 */
.perf-toolbar { display: flex; flex-wrap: wrap; align-items: center; gap: 8px 12px; }
.perf-quick, .perf-metric { display: inline-flex; border: 1px solid var(--perf-line); border-radius: 10px; padding: 2px; background: #fff; }
.perf-seg {
border: 0; background: transparent; font: inherit; font-size: 12px; font-weight: 500;
padding: 5px 11px; border-radius: 8px; cursor: pointer; color: var(--color-rich-black); white-space: nowrap;
}
.perf-seg:hover { background: var(--color-ghost-gray); }
.perf-seg.is-active { background: var(--color-deep-black); color: #fff; }
a.perf-seg.is-active, a.perf-seg.is-active:link, a.perf-seg.is-active:visited { color: #fff; }
.perf-nav { display: inline-flex; align-items: center; gap: 6px; }
.perf-nav-btn {
font-size: 12px; padding: 5px 9px; border: 1px solid var(--perf-line); border-radius: 8px; background: #fff;
white-space: nowrap;
}
.perf-nav-btn:hover { background: var(--color-ghost-gray); }
.perf-nav-label { font-weight: 600; font-size: 14px; min-width: 200px; text-align: center; }
.perf-custom { display: inline-flex; align-items: center; gap: 6px; }
.perf-custom[hidden] { display: none; }
/* 공통 .erp-input 의 min-width:240px 를 날짜칸에서만 푼다 */
.perf .erp-input.perf-date { width: 150px; min-width: 0; flex: 0 0 auto; padding: 5px 8px !important; font-size: 12px !important; }
.perf-modal .erp-input.perf-date { width: 150px; min-width: 0; }
.perf-filter { position: relative; }
.perf-filter > summary { list-style: none; cursor: pointer; }
.perf-filter > summary::-webkit-details-marker { display: none; }
.perf-filter-pop {
position: absolute; z-index: 20; top: calc(100% + 6px); left: 0; min-width: 220px;
background: #fff; border: 1px solid var(--perf-line); border-radius: 12px; padding: 10px;
box-shadow: 0 8px 24px rgba(0, 0, 0, .1); display: flex; flex-direction: column; gap: 4px;
}
.perf-check { display: flex; align-items: center; gap: 6px; font-size: 13px; padding: 3px 2px; cursor: pointer; }
.perf-filter-act { display: flex; justify-content: space-between; margin-top: 6px; }
.perf-update { margin-left: auto; display: inline-flex; align-items: center; gap: 10px; }
.perf-update b { color: var(--color-rich-black); font-weight: 600; }
/* 알림 */
.perf-notice {
font-size: 12.5px; padding: 8px 12px; border-radius: 10px; background: var(--perf-soft);
border: 1px solid var(--perf-line); display: flex; flex-wrap: wrap; gap: 6px 10px; align-items: center;
}
.perf-notice[hidden] { display: none; }
.perf-notice.is-warn { background: #fff7f5; border-color: #f3d2ca; }
.perf-notice.is-ok { background: #f3fbf5; border-color: #cdeccf; }
.perf-problem { padding: 1px 8px; border-radius: 999px; background: #fbe9e6; color: var(--perf-down); font-weight: 500; }
/* KPI */
.perf-kpis { display: grid; grid-template-columns: repeat(5, minmax(0, 1fr)); gap: 10px; }
.perf-kpi { border: 1px solid var(--perf-line); border-radius: 12px; padding: 12px 14px; background: #fff; min-width: 0; }
.perf-kpi.is-primary { border-color: #cfcfcf; box-shadow: inset 3px 0 0 var(--color-deep-black); }
.perf-kpi-label { font-size: 12px; color: var(--color-midtone-gray); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.perf-kpi-value { font-size: 22px; font-weight: 600; letter-spacing: -.5px; margin: 2px 0; white-space: nowrap; }
.perf-kpi.is-primary .perf-kpi-value { font-size: 24px; }
.perf-kpi-delta { font-size: 12px; display: flex; gap: 6px; align-items: baseline; flex-wrap: wrap; }
.perf-delta { font-weight: 600; }
.perf-delta.is-up { color: var(--perf-up); }
.perf-delta.is-down { color: var(--perf-down); }
.perf-delta.is-flat { color: var(--color-midtone-gray); }
/* 카드 */
.perf-card { padding: 12px 14px; }
.perf-card-head { display: flex; align-items: center; justify-content: space-between; gap: 10px; margin-bottom: 8px; flex-wrap: wrap; }
.perf-h { margin: 0; font-size: 14px; font-weight: 600; }
.perf-grid2 { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 12px; }
.perf-foot { margin: 8px 0 0; line-height: 1.5; }
/* 표 */
.perf-table-wrap { overflow-x: auto; }
.perf-table { width: 100%; border-collapse: collapse; font-size: 12.5px; }
.perf-table th, .perf-table td { padding: 6px 8px; border-bottom: 1px solid #efefef; white-space: nowrap; }
.perf-table thead th {
font-size: 12px; font-weight: 500; color: var(--color-midtone-gray); text-align: right;
background: var(--perf-soft); border-bottom: 1px solid var(--perf-line); position: sticky; top: 0;
}
.perf-table thead th.perf-th-label { text-align: left; }
.perf-td-label { text-align: left; font-weight: 500; }
.perf-num { text-align: right; }
.perf-zero { color: #c9c9c9; }
.perf-na::before { content: ""; }
.perf-th-total, .perf-td-total { background: #f6f6f6; font-weight: 600; }
.perf-main .perf-td-label { min-width: 88px; }
.perf-row-day.is-sat .perf-td-label { color: var(--perf-sat); }
.perf-row-day.is-sun .perf-td-label { color: var(--perf-sun); }
.perf-row-day.is-today .perf-td-label::after { content: "오늘"; margin-left: 6px; font-size: 10px; padding: 0 5px; border-radius: 999px; background: var(--color-deep-black); color: #fff; vertical-align: 1px; }
.perf-row-day.is-future td, .perf-row-month.is-future td, .perf-year tr.is-future td { color: #c9c9c9; }
.perf-hol { display: block; font-size: 10.5px; font-weight: 400; }
.perf-row-week th, .perf-row-week td { background: #f3f3f3; font-weight: 600; border-bottom: 1px solid var(--perf-line); }
.perf-row-week .perf-td-total { background: #e9e9e9; }
.perf-row-total th, .perf-row-total td { background: var(--color-deep-black); color: #fff; font-weight: 600; border-bottom: 0; }
.perf-row-total .perf-zero { color: #777; }
td.is-link { cursor: pointer; }
td.is-link:hover { background: #eef2ff; text-decoration: underline; }
/* 표시 기준 전환 — 한 칸에 3값, data-metric 으로 하나만 보인다 */
.perf .v { display: none; }
.perf[data-metric="gross"] .v-gross,
.perf[data-metric="commission"] .v-commission,
.perf[data-metric="net"] .v-net { display: inline; }
/* 비중 막대 */
.perf-share { position: relative; min-width: 110px; }
.perf-bar { position: absolute; left: 8px; bottom: 3px; height: 3px; width: calc((100% - 16px) * var(--w) / 100); background: #d4d4d4; border-radius: 2px; }
/* 연간 요약 */
.perf-year-sum { display: grid; grid-template-columns: repeat(3, 1fr); gap: 8px; margin-bottom: 8px; }
.perf-year-sum div { background: var(--perf-soft); border: 1px solid #efefef; border-radius: 10px; padding: 8px 10px; }
.perf-year-sum span { display: block; font-size: 11.5px; color: var(--color-midtone-gray); }
.perf-year-sum b { font-size: 16px; font-weight: 600; }
/* 그래프(SVG, performance.js 가 그림) */
.perf-chart { min-height: 220px; }
.perf-chart svg { display: block; width: 100%; height: auto; }
.perf-chart text { font-size: 10.5px; fill: var(--color-midtone-gray); font-family: var(--font-geist); }
.perf-chart .bar { fill: #1f1f1f; }
.perf-chart .bar.is-neg { fill: var(--perf-down); }
.perf-chart .bar:hover { fill: #555; }
.perf-chart .grid { stroke: #efefef; }
.perf-chart .axis { stroke: #d4d4d4; }
.perf-chart-empty { color: var(--color-midtone-gray); font-size: 12px; padding: 80px 0; text-align: center; }
/* 상세(Drill-down) 창 */
.perf-modal { position: fixed; inset: 0; z-index: 1000; background: rgba(0, 0, 0, .35); display: flex; align-items: center; justify-content: center; padding: 20px; }
.perf-modal-card { background: #fff; border-radius: 14px; width: min(1100px, 100%); max-height: 88vh; display: flex; flex-direction: column; box-shadow: 0 20px 60px rgba(0, 0, 0, .25); }
.perf-modal-card.is-narrow { width: min(560px, 100%); }
.perf-modal-head { display: flex; align-items: center; justify-content: space-between; gap: 10px; padding: 14px 16px; border-bottom: 1px solid var(--perf-line); }
.perf-modal-head h3 { margin: 0; font-size: 15px; font-weight: 600; }
.perf-modal-body { padding: 12px 16px; overflow: auto; }
.perf-modal-foot { display: flex; justify-content: flex-end; gap: 8px; padding: 12px 16px; border-top: 1px solid var(--perf-line); flex-wrap: wrap; align-items: center; }
.perf-modal-x { border: 0; background: none; font-size: 20px; cursor: pointer; color: var(--color-midtone-gray); }
.perf-ev-cancel td { color: var(--perf-down); }
/* 설정 */
.perf-set-table td, .perf-set-table th { vertical-align: middle; }
.perf-set-table thead th { text-align: left; }
.perf-set-table thead th:nth-child(2), .perf-set-table thead th:nth-child(3) { text-align: center; }
.perf-set-table thead th:nth-child(4) { text-align: right; padding-right: 60px; }
.perf-rate-cell { white-space: nowrap; }
.perf-rate { display: inline-block; min-width: 56px; text-align: right; font-weight: 600; margin-right: 4px; }
.perf-pill { display: inline-block; font-size: 11.5px; padding: 1px 8px; border-radius: 999px; background: var(--color-ghost-gray); color: var(--color-midtone-gray); white-space: nowrap; }
.perf-pill.is-ok { background: #e6f8e9; color: #0f8a3a; }
.perf-pill.is-bad { background: #fbe9e6; color: var(--perf-down); }
.perf-status { display: inline-flex; align-items: center; gap: 6px; font-size: 12.5px; white-space: nowrap; }
.perf-status i { width: 8px; height: 8px; border-radius: 50%; background: #bdbdbd; display: inline-block; }
.perf-status.st-ok i { background: #10b33a; }
.perf-status.st-auth_failed i, .perf-status.st-token_expired i, .perf-status.st-api_error i { background: var(--perf-down); }
.perf-status.st-not_configured i { background: #e0a526; }
.perf-status.st-disabled { color: var(--color-midtone-gray); }
.perf-err { font-size: 11px; color: var(--perf-down); max-width: 260px; white-space: normal; line-height: 1.35; margin-top: 2px; }
.perf-switch { position: relative; display: inline-block; width: 34px; height: 20px; cursor: pointer; }
.perf-switch input { opacity: 0; width: 0; height: 0; position: absolute; }
.perf-switch span { position: absolute; inset: 0; background: #d4d4d4; border-radius: 999px; transition: background .15s; }
.perf-switch span::after { content: ""; position: absolute; left: 3px; top: 3px; width: 14px; height: 14px; background: #fff; border-radius: 50%; transition: transform .15s; }
.perf-switch input:checked + span { background: var(--color-deep-black); }
.perf-switch input:checked + span::after { transform: translateX(14px); }
.perf-switch input:focus-visible + span { outline: 2px solid #93c5fd; outline-offset: 2px; }
.perf-dl { display: grid; grid-template-columns: 90px 1fr; gap: 6px 10px; margin: 0; font-size: 13px; }
.perf-dl dt { color: var(--color-midtone-gray); }
.perf-dl dd { margin: 0; }
.perf-sample-form { display: flex; align-items: center; gap: 6px; flex-wrap: wrap; margin-top: 8px; }
.perf-form { display: flex; flex-direction: column; gap: 12px; }
.perf-form-row { display: flex; flex-direction: column; gap: 4px; }
.perf-form-row > label { font-size: 12px; font-weight: 500; }
.perf-form-row .erp-input { width: 100%; box-sizing: border-box; }
.perf-form-help { font-size: 11.5px; color: var(--color-midtone-gray); }
.perf-secret-state { font-size: 11.5px; color: #0f8a3a; }
.perf-secret-state.is-empty { color: var(--color-midtone-gray); }
.perf-inline { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
.perf-test-result { font-size: 12.5px; margin-right: auto; }
.perf-test-result.is-ok { color: #0f8a3a; }
.perf-test-result.is-bad { color: var(--perf-down); }
@media (max-width: 1280px) {
.perf-kpis { grid-template-columns: repeat(3, minmax(0, 1fr)); }
}
@media (max-width: 980px) {
.perf-grid2 { grid-template-columns: 1fr; }
.perf-kpis { grid-template-columns: repeat(2, minmax(0, 1fr)); }
.perf-update { margin-left: 0; }
}
+508
View File
@@ -0,0 +1,508 @@
/* 실적(쇼핑몰 통합 매출) — 대시보드 / 설정 화면 동작.
*
* 쇼핑몰 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 { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" }[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) { 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", {});
const ok = [], bad = [], pending = [], 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 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 (pending.length) parts.push('<span class="perf-muted">연동 준비 중: ' + esc(pending.join(", ")) + "</span>");
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 = '<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.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>" + 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="erp-table-wrap"><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>금액</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">기간 내 매출이 없습니다.</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">기간 내 매출이 없습니다.</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;
if (btn.dataset.act === "rate") openRate(code, name, btn.dataset.hasHistory === "1");
else if (btn.dataset.act === "creds") openCreds(code, name);
else if (btn.dataset.act === "test") runTest(code, name, btn);
});
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) {
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", "/performance/api/marketplaces/" + 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>';
}
return '<div class="perf-form-row"><label for="' + id + '">' + esc(f.label) + (f.required ? " *" : "") + "</label>" + state +
'<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 || "") + '"') + " />" +
(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", "/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 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);
});
})();