feat(실적): 일자별 표 열 접기 — 사람마다 저장

매출 실적·광고비 일자별 표 머리글 위 버튼으로 열 하나씩 접기/펴기(날짜 열 제외).
접은 열은 26px 띠, 로그인한 사람 본인에게만 적용 — PUT /api/my-col-fold →
perf_settings col_fold:<이메일 sha1> (마이그레이션 없음, 011 테이블 재사용).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-06 19:53:39 +09:00
parent 9d2e9f6e1b
commit 8636498bc9
8 changed files with 222 additions and 5 deletions
+4
View File
@@ -88,6 +88,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-11-06) — 매출 실적·광고비 일자별 표 머리글 위 작은 화살표 버튼(`.perf-cfold`, `performance.js initColFold`)으로 열 하나씩 접기/펴기(날짜 열 빼고, 일 합계·그룹 열 포함).
접은 열 = 26px 띠(`is-cfold`, 칸 내용 숨김·클릭/메모 안 됨, 너비는 JS `CFOLD_W` 와 CSS 같게, 수동 열 너비 표도 같음). **로그인한 사람 본인에게만** —
`PUT /api/my-col-fold {kind: sales|ads, cols}` → `perf_settings` key `col_fold:<이메일 sha1>`(key 64자 제한) = `{sales, ads}`, 화면은 표 `data-col-fold`(라우터 `_load_col_fold`). 011 미적용이면 다 펼침·저장 503.
그룹 하위 열 접기(⊟, localStorage)와는 별개. 테스트 `tests/js/perf_colfold.browser.test.js`, `test_custom_groups.py::test_api_my_col_fold_per_user`.
- **표 열 너비 자동/수동**(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)·두 번 누르면 그 열만 자동. **날짜 열(`label`)은 조절 불가 — 늘 자동 너비, 손잡이 없음, 저장값 무시**. 너비 = localStorage `perf_colw_sales`/`perf_colw_ads`(th `data-col` = 쇼핑몰·채널 코드·`label`·`total`)에 계속 유지,
+37 -1
View File
@@ -5,7 +5,8 @@
GET /performance/ads 광고비(모듈 권한) — 구글·메타·쿠팡(윙)·쿠팡(로켓) 연·월·일
GET /performance/settings 실적 설정(관리자)
JSON API — 모듈 권한
POST /performance/api/sync 매출 업데이트(사용 중인 쇼핑몰 전부, 쇼핑몰별 실패 격리)
PUT /performance/api/my-col-fold 일자별 표에서 접은 열(보는 사람 본인에게만, 매출 실적·광고비 따로)
POST /performance/api/sync 매출 업데이트(사용 중인 쇼핑몰 전부, 쇼핑몰별 실패 격리)
background=true 면 백그라운드로 돌리고 작업 번호를 바로 돌려줌
GET /performance/api/sync/jobs/{id} 매출 업데이트 진행 상황(쇼핑몰별·전체 진행 막대)
GET /performance/api/sync/current 지금 돌고 있는 업데이트(없으면 null)
@@ -151,6 +152,7 @@ def dashboard_page(
ctx["update_watch"] = _update_watch("sales", user)
_unit_ctx(store, ctx)
_colw_ctx(request, ctx)
ctx["col_fold"] = _load_col_fold(store, user).get("sales", [])
return render_template(request, "performance/index.html", {**common.base_ctx(user, active_tab="dashboard"), **ctx})
@@ -243,6 +245,7 @@ def ads_page(
)
_ad_update_ctx(store, user, ctx)
_colw_ctx(request, ctx)
ctx["col_fold"] = _load_col_fold(store, user).get("ads", [])
return render_template(request, "performance/ads.html",
{**common.base_ctx(user, active_tab="ads", page_title="광고비"), **ctx})
@@ -1015,6 +1018,39 @@ def api_display_unit(request: Request, payload: dict[str, Any] = Body(...)) -> J
return JSONResponse({"ok": True, "unit": unit})
COL_FOLD_KINDS = ("sales", "ads")
def _col_fold_key(user: dict[str, Any]) -> str:
"""접은 열(2026-11-06) — 사람마다 perf_settings 한 줄. key 는 64자 제한이라 이메일을 해시로(updated_by 에 이메일)."""
import hashlib # noqa: WPS433
return "col_fold:" + hashlib.sha1(str(user.get("email", "")).lower().encode()).hexdigest()
def _load_col_fold(store: Any, user: dict[str, Any]) -> dict[str, list[str]]:
"""{sales: [열 코드], ads: [...]} — 저장 없음·011 미적용·DB 오류면 빈 값(전부 펼침)."""
try:
value = store.get_setting(_col_fold_key(user))
except Exception: # noqa: BLE001 — 접기만 못 함
return {}
return value if isinstance(value, dict) else {}
@router.put("/api/my-col-fold")
def api_my_col_fold(request: Request, payload: dict[str, Any] = Body(...)) -> JSONResponse:
"""일자별 표에서 접은 열(2026-11-06, 모듈 권한자 누구나) — 로그인한 사람 본인 화면에만 적용, 매출 실적·광고비 따로."""
store, user = common.require_store(request)
kind, cols = payload.get("kind"), payload.get("cols")
if kind not in COL_FOLD_KINDS or not isinstance(cols, list) or len(cols) > 200:
raise HTTPException(status_code=400, detail="접은 열 목록이 올바르지 않습니다.")
cols = sorted({c for c in cols if isinstance(c, str) and 0 < len(c) <= 64 and c != "label"})
value = _load_col_fold(store, user)
value[kind] = cols
_save_shared_setting(store, _col_fold_key(user), value, user)
return JSONResponse({"ok": True, "cols": cols})
def _save_shared_setting(store: Any, key: str, value: Any, user: dict[str, Any]) -> None:
from .db import SettingsMigrationNeeded # noqa: WPS433
@@ -80,7 +80,7 @@
{#- perf-main-wrap(2026-10-26) = 표 안에서 세로 스크롤 — 제목 행·기간 합계 행 고정 -#}
{#- perf-autofit(2026-10-22) = 열 너비는 내용 길이만큼, 날짜 열은 가로 스크롤해도 고정(매출 실적 표와 같음) -#}
{#- 열 너비(2026-10-27, 실적 설정 "보기 설정" 쿠키 perf_colw) — manual = 머리글 경계 드래그로 조절, 너비는 이 브라우저에 기억(th data-col 별) -#}
<table class="perf-table perf-main perf-autofit{% if colw == 'manual' %} perf-colw-manual{% endif %}" data-colw-key="ads">
<table class="perf-table perf-main perf-autofit{% if colw == 'manual' %} perf-colw-manual{% endif %}" data-colw-key="ads" data-cfold-kind="ads" data-col-fold="{{ (col_fold or []) | tojson | forceescape }}">
<thead>
<tr>
<th class="perf-th-label" data-col="label">{% if period_kind == 'year' %}월{% else %}날짜{% endif %}</th>
@@ -134,7 +134,7 @@
{#- perf-main-wrap(2026-10-26) = 표 안에서 세로 스크롤 — 제목 행·기간 합계 행 고정 -#}
{#- perf-autofit(2026-10-22) = 열 너비는 내용 길이만큼, 날짜 열은 가로 스크롤해도 고정 -#}
{#- 열 너비(2026-10-27, 실적 설정 "보기 설정" 쿠키 perf_colw) — manual = 머리글 경계 드래그로 조절, 너비는 이 브라우저에 기억(th data-col 별) -#}
<table class="perf-table perf-main perf-autofit{% if colw == 'manual' %} perf-colw-manual{% endif %}" data-colw-key="sales">
<table class="perf-table perf-main perf-autofit{% if colw == 'manual' %} perf-colw-manual{% endif %}" data-colw-key="sales" data-cfold-kind="sales" data-col-fold="{{ (col_fold or []) | tojson | forceescape }}">
<thead>
<tr>
<th class="perf-th-label" data-col="label">{% if period_kind == 'year' %}월{% else %}날짜{% endif %}</th>
@@ -380,3 +380,30 @@ def test_cafe24_real_shows_same_ad_lines(client):
row = next(tr for tr in body.split("<tr ") if 'data-date="2026-10-05"' in tr)
assert row.count("<i>구글</i>11,000") == 2 and row.count("<i>메타</i>22,000") == 2
assert row.index("<i>구글</i>") < row.index("data-code=\"naver\"")
def test_api_my_col_fold_per_user(client, monkeypatch):
"""열 접기(2026-11-06) — 로그인한 사람마다 따로 저장, 매출 실적·광고비 따로, 화면은 그 사람 값만 그린다."""
perf_router = importlib.import_module("app.modules.performance.router")
r = client.put("/performance/api/my-col-fold", json={"kind": "sales", "cols": ["naver", "label", "naver", 3, "total"]})
assert r.status_code == 200 and r.json()["cols"] == ["naver", "total"]
assert client.put("/performance/api/my-col-fold", json={"kind": "ads", "cols": ["google"]}).status_code == 200
mine = perf_router._col_fold_key({"email": "king@x"})
assert len(mine) <= 64 and client.store.settings[mine] == {"sales": ["naver", "total"], "ads": ["google"]}
assert 'data-col-fold="[&#34;naver&#34;, &#34;total&#34;]"' in client.get("/performance/?period=week&d=2026-10-07").text
assert client.put("/performance/api/my-col-fold", json={"kind": "x", "cols": []}).status_code == 400
assert client.put("/performance/api/my-col-fold", json={"kind": "sales", "cols": "naver"}).status_code == 400
# 다른 사람 — 저장값 없음 → 다 펼침, 저장해도 king 값은 그대로
other = {"email": "u@x", "name": "U", "is_admin": False}
monkeypatch.setattr(common, "guard", lambda request, admin=False: (client.store, other))
monkeypatch.setattr(common, "require_store", lambda request, admin=False: (client.store, other))
assert 'data-col-fold="[]"' in client.get("/performance/?period=week&d=2026-10-07").text
client.put("/performance/api/my-col-fold", json={"kind": "sales", "cols": ["cafe24"]})
assert client.store.settings[mine]["sales"] == ["naver", "total"]
def raises(key, value, *, user=""):
raise SettingsMigrationNeeded()
client.store.set_setting = raises
assert client.put("/performance/api/my-col-fold", json={"kind": "sales", "cols": []}).status_code == 503
+12
View File
@@ -523,3 +523,15 @@ body.perf-dragging, body.perf-dragging * { cursor: grabbing !important; user-sel
.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; }
/* 열 접기(2026-11-06) — 일자별 표 머리글 위 버튼(performance.js initColFold), 접은 열 = 26px 띠(버튼만, 너비는 JS CFOLD_W 와 같게) */
.perf-cfold { display: flex; align-items: center; justify-content: center; width: 20px; height: 16px; margin: -4px auto 2px; padding: 0;
border: 0; border-radius: 4px; background: none; color: #b5b8bd; cursor: pointer; }
.perf-cfold:hover { background: rgba(0, 0, 0, .08); color: #333; }
.perf-cfold:focus-visible { outline: 2px solid #1a56db; outline-offset: 1px; }
.perf-cfold svg { transition: transform .2s ease; }
.perf-cfold[aria-expanded="false"] svg { transform: rotate(180deg); }
.perf-main th.is-cfold, .perf-main td.is-cfold { width: 26px; min-width: 26px; max-width: 26px; padding-left: 0; padding-right: 0;
font-size: 0; pointer-events: none; }
.perf-main .is-cfold > :not(.perf-cfold) { display: none !important; } /* 보기 기준(총매출·차감) 표시 규칙보다 우선 */
.perf-main th.is-cfold .perf-cfold { pointer-events: auto; margin-top: 0; }
@media (prefers-reduced-motion: reduce) { .perf-cfold svg { transition: none; } }
+52 -2
View File
@@ -257,6 +257,7 @@
// 바꾼 너비는 이 브라우저 localStorage(perf_colw_sales / perf_colw_ads, 열 = th data-col)에 계속 유지, 경계를 두 번 누르면 그 열만 자동 너비로.
// 그룹 접기·펴기 애니메이션은 apply(접는 열)/animate/settle 로 열 너비를 0 ↔ 원래 너비로 함께 움직인다.
const COLW_MIN = 36;
const CFOLD_W = 26; // 접은 열 너비 — performance.css .is-cfold 와 같게
function initColWidths(root) {
const table = root.querySelector("table.perf-colw-manual");
const row = table && table.tHead && table.tHead.rows[0];
@@ -271,7 +272,11 @@
}
// 날짜 열(label)은 조절 안 함(2026-10-27) — 늘 자동 너비(글자 길이), 손잡이 없음
function fixedCol(th) { return th.dataset.col === "label"; }
function widthOf(th) { const c = th.dataset.col; return (!fixedCol(th) && saved[c]) || auto[c] || 80; }
function widthOf(th) {
if (th.classList.contains("is-cfold")) return CFOLD_W; // 접은 열(initColFold) — 좁은 띠
const c = th.dataset.col;
return (!fixedCol(th) && saved[c]) || auto[c] || 80;
}
function apply(zero) { // zero = 너비 0 으로 둘 열(접는 중·펴기 직전)
let sum = 0;
heads.forEach(function (th) {
@@ -288,7 +293,7 @@
table.style.width = "";
heads.forEach(function (th) {
const w = th.getBoundingClientRect().width;
if (w > 0) auto[th.dataset.col] = Math.ceil(w);
if (w > 0 && !th.classList.contains("is-cfold")) auto[th.dataset.col] = Math.ceil(w);
});
apply();
}
@@ -342,6 +347,50 @@
};
}
// 열 접기(2026-11-06) — 매출 실적·광고비 일자별 표 머리글 위 버튼으로 열 하나씩 접기/펴기(날짜 열 빼고).
// 접은 열 = 좁은 띠(버튼만, 칸 클릭·메모 안 됨). 보는 사람(로그인 계정)마다 서버에 저장(PUT /api/my-col-fold) — 다른 사람 화면은 그대로.
function initColFold(root, colw) {
const table = root.querySelector("table[data-cfold-kind]");
const row = table && table.tHead && table.tHead.rows[0];
if (!row) return;
let folded = [];
try { folded = JSON.parse(table.dataset.colFold || "[]") || []; } catch (_) { folded = []; }
const ICON = '<svg viewBox="0 0 12 12" width="12" height="12" aria-hidden="true"><path d="M7.5 3 4.5 6l3 3" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/></svg>';
function setFold(th, fold) {
const i = th.cellIndex;
Array.prototype.forEach.call(table.rows, function (r) { if (r.cells[i]) r.cells[i].classList.toggle("is-cfold", fold); });
const b = th.querySelector(".perf-cfold");
b.setAttribute("aria-expanded", fold ? "false" : "true");
b.setAttribute("aria-label", b.dataset.name + (fold ? " 열 펴기" : " 열 접기"));
b.title = fold ? b.dataset.name + " 열 펴기" : "열 접기";
}
Array.prototype.forEach.call(row.cells, function (th) {
const col = th.dataset.col;
if (!col || col === "label") return;
const b = document.createElement("button");
b.type = "button";
b.className = "perf-cfold";
b.dataset.name = th.textContent.replace(/[✎\s]+/g, " ").trim();
b.innerHTML = ICON;
th.insertBefore(b, th.firstChild);
setFold(th, folded.indexOf(col) >= 0);
});
if (colw && folded.length) colw.apply();
row.addEventListener("click", function (e) {
const b = e.target.closest(".perf-cfold");
if (!b) return;
e.stopPropagation();
const th = b.parentElement, col = th.dataset.col;
const fold = !th.classList.contains("is-cfold");
setFold(th, fold);
if (colw) colw.apply();
folded = folded.filter(function (c) { return c !== col; });
if (fold) folded.push(col);
api("PUT", "/performance/api/my-col-fold", { kind: table.dataset.cfoldKind, cols: folded })
.catch(function (err) { alertMsg("접은 열을 저장하지 못했습니다: " + err.message); });
});
}
function initDashboard(root) {
const data = JSON.parse((document.getElementById("perf-data") || {}).textContent || "{}");
const METRIC_NAMES = { gross: "총매출", commission: "수수료", net: "수수료 차감 매출" };
@@ -423,6 +472,7 @@
if (fold) collapsed.push(code);
try { localStorage.setItem(GROUP_KEY, JSON.stringify(collapsed)); } catch (_) { /* 기억만 못 함 */ }
});
initColFold(root, colw);
// 수동 입력 엑셀 업로드 — 1열 날짜, 2열부터 쇼핑몰 이름 머리글. 값이 있는 칸만 반영(빈 칸은 기존 값 그대로).
// 잘못된 칸이 있으면 서버가 아무것도 저장하지 않고 칸 위치 목록을 돌려준다.