diff --git a/app/modules/performance/CLAUDE.md b/app/modules/performance/CLAUDE.md index 3e37892..30cfa33 100644 --- a/app/modules/performance/CLAUDE.md +++ b/app/modules/performance/CLAUDE.md @@ -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 판매분석 대조는 원본 데이터 확인으로). diff --git a/app/modules/performance/auto_sync.py b/app/modules/performance/auto_sync.py index e43d183..e303932 100644 --- a/app/modules/performance/auto_sync.py +++ b/app/modules/performance/auto_sync.py @@ -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: diff --git a/app/modules/performance/db.py b/app/modules/performance/db.py index 12efbec..4622f4a 100644 --- a/app/modules/performance/db.py +++ b/app/modules/performance/db.py @@ -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( diff --git a/app/modules/performance/templates/performance/ads.html b/app/modules/performance/templates/performance/ads.html index 37cdb59..bb6b0c7 100644 --- a/app/modules/performance/templates/performance/ads.html +++ b/app/modules/performance/templates/performance/ads.html @@ -1,6 +1,6 @@ {% extends "erp_base.html" %} -{% block head_extra %}{% endblock %} +{% block head_extra %}{% endblock %} {#- ROAS 덧붙임 — "광고비(ROAS%)". 광고비가 없으면 아무것도 안 붙는다. -#} {%- macro roas(p) -%}{%- if p is not none -%}({{ "{:,}".format(p) }}%){%- endif -%}{%- endmacro -%} @@ -224,4 +224,4 @@ } | tojson }} {% endblock %} -{% block scripts %}{% endblock %} +{% block scripts %}{% endblock %} diff --git a/app/modules/performance/templates/performance/index.html b/app/modules/performance/templates/performance/index.html index e484d8b..02e255a 100644 --- a/app/modules/performance/templates/performance/index.html +++ b/app/modules/performance/templates/performance/index.html @@ -1,6 +1,6 @@ {% extends "erp_base.html" %} -{% block head_extra %}{% endblock %} +{% block head_extra %}{% endblock %} {%- macro won(v) -%} {%- if v is none -%} @@ -72,9 +72,10 @@
' + esc(job.error) + "
"; 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("취소됨(기존 매출 그대로) " + esc(cancelled.join(", "))); if (pending.length) parts.push('연동 준비 중: ' + esc(pending.join(", ")) + ""); if (unset.length) parts.push('인증정보 미설정: ' + esc(unset.join(", ")) + ""); - if (running) parts.unshift("업데이트가 아직 진행 중입니다 — 끝나면 다시 [매출 업데이트]를 눌러 결과를 보세요"); + if (running) parts.unshift("업데이트가 아직 진행 중입니다 — [업데이트 중 · 진행 보기]를 누르면 진행 창을 다시 볼 수 있습니다"); 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 ? "업데이트 진행 상황 보기" : "지금 보고 있는 기간의 매출을 쇼핑몰에서 다시 가져옵니다"; } });