Merge branch 'feat/perf-custom-shops-groups'
This commit is contained in:
@@ -46,6 +46,11 @@
|
||||
- 일자별 표 **기간 합계 행은 맨 위**(제목 행 바로 아래, 2026-10-21 `calc.main_table`) — 매출·광고비 공통, 연간 보기 "연간 합계"는 그대로 맨 아래.
|
||||
- 열 순서 카페24·네이버·쿠팡(윙)·쿠팡(로켓)·오늘의집·G마켓·카카오·GS샵·11번가·롯데ON·토스·애터미아자몰(마이그레이션 003).
|
||||
- 쿠팡(로켓)·애터미아자몰은 **수동 입력 전용**(`adapters/manual.py`, `manual_only` — 매출 업데이트에서 빠지고 인증 설정·연결 테스트 없음, 수동 입력 늘 켜짐).
|
||||
- **직접 추가 쇼핑몰·그룹·순서 드래그**(2026-10-22, 마이그레이션 009 `is_custom`·`is_group`·`parent_code`) — 설정 [+ 쇼핑몰 추가(수동 입력)]
|
||||
(코드 `custom_…`, `get_adapter` 가 `CustomManualAdapter` = 수동 입력 전용)·[+ 그룹 추가](`group_…`, 매출 없음·`include_in_sales` 꺼짐),
|
||||
직접 추가 쇼핑몰만 그룹 select 로 묶음, 이름 변경·삭제(삭제 = 그 쇼핑몰 수동 입력·수수료도). 매출 실적 표 그룹 열 = 보이는 하위 합계(일 합계엔 안 더함),
|
||||
▾/▸ 하위 열 접기(localStorage). ⠿ 드래그 → `PUT /api/marketplace-order` → `sort_order`, 화면 순서는 `dashboard.ordered_marketplaces`
|
||||
(그룹 바로 뒤 하위) 한 곳. 상세 `docs/PERFORMANCE_MODULE.md` "직접 추가 쇼핑몰·그룹".
|
||||
|
||||
## 매출 실적 화면 (2026-10-19)
|
||||
|
||||
|
||||
@@ -23,3 +23,10 @@ class CoupangRocketAdapter(ManualOnlyAdapter):
|
||||
class AtomyAzmallAdapter(ManualOnlyAdapter):
|
||||
code = "atomy"
|
||||
name = "애터미아자몰"
|
||||
|
||||
|
||||
class CustomManualAdapter(ManualOnlyAdapter):
|
||||
"""실적 설정에서 사용자가 직접 추가한 쇼핑몰(마이그레이션 009, 코드 custom_…) — 이름은 DB(perf_marketplaces.name)."""
|
||||
|
||||
def __init__(self, code: str) -> None:
|
||||
self.code = code
|
||||
|
||||
@@ -14,7 +14,7 @@ from .gmarket import GmarketAdapter
|
||||
from .gsshop import GsshopAdapter
|
||||
from .kakao import KakaoAdapter
|
||||
from .lotteon import LotteonAdapter
|
||||
from .manual import AtomyAzmallAdapter, CoupangRocketAdapter
|
||||
from .manual import AtomyAzmallAdapter, CoupangRocketAdapter, CustomManualAdapter
|
||||
from .naver import NaverAdapter
|
||||
from .ohouse import OhouseAdapter
|
||||
from .toss import TossAdapter
|
||||
@@ -36,10 +36,18 @@ _ADAPTERS: tuple[MarketplaceAdapter, ...] = (
|
||||
)
|
||||
_BY_CODE = {a.code: a for a in _ADAPTERS}
|
||||
|
||||
# 실적 설정에서 직접 추가한 행(마이그레이션 009) — 쇼핑몰은 수동 입력 전용 어댑터, 그룹은 어댑터 없음(매출 없음)
|
||||
CUSTOM_PREFIX = "custom_"
|
||||
GROUP_PREFIX = "group_"
|
||||
|
||||
|
||||
def all_adapters() -> tuple[MarketplaceAdapter, ...]:
|
||||
return _ADAPTERS
|
||||
|
||||
|
||||
def get_adapter(code: str) -> MarketplaceAdapter | None:
|
||||
return _BY_CODE.get(code)
|
||||
"""코드 → 어댑터. 직접 추가 쇼핑몰(custom_…)은 수동 입력 전용 어댑터, 그룹·모르는 코드는 None."""
|
||||
adapter = _BY_CODE.get(code)
|
||||
if adapter is None and code.startswith(CUSTOM_PREFIX):
|
||||
return CustomManualAdapter(code)
|
||||
return adapter
|
||||
|
||||
@@ -11,13 +11,50 @@ from typing import Any, Mapping, Sequence
|
||||
|
||||
from . import calc
|
||||
from .adapters.base import STATUS_LABELS
|
||||
from .adapters.registry import all_adapters, get_adapter
|
||||
from .adapters.registry import get_adapter
|
||||
|
||||
|
||||
def _sales_marketplaces(store: Any) -> list[dict[str, Any]]:
|
||||
"""대시보드 열 = 사용 ON + 매출 집계 ON 인 쇼핑몰(설정 순서)."""
|
||||
known = {a.code for a in all_adapters()}
|
||||
return [m for m in store.list_marketplaces() if m["enabled"] and m["include_in_sales"] and m["code"] in known]
|
||||
def ordered_marketplaces(markets: Sequence[Mapping[str, Any]]) -> list[Mapping[str, Any]]:
|
||||
"""화면 순서(설정 드래그 = sort_order) — 그룹(009) 바로 뒤에 그 하위 쇼핑몰(하위끼리도 sort_order).
|
||||
목록에 그룹이 없는 하위 쇼핑몰은 그룹 없음처럼 제자리. markets 는 sort_order 순(list_marketplaces)."""
|
||||
groups = {m["code"] for m in markets if m.get("is_group")}
|
||||
children: dict[str, list[Mapping[str, Any]]] = {}
|
||||
for m in markets:
|
||||
if m.get("parent_code") in groups and not m.get("is_group"):
|
||||
children.setdefault(m["parent_code"], []).append(m)
|
||||
out: list[Mapping[str, Any]] = []
|
||||
for m in markets:
|
||||
if m.get("parent_code") in groups and not m.get("is_group"):
|
||||
continue
|
||||
out.append(m)
|
||||
out.extend(children.get(m["code"], ()))
|
||||
return out
|
||||
|
||||
|
||||
def _sales_marketplaces(store: Any, rows: Sequence[Mapping[str, Any]] | None = None) -> list[dict[str, Any]]:
|
||||
"""대시보드 열 = 사용 ON + 매출 집계 ON 인 쇼핑몰(설정 순서 — 그룹 하위는 그룹 자리). 그룹 행은 빠진다(매출 없음)."""
|
||||
rows = ordered_marketplaces(store.list_marketplaces() if rows is None else rows)
|
||||
return [m for m in rows if m["enabled"] and m["include_in_sales"] and get_adapter(m["code"]) is not None]
|
||||
|
||||
|
||||
def _group_columns(store_rows: Sequence[Mapping[str, Any]], codes: Sequence[str]) -> tuple[list[dict[str, Any]], dict[str, list[str]]]:
|
||||
"""일자별 표 열 — 그룹(009)은 보이는 하위 쇼핑몰이 하나라도 있을 때 하위 열 바로 앞에 그룹 합계 열.
|
||||
[{code, kind: shop|group|child, group}], 그룹 → 보이는 하위 코드."""
|
||||
groups = {m["code"]: m for m in store_rows if m.get("is_group")}
|
||||
parent = {m["code"]: m.get("parent_code") for m in store_rows if m.get("parent_code") in groups}
|
||||
members: dict[str, list[str]] = {}
|
||||
cols: list[dict[str, Any]] = []
|
||||
for c in codes:
|
||||
g = parent.get(c)
|
||||
if g is None:
|
||||
cols.append({"code": c, "kind": "shop", "group": ""})
|
||||
continue
|
||||
if g not in members:
|
||||
members[g] = []
|
||||
cols.append({"code": g, "kind": "group", "group": g})
|
||||
members[g].append(c)
|
||||
cols.append({"code": c, "kind": "child", "group": g})
|
||||
return cols, members
|
||||
|
||||
|
||||
def display_status(marketplace: Mapping[str, Any], status_row: Mapping[str, Any] | None,
|
||||
@@ -123,11 +160,17 @@ def build_dashboard(store: Any, *, kind: str, anchor: date, today: date,
|
||||
custom_from: date | None = None, custom_to: date | None = None,
|
||||
selected: Sequence[str] = (), holidays: Mapping[str, str] | None = None,
|
||||
configured: Mapping[str, bool] | None = None) -> dict[str, Any]:
|
||||
markets = _sales_marketplaces(store)
|
||||
store_rows = store.list_marketplaces()
|
||||
markets = _sales_marketplaces(store, store_rows)
|
||||
all_codes = [m["code"] for m in markets]
|
||||
codes = [c for c in all_codes if c in set(selected)] or all_codes
|
||||
names = {m["code"]: m["name"] for m in markets}
|
||||
short = {c: _short_name(names[c]) for c in all_codes}
|
||||
# 그룹(009) — 그룹 열 = 보이는 하위 쇼핑몰 합계(표 열만, 합계·그래프·누적은 쇼핑몰 기준 그대로)
|
||||
cols, group_members = _group_columns(store_rows, codes)
|
||||
for m in store_rows:
|
||||
if m["code"] in group_members:
|
||||
names[m["code"]] = short[m["code"]] = m["name"]
|
||||
|
||||
period = calc.resolve_period(kind, anchor, custom_from=custom_from, custom_to=custom_to)
|
||||
cmp_start, cmp_end, cmp_label = period.compare_range(today)
|
||||
@@ -187,6 +230,10 @@ def build_dashboard(store: Any, *, kind: str, anchor: date, today: date,
|
||||
m_qs = "" if len(codes) == len(all_codes) else "".join(f"&m={c}" for c in codes)
|
||||
table = calc.main_table(period, codes, cells, today=today, holidays=holidays)
|
||||
_ad_lines(store, table, codes, cells, period, q_start, q_end)
|
||||
for r in table:
|
||||
for g, members in group_members.items():
|
||||
r["cells"][g] = calc.total(calc.Money(gross=r["cells"][c]["gross"], commission=r["cells"][c]["commission"])
|
||||
for c in members).as_dict()
|
||||
|
||||
def url(kind: str, anchor_d: date | None = None, start: date | None = None, end: date | None = None) -> str:
|
||||
if kind == "custom":
|
||||
@@ -221,6 +268,8 @@ def build_dashboard(store: Any, *, kind: str, anchor: date, today: date,
|
||||
"period_kind": period.kind,
|
||||
"today": today.isoformat(),
|
||||
"codes": codes,
|
||||
"cols": cols,
|
||||
"group_members": group_members,
|
||||
"all_codes": all_codes,
|
||||
"names": names,
|
||||
"short_names": short,
|
||||
@@ -258,32 +307,51 @@ def build_settings(store: Any, *, configured: Mapping[str, bool], key_info: Mapp
|
||||
today = today_kst()
|
||||
via_cafe24 = set(MARKET_MAP.values()) # 카페24 마켓 통합관리 경유로 매출이 들어오는 쇼핑몰
|
||||
rows = []
|
||||
by_code = {m["code"]: m for m in store.list_marketplaces()}
|
||||
for adapter in all_adapters():
|
||||
m = by_code.get(adapter.code)
|
||||
if m is None:
|
||||
store_rows = store.list_marketplaces()
|
||||
groups = [{"code": m["code"], "name": m["name"]} for m in store_rows if m.get("is_group")]
|
||||
group_codes = {g["code"] for g in groups}
|
||||
for m in ordered_marketplaces(store_rows):
|
||||
code = m["code"]
|
||||
parent = m.get("parent_code") if m.get("parent_code") in group_codes else ""
|
||||
if m.get("is_group"):
|
||||
# 그룹(009) — 매출·수수료·연결 없음, 하위 쇼핑몰 합계는 매출 실적 화면에서
|
||||
rows.append({"code": code, "name": m["name"], "is_group": True, "is_custom": True, "parent": "",
|
||||
"children": sum(1 for x in store_rows if x.get("parent_code") == code)})
|
||||
continue
|
||||
st_row = statuses.get(adapter.code) or {}
|
||||
st = display_status(m, st_row, configured.get(adapter.code, False))
|
||||
cur_rate = calc.rate_on(rates, adapter.code, today)
|
||||
has_rate = bool(rates.get(adapter.code))
|
||||
adapter = get_adapter(code)
|
||||
if adapter is None:
|
||||
continue
|
||||
st_row = statuses.get(code) or {}
|
||||
st = display_status(m, st_row, configured.get(code, False))
|
||||
cur_rate = calc.rate_on(rates, code, today)
|
||||
has_rate = bool(rates.get(code))
|
||||
rows.append({
|
||||
"code": adapter.code, "name": m["name"], "enabled": m["enabled"],
|
||||
"code": code, "name": m["name"], "enabled": m["enabled"],
|
||||
"is_group": False, "is_custom": bool(m.get("is_custom")), "parent": parent,
|
||||
"include_in_sales": m["include_in_sales"], "manual_input": bool(m.get("manual_input")),
|
||||
"rate": _fmt_rate(cur_rate) if has_rate else "",
|
||||
"rate_history": len(rates.get(adapter.code, ())),
|
||||
"rate_history": len(rates.get(code, ())),
|
||||
"auth_type": adapter.auth_type, "shared": adapter.uses_shared_integration,
|
||||
"manual_only": adapter.manual_only,
|
||||
"implemented": adapter.implemented, "note": adapter.note, "docs_url": adapter.docs_url,
|
||||
"configured": configured.get(adapter.code, False),
|
||||
"via_cafe24": adapter.code in via_cafe24,
|
||||
"configured": configured.get(code, False),
|
||||
"via_cafe24": code in via_cafe24,
|
||||
"status": st, "status_label": STATUS_LABELS.get(st, st),
|
||||
"last_test_at": st_row.get("last_test_at"), "last_test_ok": st_row.get("last_test_ok"),
|
||||
"last_sync_at": st_row.get("last_sync_at"), "last_success_sync_at": st_row.get("last_success_sync_at"),
|
||||
"last_error": st_row.get("last_error") or "", "last_error_at": st_row.get("last_error_at"),
|
||||
})
|
||||
# 드래그 단위 — 그룹 없는 행 하나 또는 그룹 + 하위 쇼핑몰(하위는 그 안에서만 순서 변경)
|
||||
blocks: list[dict[str, Any]] = []
|
||||
for r in rows:
|
||||
if r["parent"] and blocks and blocks[-1]["row"]["code"] == r["parent"]:
|
||||
blocks[-1]["children"].append(r)
|
||||
else:
|
||||
blocks.append({"row": r, "children": []})
|
||||
stale = {v: n for v, n in key_versions_in_use.items() if key_info.get("current_version") and v != key_info["current_version"]}
|
||||
return {"rows": rows, "key_info": key_info, "key_versions_in_use": dict(key_versions_in_use),
|
||||
return {"rows": rows, "blocks": blocks, "groups": groups,
|
||||
"custom_ready": bool(store_rows) and "is_custom" in store_rows[0],
|
||||
"key_info": key_info, "key_versions_in_use": dict(key_versions_in_use),
|
||||
"stale_key_rows": sum(stale.values()), "sample_count": sample_count,
|
||||
"default_sample_from": today.replace(month=1, day=1).isoformat(),
|
||||
"default_sample_to": today.isoformat()}
|
||||
|
||||
@@ -30,6 +30,10 @@ class ManualMigrationNeeded(Exception):
|
||||
"""수동 입력(마이그레이션 002: perf_marketplaces.manual_input · perf_manual_sales)이 아직 적용되지 않음."""
|
||||
|
||||
|
||||
class CustomMigrationNeeded(Exception):
|
||||
"""직접 추가 쇼핑몰·그룹(마이그레이션 009: perf_marketplaces.is_custom · is_group · parent_code)이 아직 적용되지 않음."""
|
||||
|
||||
|
||||
def _set_formulas(conn: Any, table: str, key_col: str, date_col: str,
|
||||
rows: list[tuple[str, date, str | None]]) -> None:
|
||||
"""날짜 칸 계산식(마이그레이션 008) 덮어쓰기 — 식이 없으면 지움. 008 미적용이면 조용히 건너뛴다
|
||||
@@ -103,6 +107,72 @@ class PerformanceDBStore:
|
||||
raise ManualMigrationNeeded() from None
|
||||
return {k: _iso(v) for k, v in row.items()} if row else None
|
||||
|
||||
# ── 직접 추가 쇼핑몰·그룹(마이그레이션 009) ──
|
||||
def add_custom_marketplace(self, code: str, name: str, *, is_group: bool) -> dict[str, Any]:
|
||||
"""맨 뒤 순서로 추가. 쇼핑몰 = 수동 입력 전용(manual_input), 그룹 = 매출 없음(include_in_sales 꺼 둠)."""
|
||||
try:
|
||||
with self._pool.connection() as conn:
|
||||
row = conn.execute(
|
||||
"INSERT INTO perf_marketplaces (code, name, sort_order, manual_input, include_in_sales, is_custom, is_group) "
|
||||
"SELECT %s, %s, COALESCE(MAX(sort_order), 0) + 10, %s, %s, TRUE, %s FROM perf_marketplaces RETURNING *",
|
||||
(code, name, not is_group, not is_group, is_group),
|
||||
).fetchone()
|
||||
except pg_errors.UndefinedColumn:
|
||||
raise CustomMigrationNeeded() from None
|
||||
return {k: _iso(v) for k, v in row.items()}
|
||||
|
||||
def rename_marketplace(self, code: str, name: str) -> dict[str, Any] | None:
|
||||
with self._pool.connection() as conn:
|
||||
row = conn.execute("UPDATE perf_marketplaces SET name = %s WHERE code = %s RETURNING *", (name, code)).fetchone()
|
||||
return {k: _iso(v) for k, v in row.items()} if row else None
|
||||
|
||||
def set_marketplace_parent(self, code: str, parent_code: str | None) -> dict[str, Any] | None:
|
||||
try:
|
||||
with self._pool.connection() as conn:
|
||||
row = conn.execute("UPDATE perf_marketplaces SET parent_code = %s WHERE code = %s RETURNING *",
|
||||
(parent_code, code)).fetchone()
|
||||
except pg_errors.UndefinedColumn:
|
||||
raise CustomMigrationNeeded() from None
|
||||
return {k: _iso(v) for k, v in row.items()} if row else None
|
||||
|
||||
def delete_custom_marketplace(self, code: str) -> bool:
|
||||
"""직접 추가 행 삭제 — 그 쇼핑몰 수동 입력·수수료·상태·(테스트) 매출 행도 함께, 그룹이면 하위 쇼핑몰은 그룹 없음으로.
|
||||
기본 쇼핑몰(is_custom = FALSE)은 지우지 않는다."""
|
||||
with self._pool.connection() as conn:
|
||||
with conn.transaction():
|
||||
row = conn.execute("SELECT is_custom FROM perf_marketplaces WHERE code = %s FOR UPDATE", (code,)).fetchone()
|
||||
if not row or not row.get("is_custom"):
|
||||
return False
|
||||
conn.execute("UPDATE perf_marketplaces SET parent_code = NULL WHERE parent_code = %s", (code,))
|
||||
for table in ("perf_manual_sales", "perf_commission_rates", "perf_credentials",
|
||||
"perf_connection_status", "perf_sales_events", "perf_sync_runs"):
|
||||
conn.execute(f"DELETE FROM {table} WHERE marketplace_code = %s", (code,))
|
||||
conn.execute("DELETE FROM perf_marketplaces WHERE code = %s", (code,))
|
||||
return True
|
||||
|
||||
def manual_day_count(self, code: str) -> int:
|
||||
"""수동 입력해 둔 날 수 — 직접 추가 쇼핑몰 삭제 확인 문구용."""
|
||||
try:
|
||||
with self._pool.connection() as conn:
|
||||
row = conn.execute("SELECT COUNT(*) AS n FROM perf_manual_sales WHERE marketplace_code = %s",
|
||||
(code,)).fetchone()
|
||||
except pg_errors.UndefinedTable:
|
||||
return 0
|
||||
return int(row["n"] or 0)
|
||||
|
||||
def reorder_marketplaces(self, codes: list[str]) -> None:
|
||||
"""설정 화면 드래그 순서 — 받은 순서대로 sort_order 10, 20, … (목록에 없는 행은 그 뒤 예전 순서)."""
|
||||
with self._pool.connection() as conn:
|
||||
with conn.transaction():
|
||||
rest = [r["code"] for r in conn.execute(
|
||||
"SELECT code FROM perf_marketplaces WHERE NOT (code = ANY(%s)) ORDER BY sort_order, code", (codes,)
|
||||
).fetchall()]
|
||||
with conn.cursor() as cur:
|
||||
cur.executemany(
|
||||
"UPDATE perf_marketplaces SET sort_order = %s WHERE code = %s AND sort_order IS DISTINCT FROM %s",
|
||||
[((i + 1) * 10, c, (i + 1) * 10) for i, c in enumerate([*codes, *rest])],
|
||||
)
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# 수수료율 이력
|
||||
# ════════════════════════════════════════════════════════════
|
||||
|
||||
@@ -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()})
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261021a" />{% endblock %}
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261022a" />{% endblock %}
|
||||
|
||||
{#- ROAS 덧붙임 — "광고비(ROAS%)". 광고비가 없으면 아무것도 안 붙는다. -#}
|
||||
{%- macro roas(p) -%}{%- if p is not none -%}<span class="perf-roas">({{ "{:,}".format(p) }}%)</span>{%- endif -%}{%- endmacro -%}
|
||||
@@ -238,4 +238,4 @@
|
||||
} | tojson }}</script>
|
||||
{% endblock %}
|
||||
|
||||
{% block scripts %}<script src="/static/performance.js?v=20261021b" defer></script>{% endblock %}
|
||||
{% block scripts %}<script src="/static/performance.js?v=20261022a" defer></script>{% endblock %}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261021a" />{% endblock %}
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261022a" />{% endblock %}
|
||||
|
||||
{%- macro won(v) -%}
|
||||
{%- if v is none -%}<span class="perf-na"></span>
|
||||
@@ -139,7 +139,11 @@
|
||||
<thead>
|
||||
<tr>
|
||||
<th class="perf-th-label">{% if period_kind == 'year' %}월{% else %}날짜{% endif %}</th>
|
||||
{% for c in codes %}<th title="{{ names[c] }}{% if c in manual_codes %} — 수동 입력(날짜 칸을 눌러 입력){% endif %}">{{ short_names[c] }}{% if c in manual_codes %} <span class="perf-manual-mark" aria-label="수동 입력">✎</span>{% endif %}</th>{% endfor %}
|
||||
{#- 그룹(2026-10-22) — 그룹 열 = 보이는 하위 쇼핑몰 합계, ▾ 로 하위 열 접기/펴기(이 브라우저에 기억) -#}
|
||||
{% for col in cols %}{% set c = col.code %}
|
||||
{% if col.kind == 'group' %}<th class="perf-th-group" data-group-head="{{ c }}" title="{{ names[c] }} — 하위 쇼핑몰 {{ group_members[c] | length }}곳 매출 합계"><button type="button" class="perf-gtoggle" data-group-toggle="{{ c }}" aria-expanded="true" title="하위 쇼핑몰 접기/펴기">▾</button>{{ short_names[c] }}</th>
|
||||
{% else %}<th{% if col.kind == 'child' %} class="perf-th-child" data-group-child="{{ col.group }}"{% endif %} title="{{ names[c] }}{% if c in manual_codes %} — 수동 입력(날짜 칸을 눌러 입력){% endif %}">{{ short_names[c] }}{% if c in manual_codes %} <span class="perf-manual-mark" aria-label="수동 입력">✎</span>{% endif %}</th>{% endif %}
|
||||
{% endfor %}
|
||||
<th class="perf-th-total">{% if period_kind == 'year' %}월 합계{% else %}일 합계{% endif %}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
@@ -149,16 +153,20 @@
|
||||
<th class="perf-td-label" scope="row"{% if r.holiday %} title="{{ r.holiday }}"{% endif %}>
|
||||
{{ r.label }}{% if r.holiday %}<small class="perf-hol">{{ r.holiday }}</small>{% endif %}
|
||||
</th>
|
||||
{% for c in codes %}
|
||||
{% for col in cols %}
|
||||
{% set c = col.code %}
|
||||
{% set m = r.cells[c] %}
|
||||
{% if r.kind == 'day' and c in manual_codes %}
|
||||
{% set gattr %}{% if col.kind == 'child' %} data-group-child="{{ col.group }}"{% endif %}{% endset %}
|
||||
{% if col.kind == 'group' %}
|
||||
<td class="perf-num perf-td-group" data-group-cell="{{ c }}">{{ m3(m) }}</td>
|
||||
{% elif r.kind == 'day' and c in manual_codes %}
|
||||
{% set is_manual = (r.date ~ '|' ~ c) in manual_cells %}
|
||||
{% set fx = (formula_cells or {}).get(r.date ~ '|' ~ c) %}
|
||||
<td class="perf-num is-manual-cell{% if is_manual %} is-manual{% endif %}{% if fx %} is-formula{% endif %}" data-manual-code="{{ c }}" data-date="{{ r.date }}"
|
||||
<td class="perf-num is-manual-cell{% if is_manual %} is-manual{% endif %}{% if fx %} is-formula{% endif %}"{{ gattr }} data-manual-code="{{ c }}" data-date="{{ r.date }}"
|
||||
data-manual-value="{{ m.gross if is_manual else '' }}"{% if fx %} data-formula="{{ fx }}"{% endif %} tabindex="0"
|
||||
title="{% if fx %}계산식 {{ fx }} — 눌러 고치기{% elif is_manual %}수동 입력값 — 눌러 고치기(비우고 저장하면 API 값){% else %}눌러 총매출 직접 입력(1000+2000 같은 계산식도 됨){% endif %}">{{ m3(m) }}{{ adl(r.ads[c]) }}</td>
|
||||
{% else %}
|
||||
<td class="perf-num{% if r['from'] and (m.gross or m.commission) %} is-link{% endif %}"
|
||||
<td class="perf-num{% if r['from'] and (m.gross or m.commission) %} is-link{% endif %}"{{ gattr }}
|
||||
{% if r['from'] %}data-code="{{ c }}" data-from="{{ r['from'] }}" data-to="{{ r['to'] }}"{% endif %}>{{ m3(m) }}{{ adl(r.ads[c]) }}</td>
|
||||
{% endif %}
|
||||
{% endfor %}
|
||||
@@ -275,4 +283,4 @@
|
||||
} | tojson }}</script>
|
||||
{% endblock %}
|
||||
|
||||
{% block scripts %}<script src="/static/performance.js?v=20261021b" defer></script>{% endblock %}
|
||||
{% block scripts %}<script src="/static/performance.js?v=20261022a" defer></script>{% endblock %}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261021a" />{% endblock %}
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261022a" />{% endblock %}
|
||||
|
||||
{%- macro when(v) -%}{{ (v or '')[:16] | replace('T', ' ') or '—' }}{%- endmacro -%}
|
||||
|
||||
@@ -41,10 +41,30 @@
|
||||
{% 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>
|
||||
{# 드래그 단위(2026-10-22) = tbody 하나 — 그룹 없는 행 하나 또는 그룹 + 하위 쇼핑몰(하위는 그 안에서만 순서 변경) #}
|
||||
{% for b in blocks %}
|
||||
<tbody class="perf-sort-block{% if b.row.is_group %} is-group-block{% endif %}">
|
||||
{% for r in [b.row] + b.children %}
|
||||
{% if r.is_group %}
|
||||
<tr class="perf-group-row" data-code="{{ r.code }}" data-name="{{ r.name }}" data-group="1">
|
||||
<th class="perf-td-label" scope="row">
|
||||
{% if is_admin %}<span class="perf-drag" title="끌어서 순서 변경(그룹은 하위 쇼핑몰과 함께 움직임)" aria-hidden="true">⠿</span>{% endif %}
|
||||
<span class="perf-group-name">{{ r.name }}</span> <span class="perf-pill">그룹</span>
|
||||
</th>
|
||||
<td colspan="{{ 7 if is_admin else 2 }}" class="perf-muted">하위 쇼핑몰 {{ r.children }}곳 — 매출 실적에서 그룹 열 = 하위 쇼핑몰 매출 합계(수수료도 쇼핑몰별 요율로 계산해 합침)</td>
|
||||
{% if is_admin %}
|
||||
<td class="perf-nowrap">
|
||||
<button type="button" class="erp-btn erp-btn-ghost erp-btn-sm" data-act="rename">이름 변경</button>
|
||||
<button type="button" class="erp-btn erp-btn-ghost erp-btn-sm perf-del-btn" data-act="delete">삭제</button>
|
||||
</td>
|
||||
{% endif %}
|
||||
</tr>
|
||||
{% else %}
|
||||
<tr data-code="{{ r.code }}" data-name="{{ r.name }}"{% if r.parent %} class="perf-child-row" data-parent="{{ r.parent }}"{% endif %}{% if r.is_custom %} data-custom="1"{% endif %}>
|
||||
<th class="perf-td-label" scope="row">
|
||||
{% if is_admin %}<span class="perf-drag" title="끌어서 순서 변경" aria-hidden="true">⠿</span>{% endif %}
|
||||
{% if r.parent %}<span class="perf-child-mark" aria-hidden="true">└</span>{% endif %}{{ r.name }}{% if r.is_custom %} <span class="perf-pill" title="실적 설정에서 직접 추가한 쇼핑몰">직접 추가</span>{% endif %}
|
||||
</th>
|
||||
{% if is_admin %}
|
||||
<td class="perf-center">
|
||||
<label class="perf-switch" title="사용 여부">
|
||||
@@ -85,17 +105,37 @@
|
||||
<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">
|
||||
{% if not r.manual_only %}
|
||||
{% if r.is_custom %}
|
||||
<select class="erp-input perf-group-sel" data-act-group title="그룹 — 그룹으로 묶으면 매출 실적에서 그룹 열이 하위 쇼핑몰 매출 합계">
|
||||
<option value="">그룹 없음</option>
|
||||
{% for g in groups %}<option value="{{ g.code }}"{% if r.parent == g.code %} selected{% endif %}>{{ g.name }}</option>{% endfor %}
|
||||
</select>
|
||||
<button type="button" class="erp-btn erp-btn-ghost erp-btn-sm" data-act="rename">이름 변경</button>
|
||||
<button type="button" class="erp-btn erp-btn-ghost erp-btn-sm perf-del-btn" data-act="delete">삭제</button>
|
||||
{% elif not r.manual_only %}
|
||||
<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>
|
||||
{% endif %}
|
||||
</td>
|
||||
{% endif %}
|
||||
</tr>
|
||||
{% endif %}
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
{% endfor %}
|
||||
</table>
|
||||
</div>
|
||||
{% if is_admin %}
|
||||
<div class="perf-add-row">
|
||||
<button type="button" class="erp-btn erp-btn-outline erp-btn-sm" id="perf-add-shop"
|
||||
title="API 연동 없이 실적 일자별 표에 매출을 직접 입력하는 쇼핑몰을 추가">+ 쇼핑몰 추가(수동 입력)</button>
|
||||
<button type="button" class="erp-btn erp-btn-outline erp-btn-sm" id="perf-add-group"
|
||||
title="직접 추가한 쇼핑몰을 묶는 그룹 — 그룹 매출 = 하위 쇼핑몰 매출 합계">+ 그룹 추가</button>
|
||||
<span class="perf-muted">⠿ 를 끌어 순서를 바꾸면 매출 실적 열 순서에 그대로 반영됩니다. 그룹은 직접 추가한 쇼핑몰만 묶을 수 있습니다.</span>
|
||||
{% if not custom_ready %}<span class="perf-notice is-warn">쇼핑몰 직접 추가·그룹은 performance_db 마이그레이션 009
|
||||
(scripts/sql/performance_db_009_custom_marketplaces.sql)을 적용해야 쓸 수 있습니다.</span>{% endif %}
|
||||
</div>
|
||||
{% endif %}
|
||||
<p class="perf-foot perf-muted">
|
||||
수수료율은 <b>적용 시작일</b>부터 반영되고, 그 전 실적은 예전 요율로 계산됩니다(과거 실적이 바뀌지 않음).
|
||||
{% if is_admin %}상태에 마우스를 올리면 마지막 연결 테스트 시각과 최근 오류를 볼 수 있습니다.{% endif %}
|
||||
@@ -219,4 +259,4 @@
|
||||
</section>
|
||||
{% endblock %}
|
||||
|
||||
{% block scripts %}<script src="/static/performance.js?v=20261021b" defer></script>{% endblock %}
|
||||
{% block scripts %}<script src="/static/performance.js?v=20261022a" defer></script>{% endblock %}
|
||||
|
||||
@@ -0,0 +1,223 @@
|
||||
"""직접 추가 쇼핑몰(수동 입력 전용)·쇼핑몰 그룹·드래그 순서 (2026-10-22, 마이그레이션 009)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib
|
||||
from datetime import date
|
||||
|
||||
import pytest
|
||||
from fastapi import FastAPI
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from app.modules.performance import common, dashboard
|
||||
from app.modules.performance.adapters.registry import get_adapter
|
||||
|
||||
TODAY = date(2026, 10, 7)
|
||||
|
||||
|
||||
def _row(code, name, sort, **kw):
|
||||
return {"code": code, "name": name, "sort_order": sort, "enabled": True, "include_in_sales": True,
|
||||
"manual_input": False, "is_custom": False, "is_group": False, "parent_code": None, **kw}
|
||||
|
||||
|
||||
class _Store:
|
||||
"""카페24 + 그룹 '오프라인'(하위 custom_a·custom_b) + 네이버 — 그룹은 순서상 네이버 뒤, 하위는 맨 앞 sort_order 여도 그룹 자리."""
|
||||
|
||||
def __init__(self):
|
||||
self.rows = [
|
||||
_row("custom_b", "매장B", 5, manual_input=True, is_custom=True, parent_code="group_x"),
|
||||
_row("cafe24", "카페24", 10),
|
||||
_row("naver", "네이버", 20),
|
||||
_row("group_x", "오프라인", 30, is_custom=True, is_group=True, include_in_sales=False),
|
||||
_row("custom_a", "매장A", 40, manual_input=True, is_custom=True, parent_code="group_x"),
|
||||
_row("custom_c", "행사", 50, manual_input=True, is_custom=True),
|
||||
]
|
||||
self.manual = {(date(2026, 10, 5), "custom_a"): 100_000, (date(2026, 10, 5), "custom_b"): 50_000,
|
||||
(date(2026, 10, 6), "custom_a"): 7_000}
|
||||
self.order = None
|
||||
self.deleted = []
|
||||
|
||||
def list_marketplaces(self):
|
||||
return sorted((dict(r) for r in self.rows), key=lambda r: (r["sort_order"], r["code"]))
|
||||
|
||||
def daily_amounts(self, start, end, codes):
|
||||
base = {(date(2026, 10, 5), "cafe24"): 1_000_000, **self.manual}
|
||||
return {k: v for k, v in base.items() if start <= k[0] <= end and k[1] in codes}
|
||||
|
||||
def manual_amounts(self, start, end, codes, *, active_only=True):
|
||||
return {k: v for k, v in self.manual.items() if start <= k[0] <= end and k[1] in codes}
|
||||
|
||||
def rate_table(self):
|
||||
return {"custom_a": [(date(2000, 1, 1), 10)]}
|
||||
|
||||
def statuses(self):
|
||||
return {}
|
||||
|
||||
def last_update_at(self):
|
||||
return None
|
||||
|
||||
def running_codes(self):
|
||||
return []
|
||||
|
||||
def ad_amounts(self, start, end):
|
||||
return {}, {}
|
||||
|
||||
# ── 009 쓰기 ──
|
||||
def add_custom_marketplace(self, code, name, *, is_group):
|
||||
row = _row(code, name, max(r["sort_order"] for r in self.rows) + 10, manual_input=not is_group,
|
||||
include_in_sales=not is_group, is_custom=True, is_group=is_group)
|
||||
self.rows.append(row)
|
||||
return dict(row)
|
||||
|
||||
def _find(self, code):
|
||||
return next(r for r in self.rows if r["code"] == code)
|
||||
|
||||
def rename_marketplace(self, code, name):
|
||||
self._find(code)["name"] = name
|
||||
return dict(self._find(code))
|
||||
|
||||
def set_marketplace_parent(self, code, parent):
|
||||
self._find(code)["parent_code"] = parent
|
||||
return dict(self._find(code))
|
||||
|
||||
def delete_custom_marketplace(self, code):
|
||||
self.deleted.append(code)
|
||||
for r in self.rows:
|
||||
if r.get("parent_code") == code:
|
||||
r["parent_code"] = None
|
||||
self.rows = [r for r in self.rows if r["code"] != code]
|
||||
return True
|
||||
|
||||
def manual_day_count(self, code):
|
||||
return sum(1 for (_, c) in self.manual if c == code)
|
||||
|
||||
def reorder_marketplaces(self, codes):
|
||||
self.order = list(codes)
|
||||
for i, c in enumerate(codes):
|
||||
self._find(c)["sort_order"] = (i + 1) * 10
|
||||
|
||||
|
||||
def test_custom_code_gets_manual_only_adapter_and_group_has_none():
|
||||
a = get_adapter("custom_1234abcd")
|
||||
assert a is not None and a.manual_only and a.code == "custom_1234abcd"
|
||||
assert get_adapter("group_1234abcd") is None and get_adapter("nope") is None
|
||||
assert get_adapter("cafe24").code == "cafe24"
|
||||
|
||||
|
||||
def test_ordered_children_follow_group():
|
||||
codes = [m["code"] for m in dashboard.ordered_marketplaces(_Store().list_marketplaces())]
|
||||
assert codes == ["cafe24", "naver", "group_x", "custom_b", "custom_a", "custom_c"]
|
||||
|
||||
|
||||
def test_dashboard_group_column_sums_children_without_double_count():
|
||||
ctx = dashboard.build_dashboard(_Store(), kind="week", anchor=TODAY, today=TODAY)
|
||||
assert ctx["codes"] == ["cafe24", "naver", "custom_b", "custom_a", "custom_c"]
|
||||
assert [(c["code"], c["kind"]) for c in ctx["cols"]] == [
|
||||
("cafe24", "shop"), ("naver", "shop"), ("group_x", "group"), ("custom_b", "child"), ("custom_a", "child"),
|
||||
("custom_c", "shop")]
|
||||
assert ctx["group_members"] == {"group_x": ["custom_b", "custom_a"]}
|
||||
assert ctx["names"]["group_x"] == "오프라인"
|
||||
day5 = next(r for r in ctx["table"] if r.get("date") == "2026-10-05")
|
||||
# 그룹 = 매장B 50,000 + 매장A 100,000(수수료 10% = 10,000)
|
||||
assert day5["cells"]["group_x"] == {"gross": 150_000, "commission": 10_000, "net": 140_000}
|
||||
assert day5["total"]["gross"] == 1_150_000 # 일 합계에 그룹을 또 더하지 않음
|
||||
week = next(r for r in ctx["table"] if r["kind"] == "week")
|
||||
assert week["cells"]["group_x"]["gross"] == 157_000
|
||||
|
||||
|
||||
def test_dashboard_filter_hides_group_when_no_child_selected():
|
||||
ctx = dashboard.build_dashboard(_Store(), kind="week", anchor=TODAY, today=TODAY, selected=["cafe24", "custom_c"])
|
||||
assert [c["code"] for c in ctx["cols"]] == ["cafe24", "custom_c"] and ctx["group_members"] == {}
|
||||
ctx = dashboard.build_dashboard(_Store(), kind="week", anchor=TODAY, today=TODAY, selected=["custom_a"])
|
||||
assert [c["kind"] for c in ctx["cols"]] == ["group", "child"]
|
||||
day5 = next(r for r in ctx["table"] if r.get("date") == "2026-10-05")
|
||||
assert day5["cells"]["group_x"]["gross"] == 100_000 # 보이는 하위만 합침
|
||||
|
||||
|
||||
def test_settings_blocks_group_children_together():
|
||||
ctx = dashboard.build_settings(_Store(), configured={}, key_info={"ok": True}, key_versions_in_use={}, sample_count=0)
|
||||
assert [(b["row"]["code"], [c["code"] for c in b["children"]]) for b in ctx["blocks"]] == [
|
||||
("cafe24", []), ("naver", []), ("group_x", ["custom_b", "custom_a"]), ("custom_c", [])]
|
||||
grp = ctx["blocks"][2]["row"]
|
||||
assert grp["is_group"] and grp["children"] == 2
|
||||
a = ctx["blocks"][2]["children"][1]
|
||||
assert a["is_custom"] and a["manual_only"] and a["parent"] == "group_x" and a["status"] == "manual"
|
||||
assert ctx["groups"] == [{"code": "group_x", "name": "오프라인"}] and ctx["custom_ready"]
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def client(monkeypatch):
|
||||
perf_router = importlib.import_module("app.modules.performance.router")
|
||||
store = _Store()
|
||||
|
||||
class _Creds:
|
||||
def configured_codes(self, adapters):
|
||||
return {}
|
||||
|
||||
user = {"email": "king@x", "name": "King", "is_admin": True}
|
||||
monkeypatch.setattr(common, "guard", lambda request, admin=False: (store, user))
|
||||
monkeypatch.setattr(common, "require_store", lambda request, admin=False: (store, user))
|
||||
monkeypatch.setattr(common, "services", lambda request, st: (_Creds(), None))
|
||||
monkeypatch.setattr(perf_router, "today_kst", lambda: TODAY)
|
||||
app = FastAPI()
|
||||
app.include_router(perf_router.router)
|
||||
c = TestClient(app)
|
||||
c.store = store
|
||||
return c
|
||||
|
||||
|
||||
def test_api_add_rename_group_delete(client):
|
||||
store = client.store
|
||||
r = client.post("/performance/api/marketplaces", json={"kind": "shop", "name": " 새 매장 "})
|
||||
assert r.status_code == 200, r.text
|
||||
m = r.json()["marketplace"]
|
||||
assert m["code"].startswith("custom_") and m["name"] == "새 매장" and m["manual_input"] and m["is_custom"]
|
||||
assert client.post("/performance/api/marketplaces", json={"kind": "shop", "name": "카페24"}).status_code == 400
|
||||
assert client.post("/performance/api/marketplaces", json={"kind": "shop", "name": ""}).status_code == 400
|
||||
g = client.post("/performance/api/marketplaces", json={"kind": "group", "name": "온라인B"}).json()["marketplace"]
|
||||
assert g["code"].startswith("group_") and g["is_group"] and not g["include_in_sales"]
|
||||
|
||||
assert client.put(f"/performance/api/marketplaces/{m['code']}", json={"parent_code": g["code"]}).status_code == 200
|
||||
assert store._find(m["code"])["parent_code"] == g["code"]
|
||||
assert client.put(f"/performance/api/marketplaces/{m['code']}", json={"parent_code": "cafe24"}).status_code == 400
|
||||
assert client.put(f"/performance/api/marketplaces/{g['code']}", json={"parent_code": "group_x"}).status_code == 400
|
||||
assert client.put("/performance/api/marketplaces/cafe24", json={"name": "자사몰"}).status_code == 400
|
||||
assert client.put("/performance/api/marketplaces/cafe24", json={"parent_code": "group_x"}).status_code == 400
|
||||
assert client.put(f"/performance/api/marketplaces/{g['code']}", json={"name": "온라인C"}).json()["marketplace"]["name"] == "온라인C"
|
||||
assert client.put(f"/performance/api/marketplaces/{g['code']}", json={"enabled": False}).status_code == 400
|
||||
assert client.put(f"/performance/api/marketplaces/{m['code']}", json={"parent_code": ""}).status_code == 200
|
||||
assert store._find(m["code"])["parent_code"] is None
|
||||
|
||||
assert client.get("/performance/api/marketplaces/custom_a/manual-days").json() == {"days": 2}
|
||||
assert client.delete("/performance/api/marketplaces/cafe24").status_code == 400
|
||||
assert client.delete("/performance/api/marketplaces/group_x").status_code == 200
|
||||
assert store._find("custom_a")["parent_code"] is None and store.deleted == ["group_x"]
|
||||
|
||||
|
||||
def test_api_manual_sale_accepts_custom_shop(client):
|
||||
calls = []
|
||||
client.store.set_manual_sale = lambda code, d, amount, user="", formula=None: calls.append((code, d, amount))
|
||||
client.store.api_amount = lambda code, d: 0
|
||||
r = client.put("/performance/api/manual-sales/custom_a/2026-10-07", json={"amount": "1000+2000"})
|
||||
assert r.status_code == 200, r.text
|
||||
assert calls == [("custom_a", date(2026, 10, 7), 3000)] and r.json()["commission"] == 300
|
||||
assert client.put("/performance/api/manual-sales/group_x/2026-10-07", json={"amount": "1"}).status_code == 404
|
||||
|
||||
|
||||
def test_api_order(client):
|
||||
order = ["naver", "cafe24", "group_x", "custom_a", "custom_b", "custom_c"]
|
||||
assert client.put("/performance/api/marketplace-order", json={"codes": order + ["ghost"]}).status_code == 200
|
||||
assert client.store.order == order
|
||||
assert client.put("/performance/api/marketplace-order", json={"codes": ["naver", "naver"]}).status_code == 400
|
||||
ctx = dashboard.build_dashboard(client.store, kind="week", anchor=TODAY, today=TODAY)
|
||||
assert ctx["codes"] == ["naver", "cafe24", "custom_a", "custom_b", "custom_c"]
|
||||
|
||||
|
||||
def test_dashboard_page_renders_group_header_and_child_cells(client):
|
||||
html = client.get("/performance/?period=week&d=2026-10-07").text
|
||||
head = html.split("<thead>", 1)[1].split("</thead>", 1)[0]
|
||||
assert 'data-group-head="group_x"' in head and 'data-group-toggle="group_x"' in head and "오프라인" in head
|
||||
assert head.index('data-group-head="group_x"') < head.index('data-group-child="group_x"')
|
||||
body = html.split("<tbody>", 1)[1].split("</tbody>", 1)[0]
|
||||
assert 'data-group-cell="group_x"' in body and "150,000" in body
|
||||
assert 'data-group-child="group_x" data-manual-code="custom_a" data-date="2026-10-05"' in body
|
||||
@@ -385,3 +385,25 @@ td.is-link:hover { background: #eef2ff; text-decoration: underline; }
|
||||
/* [매출 업데이트] — 업데이트 중이면 "업데이트 중 · 진행 보기"(눌러서 진행 창 다시 열기), 살짝 깜박임 */
|
||||
#perf-sync-btn.is-running, #perf-ad-sync-btn.is-running { animation: perf-sync-pulse 1.6s ease-in-out infinite; }
|
||||
@keyframes perf-sync-pulse { 0%, 100% { opacity: 1; } 50% { opacity: .72; } }
|
||||
|
||||
/* 쇼핑몰 그룹(2026-10-22) — 그룹 열 = 하위 쇼핑몰 합계(굵게·옅은 보라), 하위 열은 ▾/▸ 로 접기/펴기 */
|
||||
.perf-main th.perf-th-group { background: #f1edfb; color: #4c2a9a; white-space: nowrap; }
|
||||
.perf-main .perf-row-day td.perf-td-group, .perf-main .perf-row-month td.perf-td-group { background: #f8f6fd; font-weight: 600; }
|
||||
.perf-main .perf-row-week td.perf-td-group { background: #ebe6f8; }
|
||||
.perf-main th.perf-th-child { color: #5b4a86; font-weight: 500; box-shadow: inset 0 -2px 0 #d9cff3; }
|
||||
.perf-gtoggle { border: 0; background: none; padding: 0 5px 0 0; margin: 0; font: inherit; font-size: 15px; color: inherit; cursor: pointer; line-height: 1; vertical-align: -1px; }
|
||||
.perf-gtoggle:hover { color: #1a56db; }
|
||||
.perf-main .is-gfolded[data-group-child] { display: none; }
|
||||
/* 설정 — 직접 추가·그룹·드래그 순서 */
|
||||
.perf-drag { display: inline-block; width: 14px; margin-right: 6px; color: #b5b5b5; cursor: grab; user-select: none; touch-action: none; }
|
||||
.perf-drag:hover { color: var(--color-deep-black); }
|
||||
body.perf-dragging, body.perf-dragging * { cursor: grabbing !important; user-select: none; }
|
||||
.perf-set-table .is-dragging > tr > *, .perf-set-table tr.is-dragging > * { background: #eef3ff; }
|
||||
.perf-set-table tbody.perf-sort-block + tbody.perf-sort-block > tr:first-child > * { border-top: 1px solid var(--perf-line); }
|
||||
.perf-group-row > * { background: #f8f6fd; }
|
||||
.perf-group-name { font-weight: 600; color: #4c2a9a; }
|
||||
.perf-child-row .perf-td-label { padding-left: 22px; }
|
||||
.perf-child-mark { color: #b5b5b5; margin-right: 4px; }
|
||||
.perf-group-sel { width: auto; min-width: 110px; height: 28px; padding: 2px 6px; font-size: 12.5px; margin-right: 4px; }
|
||||
.perf-del-btn { color: var(--perf-down); }
|
||||
.perf-add-row { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; margin-top: 10px; }
|
||||
|
||||
@@ -276,6 +276,30 @@
|
||||
b.addEventListener("click", function () { setMetric(b.dataset.metric); });
|
||||
});
|
||||
|
||||
// 쇼핑몰 그룹(2026-10-22) — 그룹 머리글 ▾ 로 하위 쇼핑몰 열 접기/펴기. 접은 그룹은 이 브라우저에 기억(localStorage).
|
||||
const GROUP_KEY = "perf_groups_collapsed";
|
||||
let collapsed = [];
|
||||
try { collapsed = JSON.parse(localStorage.getItem(GROUP_KEY) || "[]") || []; } catch (_) { collapsed = []; }
|
||||
function setGroup(code, fold) {
|
||||
root.querySelectorAll('[data-group-child="' + code + '"]').forEach(function (n) { n.classList.toggle("is-gfolded", fold); });
|
||||
root.querySelectorAll('[data-group-toggle="' + code + '"]').forEach(function (b) {
|
||||
b.setAttribute("aria-expanded", fold ? "false" : "true");
|
||||
b.textContent = fold ? "▸" : "▾";
|
||||
});
|
||||
root.querySelectorAll('[data-group-head="' + code + '"]').forEach(function (th) { th.classList.toggle("is-gfolded", fold); });
|
||||
}
|
||||
collapsed.forEach(function (code) { setGroup(code, true); });
|
||||
root.addEventListener("click", function (e) {
|
||||
const b = e.target.closest("[data-group-toggle]");
|
||||
if (!b) return;
|
||||
const code = b.dataset.groupToggle;
|
||||
const fold = b.getAttribute("aria-expanded") !== "false";
|
||||
setGroup(code, fold);
|
||||
collapsed = collapsed.filter(function (c) { return c !== code; });
|
||||
if (fold) collapsed.push(code);
|
||||
try { localStorage.setItem(GROUP_KEY, JSON.stringify(collapsed)); } catch (_) { /* 기억만 못 함 */ }
|
||||
});
|
||||
|
||||
// 수동 입력 엑셀 업로드 — 1열 날짜, 2열부터 쇼핑몰 이름 머리글. 값이 있는 칸만 반영(빈 칸은 기존 값 그대로).
|
||||
// 잘못된 칸이 있으면 서버가 아무것도 저장하지 않고 칸 위치 목록을 돌려준다.
|
||||
const uploadBtn = document.getElementById("perf-manual-upload");
|
||||
@@ -946,6 +970,102 @@
|
||||
if (btn.dataset.act === "rate") openRate(code, name, btn.dataset.hasHistory === "1");
|
||||
else if (btn.dataset.act === "creds") openCreds(code, name, base);
|
||||
else if (btn.dataset.act === "test") runTest(code, name, btn, base);
|
||||
else if (btn.dataset.act === "rename") openName(tr.dataset.group ? "그룹 이름 변경" : "쇼핑몰 이름 변경", name, function (v) {
|
||||
return api("PUT", "/performance/api/marketplaces/" + code, { name: v });
|
||||
});
|
||||
else if (btn.dataset.act === "delete") deleteCustom(code, name, !!tr.dataset.group);
|
||||
});
|
||||
|
||||
// ── 직접 추가 쇼핑몰·그룹(2026-10-22, 마이그레이션 009) ──
|
||||
function openName(title, value, save) {
|
||||
const m = openModal(title, { narrow: true });
|
||||
m.body.innerHTML = '<form class="perf-form"><div class="perf-form-row"><label for="perf-name-in">이름</label>' +
|
||||
'<input class="erp-input" id="perf-name-in" maxlength="30" required /></div></form>';
|
||||
const input = m.body.querySelector("#perf-name-in");
|
||||
input.value = value || "";
|
||||
const ok = el("button", { type: "button", class: "erp-btn erp-btn-primary" }, "저장");
|
||||
m.foot.appendChild(ok);
|
||||
async function submit() {
|
||||
const v = input.value.trim();
|
||||
if (!v) { input.focus(); return; }
|
||||
ok.disabled = true;
|
||||
try { await save(v); location.reload(); }
|
||||
catch (err) { ok.disabled = false; alertMsg(err.message); }
|
||||
}
|
||||
ok.addEventListener("click", submit);
|
||||
m.body.querySelector("form").addEventListener("submit", function (e) { e.preventDefault(); submit(); });
|
||||
input.focus();
|
||||
input.select();
|
||||
}
|
||||
const addShop = document.getElementById("perf-add-shop");
|
||||
if (addShop) addShop.addEventListener("click", function () {
|
||||
openName("쇼핑몰 추가(수동 입력)", "", function (v) { return api("POST", "/performance/api/marketplaces", { kind: "shop", name: v }); });
|
||||
});
|
||||
const addGroup = document.getElementById("perf-add-group");
|
||||
if (addGroup) addGroup.addEventListener("click", function () {
|
||||
openName("그룹 추가", "", function (v) { return api("POST", "/performance/api/marketplaces", { kind: "group", name: v }); });
|
||||
});
|
||||
async function deleteCustom(code, name, isGroup) {
|
||||
let msg;
|
||||
if (isGroup) msg = "그룹 [" + name + "]을 삭제할까요? 하위 쇼핑몰은 지워지지 않고 그룹 없음이 됩니다.";
|
||||
else {
|
||||
let days = 0;
|
||||
try { days = (await api("GET", "/performance/api/marketplaces/" + code + "/manual-days")).days || 0; } catch (_) { /* 확인 문구만 */ }
|
||||
msg = "쇼핑몰 [" + name + "]을 삭제할까요?" + (days ? " 입력해 둔 매출 " + fmt(days) + "일치와 수수료율도 함께 지워지며 되돌릴 수 없습니다." : "");
|
||||
}
|
||||
if (!(await confirmMsg(msg))) return;
|
||||
try { await api("DELETE", "/performance/api/marketplaces/" + code); location.reload(); }
|
||||
catch (err) { alertMsg("삭제 실패: " + err.message); }
|
||||
}
|
||||
root.querySelectorAll("select[data-act-group]").forEach(function (sel) {
|
||||
const before = sel.value;
|
||||
sel.addEventListener("change", async function () {
|
||||
sel.disabled = true;
|
||||
try {
|
||||
await api("PUT", "/performance/api/marketplaces/" + sel.closest("tr").dataset.code, { parent_code: sel.value });
|
||||
location.reload(); // 행이 그룹 아래로(또는 밖으로) 옮겨 그려진다
|
||||
} catch (err) { sel.value = before; sel.disabled = false; alertMsg("저장 실패: " + err.message); }
|
||||
});
|
||||
});
|
||||
|
||||
// ── 순서 드래그(⠿) — 그룹 없는 행·그룹(하위와 함께)은 tbody 단위, 하위 쇼핑몰은 그 그룹 안에서만.
|
||||
// 놓으면 화면 순서 그대로 PUT /api/marketplace-order → 매출 실적 열 순서.
|
||||
const setTable = root.querySelector(".perf-set-table");
|
||||
function currentOrder() {
|
||||
return Array.prototype.map.call(setTable.querySelectorAll("tbody.perf-sort-block > tr[data-code]"), function (tr) { return tr.dataset.code; });
|
||||
}
|
||||
if (setTable) setTable.addEventListener("pointerdown", function (e) {
|
||||
const handle = e.target.closest(".perf-drag");
|
||||
if (!handle || e.button !== 0) return;
|
||||
const tr = handle.closest("tr");
|
||||
const item = tr.classList.contains("perf-child-row") ? tr : tr.parentElement; // 하위 행 또는 tbody 블록
|
||||
const container = item.parentElement;
|
||||
const selector = item.tagName === "TR" ? "tr.perf-child-row" : "tbody.perf-sort-block";
|
||||
const start = currentOrder().join(",");
|
||||
e.preventDefault();
|
||||
item.classList.add("is-dragging");
|
||||
document.body.classList.add("perf-dragging");
|
||||
function move(ev) {
|
||||
const under = document.elementFromPoint(ev.clientX, ev.clientY);
|
||||
const target = under && under.closest(selector);
|
||||
if (!target || target === item || target.parentElement !== container) return;
|
||||
const box = target.getBoundingClientRect();
|
||||
container.insertBefore(item, ev.clientY < box.top + box.height / 2 ? target : target.nextSibling);
|
||||
}
|
||||
async function up() {
|
||||
document.removeEventListener("pointermove", move);
|
||||
document.removeEventListener("pointerup", up);
|
||||
document.removeEventListener("pointercancel", up);
|
||||
item.classList.remove("is-dragging");
|
||||
document.body.classList.remove("perf-dragging");
|
||||
const order = currentOrder();
|
||||
if (order.join(",") === start) return;
|
||||
try { await api("PUT", "/performance/api/marketplace-order", { codes: order }); }
|
||||
catch (err) { await alertMsg("순서 저장 실패: " + err.message); location.reload(); }
|
||||
}
|
||||
document.addEventListener("pointermove", move);
|
||||
document.addEventListener("pointerup", up);
|
||||
document.addEventListener("pointercancel", up);
|
||||
});
|
||||
|
||||
function today() {
|
||||
|
||||
@@ -268,6 +268,21 @@ docker exec postgres-db psql -U postgres -d performance_db -c "\d perf_ad_spend"
|
||||
되돌리기(계산식 표시만 사라짐, 금액 그대로):
|
||||
`docker exec postgres-db psql -U postgres -d performance_db -c "ALTER TABLE perf_manual_sales DROP COLUMN formula; ALTER TABLE perf_ad_spend DROP COLUMN formula;"`
|
||||
|
||||
## 실적 직접 추가 쇼핑몰·그룹 마이그레이션 (performance_db 009)
|
||||
|
||||
009는 `perf_marketplaces` 에 `is_custom`·`is_group`·`parent_code` 열 세 개만 추가한다(기존 행·값 그대로, 기존 쇼핑몰은 모두 FALSE/NULL, 다시 실행 가능).
|
||||
002 다음에 적용한다. 미적용이어도 앱은 그대로 동작한다 — 설정의 [쇼핑몰 추가]·[그룹 추가]만 503 안내(드래그 순서는 기존 `sort_order` 라 009 없이도 됨).
|
||||
|
||||
```bash
|
||||
cd /opt/www/main
|
||||
docker exec postgres-db pg_dump -U postgres performance_db > ~/performance_db_before_009_$(date +%Y%m%d%H%M).sql
|
||||
docker exec -i postgres-db psql -v ON_ERROR_STOP=1 -U postgres -d performance_db < scripts/sql/performance_db_009_custom_marketplaces.sql
|
||||
docker exec postgres-db psql -U postgres -d performance_db -c "\d perf_marketplaces"
|
||||
```
|
||||
|
||||
되돌리기(직접 추가한 쇼핑몰·그룹을 화면에서 먼저 삭제한 뒤):
|
||||
`docker exec postgres-db psql -U postgres -d performance_db -c "ALTER TABLE perf_marketplaces DROP COLUMN parent_code, DROP COLUMN is_group, DROP COLUMN is_custom;"`
|
||||
|
||||
## 회의록 작업 등록 표 — 작업 칸 마이그레이션 (026)
|
||||
|
||||
026은 `goal_meeting_tasks.parent_task_id` 열만 추가한다(기존 값 그대로, 다시 실행 가능). 025 뒤에 적용한다. 미적용이면 작업 칸을 고를 때만 503 안내.
|
||||
|
||||
@@ -266,6 +266,26 @@
|
||||
**아무것도 저장하지 않고** 칸 위치(B3 등) 목록을 돌려준다. 저장은 한 트랜잭션(`set_manual_sales_bulk`). 5MB·2,000일 상한.
|
||||
- 표 열 제목은 가운데·굵게·검정(`.perf-table thead th`).
|
||||
|
||||
### 직접 추가 쇼핑몰·그룹·순서 드래그(마이그레이션 009, 2026-10-22)
|
||||
|
||||
- **직접 추가 쇼핑몰** — 설정 쇼핑몰 표 아래 [+ 쇼핑몰 추가(수동 입력)](관리자, `POST /api/marketplaces {kind:"shop", name}`).
|
||||
코드 `custom_<16진 8자>`, `is_custom`, 맨 뒤 순서, 사용·매출 집계·수동 입력 켬. 어댑터는 `registry.get_adapter` 가 `custom_` 접두어면
|
||||
`CustomManualAdapter`(수동 입력 전용 — 매출 업데이트 제외·인증/연결 테스트 없음, 상태 "수동 입력")를 돌려준다. 이름(30자, 다른 쇼핑몰·그룹과
|
||||
겹치면 400 — 엑셀 업로드 머리글로 씀)·수수료율·날짜 칸 입력·엑셀 업로드는 기본 쇼핑몰과 같다. 행 오른쪽 [이름 변경]·[삭제]
|
||||
(`PUT /api/marketplaces/{code} {name}`, `DELETE` — 그 쇼핑몰의 수동 입력·수수료·상태·테스트 매출 행도 한 트랜잭션으로 지움,
|
||||
확인 문구에 입력해 둔 날 수 `GET /api/marketplaces/{code}/manual-days`). 기본 쇼핑몰은 이름·그룹·삭제 400(사용을 끈다).
|
||||
- **그룹** — [+ 그룹 추가](`kind:"group"`, 코드 `group_…`, `is_group`, `include_in_sales = FALSE` — 매출 없음, 회의록 머리 카드 등 매출 집계
|
||||
목록에 안 잡힘). 직접 추가 쇼핑몰 행의 **그룹 select** 로 묶는다(`PUT … {parent_code}` — 빈 값 = 그룹 없음, 그룹 안에 그룹·기본 쇼핑몰은 400).
|
||||
그룹 삭제 = 하위는 그룹 없음으로.
|
||||
- **매출 실적 표** — 그룹 열은 보이는 하위 쇼핑몰 열 바로 앞(`dashboard._group_columns` → 템플릿 `cols`), 칸 = 하위 쇼핑몰 Money 합
|
||||
(수수료는 쇼핑몰별 요율로 계산한 것의 합). 일 합계·KPI·그래프·월 누적은 쇼핑몰 기준 그대로(그룹을 또 더하지 않음). 머리글 ▾/▸ 로 하위 열
|
||||
접기/펴기(`data-group-child`, 접은 그룹은 localStorage `perf_groups_collapsed`). 쇼핑몰 필터로 하위를 하나도 안 고르면 그룹 열도 없음.
|
||||
- **순서** — 설정 표 ⠿ 를 끌어 놓으면(`performance.js` pointer 이벤트) 화면 순서 그대로 `PUT /api/marketplace-order {codes}` → `sort_order`
|
||||
10, 20, … 다시 매김(`reorder_marketplaces`). 드래그 단위는 tbody(그룹 없는 행 하나, 또는 그룹 + 하위) — 하위 쇼핑몰은 그 그룹 안에서만.
|
||||
화면 순서 = `dashboard.ordered_marketplaces`(sort_order 순, 그룹 바로 뒤에 하위) — 설정 표·매출 실적 열·필터 공통. 설정 표도 예전
|
||||
`registry` 순서 대신 이 순서(009 없어도 됨).
|
||||
- 테스트: `app/modules/performance/tests/test_custom_groups.py`, 화면 `tests/js/perf_groups.browser.test.js`(render_performance.py 의 `perf_*_groups.html`).
|
||||
|
||||
### 연동 단계 체크리스트(쇼핑몰마다)
|
||||
|
||||
- 공식 문서로 인증 방식·호출 제한·페이지네이션·주문 상태 코드·취소/반품 API·날짜 필드 확인
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
-- =====================================================================
|
||||
-- performance_db 마이그레이션 009 — 직접 추가 쇼핑몰(수동 입력 전용) + 쇼핑몰 그룹
|
||||
-- =====================================================================
|
||||
-- 멱등(idempotent). 열 세 개만 추가(기존 행·값 그대로, 기존 쇼핑몰은 모두 is_custom = FALSE). 002 다음에 적용.
|
||||
-- docker exec -i postgres-db psql -v ON_ERROR_STOP=1 -U postgres -d performance_db \
|
||||
-- < scripts/sql/performance_db_009_custom_marketplaces.sql
|
||||
--
|
||||
-- 왜(2026-10-22 사용자 요청):
|
||||
-- 1) 실적 설정에서 API 연동 없이 수동 입력만 하는 쇼핑몰을 사용자가 직접 추가(코드 custom_…, manual_input = TRUE).
|
||||
-- 2) 직접 추가한 쇼핑몰을 그룹으로 묶기 — 그룹 = 이 표의 행 하나(코드 group_…, is_group = TRUE, 매출 없음).
|
||||
-- 하위 쇼핑몰은 parent_code 로 그룹을 가리키고, 매출 실적 화면에서 그룹 열 = 하위 쇼핑몰 매출 합계.
|
||||
-- 그룹 행은 include_in_sales = FALSE 로 넣는다(매출 집계 쇼핑몰 목록 — 회의록 머리 카드 등 — 에 안 잡히게).
|
||||
-- 3) 쇼핑몰 순서는 설정 화면 드래그로 sort_order 를 다시 매긴다(열 추가 없음).
|
||||
-- 되돌리기(실행 전 백업): 직접 추가 쇼핑몰·그룹 행과 그 수동 입력·수수료 행을 먼저 지운 뒤
|
||||
-- ALTER TABLE perf_marketplaces DROP COLUMN parent_code, DROP COLUMN is_group, DROP COLUMN is_custom;
|
||||
-- =====================================================================
|
||||
BEGIN;
|
||||
|
||||
ALTER TABLE perf_marketplaces ADD COLUMN IF NOT EXISTS is_custom BOOLEAN NOT NULL DEFAULT FALSE;
|
||||
ALTER TABLE perf_marketplaces ADD COLUMN IF NOT EXISTS is_group BOOLEAN NOT NULL DEFAULT FALSE;
|
||||
ALTER TABLE perf_marketplaces ADD COLUMN IF NOT EXISTS parent_code TEXT
|
||||
REFERENCES perf_marketplaces(code) ON DELETE SET NULL;
|
||||
COMMENT ON COLUMN perf_marketplaces.is_custom IS '실적 설정에서 사용자가 직접 추가한 행(수동 입력 전용 쇼핑몰 또는 그룹) — 이름 변경·삭제 가능';
|
||||
COMMENT ON COLUMN perf_marketplaces.is_group IS '쇼핑몰 그룹 — 매출 없음, 매출 실적 화면에서 하위 쇼핑몰(parent_code) 매출 합계';
|
||||
COMMENT ON COLUMN perf_marketplaces.parent_code IS '속한 그룹 코드(직접 추가 쇼핑몰만). NULL = 그룹 없음';
|
||||
CREATE INDEX IF NOT EXISTS idx_perf_marketplaces_parent ON perf_marketplaces (parent_code) WHERE parent_code IS NOT NULL;
|
||||
|
||||
COMMIT;
|
||||
SELECT code, name, sort_order, is_custom, is_group, parent_code FROM perf_marketplaces ORDER BY sort_order;
|
||||
@@ -0,0 +1,120 @@
|
||||
// 실적 쇼핑몰 그룹·드래그 순서(2026-10-22) — 실제 브라우저(Chromium).
|
||||
// python tests/js/render_performance.py
|
||||
// NODE_PATH=<playwright 경로> PJ_TEST_BROWSER=<Chrome 경로> node tests/js/perf_groups.browser.test.js
|
||||
// 매출 실적: 그룹 열 = 하위 합계, ▾ 누르면 하위 열이 숨고(▸) 새로고침해도 기억.
|
||||
// 설정: ⠿ 를 끌어 놓으면 화면 순서 그대로 PUT /api/marketplace-order — 그룹은 하위와 함께, 하위는 그룹 안에서만.
|
||||
const fs = require("fs"), path = require("path");
|
||||
const { chromium } = require("playwright");
|
||||
const ROOT = path.join(__dirname, "..", "..");
|
||||
const fails = [];
|
||||
function check(name, cond, extra) {
|
||||
if (cond) console.log("PASS " + name);
|
||||
else { console.log("FAIL " + name + (extra !== undefined ? " → " + JSON.stringify(extra) : "")); fails.push(name); }
|
||||
}
|
||||
function page(file) {
|
||||
const css = fs.readFileSync(path.join(ROOT, "app", "static", "performance.css"), "utf8");
|
||||
const js = fs.readFileSync(path.join(ROOT, "app", "static", "performance.js"), "utf8");
|
||||
return fs.readFileSync(path.join(__dirname, ".out", file), "utf8")
|
||||
.replace(/<link rel="stylesheet" href="\/static\/performance\.css[^"]*" \/>/, function () { return "<style>" + css + "</style>"; })
|
||||
.replace(/<script src="\/static\/performance\.js[^"]*" defer><\/script>/, function () { return "<script>" + js + "</script>"; });
|
||||
}
|
||||
|
||||
(async function () {
|
||||
const browser = await chromium.launch(process.env.PJ_TEST_BROWSER ? { executablePath: process.env.PJ_TEST_BROWSER } : {});
|
||||
try {
|
||||
// ── 매출 실적 — 그룹 열 접기/펴기 ──
|
||||
const ctx = await browser.newContext({ viewport: { width: 1400, height: 900 } });
|
||||
const p = await ctx.newPage();
|
||||
await p.route("**/*", function (r) { r.fulfill({ status: 200, contentType: "text/html; charset=utf-8", body: page("perf_dash_groups.html") }); });
|
||||
await p.goto("http://perf.test/performance/");
|
||||
const heads = function () {
|
||||
return p.evaluate(function () {
|
||||
return Array.from(document.querySelectorAll(".perf-main thead th")).filter(function (th) { return th.offsetParent !== null; })
|
||||
.map(function (th) { return th.textContent.replace(/\s+/g, " ").trim(); });
|
||||
});
|
||||
};
|
||||
const h0 = await heads();
|
||||
check("그룹 열이 하위 열 바로 앞", JSON.stringify(h0.slice(1, 7)) === JSON.stringify(["카페24", "네이버", "▾오프라인", "매장A ✎", "매장B ✎", "행사 ✎"]), h0);
|
||||
const g5 = await p.evaluate(function () {
|
||||
const tr = document.querySelector('td[data-manual-code="custom_a"][data-date="2026-10-05"]').closest("tr");
|
||||
return tr.querySelector('[data-group-cell="group_off"] .v-gross').textContent.trim();
|
||||
});
|
||||
check("그룹 칸 = 하위 합계(30,000 + 12,000)", g5 === "42,000", g5);
|
||||
await p.click('[data-group-toggle="group_off"]');
|
||||
const h1 = await heads();
|
||||
const hiddenTd = await p.evaluate(function () {
|
||||
return Array.from(document.querySelectorAll('td[data-group-child="group_off"]')).every(function (td) { return td.offsetParent === null; });
|
||||
});
|
||||
check("▾ 누르면 하위 열(머리글·칸) 숨김, ▸ 표시", h1.indexOf("매장A ✎") < 0 && h1.indexOf("▸오프라인") >= 0 && hiddenTd && h1.indexOf("행사 ✎") >= 0, h1);
|
||||
await p.reload();
|
||||
const h2 = await heads();
|
||||
check("접은 상태 새로고침 후에도 기억", h2.indexOf("매장A ✎") < 0 && h2.indexOf("▸오프라인") >= 0, h2);
|
||||
await p.click('[data-group-toggle="group_off"]');
|
||||
check("다시 누르면 펼침", (await heads()).indexOf("매장B ✎") >= 0);
|
||||
await ctx.close();
|
||||
|
||||
// ── 설정 — 드래그 순서 ──
|
||||
const sp = await browser.newPage({ viewport: { width: 1500, height: 1000 } });
|
||||
const puts = [];
|
||||
let reloads = 0; const pages = [];
|
||||
await sp.route("**/*", async function (r) {
|
||||
const req = r.request(), url = new URL(req.url()).pathname;
|
||||
if (url === "/favicon.ico" || url.startsWith("/static/")) { r.fulfill({ status: 404, body: "" }); return; }
|
||||
if (!url.startsWith("/performance/api/")) {
|
||||
reloads++; pages.push(url);
|
||||
r.fulfill({ status: 200, contentType: "text/html; charset=utf-8", body: page("perf_settings_groups.html") });
|
||||
return;
|
||||
}
|
||||
puts.push({ method: req.method(), url: url, body: req.postData() ? JSON.parse(req.postData()) : null });
|
||||
r.fulfill({ status: 200, contentType: "application/json", body: "{}" });
|
||||
});
|
||||
await sp.goto("http://perf.test/performance/settings");
|
||||
const order = function () {
|
||||
return sp.evaluate(function () {
|
||||
return Array.from(document.querySelectorAll(".perf-set-table tbody.perf-sort-block > tr[data-code]")).map(function (tr) { return tr.dataset.code; });
|
||||
});
|
||||
};
|
||||
check("설정 처음 순서(그룹 뒤에 하위)", JSON.stringify(await order()) === JSON.stringify(["cafe24", "naver", "group_off", "custom_a", "custom_b", "custom_c"]), await order());
|
||||
async function drag(fromCode, toCode, where) {
|
||||
const h = await sp.locator('tr[data-code="' + fromCode + '"] .perf-drag').boundingBox();
|
||||
const t = await sp.locator('tr[data-code="' + toCode + '"]').boundingBox();
|
||||
await sp.mouse.move(h.x + h.width / 2, h.y + h.height / 2);
|
||||
await sp.mouse.down();
|
||||
const y = where === "above" ? t.y + 3 : t.y + t.height - 3;
|
||||
await sp.mouse.move(h.x + h.width / 2, (h.y + y) / 2, { steps: 4 });
|
||||
await sp.mouse.move(h.x + h.width / 2, y, { steps: 6 });
|
||||
await sp.mouse.up();
|
||||
await sp.waitForTimeout(100);
|
||||
}
|
||||
// 그룹(하위 포함)을 카페24 위로
|
||||
await drag("group_off", "cafe24", "above");
|
||||
const o1 = await order();
|
||||
check("그룹 블록 통째로 이동", JSON.stringify(o1) === JSON.stringify(["group_off", "custom_a", "custom_b", "cafe24", "naver", "custom_c"]), o1);
|
||||
const last = puts[puts.length - 1];
|
||||
check("놓으면 화면 순서 그대로 저장", last && last.method === "PUT" && last.url === "/performance/api/marketplace-order" &&
|
||||
JSON.stringify(last.body.codes) === JSON.stringify(o1), last);
|
||||
// 하위끼리 순서 변경 — 그룹 행 위로는 못 나감
|
||||
await drag("custom_b", "custom_a", "above");
|
||||
const o2 = await order();
|
||||
check("하위 쇼핑몰은 그룹 안에서 순서 변경", JSON.stringify(o2) === JSON.stringify(["group_off", "custom_b", "custom_a", "cafe24", "naver", "custom_c"]), o2);
|
||||
const n = puts.length;
|
||||
await drag("custom_a", "naver", "below");
|
||||
check("하위 쇼핑몰은 그룹 밖으로 안 나감(저장 없음)", JSON.stringify(await order()) === JSON.stringify(o2) && puts.length === n, await order());
|
||||
// 그룹 지정 select → PUT parent_code
|
||||
check("순서 저장은 새로고침 없음", reloads === 1, pages);
|
||||
await sp.selectOption('tr[data-code="custom_c"] select[data-act-group]', "group_off");
|
||||
await sp.waitForTimeout(300);
|
||||
const g = puts[puts.length - 1];
|
||||
check("그룹 지정 → PUT parent_code 후 새로고침", g && g.url === "/performance/api/marketplaces/custom_c" && g.body.parent_code === "group_off" && reloads === 2, { g: g, reloads: reloads });
|
||||
const wraps = await sp.evaluate(function () {
|
||||
const t = document.querySelector(".perf-set-table");
|
||||
return t.scrollWidth <= t.parentElement.clientWidth + 1;
|
||||
});
|
||||
check("설정 표가 1500px 에서 가로 스크롤 없음", wraps);
|
||||
await sp.screenshot({ path: path.join(__dirname, ".out", "perf_settings_groups.png"), fullPage: true });
|
||||
} finally {
|
||||
await browser.close();
|
||||
}
|
||||
console.log(fails.length ? "\n" + fails.length + " FAIL" : "\nALL PASS");
|
||||
process.exit(fails.length ? 1 : 0);
|
||||
})();
|
||||
@@ -273,7 +273,8 @@ function gross(td) { return td.querySelector(".v-gross").textContent.trim(); }
|
||||
const heads = Array.from(e.d.querySelectorAll(SHOP + " thead th")).map(function (th) { return th.textContent.trim(); });
|
||||
check("[설정] '수동 입력' 열(매출 집계 다음)", heads.indexOf("수동 입력") === heads.indexOf("매출 집계") + 1, heads);
|
||||
const rows = Array.from(e.d.querySelectorAll(SHOP + " tbody tr")).map(function (tr) { return tr.dataset.code; });
|
||||
check("[설정] 쇼핑몰 순서 = 어댑터 등록 순서(003 열 순서)", rows.join(",") === "cafe24,naver,coupang,ohouse,gmarket,kakao,gsshop,elevenst,lotteon,toss", rows);
|
||||
// 2026-10-22 — 설정 표 순서 = DB sort_order(⠿ 드래그로 바꾸는 순서, 매출 실적 열과 같음). 예전엔 어댑터 등록 순서였다.
|
||||
check("[설정] 쇼핑몰 순서 = DB sort_order(드래그 순서)", rows.join(",") === "cafe24,naver,coupang,toss,gsshop,elevenst,ohouse,gmarket,kakao,lotteon", rows);
|
||||
const adRows = Array.from(e.d.querySelectorAll("#perf-ad-sources tbody tr")).map(function (tr) { return tr.dataset.code + ":" + tr.dataset.api; });
|
||||
check("[설정] 광고 API 연동 표는 따로(구글 광고, /api/ad-sources/)", adRows.join(",") === "google:ad-sources", adRows);
|
||||
const box = e.d.querySelector('tr[data-code="coupang"] input[data-field="manual_input"]');
|
||||
|
||||
@@ -91,6 +91,7 @@ def main() -> None:
|
||||
actx = build_ad_dashboard(FakeStore(), kind="month", anchor=date(2026, 10, 7), today=date(2026, 10, 7),
|
||||
sales_codes=["cafe24", "coupang"])
|
||||
actx["ad_sync_sources"] = [{"code": "google", "name": "구글 광고"}] # [구글 광고 불러오기]
|
||||
actx["auto_sync"] = ctx["auto_sync"] # 광고비 탭도 다음 업데이트 카운트다운(router._auto_sync_ctx)
|
||||
html = e.get_template("performance/ads.html").render(**base, active_tab="ads", **actx)
|
||||
with open(os.path.join(OUT_DIR, "perf_ads.html"), "w", encoding="utf-8") as f:
|
||||
f.write(html)
|
||||
@@ -102,8 +103,43 @@ def main() -> None:
|
||||
html = e.get_template("performance/settings.html").render(**base, active_tab="settings", **sctx)
|
||||
with open(os.path.join(OUT_DIR, "perf_settings.html"), "w", encoding="utf-8") as f:
|
||||
f.write(html)
|
||||
# 직접 추가 쇼핑몰·그룹(2026-10-22) — perf_dash_groups.html · perf_settings_groups.html (perf_groups.browser.test.js)
|
||||
gctx = build_dashboard(GroupStore(), kind="week", anchor=date(2026, 10, 7), today=date(2026, 10, 7))
|
||||
gctx["auto_sync"] = None
|
||||
html = e.get_template("performance/index.html").render(**base, active_tab="dashboard", metric="gross", **gctx)
|
||||
with open(os.path.join(OUT_DIR, "perf_dash_groups.html"), "w", encoding="utf-8") as f:
|
||||
f.write(html)
|
||||
gsctx = build_settings(GroupStore(), configured={}, key_info={"ok": True}, key_versions_in_use={}, sample_count=0)
|
||||
gsctx.update(ad_api_ready=True, ad_sources=[])
|
||||
html = e.get_template("performance/settings.html").render(**base, active_tab="settings", **gsctx)
|
||||
with open(os.path.join(OUT_DIR, "perf_settings_groups.html"), "w", encoding="utf-8") as f:
|
||||
f.write(html)
|
||||
print("ok")
|
||||
|
||||
|
||||
class GroupStore(FakeStore):
|
||||
"""카페24·네이버 + 그룹 '오프라인'(매장A·매장B) + 그룹 없는 직접 추가 '행사'."""
|
||||
|
||||
def list_marketplaces(self):
|
||||
rows = [{"code": c, "name": NAMES[c], "enabled": True, "include_in_sales": True, "sort_order": i * 10,
|
||||
"manual_input": False, "is_custom": False, "is_group": False, "parent_code": None}
|
||||
for i, c in enumerate(("cafe24", "naver"), 1)]
|
||||
custom = {"enabled": True, "include_in_sales": True, "manual_input": True, "is_custom": True, "is_group": False}
|
||||
return rows + [
|
||||
{"code": "group_off", "name": "오프라인", "sort_order": 30, "enabled": True, "include_in_sales": False,
|
||||
"manual_input": False, "is_custom": True, "is_group": True, "parent_code": None},
|
||||
{**custom, "code": "custom_a", "name": "매장A", "sort_order": 40, "parent_code": "group_off"},
|
||||
{**custom, "code": "custom_b", "name": "매장B", "sort_order": 50, "parent_code": "group_off"},
|
||||
{**custom, "code": "custom_c", "name": "행사", "sort_order": 60, "parent_code": None},
|
||||
]
|
||||
|
||||
def manual_amounts(self, start, end, codes, *, active_only=True):
|
||||
manual = {(date(2026, 10, 5), "custom_a"): 30000, (date(2026, 10, 5), "custom_b"): 12000}
|
||||
return {k: v for k, v in manual.items() if start <= k[0] <= end and k[1] in codes}
|
||||
|
||||
def ad_amounts(self, start, end):
|
||||
return {}, {}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
||||
Reference in New Issue
Block a user