884e654bea
매출 실적 - "카페24" 열 → "카페24(전체)", 바로 오른쪽 "카페24(실적)" = 전체 − 자사몰(공동구매), 광고비 줄은 카페24(전체)의 구글·메타 그대로 (예전 "공구 제외" 열 대체) - 합계 기준 통일: 일 합계·ROAS·KPI·추이·비중·월/연 누적 = 카페24(실적) + 공동구매 + 나머지 (카페24(전체)에 공동구매가 들어 있어 이중 합산 제거, 그래프·누적의 카페24 줄 = 카페24(실적)) - 실적 설정 "공통 보기 설정"(관리자, perf_settings, 모든 사용자 적용): 매출 단위(예전 브라우저 쿠키 perf_unit 대체), 표 열 숨기기(열만, 합계 그대로) 표 열 너비는 사람(브라우저)마다 그대로 매출 실적·광고비 공통 - 일 합계 열을 날짜 오른쪽으로, 날짜와 함께 가로 고정 - 이전달·다음달 = 날짜 바로 옆 진한 회색 화살표 SVG(글자 높이) - 광고비 탭 매출 대비 광고비·합계 ROAS 도 공동구매 이중 합산 제거 CSS·JS 캐시 버전 20261102a. 새 마이그레이션 없음(011 perf_settings 사용). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
460 lines
24 KiB
Python
460 lines
24 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 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(실적) 열(2026-11-02, 예전 "공구 제외") — 카페24(전체) 바로 오른쪽, 카페24 − 공동구매. 표 열만(일 합계·그래프·누적엔 안 더함).
|
||
# shortcut: 공동구매 쇼핑몰은 이름(띄어쓰기 무시)으로 찾는다 — 설정에서 다른 이름으로 바꾸면 빼지 않아 실적 = 전체가 된다, 자주 바뀌면 설정 값으로.
|
||
CAFE24_GB_NAMES = ("자사몰(공동구매)", "카페24공동구매")
|
||
CAFE24_EX_GB = "cafe24_ex_gb"
|
||
CAFE24_REAL_NAME = "카페24(실적)"
|
||
|
||
|
||
def groupbuy_code(markets: Sequence[Mapping[str, Any]]) -> str:
|
||
"""공동구매 쇼핑몰 코드, 없으면 빈 값."""
|
||
return next((m["code"] for m in markets if m["name"].replace(" ", "") in CAFE24_GB_NAMES), "")
|
||
|
||
|
||
def total_sales_codes(markets: Sequence[Mapping[str, Any]]) -> list[str]:
|
||
"""전체 매출에 더할 쇼핑몰 — 카페24(전체)에 공동구매가 들어 있어 카페24 가 있으면 공동구매는 뺀다(광고비 탭 매출 대비 광고비·합계 ROAS)."""
|
||
codes = [m["code"] for m in markets]
|
||
gb = groupbuy_code(markets)
|
||
return [c for c in codes if c != gb] if "cafe24" in codes else codes
|
||
|
||
|
||
def _summary_cells(cells: Mapping[tuple[date, str], calc.Money], gb: str) -> dict[tuple[date, str], calc.Money]:
|
||
"""합계용 칸(2026-11-02) — 카페24 칸 = 카페24(실적)(카페24 − 공동구매). 일 합계·KPI·그래프·누적은 이 값으로 더해 공동구매가 두 번 안 들어간다."""
|
||
out = dict(cells)
|
||
for (d, c), m in cells.items():
|
||
if c == gb:
|
||
a = cells.get((d, "cafe24"), calc.Money())
|
||
out[(d, "cafe24")] = calc.Money(gross=a.gross - m.gross, commission=a.commission - m.commission)
|
||
return out
|
||
|
||
|
||
def _cafe24_real_column(cols: list[dict[str, Any]], names: dict[str, str], short: dict[str, str], gb: str) -> None:
|
||
"""카페24(실적) 열 머리 — 공동구매가 없으면(gb 빈 값) 전체와 같은 값이고 화면 즉시 계산도 없다."""
|
||
col = next((c for c in cols if c["code"] == CAFE24_EX_GB), None)
|
||
if col is None:
|
||
return
|
||
# base·minus = 화면이 공동구매 칸 저장 때 이 줄 칸을 바로 다시 계산할 때 씀(performance.js saveManual)
|
||
col.update(kind="diff", base="cafe24", minus=gb)
|
||
names[CAFE24_EX_GB] = f"{names['cafe24']} − {names[gb]}" if gb else CAFE24_REAL_NAME
|
||
short[CAFE24_EX_GB] = CAFE24_REAL_NAME
|
||
|
||
|
||
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, 11-02 실적 설정 "공통 보기 설정" — 모든 사용자 같음, 마이그레이션 011 perf_settings) — (나누는 수, 소수 자리, 단위 이름)
|
||
UNITS: dict[str, tuple[int, int, str]] = {"won": (1, 0, "원"), "thousand": (1000, 0, "천원"), "million": (1_000_000, 1, "백만원")}
|
||
UNIT_SETTING = "display_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"
|
||
|
||
|
||
# 매출 실적 표 열 숨기기(2026-11-02, 실적 설정 "공통 보기 설정" — 관리자가 정하면 모든 사용자에게 적용, 마이그레이션 011 perf_settings) — 코드 목록, 열만 숨김
|
||
HIDDEN_SETTING = "hidden_marketplaces"
|
||
|
||
|
||
def _shared_setting(store: Any, key: str) -> Any:
|
||
"""모든 사용자 공통 설정 값. 저장 값 없음·011 미적용이면 None(화면은 그대로 열린다)."""
|
||
from .db import SettingsMigrationNeeded # noqa: WPS433
|
||
|
||
reader = getattr(store, "get_setting", None)
|
||
try:
|
||
return reader(key) if reader else None
|
||
except SettingsMigrationNeeded:
|
||
return None
|
||
|
||
|
||
def load_hidden(store: Any) -> set[str]:
|
||
return set(_shared_setting(store, HIDDEN_SETTING) or ())
|
||
|
||
|
||
def load_unit(store: Any) -> str:
|
||
return normalize_unit(_shared_setting(store, UNIT_SETTING))
|
||
|
||
|
||
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) — 그룹 열 = 보이는 하위 쇼핑몰 합계(표 열만, 합계·그래프·누적은 쇼핑몰 기준 그대로)
|
||
# 표에 그릴 열 = 고른 쇼핑몰 + 카페24 바로 뒤 카페24(실적) − 숨긴 열(합계·그래프·누적은 codes 그대로)
|
||
hidden = load_hidden(store)
|
||
shown = [x for c in codes for x in ((c, CAFE24_EX_GB) if c == "cafe24" else (c,)) if x not in hidden]
|
||
cols, group_members = _group_columns(store_rows, shown)
|
||
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)
|
||
gb = groupbuy_code(markets)
|
||
# 공동구매를 필터로 뺐어도 카페24(실적) 계산엔 필요 — 합계·그래프는 아래에서 codes 만 더한다
|
||
cells = calc.build_cells(store.daily_amounts(q_start, q_end, codes if not gb or gb in codes else [*codes, gb]),
|
||
store.rate_table())
|
||
summary = _summary_cells(cells, gb)
|
||
# 수동 입력(설정에서 켠 쇼핑몰) — 일자별 표의 날짜 칸을 눌러 입력. 값이 있는 칸은 표시(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(summary, codes, period.start, period.end)
|
||
prev = calc.sum_range(summary, 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(summary, codes, period.start, period.end)
|
||
# 비중 그래프·월 누적 표의 카페24 줄 = 카페24(실적) — 줄을 더하면 합계와 같다
|
||
summary_names = {**names, "cafe24": CAFE24_REAL_NAME}
|
||
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)
|
||
# 일 합계 = 카페24(실적) + 공동구매 + 나머지(2026-11-02) — 공동구매를 필터로 뺐으면 실적 + 나머지.
|
||
# 일 합계 ROAS 도 이 값 기준이라 _ad_lines 앞에서.
|
||
for r, s in zip(table, calc.main_table(period, codes, summary, today=today, holidays=holidays)):
|
||
r["total"] = s["total"]
|
||
if "cafe24" in codes:
|
||
r["cells"][CAFE24_EX_GB] = s["cells"]["cafe24"]
|
||
_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_real_column(cols, names, short, gb)
|
||
|
||
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,
|
||
"summary_names": summary_names,
|
||
"month": calc.month_summary(month_period.start.year, month_period.start.month, codes, summary),
|
||
"year": calc.year_months(year_period.start.year, codes, summary, today=today),
|
||
"chart_daily": calc.daily_series(period, codes, summary),
|
||
"chart_share": [{"code": c, "name": summary_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 {"네이버 스마트스토어": "네이버", "토스쇼핑": "토스", "카페24": "카페24(전체)"}.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"]}
|
||
# "매출 실적 표 열 숨기기" 목록 = 매출 실적 표에 나오는 열(그룹 열은 하위를 다 숨기면 사라진다)
|
||
hide_options: list[dict[str, str]] = []
|
||
for r in rows:
|
||
if not r["is_group"] and r["enabled"] and r["include_in_sales"]:
|
||
hide_options.append({"code": r["code"], "name": _short_name(r["name"])})
|
||
if r["code"] == "cafe24":
|
||
hide_options.append({"code": CAFE24_EX_GB, "name": CAFE24_REAL_NAME})
|
||
return {"rows": rows, "blocks": blocks, "groups": groups, "hide_options": hide_options, "hidden_codes": load_hidden(store),
|
||
"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
|