Files
dbx-main/tests/js/goals_meeting_ui.test.js
T
king 20232baf06 feat(project): add font options and selected goal text formatting
Restore the board header add button to the task side panel while keeping footer quick entry. Add safe, persisted goal text formatting and self-hosted Project font preferences with shared help updates and regression coverage.
2026-10-02 17:28:54 +09:00

700 lines
50 KiB
JavaScript

// 연간 목표(goals.html)·주간 회의록(goal_meeting.html) + static/project.js UI 회귀 테스트 — jsdom.
// 서버는 가짜(fetch 대체)로 두고 지연(deferred)·순서 역전·503·연속 입력을 직접 만든다. 실제 브라우저 레이아웃·입력기·터치 기기는 아니다.
//
// python tests/js/render_goals.py # 템플릿 렌더 → tests/js/.out/goals_*.html · meeting_*.html
// npm install jsdom # (최초 1회, 또는 NODE_PATH 로 jsdom 이 있는 node_modules 지정)
// node tests/js/goals_meeting_ui.test.js
//
// 성공하면 마지막 줄 ALL PASS, 실패하면 항목명과 종료코드 1.
const fs = require("fs");
const path = require("path");
const { JSDOM, VirtualConsole } = require("jsdom");
const WATCHDOG = setTimeout(function () { console.log("TIMEOUT — 어딘가에서 멈춤"); process.exit(2); }, 180000);
const ROOT = path.join(__dirname, "..", "..");
const OUT = path.join(__dirname, ".out");
const JS = fs.readFileSync(path.join(ROOT, "app", "static", "project.js"), "utf8");
const PAGE = {};
["goals_admin", "goals_ro", "meeting_admin", "meeting_err", "meeting_ro"].forEach(function (n) {
PAGE[n] = fs.readFileSync(path.join(OUT, n + ".html"), "utf8");
});
const GOALS_URL = "http://localhost/project/goals/2026";
const MEET_URL = "http://localhost/project/goals/2026/meetings/9?week=2026-09-28";
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 deferred() {
let resolve, reject;
const p = new Promise(function (a, b) { resolve = a; reject = b; });
return { promise: p, resolve: resolve, reject: reject };
}
function settle(n) {
return new Promise(function (r) { let i = 0; (function spin() { if (i++ >= (n || 40)) return r(); setImmediate(spin); })(); });
}
function wait(ms) { return new Promise(function (r) { setTimeout(r, ms); }); }
const unhandled = [];
process.on("unhandledRejection", function (e) { unhandled.push(String(e && e.message || e)); });
// env.route(method, re, fn(url, body, call)) — fn 이 {status, body, text} 또는 "NETWORK" 를 돌려준다(Promise 가능)
function makeEnv(html, url, opts) {
opts = opts || {};
const vc = new VirtualConsole();
const env = { calls: [], routes: [], navigations: 0, toasts: [], prompts: [], inflight: {}, maxInflight: {} };
vc.on("jsdomError", function (e) { if (/navigation/i.test(String(e && e.message))) env.navigations++; });
const dom = new JSDOM(html, { runScripts: "dangerously", pretendToBeVisual: true, url: url, virtualConsole: vc });
const w = dom.window, d = w.document;
env.w = w; env.d = d;
w.__PJ_TEST__ = true;
w.console.error = function () {};
w.scrollTo = function () {};
w.HTMLCanvasElement.prototype.getContext = function () { return null; };
w.erpConfirm = function () { return Promise.resolve(true); };
w.erpPrompt = function (msg, def) { env.prompts.push(msg); return Promise.resolve(opts.promptAnswer != null ? opts.promptAnswer : "새 이름"); };
w.erpAlert = function () {};
if (opts.storage) Object.keys(opts.storage).forEach(function (k) { w.localStorage.setItem(k, opts.storage[k]); });
if (opts.session) Object.keys(opts.session).forEach(function (k) { w.sessionStorage.setItem(k, opts.session[k]); });
env.route = function (method, re, fn) { env.routes.unshift({ method: method, re: re, fn: fn }); };
w.fetch = async function (u, o) {
const method = (o && o.method) || "GET";
let body = o && o.body;
if (typeof body === "string") { try { body = JSON.parse(body); } catch (_) {} }
const call = { method: method, url: String(u), body: body, keepalive: !!(o && o.keepalive), done: false };
env.calls.push(call);
const key = method + " " + String(u).replace(/^https?:\/\/[^/]+/, "");
env.inflight[key] = (env.inflight[key] || 0) + 1;
env.maxInflight[key] = Math.max(env.maxInflight[key] || 0, env.inflight[key]);
try {
for (const r of env.routes) {
if (r.method === method && r.re.test(String(u))) {
const out = await r.fn(String(u), body, call);
if (out === "NETWORK") throw new TypeError("Failed to fetch");
const status = out.status || 200;
return { ok: status < 400, status: status, statusText: "x",
json: async function () { return out.body || {}; }, text: async function () { return out.text || ""; } };
}
}
return { ok: true, status: 200, statusText: "OK", json: async function () { return {}; }, text: async function () { return ""; } };
} finally {
env.inflight[key]--;
call.done = true;
}
};
env.puts = function (re) { return env.calls.filter(function (c) { return c.method === "PUT" && re.test(c.url); }); };
env.toastText = function () { const t = d.querySelector(".erp-toast"); return t ? t.textContent : ""; };
return env;
}
async function boot(env) {
if (env.d.readyState === "loading") await new Promise(function (r) { env.d.addEventListener("DOMContentLoaded", r); });
env.w.eval(fs.readFileSync(path.join(ROOT, "app", "static", "project-goal-text.js"), "utf8"));
env.w.eval(JS);
env.d.dispatchEvent(new env.w.Event("DOMContentLoaded"));
await settle();
return env;
}
function type(env, node, value) {
node.value = value;
node.dispatchEvent(new env.w.Event("input", { bubbles: true }));
}
function fire(env, node, name) { node.dispatchEvent(new env.w.Event(name, { bubbles: name !== "blur" && name !== "focus" })); }
function key(env, node, k, extra) {
const e = new env.w.KeyboardEvent("keydown", Object.assign({ key: k, bubbles: true, cancelable: true }, extra || {}));
node.dispatchEvent(e);
return e;
}
// 블록 하나가 예외로 멈춰도 나머지 블록은 계속(예외는 FAIL 로)
async function section(fn) {
try { await fn(); } catch (e) { check("블록 예외 없음: " + String(e && e.message || e).slice(0, 120), false); }
}
function itemLabel(b) { return (b.querySelector(".pj-ctxmenu-label") || b).textContent.trim(); }
function unload(env) {
const e = new env.w.Event("beforeunload", { cancelable: true });
env.w.dispatchEvent(e);
return e;
}
// ── 가짜 서버 — 목표 표(글 칸 상태를 기억해 화면 GET 에 반영) ───────────────
function goalsServer(env, st) {
st = Object.assign({ cells: {}, areaAdded: false, cellHook: null, metricHook: null, getHook: null }, st || {});
env.route("GET", /\/project\/api\//, function () { return { body: {} }; });
env.route("PUT", /\/project\/api\/goals\/rows\/\d+\/cells\/\d+$/, async function (u, body, call) {
const m = u.match(/rows\/(\d+)\/cells\/(\d+)/);
if (st.cellHook) { const r = await st.cellHook(u, body, call); if (r) return r; }
st.cells[m[1] + ":" + m[2]] = body.body;
return { body: { ok: true } };
});
env.route("PUT", /\/project\/api\/goals\/2026\/metrics$/, async function (u, body, call) {
if (st.metricHook) { const r = await st.metricHook(u, body, call); if (r) return r; }
const n = Number(String(body.value).replace(/[,\s]/g, ""));
st.metric = String(body.value);
return { body: { ok: true, label: body.value === "" ? "" : n.toLocaleString("en-US") } };
});
env.route("POST", /\/project\/api\/goals\/2026\/areas$/, function () { st.areaAdded = true; return { body: { ok: true } }; });
env.route("POST", /\/project\/api\/goals\/areas\/\d+\/rows$/, function () { return { status: 201, body: { ok: true } }; });
env.route("POST", /\/project\/api\/goals\/areas\/\d+\/move$/, function () { return { body: { ok: true } }; });
env.route("POST", /\/project\/api\/goals\/areas\/\d+\/merge$/, function () { st.merged = true; return { body: { ok: true, row_id: 10, start: 1 } }; });
env.route("GET", /\/project\/goals\/2026$/, async function () {
if (st.getHook) await st.getHook();
st.gets = (st.gets || 0) + 1;
let html = PAGE.goals_admin.replace(/(<div class="pj-goal-text"[^>]*data-row="(\d+)" data-month="(\d+)"[^>]*>)([\s\S]*?)(<\/div>)/g,
function (all, open, row, month, text, close) {
const k = row + ":" + month;
return open + (k in st.cells ? renderGoalBody(env, st.cells[k]) : text) + close;
});
if (st.areaAdded) {
html = html.replace(/(<\/tbody>\s*)(<\/table>)/, '$1<tbody class="pj-goal-area" data-area-id="3" data-color="" style="--goal-bg: #fff">' +
'<tr data-row-id="30"><th class="pj-goal-c1 pj-goal-area-name" rowspan="1"><span class="pj-goal-area-text">새 영역</span></th>' +
'<th class="pj-goal-c2 pj-goal-row-label"><span class="pj-goal-row-text"></span></th>' +
'<td class="pj-goal-texttd pj-goal-year-col" data-month="0" data-span="1" data-rspan="1"><div class="pj-goal-text" contenteditable="true" data-row="30" data-month="0"></div></td>' +
"</tr></tbody>$2");
}
return { text: html };
});
return st;
}
function renderGoalBody(env, value) {
const div = env.d.createElement("div");
const runs = value.startsWith("pj-rich:v1:") ? JSON.parse(value.slice(11)) : [{ text: value }];
env.w.PJGoalText.paint(div, runs);
return div.innerHTML;
}
// ── 가짜 서버 — 회의록 ────────────────────────────────────────────────
function meetServer(env, st) {
st = Object.assign({ items: {}, head: {}, itemHook: null, headHook: null, getHook: null, syncHook: null, page: PAGE.meeting_admin }, st || {});
env.route("GET", /\/project\/api\//, function () { return { body: {} }; });
const amount = function (v) { if (v === "" || v == null) return null; return Number(String(v).replace(/[,\s원]/g, "")); };
env.route("PUT", /\/project\/api\/goals\/meeting-items\/\d+$/, async function (u, body, call) {
const id = Number(u.match(/meeting-items\/(\d+)/)[1]);
if (st.itemHook) { const r = await st.itemHook(id, body, call); if (r) return r; }
const it = st.items[id] = Object.assign(st.items[id] || { id: id }, {});
Object.keys(body).forEach(function (k) { it[k] = /amount$/.test(k) ? amount(body[k]) : body[k]; });
return { body: { ok: true, item: Object.assign({ target_amount: null, result_amount: null }, it) } };
});
env.route("PUT", /\/project\/api\/goals\/meetings\/2026-09-28$/, async function (u, body, call) {
if (st.headHook) { const r = await st.headHook(body, call); if (r) return r; }
Object.assign(st.head, body);
const out = { ok: true };
if ("week_target" in body) { out.week_target = amount(body.week_target); st.head.week_target = out.week_target; }
return { body: out };
});
env.route("POST", /\/project\/api\/goals\/meetings\/2026-09-28\/items$/, function () { return { status: 201, body: { ok: true, id: 9 } }; });
env.route("POST", /\/project\/api\/goals\/meeting-items\/\d+\/move$/, function () { return { body: { ok: true } }; });
env.route("GET", /\/project\/goals\/2026\/meetings\/9/, async function () {
st.gets = (st.gets || 0) + 1;
const page = st.page;
if (st.getHook) { const r = await st.getHook(); if (r) return r; }
return { text: page };
});
env.route("POST", /\/performance\/api\/sync$/, async function (u, body) {
st.syncCalls = (st.syncCalls || 0) + 1;
if (st.syncHook) return st.syncHook(body);
return { body: { joined: false, job: { id: "j1", finished: true, from: body.from, to: body.to, shops: [{ name: "쿠팡", state: "done", active: true }], overall: {} } } };
});
return st;
}
(async function () {
// ════════════════════ [1] 회의록 글 — A→B 연속 입력과 늦은 A 응답 ════════════════════
await section(async function () {
const env = makeEnv(PAGE.meeting_admin, MEET_URL);
const gate = deferred();
const st = meetServer(env, { itemHook: async function (id, body, call) { if (body.content === "draft A") await gate.promise; } });
await boot(env);
const ta = env.d.querySelector('tr[data-item="1"] textarea.pj-meet-text');
ta.focus(); type(env, ta, "draft A"); ta.blur();
await settle();
ta.focus(); type(env, ta, "draft B");
await settle();
check("[1] A 진행 중엔 같은 칸 두 번째 요청을 보내지 않음(직렬화)", env.puts(/meeting-items\/1$/).length === 1);
gate.resolve();
await wait(900); await settle();
const puts = env.puts(/meeting-items\/1$/).map(function (c) { return c.body.content; });
check("[1] A 응답 뒤 B 가 뒤이어 저장됨(PUT A→B)", JSON.stringify(puts) === JSON.stringify(["draft A", "draft B"]), puts);
check("[1] 최종 서버 값 = B", st.items[1].content === "draft B", st.items[1]);
check("[1] 화면 = B", ta.value === "draft B");
check("[1] 같은 칸 동시 요청 최대 1", env.maxInflight["PUT /project/api/goals/meeting-items/1"] === 1, env.maxInflight);
const e = unload(env);
check("[1] 저장 끝난 뒤 페이지 떠남 = 경고 없음", !e.defaultPrevented);
});
// 지연·중복 blur·빠른 연속 입력 — 응답 순서와 무관하게 최신 값이 남는다
await section(async function () {
const env = makeEnv(PAGE.meeting_admin, MEET_URL);
const gates = [];
const st = meetServer(env, { itemHook: async function () { const g = deferred(); gates.push(g); await g.promise; } });
await boot(env);
const ta = env.d.querySelector('tr[data-item="1"] textarea.pj-meet-text');
ta.focus(); type(env, ta, "x1"); ta.blur(); fire(env, ta, "blur"); fire(env, ta, "blur");
ta.focus(); type(env, ta, "x12"); type(env, ta, "x123"); ta.blur();
await settle();
check("[1b] 중복 blur·연속 입력에도 진행 중 요청 1개", env.puts(/meeting-items\/1$/).length === 1);
gates[0].resolve(); await settle();
check("[1b] 첫 응답 뒤 최신 값으로 한 번 더", env.puts(/meeting-items\/1$/).length === 2 && env.puts(/meeting-items\/1$/)[1].body.content === "x123",
env.puts(/meeting-items\/1$/).map(function (c) { return c.body.content; }));
gates[1].resolve(); await settle();
await wait(50); await settle();
check("[1b] 최종 서버 값 = 마지막 입력", st.items[1].content === "x123" && env.puts(/meeting-items\/1$/).length === 2, st.items[1]);
});
// 저장 실패 → dirty·초안 유지, 페이지 떠남 = keepalive 재전송 + 이탈 경고 + 초안 백업, 다음에 열면 되살림
await section(async function () {
const env = makeEnv(PAGE.meeting_admin, MEET_URL);
let fail = true;
const st = meetServer(env, { itemHook: function () { if (fail) return { status: 503, body: { detail: "temporary" } }; } });
await boot(env);
const ta = env.d.querySelector('tr[data-item="1"] textarea.pj-meet-text');
ta.focus(); type(env, ta, "important"); ta.blur();
await settle();
check("[1c] 실패해도 글 그대로", ta.value === "important");
check("[1c] 실패 표시(빨간 테두리)", ta.closest("td").classList.contains("is-save-failed"));
check("[1c] 실패 안내 토스트", /저장 실패/.test(env.toastText()), env.toastText());
const draft = JSON.parse(env.w.localStorage.getItem("pj_draft:meet:item:1:content") || "null");
check("[1c] 초안 백업(localStorage)", draft && draft.draft === "important" && draft.base === "original", draft);
const before = env.puts(/meeting-items\/1$/).length;
const e = unload(env);
await settle();
const after = env.puts(/meeting-items\/1$/);
check("[1c] 페이지 떠남 — 실패한 칸을 keepalive 로 다시 보냄", after.length === before + 1 && after[after.length - 1].keepalive && after[after.length - 1].body.content === "important",
after.map(function (c) { return [c.body.content, c.keepalive]; }));
check("[1c] 페이지 떠남 — 실패 칸이 있으면 이탈 경고", e.defaultPrevented === true);
// 다음에 열기 — 서버엔 아직 original(keepalive 도 실패) → 초안을 되살려 다시 저장
const env2 = makeEnv(PAGE.meeting_admin, MEET_URL, { storage: { "pj_draft:meet:item:1:content": JSON.stringify(draft) } });
const st2 = meetServer(env2);
await boot(env2);
const ta2 = env2.d.querySelector('tr[data-item="1"] textarea.pj-meet-text');
check("[1c] 다시 열면 초안 되살림", ta2.value === "important");
await wait(900); await settle();
check("[1c] 되살린 초안 자동 저장", st2.items[1] && st2.items[1].content === "important", st2.items[1]);
check("[1c] 저장 뒤 초안 백업 지움", env2.w.localStorage.getItem("pj_draft:meet:item:1:content") === null);
// 다른 곳에서 바뀐 칸(base ≠ 서버 값) — 되살리지 않는다
const stale = JSON.stringify({ base: "someone else", draft: "old draft", at: Date.now() });
const env3 = makeEnv(PAGE.meeting_admin, MEET_URL, { storage: { "pj_draft:meet:item:1:content": stale } });
meetServer(env3);
await boot(env3);
check("[1c] 서버 값이 바뀐 칸은 초안을 덮어쓰지 않음", env3.d.querySelector('tr[data-item="1"] textarea.pj-meet-text').value === "original");
fail = false; void st;
});
// 진행 중 저장이 있으면 줄 작업(위로)은 그 저장이 끝난 뒤에, 저장 실패면 줄 작업을 하지 않는다
await section(async function () {
const env = makeEnv(PAGE.meeting_admin, MEET_URL);
const gate = deferred();
let fail = false;
meetServer(env, { itemHook: async function (id, body) { if ("content" in body) { await gate.promise; if (fail) return { status: 503, body: { detail: "x" } }; } } });
await boot(env);
const ta = env.d.querySelector('tr[data-item="1"] textarea.pj-meet-text');
ta.focus(); type(env, ta, "pending text"); ta.blur();
await settle();
fail = true;
env.d.querySelector('tr[data-item="1"] th.pj-meet-c-label').dispatchEvent(new env.w.MouseEvent("contextmenu", { bubbles: true, cancelable: true, clientX: 5, clientY: 5 }));
const up = Array.from(env.d.querySelectorAll(".pj-ctxmenu-item")).find(function (b) { return itemLabel(b) === "위로"; });
up.click();
await settle();
check("[1d] 저장 진행 중엔 줄 이동 요청을 보내지 않음", !env.calls.some(function (c) { return /\/move$/.test(c.url); }));
gate.resolve();
await settle(); await wait(20); await settle();
check("[1d] 저장 실패 → 줄 이동 취소(글 유지, 새로고침 없음)", !env.calls.some(function (c) { return /\/move$/.test(c.url); }) && ta.value === "pending text" && env.navigations === 0,
{ nav: env.navigations });
});
// ════════════════════ [2] 숫자 — 늦은 응답이 최신 입력을 덮지 않음 ════════════════════
await section(async function () {
const env = makeEnv(PAGE.goals_admin, GOALS_URL);
const gates = [];
const st = goalsServer(env, { metricHook: async function (u, body) { if (body.value === "200") { const g = deferred(); gates.push(g); await g.promise; } } });
await boot(env);
const inp = env.d.querySelector('input.pj-goal-num[data-metric="sales"][data-kind="target"][data-month="1"]');
inp.focus(); inp.value = "200"; fire(env, inp, "change"); inp.blur();
await settle();
inp.focus(); type(env, inp, "300");
gates[0].resolve();
await settle();
check("[2] 늦은 200 응답 뒤에도 입력 중인 300 유지", inp.value === "300", inp.value);
inp.blur();
await settle(); await wait(10); await settle();
const vals = env.puts(/metrics$/).map(function (c) { return c.body.value; });
check("[2] 300 확정 → 최종 서버 값 300(요청 순서 200→300)", st.metric === "300" && JSON.stringify(vals) === '["200","300"]', vals);
check("[2] 같은 칸 동시 요청 최대 1(순서 역전 불가)", env.maxInflight["PUT /project/api/goals/2026/metrics"] === 1);
check("[2] 확정 뒤 서버 표기", inp.value === "300");
});
await section(async function () { // 실패 응답 — 요청 뒤 새로 입력한 값을 예전 값으로 되돌리지 않는다 / 그대로면 입력 유지 + 실패 표시, Esc = 저장된 값
const env = makeEnv(PAGE.goals_admin, GOALS_URL);
const gate = deferred();
goalsServer(env, { metricHook: async function (u, body) { if (body.value === "200") { await gate.promise; return { status: 503, body: { detail: "down" } }; } } });
await boot(env);
const inp = env.d.querySelector('input.pj-goal-num[data-metric="sales"][data-kind="target"][data-month="1"]');
inp.focus(); inp.value = "200"; inp.blur();
await settle();
inp.focus(); type(env, inp, "300");
gate.resolve(); await settle();
check("[2b] 200 실패 응답이 새 입력 300 을 되돌리지 않음", inp.value === "300", inp.value);
type(env, inp, "200"); inp.blur(); await settle(); await wait(10); await settle();
check("[2b] 실패한 값 그대로면 입력 유지 + 실패 표시", inp.value === "200" && inp.parentElement.classList.contains("is-save-failed"));
const e = unload(env);
check("[2b] 미저장 숫자 칸이 있으면 이탈 경고", e.defaultPrevented === true);
inp.focus(); key(env, inp, "Escape");
check("[2b] Esc = 저장된 값(100)으로", inp.value === "100", inp.value);
});
await section(async function () { // 회의록 정량 목표·지난주 결과 — 늦은 응답이 새 초안을 덮지 않음
const env = makeEnv(PAGE.meeting_admin, MEET_URL);
const gate = deferred();
const st = meetServer(env, { itemHook: async function (id, body) { if (body.target_amount === "200" || body.result_amount === "70") await gate.promise; } });
await boot(env);
const tin = env.d.querySelector('tr[data-item="1"] input[data-field="target_amount"]');
tin.focus(); tin.value = "200"; tin.blur(); await settle();
tin.focus(); type(env, tin, "300");
const rin = env.d.querySelector('tr[data-item="2"] input[data-field="result_amount"]');
rin.focus(); rin.value = "70"; rin.blur(); await settle();
rin.focus(); type(env, rin, "75");
gate.resolve(); await settle();
check("[2c] 정량 목표 늦은 응답이 300 초안 유지", tin.value === "300", tin.value);
check("[2c] 지난주 결과 늦은 응답이 75 초안 유지", rin.value === "75", rin.value);
tin.blur(); rin.blur(); await settle(); await wait(10); await settle();
check("[2c] 최종 서버 정량 목표 300 · 지난주 결과(7일 전 주 줄 902) 75", st.items[1].target_amount === 300 && st.items[902].result_amount === 75, st.items);
check("[2c] 지난주 달성률 = 75/200", env.d.querySelector('tr[data-item="2"] [data-rate]').textContent.trim() === "37.5%",
env.d.querySelector('tr[data-item="2"] [data-rate]').textContent);
});
await section(async function () { // 금주 목표 저장 — 새로고침하지 않고 숫자 칸만 다시(다른 칸의 미저장 글 보존)
const env = makeEnv(PAGE.meeting_admin, MEET_URL);
const st = meetServer(env, { itemHook: function (id, body) { if ("content" in body) return { status: 503, body: { detail: "x" } }; } });
await boot(env);
const gets0 = st.gets || 0;
const ta = env.d.querySelector('tr[data-item="1"] textarea.pj-meet-text');
ta.focus(); type(env, ta, "unsaved note");
const tgt = env.d.getElementById("pj-meet-target");
tgt.focus(); tgt.value = "2,000"; tgt.blur();
await settle(); await wait(10); await settle();
check("[2d] 금주 목표 저장 = 서버 확정값", st.head.week_target === 2000 && tgt.value === "2,000", st.head);
check("[2d] 페이지 새로고침 없음", env.navigations === 0);
check("[2d] 숫자 칸만 다시 받음(GET 1회 더)", (st.gets || 0) === gets0 + 1, st.gets);
check("[2d] 다른 칸 미저장 글 유지", ta.value === "unsaved note");
});
// ════════════════════ [3] 목표 표 — 글 저장 실패면 구조 변경·표 교체 중단 ════════════════════
await section(async function () {
const env = makeEnv(PAGE.goals_admin, GOALS_URL, { promptAnswer: "새 영역" });
const st = goalsServer(env, { cellHook: function () { return { status: 503, body: { detail: "temporary save failure" } }; } });
await boot(env);
const ta = env.d.querySelector('.pj-goal-text[data-row="10"][data-month="1"]');
ta.focus(); type(env, ta, "unsaved important plan");
env.d.getElementById("pj-goal-area-add").click();
await settle(); await wait(20); await settle();
check("[3] 글 저장 실패 → 영역 추가 요청 안 보냄", !env.calls.some(function (c) { return c.method === "POST" && /\/areas$/.test(c.url); }),
env.calls.map(function (c) { return c.method + " " + c.url; }));
check("[3] 표를 다시 받지 않음", !st.gets);
check("[3] 미저장 계획 그대로", env.d.querySelector('.pj-goal-text[data-row="10"][data-month="1"]').value === "unsaved important plan");
check("[3] 실패 안내", /저장/.test(env.toastText()), env.toastText());
});
await section(async function () { // 진행 중 저장 → 그 저장이 끝난 뒤에 영역 추가, 성공하면 표 교체(새 영역 보임, 저장된 글 유지)
const env = makeEnv(PAGE.goals_admin, GOALS_URL, { promptAnswer: "새 영역" });
const gate = deferred();
const st = goalsServer(env, { cellHook: async function () { await gate.promise; } });
await boot(env);
const ta = env.d.querySelector('.pj-goal-text[data-row="10"][data-month="1"]');
ta.focus(); type(env, ta, "plan v2"); ta.blur();
await settle();
env.d.getElementById("pj-goal-area-add").click();
await settle();
check("[3b] 진행 중 저장이 끝나기 전엔 영역 추가 안 보냄", !env.calls.some(function (c) { return c.method === "POST"; }));
gate.resolve();
await settle(); await wait(20); await settle();
const order = env.calls.filter(function (c) { return c.method !== "GET" || /goals\/2026$/.test(c.url); }).map(function (c) { return c.method + " " + c.url.replace(/^https?:\/\/[^/]+/, ""); });
check("[3b] 순서: 글 PUT → 영역 POST → 표 GET", order.join(" | ") === "PUT /project/api/goals/rows/10/cells/1 | POST /project/api/goals/2026/areas | GET /project/goals/2026", order);
check("[3b] 새 영역이 그 자리에 보임(새로고침 없음)", !!env.d.querySelector('tbody.pj-goal-area[data-area-id="3"]') && env.navigations === 0);
check("[3b] 저장된 글 유지", env.d.querySelector('.pj-goal-text[data-row="10"][data-month="1"]').value === "plan v2");
});
await section(async function () { // 표를 받는 사이에 새로 입력 → 저장 후 다시 받아 교체(입력 유실 없음)
const env = makeEnv(PAGE.goals_admin, GOALS_URL, { promptAnswer: "새 영역" });
const gate = deferred();
let first = true;
const st = goalsServer(env, { getHook: async function () { if (first) { first = false; await gate.promise; } } });
await boot(env);
env.d.getElementById("pj-goal-area-add").click();
await settle();
const ta = env.d.querySelector('.pj-goal-text[data-row="11"][data-month="1"]');
ta.focus(); type(env, ta, "typed during refresh");
gate.resolve();
await settle(); await wait(30); await settle();
check("[3c] 받는 사이 입력한 글 저장됨", st.cells["11:1"] === "typed during refresh", st.cells);
check("[3c] 교체된 표에도 그 글", env.d.querySelector('.pj-goal-text[data-row="11"][data-month="1"]').value === "typed during refresh");
check("[3c] 표를 다시 받음(2회)", st.gets === 2, st.gets);
});
await section(async function () { // 병합 — 저장 실패면 병합 요청 안 보냄
const env = makeEnv(PAGE.goals_admin, GOALS_URL);
const st = goalsServer(env, { cellHook: function () { return { status: 503, body: { detail: "x" } }; } });
await boot(env);
const ta = env.d.querySelector('.pj-goal-text[data-row="10"][data-month="1"]');
ta.focus(); type(env, ta, "draft before merge");
const a = env.d.querySelector('td.pj-goal-texttd[data-month="1"]'), b = env.d.querySelector('tr[data-row-id="10"] td.pj-goal-texttd[data-month="2"]');
a.dispatchEvent(new env.w.MouseEvent("mousedown", { bubbles: true, button: 0 }));
b.dispatchEvent(new env.w.MouseEvent("mouseover", { bubbles: true }));
env.d.dispatchEvent(new env.w.MouseEvent("mouseup", { bubbles: true }));
b.dispatchEvent(new env.w.MouseEvent("contextmenu", { bubbles: true, cancelable: true, clientX: 5, clientY: 5 }));
const merge = Array.from(env.d.querySelectorAll(".pj-ctxmenu-item")).find(function (x) { return /셀 병합/.test(itemLabel(x)); });
check("[3d] 끌어 고른 뒤 우클릭 → 셀 병합 메뉴(기존 동작)", !!merge);
if (merge) merge.click();
await settle(); await wait(20); await settle();
check("[3d] 저장 실패 → 병합 요청 안 보냄, 글 유지", !st.merged && ta.value === "draft before merge");
});
// ════════════════════ [7] 정량 목표 저장 → 이번주 실적 % 즉시 갱신, 다시 그리기와 엇갈려도 ════════════════════
await section(async function () {
const env = makeEnv(PAGE.meeting_admin, MEET_URL, { session: { "pj_meet_sync:2026-09-28": JSON.stringify({ at: Date.now(), state: "ok" }) } });
const st = meetServer(env);
await boot(env);
const slot = function () { return env.d.querySelector('tr[data-item="1"] .pj-meet-week-slot').textContent.trim(); };
check("[7] 처음 = 실적 100 · 목표 100 → 100%", /100%/.test(slot()), slot());
const tin = env.d.querySelector('tr[data-item="1"] input[data-field="target_amount"]');
tin.focus(); tin.value = "200"; tin.blur(); await settle(); await wait(10); await settle();
check("[7] 목표 200 저장 → 50%", /· 50%$/.test(slot()), slot());
tin.focus(); tin.value = "0"; tin.blur(); await settle(); await wait(10); await settle();
check("[7] 목표 0 → % 없음", slot() === "이번주 실적 100", slot());
tin.focus(); tin.value = ""; tin.blur(); await settle(); await wait(10); await settle();
check("[7] 목표 삭제 → % 없음", slot() === "이번주 실적 100", slot());
// 다시 그리기(옛 화면: 목표 100·100%)가 목표 저장 뒤에 도착해도 옛 비율이 들어오지 않는다
const gate = deferred();
st.getHook = async function () { await gate.promise; };
const p = env.w.eval("null"); void p;
tin.focus(); tin.value = "400"; tin.blur(); await settle(); await wait(10); await settle();
check("[7] 목표 400 → 25%", /· 25%$/.test(slot()), slot());
gate.resolve(); await settle(); await wait(10); await settle();
check("[7] 늦게 온 옛 화면(100%)이 덮지 않음 — 지금 목표 기준 25%", /· 25%$/.test(slot()), slot());
// 저장 실패 — 확정 목표(400)는 그대로라 25% 유지, 입력값은 남김
st.itemHook = function () { return { status: 503, body: { detail: "x" } }; };
tin.focus(); tin.value = "800"; tin.blur(); await settle(); await wait(10); await settle();
check("[7] 저장 실패 → 비율은 확정값(25%), 입력 800 유지", /· 25%$/.test(slot()) && tin.value === "800", [slot(), tin.value]);
});
await section(async function () { // 실적 조회 실패 화면 — 미확인(0원·0% 아님)
const env = makeEnv(PAGE.meeting_err, MEET_URL, { session: { "pj_meet_sync:2026-09-28": JSON.stringify({ at: Date.now(), state: "ok" }) } });
meetServer(env, { page: PAGE.meeting_err });
await boot(env);
const kpi = Array.from(env.d.querySelectorAll(".pj-meet-kpi")).map(function (k) { return k.textContent.replace(/\s+/g, " ").trim(); });
const mtd = kpi.find(function (t) { return /월 누적 실적/.test(t); });
check("[6] 월 누적 = 미확인(0원 아님)", /미확인/.test(mtd) && !/0원|0 원/.test(mtd), mtd);
check("[6] 주당 필요 = 미확인(목표로 계산하지 않음)", /미확인/.test(kpi.find(function (t) { return /주당 필요/.test(t); })));
check("[6] 전주 결과·금주 실적 = 미확인", /미확인/.test(kpi.find(function (t) { return /전주 결과/.test(t); })) && /미확인/.test(kpi.find(function (t) { return /금주 현재 실적/.test(t); })));
const row = env.d.querySelector('tr[data-item="1"]');
check("[6] 쇼핑몰 연결 줄 결과 = 미확인, 직접 입력 칸으로 바뀌지 않음", /미확인/.test(row.querySelector(".pj-meet-c-result").textContent) && !row.querySelector(".pj-meet-c-result input"));
check("[6] 이번주 실적 미확인 · 달성률 비움", /미확인/.test(row.querySelector(".pj-meet-week-slot").textContent) && row.querySelector("[data-rate]").textContent.trim() === "");
check("[6] 회의록 입력은 그대로 가능", !!row.querySelector("textarea.pj-meet-text") && !!env.d.getElementById("pj-meet-target"));
check("[6] 조회 실패 안내 문구", /미확인/.test(env.d.querySelector(".pj-meet-perf-warn").textContent));
});
await section(async function () { // 지난주 리뷰 머리 = 지난주(9/21~) — 지난주 회의록에 없는 줄 안내
const env = makeEnv(PAGE.meeting_admin, MEET_URL, { session: { "pj_meet_sync:2026-09-28": JSON.stringify({ at: Date.now(), state: "ok" }) } });
meetServer(env);
await boot(env);
check("[5] 지난주 리뷰 머리 = 09/21 ~ 09/27", /09\/21 ~ 09\/27/.test(env.d.querySelector("th.is-prev").textContent));
check("[5] 새 줄 = 지난주 회의록에 없는 줄", /지난주 회의록에 없는 줄/.test(env.d.querySelector('tr[data-item="3"]').textContent));
});
// ════════════════════ [8] 구역·항목 메뉴 — ⋮ 버튼(키보드·터치) + 우클릭 ════════════════════
await section(async function () {
const env = makeEnv(PAGE.goals_admin, GOALS_URL, { promptAnswer: "줄 이름" });
goalsServer(env);
await boot(env);
const btns = env.d.querySelectorAll(".pj-goal-menu-btn");
check("[8] 관리자: 구역 2 + 항목 4 메뉴 버튼", btns.length === 6, btns.length);
const areaBtn = env.d.querySelector('tbody[data-area-id="1"] .pj-goal-menu-btn[data-goal-menu="area"]');
check("[8] 접근성 이름", areaBtn.getAttribute("aria-label") === "상품 구역 메뉴" && areaBtn.getAttribute("aria-haspopup") === "menu");
check("[8] Tab 으로 갈 수 있는 버튼", areaBtn.tagName === "BUTTON" && areaBtn.tabIndex === 0);
areaBtn.focus();
areaBtn.dispatchEvent(new env.w.MouseEvent("click", { bubbles: true, cancelable: true, detail: 0 })); // Enter/Space → click(detail 0)
let menu = env.d.querySelector(".pj-ctxmenu");
check("[8] 키보드로 열기 → role=menu, 첫 항목 포커스", menu && menu.getAttribute("role") === "menu" && env.d.activeElement === menu.querySelector(".pj-ctxmenu-item"));
check("[8] aria-expanded=true", areaBtn.getAttribute("aria-expanded") === "true");
key(env, env.d.activeElement, "ArrowDown");
check("[8] ↓ 로 다음 항목", env.d.activeElement === menu.querySelectorAll(".pj-ctxmenu-item")[1]);
await settle();
key(env, env.d.activeElement, "Escape");
check("[8] Esc 닫기 → 버튼으로 포커스 복귀", !env.d.querySelector(".pj-ctxmenu") && env.d.activeElement === areaBtn && areaBtn.getAttribute("aria-expanded") === "false");
// 키보드로 항목 실행 — "줄 추가(구역 맨 아래)"
areaBtn.dispatchEvent(new env.w.MouseEvent("click", { bubbles: true, cancelable: true, detail: 0 }));
menu = env.d.querySelector(".pj-ctxmenu");
const add = Array.from(menu.querySelectorAll(".pj-ctxmenu-item")).find(function (b) { return /줄 추가/.test(itemLabel(b)); });
add.focus(); add.click();
await settle(); await wait(20); await settle();
check("[8] 메뉴 항목 실행 → 줄 추가 API", env.calls.some(function (c) { return c.method === "POST" && /areas\/1\/rows$/.test(c.url); }));
// 터치(탭) — 포인터 터치 뒤 click(detail 1)
const rowBtn = env.d.querySelector('tr[data-row-id="20"] .pj-goal-menu-btn[data-goal-menu="row"]');
rowBtn.dispatchEvent(new env.w.Event("pointerdown", { bubbles: true }));
rowBtn.dispatchEvent(new env.w.MouseEvent("click", { bubbles: true, cancelable: true, detail: 1 }));
menu = env.d.querySelector(".pj-ctxmenu");
const labels = menu ? Array.from(menu.querySelectorAll(".pj-ctxmenu-item")).map(itemLabel) : [];
check("[8] 탭(click) → 줄 메뉴(우클릭과 같은 항목)", labels.indexOf("위에 줄 추가") >= 0 && labels.indexOf("아래에 줄 추가") >= 0 && labels.indexOf("줄 삭제") >= 0, labels);
check("[8] 터치로 연 메뉴도 ↑↓·Esc 가능(메뉴에 포커스)", env.d.activeElement === menu);
// 다시 누르면 닫힘(토글) — 마우스는 mousedown 이 먼저 닫는다
env.d.dispatchEvent(new env.w.MouseEvent("mousedown", { bubbles: true }));
rowBtn.dispatchEvent(new env.w.MouseEvent("mousedown", { bubbles: true }));
await settle();
rowBtn.dispatchEvent(new env.w.MouseEvent("click", { bubbles: true, cancelable: true, detail: 1 }));
check("[8] 열린 메뉴 버튼 다시 누름 = 닫힘", !env.d.querySelector(".pj-ctxmenu"));
// 우클릭은 그대로
env.d.querySelector('tbody[data-area-id="2"] th.pj-goal-area-name').dispatchEvent(new env.w.MouseEvent("contextmenu", { bubbles: true, cancelable: true, clientX: 3, clientY: 3 }));
const ctx = Array.from(env.d.querySelectorAll(".pj-ctxmenu-item")).map(itemLabel);
check("[8] 우클릭 메뉴 그대로(색·위로·줄 추가·삭제)", ctx.indexOf("색 바꾸기") >= 0 && ctx.indexOf("위로") >= 0 && ctx.indexOf("영역 삭제") >= 0, ctx);
key(env, env.d.body, "Escape");
// 이름 칸 — Tab 으로 와서 Enter = 이름 수정, 한글 조합 중 Enter 는 무시
const name = env.d.querySelector('tr[data-row-id="10"] .pj-goal-row-text');
check("[8] 이름 칸 Tab 접근(tabindex=0)", name.getAttribute("tabindex") === "0");
name.focus();
key(env, name, "Enter", { isComposing: true });
check("[8] 한글 조합 중 Enter 는 편집 시작 안 함", name.isContentEditable !== true && name.contentEditable !== "true");
key(env, name, "Enter");
check("[8] Enter → 이름 수정", name.contentEditable === "true");
key(env, name, "Escape");
});
await section(async function () {
const env = makeEnv(PAGE.goals_ro, GOALS_URL);
goalsServer(env);
await boot(env);
check("[8] 보기 전용: 메뉴 버튼·이름 편집 없음", !env.d.querySelector(".pj-goal-menu-btn") && !env.d.querySelector("[data-goal-edit]"));
const th = env.d.querySelector("th.pj-goal-area-name");
th.dispatchEvent(new env.w.MouseEvent("contextmenu", { bubbles: true, cancelable: true }));
check("[8] 보기 전용: 우클릭 편집 메뉴 없음", !env.d.querySelector(".pj-ctxmenu"));
// 분기 접기는 보기 전용도
const qth = env.d.querySelector('th.pj-goal-fold-th[data-h="1"]');
qth.dispatchEvent(new env.w.MouseEvent("click", { bubbles: true }));
check("[회귀] 분기 머리 클릭 → 접힘(보기 전용도)", qth.classList.contains("is-folded") && env.d.querySelector('td.pj-goal-m[data-h="1"]').classList.contains("is-shrunk"));
check("[회귀] 접기 상태 기억", /"1":true/.test(env.w.localStorage.getItem("pj_goal_fold_q") || ""));
});
await section(async function () { // 회귀 — 열 너비 끌기·고정 열 변수·스크롤 위치 되살리기
const env = makeEnv(PAGE.goals_admin, GOALS_URL, { session: { pj_goal_scroll: JSON.stringify(["/project/goals/2026", 120, 45]) } });
goalsServer(env);
await boot(env);
const pane = env.d.getElementById("pj-goal-pane");
check("[회귀] 스크롤 위치 되살림", pane.scrollLeft === 120 && pane.scrollTop === 45, [pane.scrollLeft, pane.scrollTop]);
const h = env.d.querySelector('.pj-goal-colresize[data-col="c1"]');
h.dispatchEvent(new env.w.MouseEvent("mousedown", { bubbles: true, button: 0, clientX: 100 }));
env.d.dispatchEvent(new env.w.MouseEvent("mousemove", { bubbles: true, clientX: 140 }));
env.d.dispatchEvent(new env.w.MouseEvent("mouseup", { bubbles: true }));
const table = env.d.getElementById("pj-goal-table");
check("[회귀] 1열 너비 끌기 → --goal-c1-w 112px·기억", table.style.getPropertyValue("--goal-c1-w") === "112px" && /"c1":112/.test(env.w.localStorage.getItem("pj_goal_col_w") || ""),
table.style.getPropertyValue("--goal-c1-w"));
});
// ════════════════════ [9] 매출 자동 갱신 — 정상 조용히 · 실패/일부 실패 안내 + 재시도 · 권한 없음 ════════════════════
await section(async function () {
const env = makeEnv(PAGE.meeting_admin, MEET_URL);
const st = meetServer(env);
await boot(env);
await wait(20); await settle();
const box = env.d.getElementById("pj-meet-sync");
check("[9] 정상 갱신 → 안내 숨김(조용)", st.syncCalls === 1 && box.hidden === true);
check("[9] 갱신 뒤 숫자 칸 다시 그림(GET)", (st.gets || 0) >= 1);
});
await section(async function () {
const env = makeEnv(PAGE.meeting_admin, MEET_URL);
const st = meetServer(env, { syncHook: function (body) {
return { body: { joined: false, job: { id: "j1", finished: true, from: body.from, to: body.to,
shops: [{ name: "쿠팡", state: "done", active: true }, { name: "네이버", state: "error", label: "인증 오류", active: true }], overall: {} } } };
} });
await boot(env);
const ta = env.d.querySelector('tr[data-item="1"] textarea.pj-meet-text');
ta.focus(); type(env, ta, "editing while sync");
await wait(20); await settle();
const box = env.d.getElementById("pj-meet-sync"), btn = env.d.getElementById("pj-meet-sync-btn");
check("[9] 일부 실패 → 안내 보임 + 실패 쇼핑몰 이름", !box.hidden && box.dataset.state === "partial" && /네이버\(인증 오류\)/.test(box.textContent), box.textContent);
check("[9] 일부 실패를 전체 성공처럼 쓰지 않음 + 서버 기록 시각", !/갱신 성공 10\/01 14:20.*전체/.test(box.textContent) && /마지막 갱신 성공 10\/01 14:20/.test(box.textContent), box.textContent);
check("[9] 재시도 버튼", !btn.hidden);
check("[9] 갱신·다시 그리기 중에도 편집 글 유지", ta.value === "editing while sync");
const rec = JSON.parse(env.w.sessionStorage.getItem("pj_meet_sync:2026-09-28"));
check("[9] 기록 = partial(성공으로 기록하지 않음)", rec.state === "partial");
btn.click(); await wait(20); await settle();
check("[9] 재시도 → 다시 부름", st.syncCalls === 2);
});
await section(async function () {
const env = makeEnv(PAGE.meeting_admin, MEET_URL);
const st = meetServer(env, { syncHook: function () { return { status: 500, body: { detail: "서버 오류" } }; } });
await boot(env);
await wait(20); await settle();
const box = env.d.getElementById("pj-meet-sync");
check("[9] 실패 → 식별 가능한 안내 + 재시도", !box.hidden && box.dataset.state === "error" && /실패/.test(box.textContent) && !env.d.getElementById("pj-meet-sync-btn").hidden, box.textContent);
st.syncHook = null;
env.d.getElementById("pj-meet-sync-btn").click(); await wait(20); await settle();
check("[9] 재시도 성공 → 안내 사라짐", box.hidden === true);
});
await section(async function () {
const env = makeEnv(PAGE.meeting_admin, MEET_URL);
const st = meetServer(env, { syncHook: function () { return { status: 403, body: { detail: "권한 없음" } }; } });
await boot(env);
await wait(20); await settle();
const box = env.d.getElementById("pj-meet-sync");
check("[9] 403 → 권한 없음 설명, 재시도 버튼 없음", box.dataset.state === "noperm" && env.d.getElementById("pj-meet-sync-btn").hidden);
check("[9] 403 기억 → 같은 세션 자동 재호출 안 함", JSON.parse(env.w.sessionStorage.getItem("pj_meet_sync:2026-09-28")).state === "noperm");
void st;
});
await section(async function () { // 권한 없음(서버가 can_sync=0) — API 를 아예 부르지 않는다
const env = makeEnv(PAGE.meeting_ro, MEET_URL);
const st = meetServer(env, { page: PAGE.meeting_ro });
await boot(env);
await wait(20); await settle();
check("[9] 실적 권한 없음 → sync API 호출 0", !st.syncCalls && !env.calls.some(function (c) { return /performance/.test(c.url); }));
check("[9] 권한 없음 설명(저장된 실적·마지막 갱신 시각)", /권한이 없어/.test(env.d.getElementById("pj-meet-sync").textContent) && /10\/01 14:20/.test(env.d.getElementById("pj-meet-sync").textContent));
check("[9] 보기 전용: 입력칸 없음", !env.d.querySelector("textarea.pj-meet-text") && !env.d.getElementById("pj-meet-target"));
});
await section(async function () { // 10분 제한 — 최근 기록이 있으면 다시 부르지 않고 그 상태만(일부 실패면 안내 유지)
const env = makeEnv(PAGE.meeting_admin, MEET_URL, { session: { "pj_meet_sync:2026-09-28": JSON.stringify({ at: Date.now(), state: "partial", bad: ["네이버"] }) } });
const st = meetServer(env);
await boot(env);
await wait(20); await settle();
check("[9] 10분 안 = 다시 부르지 않음, 일부 실패 안내 유지", !st.syncCalls && env.d.getElementById("pj-meet-sync").dataset.state === "partial");
});
await section(async function () { // 다른 사람 업데이트에 합류했는데 기간이 이 주를 다 덮지 못하면 한 번 더
const env = makeEnv(PAGE.meeting_admin, MEET_URL);
let n = 0;
const st = meetServer(env, { syncHook: function (body) {
n++;
if (n === 1) return { body: { joined: true, job: { id: "other", finished: true, from: "2026-09-29", to: "2026-10-01", shops: [], overall: {} } } };
return { body: { joined: false, job: { id: "mine", finished: true, from: body.from, to: body.to, shops: [], overall: {} } } };
} });
await boot(env);
await wait(20); await settle();
check("[9] 합류한 작업이 기간을 못 덮으면 이 주 기간으로 한 번 더", st.syncCalls === 2 && env.d.getElementById("pj-meet-sync").hidden);
});
await section(async function () { // 회귀 — 참석자 고르기(칩·저장)
const html = PAGE.meeting_admin.replace("window.PJ_MEET_MEMBERS = []", 'window.PJ_MEET_MEMBERS = [{"email":"a@test.local","name":"에이","avatar":""}]');
const env = makeEnv(html, MEET_URL, { session: { "pj_meet_sync:2026-09-28": JSON.stringify({ at: Date.now(), state: "ok" }) } });
const st = meetServer(env);
await boot(env);
env.d.getElementById("pj-meet-attend-add").click();
const cb = env.d.querySelector('.pj-meet-pick input[type=checkbox][data-email="a@test.local"]');
cb.checked = true; cb.dispatchEvent(new env.w.Event("change", { bubbles: true }));
await settle();
check("[회귀] 참석자 고르기 → 칩 + 저장", !!env.d.querySelector('.pj-meet-chip[data-key="a@test.local"]') && st.head.attendees === "a@test.local", st.head);
});
await section(async function () { // 선택한 글자만 서식·서식 초기화·저장·다시 그리기
const env = makeEnv(PAGE.goals_admin, "http://localhost/project/goals/2026"); const st = goalsServer(env); await boot(env);
const d = env.d, w = env.w, editor = d.querySelector('.pj-goal-text[data-row="10"][data-month="1"]');
type(env, editor, "앞 선택 뒤"); editor.focus();
const range = d.createRange(); range.setStart(editor.firstChild, 2); range.setEnd(editor.firstChild, 4);
w.getSelection().removeAllRanges(); w.getSelection().addRange(range); fire(env, editor, "mouseup");
const format = function (name, value, event) { const el = d.querySelector('[data-goal-format="' + name + '"]'); el.value = value; fire(env, el, event || "change"); };
format("bold", "700"); format("color", "#ff0000", "input"); format("size", "20");
let runs = w.PJGoalText.readRuns(editor);
check("[서식] 선택한 두 글자에만 색·굵기·크기", runs.length === 3 && runs[0].text === "앞 " && runs[1].text === "선택" && runs[1].bold === true && runs[1].color === "#ff0000" && runs[1].size === 20 && !runs[2].bold, runs);
fire(env, editor, "blur"); await settle();
check("[서식] 텍스트 조각을 기존 셀 API에 저장", st.cells["10:1"].startsWith("pj-rich:v1:") && JSON.parse(st.cells["10:1"].slice(11))[1].size === 20);
const persisted = st.cells["10:1"];
d.querySelector('[data-goal-format="reset"]').click(); fire(env, editor, "blur"); await settle();
check("[서식] 선택 서식 초기화는 글을 유지하고 평문 저장", editor.textContent === "앞 선택 뒤" && st.cells["10:1"] === "앞 선택 뒤");
editor.value = persisted; fire(env, editor, "input"); fire(env, editor, "blur"); await settle();
d.getElementById("pj-goal-area-add").click(); await settle(); await wait(20); await settle();
const fresh = d.querySelector('.pj-goal-text[data-row="10"][data-month="1"]');
check("[서식] 표 다시 그리기에도 선택 서식 유지", fresh !== editor && w.PJGoalText.readRuns(fresh)[1].size === 20);
fresh.focus();
const plainRange = d.createRange(); plainRange.setStart(fresh.firstChild, 0); plainRange.setEnd(fresh.firstChild, 1);
w.getSelection().removeAllRanges(); w.getSelection().addRange(plainRange); fire(env, fresh, "mouseup");
check("[서식] 새 평문 선택은 도구 값을 기본값으로 표시", d.querySelector('[data-goal-format="bold"]').value === "400" && d.querySelector('[data-goal-format="size"]').value === "14");
plainRange.collapse(true); w.getSelection().removeAllRanges(); w.getSelection().addRange(plainRange); fire(env, fresh, "keyup");
check("[서식] 글자 선택을 해제하면 이전 선택에 적용하지 않음", d.querySelector('[data-goal-format="reset"]').disabled);
});
clearTimeout(WATCHDOG);
const realUnhandled = unhandled.filter(function (m) { return !/Not implemented/.test(m); });
check("처리 안 된 Promise 거부 없음", realUnhandled.length === 0, realUnhandled);
console.log(fails.length ? fails.length + " FAIL" : "ALL PASS");
process.exit(fails.length ? 1 : 0);
})().catch(function (e) { console.error(e); process.exit(1); });