feat(performance): 메타 광고 상세보기 [합계 | 계정별] 탭
- 가져올 때 그날 메타 행 metrics 에 계정별 값(_accounts: 이름·광고비·ROAS·항목, insights account_name)을 함께 저장 — 새 마이그레이션 없음. "_" 키는 일자별 표 열·합계·화면 값에서 제외. - ad_spend.detail_tabs: 합계 탭 + 계정 탭(그 계정이 광고 낸 날만, 광고비 큰 계정부터), 계정별 값 없는 날 수 안내. - 상세보기 창: 탭(주황 강조, 계정 ID 말풍선), 계정 탭은 1원 반올림 차이 안내. 네이버·구글은 그대로 표 하나. - 테스트: 계정별 변환·탭 순서/이름/가중 ROAS·옛 자료 안내·API 응답, jsdom 탭 전환. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -32,7 +32,7 @@ from typing import Any
|
||||
import httpx
|
||||
|
||||
from ..adapters.base import AdapterContext, AdapterError, ApiError, AuthFailed, CredentialField, NotConfigured, TokenExpired
|
||||
from .base import AdDay, AdSource
|
||||
from .base import ACCOUNTS_KEY, AdDay, AdSource
|
||||
|
||||
API_BASE = "https://graph.facebook.com"
|
||||
DEFAULT_VERSION = "v26.0" # 2026-07-29 출시(2026-10 기준 최신)
|
||||
@@ -41,7 +41,7 @@ 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"
|
||||
INSIGHT_FIELDS = "date_start,account_id,account_name,account_currency,spend,impressions,clicks,inline_link_clicks,actions,action_values"
|
||||
|
||||
# 일자별 표(광고비 탭 메타 머리글) 항목 — 순서 = 열 순서. 클릭률·ROAS 합계는 ad_spend.detail_table 이 이름으로 다시 계산.
|
||||
M_SPEND, M_COST = "광고비(부가세 포함)", "지출 금액(부가세 별도)"
|
||||
@@ -295,8 +295,9 @@ class MetaAdsSource(AdSource):
|
||||
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]] = {}
|
||||
sums: dict[date, dict[str, Decimal]] = {} # 날짜 → 모든 계정 합
|
||||
per_acc: dict[date, dict[str, dict[str, Decimal]]] = {} # 날짜 → 계정 → 그 계정 값(상세보기 계정별 탭)
|
||||
names: dict[str, str] = {}
|
||||
with _http(ctx) as client:
|
||||
for acc in accounts:
|
||||
url: str | None = f"{API_BASE}/{version}/act_{acc}/insights"
|
||||
@@ -311,13 +312,11 @@ class MetaAdsSource(AdSource):
|
||||
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"))
|
||||
if r.get("account_name"):
|
||||
names[acc] = str(r["account_name"])[:100]
|
||||
one = per_acc.setdefault(day, {}).setdefault(acc, _zero())
|
||||
_add(one, r)
|
||||
_add(sums.setdefault(day, _zero()), r)
|
||||
nxt = ((body.get("paging") or {}).get("next") or "").strip()
|
||||
if not nxt:
|
||||
break
|
||||
@@ -328,20 +327,46 @@ class MetaAdsSource(AdSource):
|
||||
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,
|
||||
}
|
||||
amount, roas, metrics = _convert(sums[day])
|
||||
# 계정별 값 — 화면 표 열이 아니라 상세보기 계정별 탭용(ad_spend.detail_tabs, "_" 로 시작하는 키는 표 열에서 빠짐).
|
||||
# 계정마다 따로 반올림하므로 계정 광고비 합이 합계와 1원 다를 수 있다.
|
||||
accounts_out: dict[str, Any] = {}
|
||||
for acc, a in per_acc.get(day, {}).items():
|
||||
a_amount, a_roas, a_metrics = _convert(a)
|
||||
accounts_out[acc] = {"name": names.get(acc) or f"act_{acc}", "amount": a_amount,
|
||||
"roas": float(a_roas) if a_roas is not None else None, "metrics": a_metrics}
|
||||
metrics[ACCOUNTS_KEY] = accounts_out
|
||||
out.append(AdDay(day=day, amount=amount, roas=roas, metrics=metrics))
|
||||
return out
|
||||
|
||||
|
||||
def _zero() -> dict[str, Decimal]:
|
||||
return {k: Decimal(0) for k in ("spend", "impr", "clicks", "link", "purchases", "value")}
|
||||
|
||||
|
||||
def _add(acc: dict[str, Decimal], r: dict[str, Any]) -> None:
|
||||
"""insights 한 줄(계정 하나·하루)을 더한다."""
|
||||
acc["spend"] += _num(r.get("spend"))
|
||||
acc["impr"] += _num(r.get("impressions"))
|
||||
acc["clicks"] += _num(r.get("clicks"))
|
||||
acc["link"] += _num(r.get("inline_link_clicks"))
|
||||
acc["purchases"] += _purchase(r.get("actions"))
|
||||
acc["value"] += _purchase(r.get("action_values"))
|
||||
|
||||
|
||||
def _convert(a: dict[str, Decimal]) -> tuple[int, Decimal | None, dict[str, Any]]:
|
||||
"""더한 값 → (광고비(부가세 포함) 원, ROAS %, 일자별 표 항목)."""
|
||||
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
|
||||
return amount, roas, {
|
||||
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,
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user