feat(performance): 매출 업데이트 진행 창 — 쇼핑몰별·전체 진행 막대

- POST /api/sync background=true 로 수집을 백그라운드 스레드에서 돌리고 작업 번호를 바로 돌려줌,
  GET /api/sync/jobs/{id}·/api/sync/current 로 진행 상황 조회(jobs.py, 메모리 보관)
- 어댑터 진행 알림(ctx.progress plan/step/add): 네이버 = 일, 11번가·카페24 = 조회 구간, 받은 자료 건수
- 창: 쇼핑몰마다 막대(대기·수집 중 n/전체·저장 중·완료 n건·실패·건너뜀·경과), 전체 막대(평균),
  수집 없는/인증정보 없는 쇼핑몰은 건너뜀 한 줄, 창을 닫아도 서버에서 계속
- [매출 업데이트]·[과거 매출 가져오기] 모두 진행 창 사용, 이미 진행 중이면 그 진행 상황을 보여 줌
- 테스트 1개 추가(27개 통과), performance.js/css 캐시 버전, 문서 갱신

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-09-30 13:56:57 +09:00
parent 077c92fa32
commit 3203ff87a4
13 changed files with 519 additions and 22 deletions
+58
View File
@@ -5,6 +5,9 @@
GET /performance/settings 실적 설정(관리자)
JSON API — 모듈 권한
POST /performance/api/sync 매출 업데이트(사용 중인 쇼핑몰 전부, 쇼핑몰별 실패 격리)
background=true 면 백그라운드로 돌리고 작업 번호를 바로 돌려줌
GET /performance/api/sync/jobs/{id} 매출 업데이트 진행 상황(쇼핑몰별·전체 진행 막대)
GET /performance/api/sync/current 지금 돌고 있는 업데이트(없으면 null)
GET /performance/api/events 금액 클릭 상세(쇼핑몰+기간)
JSON API — 관리자
PUT /performance/api/marketplaces/{code} 사용/매출 집계 여부
@@ -155,10 +158,65 @@ def api_sync(request: Request, payload: dict[str, Any] = Body(default={})) -> JS
if days > MAX_USER_SYNC_DAYS and not is_admin(user):
raise HTTPException(status_code=403,
detail=f"{MAX_USER_SYNC_DAYS}일보다 긴 기간은 관리자만 가져올 수 있습니다.")
if payload.get("background"):
return JSONResponse(_start_background_sync(store, sync, start=start, end=end, codes=codes or None,
user=user["email"]))
results = sync.sync_all(start=start, end=end, codes=codes or None, user=user["email"])
return JSONResponse({"results": results, "last_update_at": store.last_update_at()})
def _start_background_sync(store: Any, sync: Any, *, start: date | None, end: date | None,
codes: list[str] | None, user: str) -> dict[str, Any]:
"""수집을 스레드로 돌리고 작업 번호를 바로 돌려준다. 이미 돌고 있는 업데이트가 있으면 새로 시작하지 않고
그 작업을 보여 준다(같은 쇼핑몰 동시 실행은 어차피 막혀 있다)."""
import logging # noqa: WPS433
import threading # noqa: WPS433
from . import jobs # noqa: WPS433
live = jobs.running_job()
if live is not None:
return {"job": live.snapshot(), "joined": True}
job = jobs.create_job(user=user, start=start, end=end)
def run() -> None:
error = ""
try:
sync.sync_all(start=start, end=end, codes=codes, user=user, job=job)
except Exception as exc: # noqa: BLE001 — 스레드 밖으로 새지 않게, 화면에는 "오류"로
logging.getLogger("performance.sync").exception("background sync failed")
error = f"업데이트 중 오류: {type(exc).__name__}"
last = None
try:
last = store.last_update_at()
except Exception: # noqa: BLE001
pass
job.finish(error=error, last_update_at=last)
threading.Thread(target=run, name=f"perf-sync-{job.id}", daemon=True).start()
return {"job": job.snapshot(), "joined": False}
@router.get("/api/sync/jobs/{job_id}")
def api_sync_job(request: Request, job_id: str) -> JSONResponse:
common.require_store(request)
from . import jobs # noqa: WPS433
job = jobs.get_job(job_id)
if job is None:
raise HTTPException(status_code=404, detail="진행 상황을 찾을 수 없습니다(서버가 다시 시작됐을 수 있습니다).")
return JSONResponse({"job": job.snapshot()})
@router.get("/api/sync/current")
def api_sync_current(request: Request) -> JSONResponse:
common.require_store(request)
from . import jobs # noqa: WPS433
job = jobs.running_job()
return JSONResponse({"job": job.snapshot() if job else None})
@router.get("/api/events")
def api_events(request: Request, code: str, from_: str = Query(..., alias="from"), to: str | None = None) -> JSONResponse:
store, _ = common.require_store(request)