feat(실적): 틱톡 탭과 틱톡 광고 API 연동

광고비 탭 오른쪽에 틱톡 탭 추가. 일자별 ROAS, 광고비, 매출을 광고비 탭과 같은 틀로 보여 준다.
실적 설정 광고 API 연동에 틱톡 추가(광고 계정 ID, 액세스 토큰, 선택 틱톡샵 ID).
채널 표(CHANNELS)에 넣지 않아 매출 실적·광고비 탭 합계에는 들어가지 않는다. DB 변경 없음.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-05 14:19:25 +09:00
parent d27257f15b
commit 54e4e08802
16 changed files with 819 additions and 61 deletions
+9 -1
View File
@@ -106,9 +106,17 @@
- **표 몸통 칸에는 풍선 도움말(title) 없음**(2026-10-22 사용자 요청) — 입력 칸·날짜 칸(공휴일은 칸 안 글자)·광고비 줄 모두. 열 머리글 말풍선은 그대로. - **표 몸통 칸에는 풍선 도움말(title) 없음**(2026-10-22 사용자 요청) — 입력 칸·날짜 칸(공휴일은 칸 안 글자)·광고비 줄 모두. 열 머리글 말풍선은 그대로.
새 칸 기능에 title 을 다시 달지 말 것(설명은 표 아래 안내 문구에). 새 칸 기능에 title 을 다시 달지 말 것(설명은 표 아래 안내 문구에).
## 틱톡 (`/performance/tiktok`, 2026-11-05, 마이그레이션 없음)
- 광고비 탭 틀(기간 이동·KPI·표·그래프·연 누적), 표 열 = ROAS·광고비·매출. 값은 광고 API 만(읽기 전용, 칸 입력·메모 없음). 화면 데이터 `ad_spend.build_tiktok_dashboard`.
- **틱톡 탭에서만 보임** — 채널 코드 `tiktok` 은 `ad_sources` 에는 있지만 `ad_spend.CHANNELS` 에는 넣지 않는다(넣으면 광고비 탭 합계에 들어감). 쇼핑몰 표(`perf_marketplaces`)에도 없어 매출 실적 합계·열과 무관. 저장은 다른 광고 API 처럼 `perf_ad_spend`(`source='api'`), 매출 = `metrics["매출"]`.
- 설정 = 실적 설정 **광고 API 연동** 카드 → 틱톡 — 광고 계정 ID·장기 액세스 토큰·틱톡샵 ID(선택). [광고비 업데이트]·광고비 자동 업데이트에 함께 돈다.
- `ad_sources/tiktok_ads.py` — `report/integrated/get`(30일씩), 매출 = 웹 구매금액 + 틱톡샵 매출, 틱톡샵 ID 가 있으면 `gmv_max/report/get` 비용·매출도 더함(항목별 값은 metrics 에 따로 저장). 외화 계정은 그날 환율로 원화(`fx`). ROAS = 매출 ÷ 광고비.
**실제 토큰 대조 전**(2026-11-05) — 공식 문서를 읽지 못해 지표 이름은 이차 자료로 확인. 일반 보고서에 GMV Max 가 이미 들어 있으면 틱톡샵 ID 를 넣었을 때 중복되므로, 처음 쓸 때 광고 관리자 화면과 대조할 것.
## 광고비 (`/performance/ads`) ## 광고비 (`/performance/ads`)
- 탭은 [매출 실적]·[광고비] + 맨 오른쪽 설정 톱니. - 탭은 [매출 실적]·[광고비]·[틱톡] + 맨 오른쪽 설정 톱니.
- **표 모양(2026-10-22)** — 매출 실적 표와 같은 `perf-autofit`(열 너비 = 내용 길이, 날짜 열 가로 스크롤 고정). - **표 모양(2026-10-22)** — 매출 실적 표와 같은 `perf-autofit`(열 너비 = 내용 길이, 날짜 열 가로 스크롤 고정).
- **기타광고비** 열(`etc`, 애터미아자몰 오른쪽, 2026-10-22) — 쇼핑몰에 딸리지 않은 광고비 직접 입력. 매출 쇼핑몰이 없어(`ad_spend.NO_SALES`) ROAS 없음·매출 탭 광고비 줄에 안 나옴, 광고비 합계·매출 대비 광고비에는 들어감. - **기타광고비** 열(`etc`, 애터미아자몰 오른쪽, 2026-10-22) — 쇼핑몰에 딸리지 않은 광고비 직접 입력. 매출 쇼핑몰이 없어(`ad_spend.NO_SALES`) ROAS 없음·매출 탭 광고비 줄에 안 나옴, 광고비 합계·매출 대비 광고비에는 들어감.
- `ad_spend.py`, 마이그레이션 005 `perf_ad_spend`. 구글·메타·네이버·쿠팡(윙)·쿠팡(로켓)·오늘의집·G마켓·카카오·GS샵·11번가·롯데ON·토스·애터미아자몰 일 광고비를 연·월·일로. - `ad_spend.py`, 마이그레이션 005 `perf_ad_spend`. 구글·메타·네이버·쿠팡(윙)·쿠팡(로켓)·오늘의집·G마켓·카카오·GS샵·11번가·롯데ON·토스·애터미아자몰 일 광고비를 연·월·일로.
@@ -1,12 +1,14 @@
"""광고 API 연동 목록 — 새 광고 채널은 파일 하나 + 여기 한 줄(채널 코드는 ad_spend.CHANNELS 와 같아야 한다).""" """광고 API 연동 목록 — 새 광고 채널은 파일 하나 + 여기 한 줄(채널 코드는 ad_spend.CHANNELS 와 같아야 한다 —
틱톡만 예외: 광고비 탭에 안 나오게 CHANNELS 에 넣지 않고 틱톡 탭이 따로 읽는다)."""
from __future__ import annotations from __future__ import annotations
from .base import AdSource from .base import AdSource
from .google_ads import GoogleAdsSource from .google_ads import GoogleAdsSource
from .meta_ads import MetaAdsSource from .meta_ads import MetaAdsSource
from .tiktok_ads import TiktokAdsSource
_SOURCES: tuple[AdSource, ...] = (GoogleAdsSource(), MetaAdsSource()) _SOURCES: tuple[AdSource, ...] = (GoogleAdsSource(), MetaAdsSource(), TiktokAdsSource())
_BY_CODE = {s.code: s for s in _SOURCES} _BY_CODE = {s.code: s for s in _SOURCES}
@@ -0,0 +1,202 @@
"""틱톡 광고(TikTok API for Business v1.3) — 날짜별 광고비·매출·ROAS. 화면은 틱톡 탭(광고비 탭·매출 실적에는 안 나옴).
인증(2026-11-05): 광고 계정(advertiser) ID 하나 + 장기 액세스 토큰(머리글 Access-Token). 토큰 앱에 보고서·광고 계정 읽기 권한이 있어야 한다.
조회
GET /report/integrated/get/ — report_type=BASIC · data_level=AUCTION_ADVERTISER · 차원 advertiser_id·stat_time_day.
매출 = 웹 구매금액(total_complete_payment_rate — 이름과 달리 금액) + 틱톡샵 매출(total_onsite_shopping_value).
GET /gmv_max/report/get/ — 틱톡샵 ID 를 넣었을 때만. 비용(cost)·매출(gross_revenue)을 더한다.
- 하루 단위 조회는 기간 제한이 있어 30일씩 나눠 묻는다.
- 금액은 광고 계정 통화 → 그날 환율로 원화(fx.krw_rates, 메타와 같음).
- ROAS(%) = 매출 ÷ 광고비 × 100(합친 값으로 계산 — 틱톡의 ROAS 칸은 더할 수 없다).
공식 문서가 스크립트 화면이라 지표 이름을 이차 자료로 확인했다 — 연결 테스트가 어제 하루를 실제로 물어 지표 이름 오류까지 잡는다.
"""
from __future__ import annotations
import json
import re
from datetime import date, timedelta
from decimal import ROUND_HALF_UP, Decimal
from typing import Any
import httpx
from app.timezone import today_kst
from .. import fx
from ..adapters.base import AdapterContext, ApiError, AuthFailed, CredentialField, TokenExpired
from .base import AdDay, AdSource
from .meta_ads import _num, _won
API_BASE = "https://business-api.tiktok.com/open_api/v1.3"
MAX_DAYS = 366
SPAN_DAYS = 30
PAGE_SIZE = 100 # 계정 하나·30일 = 많아야 30줄이라 한 쪽이면 된다
RATE_LIMIT = 40100
REPORT_METRICS = ("spend", "impressions", "clicks", "complete_payment", "total_complete_payment_rate",
"onsite_shopping", "total_onsite_shopping_value")
GMV_METRICS = ("cost", "gross_revenue", "orders")
# metrics 키 — 화면 이름 그대로 저장. 틱톡 탭은 M_REVENUE 를 매출로 읽는다(ad_spend.build_tiktok_dashboard).
M_SPEND, M_REVENUE, M_ROAS = "광고비", "매출", "ROAS(%)"
M_IMPR, M_CLICKS, M_ORDERS = "노출수", "클릭수", "구매수"
M_WEB, M_SHOP, M_GMV_COST, M_GMV_REVENUE = "웹 구매금액", "틱톡샵 매출", "GMV Max 비용", "GMV Max 매출"
def _http(ctx: AdapterContext) -> httpx.Client:
"""HTTP 클라이언트 — 테스트가 바꿔 끼운다."""
return httpx.Client(timeout=ctx.timeout_sec)
def _spans(start: date, end: date) -> list[tuple[date, date]]:
"""기간을 SPAN_DAYS 일씩 나눈다."""
out = []
while start <= end:
stop = min(start + timedelta(days=SPAN_DAYS - 1), end)
out.append((start, stop))
start = stop + timedelta(days=1)
return out
class TiktokAdsSource(AdSource):
code = "tiktok"
name = "틱톡"
docs_url = "https://business-api.tiktok.com/portal/docs"
note = ("TikTok API for Business 로 날짜별 광고비·매출·ROAS 를 가져와 틱톡 탭에 보여 줍니다(매출 실적·광고비 탭 합계에는 들어가지 않음). "
"준비: 개발자 앱에서 광고 계정을 승인해 장기 액세스 토큰 발급(보고서·광고 계정 읽기 권한). 외화 계정은 그날 환율로 원화로 바꿉니다.")
def credential_fields(self) -> list[CredentialField]:
return [
CredentialField("advertiser_id", "광고 계정 ID", placeholder="7123456789012345678",
help="틱톡 광고 관리자 주소의 aadvid= 뒤 숫자."),
CredentialField("access_token", "액세스 토큰", secret=True,
help="광고 계정을 승인할 때 받은 장기 액세스 토큰. 저장 후에는 화면에 다시 보이지 않습니다."),
CredentialField("shop_id", "틱톡샵 ID", required=False, placeholder="GMV Max 캠페인을 쓸 때만",
help="GMV Max 캠페인은 일반 보고서와 따로 조회합니다 — 넣으면 그 비용·매출도 더합니다. 안 쓰면 비워 둡니다."),
]
def validate_credentials(self, values: dict[str, str]) -> list[str]:
errors = super().validate_credentials(values)
advertiser = (values.get("advertiser_id") or "").strip()
if advertiser and advertiser != "__stored__" and not re.fullmatch(r"\d{5,30}", advertiser):
errors.append("광고 계정 ID 는 숫자여야 합니다.")
shop = (values.get("shop_id") or "").strip()
if shop and shop != "__stored__" and not re.fullmatch(r"\d{5,30}", shop):
errors.append("틱톡샵 ID 는 숫자여야 합니다.")
token = (values.get("access_token") or "").strip()
if token and token != "__stored__" and (len(token) < 20 or re.search(r"\s", token)):
errors.append("액세스 토큰 형식이 아닙니다(공백 없이 통째로 붙여 넣으세요).")
return errors
def _get(self, ctx: AdapterContext, client: httpx.Client, path: str, params: dict[str, Any]) -> dict[str, Any]:
"""틱톡은 오류도 HTTP 200 + code 로 준다. 토큰은 머리글로만 보내 주소·오류 문구에 들어가지 않는다."""
ctx.progress.check()
token = (ctx.credentials.get("access_token") or "").strip()
try:
resp = client.get(API_BASE + path, params=params, headers={"Access-Token": token})
except httpx.HTTPError as exc:
raise ApiError(f"틱톡 API 에 연결하지 못했습니다({type(exc).__name__}).") from None
try:
body = resp.json()
except ValueError:
raise ApiError(f"틱톡 API 응답을 읽을 수 없습니다(HTTP {resp.status_code}).") from None
code = body.get("code") if isinstance(body, dict) else None
if resp.status_code == 200 and code == 0:
return body.get("data") or {}
text = f"틱톡 API 오류({code if code is not None else resp.status_code}): {str((body or {}).get('message') or '')[:200]}"
if code == 40102:
raise TokenExpired(text + " — 액세스 토큰을 다시 발급해 넣으세요.")
if code == RATE_LIMIT:
raise ApiError(text + " — 호출 한도에 걸렸습니다. 잠시 뒤 다시 누르세요.")
if resp.status_code in (401, 403) or (isinstance(code, int) and 40100 < code < 40200):
raise AuthFailed(text + " — 토큰과 광고 계정 ID, 앱 권한을 확인하세요.")
raise ApiError(text)
def _info(self, ctx: AdapterContext, client: httpx.Client) -> dict[str, Any]:
advertiser = (ctx.credentials.get("advertiser_id") or "").strip()
rows = self._get(ctx, client, "/advertiser/info/", {
"advertiser_ids": json.dumps([advertiser]), "fields": json.dumps(["name", "currency", "timezone"])}).get("list") or []
if not rows:
raise AuthFailed("이 토큰으로 볼 수 없는 광고 계정입니다 — 광고 계정 ID 와 승인 여부를 확인하세요.")
return rows[0]
def _rows(self, ctx: AdapterContext, client: httpx.Client, path: str, metrics: tuple[str, ...], start: date, end: date,
**extra: Any) -> list[tuple[date, dict[str, Any]]]:
"""보고서 하나를 30일씩 물어 (날짜, 지표) 목록으로."""
advertiser = (ctx.credentials.get("advertiser_id") or "").strip()
out = []
for s, e in _spans(start, end):
data = self._get(ctx, client, path, {
"advertiser_id": advertiser, "dimensions": json.dumps(["advertiser_id", "stat_time_day"]), "metrics": json.dumps(metrics),
"start_date": s.isoformat(), "end_date": e.isoformat(), "page": 1, "page_size": PAGE_SIZE, **extra})
for r in data.get("list") or []:
try:
day = date.fromisoformat(str((r.get("dimensions") or {}).get("stat_time_day"))[:10])
except ValueError:
continue
out.append((day, r.get("metrics") or {}))
return out
def _collect(self, ctx: AdapterContext, client: httpx.Client, start: date, end: date) -> dict[date, dict[str, Decimal]]:
"""날짜 → 항목 합(계정 통화)."""
sums: dict[date, dict[str, Decimal]] = {}
def day_of(d: date) -> dict[str, Decimal]:
return sums.setdefault(d, {k: Decimal(0) for k in ("spend", "impr", "clicks", "orders", "web", "shop", "gmv_cost", "gmv")})
for d, m in self._rows(ctx, client, "/report/integrated/get/", REPORT_METRICS, start, end,
report_type="BASIC", data_level="AUCTION_ADVERTISER"):
one = day_of(d)
one["spend"] += _num(m.get("spend"))
one["impr"] += _num(m.get("impressions"))
one["clicks"] += _num(m.get("clicks"))
one["orders"] += _num(m.get("complete_payment")) + _num(m.get("onsite_shopping"))
one["web"] += _num(m.get("total_complete_payment_rate"))
one["shop"] += _num(m.get("total_onsite_shopping_value"))
shop_id = (ctx.credentials.get("shop_id") or "").strip()
if shop_id:
for d, m in self._rows(ctx, client, "/gmv_max/report/get/", GMV_METRICS, start, end, store_ids=json.dumps([shop_id])):
one = day_of(d)
one["orders"] += _num(m.get("orders"))
one["gmv_cost"] += _num(m.get("cost"))
one["gmv"] += _num(m.get("gross_revenue"))
return sums
def test_connection(self, ctx: AdapterContext) -> str:
self.require_configured(ctx)
yesterday = today_kst() - timedelta(days=1)
with _http(ctx) as client:
info = self._info(ctx, client)
self._collect(ctx, client, yesterday, yesterday) # 지표 이름·GMV Max 권한까지 실제로 확인
return f"연결됨 — {info.get('name') or '광고 계정'}({info.get('currency') or '?'}·{info.get('timezone') or '?'})"
def fetch_days(self, ctx: AdapterContext, start: date, end: date) -> list[AdDay]:
if end < start:
start, end = end, start
if (end - start).days + 1 > MAX_DAYS:
raise ApiError(f"한 번에 {MAX_DAYS}일까지 가져올 수 있습니다.")
self.require_configured(ctx)
with _http(ctx) as client:
currency = str(self._info(ctx, client).get("currency") or "").upper()
if not re.fullmatch(r"[A-Z]{3}", currency):
raise ApiError(f"광고 계정 통화({currency[:10] or '없음'})를 알 수 없습니다.")
sums = self._collect(ctx, client, start, end)
try:
rates = fx.krw_rates(client, currency, start, end) if sums else {}
except fx.FxError as exc:
raise ApiError(f"{currency} 광고 계정을 원화로 바꿀 환율을 가져오지 못했습니다 — {exc}") from None
return [_day(d, sums[d], rates[d]) for d in sorted(sums)]
def _day(day: date, a: dict[str, Decimal], rate: Decimal) -> AdDay:
"""합친 값(계정 통화) → 하루치(원화). ROAS 는 비율이라 반올림 전 값으로."""
spend = (a["spend"] + a["gmv_cost"]) * rate
revenue = (a["web"] + a["shop"] + a["gmv"]) * rate
roas = (revenue / spend * 100).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP) if spend > 0 else None
return AdDay(day=day, amount=_won(spend), roas=roas, metrics={
M_SPEND: _won(spend), M_REVENUE: _won(revenue), M_ROAS: float(roas) if roas is not None else None,
M_WEB: _won(a["web"] * rate), M_SHOP: _won(a["shop"] * rate), M_GMV_COST: _won(a["gmv_cost"] * rate), M_GMV_REVENUE: _won(a["gmv"] * rate),
M_IMPR: int(a["impr"]), M_CLICKS: int(a["clicks"]), M_ORDERS: int(a["orders"]),
})
+84 -25
View File
@@ -22,12 +22,13 @@ from __future__ import annotations
import csv import csv
import io import io
from dataclasses import dataclass, field from dataclasses import dataclass, field
from datetime import date from datetime import date, timedelta
from decimal import ROUND_HALF_UP, Decimal, InvalidOperation from decimal import ROUND_HALF_UP, Decimal, InvalidOperation
from typing import Any, Callable, Mapping, Sequence from typing import Any, Callable, Mapping, Sequence
from . import calc from . import calc
from .ad_sources.base import ACCOUNTS_KEY 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 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). # 채널 — 표 열 순서(2026-10-14 사용자 지정). 쇼핑몰 채널 코드는 실적 쇼핑몰 코드와 같다(쿠팡(윙)만 coupang_wing ↔ 매출 coupang).
@@ -57,6 +58,7 @@ NO_ROAS = FILE_ROAS # 예전 이름(계산 안 하는 채널)
NO_SALES = frozenset({"etc"}) # 매출 쇼핑몰이 없는 채널 — 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: 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" ROAS_SALES_CODE["coupang_wing"] = "coupang"
TIKTOK = "tiktok" # 광고 API 채널이지만 CHANNELS 에 없다 — 틱톡 탭(build_tiktok_dashboard)에서만 보인다
def roas(sales: int, spend: int) -> int | None: 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, def build_ad_dashboard(store: Any, *, kind: str, anchor: date, today: date,
custom_from: date | None = None, custom_to: date | None = None, custom_from: date | None = None, custom_to: date | None = None,
holidays: Mapping[str, str] | 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 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 ratio = round(cur.gross / sales_total * 100, 1) if sales_total and sales_total > 0 else None
word = {"day": "오늘" if period.start == today else "해당일", word = _period_word(period, today)
"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]
kpis = [ kpis = [
{"key": "spend", "label": f"{word} 광고비", "value": cur.gross, "primary": True, {"key": "spend", "label": f"{word} 광고비", "value": cur.gross, "primary": True,
"delta": calc.pct_change(cur.gross, prev.gross), "cmp": cmp_label, "invert": 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}, "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: nav = _period_nav(period, today)
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},
]}
share = calc.by_code(cells, codes, period.start, period.end) share = calc.by_code(cells, codes, period.start, period.end)
month = calc.month_summary(month_period.start.year, month_period.start.month, codes, cells) 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) table = calc.main_table(period, codes, cells, today=today, holidays=holidays)
+35 -4
View File
@@ -241,8 +241,15 @@ def ads_page(
custom_from=_parse_date(from_), custom_to=_parse_date(to), holidays=_holidays(), custom_from=_parse_date(from_), custom_to=_parse_date(to), holidays=_holidays(),
sales_codes=total_sales_codes(_sales_marketplaces(store)), sales_codes=total_sales_codes(_sales_marketplaces(store)),
) )
# [광고비 업데이트](2026-10-20) — 관리자가 실적 설정에서 인증정보를 넣은 광고 연동 전부를 진행 창으로. _ad_update_ctx(store, user, ctx)
# 마지막 업데이트 = 광고 API 마지막 성공 가져오기, 다음 업데이트 = 매출 자동 업데이트와 같은 회차. _colw_ctx(request, ctx)
return render_template(request, "performance/ads.html",
{**common.base_ctx(user, active_tab="ads", page_title="광고비"), **ctx})
def _ad_update_ctx(store: Any, user: dict[str, Any], ctx: dict[str, Any]) -> None:
"""[광고비 업데이트](2026-10-20, 광고비·틱톡 탭 공통) — 관리자가 실적 설정에서 인증정보를 넣은 광고 연동 전부를 진행 창으로.
마지막 업데이트 = 광고 API 마지막 성공 가져오기, 다음 업데이트 = 매출 자동 업데이트와 같은 회차."""
from . import jobs # noqa: WPS433 from . import jobs # noqa: WPS433
from .ad_sources.registry import get_source # noqa: WPS433 from .ad_sources.registry import get_source # noqa: WPS433
from .ad_sync import last_ad_update_at # noqa: WPS433 from .ad_sync import last_ad_update_at # noqa: WPS433
@@ -257,9 +264,33 @@ def ads_page(
ctx["ad_running"] = jobs.running_job("ads") is not None ctx["ad_running"] = jobs.running_job("ads") is not None
ctx["auto_sync"] = _auto_sync_ctx(store, "ads") ctx["auto_sync"] = _auto_sync_ctx(store, "ads")
ctx["update_watch"] = _update_watch("ads", user) ctx["update_watch"] = _update_watch("ads", user)
@router.get("/tiktok", response_class=HTMLResponse)
def tiktok_page(
request: Request,
period: str = "month",
d: str | None = None,
from_: str | None = Query(None, alias="from"),
to: str | None = None,
):
"""틱톡 탭(2026-11-05) — 일자별 ROAS·광고비·매출(광고 API 값, 읽기 전용). 설정 = 실적 설정 → 광고 API 연동."""
from app.main import render_template # noqa: WPS433
g = common.guard(request)
if not isinstance(g, tuple):
return g
store, user = g
from .ad_spend import build_tiktok_dashboard # noqa: WPS433
today = today_kst()
ctx = build_tiktok_dashboard(store, kind=period, anchor=_parse_date(d) or today, today=today,
custom_from=_parse_date(from_), custom_to=_parse_date(to), holidays=_holidays())
_ad_update_ctx(store, user, ctx)
ctx["tiktok_configured"] = any(s["code"] == "tiktok" for s in ctx["ad_sync_sources"])
_colw_ctx(request, ctx) _colw_ctx(request, ctx)
return render_template(request, "performance/ads.html", return render_template(request, "performance/tiktok.html",
{**common.base_ctx(user, active_tab="ads", page_title="광고비"), **ctx}) {**common.base_ctx(user, active_tab="tiktok", page_title="틱톡"), **ctx})
@router.get("/settings", response_class=HTMLResponse) @router.get("/settings", response_class=HTMLResponse)
@@ -0,0 +1,15 @@
{# 광고비 업데이트(2026-10-20, 광고비·틱톡 탭 공통) — 매출 탭과 같은 모양: 마지막 업데이트(광고 API 마지막 성공) · 다음 자동 업데이트(실적 설정의 광고비 일정)
· [광고비 업데이트](설정된 광고 API 전부, 진행 창). 업데이트 중에도 누르면 진행 창을 다시 연다. #}
{% if ad_sync_sources %}
<div class="perf-update">
<span class="perf-muted" id="perf-last-update" title="광고 API({{ ad_sync_sources | map(attribute='name') | join('·') }}) 마지막 업데이트">마지막 업데이트
<b>{{ (ad_last_update_at or '')[:16] | replace('T', ' ') or '—' }}</b></span>
{% if auto_sync %}
<span class="perf-muted perf-next-update" id="perf-next-update" title="광고비 자동 업데이트: {{ auto_sync.label }} (실적 설정에서 바꿈)">다음 업데이트까지 <b>—</b></span>
{% endif %}
<button type="button" class="erp-btn erp-btn-primary{% if ad_running %} is-running{% endif %}" id="perf-ad-sync-btn"
title="{% if ad_running %}업데이트 진행 상황 보기{% else %}지금 보고 있는 기간({{ period.label }}, 오늘까지)의 광고비·ROAS 를 광고 API({{ ad_sync_sources | map(attribute='name') | join('·') }})에서 다시 가져옵니다{% endif %}">
{% if ad_running %}업데이트 중 · 진행 보기{% else %}광고비 업데이트{% endif %}
</button>
</div>
{% endif %}
@@ -1,4 +1,4 @@
{# 실적 모듈 탭 — [매출 실적] [광고비] 큰 탭 둘(아이콘 + 색으로 구분) + 맨 오른쪽 설정 톱니(프로젝트 모듈과 같은 아이콘). {# 실적 모듈 탭 — [매출 실적] [광고비] [틱톡] 큰 탭(아이콘 + 색으로 구분) + 맨 오른쪽 설정 톱니(프로젝트 모듈과 같은 아이콘).
설정은 모듈 권한자 모두(일반 사용자 화면은 수수료율만, 나머지는 관리자). #} 설정은 모듈 권한자 모두(일반 사용자 화면은 수수료율만, 나머지는 관리자). #}
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" /> <link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
<nav class="perf-tabs" aria-label="실적 메뉴"> <nav class="perf-tabs" aria-label="실적 메뉴">
@@ -9,6 +9,9 @@
<a class="perf-tab perf-tab-ads{% if active_tab == 'ads' %} is-active{% endif %}" href="/performance/ads" <a class="perf-tab perf-tab-ads{% if active_tab == 'ads' %} is-active{% endif %}" href="/performance/ads"
role="tab" aria-selected="{{ 'true' if active_tab == 'ads' else 'false' }}"> role="tab" aria-selected="{{ 'true' if active_tab == 'ads' else 'false' }}">
<span class="material-symbols-outlined" aria-hidden="true">campaign</span>광고비</a> <span class="material-symbols-outlined" aria-hidden="true">campaign</span>광고비</a>
<a class="perf-tab perf-tab-tiktok{% if active_tab == 'tiktok' %} is-active{% endif %}" href="/performance/tiktok"
role="tab" aria-selected="{{ 'true' if active_tab == 'tiktok' else 'false' }}">
<span class="material-symbols-outlined" aria-hidden="true">music_note</span>틱톡</a>
</div> </div>
<a class="perf-tab-gear{% if active_tab == 'settings' %} is-active{% endif %}" href="/performance/settings" <a class="perf-tab-gear{% if active_tab == 'settings' %} is-active{% endif %}" href="/performance/settings"
title="{{ '실적 설정' if is_admin else '수수료 설정' }}" aria-label="{{ '실적 설정' if is_admin else '수수료 설정' }}"> title="{{ '실적 설정' if is_admin else '수수료 설정' }}" aria-label="{{ '실적 설정' if is_admin else '수수료 설정' }}">
@@ -1,6 +1,6 @@
{% extends "erp_base.html" %} {% extends "erp_base.html" %}
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261102b" />{% endblock %} {% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261105a" />{% endblock %}
{#- ROAS 덧붙임 — "광고비(ROAS%)". 광고비가 없으면 아무것도 안 붙는다. -#} {#- ROAS 덧붙임 — "광고비(ROAS%)". 광고비가 없으면 아무것도 안 붙는다. -#}
{%- macro roas(p) -%}{%- if p is not none -%}<span class="perf-roas">({{ "{:,}".format(p) }}%)</span>{%- endif -%}{%- endmacro -%} {%- macro roas(p) -%}{%- if p is not none -%}<span class="perf-roas">({{ "{:,}".format(p) }}%)</span>{%- endif -%}{%- endmacro -%}
@@ -34,21 +34,7 @@
<button class="erp-btn erp-btn-outline" type="submit">조회</button> <button class="erp-btn erp-btn-outline" type="submit">조회</button>
</form> </form>
{# 광고비 업데이트(2026-10-20) — 매출 탭과 같은 모양: 마지막 업데이트(광고 API 마지막 성공) · 다음 자동 업데이트(실적 설정의 광고비 일정) {% include "performance/_ad_update.html" %}
· [광고비 업데이트](설정된 광고 API 전부, 진행 창). 업데이트 중에도 누르면 진행 창을 다시 연다. #}
{% if ad_sync_sources %}
<div class="perf-update">
<span class="perf-muted" id="perf-last-update" title="광고 API({{ ad_sync_sources | map(attribute='name') | join('·') }}) 마지막 업데이트">마지막 업데이트
<b>{{ (ad_last_update_at or '')[:16] | replace('T', ' ') or '—' }}</b></span>
{% if auto_sync %}
<span class="perf-muted perf-next-update" id="perf-next-update" title="광고비 자동 업데이트: {{ auto_sync.label }} (실적 설정에서 바꿈)">다음 업데이트까지 <b>—</b></span>
{% endif %}
<button type="button" class="erp-btn erp-btn-primary{% if ad_running %} is-running{% endif %}" id="perf-ad-sync-btn"
title="{% if ad_running %}업데이트 진행 상황 보기{% else %}지금 보고 있는 기간({{ period.label }}, 오늘까지)의 광고비·ROAS 를 광고 API({{ ad_sync_sources | map(attribute='name') | join('·') }})에서 다시 가져옵니다{% endif %}">
{% if ad_running %}업데이트 중 · 진행 보기{% else %}광고비 업데이트{% endif %}
</button>
</div>
{% endif %}
</div> </div>
<div class="perf-notice" id="perf-sync-result" hidden></div> <div class="perf-notice" id="perf-sync-result" hidden></div>
@@ -237,4 +223,4 @@
} | tojson }}</script> } | tojson }}</script>
{% endblock %} {% endblock %}
{% block scripts %}<script src="/static/performance.js?v=20261102b" defer></script>{% endblock %} {% block scripts %}<script src="/static/performance.js?v=20261105a" defer></script>{% endblock %}
@@ -1,6 +1,6 @@
{% extends "erp_base.html" %} {% extends "erp_base.html" %}
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261102b" />{% endblock %} {% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261105a" />{% endblock %}
{%- macro won(v) -%} {%- macro won(v) -%}
{%- if v is none -%}<span class="perf-na"></span> {%- if v is none -%}<span class="perf-na"></span>
@@ -294,4 +294,4 @@
} | tojson }}</script> } | tojson }}</script>
{% endblock %} {% endblock %}
{% block scripts %}<script src="/static/performance.js?v=20261102b" defer></script>{% endblock %} {% block scripts %}<script src="/static/performance.js?v=20261105a" defer></script>{% endblock %}
@@ -1,6 +1,6 @@
{% extends "erp_base.html" %} {% extends "erp_base.html" %}
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261102b" />{% endblock %} {% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261105a" />{% endblock %}
{%- macro when(v) -%}{{ (v or '')[:16] | replace('T', ' ') or '—' }}{%- endmacro -%} {%- macro when(v) -%}{{ (v or '')[:16] | replace('T', ' ') or '—' }}{%- endmacro -%}
@@ -255,7 +255,7 @@
<div class="erp-card perf-card" id="perf-ad-sources"> <div class="erp-card perf-card" id="perf-ad-sources">
<div class="perf-card-head"> <div class="perf-card-head">
<h2 class="perf-h">광고 API 연동</h2> <h2 class="perf-h">광고 API 연동</h2>
<span class="perf-muted">광고비 탭의 광고비·ROAS 를 광고 API 로 가져옵니다. 인증정보는 [설정]에서 입력하면 암호화해 저장합니다. <span class="perf-muted">광고비 탭의 광고비·ROAS 를 광고 API 로 가져옵니다. 틱톡은 틱톡 탭에서만 보입니다(매출 실적·광고비 탭 합계 제외). 인증정보는 [설정]에서 입력하면 암호화해 저장합니다.
설정이 끝나면 광고비 탭 [광고비 업데이트]와 광고비 자동 업데이트(위 "자동 업데이트" 일정) 때 가져옵니다.</span> 설정이 끝나면 광고비 탭 [광고비 업데이트]와 광고비 자동 업데이트(위 "자동 업데이트" 일정) 때 가져옵니다.</span>
</div> </div>
{% if not ad_api_ready %} {% if not ad_api_ready %}
@@ -347,4 +347,4 @@
</section> </section>
{% endblock %} {% endblock %}
{% block scripts %}<script src="/static/performance.js?v=20261102b" defer></script>{% endblock %} {% block scripts %}<script src="/static/performance.js?v=20261105a" defer></script>{% endblock %}
@@ -0,0 +1,155 @@
{% extends "erp_base.html" %}
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261105a" />{% endblock %}
{%- macro won(v) -%}
{%- if v is none -%}<span class="perf-na"></span>
{%- elif v == 0 -%}<span class="perf-zero">–</span>
{%- else -%}{{ "{:,}".format(v) }}{%- endif -%}
{%- endmacro -%}
{%- macro pct(p) -%}{%- if p is none -%}<span class="perf-zero">–</span>{%- else -%}{{ "{:,}".format(p) }}%{%- endif -%}{%- endmacro -%}
{% block content %}
{#- 틱톡(2026-11-05) — 광고비 탭과 같은 기간 이동·표·그래프. 값은 광고 API 만(읽기 전용, 직접 입력 없음). 매출 실적·광고비 탭 합계에는 안 들어간다. -#}
<section class="perf perf-ads perf-tiktok" id="perf-dash" data-metric="gross" data-fixed-metric="gross">
{% include "performance/_tabs.html" %}
<div class="perf-toolbar">
<div class="perf-quick" role="group" aria-label="기간 선택">
{% for q in nav.quick %}
<a class="perf-seg{% if q.active %} is-active{% endif %}" href="{{ q.url }}">{{ q.label }}</a>
{% endfor %}
<button type="button" class="perf-seg{% if period_kind == 'custom' %} is-active{% endif %}" id="perf-custom-btn">직접선택</button>
</div>
{% include "performance/_period_nav.html" %}
<form class="perf-custom" id="perf-custom" method="get" action="/performance/tiktok"{% if period_kind != 'custom' %} hidden{% endif %}>
<input type="hidden" name="period" value="custom" />
<input class="erp-input perf-date" type="date" name="from" value="{{ period.start.isoformat() }}" required />
<span class="perf-muted">~</span>
<input class="erp-input perf-date" type="date" name="to" value="{{ period.end.isoformat() }}" required />
<button class="erp-btn erp-btn-outline" type="submit">조회</button>
</form>
{% include "performance/_ad_update.html" %}
</div>
<div class="perf-notice" id="perf-sync-result" hidden></div>
{% if migration_needed %}
<div class="perf-notice is-warn">광고비 저장 표가 아직 없습니다. 관리자가 performance_db 마이그레이션 005·006 을 적용해야 합니다.</div>
{% endif %}
{% if not tiktok_configured %}
<div class="perf-notice is-warn">틱톡 API 가 아직 설정되지 않았습니다. {% if is_admin %}<a href="/performance/settings#perf-ad-sources">실적 설정 → 광고 API 연동</a>에서{% else %}관리자가 실적 설정 → 광고 API 연동에서{% endif %} 틱톡 [설정]을 입력하면 데이터가 들어옵니다.</div>
{% endif %}
<div class="perf-kpi-line">
{% for k in kpis %}
<span class="perf-kpi-item">
<span class="perf-muted">{{ k.label }}</span>
{% if k.key == 'roas' %}
<b class="perf-kpi-line-value is-sub">{{ pct(k.pct) }}</b>
{% else %}
<b class="perf-kpi-line-value{% if not k.primary %} is-sub{% endif %}">₩{{ "{:,}".format(k.value) }}</b>
{% if k.delta is none %}<span class="perf-muted">{{ k.cmp }} 비교 없음</span>
{% else %}
{% set up = k.delta > 0 %}
<span class="perf-delta {% if k.delta == 0 %}is-flat{% elif up != (k.invert or false) %}is-up{% else %}is-down{% endif %}">
{% if k.delta > 0 %}▲{% elif k.delta < 0 %}▼{% else %}–{% endif %} {{ "%.1f" | format(k.delta | abs) }}%</span>
<span class="perf-muted">{{ k.cmp }} 대비</span>
{% endif %}
{% endif %}
</span>
{% endfor %}
</div>
<div class="erp-card perf-card">
<div class="perf-card-head">
<h2 class="perf-h">{% if period_kind == 'year' %}월별 틱톡 실적{% else %}일자별 틱톡 실적{% endif %}</h2>
</div>
<div class="erp-table-wrap perf-table-wrap perf-main-wrap">
<table class="perf-table perf-main perf-autofit{% if colw == 'manual' %} perf-colw-manual{% endif %}" data-colw-key="tiktok">
<thead>
<tr>
<th class="perf-th-label" data-col="label">{% if period_kind == 'year' %}월{% else %}날짜{% endif %}</th>
<th data-col="roas">ROAS</th>
<th data-col="spend">광고비</th>
<th data-col="sales">매출</th>
</tr>
</thead>
<tbody>
{% for r in table %}
<tr class="perf-row-{{ r.kind }}{% if r.weekday == 5 %} is-sat{% endif %}{% if r.weekday == 6 or r.holiday %} is-sun{% endif %}{% if r.today %} is-today{% endif %}{% if r.future %} is-future{% endif %}">
<th class="perf-td-label" scope="row">
{{ r.label }}{% if r.holiday %}<small class="perf-hol">{{ r.holiday }}</small>{% endif %}
</th>
<td class="perf-num">{{ pct(r.roas) }}</td>
<td class="perf-num"><span class="v v-gross">{{ won(r.cells.spend.gross) }}</span></td>
<td class="perf-num"><span class="v v-gross">{{ won(r.cells.sales.gross) }}</span></td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
<div class="perf-grid2">
<div class="erp-card perf-card">
<div class="perf-card-head"><h2 class="perf-h">{% if period_kind == 'year' %}월별{% else %}일별{% endif %} 매출 추이</h2></div>
<div class="perf-chart" id="perf-chart-daily"></div>
</div>
<div class="erp-card perf-card">
<div class="perf-card-head"><h2 class="perf-h">{% if period_kind == 'year' %}월별{% else %}일별{% endif %} 광고비 추이</h2></div>
<div class="perf-chart" id="perf-chart-daily2"></div>
</div>
</div>
<div class="erp-card perf-card">
<div class="perf-card-head"><h2 class="perf-h">{{ year.year }}년 누적</h2></div>
<div class="erp-table-wrap">
<table class="perf-table perf-year">
<thead><tr><th class="perf-th-label">월</th><th>ROAS</th><th>광고비</th><th>매출</th></tr></thead>
<tbody>
{% for r in year.rows %}
<tr class="{% if r.future %}is-future{% endif %}">
<th class="perf-td-label" scope="row">{{ r.label }}</th>
<td class="perf-num">{% if not r.future %}{{ pct(r.roas) }}{% endif %}</td>
<td class="perf-num">{{ won(r.spend) }}</td>
<td class="perf-num">{{ won(r.sales) }}</td>
</tr>
{% endfor %}
</tbody>
<tfoot>
<tr class="perf-row-total">
<th class="perf-td-label" scope="row">합계</th>
<td class="perf-num">{{ pct(year.roas) }}</td>
<td class="perf-num">{{ won(year.spend) }}</td>
<td class="perf-num">{{ won(year.sales) }}</td>
</tr>
</tfoot>
</table>
</div>
</div>
<p class="perf-foot perf-muted">
틱톡 광고 API 값입니다. 매출 = 광고에 귀속된 구매금액(웹 구매 + 틱톡샵, 틱톡샵 ID 를 넣으면 GMV Max 포함)이며 틱톡샵 전체 판매액과는 다를 수 있습니다.
ROAS = 매출 ÷ 광고비 × 100, 외화 계정은 그날 환율로 원화로 바꿉니다. 이 값은 매출 실적·광고비 탭 합계에 들어가지 않습니다.
[광고비 업데이트]는 설정된 광고 API 전부를 함께 가져옵니다.
</p>
</section>
<script type="application/json" id="perf-data">{{ {
"period_kind": period_kind,
"today": today,
"period_start": period.start.isoformat(),
"period_end": period.end.isoformat(),
"period_label": period.label,
"daily": chart_sales,
"daily2": chart_spend,
"empty_text": "기간 내 틱톡 데이터가 없습니다.",
"auto_sync": auto_sync,
"update_watch": update_watch
} | tojson }}</script>
{% endblock %}
{% block scripts %}<script src="/static/performance.js?v=20261105a" defer></script>{% endblock %}
@@ -0,0 +1,216 @@
"""틱톡 탭(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
+5
View File
@@ -43,6 +43,7 @@
.perf-tab.is-active { color: #fff; box-shadow: 0 1px 3px rgba(0, 0, 0, .18); } .perf-tab.is-active { color: #fff; box-shadow: 0 1px 3px rgba(0, 0, 0, .18); }
.perf-tab-sales.is-active, .perf-tab-sales.is-active:hover { background: var(--color-deep-black, #1e1f21); } .perf-tab-sales.is-active, .perf-tab-sales.is-active:hover { background: var(--color-deep-black, #1e1f21); }
.perf-tab-ads.is-active, .perf-tab-ads.is-active:hover { background: var(--perf-ad, #d9480f); } .perf-tab-ads.is-active, .perf-tab-ads.is-active:hover { background: var(--perf-ad, #d9480f); }
.perf-tab-tiktok.is-active, .perf-tab-tiktok.is-active:hover { background: var(--perf-tiktok, #e11d48); }
a.perf-tab.is-active:link, a.perf-tab.is-active:visited { color: #fff; } a.perf-tab.is-active:link, a.perf-tab.is-active:visited { color: #fff; }
.perf-tab-gear { .perf-tab-gear {
margin-left: auto; display: inline-flex; align-items: center; justify-content: center; width: 36px; height: 36px; margin-left: auto; display: inline-flex; align-items: center; justify-content: center; width: 36px; height: 36px;
@@ -59,6 +60,10 @@ a.perf-tab.is-active:link, a.perf-tab.is-active:visited { color: #fff; }
.perf-ads td.is-upload .v-gross { color: var(--perf-ad); } .perf-ads td.is-upload .v-gross { color: var(--perf-ad); }
/* 광고 API(구글 광고 등)로 가져온 칸 — 초록 숫자 */ /* 광고 API(구글 광고 등)로 가져온 칸 — 초록 숫자 */
.perf-ads td.is-api .v-gross { color: #1e8e3e; } .perf-ads td.is-api .v-gross { color: #1e8e3e; }
/* 틱톡 화면 — 광고비 화면 틀에 색만 바꿈 */
.perf, .perf-modal { --perf-tiktok: #e11d48; }
.perf-tiktok .perf-quick .perf-seg.is-active { background: var(--perf-tiktok); }
.perf-tiktok .perf-chart .bar { fill: var(--perf-tiktok); }
.perf-ad-actions { margin-left: auto; display: inline-flex; align-items: center; gap: 6px; flex-wrap: wrap; } .perf-ad-actions { margin-left: auto; display: inline-flex; align-items: center; gap: 6px; flex-wrap: wrap; }
/* 광고 API 설정 창 — 서비스 계정 JSON 같은 여러 줄 항목 */ /* 광고 API 설정 창 — 서비스 계정 JSON 같은 여러 줄 항목 */
.perf-cred-multi { width: 100%; font-family: ui-monospace, Consolas, monospace; font-size: 12px; resize: vertical; } .perf-cred-multi { width: 100%; font-family: ui-monospace, Consolas, monospace; font-size: 12px; resize: vertical; }
+6 -5
View File
@@ -358,7 +358,8 @@
root.querySelectorAll(".perf-metric .perf-seg").forEach(function (b) { root.querySelectorAll(".perf-metric .perf-seg").forEach(function (b) {
b.classList.toggle("is-active", b.dataset.metric === m); b.classList.toggle("is-active", b.dataset.metric === m);
}); });
drawDaily(m); drawDaily(m, "perf-chart-daily", data.daily);
drawDaily(m, "perf-chart-daily2", data.daily2); // 틱톡 탭 — 매출·광고비 두 그래프
drawShare(m); drawShare(m);
root.querySelectorAll(".perf-metric-name").forEach(function (n) { n.textContent = METRIC_NAMES[m]; }); root.querySelectorAll(".perf-metric-name").forEach(function (n) { n.textContent = METRIC_NAMES[m]; });
} }
@@ -1045,10 +1046,10 @@
const n = v / p; const n = v / p;
return (n <= 1 ? 1 : n <= 2 ? 2 : n <= 5 ? 5 : 10) * p; return (n <= 1 ? 1 : n <= 2 ? 2 : n <= 5 ? 5 : 10) * p;
} }
function drawDaily(metric) { function drawDaily(metric, boxId, series) {
const box = document.getElementById("perf-chart-daily"); const box = document.getElementById(boxId);
if (!box) return; if (!box) return;
const pts = data.daily || []; const pts = series || [];
const vals = pts.map(function (p) { return p[metric] || 0; }); const vals = pts.map(function (p) { return p[metric] || 0; });
if (!pts.length || vals.every(function (v) { return !v; })) { if (!pts.length || vals.every(function (v) { return !v; })) {
box.innerHTML = '<div class="perf-chart-empty">' + esc(EMPTY_TEXT) + "</div>"; box.innerHTML = '<div class="perf-chart-empty">' + esc(EMPTY_TEXT) + "</div>";
@@ -1332,7 +1333,7 @@
}); });
if (colwReset) colwReset.addEventListener("click", async function () { if (colwReset) colwReset.addEventListener("click", async function () {
if (!(await confirmMsg("매출 실적·광고비 표에서 조절한 열 너비를 모두 지우고 자동 너비로 되돌릴까요?"))) return; if (!(await confirmMsg("매출 실적·광고비 표에서 조절한 열 너비를 모두 지우고 자동 너비로 되돌릴까요?"))) return;
try { localStorage.removeItem("perf_colw_sales"); localStorage.removeItem("perf_colw_ads"); } catch (_) { /* 저장소 없음 */ } try { localStorage.removeItem("perf_colw_sales"); localStorage.removeItem("perf_colw_ads"); localStorage.removeItem("perf_colw_tiktok"); } catch (_) { /* 저장소 없음 */ }
colwReset.textContent = "초기화했습니다"; colwReset.textContent = "초기화했습니다";
setTimeout(function () { colwReset.textContent = "조절한 너비 초기화"; }, 1800); setTimeout(function () { colwReset.textContent = "조절한 너비 초기화"; }, 1800);
}); });
+63
View File
@@ -0,0 +1,63 @@
// 실적 틱톡 탭(2026-11-05) — 실제 브라우저(Chromium).
// python tests/js/render_performance.py
// NODE_PATH=<playwright 경로> PJ_TEST_BROWSER=<Chrome 경로> node tests/js/perf_tiktok.browser.test.js
// 광고비 오른쪽 탭, ROAS·광고비·매출 열, 매출·광고비 그래프 둘, 합계 줄 스크롤 고정, 칸 입력 없음, 스크립트 오류 없음.
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); }
}
(async function () {
const exe = process.env.PJ_TEST_BROWSER;
const browser = await chromium.launch(exe ? { executablePath: exe } : {});
try {
const p = await (await browser.newContext({ viewport: { width: 1400, height: 800 } })).newPage();
const errors = [];
p.on("pageerror", function (e) { errors.push(String(e)); });
await p.route("**/*", function (r) {
const url = new URL(r.request().url()).pathname;
if (url.startsWith("/static/")) {
const f = path.join(ROOT, "app", url);
if (!fs.existsSync(f)) return r.fulfill({ status: 404, body: "" });
const type = f.endsWith(".css") ? "text/css" : f.endsWith(".js") ? "application/javascript" : "font/woff2";
return r.fulfill({ status: 200, contentType: type, body: fs.readFileSync(f) });
}
if (!url.endsWith(".html")) return r.fulfill({ status: 200, contentType: "application/json", body: "{}" });
r.fulfill({ status: 200, contentType: "text/html; charset=utf-8", body: fs.readFileSync(path.join(__dirname, ".out", url.slice(1)), "utf8") });
});
await p.goto("http://erp.test/perf_tiktok_shell.html");
await p.waitForTimeout(300);
const tabs = await p.locator(".perf-tabs-main .perf-tab").allInnerTexts();
check("탭 순서 = 매출 실적·광고비·틱톡", tabs.map(function (t) { return t.replace(/^[a-z_]+\s*/, "").trim(); }).join() === "매출 실적,광고비,틱톡", tabs);
check("틱톡 탭이 켜짐", await p.locator(".perf-tab-tiktok.is-active").count() === 1);
const head = await p.locator("table.perf-main thead th").allInnerTexts();
check("열 = 날짜·ROAS·광고비·매출", head.join() === "날짜,ROAS,광고비,매출", head);
const total = await p.locator("table.perf-main tbody tr").first().innerText();
check("맨 위 기간 합계", total.includes("합계") && total.includes("210,000") && total.includes("630,000") && total.includes("300%"), total);
const day = await p.locator("table.perf-main tbody tr", { hasText: "400%" }).first().innerText();
check("일자 줄 값", day.includes("120,000") && day.includes("480,000"), day);
check("매출 그래프", await p.locator("#perf-chart-daily svg rect.bar").count() > 0);
check("광고비 그래프", await p.locator("#perf-chart-daily2 svg rect.bar").count() > 0);
check("칸 입력 없음", await p.locator("[data-manual-code]").count() === 0);
check("업데이트 버튼", (await p.locator("#perf-ad-sync-btn").innerText()).includes("광고비 업데이트"));
await p.screenshot({ path: path.join(__dirname, ".out", "perf_tiktok.png") });
await p.locator("table.perf-main").hover();
await p.mouse.wheel(0, 500);
await p.waitForTimeout(250);
const stuck = await p.evaluate(function () {
const first = document.querySelector("table.perf-main tbody tr.perf-row-total:first-child th");
const top = first.getBoundingClientRect().top;
return document.querySelector("table.perf-main thead th").getBoundingClientRect().bottom <= top + 2 && top >= 0 && top < 300;
});
check("스크롤해도 제목·합계 줄 고정", stuck);
check("스크립트 오류 없음", errors.length === 0, errors);
} finally {
await browser.close();
}
if (fails.length) { console.log("\n" + fails.length + " FAILED"); process.exit(1); }
console.log("\nALL OK");
})();
+13 -1
View File
@@ -19,7 +19,7 @@ ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)
sys.path.insert(0, ROOT) sys.path.insert(0, ROOT)
OUT_DIR = os.path.join(ROOT, "tests", "js", ".out") OUT_DIR = os.path.join(ROOT, "tests", "js", ".out")
from app.modules.performance.ad_spend import build_ad_dashboard # noqa: E402 from app.modules.performance.ad_spend import build_ad_dashboard, build_tiktok_dashboard # noqa: E402
from app.modules.performance.dashboard import amount_text, build_dashboard, build_settings # noqa: E402 from app.modules.performance.dashboard import amount_text, build_dashboard, build_settings # noqa: E402
from app.modules.performance.router import _auto_sync_settings_ctx # noqa: E402 from app.modules.performance.router import _auto_sync_settings_ctx # noqa: E402
@@ -84,6 +84,12 @@ def env() -> jinja2.Environment:
return e return e
class TiktokStore:
def ad_details(self, code, start, end):
rows = [("2026-10-02", 120000, 480000), ("2026-10-05", 90000, 150000), ("2026-09-20", 50000, 100000)]
return [{"date": d, "amount": a, "roas": None, "metrics": {"매출": b}, "source": "api"} for d, a, b in rows]
def main() -> None: def main() -> None:
os.makedirs(OUT_DIR, exist_ok=True) os.makedirs(OUT_DIR, exist_ok=True)
e = env() e = env()
@@ -117,6 +123,12 @@ def main() -> None:
html = shell.get_template("performance/ads.html").render(**sbase, active_tab="ads", **sactx) html = shell.get_template("performance/ads.html").render(**sbase, active_tab="ads", **sactx)
with open(os.path.join(OUT_DIR, "perf_ads_shell.html"), "w", encoding="utf-8") as f: with open(os.path.join(OUT_DIR, "perf_ads_shell.html"), "w", encoding="utf-8") as f:
f.write(html) f.write(html)
# 틱톡 탭(2026-11-05) — 가상의 광고 API 값
tk = build_tiktok_dashboard(TiktokStore(), kind="month", anchor=date(2026, 10, 7), today=date(2026, 10, 7), holidays={"2026-10-03": "개천절"})
tk.update(auto_sync=ctx["auto_sync"], update_watch={"kind": "ads", "seen": "job-old"}, tiktok_configured=True, ad_running=False,
ad_last_update_at=None, ad_sync_sources=[{"code": "tiktok", "name": "틱톡"}])
with open(os.path.join(OUT_DIR, "perf_tiktok_shell.html"), "w", encoding="utf-8") as f:
f.write(shell.get_template("performance/tiktok.html").render(**sbase, active_tab="tiktok", **tk))
actx =build_ad_dashboard(FakeStore(), kind="month", anchor=date(2026, 10, 7), today=date(2026, 10, 7), actx =build_ad_dashboard(FakeStore(), kind="month", anchor=date(2026, 10, 7), today=date(2026, 10, 7),
sales_codes=["cafe24", "coupang"]) sales_codes=["cafe24", "coupang"])
actx["ad_sync_sources"] = [{"code": "google", "name": "구글 광고"}] # [구글 광고 불러오기] actx["ad_sync_sources"] = [{"code": "google", "name": "구글 광고"}] # [구글 광고 불러오기]