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