feat(performance): 직접 추가 쇼핑몰(수동 입력)·쇼핑몰 그룹·설정 드래그 순서

- 마이그레이션 009: perf_marketplaces.is_custom·is_group·parent_code
- 설정: [+ 쇼핑몰 추가(수동 입력)]·[+ 그룹 추가], 이름 변경·삭제, 직접 추가 쇼핑몰 그룹 select
- custom_ 코드는 registry.get_adapter 가 수동 입력 전용 어댑터(CustomManualAdapter)로
- 매출 실적 표: 그룹 열 = 보이는 하위 쇼핑몰 합계(일 합계엔 안 더함), ▾/▸ 하위 열 접기(localStorage)
- 설정 표 ⠿ 드래그 → PUT /api/marketplace-order → sort_order, 화면 순서는 ordered_marketplaces 한 곳
- 테스트: test_custom_groups.py, perf_groups.browser.test.js

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-22 10:57:03 +09:00
parent 5ef9a55d91
commit e3a8649b41
18 changed files with 948 additions and 44 deletions
+118 -6
View File
@@ -25,7 +25,11 @@ JSON API — 모듈 권한
JSON API — 관리자
GET|PUT /performance/api/ad-sources/{code}/credentials 광고 API 인증정보(마이그레이션 007, 암호화 저장·비밀 원문 없음)
POST /performance/api/ad-sources/{code}/test 광고 API 연결 테스트(저장값 또는 새 입력값)
PUT /performance/api/marketplaces/{code} 사용/매출 집계/수동 입력 여부
PUT /performance/api/marketplaces/{code} 사용/매출 집계/수동 입력 여부, 직접 추가 행 이름·그룹(009)
POST /performance/api/marketplaces 쇼핑몰(수동 입력 전용)·그룹 직접 추가(009)
DELETE /performance/api/marketplaces/{code} 직접 추가 쇼핑몰·그룹 삭제(그 쇼핑몰 수동 입력·수수료도)
PUT /performance/api/marketplace-order 쇼핑몰 순서(설정 드래그 — 매출 실적 열 순서)
GET /performance/api/marketplaces/{code}/manual-days 수동 입력해 둔 날 수(삭제 확인 문구)
POST /performance/api/marketplaces/{code}/rates 수수료율(적용 시작일)
DELETE /performance/api/marketplaces/{code}/rates/{id}
GET /performance/api/marketplaces/{code}/credentials 입력칸 + 저장 여부(비밀 원문 없음)
@@ -72,6 +76,9 @@ AD_MIGRATION_HELP_007 = ("광고 API 연동(구글 광고) 인증정보를 저
def _ad_migration_help(exc: Exception) -> str:
text = str(exc)
return AD_MIGRATION_HELP_007 if "007" in text else AD_MIGRATION_HELP_006 if "006" in text else AD_MIGRATION_HELP
CUSTOM_MIGRATION_HELP = ("쇼핑몰 직접 추가·그룹을 쓰려면 performance_db 마이그레이션 009"
"(scripts/sql/performance_db_009_custom_marketplaces.sql)를 먼저 적용해야 합니다.")
MAX_MARKET_NAME = 30
MANUAL_MIGRATION_HELP = ("수동 입력을 쓰려면 performance_db 마이그레이션 002(scripts/sql/performance_db_002_manual_sales.sql)를 "
"먼저 적용해야 합니다.")
@@ -451,9 +458,9 @@ def api_manual_upload(request: Request, file: UploadFile = File(...)) -> JSONRes
store, user = common.require_store(request) # 날짜 칸 수동 입력과 같은 권한(모듈 권한자 누구나)
content = file.file.read(manual_upload.MAX_FILE_BYTES + 1)
known = {a.code: a for a in all_adapters()}
markets = [m for m in store.list_marketplaces() if m["code"] in known and m["enabled"]]
extra = {m["code"]: (known[m["code"]].name, _short_name(m["name"])) for m in markets}
# 직접 추가 쇼핑몰(009)도 대상 — 어댑터 = 수동 입력 전용(이름은 DB), 그룹 행은 어댑터가 없어 빠진다
markets = [m for m in store.list_marketplaces() if get_adapter(m["code"]) is not None and m["enabled"]]
extra = {m["code"]: tuple(n for n in (get_adapter(m["code"]).name, _short_name(m["name"])) if n) for m in markets}
try:
res = manual_upload.parse_workbook(content, markets=markets, today=today_kst(), extra_names=extra)
except manual_upload.UploadError as exc:
@@ -730,15 +737,120 @@ def api_ad_source_sync(request: Request, code: str, payload: dict[str, Any] = Bo
# ════════════════════════════════════════════════════════════
# JSON API — 설정(수수료율은 모듈 권한자 누구나, 나머지는 관리자)
# ════════════════════════════════════════════════════════════
def _market_or_404(store: Any, code: str) -> dict[str, Any]:
"""DB 행(그룹 포함)."""
m = next((x for x in store.list_marketplaces() if x["code"] == code), None)
if m is None or (get_adapter(code) is None and not m.get("is_group")):
raise HTTPException(status_code=404, detail="알 수 없는 쇼핑몰입니다.")
return m
def _clean_market_name(store: Any, raw: Any, *, code: str = "") -> str:
"""직접 추가 행 이름 — 엑셀 업로드 머리글로도 쓰여 다른 쇼핑몰·그룹과 겹치면 안 된다."""
name = " ".join(str(raw or "").split())
if not name:
raise HTTPException(status_code=400, detail="이름을 입력하세요.")
if len(name) > MAX_MARKET_NAME:
raise HTTPException(status_code=400, detail=f"이름은 {MAX_MARKET_NAME}자까지입니다.")
if any(m["code"] != code and m["name"].strip().lower() == name.lower() for m in store.list_marketplaces()):
raise HTTPException(status_code=400, detail=f"같은 이름({name})이 이미 있습니다.")
return name
def _set_parent(store: Any, code: str, parent: str | None) -> dict[str, Any] | None:
from .db import CustomMigrationNeeded # noqa: WPS433
if parent:
g = next((x for x in store.list_marketplaces() if x["code"] == parent), None)
if g is None or not g.get("is_group"):
raise HTTPException(status_code=400, detail="그룹을 찾지 못했습니다.")
try:
return store.set_marketplace_parent(code, parent or None)
except CustomMigrationNeeded:
raise HTTPException(status_code=503, detail=CUSTOM_MIGRATION_HELP) from None
@router.post("/api/marketplaces")
def api_add_marketplace(request: Request, payload: dict[str, Any] = Body(...)) -> JSONResponse:
"""직접 추가(009) — kind="shop" 수동 입력 전용 쇼핑몰(맨 뒤, 사용·매출 집계·수동 입력 켬), kind="group" 그룹."""
import secrets # noqa: WPS433
from .adapters.registry import CUSTOM_PREFIX, GROUP_PREFIX # noqa: WPS433
from .db import CustomMigrationNeeded # noqa: WPS433
store, _ = common.require_store(request, admin=True)
kind = payload.get("kind") or "shop"
if kind not in ("shop", "group"):
raise HTTPException(status_code=400, detail="kind 는 shop 또는 group 입니다.")
name = _clean_market_name(store, payload.get("name"))
code = (GROUP_PREFIX if kind == "group" else CUSTOM_PREFIX) + secrets.token_hex(4)
try:
row = store.add_custom_marketplace(code, name, is_group=kind == "group")
except CustomMigrationNeeded:
raise HTTPException(status_code=503, detail=CUSTOM_MIGRATION_HELP) from None
if kind == "shop" and payload.get("parent_code"):
row = _set_parent(store, code, str(payload["parent_code"])) or row
return JSONResponse({"marketplace": row})
@router.delete("/api/marketplaces/{code}")
def api_delete_marketplace(request: Request, code: str) -> JSONResponse:
"""직접 추가한 쇼핑몰·그룹만 — 쇼핑몰이면 수동 입력 매출·수수료율도 지운다, 그룹이면 하위 쇼핑몰은 그룹 없음."""
store, _ = common.require_store(request, admin=True)
m = _market_or_404(store, code)
if not m.get("is_custom"):
raise HTTPException(status_code=400, detail="기본 쇼핑몰은 삭제할 수 없습니다(사용을 끄세요).")
if not store.delete_custom_marketplace(code):
raise HTTPException(status_code=404, detail="알 수 없는 쇼핑몰입니다.")
return JSONResponse({"ok": True})
@router.get("/api/marketplaces/{code}/manual-days")
def api_manual_days(request: Request, code: str) -> JSONResponse:
"""수동 입력해 둔 날 수 — 직접 추가 쇼핑몰 삭제 확인 문구용."""
store, _ = common.require_store(request, admin=True)
_market_or_404(store, code)
return JSONResponse({"days": store.manual_day_count(code)})
@router.put("/api/marketplace-order")
def api_marketplace_order(request: Request, payload: dict[str, Any] = Body(...)) -> JSONResponse:
"""설정 드래그 순서 — 화면에 보이는 순서(그룹 뒤에 하위) 그대로 codes. 매출 실적 열 순서가 된다."""
store, _ = common.require_store(request, admin=True)
known = {m["code"] for m in store.list_marketplaces()}
codes = [str(c) for c in (payload.get("codes") or []) if str(c) in known]
if len(set(codes)) != len(codes):
raise HTTPException(status_code=400, detail="순서 목록에 같은 쇼핑몰이 두 번 있습니다.")
if not codes:
raise HTTPException(status_code=400, detail="순서 목록이 비었습니다.")
store.reorder_marketplaces(codes)
return JSONResponse({"ok": True})
@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)
m = _market_or_404(store, code)
from .db import ManualMigrationNeeded # noqa: WPS433
adapter = get_adapter(code)
if adapter is not None and adapter.manual_only and payload.get("manual_input") is False:
raise HTTPException(status_code=400, detail="수동 입력 전용 쇼핑몰은 수동 입력을 끌 수 없습니다.")
# 직접 추가 행(009) — 이름·그룹. 그룹으로 묶을 수 있는 건 직접 추가한 쇼핑몰만(그룹 안에 그룹 없음)
if "name" in payload or "parent_code" in payload:
if not m.get("is_custom"):
raise HTTPException(status_code=400, detail="기본 쇼핑몰은 이름·그룹을 바꿀 수 없습니다.")
if "parent_code" in payload and m.get("is_group"):
raise HTTPException(status_code=400, detail="그룹은 다른 그룹에 넣을 수 없습니다.")
row = None
if "name" in payload:
row = store.rename_marketplace(code, _clean_market_name(store, payload.get("name"), code=code))
if "parent_code" in payload:
row = _set_parent(store, code, str(payload.get("parent_code") or "") or None)
if not any(k in payload for k in ("enabled", "include_in_sales", "manual_input")):
return JSONResponse({"marketplace": row})
if m.get("is_group"):
raise HTTPException(status_code=400, detail="그룹은 이름만 바꿀 수 있습니다.")
try:
row = store.update_marketplace(
@@ -891,7 +1003,7 @@ def api_sample_data(request: Request, payload: dict[str, Any] = Body(...)) -> JS
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"]]
codes = [m["code"] for m in store.list_marketplaces() if m["enabled"] and get_adapter(m["code"]) is not None]
_, sync = common.services(request, store)
n = sync.generate_samples(start, end, codes)
return JSONResponse({"generated": n, "sample_count": store.sample_count()})