feat(project,performance): 보드 카드 끌기 실시간 미리보기 · 회의록 항목 끌어 옮기기·검정 테두리 · 실적 매출 단위·광고비(ROAS%) 줄

[프로젝트]
- 보드 카드 끌기: 기울어진 끄는 모양 + 점선 자리 표시가 카드 사이로 FLIP 애니메이션, 놓은 자리 그대로(다른 섹션도 순서 저장)
- 컬럼 dragenter 도 허용 — 자리 표시가 들어온 직후 놓을 때 drop 이 거부되던 문제
- 끄는 동안 실시간 동기화가 보드를 다시 그리지 않음
- 주간 회의록 항목 칸을 끌어 위아래로 이동(묶인 줄·세로 병합째, 같은 구역) — POST meeting-items/{id}/move-to
- 주간 회의록 표 테두리 모두 검정
- 도움말·모듈 문서 갱신

[실적]
- 설정의 쇼핑몰 원본 데이터 확인·카페24 매출 대조·일별 한 번에 비교 카드 삭제(서버 API 는 유지)
- 보기 설정: 매출 단위 원·천원·백만원(이 브라우저 쿠키 perf_unit)
- 매출 실적 표 매출 칸 아래 광고비(ROAS%) 줄(광고비 색), 카페24 는 구글·메타 두 줄

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-19 10:44:24 +09:00
parent ee728ed006
commit 62c345bbb5
26 changed files with 767 additions and 556 deletions
+23 -441
View File
@@ -24,6 +24,13 @@
}
function fmt(n) { return Number(n || 0).toLocaleString("ko-KR"); }
function won(n) { return n ? fmt(n) : '<span class="perf-zero">–</span>'; }
// 매출 단위(실적 설정 "보기 설정", 쿠키 perf_unit) — 서버 dashboard.amount_text 와 같은 표기(천원 정수, 백만원 소수 한 자리)
function unitWon(n, unit) {
if (!n) return won(0);
if (unit === "thousand") return Math.round(n / 1000).toLocaleString("ko-KR");
if (unit === "million") return (Math.round(n / 100000) / 10).toLocaleString("ko-KR", { minimumFractionDigits: 1, maximumFractionDigits: 1 });
return fmt(n);
}
// 축 눈금용 짧은 금액(1.2억 / 350만)
function short(n) {
const a = Math.abs(n), s = n < 0 ? "-" : "";
@@ -582,7 +589,7 @@
td.title = manual !== "" ? "직접 입력값 — 눌러 고치기(비우고 저장하면 " + (FIXED_METRIC ? "지움" : "API 값") + ")"
: "눌러 " + MANUAL_WORD + " 직접 입력";
const g = td.querySelector(".v-gross");
if (g) g.innerHTML = won(res.amount);
if (g) g.innerHTML = unitWon(res.amount, data.unit);
td.classList.add("is-stale"); // 수수료·차감 매출은 새로고침 때 다시 계산
manualDirty = true;
return true;
@@ -745,6 +752,21 @@
// 설정
// ════════════════════════════════════════════════════
function initSettings(root) {
// 보기 설정 — 매출 단위(원·천원·백만원)를 이 브라우저 쿠키에(1년). 매출 실적 화면을 다시 열면 적용
const UNIT_EX = { won: "2,475,300", thousand: "2,475", million: "2.5" };
root.querySelectorAll("#perf-view-opts [data-unit]").forEach(function (b) {
b.addEventListener("click", function () {
const u = b.dataset.unit;
document.cookie = "perf_unit=" + u + "; path=/performance; max-age=31536000; SameSite=Lax";
root.querySelectorAll("#perf-view-opts [data-unit]").forEach(function (x) {
x.classList.toggle("is-active", x === b);
x.setAttribute("aria-checked", x === b ? "true" : "false");
});
const ex = document.getElementById("perf-unit-example");
if (ex) ex.textContent = "예: 2,475,300원 → " + UNIT_EX[u];
});
});
// 사용 / 매출 집계 토글 — 바로 저장, 실패하면 되돌림
root.querySelectorAll(".perf-switch input").forEach(function (box) {
box.addEventListener("change", async function () {
@@ -950,446 +972,6 @@
} 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 () {