diff --git a/app/modules/performance/CLAUDE.md b/app/modules/performance/CLAUDE.md index 812c775..21acbf3 100644 --- a/app/modules/performance/CLAUDE.md +++ b/app/modules/performance/CLAUDE.md @@ -64,8 +64,12 @@ 직접 추가 쇼핑몰만 그룹 select 로 묶음, 이름 변경·삭제(삭제 = 그 쇼핑몰 수동 입력·수수료도). 매출 실적 표 그룹 열 = 보이는 하위 합계(일 합계엔 안 더함), ▾/▸ 하위 열 접기(localStorage). ⠿ 드래그 → `PUT /api/marketplace-order` → `sort_order`, 화면 순서는 `dashboard.ordered_marketplaces` (그룹 바로 뒤 하위) 한 곳. 상세 `docs/PERFORMANCE_MODULE.md` "직접 추가 쇼핑몰·그룹". -- **카페24(공구 제외) 열**(2026-10-30) — 직접 추가 쇼핑몰 "카페24 공동구매"(이름으로 찾음, 띄어쓰기 무시) 바로 오른쪽에 카페24 − 공동구매 계산 열 - (`dashboard._cafe24_ex_gb_column`, kind `diff`, 표 열만 — 일 합계엔 안 더함, 클릭·메모 없음). 공동구매 칸을 저장하면 그 줄 차이 칸이 바로 바뀜(`performance.js saveManual`, td `data-diff-minus`·`data-base`), 합계 줄은 입력 마친 뒤 새로고침 때. 상세 `docs/PERFORMANCE_MODULE.md` "직접 추가 쇼핑몰·그룹". +- **카페24(전체)·카페24(실적) 열**(2026-11-02, 예전 "공구 제외") — 카페24 열 이름 = 카페24(전체)(`_short_name`), 바로 오른쪽 카페24(실적) = 카페24 − 직접 추가 쇼핑몰 "자사몰(공동구매)"("카페24 공동구매"도, 이름으로 찾음·띄어쓰기 무시 — 없으면 전체 그대로, 쇼핑몰 필터·숨김과 무관하게 뺌). + 광고비 줄은 카페24(전체)와 같은 구글·메타(`dashboard._cafe24_real_column`, kind `diff`, 표 열만 — 일 합계엔 안 더함, 클릭·메모 없음). 공동구매 칸을 저장하면 그 줄 칸이 바로 바뀜(`performance.js saveManual`, td `data-diff-minus`·`data-base`), 합계 줄은 입력 마친 뒤 새로고침 때. 상세 `docs/PERFORMANCE_MODULE.md` "직접 추가 쇼핑몰·그룹". +- **합계 기준**(2026-11-02) — 일 합계 = 카페24(실적) + 공동구매 + 나머지 쇼핑몰(카페24(전체)는 안 더함 — 공동구매가 들어 있어 중복). 일 합계·ROAS·KPI·추이·비중·월/연 누적 모두 `dashboard._summary_cells`(카페24 칸 = 실적, 그래프·누적의 카페24 줄 이름도 `summary_names` = 카페24(실적)), 표의 카페24(전체) 열만 원래 값. 광고비 탭 매출 대비 광고비·합계 ROAS = `total_sales_codes`(카페24 있으면 공동구매 코드 뺌, 같은 금액). **프로젝트 회의록 머리 카드는 아직 예전 합계**(`project/router.py` `total` — 공동구매 중복). +- **매출 실적 표 열 숨기기**(2026-11-02) — 실적 설정 "공통 보기 설정" 카드(관리자만, `PUT /api/hidden-marketplaces`, `perf_settings` key `hidden_marketplaces`, 011 미적용 503) → **모든 사용자에게 적용**. **열만** 숨김(`dashboard.load_hidden`) — 일 합계·KPI·그래프·누적은 그대로, 그룹 열 = 보이는 하위 합계(다 숨기면 그룹 열도 없음). 쇼핑몰 필터(합계까지 바뀜)와 다름. 광고비 탭은 적용 안 함. +- **일 합계 열 위치**(2026-11-02) — 매출 실적·광고비 표 모두 날짜 바로 오른쪽, 날짜 열과 함께 가로 고정(왼쪽 위치 `--perf-label-w` = 날짜 열 너비, `performance.js stickyHead`). +- **기간 이동**(2026-11-02, `_period_nav.html` 공통) — 날짜 바로 좌우 화살표 SVG(글자 높이, 진한 회색), 글자 버튼 없음. - **매출 실적 표 모양(2026-10-22)** — `table.perf-autofit`(매출 탭만, 모든 기간 같음): 표가 100% 로 늘지 않고 **열 너비 = 내용 길이**, 날짜 열은 고정 210px 대신 자동 + **가로 스크롤해도 고정**(sticky left, 오른쪽 그림자). 그룹 열 = 진한 보라 머리·왼쪽 묶음 선, 하위 열 = 옅은 보라 머리(위 띠)·옅은 칸, 마지막 하위(`is-glast`, 접히면 그룹 열 `is-gclosed`) = 오른쪽 선. 접기 단추 = 22px ⊟/⊞(SVG, 세로 막대가 돌아 바뀜). 접기·펴기 애니메이션 = 하위 칸 내용 `.perf-gc` 너비·칸 여백·투명도 260ms(`setGroup(code, fold, animate)`, @@ -86,7 +90,7 @@ 수동 = 매출 실적·광고비 일자별 표에 `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`)에 계속 유지, 설정 [조절한 너비 초기화]가 둘 다 지움. 그룹 접기·펴기 때 열 너비도 함께 움직임(`colw.animate/settle`). 테스트 `tests/js/perf_colw.browser.test.js`. -- **매출 단위** 원·천원·백만원 — 설정 "보기 설정"(누구나, 이 브라우저 쿠키 `perf_unit`), 서버가 `amount_text`(천원 정수·백만원 소수 한 자리)로 그림(`router._unit_ctx` → 템플릿 `amt`). 광고비 탭은 원 그대로. +- **매출 단위** 원·천원·백만원(2026-11-02 모든 사용자 공통) — 설정 "공통 보기 설정"(관리자, `PUT /api/display-unit`, `perf_settings` key `display_unit`, 저장 값 없음·011 미적용 = 원, 예전 쿠키 `perf_unit` 은 안 봄), 서버가 `amount_text`(천원 정수·백만원 소수 한 자리)로 그림(`router._unit_ctx` → 템플릿 `amt`). 광고비 탭은 원 그대로. 표 열 너비는 사람(브라우저)마다 그대로. - 설정의 진단 카드(쇼핑몰 원본 데이터 확인·카페24 매출 대조·일별 한 번에 비교)는 2026-10-19 화면에서 뺐다(서버 API `marketplaces/{code}/reconcile`·`daily-check` 는 진단용으로 남김). ## 날짜 칸 메모 (2026-10-22, 마이그레이션 010 `perf_cell_memos`) diff --git a/app/modules/performance/dashboard.py b/app/modules/performance/dashboard.py index 45d539f..efe2148 100644 --- a/app/modules/performance/dashboard.py +++ b/app/modules/performance/dashboard.py @@ -57,27 +57,44 @@ def _group_columns(store_rows: Sequence[Mapping[str, Any]], codes: Sequence[str] return cols, members -# 카페24 − 카페24 공동구매 열(2026-10-30) — 직접 추가 쇼핑몰 "카페24 공동구매" 바로 오른쪽, 표 열만(일 합계·그래프·누적엔 안 더함). -# shortcut: 공동구매 쇼핑몰은 이름(띄어쓰기 무시)으로 찾는다 — 설정에서 이름을 바꾸면 이 열이 사라진다, 자주 바뀌면 설정 값으로. -CAFE24_GB_NAME = "카페24공동구매" +# 카페24(실적) 열(2026-11-02, 예전 "공구 제외") — 카페24(전체) 바로 오른쪽, 카페24 − 공동구매. 표 열만(일 합계·그래프·누적엔 안 더함). +# shortcut: 공동구매 쇼핑몰은 이름(띄어쓰기 무시)으로 찾는다 — 설정에서 다른 이름으로 바꾸면 빼지 않아 실적 = 전체가 된다, 자주 바뀌면 설정 값으로. +CAFE24_GB_NAMES = ("자사몰(공동구매)", "카페24공동구매") CAFE24_EX_GB = "cafe24_ex_gb" +CAFE24_REAL_NAME = "카페24(실적)" -def _cafe24_ex_gb_column(markets: Sequence[Mapping[str, Any]], codes: Sequence[str], cols: list[dict[str, Any]], - names: dict[str, str], short: dict[str, str], table: list[dict[str, Any]]) -> None: - """카페24·공동구매 둘 다 보일 때만 공동구매 열 뒤에 차이 열(kind diff — 공동구매가 그룹 하위면 같은 그룹으로 접힘).""" - gb = next((m["code"] for m in markets - if m["name"].replace(" ", "") == CAFE24_GB_NAME and m["code"] in codes), None) - if gb is None or "cafe24" not in codes: +def groupbuy_code(markets: Sequence[Mapping[str, Any]]) -> str: + """공동구매 쇼핑몰 코드, 없으면 빈 값.""" + return next((m["code"] for m in markets if m["name"].replace(" ", "") in CAFE24_GB_NAMES), "") + + +def total_sales_codes(markets: Sequence[Mapping[str, Any]]) -> list[str]: + """전체 매출에 더할 쇼핑몰 — 카페24(전체)에 공동구매가 들어 있어 카페24 가 있으면 공동구매는 뺀다(광고비 탭 매출 대비 광고비·합계 ROAS).""" + codes = [m["code"] for m in markets] + gb = groupbuy_code(markets) + return [c for c in codes if c != gb] if "cafe24" in codes else codes + + +def _summary_cells(cells: Mapping[tuple[date, str], calc.Money], gb: str) -> dict[tuple[date, str], calc.Money]: + """합계용 칸(2026-11-02) — 카페24 칸 = 카페24(실적)(카페24 − 공동구매). 일 합계·KPI·그래프·누적은 이 값으로 더해 공동구매가 두 번 안 들어간다.""" + out = dict(cells) + for (d, c), m in cells.items(): + if c == gb: + a = cells.get((d, "cafe24"), calc.Money()) + out[(d, "cafe24")] = calc.Money(gross=a.gross - m.gross, commission=a.commission - m.commission) + return out + + +def _cafe24_real_column(cols: list[dict[str, Any]], names: dict[str, str], short: dict[str, str], gb: str) -> None: + """카페24(실적) 열 머리 — 공동구매가 없으면(gb 빈 값) 전체와 같은 값이고 화면 즉시 계산도 없다.""" + col = next((c for c in cols if c["code"] == CAFE24_EX_GB), None) + if col is None: return - i = next(i for i, col in enumerate(cols) if col["code"] == gb) - # base·minus = 화면이 공동구매 칸 저장 때 이 줄 차이 칸을 바로 다시 계산할 때 씀(performance.js saveManual) - cols.insert(i + 1, {"code": CAFE24_EX_GB, "kind": "diff", "group": cols[i]["group"], "base": "cafe24", "minus": gb}) - names[CAFE24_EX_GB] = f"{names['cafe24']} − {names[gb]}" - short[CAFE24_EX_GB] = f"{short['cafe24']}(공구 제외)" - for r in table: - a, b = r["cells"]["cafe24"], r["cells"][gb] - r["cells"][CAFE24_EX_GB] = {k: a[k] - b[k] for k in ("gross", "commission", "net")} + # base·minus = 화면이 공동구매 칸 저장 때 이 줄 칸을 바로 다시 계산할 때 씀(performance.js saveManual) + col.update(kind="diff", base="cafe24", minus=gb) + names[CAFE24_EX_GB] = f"{names['cafe24']} − {names[gb]}" if gb else CAFE24_REAL_NAME + short[CAFE24_EX_GB] = CAFE24_REAL_NAME def display_status(marketplace: Mapping[str, Any], status_row: Mapping[str, Any] | None, @@ -92,9 +109,9 @@ def display_status(marketplace: Mapping[str, Any], status_row: Mapping[str, Any] return (status_row or {}).get("status") or "unknown" -# 매출 단위(2026-10-19, 실적 설정 "보기 설정" — 이 브라우저 쿠키 perf_unit) — (나누는 수, 소수 자리, 단위 이름) +# 매출 단위(2026-10-19, 11-02 실적 설정 "공통 보기 설정" — 모든 사용자 같음, 마이그레이션 011 perf_settings) — (나누는 수, 소수 자리, 단위 이름) UNITS: dict[str, tuple[int, int, str]] = {"won": (1, 0, "원"), "thousand": (1000, 0, "천원"), "million": (1_000_000, 1, "백만원")} -UNIT_COOKIE = "perf_unit" +UNIT_SETTING = "display_unit" def normalize_unit(value: Any) -> str: @@ -109,6 +126,29 @@ def normalize_colw(value: Any) -> str: return "manual" if value == "manual" else "auto" +# 매출 실적 표 열 숨기기(2026-11-02, 실적 설정 "공통 보기 설정" — 관리자가 정하면 모든 사용자에게 적용, 마이그레이션 011 perf_settings) — 코드 목록, 열만 숨김 +HIDDEN_SETTING = "hidden_marketplaces" + + +def _shared_setting(store: Any, key: str) -> Any: + """모든 사용자 공통 설정 값. 저장 값 없음·011 미적용이면 None(화면은 그대로 열린다).""" + from .db import SettingsMigrationNeeded # noqa: WPS433 + + reader = getattr(store, "get_setting", None) + try: + return reader(key) if reader else None + except SettingsMigrationNeeded: + return None + + +def load_hidden(store: Any) -> set[str]: + return set(_shared_setting(store, HIDDEN_SETTING) or ()) + + +def load_unit(store: Any) -> str: + return normalize_unit(_shared_setting(store, UNIT_SETTING)) + + def amount_text(value: Any, unit: str = "won") -> str: """금액 → 화면 글자(쉼표). 천원은 정수, 백만원은 소수 한 자리(반올림).""" div, places, _ = UNITS[normalize_unit(unit)] @@ -198,7 +238,10 @@ def build_dashboard(store: Any, *, kind: str, anchor: date, today: date, names = {m["code"]: m["name"] for m in markets} short = {c: _short_name(names[c]) for c in all_codes} # 그룹(009) — 그룹 열 = 보이는 하위 쇼핑몰 합계(표 열만, 합계·그래프·누적은 쇼핑몰 기준 그대로) - cols, group_members = _group_columns(store_rows, codes) + # 표에 그릴 열 = 고른 쇼핑몰 + 카페24 바로 뒤 카페24(실적) − 숨긴 열(합계·그래프·누적은 codes 그대로) + hidden = load_hidden(store) + shown = [x for c in codes for x in ((c, CAFE24_EX_GB) if c == "cafe24" else (c,)) if x not in hidden] + cols, group_members = _group_columns(store_rows, shown) for m in store_rows: if m["code"] in group_members: names[m["code"]] = short[m["code"]] = m["name"] @@ -220,7 +263,11 @@ def build_dashboard(store: Any, *, kind: str, anchor: date, today: date, q_start = min(period.start, cmp_start, m_cmp_start, y_cmp_start) q_end = max(period.end, year_period.end) - cells = calc.build_cells(store.daily_amounts(q_start, q_end, codes), store.rate_table()) + gb = groupbuy_code(markets) + # 공동구매를 필터로 뺐어도 카페24(실적) 계산엔 필요 — 합계·그래프는 아래에서 codes 만 더한다 + cells = calc.build_cells(store.daily_amounts(q_start, q_end, codes if not gb or gb in codes else [*codes, gb]), + store.rate_table()) + summary = _summary_cells(cells, gb) # 수동 입력(설정에서 켠 쇼핑몰) — 일자별 표의 날짜 칸을 눌러 입력. 값이 있는 칸은 표시(API 값 대신 쓰는 중) manual_codes = [m["code"] for m in markets if m.get("manual_input") and m["code"] in codes] manual_amounts = getattr(store, "manual_amounts", None) @@ -232,8 +279,8 @@ def build_dashboard(store: Any, *, kind: str, anchor: date, today: date, (manual_formulas(period.start, period.end, manual_codes) if manual_formulas and manual_codes else {}).items() if f"{d.isoformat()}|{c}" in manual_cells} - cur = calc.sum_range(cells, codes, period.start, period.end) - prev = calc.sum_range(cells, codes, cmp_start, cmp_end) + cur = calc.sum_range(summary, codes, period.start, period.end) + prev = calc.sum_range(summary, codes, cmp_start, cmp_end) period_word = {"day": "오늘" if period.start == today else "해당일", "week": "이번주" if period.start <= today <= period.end else "해당 주", "month": "이번달" if period.start <= today <= period.end else "해당 월", @@ -246,7 +293,9 @@ def build_dashboard(store: Any, *, kind: str, anchor: date, today: date, "delta": calc.pct_change(cur.net, prev.net), "cmp": cmp_label}, ] - share = calc.by_code(cells, codes, period.start, period.end) + share = calc.by_code(summary, codes, period.start, period.end) + # 비중 그래프·월 누적 표의 카페24 줄 = 카페24(실적) — 줄을 더하면 합계와 같다 + summary_names = {**names, "cafe24": CAFE24_REAL_NAME} statuses = store.statuses() configured = configured or {} problems = [] @@ -260,12 +309,18 @@ def build_dashboard(store: Any, *, kind: str, anchor: date, today: date, m_qs = "" if len(codes) == len(all_codes) else "".join(f"&m={c}" for c in codes) table = calc.main_table(period, codes, cells, today=today, holidays=holidays) + # 일 합계 = 카페24(실적) + 공동구매 + 나머지(2026-11-02) — 공동구매를 필터로 뺐으면 실적 + 나머지. + # 일 합계 ROAS 도 이 값 기준이라 _ad_lines 앞에서. + for r, s in zip(table, calc.main_table(period, codes, summary, today=today, holidays=holidays)): + r["total"] = s["total"] + if "cafe24" in codes: + r["cells"][CAFE24_EX_GB] = s["cells"]["cafe24"] _ad_lines(store, table, codes, cells, period, q_start, q_end) for r in table: for g, members in group_members.items(): r["cells"][g] = calc.total(calc.Money(gross=r["cells"][c]["gross"], commission=r["cells"][c]["commission"]) for c in members).as_dict() - _cafe24_ex_gb_column(markets, codes, cols, names, short, table) + _cafe24_real_column(cols, names, short, gb) def url(kind: str, anchor_d: date | None = None, start: date | None = None, end: date | None = None) -> str: if kind == "custom": @@ -305,10 +360,11 @@ def build_dashboard(store: Any, *, kind: str, anchor: date, today: date, "selected_all": len(codes) == len(all_codes), "kpis": kpis, "table": table, - "month": calc.month_summary(month_period.start.year, month_period.start.month, codes, cells), - "year": calc.year_months(year_period.start.year, codes, cells, today=today), - "chart_daily": calc.daily_series(period, codes, cells), - "chart_share": [{"code": c, "name": names[c], **share[c].as_dict()} for c in codes], + "summary_names": summary_names, + "month": calc.month_summary(month_period.start.year, month_period.start.month, codes, summary), + "year": calc.year_months(year_period.start.year, codes, summary, today=today), + "chart_daily": calc.daily_series(period, codes, summary), + "chart_share": [{"code": c, "name": summary_names[c], **share[c].as_dict()} for c in codes], "problems": problems, "manual_codes": manual_codes, "manual_cells": manual_cells, @@ -325,7 +381,7 @@ def build_dashboard(store: Any, *, kind: str, anchor: date, today: date, def _short_name(name: str) -> str: - return {"네이버 스마트스토어": "네이버", "토스쇼핑": "토스"}.get(name, name) + return {"네이버 스마트스토어": "네이버", "토스쇼핑": "토스", "카페24": "카페24(전체)"}.get(name, name) def build_settings(store: Any, *, configured: Mapping[str, bool], key_info: Mapping[str, Any], @@ -381,7 +437,14 @@ def build_settings(store: Any, *, configured: Mapping[str, bool], key_info: Mapp else: blocks.append({"row": r, "children": []}) stale = {v: n for v, n in key_versions_in_use.items() if key_info.get("current_version") and v != key_info["current_version"]} - return {"rows": rows, "blocks": blocks, "groups": groups, + # "매출 실적 표 열 숨기기" 목록 = 매출 실적 표에 나오는 열(그룹 열은 하위를 다 숨기면 사라진다) + hide_options: list[dict[str, str]] = [] + for r in rows: + if not r["is_group"] and r["enabled"] and r["include_in_sales"]: + hide_options.append({"code": r["code"], "name": _short_name(r["name"])}) + if r["code"] == "cafe24": + hide_options.append({"code": CAFE24_EX_GB, "name": CAFE24_REAL_NAME}) + return {"rows": rows, "blocks": blocks, "groups": groups, "hide_options": hide_options, "hidden_codes": load_hidden(store), "custom_ready": bool(store_rows) and "is_custom" in store_rows[0], "key_info": key_info, "key_versions_in_use": dict(key_versions_in_use), "stale_key_rows": sum(stale.values()), "sample_count": sample_count, diff --git a/app/modules/performance/router.py b/app/modules/performance/router.py index 5467f94..6fdd1c4 100644 --- a/app/modules/performance/router.py +++ b/app/modules/performance/router.py @@ -29,6 +29,8 @@ JSON API — 관리자 POST /performance/api/marketplaces 쇼핑몰(수동 입력 전용)·그룹 직접 추가(009) DELETE /performance/api/marketplaces/{code} 직접 추가 쇼핑몰·그룹 삭제(그 쇼핑몰 수동 입력·수수료도) PUT /performance/api/marketplace-order 쇼핑몰 순서(설정 드래그 — 매출 실적 열 순서) + PUT /performance/api/hidden-marketplaces 매출 실적 표 열 숨기기(모든 사용자에게 적용) + PUT /performance/api/display-unit 매출 단위(모든 사용자에게 적용) GET /performance/api/marketplaces/{code}/manual-days 수동 입력해 둔 날 수(삭제 확인 문구) POST /performance/api/marketplaces/{code}/rates 수수료율(적용 시작일) DELETE /performance/api/marketplaces/{code}/rates/{id} @@ -147,7 +149,7 @@ def dashboard_page( ctx["metric"] = metric if metric in ("gross", "commission", "net") else "net" ctx["auto_sync"] = _auto_sync_ctx(store, "sales") ctx["update_watch"] = _update_watch("sales", user) - _unit_ctx(request, ctx) + _unit_ctx(store, ctx) _colw_ctx(request, ctx) return render_template(request, "performance/index.html", {**common.base_ctx(user, active_tab="dashboard"), **ctx}) @@ -198,11 +200,11 @@ def api_update_status(request: Request, kind: str = "sales") -> JSONResponse: "user": job.user if job else ""}) -def _unit_ctx(request: Request, ctx: dict[str, Any]) -> None: - """매출 단위(원·천원·백만원) — 실적 설정 "보기 설정"이 이 브라우저 쿠키(perf_unit)에 둔다. 템플릿은 amt(v) 로 그린다.""" - from .dashboard import UNIT_COOKIE, UNITS, amount_text, normalize_unit # noqa: WPS433 +def _unit_ctx(store: Any, ctx: dict[str, Any]) -> None: + """매출 단위(원·천원·백만원) — 관리자가 실적 설정 "공통 보기 설정"에서 정하면 모든 사용자에게 같게. 템플릿은 amt(v) 로 그린다.""" + from .dashboard import UNITS, amount_text, load_unit # noqa: WPS433 - unit = normalize_unit(request.cookies.get(UNIT_COOKIE)) + unit = load_unit(store) ctx["unit"] = unit ctx["unit_label"] = UNITS[unit][2] ctx["amt"] = lambda v: amount_text(v, unit) @@ -231,13 +233,13 @@ def ads_page( return g store, user = g from .ad_spend import build_ad_dashboard # noqa: WPS433 - from .dashboard import _sales_marketplaces # noqa: WPS433 + from .dashboard import _sales_marketplaces, total_sales_codes # noqa: WPS433 today = today_kst() ctx = build_ad_dashboard( store, kind=period, anchor=_parse_date(d) or today, today=today, custom_from=_parse_date(from_), custom_to=_parse_date(to), holidays=_holidays(), - sales_codes=[m["code"] for m in _sales_marketplaces(store)], + sales_codes=total_sales_codes(_sales_marketplaces(store)), ) # [광고비 업데이트](2026-10-20) — 관리자가 실적 설정에서 인증정보를 넣은 광고 연동 전부를 진행 창으로. # 마지막 업데이트 = 광고 API 마지막 성공 가져오기, 다음 업데이트 = 매출 자동 업데이트와 같은 회차. @@ -283,7 +285,7 @@ def settings_page(request: Request): ctx["ad_sources"] = _ad_source_rows(store, ad_sync.configured()) ctx["ad_api_ready"] = store.ad_api_ready() ctx["auto_sync_settings"] = _auto_sync_settings_ctx(store) # 카드는 관리자에게만(템플릿) - _unit_ctx(request, ctx) + _unit_ctx(store, ctx) _colw_ctx(request, ctx) return render_template(request, "performance/settings.html", {**common.base_ctx(user, active_tab="settings", page_title="실적 설정"), **ctx}) @@ -954,6 +956,44 @@ def api_marketplace_order(request: Request, payload: dict[str, Any] = Body(...)) return JSONResponse({"ok": True}) +@router.put("/api/hidden-marketplaces") +def api_hidden_marketplaces(request: Request, payload: dict[str, Any] = Body(...)) -> JSONResponse: + """매출 실적 표 열 숨기기(2026-11-02, 관리자, 마이그레이션 011) — 체크한 코드 전부. 모든 사용자의 표에 적용.""" + from .dashboard import CAFE24_EX_GB, HIDDEN_SETTING # noqa: WPS433 + + store, user = common.require_store(request, admin=True) + raw = payload.get("codes") + if not isinstance(raw, list): + raise HTTPException(status_code=400, detail="숨길 쇼핑몰 목록이 필요합니다.") + known = {m["code"] for m in store.list_marketplaces()} | {CAFE24_EX_GB} + codes = sorted({str(c) for c in raw} & known) + _save_shared_setting(store, HIDDEN_SETTING, codes, user) + return JSONResponse({"ok": True, "codes": codes}) + + +@router.put("/api/display-unit") +def api_display_unit(request: Request, payload: dict[str, Any] = Body(...)) -> JSONResponse: + """매출 단위(2026-11-02, 관리자, 마이그레이션 011) — won·thousand·million. 모든 사용자의 매출 실적 화면에 적용.""" + from .dashboard import UNIT_SETTING, UNITS # noqa: WPS433 + + store, user = common.require_store(request, admin=True) + unit = payload.get("unit") + if not isinstance(unit, str) or unit not in UNITS: + raise HTTPException(status_code=400, detail="알 수 없는 매출 단위입니다.") + _save_shared_setting(store, UNIT_SETTING, unit, user) + return JSONResponse({"ok": True, "unit": unit}) + + +def _save_shared_setting(store: Any, key: str, value: Any, user: dict[str, Any]) -> None: + from .db import SettingsMigrationNeeded # noqa: WPS433 + + try: + store.set_setting(key, value, user=user.get("email", "")) + except SettingsMigrationNeeded: + raise HTTPException(status_code=503, detail="저장하려면 performance_db 마이그레이션 011" + "(scripts/sql/performance_db_011_settings.sql)을 먼저 적용해야 합니다.") from None + + @router.put("/api/marketplaces/{code}") def api_update_marketplace(request: Request, code: str, payload: dict[str, Any] = Body(...)) -> JSONResponse: store, _ = common.require_store(request, admin=True) diff --git a/app/modules/performance/templates/performance/_period_nav.html b/app/modules/performance/templates/performance/_period_nav.html new file mode 100644 index 0000000..46afa7a --- /dev/null +++ b/app/modules/performance/templates/performance/_period_nav.html @@ -0,0 +1,6 @@ +{# 기간 이동(2026-11-02, 매출 실적·광고비 공통) — 날짜 바로 좌우에 화살표 이미지(SVG, 글자 높이), 글자 버튼 없음 #} +
+ + {{ period.label }} + +
diff --git a/app/modules/performance/templates/performance/ads.html b/app/modules/performance/templates/performance/ads.html index 0e24291..9ef77a1 100644 --- a/app/modules/performance/templates/performance/ads.html +++ b/app/modules/performance/templates/performance/ads.html @@ -1,6 +1,6 @@ {% extends "erp_base.html" %} -{% block head_extra %}{% endblock %} +{% block head_extra %}{% endblock %} {#- ROAS 덧붙임 — "광고비(ROAS%)". 광고비가 없으면 아무것도 안 붙는다. -#} {%- macro roas(p) -%}{%- if p is not none -%}({{ "{:,}".format(p) }}%){%- endif -%}{%- endmacro -%} @@ -24,11 +24,7 @@ -
- ‹ {{ period.prev_label }} - {{ period.label }} - {{ period.next_label }} › -
+ {% include "performance/_period_nav.html" %}
@@ -102,8 +98,8 @@ {% if period_kind == 'year' %}월{% else %}날짜{% endif %} - {% for c in codes %}{% if c in detail_channels %}{% else %}{{ names[c] }} {% endif %}{% endfor %} {% if period_kind == 'year' %}월 합계{% else %}일 합계{% endif %} + {% for c in codes %}{% if c in detail_channels %}{% else %}{{ names[c] }} {% endif %}{% endfor %} @@ -112,6 +108,7 @@ {{ r.label }}{% if r.holiday %}{{ r.holiday }}{% endif %} + {{ won(r.total.gross) }}{{ roas(r.roas_total) }} {% for c in codes %} {% set v = r.cells[c].gross %} {% if r.kind == 'day' and not migration_needed %} @@ -125,7 +122,6 @@ {{ won(v) }}{{ roas(r.roas[c]) }} {% endif %} {% endfor %} - {{ won(r.total.gross) }}{{ roas(r.roas_total) }} {% endfor %} @@ -241,4 +237,4 @@ } | tojson }} {% endblock %} -{% block scripts %}{% endblock %} +{% block scripts %}{% endblock %} diff --git a/app/modules/performance/templates/performance/index.html b/app/modules/performance/templates/performance/index.html index d287f8e..408740a 100644 --- a/app/modules/performance/templates/performance/index.html +++ b/app/modules/performance/templates/performance/index.html @@ -1,6 +1,6 @@ {% extends "erp_base.html" %} -{% block head_extra %}{% endblock %} +{% block head_extra %}{% endblock %} {%- macro won(v) -%} {%- if v is none -%} @@ -42,11 +42,7 @@ -
- ‹ {{ period.prev_label }} - {{ period.label }} - {{ period.next_label }} › -
+ {% include "performance/_period_nav.html" %} @@ -142,6 +138,7 @@ {% if period_kind == 'year' %}월{% else %}날짜{% endif %} + {% if period_kind == 'year' %}월 합계{% else %}일 합계{% endif %} {#- 그룹(2026-10-22) — 그룹 열 = 보이는 하위 쇼핑몰 합계, ⊟/⊞ 로 하위 열 접기/펴기(이 브라우저에 기억, 펼치고 접을 때 애니메이션). 하위 열은 .perf-gc 로 내용을 감싼다 — 접을 때 그 너비를 0 으로 줄여 열이 부드럽게 닫힌다. is-glast = 그룹의 마지막 하위 열(오른쪽 묶음 선) -#} {% for col in cols %}{% set c = col.code %} @@ -149,7 +146,6 @@ {% if col.kind == 'group' %}{{ short_names[c] }} {% else %}{% if sub %}
{% endif %}{{ short_names[c] }}{% if c in manual_codes %} ✎{% endif %}{% if sub %}
{% endif %}{% endif %} {% endfor %} - {% if period_kind == 'year' %}월 합계{% else %}일 합계{% endif %} @@ -158,6 +154,7 @@ {{ r.label }}{% if r.holiday %}{{ r.holiday }}{% endif %} + {{ m3(r.total) }}{% if r.ads_total %}{{ adl_total(r.ads_total) }}{% endif %} {% for col in cols %} {% set c = col.code %} {% set m = r.cells[c] %} @@ -166,9 +163,9 @@ {% set gc0 %}{% if sub %}
{% endif %}{% endset %}{% set gc1 %}{% if sub %}
{% endif %}{% endset %} {% if col.kind == 'group' %} {{ m3(m) }} - {% elif col.kind == 'diff' %}{#- 카페24 − 카페24 공동구매(2026-10-30, dashboard._cafe24_ex_gb_column) — 계산 열이라 클릭·메모 없음 -#} + {% elif col.kind == 'diff' %}{#- 카페24(실적) = 카페24(전체) − 공동구매(dashboard._cafe24_real_column) — 계산 열이라 클릭·메모 없음, 광고비 줄은 카페24(전체)와 같음 -#} {%- set b = r.cells[col.base] %}{#- 일 행 = 공동구매 칸 저장 때 performance.js 가 base(카페24 총매출,수수료,차감) − 새 값으로 바로 바꿈 -#} - {{ gc0 }}{{ m3(m) }}{{ gc1 }} + {{ gc0 }}{{ m3(m) }}{{ adl(r.ads[col.base]) }}{{ gc1 }} {% elif r.kind == 'day' and c in manual_codes %} {% set is_manual = (r.date ~ '|' ~ c) in manual_cells %} {% set fx = (formula_cells or {}).get(r.date ~ '|' ~ c) %} @@ -182,7 +179,6 @@ {% if r['from'] %}data-code="{{ c }}" data-from="{{ r['from'] }}" data-to="{{ r['to'] }}"{% endif %}{% if r.kind == 'day' %} data-memo-code="{{ c }}" data-date="{{ r.date }}"{% endif %}{% if memo %} data-memo="{{ memo }}"{% endif %}>{{ gc0 }}{{ m3(m) }}{{ adl(r.ads[c]) }}{{ gc1 }} {% endif %} {% endfor %} - {{ m3(r.total) }}{% if r.ads_total %}{{ adl_total(r.ads_total) }}{% endif %} {% endfor %} @@ -218,7 +214,7 @@ {% for r in month.rows %} - {{ names[r.code] }} + {{ summary_names[r.code] }} {{ won(r.gross) }} {{ won(r.commission) }} {{ won(r.net) }} @@ -277,6 +273,7 @@

매출 기준: 결제는 결제일, 취소·반품은 발생일에 반영(음수). 수수료는 그날 적용되는 쇼핑몰 수수료율로 계산하며 일·쇼핑몰 단위로 원 미만 반올림합니다. 금액을 누르면 주문 목록을 볼 수 있습니다. + 일 합계·상단 금액·그래프·누적 = 카페24(실적) + 자사몰(공동구매) + 나머지 쇼핑몰(카페24(전체)는 더하지 않음).

@@ -297,4 +294,4 @@ } | tojson }} {% endblock %} -{% block scripts %}{% endblock %} +{% block scripts %}{% endblock %} diff --git a/app/modules/performance/templates/performance/settings.html b/app/modules/performance/templates/performance/settings.html index f673637..845a38d 100644 --- a/app/modules/performance/templates/performance/settings.html +++ b/app/modules/performance/templates/performance/settings.html @@ -1,6 +1,6 @@ {% extends "erp_base.html" %} -{% block head_extra %}{% endblock %} +{% block head_extra %}{% endblock %} {%- macro when(v) -%}{{ (v or '')[:16] | replace('T', ' ') or '—' }}{%- endmacro -%} @@ -142,23 +142,12 @@

- {# 보기 설정(2026-10-19) — 모듈 권한자 누구나, 이 브라우저에만(쿠키 perf_unit). 매출 실적 화면 금액·광고비 줄에 적용 #} + {# 보기 설정(2026-10-19) — 모듈 권한자 누구나, 이 브라우저에만 #}

보기 설정

매출 실적·광고비 화면을 보는 방식입니다. 이 브라우저에만 적용되며 고르면 바로 저장됩니다.
-
- 매출 단위 -
- {% for k, label in [('won', '원'), ('thousand', '천원'), ('million', '백만원')] %} - - {% endfor %} -
- 예: 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) #}
표 열 너비 @@ -173,6 +162,36 @@
+ {% if is_admin %} + {# 공통 보기 설정(2026-11-02, 관리자, 마이그레이션 011 perf_settings) — 매출 단위·열 숨기기, 모든 사용자에게 적용 #} +
+
+

공통 보기 설정

+ 모든 사용자의 매출 실적 화면에 적용됩니다. 고르면 바로 저장됩니다. +
+
+ 매출 단위 +
+ {% for k, label in [('won', '원'), ('thousand', '천원'), ('million', '백만원')] %} + + {% endfor %} +
+ 예: 2,475,300원 → + {% if unit == 'thousand' %}2,475{% elif unit == 'million' %}2.5{% else %}2,475,300{% endif %} +
+
+ 숨길 쇼핑몰 +
+ {% for m in hide_options %} + + {% endfor %} +
+ 체크한 쇼핑몰은 일자별 표에서 열만 숨겨집니다. 일 합계·그래프·누적 금액은 그대로입니다. +
+
+ {% endif %} + {% if is_admin and auto_sync_settings %} {# 자동 업데이트 일정(2026-10-26, 마이그레이션 011 perf_settings) — 매출 실적·광고비 따로: 사용·요일·시작/끝 시각(5분 단위)·간격(5분 단위, 기본 30분). [저장] = PUT /api/auto-sync-schedule, 스레드(auto_sync.py)가 1분 안에 반영. #} @@ -328,4 +347,4 @@ {% endblock %} -{% block scripts %}{% endblock %} +{% block scripts %}{% endblock %} diff --git a/app/modules/performance/tests/test_custom_groups.py b/app/modules/performance/tests/test_custom_groups.py index eb88932..063f7c9 100644 --- a/app/modules/performance/tests/test_custom_groups.py +++ b/app/modules/performance/tests/test_custom_groups.py @@ -6,11 +6,12 @@ import importlib from datetime import date import pytest -from fastapi import FastAPI +from fastapi import FastAPI, HTTPException from fastapi.testclient import TestClient from app.modules.performance import common, dashboard from app.modules.performance.adapters.registry import get_adapter +from app.modules.performance.db import SettingsMigrationNeeded TODAY = date(2026, 10, 7) @@ -36,6 +37,13 @@ class _Store: (date(2026, 10, 6), "custom_a"): 7_000} self.order = None self.deleted = [] + self.settings = {} + + def get_setting(self, key): + return self.settings.get(key) + + def set_setting(self, key, value, *, user=""): + self.settings[key] = value def list_marketplaces(self): return sorted((dict(r) for r in self.rows), key=lambda r: (r["sort_order"], r["code"])) @@ -113,8 +121,8 @@ def test_dashboard_group_column_sums_children_without_double_count(): ctx = dashboard.build_dashboard(_Store(), kind="week", anchor=TODAY, today=TODAY) assert ctx["codes"] == ["cafe24", "naver", "custom_b", "custom_a", "custom_c"] assert [(c["code"], c["kind"]) for c in ctx["cols"]] == [ - ("cafe24", "shop"), ("naver", "shop"), ("group_x", "group"), ("custom_b", "child"), ("custom_a", "child"), - ("custom_c", "shop")] + ("cafe24", "shop"), (dashboard.CAFE24_EX_GB, "diff"), ("naver", "shop"), ("group_x", "group"), ("custom_b", "child"), + ("custom_a", "child"), ("custom_c", "shop")] assert ctx["group_members"] == {"group_x": ["custom_b", "custom_a"]} assert ctx["names"]["group_x"] == "오프라인" day5 = next(r for r in ctx["table"] if r.get("date") == "2026-10-05") @@ -127,7 +135,7 @@ def test_dashboard_group_column_sums_children_without_double_count(): def test_dashboard_filter_hides_group_when_no_child_selected(): ctx = dashboard.build_dashboard(_Store(), kind="week", anchor=TODAY, today=TODAY, selected=["cafe24", "custom_c"]) - assert [c["code"] for c in ctx["cols"]] == ["cafe24", "custom_c"] and ctx["group_members"] == {} + assert [c["code"] for c in ctx["cols"]] == ["cafe24", dashboard.CAFE24_EX_GB, "custom_c"] and ctx["group_members"] == {} ctx = dashboard.build_dashboard(_Store(), kind="week", anchor=TODAY, today=TODAY, selected=["custom_a"]) assert [c["kind"] for c in ctx["cols"]] == ["group", "child"] day5 = next(r for r in ctx["table"] if r.get("date") == "2026-10-05") @@ -223,36 +231,152 @@ def test_dashboard_page_renders_group_header_and_child_cells(client): assert 'data-group-child="group_x" data-manual-code="custom_a" data-date="2026-10-05"' in body -def test_cafe24_minus_groupbuy_column(): - """'카페24 공동구매' 바로 오른쪽 = 카페24 − 공동구매(2026-10-30). 표 열만 — 일 합계엔 안 더함.""" +def _real(ctx, date_iso): + return next(r for r in ctx["table"] if r.get("date") == date_iso)["cells"][dashboard.CAFE24_EX_GB] + + +def test_cafe24_real_column(): + """카페24(실적) = 카페24(전체) 바로 오른쪽, 카페24 − 자사몰(공동구매). 표 열만 — 일 합계엔 안 더함.""" st = _Store() - st._find("custom_c")["name"] = "카페24 공동구매" + # 공동구매 없음 = 전체 그대로 + ctx = dashboard.build_dashboard(st, kind="week", anchor=TODAY, today=TODAY) + assert _real(ctx, "2026-10-05")["gross"] == 1_000_000 + assert ctx["short_names"]["cafe24"] == "카페24(전체)" and ctx["short_names"][dashboard.CAFE24_EX_GB] == "카페24(실적)" + + st._find("custom_c")["name"] = "자사몰 (공동구매)" + st._find("custom_c")["parent_code"] = "group_x" st.manual[(date(2026, 10, 5), "custom_c")] = 300_000 ctx = dashboard.build_dashboard(st, kind="week", anchor=TODAY, today=TODAY) - assert [c["code"] for c in ctx["cols"]][-2:] == ["custom_c", dashboard.CAFE24_EX_GB] + assert [c["code"] for c in ctx["cols"]][:2] == ["cafe24", dashboard.CAFE24_EX_GB] + assert ctx["cols"][1] == {"code": dashboard.CAFE24_EX_GB, "kind": "diff", "group": "", "base": "cafe24", "minus": "custom_c"} + assert _real(ctx, "2026-10-05") == {"gross": 700_000, "commission": 0, "net": 700_000} day5 = next(r for r in ctx["table"] if r.get("date") == "2026-10-05") - assert day5["cells"][dashboard.CAFE24_EX_GB] == {"gross": 700_000, "commission": 0, "net": 700_000} - assert day5["total"]["gross"] == 1_450_000 # 카페24 + 매장 150,000 + 공동구매 300,000 + # 일 합계 = 카페24(실적) 700,000 + 공동구매 300,000 + 매장 150,000 — 카페24(전체) 1,000,000 은 안 더함 + assert day5["total"] == {"gross": 1_150_000, "commission": 10_000, "net": 1_140_000} week = next(r for r in ctx["table"] if r["kind"] == "week") assert week["cells"][dashboard.CAFE24_EX_GB]["gross"] == 700_000 + assert week["total"]["gross"] == 1_157_000 # 주간합계도 같은 규칙(매장 157,000) - # 카페24 를 고르지 않으면 열 없음, 공동구매가 그룹 하위면 같은 그룹으로 접힘 + # 공동구매를 필터로 빼도 실적에서는 뺀다 — 일 합계 = 실적 + 나머지 + ctx = dashboard.build_dashboard(st, kind="week", anchor=TODAY, today=TODAY, selected=["cafe24"]) + assert _real(ctx, "2026-10-05")["gross"] == 700_000 + assert next(r for r in ctx["table"] if r.get("date") == "2026-10-05")["total"]["gross"] == 700_000 + # 카페24 를 고르지 않으면 열 없음, 일 합계에 공동구매 그대로 ctx = dashboard.build_dashboard(st, kind="week", anchor=TODAY, today=TODAY, selected=["custom_c"]) assert dashboard.CAFE24_EX_GB not in [c["code"] for c in ctx["cols"]] - st._find("custom_c")["parent_code"] = "group_x" + assert next(r for r in ctx["table"] if r.get("date") == "2026-10-05")["total"]["gross"] == 300_000 + + +def test_summaries_match_day_total(): + """KPI·추이·비중·월/연 누적도 일 합계와 같은 기준 — 공동구매가 두 번 안 들어감, 카페24 줄 = 카페24(실적).""" + st = _Store() + st._find("custom_c")["name"] = "자사몰(공동구매)" + st.manual[(date(2026, 10, 5), "custom_c")] = 300_000 ctx = dashboard.build_dashboard(st, kind="week", anchor=TODAY, today=TODAY) - assert ctx["cols"][-1] == {"code": dashboard.CAFE24_EX_GB, "kind": "diff", "group": "group_x", - "base": "cafe24", "minus": "custom_c"} + week_total = next(r for r in ctx["table"] if r["kind"] == "week")["total"] + assert week_total["gross"] == 1_157_000 # 카페24(전체) 1,000,000 + 매장 157,000 + assert ctx["kpis"][0]["value"] == week_total["net"] + assert next(p for p in ctx["chart_daily"] if p["date"] == "2026-10-05")["gross"] == 1_150_000 + assert sum(s["gross"] for s in ctx["chart_share"]) == 1_157_000 + assert next(s for s in ctx["chart_share"] if s["code"] == "cafe24")["name"] == "카페24(실적)" + assert ctx["month"]["total"]["gross"] == 1_157_000 and ctx["year"]["total"]["gross"] == 1_157_000 + assert next(r for r in ctx["month"]["rows"] if r["code"] == "cafe24")["gross"] == 700_000 + assert ctx["year"]["rows"][9]["gross"] == 1_157_000 + # 카페24(전체) 열은 원래 값 그대로, 공동구매 열도 그대로 + day5 = next(r for r in ctx["table"] if r.get("date") == "2026-10-05") + assert day5["cells"]["cafe24"]["gross"] == 1_000_000 and day5["cells"]["custom_c"]["gross"] == 300_000 -def test_dashboard_page_renders_cafe24_minus_groupbuy(client): - client.store._find("custom_c")["name"] = "카페24 공동구매" +def test_total_sales_codes_drops_groupbuy_only_with_cafe24(): + m = lambda c, n: {"code": c, "name": n} # noqa: E731 + assert dashboard.total_sales_codes([m("cafe24", "카페24"), m("x", "자사몰 (공동구매)"), m("y", "네이버")]) == ["cafe24", "y"] + assert dashboard.total_sales_codes([m("x", "자사몰(공동구매)"), m("y", "네이버")]) == ["x", "y"] + assert dashboard.total_sales_codes([m("cafe24", "카페24"), m("y", "네이버")]) == ["cafe24", "y"] + + +def test_day_total_roas_uses_real_total(): + """일 합계 ROAS = 일 합계 금액(공동구매 중복 없음) ÷ 일 합계 광고비.""" + st = _Store() + st._find("custom_c")["name"] = "자사몰(공동구매)" + st.manual[(date(2026, 10, 5), "custom_c")] = 300_000 + st.ad_amounts = lambda s, e: ({(date(2026, 10, 5), "google"): 115_000}, {}) + ctx = dashboard.build_dashboard(st, kind="week", anchor=TODAY, today=TODAY) + day5 = next(r for r in ctx["table"] if r.get("date") == "2026-10-05") + assert day5["ads_total"]["amount"] == 115_000 and day5["ads_total"]["roas"] == 1000 # 1,150,000 ÷ 115,000 + + +def test_hidden_columns_only_hide_table_columns(): + """열 숨기기(모든 사용자 공통 설정) — 열만 숨김, 일 합계·그래프 그대로. 하위를 다 숨기면 그룹 열도 없음.""" + st = _Store() + st.settings[dashboard.HIDDEN_SETTING] = ["cafe24", "custom_a", "custom_b"] + ctx = dashboard.build_dashboard(st, kind="week", anchor=TODAY, today=TODAY) + assert [c["code"] for c in ctx["cols"]] == [dashboard.CAFE24_EX_GB, "naver", "custom_c"] + assert _real(ctx, "2026-10-05")["gross"] == 1_000_000 # 전체를 숨겨도 실적은 계산됨 + assert next(r for r in ctx["table"] if r.get("date") == "2026-10-05")["total"]["gross"] == 1_150_000 + assert ctx["codes"] == ["cafe24", "naver", "custom_b", "custom_a", "custom_c"] + st.settings[dashboard.HIDDEN_SETTING] = [dashboard.CAFE24_EX_GB] + ctx = dashboard.build_dashboard(st, kind="week", anchor=TODAY, today=TODAY) + assert dashboard.CAFE24_EX_GB not in [c["code"] for c in ctx["cols"]] + + +def test_hidden_setting_missing_migration_shows_everything(): + st = _Store() + + def raises(key): + raise SettingsMigrationNeeded() + + st.get_setting = raises + assert dashboard.load_hidden(st) == set() + assert "naver" in [c["code"] for c in dashboard.build_dashboard(st, kind="week", anchor=TODAY, today=TODAY)["cols"]] + + +def test_api_hidden_marketplaces(client): + """저장값이 그대로 다른 사용자 화면에도 — 쿠키가 아니라 서버 설정(모르는 코드는 버림).""" + r = client.put("/performance/api/hidden-marketplaces", json={"codes": ["naver", "ghost", dashboard.CAFE24_EX_GB, "naver"]}) + assert r.status_code == 200 and r.json()["codes"] == [dashboard.CAFE24_EX_GB, "naver"] + assert client.store.settings[dashboard.HIDDEN_SETTING] == [dashboard.CAFE24_EX_GB, "naver"] + head = TestClient(client.app).get("/performance/?period=week&d=2026-10-07").text.split("", 1)[1].split("", 1)[0] + assert 'data-col="naver"' not in head and 'data-col="cafe24"' in head + assert client.put("/performance/api/hidden-marketplaces", json={"codes": "naver"}).status_code == 400 + assert client.put("/performance/api/hidden-marketplaces", json={"codes": []}).json()["codes"] == [] + + def raises(key, value, *, user=""): + raise SettingsMigrationNeeded() + + client.store.set_setting = raises + assert client.put("/performance/api/hidden-marketplaces", json={"codes": []}).status_code == 503 + + +def test_api_hidden_marketplaces_admin_only(client, monkeypatch): + def require_store(request, admin=False): + if admin: + raise HTTPException(status_code=403) + return client.store, {"email": "u@x"} + + monkeypatch.setattr(common, "require_store", require_store) + assert client.put("/performance/api/hidden-marketplaces", json={"codes": ["naver"]}).status_code == 403 + assert dashboard.HIDDEN_SETTING not in client.store.settings + + +def test_dashboard_page_renders_cafe24_real(client): + client.store._find("custom_c")["name"] = "자사몰(공동구매)" client.store.manual[(date(2026, 10, 5), "custom_c")] = 300_000 + client.store.settings[dashboard.HIDDEN_SETTING] = ["naver"] html = client.get("/performance/?period=week&d=2026-10-07").text head = html.split("", 1)[1].split("", 1)[0] - assert head.index('data-col="custom_c"') < head.index(f'data-col="{dashboard.CAFE24_EX_GB}"') - assert "카페24(공구 제외)" in head + # 날짜 → 일 합계 → 카페24(전체) → 카페24(실적) + assert head.index('data-col="label"') < head.index('data-col="total"') < head.index('data-col="cafe24"') < head.index(f'data-col="{dashboard.CAFE24_EX_GB}"') + assert "카페24(전체)" in head and "카페24(실적)" in head and 'data-col="naver"' not in head body = html.split("", 1)[1].split("", 1)[0] assert "700,000" in body # 일 행만 화면 즉시 계산용 값(카페24 총매출,수수료,차감) — performance.js saveManual assert 'data-diff-minus="custom_c" data-base="1000000,0,1000000"' in body + + +def test_cafe24_real_shows_same_ad_lines(client): + """카페24(전체)의 구글·메타 광고비 줄이 카페24(실적) 칸에도 그대로.""" + client.store.ad_amounts = lambda s, e: ({(date(2026, 10, 5), "google"): 11_000, (date(2026, 10, 5), "meta"): 22_000}, {}) + body = client.get("/performance/?period=week&d=2026-10-07").text.split("", 1)[1] + row = next(tr for tr in body.split("구글11,000") == 2 and row.count("메타22,000") == 2 + assert row.index("구글") < row.index("data-code=\"naver\"") diff --git a/app/modules/performance/tests/test_dashboard_ads_units.py b/app/modules/performance/tests/test_dashboard_ads_units.py index f3c988c..66972c5 100644 --- a/app/modules/performance/tests/test_dashboard_ads_units.py +++ b/app/modules/performance/tests/test_dashboard_ads_units.py @@ -121,15 +121,51 @@ def test_dashboard_page_renders_unit_and_ad_lines(monkeypatch): assert 'class="perf-adl"' in html and "구글100,000(413%)" in html and "메타50,000" in html assert "200,000(300%)" in html and "단위:" not in html - client.cookies.set("perf_unit", "thousand") + # 매출 단위 = 서버 공통 설정(2026-11-02) — 예전 브라우저 쿠키는 안 봄 + client.cookies.set("perf_unit", "million") + assert "단위:" not in client.get("/performance/?period=week&d=2026-10-07").text + client.cookies.delete("perf_unit") + store.get_setting = lambda key: "thousand" if key == dashboard.UNIT_SETTING else None html = client.get("/performance/?period=week&d=2026-10-07").text assert "단위: 천원" in html and "2,000<" in html and "구글100(413%)" in html assert "2,000,000<" not in html.split("perf-main", 1)[1].split("", 1)[0] - client.cookies.set("perf_unit", "million") + store.get_setting = lambda key: "million" if key == dashboard.UNIT_SETTING else None html = client.get("/performance/?period=week&d=2026-10-07").text assert "단위: 백만원" in html and ">2.0<" in html and '"unit": "million"' in html +def test_api_display_unit(monkeypatch): + import importlib + + from fastapi import FastAPI, HTTPException + from fastapi.testclient import TestClient + + from app.modules.performance import common + + perf_router = importlib.import_module("app.modules.performance.router") + saved = {} + store = _Store() + store.set_setting = lambda key, value, *, user="": saved.__setitem__(key, (value, user)) + monkeypatch.setattr(common, "require_store", lambda request, admin=False: (store, {"email": "king@x"})) + app = FastAPI() + app.include_router(perf_router.router) + client = TestClient(app) + + assert client.put("/performance/api/display-unit", json={"unit": "thousand"}).json()["unit"] == "thousand" + assert saved[dashboard.UNIT_SETTING] == ("thousand", "king@x") + assert client.put("/performance/api/display-unit", json={"unit": "nope"}).status_code == 400 + assert client.put("/performance/api/display-unit", json={"unit": ["won"]}).status_code == 400 + + def not_admin(request, admin=False): + if admin: + raise HTTPException(status_code=403) + return store, {"email": "u@x"} + + monkeypatch.setattr(common, "require_store", not_admin) + assert client.put("/performance/api/display-unit", json={"unit": "won"}).status_code == 403 + assert saved[dashboard.UNIT_SETTING] == ("thousand", "king@x") + + def test_total_roas_uses_whole_day_total(): """일 합계 ROAS = 그날 일 합계 금액(광고비 없는 쇼핑몰 매출 포함) ÷ 일 합계 광고비 — 예전엔 광고비 있는 쇼핑몰 매출만 더했다.""" class _S(_Store): diff --git a/app/static/performance.css b/app/static/performance.css index 4724a44..a31932c 100644 --- a/app/static/performance.css +++ b/app/static/performance.css @@ -87,13 +87,12 @@ a.perf-tab.is-active:link, a.perf-tab.is-active:visited { color: #fff; } .perf-seg:hover { background: var(--color-ghost-gray); } .perf-seg.is-active { background: var(--color-deep-black); color: #fff; } a.perf-seg.is-active, a.perf-seg.is-active:link, a.perf-seg.is-active:visited { color: #fff; } -.perf-nav { display: inline-flex; align-items: center; gap: 6px; } -.perf-nav-btn { - font-size: 12px; padding: 5px 9px; border: 1px solid var(--perf-line); border-radius: 8px; background: #fff; - white-space: nowrap; -} +.perf-nav { display: inline-flex; align-items: center; gap: 2px; } +/* 기간 이동 화살표(2026-11-02) — 진한 회색 SVG, 높이 = 날짜 글자 크기(1em) */ +.perf-nav-btn { display: inline-flex; padding: 4px 5px; border-radius: 6px; font-size: 14px; } .perf-nav-btn:hover { background: var(--color-ghost-gray); } -.perf-nav-label { font-weight: 600; font-size: 14px; min-width: 200px; text-align: center; } +.perf-nav-btn svg { display: block; height: 1em; width: auto; fill: none; stroke: #444; stroke-width: 2.6; stroke-linecap: round; stroke-linejoin: round; } +.perf-nav-label { font-weight: 600; font-size: 14px; text-align: center; } .perf-custom { display: inline-flex; align-items: center; gap: 6px; } .perf-custom[hidden] { display: none; } /* 공통 .erp-input 의 min-width:240px 를 날짜칸에서만 푼다 */ @@ -368,6 +367,7 @@ td.is-link:hover { background: #eef2ff; text-decoration: underline; } .perf-opt-row { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; } .perf-opt-label { font-weight: 600; min-width: 72px; } .perf-opt-row + .perf-opt-row { margin-top: 10px; } +.perf-hide-list { display: flex; flex-wrap: wrap; gap: 0 12px; } /* 자동 업데이트 일정(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); } @@ -438,11 +438,15 @@ body.perf-dragging, body.perf-dragging * { cursor: grabbing !important; user-sel /* ── 매출 실적 표(2026-10-22): 열 너비 = 내용 길이(모든 기간 같음), 날짜 열 고정, 그룹·하위 열 구분, 접기 애니메이션 ── */ .perf-main.perf-autofit { width: auto; } .perf-main.perf-autofit thead th.perf-th-label, .perf-main.perf-autofit .perf-td-label { width: auto; min-width: 0; max-width: none; overflow: visible; } -/* 날짜 열 — 가로 스크롤해도 왼쪽에 고정(배경을 깔아 뒤로 지나가는 칸을 가림, 오른쪽 그림자로 경계) */ +/* 날짜 열 + 일 합계 열(2026-11-02) — 가로 스크롤해도 왼쪽에 고정(배경을 깔아 뒤로 지나가는 칸을 가림, 일 합계 오른쪽 그림자로 경계). + 일 합계 왼쪽 위치 = 날짜 열 너비(자동 너비라 performance.js stickyHead 가 --perf-label-w 로 넣는다) */ .perf-main.perf-autofit .perf-th-label, .perf-main.perf-autofit .perf-td-label { - position: sticky; left: 0; z-index: 2; box-shadow: inset -1px 0 0 #e3e3e3, 6px 0 6px -6px rgba(0, 0, 0, .22); + position: sticky; left: 0; z-index: 2; box-shadow: inset -1px 0 0 #e3e3e3; } -.perf-main.perf-autofit thead th.perf-th-label { z-index: 4; } +.perf-main.perf-autofit .perf-th-total, .perf-main.perf-autofit .perf-td-total { + position: sticky; left: var(--perf-label-w, 0); z-index: 2; box-shadow: inset -1px 0 0 #e3e3e3, 6px 0 6px -6px rgba(0, 0, 0, .22); +} +.perf-main.perf-autofit thead th.perf-th-label, .perf-main.perf-autofit thead th.perf-th-total { z-index: 4; } :where(.perf-main.perf-autofit) .perf-td-label { background: #fff; } /* 주간합계·기간 합계 줄 배경은 그 줄 규칙 그대로 */ /* 그룹 열 = 진한 보라 머리 + 왼쪽 묶음 선, 하위 열 = 옅은 보라 머리(위 띠) + 옅은 칸, 마지막 하위 열(접히면 그룹 열)이 오른쪽 묶음 선 */ .perf-main th.perf-th-group { background: #e6defa; color: #3d1d8a; font-weight: 800; box-shadow: inset 2px 0 0 #8a6fd8; } @@ -491,9 +495,10 @@ body.perf-dragging, body.perf-dragging * { cursor: grabbing !important; user-sel 날짜 칸 가로 고정(sticky left)은 그대로. 연간 보기 "연간 합계"는 맨 아래 그대로(제목 행만 고정). */ .perf-main-wrap { overflow-x: auto; overflow-y: hidden; } .perf-main-wrap .perf-main thead th { z-index: 3; } -.perf-main-wrap .perf-main thead th.perf-th-label { z-index: 5; } +.perf-main-wrap .perf-main thead th.perf-th-label, .perf-main-wrap .perf-main thead th.perf-th-total { z-index: 5; } .perf-main-wrap .perf-main tbody tr.perf-row-total:first-child > * { position: relative; z-index: 2; } .perf-main-wrap .perf-main tbody tr.perf-row-total:first-child > .perf-td-label { position: sticky; left: 0; z-index: 4; } +.perf-main-wrap .perf-main tbody tr.perf-row-total:first-child > .perf-td-total { position: sticky; left: var(--perf-label-w, 0); z-index: 4; } /* 내려온 제목 행 아래 1px — 표 칸 사이 선(border-collapse)은 칸과 함께 안 움직여 그 틈으로 뒤 줄 글자가 비쳤다 → 칸이 직접 선을 그림 */ .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) — 표 상자 가로 막대·실적 화면 세로 막대. 손잡이만 옅은 회색 */ diff --git a/app/static/performance.js b/app/static/performance.js index 674e041..bb4050e 100644 --- a/app/static/performance.js +++ b/app/static/performance.js @@ -24,7 +24,7 @@ } function fmt(n) { return Number(n || 0).toLocaleString("ko-KR"); } function won(n) { return n ? fmt(n) : '–'; } - // 매출 단위(실적 설정 "보기 설정", 쿠키 perf_unit) — 서버 dashboard.amount_text 와 같은 표기(천원 정수, 백만원 소수 한 자리) + // 매출 단위(실적 설정 "공통 보기 설정", 모든 사용자 같음) — 서버 dashboard.amount_text 와 같은 표기(천원 정수, 백만원 소수 한 자리) function unitWon(n, unit) { if (!n) return won(0); if (unit === "thousand") return Math.round(n / 1000).toLocaleString("ko-KR"); @@ -817,7 +817,7 @@ if (s && shown[cls] != null) s.innerHTML = unitWon(shown[cls], data.unit); }); td.classList.toggle("is-stale", res.net == null); - // 카페24(공구 제외) 열(2026-10-30) — 공동구매 칸을 저장하면 같은 줄 차이 칸도 바로(카페24 − 새 값). 합계 줄은 새로고침 때. + // 카페24(실적) 열 — 공동구매 칸을 저장하면 같은 줄 칸도 바로(카페24 − 새 값). 합계 줄은 새로고침 때. const diff = td.parentElement.querySelector('td[data-diff-minus="' + td.dataset.manualCode + '"]'); if (diff) { const base = diff.dataset.base.split(",").map(Number); @@ -1292,13 +1292,18 @@ } function initSettings(root) { - // 보기 설정 — 매출 단위(원·천원·백만원)를 이 브라우저 쿠키에(1년). 매출 실적 화면을 다시 열면 적용 + // 공통 보기 설정(관리자) — 매출 단위(원·천원·백만원)를 서버에, 모든 사용자의 매출 실적 화면에 적용 const UNIT_EX = { won: "2,475,300", thousand: "2,475", million: "2.5" }; - root.querySelectorAll("#perf-view-opts [data-unit]").forEach(function (b) { - b.addEventListener("click", function () { + root.querySelectorAll("#perf-shared-view [data-unit]").forEach(function (b) { + b.addEventListener("click", async function () { const u = b.dataset.unit; - document.cookie = "perf_unit=" + u + "; path=/performance; max-age=31536000; SameSite=Lax"; - root.querySelectorAll("#perf-view-opts [data-unit]").forEach(function (x) { + try { + await api("PUT", "/performance/api/display-unit", { unit: u }); + } catch (err) { + alertMsg("저장 실패: " + err.message); + return; + } + root.querySelectorAll("#perf-shared-view [data-unit]").forEach(function (x) { x.classList.toggle("is-active", x === b); x.setAttribute("aria-checked", x === b ? "true" : "false"); }); @@ -1331,6 +1336,20 @@ colwReset.textContent = "초기화했습니다"; setTimeout(function () { colwReset.textContent = "조절한 너비 초기화"; }, 1800); }); + // 공통 보기 설정 — 매출 실적 표 열 숨기기(2026-11-02, 관리자), 고르면 바로 저장(차례대로, 실패하면 그 칸만 되돌림) + const hideBoxes = Array.from(root.querySelectorAll("#perf-shared-view [data-hide]")); + let hideSave = Promise.resolve(); + hideBoxes.forEach(function (c) { + c.addEventListener("change", function () { + const codes = hideBoxes.filter(function (x) { return x.checked; }).map(function (x) { return x.dataset.hide; }); + hideSave = hideSave.then(function () { + return api("PUT", "/performance/api/hidden-marketplaces", { codes: codes }); + }).catch(function (err) { + c.checked = !c.checked; + alertMsg("저장 실패: " + err.message); + }); + }); + }); initAutoSyncSettings(root); // 사용 / 매출 집계 토글 — 바로 저장, 실패하면 되돌림 @@ -1744,10 +1763,15 @@ cells.forEach(function (c) { c.style.transform = v; }); wrap.classList.toggle("is-stuck", off > 0); } + const labelHead = head.querySelector(".perf-th-label"); + function layout() { // 일 합계 열 가로 고정 위치 = 날짜 열 너비(자동 너비라 CSS 만으로는 모른다) + if (labelHead) table.style.setProperty("--perf-label-w", labelHead.getBoundingClientRect().width + "px"); + update(); + } window.addEventListener("scroll", update, true); - window.addEventListener("resize", update); - if (window.ResizeObserver) new ResizeObserver(update).observe(table); - update(); + window.addEventListener("resize", layout); + if (window.ResizeObserver) new ResizeObserver(layout).observe(table); + layout(); }); } diff --git a/docs/PERFORMANCE_MODULE.md b/docs/PERFORMANCE_MODULE.md index 47a854c..e41056f 100644 --- a/docs/PERFORMANCE_MODULE.md +++ b/docs/PERFORMANCE_MODULE.md @@ -284,11 +284,15 @@ 10, 20, … 다시 매김(`reorder_marketplaces`). 드래그 단위는 tbody(그룹 없는 행 하나, 또는 그룹 + 하위) — 하위 쇼핑몰은 그 그룹 안에서만. 화면 순서 = `dashboard.ordered_marketplaces`(sort_order 순, 그룹 바로 뒤에 하위) — 설정 표·매출 실적 열·필터 공통. 설정 표도 예전 `registry` 순서 대신 이 순서(009 없어도 됨). -- **카페24(공구 제외) 열**(2026-10-30) — 직접 추가 쇼핑몰 이름이 "카페24 공동구매"(띄어쓰기 무시)면 그 열 바로 오른쪽에 - 카페24 − 카페24 공동구매(총매출·수수료·차감 매출 각각) 계산 열(`dashboard._cafe24_ex_gb_column`, 열 코드 `cafe24_ex_gb`, kind `diff`). - 카페24·공동구매 둘 다 보일 때만, 표 열만(일 합계·KPI·그래프엔 안 더함), 클릭·메모 없음. 공동구매가 그룹 하위면 같은 그룹으로 접힘. - 이름으로 찾으므로 설정에서 이름을 바꾸면 열이 사라진다. 공동구매 칸 저장 즉시 그 줄 차이 칸 = 카페24(td `data-base` 총매출,수수료,차감) − 저장 응답 - (`performance.js saveManual`, 일 행만 — 주간·기간 합계 줄은 입력을 마친 뒤 새로고침 때). 테스트 `tests/js/perf_manual.test.js` "[공구 제외]". +- **카페24(전체)·카페24(실적) 열**(2026-11-02, 예전 2026-10-30 "공구 제외") — 카페24 열 이름 = 카페24(전체), 바로 오른쪽에 카페24(실적) = + 카페24 − 직접 추가 쇼핑몰 "자사몰(공동구매)" 또는 "카페24 공동구매"(띄어쓰기 무시, 총매출·수수료·차감 매출 각각) 계산 열(`dashboard._cafe24_real_column`, 열 코드 `cafe24_ex_gb`, kind `diff`). + 카페24가 보이면 늘 있고, 공동구매 쇼핑몰이 없으면(다른 이름으로 바꿔도) 전체 그대로. 쇼핑몰 필터·숨김으로 공동구매 열이 안 보여도 뺀다. 표 열만(일 합계·KPI·그래프엔 안 더함), 클릭·메모 없음. + 칸 아래 광고비 줄 = 카페24(전체)의 구글·메타 그대로. 공동구매 칸 저장 즉시 그 줄 칸 = 카페24(td `data-base` 총매출,수수료,차감) − 저장 응답 + (`performance.js saveManual`, 일 행만 — 주간·기간 합계 줄은 입력을 마친 뒤 새로고침 때). 테스트 `tests/js/perf_manual.test.js` "[공구 제외]", `test_custom_groups.py`. +- **합계 기준**(2026-11-02) — 일 합계 = 카페24(실적) + 공동구매 + 나머지 쇼핑몰(카페24(전체)는 공동구매가 들어 있어 안 더함). 공동구매를 필터로 뺐으면 실적 + 나머지, 카페24 를 안 골랐으면 고른 쇼핑몰 합. + 일 합계·ROAS·KPI·추이·비중·월/연 누적 모두 같은 기준(`dashboard._summary_cells` — 카페24 칸을 실적으로 바꾼 값, 그래프·누적의 카페24 줄 이름 = 카페24(실적)), 표의 카페24(전체) 열만 원래 값. + 광고비 탭 매출 대비 광고비·합계 ROAS 도 같은 금액(`total_sales_codes` — 카페24 가 있으면 공동구매 코드를 뺌). 프로젝트 회의록 머리 카드(`project/router.py`)는 아직 예전 합계. +- **매출 실적 표 열 숨기기**(2026-11-02) — 실적 설정 "공통 보기 설정" 카드(관리자), `PUT /performance/api/hidden-marketplaces`, `perf_settings` key `hidden_marketplaces`(코드 배열, 011 미적용이면 저장 503·표는 다 보임). 모든 사용자의 일자별 표에서 열만 숨김(일 합계·KPI·그래프·누적 그대로), 그룹 열은 보이는 하위 합계. - 테스트: `app/modules/performance/tests/test_custom_groups.py`, 화면 `tests/js/perf_groups.browser.test.js`(render_performance.py 의 `perf_*_groups.html`). ### 연동 단계 체크리스트(쇼핑몰마다) @@ -417,7 +421,7 @@ - **설정 진단 카드 삭제** — "쇼핑몰 원본 데이터 확인"·"카페24 매출 대조"·"일별 한 번에 비교" 카드와 그 화면 스크립트를 뺐다 (사용자 요청 — 쇼핑몰별 규칙 대조가 끝나 더 안 씀). 서버 API `GET /api/marketplaces/{code}/reconcile`·`daily-check` 와 어댑터 `reconcile`은 다시 대조가 필요할 때를 위해 남겼다(화면 진입점 없음). 아래 절의 "원본 데이터 확인"·"매출 대조" 설명은 그 당시 기록. - - **보기 설정 · 매출 단위** — 설정 화면 "보기 설정" 카드(모듈 권한자 누구나): 원·천원·백만원. 이 브라우저 쿠키 `perf_unit`(1년, path `/performance`)에 두고 + - **공통 보기 설정 · 매출 단위**(2026-11-02 모든 사용자 공통, 예전엔 브라우저 쿠키 `perf_unit`) — 설정 화면 "공통 보기 설정" 카드(관리자): 원·천원·백만원. `perf_settings` key `display_unit`(`PUT /api/display-unit`, 저장 값 없음·011 미적용 = 원)에 두고 매출 실적 화면을 서버가 그 단위로 그린다(`dashboard.amount_text` — 천원 = 정수 반올림, 백만원 = 소수 한 자리, `router._unit_ctx` → 템플릿 `amt`·`money`). 표·월/연 누적 카드 머리에 "단위: 천원", KPI·연 누적은 "3,835천원". 수동 입력은 늘 원 단위로 넣는다(입력 직후 칸은 JS `unitWon`). 광고비 탭·그래프 말풍선은 원 그대로. - **매출 칸 아래 광고비(ROAS%)** — 일자별 × 쇼핑몰 표의 매출 칸마다 그 쇼핑몰 광고비와 ROAS 를 광고비 색(`--perf-ad`) 작은 줄로(`dashboard._ad_lines`). diff --git a/tests/js/perf_groups.browser.test.js b/tests/js/perf_groups.browser.test.js index f887685..9f2fde0 100644 --- a/tests/js/perf_groups.browser.test.js +++ b/tests/js/perf_groups.browser.test.js @@ -35,7 +35,7 @@ function page(file) { }); }; const h0 = await heads(); - check("그룹 열이 하위 열 바로 앞", JSON.stringify(h0.slice(1, 7)) === JSON.stringify(["카페24", "네이버", "오프라인", "매장A ✎", "매장B ✎", "행사 ✎"]), h0); + check("그룹 열이 하위 열 바로 앞", JSON.stringify(h0.slice(1, 9)) === JSON.stringify(["일 합계", "카페24(전체)", "카페24(실적)", "네이버", "오프라인", "매장A ✎", "매장B ✎", "행사 ✎"]), h0); const expanded = function () { return p.getAttribute('[data-group-toggle="group_off"]', "aria-expanded"); }; // 열 너비 = 내용 길이 — 표가 화면보다 좁으면 늘이지 않는다, 각 열은 그 열의 가장 긴 글자 + 여백 정도 const fit = await p.evaluate(function () { diff --git a/tests/js/perf_manual.test.js b/tests/js/perf_manual.test.js index 8607c87..3d824ab 100644 --- a/tests/js/perf_manual.test.js +++ b/tests/js/perf_manual.test.js @@ -72,9 +72,9 @@ function gross(td) { return td.querySelector(".v-gross").textContent.trim(); } const e = await env("perf_dash.html"); const heads = Array.from(e.d.querySelectorAll(".perf-main thead th")).map(function (th) { return th.textContent.replace("✎", "").trim(); }); check("[순서] 카페24·네이버·쿠팡·토스·GS샵·11번가 다음 나머지", heads.join(",") === - "날짜,카페24,네이버,쿠팡,토스,GS샵,11번가,오늘의집,G마켓,카카오,롯데ON,일 합계", heads); - check("[수동] 수동 입력 쇼핑몰 제목에 ✎ 표시", /✎/.test(e.d.querySelectorAll(".perf-main thead th")[3].textContent) && - !/✎/.test(e.d.querySelectorAll(".perf-main thead th")[1].textContent)); + "날짜,일 합계,카페24(전체),카페24(실적),네이버,쿠팡,토스,GS샵,11번가,오늘의집,G마켓,카카오,롯데ON", heads); + check("[수동] 수동 입력 쇼핑몰 제목에 ✎ 표시", /✎/.test(e.d.querySelectorAll(".perf-main thead th")[5].textContent) && + !/✎/.test(e.d.querySelectorAll(".perf-main thead th")[2].textContent)); // 2026-10-21 — 앞으로의 날도 입력 칸(사용자 요청). 주간합계 줄은 여전히 아님 check("[수동] 날짜 칸은 앞으로의 날도 입력 칸(주간합계 아님), 수동 값 칸은 파란 표시", !!cell(e, "coupang", "2026-10-07") && !!cell(e, "coupang", "2026-10-08") && cell(e, "coupang", "2026-10-05").classList.contains("is-manual") && @@ -112,7 +112,7 @@ function gross(td) { return td.querySelector(".v-gross").textContent.trim(); } check("[입력] 숫자가 아니면 저장 안 하고 안내", e.alerts.some(function (m) { return /숫자/.test(m); }) && e.calls.filter(function (c) { return c.method === "PUT"; }).length === 1, e.alerts); } - // ── 카페24(공구 제외) 열(2026-10-30) — 공동구매 칸 저장 → 같은 줄 차이 칸 = 카페24 − 새 값(dashboard._cafe24_ex_gb_column) ── + // ── 카페24(실적) 열 — 공동구매 칸 저장 → 같은 줄 칸 = 카페24 − 새 값(dashboard._cafe24_real_column) ── { const e = await env("perf_dash.html"); const td5 = cell(e, "coupang", "2026-10-05"); @@ -182,7 +182,7 @@ function gross(td) { return td.querySelector(".v-gross").textContent.trim(); } check("[광고비] 광고비 탭이 고른 탭", e.d.querySelector(".perf-tab-ads").classList.contains("is-active")); const heads = Array.from(e.d.querySelectorAll(".perf-main thead th")).map(function (th) { return th.textContent.replace("✎", "").replace("table_view", "").trim(); }); check("[광고비] 열 = 구글·메타·네이버·쿠팡(윙)·쿠팡(로켓)·오늘의집·G마켓·카카오·GS샵·11번가·롯데ON·토스·애터미아자몰·기타광고비(2026-10-22)", - heads.join(",") === "날짜,구글,메타,네이버,쿠팡(윙),쿠팡(로켓),오늘의집,G마켓,카카오,GS샵,11번가,롯데ON,토스,애터미아자몰,기타광고비,일 합계", heads); + heads.join(",") === "날짜,일 합계,구글,메타,네이버,쿠팡(윙),쿠팡(로켓),오늘의집,G마켓,카카오,GS샵,11번가,롯데ON,토스,애터미아자몰,기타광고비", heads); const wing = cell(e, "coupang_wing", "2026-10-05"); check("[광고비] 칸 = 광고비(ROAS%) — 쿠팡(윙) 29,000 · 쿠팡 매출 87,000 → 300%", wing.textContent.trim() === "29,000(300%)" && !cell(e, "naver", "2026-10-05").querySelector(".perf-roas"), wing.textContent); @@ -312,6 +312,40 @@ function gross(td) { return td.querySelector(".v-gross").textContent.trim(); } await settle(); check("[설정] 저장 실패(002 미적용) → 되돌리고 안내", !box2.checked && e.alerts.some(function (m) { return /마이그레이션/.test(m); }), e.alerts); } + // ── 설정: 공통 보기 설정 — 매출 단위·열 숨기기, 모든 사용자에게 적용(서버 저장, 쿠키 아님) ── + { + const e = await env("perf_settings.html"); + check("[매출 단위] 공통 카드로 이동, 표 열 너비는 보기 설정에 그대로", + e.d.querySelectorAll("#perf-shared-view [data-unit]").length === 3 && !e.d.querySelector("#perf-view-opts [data-unit]") && !!e.d.querySelector("#perf-view-opts [data-colw]")); + const thousand = e.d.querySelector('#perf-shared-view [data-unit="thousand"]'); + thousand.click(); + await settle(); + const unitPut = e.calls.find(function (c) { return c.method === "PUT"; }); + check("[매출 단위] 누르면 서버에 저장·쿠키 안 씀", unitPut && unitPut.url === "/performance/api/display-unit" && unitPut.body.unit === "thousand" && + thousand.classList.contains("is-active") && !/perf_unit/.test(e.d.cookie), e.calls); + e.status = 503; + const million = e.d.querySelector('#perf-shared-view [data-unit="million"]'); + million.click(); + await settle(); + check("[매출 단위] 저장 실패 → 그대로·안내", !million.classList.contains("is-active") && thousand.classList.contains("is-active") && e.alerts.length > 0, e.alerts); + } + { + const e = await env("perf_settings.html"); + const list = Array.from(e.d.querySelectorAll("#perf-shared-view [data-hide]")).map(function (x) { return x.dataset.hide; }); + check("[숨기기] 목록 = 표 열(카페24 바로 뒤 카페24(실적))", list.slice(0, 3).join(",") === "cafe24,cafe24_ex_gb,naver", list); + const box = e.d.querySelector('#perf-shared-view [data-hide="naver"]'); + box.checked = true; + box.dispatchEvent(new e.w.Event("change", { bubbles: true })); + await settle(); + const put = e.calls.find(function (c) { return c.method === "PUT"; }); + check("[숨기기] 체크 → 서버에 바로 저장", put && put.url === "/performance/api/hidden-marketplaces" && put.body.codes.join(",") === "naver", e.calls); + check("[숨기기] 쿠키에 안 남김", !/perf_hidden/.test(e.d.cookie), e.d.cookie); + e.status = 503; + box.checked = false; + box.dispatchEvent(new e.w.Event("change", { bubbles: true })); + await settle(); + check("[숨기기] 저장 실패 → 되돌리고 안내", box.checked && e.alerts.length > 0, e.alerts); + } console.log(fails.length ? "\n" + fails.length + " FAILED" : "\nALL PASS"); process.exit(fails.length ? 1 : 0); })(); diff --git a/tests/js/perf_sticky.browser.test.js b/tests/js/perf_sticky.browser.test.js index 83a120e..eaf51d3 100644 --- a/tests/js/perf_sticky.browser.test.js +++ b/tests/js/perf_sticky.browser.test.js @@ -73,6 +73,23 @@ async function stickyFlow(browser, file, label) { const g2 = await geo(); check(label + " 가로 스크롤해도 기간 합계 날짜 칸은 왼쪽 고정", Math.abs(g2.labelLeft - g2.wrapLeft) <= 1.5 && g2.hitLabel && Math.abs(g2.headTop - g2.pageTop) <= 1, g2); + // 일 합계 열 — 날짜 열 바로 오른쪽에 함께 고정(제목·기간 합계·일 행 모두), 위에 다른 칸이 안 겹침(2026-11-02) + const tg = await p.evaluate(function () { + const box = function (s) { return document.querySelector(s).getBoundingClientRect(); }; + const hit = function (s) { const r = box(s), n = document.elementFromPoint(r.left + r.width / 2, r.top + r.height / 2); return !!n.closest(s); }; + const label = box(".perf-main thead th.perf-th-label"); + const rows = [".perf-main thead th.perf-th-total", ".perf-main tbody tr.perf-row-total:first-child > .perf-td-total", ".perf-main tbody tr.perf-row-day > .perf-td-total"]; + return { labelRight: label.right, lefts: rows.map(function (s) { return box(s).left; }), hits: rows.slice(0, 2).map(hit), scrolled: document.querySelector(".perf-main-wrap").scrollLeft }; + }); + check(label + " 가로 스크롤해도 일 합계 열은 날짜 열 바로 옆 고정", tg.scrolled > 0 && tg.lefts.every(function (x) { return Math.abs(x - tg.labelRight) <= 1.5; }) && tg.hits.every(Boolean), tg); + // 기간 이동 — 날짜 바로 좌우 화살표 SVG(글자 높이), 글자 없음 + const nv = await p.evaluate(function () { + const a = document.querySelectorAll(".perf-nav-btn"), lb = document.querySelector(".perf-nav-label").getBoundingClientRect(); + const svg = a[0].querySelector("svg"); + return { text: a[0].textContent.trim() + a[1].textContent.trim(), h: svg.getBoundingClientRect().height, size: parseFloat(getComputedStyle(document.querySelector(".perf-nav-label")).fontSize), + stroke: getComputedStyle(svg).stroke, gapL: lb.left - a[0].getBoundingClientRect().right, gapR: a[1].getBoundingClientRect().left - lb.right }; + }); + check(label + " 기간 이동 = 날짜 바로 옆 글자 높이 화살표(진한 회색)", nv.text === "" && Math.abs(nv.h - nv.size) <= 1 && nv.gapL <= 3 && nv.gapR <= 3 && nv.stroke === "rgb(68, 68, 68)", nv); // 표 끝을 넘어가면 같이 올라간다(표 밖으로 나가지 않음) await p.evaluate(function () { const pg = document.querySelector(".erp-page"); pg.scrollTop = pg.scrollHeight; }); await p.waitForTimeout(120);