From 91fd454b2cdb70cf90ef1f6a4decfe7cde548502 Mon Sep 17 00:00:00 2001 From: king Date: Mon, 16 Nov 2026 11:34:56 +0900 Subject: [PATCH] =?UTF-8?q?feat(=EC=8B=A4=EC=A0=81):=20=EB=A7=A4=EC=B6=9C?= =?UTF-8?q?=20KPI=20=EC=A0=84=EB=85=84=20=EA=B0=99=EC=9D=80=20=EA=B8=B0?= =?UTF-8?q?=EA=B0=84=20=EB=8C=80=EB=B9=84=20=C2=B7=20=EA=B4=91=EA=B3=A0?= =?UTF-8?q?=EB=B9=84=20=EC=B9=B4=ED=86=A1=20=ED=94=8C=EC=B9=9C=20=EC=97=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 매출 실적 KPI 줄에 전월 대비 옆 "전년 같은 기간 대비" % (연 보기 제외) - 광고비 탭 카톡 플친(kakao_pf) 열 — 직접 입력, ROAS 없음 - 매출 탭 카페24 칸 광고비 줄에 구글·메타 다음 카톡 플친 Co-Authored-By: Claude Opus 5.5 --- app/modules/performance/CLAUDE.md | 5 ++-- app/modules/performance/ad_spend.py | 3 ++- app/modules/performance/calc.py | 11 ++++++++ app/modules/performance/dashboard.py | 13 +++++++--- .../templates/performance/index.html | 8 ++++++ .../performance/tests/test_ad_spend.py | 2 +- .../tests/test_dashboard_ads_units.py | 25 ++++++++++++++++++- .../performance/tests/test_performance.py | 5 ++++ 8 files changed, 63 insertions(+), 9 deletions(-) diff --git a/app/modules/performance/CLAUDE.md b/app/modules/performance/CLAUDE.md index 88ae264..3e4d657 100644 --- a/app/modules/performance/CLAUDE.md +++ b/app/modules/performance/CLAUDE.md @@ -79,7 +79,7 @@ ## 매출 실적 화면 (2026-10-19) -- KPI 는 **수수료 차감 매출 하나만** 화면 왼쪽 한 줄(`.perf-kpi-line` — 금액 + 비교 기간 대비 %, 모든 기간 공통). 총매출·수수료·월/연 누적 카드는 뺐다. +- KPI 는 **수수료 차감 매출 하나만** 화면 왼쪽 한 줄(`.perf-kpi-line` — 금액 + 비교 기간 대비 % + **전년 같은 기간 대비 %**(2026-11-16, `calc.Period.yoy_range` — 1년 전 같은 날짜, 진행 중이면 오늘까지, 연 보기는 직전 비교가 이미 전년이라 없음), 모든 기간 공통). 총매출·수수료·월/연 누적 카드는 뺐다. - 일자별 표 기본 보기 = **수수료 차감 매출**(라우터 기본 `metric=net`, 예전에 고른 보기 localStorage 는 안 씀). - 마지막 업데이트 옆 **다음 업데이트까지 남은 시간** 초 단위 실시간(`router._auto_sync_ctx(store, kind)` — 매출 탭 = 매출 일정, 광고비 탭 = 광고비 일정 → `performance.js initNextUpdate`·`nextScheduleSlot`, `auto_sync.next_slot` 과 같은 규칙으로 화면이 다음 회차 계산, 서버 시각으로 PC 시계 보정, 자동 업데이트(env·그 종류 일정) 꺼지면 숨김). - **화면 자동 새로 고침**(2026-10-26) — 자동 업데이트(다른 사람이 누른 업데이트 포함)가 끝나면 매출 실적·광고비 화면이 20초 안에 reload. @@ -87,7 +87,7 @@ (`jobs.last_finished` — 메모리 작업만, DB 안 읽음). 도는 중이면 끝날 때까지, 칸 입력·창(`.perf-modal`)·메뉴·확인 창이 열려 있으면 닫힐 때까지 기다림 (마지막 업데이트 옆 안내), 탭이 안 보이면 안 묻고 다시 보이면 바로. 보는 사람이 직접 누른 업데이트는 진행 창이 새로 그린다. `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` 수수료 차감 매출 기준, 보기 기준에 따라 하나만). 광고비 표 없으면 줄 없음. +- 일자별 표 매출 칸 아래 **광고비(ROAS%)** 주황 줄(`--perf-ad`, `dashboard._ad_lines`) — 광고비 탭과 같은 값(`ad_spend.channel_roas`). 쇼핑몰 → 광고 채널은 `dashboard.sales_ad_channels`: 카페24 = 구글·메타·카톡 플친 줄(이름 붙임, 카페24(전체)·카페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. @@ -124,6 +124,7 @@ - 탭은 [매출 실적]·[광고비]·[틱톡] + 맨 오른쪽 설정 톱니. - **표 모양(2026-10-22)** — 매출 실적 표와 같은 `perf-autofit`(열 너비 = 내용 길이, 날짜 열 가로 스크롤 고정). - **기타광고비** 열(`etc`, 애터미아자몰 오른쪽, 2026-10-22) — 쇼핑몰에 딸리지 않은 광고비 직접 입력. 매출 쇼핑몰이 없어(`ad_spend.NO_SALES`) ROAS 없음·매출 탭 광고비 줄에 안 나옴, 광고비 합계·매출 대비 광고비에는 들어감. +- **카톡 플친** 열(`kakao_pf`, 메타 오른쪽, 2026-11-16) — 직접 입력, `NO_SALES` 라 ROAS 없음. 매출 탭 카페24 칸 아래 구글·메타 다음 줄, 일 합계 광고비에도 더함. - `ad_spend.py`, 마이그레이션 005 `perf_ad_spend`. 구글·메타·네이버·쿠팡(윙)·쿠팡(로켓)·오늘의집·G마켓·카카오·GS샵·11번가·롯데ON·토스·애터미아자몰 일 광고비를 연·월·일로. - 칸 = "광고비(ROAS%)"(ROAS = 그 쇼핑몰 매출 ÷ 광고비). 구글·메타·네이버는 계산 안 함 — 광고 보고서 ROAS(마이그레이션 006 `roas`·`metrics`). - 날짜 칸 직접 입력 + 쿠팡(윙)·쿠팡(로켓)·네이버 광고 보고서 업로드. diff --git a/app/modules/performance/ad_spend.py b/app/modules/performance/ad_spend.py index 90e4f8d..7769188 100644 --- a/app/modules/performance/ad_spend.py +++ b/app/modules/performance/ad_spend.py @@ -35,6 +35,7 @@ from .manual_upload import MAX_AMOUNT, MAX_DATA_ROWS, MAX_ERRORS, MAX_FILE_BYTES CHANNELS: tuple[tuple[str, str], ...] = ( ("google", "구글"), ("meta", "메타"), + ("kakao_pf", "카톡 플친"), # 2026-11-16 — 카카오톡 플러스친구(자사몰 광고, 직접 입력), ROAS 없음, 매출 탭 카페24 줄에 구글·메타 아래 ("naver", "네이버"), ("coupang_wing", "쿠팡(윙)"), ("coupang_rocket", "쿠팡(로켓)"), @@ -55,7 +56,7 @@ CHANNEL_CODES = tuple(c for c, _ in CHANNELS) # 여러 날(주·월·합계)의 ROAS = Σ(그날 ROAS × 그날 광고비) ÷ Σ광고비(ROAS 가 있는 날만) = 광고 매출 합 ÷ 광고비 합. FILE_ROAS = frozenset({"google", "meta", "naver"}) NO_ROAS = FILE_ROAS # 예전 이름(계산 안 하는 채널) -NO_SALES = frozenset({"etc"}) # 매출 쇼핑몰이 없는 채널 — ROAS 를 계산하지 않고 매출 탭 광고비 줄에도 안 나온다 +NO_SALES = frozenset({"etc", "kakao_pf"}) # ROAS 를 계산하지 않는 채널 — 매출 탭 광고비 줄은 sales_ad_channels 에 적은 것만(카톡 플친 = 카페24) ROAS_SALES_CODE: dict[str, str] = {c: c for c in CHANNEL_CODES if c not in FILE_ROAS and c not in NO_SALES} ROAS_SALES_CODE["coupang_wing"] = "coupang" TIKTOK = "tiktok" # 광고 API 채널이지만 CHANNELS 에 없다 — 틱톡 탭(build_tiktok_dashboard)에서만 보인다 diff --git a/app/modules/performance/calc.py b/app/modules/performance/calc.py index a6b7848..0a4be0d 100644 --- a/app/modules/performance/calc.py +++ b/app/modules/performance/calc.py @@ -156,6 +156,17 @@ class Period: unit = {"day": "전일", "week": "전주", "month": "전월", "year": "전년"}.get(self.kind, "직전 기간") return prev_start, prev_end, f"{unit} {note}".strip() + def yoy_range(self, today: date) -> tuple[date, date, str]: + """1년 전 같은 날짜 범위(2026-11-16 매출 KPI 전년 대비). 진행 중인 기간이면 오늘까지만. 2/29 → 2/28.""" + def back(d: date) -> date: + try: + return d.replace(year=d.year - 1) + except ValueError: + return d.replace(year=d.year - 1, day=28) + + end = today if self.start <= today < self.end else self.end + return back(self.start), back(end), "전년 같은 기간" + def resolve_period( kind: str, diff --git a/app/modules/performance/dashboard.py b/app/modules/performance/dashboard.py index efe2148..014cd60 100644 --- a/app/modules/performance/dashboard.py +++ b/app/modules/performance/dashboard.py @@ -161,7 +161,7 @@ def amount_text(value: Any, unit: str = "won") -> str: def _ad_lines(store: Any, table: list[dict[str, Any]], codes: Sequence[str], cells: Mapping[Any, Any], period: Any, q_start: date, q_end: date) -> None: """매출 칸 아래 광고비(ROAS%) — 광고비 화면과 같은 값(ROAS = 그 쇼핑몰 매출 ÷ 광고비, 구글·메타·네이버는 보고서 ROAS). - 카페24 = 구글·메타 두 줄. 행마다 r["ads"][쇼핑몰] = [{label, amount, roas}], r["ads_total"] = 보이는 쇼핑몰 광고비 합. + 카페24 = 구글·메타·카톡 플친 줄. 행마다 r["ads"][쇼핑몰] = [{label, amount, roas}], r["ads_total"] = 보이는 쇼핑몰 광고비 합. 일 합계 ROAS 는 단순하게 일 합계 금액 ÷ 일 합계 광고비(2026-10-19) — roas = 총매출 기준, roas_net = 수수료 차감 매출 기준 (화면 표시 기준에 따라 하나만 보인다). 예전엔 광고비가 있는 쇼핑몰 매출만 더해 일 합계 금액과 맞지 않았다. 광고비 표(005)가 없거나 읽기 실패면 줄 없음.""" @@ -217,11 +217,11 @@ def _ad_lines(store: Any, table: list[dict[str, Any]], codes: Sequence[str], cel def sales_ad_channels() -> dict[str, tuple[tuple[str, str], ...]]: - """쇼핑몰(매출 코드) → 그 아래 보일 광고 채널 [(채널, 줄 이름)]. 카페24 = 구글·메타(자사몰 광고), 네이버 = 네이버 광고, + """쇼핑몰(매출 코드) → 그 아래 보일 광고 채널 [(채널, 줄 이름)]. 카페24 = 구글·메타·카톡 플친(자사몰 광고), 네이버 = 네이버 광고, 나머지는 광고비 화면의 ROAS 매출 쇼핑몰(쿠팡(윙) 광고 → 쿠팡 매출).""" from . import ad_spend # noqa: WPS433 - out: dict[str, tuple[tuple[str, str], ...]] = {"cafe24": (("google", "구글"), ("meta", "메타")), "naver": (("naver", ""),)} + out: dict[str, tuple[tuple[str, str], ...]] = {"cafe24": (("google", "구글"), ("meta", "메타"), ("kakao_pf", "카톡 플친")), "naver": (("naver", ""),)} for ch, c in ad_spend.ROAS_SALES_CODE.items(): out[c] = out.get(c, ()) + ((ch, ""),) return out @@ -261,7 +261,10 @@ def build_dashboard(store: Any, *, kind: str, anchor: date, today: date, m_cmp_start, m_cmp_end, m_cmp_label = month_period.compare_range(today) y_cmp_start, y_cmp_end, y_cmp_label = year_period.compare_range(today) - q_start = min(period.start, cmp_start, m_cmp_start, y_cmp_start) + # 전년 같은 기간 대비(2026-11-16) — 연 보기는 직전 비교가 이미 전년이라 뺀다 + yoy = period.yoy_range(today) if period.kind != "year" else None + + q_start = min(period.start, cmp_start, m_cmp_start, y_cmp_start, *(yoy[:1] if yoy else ())) q_end = max(period.end, year_period.end) gb = groupbuy_code(markets) # 공동구매를 필터로 뺐어도 카페24(실적) 계산엔 필요 — 합계·그래프는 아래에서 codes 만 더한다 @@ -292,6 +295,8 @@ def build_dashboard(store: Any, *, kind: str, anchor: date, today: date, {"key": "net", "label": f"{period_word} 수수료 차감 매출", "value": cur.net, "primary": True, "delta": calc.pct_change(cur.net, prev.net), "cmp": cmp_label}, ] + if yoy: + kpis[0].update(yoy_delta=calc.pct_change(cur.net, calc.sum_range(summary, codes, yoy[0], yoy[1]).net), yoy_cmp=yoy[2]) share = calc.by_code(summary, codes, period.start, period.end) # 비중 그래프·월 누적 표의 카페24 줄 = 카페24(실적) — 줄을 더하면 합계와 같다 diff --git a/app/modules/performance/templates/performance/index.html b/app/modules/performance/templates/performance/index.html index 4b3f076..d55f12b 100644 --- a/app/modules/performance/templates/performance/index.html +++ b/app/modules/performance/templates/performance/index.html @@ -111,6 +111,14 @@ {% if k.delta > 0 %}▲{% elif k.delta < 0 %}▼{% else %}–{% endif %} {{ "%.1f" | format(k.delta | abs) }}% {{ k.cmp }} 대비 {% endif %} + {% if k.yoy_cmp %} + {% if k.yoy_delta is none %}{{ k.yoy_cmp }} 비교 없음 + {% else %} + + {% if k.yoy_delta > 0 %}▲{% elif k.yoy_delta < 0 %}▼{% else %}–{% endif %} {{ "%.1f" | format(k.yoy_delta | abs) }}% + {{ k.yoy_cmp }} 대비 + {% endif %} + {% endif %} {% endfor %} diff --git a/app/modules/performance/tests/test_ad_spend.py b/app/modules/performance/tests/test_ad_spend.py index 6385dbe..38fd2da 100644 --- a/app/modules/performance/tests/test_ad_spend.py +++ b/app/modules/performance/tests/test_ad_spend.py @@ -120,7 +120,7 @@ class _Store: def test_ad_dashboard_month(): ctx = ads.build_ad_dashboard(_Store(), kind="month", anchor=date(2026, 10, 7), today=date(2026, 10, 7), sales_codes=["cafe24"]) - assert ctx["codes"] == ["google", "meta", "naver", "coupang_wing", "coupang_rocket", "ohouse", "gmarket", "kakao", + assert ctx["codes"] == ["google", "meta", "kakao_pf", "naver", "coupang_wing", "coupang_rocket", "ohouse", "gmarket", "kakao", "gsshop", "elevenst", "lotteon", "toss", "atomy", "etc"] # 기타광고비(2026-10-22) = 애터미아자몰 오른쪽 assert ctx["names"]["etc"] == "기타광고비" and ctx["roas_basis"]["etc"] == "" and "etc" not in ads.ROAS_SALES_CODE # 매출 쇼핑몰 없음 = ROAS 없음 k = {x["key"]: x for x in ctx["kpis"]} diff --git a/app/modules/performance/tests/test_dashboard_ads_units.py b/app/modules/performance/tests/test_dashboard_ads_units.py index 66972c5..317f1ac 100644 --- a/app/modules/performance/tests/test_dashboard_ads_units.py +++ b/app/modules/performance/tests/test_dashboard_ads_units.py @@ -51,7 +51,7 @@ class _Store: def test_sales_ad_channels_mapping(): m = dashboard.sales_ad_channels() - assert m["cafe24"] == (("google", "구글"), ("meta", "메타")) + assert m["cafe24"] == (("google", "구글"), ("meta", "메타"), ("kakao_pf", "카톡 플친")) assert m["naver"] == (("naver", ""),) and m["coupang"] == (("coupang_wing", ""),) assert m["coupang_rocket"] == (("coupang_rocket", ""),) and "google" not in m @@ -187,6 +187,29 @@ def test_kpi_is_net_only(): ctx = dashboard.build_dashboard(_Store(), kind="week", anchor=TODAY, today=TODAY) assert [k["key"] for k in ctx["kpis"]] == ["net"] assert ctx["kpis"][0]["value"] == 2_600_000 + 1_234_567 + assert ctx["kpis"][0]["yoy_cmp"] == "전년 같은 기간" and ctx["kpis"][0]["yoy_delta"] is None # 작년 매출 없음 + assert "yoy_cmp" not in dashboard.build_dashboard(_Store(), kind="year", anchor=TODAY, today=TODAY)["kpis"][0] + + +def test_kakao_pf_line_under_cafe24(): + """카톡 플친(2026-11-16) — 광고비 탭 열, ROAS 없음, 매출 탭 카페24 칸 아래 구글·메타 다음 줄.""" + from app.modules.performance import ad_spend + + assert ad_spend.CHANNEL_NAMES["kakao_pf"] == "카톡 플친" and "kakao_pf" not in ad_spend.ROAS_SALES_CODE + + class _S(_Store): + def ad_amounts(self, start, end): + rows = {(date(2026, 10, 5), "google"): 100_000, (date(2026, 10, 5), "kakao_pf"): 30_000} + rows = {k: v for k, v in rows.items() if start <= k[0] <= end} + return rows, {k: "manual" for k in rows} + + def ad_roas(self, start, end): + return {} + + day5 = next(r for r in dashboard.build_dashboard(_S(), kind="week", anchor=TODAY, today=TODAY)["table"] + if r.get("date") == "2026-10-05") + assert [(a["label"], a["amount"], a["roas"]) for a in day5["ads"]["cafe24"]] == [("구글", 100_000, None), ("카톡 플친", 30_000, None)] + assert day5["ads_total"]["amount"] == 130_000 def test_pages_render_formula_cells_future_inputs_and_total_on_top(monkeypatch): diff --git a/app/modules/performance/tests/test_performance.py b/app/modules/performance/tests/test_performance.py index 180cef4..1c8b66e 100644 --- a/app/modules/performance/tests/test_performance.py +++ b/app/modules/performance/tests/test_performance.py @@ -160,6 +160,11 @@ def test_periods(): # 진행 중인 달 — 전월 같은 날까지(말일 넘지 않게) s, e, _ = calc.resolve_period("month", date(2026, 3, 31)).compare_range(today=date(2026, 3, 31)) assert (s, e) == (date(2026, 2, 1), date(2026, 2, 28)) + # 전년 같은 기간 — 진행 중이면 오늘까지, 2/29 → 2/28 + s, e, label = calc.resolve_period("month", date(2026, 11, 16)).yoy_range(today=date(2026, 11, 16)) + assert (s, e, label) == (date(2025, 11, 1), date(2025, 11, 16), "전년 같은 기간") + s, e, _ = calc.resolve_period("month", date(2028, 2, 10)).yoy_range(today=date(2028, 3, 5)) + assert (s, e) == (date(2027, 2, 1), date(2027, 2, 28)) assert calc.pct_change(110, 100) == 10.0 and calc.pct_change(5, 0) is None and calc.pct_change(0, 0) is None