feat(performance): 메타 광고 API 연동 — 광고비·구매 ROAS 자동 가져오기

- ad_sources/meta_ads.py + registry 한 줄: Meta Marketing API Insights(기본 v26.0),
  level=account·하루 단위, 광고 계정 여러 개를 날짜별로 합산, paging.next 따라감(graph.facebook.com 밖 주소 거부).
- 설정(실적 설정 → 광고 API 연동): 광고 계정 ID(여러 개)·액세스 토큰(암호화)·앱 시크릿(선택, appsecret_proof)·API 버전.
- 광고비 = 지출 금액 × 1.1(부가세 포함, 구글과 같은 기준), ROAS = 구매 전환값 ÷ 지출 금액(광고 관리자 구매 ROAS).
  구매 값은 omni_purchase → purchase → 픽셀 구매 중 처음 있는 것 하나(겹친 값 더하지 않음). 원화 계정만.
- 메타 오류 코드 안내(토큰 만료 190·권한 200·계정 ID 100·호출 한도), 오류 문구에 토큰·주소 미포함.
- 메타 머리글 = 일자별 보고서 표(DETAIL_CHANNELS), 화면 안내 문구·문서 갱신. 새 마이그레이션·환경변수 없음.
- 테스트: test_meta_ads.py(가짜 메타 서버, 실제 fetch_days → AdSyncService), 메타 연동 반영해 기존 테스트 기대값 갱신.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-16 13:09:43 +09:00
parent 32457e4ce8
commit b397bdf83b
12 changed files with 546 additions and 20 deletions
+1 -1
View File
File diff suppressed because one or more lines are too long
@@ -0,0 +1,280 @@
"""메타 광고(Meta Marketing API — Insights) — 날짜별 광고비·ROAS·보고서 항목.
인증(2026-10-16 사용자: 토큰·광고 계정 ID 준비 완료)
- 액세스 토큰 하나(시스템 사용자 토큰 권장 — 만료 없음. 사용자 토큰은 약 60일 뒤 만료) + 광고 계정 ID 여러 개.
토큰에 ads_read 권한이 있어야 하고, 토큰 주인(시스템 사용자 등)이 각 광고 계정에 배정돼 있어야 한다.
- 메타 문서대로 토큰은 access_token 매개변수로 보낸다. 앱 설정에서 "앱 시크릿 필요"를 켰다면 앱 시크릿을 넣어
appsecret_proof(HMAC-SHA256)를 같이 보낸다. 토큰은 오류 문구에 넣지 않고(주소도 넣지 않음),
ad_sync 가 저장된 비밀값을 다시 한 번 가린다. httpx 요청 로그(INFO)는 주소에 토큰이 들어가므로 켜지 않는다.
조회(GET /{버전}/act_{계정}/insights)
level=account · time_increment=1(하루씩) · time_range={since, until} · fields=spend·노출·클릭·구매 전환 등.
- 날짜는 광고 계정 시간대 기준. 광고가 없던 날은 행이 없다. 여러 계정은 날짜별로 더한다(계정 통화는 모두 KRW 여야 함).
- 기여(어트리뷰션)는 메타가 광고 관리자 설정을 그대로 따른다(2025-06 부터 API 의 기여 매개변수는 무시됨) — 화면 값과 같다.
- 구매 전환값·구매수 = action_values·actions 의 구매 항목 하나(omni_purchase → purchase → 픽셀 구매 순서로 처음 있는 것).
메타는 같은 구매를 여러 action_type 에 같은 값으로 겹쳐 주므로 더하지 않는다.
- 금액(광고비) = **부가세 포함**(구글과 같은 기준 — 2026-10-15 사용자 요청: 쿠팡 청구금액처럼 부가세 포함) = 지출 금액 × 1.1 원 반올림.
- ROAS(%) = 구매 전환값 ÷ 지출 금액(부가세 별도) × 100 — 광고 관리자 "구매 ROAS" 와 같은 값, 지출 0 이면 없음.
- 나머지 항목(노출수·클릭수·클릭률·링크 클릭·구매수·구매 전환값)은 광고비 탭 메타 머리글 → 일자별 표.
API 버전은 설정 칸(기본 DEFAULT_VERSION) — 메타는 버전을 약 2년 뒤 종료하므로 종료 안내가 오면 설정에서 올린다.
"""
from __future__ import annotations
import hashlib
import hmac
import json
import re
from datetime import date
from decimal import ROUND_HALF_UP, Decimal
from typing import Any
import httpx
from ..adapters.base import AdapterContext, ApiError, AuthFailed, CredentialField, NotConfigured, TokenExpired
from .base import AdDay, AdSource
API_BASE = "https://graph.facebook.com"
DEFAULT_VERSION = "v26.0" # 2026-07-29 출시(2026-10 기준 최신)
MAX_DAYS = 366
MAX_ACCOUNTS = 30
MAX_PAGES = 50 # 계정 하나 페이지 상한(하루 한 줄이라 366일도 몇 쪽)
VAT = Decimal("1.1") # 광고비 = 메타 지출 금액 + 부가세 10%
PURCHASE_TYPES = ("omni_purchase", "purchase", "offsite_conversion.fb_pixel_purchase")
INSIGHT_FIELDS = "date_start,account_currency,spend,impressions,clicks,inline_link_clicks,actions,action_values"
# 일자별 표(광고비 탭 메타 머리글) 항목 — 순서 = 열 순서. 클릭률·ROAS 합계는 ad_spend.detail_table 이 이름으로 다시 계산.
M_SPEND, M_COST = "광고비(부가세 포함)", "지출 금액(부가세 별도)"
M_IMPR, M_CLICKS, M_CTR, M_LINK = "노출수", "클릭수", "클릭률(%)", "링크 클릭"
M_PURCHASES, M_VALUE, M_ROAS = "구매수", "구매 전환값", "ROAS(%)"
# 메타 오류 코드 → 고칠 곳 안내(오류 문구 뒤에 붙임)
_HINTS = {
190: "토큰이 만료됐거나 무효입니다. 비즈니스 설정 → 시스템 사용자에서 토큰을 다시 만들어 [액세스 토큰]에 넣으세요(시스템 사용자 토큰은 만료 없음).",
102: "토큰을 읽을 수 없습니다. 토큰을 다시 복사해 넣으세요.",
200: "토큰에 권한이 없습니다. 토큰을 만들 때 ads_read 권한을 고르고, 토큰 주인(시스템 사용자)을 이 광고 계정에 배정했는지 확인하세요.",
10: "토큰에 권한이 없습니다(ads_read). 앱·토큰 권한을 확인하세요.",
100: "요청 값이 올바르지 않습니다 — 광고 계정 ID 가 맞는지, 토큰 주인이 그 계정을 볼 수 있는지 확인하세요.",
803: "광고 계정 ID 를 찾을 수 없습니다(숫자만, act_ 는 있어도 됨).",
4: "메타 API 호출 한도에 걸렸습니다. 잠시 뒤 다시 누르세요.",
17: "메타 API 호출 한도에 걸렸습니다. 잠시 뒤 다시 누르세요.",
613: "메타 API 호출 한도에 걸렸습니다. 잠시 뒤 다시 누르세요.",
80000: "광고 계정 호출 한도에 걸렸습니다. 잠시 뒤 다시 누르세요.",
80004: "광고 계정 호출 한도에 걸렸습니다. 잠시 뒤 다시 누르세요.",
2635: "API 버전이 종료됐습니다 — 실적 설정에서 API 버전을 최신으로 바꾸세요.",
}
_RATE_LIMIT = {4, 17, 613, 80000, 80004}
_AUTH = {10, 102, 200}
_ACCOUNT_STATUS = {1: "운영 중", 2: "사용 중지", 3: "미결제", 7: "검토 대기", 8: "결제 대기", 9: "유예 기간", 100: "종료 대기", 101: "종료"}
def _http(ctx: AdapterContext) -> httpx.Client:
"""HTTP 클라이언트 — 테스트가 바꿔 끼운다."""
return httpx.Client(timeout=ctx.timeout_sec)
def parse_account_ids(raw: str) -> list[str]:
"""'act_123, 456\\n789' → ['123', '456', '789'](순서 유지·중복 제거). 형식이 틀리면 ValueError."""
out: list[str] = []
for part in re.split(r"[\s,;]+", raw or ""):
if not part:
continue
v = part[4:] if part.lower().startswith("act_") else part
if not re.fullmatch(r"\d{5,20}", v):
raise ValueError("광고 계정 ID 는 숫자여야 합니다(act_ 는 있어도 됨, 여러 개는 쉼표나 줄바꿈으로 구분).")
if v not in out:
out.append(v)
if len(out) > MAX_ACCOUNTS:
raise ValueError(f"광고 계정은 {MAX_ACCOUNTS}개까지 넣을 수 있습니다.")
return out
def _num(v: Any) -> Decimal:
"""메타 응답 숫자(문자열로 옴, 0 이면 빠지기도 함) → Decimal."""
if v is None or v == "":
return Decimal(0)
try:
return Decimal(str(v))
except ArithmeticError:
return Decimal(0)
def _won(v: Decimal) -> int:
return int(v.quantize(Decimal(1), rounding=ROUND_HALF_UP))
def _purchase(items: Any) -> Decimal:
"""actions / action_values 목록에서 구매 값 하나(PURCHASE_TYPES 순서로 처음 있는 것 — 겹친 값을 더하지 않는다)."""
by_type = {str((i or {}).get("action_type")): (i or {}).get("value") for i in (items or []) if isinstance(i, dict)}
for t in PURCHASE_TYPES:
if t in by_type:
return _num(by_type[t])
return Decimal(0)
def _meta_error(resp: httpx.Response) -> tuple[int, str]:
"""메타 오류 응답 {"error": {"message", "code", "error_subcode", ...}} → (코드, 문구)."""
try:
err = (resp.json() or {}).get("error") or {}
except ValueError:
return 0, f"HTTP {resp.status_code}"
if not isinstance(err, dict):
return 0, f"HTTP {resp.status_code}"
msg = str(err.get("error_user_msg") or err.get("message") or f"HTTP {resp.status_code}")
try:
code = int(err.get("code") or 0)
except (TypeError, ValueError):
code = 0
return code, msg
class MetaAdsSource(AdSource):
code = "meta"
name = "메타 광고"
docs_url = "https://developers.facebook.com/docs/marketing-api/insights"
note = ("메타 마케팅 API(Insights)로 광고 계정별 날짜별 지출 금액·구매 ROAS·노출수·클릭수·구매를 가져와 계정을 합칩니다. "
"준비: ① ads_read 권한이 있는 액세스 토큰(비즈니스 설정 → 시스템 사용자 토큰 권장 — 만료 없음) "
"② 토큰 주인을 각 광고 계정에 배정. 광고비는 지출 금액 + 부가세 10%(구글과 같은 기준)입니다.")
def credential_fields(self) -> list[CredentialField]:
return [
CredentialField("account_ids", "광고 계정 ID", multiline=True, placeholder="act_1234567890\nact_9876543210",
help="광고비를 가져올 광고 계정 번호(광고 관리자 주소의 act= 뒤 숫자). 여러 개면 줄바꿈이나 쉼표로 — "
"날짜별로 합쳐서 메타 한 칸에 들어갑니다."),
CredentialField("access_token", "액세스 토큰", secret=True,
help="ads_read 권한이 있는 토큰. 저장 후에는 화면에 다시 보이지 않습니다."),
CredentialField("app_secret", "앱 시크릿", secret=True, required=False, placeholder="앱에서 '앱 시크릿 필요'를 켰을 때만",
help="메타 앱 설정 → 고급에서 'API 호출에 앱 시크릿 필요'를 켰다면 넣습니다(appsecret_proof). 아니면 비워 둡니다."),
CredentialField("api_version", "API 버전", required=False, placeholder=DEFAULT_VERSION,
help=f"비워 두면 {DEFAULT_VERSION}. 메타가 버전 종료를 알리면 새 버전(예: v27.0)으로 바꿉니다."),
]
def validate_credentials(self, values: dict[str, str]) -> list[str]:
errors = super().validate_credentials(values)
ids = (values.get("account_ids") or "").strip()
if ids and ids != "__stored__":
try:
parse_account_ids(ids)
except ValueError as exc:
errors.append(str(exc))
token = (values.get("access_token") or "").strip()
if token and token != "__stored__" and (len(token) < 20 or re.search(r"\s", token)):
errors.append("액세스 토큰 형식이 아닙니다(공백 없이 통째로 붙여 넣으세요).")
ver = (values.get("api_version") or "").strip()
if ver and ver != "__stored__" and not re.fullmatch(r"v\d{2,3}\.0", ver):
errors.append("API 버전은 v26.0 처럼 입력하세요.")
return errors
# ── 요청 ──────────────────────────────────────────────
def _setup(self, ctx: AdapterContext) -> tuple[list[str], str, dict[str, str]]:
self.require_configured(ctx)
try:
accounts = parse_account_ids(ctx.credentials.get("account_ids"))
except ValueError as exc:
raise NotConfigured(str(exc)) from None
if not accounts:
raise NotConfigured("광고 계정 ID 를 입력하세요.")
token = (ctx.credentials.get("access_token") or "").strip()
auth = {"access_token": token}
secret = (ctx.credentials.get("app_secret") or "").strip()
if secret:
auth["appsecret_proof"] = hmac.new(secret.encode(), token.encode(), hashlib.sha256).hexdigest()
version = (ctx.credentials.get("api_version") or "").strip() or DEFAULT_VERSION
return accounts, version, auth
def _get(self, ctx: AdapterContext, client: httpx.Client, url: str, params: dict[str, Any] | None) -> dict[str, Any]:
ctx.progress.check()
try:
resp = client.get(url, params=params)
except httpx.HTTPError as exc:
raise ApiError(f"메타 API 에 연결하지 못했습니다({type(exc).__name__}).") from None # 주소(토큰 포함)는 넣지 않는다
if resp.status_code != 200:
code, msg = _meta_error(resp)
hint = _HINTS.get(code, "")
text = f"메타 API 오류({code or resp.status_code}): {msg[:200]}" + (f" — {hint}" if hint else "")
if code == 190:
raise TokenExpired(text)
auth_problem = code in _AUTH or (resp.status_code in (401, 403) and code not in _RATE_LIMIT)
raise (AuthFailed if auth_problem else ApiError)(text)
try:
body = resp.json()
except ValueError:
raise ApiError("메타 API 응답을 읽을 수 없습니다.") from None
return body if isinstance(body, dict) else {}
# ── 연결 테스트 · 가져오기 ─────────────────────────────
def test_connection(self, ctx: AdapterContext) -> str:
accounts, version, auth = self._setup(ctx)
parts: list[str] = []
not_krw = False
with _http(ctx) as client:
for acc in accounts:
info = self._get(ctx, client, f"{API_BASE}/{version}/act_{acc}",
{**auth, "fields": "name,currency,timezone_name,account_status"})
cur = str(info.get("currency") or "?")
not_krw = not_krw or cur != "KRW"
status = _ACCOUNT_STATUS.get(info.get("account_status"), "")
parts.append(f"{info.get('name') or acc}({cur}·{info.get('timezone_name') or '?'}{'·' + status if status else ''})")
msg = f"연결됨 — 광고 계정 {len(accounts)}개: " + ", ".join(parts)
if not_krw:
msg += " (원화가 아닌 계정이 있어 광고비를 가져올 수 없습니다)"
return msg
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}일까지 가져올 수 있습니다.")
accounts, version, auth = self._setup(ctx)
params = {**auth, "level": "account", "time_increment": 1, "limit": 100, "fields": INSIGHT_FIELDS,
"time_range": json.dumps({"since": start.isoformat(), "until": end.isoformat()})}
keys = ("spend", "impr", "clicks", "link", "purchases", "value")
sums: dict[date, dict[str, Decimal]] = {}
with _http(ctx) as client:
for acc in accounts:
url: str | None = f"{API_BASE}/{version}/act_{acc}/insights"
page_params: dict[str, Any] | None = params
for _ in range(MAX_PAGES):
body = self._get(ctx, client, url, page_params)
for r in body.get("data") or []:
cur = str(r.get("account_currency") or "").upper()
if cur and cur != "KRW":
raise ApiError(f"광고 계정 {acc} 의 통화가 {cur} 입니다 — 원화(KRW) 계정만 광고비로 가져옵니다.")
try:
day = date.fromisoformat(str(r.get("date_start")))
except ValueError:
continue
acc_sum = sums.setdefault(day, {k: Decimal(0) for k in keys})
acc_sum["spend"] += _num(r.get("spend"))
acc_sum["impr"] += _num(r.get("impressions"))
acc_sum["clicks"] += _num(r.get("clicks"))
acc_sum["link"] += _num(r.get("inline_link_clicks"))
acc_sum["purchases"] += _purchase(r.get("actions"))
acc_sum["value"] += _purchase(r.get("action_values"))
nxt = ((body.get("paging") or {}).get("next") or "").strip()
if not nxt:
break
if not nxt.startswith(API_BASE + "/"):
raise ApiError("메타 API 다음 쪽 주소가 올바르지 않습니다.")
url, page_params = nxt, None # next 주소에 매개변수(토큰 포함)가 다 들어 있다
else:
raise ApiError("메타 API 응답 쪽수가 너무 많습니다. 기간을 줄여 다시 시도하세요.")
out: list[AdDay] = []
for day in sorted(sums):
a = sums[day]
amount = _won(a["spend"] * VAT) # 광고비 = 부가세 포함
roas = (a["value"] / a["spend"] * 100).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP) if a["spend"] > 0 else None
ctr = (a["clicks"] / a["impr"] * 100).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP) if a["impr"] > 0 else None
metrics = {
M_SPEND: amount,
M_COST: _won(a["spend"]),
M_IMPR: int(a["impr"]),
M_CLICKS: int(a["clicks"]),
M_CTR: float(ctr) if ctr is not None else None,
M_LINK: int(a["link"]),
M_PURCHASES: int(a["purchases"]),
M_VALUE: _won(a["value"]),
M_ROAS: float(roas) if roas is not None else None,
}
out.append(AdDay(day=day, amount=amount, roas=roas, metrics=metrics))
return out
@@ -4,8 +4,9 @@ from __future__ import annotations
from .base import AdSource
from .google_ads import GoogleAdsSource
from .meta_ads import MetaAdsSource
_SOURCES: tuple[AdSource, ...] = (GoogleAdsSource(),)
_SOURCES: tuple[AdSource, ...] = (GoogleAdsSource(), MetaAdsSource())
_BY_CODE = {s.code: s for s in _SOURCES}
+2 -2
View File
@@ -341,8 +341,8 @@ def merge_results(parsed: list[tuple[str, float, ParseResult]]) -> tuple[ParseRe
return merged, sorted(overlap)
# 머리글을 누르면 일자별 상세 표가 열리는 채널(보고서 항목을 보관하는 채널) — 구글은 광고 API 로 가져온 항목(2026-10-15)
DETAIL_CHANNELS = frozenset({"naver", "google"})
# 머리글을 누르면 일자별 상세 표가 열리는 채널(보고서 항목을 보관하는 채널) — 구글(2026-10-15)·메타(2026-10-16)는 광고 API 로 가져온 항목
DETAIL_CHANNELS = frozenset({"naver", "google", "meta"})
def detail_table(rows: list[dict[str, Any]]) -> dict[str, Any]:
+2 -2
View File
@@ -17,8 +17,8 @@ JSON API — 모듈 권한
PUT /performance/api/ad-spend/{channel}/{day} 광고비 한 칸 저장/지움(오늘까지)
POST /performance/api/ad-spend/upload?channel= 광고비 파일 업로드(쿠팡 윙·로켓 광고 보고서 1열 날짜·19열 청구금액,
네이버 광고 보고서 3열 기간·4열 총비용·12열 ROAS + 나머지 항목)
GET /performance/api/ad-spend/{channel}/details?from=&to= 일자별 보고서 항목(네이버·구글 머리글 클릭)
POST /performance/api/ad-sources/{code}/sync 광고 API(구글 광고) 가져오기 — 보는 기간(오늘까지), 92일 넘으면 관리자
GET /performance/api/ad-spend/{channel}/details?from=&to= 일자별 보고서 항목(네이버·구글·메타 머리글 클릭)
POST /performance/api/ad-sources/{code}/sync 광고 API(구글·메타 광고) 가져오기 — 보는 기간(오늘까지), 92일 넘으면 관리자
JSON API — 관리자
GET|PUT /performance/api/ad-sources/{code}/credentials 광고 API 인증정보(마이그레이션 007, 암호화 저장·비밀 원문 없음)
POST /performance/api/ad-sources/{code}/test 광고 API 연결 테스트(저장값 또는 새 입력값)
@@ -89,7 +89,7 @@
<thead>
<tr>
<th class="perf-th-label">{% if period_kind == 'year' %}월{% else %}날짜{% endif %}</th>
{% for c in codes %}{% if c in detail_channels %}<th class="perf-th-detail" title="{{ names[c] }} — 눌러 일자별 광고 보고서 항목 보기. 괄호 = {% if c == 'google' %}구글 광고 ROAS(전환 가치 ÷ 비용){% else %}보고서 ROAS(구매완료 광고수익률){% endif %}"><button type="button" class="perf-detail-btn" data-detail-channel="{{ c }}">{{ names[c] }} <span class="material-symbols-outlined" aria-hidden="true">table_view</span></button></th>{% else %}<th title="{{ names[c] }} — 날짜 칸을 눌러 광고비 입력.{% if roas_basis[c] %} 괄호 = ROAS({{ roas_basis[c] }} 매출 ÷ 광고비){% else %} ROAS 는 계산하지 않음(따로 입력){% endif %}">{{ names[c] }} <span class="perf-manual-mark" aria-hidden="true">✎</span></th>{% endif %}{% endfor %}
{% for c in codes %}{% if c in detail_channels %}<th class="perf-th-detail" title="{{ names[c] }} — 눌러 일자별 광고 보고서 항목 보기. 괄호 = {% if c == 'google' %}구글 광고 ROAS(전환 가치 ÷ 비용){% elif c == 'meta' %}메타 광고 구매 ROAS(구매 전환값 ÷ 지출 금액){% else %}보고서 ROAS(구매완료 광고수익률){% endif %}"><button type="button" class="perf-detail-btn" data-detail-channel="{{ c }}">{{ names[c] }} <span class="material-symbols-outlined" aria-hidden="true">table_view</span></button></th>{% else %}<th title="{{ names[c] }} — 날짜 칸을 눌러 광고비 입력.{% if roas_basis[c] %} 괄호 = ROAS({{ roas_basis[c] }} 매출 ÷ 광고비){% else %} ROAS 는 계산하지 않음(따로 입력){% endif %}">{{ names[c] }} <span class="perf-manual-mark" aria-hidden="true">✎</span></th>{% endif %}{% endfor %}
<th class="perf-th-total">{% if period_kind == 'year' %}월 합계{% else %}일 합계{% endif %}</th>
</tr>
</thead>
@@ -119,10 +119,10 @@
</div>
{% if period_kind != 'year' %}
<p class="perf-muted perf-manual-help">날짜 칸을 눌러 그날 <b>광고비</b>를 직접 입력합니다 — Enter 저장 후 아래 칸, Esc 취소, 비우고 저장하면 지움.
칸은 <b>광고비(ROAS%)</b> — ROAS = 그 쇼핑몰 매출 실적 총매출 ÷ 광고비(합계 열은 전체 매출). 메타는 ROAS 를 계산하지 않고,
네이버는 광고 보고서의 ROAS(구매완료 광고수익률), 구글은 구글 광고 API 의 ROAS(전환 가치 ÷ 비용)를 씁니다 — 네이버·구글 머리글을 누르면 일자별 보고서 항목.
칸은 <b>광고비(ROAS%)</b> — ROAS = 그 쇼핑몰 매출 실적 총매출 ÷ 광고비(합계 열은 전체 매출). 메타는 메타 광고 API 의 구매 ROAS(구매 전환값 ÷ 지출 금액),
네이버는 광고 보고서의 ROAS(구매완료 광고수익률), 구글은 구글 광고 API 의 ROAS(전환 가치 ÷ 비용)를 씁니다 — 네이버·구글·메타 머리글을 누르면 일자별 보고서 항목.
파란 숫자 = 직접 입력, 주황 숫자 = 파일 업로드 값, 초록 숫자 = 광고 API 값. 쿠팡(윙)·쿠팡(로켓)·네이버는 [파일 업로드]로 광고 보고서를 올리면 날짜별로 한 번에 들어갑니다.
구글은 [구글 광고 불러오기](관리자가 실적 설정 → 광고 API 연동을 마친 뒤) 또는 매출 자동 업데이트 때 들어옵니다.</p>
구글·메타는 [구글 광고 불러오기]·[메타 광고 불러오기](관리자가 실적 설정 → 광고 API 연동을 마친 뒤) 또는 매출 자동 업데이트 때 들어옵니다.</p>
{% endif %}
</div>
@@ -200,8 +200,8 @@
</div>
<p class="perf-foot perf-muted">
광고비 기준: 쿠팡(윙)·쿠팡(로켓)은 광고 보고서의 청구금액(+부가가치세), 구글은 구글 광고 비용 + 부가세 10%(부가세 포함).
ROAS = 그 쇼핑몰 매출 ÷ 광고비 × 100(메타는 계산 안 함, 네이버·구글은 광고 쪽 값).
광고비 기준: 쿠팡(윙)·쿠팡(로켓)은 광고 보고서의 청구금액(+부가가치세), 구글·메타는 광고 API 비용(메타 = 지출 금액) + 부가세 10%(부가세 포함).
ROAS = 그 쇼핑몰 매출 ÷ 광고비 × 100(네이버·구글·메타는 광고 쪽 값).
매출 대비 광고비 = 같은 기간 광고비 ÷ 매출 실적 총매출.
메타는 지금은 직접 입력합니다.
</p>
@@ -103,13 +103,13 @@
</div>
{% if is_admin %}
{# 광고 API 연동(2026-10-15, 마이그레이션 007) — 구글 광고 등. 인증정보는 쇼핑몰과 같은 마스터 키로 암호화 저장.
{# 광고 API 연동(2026-10-15, 마이그레이션 007) — 구글 광고·메타 광고(2026-10-16). 인증정보는 쇼핑몰과 같은 마스터 키로 암호화 저장.
가져온 광고비·ROAS 는 광고비 탭(초록 숫자). [설정]·[연결 테스트]는 쇼핑몰 표와 같은 창(/api/ad-sources/…). #}
<div class="erp-card perf-card" id="perf-ad-sources">
<div class="perf-card-head">
<h2 class="perf-h">광고 API 연동</h2>
<span class="perf-muted">광고비 탭의 광고비·ROAS 를 광고 API 로 가져옵니다. 인증정보는 [설정]에서 입력하면 암호화해 저장합니다.
설정이 끝나면 광고비 탭 [구글 광고 불러오기]와 매출 자동 업데이트(30분마다 최근 며칠) 때 함께 가져옵니다.</span>
설정이 끝나면 광고비 탭 [구글 광고 불러오기]·[메타 광고 불러오기]와 매출 자동 업데이트(30분마다 최근 며칠) 때 함께 가져옵니다.</span>
</div>
{% if not ad_api_ready %}
<div class="perf-notice is-warn">광고 API 인증정보 저장 표가 아직 없습니다. performance_db 마이그레이션 007
@@ -142,7 +142,8 @@
</table>
</div>
<p class="perf-foot perf-muted">
구글 광고: 광고비 = 구글 광고 화면의 "비용" + 부가세 10%(부가세 포함), ROAS = 전환 가치 ÷ 비용(구글 화면 값 그대로). 날짜는 광고 계정 시간대 기준이며 원화(KRW) 계정만 가져옵니다.
구글 광고: 광고비 = 구글 광고 화면의 "비용" + 부가세 10%(부가세 포함), ROAS = 전환 가치 ÷ 비용(구글 화면 값 그대로). 날짜는 광고 계정 시간대 기준이며 원화(KRW) 계정만 가져옵니다.<br>
메타 광고: 광고비 = 광고 관리자의 "지출 금액" + 부가세 10%(부가세 포함), ROAS = 구매 전환값 ÷ 지출 금액(광고 관리자 "구매 ROAS"). 광고 계정이 여러 개면 날짜별로 합칩니다. 날짜는 광고 계정 시간대 기준이며 원화(KRW) 계정만 가져옵니다.
가져온 날은 직접 입력·업로드 값보다 우선해 덮어씁니다.
</p>
</div>
@@ -126,7 +126,7 @@ def test_ad_dashboard_month():
assert k["ytd"]["value"] == 370000 and k["mtd"]["value"] == 270000
assert ctx["upload_cells"] == ["2026-10-01|coupang_rocket"]
assert [c["code"] for c in ctx["upload_channels"]] == ["naver", "coupang_wing", "coupang_rocket"]
assert ctx["detail_channels"] == ["google", "naver"] # 구글 = 광고 API 로 가져온 항목(2026-10-15)
assert ctx["detail_channels"] == ["google", "meta", "naver"] # 구글(2026-10-15)·메타(2026-10-16) = 광고 API 로 가져온 항목
assert ctx["api_cells"] == []
day1 = next(r for r in ctx["table"] if r.get("date") == "2026-10-01")
assert day1["cells"]["coupang_rocket"]["gross"] == 220000 and day1["total"]["gross"] == 220000
@@ -306,7 +306,9 @@ def test_sync_endpoint(monkeypatch):
assert r.status_code == 403 # 92일 넘으면 관리자만
admin["v"] = True
assert client.post("/performance/api/ad-sources/google/sync", json={"from": "2026-01-01", "to": "2026-10-15"}).status_code == 200
assert client.post("/performance/api/ad-sources/meta/sync", json={}).status_code == 404
assert client.post("/performance/api/ad-sources/kakao/sync", json={}).status_code == 404 # 광고 API 연동이 없는 채널
r = client.post("/performance/api/ad-sources/meta/sync", json={}) # 메타(2026-10-16) — 연동은 있으나 미설정
assert r.status_code == 400 and "설정되지 않았습니다" in r.json()["detail"]
svc.result = {"ok": False, "code": "google", "name": "구글 광고", "status": "auth_failed", "message": "권한 없음"}
r = client.post("/performance/api/ad-sources/google/sync", json={})
assert r.status_code == 502 and "권한 없음" in r.json()["detail"]
@@ -0,0 +1,226 @@
"""메타 광고 API 연동(2026-10-16) — 입력 검사·요청 매개변수·여러 계정 합산·쪽 넘김·구매 값·부가세·ROAS·오류 안내·저장 서비스.
메타 서버는 가짜(httpx MockTransport)."""
from __future__ import annotations
import hashlib
import hmac
import json
from datetime import date
from decimal import Decimal
import httpx
import pytest
from app.modules.performance import ad_spend, ad_sync
from app.modules.performance.ad_sources import meta_ads as ma
from app.modules.performance.ad_sources.registry import get_source
from app.modules.performance.adapters.base import AdapterContext, ApiError, AuthFailed, NotConfigured, TokenExpired
from app.modules.performance.credentials import CredentialService
TOKEN = "EAAGtesttoken0123456789abcdefSECRET"
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 set(self, key, value):
self.values[key] = value
def known_secrets(self):
return [v for k, v in self.values.items() if v and k in ("access_token", "app_secret")]
def _ctx(**over):
values = {"account_ids": "act_1111111111\n2222222222", "access_token": TOKEN}
values.update(over)
return AdapterContext(code="meta", credentials=Creds(values))
def _install(monkeypatch, handler):
"""가짜 메타 서버 — handler(request) 가 응답을 만든다. 보낸 요청을 돌려준다."""
seen = []
def route(request: httpx.Request) -> httpx.Response:
seen.append(request)
return handler(request)
monkeypatch.setattr(ma, "_http", lambda ctx: httpx.Client(transport=httpx.MockTransport(route)))
return seen
def _row(day, spend, **extra):
r = {"date_start": day, "date_stop": day, "account_currency": "KRW", "spend": spend}
r.update(extra)
return r
# 계정 1: 두 쪽(paging.next), 계정 2: 한 쪽. 10-01 은 두 계정 모두 있음 → 날짜별 합산.
PAGE1 = {"data": [_row("2026-10-01", "100000", impressions="20000", clicks="400", inline_link_clicks="300",
actions=[{"action_type": "omni_purchase", "value": "10"}, {"action_type": "purchase", "value": "10"},
{"action_type": "offsite_conversion.fb_pixel_purchase", "value": "10"},
{"action_type": "link_click", "value": "300"}],
action_values=[{"action_type": "omni_purchase", "value": "450000"},
{"action_type": "purchase", "value": "450000"},
{"action_type": "offsite_conversion.fb_pixel_purchase", "value": "450000"}])],
"paging": {"next": "https://graph.facebook.com/v26.0/act_1111111111/insights?after=CUR&access_token=" + TOKEN}}
PAGE2 = {"data": [_row("2026-10-02", "0", impressions="10")], "paging": {}}
ACC2 = {"data": [_row("2026-10-01", "50000.5", impressions="5000", clicks="100", inline_link_clicks="80",
actions=[{"action_type": "offsite_conversion.fb_pixel_purchase", "value": "2"}],
action_values=[{"action_type": "offsite_conversion.fb_pixel_purchase", "value": "150000"}])]}
def _insights_server(request: httpx.Request) -> httpx.Response:
path, q = request.url.path, request.url.params
if path == "/v26.0/act_1111111111/insights":
return httpx.Response(200, json=PAGE2 if q.get("after") == "CUR" else PAGE1)
if path == "/v26.0/act_2222222222/insights":
return httpx.Response(200, json=ACC2)
return httpx.Response(404, json={"error": {"message": "unknown path", "code": 100}})
def test_registered_and_detail_channel():
assert get_source("meta").name == "메타 광고"
assert "meta" in ad_spend.DETAIL_CHANNELS and "meta" in ad_spend.FILE_ROAS # 머리글 → 일자별 표, ROAS 는 광고 쪽 값
def test_parse_account_ids():
assert ma.parse_account_ids("act_123456, 654321\n\nACT_123456;777777") == ["123456", "654321", "777777"]
assert ma.parse_account_ids("") == []
for bad in ("act_abc", "12-34", "act_"):
with pytest.raises(ValueError):
ma.parse_account_ids(bad)
with pytest.raises(ValueError):
ma.parse_account_ids(",".join(str(100000 + i) for i in range(ma.MAX_ACCOUNTS + 1)))
def test_validate_credentials():
src = ma.MetaAdsSource()
ok = {"account_ids": "act_1111111111", "access_token": TOKEN}
assert src.validate_credentials(ok) == []
assert src.validate_credentials({**ok, "access_token": "__stored__"}) == []
assert {f.key for f in src.visible_fields()} == {"account_ids", "access_token", "app_secret", "api_version"}
assert {f.key for f in src.visible_fields() if f.secret} == {"access_token", "app_secret"}
errs = src.validate_credentials({"account_ids": "act_x", "access_token": "short token", "api_version": "26"})
assert len(errs) == 3 and not any("short token" in e for e in errs) # 토큰 값은 문구에 없음
assert "입력하세요" in " ".join(src.validate_credentials({}))
def test_fetch_days_sums_accounts_pages_and_converts(monkeypatch):
seen = _install(monkeypatch, _insights_server)
days = ma.MetaAdsSource().fetch_days(_ctx(), date(2026, 10, 1), date(2026, 10, 2))
first = seen[0]
assert first.url.path == "/v26.0/act_1111111111/insights"
q = first.url.params
assert q["access_token"] == TOKEN and "appsecret_proof" not in q
assert (q["level"], q["time_increment"]) == ("account", "1")
assert json.loads(q["time_range"]) == {"since": "2026-10-01", "until": "2026-10-02"}
assert {"spend", "action_values", "actions", "account_currency", "date_start"} <= set(q["fields"].split(","))
assert [r.url.params.get("after") for r in seen] == [None, "CUR", None] # 계정 1 두 쪽 → 계정 2
d1, d2 = days
# 10-01: 지출 100,000 + 50,000.5 = 150,000.5 → 광고비(부가세 포함) 165,000.55 → 165,001
# 구매 전환값 = 계정1 omni_purchase 450,000(겹친 purchase·픽셀 값은 더하지 않음) + 계정2 픽셀 150,000 = 600,000
# ROAS = 600,000 ÷ 150,000.5 × 100 = 399.998... → 400.00
assert (d1.day, d1.amount, d1.roas) == (date(2026, 10, 1), 165001, Decimal("400.00"))
assert d1.metrics == {"광고비(부가세 포함)": 165001, "지출 금액(부가세 별도)": 150001, "노출수": 25000, "클릭수": 500,
"클릭률(%)": 2.0, "링크 클릭": 380, "구매수": 12, "구매 전환값": 600000, "ROAS(%)": 400.0}
assert list(d1.metrics)[:2] == ["광고비(부가세 포함)", "지출 금액(부가세 별도)"] # 일자별 표 열 순서
assert (d2.day, d2.amount, d2.roas, d2.metrics["클릭률(%)"]) == (date(2026, 10, 2), 0, None, 0.0) # 지출 0 → ROAS 없음
def test_app_secret_proof_and_version(monkeypatch):
seen = _install(monkeypatch, lambda req: httpx.Response(200, json={"data": []}))
out = ma.MetaAdsSource().fetch_days(_ctx(account_ids="333333", app_secret="appsecret", api_version="v27.0"),
date(2026, 10, 1), date(2026, 10, 1))
assert out == []
assert seen[0].url.path == "/v27.0/act_333333/insights"
expected = hmac.new(b"appsecret", TOKEN.encode(), hashlib.sha256).hexdigest()
assert seen[0].url.params["appsecret_proof"] == expected
def test_non_krw_and_limits(monkeypatch):
_install(monkeypatch, lambda req: httpx.Response(200, json={"data": [{**_row("2026-10-01", "10"), "account_currency": "USD"}]}))
with pytest.raises(ApiError, match="USD"):
ma.MetaAdsSource().fetch_days(_ctx(account_ids="333333"), date(2026, 10, 1), date(2026, 10, 1))
with pytest.raises(ApiError, match="366"):
ma.MetaAdsSource().fetch_days(_ctx(), date(2025, 1, 1), date(2026, 10, 1))
with pytest.raises(NotConfigured):
ma.MetaAdsSource().fetch_days(_ctx(access_token=""), date(2026, 10, 1), date(2026, 10, 1))
# 다음 쪽 주소가 메타가 아니면 따라가지 않는다(토큰을 다른 곳에 보내지 않게)
_install(monkeypatch, lambda req: httpx.Response(200, json={"data": [], "paging": {"next": "https://evil.example/x"}}))
with pytest.raises(ApiError, match="다음 쪽"):
ma.MetaAdsSource().fetch_days(_ctx(account_ids="333333"), date(2026, 10, 1), date(2026, 10, 1))
@pytest.mark.parametrize("code,status,exc,hint", [
(190, 400, TokenExpired, "시스템 사용자"),
(200, 403, AuthFailed, "ads_read"),
(100, 400, ApiError, "광고 계정 ID"),
(17, 400, ApiError, "호출 한도"),
(80004, 403, ApiError, "호출 한도"), # 403 이어도 호출 한도는 인증 실패가 아님
])
def test_errors_are_explained(monkeypatch, code, status, exc, hint):
_install(monkeypatch, lambda req: httpx.Response(status, json={"error": {"message": "meta says no", "code": code}}))
with pytest.raises(exc) as info:
ma.MetaAdsSource().fetch_days(_ctx(account_ids="333333"), date(2026, 10, 1), date(2026, 10, 1))
assert hint in str(info.value) and f"({code})" in str(info.value) and TOKEN not in str(info.value)
def test_network_error_has_no_token(monkeypatch):
def boom(req):
raise httpx.ConnectError("connect failed for " + str(req.url))
_install(monkeypatch, boom)
with pytest.raises(ApiError) as info:
ma.MetaAdsSource().fetch_days(_ctx(account_ids="333333"), date(2026, 10, 1), date(2026, 10, 1))
assert "ConnectError" in str(info.value) and TOKEN not in str(info.value)
def test_connection_message(monkeypatch):
accounts = {"/v26.0/act_1111111111": {"name": "본계정", "currency": "KRW", "timezone_name": "Asia/Seoul", "account_status": 1},
"/v26.0/act_2222222222": {"name": "해외", "currency": "USD", "timezone_name": "America/Los_Angeles", "account_status": 2}}
seen = _install(monkeypatch, lambda req: httpx.Response(200, json=accounts[req.url.path]))
msg = ma.MetaAdsSource().test_connection(_ctx())
assert "광고 계정 2개" in msg and "본계정(KRW·Asia/Seoul·운영 중)" in msg and "해외(USD" in msg and "사용 중지" in msg
assert "원화가 아닌 계정" in msg
assert seen[0].url.params["fields"] == "name,currency,timezone_name,account_status"
class FakeStore:
def __init__(self):
self.replaced, self.status = [], []
def replace_ad_api_range(self, code, start, end, days, *, user=""):
self.replaced.append((code, start, end, days, user))
return len(days)
def record_ad_status(self, code, *, status, ok, error="", kind="test"):
self.status.append((code, status, ok, error, kind))
def test_sync_service_end_to_end(monkeypatch):
"""실제 MetaAdsSource.fetch_days → AdSyncService 저장·상태. 실패 문구에서 토큰은 가린다."""
_install(monkeypatch, _insights_server)
store = FakeStore()
svc = ad_sync.AdSyncService(store, CredentialService(None, lambda: None))
svc._ctx = lambda code, values=None, user="", cleared=None: _ctx()
res = svc.sync("meta", date(2026, 10, 1), date(2026, 10, 2), user="king@x")
assert res["ok"] and res["days"] == 2 and res["total"] == 165001 and res["name"] == "메타 광고"
code, start, end, days, user = store.replaced[0]
assert (code, start, end, user) == ("meta", date(2026, 10, 1), date(2026, 10, 2), "king@x")
assert [(d, amt, roas) for d, amt, roas, _m in days] == [(date(2026, 10, 1), 165001, Decimal("400.00")),
(date(2026, 10, 2), 0, None)]
assert store.status[-1] == ("meta", "ok", True, "", "sync")
# 메타가 오류 문구에 토큰을 되돌려 줘도 저장·화면 문구에서는 가린다
_install(monkeypatch, lambda req: httpx.Response(400, json={"error": {"message": "bad token " + TOKEN, "code": 190}}))
res = svc.sync("meta", date(2026, 10, 1), date(2026, 10, 1))
assert not res["ok"] and res["status"] == "token_expired" and TOKEN not in res["message"]
assert len(store.replaced) == 1 and store.status[-1][1:3] == ("token_expired", False) and TOKEN not in store.status[-1][3]
+18 -2
View File
@@ -378,7 +378,7 @@
머리글 이름 그대로 `metrics`(JSONB). 광고 계정 이름·ID 는 넣지 않음. 직접 입력으로 광고비를 고쳐도 ROAS·상세는 그대로.
- **네이버 머리글 클릭** → 지금 보는 기간의 일자별 보고서 표(`GET /api/ad-spend/naver/details?from=&to=`, `ad_spend.detail_table`):
열 = 파일 머리글 순서, 맨 아래 합계(숫자 항목은 합, 클릭률 = 클릭수 ÷ 노출수, 광고수익률 = 총비용 가중 평균). `DETAIL_CHANNELS`.
- **구글 = 구글 광고 API**(2026-10-15, 마이그레이션 007) — 아래 "광고 API 연동". 메타는 아직 직접 입력.
- **구글 = 구글 광고 API**(2026-10-15, 마이그레이션 007)·**메타 = 메타 마케팅 API**(2026-10-16, 새 마이그레이션 없음) — 아래 "광고 API 연동".
- **광고 API 연동**(2026-10-15) — 구조: `ad_sources/`(채널 하나 = 파일 하나 + `registry.py` 한 줄, 쇼핑몰 어댑터와 같은 입력칸·연결 테스트 모양,
돌려주는 것은 날짜별 `AdDay`(금액·ROAS·항목)) + `ad_sync.py`(가져오기·저장·상태, 같은 채널 동시 실행 차단).
- **인증정보**: 실적 설정 → **광고 API 연동** 카드 [설정](관리자). 쇼핑몰과 같은 마스터 키·AES-256-GCM, 표만 따로
@@ -397,6 +397,19 @@
ROAS = 전환 가치 ÷ 비용(부가세 별도) × 100(소수 둘째, 구글 화면 값 그대로), 항목에 광고비(부가세 포함)·비용(부가세 별도) 둘 다,
항목 `metrics` = 비용·노출수·클릭수·클릭률(%)·전환수·전환 가치·ROAS(%) → 구글 머리글 클릭 = 일자별 표(`DETAIL_CHANNELS`).
통화가 KRW 가 아니면 저장 안 함. 구글 오류 코드는 고칠 곳 안내를 붙여 보여 줌(`_HINTS`: 권한 없음·토큰 미승인 등), 404 = API 버전 종료 안내.
- **메타 광고**(`ad_sources/meta_ads.py`, 2026-10-16): 입력 = 광고 계정 ID(여러 개 — 줄바꿈·쉼표, `act_` 있어도 됨, 30개까지, 비밀 아님 여러 줄) ·
액세스 토큰(비밀 — `ads_read` 권한, 비즈니스 설정 → 시스템 사용자 토큰 권장(만료 없음), 토큰 주인을 각 광고 계정에 배정) ·
앱 시크릿(비밀, 선택 — 앱에서 "API 호출에 앱 시크릿 필요"를 켰을 때만, `appsecret_proof` = HMAC-SHA256(토큰)) · API 버전(기본 `v26.0`).
조회 = `GET graph.facebook.com/{버전}/act_{계정}/insights` `level=account`·`time_increment=1`·`time_range`, 계정마다 `paging.next` 따라감
(다음 쪽 주소가 graph.facebook.com 이 아니면 중단 — 토큰을 다른 곳에 보내지 않음). 토큰은 메타 문서대로 `access_token` 매개변수
(주소에 들어가므로 오류 문구에 주소를 넣지 않고, httpx INFO 요청 로그는 켜지 않는다). 여러 계정은 날짜별로 더함, 날짜는 광고 계정 시간대.
기여(어트리뷰션)는 메타가 광고 관리자 설정을 따른다(2025-06 부터 API 기여 매개변수 무시) — 광고 관리자 화면 값과 같음.
금액 = 지출 금액(`spend`) × 1.1 원 반올림 — **부가세 포함**(구글과 같은 기준), ROAS = 구매 전환값 ÷ 지출 금액(부가세 별도) × 100
(= 광고 관리자 "구매 ROAS"). 구매 전환값·구매수 = `action_values`·`actions` 에서 `omni_purchase` → `purchase` → 픽셀 구매 순서로 처음 있는 것 하나
(메타가 같은 구매를 여러 종류에 같은 값으로 겹쳐 주므로 더하지 않음). 항목 `metrics` = 광고비(부가세 포함)·지출 금액(부가세 별도)·노출수·클릭수·
클릭률(%)·링크 클릭·구매수·구매 전환값·ROAS(%) → 메타 머리글 클릭 = 일자별 표(`DETAIL_CHANNELS`).
원화(KRW)가 아닌 계정이 있으면 저장 안 함. 오류 코드 안내(`_HINTS`): 190 = 토큰 만료·무효(상태 "Token 만료"), 200·10 = 권한(ads_read·계정 배정),
100·803 = 계정 ID, 4·17·613·80000·80004 = 호출 한도, 2635 = 버전 종료. 연결 테스트 = 계정마다 이름·통화·시간대·상태.
- **저장**(`db.replace_ad_api_range`, 한 트랜잭션): API 가 준 날은 `source='api'` 로 덮어씀(직접 입력·업로드 값이 있던 날도),
기간 안에서 API 가 안 준 날(광고 없음)은 **예전 API 값만** 지움 — 직접 입력·업로드 값은 그대로. 화면 초록 숫자 = API 값.
- **언제**: 광고비 탭 **[구글 광고 불러오기]**(설정된 연동만 보임, 지금 보는 기간 → 오늘까지, 모듈 권한자 92일·관리자 366일,
@@ -408,7 +421,7 @@
[총매출|수수료|수수료 차감 매출] 전환(서버가 세 값을 다 그리고 CSS 로 전환, 선택은 localStorage), 일별 추이·쇼핑몰 비중(SVG),
월 누적(비중), 연간 누적(월별, 지나지 않은 달 빈칸). 금액 클릭 → 주문 상세(`GET /api/events`, 31일 이내).
- **설정** `/performance/settings` — 사용/매출 집계 토글, 수수료율(적용 시작일·이력), API 설정 창, 연결 상태
(정상/미설정/인증 실패/Token 만료/API 오류/연동 준비 중/사용 중지, 마지막 테스트·동기화, 최근 오류), **광고 API 연동**(구글 광고 —
(정상/미설정/인증 실패/Token 만료/API 오류/연동 준비 중/사용 중지, 마지막 테스트·동기화, 최근 오류), **광고 API 연동**(구글 광고·메타 광고 —
설정·연결 테스트·연결 상태·마지막 가져오기, 관리자), 마스터 키 상태·재암호화, 테스트 데이터 생성/삭제(`is_sample`).
## 8. 테스트
@@ -421,3 +434,6 @@ python -m app.modules.performance.tests.test_performance # 또는 pytest
동기화 격리·가리기·중복 방지·매출 기준일, 모의 데이터를 DB/네트워크 없이 검증한다.
`tests/test_google_ads.py` — 구글 광고 입력 검사, 토큰 교환·머리글·GAQL 기간·버전, 금액 반올림·ROAS·항목 변환, 오류 안내(권한·버전·통화·키),
광고 인증정보 AAD 이름 공간, 가져오기 저장·상태·비밀값 가림·동시 실행 차단, 불러오기 API(오늘까지 자름·92일 권한·미설정)를 가짜 구글 서버로 검증.
`tests/test_meta_ads.py` — 메타 광고 입력 검사(계정 ID 여러 개·토큰·버전), 요청 매개변수(기간·level·appsecret_proof·버전), 여러 계정 날짜별 합산·
쪽 넘김(메타 밖 주소 거부), 구매 값 겹침 처리·부가세·ROAS·항목, 원화 아님·366일, 오류 코드 안내·토큰 미노출, 연결 테스트 문구,
실제 fetch_days → AdSyncService 저장·상태·토큰 가림을 가짜 메타 서버로 검증.
+1 -1
View File
@@ -225,7 +225,7 @@ function gross(td) { return td.querySelector(".v-gross").textContent.trim(); }
const hb = e.d.querySelector('.perf-main thead [data-detail-channel="naver"]');
const detailChans = Array.from(e.d.querySelectorAll(".perf-main thead [data-detail-channel]")).map(function (b) { return b.dataset.detailChannel; });
// 구글도 광고 API 로 가져온 보고서 항목이 있어 상세 보기(2026-10-15) — 그 밖의 채널은 아님
check("[네이버] 머리글 = 상세 보기 버튼(네이버·구글만)", !!hb && detailChans.sort().join(",") === "google,naver", detailChans);
check("[네이버] 머리글 = 상세 보기 버튼(네이버·구글·메타만)", !!hb && detailChans.sort().join(",") === "google,meta,naver", detailChans);
hb.click(); await settle();
const call = e.calls.find(function (c) { return /\/details/.test(c.url); });
check("[네이버] 지금 기간으로 상세 요청", call && call.url === "/performance/api/ad-spend/naver/details?from=2026-10-01&to=2026-10-31", e.calls);