e3e3b42c28
메타가 기간(10/01~10/21)으로 물으면 지출·노출·클릭을 0 으로 주고(링크 클릭·구매는 정상), 하루만 물으면 정상 값을 준다(운영 진단 스크립트로 확인). 지출·노출 0 인데 링크 클릭·구매가 있는 날만 그날 하루를 다시 물어 바꾼다. 집행 없는 계정·진짜 0 인 날은 추가 호출 없음. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
535 lines
31 KiB
Python
535 lines
31 KiB
Python
"""메타 광고 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", account_name="본계정", 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", account_name="서브계정", 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 → 광고비 = 지출 그대로(메타는 부가세 포함, 2026-10-16) → 150,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), 150001, Decimal("400.00"))
|
||
total_metrics = {k: v for k, v in d1.metrics.items() if k != "_accounts"}
|
||
assert total_metrics == {"지출 금액(부가세 포함)": 150001, "노출수": 25000, "클릭수": 500,
|
||
"클릭률(%)": 2.0, "링크 클릭": 380, "구매수": 12, "구매 전환값": 600000, "ROAS(%)": 400.0}
|
||
assert list(d1.metrics)[0] == "지출 금액(부가세 포함)" # 일자별 표 첫 열(× 1.1 없음 — 부가세 별도 열도 없음)
|
||
assert (d2.day, d2.amount, d2.roas, d2.metrics["클릭률(%)"]) == (date(2026, 10, 2), 0, None, 0.0) # 지출 0 → ROAS 없음
|
||
# 계정별(상세보기 탭, 2026-10-16) — 계정마다 따로 변환. 이름은 insights 의 account_name(없는 쪽은 같은 계정 앞 줄 이름)
|
||
a1, a2 = d1.metrics["_accounts"]["1111111111"], d1.metrics["_accounts"]["2222222222"]
|
||
assert (a1["name"], a1["amount"], a1["roas"]) == ("본계정", 100000, 450.0) # 지출 그대로, 450,000 ÷ 100,000
|
||
assert (a2["name"], a2["amount"], a2["roas"]) == ("서브계정", 50001, 300.0) # 50,000.5 → 50,001, 150,000 ÷ 50,000.5 = 299.997 → 300.00
|
||
assert a1["metrics"]["구매수"] == 10 and a2["metrics"]["구매 전환값"] == 150000 and a2["metrics"]["링크 클릭"] == 80
|
||
assert list(d2.metrics["_accounts"]) == ["1111111111"] and d2.metrics["_accounts"]["1111111111"]["name"] == "본계정"
|
||
assert "account_name" in seen[0].url.params["fields"].split(",")
|
||
|
||
|
||
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_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):
|
||
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"] == 150001 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), 150001, 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]
|
||
|
||
|
||
# ── 권한 오류(#200) 진단 — 연결 테스트가 메타에 토큰 정보를 물어 원인 하나를 짚는다(2026-10-16) ──
|
||
DENIED = {"error": {"message": "(#200) Ad account owner has NOT grant ads_management or ads_read permission", "code": 200}}
|
||
|
||
|
||
def _diag_server(debug=None, perms=None, adaccounts=None):
|
||
"""debug/perms/adaccounts = 응답 dict, None 이면 그 조회도 실패(권한 오류)."""
|
||
def handler(req: httpx.Request) -> httpx.Response:
|
||
path = req.url.path
|
||
if path.endswith("/debug_token"):
|
||
assert req.url.params["input_token"] == TOKEN
|
||
return httpx.Response(200, json=debug) if debug is not None else httpx.Response(400, json=DENIED)
|
||
if path.endswith("/me/permissions"):
|
||
return httpx.Response(200, json=perms) if perms is not None else httpx.Response(400, json=DENIED)
|
||
if path.endswith("/me/adaccounts"):
|
||
return httpx.Response(200, json=adaccounts) if adaccounts is not None else httpx.Response(400, json=DENIED)
|
||
return httpx.Response(400, json=DENIED) # 광고 계정 조회 = 권한 오류
|
||
return handler
|
||
|
||
|
||
def _diag(monkeypatch, **server):
|
||
_install(monkeypatch, _diag_server(**server))
|
||
with pytest.raises(AuthFailed) as info:
|
||
ma.MetaAdsSource().test_connection(_ctx(account_ids="1111111111,2222222222"))
|
||
msg = str(info.value)
|
||
assert "(#200)" in msg and "[진단]" in msg and TOKEN not in msg
|
||
return msg
|
||
|
||
|
||
def _debug(scopes, granular=None, exp=0):
|
||
return {"data": {"app_id": "777", "application": "DBX ERP", "is_valid": True, "expires_at": exp,
|
||
"scopes": scopes, "granular_scopes": granular or []}}
|
||
|
||
|
||
ALL_VISIBLE = {"data": [{"account_id": "1111111111"}, {"account_id": "2222222222"}]}
|
||
|
||
|
||
def test_diagnose_missing_ads_read(monkeypatch):
|
||
msg = _diag(monkeypatch, debug=_debug(["public_profile", "business_management"]), adaccounts=ALL_VISIBLE)
|
||
assert "광고 권한: 없음" in msg and "ads_read 권한이 없습니다" in msg and "DBX ERP(777)" in msg and "만료 없음" in msg
|
||
|
||
|
||
def test_diagnose_account_not_assigned(monkeypatch):
|
||
msg = _diag(monkeypatch, debug=_debug(["ads_read"]), adaccounts={"data": [{"account_id": "1111111111"}]})
|
||
assert "광고 권한: ads_read" in msg and "보이는 광고 계정 1개" in msg
|
||
assert "배정되지 않은 계정: act_2222222222" in msg and "act_1111111111" not in msg.split("배정되지 않은 계정")[1].split("→")[0]
|
||
assert "자산 할당" in msg
|
||
|
||
|
||
def test_diagnose_scope_targets_other_accounts(monkeypatch):
|
||
granular = [{"scope": "ads_read", "target_ids": ["1111111111"]}]
|
||
msg = _diag(monkeypatch, debug=_debug(["ads_read"], granular), adaccounts=ALL_VISIBLE)
|
||
assert "다른 계정에만" in msg and "act_2222222222" in msg
|
||
|
||
|
||
def test_diagnose_points_to_app_when_token_and_accounts_ok(monkeypatch):
|
||
msg = _diag(monkeypatch, debug=_debug(["ads_read", "ads_management"]), adaccounts=ALL_VISIBLE)
|
||
assert "광고 권한: ads_management, ads_read" in msg and "앱 쪽 문제" in msg
|
||
|
||
|
||
def test_diagnose_falls_back_to_permissions(monkeypatch):
|
||
perms = {"data": [{"permission": "ads_read", "status": "declined"}, {"permission": "public_profile", "status": "granted"}]}
|
||
msg = _diag(monkeypatch, debug=None, perms=perms, adaccounts=None)
|
||
assert "광고 권한: 없음" in msg and "ads_read 권한이 없습니다" in msg # 거절(declined)은 받은 권한이 아님
|
||
|
||
|
||
def test_diagnose_unknown_when_meta_says_nothing(monkeypatch):
|
||
msg = _diag(monkeypatch, debug=None, perms=None, adaccounts=None)
|
||
assert "원인을 좁히지 못했습니다" in msg
|
||
|
||
|
||
def test_diag_hint_only_outside_connection_test(monkeypatch):
|
||
"""불러오기(fetch_days) 권한 오류엔 '연결 테스트가 진단' 안내, 연결 테스트 자체엔 그 안내 대신 진단 결과."""
|
||
_install(monkeypatch, _diag_server(debug=_debug(["ads_read"]), adaccounts=ALL_VISIBLE))
|
||
with pytest.raises(AuthFailed) as info:
|
||
ma.MetaAdsSource().fetch_days(_ctx(account_ids="1111111111"), date(2026, 10, 1), date(2026, 10, 1))
|
||
assert ma._DIAG_HINT in str(info.value) and "[진단]" not in str(info.value)
|
||
msg = _diag(monkeypatch, debug=_debug(["ads_read"]), adaccounts=ALL_VISIBLE)
|
||
assert ma._DIAG_HINT not in msg
|
||
|
||
|
||
def test_connection_test_shows_full_diagnosis_first(monkeypatch):
|
||
"""설정 [연결 테스트](AdSyncService) 문구 — 진단이 맨 앞, 잘리지 않음, 메타 원문의 긴 주소는 뺌(2026-10-16 "[진…" 잘림)."""
|
||
long_denied = {"error": {"code": 200, "message": "(#200) Ad account owner has NOT grant ads_management or ads_read permission, "
|
||
"refer to https://developers.facebook.com/docs/marketing-api/get-started/authorization/"
|
||
"#permissions-and-features for details"}}
|
||
|
||
def handler(req):
|
||
if req.url.path.endswith("/debug_token"):
|
||
return httpx.Response(200, json=_debug(["ads_read"]))
|
||
if req.url.path.endswith("/me/adaccounts"):
|
||
return httpx.Response(200, json={"data": []})
|
||
return httpx.Response(400, json=long_denied)
|
||
|
||
_install(monkeypatch, handler)
|
||
store = FakeStore()
|
||
svc = ad_sync.AdSyncService(store, CredentialService(None, lambda: None))
|
||
svc._ctx = lambda code, values=None, user="", cleared=None: _ctx(account_ids="1111111111,2222222222")
|
||
res = svc.test_connection("meta")
|
||
msg = res["message"]
|
||
assert not res["ok"] and res["status"] == "auth_failed"
|
||
assert msg.startswith("[진단]") and not msg.endswith("…") and len(msg) > 300 # 예전 300자 한도면 잘렸을 길이
|
||
assert "배정되지 않은 계정: act_1111111111, act_2222222222" in msg and "자산 할당" in msg
|
||
assert "(메타 원문: 메타 API 오류(200): (#200) Ad account owner has NOT grant" in msg
|
||
assert "https://" not in msg and ma._DIAG_HINT not in msg and TOKEN not in msg
|
||
|
||
|
||
# ── 상세보기 [합계 | 계정…] 탭(2026-10-16) ──
|
||
def _stored(day, amount, roas, metrics):
|
||
"""저장소 ad_details 행 모양."""
|
||
return {"date": day, "amount": amount, "roas": roas, "metrics": metrics, "source": "api"}
|
||
|
||
|
||
def test_detail_tabs_total_and_accounts():
|
||
def acc(name, amount, roas, spend_metric):
|
||
return {"name": name, "amount": amount, "roas": roas,
|
||
"metrics": {"지출 금액(부가세 포함)": amount, "노출수": spend_metric, "클릭수": spend_metric // 100, "클릭률(%)": 1.0,
|
||
"ROAS(%)": roas}}
|
||
rows = [
|
||
_stored("2026-10-01", 300, 200.0, {"지출 금액(부가세 포함)": 300, "노출수": 3000, "클릭수": 30, "클릭률(%)": 1.0, "ROAS(%)": 200.0,
|
||
"_accounts": {"1": acc("작은계정", 100, 100.0, 1000), "2": acc("큰계정", 200, 250.0, 2000)}}),
|
||
_stored("2026-10-02", 500, 300.0, {"지출 금액(부가세 포함)": 500, "노출수": 5000, "클릭수": 50, "클릭률(%)": 1.0, "ROAS(%)": 300.0,
|
||
"_accounts": {"2": acc("큰계정(새 이름)", 500, 300.0, 5000)}}),
|
||
_stored("2026-10-03", 70, None, {"지출 금액(부가세 포함)": 70}), # 계정별 저장 전에 가져온 날
|
||
]
|
||
t = ad_spend.detail_table(rows)
|
||
assert "_accounts" not in t["columns"] and "_accounts" not in t["total"] # "_" 키는 표 열·합계에 없음
|
||
assert all("_accounts" not in r["values"] for r in t["rows"]) # 화면으로도 보내지 않음
|
||
out = ad_spend.detail_tabs(rows)
|
||
tabs = out["tabs"]
|
||
assert [x["key"] for x in tabs] == ["total", "2", "1"] # 합계 → 광고비 큰 계정부터
|
||
assert [x["label"] for x in tabs] == ["합계", "큰계정(새 이름)", "작은계정"] # 이름 = 최근 날 이름
|
||
assert tabs[0]["total"] == t["total"] and len(tabs[0]["rows"]) == 3
|
||
big = tabs[1]
|
||
assert big["account_id"] == "2" and [r["date"] for r in big["rows"]] == ["2026-10-01", "2026-10-02"]
|
||
assert big["total"]["지출 금액(부가세 포함)"] == 700 and big["total"]["노출수"] == 7000
|
||
assert big["total"]["ROAS(%)"] == round((200 * 250 + 500 * 300) / 700, 2) # 광고비 가중 평균
|
||
assert [r["date"] for r in tabs[2]["rows"]] == ["2026-10-01"] # 광고를 낸 날만
|
||
assert out["accounts_missing"] == 1
|
||
|
||
|
||
def test_detail_tabs_absent_without_accounts():
|
||
rows = [_stored("2026-10-01", 100, 150.0, {"지출 금액(부가세 포함)": 100, "ROAS(%)": 150.0})]
|
||
assert ad_spend.detail_tabs(rows) == {"tabs": [], "accounts_missing": 0} # 네이버·구글·옛 메타 자료 = 탭 없음
|
||
|
||
|
||
def test_details_endpoint_returns_tabs(monkeypatch):
|
||
import importlib
|
||
|
||
from fastapi import FastAPI
|
||
from fastapi.testclient import TestClient
|
||
|
||
from app.modules.performance import common
|
||
|
||
perf_router = importlib.import_module("app.modules.performance.router")
|
||
rows = [_stored("2026-10-01", 110, 450.0, {"지출 금액(부가세 포함)": 110, "_accounts": {
|
||
"1": {"name": "본계정", "amount": 110, "roas": 450.0, "metrics": {"지출 금액(부가세 포함)": 110}}}})]
|
||
|
||
class Store:
|
||
def ad_details(self, code, start, end):
|
||
assert code == "meta"
|
||
return rows
|
||
|
||
monkeypatch.setattr(common, "require_store", lambda request: (Store(), {"email": "a@x"}))
|
||
app = FastAPI()
|
||
app.include_router(perf_router.router)
|
||
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 = 광고비(메타 지출은 부가세 포함 — × 1.1 없음)
|
||
# 구매 전환값 USD 400 × 1,350 = 540,000 → ROAS = 540,000 ÷ 185,000 = 291.89%
|
||
assert (d1.amount, d1.roas) == (185000, Decimal("291.89"))
|
||
assert d1.metrics["지출 금액(부가세 포함)"] == 185000 and d1.metrics["구매 전환값"] == 540000
|
||
us = d1.metrics["_accounts"]["333333"]
|
||
assert (us["amount"], us["roas"]) == (135000, 400.0) # 100 × 1,350, 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 → 14,285
|
||
assert d3.day == date(2026, 10, 3) and d3.amount == 14285
|
||
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
|
||
|
||
|
||
def test_period_zero_spend_refetches_single_days(monkeypatch):
|
||
"""2026-10-21 운영 — 기간으로 물으면 메타가 지출·노출·클릭을 0 으로(링크 클릭·구매는 정상) 주고, 하루만 물으면 정상.
|
||
그런 날만 하루씩 다시 물어 바꾼다. 집행 없는 계정(행 없음)·진짜 0 인 날(링크 클릭·구매도 0)은 다시 묻지 않는다."""
|
||
real = {"2026-10-19": ("700000", "25000", "900"), "2026-10-20": ("817212", "29103", "983")}
|
||
|
||
def handler(request: httpx.Request) -> httpx.Response:
|
||
tr = json.loads(request.url.params["time_range"])
|
||
if "1111111111" not in str(request.url):
|
||
return httpx.Response(200, json={"data": []}) # 집행 없는 계정
|
||
if tr["since"] == tr["until"]: # 하루 조회 = 정상 값
|
||
spend, impr, clicks = real[tr["since"]]
|
||
return httpx.Response(200, json={"data": [_row(tr["since"], spend, impressions=impr, clicks=clicks,
|
||
inline_link_clicks="941",
|
||
actions=[{"action_type": "omni_purchase", "value": "50"}],
|
||
action_values=[{"action_type": "omni_purchase", "value": "2713820"}])]})
|
||
rows = [_row(d, "0", impressions="0", clicks="0", inline_link_clicks="941", # 기간 조회 = 핵심 칸 0
|
||
actions=[{"action_type": "omni_purchase", "value": "50"}],
|
||
action_values=[{"action_type": "omni_purchase", "value": "2713820"}]) for d in real]
|
||
rows.append(_row("2026-10-21", "0", impressions="0", clicks="0", inline_link_clicks="0")) # 진짜 0 인 날
|
||
return httpx.Response(200, json={"data": rows})
|
||
|
||
seen = _install(monkeypatch, handler)
|
||
days = {d.day.isoformat(): d for d in ma.MetaAdsSource().fetch_days(_ctx(), date(2026, 10, 19), date(2026, 10, 21))}
|
||
assert days["2026-10-20"].amount == 817212 and days["2026-10-20"].metrics["노출수"] == 29103
|
||
assert days["2026-10-20"].metrics["클릭수"] == 983 and days["2026-10-20"].roas == Decimal("332.08")
|
||
assert days["2026-10-19"].amount == 700000
|
||
assert days["2026-10-21"].amount == 0
|
||
singles = [json.loads(r.url.params["time_range"]) for r in seen]
|
||
singles = [t["since"] for t in singles if t["since"] == t["until"]]
|
||
assert sorted(singles) == ["2026-10-19", "2026-10-20"] # 이상한 날만, 계정 1 에만
|
||
assert len(seen) == 2 + 2 # 기간 2(계정 2개) + 하루 2
|