diff --git a/app/modules/performance/CLAUDE.md b/app/modules/performance/CLAUDE.md index 175cbef..4de4060 100644 --- a/app/modules/performance/CLAUDE.md +++ b/app/modules/performance/CLAUDE.md @@ -80,6 +80,10 @@ (마지막 업데이트 옆 안내), 탭이 안 보이면 안 묻고 다시 보이면 바로. 보는 사람이 직접 누른 업데이트는 진행 창이 새로 그린다. `performance.js initUpdateWatch`. - 일자별 표 매출 칸 아래 **광고비(ROAS%)** 주황 줄(`--perf-ad`, `dashboard._ad_lines`) — 광고비 탭과 같은 값(`ad_spend.channel_roas`). 쇼핑몰 → 광고 채널은 `dashboard.sales_ad_channels`: 카페24 = 구글·메타 두 줄(이름 붙임), 네이버 = 네이버, 나머지는 `ROAS_SALES_CODE`(쿠팡 ← 쿠팡(윙)). 일 합계 = 보이는 쇼핑몰 광고비 합, ROAS = **일 합계 금액 ÷ 일 합계 광고비**(2026-10-19 — 예전엔 광고비 있는 쇼핑몰 매출만 더했다; `roas` 총매출·`roas_net` 수수료 차감 매출 기준, 보기 기준에 따라 하나만). 광고비 표 없으면 줄 없음. +- **표 열 너비 자동/수동**(2026-10-27) — 설정 "보기 설정" **표 열 너비** [자동(글자 길이)]·[수동 조절](누구나, 이 브라우저 쿠키 `perf_colw`, `router._colw_ctx` → 템플릿 `colw`). + 수동 = 매출 실적·광고비 일자별 표에 `perf-colw-manual` → `performance.js initColWidths` 가 자동 너비를 잰 뒤 `table-layout:fixed`(`is-colw-fixed`, 넘치는 글자 …), + 머리글 오른쪽 경계 `.perf-colw-grip` 드래그(최소 36px)·두 번 누르면 그 열만 자동. 너비 = localStorage `perf_colw_sales`/`perf_colw_ads`(th `data-col` = 쇼핑몰·채널 코드·`label`·`total`)에 계속 유지, + 설정 [조절한 너비 초기화]가 둘 다 지움. 그룹 접기·펴기 때 열 너비도 함께 움직임(`colw.animate/settle`). 테스트 `tests/js/perf_colw.browser.test.js`. - **매출 단위** 원·천원·백만원 — 설정 "보기 설정"(누구나, 이 브라우저 쿠키 `perf_unit`), 서버가 `amount_text`(천원 정수·백만원 소수 한 자리)로 그림(`router._unit_ctx` → 템플릿 `amt`). 광고비 탭은 원 그대로. - 설정의 진단 카드(쇼핑몰 원본 데이터 확인·카페24 매출 대조·일별 한 번에 비교)는 2026-10-19 화면에서 뺐다(서버 API `marketplaces/{code}/reconcile`·`daily-check` 는 진단용으로 남김). diff --git a/app/modules/performance/dashboard.py b/app/modules/performance/dashboard.py index ed06300..c8a7559 100644 --- a/app/modules/performance/dashboard.py +++ b/app/modules/performance/dashboard.py @@ -78,6 +78,14 @@ def normalize_unit(value: Any) -> str: return value if value in UNITS else "won" +# 일자별 표 열 너비(2026-10-27, 실적 설정 "보기 설정" — 이 브라우저 쿠키 perf_colw) — auto = 글자 길이에 맞춤, manual = 머리글 경계 드래그 +COLW_COOKIE = "perf_colw" + + +def normalize_colw(value: Any) -> str: + return "manual" if value == "manual" else "auto" + + def amount_text(value: Any, unit: str = "won") -> str: """금액 → 화면 글자(쉼표). 천원은 정수, 백만원은 소수 한 자리(반올림).""" div, places, _ = UNITS[normalize_unit(unit)] diff --git a/app/modules/performance/router.py b/app/modules/performance/router.py index bc3f74a..5467f94 100644 --- a/app/modules/performance/router.py +++ b/app/modules/performance/router.py @@ -148,6 +148,7 @@ def dashboard_page( ctx["auto_sync"] = _auto_sync_ctx(store, "sales") ctx["update_watch"] = _update_watch("sales", user) _unit_ctx(request, ctx) + _colw_ctx(request, ctx) return render_template(request, "performance/index.html", {**common.base_ctx(user, active_tab="dashboard"), **ctx}) @@ -207,6 +208,14 @@ def _unit_ctx(request: Request, ctx: dict[str, Any]) -> None: ctx["amt"] = lambda v: amount_text(v, unit) +def _colw_ctx(request: Request, ctx: dict[str, Any]) -> None: + """일자별 표 열 너비(2026-10-27) — 실적 설정 "보기 설정"이 이 브라우저 쿠키(perf_colw)에 둔다. + manual 이면 표에 perf-colw-manual — performance.js initColWidths 가 머리글 경계 드래그 + 너비 기억(localStorage).""" + from .dashboard import COLW_COOKIE, normalize_colw # noqa: WPS433 + + ctx["colw"] = normalize_colw(request.cookies.get(COLW_COOKIE)) + + @router.get("/ads", response_class=HTMLResponse) def ads_page( request: Request, @@ -246,6 +255,7 @@ def ads_page( ctx["ad_running"] = jobs.running_job("ads") is not None ctx["auto_sync"] = _auto_sync_ctx(store, "ads") ctx["update_watch"] = _update_watch("ads", user) + _colw_ctx(request, ctx) return render_template(request, "performance/ads.html", {**common.base_ctx(user, active_tab="ads", page_title="광고비"), **ctx}) @@ -274,6 +284,7 @@ def settings_page(request: Request): ctx["ad_api_ready"] = store.ad_api_ready() ctx["auto_sync_settings"] = _auto_sync_settings_ctx(store) # 카드는 관리자에게만(템플릿) _unit_ctx(request, ctx) + _colw_ctx(request, ctx) return render_template(request, "performance/settings.html", {**common.base_ctx(user, active_tab="settings", page_title="실적 설정"), **ctx}) diff --git a/app/modules/performance/templates/performance/ads.html b/app/modules/performance/templates/performance/ads.html index 0c0b434..a3c9c6d 100644 --- a/app/modules/performance/templates/performance/ads.html +++ b/app/modules/performance/templates/performance/ads.html @@ -99,12 +99,13 @@
{#- perf-main-wrap(2026-10-26) = 표 안에서 세로 스크롤 — 제목 행·기간 합계 행 고정 -#} {#- perf-autofit(2026-10-22) = 열 너비는 내용 길이만큼, 날짜 열은 가로 스크롤해도 고정(매출 실적 표와 같음) -#} - + {#- 열 너비(2026-10-27, 실적 설정 "보기 설정" 쿠키 perf_colw) — manual = 머리글 경계 드래그로 조절, 너비는 이 브라우저에 기억(th data-col 별) -#} +
- - {% for c in codes %}{% if c in detail_channels %}{% else %}{% endif %}{% endfor %} - + + {% for c in codes %}{% if c in detail_channels %}{% else %}{% endif %}{% endfor %} + diff --git a/app/modules/performance/templates/performance/index.html b/app/modules/performance/templates/performance/index.html index aed74e5..6713a35 100644 --- a/app/modules/performance/templates/performance/index.html +++ b/app/modules/performance/templates/performance/index.html @@ -137,18 +137,19 @@
{#- perf-main-wrap(2026-10-26) = 표 안에서 세로 스크롤 — 제목 행·기간 합계 행 고정 -#} {#- perf-autofit(2026-10-22) = 열 너비는 내용 길이만큼, 날짜 열은 가로 스크롤해도 고정 -#} -
{% if period_kind == 'year' %}월{% else %}날짜{% endif %}{{ names[c] }} {% if period_kind == 'year' %}월 합계{% else %}일 합계{% endif %}{% if period_kind == 'year' %}월{% else %}날짜{% endif %}{{ names[c] }} {% if period_kind == 'year' %}월 합계{% else %}일 합계{% endif %}
+ {#- 열 너비(2026-10-27, 실적 설정 "보기 설정" 쿠키 perf_colw) — manual = 머리글 경계 드래그로 조절, 너비는 이 브라우저에 기억(th data-col 별) -#} +
- + {#- 그룹(2026-10-22) — 그룹 열 = 보이는 하위 쇼핑몰 합계, ⊟/⊞ 로 하위 열 접기/펴기(이 브라우저에 기억, 펼치고 접을 때 애니메이션). 하위 열은 .perf-gc 로 내용을 감싼다 — 접을 때 그 너비를 0 으로 줄여 열이 부드럽게 닫힌다. is-glast = 그룹의 마지막 하위 열(오른쪽 묶음 선) -#} {% for col in cols %}{% set c = col.code %} {% set glast = col.kind == 'child' and (not loop.nextitem or loop.nextitem.group != col.group) %} - {% if col.kind == 'group' %} - {% else %}{% if col.kind == 'child' %}
{% endif %}{{ short_names[c] }}{% if c in manual_codes %} ✎{% endif %}{% if col.kind == 'child' %}
{% endif %}{% endif %} + {% if col.kind == 'group' %}
+ {% else %}{% endif %} {% endfor %} - + diff --git a/app/modules/performance/templates/performance/settings.html b/app/modules/performance/templates/performance/settings.html index ae681ec..fa401ee 100644 --- a/app/modules/performance/templates/performance/settings.html +++ b/app/modules/performance/templates/performance/settings.html @@ -146,7 +146,7 @@

보기 설정

- 매출 실적 화면의 금액 단위입니다. 이 브라우저에만 적용되며 고르면 바로 저장됩니다. + 매출 실적·광고비 화면을 보는 방식입니다. 이 브라우저에만 적용되며 고르면 바로 저장됩니다.
매출 단위 @@ -159,6 +159,18 @@ 예: 2,475,300원 → {% if unit == 'thousand' %}2,475{% elif unit == 'million' %}2.5{% else %}2,475,300{% endif %}
+ {# 표 열 너비(2026-10-27, 쿠키 perf_colw) — 매출 실적·광고비 일자별 표. 수동 = 머리글 오른쪽 경계 드래그, 너비는 이 브라우저 localStorage(perf_colw_sales/ads) #} +
+ 표 열 너비 +
+ {% for k, label in [('auto', '자동(글자 길이)'), ('manual', '수동 조절')] %} + + {% endfor %} +
+ {% if colw == 'manual' %}매출 실적·광고비 표 머리글의 오른쪽 경계를 끌어 너비를 바꿉니다(두 번 누르면 그 열만 자동 너비). 바꾼 너비는 계속 유지됩니다.{% else %}열 너비가 글자 길이에 맞춰 자동으로 정해집니다.{% endif %} + +
{% if is_admin and auto_sync_settings %} diff --git a/app/static/performance.css b/app/static/performance.css index c58f44e..73fa567 100644 --- a/app/static/performance.css +++ b/app/static/performance.css @@ -376,7 +376,8 @@ td.is-link:hover { background: #eef2ff; text-decoration: underline; } .perf-unit-suffix { margin-left: 2px; font-size: .55em; font-weight: 600; color: var(--color-midtone-gray, #777); } /* 보기 설정(매출 단위) */ .perf-opt-row { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; } -.perf-opt-label { font-weight: 600; } +.perf-opt-label { font-weight: 600; min-width: 72px; } +.perf-opt-row + .perf-opt-row { margin-top: 10px; } /* 자동 업데이트 일정(2026-10-26) — 매출 실적·광고비 한 줄씩: 이름·사용 | 요일·시간·간격 | 다음 회차 */ .perf-auto-rows { display: flex; flex-direction: column; } .perf-auto-row { display: grid; grid-template-columns: 130px 1fr; gap: 6px 16px; padding: 12px 0; border-top: 1px solid var(--perf-line); } @@ -507,3 +508,18 @@ body.perf-dragging, body.perf-dragging * { cursor: grabbing !important; user-sel .perf-main-wrap.is-stuck .perf-main thead th::after { content: ""; position: absolute; left: 0; right: 0; bottom: -1px; height: 1px; background: var(--perf-line); } /* 스크롤 막대 배경(트랙) 투명(2026-10-27) — 표 상자 가로 막대·실적 화면 세로 막대. 손잡이만 옅은 회색 */ .perf-table-wrap, .erp-page:has(> .perf) { scrollbar-color: #c3c6cb transparent; } + +/* ── 일자별 표 열 너비 수동 조절(2026-10-27, 실적 설정 "보기 설정" 쿠키 perf_colw=manual) ── + performance.js initColWidths 가 자동 너비를 잰 뒤 th 너비·표 너비를 px 로 주고 is-colw-fixed(table-layout fixed) — 넘치는 글자는 … 로 자른다. + 머리글 오른쪽 경계 .perf-colw-grip 을 끌어 조절(마우스 올리면 선), 그룹 접기 애니메이션 동안 is-colw-anim 으로 열 너비도 함께 움직인다. */ +.perf-main.perf-colw-manual.is-colw-fixed { table-layout: fixed; } +.perf-main.is-colw-fixed th, .perf-main.is-colw-fixed td { box-sizing: border-box; overflow: hidden; text-overflow: ellipsis; } +.perf-main.is-colw-fixed thead th.perf-th-label, .perf-main.is-colw-fixed .perf-td-label { min-width: 0; max-width: none; } +.perf-main.is-colw-fixed .perf-adl { overflow: hidden; text-overflow: ellipsis; } +.perf-main.is-colw-anim, .perf-main.is-colw-anim thead th { transition: width .26s ease, padding .26s ease; } +.perf-main-wrap.is-stuck .perf-main.is-colw-fixed thead th::after { bottom: 0; } /* 칸이 넘침을 자르므로 아래 선을 칸 안에 */ +.perf-colw-grip { position: absolute; top: 0; right: 0; bottom: 0; width: 8px; cursor: col-resize; z-index: 6; touch-action: none; } +.perf-colw-grip::after { content: ""; position: absolute; top: 6px; bottom: 6px; right: 1px; width: 2px; border-radius: 1px; background: transparent; } +.perf-main thead th:hover > .perf-colw-grip::after { background: #c3c6cb; } +.perf-main thead th > .perf-colw-grip:hover::after, .perf-colw-grip.is-active::after { background: #1a56db; } +body.perf-colw-dragging, body.perf-colw-dragging * { cursor: col-resize !important; user-select: none; } diff --git a/app/static/performance.js b/app/static/performance.js index 34bfb1c..436df37 100644 --- a/app/static/performance.js +++ b/app/static/performance.js @@ -252,6 +252,93 @@ // ════════════════════════════════════════════════════ // 대시보드 // ════════════════════════════════════════════════════ + // 일자별 표 열 너비 수동 조절(2026-10-27) — 실적 설정 "보기 설정"에서 수동(쿠키 perf_colw=manual)이면 서버가 표에 perf-colw-manual. + // 처음엔 자동 너비(글자 길이)를 재 두고 table-layout:fixed 로 고정, 머리글 오른쪽 경계(.perf-colw-grip)를 끌면 그 열만 그 너비로. + // 바꾼 너비는 이 브라우저 localStorage(perf_colw_sales / perf_colw_ads, 열 = th data-col)에 계속 유지, 경계를 두 번 누르면 그 열만 자동 너비로. + // 그룹 접기·펴기 애니메이션은 apply(접는 열)/animate/settle 로 열 너비를 0 ↔ 원래 너비로 함께 움직인다. + const COLW_MIN = 36; + function initColWidths(root) { + const table = root.querySelector("table.perf-colw-manual"); + const row = table && table.tHead && table.tHead.rows[0]; + if (!row) return null; + const KEY = "perf_colw_" + (table.dataset.colwKey || "sales"); + const heads = Array.prototype.slice.call(row.cells); + const auto = {}; + let saved = {}; + try { saved = JSON.parse(localStorage.getItem(KEY) || "{}") || {}; } catch (_) { saved = {}; } + function store() { + try { localStorage.setItem(KEY, JSON.stringify(saved)); } catch (_) { /* 기억만 못 함 */ } + } + function widthOf(th) { const c = th.dataset.col; return saved[c] || auto[c] || 80; } + function apply(zero) { // zero = 너비 0 으로 둘 열(접는 중·펴기 직전) + let sum = 0; + heads.forEach(function (th) { + const w = zero && zero.indexOf(th) >= 0 ? 0 : widthOf(th); + th.style.width = w + "px"; + if (!th.classList.contains("is-gfolded")) sum += w; + }); + table.style.width = sum + "px"; + table.classList.add("is-colw-fixed"); + } + function measure() { // 자동 너비 다시 재기(접혀 안 보이는 열은 앞서 잰 값 그대로) + table.classList.remove("is-colw-fixed", "is-colw-anim"); + heads.forEach(function (th) { th.style.width = ""; }); + table.style.width = ""; + heads.forEach(function (th) { + const w = th.getBoundingClientRect().width; + if (w > 0) auto[th.dataset.col] = Math.ceil(w); + }); + apply(); + } + heads.forEach(function (th) { + const g = document.createElement("span"); + g.className = "perf-colw-grip"; + g.setAttribute("aria-hidden", "true"); + th.appendChild(g); + }); + measure(); + if (document.fonts && document.fonts.status !== "loaded") document.fonts.ready.then(measure); // 글꼴 늦게 오면 자동 너비 다시 + + let drag = null; + row.addEventListener("pointerdown", function (e) { + const g = e.target.closest(".perf-colw-grip"); + if (!g || e.button !== 0) return; + e.preventDefault(); + e.stopPropagation(); + drag = { th: g.parentElement, grip: g, x: e.clientX, w: widthOf(g.parentElement) }; + try { g.setPointerCapture(e.pointerId); } catch (_) { /* 캡처 못 해도 끌기는 됨 */ } + g.classList.add("is-active"); + document.body.classList.add("perf-colw-dragging"); + }); + row.addEventListener("pointermove", function (e) { + if (!drag) return; + saved[drag.th.dataset.col] = Math.max(COLW_MIN, Math.round(drag.w + e.clientX - drag.x)); + apply(); + }); + function end() { + if (!drag) return; + drag.grip.classList.remove("is-active"); + document.body.classList.remove("perf-colw-dragging"); + drag = null; + store(); + } + row.addEventListener("pointerup", end); + row.addEventListener("pointercancel", end); + row.addEventListener("click", function (e) { if (e.target.closest(".perf-colw-grip")) e.stopPropagation(); }); + row.addEventListener("dblclick", function (e) { + const g = e.target.closest(".perf-colw-grip"); + if (!g) return; + delete saved[g.parentElement.dataset.col]; + store(); + apply(); + }); + return { + apply: apply, + animate: function (zero) { table.classList.add("is-colw-anim"); apply(zero); }, + settle: function () { table.classList.remove("is-colw-anim"); apply(); }, + }; + } + function initDashboard(root) { const data = JSON.parse((document.getElementById("perf-data") || {}).textContent || "{}"); const METRIC_NAMES = { gross: "총매출", commission: "수수료", net: "수수료 차감 매출" }; @@ -285,8 +372,10 @@ const groupRun = {}; // 그룹 → 애니메이션 번호(빠르게 두 번 누르면 앞 애니메이션의 마무리를 버린다) let collapsed = []; try { collapsed = JSON.parse(localStorage.getItem(GROUP_KEY) || "[]") || []; } catch (_) { collapsed = []; } + const colw = initColWidths(root); // 열 너비 수동 조절(보기 설정) — 그룹을 접기 전에 자동 너비를 잰다 function setGroup(code, fold, animate) { const cells = Array.prototype.slice.call(root.querySelectorAll('[data-group-child="' + code + '"]')); + const heads = cells.filter(function (n) { return n.tagName === "TH"; }); root.querySelectorAll('[data-group-toggle="' + code + '"]').forEach(function (b) { b.setAttribute("aria-expanded", fold ? "false" : "true"); b.setAttribute("aria-label", (b.getAttribute("aria-label") || "").replace(/ (접기|펴기)$/, "") + (fold ? " 펴기" : " 접기")); @@ -298,6 +387,7 @@ if (groupRun[code] !== run) return; cells.forEach(function (n) { n.classList.remove("is-ganim", "is-gshut"); n.classList.toggle("is-gfolded", fold); }); boxes.forEach(function (b) { b.style.maxWidth = ""; }); + if (colw) colw.settle(); }; if (!animate || REDUCE_MOTION || !boxes.length) { settle(); return; } if (fold) { @@ -306,12 +396,15 @@ void root.offsetWidth; // 지금 너비에서 출발 cells.forEach(function (n) { n.classList.add("is-gshut"); }); boxes.forEach(function (b) { b.style.maxWidth = "0px"; }); + if (colw) colw.animate(heads); // 수동 너비 표 — 열 너비도 0 으로 } else { cells.forEach(function (n) { n.classList.remove("is-gfolded", "is-ganim"); n.classList.add("is-gshut"); }); boxes.forEach(function (b) { b.style.maxWidth = "0px"; }); + if (colw) colw.apply(heads); void root.offsetWidth; // 0 에서 출발 cells.forEach(function (n) { n.classList.add("is-ganim"); n.classList.remove("is-gshut"); }); boxes.forEach(function (b) { b.style.maxWidth = b.scrollWidth + "px"; }); + if (colw) colw.animate(); // 수동 너비 표 — 열 너비도 원래대로 } setTimeout(settle, GROUP_MS + 30); } @@ -1199,6 +1292,31 @@ if (ex) ex.textContent = "예: 2,475,300원 → " + UNIT_EX[u]; }); }); + // 보기 설정 — 표 열 너비 자동/수동(2026-10-27, 쿠키 perf_colw 1년). 수동으로 바꾼 너비는 표 화면 localStorage 에 있고 [초기화]가 지운다 + const COLW_HELP = { + auto: "열 너비가 글자 길이에 맞춰 자동으로 정해집니다.", + manual: "매출 실적·광고비 표 머리글의 오른쪽 경계를 끌어 너비를 바꿉니다(두 번 누르면 그 열만 자동 너비). 바꾼 너비는 계속 유지됩니다.", + }; + const colwReset = document.getElementById("perf-colw-reset"); + root.querySelectorAll("#perf-view-opts [data-colw]").forEach(function (b) { + b.addEventListener("click", function () { + const v = b.dataset.colw; + document.cookie = "perf_colw=" + v + "; path=/performance; max-age=31536000; SameSite=Lax"; + root.querySelectorAll("#perf-view-opts [data-colw]").forEach(function (x) { + x.classList.toggle("is-active", x === b); + x.setAttribute("aria-checked", x === b ? "true" : "false"); + }); + const help = document.getElementById("perf-colw-help"); + if (help) help.textContent = COLW_HELP[v]; + if (colwReset) colwReset.hidden = v !== "manual"; + }); + }); + if (colwReset) colwReset.addEventListener("click", async function () { + if (!(await confirmMsg("매출 실적·광고비 표에서 조절한 열 너비를 모두 지우고 자동 너비로 되돌릴까요?"))) return; + try { localStorage.removeItem("perf_colw_sales"); localStorage.removeItem("perf_colw_ads"); } catch (_) { /* 저장소 없음 */ } + colwReset.textContent = "초기화했습니다"; + setTimeout(function () { colwReset.textContent = "조절한 너비 초기화"; }, 1800); + }); initAutoSyncSettings(root); // 사용 / 매출 집계 토글 — 바로 저장, 실패하면 되돌림 diff --git a/tests/js/perf_colw.browser.test.js b/tests/js/perf_colw.browser.test.js new file mode 100644 index 0000000..c3580c4 --- /dev/null +++ b/tests/js/perf_colw.browser.test.js @@ -0,0 +1,168 @@ +// 실적 일자별 표 열 너비 자동/수동(2026-10-27) — 실제 브라우저(Chromium). +// python tests/js/render_performance.py +// NODE_PATH= PJ_TEST_BROWSER= node tests/js/perf_colw.browser.test.js +// 자동(기본) = 예전 그대로(글자 길이, 손잡이 없음). 수동(쿠키 perf_colw=manual → 표 perf-colw-manual) = 처음엔 자동 너비 그대로 고정, +// 머리글 오른쪽 경계를 끌면 그 열만 바뀌고 새로고침해도 유지(localStorage perf_colw_sales / _ads 따로), 두 번 누르면 자동 너비, +// 그룹 접기·펴기 때 열 너비도 함께, 머리글 고정(스크롤)·날짜 열 고정 그대로. 설정 "보기 설정"에서 고르면 쿠키, [초기화]는 저장 너비 지움. +const fs = require("fs"), path = require("path"); +const { chromium } = require("playwright"); +const ROOT = path.join(__dirname, "..", ".."); +const fails = []; +function check(name, cond, extra) { + if (cond) console.log("PASS " + name); + else { console.log("FAIL " + name + (extra !== undefined ? " → " + JSON.stringify(extra) : "")); fails.push(name); } +} +function route(p, file) { + return p.route("**/*", function (r) { + const url = new URL(r.request().url()).pathname; + if (url.startsWith("/static/")) { + const f = path.join(ROOT, "app", url); + if (!fs.existsSync(f)) return r.fulfill({ status: 404, body: "" }); + return r.fulfill({ status: 200, contentType: f.endsWith(".css") ? "text/css" : "application/javascript", body: fs.readFileSync(f) }); + } + if (url.includes("/api/")) return r.fulfill({ status: 200, contentType: "application/json", body: "{}" }); + r.fulfill({ status: 200, contentType: "text/html; charset=utf-8", body: fs.readFileSync(path.join(__dirname, ".out", file), "utf8") }); + }); +} +function widths(p) { + return p.evaluate(function () { + const t = document.querySelector("table.perf-main"), o = {}; + t.tHead.rows[0].querySelectorAll("th").forEach(function (th) { o[th.dataset.col] = Math.round(th.getBoundingClientRect().width); }); + return { cols: o, table: Math.round(t.getBoundingClientRect().width), fixed: t.classList.contains("is-colw-fixed"), + grips: t.querySelectorAll(".perf-colw-grip").length }; + }); +} +async function drag(p, col, dx) { + const box = await p.locator('th[data-col="' + col + '"] > .perf-colw-grip').boundingBox(); + const x = box.x + box.width / 2, y = box.y + box.height / 2; + await p.mouse.move(x, y); + await p.mouse.down(); + await p.mouse.move(x + dx / 2, y, { steps: 3 }); + await p.mouse.move(x + dx, y, { steps: 3 }); + await p.mouse.up(); +} + +(async function () { + const browser = await chromium.launch(process.env.PJ_TEST_BROWSER ? { executablePath: process.env.PJ_TEST_BROWSER } : {}); + try { + // ── 자동(기본) — 예전 그대로 ── + const actx = await browser.newContext({ viewport: { width: 1400, height: 800 } }); + const ap = await actx.newPage(); + await route(ap, "perf_dash_shell.html"); + await ap.goto("http://perf.test/performance/"); + const a0 = await widths(ap); + check("자동 = 고정 안 함·손잡이 없음", !a0.fixed && a0.grips === 0, a0); + await actx.close(); + + // ── 수동 — 매출 실적(그룹 있음) ── + const ctx = await browser.newContext({ viewport: { width: 1400, height: 800 } }); + const p = await ctx.newPage(); + await route(p, "perf_dash_colw_shell.html"); + await p.goto("http://perf.test/performance/"); + await p.waitForTimeout(150); + const w0 = await widths(p); + const fits = await p.evaluate(function () { + return Array.from(document.querySelectorAll("table.perf-main th, table.perf-main td")).filter(function (c) { + return c.offsetParent && c.scrollWidth > c.clientWidth + 1; + }).length; + }); + const sum0 = Object.keys(w0.cols).reduce(function (s, k) { return s + w0.cols[k]; }, 0); + check("수동 = 고정 표 + 열마다 손잡이, 처음엔 글자가 잘리지 않는 자동 너비", w0.fixed && w0.grips === Object.keys(w0.cols).length && fits === 0, { w0: w0, fits: fits }); + check("표 너비 = 열 너비 합", Math.abs(w0.table - sum0) <= 2, { table: w0.table, sum: sum0 }); + await drag(p, "naver", 70); + const w1 = await widths(p); + check("네이버 경계 오른쪽으로 70px 끌기 → 그 열만 +70", Math.abs(w1.cols.naver - w0.cols.naver - 70) <= 2 && w1.cols.cafe24 === w0.cols.cafe24 && Math.abs(w1.table - w0.table - 70) <= 2, { w0: w0.cols, w1: w1.cols }); + await drag(p, "cafe24", -400); + const w2 = await widths(p); + check("너무 좁히면 최소 36px", w2.cols.cafe24 >= 35 && w2.cols.cafe24 <= 37, w2.cols.cafe24); + const clip = await p.evaluate(function () { + const th = document.querySelector('th[data-col="cafe24"]'); + const td = document.querySelector("tr.perf-row-total").children[th.cellIndex]; + return { ov: getComputedStyle(td).overflow, w: Math.round(td.getBoundingClientRect().width) }; + }); + check("좁힌 열 칸은 넘치는 글자를 자름(너비 그대로)", clip.ov === "hidden" && clip.w <= 37, clip); + const clicked = await p.evaluate(function () { return location.href; }); + await p.reload(); + await p.waitForTimeout(150); + const w3 = await widths(p); + check("새로고침해도 조절한 너비 유지", Math.abs(w3.cols.naver - w1.cols.naver) <= 1 && Math.abs(w3.cols.cafe24 - w2.cols.cafe24) <= 1 && w3.cols.total === w0.cols.total, { w3: w3.cols }); + const stored = await p.evaluate(function () { return JSON.parse(localStorage.getItem("perf_colw_sales") || "{}"); }); + check("localStorage perf_colw_sales 에 열별 너비", stored.naver > 0 && stored.cafe24 === 36 && !("total" in stored), stored); + await p.dblclick('th[data-col="cafe24"] > .perf-colw-grip'); + const w4 = await widths(p); + check("경계 두 번 누르면 그 열만 자동 너비로", Math.abs(w4.cols.cafe24 - w0.cols.cafe24) <= 1 && Math.abs(w4.cols.naver - w1.cols.naver) <= 1 && clicked === (await p.evaluate(function () { return location.href; })), w4.cols); + // 그룹 접기·펴기 — 열 너비도 함께, 끝나면 표 너비 = 보이는 열 합 + const childW = w4.cols.custom_a; + await p.click('[data-group-toggle="group_off"]'); + await p.waitForTimeout(110); + const mid = await p.evaluate(function () { return Math.round(document.querySelector('th[data-col="custom_a"]').getBoundingClientRect().width); }); + await p.waitForTimeout(400); + const w5 = await widths(p); + const vis5 = Object.keys(w5.cols).reduce(function (s, k) { return s + w5.cols[k]; }, 0); + check("그룹 접는 중 열이 줄고, 끝나면 숨김·표 너비 = 보이는 열 합", mid > 0 && mid < childW && w5.cols.custom_a === 0 && Math.abs(w5.table - vis5) <= 2, { mid: mid, childW: childW, w5: w5 }); + await p.click('[data-group-toggle="group_off"]'); + await p.waitForTimeout(450); + const w6 = await widths(p); + check("다시 펴면 원래 너비로", Math.abs(w6.cols.custom_a - childW) <= 1 && Math.abs(w6.table - w4.table) <= 2, { w6: w6, w4: w4.table }); + // 그룹 단추 클릭은 그대로(손잡이 클릭이 단추를 누르지 않음) + const exp = await p.getAttribute('[data-group-toggle="group_off"]', "aria-expanded"); + check("그룹 단추 상태 정상(펼침)", exp === "true", exp); + // 머리글 스크롤 고정 그대로 + const sticky = await p.evaluate(function () { + const page = document.querySelector(".erp-page"), th = document.querySelector('th[data-col="naver"]'); + page.scrollTop = 400; + return new Promise(function (res) { + requestAnimationFrame(function () { requestAnimationFrame(function () { + res({ top: th.getBoundingClientRect().top, pageTop: page.getBoundingClientRect().top, w: Math.round(th.getBoundingClientRect().width) }); + }); }); + }); + }); + check("페이지 스크롤해도 제목 행 화면 위 고정(너비 그대로)", Math.abs(sticky.top - sticky.pageTop) <= 2 && Math.abs(sticky.w - w1.cols.naver) <= 1, sticky); + await p.evaluate(function () { document.querySelector(".erp-page").scrollTop = 0; }); + await p.locator(".perf-main-wrap").screenshot({ path: path.join(__dirname, ".out", "perf_colw_dash.png") }); + + // ── 수동 — 광고비(같은 브라우저, 따로 기억) ── + const q = await ctx.newPage(); + await route(q, "perf_ads_colw_shell.html"); + await q.goto("http://perf.test/performance/ads"); + await q.waitForTimeout(150); + const b0 = await widths(q); + const col = Object.keys(b0.cols)[2]; + await drag(q, col, 50); + await q.reload(); + await q.waitForTimeout(150); + const b1 = await widths(q); + const both = await q.evaluate(function () { + return { ads: JSON.parse(localStorage.getItem("perf_colw_ads") || "{}"), sales: JSON.parse(localStorage.getItem("perf_colw_sales") || "{}") }; + }); + check("광고비 표도 조절·유지(perf_colw_ads 따로)", b0.fixed && Math.abs(b1.cols[col] - b0.cols[col] - 50) <= 2 && both.ads[col] > 0 && !(col in both.sales), { col: col, b0: b0.cols[col], b1: b1.cols[col], both: both }); + await q.locator(".perf-main-wrap").screenshot({ path: path.join(__dirname, ".out", "perf_colw_ads.png") }); + + // ── 설정 — 보기 설정 ── + const s = await ctx.newPage(); + s.on("dialog", function (d) { d.accept(); }); + await route(s, "perf_settings.html"); + await s.goto("http://perf.test/performance/settings"); + const st0 = await s.evaluate(function () { + return { active: document.querySelector("#perf-view-opts [data-colw].is-active").dataset.colw, reset: document.getElementById("perf-colw-reset").hidden }; + }); + check("설정 기본 = 자동, [초기화] 숨김", st0.active === "auto" && st0.reset, st0); + await s.click('#perf-view-opts [data-colw="manual"]'); + const st1 = await s.evaluate(function () { + return { cookie: document.cookie, reset: document.getElementById("perf-colw-reset").hidden, help: document.getElementById("perf-colw-help").textContent }; + }); + check("수동 고르면 쿠키 perf_colw=manual·[초기화] 보임·안내", /perf_colw=manual/.test(st1.cookie) && !st1.reset && /경계/.test(st1.help), st1); + await s.click("#perf-colw-reset"); + await s.waitForTimeout(100); + const st2 = await s.evaluate(function () { return [localStorage.getItem("perf_colw_sales"), localStorage.getItem("perf_colw_ads")]; }); + check("[조절한 너비 초기화] = 매출·광고비 저장 너비 지움", st2[0] === null && st2[1] === null, st2); + await s.locator("#perf-view-opts").screenshot({ path: path.join(__dirname, ".out", "perf_colw_settings.png") }); + await s.click('#perf-view-opts [data-colw="auto"]'); + check("자동 고르면 쿠키 perf_colw=auto", /perf_colw=auto/.test(await s.evaluate(function () { return document.cookie; }))); + await ctx.close(); + } finally { + await browser.close(); + } + console.log(fails.length ? "\n" + fails.length + " FAIL" : "\nALL PASS"); + process.exit(fails.length ? 1 : 0); +})(); diff --git a/tests/js/render_performance.py b/tests/js/render_performance.py index 04b7180..40a0cbd 100644 --- a/tests/js/render_performance.py +++ b/tests/js/render_performance.py @@ -88,7 +88,7 @@ def main() -> None: os.makedirs(OUT_DIR, exist_ok=True) e = env() base = {"user": {"email": "me@test.local"}, "is_admin": True, "nav_items": [], "page_title": "실적", "page_subtitle": "", - "unit": "won", "unit_label": "원", "amt": lambda v: amount_text(v)} + "unit": "won", "unit_label": "원", "amt": lambda v: amount_text(v), "colw": "auto"} ctx = build_dashboard(FakeStore(), kind="week", anchor=date(2026, 10, 7), today=date(2026, 10, 7)) # 다음 자동 업데이트(router._auto_sync_ctx 와 같은 모양) — 화면이 초 단위로 센다 # 일정 = 실적 설정 "자동 업데이트"(2026-10-26) — 화면이 schedule 로 다음 회차를 계산 @@ -150,6 +150,15 @@ def main() -> None: html = e.get_template("performance/settings.html").render(**base, active_tab="settings", **gsctx) with open(os.path.join(OUT_DIR, "perf_settings_groups.html"), "w", encoding="utf-8") as f: f.write(html) + # 표 열 너비 수동 조절(2026-10-27, 쿠키 perf_colw=manual) — 진짜 셸 + 그룹 있는 매출 실적·광고비 (perf_colw.browser.test.js) + cctx = build_dashboard(GroupStore(), kind="month", anchor=date(2026, 10, 7), today=date(2026, 10, 7)) + cctx.update(auto_sync=None, update_watch=None) + html = shell.get_template("performance/index.html").render(**{**sbase, "colw": "manual"}, active_tab="dashboard", metric="gross", **cctx) + with open(os.path.join(OUT_DIR, "perf_dash_colw_shell.html"), "w", encoding="utf-8") as f: + f.write(html) + html = shell.get_template("performance/ads.html").render(**{**sbase, "colw": "manual"}, active_tab="ads", **sactx) + with open(os.path.join(OUT_DIR, "perf_ads_colw_shell.html"), "w", encoding="utf-8") as f: + f.write(html) print("ok")
{% if period_kind == 'year' %}월{% else %}날짜{% endif %}{% if period_kind == 'year' %}월{% else %}날짜{% endif %}{{ short_names[c] }}{{ short_names[c] }}{% if col.kind == 'child' %}
{% endif %}{{ short_names[c] }}{% if c in manual_codes %} ✎{% endif %}{% if col.kind == 'child' %}
{% endif %}
{% if period_kind == 'year' %}월 합계{% else %}일 합계{% endif %}{% if period_kind == 'year' %}월 합계{% else %}일 합계{% endif %}