From 54e4e08802f66f47a1219401c8c57ab6bba17f8a Mon Sep 17 00:00:00 2001 From: king Date: Thu, 5 Nov 2026 14:19:25 +0900 Subject: [PATCH] =?UTF-8?q?feat(=EC=8B=A4=EC=A0=81):=20=ED=8B=B1=ED=86=A1?= =?UTF-8?q?=20=ED=83=AD=EA=B3=BC=20=ED=8B=B1=ED=86=A1=20=EA=B4=91=EA=B3=A0?= =?UTF-8?q?=20API=20=EC=97=B0=EB=8F=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 광고비 탭 오른쪽에 틱톡 탭 추가. 일자별 ROAS, 광고비, 매출을 광고비 탭과 같은 틀로 보여 준다. 실적 설정 광고 API 연동에 틱톡 추가(광고 계정 ID, 액세스 토큰, 선택 틱톡샵 ID). 채널 표(CHANNELS)에 넣지 않아 매출 실적·광고비 탭 합계에는 들어가지 않는다. DB 변경 없음. Co-Authored-By: Claude Opus 5.5 --- app/modules/performance/CLAUDE.md | 10 +- .../performance/ad_sources/registry.py | 6 +- .../performance/ad_sources/tiktok_ads.py | 202 ++++++++++++++++ app/modules/performance/ad_spend.py | 109 +++++++-- app/modules/performance/router.py | 39 +++- .../templates/performance/_ad_update.html | 15 ++ .../templates/performance/_tabs.html | 5 +- .../templates/performance/ads.html | 20 +- .../templates/performance/index.html | 4 +- .../templates/performance/settings.html | 6 +- .../templates/performance/tiktok.html | 155 +++++++++++++ .../performance/tests/test_tiktok_ads.py | 216 ++++++++++++++++++ app/static/performance.css | 5 + app/static/performance.js | 11 +- tests/js/perf_tiktok.browser.test.js | 63 +++++ tests/js/render_performance.py | 14 +- 16 files changed, 819 insertions(+), 61 deletions(-) create mode 100644 app/modules/performance/ad_sources/tiktok_ads.py create mode 100644 app/modules/performance/templates/performance/_ad_update.html create mode 100644 app/modules/performance/templates/performance/tiktok.html create mode 100644 app/modules/performance/tests/test_tiktok_ads.py create mode 100644 tests/js/perf_tiktok.browser.test.js diff --git a/app/modules/performance/CLAUDE.md b/app/modules/performance/CLAUDE.md index cceb2a7..053370d 100644 --- a/app/modules/performance/CLAUDE.md +++ b/app/modules/performance/CLAUDE.md @@ -106,9 +106,17 @@ - **표 몸통 칸에는 풍선 도움말(title) 없음**(2026-10-22 사용자 요청) — 입력 칸·날짜 칸(공휴일은 칸 안 글자)·광고비 줄 모두. 열 머리글 말풍선은 그대로. 새 칸 기능에 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`) -- 탭은 [매출 실적]·[광고비] + 맨 오른쪽 설정 톱니. +- 탭은 [매출 실적]·[광고비]·[틱톡] + 맨 오른쪽 설정 톱니. - **표 모양(2026-10-22)** — 매출 실적 표와 같은 `perf-autofit`(열 너비 = 내용 길이, 날짜 열 가로 스크롤 고정). - **기타광고비** 열(`etc`, 애터미아자몰 오른쪽, 2026-10-22) — 쇼핑몰에 딸리지 않은 광고비 직접 입력. 매출 쇼핑몰이 없어(`ad_spend.NO_SALES`) ROAS 없음·매출 탭 광고비 줄에 안 나옴, 광고비 합계·매출 대비 광고비에는 들어감. - `ad_spend.py`, 마이그레이션 005 `perf_ad_spend`. 구글·메타·네이버·쿠팡(윙)·쿠팡(로켓)·오늘의집·G마켓·카카오·GS샵·11번가·롯데ON·토스·애터미아자몰 일 광고비를 연·월·일로. diff --git a/app/modules/performance/ad_sources/registry.py b/app/modules/performance/ad_sources/registry.py index d5d9a18..040591b 100644 --- a/app/modules/performance/ad_sources/registry.py +++ b/app/modules/performance/ad_sources/registry.py @@ -1,12 +1,14 @@ -"""광고 API 연동 목록 — 새 광고 채널은 파일 하나 + 여기 한 줄(채널 코드는 ad_spend.CHANNELS 와 같아야 한다).""" +"""광고 API 연동 목록 — 새 광고 채널은 파일 하나 + 여기 한 줄(채널 코드는 ad_spend.CHANNELS 와 같아야 한다 — +틱톡만 예외: 광고비 탭에 안 나오게 CHANNELS 에 넣지 않고 틱톡 탭이 따로 읽는다).""" from __future__ import annotations from .base import AdSource from .google_ads import GoogleAdsSource 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} diff --git a/app/modules/performance/ad_sources/tiktok_ads.py b/app/modules/performance/ad_sources/tiktok_ads.py new file mode 100644 index 0000000..1dd0fcb --- /dev/null +++ b/app/modules/performance/ad_sources/tiktok_ads.py @@ -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"]), + }) diff --git a/app/modules/performance/ad_spend.py b/app/modules/performance/ad_spend.py index 133f7a1..90e4f8d 100644 --- a/app/modules/performance/ad_spend.py +++ b/app/modules/performance/ad_spend.py @@ -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) diff --git a/app/modules/performance/router.py b/app/modules/performance/router.py index 6fdd1c4..2d7b95d 100644 --- a/app/modules/performance/router.py +++ b/app/modules/performance/router.py @@ -241,8 +241,15 @@ def ads_page( custom_from=_parse_date(from_), custom_to=_parse_date(to), holidays=_holidays(), sales_codes=total_sales_codes(_sales_marketplaces(store)), ) - # [광고비 업데이트](2026-10-20) — 관리자가 실적 설정에서 인증정보를 넣은 광고 연동 전부를 진행 창으로. - # 마지막 업데이트 = 광고 API 마지막 성공 가져오기, 다음 업데이트 = 매출 자동 업데이트와 같은 회차. + _ad_update_ctx(store, user, ctx) + _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 .ad_sources.registry import get_source # 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["auto_sync"] = _auto_sync_ctx(store, "ads") 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) - return render_template(request, "performance/ads.html", - {**common.base_ctx(user, active_tab="ads", page_title="광고비"), **ctx}) + return render_template(request, "performance/tiktok.html", + {**common.base_ctx(user, active_tab="tiktok", page_title="틱톡"), **ctx}) @router.get("/settings", response_class=HTMLResponse) diff --git a/app/modules/performance/templates/performance/_ad_update.html b/app/modules/performance/templates/performance/_ad_update.html new file mode 100644 index 0000000..fa9aa05 --- /dev/null +++ b/app/modules/performance/templates/performance/_ad_update.html @@ -0,0 +1,15 @@ +{# 광고비 업데이트(2026-10-20, 광고비·틱톡 탭 공통) — 매출 탭과 같은 모양: 마지막 업데이트(광고 API 마지막 성공) · 다음 자동 업데이트(실적 설정의 광고비 일정) + · [광고비 업데이트](설정된 광고 API 전부, 진행 창). 업데이트 중에도 누르면 진행 창을 다시 연다. #} +{% if ad_sync_sources %} +
+ 마지막 업데이트 + {{ (ad_last_update_at or '')[:16] | replace('T', ' ') or '—' }} + {% if auto_sync %} + 다음 업데이트까지 — + {% endif %} + +
+{% endif %} diff --git a/app/modules/performance/templates/performance/_tabs.html b/app/modules/performance/templates/performance/_tabs.html index 9fc886e..e9b2b98 100644 --- a/app/modules/performance/templates/performance/_tabs.html +++ b/app/modules/performance/templates/performance/_tabs.html @@ -1,4 +1,4 @@ -{# 실적 모듈 탭 — [매출 실적] [광고비] 큰 탭 둘(아이콘 + 색으로 구분) + 맨 오른쪽 설정 톱니(프로젝트 모듈과 같은 아이콘). +{# 실적 모듈 탭 — [매출 실적] [광고비] [틱톡] 큰 탭(아이콘 + 색으로 구분) + 맨 오른쪽 설정 톱니(프로젝트 모듈과 같은 아이콘). 설정은 모듈 권한자 모두(일반 사용자 화면은 수수료율만, 나머지는 관리자). #}