Files
dbx-main/app/modules/performance/tests/test_custom_groups.py
T
king 38afbca839 feat(실적): 공동구매 칸 저장 즉시 카페24(공구 제외) 칸 반영
- 공동구매 날짜 칸을 저장하면 같은 줄 차이 칸 = 카페24 − 저장 응답(총매출·수수료·차감)
- 차이 칸에 data-diff-minus·data-base(카페24 값) — 일 행만, 합계 줄은 새로고침 때
- performance.js 캐시 버전 20261030a

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 14:36:53 +09:00

259 lines
13 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""직접 추가 쇼핑몰(수동 입력 전용)·쇼핑몰 그룹·드래그 순서 (2026-10-22, 마이그레이션 009)."""
from __future__ import annotations
import importlib
from datetime import date
import pytest
from fastapi import FastAPI
from fastapi.testclient import TestClient
from app.modules.performance import common, dashboard
from app.modules.performance.adapters.registry import get_adapter
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 = []
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"), ("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", "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 test_cafe24_minus_groupbuy_column():
"""'카페24 공동구매' 바로 오른쪽 = 카페24 − 공동구매(2026-10-30). 표 열만 — 일 합계엔 안 더함."""
st = _Store()
st._find("custom_c")["name"] = "카페24 공동구매"
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]
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
week = next(r for r in ctx["table"] if r["kind"] == "week")
assert week["cells"][dashboard.CAFE24_EX_GB]["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"
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"}
def test_dashboard_page_renders_cafe24_minus_groupbuy(client):
client.store._find("custom_c")["name"] = "카페24 공동구매"
client.store.manual[(date(2026, 10, 5), "custom_c")] = 300_000
html = client.get("/performance/?period=week&d=2026-10-07").text
head = html.split("<thead>", 1)[1].split("</thead>", 1)[0]
assert head.index('data-col="custom_c"') < head.index(f'data-col="{dashboard.CAFE24_EX_GB}"')
assert "카페24(공구 제외)" 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