feat(performance): 자동 업데이트가 끝나면 매출 실적·광고비 화면 새로 고침

- 화면이 20초마다 GET /api/update-status?kind=sales|ads 로 마지막으로 끝난 업데이트를 보고,
  그린 때(update_watch.seen)와 다르고 도는 중이 아니면 reload (jobs.last_finished — 메모리만, DB 안 읽음)
- 보는 사람이 직접 누른 업데이트는 제외(진행 창이 새로 그림), 매출·광고비 따로
- 칸 입력·창·메뉴·확인 창이 열려 있으면 닫힐 때까지 기다리고 "새 데이터 있음" 안내, 탭이 안 보이면 안 물음
- 테스트: last_finished·update-status API, 브라우저(새로 고침·기다림·종류별)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-26 18:37:39 +09:00
parent fba27772a4
commit 18d2835304
12 changed files with 272 additions and 8 deletions
+4
View File
@@ -74,6 +74,10 @@
- KPI 는 **수수료 차감 매출 하나만** 화면 왼쪽 한 줄(`.perf-kpi-line` — 금액 + 비교 기간 대비 %, 모든 기간 공통). 총매출·수수료·월/연 누적 카드는 뺐다.
- 일자별 표 기본 보기 = **수수료 차감 매출**(라우터 기본 `metric=net`, 예전에 고른 보기 localStorage 는 안 씀).
- 마지막 업데이트 옆 **다음 업데이트까지 남은 시간** 초 단위 실시간(`router._auto_sync_ctx(store, kind)` — 매출 탭 = 매출 일정, 광고비 탭 = 광고비 일정 → `performance.js initNextUpdate`·`nextScheduleSlot`, `auto_sync.next_slot` 과 같은 규칙으로 화면이 다음 회차 계산, 서버 시각으로 PC 시계 보정, 자동 업데이트(env·그 종류 일정) 꺼지면 숨김).
- **화면 자동 새로 고침**(2026-10-26) — 자동 업데이트(다른 사람이 누른 업데이트 포함)가 끝나면 매출 실적·광고비 화면이 20초 안에 reload.
화면 데이터 `update_watch`(`router._update_watch` = 그린 때 마지막으로 끝난 작업 id, 보는 사람 것 제외) ↔ `GET /api/update-status?kind=sales|ads`
(`jobs.last_finished` — 메모리 작업만, DB 안 읽음). 도는 중이면 끝날 때까지, 칸 입력·창(`.perf-modal`)·메뉴·확인 창이 열려 있으면 닫힐 때까지 기다림
(마지막 업데이트 옆 안내), 탭이 안 보이면 안 묻고 다시 보이면 바로. 보는 사람이 직접 누른 업데이트는 진행 창이 새로 그린다. `performance.js initUpdateWatch`.
- 일자별 표 매출 칸 아래 **광고비(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`). 광고비 탭은 원 그대로.
+8
View File
@@ -238,6 +238,14 @@ def get_job(job_id: str) -> SyncJob | None:
return _JOBS.get(job_id)
def last_finished(kind: str = "sales", *, exclude_user: str = "") -> SyncJob | None:
"""가장 최근에 끝난 그 종류의 작업(exclude_user 가 시작한 것은 뺌). 화면이 자동 업데이트(다른 사람 업데이트 포함)가 끝난 것을
알아채 새로 그리려고(2026-10-26) — 보는 사람이 직접 누른 업데이트는 진행 창이 알아서 새로 그린다."""
with _LOCK:
done = [j for j in _JOBS.values() if j.finished and j.kind == kind and not (exclude_user and j.user == exclude_user)]
return max(done, key=lambda j: j.finished_at) if done else None
def running_job(kind: str = "sales") -> SyncJob | None:
"""지금 돌고 있는 그 종류의 작업(가장 최근). 없으면 None — 다른 사람이 누른 업데이트도 같이 보여 주려고."""
with _LOCK:
+25
View File
@@ -146,6 +146,7 @@ def dashboard_page(
)
ctx["metric"] = metric if metric in ("gross", "commission", "net") else "net"
ctx["auto_sync"] = _auto_sync_ctx(store, "sales")
ctx["update_watch"] = _update_watch("sales", user)
_unit_ctx(request, ctx)
return render_template(request, "performance/index.html", {**common.base_ctx(user, active_tab="dashboard"), **ctx})
@@ -173,6 +174,29 @@ def _auto_sync_ctx(store: Any, kind: str) -> dict[str, Any] | None:
"label": auto_sync.describe(sched)}
def _update_watch(kind: str, user: dict[str, Any]) -> dict[str, str]:
"""화면 자동 새로 그리기(2026-10-26) — 그린 시점에 마지막으로 끝난 업데이트(보는 사람 것 제외). 화면이
GET /api/update-status 로 이 값이 바뀌면(자동 업데이트 등이 끝나면) 새로 고친다."""
from . import jobs # noqa: WPS433
job = jobs.last_finished(kind, exclude_user=user.get("email", ""))
return {"kind": kind, "seen": job.id if job else ""}
@router.get("/api/update-status")
def api_update_status(request: Request, kind: str = "sales") -> JSONResponse:
"""지금 그 종류 업데이트가 도는지 · 마지막으로 끝난 업데이트(보는 사람이 시작한 것 제외) — 화면이 20초마다 본다.
메모리의 진행 작업만 보고 DB 는 안 읽는다."""
from . import jobs # noqa: WPS433
_, user = common.require_store(request)
if kind not in jobs.KINDS:
raise HTTPException(status_code=404, detail="알 수 없는 업데이트 종류입니다.")
job = jobs.last_finished(kind, exclude_user=user.get("email", ""))
return JSONResponse({"kind": kind, "running": jobs.running_job(kind) is not None, "done": job.id if job else "",
"user": job.user if job else ""})
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
@@ -221,6 +245,7 @@ def ads_page(
ctx["ad_last_update_at"] = last_ad_update_at(store)
ctx["ad_running"] = jobs.running_job("ads") is not None
ctx["auto_sync"] = _auto_sync_ctx(store, "ads")
ctx["update_watch"] = _update_watch("ads", user)
return render_template(request, "performance/ads.html",
{**common.base_ctx(user, active_tab="ads", page_title="광고비"), **ctx})
@@ -1,6 +1,6 @@
{% extends "erp_base.html" %}
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261027c" />{% endblock %}
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261027d" />{% endblock %}
{#- ROAS 덧붙임 — "광고비(ROAS%)". 광고비가 없으면 아무것도 안 붙는다. -#}
{%- macro roas(p) -%}{%- if p is not none -%}<span class="perf-roas">({{ "{:,}".format(p) }}%)</span>{%- endif -%}{%- endmacro -%}
@@ -237,8 +237,9 @@
"period_label": period.label,
"empty_text": "기간 내 광고비가 없습니다.",
"upload_channels": upload_channels,
"auto_sync": auto_sync
"auto_sync": auto_sync,
"update_watch": update_watch
} | tojson }}</script>
{% endblock %}
{% block scripts %}<script src="/static/performance.js?v=20261027c" defer></script>{% endblock %}
{% block scripts %}<script src="/static/performance.js?v=20261027d" defer></script>{% endblock %}
@@ -1,6 +1,6 @@
{% extends "erp_base.html" %}
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261027c" />{% endblock %}
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261027d" />{% endblock %}
{%- macro won(v) -%}
{%- if v is none -%}<span class="perf-na"></span>
@@ -288,8 +288,9 @@
"today": today,
"unit": unit,
"manual_upload_names": manual_upload_names,
"auto_sync": auto_sync
"auto_sync": auto_sync,
"update_watch": update_watch
} | tojson }}</script>
{% endblock %}
{% block scripts %}<script src="/static/performance.js?v=20261027c" defer></script>{% endblock %}
{% block scripts %}<script src="/static/performance.js?v=20261027d" defer></script>{% endblock %}
@@ -1,6 +1,6 @@
{% extends "erp_base.html" %}
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261027c" />{% endblock %}
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261027d" />{% endblock %}
{%- macro when(v) -%}{{ (v or '')[:16] | replace('T', ' ') or '—' }}{%- endmacro -%}
@@ -316,4 +316,4 @@
</section>
{% endblock %}
{% block scripts %}<script src="/static/performance.js?v=20261027c" defer></script>{% endblock %}
{% block scripts %}<script src="/static/performance.js?v=20261027d" defer></script>{% endblock %}
@@ -0,0 +1,60 @@
"""화면 자동 새로 고침(2026-10-26) — 자동 업데이트가 끝나면 매출 실적·광고비 화면이 알아채도록:
jobs.last_finished(종류별·보는 사람 것 제외) · GET /api/update-status · 화면 데이터 update_watch."""
from __future__ import annotations
import importlib
import time
import pytest
from fastapi import FastAPI
from fastapi.testclient import TestClient
from app.modules.performance import auto_sync, common, jobs
perf_router = importlib.import_module("app.modules.performance.router")
@pytest.fixture(autouse=True)
def clean_jobs(monkeypatch):
monkeypatch.setattr(jobs, "_JOBS", {})
def _job(kind="sales", user=auto_sync.AUTO_USER, finished=True, at=None):
j = jobs.create_job(user=user, start=None, end=None, kind=kind)
if finished:
j.finish()
if at is not None:
j.finished_at = at
return j
def test_last_finished_by_kind_and_excludes_viewer():
assert jobs.last_finished("sales") is None
a = _job(at=time.time() - 100)
b = _job(user="me@x", at=time.time() - 10) # 보는 사람이 누른 것 — 진행 창이 알아서 새로 그림
ad = _job(kind="ads", at=time.time())
_job(finished=False) # 도는 중인 작업은 아님
assert jobs.last_finished("sales") is b
assert jobs.last_finished("sales", exclude_user="me@x") is a
assert jobs.last_finished("ads", exclude_user="me@x") is ad
assert perf_router._update_watch("sales", {"email": "me@x"}) == {"kind": "sales", "seen": a.id}
assert perf_router._update_watch("ads", {"email": "other@x"}) == {"kind": "ads", "seen": ad.id}
def test_update_status_api(monkeypatch):
monkeypatch.setattr(common, "require_store", lambda request, admin=False: (object(), {"email": "me@x"}))
app = FastAPI()
app.include_router(perf_router.router)
c = TestClient(app)
assert c.get("/performance/api/update-status?kind=sales").json() == {"kind": "sales", "running": False, "done": "", "user": ""}
run = _job(finished=False)
r = c.get("/performance/api/update-status?kind=sales").json()
assert r["running"] and r["done"] == ""
run.finish()
r = c.get("/performance/api/update-status?kind=sales").json()
assert r == {"kind": "sales", "running": False, "done": run.id, "user": auto_sync.AUTO_USER}
_job(user="me@x") # 내 업데이트는 done 을 바꾸지 않는다
assert c.get("/performance/api/update-status?kind=sales").json()["done"] == run.id
assert c.get("/performance/api/update-status?kind=ads").json()["done"] == "" # 광고비는 따로
assert c.get("/performance/api/update-status?kind=nope").status_code == 404
+1
View File
@@ -146,6 +146,7 @@ a.perf-seg.is-active, a.perf-seg.is-active:link, a.perf-seg.is-active:visited {
.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-refresh-note { color: var(--perf-up); font-weight: 600; } /* 자동 업데이트 끝 → 새로 고침 안내 */
.perf-delta { font-weight: 600; }
.perf-delta.is-up { color: var(--perf-good); } /* is-up = 좋음(수수료는 줄어야 좋음, invert) */
.perf-delta.is-down { color: var(--perf-down); }
+43
View File
@@ -993,6 +993,49 @@
// 매출 실적 화면은 늘 수수료 차감 매출로 연다(2026-10-19) — 서버 기본 data-metric="net", 예전에 고른 보기(localStorage)는 쓰지 않음
setMetric(root.dataset.metric || "net");
initNextUpdate(data.auto_sync);
initUpdateWatch(data.update_watch);
}
// 자동 업데이트(다른 사람이 누른 업데이트 포함)가 끝나면 화면 새로 고침(2026-10-26) — 20초마다 GET /api/update-status 로
// 마지막으로 끝난 업데이트를 보고, 화면을 그린 때(update_watch.seen)와 다르고 지금 도는 업데이트가 없으면 reload.
// 칸 입력 중·창(메모·진행 창 등)·확인 창·메뉴가 열려 있으면 닫힐 때까지 기다린다. 탭이 안 보이면 묻지 않고, 다시 보이면 바로 본다.
// 보는 사람이 직접 누른 업데이트는 서버가 빼고 준다(진행 창이 알아서 새로 그림).
const WATCH_MS = 20000;
function initUpdateWatch(w) {
if (!w || !w.kind) return;
const seen = w.seen || "";
let pending = false, asking = false;
function busyUi() {
const a = document.activeElement;
if (a && a !== document.body && (/^(INPUT|TEXTAREA|SELECT)$/.test(a.tagName) || a.isContentEditable)) return true;
return !!document.querySelector(".perf-modal, .perf-ctx, .erp-dialog-backdrop");
}
function note(text) {
const lu = document.getElementById("perf-last-update");
if (!lu) return;
let n = lu.querySelector(".perf-refresh-note");
if (!n) { n = el("span", { class: "perf-refresh-note" }); lu.appendChild(n); }
n.textContent = text;
}
function reloadWhenFree() {
if (busyUi()) {
note(" · 새 데이터 있음 — 입력·창을 닫으면 새로 고칩니다");
setTimeout(reloadWhenFree, 1500);
return;
}
note(" · 새 데이터로 고치는 중…");
location.reload();
}
async function check() {
if (pending || asking || document.hidden) return;
asking = true;
try {
const st = await api("GET", "/performance/api/update-status?kind=" + encodeURIComponent(w.kind));
if (st.done && st.done !== seen && !st.running) { pending = true; reloadWhenFree(); }
} catch (_) { /* 잠깐 끊김·로그아웃 — 다음 차례에 */ } finally { asking = false; }
}
setInterval(check, WATCH_MS);
document.addEventListener("visibilitychange", function () { if (!document.hidden) check(); });
}
// 다음 자동 업데이트까지 남은 시간 — 초 단위 실시간(2026-10-19). 서버가 준 다음 회차·지금 시각(PC 시계 차이 보정)으로 세고,