feat(performance): 수수료 설정 일반 사용자에게 열기 · 매출 업데이트 쇼핑몰별 [중지](다음 쇼핑몰로 계속)

- 설정 화면을 실적 권한자 누구나 — 일반 사용자는 탭 "수수료 설정", 쇼핑몰 표에 쇼핑몰·수수료율·마지막 동기화만
  (사용·집계 토글·API 설정·연결 상태·아래 카드는 관리자만), 수수료율 API(조회·변경·이력 삭제)만 모듈 권한으로
- 쇼핑몰별 [중지]: POST /api/sync/jobs/{id}/shops/{code}/stop — 그 쇼핑몰만 다음 API 호출 직전에 멈추고 저장 안 함,
  업데이트는 다음 쇼핑몰로 계속. 차례 전 중지는 차례에 건너뜀, 저장 중·끝난 쇼핑몰은 409, 실행 기록 "쇼핑몰 중지"
- 진행 창 쇼핑몰 이름 옆 [중지] 버튼, 결과 요약에 "중지됨" 구분, css·js 캐시 버전 올림
- 테스트(test_sync_job_stop_shop)·문서 갱신

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-01 10:30:46 +09:00
parent ff81d80cf9
commit b6b4f8c360
11 changed files with 203 additions and 40 deletions
+31 -4
View File
@@ -9,6 +9,8 @@
- [업데이트 취소]: SyncJob.cancel() → 각 쇼핑몰이 다음 API 호출 직전(ShopProgress.check)에 Cancelled 로 멈춘다.
수집 중에 멈춘 쇼핑몰은 DB 에 아무것도 쓰지 않는다(저장은 수집이 끝난 뒤 한 트랜잭션). 저장 중이면 그 저장은 끝낸다.
아직 차례가 안 온 쇼핑몰은 "취소됨"으로 건너뛴다.
- 쇼핑몰별 [중지]: SyncJob.stop_shop(code) → 그 쇼핑몰만 같은 방식(다음 API 호출 직전, 저장 안 함)으로 멈추고 "중지됨",
업데이트는 다음 쇼핑몰로 넘어간다. 차례가 안 온 쇼핑몰을 미리 중지하면 차례가 왔을 때 건너뛴다. 저장 중이면 못 멈춘다.
"""
from __future__ import annotations
@@ -39,8 +41,17 @@ class ShopProgress(Progress):
self.unit = "단계"
self.status = self.label = self.message = ""
self.started_at = self.finished_at = 0.0
self.stop_requested = False # 쇼핑몰별 [중지] — 이 쇼핑몰만 멈추고 다음 쇼핑몰로
self._lock = threading.Lock()
def stop(self) -> bool:
"""[중지] — 대기·수집 중일 때만(저장 중·끝난 뒤엔 못 멈춤). 받아들였으면 True."""
with self._lock:
if self.state not in ("waiting", "running"):
return False
self.stop_requested = True
return True
# ── 어댑터가 부르는 쪽(Progress) ──
def plan(self, total: int, unit: str = "단계") -> None:
with self._lock:
@@ -52,11 +63,18 @@ class ShopProgress(Progress):
def check(self) -> None:
if self.cancel_requested and self.state == "running":
raise Cancelled("사용자가 업데이트를 취소했습니다.")
raise Cancelled("사용자가 이 쇼핑몰 업데이트를 중지했습니다." if self.stopped_only else
"사용자가 업데이트를 취소했습니다.")
@property
def cancel_requested(self) -> bool:
return bool(self.job is not None and self.job.cancel_requested)
"""멈춰야 하나 — 업데이트 전체 취소 또는 이 쇼핑몰만 중지."""
return self.stop_requested or bool(self.job is not None and self.job.cancel_requested)
@property
def stopped_only(self) -> bool:
"""이 쇼핑몰만 중지(전체 취소가 아님) — 업데이트는 다음 쇼핑몰로 계속된다."""
return self.stop_requested and not (self.job is not None and self.job.cancel_requested)
def step(self, n: int = 1, *, items: int = 0) -> None:
self.check()
@@ -91,7 +109,8 @@ class ShopProgress(Progress):
def cancelled(self) -> None:
with self._lock:
self.state, self.status, self.message = "cancelled", "cancelled", "취소됨"
self.state, self.status = "cancelled", "cancelled"
self.message = "중지됨" if self.stopped_only else "취소됨"
self.finished_at = time.time()
def skip(self, message: str) -> None:
@@ -118,7 +137,7 @@ class ShopProgress(Progress):
"code": self.code, "name": self.name, "active": self.active, "state": self.state,
"done": self.done, "total": self.total, "unit": self.unit, "items": self.items,
"upserted": self.upserted, "status": self.status, "label": self.label, "message": self.message,
"fraction": round(self.fraction(), 4),
"stop_requested": self.stop_requested, "fraction": round(self.fraction(), 4),
"elapsed": round((self.finished_at or time.time()) - self.started_at, 1) if self.started_at else 0,
}
@@ -148,6 +167,14 @@ class SyncJob:
if not self.finished_at and not self.cancel_requested:
self.cancel_requested, self.cancelled_by = True, user
def stop_shop(self, code: str) -> bool:
"""쇼핑몰별 [중지] — 그 쇼핑몰만 멈추고 다음 쇼핑몰로. 끝난 작업·없는 쇼핑몰·저장 중·끝난 쇼핑몰은 False."""
with self._lock:
if self.finished_at:
return False
shop = next((s for s in self.shops if s.code == code), None)
return bool(shop is not None and shop.stop())
def finish(self, *, error: str = "", last_update_at: str | None = None) -> None:
with self._lock:
self.error, self.last_update_at, self.finished_at = error, last_update_at, time.time()
+25 -5
View File
@@ -115,7 +115,8 @@ def dashboard_page(
def settings_page(request: Request):
from app.main import render_template # noqa: WPS433
g = common.guard(request, admin=True)
# 모듈 권한자 누구나 들어온다 — 일반 사용자는 수수료율만(쇼핑몰 표의 다른 칸·다른 카드는 템플릿이 관리자에게만 그린다).
g = common.guard(request)
if not isinstance(g, tuple):
return g
store, user = g
@@ -227,6 +228,25 @@ def api_sync_cancel(request: Request, job_id: str) -> JSONResponse:
return JSONResponse({"job": job.snapshot()})
@router.post("/api/sync/jobs/{job_id}/shops/{code}/stop")
def api_sync_stop_shop(request: Request, job_id: str, code: str) -> JSONResponse:
"""쇼핑몰별 [중지] — 시작한 사람 또는 관리자. 그 쇼핑몰만 다음 API 호출 직전에 멈추고(저장 안 함, 기존 매출 그대로)
업데이트는 다음 쇼핑몰로 넘어간다. 차례가 안 온 쇼핑몰은 차례가 오면 건너뛴다. 저장 중·끝난 쇼핑몰은 409."""
from app.store import is_admin # noqa: WPS433
from . import jobs # noqa: WPS433
_, user = common.require_store(request)
job = jobs.get_job(job_id)
if job is None:
raise HTTPException(status_code=404, detail="진행 상황을 찾을 수 없습니다(서버가 다시 시작됐을 수 있습니다).")
if job.user and job.user != user["email"] and not is_admin(user):
raise HTTPException(status_code=403, detail="업데이트를 시작한 사람이나 관리자만 중지할 수 있습니다.")
if not job.stop_shop(code):
raise HTTPException(status_code=409, detail="이미 끝났거나 저장 중인 쇼핑몰은 중지할 수 없습니다.")
return JSONResponse({"job": job.snapshot()})
@router.get("/api/sync/current")
def api_sync_current(request: Request) -> JSONResponse:
common.require_store(request)
@@ -251,7 +271,7 @@ def api_events(request: Request, code: str, from_: str = Query(..., alias="from"
# ════════════════════════════════════════════════════════════
# JSON API — 관리자(설정)
# JSON API — 설정(수수료율은 모듈 권한자 누구나, 나머지는 관리자)
# ════════════════════════════════════════════════════════════
@router.put("/api/marketplaces/{code}")
def api_update_marketplace(request: Request, code: str, payload: dict[str, Any] = Body(...)) -> JSONResponse:
@@ -267,7 +287,7 @@ def api_update_marketplace(request: Request, code: str, payload: dict[str, Any]
@router.post("/api/marketplaces/{code}/rates")
def api_set_rate(request: Request, code: str, payload: dict[str, Any] = Body(...)) -> JSONResponse:
store, user = common.require_store(request, admin=True)
store, user = common.require_store(request) # 수수료 설정은 모듈 권한자 누구나
_code_or_404(store, code)
raw = str(payload.get("rate_percent", "")).strip().rstrip("%").strip()
try:
@@ -288,14 +308,14 @@ def api_set_rate(request: Request, code: str, payload: dict[str, Any] = Body(...
@router.get("/api/marketplaces/{code}/rates")
def api_list_rates(request: Request, code: str) -> JSONResponse:
store, _ = common.require_store(request, admin=True)
store, _ = common.require_store(request) # 수수료 설정은 모듈 권한자 누구나
_code_or_404(store, code)
return JSONResponse({"rates": store.list_rates(code)})
@router.delete("/api/marketplaces/{code}/rates/{rate_id}")
def api_delete_rate(request: Request, code: str, rate_id: int) -> JSONResponse:
store, _ = common.require_store(request, admin=True)
store, _ = common.require_store(request) # 수수료 설정은 모듈 권한자 누구나
_code_or_404(store, code)
if not store.delete_rate(code, rate_id):
raise HTTPException(status_code=404, detail="수수료 이력을 찾지 못했습니다.")
+7 -5
View File
@@ -102,9 +102,9 @@ class SyncService:
if progress is not None:
progress.fail(status="api_error", label=STATUS_LABELS["api_error"], message="알 수 없는 쇼핑몰입니다.")
return {**result, "status": "api_error", "message": "알 수 없는 쇼핑몰입니다."}
if progress is not None and progress.cancel_requested: # [업데이트 취소] 뒤 차례가 온 쇼핑몰
if progress is not None and progress.cancel_requested: # [업데이트 취소]·쇼핑몰 [중지] 뒤 차례가 온 쇼핑몰
progress.cancelled()
return {**result, "cancelled": True, "status": "cancelled", "message": "취소됨"}
return {**result, "cancelled": True, "status": "cancelled", "message": progress.message}
run_id = self._store.start_run(code, trigger=trigger, range_from=start, range_to=end, user=user)
if run_id is None:
if progress is not None:
@@ -140,11 +140,13 @@ class SyncService:
return {**result, "ok": True, "status": "ok", "fetched": fetched, "upserted": upserted,
"message": f"{upserted}건 반영"}
except Cancelled:
# 수집 중 취소 — 아직 아무것도 저장하지 않았다. 연결 상태(오류 표시)는 바꾸지 않는다.
self._store.finish_run(run_id, ok=False, error="업데이트 취소")
# 수집 중 취소·중지 — 아직 아무것도 저장하지 않았다. 연결 상태(오류 표시)는 바꾸지 않는다.
# 쇼핑몰 [중지]면 이 쇼핑몰만 멈추고 sync_all 이 다음 쇼핑몰로 넘어간다.
stopped = progress is not None and progress.stopped_only
self._store.finish_run(run_id, ok=False, error="쇼핑몰 중지" if stopped else "업데이트 취소")
if progress is not None:
progress.cancelled()
return {**result, "cancelled": True, "status": "cancelled", "message": "취소됨"}
return {**result, "cancelled": True, "status": "cancelled", "message": "중지됨" if stopped else "취소됨"}
except Exception as exc: # noqa: BLE001 — 한 쇼핑몰 실패가 전체를 멈추지 않게
status, message = self._failure(exc, ctx)
logger.warning("performance sync %s failed: %s %s", code, status, message)
@@ -1,7 +1,5 @@
{# 실적 모듈 탭 — 설정 탭은 관리자에게만(서버도 관리자만 허용). #}
{# 실적 모듈 탭 — 설정 탭은 모듈 권한자 모두(일반 사용자 화면은 수수료율만, 나머지는 관리자). #}
<nav class="perf-tabs" aria-label="실적 메뉴">
<a class="perf-tab{% if active_tab == 'dashboard' %} is-active{% endif %}" href="/performance/">실적</a>
{% if is_admin %}
<a class="perf-tab{% if active_tab == 'settings' %} is-active{% endif %}" href="/performance/settings">설정</a>
{% endif %}
<a class="perf-tab{% if active_tab == 'settings' %} is-active{% endif %}" href="/performance/settings">{{ '설정' if is_admin else '수수료 설정' }}</a>
</nav>
@@ -1,6 +1,6 @@
{% extends "erp_base.html" %}
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20260930g" />{% endblock %}
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261001a" />{% endblock %}
{%- macro won(v) -%}
{%- if v is none -%}<span class="perf-na"></span>
@@ -239,4 +239,4 @@
} | tojson }}</script>
{% endblock %}
{% block scripts %}<script src="/static/performance.js?v=20261001d" defer></script>{% endblock %}
{% block scripts %}<script src="/static/performance.js?v=20261001e" defer></script>{% endblock %}
@@ -1,6 +1,6 @@
{% extends "erp_base.html" %}
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20260930g" />{% endblock %}
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261001a" />{% endblock %}
{%- macro when(v) -%}{{ (v or '')[:16] | replace('T', ' ') or '—' }}{%- endmacro -%}
@@ -8,7 +8,8 @@
<section class="perf perf-settings" id="perf-settings">
{% include "performance/_tabs.html" %}
{% if not key_info.ok %}
{# 일반 사용자(실적 권한)는 쇼핑몰별 수수료율만 — 사용·집계 토글·API 인증정보·연결 상태·아래 카드는 관리자만(서버 API 도 관리자만) #}
{% if is_admin and not key_info.ok %}
<div class="perf-notice is-warn">
<b>암호화 마스터 키가 없습니다.</b> {{ key_info.message }}
— 키가 없으면 API 인증정보를 저장할 수 없습니다(수수료 설정·대시보드는 사용 가능).
@@ -18,26 +19,31 @@
<div class="erp-card perf-card">
<div class="perf-card-head">
<h2 class="perf-h">쇼핑몰 설정</h2>
{% if is_admin %}
<span class="perf-muted">사용 · 매출 집계 · 수수료율은 바로 저장됩니다. API 인증정보는 [설정]에서 입력합니다.</span>
{% else %}
<span class="perf-muted">쇼핑몰별 수수료율을 설정합니다. 바로 저장되며 실적 화면의 수수료·수수료 차감 매출에 반영됩니다.</span>
{% endif %}
</div>
<div class="erp-table-wrap">
<table class="perf-table perf-set-table">
<thead>
<tr>
<th class="perf-th-label">쇼핑몰</th>
<th>사용</th>
<th>매출 집계</th>
{% if is_admin %}<th>사용</th>
<th>매출 집계</th>{% endif %}
<th>수수료율</th>
<th>API 설정</th>
<th>연결 상태</th>
{% if is_admin %}<th>API 설정</th>
<th>연결 상태</th>{% endif %}
<th>마지막 동기화</th>
<th></th>
{% if is_admin %}<th></th>{% endif %}
</tr>
</thead>
<tbody>
{% for r in rows %}
<tr data-code="{{ r.code }}" data-name="{{ r.name }}">
<th class="perf-td-label" scope="row">{{ r.name }}</th>
{% if is_admin %}
<td class="perf-center">
<label class="perf-switch" title="사용 여부">
<input type="checkbox" data-field="enabled"{% if r.enabled %} checked{% endif %} /><span></span>
@@ -48,11 +54,13 @@
<input type="checkbox" data-field="include_in_sales"{% if r.include_in_sales %} checked{% endif %} /><span></span>
</label>
</td>
{% endif %}
<td class="perf-rate-cell">
<span class="perf-rate">{% if r.rate %}{{ r.rate }}%{% else %}<span class="perf-muted">미설정</span>{% endif %}</span>
<button type="button" class="erp-btn erp-btn-ghost erp-btn-sm" data-act="rate"
data-has-history="{{ 1 if r.rate_history else 0 }}">변경{% if r.rate_history > 1 %} · 이력 {{ r.rate_history }}{% endif %}</button>
</td>
{% if is_admin %}
<td>
{% if r.shared %}<span class="perf-pill">공통 연동</span>
{% elif r.configured %}<span class="perf-pill is-ok">설정완료</span>
@@ -65,11 +73,14 @@
<i></i>{{ r.status_label }}</span>
{% if r.last_error and r.status not in ('ok', 'disabled') %}<div class="perf-err">{{ r.last_error }}</div>{% endif %}
</td>
{% endif %}
<td class="perf-muted perf-nowrap" title="마지막 시도: {{ when(r.last_sync_at) }}">{{ when(r.last_success_sync_at) }}</td>
{% if is_admin %}
<td class="perf-nowrap">
<button type="button" class="erp-btn erp-btn-outline erp-btn-sm" data-act="creds">설정</button>
<button type="button" class="erp-btn erp-btn-outline erp-btn-sm" data-act="test">연결 테스트</button>
</td>
{% endif %}
</tr>
{% endfor %}
</tbody>
@@ -77,10 +88,11 @@
</div>
<p class="perf-foot perf-muted">
수수료율은 <b>적용 시작일</b>부터 반영되고, 그 전 실적은 예전 요율로 계산됩니다(과거 실적이 바뀌지 않음).
상태에 마우스를 올리면 마지막 연결 테스트 시각과 최근 오류를 볼 수 있습니다.
{% if is_admin %}상태에 마우스를 올리면 마지막 연결 테스트 시각과 최근 오류를 볼 수 있습니다.{% endif %}
</p>
</div>
{% if is_admin %}
<div class="perf-grid2">
<div class="erp-card perf-card">
<div class="perf-card-head"><h2 class="perf-h">인증정보 암호화</h2></div>
@@ -176,7 +188,8 @@
</div>
</div>
</div>
{% endif %}
</section>
{% endblock %}
{% block scripts %}<script src="/static/performance.js?v=20261001d" defer></script>{% endblock %}
{% block scripts %}<script src="/static/performance.js?v=20261001e" defer></script>{% endblock %}
@@ -1653,6 +1653,68 @@ def test_sync_job_cancel():
assert snapshot["cancel_requested"] and snapshot["overall"]["finished"] == 2 and snapshot["overall"]["fraction"] == 1.0
def test_sync_job_stop_shop():
"""쇼핑몰별 [중지]: 그 쇼핑몰만 다음 API 호출 직전에 멈추고(저장 안 함, "중지됨") 다음 쇼핑몰로 넘어간다.
차례가 안 온 쇼핑몰을 미리 중지하면 차례가 왔을 때 건너뛴다. 끝난 쇼핑몰·없는 쇼핑몰은 중지 못 함."""
import bcrypt
import httpx
from app.modules.performance import jobs
from app.modules.performance.adapters import naver as nv
from app.modules.performance.adapters import toss as ts
job = jobs.create_job(user="king@x", start=None, end=None)
naver_days = []
def get(url, params=None, headers=None, timeout=None):
if "commerce.naver.com" in url:
naver_days.append(params["from"][:10])
if len(naver_days) == 1:
assert job.stop_shop("gsshop") # 차례가 안 온 GS샵을 미리 중지
if len(naver_days) == 2:
assert job.stop_shop("naver") # 둘째 날을 받는 도중 네이버 중지
rows = [_naver_item("A" + naver_days[-1], "P" + naver_days[-1], naver_days[-1], 10000)]
return httpx.Response(200, json={"data": {"contents": rows, "pagination": {"hasNext": False}}})
if url.endswith("/claims"):
return httpx.Response(200, json={"resultType": "SUCCESS", "success": {"items": [], "nextToken": None}})
found = [_toss_item(1, 11, "2026-09-09T10:00:00", 12000)] if params["startDate"] == "2026-09-09" else []
return httpx.Response(200, json={"resultType": "SUCCESS", "success": {"results": found, "nextCursor": None}})
def post(url, data=None, timeout=None, headers=None):
return httpx.Response(200, json={"access_token": "T", "expires_in": 10799})
st = FakeStore()
st.markets = [m for m in st.markets if m["code"] in ("naver", "gsshop", "toss")]
creds = CredentialService(st, lambda: ring())
creds.save(next(a for a in all_adapters() if a.code == "naver"),
{"client_id": "app-id", "client_secret": bcrypt.gensalt(rounds=4).decode()})
creds.save(next(a for a in all_adapters() if a.code == "gsshop"),
{"vendor_code": "1047142", "api_key": "0123456789abcdef0123456789ABCDEF"})
creds.save(next(a for a in all_adapters() if a.code == "toss"), {"api_key": "ak", "api_secret": "sk"})
st.events[("naver", "SALE", "naver:OLD")] = {"amount": 5000, "is_sample": False, "sales_date": date(2026, 9, 10)}
orig = (httpx.post, httpx.get, nv.CALL_INTERVAL_SEC, ts.CALL_INTERVAL_SEC)
httpx.post, httpx.get, nv.CALL_INTERVAL_SEC, ts.CALL_INTERVAL_SEC = post, get, 0, 0
try:
res = SyncService(st, creds).sync_all(start=date(2026, 9, 9), end=date(2026, 9, 12), user="king@x", job=job)
finally:
httpx.post, httpx.get, nv.CALL_INTERVAL_SEC, ts.CALL_INTERVAL_SEC = orig
job.finish()
by = {r["code"]: r for r in res}
assert naver_days == ["2026-09-09", "2026-09-10"] # 중지 뒤 네이버는 더 부르지 않음
assert by["naver"]["cancelled"] and by["naver"]["message"] == "중지됨"
assert by["gsshop"]["cancelled"] and by["gsshop"]["message"] == "중지됨" # 미리 중지 → 차례에 건너뜀
assert by["toss"]["ok"] and by["toss"]["upserted"] == 1 # 다음 쇼핑몰은 계속
assert ("naver", "SALE", "naver:OLD") in st.events and not any(k[0] == "naver" and k[2] != "naver:OLD" for k in st.events)
assert ("toss", "SALE", "toss:1") in st.events
snap = job.snapshot()
shops = {s["code"]: s for s in snap["shops"]}
assert shops["naver"]["state"] == "cancelled" and shops["naver"]["message"] == "중지됨" and shops["naver"]["stop_requested"]
assert shops["toss"]["state"] == "done" and not snap["cancel_requested"]
assert "naver" not in st.status # 연결 상태 안 바뀜
assert not job.stop_shop("toss") and not job.stop_shop("nope") # 끝난 작업·없는 쇼핑몰
if __name__ == "__main__":
os.environ.pop("APP_ENCRYPTION_KEY", None)
n = 0