feat(실적): 틱톡 탭과 틱톡 광고 API 연동
광고비 탭 오른쪽에 틱톡 탭 추가. 일자별 ROAS, 광고비, 매출을 광고비 탭과 같은 틀로 보여 준다. 실적 설정 광고 API 연동에 틱톡 추가(광고 계정 ID, 액세스 토큰, 선택 틱톡샵 ID). 채널 표(CHANNELS)에 넣지 않아 매출 실적·광고비 탭 합계에는 들어가지 않는다. DB 변경 없음. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -22,12 +22,13 @@ from __future__ import annotations
|
||||
import csv
|
||||
import io
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import date
|
||||
from datetime import date, timedelta
|
||||
from decimal import ROUND_HALF_UP, Decimal, InvalidOperation
|
||||
from typing import Any, Callable, Mapping, Sequence
|
||||
|
||||
from . import calc
|
||||
from .ad_sources.base import ACCOUNTS_KEY
|
||||
from .ad_sources.tiktok_ads import M_REVENUE as TIKTOK_REVENUE_KEY
|
||||
from .manual_upload import MAX_AMOUNT, MAX_DATA_ROWS, MAX_ERRORS, MAX_FILE_BYTES, UploadError, parse_amount, parse_date
|
||||
|
||||
# 채널 — 표 열 순서(2026-10-14 사용자 지정). 쇼핑몰 채널 코드는 실적 쇼핑몰 코드와 같다(쿠팡(윙)만 coupang_wing ↔ 매출 coupang).
|
||||
@@ -57,6 +58,7 @@ NO_ROAS = FILE_ROAS # 예전 이름(계산 안 하는 채널)
|
||||
NO_SALES = frozenset({"etc"}) # 매출 쇼핑몰이 없는 채널 — ROAS 를 계산하지 않고 매출 탭 광고비 줄에도 안 나온다
|
||||
ROAS_SALES_CODE: dict[str, str] = {c: c for c in CHANNEL_CODES if c not in FILE_ROAS and c not in NO_SALES}
|
||||
ROAS_SALES_CODE["coupang_wing"] = "coupang"
|
||||
TIKTOK = "tiktok" # 광고 API 채널이지만 CHANNELS 에 없다 — 틱톡 탭(build_tiktok_dashboard)에서만 보인다
|
||||
|
||||
|
||||
def roas(sales: int, spend: int) -> int | None:
|
||||
@@ -476,6 +478,85 @@ def detail_tabs(rows: list[dict[str, Any]]) -> dict[str, Any]:
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# 화면 데이터
|
||||
# ════════════════════════════════════════════════════════════
|
||||
def _period_word(period: Any, today: date) -> str:
|
||||
"""KPI 이름 앞 말 — 이번달·해당 월 등."""
|
||||
return {"day": "오늘" if period.start == today else "해당일",
|
||||
"week": "이번주" if period.start <= today <= period.end else "해당 주",
|
||||
"month": "이번달" if period.start <= today <= period.end else "해당 월",
|
||||
"year": "올해" if period.start <= today <= period.end else "해당 연도",
|
||||
"custom": "선택 기간"}[period.kind]
|
||||
|
||||
|
||||
def _period_nav(period: Any, today: date) -> dict[str, Any]:
|
||||
"""기간 이동 화살표·빠른 선택(이번달·올해만 — 2026-10-26 오늘·이번주 버튼 삭제, 매출 실적과 같게)."""
|
||||
def url(k: str, anchor_d: date | None = None, start: date | None = None, end: date | None = None) -> str:
|
||||
if k == "custom":
|
||||
return f"?period=custom&from={start.isoformat()}&to={end.isoformat()}"
|
||||
return f"?period={k}&d={anchor_d.isoformat()}"
|
||||
|
||||
if period.kind == "custom":
|
||||
length = timedelta(days=period.days)
|
||||
prev_url = url("custom", start=period.start - length, end=period.start - timedelta(days=1))
|
||||
next_url = url("custom", start=period.end + timedelta(days=1), end=period.end + length)
|
||||
else:
|
||||
prev_url, next_url = url(period.kind, period.prev_anchor), url(period.kind, period.next_anchor)
|
||||
return {"prev": prev_url, "next": next_url, "quick": [
|
||||
{"label": "이번달", "url": url("month", today), "active": period.kind == "month" and period.start <= today <= period.end},
|
||||
{"label": "올해", "url": url("year", today), "active": period.kind == "year" and period.start <= today <= period.end},
|
||||
]}
|
||||
|
||||
|
||||
def build_tiktok_dashboard(store: Any, *, kind: str, anchor: date, today: date, custom_from: date | None = None,
|
||||
custom_to: date | None = None, holidays: Mapping[str, str] | None = None) -> dict[str, Any]:
|
||||
"""틱톡 탭(2026-11-05) — 광고비 탭과 같은 기간 이동·표·그래프, 열 = ROAS·광고비·매출. 광고 API 가 저장한 perf_ad_spend 만 읽는다.
|
||||
CHANNELS 에 없어 광고비 탭·매출 실적 합계에는 들어가지 않는다."""
|
||||
period = calc.resolve_period(kind, anchor, custom_from=custom_from, custom_to=custom_to)
|
||||
cmp_start, cmp_end, cmp_label = period.compare_range(today)
|
||||
ref = period.end if period.end < today else today if period.start <= today else period.start
|
||||
year_period = calc.resolve_period("year", ref)
|
||||
migration_needed = False
|
||||
try:
|
||||
rows = store.ad_details(TIKTOK, min(period.start, cmp_start, year_period.start), max(period.end, year_period.end))
|
||||
except AdMigrationNeeded:
|
||||
rows, migration_needed = [], True
|
||||
cells: dict[tuple[date, str], calc.Money] = {}
|
||||
for r in rows:
|
||||
d = date.fromisoformat(r["date"])
|
||||
cells[(d, "spend")] = calc.Money(gross=int(r["amount"] or 0))
|
||||
cells[(d, "sales")] = calc.Money(gross=int((r["metrics"] or {}).get(TIKTOK_REVENUE_KEY) or 0))
|
||||
|
||||
table = calc.main_table(period, ("spend", "sales"), cells, today=today, holidays=holidays)
|
||||
for row in table:
|
||||
row["roas"] = roas(row["cells"]["sales"]["gross"], row["cells"]["spend"]["gross"])
|
||||
cur = {c: calc.sum_range(cells, [c], period.start, period.end).gross for c in ("spend", "sales")}
|
||||
prev = {c: calc.sum_range(cells, [c], cmp_start, cmp_end).gross for c in ("spend", "sales")}
|
||||
word = _period_word(period, today)
|
||||
spend_y = calc.year_months(year_period.start.year, ["spend"], cells, today=today)
|
||||
sales_y = calc.year_months(year_period.start.year, ["sales"], cells, today=today)
|
||||
year_rows = [{"label": a["label"], "future": a["future"], "spend": a["gross"], "sales": b["gross"],
|
||||
"roas": None if a["future"] else roas(b["gross"], a["gross"])}
|
||||
for a, b in zip(spend_y["rows"], sales_y["rows"])]
|
||||
return {
|
||||
"nav": _period_nav(period, today),
|
||||
"period": period,
|
||||
"period_kind": period.kind,
|
||||
"today": today.isoformat(),
|
||||
"kpis": [
|
||||
{"key": "spend", "label": f"{word} 광고비", "value": cur["spend"], "primary": True,
|
||||
"delta": calc.pct_change(cur["spend"], prev["spend"]), "cmp": cmp_label, "invert": True},
|
||||
{"key": "sales", "label": f"{word} 매출", "value": cur["sales"],
|
||||
"delta": calc.pct_change(cur["sales"], prev["sales"]), "cmp": cmp_label},
|
||||
{"key": "roas", "label": f"{word} ROAS", "pct": roas(cur["sales"], cur["spend"])},
|
||||
],
|
||||
"table": table,
|
||||
"chart_sales": calc.daily_series(period, ["sales"], cells),
|
||||
"chart_spend": calc.daily_series(period, ["spend"], cells),
|
||||
"year": {"year": year_period.start.year, "rows": year_rows, "spend": spend_y["total"]["gross"], "sales": sales_y["total"]["gross"],
|
||||
"roas": roas(sales_y["total"]["gross"], spend_y["total"]["gross"])},
|
||||
"migration_needed": migration_needed,
|
||||
}
|
||||
|
||||
|
||||
def build_ad_dashboard(store: Any, *, kind: str, anchor: date, today: date,
|
||||
custom_from: date | None = None, custom_to: date | None = None,
|
||||
holidays: Mapping[str, str] | None = None,
|
||||
@@ -522,11 +603,7 @@ def build_ad_dashboard(store: Any, *, kind: str, anchor: date, today: date,
|
||||
sales_total = sales_sum(total_codes, period.start, period.end) if total_codes else None
|
||||
ratio = round(cur.gross / sales_total * 100, 1) if sales_total and sales_total > 0 else None
|
||||
|
||||
word = {"day": "오늘" if period.start == today else "해당일",
|
||||
"week": "이번주" if period.start <= today <= period.end else "해당 주",
|
||||
"month": "이번달" if period.start <= today <= period.end else "해당 월",
|
||||
"year": "올해" if period.start <= today <= period.end else "해당 연도",
|
||||
"custom": "선택 기간"}[period.kind]
|
||||
word = _period_word(period, today)
|
||||
kpis = [
|
||||
{"key": "spend", "label": f"{word} 광고비", "value": cur.gross, "primary": True,
|
||||
"delta": calc.pct_change(cur.gross, prev.gross), "cmp": cmp_label, "invert": True},
|
||||
@@ -536,25 +613,7 @@ def build_ad_dashboard(store: Any, *, kind: str, anchor: date, today: date,
|
||||
"delta": calc.pct_change(ytd.gross, y_prev.gross), "cmp": y_cmp_label, "invert": True},
|
||||
]
|
||||
|
||||
def url(k: str, anchor_d: date | None = None, start: date | None = None, end: date | None = None) -> str:
|
||||
if k == "custom":
|
||||
return f"?period=custom&from={start.isoformat()}&to={end.isoformat()}"
|
||||
return f"?period={k}&d={anchor_d.isoformat()}"
|
||||
|
||||
if period.kind == "custom":
|
||||
from datetime import timedelta # noqa: WPS433
|
||||
|
||||
length = timedelta(days=period.days)
|
||||
prev_url = url("custom", start=period.start - length, end=period.start - timedelta(days=1))
|
||||
next_url = url("custom", start=period.end + timedelta(days=1), end=period.end + length)
|
||||
else:
|
||||
prev_url, next_url = url(period.kind, period.prev_anchor), url(period.kind, period.next_anchor)
|
||||
# 빠른 선택은 이번달·올해만(2026-10-26 — 오늘·이번주 버튼 삭제, 매출 실적과 같게)
|
||||
nav = {"prev": prev_url, "next": next_url, "quick": [
|
||||
{"label": "이번달", "url": url("month", today), "active": period.kind == "month" and period.start <= today <= period.end},
|
||||
{"label": "올해", "url": url("year", today), "active": period.kind == "year" and period.start <= today <= period.end},
|
||||
]}
|
||||
|
||||
nav = _period_nav(period, today)
|
||||
share = calc.by_code(cells, codes, period.start, period.end)
|
||||
month = calc.month_summary(month_period.start.year, month_period.start.month, codes, cells)
|
||||
table = calc.main_table(period, codes, cells, today=today, holidays=holidays)
|
||||
|
||||
Reference in New Issue
Block a user