Files
dbx-main/app/modules/performance/dashboard.py
T
king 45f92f60ca feat(실적): 매출 실적 표에 카페24(공구 제외) 열 추가
- "카페24 공동구매" 열 바로 오른쪽에 카페24 − 카페24 공동구매 계산 열
  (총매출·수수료·차감 매출 각각, 기간·주간 합계 행 포함)
- 표 열만 — 일 합계·KPI·그래프엔 안 더함, 클릭·메모 없음
- 공동구매 쇼핑몰은 이름으로 찾음, 그룹 하위면 같은 그룹으로 접힘

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

396 lines
21 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.
"""④ 대시보드/설정 화면 데이터 조립 — 저장소 조회 + calc 계산 결과를 템플릿 컨텍스트로.
HTTP 와 무관하다(store 만 주입). 라우터는 파라미터 파싱·권한만 하고 여기로 넘긴다.
"""
from __future__ import annotations
from datetime import date, timedelta
from decimal import ROUND_HALF_UP, Decimal
from typing import Any, Mapping, Sequence
from . import calc
from .adapters.base import STATUS_LABELS
from .adapters.registry import get_adapter
def ordered_marketplaces(markets: Sequence[Mapping[str, Any]]) -> list[Mapping[str, Any]]:
"""화면 순서(설정 드래그 = sort_order) — 그룹(009) 바로 뒤에 그 하위 쇼핑몰(하위끼리도 sort_order).
목록에 그룹이 없는 하위 쇼핑몰은 그룹 없음처럼 제자리. markets 는 sort_order 순(list_marketplaces)."""
groups = {m["code"] for m in markets if m.get("is_group")}
children: dict[str, list[Mapping[str, Any]]] = {}
for m in markets:
if m.get("parent_code") in groups and not m.get("is_group"):
children.setdefault(m["parent_code"], []).append(m)
out: list[Mapping[str, Any]] = []
for m in markets:
if m.get("parent_code") in groups and not m.get("is_group"):
continue
out.append(m)
out.extend(children.get(m["code"], ()))
return out
def _sales_marketplaces(store: Any, rows: Sequence[Mapping[str, Any]] | None = None) -> list[dict[str, Any]]:
"""대시보드 열 = 사용 ON + 매출 집계 ON 인 쇼핑몰(설정 순서 — 그룹 하위는 그룹 자리). 그룹 행은 빠진다(매출 없음)."""
rows = ordered_marketplaces(store.list_marketplaces() if rows is None else rows)
return [m for m in rows if m["enabled"] and m["include_in_sales"] and get_adapter(m["code"]) is not None]
def _group_columns(store_rows: Sequence[Mapping[str, Any]], codes: Sequence[str]) -> tuple[list[dict[str, Any]], dict[str, list[str]]]:
"""일자별 표 열 — 그룹(009)은 보이는 하위 쇼핑몰이 하나라도 있을 때 하위 열 바로 앞에 그룹 합계 열.
[{code, kind: shop|group|child, group}], 그룹 → 보이는 하위 코드."""
groups = {m["code"]: m for m in store_rows if m.get("is_group")}
parent = {m["code"]: m.get("parent_code") for m in store_rows if m.get("parent_code") in groups}
members: dict[str, list[str]] = {}
cols: list[dict[str, Any]] = []
for c in codes:
g = parent.get(c)
if g is None:
cols.append({"code": c, "kind": "shop", "group": ""})
continue
if g not in members:
members[g] = []
cols.append({"code": g, "kind": "group", "group": g})
members[g].append(c)
cols.append({"code": c, "kind": "child", "group": g})
return cols, members
# 카페24 − 카페24 공동구매 열(2026-10-30) — 직접 추가 쇼핑몰 "카페24 공동구매" 바로 오른쪽, 표 열만(일 합계·그래프·누적엔 안 더함).
# shortcut: 공동구매 쇼핑몰은 이름(띄어쓰기 무시)으로 찾는다 — 설정에서 이름을 바꾸면 이 열이 사라진다, 자주 바뀌면 설정 값으로.
CAFE24_GB_NAME = "카페24공동구매"
CAFE24_EX_GB = "cafe24_ex_gb"
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:
return
i = next(i for i, col in enumerate(cols) if col["code"] == gb)
cols.insert(i + 1, {"code": CAFE24_EX_GB, "kind": "diff", "group": cols[i]["group"]})
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")}
def display_status(marketplace: Mapping[str, Any], status_row: Mapping[str, Any] | None,
configured: bool) -> str:
if not marketplace.get("enabled"):
return "disabled"
adapter = get_adapter(marketplace["code"])
if adapter is not None and adapter.manual_only:
return "manual"
if adapter is not None and not adapter.uses_shared_integration and not configured:
return "not_configured"
return (status_row or {}).get("status") or "unknown"
# 매출 단위(2026-10-19, 실적 설정 "보기 설정" — 이 브라우저 쿠키 perf_unit) — (나누는 수, 소수 자리, 단위 이름)
UNITS: dict[str, tuple[int, int, str]] = {"won": (1, 0, "원"), "thousand": (1000, 0, "천원"), "million": (1_000_000, 1, "백만원")}
UNIT_COOKIE = "perf_unit"
def normalize_unit(value: Any) -> str:
return value if value in UNITS else "won"
# 일자별 표 열 너비(2026-10-27, 실적 설정 "보기 설정" — 이 브라우저 쿠키 perf_colw) — auto = 글자 길이에 맞춤, manual = 머리글 경계 드래그
COLW_COOKIE = "perf_colw"
def normalize_colw(value: Any) -> str:
return "manual" if value == "manual" else "auto"
def amount_text(value: Any, unit: str = "won") -> str:
"""금액 → 화면 글자(쉼표). 천원은 정수, 백만원은 소수 한 자리(반올림)."""
div, places, _ = UNITS[normalize_unit(unit)]
if div == 1:
return f"{int(value):,}"
q = (Decimal(int(value)) / div).quantize(Decimal(1).scaleb(-places), rounding=ROUND_HALF_UP)
return f"{q:,.{places}f}"
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"] = 보이는 쇼핑몰 광고비 합.
일 합계 ROAS 는 단순하게 일 합계 금액 ÷ 일 합계 광고비(2026-10-19) — roas = 총매출 기준, roas_net = 수수료 차감 매출 기준
(화면 표시 기준에 따라 하나만 보인다). 예전엔 광고비가 있는 쇼핑몰 매출만 더해 일 합계 금액과 맞지 않았다.
광고비 표(005)가 없거나 읽기 실패면 줄 없음."""
from . import ad_spend # noqa: WPS433
by_code = sales_ad_channels()
want = {ch for c in codes for ch, _ in by_code.get(c, ())}
for r in table:
r["ads"], r["ads_total"] = {}, None
if not want:
return
try:
amounts, _ = store.ad_amounts(q_start, q_end)
reader = getattr(store, "ad_roas", None)
roas_map = reader(q_start, q_end) if reader else {}
except Exception: # noqa: BLE001 — 광고비 표가 없어도 매출 화면은 그대로
return
spend_by: dict[str, list[tuple[date, int]]] = {}
for (d, ch), v in amounts.items():
if ch in want and v:
spend_by.setdefault(ch, []).append((d, int(v)))
sales_by: dict[str, list[tuple[date, int]]] = {}
for (d, c), m in cells.items():
sales_by.setdefault(c, []).append((d, int(m.gross)))
def spend(ch: str, s: date, e: date) -> int:
return sum(v for d, v in spend_by.get(ch, ()) if s <= d <= e)
def sales(c: str, s: date, e: date) -> int:
return sum(v for d, v in sales_by.get(c, ()) if s <= d <= e)
for r in table:
s = date.fromisoformat(r["from"]) if r.get("from") else period.start
e = date.fromisoformat(r["to"]) if r.get("to") else period.end
tot_spend = 0
for c in codes:
lines = []
for ch, label in by_code.get(c, ()):
amt = spend(ch, s, e)
if not amt:
continue
rs = ad_spend.channel_roas(ch, lambda m: sales(m, s, e), amt,
lambda f: ad_spend.file_roas(f, roas_map, amounts, s, e))
lines.append({"label": label, "amount": amt, "roas": rs})
tot_spend += amt
if lines:
r["ads"][c] = lines
if tot_spend:
tot = r.get("total") or {}
r["ads_total"] = {"amount": tot_spend, "roas": ad_spend.roas(tot.get("gross") or 0, tot_spend),
"roas_net": ad_spend.roas(tot.get("net") or 0, tot_spend)}
def sales_ad_channels() -> dict[str, tuple[tuple[str, str], ...]]:
"""쇼핑몰(매출 코드) → 그 아래 보일 광고 채널 [(채널, 줄 이름)]. 카페24 = 구글·메타(자사몰 광고), 네이버 = 네이버 광고,
나머지는 광고비 화면의 ROAS 매출 쇼핑몰(쿠팡(윙) 광고 → 쿠팡 매출)."""
from . import ad_spend # noqa: WPS433
out: dict[str, tuple[tuple[str, str], ...]] = {"cafe24": (("google", "구글"), ("meta", "메타")), "naver": (("naver", ""),)}
for ch, c in ad_spend.ROAS_SALES_CODE.items():
out[c] = out.get(c, ()) + ((ch, ""),)
return out
def build_dashboard(store: Any, *, kind: str, anchor: date, today: date,
custom_from: date | None = None, custom_to: date | None = None,
selected: Sequence[str] = (), holidays: Mapping[str, str] | None = None,
configured: Mapping[str, bool] | None = None) -> dict[str, Any]:
store_rows = store.list_marketplaces()
markets = _sales_marketplaces(store, store_rows)
all_codes = [m["code"] for m in markets]
codes = [c for c in all_codes if c in set(selected)] or all_codes
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)
for m in store_rows:
if m["code"] in group_members:
names[m["code"]] = short[m["code"]] = m["name"]
period = calc.resolve_period(kind, anchor, custom_from=custom_from, custom_to=custom_to)
cmp_start, cmp_end, cmp_label = period.compare_range(today)
# 월·연 누적의 기준일 — 선택 기간이 오늘을 포함하면 오늘(이번주가 다음 달로 걸쳐도
# "이번달"), 지난 기간이면 기간 끝, 앞으로의 기간이면 기간 시작.
if period.end < today:
ref = period.end
elif period.start <= today:
ref = today
else:
ref = period.start
month_period = calc.resolve_period("month", ref)
year_period = calc.resolve_period("year", ref)
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)
q_end = max(period.end, year_period.end)
cells = calc.build_cells(store.daily_amounts(q_start, q_end, codes), store.rate_table())
# 수동 입력(설정에서 켠 쇼핑몰) — 일자별 표의 날짜 칸을 눌러 입력. 값이 있는 칸은 표시(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)
manual_cells = sorted(f"{d.isoformat()}|{c}" for d, c in
(manual_amounts(period.start, period.end, manual_codes) if manual_amounts and manual_codes else {}))
# 계산식으로 입력한 수동 칸(마이그레이션 008) — "날짜|쇼핑몰" → 식
manual_formulas = getattr(store, "manual_formulas", None)
formula_cells = {f"{d.isoformat()}|{c}": f for (d, c), f in
(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)
period_word = {"day": "오늘" if period.start == today else "해당일", "week": "이번주" if period.start <= today <= period.end else "해당 주",
"month": "이번달" if period.start <= today <= period.end else "해당 월",
"year": "올해" if period.start <= today <= period.end else "해당 연도",
"custom": "선택 기간"}[period.kind]
# KPI 는 수수료 차감 매출 하나만(2026-10-19) — 화면 왼쪽 한 줄(금액 + 비교 기간 대비 %).
# 총매출·수수료·월 누적·연 누적 카드는 뺐다(아래 표·월/연 누적 카드에 같은 값이 있다).
kpis = [
{"key": "net", "label": f"{period_word} 수수료 차감 매출", "value": cur.net, "primary": True,
"delta": calc.pct_change(cur.net, prev.net), "cmp": cmp_label},
]
share = calc.by_code(cells, codes, period.start, period.end)
statuses = store.statuses()
configured = configured or {}
problems = []
for m in markets:
if m["code"] not in codes:
continue
st = display_status(m, statuses.get(m["code"]), configured.get(m["code"], False))
if st in ("auth_failed", "token_expired", "api_error"):
problems.append({"code": m["code"], "name": m["name"], "label": STATUS_LABELS[st],
"error": (statuses.get(m["code"]) or {}).get("last_error", "")})
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)
_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)
def url(kind: str, anchor_d: date | None = None, start: date | None = None, end: date | None = None) -> str:
if kind == "custom":
return f"?period=custom&from={start.isoformat()}&to={end.isoformat()}{m_qs}"
return f"?period={kind}&d={anchor_d.isoformat()}{m_qs}"
if period.kind == "custom":
length = timedelta(days=period.days)
prev_url = url("custom", start=period.start - length, end=period.start - timedelta(days=1))
next_url = url("custom", start=period.end + timedelta(days=1), end=period.end + length)
else:
prev_url = url(period.kind, period.prev_anchor)
next_url = url(period.kind, period.next_anchor)
nav = {
"prev": prev_url, "next": next_url,
# 빠른 선택은 이번달·올해만(2026-10-26 — 오늘·이번주 버튼 삭제, 기본 = 이번달)
"quick": [
{"key": "month", "label": "이번달", "url": url("month", today),
"active": period.kind == "month" and period.start <= today <= period.end},
{"key": "year", "label": "올해", "url": url("year", today),
"active": period.kind == "year" and period.start <= today <= period.end},
],
"m_qs": m_qs,
}
return {
"nav": nav,
"period": period,
"period_kind": period.kind,
"today": today.isoformat(),
"codes": codes,
"cols": cols,
"group_members": group_members,
"all_codes": all_codes,
"names": names,
"short_names": short,
"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],
"problems": problems,
"manual_codes": manual_codes,
"manual_cells": manual_cells,
"formula_cells": formula_cells,
# 날짜 칸 메모(마이그레이션 010) — "날짜|쇼핑몰" → 메모
"memo_cells": {f"{d.isoformat()}|{c}": m for (d, c), m in
(store.cell_memos("sales", period.start, period.end) if hasattr(store, "cell_memos") else {}).items()},
# 엑셀 업로드 대상 — 수동 입력이 켜진 쇼핑몰 전부(쇼핑몰 선택 필터와 무관, 설정 순서)
"manual_upload_names": [m["name"] for m in markets if m.get("manual_input")],
"last_update_at": store.last_update_at(),
"running": store.running_codes(),
"no_marketplaces": not all_codes,
}
def _short_name(name: str) -> str:
return {"네이버 스마트스토어": "네이버", "토스쇼핑": "토스"}.get(name, name)
def build_settings(store: Any, *, configured: Mapping[str, bool], key_info: Mapping[str, Any],
key_versions_in_use: Mapping[int, int], sample_count: int) -> dict[str, Any]:
from app.timezone import today_kst # noqa: WPS433
from .adapters.cafe24 import MARKET_MAP # noqa: WPS433
statuses = store.statuses()
rates = store.rate_table()
today = today_kst()
via_cafe24 = set(MARKET_MAP.values()) # 카페24 마켓 통합관리 경유로 매출이 들어오는 쇼핑몰
rows = []
store_rows = store.list_marketplaces()
groups = [{"code": m["code"], "name": m["name"]} for m in store_rows if m.get("is_group")]
group_codes = {g["code"] for g in groups}
for m in ordered_marketplaces(store_rows):
code = m["code"]
parent = m.get("parent_code") if m.get("parent_code") in group_codes else ""
if m.get("is_group"):
# 그룹(009) — 매출·수수료·연결 없음, 하위 쇼핑몰 합계는 매출 실적 화면에서
rows.append({"code": code, "name": m["name"], "is_group": True, "is_custom": True, "parent": "",
"children": sum(1 for x in store_rows if x.get("parent_code") == code)})
continue
adapter = get_adapter(code)
if adapter is None:
continue
st_row = statuses.get(code) or {}
st = display_status(m, st_row, configured.get(code, False))
cur_rate = calc.rate_on(rates, code, today)
has_rate = bool(rates.get(code))
rows.append({
"code": code, "name": m["name"], "enabled": m["enabled"],
"is_group": False, "is_custom": bool(m.get("is_custom")), "parent": parent,
"include_in_sales": m["include_in_sales"], "manual_input": bool(m.get("manual_input")),
"rate": _fmt_rate(cur_rate) if has_rate else "",
"rate_history": len(rates.get(code, ())),
"auth_type": adapter.auth_type, "shared": adapter.uses_shared_integration,
"manual_only": adapter.manual_only,
"implemented": adapter.implemented, "note": adapter.note, "docs_url": adapter.docs_url,
"configured": configured.get(code, False),
"via_cafe24": code in via_cafe24,
"status": st, "status_label": STATUS_LABELS.get(st, st),
"last_test_at": st_row.get("last_test_at"), "last_test_ok": st_row.get("last_test_ok"),
"last_sync_at": st_row.get("last_sync_at"), "last_success_sync_at": st_row.get("last_success_sync_at"),
"last_error": st_row.get("last_error") or "", "last_error_at": st_row.get("last_error_at"),
})
# 드래그 단위 — 그룹 없는 행 하나 또는 그룹 + 하위 쇼핑몰(하위는 그 안에서만 순서 변경)
blocks: list[dict[str, Any]] = []
for r in rows:
if r["parent"] and blocks and blocks[-1]["row"]["code"] == r["parent"]:
blocks[-1]["children"].append(r)
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,
"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,
"default_sample_from": today.replace(month=1, day=1).isoformat(),
"default_sample_to": today.isoformat()}
def _fmt_rate(rate: Decimal) -> str:
s = f"{Decimal(rate):f}"
if "." in s:
s = s.rstrip("0").rstrip(".")
return s