Files
dbx-main/app/modules/performance/dashboard.py
T
king 1d3573a44a feat(performance): upload manual-input sales from an Excel file
- [엑셀 업로드] button on the daily x marketplace table opens a popup with
  a sample download (module upload_sample.xlsx) and a file picker
- Format: column 1 = date, columns 2+ = marketplace names as headers
  (setting name / short name / code, spaces and case ignored)
- Only filled cells of marketplaces with manual input ON are saved
  (overwrite same day, blank cells keep existing values); other columns
  are skipped and reported
- Any bad cell (not a number, unreadable/future date, duplicate day) rejects
  the whole file with cell references; saving is one transaction
- Ignore Excel lock files (~$*)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 04:58:00 +09:00

214 lines
11 KiB
Python

"""④ 대시보드/설정 화면 데이터 조립 — 저장소 조회 + calc 계산 결과를 템플릿 컨텍스트로.
HTTP 와 무관하다(store 만 주입). 라우터는 파라미터 파싱·권한만 하고 여기로 넘긴다.
"""
from __future__ import annotations
from datetime import date, timedelta
from decimal import 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"
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)
mtd = calc.sum_range(cells, codes, month_period.start, month_period.end)
m_prev = calc.sum_range(cells, codes, m_cmp_start, m_cmp_end)
ytd = calc.sum_range(cells, codes, year_period.start, year_period.end)
y_prev = calc.sum_range(cells, codes, y_cmp_start, y_cmp_end)
has_prev = prev.gross != 0 or prev.commission != 0
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]
kpis = [
{"key": "gross", "label": f"{period_word} 총매출", "value": cur.gross, "primary": True,
"delta": calc.pct_change(cur.gross, prev.gross), "cmp": cmp_label},
{"key": "net", "label": f"{period_word} 수수료 차감 매출", "value": cur.net, "primary": True,
"delta": calc.pct_change(cur.net, prev.net), "cmp": cmp_label},
{"key": "commission", "label": f"{period_word} 수수료", "value": cur.commission,
"delta": calc.pct_change(cur.commission, prev.commission) if has_prev else None, "cmp": cmp_label,
"invert": True},
{"key": "mtd", "label": f"{month_period.label} 누적 매출", "value": mtd.gross,
"delta": calc.pct_change(mtd.gross, m_prev.gross), "cmp": m_cmp_label},
{"key": "ytd", "label": f"{year_period.label} 누적 매출", "value": ytd.gross,
"delta": calc.pct_change(ytd.gross, y_prev.gross), "cmp": y_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)
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": calc.main_table(period, codes, cells, today=today, holidays=holidays),
"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