feat(실적): 틱톡 탭 삭제 + [말레이시아 실적] 모듈 추가

- 실적 틱톡 탭·tiktok_ads 광고 API·테스트 삭제, 틱톡 데이터 삭제 SQL(performance_db 012)
- 말레이시아 실적: 실적 라우터·화면을 /malaysia/performance 에 한 번 더 마운트,
  차이는 performance/variant.py(KR·MY) 한 곳 — 저장소·권한키·주소·광고 채널·통화
- 틱톡·쇼피·라자다 그룹(쇼핑몰 + 라이브커머스 하위, 그룹 열 = 합계), 광고비 채널 3개
- 금액 RM 소수 2자리 = 센 정수 저장(입력·엑셀 scale, 화면 num/money, JS money)
- malaysia_performance_db = performance_db 구조 복사 + seed

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-20 16:03:18 +09:00
parent e9f57b6ff6
commit 62cc5e2778
34 changed files with 790 additions and 892 deletions
+79
View File
@@ -0,0 +1,79 @@
// 말레이시아 실적(2026-11-20) — 실제 브라우저. 같은 performance.js 가 data-base(/malaysia/performance)로 저장하고
// 금액을 RM 소수 2자리로 보이는지(저장 단위 = 센).
// python tests/js/render_performance.py
// NODE_PATH=<playwright 경로> PJ_TEST_BROWSER=<Chrome 경로> node tests/js/perf_malaysia.browser.test.js
const fs = require("fs"), path = require("path");
const { chromium } = require("playwright");
const ROOT = path.join(__dirname, "..", "..");
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); }
}
function load(file) {
const css = fs.readFileSync(path.join(ROOT, "app", "static", "performance.css"), "utf8");
const js = fs.readFileSync(path.join(ROOT, "app", "static", "performance.js"), "utf8");
return fs.readFileSync(path.join(__dirname, ".out", file), "utf8")
.replace(/<link rel="stylesheet" href="\/static\/performance\.css[^"]*" \/>/, function () { return "<style>" + css + "</style>"; })
.replace(/<script src="\/static\/performance\.js[^"]*" defer><\/script>/, function () { return "<script>" + js + "</script>"; });
}
(async function () {
const browser = await chromium.launch(process.env.PJ_TEST_BROWSER ? { executablePath: process.env.PJ_TEST_BROWSER } : {});
try {
// 매출 실적 — 틱톡 라이브커머스 10/5 칸(RM 100.05)을 12.34 로
const page = await browser.newPage({ viewport: { width: 1400, height: 900 } });
const calls = [];
await page.route("**/*", function (r) {
if (!/\/api\//.test(r.request().url())) return r.fulfill({ status: 200, contentType: "text/html; charset=utf-8", body: load("perf_my_dash.html") });
calls.push({ url: r.request().url(), body: r.request().postData() });
r.fulfill({ status: 200, contentType: "application/json",
body: JSON.stringify({ ok: true, manual: 1234, amount: 1234, commission: 0, net: 1234, formula: null }) });
});
await page.goto("http://perf.test/malaysia/performance/");
const sel = 'td.is-manual-cell[data-manual-code="custom_tiktok_live"][data-date="2026-10-05"]';
await page.click(sel);
const prefill = await page.$eval(sel + " .perf-manual-input", function (i) { return i.value; });
check("편집창 = RM 값(100.05)", prefill === "100.05", prefill);
await page.keyboard.press("Control+A");
await page.keyboard.type("RM 12.34");
await page.keyboard.press("Escape"); // 저장 뒤 새로고침(합계 다시 계산) 전에 칸 값을 본다 — Enter 는 다음 칸 편집으로 넘어감
await page.click(sel);
await page.keyboard.press("Control+A");
await page.keyboard.type("RM 12.34");
await page.keyboard.press("Enter");
await page.waitForTimeout(300);
const put = calls.find(function (c) { return /manual-sales/.test(c.url); });
check("저장 주소 = /malaysia/performance/api/manual-sales/…", put && /\/malaysia\/performance\/api\/manual-sales\/custom_tiktok_live\/2026-10-05$/.test(put.url), put);
check("보낸 값 = 12.34(RM 글자 지움)", put && JSON.parse(put.body).amount === "12.34", put);
const cell = await page.$eval(sel, function (td) { return { gross: td.querySelector(".v-gross").textContent, v: td.dataset.manualValue }; });
check("저장 뒤 칸 = 12.34, 편집값 12.34", cell.gross === "12.34" && cell.v === "12.34", cell);
const head = await page.$eval("#perf-chart-daily svg", function (s) { return s.querySelector("title").textContent; });
check("그래프 말풍선 = RM", / RM$/.test(head) && /\d\.\d\d RM$/.test(head), head);
await page.close();
// 광고비 — 쇼피 10/5 칸에 계산식
const ap = await browser.newPage({ viewport: { width: 1400, height: 900 } });
const acalls = [];
await ap.route("**/*", function (r) {
if (!/\/api\//.test(r.request().url())) return r.fulfill({ status: 200, contentType: "text/html; charset=utf-8", body: load("perf_my_ads.html") });
acalls.push({ url: r.request().url(), body: r.request().postData() });
r.fulfill({ status: 200, contentType: "application/json", body: JSON.stringify({ ok: true, manual: 300, amount: 300, formula: "1.5*2" }) });
});
await ap.goto("http://perf.test/malaysia/performance/ads");
const heads = await ap.$$eval(".perf-main thead th", function (ths) { return ths.map(function (t) { return t.textContent.trim(); }); });
check("광고비 열 = 틱톡·쇼피·라자다", /틱톡/.test(heads[2]) && /쇼피/.test(heads[3]) && /라자다/.test(heads[4]) && heads.length === 5, heads);
const asel = 'td.is-manual-cell[data-manual-code="shopee"][data-date="2026-10-05"]';
await ap.click(asel);
await ap.keyboard.type("1.5*2");
await ap.keyboard.press("Enter");
await ap.waitForTimeout(300);
const aput = acalls.find(function (c) { return /ad-spend/.test(c.url); });
check("광고비 저장 주소 = /malaysia/performance/api/ad-spend/shopee/…", aput && /\/malaysia\/performance\/api\/ad-spend\/shopee\/2026-10-05$/.test(aput.url), aput);
const av = await ap.$eval(asel + " .v-gross", function (s) { return s.textContent; });
check("광고비 칸 = 3.00", av === "3.00", av);
await ap.close();
} finally { await browser.close(); }
console.log(fails.length ? "\n" + fails.length + " FAILED" : "\nALL PASS");
process.exit(fails.length ? 1 : 0);
})();
-63
View File
@@ -1,63 +0,0 @@
// 실적 틱톡 탭(2026-11-05) — 실제 브라우저(Chromium).
// python tests/js/render_performance.py
// NODE_PATH=<playwright 경로> PJ_TEST_BROWSER=<Chrome 경로> node tests/js/perf_tiktok.browser.test.js
// 광고비 오른쪽 탭, ROAS·광고비·매출 열, 매출·광고비 그래프 둘, 합계 줄 스크롤 고정, 칸 입력 없음, 스크립트 오류 없음.
const fs = require("fs"), path = require("path");
const { chromium } = require("playwright");
const ROOT = path.join(__dirname, "..", "..");
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); }
}
(async function () {
const exe = process.env.PJ_TEST_BROWSER;
const browser = await chromium.launch(exe ? { executablePath: exe } : {});
try {
const p = await (await browser.newContext({ viewport: { width: 1400, height: 800 } })).newPage();
const errors = [];
p.on("pageerror", function (e) { errors.push(String(e)); });
await p.route("**/*", function (r) {
const url = new URL(r.request().url()).pathname;
if (url.startsWith("/static/")) {
const f = path.join(ROOT, "app", url);
if (!fs.existsSync(f)) return r.fulfill({ status: 404, body: "" });
const type = f.endsWith(".css") ? "text/css" : f.endsWith(".js") ? "application/javascript" : "font/woff2";
return r.fulfill({ status: 200, contentType: type, body: fs.readFileSync(f) });
}
if (!url.endsWith(".html")) return r.fulfill({ status: 200, contentType: "application/json", body: "{}" });
r.fulfill({ status: 200, contentType: "text/html; charset=utf-8", body: fs.readFileSync(path.join(__dirname, ".out", url.slice(1)), "utf8") });
});
await p.goto("http://erp.test/perf_tiktok_shell.html");
await p.waitForTimeout(300);
const tabs = await p.locator(".perf-tabs-main .perf-tab").allInnerTexts();
check("탭 순서 = 매출 실적·광고비·틱톡", tabs.map(function (t) { return t.replace(/^[a-z_]+\s*/, "").trim(); }).join() === "매출 실적,광고비,틱톡", tabs);
check("틱톡 탭이 켜짐", await p.locator(".perf-tab-tiktok.is-active").count() === 1);
const head = await p.locator("table.perf-main thead th").allInnerTexts();
check("열 = 날짜·ROAS·광고비·매출", head.join() === "날짜,ROAS,광고비,매출", head);
const total = await p.locator("table.perf-main tbody tr").first().innerText();
check("맨 위 기간 합계", total.includes("합계") && total.includes("210,000") && total.includes("630,000") && total.includes("300%"), total);
const day = await p.locator("table.perf-main tbody tr", { hasText: "400%" }).first().innerText();
check("일자 줄 값", day.includes("120,000") && day.includes("480,000"), day);
check("매출 그래프", await p.locator("#perf-chart-daily svg rect.bar").count() > 0);
check("광고비 그래프", await p.locator("#perf-chart-daily2 svg rect.bar").count() > 0);
check("칸 입력 없음", await p.locator("[data-manual-code]").count() === 0);
check("업데이트 버튼", (await p.locator("#perf-ad-sync-btn").innerText()).includes("광고비 업데이트"));
await p.screenshot({ path: path.join(__dirname, ".out", "perf_tiktok.png") });
await p.locator("table.perf-main").hover();
await p.mouse.wheel(0, 500);
await p.waitForTimeout(250);
const stuck = await p.evaluate(function () {
const first = document.querySelector("table.perf-main tbody tr.perf-row-total:first-child th");
const top = first.getBoundingClientRect().top;
return document.querySelector("table.perf-main thead th").getBoundingClientRect().bottom <= top + 2 && top >= 0 && top < 300;
});
check("스크롤해도 제목·합계 줄 고정", stuck);
check("스크립트 오류 없음", errors.length === 0, errors);
} finally {
await browser.close();
}
if (fails.length) { console.log("\n" + fails.length + " FAILED"); process.exit(1); }
console.log("\nALL OK");
})();
+23 -14
View File
@@ -19,9 +19,10 @@ 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.ad_spend import build_ad_dashboard, build_tiktok_dashboard # noqa: E402
from app.modules.performance.ad_spend import build_ad_dashboard # noqa: E402
from app.modules.performance.dashboard import amount_text, build_dashboard, build_settings # noqa: E402
from app.modules.performance.router import _auto_sync_settings_ctx # noqa: E402
from app.modules.performance import variant # noqa: E402
BASE_STUB = ("{% block head_extra %}{% endblock %}<body><main class='erp-page'>{% block content %}{% endblock %}</main>"
"{% block scripts %}{% endblock %}</body>")
@@ -84,17 +85,11 @@ def env() -> jinja2.Environment:
return e
class TiktokStore:
def ad_details(self, code, start, end):
rows = [("2026-10-02", 120000, 480000), ("2026-10-05", 90000, 150000), ("2026-09-20", 50000, 100000)]
return [{"date": d, "amount": a, "roas": None, "metrics": {"매출": b}, "source": "api"} for d, a, b in rows]
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": "",
"unit": "won", "unit_label": "원", "amt": lambda v: amount_text(v), "colw": "auto"}
"unit": "won", "unit_label": "원", "amt": lambda v: amount_text(v), "colw": "auto", **variant.template_ctx()}
ctx = build_dashboard(FakeStore(), kind="week", anchor=date(2026, 10, 7), today=date(2026, 10, 7))
# 다음 자동 업데이트(router._auto_sync_ctx 와 같은 모양) — 화면이 초 단위로 센다
# 일정 = 실적 설정 "자동 업데이트"(2026-10-26) — 화면이 schedule 로 다음 회차를 계산
@@ -123,12 +118,6 @@ def main() -> None:
html = shell.get_template("performance/ads.html").render(**sbase, active_tab="ads", **sactx)
with open(os.path.join(OUT_DIR, "perf_ads_shell.html"), "w", encoding="utf-8") as f:
f.write(html)
# 틱톡 탭(2026-11-05) — 가상의 광고 API 값
tk = build_tiktok_dashboard(TiktokStore(), kind="month", anchor=date(2026, 10, 7), today=date(2026, 10, 7), holidays={"2026-10-03": "개천절"})
tk.update(auto_sync=ctx["auto_sync"], update_watch={"kind": "ads", "seen": "job-old"}, tiktok_configured=True, ad_running=False,
ad_last_update_at=None, ad_sync_sources=[{"code": "tiktok", "name": "틱톡"}])
with open(os.path.join(OUT_DIR, "perf_tiktok_shell.html"), "w", encoding="utf-8") as f:
f.write(shell.get_template("performance/tiktok.html").render(**sbase, active_tab="tiktok", **tk))
actx =build_ad_dashboard(FakeStore(), kind="month", anchor=date(2026, 10, 7), today=date(2026, 10, 7),
sales_codes=["cafe24", "coupang"])
actx["ad_sync_sources"] = [{"code": "google", "name": "구글 광고"}] # [구글 광고 불러오기]
@@ -171,9 +160,29 @@ def main() -> None:
html = shell.get_template("performance/ads.html").render(**{**sbase, "colw": "manual"}, active_tab="ads", **sactx)
with open(os.path.join(OUT_DIR, "perf_ads_colw_shell.html"), "w", encoding="utf-8") as f:
f.write(html)
render_malaysia(e, base)
print("ok")
def render_malaysia(e: jinja2.Environment, base: dict) -> None:
"""말레이시아 실적(2026-11-20) — perf_my_dash.html · perf_my_ads.html (perf_malaysia.browser.test.js). 금액 = 센."""
from app.modules.performance.tests.test_malaysia_variant import _Store # noqa: WPS433
token = variant._current.set(variant.MY)
try:
mb = {**base, **variant.template_ctx(), "unit": "rm", "unit_label": "RM", "amt": lambda v: amount_text(v, "rm")}
ctx = build_dashboard(_Store(), kind="week", anchor=date(2026, 10, 7), today=date(2026, 10, 7))
ctx.update(auto_sync=None, update_watch=None)
with open(os.path.join(OUT_DIR, "perf_my_dash.html"), "w", encoding="utf-8") as f:
f.write(e.get_template("performance/index.html").render(**mb, active_tab="dashboard", metric="gross", **ctx))
actx = build_ad_dashboard(_Store(), kind="week", anchor=date(2026, 10, 7), today=date(2026, 10, 7), sales_codes=[])
actx.update(auto_sync=None, update_watch=None)
with open(os.path.join(OUT_DIR, "perf_my_ads.html"), "w", encoding="utf-8") as f:
f.write(e.get_template("performance/ads.html").render(**mb, active_tab="ads", **actx))
finally:
variant._current.reset(token)
class GroupStore(FakeStore):
"""카페24·네이버 + 그룹 '오프라인'(매장A·매장B) + 그룹 없는 직접 추가 '행사'."""