54e4e08802
광고비 탭 오른쪽에 틱톡 탭 추가. 일자별 ROAS, 광고비, 매출을 광고비 탭과 같은 틀로 보여 준다. 실적 설정 광고 API 연동에 틱톡 추가(광고 계정 ID, 액세스 토큰, 선택 틱톡샵 ID). 채널 표(CHANNELS)에 넣지 않아 매출 실적·광고비 탭 합계에는 들어가지 않는다. DB 변경 없음. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
217 lines
11 KiB
Python
217 lines
11 KiB
Python
"""틱톡 탭(2026-11-05) — 입력 검사·요청 매개변수·30일 나누기·매출 합산·환율·오류 안내·화면 데이터·다른 탭과 분리.
|
|
틱톡 서버는 가짜(httpx MockTransport)."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
from datetime import date
|
|
from decimal import Decimal
|
|
from urllib.parse import parse_qs, urlparse
|
|
|
|
import httpx
|
|
import pytest
|
|
|
|
from app.modules.performance import ad_spend, fx
|
|
from app.modules.performance.ad_sources import tiktok_ads as tt
|
|
from app.modules.performance.ad_sources.registry import get_source
|
|
from app.modules.performance.adapters.base import AdapterContext, ApiError, AuthFailed, TokenExpired
|
|
|
|
TOKEN = "tiktoktoken0123456789abcdefSECRET"
|
|
|
|
|
|
class Creds:
|
|
def __init__(self, values):
|
|
self.values = values
|
|
|
|
def get(self, key):
|
|
return self.values.get(key, "")
|
|
|
|
def has(self, key):
|
|
return bool(self.values.get(key))
|
|
|
|
|
|
def ctx(**extra):
|
|
return AdapterContext(code="tiktok", credentials=Creds({"advertiser_id": "71234567", "access_token": TOKEN, **extra}), timeout_sec=5.0)
|
|
|
|
|
|
def server(monkeypatch, *, currency="KRW", report=None, gmv=None, seen=None):
|
|
"""가짜 틱톡 + 환율 서버. seen 에 (경로, 쿼리, 머리글)을 쌓는다."""
|
|
def handler(req: httpx.Request) -> httpx.Response:
|
|
url = urlparse(str(req.url))
|
|
q = {k: v[0] for k, v in parse_qs(url.query).items()}
|
|
if seen is not None:
|
|
seen.append((url.path, q, req.headers.get("access-token")))
|
|
if "business-api.tiktok.com" not in str(req.url):
|
|
return httpx.Response(200, json=[{"date": "2026-10-05", "base": "MYR", "quote": "KRW", "rate": 300}])
|
|
if url.path.endswith("/advertiser/info/"):
|
|
return httpx.Response(200, json={"code": 0, "data": {"list": [{"name": "DBX", "currency": currency, "timezone": "Asia/Seoul"}]}})
|
|
rows = gmv if url.path.endswith("/gmv_max/report/get/") else report
|
|
if isinstance(rows, httpx.Response):
|
|
return rows
|
|
return httpx.Response(200, json={"code": 0, "data": {"list": [
|
|
{"dimensions": {"stat_time_day": f"{d} 00:00:00"}, "metrics": m} for d, m in (rows or {}).items()]}})
|
|
monkeypatch.setattr(tt, "_http", lambda c: httpx.Client(transport=httpx.MockTransport(handler)))
|
|
|
|
|
|
def test_registered_but_not_a_channel():
|
|
"""틱톡은 광고 연동에는 있지만 광고비 탭 채널이 아니다(틱톡 탭에서만 보임)."""
|
|
assert get_source("tiktok").name == "틱톡"
|
|
assert "tiktok" not in ad_spend.CHANNEL_CODES
|
|
|
|
|
|
@pytest.mark.parametrize("values,word", [
|
|
({"advertiser_id": "abc", "access_token": TOKEN}, "광고 계정 ID"),
|
|
({"advertiser_id": "71234567", "access_token": "short"}, "액세스 토큰"),
|
|
({"advertiser_id": "71234567", "access_token": TOKEN, "shop_id": "x1"}, "틱톡샵 ID"),
|
|
])
|
|
def test_validation(values, word):
|
|
assert any(word in e for e in tt.TiktokAdsSource().validate_credentials(values))
|
|
|
|
|
|
def test_stored_values_pass_validation():
|
|
assert tt.TiktokAdsSource().validate_credentials({"advertiser_id": "71234567", "access_token": "__stored__"}) == []
|
|
|
|
|
|
def test_fetch_sums_revenue_and_splits_30_days(monkeypatch):
|
|
seen = []
|
|
server(monkeypatch, seen=seen, report={"2026-10-05": {
|
|
"spend": "1000", "impressions": "50", "clicks": "5", "complete_payment": "1", "onsite_shopping": "2",
|
|
"total_complete_payment_rate": "2000", "total_onsite_shopping_value": "1000.4"}})
|
|
days = tt.TiktokAdsSource().fetch_days(ctx(), date(2026, 9, 1), date(2026, 11, 3))
|
|
reports = [q for path, q, _ in seen if path.endswith("/report/integrated/get/")]
|
|
assert [(q["start_date"], q["end_date"]) for q in reports] == [
|
|
("2026-09-01", "2026-09-30"), ("2026-10-01", "2026-10-30"), ("2026-10-31", "2026-11-03")]
|
|
assert reports[0]["data_level"] == "AUCTION_ADVERTISER" and "stat_time_day" in json.loads(reports[0]["dimensions"])
|
|
assert not [p for p, _, _ in seen if p.endswith("/gmv_max/report/get/")] # 틱톡샵 ID 없으면 안 물음
|
|
assert all(h == TOKEN for _, _, h in seen) and not any(TOKEN in json.dumps(q) for _, q, _ in seen) # 토큰은 머리글로만
|
|
# 같은 날 응답이 쪽마다 오므로 3번 더해진다 — 가짜 서버가 기간과 무관하게 같은 줄을 주는 탓, 합산 동작 자체를 확인
|
|
d = days[0]
|
|
assert d.day == date(2026, 10, 5) and d.amount == 3000 and d.metrics[tt.M_REVENUE] == 9001
|
|
assert d.roas == Decimal("300.04") and d.metrics[tt.M_ORDERS] == 9
|
|
|
|
|
|
def test_gmv_max_added_only_with_shop_id(monkeypatch):
|
|
seen = []
|
|
server(monkeypatch, seen=seen, report={"2026-10-05": {"spend": "100", "total_onsite_shopping_value": "100"}},
|
|
gmv={"2026-10-05": {"cost": "100", "gross_revenue": "500", "orders": "3"}})
|
|
d = tt.TiktokAdsSource().fetch_days(ctx(shop_id="7555"), date(2026, 10, 5), date(2026, 10, 5))[0]
|
|
assert d.amount == 200 and d.metrics[tt.M_REVENUE] == 600 and d.roas == Decimal("300.00")
|
|
assert d.metrics[tt.M_GMV_REVENUE] == 500 and d.metrics[tt.M_GMV_COST] == 100 # 대조용으로 따로 남김
|
|
gmv_q = next(q for p, q, _ in seen if p.endswith("/gmv_max/report/get/"))
|
|
assert json.loads(gmv_q["store_ids"]) == ["7555"]
|
|
|
|
|
|
def test_foreign_currency_uses_that_day_rate(monkeypatch):
|
|
fx.clear_cache()
|
|
server(monkeypatch, currency="MYR", report={"2026-10-05": {"spend": "10", "total_onsite_shopping_value": "40"}})
|
|
d = tt.TiktokAdsSource().fetch_days(ctx(), date(2026, 10, 5), date(2026, 10, 5))[0]
|
|
assert d.amount == 3000 and d.metrics[tt.M_REVENUE] == 12000 and d.roas == Decimal("400.00")
|
|
fx.clear_cache()
|
|
|
|
|
|
def test_no_spend_means_no_roas(monkeypatch):
|
|
server(monkeypatch, report={"2026-10-05": {"spend": "0", "total_onsite_shopping_value": "40"}})
|
|
d = tt.TiktokAdsSource().fetch_days(ctx(), date(2026, 10, 5), date(2026, 10, 5))[0]
|
|
assert d.roas is None and d.metrics[tt.M_ROAS] is None
|
|
|
|
|
|
@pytest.mark.parametrize("code,exc", [(40102, TokenExpired), (40105, AuthFailed), (40100, ApiError), (40002, ApiError)])
|
|
def test_error_codes(monkeypatch, code, exc):
|
|
server(monkeypatch, report=httpx.Response(200, json={"code": code, "message": "bad"}))
|
|
with pytest.raises(exc) as got:
|
|
tt.TiktokAdsSource().fetch_days(ctx(), date(2026, 10, 5), date(2026, 10, 5))
|
|
assert str(code) in str(got.value) and TOKEN not in str(got.value)
|
|
|
|
|
|
def test_connection_also_asks_report(monkeypatch):
|
|
"""연결 테스트가 보고서까지 물어야 지표 이름 오류를 저장 전에 잡는다."""
|
|
seen = []
|
|
server(monkeypatch, seen=seen)
|
|
msg = tt.TiktokAdsSource().test_connection(ctx())
|
|
assert "DBX" in msg and "KRW" in msg
|
|
assert any(p.endswith("/report/integrated/get/") for p, _, _ in seen)
|
|
|
|
|
|
class Store:
|
|
def __init__(self, rows=None, missing=False):
|
|
self.rows, self.missing = rows or [], missing
|
|
|
|
def ad_details(self, code, start, end):
|
|
assert code == "tiktok"
|
|
if self.missing:
|
|
raise ad_spend.AdMigrationNeeded("005")
|
|
return [r for r in self.rows if start.isoformat() <= r["date"] <= end.isoformat()]
|
|
|
|
|
|
def row(day, spend, sales):
|
|
return {"date": day, "amount": spend, "roas": None, "metrics": {tt.M_REVENUE: sales}, "source": "api"}
|
|
|
|
|
|
def test_dashboard_table_and_kpis():
|
|
store = Store([row("2026-10-05", 1000, 3000), row("2026-10-06", 1000, 1000), row("2026-09-05", 500, 500)])
|
|
ctx_ = ad_spend.build_tiktok_dashboard(store, kind="month", anchor=date(2026, 10, 15), today=date(2026, 10, 31),
|
|
holidays={"2026-10-09": "한글날"})
|
|
total = ctx_["table"][0]
|
|
assert total["kind"] == "total" and total["cells"]["spend"]["gross"] == 2000 and total["cells"]["sales"]["gross"] == 4000 and total["roas"] == 200
|
|
day = next(r for r in ctx_["table"] if r.get("date") == "2026-10-05")
|
|
assert day["roas"] == 300
|
|
assert next(r for r in ctx_["table"] if r.get("date") == "2026-10-09")["holiday"] == "한글날"
|
|
kpi = {k["key"]: k for k in ctx_["kpis"]}
|
|
assert kpi["spend"]["value"] == 2000 and kpi["sales"]["value"] == 4000 and kpi["roas"]["pct"] == 200
|
|
assert kpi["spend"]["delta"] == 300.0 and kpi["sales"]["delta"] == 700.0
|
|
assert ctx_["year"]["spend"] == 2500 and ctx_["year"]["sales"] == 4500 and ctx_["year"]["rows"][9]["roas"] == 200
|
|
assert ctx_["year"]["rows"][10]["future"] is True and ctx_["year"]["rows"][10]["roas"] is None
|
|
assert sum(p["gross"] for p in ctx_["chart_sales"]) == 4000 and sum(p["gross"] for p in ctx_["chart_spend"]) == 2000
|
|
|
|
|
|
def test_dashboard_without_table_or_data():
|
|
got = ad_spend.build_tiktok_dashboard(Store(missing=True), kind="month", anchor=date(2026, 10, 1), today=date(2026, 10, 31))
|
|
assert got["migration_needed"] is True and got["table"][0]["roas"] is None
|
|
assert {k["key"]: k for k in got["kpis"]}["roas"]["pct"] is None
|
|
|
|
|
|
def test_ads_tab_ignores_tiktok_rows():
|
|
"""perf_ad_spend 에 틱톡 줄이 있어도 광고비 탭 합계에 안 들어간다."""
|
|
class AdStore:
|
|
def ad_amounts(self, start, end):
|
|
return {(date(2026, 10, 5), "google"): 100, (date(2026, 10, 5), "tiktok"): 9000}, {}
|
|
|
|
def daily_amounts(self, start, end, codes):
|
|
return {}
|
|
|
|
got = ad_spend.build_ad_dashboard(AdStore(), kind="month", anchor=date(2026, 10, 1), today=date(2026, 10, 31))
|
|
assert got["table"][0]["total"]["gross"] == 100 and "tiktok" not in got["codes"]
|
|
assert {k["key"]: k for k in got["kpis"]}["spend"]["value"] == 100
|
|
|
|
|
|
def test_page_renders_after_ads_tab(monkeypatch):
|
|
"""진짜 라우터·템플릿 — 탭 순서, 열 순서, 값, 미설정 안내, 칸 입력 없음."""
|
|
import importlib
|
|
|
|
from fastapi import FastAPI
|
|
from fastapi.testclient import TestClient
|
|
|
|
from app.modules.performance import common
|
|
|
|
perf_router = importlib.import_module("app.modules.performance.router") # 패키지의 router 는 APIRouter 객체
|
|
store = Store([row("2026-10-05", 1000, 3000)])
|
|
user = {"email": "a@x", "name": "A", "role": "user"}
|
|
|
|
class Sync:
|
|
def configured(self):
|
|
return {"google": True, "tiktok": False}
|
|
|
|
monkeypatch.setattr(common, "guard", lambda request, admin=False: (store, user))
|
|
monkeypatch.setattr(perf_router, "_ad_services", lambda st: (None, Sync()))
|
|
monkeypatch.setattr(perf_router, "_auto_sync_ctx", lambda st, kind: None)
|
|
monkeypatch.setattr(perf_router, "today_kst", lambda: date(2026, 10, 31))
|
|
app = FastAPI()
|
|
app.include_router(perf_router.router)
|
|
html = TestClient(app).get("/performance/tiktok").text
|
|
tabs = html.split('class="perf-tabs-main"', 1)[1]
|
|
assert tabs.index("광고비</a>") < tabs.index("틱톡</a>") and "perf-tab-tiktok is-active" in tabs
|
|
head = html.split("<thead>", 1)[1].split("</thead>", 1)[0]
|
|
assert head.index("ROAS") < head.index("광고비") < head.index("매출")
|
|
assert "3,000" in html and "300%" in html
|
|
assert "틱톡 API 가 아직 설정되지 않았습니다" in html and "data-manual-code" not in html
|