feat(performance): 메타 외화(USD) 광고 계정 — 그날 환율로 원화 환산

- 예전엔 원화가 아닌 계정이면 "원화 계정만" 오류로 저장 안 함 → 이제 지출 금액·구매 전환값을 그날 환율로 원화 환산해
  다른 계정과 합산(광고비 = 지출 × 환율 × 1.1, ROAS 는 비율이라 그대로).
- fx.py: Frankfurter v2(키 없음, 중앙은행 고시 환율 종합, 매일)에서 기간 환율 한 번에, 빈 날은 앞 가장 가까운 날,
  못 구하면 그 회차 저장 안 함, 지난 날 환율은 프로세스 캐시.
- 계정 탭에 지출 금액(USD)·적용 환율(원)(합계 = 광고비 가중 평균), 연결 테스트·설정 안내 문구 갱신.
- 테스트: 혼합 계정 환산·빈 날 환율·환율 장애·캐시·환율 합계, 실제 Frankfurter 응답으로 파싱 확인.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-16 13:59:49 +09:00
parent 36b1f49340
commit 0836d6a926
7 changed files with 236 additions and 21 deletions
+32 -14
View File
@@ -9,7 +9,9 @@
조회(GET /{버전}/act_{계정}/insights)
level=account · time_increment=1(하루씩) · time_range={since, until} · fields=spend·노출·클릭·구매 전환 등.
- 날짜는 광고 계정 시간대 기준. 광고가 없던 날은 행이 없다. 여러 계정은 날짜별로 더한다(계정 통화는 모두 KRW 여야 함).
- 날짜는 광고 계정 시간대 기준. 광고가 없던 날은 행이 없다. 여러 계정은 날짜별로 더한다.
- 원화가 아닌 계정(USD 등, 2026-10-16)은 지출 금액·구매 전환값을 그날 환율로 원화 환산(fx.krw_rates — Frankfurter 중앙은행 고시 환율 종합,
그날 값이 없으면 앞 가장 가까운 날). 계정 탭에 원래 통화 지출·적용 환율. ROAS 는 비율이라 환율과 무관.
- 기여(어트리뷰션)는 메타가 광고 관리자 설정을 그대로 따른다(2025-06 부터 API 의 기여 매개변수는 무시됨) — 화면 값과 같다.
- 구매 전환값·구매수 = action_values·actions 의 구매 항목 하나(omni_purchase → purchase → 픽셀 구매 순서로 처음 있는 것).
메타는 같은 구매를 여러 action_type 에 같은 값으로 겹쳐 주므로 더하지 않는다.
@@ -32,6 +34,7 @@ from typing import Any
import httpx
from ..adapters.base import AdapterContext, AdapterError, ApiError, AuthFailed, CredentialField, NotConfigured, TokenExpired
from .. import fx
from .base import ACCOUNTS_KEY, AdDay, AdSource
API_BASE = "https://graph.facebook.com"
@@ -47,6 +50,7 @@ INSIGHT_FIELDS = "date_start,account_id,account_name,account_currency,spend,impr
M_SPEND, M_COST = "광고비(부가세 포함)", "지출 금액(부가세 별도)"
M_IMPR, M_CLICKS, M_CTR, M_LINK = "노출수", "클릭수", "클릭률(%)", "링크 클릭"
M_PURCHASES, M_VALUE, M_ROAS = "구매수", "구매 전환값", "ROAS(%)"
M_FX = "적용 환율(원)" # 외화 계정 탭에만 — 그날 1 계정 통화 = ? 원(fx.krw_rates)
# 메타 오류 코드 → 고칠 곳 안내(오류 문구 뒤에 붙임). 권한 오류는 연결 테스트가 원인을 진단한다(_diagnose) —
# 불러오기에서 난 오류엔 그 안내를 붙이고, 연결 테스트 자체에서는 진단 결과로 바꿔 쓴다.
@@ -284,7 +288,7 @@ class MetaAdsSource(AdSource):
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 += " (원화가 아닌 계정이 있어 광고비를 가져올 수 없습니다)"
msg += f" (원화가 아닌 계정은 날마다 그날 환율로 원화로 바꿔 넣습니다 — {fx.SOURCE_LABEL})"
return msg
def fetch_days(self, ctx: AdapterContext, start: date, end: date) -> list[AdDay]:
@@ -295,8 +299,7 @@ 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()})}
sums: dict[date, dict[str, Decimal]] = {} # 날짜 → 모든 계정 합
per_acc: dict[date, dict[str, dict[str, Decimal]]] = {} # 날짜 → 계정 → 그 계정 값(상세보기 계정별 탭)
raw: list[tuple[str, date, str, dict[str, Any]]] = [] # (계정, 날짜, 통화, insights 한 줄)
names: dict[str, str] = {}
with _http(ctx) as client:
for acc in accounts:
@@ -305,18 +308,13 @@ class MetaAdsSource(AdSource):
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
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)
raw.append((acc, day, str(r.get("account_currency") or "KRW").upper(), r))
nxt = ((body.get("paging") or {}).get("next") or "").strip()
if not nxt:
break
@@ -325,6 +323,23 @@ class MetaAdsSource(AdSource):
url, page_params = nxt, None # next 주소에 매개변수(토큰 포함)가 다 들어 있다
else:
raise ApiError("메타 API 응답 쪽수가 너무 많습니다. 기간을 줄여 다시 시도하세요.")
# 원화가 아닌 계정(USD 등) — 그날 환율로 원화 환산(2026-10-16). 통화마다 기간 환율을 한 번에.
rates: dict[str, dict[date, Decimal]] = {}
for cur in sorted({c for _a, _d, c, _r in raw if c != "KRW"}):
if not re.fullmatch(r"[A-Z]{3}", cur):
raise ApiError(f"광고 계정 통화({cur[:10]})를 알 수 없습니다.")
try:
rates[cur] = fx.krw_rates(client, cur, start, end)
except fx.FxError as exc:
raise ApiError(f"{cur} 광고 계정을 원화로 바꿀 환율을 가져오지 못했습니다 — {exc}") from None
sums: dict[date, dict[str, Decimal]] = {} # 날짜 → 모든 계정 합(원화)
per_acc: dict[date, dict[str, dict[str, Any]]] = {} # 날짜 → 계정 → 그 계정 값(상세보기 계정별 탭)
for acc, day, cur, r in raw:
rate = Decimal(1) if cur == "KRW" else rates[cur][day]
one = per_acc.setdefault(day, {}).setdefault(acc, {**_zero(), "cur": cur, "rate": rate, "orig": Decimal(0)})
_add(one, r, rate)
one["orig"] += _num(r.get("spend")) # 그 계정 통화 그대로의 지출 금액
_add(sums.setdefault(day, _zero()), r, rate)
out: list[AdDay] = []
for day in sorted(sums):
amount, roas, metrics = _convert(sums[day])
@@ -333,6 +348,9 @@ class MetaAdsSource(AdSource):
accounts_out: dict[str, Any] = {}
for acc, a in per_acc.get(day, {}).items():
a_amount, a_roas, a_metrics = _convert(a)
if a["cur"] != "KRW": # 외화 계정 — 원래 통화 지출과 적용 환율도 보여 준다(계정 탭)
a_metrics[f"지출 금액({a['cur']})"] = float(a["orig"].quantize(Decimal("0.01"), rounding=ROUND_HALF_UP))
a_metrics[M_FX] = float(a["rate"])
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
@@ -344,14 +362,14 @@ 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"))
def _add(acc: dict[str, Any], r: dict[str, Any], rate: Decimal = Decimal(1)) -> None:
"""insights 한 줄(계정 하나·하루)을 더한다 — 금액(지출·구매 전환값)은 × rate(그날 1 계정 통화 = ? 원)로 원화."""
acc["spend"] += _num(r.get("spend")) * rate
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"))
acc["value"] += _purchase(r.get("action_values")) * rate
def _convert(a: dict[str, Decimal]) -> tuple[int, Decimal | None, dict[str, Any]]: