Files
dbx-main/app/modules/performance/tests/test_dashboard_ads_units.py
T
king 884e654bea feat(실적): 카페24(실적) 열·합계 기준 통일·공통 보기 설정·일 합계 고정
매출 실적
- "카페24" 열 → "카페24(전체)", 바로 오른쪽 "카페24(실적)" = 전체 − 자사몰(공동구매),
  광고비 줄은 카페24(전체)의 구글·메타 그대로 (예전 "공구 제외" 열 대체)
- 합계 기준 통일: 일 합계·ROAS·KPI·추이·비중·월/연 누적 = 카페24(실적) + 공동구매 + 나머지
  (카페24(전체)에 공동구매가 들어 있어 이중 합산 제거, 그래프·누적의 카페24 줄 = 카페24(실적))
- 실적 설정 "공통 보기 설정"(관리자, perf_settings, 모든 사용자 적용):
  매출 단위(예전 브라우저 쿠키 perf_unit 대체), 표 열 숨기기(열만, 합계 그대로)
  표 열 너비는 사람(브라우저)마다 그대로

매출 실적·광고비 공통
- 일 합계 열을 날짜 오른쪽으로, 날짜와 함께 가로 고정
- 이전달·다음달 = 날짜 바로 옆 진한 회색 화살표 SVG(글자 높이)
- 광고비 탭 매출 대비 광고비·합계 ROAS 도 공동구매 이중 합산 제거

CSS·JS 캐시 버전 20261102a. 새 마이그레이션 없음(011 perf_settings 사용).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 12:21:33 +09:00

237 lines
11 KiB
Python

"""매출 실적 화면 — 매출 칸 아래 광고비(ROAS%)·매출 단위(원·천원·백만원) (2026-10-19)."""
from __future__ import annotations
from datetime import date
from app.modules.performance import dashboard
TODAY = date(2026, 10, 7)
class _Store:
"""build_dashboard 가 읽는 것만 — 카페24·네이버·쿠팡 매출 + 구글·메타·네이버·쿠팡(윙) 광고비."""
def __init__(self, ads_missing=False):
self.ads_missing = ads_missing
def list_marketplaces(self):
return [{"code": c, "name": n, "enabled": True, "include_in_sales": True}
for c, n in (("cafe24", "카페24"), ("naver", "네이버 스마트스토어"), ("coupang", "쿠팡"))]
def daily_amounts(self, start, end, codes):
rows = {(date(2026, 10, 5), "cafe24"): 2_000_000, (date(2026, 10, 5), "coupang"): 600_000,
(date(2026, 10, 6), "naver"): 1_234_567}
return {k: v for k, v in rows.items() if start <= k[0] <= end and k[1] in codes}
def rate_table(self):
return {}
def statuses(self):
return {}
def last_update_at(self):
return None
def running_codes(self):
return []
def ad_amounts(self, start, end):
if self.ads_missing:
raise RuntimeError("perf_ad_spend 없음")
rows = {(date(2026, 10, 5), "google"): 100_000, (date(2026, 10, 5), "meta"): 50_000,
(date(2026, 10, 5), "coupang_wing"): 200_000, (date(2026, 10, 6), "naver"): 300_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):
rows = {(date(2026, 10, 5), "google"): 412.5, (date(2026, 10, 6), "naver"): 150}
return {k: v for k, v in rows.items() if start <= k[0] <= end}
def test_sales_ad_channels_mapping():
m = dashboard.sales_ad_channels()
assert m["cafe24"] == (("google", "구글"), ("meta", "메타"))
assert m["naver"] == (("naver", ""),) and m["coupang"] == (("coupang_wing", ""),)
assert m["coupang_rocket"] == (("coupang_rocket", ""),) and "google" not in m
def test_ad_lines_under_sales_cells():
ctx = dashboard.build_dashboard(_Store(), kind="week", anchor=TODAY, today=TODAY)
day5 = next(r for r in ctx["table"] if r.get("date") == "2026-10-05")
# 카페24 = 구글·메타 두 줄, ROAS 는 광고 보고서 값(구글 412.5 → 413), 메타는 보고서 ROAS 없음
assert day5["ads"]["cafe24"] == [{"label": "구글", "amount": 100_000, "roas": 413},
{"label": "메타", "amount": 50_000, "roas": None}]
# 쿠팡 = 쿠팡(윙) 광고비, ROAS = 쿠팡 매출 ÷ 광고비 = 600,000 ÷ 200,000
assert day5["ads"]["coupang"] == [{"label": "", "amount": 200_000, "roas": 300}]
assert "naver" not in day5["ads"] # 그날 네이버 광고비 없음 → 줄 없음
# 일 합계 = 보이는 쇼핑몰 광고비 합, ROAS = 일 합계 금액 ÷ 일 합계 광고비(총매출·수수료 차감 매출 두 기준, 2026-10-19)
assert day5["ads_total"] == {"amount": 350_000, "roas": 743, "roas_net": 743} # 2,600,000 ÷ 350,000(수수료율 없음)
day6 = next(r for r in ctx["table"] if r.get("date") == "2026-10-06")
assert day6["ads"]["naver"] == [{"label": "", "amount": 300_000, "roas": 150}]
week = next(r for r in ctx["table"] if r["kind"] == "week")
assert [a["amount"] for a in week["ads"]["cafe24"]] == [100_000, 50_000] and week["ads_total"]["amount"] == 650_000
day1 = next(r for r in ctx["table"] if r.get("date") == "2026-10-07")
assert day1["ads"] == {} and day1["ads_total"] is None
def test_ad_lines_follow_shop_filter_and_missing_table():
ctx = dashboard.build_dashboard(_Store(), kind="week", anchor=TODAY, today=TODAY, selected=["coupang"])
day5 = next(r for r in ctx["table"] if r.get("date") == "2026-10-05")
assert list(day5["ads"]) == ["coupang"] and day5["ads_total"] == {"amount": 200_000, "roas": 300, "roas_net": 300}
ctx = dashboard.build_dashboard(_Store(ads_missing=True), kind="week", anchor=TODAY, today=TODAY)
assert all(r["ads"] == {} and r["ads_total"] is None for r in ctx["table"]) # 광고비 표 없어도 매출 화면은 그대로
def test_amount_text_units():
assert dashboard.amount_text(2_475_300) == "2,475,300"
assert dashboard.amount_text(2_475_300, "thousand") == "2,475"
assert dashboard.amount_text(2_475_500, "thousand") == "2,476"
assert dashboard.amount_text(2_475_300, "million") == "2.5"
assert dashboard.amount_text(158_000, "million") == "0.2"
assert dashboard.amount_text(-158_000, "thousand") == "-158"
assert dashboard.amount_text(1_234_567_890, "million") == "1,234.6"
assert dashboard.amount_text(5, "nope") == "5" and dashboard.normalize_unit("x") == "won"
def test_dashboard_page_renders_unit_and_ad_lines(monkeypatch):
import importlib
from fastapi import FastAPI
from fastapi.testclient import TestClient
from app.modules.performance import common
perf_router = importlib.import_module("app.modules.performance.router")
class _Creds:
def configured_codes(self, adapters):
return {}
store = _Store()
monkeypatch.setattr(common, "guard", lambda request, admin=False: (store, {"email": "king@x", "name": "King", "is_admin": True}))
monkeypatch.setattr(common, "services", lambda request, st: (_Creds(), None))
monkeypatch.setattr(perf_router, "today_kst", lambda: TODAY)
app = FastAPI()
app.include_router(perf_router.router)
client = TestClient(app)
html = client.get("/performance/?period=week&d=2026-10-07").text
assert "2,000,000" in html
assert 'class="perf-adl"' in html and "<i>구글</i>100,000<em>(413%)</em>" in html and "<i>메타</i>50,000" in html
assert "200,000<em>(300%)</em>" in html and "단위:" not in html
# 매출 단위 = 서버 공통 설정(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 "<i>구글</i>100<em>(413%)</em>" in html
assert "2,000,000<" not in html.split("perf-main", 1)[1].split("</table>", 1)[0]
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):
def ad_amounts(self, start, end):
rows = {(date(2026, 10, 5), "google"): 100_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 {}
ctx = dashboard.build_dashboard(_S(), kind="week", anchor=TODAY, today=TODAY)
day5 = next(r for r in ctx["table"] if r.get("date") == "2026-10-05")
assert day5["total"]["gross"] == 2_600_000 # 카페24 2,000,000 + 쿠팡 600,000(광고비 없음)
assert day5["ads_total"] == {"amount": 100_000, "roas": 2600, "roas_net": 2600}
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
def test_pages_render_formula_cells_future_inputs_and_total_on_top(monkeypatch):
"""2026-10-21 — 계산식 칸(is-formula·data-formula), 오늘 뒤 날짜도 입력 칸, 이번달 기간 합계 = 제목 행 바로 아래."""
import importlib
from fastapi import FastAPI
from fastapi.testclient import TestClient
from app.modules.performance import common
perf_router = importlib.import_module("app.modules.performance.router")
class _S(_Store):
def list_marketplaces(self):
return [{**m, "manual_input": m["code"] == "coupang"} for m in super().list_marketplaces()]
def manual_amounts(self, start, end, codes, *, active_only=True):
return {(date(2026, 10, 5), "coupang"): 600_000}
def manual_formulas(self, start, end, codes):
return {(date(2026, 10, 5), "coupang"): "500000+100000"}
def ad_formulas(self, start, end):
return {(date(2026, 10, 5), "meta"): "20000+30000"}
class _Creds:
def configured_codes(self, adapters):
return {}
store = _S()
monkeypatch.setattr(common, "guard", lambda request, admin=False: (store, {"email": "king@x", "name": "King", "is_admin": True}))
monkeypatch.setattr(common, "services", lambda request, st: (_Creds(), None))
monkeypatch.setattr(perf_router, "today_kst", lambda: TODAY)
app = FastAPI()
app.include_router(perf_router.router)
client = TestClient(app)
for url, code, fx in (("/performance/?period=month&d=2026-10-07", "coupang", "500000+100000"),
("/performance/ads?period=month&d=2026-10-07", "meta", "20000+30000")):
r = client.get(url)
assert r.status_code == 200, r.text
body = r.text.split("<tbody>", 1)[1].split("</tbody>", 1)[0]
assert body.lstrip().startswith('<tr class="perf-row-total') and "기간 합계" in body.split("</tr>", 1)[0]
cell = body.split(f'data-manual-code="{code}" data-date="2026-10-05"', 1)
assert len(cell) == 2 and "is-formula" in cell[0].rsplit("<td", 1)[1] and f'data-formula="{fx}"' in cell[1].split(">", 1)[0]
assert f'data-manual-code="{code}" data-date="2026-10-20"' in body # 오늘(10/7) 뒤 날짜도 입력 칸