fix(project): 목표·주간 회의록 저장 손실·지난주 연결·실적 미확인 수정 (점검 9건)
- 칸별 자동 저장 createFieldSaver: 같은 칸 요청 직렬화, 보낸 값만 saved, 늦은 응답이 새 초안을 덮지 않음, 실패 시 초안·dirty 유지(빨간 테두리), localStorage 초안 백업·되살리기, 페이지 떠남 keepalive + 이탈 경고 - 목표 표: 저장 실패면 영역·줄·병합 작업과 표 교체 중단, 받는 사이 입력 보호 - 회의록: 금주 목표 저장 뒤 새로고침 대신 숫자 칸만 다시(차례 번호로 옛 응답 버림), 이번주 실적 %는 서버 확정 목표로 즉시 재계산 - 지난주 = 정확히 7일 전 주의 같은 연결키 줄(line_key, 마이그레이션 018), 역순 생성·이름 변경·삭제 후 재생성에도 연결, 이름 추정 연결 없음 - 실적 조회 장애를 0원 대신 미확인으로(목록·매출·부분 실패 구분) - 구역·항목 ⋮ 메뉴 버튼(키보드·터치), 메뉴 키보드 탐색·포커스 복귀 - 매출 갱신 실패·일부 실패 안내 + 재시도, 서버 기록 갱신 시각, 권한 없으면 호출 안 함 - 테스트: Python 통합(역순 생성·실적 장애), 018 백필, jsdom UI 106건 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -13,3 +13,15 @@ node tests/js/box_calc_ui.test.js
|
||||
```
|
||||
|
||||
성공하면 마지막 줄에 `ALL PASS`, 실패하면 실패한 항목명이 출력되고 종료코드 1.
|
||||
|
||||
# 연간 목표·주간 회의록 UI 테스트 (jsdom)
|
||||
|
||||
`goals.html`·`goal_meeting.html` + `static/project.js` — 칸 저장 직렬화·늦은 응답·503·초안 보호·구조 변경 중단·이번주 실적 %·
|
||||
실적 미확인 표시·⋮ 메뉴(키보드·터치 클릭)·매출 갱신 안내를 가짜 서버(지연·실패를 직접 만듦)로 검증한다.
|
||||
|
||||
```bash
|
||||
python tests/js/render_goals.py # → tests/js/.out/goals_*.html · meeting_*.html
|
||||
node tests/js/goals_meeting_ui.test.js # jsdom 필요(npm install jsdom 또는 NODE_PATH)
|
||||
```
|
||||
|
||||
실제 브라우저 레이아웃·입력기·터치 기기는 아니다(그건 헤드리스 크롬으로 따로 확인).
|
||||
|
||||
@@ -0,0 +1,664 @@
|
||||
// 연간 목표(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(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(/(<textarea class="pj-goal-text"[^>]*data-row="(\d+)" data-month="(\d+)"[^>]*>)([\s\S]*?)(<\/textarea>)/g,
|
||||
function (all, open, row, month, text, close) {
|
||||
const k = row + ":" + month;
|
||||
return open + (k in st.cells ? st.cells[k].replace(/&/g, "&").replace(/</g, "<") : 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"><textarea class="pj-goal-text" rows="1" data-row="30" data-month="0"></textarea></td>' +
|
||||
"</tr></tbody>$2");
|
||||
}
|
||||
return { text: html };
|
||||
});
|
||||
return st;
|
||||
}
|
||||
|
||||
// ── 가짜 서버 — 회의록 ────────────────────────────────────────────────
|
||||
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('textarea.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('textarea.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('textarea.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('textarea.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('textarea.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('textarea.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('textarea.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);
|
||||
});
|
||||
|
||||
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); });
|
||||
@@ -0,0 +1,129 @@
|
||||
"""연간 목표(goals.html)·주간 회의록(goal_meeting.html)을 테스트용 HTML 로 렌더한다(erp_base.html 은 최소 스텁, 가상의 데이터).
|
||||
|
||||
python tests/js/render_goals.py # → tests/js/.out/goals_admin.html · goals_ro.html · meeting_admin.html · meeting_err.html · meeting_ro.html
|
||||
|
||||
칸 배치는 실제 라우터 도우미(_goal_area_layout·_goal_label_spans)로 만든다. DB·실적 모듈은 쓰지 않는다.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import copy
|
||||
import io
|
||||
import os
|
||||
import sys
|
||||
|
||||
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.project import store # noqa: E402
|
||||
from app.modules.project.router import _goal_area_layout, _goal_label_spans # noqa: E402
|
||||
|
||||
BASE_STUB = ("{% block head_extra %}{% endblock %}<body>{% block topbar_actions %}{% endblock %}"
|
||||
"<main class='erp-page'>{% block content %}{% endblock %}</main></body>")
|
||||
ME = "me@test.local"
|
||||
|
||||
|
||||
def board() -> dict:
|
||||
rows_a = [{"id": 10, "label": "신제품", "cells": {0: "연간 계획", 1: "original"}, "merges": {}},
|
||||
{"id": 11, "label": "리뉴얼", "cells": {}, "merges": {}}]
|
||||
rows_b = [{"id": 20, "label": "쿠팡", "cells": {2: "행사"}, "merges": {}},
|
||||
{"id": 21, "label": "", "cells": {}, "merges": {}}]
|
||||
areas = [{"id": 1, "name": "상품", "color": "#fde2e4", "rows": rows_a},
|
||||
{"id": 2, "name": "유통", "color": "", "rows": rows_b}]
|
||||
for a in areas:
|
||||
_goal_area_layout(a["rows"], 10)
|
||||
_goal_label_spans(a["rows"])
|
||||
return {
|
||||
"year": 2026, "sales_unit": "만원", "halves": True, "quarters": True,
|
||||
"metrics": {"sales": {"target_label": {1: "100", 2: "100"}, "actual_label": {1: "50"}},
|
||||
"roas": {"target_label": {}, "actual_label": {}}},
|
||||
"areas": areas,
|
||||
}
|
||||
|
||||
|
||||
def goals_ctx(admin: bool) -> dict:
|
||||
return {
|
||||
"user": {"email": ME, "is_super_admin": False}, "is_admin": admin, "nav_projects": [], "goal_years": [2026],
|
||||
"goal_year_active": 2026, "my_open_total": 0, "mention_unread": 0, "color_palette": ["#4573d2"],
|
||||
"project_icons": ["folder"], "goals_enabled": True, "goal_year": 2026, "board": board(),
|
||||
"months": list(range(1, 13)),
|
||||
"quarters": [(q, list(range(q * 3 - 2, q * 3 + 1)), store.GOAL_QUARTER_COL[q], f"{q}분기") for q in (1, 2, 3, 4)],
|
||||
"this_month": 10, "goal_area_colors": list(store.GOAL_AREA_COLORS),
|
||||
}
|
||||
|
||||
|
||||
def meeting_view(err: bool) -> dict:
|
||||
"""회의록 2026-09-28 주 — 유통 쿠팡(쇼핑몰 연결, 이번주 실적 100, 정량 목표 100), 상품1(직접 입력 결과)."""
|
||||
prev_cou = {"id": 901, "week_start": "2026-09-21", "content": "지난주 행사", "target_amount": 100, "result_amount": None,
|
||||
"status": "", "marketplace_code": "coupang", "period": "9/21~9/27", "not_started": False,
|
||||
"market_off": False, "auto_error": err, "auto_result": None if err else 80,
|
||||
"result": None if err else 80, "market_name": "쿠팡"}
|
||||
prev_p1 = {"id": 902, "week_start": "2026-09-21", "content": "샘플", "target_amount": 200, "result_amount": 100,
|
||||
"status": "partial", "marketplace_code": "", "period": "9/21~9/27", "not_started": False,
|
||||
"market_off": False, "auto_error": False, "auto_result": None, "result": 100, "market_name": ""}
|
||||
it_cou = {"id": 1, "section": "유통", "section_color": "", "label": "쿠팡", "content": "original",
|
||||
"target_amount": 100, "marketplace_code": "coupang", "market_name": "쿠팡", "market_off": False,
|
||||
"market_unknown": err, "week_auto": None if err else 100, "week_error": err,
|
||||
"prev": prev_cou, "rate": None if err else 80.0}
|
||||
it_p1 = {"id": 2, "section": "상품", "section_color": "#fde2e4", "label": "상품1", "content": "",
|
||||
"target_amount": None, "marketplace_code": "", "market_name": "", "market_off": False,
|
||||
"market_unknown": False, "week_auto": None, "week_error": False, "prev": prev_p1, "rate": 50.0}
|
||||
it_new = {"id": 3, "section": "상품", "section_color": "#fde2e4", "label": "새 줄", "content": "",
|
||||
"target_amount": None, "marketplace_code": "", "market_name": "", "market_off": False,
|
||||
"market_unknown": False, "week_auto": None, "week_error": False, "prev": None, "rate": None}
|
||||
meeting = {"week_start": "2026-09-28", "week_target": 1000, "attendees": "", "notes": "메모 원본",
|
||||
"items": [it_p1, it_new, it_cou],
|
||||
"sections": [{"name": "상품", "color": "#fde2e4", "rows": [it_p1, it_new]},
|
||||
{"name": "유통", "color": "", "rows": [it_cou]}]}
|
||||
head = {"sales_unit": "원", "sales_target": 10000.0, "roas_target": None, "month_target_won": 10000,
|
||||
"mtd": None if err else 0, "mtd_end": "2026-09-27", "weeks_left": 1,
|
||||
"need_per_week": None if err else 10000, "prev_target": 500, "prev_exists": True,
|
||||
"prev_result": None if err else 0, "week_result": None if err else 0,
|
||||
"perf": True, "perf_state": "error" if err else "ok",
|
||||
"unknown": ["mtd", "prev_result", "week_result"] if err else [],
|
||||
"fresh_oldest": "" if err else "10/01 14:20",
|
||||
"fresh_tip": "" if err else "매출 자료(실적 모듈) 쇼핑몰별 마지막 갱신 성공 — 쿠팡 10/01 14:20"}
|
||||
return {"meeting": meeting, "head": head, "markets": [] if err else [{"code": "coupang", "name": "쿠팡"}]}
|
||||
|
||||
|
||||
def meeting_ctx(admin: bool, err: bool, can_sync: bool = True) -> dict:
|
||||
view = meeting_view(err)
|
||||
return {
|
||||
"user": {"email": ME, "is_super_admin": False}, "is_admin": admin, "nav_projects": [], "goal_years": [2026],
|
||||
"goal_year_active": 2026, "my_open_total": 0, "mention_unread": 0, "color_palette": ["#4573d2"],
|
||||
"project_icons": ["folder"], "goal_year": 2026, "goal_month": 9, "meetings_enabled": True,
|
||||
"weeks": [{"start": "2026-09-28", "end": "2026-10-04", "n": 4, "label": "9/28~10/4", "has": True, "now": False,
|
||||
"days": []}],
|
||||
"cal_weeks": [], "week": "2026-09-28", "week_n": 4, "week_end": "2026-10-04",
|
||||
"prev_week": "2026-09-21", "prev_week_end": "2026-09-27", "sync_from": "2026-09-21", "sync_to": "2026-10-01",
|
||||
"can_sync": can_sync, "meeting_status": store.MEETING_STATUS, "meet_members": [], "month_plan": None,
|
||||
"attendee_list": [], **copy.deepcopy(view),
|
||||
}
|
||||
|
||||
|
||||
def main() -> None:
|
||||
env = jinja2.Environment(loader=jinja2.ChoiceLoader([
|
||||
jinja2.DictLoader({"erp_base.html": BASE_STUB}),
|
||||
jinja2.FileSystemLoader(os.path.join(ROOT, "app", "modules", "project", "templates")),
|
||||
]))
|
||||
env.globals["pj_kr_holidays"] = {}
|
||||
os.makedirs(OUT_DIR, exist_ok=True)
|
||||
pages = {
|
||||
"goals_admin.html": ("project/goals.html", goals_ctx(True)),
|
||||
"goals_ro.html": ("project/goals.html", goals_ctx(False)),
|
||||
"meeting_admin.html": ("project/goal_meeting.html", meeting_ctx(True, False)),
|
||||
"meeting_err.html": ("project/goal_meeting.html", meeting_ctx(True, True)),
|
||||
"meeting_ro.html": ("project/goal_meeting.html", meeting_ctx(False, False, can_sync=False)),
|
||||
}
|
||||
for name, (tpl, ctx) in pages.items():
|
||||
html = env.get_template(tpl).render(**ctx)
|
||||
path = os.path.join(OUT_DIR, name)
|
||||
io.open(path, "w", encoding="utf-8", newline="\n").write(html)
|
||||
print("rendered:", path)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,132 @@
|
||||
"""마이그레이션 018(주간 회의록 줄 연결키 line_key) 백필 검증 — 로컬 테스트용 PostgreSQL 에서만.
|
||||
|
||||
예전 코드가 만든 데이터 모양(carry_from 사슬·역순 생성·끊긴 연결·같은 이름 줄)을 임시 스키마에 만들고
|
||||
scripts/sql/project_db_018_meeting_line_keys.sql 을 두 번 돌려(멱등) 결과를 확인한다.
|
||||
전부 한 트랜잭션 안에서 하고 마지막에 ROLLBACK — 테스트 DB 에 아무것도 남기지 않는다(DROP 없음).
|
||||
|
||||
PROJECT_TEST_DB_URL=postgresql://postgres@127.0.0.1:55432/project_db \
|
||||
python tests/test_meeting_line_keys_migration.py
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import sys
|
||||
import uuid
|
||||
from datetime import date, timedelta
|
||||
from urllib.parse import urlparse
|
||||
|
||||
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
DSN = os.getenv("PROJECT_TEST_DB_URL", "")
|
||||
ENABLED = bool(DSN) and urlparse(DSN).hostname in ("localhost", "127.0.0.1")
|
||||
|
||||
DDL = """
|
||||
CREATE TABLE goal_meetings (
|
||||
week_start DATE PRIMARY KEY CHECK (EXTRACT(ISODOW FROM week_start) = 1),
|
||||
week_target BIGINT NULL, attendees TEXT NOT NULL DEFAULT '', notes TEXT NOT NULL DEFAULT '',
|
||||
created_by TEXT NOT NULL DEFAULT '', created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
updated_by TEXT NOT NULL DEFAULT '', updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
CREATE TABLE goal_meeting_items (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
week_start DATE NOT NULL REFERENCES goal_meetings(week_start) ON DELETE CASCADE,
|
||||
section TEXT NOT NULL DEFAULT '', section_color TEXT NOT NULL DEFAULT '', label TEXT NOT NULL DEFAULT '',
|
||||
content TEXT NOT NULL DEFAULT '', target_amount BIGINT NULL, result_amount BIGINT NULL,
|
||||
status TEXT NOT NULL DEFAULT '', marketplace_code TEXT NOT NULL DEFAULT '',
|
||||
carry_from BIGINT NULL REFERENCES goal_meeting_items(id) ON DELETE SET NULL,
|
||||
sort_order INT NOT NULL DEFAULT 0, updated_by TEXT NOT NULL DEFAULT '', updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
"""
|
||||
|
||||
|
||||
def migration_sql() -> str:
|
||||
"""018 파일에서 psql 메타 명령(\\set·\\connect)과 BEGIN/COMMIT 을 뺀 본문 — 바깥 트랜잭션(ROLLBACK) 안에서 돌린다."""
|
||||
path = os.path.join(ROOT, "scripts", "sql", "project_db_018_meeting_line_keys.sql")
|
||||
with open(path, encoding="utf-8") as fh:
|
||||
lines = [ln for ln in fh.read().splitlines()
|
||||
if not ln.startswith("\\") and ln.strip() not in ("BEGIN;", "COMMIT;")]
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def main() -> int:
|
||||
if not ENABLED:
|
||||
print("SKIP: PROJECT_TEST_DB_URL(localhost) not set")
|
||||
return 0
|
||||
import psycopg
|
||||
from psycopg.rows import dict_row
|
||||
|
||||
schema = "mig018_" + uuid.uuid4().hex[:8]
|
||||
W = [date(2026, 9, 7) + timedelta(days=7 * i) for i in range(5)] # 9/7 9/14 9/21 9/28 10/5 (월요일)
|
||||
with psycopg.connect(DSN, row_factory=dict_row) as conn: # autocommit 아님 — 끝에 rollback
|
||||
conn.execute(f"CREATE SCHEMA {schema}")
|
||||
conn.execute(f"SET LOCAL search_path TO {schema}")
|
||||
conn.execute(DDL)
|
||||
for w in W:
|
||||
conn.execute("INSERT INTO goal_meetings (week_start) VALUES (%s)", (w,))
|
||||
|
||||
def add(week, section, label, carry=None, order=0):
|
||||
return conn.execute(
|
||||
"INSERT INTO goal_meeting_items (week_start, section, label, carry_from, sort_order) "
|
||||
"VALUES (%s,%s,%s,%s,%s) RETURNING id", (week, section, label, carry, order),
|
||||
).fetchone()["id"]
|
||||
|
||||
# 9/14 = 양식으로 처음(사슬 뿌리) — 같은 구역에 같은 이름 "기타" 두 줄
|
||||
a_cou = add(W[1], "유통", "쿠팡", order=0)
|
||||
a_et1 = add(W[1], "유통", "기타", order=1)
|
||||
a_et2 = add(W[1], "유통", "기타", order=2)
|
||||
a_meta = add(W[1], "마케팅", "메타", order=3)
|
||||
# 9/28 을 먼저 만듦(예전 코드: 앞선 가장 가까운 9/14 를 원본으로) → 9/21 을 나중에(역시 9/14 원본)
|
||||
b_cou = add(W[3], "유통", "쿠팡", a_cou, 0)
|
||||
b_et1 = add(W[3], "유통", "기타", a_et1, 1)
|
||||
b_et2 = add(W[3], "유통", "기타", a_et2, 2)
|
||||
b_meta = add(W[3], "마케팅", "메타 광고", a_meta, 3) # 이름 바꾼 줄
|
||||
b_new = add(W[3], "유통", "쿠팡", None, 4) # 9/28 에 새로 추가한 같은 이름 줄
|
||||
c_cou = add(W[2], "유통", "쿠팡", a_cou, 0)
|
||||
c_et1 = add(W[2], "유통", "기타", a_et1, 1)
|
||||
c_et2 = add(W[2], "유통", "기타", a_et2, 2)
|
||||
c_meta = add(W[2], "마케팅", "메타", a_meta, 3)
|
||||
# 10/5 = 9/28 원본 — 9/28 의 새 줄도 이어받음
|
||||
d_cou = add(W[4], "유통", "쿠팡", b_cou, 0)
|
||||
d_new = add(W[4], "유통", "쿠팡", b_new, 1)
|
||||
# 9/7 = 앞 주를 지웠다 다시 만든 흔적 — 연결 끊김(carry_from NULL), 같은 이름이지만 붙이면 안 됨
|
||||
e_cou = add(W[0], "유통", "쿠팡", None, 0)
|
||||
|
||||
sql = migration_sql()
|
||||
conn.execute(sql)
|
||||
key = lambda i: conn.execute("SELECT line_key FROM goal_meeting_items WHERE id = %s", (i,)).fetchone()["line_key"] # noqa: E731
|
||||
first = {i: key(i) for i in (a_cou, b_cou, c_cou, d_cou, a_et1, a_et2, b_et1, b_et2, c_et1, c_et2,
|
||||
a_meta, b_meta, c_meta, b_new, d_new, e_cou)}
|
||||
conn.execute(sql) # 두 번째 — 멱등(키가 바뀌지 않아야)
|
||||
second = {i: key(i) for i in first}
|
||||
|
||||
checks = [
|
||||
("모든 줄에 키", conn.execute("SELECT count(*) AS n FROM goal_meeting_items WHERE line_key IS NULL").fetchone()["n"] == 0),
|
||||
("역순 생성: 9/28 쿠팡 ↔ 9/21 쿠팡 같은 키", first[b_cou] == first[c_cou] == first[a_cou] == first[d_cou]),
|
||||
("같은 이름 '기타' 두 줄은 서로 다른 키", first[a_et1] != first[a_et2]),
|
||||
("'기타' 각 줄이 자기 사슬로만", first[b_et1] == first[c_et1] == first[a_et1] and first[b_et2] == first[c_et2] == first[a_et2]),
|
||||
("이름 바꾼 줄도 같은 키", first[b_meta] == first[c_meta] == first[a_meta]),
|
||||
("새로 추가한 같은 이름 줄은 다른 키", first[b_new] != first[b_cou] and first[d_new] == first[b_new]),
|
||||
("끊긴 연결(carry_from NULL)은 이름이 같아도 붙이지 않음", first[e_cou] != first[a_cou]),
|
||||
("두 번 돌려도 같은 키(멱등)", first == second),
|
||||
("NOT NULL 제약", conn.execute(
|
||||
"SELECT is_nullable FROM information_schema.columns WHERE table_schema = %s "
|
||||
"AND table_name = 'goal_meeting_items' AND column_name = 'line_key'", (schema,)).fetchone()["is_nullable"] == "NO"),
|
||||
]
|
||||
# UNIQUE(week_start, line_key) — 같은 주 같은 키는 막힌다
|
||||
try:
|
||||
with conn.transaction():
|
||||
conn.execute("UPDATE goal_meeting_items SET line_key = %s WHERE id = %s", (first[b_cou], b_new))
|
||||
checks.append(("한 주 안 같은 키 금지(UNIQUE)", False))
|
||||
except psycopg.errors.UniqueViolation:
|
||||
checks.append(("한 주 안 같은 키 금지(UNIQUE)", True))
|
||||
conn.rollback() # 아무것도 남기지 않는다
|
||||
|
||||
bad = [n for n, ok in checks if not ok]
|
||||
for n, ok in checks:
|
||||
print(("PASS " if ok else "FAIL ") + n)
|
||||
print("ALL PASS" if not bad else f"{len(bad)} FAIL")
|
||||
return 1 if bad else 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -753,6 +753,207 @@ def test_goal_meetings():
|
||||
pass
|
||||
|
||||
|
||||
def _meet_weeks(seed: int, n: int) -> list[date]:
|
||||
"""지난 주들(실적 기간이 "진행 전"이 아니게) — test_goal_meetings(2001~2008)와 겹치지 않는 2010~2018 의 월요일 n 개."""
|
||||
base = date(2010, 1, 4) + timedelta(days=7 * ((int(RUN, 16) + seed * 60) % 400))
|
||||
assert base.weekday() == 0
|
||||
return [base + timedelta(days=7 * i) for i in range(n)]
|
||||
|
||||
|
||||
def _drop_meetings(weeks: list[date]) -> None:
|
||||
for w in weeks:
|
||||
try:
|
||||
ST.delete_meeting(week_start=w)
|
||||
except KeyError:
|
||||
pass
|
||||
|
||||
|
||||
def _create_meeting(w: date) -> None:
|
||||
r = req("POST", f"/project/api/goals/meetings/{w}", ADMIN, json={"year": w.year})
|
||||
assert r.status_code == 201, r.text
|
||||
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# [G4·G5] 회의록 "지난주" — 정확히 7일 전 주, 생성 순서·이름 변경·같은 이름·삭제/재생성과 무관(018 line_key)
|
||||
# ════════════════════════════════════════════════════════════
|
||||
def test_meeting_prev_week_links():
|
||||
"""지난주 = 정확히 7일 전 주 회의록의 같은 연결키 줄. 018 미적용이면 carry_from 이 7일 전 주일 때만."""
|
||||
w0, w1, w2, w3 = _meet_weeks(1, 4)
|
||||
_drop_meetings([w0, w1, w2, w3])
|
||||
with ST._pool.connection() as conn: # noqa: SLF001
|
||||
keyed = ST._meeting_keys(conn) # noqa: SLF001
|
||||
print(" meeting line_key(018):", "applied" if keyed else "not applied — carry_from fallback")
|
||||
try:
|
||||
# ① 역순 생성 — 다음 주(w3)를 먼저(양식), 앞 주(w2)를 나중에
|
||||
_create_meeting(w3)
|
||||
_create_meeting(w2)
|
||||
m3 = ST.get_meeting(week_start=w3)
|
||||
assert m3["prev_meeting"] is not None and m3["prev_meeting"]["week_start"] == w2.isoformat()
|
||||
if keyed:
|
||||
assert all(it["prev"] is not None for it in m3["items"]), "역순 생성인데 지난주 줄이 빠짐"
|
||||
for it in m3["items"]:
|
||||
assert it["prev"]["week_start"] == w2.isoformat()
|
||||
assert (it["prev"]["section"], it["prev"]["label"]) == (it["section"], it["label"])
|
||||
# 다른 구역의 같은 이름(마케팅 "네이버" ↔ 유통 "네이버")이 섞이지 않는다
|
||||
navers = [it for it in m3["items"] if it["label"] == "네이버"]
|
||||
assert len(navers) == 2 and len({it["prev"]["id"] for it in navers}) == 2
|
||||
assert all(it["prev"]["section"] == it["section"] for it in navers)
|
||||
else:
|
||||
assert all(it["prev"] is None for it in m3["items"]), "018 미적용 — 역순 생성 연결은 안 됨(문서화된 제한)"
|
||||
# ② 지난주(w2) 결과를 w2 줄에 저장 → w3 화면에서 보인다(그 주 데이터만)
|
||||
m2 = ST.get_meeting(week_start=w2)
|
||||
cou2 = next(it for it in m2["items"] if it["section"] == "유통" and it["label"] == "쿠팡")
|
||||
assert req("PUT", f"/project/api/goals/meeting-items/{cou2['id']}", ADMIN,
|
||||
json={"content": "w2 쿠팡 행사", "target_amount": "100", "result_amount": "50"}).status_code == 200
|
||||
cou3 = next(it for it in ST.get_meeting(week_start=w3)["items"] if it["section"] == "유통" and it["label"] == "쿠팡")
|
||||
if keyed:
|
||||
assert cou3["prev"]["id"] == cou2["id"] and cou3["prev"]["content"] == "w2 쿠팡 행사"
|
||||
# ③ 이름 변경·순서 이동에도 연결 유지
|
||||
assert req("PUT", f"/project/api/goals/meeting-items/{cou3['id']}", ADMIN, json={"label": "쿠팡 로켓"}).status_code == 200
|
||||
assert req("POST", f"/project/api/goals/meeting-items/{cou3['id']}/move", ADMIN, json={"direction": -1}).status_code == 200
|
||||
again = next(it for it in ST.get_meeting(week_start=w3)["items"] if it["id"] == cou3["id"])
|
||||
assert again["prev"]["id"] == cou2["id"]
|
||||
# ④ 같은 이름의 새 줄은 지난주와 연결되지 않고, 기존 줄 연결도 그대로
|
||||
r = req("POST", f"/project/api/goals/meetings/{w3}/items", ADMIN,
|
||||
json={"section": "유통", "label": "쿠팡", "ref_item_id": cou3["id"], "place": "below"})
|
||||
new_id = r.json()["id"]
|
||||
items3 = {it["id"]: it for it in ST.get_meeting(week_start=w3)["items"]}
|
||||
assert items3[new_id]["prev"] is None and items3[cou3["id"]]["prev"]["id"] == cou2["id"]
|
||||
# ⑤ 앞 주 삭제 → 지난주 칸 빔, 다시 만들면(앞선 회의록 없음 → 다음 주 w3 양식·키) 다시 연결
|
||||
ST.delete_meeting(week_start=w2)
|
||||
assert all(it["prev"] is None for it in ST.get_meeting(week_start=w3)["items"])
|
||||
_create_meeting(w2)
|
||||
items3 = {it["id"]: it for it in ST.get_meeting(week_start=w3)["items"]}
|
||||
assert items3[cou3["id"]]["prev"] is not None and items3[cou3["id"]]["prev"]["week_start"] == w2.isoformat()
|
||||
assert items3[cou3["id"]]["prev"]["content"] == "" # 새 회의록 — 예전 글이 섞이지 않는다
|
||||
# ⑥ 한 주 건너뜀 — w0 를 만들고 w1 없이 w2 를 보면 지난주(w1) 자료 없음(w0 결과를 지난주로 보이지 않음)
|
||||
_drop_meetings([w2, w3])
|
||||
_create_meeting(w0)
|
||||
cou0 = next(it for it in ST.get_meeting(week_start=w0)["items"] if it["section"] == "유통" and it["label"] == "쿠팡")
|
||||
req("PUT", f"/project/api/goals/meeting-items/{cou0['id']}", ADMIN, json={"target_amount": "100", "result_amount": "50"})
|
||||
_create_meeting(w2)
|
||||
m2 = ST.get_meeting(week_start=w2)
|
||||
assert m2["prev_meeting"] is None and all(it["prev"] is None for it in m2["items"])
|
||||
v = req("GET", f"/project/api/goals/meetings/{w2}?year={w2.year}&month={w2.month}", ADMIN).json()
|
||||
assert v["head"]["prev_exists"] is False and v["head"]["prev_target"] is None
|
||||
assert all(it["rate"] is None for it in v["meeting"]["items"])
|
||||
# w1 을 만들면 w2 의 지난주 = w1(그 주 줄, 비어 있음) — w0 의 50/100 이 아니다
|
||||
_create_meeting(w1)
|
||||
v = req("GET", f"/project/api/goals/meetings/{w2}?year={w2.year}&month={w2.month}", ADMIN).json()
|
||||
assert v["head"]["prev_exists"] is True
|
||||
prevs = [it["prev"] for it in v["meeting"]["items"] if it["prev"]]
|
||||
if keyed:
|
||||
assert prevs and all(p["week_start"] == w1.isoformat() for p in prevs)
|
||||
assert all(p["week_start"] == w1.isoformat() for p in prevs)
|
||||
assert all(it["rate"] is None for it in v["meeting"]["items"])
|
||||
finally:
|
||||
_drop_meetings([w0, w1, w2, w3])
|
||||
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# [G6] 실적 조회 장애 ≠ 0원 — 목록 장애·매출 조회 장애·부분 실패·정상 0건·미연결·집계 쇼핑몰 없음
|
||||
# ════════════════════════════════════════════════════════════
|
||||
class _FakePerf:
|
||||
def __init__(self, *, list_error=False, sales_error=None, markets=None, amounts=None):
|
||||
self.list_error, self.sales_error = list_error, sales_error or (lambda a, b: False)
|
||||
self.markets = markets if markets is not None else [
|
||||
{"code": "coupang", "name": "쿠팡", "enabled": True, "include_in_sales": True}]
|
||||
self.amounts = amounts or {}
|
||||
self.calls = []
|
||||
|
||||
def list_marketplaces(self):
|
||||
if self.list_error:
|
||||
raise RuntimeError("perf db down")
|
||||
return self.markets
|
||||
|
||||
def daily_amounts(self, start, end, codes):
|
||||
self.calls.append((start, end))
|
||||
if self.sales_error(start, end):
|
||||
raise RuntimeError("sales query failed")
|
||||
return {(d, c): v for (d, c), v in self.amounts.items() if start <= d <= end and c in codes}
|
||||
|
||||
def statuses(self):
|
||||
return {"coupang": {"last_success_sync_at": "2026-10-01T14:20:00+09:00"}}
|
||||
|
||||
|
||||
def test_meeting_perf_unknown_vs_zero():
|
||||
"""실적 모듈 장애는 미확인(None + head.unknown), 정상 무매출만 0. 의존하는 필요 매출·달성률도 미확인."""
|
||||
from app.modules.project import store
|
||||
|
||||
(w,) = _meet_weeks(2, 1)
|
||||
# 그 달 셋째 주 — 월 누적(1일~지난주 일요일)과 전주 결과(지난주 월~일) 조회 기간이 서로 다르게
|
||||
weeks = store.month_weeks(w.year, w.month)
|
||||
w = weeks[2][0]
|
||||
month_first = date(w.year, w.month, 1)
|
||||
_drop_meetings([w, w - timedelta(days=7)])
|
||||
orig_targets = ST.goal_month_targets
|
||||
ST.goal_month_targets = lambda **kw: {"sales_unit": "원", "sales_target": 1000.0, "sales_actual": None, "roas_target": None}
|
||||
try:
|
||||
_create_meeting(w - timedelta(days=7))
|
||||
_create_meeting(w)
|
||||
prev = ST.get_meeting(week_start=w - timedelta(days=7))
|
||||
cou_prev = next(it for it in prev["items"] if it["label"] == "쿠팡")
|
||||
req("PUT", f"/project/api/goals/meeting-items/{cou_prev['id']}", ADMIN, json={"target_amount": "100"})
|
||||
url = f"/project/api/goals/meetings/{w}?year={w.year}&month={w.month}"
|
||||
|
||||
def view(perf):
|
||||
APP.state.performance_store = perf
|
||||
try:
|
||||
r = req("GET", url, ADMIN)
|
||||
assert r.status_code == 200, r.text
|
||||
return r.json()
|
||||
finally:
|
||||
APP.state.performance_store = None
|
||||
|
||||
def coupang_row(v):
|
||||
return next(it for it in v["meeting"]["items"] if it["label"] == "쿠팡" and it["section"] == "유통")
|
||||
|
||||
# 실적 모듈 미연결 — perf False, 값 없음(미확인 아님)
|
||||
v = view(None)
|
||||
assert v["head"]["perf"] is False and v["head"]["perf_state"] == "off" and v["head"]["unknown"] == []
|
||||
# 쇼핑몰 목록 장애 — 0 이 아니라 미확인, 필요 매출도 계산하지 않음, 회의록은 열림
|
||||
v = view(_FakePerf(list_error=True))
|
||||
h = v["head"]
|
||||
assert h["perf"] is True and h["perf_state"] == "error"
|
||||
assert h["mtd"] is None and h["prev_result"] is None and h["need_per_week"] is None
|
||||
assert {"mtd", "prev_result"} <= set(h["unknown"]), h
|
||||
row = coupang_row(v)
|
||||
assert row["prev"]["auto_error"] is True and row["prev"]["result"] is None and row["rate"] is None
|
||||
assert row["market_unknown"] is True and row["market_off"] is False
|
||||
assert v["markets"] == []
|
||||
# 매출 조회 장애(목록은 정상) — 전부 미확인
|
||||
v = view(_FakePerf(sales_error=lambda a, b: True))
|
||||
h = v["head"]
|
||||
assert h["perf_state"] == "ok" and h["mtd"] is None and h["need_per_week"] is None
|
||||
assert {"mtd", "prev_result"} <= set(h["unknown"])
|
||||
assert coupang_row(v)["prev"]["auto_error"] is True and coupang_row(v)["rate"] is None
|
||||
# 정상 조회 0 건 — 진짜 0원(미확인 아님), 필요 매출 = 목표 ÷ 남은 주
|
||||
v = view(_FakePerf())
|
||||
h = v["head"]
|
||||
assert h["mtd"] == 0 and h["prev_result"] == 0 and h["unknown"] == [], h
|
||||
assert h["need_per_week"] == 1000 // h["weeks_left"]
|
||||
row = coupang_row(v)
|
||||
assert row["prev"]["auto_result"] == 0 and row["prev"]["auto_error"] is False and row["rate"] == 0.0
|
||||
assert h["fresh_oldest"] == "10/01 14:20" and "쿠팡 10/01 14:20" in h["fresh_tip"]
|
||||
# 부분 실패 — 월 누적(1일부터) 조회만 실패: 누적·필요 매출만 미확인, 전주 결과·줄 결과는 정상
|
||||
prev_start = w - timedelta(days=7)
|
||||
v = view(_FakePerf(sales_error=lambda a, b: a == month_first and a != prev_start,
|
||||
amounts={(prev_start, "coupang"): 70}))
|
||||
h = v["head"]
|
||||
assert "mtd" in h["unknown"] and "prev_result" not in h["unknown"], h
|
||||
assert h["mtd"] is None and h["need_per_week"] is None and h["prev_result"] == 70
|
||||
assert coupang_row(v)["prev"]["auto_result"] == 70 and coupang_row(v)["rate"] == 70.0
|
||||
# 매출 집계 쇼핑몰 없음 — 0 원으로 보이지 않게(empty, 미확인도 아님)
|
||||
v = view(_FakePerf(markets=[{"code": "coupang", "name": "쿠팡", "enabled": True, "include_in_sales": False}]))
|
||||
assert v["head"]["perf_state"] == "empty" and v["head"]["mtd"] is None and v["head"]["unknown"] == []
|
||||
# 금주 목표 저장 응답 = 서버 확정값(원 정수)
|
||||
r = req("PUT", f"/project/api/goals/meetings/{w}", ADMIN, json={"week_target": "120만"})
|
||||
assert r.status_code == 200 and r.json()["week_target"] == 1_200_000
|
||||
finally:
|
||||
ST.goal_month_targets = orig_targets
|
||||
_drop_meetings([w, w - timedelta(days=7)])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
if not ENABLED:
|
||||
print("SKIP: PROJECT_TEST_DB_URL(localhost) not set")
|
||||
|
||||
Reference in New Issue
Block a user