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:
@@ -153,10 +153,8 @@ def test_app_secret_proof_and_version(monkeypatch):
|
||||
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))
|
||||
def test_limits(monkeypatch):
|
||||
_install(monkeypatch, lambda req: httpx.Response(200, json={"data": []}))
|
||||
with pytest.raises(ApiError, match="366"):
|
||||
ma.MetaAdsSource().fetch_days(_ctx(), date(2025, 1, 1), date(2026, 10, 1))
|
||||
with pytest.raises(NotConfigured):
|
||||
@@ -402,3 +400,102 @@ def test_details_endpoint_returns_tabs(monkeypatch):
|
||||
d = TestClient(app).get("/performance/api/ad-spend/meta/details?from=2026-10-01&to=2026-10-31").json()
|
||||
assert d["columns"] == ["광고비(부가세 포함)"] and [t["label"] for t in d["tabs"]] == ["합계", "본계정"]
|
||||
assert d["accounts_missing"] == 0
|
||||
|
||||
|
||||
# ── 외화(USD) 광고 계정 — 그날 환율로 원화 환산(2026-10-16) ──
|
||||
from app.modules.performance import fx # noqa: E402
|
||||
|
||||
FX_ROWS = [{"date": "2026-10-01", "base": "USD", "quote": "KRW", "rate": 1350.0},
|
||||
{"date": "2026-10-02", "base": "USD", "quote": "KRW", "rate": 1360.5}] # 10-03 은 없음 → 10-02 값
|
||||
|
||||
|
||||
def _fx_and_meta(insights_by_account, fx_rows=FX_ROWS, fx_status=200):
|
||||
calls = {"fx": []}
|
||||
|
||||
def handler(req: httpx.Request) -> httpx.Response:
|
||||
if req.url.host == "api.frankfurter.dev":
|
||||
calls["fx"].append(req)
|
||||
return httpx.Response(fx_status, json=fx_rows if fx_status == 200 else {"status": fx_status, "message": "down"})
|
||||
acc = req.url.path.split("/act_")[1].split("/")[0]
|
||||
return httpx.Response(200, json={"data": insights_by_account.get(acc, [])})
|
||||
return handler, calls
|
||||
|
||||
|
||||
def _usd(day, spend, value, **extra):
|
||||
return {**_row(day, spend, account_currency="USD", account_name="US 계정",
|
||||
action_values=[{"action_type": "omni_purchase", "value": value}]), **extra}
|
||||
|
||||
|
||||
def test_usd_account_converted_with_daily_rate(monkeypatch):
|
||||
fx.clear_cache()
|
||||
handler, calls = _fx_and_meta({
|
||||
"333333": [_usd("2026-10-01", "100", "400"), _usd("2026-10-03", "10.5", "0")],
|
||||
"444444": [_row("2026-10-01", "50000", account_name="원화 계정")],
|
||||
})
|
||||
_install(monkeypatch, handler)
|
||||
d1, d3 = ma.MetaAdsSource().fetch_days(_ctx(account_ids="333333,444444"), date(2026, 10, 1), date(2026, 10, 3))
|
||||
q = calls["fx"][0].url.params
|
||||
assert (q["base"], q["quotes"], q["to"]) == ("USD", "KRW", "2026-10-03") and q["from"] <= "2026-10-01"
|
||||
assert len(calls["fx"]) == 1 # 통화마다 기간 한 번
|
||||
# 10-01: USD 100 × 1,350 = 135,000원 + 원화 50,000 = 185,000 → 부가세 포함 203,500
|
||||
# 구매 전환값 USD 400 × 1,350 = 540,000 → ROAS = 540,000 ÷ 185,000 = 291.89%
|
||||
assert (d1.amount, d1.roas) == (203500, Decimal("291.89"))
|
||||
assert d1.metrics["지출 금액(부가세 별도)"] == 185000 and d1.metrics["구매 전환값"] == 540000
|
||||
us = d1.metrics["_accounts"]["333333"]
|
||||
assert (us["amount"], us["roas"]) == (148500, 400.0) # 135,000 × 1.1, ROAS 는 환율과 무관(400 ÷ 100)
|
||||
assert us["metrics"]["지출 금액(USD)"] == 100.0 and us["metrics"]["적용 환율(원)"] == 1350.0
|
||||
assert "적용 환율(원)" not in d1.metrics["_accounts"]["444444"]["metrics"] # 원화 계정엔 없음
|
||||
assert "적용 환율(원)" not in d1.metrics # 합계 표에도 없음
|
||||
# 10-03: 그날 환율 없음 → 10-02 값(1,360.5). 10.5 × 1,360.5 = 14,285.25 → 부가세 포함 15,713.775 → 15,714
|
||||
assert d3.day == date(2026, 10, 3) and d3.amount == 15714
|
||||
assert d3.metrics["_accounts"]["333333"]["metrics"]["적용 환율(원)"] == 1360.5
|
||||
|
||||
|
||||
def test_usd_rate_unavailable_saves_nothing(monkeypatch):
|
||||
fx.clear_cache()
|
||||
handler, _calls = _fx_and_meta({"333333": [_usd("2026-10-01", "100", "0")]}, fx_status=503)
|
||||
_install(monkeypatch, handler)
|
||||
with pytest.raises(ApiError) as info:
|
||||
ma.MetaAdsSource().fetch_days(_ctx(account_ids="333333"), date(2026, 10, 1), date(2026, 10, 1))
|
||||
assert "USD 광고 계정을 원화로 바꿀 환율" in str(info.value) and "503" in str(info.value) and TOKEN not in str(info.value)
|
||||
|
||||
|
||||
def test_krw_rates_fill_cache_and_errors():
|
||||
fx.clear_cache()
|
||||
seen = []
|
||||
|
||||
def route(req):
|
||||
seen.append(req)
|
||||
return httpx.Response(200, json=FX_ROWS + [{"date": "x", "quote": "KRW", "rate": 1}, {"date": "2026-10-02", "quote": "JPY", "rate": 9}])
|
||||
|
||||
client = httpx.Client(transport=httpx.MockTransport(route))
|
||||
rates = fx.krw_rates(client, "usd", date(2026, 10, 1), date(2026, 10, 4), today=date(2026, 10, 10))
|
||||
assert rates == {date(2026, 10, 1): Decimal("1350.0"), date(2026, 10, 2): Decimal("1360.5"),
|
||||
date(2026, 10, 3): Decimal("1360.5"), date(2026, 10, 4): Decimal("1360.5")} # 빈 날 = 앞 날 값
|
||||
# 실제로 고시된 지난 날(10-01·10-02)만 기억 — 그 두 날만 다시 물으면 서버에 묻지 않는다
|
||||
assert fx.krw_rates(client, "USD", date(2026, 10, 1), date(2026, 10, 2), today=date(2026, 10, 10))[date(2026, 10, 2)] == Decimal("1360.5")
|
||||
assert len(seen) == 1
|
||||
fx.krw_rates(client, "USD", date(2026, 10, 1), date(2026, 10, 3), today=date(2026, 10, 10)) # 10-03 은 앞 날 값이라 기억 안 함
|
||||
assert len(seen) == 2
|
||||
assert fx.krw_rates(client, "KRW", date(2026, 10, 1), date(2026, 10, 2)) == {date(2026, 10, 1): 1, date(2026, 10, 2): 1}
|
||||
with pytest.raises(fx.FxError, match="찾지 못했습니다"): # 앞 열흘에도 없음
|
||||
fx.krw_rates(client, "USD", date(2026, 11, 1), date(2026, 11, 1), today=date(2026, 11, 5))
|
||||
|
||||
def down(req):
|
||||
raise httpx.ConnectError("boom")
|
||||
with pytest.raises(fx.FxError, match="ConnectError"):
|
||||
fx.krw_rates(httpx.Client(transport=httpx.MockTransport(down)), "EUR", date(2026, 10, 1), date(2026, 10, 1))
|
||||
|
||||
|
||||
def test_detail_table_rate_total_is_weighted_average():
|
||||
rows = [_stored("2026-10-01", 1000, None, {"적용 환율(원)": 1300.0}),
|
||||
_stored("2026-10-02", 3000, None, {"적용 환율(원)": 1400.0}),
|
||||
_stored("2026-10-03", 0, None, {"적용 환율(원)": 9999.0})] # 광고비 0 인 날은 빼고
|
||||
assert ad_spend.detail_table(rows)["total"]["적용 환율(원)"] == 1375.0 # (1300×1000 + 1400×3000) ÷ 4000
|
||||
|
||||
|
||||
def test_connection_mentions_conversion(monkeypatch):
|
||||
_install(monkeypatch, lambda req: httpx.Response(200, json={"name": "US", "currency": "USD", "timezone_name": "America/Los_Angeles",
|
||||
"account_status": 1}))
|
||||
msg = ma.MetaAdsSource().test_connection(_ctx(account_ids="333333"))
|
||||
assert "그날 환율로 원화로 바꿔 넣습니다" in msg and "가져올 수 없습니다" not in msg
|
||||
|
||||
Reference in New Issue
Block a user