da63b93302
- 진행 창 [업데이트 취소](시작한 사람·관리자) → POST /api/sync/jobs/{id}/cancel
- 어댑터가 API 호출 직전마다 ctx.progress.check() — 취소면 Cancelled 로 멈추고 저장하지 않음(기존 매출 그대로),
차례가 안 온 쇼핑몰은 취소됨으로 건너뜀, 이미 끝난 쇼핑몰 결과는 유지
- 취소 실행은 perf_sync_runs failed + 업데이트 취소, 연결 상태는 바꾸지 않음
- 테스트 1개 추가(30개 통과), performance.js/css 캐시 버전, 문서 갱신
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
412 lines
20 KiB
Python
412 lines
20 KiB
Python
"""실적 모듈 라우터 (prefix=/performance).
|
|
|
|
화면
|
|
GET /performance/ 대시보드(모듈 권한)
|
|
GET /performance/settings 실적 설정(관리자)
|
|
JSON API — 모듈 권한
|
|
POST /performance/api/sync 매출 업데이트(사용 중인 쇼핑몰 전부, 쇼핑몰별 실패 격리)
|
|
background=true 면 백그라운드로 돌리고 작업 번호를 바로 돌려줌
|
|
GET /performance/api/sync/jobs/{id} 매출 업데이트 진행 상황(쇼핑몰별·전체 진행 막대)
|
|
GET /performance/api/sync/current 지금 돌고 있는 업데이트(없으면 null)
|
|
POST /performance/api/sync/jobs/{id}/cancel 업데이트 취소(시작한 사람 또는 관리자)
|
|
GET /performance/api/events 금액 클릭 상세(쇼핑몰+기간)
|
|
JSON API — 관리자
|
|
PUT /performance/api/marketplaces/{code} 사용/매출 집계 여부
|
|
POST /performance/api/marketplaces/{code}/rates 수수료율(적용 시작일)
|
|
DELETE /performance/api/marketplaces/{code}/rates/{id}
|
|
GET /performance/api/marketplaces/{code}/credentials 입력칸 + 저장 여부(비밀 원문 없음)
|
|
GET /performance/api/marketplaces/{code}/daily-check 일별 매출 비교(저장값 + 지금 API 값)
|
|
PUT /performance/api/marketplaces/{code}/credentials 저장(암호화)
|
|
POST /performance/api/marketplaces/{code}/test 연결 테스트(저장값 또는 새 입력값)
|
|
POST /performance/api/sample-data 테스트 데이터 생성/삭제
|
|
POST /performance/api/rekey 마스터 키 교체 후 재암호화
|
|
|
|
핸들러는 동기 DB 라 `def` 로 둔다(FastAPI 가 스레드풀에서 실행).
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
from datetime import date
|
|
from decimal import Decimal, InvalidOperation
|
|
from typing import Any
|
|
|
|
from fastapi import APIRouter, Body, HTTPException, Query, Request
|
|
from fastapi.responses import HTMLResponse, JSONResponse
|
|
|
|
from app.timezone import today_kst
|
|
|
|
from . import common
|
|
from .adapters.registry import all_adapters, get_adapter
|
|
|
|
router = APIRouter(prefix="/performance", tags=["performance"])
|
|
|
|
MAX_EVENT_DAYS = 31
|
|
MAX_CHECK_DAYS = 62 # 쇼핑몰 화면 일별 비교(카페24 일별 매출내역 붙여넣기)
|
|
MAX_BACKFILL_DAYS = 366
|
|
MAX_USER_SYNC_DAYS = 92 # 관리자가 아니어도 가져올 수 있는 기간(이번달·직접선택 짧은 기간)
|
|
|
|
|
|
def _parse_date(value: Any, *, field: str = "날짜") -> date | None:
|
|
if value in (None, ""):
|
|
return None
|
|
try:
|
|
return date.fromisoformat(str(value)[:10])
|
|
except ValueError:
|
|
raise HTTPException(status_code=400, detail=f"{field} 형식이 올바르지 않습니다(YYYY-MM-DD).") from None
|
|
|
|
|
|
def _holidays() -> dict[str, str]:
|
|
try:
|
|
from app.modules.project.store import KR_HOLIDAYS # noqa: WPS433 — 공휴일 표 공유(읽기 전용)
|
|
|
|
return dict(KR_HOLIDAYS)
|
|
except Exception: # noqa: BLE001
|
|
return {}
|
|
|
|
|
|
def _code_or_404(store: Any, code: str):
|
|
adapter = get_adapter(code)
|
|
if adapter is None or code not in {m["code"] for m in store.list_marketplaces()}:
|
|
raise HTTPException(status_code=404, detail="알 수 없는 쇼핑몰입니다.")
|
|
return adapter
|
|
|
|
|
|
@router.get("/health")
|
|
def health(request: Request) -> JSONResponse:
|
|
st = common.get_store(request)
|
|
return JSONResponse({"ok": st is not None, "module": "performance",
|
|
"encryption_key": common.key_status()["ok"]})
|
|
|
|
|
|
# ════════════════════════════════════════════════════════════
|
|
# 화면
|
|
# ════════════════════════════════════════════════════════════
|
|
@router.get("/", response_class=HTMLResponse)
|
|
def dashboard_page(
|
|
request: Request,
|
|
period: str = "week",
|
|
d: str | None = None,
|
|
from_: str | None = Query(None, alias="from"),
|
|
to: str | None = None,
|
|
m: list[str] = Query(default=[]),
|
|
metric: str = "gross",
|
|
):
|
|
from app.main import render_template # noqa: WPS433
|
|
|
|
g = common.guard(request)
|
|
if not isinstance(g, tuple):
|
|
return g
|
|
store, user = g
|
|
from .dashboard import build_dashboard # noqa: WPS433
|
|
|
|
today = today_kst()
|
|
anchor = _parse_date(d) or today
|
|
creds, _ = common.services(request, store)
|
|
ctx = build_dashboard(
|
|
store, kind=period, anchor=anchor, today=today,
|
|
custom_from=_parse_date(from_), custom_to=_parse_date(to), selected=m,
|
|
holidays=_holidays(), configured=creds.configured_codes(list(all_adapters())),
|
|
)
|
|
ctx["metric"] = metric if metric in ("gross", "commission", "net") else "gross"
|
|
return render_template(request, "performance/index.html", {**common.base_ctx(user, active_tab="dashboard"), **ctx})
|
|
|
|
|
|
@router.get("/settings", response_class=HTMLResponse)
|
|
def settings_page(request: Request):
|
|
from app.main import render_template # noqa: WPS433
|
|
|
|
g = common.guard(request, admin=True)
|
|
if not isinstance(g, tuple):
|
|
return g
|
|
store, user = g
|
|
from .dashboard import build_settings # noqa: WPS433
|
|
|
|
creds, _ = common.services(request, store)
|
|
ctx = build_settings(
|
|
store, configured=creds.configured_codes(list(all_adapters())), key_info=common.key_status(),
|
|
key_versions_in_use=creds.key_versions_in_use(), sample_count=store.sample_count(),
|
|
)
|
|
return render_template(request, "performance/settings.html",
|
|
{**common.base_ctx(user, active_tab="settings", page_title="실적 설정"), **ctx})
|
|
|
|
|
|
# ════════════════════════════════════════════════════════════
|
|
# JSON API — 모듈 권한
|
|
# ════════════════════════════════════════════════════════════
|
|
@router.post("/api/sync")
|
|
def api_sync(request: Request, payload: dict[str, Any] = Body(default={})) -> JSONResponse:
|
|
"""from/to 가 없으면 최근 N일(PERFORMANCE_SYNC_DAYS). 기간 지정은 대시보드 [매출 업데이트](보고 있는 기간)와
|
|
설정 [과거 매출 가져오기]가 쓴다 — 모듈 권한자는 92일까지, 그보다 길면(최대 366일) 관리자만."""
|
|
store, user = common.require_store(request)
|
|
_, sync = common.services(request, store)
|
|
codes = [str(c) for c in (payload.get("codes") or []) if get_adapter(str(c))]
|
|
start = _parse_date(payload.get("from"), field="시작일")
|
|
end = _parse_date(payload.get("to"), field="종료일")
|
|
if start or end:
|
|
from app.store import is_admin # noqa: WPS433
|
|
|
|
end = end or today_kst()
|
|
start = start or end
|
|
if end < start:
|
|
start, end = end, start
|
|
if end > today_kst():
|
|
end = today_kst()
|
|
if start > end:
|
|
raise HTTPException(status_code=400, detail="앞으로의 기간은 가져올 수 없습니다.")
|
|
days = (end - start).days + 1
|
|
if days > MAX_BACKFILL_DAYS:
|
|
raise HTTPException(status_code=400, detail=f"한 번에 {MAX_BACKFILL_DAYS}일까지 가져올 수 있습니다.")
|
|
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.post("/api/sync/jobs/{job_id}/cancel")
|
|
def api_sync_cancel(request: Request, job_id: str) -> JSONResponse:
|
|
"""[업데이트 취소] — 시작한 사람 또는 관리자. 돌고 있는 쇼핑몰은 다음 API 호출 직전에 멈추고(저장 전이면 DB 그대로),
|
|
기다리는 쇼핑몰은 건너뛴다. 이미 저장이 끝난 쇼핑몰 결과는 그대로 남는다."""
|
|
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="업데이트를 시작한 사람이나 관리자만 취소할 수 있습니다.")
|
|
job.cancel(user["email"])
|
|
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)
|
|
_code_or_404(store, code)
|
|
start = _parse_date(from_)
|
|
end = _parse_date(to) or start
|
|
if end < start:
|
|
start, end = end, start
|
|
if (end - start).days + 1 > MAX_EVENT_DAYS:
|
|
raise HTTPException(status_code=400, detail=f"상세 조회는 {MAX_EVENT_DAYS}일 이내만 가능합니다.")
|
|
rows = store.list_events(code, start, end)
|
|
return JSONResponse({"rows": rows, "truncated": len(rows) >= 500})
|
|
|
|
|
|
# ════════════════════════════════════════════════════════════
|
|
# JSON API — 관리자(설정)
|
|
# ════════════════════════════════════════════════════════════
|
|
@router.put("/api/marketplaces/{code}")
|
|
def api_update_marketplace(request: Request, code: str, payload: dict[str, Any] = Body(...)) -> JSONResponse:
|
|
store, _ = common.require_store(request, admin=True)
|
|
_code_or_404(store, code)
|
|
row = store.update_marketplace(
|
|
code,
|
|
enabled=bool(payload["enabled"]) if "enabled" in payload else None,
|
|
include_in_sales=bool(payload["include_in_sales"]) if "include_in_sales" in payload else None,
|
|
)
|
|
return JSONResponse({"marketplace": row})
|
|
|
|
|
|
@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)
|
|
_code_or_404(store, code)
|
|
raw = str(payload.get("rate_percent", "")).strip().rstrip("%").strip()
|
|
try:
|
|
rate = Decimal(raw)
|
|
except InvalidOperation:
|
|
raise HTTPException(status_code=400, detail="수수료율은 숫자로 입력하세요(예: 5, 10.8, 15.35).") from None
|
|
if not rate.is_finite() or rate < 0 or rate > 100:
|
|
raise HTTPException(status_code=400, detail="수수료율은 0 ~ 100 사이여야 합니다.")
|
|
if rate != rate.quantize(Decimal("0.001")):
|
|
raise HTTPException(status_code=400, detail="수수료율은 소수점 셋째 자리까지 입력할 수 있습니다.")
|
|
effective_from = _parse_date(payload.get("effective_from"), field="적용 시작일")
|
|
if effective_from is None:
|
|
raise HTTPException(status_code=400, detail="적용 시작일을 입력하세요.")
|
|
store.set_rate(code, rate_percent=rate, effective_from=effective_from,
|
|
memo=str(payload.get("memo") or "")[:200], user=user["email"])
|
|
return JSONResponse({"rates": store.list_rates(code)})
|
|
|
|
|
|
@router.get("/api/marketplaces/{code}/rates")
|
|
def api_list_rates(request: Request, code: str) -> JSONResponse:
|
|
store, _ = common.require_store(request, admin=True)
|
|
_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)
|
|
_code_or_404(store, code)
|
|
if not store.delete_rate(code, rate_id):
|
|
raise HTTPException(status_code=404, detail="수수료 이력을 찾지 못했습니다.")
|
|
return JSONResponse({"rates": store.list_rates(code)})
|
|
|
|
|
|
@router.get("/api/marketplaces/{code}/credentials")
|
|
def api_get_credentials(request: Request, code: str) -> JSONResponse:
|
|
"""입력칸 정의 + 저장 여부만. secret 항목의 원문은 보내지 않는다."""
|
|
store, _ = common.require_store(request, admin=True)
|
|
adapter = _code_or_404(store, code)
|
|
creds, _ = common.services(request, store)
|
|
info = creds.describe(adapter)
|
|
return JSONResponse({"code": code, "name": adapter.name, "shared": adapter.uses_shared_integration,
|
|
"note": adapter.note, "docs_url": adapter.docs_url,
|
|
"key": common.key_status(), **info})
|
|
|
|
|
|
def _clean_values(adapter, payload: dict[str, Any]) -> dict[str, str]:
|
|
allowed = {f.key for f in adapter.visible_fields()}
|
|
values = payload.get("values") or {}
|
|
if not isinstance(values, dict):
|
|
raise HTTPException(status_code=400, detail="values 형식이 올바르지 않습니다.")
|
|
return {k: str(v) for k, v in values.items() if k in allowed and v is not None}
|
|
|
|
|
|
@router.put("/api/marketplaces/{code}/credentials")
|
|
def api_save_credentials(request: Request, code: str, payload: dict[str, Any] = Body(...)) -> JSONResponse:
|
|
store, user = common.require_store(request, admin=True)
|
|
adapter = _code_or_404(store, code)
|
|
if adapter.uses_shared_integration:
|
|
raise HTTPException(status_code=400, detail=f"{adapter.name}은(는) 공통 연동을 사용해 여기서 입력하지 않습니다.")
|
|
if not common.key_status()["ok"]:
|
|
raise HTTPException(status_code=503, detail=common.key_status()["message"])
|
|
creds, _ = common.services(request, store)
|
|
values = _clean_values(adapter, payload)
|
|
clear = [str(k) for k in (payload.get("clear") or [])]
|
|
merged = creds.merged_values(adapter, values)
|
|
for k in clear:
|
|
if k in merged and not values.get(k):
|
|
merged[k] = ""
|
|
errors = adapter.validate_credentials(merged)
|
|
if errors:
|
|
raise HTTPException(status_code=400, detail=" ".join(errors))
|
|
saved = creds.save(adapter, values, clear=clear, user=user["email"])
|
|
return JSONResponse({"saved": saved, **creds.describe(adapter)})
|
|
|
|
|
|
@router.post("/api/marketplaces/{code}/test")
|
|
def api_test_connection(request: Request, code: str, payload: dict[str, Any] = Body(default={})) -> JSONResponse:
|
|
"""values 가 있으면 저장하지 않은 새 입력값으로 시험(빈 칸은 저장된 값 사용)."""
|
|
store, user = common.require_store(request, admin=True)
|
|
adapter = _code_or_404(store, code)
|
|
_, sync = common.services(request, store)
|
|
values = {k: v for k, v in _clean_values(adapter, payload).items() if v.strip()}
|
|
result = sync.test_connection(code, values=values or None, user=user["email"])
|
|
return JSONResponse(result)
|
|
|
|
|
|
@router.get("/api/marketplaces/{code}/reconcile")
|
|
def api_reconcile(request: Request, code: str, date_: str = Query(..., alias="date"), to: str | None = None) -> JSONResponse:
|
|
"""쇼핑몰 화면(예: 카페24 일별 매출내역)과 비교용 — 그날 원천 금액 항목별 합계. DB 는 바꾸지 않는다."""
|
|
store, user = common.require_store(request, admin=True)
|
|
_code_or_404(store, code)
|
|
day = _parse_date(date_)
|
|
_, sync = common.services(request, store)
|
|
return JSONResponse(sync.reconcile(code, day, to=_parse_date(to, field="종료일"), user=user["email"]))
|
|
|
|
|
|
@router.get("/api/marketplaces/{code}/daily-check")
|
|
def api_daily_check(request: Request, code: str, from_: str = Query(..., alias="from"), to: str | None = None,
|
|
live: bool = False) -> JSONResponse:
|
|
"""쇼핑몰 화면 일별 매출과 날짜별 비교 — 저장값(db) + live=1 이면 지금 API 로 다시 계산한 값(저장 안 함)."""
|
|
store, user = common.require_store(request, admin=True)
|
|
_code_or_404(store, code)
|
|
start = _parse_date(from_)
|
|
end = _parse_date(to) or start
|
|
if end < start:
|
|
start, end = end, start
|
|
if (end - start).days + 1 > MAX_CHECK_DAYS:
|
|
raise HTTPException(status_code=400, detail=f"일별 비교는 {MAX_CHECK_DAYS}일 이내만 가능합니다.")
|
|
_, sync = common.services(request, store)
|
|
return JSONResponse(sync.daily_check(code, start, end, live=live, user=user["email"]))
|
|
|
|
|
|
@router.post("/api/sample-data")
|
|
def api_sample_data(request: Request, payload: dict[str, Any] = Body(...)) -> JSONResponse:
|
|
store, _ = common.require_store(request, admin=True)
|
|
action = payload.get("action")
|
|
if action == "delete":
|
|
return JSONResponse({"deleted": store.delete_sample_events(), "sample_count": store.sample_count()})
|
|
if action != "generate":
|
|
raise HTTPException(status_code=400, detail="action 은 generate 또는 delete 입니다.")
|
|
today = today_kst()
|
|
start = _parse_date(payload.get("from")) or today.replace(month=1, day=1)
|
|
end = _parse_date(payload.get("to")) or today
|
|
if end < start:
|
|
start, end = end, start
|
|
if (end - start).days > 400:
|
|
raise HTTPException(status_code=400, detail="테스트 데이터는 한 번에 400일까지 만들 수 있습니다.")
|
|
codes = [m["code"] for m in store.list_marketplaces() if m["enabled"]]
|
|
_, sync = common.services(request, store)
|
|
n = sync.generate_samples(start, end, codes)
|
|
return JSONResponse({"generated": n, "sample_count": store.sample_count()})
|
|
|
|
|
|
@router.post("/api/rekey")
|
|
def api_rekey(request: Request) -> JSONResponse:
|
|
store, _ = common.require_store(request, admin=True)
|
|
if not common.key_status()["ok"]:
|
|
raise HTTPException(status_code=503, detail=common.key_status()["message"])
|
|
creds, _ = common.services(request, store)
|
|
return JSONResponse({**creds.reencrypt_all(), "versions_in_use": creds.key_versions_in_use()})
|