feat(performance): 업데이트 중에도 [매출 업데이트]로 진행 창 다시 보기 · 서버 재시작으로 남은 진행 기록 정리

- 버튼은 업데이트 중 '업데이트 중 · 진행 보기', 누르면 진행 중 작업(수동·자동)을 새로 시작하지 않고 진행 창으로
- 서버 시작 때 perf_sync_runs running 행을 '중단됨(서버 재시작)'으로 정리 — 30분 막힘 방지

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-19 16:50:16 +09:00
parent 50d66c00a6
commit c710e184e7
9 changed files with 85 additions and 22 deletions
+2
View File
@@ -29,6 +29,8 @@
## 매출 업데이트
- 진행 창에서 쇼핑몰별 [중지](그 쇼핑몰만 멈추고 다음 쇼핑몰로).
- **업데이트 중에도 [매출 업데이트] 누르기 가능**(2026-10-19) — 버튼이 "업데이트 중 · 진행 보기"로 바뀌고, 누르면 `GET /api/sync/current` 의 진행 중 작업(수동·자동)을 새로 시작하지 않고 진행 창으로 다시 연다.
- 서버 시작 때 남은 `perf_sync_runs` running 행은 `abandon_running_runs` 로 "중단됨(서버 재시작)" 정리(앱은 프로세스 하나 — 진행 작업은 메모리에만). 예전엔 30분(`STALE_RUN_AFTER`) 동안 버튼이 '업데이트 중'으로 막히고 그 쇼핑몰이 '이미 진행 중'으로 건너뛰어졌다.
- **자동 업데이트**(`auto_sync.py`, 웹 프로세스 데몬 스레드) — 매일 09~19시 정각·30분마다 오늘 포함 최근 10일, 진행 창 작업으로 돌고 다른 업데이트 중이면 그 회차 건너뜀. env `PERFORMANCE_AUTO_SYNC`·`_DAYS`·`_HOURS`.
- 쿠팡은 판매자배송 발주서 + 로켓그로스 주문을 결제일로 합산(WING 판매분석 대조는 원본 데이터 확인으로).
+7
View File
@@ -122,6 +122,13 @@ def start_auto_sync_thread(app_state: Any) -> bool:
"""웹 프로세스 시작 시 1번. 저장소가 없거나 꺼져 있거나 이미 돌고 있으면 False."""
global _started # noqa: PLW0603
store = getattr(app_state, "performance_store", None)
if store is not None and not _started:
try: # 지난 프로세스가 업데이트 도중 끝나 남은 '진행 중' 기록 정리(자동 업데이트를 꺼 둬도)
n = store.abandon_running_runs()
if n:
logger.warning("매출 업데이트 '진행 중' 기록 %d건 정리(서버 재시작으로 중단)", n)
except Exception: # noqa: BLE001 — DB 가 아직 안 붙었어도 앱은 뜬다
logger.exception("매출 업데이트 진행 기록 정리 실패")
if store is None or not enabled():
return False
with _start_lock:
+9
View File
@@ -563,6 +563,15 @@ class PerformanceDBStore:
).fetchone()
return _iso(row["t"]) if row and row["t"] else None
def abandon_running_runs(self) -> int:
"""서버 시작 때 1번(2026-10-19) — 남아 있는 running 행은 지난 프로세스가 업데이트 도중 끝난 것(앱은 프로세스 하나,
진행 작업은 메모리에만)이라 '중단됨'으로 정리한다. 안 하면 30분(STALE_RUN_AFTER) 동안 [매출 업데이트]가 '업데이트 중'으로
보이고 그 쇼핑몰 업데이트가 '이미 진행 중'으로 건너뛰어진다. 정리한 행 수."""
with self._pool.connection() as conn:
cur = conn.execute("UPDATE perf_sync_runs SET status = 'failed', finished_at = now(), "
"error = '중단됨(서버 재시작)' WHERE status = 'running'")
return cur.rowcount
def running_codes(self) -> list[str]:
with self._pool.connection() as conn:
rows = conn.execute(
@@ -1,6 +1,6 @@
{% extends "erp_base.html" %}
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261019d" />{% endblock %}
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261019e" />{% 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=20261019b" defer></script>{% endblock %}
{% block scripts %}<script src="/static/performance.js?v=20261019c" defer></script>{% endblock %}
@@ -1,6 +1,6 @@
{% extends "erp_base.html" %}
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261019d" />{% endblock %}
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261019e" />{% endblock %}
{%- macro won(v) -%}
{%- if v is none -%}<span class="perf-na"></span>
@@ -72,9 +72,10 @@
<div class="perf-update">
<span class="perf-muted" id="perf-last-update">마지막 업데이트
<b>{{ (last_update_at or '')[:16] | replace('T', ' ') or '—' }}</b></span>
<button type="button" class="erp-btn erp-btn-primary" id="perf-sync-btn"{% if running %} disabled{% endif %}
title="지금 보고 있는 기간({{ period.label }}, 오늘까지)의 매출을 쇼핑몰에서 다시 가져옵니다">
{% if running %}업데이트 중…{% else %}매출 업데이트{% 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 %}">
{% if running %}업데이트 중 · 진행 보기{% else %}매출 업데이트{% endif %}
</button>
</div>
</div>
@@ -266,4 +267,4 @@
} | tojson }}</script>
{% endblock %}
{% block scripts %}<script src="/static/performance.js?v=20261019b" defer></script>{% endblock %}
{% block scripts %}<script src="/static/performance.js?v=20261019c" defer></script>{% endblock %}
@@ -1,6 +1,6 @@
{% extends "erp_base.html" %}
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261019d" />{% endblock %}
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261019e" />{% 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=20261019b" defer></script>{% endblock %}
{% block scripts %}<script src="/static/performance.js?v=20261019c" defer></script>{% endblock %}
@@ -67,3 +67,28 @@ def test_run_once_uses_job_and_skips_when_busy(monkeypatch):
monkeypatch.setattr(jobs, "running_job", lambda: object())
assert au.run_once(Store(), None, today=date(2026, 10, 13), days=10)["skipped"]
assert len(calls) == 1
def test_startup_clears_orphan_running_runs(monkeypatch):
"""서버 시작 때 지난 프로세스가 남긴 '진행 중' 기록을 정리(2026-10-19) — 자동 업데이트를 꺼 둬도, DB 오류여도 앱은 뜬다."""
from types import SimpleNamespace
from app.modules.performance import auto_sync as a
calls = []
class Store:
def abandon_running_runs(self):
calls.append(1)
return 2
monkeypatch.setattr(a, "_started", False)
monkeypatch.setenv("PERFORMANCE_AUTO_SYNC", "false")
assert a.start_auto_sync_thread(SimpleNamespace(performance_store=Store())) is False
assert calls == [1]
class Broken:
def abandon_running_runs(self):
raise RuntimeError("db down")
assert a.start_auto_sync_thread(SimpleNamespace(performance_store=Broken())) is False # 예외가 새지 않음
+3
View File
@@ -371,3 +371,6 @@ td.is-link:hover { background: #eef2ff; text-decoration: underline; }
.perf-ev-xsub { font-size: 11px; font-weight: 500; color: var(--color-midtone-gray, #777); }
.perf-ev-table tfoot .perf-ev-x, .perf-ev-table tfoot .perf-ev-x b { color: #fff; } /* 검은 합계 줄 — 흰 글자 */
.perf-ev-table tfoot .perf-ev-xsub { color: #c9c9c9; }
/* [매출 업데이트] — 업데이트 중이면 "업데이트 중 · 진행 보기"(눌러서 진행 창 다시 열기), 살짝 깜박임 */
#perf-sync-btn.is-running { animation: perf-sync-pulse 1.6s ease-in-out infinite; }
@keyframes perf-sync-pulse { 0%, 100% { opacity: 1; } 50% { opacity: .72; } }
+29 -13
View File
@@ -148,7 +148,8 @@
if (job.error) html += '<p class="perf-notice is-warn">' + esc(job.error) + "</p>";
box.innerHTML = html;
}
function runSyncWithProgress(payload, title) {
// existing = 이미 돌고 있는 작업(GET /api/sync/current) — 주면 새로 시작하지 않고 그 진행 창만 다시 연다(2026-10-19)
function runSyncWithProgress(payload, title, existing) {
return new Promise(function (resolve, reject) {
let timer = null, closed = false, last = null;
const m = openModal(title || "매출 업데이트", { narrow: true, onClose: function () { closed = true; clearTimeout(timer); if (last) resolve(last); } });
@@ -194,7 +195,8 @@
alertMsg("취소 실패: " + err.message);
}
});
api("POST", "/performance/api/sync", Object.assign({ background: true }, payload)).then(function (res) {
(existing ? Promise.resolve({ job: existing, joined: true })
: api("POST", "/performance/api/sync", Object.assign({ background: true }, payload))).then(function (res) {
last = res.job;
jobId = res.job.id;
const joined = res.joined;
@@ -497,15 +499,24 @@
const syncBtn = document.getElementById("perf-sync-btn");
const resultBox = document.getElementById("perf-sync-result");
if (syncBtn) syncBtn.addEventListener("click", async function () {
syncBtn.disabled = true;
const label = syncBtn.textContent;
syncBtn.textContent = "업데이트 중…";
if (syncBtn.dataset.busy === "1") return; // 같은 창을 두 번 열지 않게
syncBtn.dataset.busy = "1";
syncBtn.textContent = "업데이트 중 · 진행 보기";
syncBtn.classList.add("is-running");
try {
// 지금 보고 있는 기간(오늘까지)을 가져온다 — "이번달"이면 1일부터 오늘까지.
const from = data.period_start, to = data.period_end < data.today ? data.period_end : data.today;
if (from > data.today) throw new Error("앞으로의 기간은 가져올 수 없습니다.");
// 진행 창(쇼핑몰별·전체 막대) — 창을 닫아도 서버에서 계속된다.
const job = await runSyncWithProgress({ from: from, to: to }, "매출 업데이트 " + from + " ~ " + to);
// 이미 돌고 있는 업데이트(다른 사람·자동 업데이트 포함)가 있으면 새로 시작하지 않고 그 진행 창을 다시 연다
let cur = null;
try { cur = (await api("GET", "/performance/api/sync/current")).job; } catch (_) { cur = null; }
let job;
if (cur && !cur.finished) {
job = await runSyncWithProgress(null, "매출 업데이트 진행 상황 " + (cur.from || "") + " ~ " + (cur.to || ""), cur);
} else {
// 지금 보고 있는 기간(오늘까지)을 가져온다 — "이번달"이면 1일부터 오늘까지.
const from = data.period_start, to = data.period_end < data.today ? data.period_end : data.today;
if (from > data.today) throw new Error("앞으로의 기간은 가져올 수 없습니다.");
// 진행 창(쇼핑몰별·전체 막대) — 창을 닫아도 서버에서 계속된다.
job = await runSyncWithProgress({ from: from, to: to }, "매출 업데이트 " + from + " ~ " + to);
}
const res = { results: jobResults(job).filter(function (r) { return r.finished; }), last_update_at: job && job.last_update_at };
const running = job && !job.finished;
// 실패(빨강)는 인증 실패·API 오류처럼 손봐야 하는 것만. 인증정보를 아직 안 넣은 쇼핑몰(미설정)과
@@ -530,7 +541,7 @@
if (cancelled.length) parts.push("<b>취소됨</b>(기존 매출 그대로) " + esc(cancelled.join(", ")));
if (pending.length) parts.push('<span class="perf-muted">연동 준비 중: ' + esc(pending.join(", ")) + "</span>");
if (unset.length) parts.push('<span class="perf-muted">인증정보 미설정: ' + esc(unset.join(", ")) + "</span>");
if (running) parts.unshift("<b>업데이트가 아직 진행 중입니다</b> — 끝나면 다시 [매출 업데이트]를 눌러 결과를 보세요");
if (running) parts.unshift("<b>업데이트가 아직 진행 중입니다</b> — [업데이트 중 · 진행 보기]를 누르면 진행 창을 다시 볼 수 있습니다");
resultBox.innerHTML = parts.join(" · ") || "업데이트할 쇼핑몰이 없습니다.";
resultBox.className = "perf-notice" + (bad.length ? " is-warn" : " is-ok");
resultBox.hidden = false;
@@ -539,13 +550,18 @@
if (lu) lu.textContent = res.last_update_at.slice(0, 16).replace("T", " ");
}
if (changed > 0 && !running) setTimeout(function () { location.reload(); }, 800);
syncBtn.dataset.running = running ? "1" : ""; // 창을 닫았는데 아직 진행 중 → 버튼은 [업데이트 중 · 진행 보기]
} catch (err) {
resultBox.textContent = "업데이트 실패: " + err.message;
resultBox.className = "perf-notice is-warn";
resultBox.hidden = false;
syncBtn.dataset.running = "";
} finally {
syncBtn.disabled = false;
syncBtn.textContent = label === "업데이트 중…" ? "매출 업데이트" : label;
syncBtn.dataset.busy = "";
const still = syncBtn.dataset.running === "1";
syncBtn.textContent = still ? "업데이트 중 · 진행 보기" : "매출 업데이트";
syncBtn.classList.toggle("is-running", still);
syncBtn.title = still ? "업데이트 진행 상황 보기" : "지금 보고 있는 기간의 매출을 쇼핑몰에서 다시 가져옵니다";
}
});