feat(performance): per-shop manual sales input, column order, bold centered table headers (migration 002)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-12 17:26:57 +09:00
parent dd1bc310dc
commit 454b3cc700
16 changed files with 690 additions and 34 deletions
+145
View File
@@ -0,0 +1,145 @@
// 실적 — 수동 입력(static/performance.js) · 열 순서 · 설정 토글 — jsdom.
// python tests/js/render_performance.py && NODE_PATH=<jsdom 경로> node tests/js/perf_manual.test.js
const fs = require("fs"), path = require("path");
const { JSDOM } = require("jsdom");
const OUT = path.join(__dirname, ".out");
const JS = fs.readFileSync(path.join(__dirname, "..", "..", "app", "static", "performance.js"), "utf8");
const fails = [];
function check(name, cond, extra) {
if (cond) console.log("PASS " + name);
else { console.log("FAIL " + name + (extra !== undefined ? " → " + JSON.stringify(extra) : "")); fails.push(name); }
}
const settle = function () { return new Promise(function (r) { let i = 0; (function s() { if (i++ > 40) return r(); setImmediate(s); })(); }); };
const wait = function (ms) { return new Promise(function (r) { setTimeout(r, ms); }); };
async function env(file) {
const html = fs.readFileSync(path.join(OUT, file), "utf8").replace(/<script src="\/static\/performance\.js[^"]*" defer><\/script>/, "");
const dom = new JSDOM(html, { runScripts: "dangerously", pretendToBeVisual: true, url: "http://localhost/performance/" });
const w = dom.window;
const e = { w: w, d: w.document, calls: [], status: 200, alerts: [] };
w.erpAlert = function (m) { e.alerts.push(m); return Promise.resolve(); };
w.fetch = async function (url, o) {
const method = (o && o.method) || "GET";
const body = o && o.body ? JSON.parse(o.body) : null;
e.calls.push({ method: method, url: url, body: body });
if (e.status >= 400) return { ok: false, status: e.status, json: async function () { return { detail: "수동 입력을 쓰려면 마이그레이션 002" }; } };
const m = /^\/performance\/api\/manual-sales\/([^/]+)\/([\d-]+)$/.exec(url);
if (m) {
const api = m[1] === "coupang" && m[2] === "2026-10-05" ? 50000 : m[1] === "coupang" && m[2] === "2026-10-06" ? 7000 : 0;
const manual = body.amount == null ? null : body.amount;
return { ok: true, status: 200, json: async function () { return { ok: true, manual: manual, amount: manual == null ? api : manual, api_amount: api }; } };
}
return { ok: true, status: 200, json: async function () { return {}; } };
};
w.eval(JS);
// jsdom 이 문서를 다 읽은 뒤 DOMContentLoaded 를 스스로 보낸다(직접 보내면 초기화가 두 번 됨)
if (w.document.readyState !== "loading") w.document.dispatchEvent(new w.Event("DOMContentLoaded"));
await settle();
return e;
}
function key(e, el, k, extra) { el.dispatchEvent(new e.w.KeyboardEvent("keydown", Object.assign({ key: k, bubbles: true, cancelable: true }, extra || {}))); }
function cell(e, code, day) { return e.d.querySelector('td.is-manual-cell[data-manual-code="' + code + '"][data-date="' + day + '"]'); }
function gross(td) { return td.querySelector(".v-gross").textContent.trim(); }
(async function () {
// ── 열 순서·제목 ──
{
const e = await env("perf_dash.html");
const heads = Array.from(e.d.querySelectorAll(".perf-main thead th")).map(function (th) { return th.textContent.replace("✎", "").trim(); });
check("[순서] 카페24·네이버·쿠팡·토스·GS샵·11번가 다음 나머지", heads.join(",") ===
"날짜,카페24,네이버,쿠팡,토스,GS샵,11번가,오늘의집,G마켓,카카오,롯데ON,일 합계", heads);
check("[수동] 수동 입력 쇼핑몰 제목에 ✎ 표시", /✎/.test(e.d.querySelectorAll(".perf-main thead th")[3].textContent) &&
!/✎/.test(e.d.querySelectorAll(".perf-main thead th")[1].textContent));
check("[수동] 오늘까지 날짜 칸만 입력 칸(앞으로의 날·주간합계 아님), 수동 값 칸은 파란 표시",
!!cell(e, "coupang", "2026-10-07") && !cell(e, "coupang", "2026-10-08") && cell(e, "coupang", "2026-10-05").classList.contains("is-manual") &&
!cell(e, "coupang", "2026-10-06").classList.contains("is-manual") && !e.d.querySelector(".perf-row-week td.is-manual-cell"));
check("[수동] 입력 칸은 주문 상세 링크가 아님", !cell(e, "coupang", "2026-10-06").classList.contains("is-link") &&
e.d.querySelector('td.is-link[data-code="cafe24"]') !== null);
check("[수동] 표 아래 사용법 안내", /직접 입력/.test((e.d.querySelector(".perf-manual-help") || {}).textContent || ""));
}
// ── 입력 → Enter 저장 후 아래 칸 → Esc 끝 ──
{
const e = await env("perf_dash.html");
let reloaded = 0;
const td5 = cell(e, "coupang", "2026-10-05");
td5.click();
const in5 = td5.querySelector(".perf-manual-input");
check("[입력] 칸을 누르면 입력칸(수동 값이 들어 있음)", !!in5 && in5.value === "87000" && e.d.activeElement === in5);
in5.value = "90,000원";
key(e, in5, "Enter");
await settle();
const put = e.calls.find(function (c) { return c.method === "PUT"; });
check("[입력] Enter → 그 칸 저장(쉼표·원 빼고 숫자)", put && put.url === "/performance/api/manual-sales/coupang/2026-10-05" && put.body.amount === 90000, e.calls);
check("[입력] 저장한 값 표시 + 아래 칸(10/6)으로 입력칸 이동", gross(td5) === "90,000" && !td5.querySelector(".perf-manual-input") &&
!!cell(e, "coupang", "2026-10-06").querySelector(".perf-manual-input"));
const in6 = cell(e, "coupang", "2026-10-06").querySelector(".perf-manual-input");
check("[입력] 수동 값 없는 칸은 비어 있고 API 값이 흐리게(placeholder)", in6.value === "" && in6.placeholder === "7,000", in6.placeholder);
key(e, in6, "Enter"); // 아무것도 안 넣고 Enter — 저장 안 함
await settle();
check("[입력] 빈 칸 그대로 Enter → 저장 요청 없음", e.calls.filter(function (c) { return c.method === "PUT"; }).length === 1);
const in7 = cell(e, "coupang", "2026-10-07").querySelector(".perf-manual-input");
check("[입력] 마지막 입력 칸(오늘)까지 이동", !!in7);
in7.value = "abc";
key(e, in7, "Enter");
await settle(); await wait(200); await settle();
check("[입력] 숫자가 아니면 저장 안 하고 안내", e.alerts.some(function (m) { return /숫자/.test(m); }) &&
e.calls.filter(function (c) { return c.method === "PUT"; }).length === 1, e.alerts);
}
// ── 수동 값 지우기(비우고 저장) → API 값, 실패 시 안내 ──
{
const e = await env("perf_dash.html");
const td5 = cell(e, "coupang", "2026-10-05");
td5.click();
const inp = td5.querySelector(".perf-manual-input");
inp.value = "";
key(e, inp, "Escape");
check("[지우기] Esc → 저장 없이 닫힘", !td5.querySelector(".perf-manual-input") && !e.calls.some(function (c) { return c.method === "PUT"; }));
td5.click();
const inp2 = td5.querySelector(".perf-manual-input");
inp2.value = "";
inp2.dispatchEvent(new e.w.FocusEvent("blur"));
await settle();
const put = e.calls.find(function (c) { return c.method === "PUT"; });
check("[지우기] 비우고 칸을 떠나면 amount=null(그날 API 값)", put && put.body.amount === null);
check("[지우기] API 값(50,000) 표시·파란 표시 해제", gross(td5) === "50,000" && !td5.classList.contains("is-manual"));
e.status = 503;
const td6 = cell(e, "coupang", "2026-10-06");
td6.click();
const i6 = td6.querySelector(".perf-manual-input");
i6.value = "100";
i6.dispatchEvent(new e.w.FocusEvent("blur"));
await settle();
check("[실패] 저장 실패 → 안내(마이그레이션), 값은 그대로", e.alerts.some(function (m) { return /마이그레이션 002/.test(m); }) && gross(td6) === "7,000", e.alerts);
}
// ── 키보드: 칸에서 Enter 로 입력 시작 ──
{
const e = await env("perf_dash.html");
const td = cell(e, "kakao", "2026-10-06");
td.focus();
key(e, td, "Enter");
check("[키보드] 칸에 포커스 후 Enter → 입력칸", !!td.querySelector(".perf-manual-input"));
}
// ── 설정: 수동 입력 토글 ──
{
const e = await env("perf_settings.html");
const heads = Array.from(e.d.querySelectorAll(".perf-set-table thead th")).map(function (th) { return th.textContent.trim(); });
check("[설정] '수동 입력' 열(매출 집계 다음)", heads.indexOf("수동 입력") === heads.indexOf("매출 집계") + 1, heads);
const rows = Array.from(e.d.querySelectorAll(".perf-set-table tbody tr")).map(function (tr) { return tr.dataset.code; });
check("[설정] 쇼핑몰 순서 = 표 순서", rows.join(",") === "cafe24,naver,coupang,toss,gsshop,elevenst,ohouse,gmarket,kakao,lotteon", rows);
const box = e.d.querySelector('tr[data-code="coupang"] input[data-field="manual_input"]');
check("[설정] 켜진 쇼핑몰은 체크", box && box.checked && !e.d.querySelector('tr[data-code="cafe24"] input[data-field="manual_input"]').checked);
box.checked = false;
box.dispatchEvent(new e.w.Event("change", { bubbles: true }));
await settle();
const put = e.calls.find(function (c) { return c.method === "PUT"; });
check("[설정] 토글 → 바로 저장(manual_input)", put && put.url === "/performance/api/marketplaces/coupang" && put.body.manual_input === false, e.calls);
e.status = 503;
const box2 = e.d.querySelector('tr[data-code="naver"] input[data-field="manual_input"]');
box2.checked = true;
box2.dispatchEvent(new e.w.Event("change", { bubbles: true }));
await settle();
check("[설정] 저장 실패(002 미적용) → 되돌리고 안내", !box2.checked && e.alerts.some(function (m) { return /마이그레이션/.test(m); }), e.alerts);
}
console.log(fails.length ? "\n" + fails.length + " FAILED" : "\nALL PASS");
process.exit(fails.length ? 1 : 0);
})();
+84
View File
@@ -0,0 +1,84 @@
"""실적 대시보드(index.html)·설정(settings.html)을 테스트용 HTML 로 렌더한다(erp_base.html 은 최소 스텁, 가상의 데이터).
python tests/js/render_performance.py # → tests/js/.out/perf_dash.html · perf_settings.html
화면 데이터는 실제 build_dashboard·build_settings 로 만든다(저장소만 가짜). DB·쇼핑몰 API 는 쓰지 않는다.
쿠팡은 수동 입력 켬(10/5 수동 값 87,000, 10/6 은 API 값만), 카카오도 켬(값 없음), 나머지는 끔.
"""
from __future__ import annotations
import os
import sys
from datetime import date
from decimal import Decimal
import jinja2
ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
sys.path.insert(0, ROOT)
OUT_DIR = os.path.join(ROOT, "tests", "js", ".out")
from app.modules.performance.dashboard import build_dashboard, build_settings # noqa: E402
BASE_STUB = ("{% block head_extra %}{% endblock %}<body><main class='erp-page'>{% block content %}{% endblock %}</main>"
"{% block scripts %}{% endblock %}</body>")
ORDER = ["cafe24", "naver", "coupang", "toss", "gsshop", "elevenst", "ohouse", "gmarket", "kakao", "lotteon"]
NAMES = {"cafe24": "카페24", "naver": "네이버 스마트스토어", "coupang": "쿠팡", "toss": "토스쇼핑", "gsshop": "GS샵",
"elevenst": "11번가", "ohouse": "오늘의집", "gmarket": "G마켓", "kakao": "카카오", "lotteon": "롯데ON"}
class FakeStore:
def list_marketplaces(self):
return [{"code": c, "name": NAMES[c], "enabled": True, "include_in_sales": True, "sort_order": i * 10,
"manual_input": c in ("coupang", "kakao")} for i, c in enumerate(ORDER, 1)]
def daily_amounts(self, start, end, codes):
api = {(date(2026, 10, 5), "coupang"): 50000, (date(2026, 10, 6), "coupang"): 7000,
(date(2026, 10, 5), "cafe24"): 100000}
out = {k: v for k, v in api.items() if start <= k[0] <= end and k[1] in codes}
out.update(self.manual_amounts(start, end, codes))
return out
def manual_amounts(self, start, end, codes, *, active_only=True):
manual = {(date(2026, 10, 5), "coupang"): 87000}
return {k: v for k, v in manual.items() if start <= k[0] <= end and k[1] in codes}
def rate_table(self):
return {"coupang": [(date(2026, 1, 1), Decimal("12"))]}
def statuses(self):
return {}
def last_update_at(self):
return None
def running_codes(self):
return []
def env() -> jinja2.Environment:
e = jinja2.Environment(loader=jinja2.ChoiceLoader([
jinja2.DictLoader({"erp_base.html": BASE_STUB}),
jinja2.FileSystemLoader(os.path.join(ROOT, "app", "modules", "performance", "templates")),
]), autoescape=True)
return e
def main() -> None:
os.makedirs(OUT_DIR, exist_ok=True)
e = env()
base = {"user": {"email": "me@test.local"}, "is_admin": True, "nav_items": [], "page_title": "실적", "page_subtitle": ""}
ctx = build_dashboard(FakeStore(), kind="week", anchor=date(2026, 10, 7), today=date(2026, 10, 7))
html = e.get_template("performance/index.html").render(**base, active_tab="dashboard", metric="gross", **ctx)
with open(os.path.join(OUT_DIR, "perf_dash.html"), "w", encoding="utf-8") as f:
f.write(html)
sctx = build_settings(FakeStore(), configured={}, key_info={}, key_versions_in_use={}, sample_count=0)
html = e.get_template("performance/settings.html").render(**base, active_tab="settings", **sctx)
with open(os.path.join(OUT_DIR, "perf_settings.html"), "w", encoding="utf-8") as f:
f.write(html)
print("ok")
if __name__ == "__main__":
main()