diff --git a/CLAUDE.md b/CLAUDE.md
index 1755fd5..24a0f7c 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -38,7 +38,7 @@ Claude Code는 이 저장소에서 작업을 시작하기 전에 **반드시 아
- 카페24 상품관리 (`app/modules/cafe24/`, `cafe24_db`) — 카페24 관리자에 들어가지 않고 상품 상세페이지(description HTML) 조회·편집·즉시적용·예약적용·버전 이력. 3분할 화면(목록 | HTML 편집기 | 상품 정보 패널). 정보 패널(`routes_product_info.py`, `_side.html`)에서 상품명·판매가·공급가·소비자가, 대표이미지(`POST /admin/products/{no}/images` 에 base64 data URI + `image_upload_type=A` — NNEditor 업로드 경로를 PUT `detail_image` 에 넣는 방식은 적용 안 됨), 옵션(생성/이름·썸네일·표시방식 수정/삭제)·품목(자체코드·추가금액·진열·판매)을 수정. 카페24 OAuth/API 클라이언트는 향후 주문관리와 공유하기 위해 **공통 계층 `app/integrations/cafe24/`** 에 둔다 — 라우터에서 `httpx`/`requests` 직접 호출 금지. 토큰은 Fernet 암호화 저장(`CAFE24_TOKEN_SECRET`), 로그/화면에 토큰·시크릿 절대 미출력. 쓰기 직전 항상 카페24 현재 HTML 을 다시 읽어 `BACKUP` revision 생성(로컬 값을 현재값으로 가정 금지). **카페24 관리자 API 는 PUT 뒤 한동안 GET 에서 예전 값을 돌려준다(읽기 지연)** — 우리 캐시 문제가 아니다. 그래서 "마지막 쓰기가 권위": 상세설명은 카페24 값이 최근 revision 중 하나와 같으면 지연으로 보고 마지막 MANUAL/SCHEDULED 를 표시·지문 기준으로 쓰고(`store.resolve_description`), 스칼라(상품명·가격·이미지·진열/판매)는 PUT 응답 스냅샷(`cafe24_products.last_write_snapshot`, 마이그레이션 004)과 GET 의 `updated_date` 를 비교해 덮어씌운다(`store.overlay_recent_write`). 유예시간 `CAFE24_READ_LAG_GRACE_MIN`(기본 360분). 쓰기 후 화면은 PUT 응답으로 그리고 다시 GET 하지 않는다. 예약은 DB 저장 + 별도 worker(`app/modules/cafe24/worker.py`, compose 서비스 `dbx-cafe24-worker`)가 처리 — 웹 프로세스에서 대기하지 않는다. 권한키 `cafe24`(연결/해제는 admin 전용). 상세는 `docs/CAFE24_MODULE.md`
- 프로젝트 관리 (`app/modules/project/`, `project_db`) — 아사나식. 프로젝트/서브프로젝트(self-FK `parent_id`, CASCADE)·프로젝트 색상(32색 — 아사나 16색 + 진한 16색)·아이콘(`projects.icon`, Material Symbols 42종, 마이그레이션 011)·작업(`tasks`: 담당자·우선순위·시작/마감)·진행단계(`project_stages` 칸반, 생성시 기본 4단계 seed, 섹션 기본 담당자 `default_assignee_email` — 담당자 빈 작업을 그 섹션에 만들거나 옮기면 자동 배정, 마이그레이션 009)·멤버 배정(`project_members`)·활동이력(`project_activity`). 첫 화면(`/project/`)은 **내 작업 목록**(프로젝트 홈 카드 화면은 폐지). 프로젝트 화면은 캘린더(FullCalendar)/타임라인(vis-timeline)/보드/목록/대시보드 뷰 토글. 좌측 사이드바는 수신함·내 작업·휴지통·프로젝트 화면 공용(`templates/project/_side.html` + 프로젝트 목록 동작 `initSideTree`, 새 프로젝트/수정 모달 `_side_modals.html`) — 프로젝트 목록(순서 변경·✎·×)은 어느 화면에서나 같다. 보드는 아사나처럼 섹션이 가로로 계속 늘어나고(넘치면 가로 스크롤) 카드의 담당자·마감일을 클릭해 그 자리에서 바꾼다. 좌측 사이드바에 수신함·내 작업(접이식) 메뉴. 설명란은 주소 붙여넣기 시 자동 링크, 설명란·댓글에서 @로 멤버를 태그하면 (`task_mentions`, 마이그레이션 006) 수신함에 그 작업이 쌓인다. 진입 권한키 `project`(관리자 페이지 토글로 직원별 부여, admin 자동). 프로젝트 생성은 `project` 권한자 누구나(만든 사람이 owner), 삭제는 만든 사람만(슈퍼관리자 예외), 사용자 배정은 `is_admin` 만. 배정 멤버(또는 owner/admin)만 그 프로젝트를 조회(화면·API 모두, 비멤버 403)하고 서브프로젝트/작업/단계 CRUD — URL 의 섹션·부모 작업이 그 프로젝트 것인지 서버가 검증. 실시간 반영은 `project_live_version` 카운터(마이그레이션 007, 미적용 시 MAX 폴백). 사이드바 전체 검색(`/api/search`, 제목·설명·댓글, pg_trgm) + 프로젝트/내 작업 필터 바(찾기·상태·담당자·마감·우선순위·정렬, 클라이언트 필터). 협업자(`task_followers`, 자동 팔로우: 만든 사람·담당자·댓글·@태그) — 완료·댓글 알림은 담당자+협업자에게만. 작업 삭제는 휴지통(`project_trash`, 마이그레이션 010) — 삭제 직전 스냅샷 3개월 보관, 관리자만 보기·복구(`/project/trash`). 권한은 **지금 기준 공통 모듈 `access.py`**(목록·배지·알림·멘션·메일 수신자·삭제·댓글 수정까지 — 멤버에서 빠지면 기록이 있어도 안 보이고 알림도 없음), 소유자 변경은 관리자만, 연결(멀티호밍)된 작업은 연결된 프로젝트 멤버에게 읽기 전용(docs/PROJECT_MODULE.md 6-10). 연간 목표(마이그레이션 013, `goal_*` 테이블) — 사이드바 "목표" → 연도 펼침 → `/project/goals/{연도}` 에 매출(목표·실적·달성)·로아스 월별 숫자 + 업무 영역(상품·마케팅·컨텐츠·유통 등)별 연간·월별 글, 조회는 전원·입력은 `is_admin` 만. 6월·12월 오른쪽 상·하반기 칸(글 칸 month 13·14) + 반기 월 칸 접기 애니메이션(localStorage `pj_goal_fold`, 표는 `width:1px`+`table-layout:fixed`), 영역·줄 이름 클릭 바로 수정, 월 칸 가로 병합(`goal_cell_merges`, 반기 안에서만, Shift+클릭·우클릭) — 마이그레이션 014, 로아스는 % 표기. 모든 열 너비 끌어서 조절(localStorage `pj_goal_col_w`), 세로 스크롤 틀 고정은 머리 줄+매출·로아스 줄까지, 항목 칸 +·우클릭으로 줄 위/아래 추가·삭제. 마감 알림(`reminders.py` 데몬 스레드, 영업일 09시, D-1/당일/지연, `task_reminders` 로 중복 방지, `PROJECT_REMINDER_*` env) — 마이그레이션 008. 라우터 핸들러는 동기 DB 라 `def` 로 둔다(`async def` 금지). 말풍선은 전부 아사나식 공용 말풍선(`.pj-hovertip`) — 새 기능도 `title=`/`data-tip=` 만 달고 별도 툴팁 구현 금지. 멤버 배정 후보는 `project` 권한 보유 등록 사용자에서 자동 목록(`GET /project/api/assignable-users`). 작업 배정·완료 시 관리자에게 메일(`app/mail.py` stdlib smtplib, `SMTP_*`+`PROJECT_NOTIFY_EMAIL` env, 미설정 시 조용히 skip, `BackgroundTasks` 비동기). 작업 창은 **저장 버튼 없이 실시간 저장**(칸별 PUT, `saveField`/`saveChain`, 새 작업은 제목이 생기는 순간 생성). 댓글 답글·이모티콘 반응(마이그레이션 012 `task_comments.parent_id`·`task_comment_reactions`, 미적용 시 버튼 숨김·API 503), 완료 이력 줄은 `project_activity` completed 를 댓글 사이에 표시(댓글 수 제외), 댓글 `@아이디` 는 아이콘+이름 칩. 수신함 "확인"은 페이지 이동 없이 오른쪽 iframe 패널(`/project/p/{pid}?task=&embed=1`, `html.pj-embed`). 상단 바 화면 배율 토글(`html.pj-ui-scale` → `.erp-app` zoom .75, 2880×1620·200%용) — **팝업은 반드시 `document.body` 에 붙인다**(배율 안의 fixed 좌표는 어긋남). 상세는 `docs/PROJECT_MODULE.md`
-- 실적 (`app/modules/performance/`, `performance_db`) — 쇼핑몰 통합 매출. 네 영역 분리: ① 수집 `adapters/`(쇼핑몰 하나 = 어댑터 파일 하나 + `registry.py` 한 줄 + SQL seed 한 줄) + `sync.py`(공통 동기화, 같은 쇼핑몰 동시 실행 차단, 쇼핑몰별 실패 격리) ② 보안 `security/`(AES-256-GCM, 키 버전, 비밀값 가리기) + `credentials.py` ③ 계산 `calc.py`(주=월~일, 수수료 반올림은 `commission()` 한 곳, 요율 이력) + `db.py` ④ 화면 `dashboard.py`/`router.py`/템플릿. 쇼핑몰 API 인증정보는 `.env` 가 아니라 **설정 화면에서 입력 → 마스터 키 `APP_ENCRYPTION_KEY` 로 암호화해 DB 저장**, secret 원문은 화면으로 다시 보내지 않는다. 쇼핑몰 API 는 백엔드에서만 호출, 오류·로그·raw 는 `redact` 후 저장. 매출 기준일: 결제=결제일, 취소·반품=발생일(`sync.sales_date_for`). 금액은 원 단위 정수. 권한키 `performance`, 설정 화면·API 는 `is_admin`. 카페24 어댑터는 기존 `app/integrations/cafe24` 토큰 재사용. 1단계는 모의 데이터(`is_sample`)·구조까지, 실제 수집은 쇼핑몰별로 공식 문서 확인 후 순차 구현. 상세는 `docs/PERFORMANCE_MODULE.md`
+- 실적 (`app/modules/performance/`, `performance_db`) — 쇼핑몰 통합 매출. 네 영역 분리: ① 수집 `adapters/`(쇼핑몰 하나 = 어댑터 파일 하나 + `registry.py` 한 줄 + SQL seed 한 줄) + `sync.py`(공통 동기화, 같은 쇼핑몰 동시 실행 차단, 쇼핑몰별 실패 격리) ② 보안 `security/`(AES-256-GCM, 키 버전, 비밀값 가리기) + `credentials.py` ③ 계산 `calc.py`(주=월~일, 수수료 반올림은 `commission()` 한 곳, 요율 이력) + `db.py` ④ 화면 `dashboard.py`/`router.py`/템플릿. 쇼핑몰 API 인증정보는 `.env` 가 아니라 **설정 화면에서 입력 → 마스터 키 `APP_ENCRYPTION_KEY` 로 암호화해 DB 저장**, secret 원문은 화면으로 다시 보내지 않는다. 쇼핑몰 API 는 백엔드에서만 호출, 오류·로그·raw 는 `redact` 후 저장. 매출 기준일: 결제=결제일, 취소·반품=발생일(`sync.sales_date_for`). 금액은 원 단위 정수. 권한키 `performance`, 설정 화면은 모듈 권한자 누구나(일반 사용자는 수수료율만), 수수료 외 설정 API 는 `is_admin`. 매출 업데이트 진행 창에서 쇼핑몰별 [중지](그 쇼핑몰만 멈추고 다음 쇼핑몰로). 카페24 어댑터는 기존 `app/integrations/cafe24` 토큰 재사용. 1단계는 모의 데이터(`is_sample`)·구조까지, 실제 수집은 쇼핑몰별로 공식 문서 확인 후 순차 구현. 상세는 `docs/PERFORMANCE_MODULE.md`
상세는 `docs/PROJECT_OVERVIEW.md`.
diff --git a/app/modules/performance/jobs.py b/app/modules/performance/jobs.py
index 267055e..f359d8e 100644
--- a/app/modules/performance/jobs.py
+++ b/app/modules/performance/jobs.py
@@ -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()
diff --git a/app/modules/performance/router.py b/app/modules/performance/router.py
index f46ed9e..51a0277 100644
--- a/app/modules/performance/router.py
+++ b/app/modules/performance/router.py
@@ -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="수수료 이력을 찾지 못했습니다.")
diff --git a/app/modules/performance/sync.py b/app/modules/performance/sync.py
index 49a10a3..569d273 100644
--- a/app/modules/performance/sync.py
+++ b/app/modules/performance/sync.py
@@ -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)
diff --git a/app/modules/performance/templates/performance/_tabs.html b/app/modules/performance/templates/performance/_tabs.html
index ab73e5d..eb98526 100644
--- a/app/modules/performance/templates/performance/_tabs.html
+++ b/app/modules/performance/templates/performance/_tabs.html
@@ -1,7 +1,5 @@
-{# 실적 모듈 탭 — 설정 탭은 관리자에게만(서버도 관리자만 허용). #}
+{# 실적 모듈 탭 — 설정 탭은 모듈 권한자 모두(일반 사용자 화면은 수수료율만, 나머지는 관리자). #}
diff --git a/app/modules/performance/templates/performance/index.html b/app/modules/performance/templates/performance/index.html
index 78121b2..ca3d8a0 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 -%}
@@ -239,4 +239,4 @@
} | tojson }}
{% endblock %}
-{% block scripts %}{% endblock %}
+{% block scripts %}{% endblock %}
diff --git a/app/modules/performance/templates/performance/settings.html b/app/modules/performance/templates/performance/settings.html
index a0585bf..478844d 100644
--- a/app/modules/performance/templates/performance/settings.html
+++ b/app/modules/performance/templates/performance/settings.html
@@ -1,6 +1,6 @@
{% extends "erp_base.html" %}
-{% block head_extra %}{% endblock %}
+{% block head_extra %}{% endblock %}
{%- macro when(v) -%}{{ (v or '')[:16] | replace('T', ' ') or '—' }}{%- endmacro -%}
@@ -8,7 +8,8 @@
{% include "performance/_tabs.html" %}
- {% if not key_info.ok %}
+ {# 일반 사용자(실적 권한)는 쇼핑몰별 수수료율만 — 사용·집계 토글·API 인증정보·연결 상태·아래 카드는 관리자만(서버 API 도 관리자만) #}
+ {% if is_admin and not key_info.ok %}
암호화 마스터 키가 없습니다. {{ key_info.message }}
— 키가 없으면 API 인증정보를 저장할 수 없습니다(수수료 설정·대시보드는 사용 가능).
@@ -18,26 +19,31 @@
쇼핑몰 설정
+ {% if is_admin %}
사용 · 매출 집계 · 수수료율은 바로 저장됩니다. API 인증정보는 [설정]에서 입력합니다.
+ {% else %}
+ 쇼핑몰별 수수료율을 설정합니다. 바로 저장되며 실적 화면의 수수료·수수료 차감 매출에 반영됩니다.
+ {% endif %}
쇼핑몰
-
사용
-
매출 집계
+ {% if is_admin %}
사용
+
매출 집계
{% endif %}
수수료율
-
API 설정
-
연결 상태
+ {% if is_admin %}
API 설정
+
연결 상태
{% endif %}
마지막 동기화
-
+ {% if is_admin %}
{% endif %}
{% for r in rows %}
{{ r.name }}
+ {% if is_admin %}
+ {% endif %}
{% if r.rate %}{{ r.rate }}%{% else %}미설정{% endif %}
+ {% if is_admin %}
{% if r.shared %}공통 연동
{% elif r.configured %}설정완료
@@ -65,11 +73,14 @@
{{ r.status_label }}
{% if r.last_error and r.status not in ('ok', 'disabled') %}
{{ r.last_error }}
{% endif %}
+ {% endif %}
{{ when(r.last_success_sync_at) }}
+ {% if is_admin %}
+ {% endif %}
{% endfor %}
@@ -77,10 +88,11 @@
수수료율은 적용 시작일부터 반영되고, 그 전 실적은 예전 요율로 계산됩니다(과거 실적이 바뀌지 않음).
- 상태에 마우스를 올리면 마지막 연결 테스트 시각과 최근 오류를 볼 수 있습니다.
+ {% if is_admin %}상태에 마우스를 올리면 마지막 연결 테스트 시각과 최근 오류를 볼 수 있습니다.{% endif %}
+ {% if is_admin %}
인증정보 암호화
@@ -176,7 +188,8 @@
+ {% endif %}
{% endblock %}
-{% block scripts %}{% endblock %}
+{% block scripts %}{% endblock %}
diff --git a/app/modules/performance/tests/test_performance.py b/app/modules/performance/tests/test_performance.py
index 7801224..455f386 100644
--- a/app/modules/performance/tests/test_performance.py
+++ b/app/modules/performance/tests/test_performance.py
@@ -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
diff --git a/app/static/performance.css b/app/static/performance.css
index 2eb0fcf..eab47dd 100644
--- a/app/static/performance.css
+++ b/app/static/performance.css
@@ -262,6 +262,15 @@ td.is-link:hover { background: #eef2ff; text-decoration: underline; }
@media (max-width: 560px) { .perf-prog-row { grid-template-columns: 1fr 44px; } .perf-prog-name { grid-column: 1 / -1; } .perf-prog-text { grid-column: 1 / -1; } }
/* [업데이트 취소] — 창 아래 왼쪽, 빨간 글자. 끝나면 숨김 */
+/* 쇼핑몰별 [중지] — 이름 옆 작은 버튼(이 쇼핑몰만 멈추고 다음 쇼핑몰로) */
+.perf-prog-name { display: flex; align-items: center; gap: 6px; }
+.perf-prog-name > span { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+.perf-prog-stop {
+ flex: none; margin-left: auto; padding: 1px 8px; border: 1px solid var(--perf-line); border-radius: 999px;
+ background: #fff; color: var(--perf-down); font-size: 11.5px; font-weight: 600; line-height: 1.6; cursor: pointer;
+}
+.perf-prog-stop:hover { border-color: var(--perf-down); background: #fff5f5; }
+.perf-prog-stop:disabled { opacity: .6; cursor: default; }
.perf-prog-cancel { margin-right: auto; color: var(--perf-down); border-color: currentColor; }
.perf-prog-cancel[hidden] { display: none; }
.perf-prog-cancel:disabled { opacity: .6; cursor: default; }
diff --git a/app/static/performance.js b/app/static/performance.js
index a168fbd..a4dfce3 100644
--- a/app/static/performance.js
+++ b/app/static/performance.js
@@ -85,10 +85,10 @@
sec = Math.max(0, Math.round(sec || 0));
return Math.floor(sec / 60) + ":" + String(sec % 60).padStart(2, "0");
}
- function progressRow(name, fraction, text, cls) {
+ function progressRow(name, fraction, text, cls, action) {
const pct = Math.round((fraction || 0) * 100);
return '
' +
- '
' + esc(name) + "
" +
+ '
' + esc(name) + "" + (action || "") + "
" +
'
' +
'
' +
'
' + pct + "%
" +
@@ -101,8 +101,10 @@
if (s.state === "done") t += " · " + fmt(s.upserted) + "건 반영";
if (s.state === "error") t += " · " + (s.label ? s.label + " — " : "") + (s.message || "");
if (s.state === "skipped") t += " · " + (s.message || "");
- if (s.state === "cancelled") t += " · 저장하지 않음(기존 매출 그대로)";
+ if (s.state === "cancelled") t = (s.message === "중지됨" ? "중지됨" : t) + " · 저장하지 않음(기존 매출 그대로)";
if (s.state === "running" && s.cancel_pending) t += " · 취소하는 중…";
+ else if (s.state === "running" && s.stop_requested) t += " · 중지하는 중…";
+ if (s.state === "waiting" && s.stop_requested) t += " · 중지 — 차례가 오면 건너뜀";
let html = esc(t);
if (s.elapsed && s.state !== "waiting") html += ' (' + fmtSec(s.elapsed) + ")";
return html;
@@ -118,7 +120,12 @@
const cls = s.state === "error" ? "is-error" : s.state === "done" ? "is-done" :
(s.state === "skipped" || s.state === "cancelled") ? "is-skip" : "";
if (job.cancel_requested) s.cancel_pending = true;
- return progressRow(s.name, s.fraction, shopText(s), cls);
+ // 쇼핑몰별 [중지] — 이 쇼핑몰만 멈추고 다음 쇼핑몰로(대기·수집 중일 때만, 저장 중엔 못 멈춤)
+ const stoppable = !job.finished && !job.cancel_requested && !s.stop_requested &&
+ (s.state === "waiting" || s.state === "running");
+ const stopBtn = stoppable ? '' : "";
+ return progressRow(s.name, s.fraction, shopText(s), cls, stopBtn);
}).join("");
html += progressRow("전체", o.fraction,
esc((job.cancel_requested ? (job.finished ? "업데이트 취소됨 · " : "취소하는 중 · ") : "") +
@@ -147,6 +154,23 @@
m.foot.appendChild(cancelBtn);
m.foot.appendChild(closeBtn);
let jobId = null;
+ // 쇼핑몰별 [중지] — 진행 창은 0.8초마다 다시 그려지므로 위임으로 받는다
+ m.body.addEventListener("click", async function (e) {
+ const b = e.target.closest("[data-stop]");
+ if (!b || !jobId) return;
+ b.disabled = true;
+ b.textContent = "중지하는 중…";
+ try {
+ const r = await api("POST", "/performance/api/sync/jobs/" + encodeURIComponent(jobId) + "/shops/" +
+ encodeURIComponent(b.dataset.stop) + "/stop");
+ last = r.job;
+ renderSyncJob(m.body, r.job, false);
+ } catch (err) {
+ b.disabled = false;
+ b.textContent = "중지";
+ alertMsg("중지 실패: " + err.message);
+ }
+ });
cancelBtn.addEventListener("click", async function () {
if (!jobId) return;
if (!(await confirmMsg("매출 업데이트를 취소할까요?\n수집 중인 쇼핑몰은 저장하지 않고 멈추고, 이미 끝난 쇼핑몰 결과는 그대로 남습니다."))) return;
@@ -199,7 +223,7 @@
function jobResults(job) {
return (job && job.shops || []).map(function (s) {
return { code: s.code, name: s.name, ok: s.state === "done", skipped: s.state === "skipped",
- cancelled: s.state === "cancelled",
+ cancelled: s.state === "cancelled", stopped: s.state === "cancelled" && s.message === "중지됨",
upserted: s.upserted, status: s.status, label: s.label, message: s.message, finished: s.state !== "waiting" && s.state !== "running" && s.state !== "saving" };
});
}
@@ -263,11 +287,12 @@
const running = job && !job.finished;
// 실패(빨강)는 인증 실패·API 오류처럼 손봐야 하는 것만. 인증정보를 아직 안 넣은 쇼핑몰(미설정)과
// 수집을 아직 만들지 않은 쇼핑몰(연동 준비 중)은 회색 한 줄로 이름만.
- const ok = [], bad = [], pending = [], unset = [], busy = [], cancelled = [];
+ const ok = [], bad = [], pending = [], unset = [], busy = [], cancelled = [], stopped = [];
let changed = 0;
(res.results || []).forEach(function (r) {
const name = (data.names || {})[r.code] || r.name || r.code;
- if (r.cancelled) cancelled.push(name);
+ if (r.stopped) stopped.push(name);
+ else if (r.cancelled) cancelled.push(name);
else if (r.skipped) busy.push(name);
else if (r.ok) { ok.push(name + " " + fmt(r.upserted) + "건"); changed += r.upserted; }
else if (r.status === "not_implemented") pending.push(name);
@@ -278,6 +303,7 @@
if (ok.length) parts.push("반영 " + esc(ok.join(", ")));
if (bad.length) parts.push("실패 " + esc(bad.join(", ")));
if (busy.length) parts.push("이미 진행 중 " + esc(busy.join(", ")));
+ if (stopped.length) parts.push("중지됨(기존 매출 그대로) " + esc(stopped.join(", ")));
if (cancelled.length) parts.push("취소됨(기존 매출 그대로) " + esc(cancelled.join(", ")));
if (pending.length) parts.push('연동 준비 중: ' + esc(pending.join(", ")) + "");
if (unset.length) parts.push('인증정보 미설정: ' + esc(unset.join(", ")) + "");
@@ -1058,7 +1084,7 @@
if (job && !job.finished) rest.push("(아직 진행 중 — 창을 닫았습니다. 끝나면 대시보드에 반영됩니다)");
(res.results || []).forEach(function (r) {
const name = names[r.code] || r.name || r.code;
- if (r.cancelled) rest.push(name + "(취소됨)");
+ if (r.cancelled) rest.push(name + (r.stopped ? "(중지됨)" : "(취소됨)"));
else if (r.ok) ok.push(name + " " + fmt(r.upserted) + "건");
else if (r.skipped) rest.push(name + "(이미 진행 중)");
else if (r.status === "not_implemented" || r.status === "not_configured") rest.push(name);
diff --git a/docs/PERFORMANCE_MODULE.md b/docs/PERFORMANCE_MODULE.md
index c2deaa4..e423292 100644
--- a/docs/PERFORMANCE_MODULE.md
+++ b/docs/PERFORMANCE_MODULE.md
@@ -234,9 +234,11 @@
| 기능 | 권한 |
|---|---|
| 대시보드 · 매출 업데이트 · 금액 상세 | `performance` (admin 자동) |
-| 설정 화면 · 수수료 · 인증정보 · 연결 테스트 · 테스트 데이터 · 재암호화 | `is_admin` |
+| 설정 화면 진입 · **수수료율 조회·변경·이력 삭제**(`/api/marketplaces/{code}/rates`) | `performance` (2026-10-01부터 일반 사용자도) |
+| 사용·매출 집계 토글 · 인증정보 · 연결 테스트 · 원본 데이터 확인·대조 · 과거 매출 가져오기(92일 초과) · 테스트 데이터 · 재암호화 | `is_admin` |
-화면에서 설정 탭을 숨기는 것과 별개로 모든 설정 API 가 `common.require_store(admin=True)` 로 403 을 낸다.
+일반 사용자의 설정 화면(탭 이름 "수수료 설정")은 쇼핑몰 표에 쇼핑몰·수수료율·마지막 동기화만, 다른 칸·카드는 템플릿이 관리자에게만
+그린다. 화면과 별개로 수수료 API 를 뺀 설정 API 는 모두 `common.require_store(admin=True)` 로 403 을 낸다.
## 6. 동기화 (`sync.py`)
@@ -256,6 +258,10 @@
직전(`ctx.progress.check()` → `Cancelled`)에 멈추고 **저장하지 않는다**(저장은 수집이 끝난 뒤 한 트랜잭션이라 기존 매출 그대로),
차례가 안 온 쇼핑몰은 "취소됨"으로 건너뛴다. 이미 저장이 끝난 쇼핑몰 결과는 남고, 저장 중이던 쇼핑몰은 그 저장을 끝낸다.
취소된 실행은 `perf_sync_runs` 에 failed + "업데이트 취소", 연결 상태(`perf_connection_status`)는 바꾸지 않는다.
+- **쇼핑몰별 [중지]**(진행 창 쇼핑몰 이름 옆, 대기·수집 중일 때만, 시작한 사람·관리자,
+ `POST /api/sync/jobs/{id}/shops/{code}/stop`): 그 쇼핑몰만 위와 같은 방식으로 멈추고(저장 안 함, 기존 매출 그대로) **다음 쇼핑몰로
+ 넘어간다**. 차례가 안 온 쇼핑몰을 미리 중지하면 차례가 왔을 때 건너뛴다. `ShopProgress.stop_requested` → `cancel_requested`/`check()`,
+ 상태 "중지됨"(`stopped_only`), `perf_sync_runs` 는 failed + "쇼핑몰 중지". 저장 중·끝난 쇼핑몰은 409.
- 카페24 **환불합계 규칙(확정, 2026-09-29 실데이터)**: 카페24 "일별 매출내역" 환불합계 = 환불 목록의 (실제 환불액 + 적립금·예치금 환불)
+ 환불 목록에 없는 취소·반품(네이버페이 등, 취소일 기준). 9/26 = 178,220 + 1,080 + 네이버페이 취소 96,500 = 275,800,
9/27 = 145,000 + 네이버페이 55,800 = 200,800 으로 일치. 대조 도구에 환불합계 후보(값 입력 시 일치 줄 강조)·환불 건별·