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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 19:53:39 +09:00

410 lines
23 KiB
Python

"""직접 추가 쇼핑몰(수동 입력 전용)·쇼핑몰 그룹·드래그 순서 (2026-10-22, 마이그레이션 009)."""
from __future__ import annotations
import importlib
from datetime import date
import pytest
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)
def _row(code, name, sort, **kw):
return {"code": code, "name": name, "sort_order": sort, "enabled": True, "include_in_sales": True,
"manual_input": False, "is_custom": False, "is_group": False, "parent_code": None, **kw}
class _Store:
"""카페24 + 그룹 '오프라인'(하위 custom_a·custom_b) + 네이버 — 그룹은 순서상 네이버 뒤, 하위는 맨 앞 sort_order 여도 그룹 자리."""
def __init__(self):
self.rows = [
_row("custom_b", "매장B", 5, manual_input=True, is_custom=True, parent_code="group_x"),
_row("cafe24", "카페24", 10),
_row("naver", "네이버", 20),
_row("group_x", "오프라인", 30, is_custom=True, is_group=True, include_in_sales=False),
_row("custom_a", "매장A", 40, manual_input=True, is_custom=True, parent_code="group_x"),
_row("custom_c", "행사", 50, manual_input=True, is_custom=True),
]
self.manual = {(date(2026, 10, 5), "custom_a"): 100_000, (date(2026, 10, 5), "custom_b"): 50_000,
(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"]))
def daily_amounts(self, start, end, codes):
base = {(date(2026, 10, 5), "cafe24"): 1_000_000, **self.manual}
return {k: v for k, v in base.items() if start <= k[0] <= end and k[1] in codes}
def manual_amounts(self, start, end, codes, *, active_only=True):
return {k: v for k, v in self.manual.items() if start <= k[0] <= end and k[1] in codes}
def rate_table(self):
return {"custom_a": [(date(2000, 1, 1), 10)]}
def statuses(self):
return {}
def last_update_at(self):
return None
def running_codes(self):
return []
def ad_amounts(self, start, end):
return {}, {}
# ── 009 쓰기 ──
def add_custom_marketplace(self, code, name, *, is_group):
row = _row(code, name, max(r["sort_order"] for r in self.rows) + 10, manual_input=not is_group,
include_in_sales=not is_group, is_custom=True, is_group=is_group)
self.rows.append(row)
return dict(row)
def _find(self, code):
return next(r for r in self.rows if r["code"] == code)
def rename_marketplace(self, code, name):
self._find(code)["name"] = name
return dict(self._find(code))
def set_marketplace_parent(self, code, parent):
self._find(code)["parent_code"] = parent
return dict(self._find(code))
def delete_custom_marketplace(self, code):
self.deleted.append(code)
for r in self.rows:
if r.get("parent_code") == code:
r["parent_code"] = None
self.rows = [r for r in self.rows if r["code"] != code]
return True
def manual_day_count(self, code):
return sum(1 for (_, c) in self.manual if c == code)
def reorder_marketplaces(self, codes):
self.order = list(codes)
for i, c in enumerate(codes):
self._find(c)["sort_order"] = (i + 1) * 10
def test_custom_code_gets_manual_only_adapter_and_group_has_none():
a = get_adapter("custom_1234abcd")
assert a is not None and a.manual_only and a.code == "custom_1234abcd"
assert get_adapter("group_1234abcd") is None and get_adapter("nope") is None
assert get_adapter("cafe24").code == "cafe24"
def test_ordered_children_follow_group():
codes = [m["code"] for m in dashboard.ordered_marketplaces(_Store().list_marketplaces())]
assert codes == ["cafe24", "naver", "group_x", "custom_b", "custom_a", "custom_c"]
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"), (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")
# 그룹 = 매장B 50,000 + 매장A 100,000(수수료 10% = 10,000)
assert day5["cells"]["group_x"] == {"gross": 150_000, "commission": 10_000, "net": 140_000}
assert day5["total"]["gross"] == 1_150_000 # 일 합계에 그룹을 또 더하지 않음
week = next(r for r in ctx["table"] if r["kind"] == "week")
assert week["cells"]["group_x"]["gross"] == 157_000
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", 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")
assert day5["cells"]["group_x"]["gross"] == 100_000 # 보이는 하위만 합침
def test_settings_blocks_group_children_together():
ctx = dashboard.build_settings(_Store(), configured={}, key_info={"ok": True}, key_versions_in_use={}, sample_count=0)
assert [(b["row"]["code"], [c["code"] for c in b["children"]]) for b in ctx["blocks"]] == [
("cafe24", []), ("naver", []), ("group_x", ["custom_b", "custom_a"]), ("custom_c", [])]
grp = ctx["blocks"][2]["row"]
assert grp["is_group"] and grp["children"] == 2
a = ctx["blocks"][2]["children"][1]
assert a["is_custom"] and a["manual_only"] and a["parent"] == "group_x" and a["status"] == "manual"
assert ctx["groups"] == [{"code": "group_x", "name": "오프라인"}] and ctx["custom_ready"]
@pytest.fixture()
def client(monkeypatch):
perf_router = importlib.import_module("app.modules.performance.router")
store = _Store()
class _Creds:
def configured_codes(self, adapters):
return {}
user = {"email": "king@x", "name": "King", "is_admin": True}
monkeypatch.setattr(common, "guard", lambda request, admin=False: (store, user))
monkeypatch.setattr(common, "require_store", lambda request, admin=False: (store, user))
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)
c = TestClient(app)
c.store = store
return c
def test_api_add_rename_group_delete(client):
store = client.store
r = client.post("/performance/api/marketplaces", json={"kind": "shop", "name": " 새 매장 "})
assert r.status_code == 200, r.text
m = r.json()["marketplace"]
assert m["code"].startswith("custom_") and m["name"] == "새 매장" and m["manual_input"] and m["is_custom"]
assert client.post("/performance/api/marketplaces", json={"kind": "shop", "name": "카페24"}).status_code == 400
assert client.post("/performance/api/marketplaces", json={"kind": "shop", "name": ""}).status_code == 400
g = client.post("/performance/api/marketplaces", json={"kind": "group", "name": "온라인B"}).json()["marketplace"]
assert g["code"].startswith("group_") and g["is_group"] and not g["include_in_sales"]
assert client.put(f"/performance/api/marketplaces/{m['code']}", json={"parent_code": g["code"]}).status_code == 200
assert store._find(m["code"])["parent_code"] == g["code"]
assert client.put(f"/performance/api/marketplaces/{m['code']}", json={"parent_code": "cafe24"}).status_code == 400
assert client.put(f"/performance/api/marketplaces/{g['code']}", json={"parent_code": "group_x"}).status_code == 400
assert client.put("/performance/api/marketplaces/cafe24", json={"name": "자사몰"}).status_code == 400
assert client.put("/performance/api/marketplaces/cafe24", json={"parent_code": "group_x"}).status_code == 400
assert client.put(f"/performance/api/marketplaces/{g['code']}", json={"name": "온라인C"}).json()["marketplace"]["name"] == "온라인C"
assert client.put(f"/performance/api/marketplaces/{g['code']}", json={"enabled": False}).status_code == 400
assert client.put(f"/performance/api/marketplaces/{m['code']}", json={"parent_code": ""}).status_code == 200
assert store._find(m["code"])["parent_code"] is None
assert client.get("/performance/api/marketplaces/custom_a/manual-days").json() == {"days": 2}
assert client.delete("/performance/api/marketplaces/cafe24").status_code == 400
assert client.delete("/performance/api/marketplaces/group_x").status_code == 200
assert store._find("custom_a")["parent_code"] is None and store.deleted == ["group_x"]
def test_api_manual_sale_accepts_custom_shop(client):
calls = []
client.store.set_manual_sale = lambda code, d, amount, user="", formula=None: calls.append((code, d, amount))
client.store.api_amount = lambda code, d: 0
r = client.put("/performance/api/manual-sales/custom_a/2026-10-07", json={"amount": "1000+2000"})
assert r.status_code == 200, r.text
assert calls == [("custom_a", date(2026, 10, 7), 3000)] and r.json()["commission"] == 300
assert client.put("/performance/api/manual-sales/group_x/2026-10-07", json={"amount": "1"}).status_code == 404
def test_api_order(client):
order = ["naver", "cafe24", "group_x", "custom_a", "custom_b", "custom_c"]
assert client.put("/performance/api/marketplace-order", json={"codes": order + ["ghost"]}).status_code == 200
assert client.store.order == order
assert client.put("/performance/api/marketplace-order", json={"codes": ["naver", "naver"]}).status_code == 400
ctx = dashboard.build_dashboard(client.store, kind="week", anchor=TODAY, today=TODAY)
assert ctx["codes"] == ["naver", "cafe24", "custom_a", "custom_b", "custom_c"]
def test_dashboard_page_renders_group_header_and_child_cells(client):
html = client.get("/performance/?period=week&d=2026-10-07").text
head = html.split("<thead>", 1)[1].split("</thead>", 1)[0]
assert 'data-group-head="group_x"' in head and 'data-group-toggle="group_x"' in head and "오프라인" in head
assert head.index('data-group-head="group_x"') < head.index('data-group-child="group_x"')
body = html.split("<tbody>", 1)[1].split("</tbody>", 1)[0]
assert 'data-group-cell="group_x"' in body and "150,000" in body
assert 'data-group-child="group_x" data-manual-code="custom_a" data-date="2026-10-05"' in body
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()
# 공동구매 없음 = 전체 그대로
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] == ["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")
# 일 합계 = 카페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)
# 공동구매를 필터로 빼도 실적에서는 뺀다 — 일 합계 = 실적 + 나머지
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"]]
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)
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_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("<thead>", 1)[1].split("</thead>", 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("<thead>", 1)[1].split("</thead>", 1)[0]
# 날짜 → 일 합계 → 카페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("<tbody>", 1)[1].split("</tbody>", 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("<tbody>", 1)[1]
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