feat(performance): KPI 수수료 차감 매출 한 줄·기본 보기 차감 매출·다음 업데이트 카운트다운·일 합계 ROAS

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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-19 23:19:14 +09:00
parent b23774420b
commit ee96c924fc
10 changed files with 151 additions and 57 deletions
+5 -1
View File
@@ -43,7 +43,11 @@
## 매출 실적 화면 (2026-10-19)
- 일자별 표 매출 칸 아래 **광고비(ROAS%)** 주황 줄(`--perf-ad`, `dashboard._ad_lines`) — 광고비 탭과 같은 값(`ad_spend.channel_roas`). 쇼핑몰 → 광고 채널은 `dashboard.sales_ad_channels`: 카페24 = 구글·메타 두 줄(이름 붙임), 네이버 = 네이버, 나머지는 `ROAS_SALES_CODE`(쿠팡 ← 쿠팡(윙)). 일 합계 = 보이는 쇼핑몰 광고비 합(ROAS = 매출 합 ÷ 광고비 합). 광고비 표 없으면 줄 없음.
- KPI 는 **수수료 차감 매출 하나만** 화면 왼쪽 한 줄(`.perf-kpi-line` — 금액 + 비교 기간 대비 %, 모든 기간 공통). 총매출·수수료·월/연 누적 카드는 뺐다.
- 일자별 표 기본 보기 = **수수료 차감 매출**(라우터 기본 `metric=net`, 예전에 고른 보기 localStorage 는 안 씀).
- 마지막 업데이트 옆 **다음 업데이트까지 남은 시간** 초 단위 실시간(`router._auto_sync_ctx` → `performance.js initNextUpdate`, 자동 업데이트 규칙 `auto_sync.next_slot` 과 같게 화면이 다음 회차 계산, 서버 시각으로 PC 시계 보정, 자동 업데이트 꺼지면 숨김).
- 일자별 표 매출 칸 아래 **광고비(ROAS%)** 주황 줄(`--perf-ad`, `dashboard._ad_lines`) — 광고비 탭과 같은 값(`ad_spend.channel_roas`). 쇼핑몰 → 광고 채널은 `dashboard.sales_ad_channels`: 카페24 = 구글·메타 두 줄(이름 붙임), 네이버 = 네이버, 나머지는 `ROAS_SALES_CODE`(쿠팡 ← 쿠팡(윙)). 일 합계 = 보이는 쇼핑몰 광고비 합, ROAS = **일 합계 금액 ÷ 일 합계 광고비**(2026-10-19 — 예전엔 광고비 있는 쇼핑몰 매출만 더했다; `roas` 총매출·`roas_net` 수수료 차감 매출 기준, 보기 기준에 따라 하나만). 광고비 표 없으면 줄 없음.
- **매출 단위** 원·천원·백만원 — 설정 "보기 설정"(누구나, 이 브라우저 쿠키 `perf_unit`), 서버가 `amount_text`(천원 정수·백만원 소수 한 자리)로 그림(`router._unit_ctx` → 템플릿 `amt`). 광고비 탭은 원 그대로.
- 설정의 진단 카드(쇼핑몰 원본 데이터 확인·카페24 매출 대조·일별 한 번에 비교)는 2026-10-19 화면에서 뺐다(서버 API `marketplaces/{code}/reconcile`·`daily-check` 는 진단용으로 남김).
+9 -18
View File
@@ -53,7 +53,9 @@ def amount_text(value: Any, unit: str = "won") -> str:
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 = 매출 합 ÷ 광고비 합).
카페24 = 구글·메타 두 줄. 행마다 r["ads"][쇼핑몰] = [{label, amount, roas}], r["ads_total"] = 보이는 쇼핑몰 광고비 합.
일 합계 ROAS 는 단순하게 일 합계 금액 ÷ 일 합계 광고비(2026-10-19) — roas = 총매출 기준, roas_net = 수수료 차감 매출 기준
(화면 표시 기준에 따라 하나만 보인다). 예전엔 광고비가 있는 쇼핑몰 매출만 더해 일 합계 금액과 맞지 않았다.
광고비 표(005)가 없거나 읽기 실패면 줄 없음."""
from . import ad_spend # noqa: WPS433
@@ -87,7 +89,7 @@ def _ad_lines(store: Any, table: list[dict[str, Any]], codes: Sequence[str], cel
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 = tot_sales = 0
tot_spend = 0
for c in codes:
lines = []
for ch, label in by_code.get(c, ()):
@@ -100,9 +102,10 @@ def _ad_lines(store: Any, table: list[dict[str, Any]], codes: Sequence[str], cel
tot_spend += amt
if lines:
r["ads"][c] = lines
tot_sales += sales(c, s, e)
if tot_spend:
r["ads_total"] = {"amount": tot_spend, "roas": ad_spend.roas(tot_sales, 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], ...]]:
@@ -152,28 +155,16 @@ def build_dashboard(store: Any, *, kind: str, anchor: date, today: date,
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]
# KPI 는 수수료 차감 매출 하나만(2026-10-19) — 화면 왼쪽 한 줄(금액 + 비교 기간 대비 %).
# 총매출·수수료·월 누적·연 누적 카드는 뺐다(아래 표·월/연 누적 카드에 같은 값이 있다).
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)
+18 -2
View File
@@ -116,7 +116,7 @@ def dashboard_page(
from_: str | None = Query(None, alias="from"),
to: str | None = None,
m: list[str] = Query(default=[]),
metric: str = "gross",
metric: str = "net",
):
from app.main import render_template # noqa: WPS433
@@ -134,11 +134,27 @@ def dashboard_page(
custom_from=_parse_date(from_), custom_to=_parse_date(to), selected=m,
holidays=_holidays(), configured=creds.configured_codes(list(all_adapters())),
)
ctx["metric"] = metric if metric in ("gross", "commission", "net") else "gross"
ctx["metric"] = metric if metric in ("gross", "commission", "net") else "net"
ctx["auto_sync"] = _auto_sync_ctx()
_unit_ctx(request, ctx)
return render_template(request, "performance/index.html", {**common.base_ctx(user, active_tab="dashboard"), **ctx})
def _auto_sync_ctx() -> dict[str, Any] | None:
"""다음 자동 업데이트까지 남은 시간(2026-10-19) — 화면이 초 단위로 센다. 회차가 지나면 화면이 같은 규칙
(hours·slot, KST)으로 다음 회차를 계산한다. 서버 시각(now)으로 PC 시계 차이를 보정. 자동 업데이트가 꺼져 있으면 None."""
from app.timezone import now_kst # noqa: WPS433
from . import auto_sync # noqa: WPS433
if not auto_sync.enabled():
return None
hours = auto_sync.hour_window()
now = now_kst()
return {"next_at": auto_sync.next_slot(now, hours).isoformat(), "now": now.isoformat(timespec="milliseconds"),
"hours": list(hours), "slot": auto_sync.SLOT_MINUTES}
def _unit_ctx(request: Request, ctx: dict[str, Any]) -> None:
"""매출 단위(원·천원·백만원) — 실적 설정 "보기 설정"이 이 브라우저 쿠키(perf_unit)에 둔다. 템플릿은 amt(v) 로 그린다."""
from .dashboard import UNIT_COOKIE, UNITS, amount_text, normalize_unit # noqa: WPS433
@@ -1,6 +1,6 @@
{% extends "erp_base.html" %}
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261019e" />{% endblock %}
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261019f" />{% endblock %}
{#- ROAS 덧붙임 — "광고비(ROAS%)". 광고비가 없으면 아무것도 안 붙는다. -#}
{%- macro roas(p) -%}{%- if p is not none -%}<span class="perf-roas">({{ "{:,}".format(p) }}%)</span>{%- endif -%}{%- endmacro -%}
@@ -224,4 +224,4 @@
} | tojson }}</script>
{% endblock %}
{% block scripts %}<script src="/static/performance.js?v=20261019d" defer></script>{% endblock %}
{% block scripts %}<script src="/static/performance.js?v=20261019e" defer></script>{% endblock %}
@@ -1,6 +1,6 @@
{% extends "erp_base.html" %}
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261019e" />{% endblock %}
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261019f" />{% endblock %}
{%- macro won(v) -%}
{%- if v is none -%}<span class="perf-na"></span>
@@ -16,6 +16,14 @@
{%- for a in lines or [] -%}<span class="perf-adl" title="{{ (a.label ~ ' ') if a.label }}광고비 {{ '{:,}'.format(a.amount) }}원{% if a.roas is not none %} · ROAS {{ '{:,}'.format(a.roas) }}%{% endif %}">{% if a.label %}<i>{{ a.label }}</i>{% endif %}{{ amt(a.amount) }}{% if a.roas is not none %}<em>({{ "{:,}".format(a.roas) }}%)</em>{% endif %}</span>{%- endfor -%}
{%- endmacro -%}
{#- 일 합계 광고비(ROAS%) — ROAS = 일 합계 금액 ÷ 일 합계 광고비. 수수료 차감 매출 보기면 차감 매출 기준, 그 밖엔 총매출 기준 -#}
{%- macro adl_total(a) -%}
{%- for key, cls in (("roas", "for-gross"), ("roas_net", "for-net")) -%}
{%- set rs = a[key] -%}
<span class="perf-adl perf-adl-tot {{ cls }}" title="광고비 합계 {{ '{:,}'.format(a.amount) }}원{% if rs is not none %} · ROAS {{ '{:,}'.format(rs) }}% (일 합계 {{ '수수료 차감 매출' if key == 'roas_net' else '총매출' }} ÷ 광고비){% endif %}">{{ amt(a.amount) }}{% if rs is not none %}<em>({{ "{:,}".format(rs) }}%)</em>{% endif %}</span>
{%- endfor -%}
{%- endmacro -%}
{#- 한 칸에 총매출/수수료/차감매출 세 값을 넣고, 보기 전환은 CSS(data-metric)로. -#}
{%- macro m3(m) -%}
<span class="v v-gross">{{ won(m.gross) }}</span><span class="v v-commission">{{ won(m.commission) }}</span><span class="v v-net">{{ won(m.net) }}</span>
@@ -72,6 +80,10 @@
<div class="perf-update">
<span class="perf-muted" id="perf-last-update">마지막 업데이트
<b>{{ (last_update_at or '')[:16] | replace('T', ' ') or '—' }}</b></span>
{% if auto_sync %}
{# 다음 자동 업데이트까지 남은 시간 — 초 단위로 실시간(performance.js initNextUpdate, 2026-10-19) #}
<span class="perf-muted perf-next-update" id="perf-next-update" title="자동 업데이트: 매일 {{ auto_sync.hours[0] }}~{{ auto_sync.hours[1] }}시 {{ auto_sync.slot }}분마다">다음 업데이트까지 <b>—</b></span>
{% endif %}
{# 업데이트 중에도 누를 수 있다 — 진행 중인 업데이트(수동·자동)의 진행 창을 다시 연다(2026-10-19) #}
<button type="button" class="erp-btn erp-btn-primary{% if running %} is-running{% endif %}" id="perf-sync-btn"
title="{% if running %}업데이트 진행 상황 보기{% else %}지금 보고 있는 기간({{ period.label }}, 오늘까지)의 매출을 쇼핑몰에서 다시 가져옵니다{% endif %}">
@@ -93,24 +105,18 @@
{% endif %}
<div class="perf-notice" id="perf-sync-result" hidden></div>
<!-- ── KPI ── -->
<div class="perf-kpis">
{% for k in kpis %}
<div class="perf-kpi{% if k.primary %} is-primary{% endif %}">
<div class="perf-kpi-label">{{ k.label }}</div>
<div class="perf-kpi-value">{{ money(k.value) }}</div>
<div class="perf-kpi-delta">
{% if k.delta is none %}<span class="perf-muted">{{ k.cmp }} 비교 없음</span>
{% else %}
{% set up = k.delta > 0 %}
<span class="perf-delta {% if k.delta == 0 %}is-flat{% elif up != (k.invert or false) %}is-up{% else %}is-down{% endif %}">
{% if k.delta > 0 %}▲{% elif k.delta < 0 %}▼{% else %}–{% endif %} {{ "%.1f" | format(k.delta | abs) }}%</span>
<span class="perf-muted">{{ k.cmp }} 대비</span>
{% endif %}
</div>
</div>
{% endfor %}
<!-- ── KPI — 수수료 차감 매출 한 줄(금액 + 비교 기간 대비 %, 2026-10-19) ── -->
{% for k in kpis %}
<div class="perf-kpi-line" title="{{ k.label }}">
<b class="perf-kpi-line-value">{{ money(k.value) }}</b>
{% if k.delta is none %}<span class="perf-muted">{{ k.cmp }} 비교 없음</span>
{% else %}
<span class="perf-delta {% if k.delta == 0 %}is-flat{% elif k.delta > 0 %}is-up{% else %}is-down{% endif %}">
{% if k.delta > 0 %}▲{% elif k.delta < 0 %}▼{% else %}–{% endif %} {{ "%.1f" | format(k.delta | abs) }}%</span>
<span class="perf-muted">{{ k.cmp }} 대비</span>
{% endif %}
</div>
{% endfor %}
<!-- ── 일자 × 쇼핑몰 ── -->
<div class="erp-card perf-card">
@@ -155,7 +161,7 @@
{% if r['from'] %}data-code="{{ c }}" data-from="{{ r['from'] }}" data-to="{{ r['to'] }}"{% endif %}>{{ m3(m) }}{{ adl(r.ads[c]) }}</td>
{% endif %}
{% endfor %}
<td class="perf-num perf-td-total">{{ m3(r.total) }}{% if r.ads_total %}{{ adl([r.ads_total]) }}{% endif %}</td>
<td class="perf-num perf-td-total">{{ m3(r.total) }}{% if r.ads_total %}{{ adl_total(r.ads_total) }}{% endif %}</td>
</tr>
{% endfor %}
</tbody>
@@ -263,8 +269,9 @@
"period_end": period.end.isoformat(),
"today": today,
"unit": unit,
"manual_upload_names": manual_upload_names
"manual_upload_names": manual_upload_names,
"auto_sync": auto_sync
} | tojson }}</script>
{% endblock %}
{% block scripts %}<script src="/static/performance.js?v=20261019d" defer></script>{% endblock %}
{% block scripts %}<script src="/static/performance.js?v=20261019e" defer></script>{% endblock %}
@@ -1,6 +1,6 @@
{% extends "erp_base.html" %}
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261019e" />{% endblock %}
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261019f" />{% endblock %}
{%- macro when(v) -%}{{ (v or '')[:16] | replace('T', ' ') or '—' }}{%- endmacro -%}
@@ -219,4 +219,4 @@
</section>
{% endblock %}
{% block scripts %}<script src="/static/performance.js?v=20261019d" defer></script>{% endblock %}
{% block scripts %}<script src="/static/performance.js?v=20261019e" defer></script>{% endblock %}
@@ -65,8 +65,8 @@ def test_ad_lines_under_sales_cells():
# 쿠팡 = 쿠팡(윙) 광고비, ROAS = 쿠팡 매출 ÷ 광고비 = 600,000 ÷ 200,000
assert day5["ads"]["coupang"] == [{"label": "", "amount": 200_000, "roas": 300}]
assert "naver" not in day5["ads"] # 그날 네이버 광고비 없음 → 줄 없음
# 일 합계 = 보이는 쇼핑몰 광고비 합, ROAS = 그 쇼핑몰들 매출 합 ÷ 광고비 합
assert day5["ads_total"] == {"amount": 350_000, "roas": 743} # 2,600,000 ÷ 350,000
# 일 합계 = 보이는 쇼핑몰 광고비 합, ROAS = 일 합계 금액 ÷ 일 합계 광고비(총매출·수수료 차감 매출 두 기준, 2026-10-19)
assert day5["ads_total"] == {"amount": 350_000, "roas": 743, "roas_net": 743} # 2,600,000 ÷ 350,000(수수료율 없음)
day6 = next(r for r in ctx["table"] if r.get("date") == "2026-10-06")
assert day6["ads"]["naver"] == [{"label": "", "amount": 300_000, "roas": 150}]
week = next(r for r in ctx["table"] if r["kind"] == "week")
@@ -78,7 +78,7 @@ def test_ad_lines_under_sales_cells():
def test_ad_lines_follow_shop_filter_and_missing_table():
ctx = dashboard.build_dashboard(_Store(), kind="week", anchor=TODAY, today=TODAY, selected=["coupang"])
day5 = next(r for r in ctx["table"] if r.get("date") == "2026-10-05")
assert list(day5["ads"]) == ["coupang"] and day5["ads_total"] == {"amount": 200_000, "roas": 300}
assert list(day5["ads"]) == ["coupang"] and day5["ads_total"] == {"amount": 200_000, "roas": 300, "roas_net": 300}
ctx = dashboard.build_dashboard(_Store(ads_missing=True), kind="week", anchor=TODAY, today=TODAY)
assert all(r["ads"] == {} and r["ads_total"] is None for r in ctx["table"]) # 광고비 표 없어도 매출 화면은 그대로
@@ -128,3 +128,26 @@ def test_dashboard_page_renders_unit_and_ad_lines(monkeypatch):
client.cookies.set("perf_unit", "million")
html = client.get("/performance/?period=week&d=2026-10-07").text
assert "단위: 백만원" in html and ">2.0<" in html and '"unit": "million"' in html
def test_total_roas_uses_whole_day_total():
"""일 합계 ROAS = 그날 일 합계 금액(광고비 없는 쇼핑몰 매출 포함) ÷ 일 합계 광고비 — 예전엔 광고비 있는 쇼핑몰 매출만 더했다."""
class _S(_Store):
def ad_amounts(self, start, end):
rows = {(date(2026, 10, 5), "google"): 100_000}
rows = {k: v for k, v in rows.items() if start <= k[0] <= end}
return rows, {k: "manual" for k in rows}
def ad_roas(self, start, end):
return {}
ctx = dashboard.build_dashboard(_S(), kind="week", anchor=TODAY, today=TODAY)
day5 = next(r for r in ctx["table"] if r.get("date") == "2026-10-05")
assert day5["total"]["gross"] == 2_600_000 # 카페24 2,000,000 + 쿠팡 600,000(광고비 없음)
assert day5["ads_total"] == {"amount": 100_000, "roas": 2600, "roas_net": 2600}
def test_kpi_is_net_only():
ctx = dashboard.build_dashboard(_Store(), kind="week", anchor=TODAY, today=TODAY)
assert [k["key"] for k in ctx["kpis"]] == ["net"]
assert ctx["kpis"][0]["value"] == 2_600_000 + 1_234_567
+9
View File
@@ -143,6 +143,11 @@ a.perf-seg.is-active, a.perf-seg.is-active:link, a.perf-seg.is-active:visited {
.perf-kpi-value { font-size: 22px; font-weight: 600; letter-spacing: -.5px; margin: 2px 0; white-space: nowrap; }
.perf-kpi.is-primary .perf-kpi-value { font-size: 24px; }
.perf-kpi-delta { font-size: 12px; display: flex; gap: 6px; align-items: baseline; flex-wrap: wrap; }
/* 매출 실적 KPI 한 줄(2026-10-19) — 수수료 차감 매출 금액 + 비교 기간 대비 %, 화면 왼쪽 */
.perf-kpi-line { display: flex; align-items: baseline; gap: 8px; flex-wrap: wrap; font-size: 13px; padding: 2px 2px 0; }
.perf-kpi-line-value { font-size: 22px; font-weight: 700; letter-spacing: -.5px; color: var(--color-rich-black); white-space: nowrap; }
/* 다음 자동 업데이트까지 남은 시간(초 단위) — 숫자 폭이 바뀌어도 흔들리지 않게 */
.perf-next-update b { font-variant-numeric: tabular-nums; }
.perf-delta { font-weight: 600; }
.perf-delta.is-up { color: var(--perf-good); } /* is-up = 좋음(수수료는 줄어야 좋음, invert) */
.perf-delta.is-down { color: var(--perf-down); }
@@ -358,6 +363,10 @@ td.is-link:hover { background: #eef2ff; text-decoration: underline; }
.perf-adl i { margin-right: 3px; font-style: normal; font-weight: 500; opacity: .8; }
.perf-adl em { margin-left: 1px; font-style: normal; font-weight: 500; opacity: .85; }
.perf .perf-main td.is-editing .perf-adl { visibility: hidden; }
/* 일 합계 광고비(ROAS%) — ROAS 는 일 합계 금액 ÷ 광고비라 표시 기준(수수료 차감 매출 / 그 밖)에 따라 하나만 */
.perf .perf-adl-tot { display: none; }
.perf[data-metric="net"] .perf-adl-tot.for-net,
.perf:not([data-metric="net"]) .perf-adl-tot.for-gross { display: block; }
.perf-adl-note { display: inline-flex; align-items: center; gap: 5px; color: var(--perf-ad); font-weight: 600; }
.perf-adl-key { width: 10px; height: 10px; border-radius: 3px; background: var(--perf-ad); }
.perf-unit-note { margin-left: 4px; }
+46 -5
View File
@@ -244,7 +244,6 @@
function initDashboard(root) {
const data = JSON.parse((document.getElementById("perf-data") || {}).textContent || "{}");
const METRIC_NAMES = { gross: "총매출", commission: "수수료", net: "수수료 차감 매출" };
const KEY = "perf_metric";
const FIXED_METRIC = root.dataset.fixedMetric || ""; // 광고비 화면 = 금액 하나(gross)뿐
const MANUAL_API = data.manual_api || "/performance/api/manual-sales/";
const MANUAL_WORD = data.manual_word || "총매출";
@@ -258,7 +257,6 @@
root.querySelectorAll(".perf-metric .perf-seg").forEach(function (b) {
b.classList.toggle("is-active", b.dataset.metric === m);
});
if (!FIXED_METRIC) { try { localStorage.setItem(KEY, m); } catch (_) {} }
drawDaily(m);
drawShare(m);
root.querySelectorAll(".perf-metric-name").forEach(function (n) { n.textContent = METRIC_NAMES[m]; });
@@ -788,9 +786,52 @@
box.innerHTML = svg(W, H, g);
}
let saved = null;
try { saved = localStorage.getItem(KEY); } catch (_) {}
setMetric(saved || root.dataset.metric || "gross");
// 매출 실적 화면은 늘 수수료 차감 매출로 연다(2026-10-19) — 서버 기본 data-metric="net", 예전에 고른 보기(localStorage)는 쓰지 않음
setMetric(root.dataset.metric || "net");
initNextUpdate(data.auto_sync);
}
// 다음 자동 업데이트까지 남은 시간 — 초 단위 실시간(2026-10-19). 서버가 준 다음 회차·지금 시각(PC 시계 차이 보정)으로 세고,
// 회차가 지나면 1분 동안 "자동 업데이트 중" 뒤 같은 규칙(auto_sync.next_slot: KST hours[0]시 정각 ~ hours[1]시 정각, slot 분마다)으로 다음 회차.
function initNextUpdate(cfg) {
const span = document.getElementById("perf-next-update");
if (!span || !cfg || !cfg.next_at) return;
span.innerHTML = '<span class="perf-next-label">다음 업데이트까지 </span><b></b>';
const label = span.firstChild, box = span.lastChild;
const KST = 9 * 3600000, step = (cfg.slot || 30) * 60000;
const first = cfg.hours ? cfg.hours[0] : 9, last = cfg.hours ? cfg.hours[1] : 19;
const skew = cfg.now ? Date.parse(cfg.now) - Date.now() : 0;
function now() { return Date.now() + skew; }
function nextSlot(after) {
let t = Math.floor((after + KST) / step) * step + step; // KST 벽시계(ms)
for (let i = 0; i < 48 * 2 + 2; i++) {
const d = new Date(t), h = d.getUTCHours(), m = d.getUTCMinutes();
if ((h >= first && h < last) || (h === last && m === 0)) return t - KST;
t += step;
}
return null;
}
function two(n) { return (n < 10 ? "0" : "") + n; }
function left(ms) {
const s = Math.max(0, Math.ceil(ms / 1000));
const h = Math.floor(s / 3600), m = Math.floor((s % 3600) / 60), sec = s % 60;
if (h) return h + "시간 " + two(m) + "분 " + two(sec) + "초";
if (m) return m + "분 " + two(sec) + "초";
return sec + "초";
}
let due = Date.parse(cfg.next_at);
function tick() {
const t = now();
if (t >= due) {
if (t - due < 60000) { label.hidden = true; box.textContent = "자동 업데이트 중"; return; }
due = nextSlot(t);
if (due == null) { span.hidden = true; return; }
}
label.hidden = false;
box.textContent = left(due - t);
}
tick();
setInterval(tick, 1000);
}
// ════════════════════════════════════════════════════
+6 -3
View File
@@ -20,7 +20,7 @@ sys.path.insert(0, ROOT)
OUT_DIR = os.path.join(ROOT, "tests", "js", ".out")
from app.modules.performance.ad_spend import build_ad_dashboard # noqa: E402
from app.modules.performance.dashboard import build_dashboard, build_settings # noqa: E402
from app.modules.performance.dashboard import amount_text, build_dashboard, build_settings # noqa: E402
BASE_STUB = ("{% block head_extra %}{% endblock %}<body><main class='erp-page'>{% block content %}{% endblock %}</main>"
"{% block scripts %}{% endblock %}</body>")
@@ -80,9 +80,12 @@ def env() -> jinja2.Environment:
def main() -> None:
os.makedirs(OUT_DIR, exist_ok=True)
e = env()
base = {"user": {"email": "me@test.local"}, "is_admin": True, "nav_items": [], "page_title": "실적", "page_subtitle": ""}
base = {"user": {"email": "me@test.local"}, "is_admin": True, "nav_items": [], "page_title": "실적", "page_subtitle": "",
"unit": "won", "unit_label": "원", "amt": lambda v: amount_text(v)}
ctx = build_dashboard(FakeStore(), kind="week", anchor=date(2026, 10, 7), today=date(2026, 10, 7))
html = e.get_template("performance/index.html").render(**base, active_tab="dashboard", metric="gross", **ctx)
# 다음 자동 업데이트(router._auto_sync_ctx 와 같은 모양) — 화면이 초 단위로 센다
ctx["auto_sync"] = {"next_at": "2026-10-07T10:30:00+09:00", "now": "2026-10-07T10:17:25.000+09:00", "hours": [9, 19], "slot": 30}
html = e.get_template("performance/index.html").render(**base, active_tab="dashboard", metric="net", **ctx)
with open(os.path.join(OUT_DIR, "perf_dash.html"), "w", encoding="utf-8") as f:
f.write(html)
actx = build_ad_dashboard(FakeStore(), kind="month", anchor=date(2026, 10, 7), today=date(2026, 10, 7),