Files
dbx-main/tests/js/perf_auto_sync.browser.test.js
T
king 07861dfe8c feat(performance): 자동 업데이트 일정 설정 — 매출·광고비 따로 간격·요일·시작/끝
- 실적 설정 "자동 업데이트" 카드(관리자): 매출 실적·광고비 각각 사용·요일([매일]·[평일])·
  시작/끝 시각(5분 단위)·간격(5~720분, 5분 단위, 기본 30분), PUT /api/auto-sync-schedule
- 마이그레이션 011 perf_settings(key auto_sync, JSONB). 미적용·값 없음 = 기본 일정(매일 9~19시 30분)
- auto_sync: 종류별 일정·Scheduler(1분마다 다시 읽어 바뀐 종류만 다시 계산, 종류마다 따로 스레드)
- 매출·광고비 탭 카운트다운이 각자 일정대로 다음 회차 계산(nextScheduleSlot)
- 테스트: 일정 계산·검증·Scheduler·저장 API·브라우저(설정 카드·카운트다운)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 18:01:00 +09:00

163 lines
11 KiB
JavaScript

// 실적 자동 업데이트 일정(2026-10-26) — 실제 브라우저(Chromium).
// python tests/js/render_performance.py
// NODE_PATH=<playwright 경로> PJ_TEST_BROWSER=<Chrome 경로> node tests/js/perf_auto_sync.browser.test.js
// 설정: "자동 업데이트" 카드 — 매출 실적·광고비 따로 사용·요일(매일/평일)·시작/끝(5분 단위)·간격, [저장] = PUT /api/auto-sync-schedule,
// 잘못된 값은 보내지 않음, 진짜 ERP 셸에서 가로로 넘치지 않음(PC·폰).
// 매출 실적: 다음 업데이트 카운트다운이 일정(간격·요일·시작/끝)대로 다음 회차를 센다(auto_sync.next_slot 과 같은 규칙).
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 page(file, edit) {
const css = fs.readFileSync(path.join(ROOT, "app", "static", "performance.css"), "utf8");
const js = fs.readFileSync(path.join(ROOT, "app", "static", "performance.js"), "utf8");
let html = 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>"; });
return edit ? edit(html) : html;
}
(async function () {
const browser = await chromium.launch(process.env.PJ_TEST_BROWSER ? { executablePath: process.env.PJ_TEST_BROWSER } : {});
try {
// ── 설정 카드 ──
const ctx = await browser.newContext({ viewport: { width: 1400, height: 900 } });
const p = await ctx.newPage();
const puts = [];
p.on("dialog", function (d) { d.accept(); });
await p.route("**/*", function (r) {
const req = r.request();
if (req.method() === "PUT" && req.url().indexOf("/performance/api/auto-sync-schedule") >= 0) {
const body = JSON.parse(req.postData());
puts.push(body);
return r.fulfill({ status: 200, contentType: "application/json", body: JSON.stringify({
ok: true, env_on: true,
sales: { schedule: body.sales, label: "매일 08:30~19:00 · 15분마다", next_at: "2026-10-27T08:30:00+09:00" },
ads: { schedule: body.ads, label: "꺼짐", next_at: "" } }) });
}
if (req.url().indexOf("/static/") >= 0) return r.fulfill({ status: 200, body: "" });
r.fulfill({ status: 200, contentType: "text/html; charset=utf-8", body: page("perf_settings_shell.html") });
});
await p.goto("http://perf.test/performance/settings");
const state = function () {
return p.evaluate(function () {
return Array.from(document.querySelectorAll("#perf-auto-sync .perf-auto-row")).map(function (row) {
const v = function (k) { return row.querySelector('[data-t="' + k + '"]').value; };
return { kind: row.dataset.kind, on: row.querySelector('[data-f="enabled"]').checked, off: row.classList.contains("is-off"),
days: Array.from(row.querySelectorAll("[data-day]:checked")).map(function (c) { return Number(c.dataset.day); }),
start: v("start-h") + ":" + v("start-m"), end: v("end-h") + ":" + v("end-m"),
interval: row.querySelector('[data-f="interval"]').value, next: row.querySelector("[data-next]").textContent.trim() };
});
});
};
let st = await state();
check("두 줄(매출 실적·광고비)", JSON.stringify(st.map(function (r) { return r.kind; })) === '["sales","ads"]', st);
check("기본 일정 = 매일 09:00~19:00 30분", st.every(function (r) {
return r.on && r.days.length === 7 && r.start === "09:00" && r.end === "19:00" && r.interval === "30";
}), st);
check("일정 설명 표시", st[0].next.indexOf("매일 09:00~19:00 · 30분마다") === 0, st[0].next);
const minuteOpts = await p.$$eval('[data-kind="sales"] [data-t="start-m"] option', function (os) { return os.map(function (o) { return o.value; }); });
check("분은 5분 단위(00~55)", minuteOpts.length === 12 && minuteOpts[1] === "05" && minuteOpts[11] === "55", minuteOpts);
const noOverflow = function () {
return p.evaluate(function () {
// 카드만 본다 — 테스트는 erp.css·아이콘 글꼴을 싣지 않아 다른 표·아이콘이 페이지를 넓힌다
const card = document.getElementById("perf-auto-sync"), r = card.getBoundingClientRect();
let inner = 0;
card.querySelectorAll("*").forEach(function (e) { inner = Math.max(inner, e.getBoundingClientRect().right - r.right); });
return { page: Math.round(r.right - document.documentElement.clientWidth), card: card.scrollWidth - card.clientWidth, inner: Math.round(inner) };
});
};
let ov = await noOverflow();
check("PC: 가로로 넘치지 않음", ov.page <= 0 && ov.card <= 0 && ov.inner <= 0, ov);
// 광고비 [평일] → 토·일 빠짐, 그다음 [매일] → 다시 7일
await p.click('[data-kind="ads"] [data-days="weekday"]');
st = await state();
check("[평일] = 월~금", JSON.stringify(st[1].days) === "[0,1,2,3,4]", st[1].days);
check("바꾸면 저장 안내", (await p.textContent("#perf-auto-msg")).indexOf("[저장]") >= 0);
await p.click('[data-kind="ads"] [data-days="all"]');
check("[매일] = 7일", (await state())[1].days.length === 7);
// 매출: 08:30 시작, 15분 / 광고비: 평일 + 사용 끔
await p.selectOption('[data-kind="sales"] [data-t="start-h"]', "08");
await p.selectOption('[data-kind="sales"] [data-t="start-m"]', "30");
await p.fill('[data-kind="sales"] [data-f="interval"]', "15");
await p.click('[data-kind="ads"] [data-days="weekday"]');
await p.click('[data-kind="ads"] .perf-day.is-sat'); // 토요일 다시 켬 — 동그라미 눌러 고르기
await p.uncheck('[data-kind="ads"] [data-f="enabled"]');
st = await state();
check("사용 끄면 흐리게", st[1].off && !st[1].on, st[1]);
check("요일 동그라미 눌러 고르기", JSON.stringify(st[1].days) === "[0,1,2,3,4,5]", st[1].days);
// 잘못된 값 — 보내지 않음
await p.fill('[data-kind="sales"] [data-f="interval"]', "7");
await p.click("#perf-auto-save");
await p.waitForTimeout(300);
check("간격 7분 → 저장 안 함", puts.length === 0, puts);
await p.keyboard.press("Escape");
await p.fill('[data-kind="sales"] [data-f="interval"]', "15");
await p.selectOption('[data-kind="sales"] [data-t="end-h"]', "07");
await p.click("#perf-auto-save");
await p.waitForTimeout(300);
check("끝 < 시작 → 저장 안 함", puts.length === 0, puts);
await p.keyboard.press("Escape");
await p.selectOption('[data-kind="sales"] [data-t="end-h"]', "19");
await p.click("#perf-auto-save");
await p.waitForFunction(function () { return /저장했습니다/.test(document.getElementById("perf-auto-msg").textContent); });
check("저장 = 두 일정 한 번에", puts.length === 1 && JSON.stringify(puts[0]) === JSON.stringify({
sales: { enabled: true, interval: 15, days: [0, 1, 2, 3, 4, 5, 6], start: "08:30", end: "19:00" },
ads: { enabled: false, interval: 30, days: [0, 1, 2, 3, 4, 5], start: "09:00", end: "19:00" } }), puts);
st = await state();
check("저장 뒤 다음 회차 표시", st[0].next === "매일 08:30~19:00 · 15분마다 · 다음 10-27 08:30" && st[1].next === "꺼짐", st.map(function (r) { return r.next; }));
await p.screenshot({ path: path.join(__dirname, ".out", "perf_auto_sync_settings.png"), fullPage: false,
clip: await p.evaluate(function () { const r = document.getElementById("perf-auto-sync").getBoundingClientRect(); return { x: r.x, y: r.y, width: r.width, height: r.height }; }) });
await p.setViewportSize({ width: 390, height: 844 });
ov = await noOverflow();
check("폰: 가로로 넘치지 않음", ov.page <= 0 && ov.card <= 0 && ov.inner <= 0, ov);
await ctx.close();
// ── 다음 업데이트 카운트다운(매출 실적) ──
async function countdown(edit, at) {
const c = await browser.newContext({ viewport: { width: 1400, height: 900 }, timezoneId: "America/New_York" }); // PC 시간대와 무관하게 KST
const pg = await c.newPage();
await pg.clock.install({ time: new Date(at) });
await pg.route("**/*", function (r) { r.fulfill({ status: 200, contentType: "text/html; charset=utf-8", body: page("perf_dash.html", edit) }); });
await pg.goto("http://perf.test/performance/");
return { c: c, p: pg, text: function () { return pg.textContent("#perf-next-update"); } };
}
let cd = await countdown(null, "2026-10-07T10:17:25+09:00");
check("기본 일정: 10:30 까지 12분 35초", (await cd.text()).indexOf("12분 35초") >= 0, await cd.text());
await cd.p.clock.runFor(12 * 60000 + 36000);
check("회차 시각 = 자동 업데이트 중", (await cd.text()).indexOf("자동 업데이트 중") >= 0, await cd.text());
await cd.p.clock.runFor(61000); // 10:31:02
check("1분 뒤 다음 회차(11:00) 까지", (await cd.text()).indexOf("28분 58초") >= 0, await cd.text());
await cd.c.close();
// 평일 08:35~10:00 25분마다 — 금요일 09:50 회차 뒤 다음은 월요일 08:35
const weekday = function (html) {
return html.replace(/"auto_sync": \{[^}]*"schedule": \{[^}]*\}/, function () {
return '"auto_sync": {"next_at": "2026-10-09T09:50:00+09:00", "now": "2026-10-09T09:49:00.000+09:00", ' +
'"schedule": {"enabled": true, "interval": 25, "days": [0, 1, 2, 3, 4], "start": "08:35", "end": "10:00"}';
});
};
cd = await countdown(weekday, "2026-10-09T09:49:00+09:00");
check("일정 바꾼 화면: 09:50 까지 1분", (await cd.text()).indexOf("1분 00초") >= 0, await cd.text());
await cd.p.clock.runFor(2 * 60000); // 09:51 — 회차 1분 지남 → 월요일 08:35
const want = (Date.parse("2026-10-12T08:35:00+09:00") - Date.parse("2026-10-09T09:51:00+09:00")) / 1000;
const hh = Math.floor(want / 3600), mm = Math.floor((want % 3600) / 60);
check("금 09:50 회차 뒤 → 월 08:35 까지(" + hh + "시간 " + mm + "분)", (await cd.text()).indexOf(hh + "시간 " + (mm < 10 ? "0" : "") + mm + "분") >= 0, await cd.text());
await cd.c.close();
} finally {
await browser.close();
}
console.log(fails.length ? "\n" + fails.length + " FAILED" : "\nALL PASS");
process.exit(fails.length ? 1 : 0);
})();