Files
dbx-main/app/modules/performance/dashboard.py
T
king ee96c924fc feat(performance): KPI 수수료 차감 매출 한 줄·기본 보기 차감 매출·다음 업데이트 카운트다운·일 합계 ROAS
- KPI 는 수수료 차감 매출만 화면 왼쪽 한 줄(금액 + 비교 기간 대비 %), 나머지 카드 제거
- 일자별 표 기본 보기 = 수수료 차감 매출(localStorage 저장값 안 씀)
- 마지막 업데이트 옆 다음 자동 업데이트까지 남은 시간(초 단위 실시간)
- 일 합계 ROAS = 일 합계 금액 ÷ 일 합계 광고비(보기 기준별 roas / roas_net)

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

291 lines
14 KiB
Python

"""④ 대시보드/설정 화면 데이터 조립 — 저장소 조회 + 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 all_adapters, get_adapter
def _sales_marketplaces(store: Any) -> list[dict[str, Any]]:
"""대시보드 열 = 사용 ON + 매출 집계 ON 인 쇼핑몰(설정 순서)."""
known = {a.code for a in all_adapters()}
return [m for m in store.list_marketplaces() if m["enabled"] and m["include_in_sales"] and m["code"] in known]
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"
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]:
markets = _sales_marketplaces(store)
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}
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 {}))
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)
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,
"quick": [
{"key": "day", "label": "오늘", "url": url("day", today),
"active": period.kind == "day" and period.start == today},
{"key": "week", "label": "이번주", "url": url("week", today),
"active": period.kind == "week" and period.start <= today <= period.end},
{"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,
"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,
# 엑셀 업로드 대상 — 수동 입력이 켜진 쇼핑몰 전부(쇼핑몰 선택 필터와 무관, 설정 순서)
"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 = []
by_code = {m["code"]: m for m in store.list_marketplaces()}
for adapter in all_adapters():
m = by_code.get(adapter.code)
if m is None:
continue
st_row = statuses.get(adapter.code) or {}
st = display_status(m, st_row, configured.get(adapter.code, False))
cur_rate = calc.rate_on(rates, adapter.code, today)
has_rate = bool(rates.get(adapter.code))
rows.append({
"code": adapter.code, "name": m["name"], "enabled": m["enabled"],
"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(adapter.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(adapter.code, False),
"via_cafe24": adapter.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"),
})
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, "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