Merge branch 'fix/meta-ads-permission-diagnosis'

This commit is contained in:
2026-10-16 13:21:51 +09:00
3 changed files with 155 additions and 5 deletions
+69 -5
View File
@@ -31,7 +31,7 @@ from typing import Any
import httpx
from ..adapters.base import AdapterContext, ApiError, AuthFailed, CredentialField, NotConfigured, TokenExpired
from ..adapters.base import AdapterContext, AdapterError, ApiError, AuthFailed, CredentialField, NotConfigured, TokenExpired
from .base import AdDay, AdSource
API_BASE = "https://graph.facebook.com"
@@ -48,11 +48,14 @@ M_SPEND, M_COST = "광고비(부가세 포함)", "지출 금액(부가세 별도
M_IMPR, M_CLICKS, M_CTR, M_LINK = "노출수", "클릭수", "클릭률(%)", "링크 클릭"
M_PURCHASES, M_VALUE, M_ROAS = "구매수", "구매 전환값", "ROAS(%)"
# 메타 오류 코드 → 고칠 곳 안내(오류 문구 뒤에 붙임)
# 메타 오류 코드 → 고칠 곳 안내(오류 문구 뒤에 붙임). 권한 오류는 연결 테스트가 원인을 진단한다(_diagnose) —
# 불러오기에서 난 오류엔 그 안내를 붙이고, 연결 테스트 자체에서는 진단 결과로 바꿔 쓴다.
_DIAG_HINT = "(실적 설정 → 광고 API 연동 → 메타 [연결 테스트]가 원인을 진단합니다)"
_HINTS = {
190: "토큰이 만료됐거나 무효입니다. 비즈니스 설정 → 시스템 사용자에서 토큰을 다시 만들어 [액세스 토큰]에 넣으세요(시스템 사용자 토큰은 만료 없음).",
102: "토큰을 읽을 수 없습니다. 토큰을 다시 복사해 넣으세요.",
200: "토큰에 권한이 없습니다. 토큰을 만들 때 ads_read 권한을 고르고, 토큰 주인(시스템 사용자)을 이 광고 계정에 배정했는지 확인하세요.",
200: "토큰에 권한이 없습니다. 토큰을 만들 때 ads_read 권한을 고르고, 토큰 주인(시스템 사용자)을 이 광고 계정에 배정했는지 확인하세요"
+ _DIAG_HINT + ".",
10: "토큰에 권한이 없습니다(ads_read). 앱·토큰 권한을 확인하세요.",
100: "요청 값이 올바르지 않습니다 — 광고 계정 ID 가 맞는지, 토큰 주인이 그 계정을 볼 수 있는지 확인하세요.",
803: "광고 계정 ID 를 찾을 수 없습니다(숫자만, act_ 는 있어도 됨).",
@@ -202,6 +205,63 @@ class MetaAdsSource(AdSource):
raise ApiError("메타 API 응답을 읽을 수 없습니다.") from None
return body if isinstance(body, dict) else {}
# ── 권한 진단(연결 테스트가 권한 오류를 받았을 때) ─────────
def _diagnose(self, ctx: AdapterContext, client: httpx.Client, version: str, auth: dict[str, str],
accounts: list[str]) -> str:
"""토큰이 받은 권한·권한 대상 계정·볼 수 있는 광고 계정을 메타에 물어 원인을 짚는다(2026-10-16 #200 오류).
조회가 실패해도 예외를 내지 않는다(진단은 덧붙이는 정보). 토큰 값은 문구에 넣지 않는다."""
lines: list[str] = []
scopes: set[str] | None = None
ads_targets: set[str] | None = None # ads_read/ads_management 가 특정 계정에만 걸려 있으면 그 계정들
try: # ① 토큰 점검 — 앱 개발자 토큰·시스템 사용자 토큰이면 같은 토큰으로 된다
d = (self._get(ctx, client, f"{API_BASE}/{version}/debug_token",
{**auth, "input_token": auth["access_token"]}).get("data") or {})
scopes = {str(s) for s in d.get("scopes") or []}
for g in d.get("granular_scopes") or []:
if str((g or {}).get("scope")) in ("ads_read", "ads_management") and (g or {}).get("target_ids"):
ads_targets = (ads_targets or set()) | {str(t) for t in g["target_ids"]}
exp = int(d.get("expires_at") or 0)
expires = "만료 없음" if exp == 0 else date.fromtimestamp(exp).isoformat() + " 만료"
lines.append(f"토큰: 앱 {d.get('application') or d.get('app_id') or '?'}({d.get('app_id') or '?'}) · {expires}"
+ ("" if d.get("is_valid", True) else " · 무효"))
except AdapterError:
try: # ② 토큰 점검을 못 하면 받은 권한 목록만
rows = self._get(ctx, client, f"{API_BASE}/{version}/me/permissions", dict(auth)).get("data") or []
scopes = {str(r.get("permission")) for r in rows if r.get("status") == "granted"}
except AdapterError:
pass
if scopes is not None:
has = sorted(scopes & {"ads_read", "ads_management"})
lines.append("광고 권한: " + (", ".join(has) if has else "없음(ads_read·ads_management 둘 다 없음)"))
visible: set[str] | None = None
try: # ③ 이 토큰으로 볼 수 있는 광고 계정
rows = self._get(ctx, client, f"{API_BASE}/{version}/me/adaccounts",
{**auth, "fields": "account_id,name", "limit": 200}).get("data") or []
visible = {str(r.get("account_id") or "") for r in rows}
lines.append(f"이 토큰으로 보이는 광고 계정 {len(visible)}개")
except AdapterError:
pass
missing = [a for a in accounts if visible is not None and a not in visible]
not_target = [a for a in accounts if ads_targets is not None and a not in ads_targets]
# 결론 — 가장 앞선 원인 하나
if scopes is not None and not scopes & {"ads_read", "ads_management"}:
todo = ("토큰에 ads_read 권한이 없습니다 → 토큰을 새로 만들면서 ads_read 를 체크하세요"
"(비즈니스 설정 → 사용자 → 시스템 사용자 → 새 토큰 생성 → 권한에서 ads_read).")
elif missing:
todo = ("입력한 계정 중 이 토큰 주인에게 배정되지 않은 계정: " + ", ".join("act_" + a for a in missing)
+ " → 비즈니스 설정 → 사용자 → 시스템 사용자(토큰 주인) → [자산 할당] → 광고 계정에서 그 계정을 고르고 "
"'성과 보기'(또는 전체 권한)를 켠 뒤, 토큰을 새로 만들어 넣으세요(배정 전에 만든 토큰은 권한이 안 바뀔 수 있음).")
elif not_target:
todo = ("토큰의 ads_read 권한이 다른 계정에만 걸려 있습니다(대상 아님: " + ", ".join("act_" + a for a in not_target)
+ ") → 토큰을 새로 만들 때 이 광고 계정도 대상에 포함하세요.")
elif visible is not None:
todo = ("토큰 권한·계정 배정은 맞습니다 → 앱 쪽 문제일 가능성이 큽니다: 앱이 이 광고 계정을 가진 비즈니스에 연결돼 있는지"
"(비즈니스 설정 → 계정 → 앱), 앱 대시보드에 Marketing API 제품이 추가돼 있는지, 앱이 '제한 액세스'라면 토큰 주인이 앱의 "
"관리자·개발자 역할인지 확인하세요.")
else:
todo = "토큰 정보를 메타에서 읽지 못해 원인을 좁히지 못했습니다 — 토큰 권한(ads_read)과 광고 계정 배정을 확인하세요."
return " [진단] " + " · ".join(lines + [todo]) if lines else " [진단] " + todo
# ── 연결 테스트 · 가져오기 ─────────────────────────────
def test_connection(self, ctx: AdapterContext) -> str:
accounts, version, auth = self._setup(ctx)
@@ -209,8 +269,12 @@ class MetaAdsSource(AdSource):
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"})
try:
info = self._get(ctx, client, f"{API_BASE}/{version}/act_{acc}",
{**auth, "fields": "name,currency,timezone_name,account_status"})
except AuthFailed as exc: # 권한 오류(#200 등) — 메타에 토큰 정보를 물어 원인을 덧붙인다
base = str(exc).replace(_DIAG_HINT, "")
raise AuthFailed(base + self._diagnose(ctx, client, version, auth, accounts)) from None
cur = str(info.get("currency") or "?")
not_krw = not_krw or cur != "KRW"
status = _ACCOUNT_STATUS.get(info.get("account_status"), "")
@@ -224,3 +224,83 @@ def test_sync_service_end_to_end(monkeypatch):
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
+6
View File
@@ -410,6 +410,12 @@
클릭률(%)·링크 클릭·구매수·구매 전환값·ROAS(%) → 메타 머리글 클릭 = 일자별 표(`DETAIL_CHANNELS`).
원화(KRW)가 아닌 계정이 있으면 저장 안 함. 오류 코드 안내(`_HINTS`): 190 = 토큰 만료·무효(상태 "Token 만료"), 200·10 = 권한(ads_read·계정 배정),
100·803 = 계정 ID, 4·17·613·80000·80004 = 호출 한도, 2635 = 버전 종료. 연결 테스트 = 계정마다 이름·통화·시간대·상태.
**권한 오류 진단**(2026-10-16, 실제로 `(#200) Ad account owner has NOT grant ads_management or ads_read permission` 발생): 연결 테스트가
권한 오류를 받으면 메타에 ① `debug_token`(같은 토큰 — 앱·만료·`scopes`·`granular_scopes.target_ids`, 안 되면 `me/permissions`)
② `me/adaccounts`(이 토큰으로 보이는 계정)를 물어 원인 하나를 짚는다(`_diagnose`): ads_read 없음 → 토큰 재발급 /
입력한 계정이 안 보임 → 시스템 사용자 [자산 할당]에서 광고 계정 배정 후 토큰 재발급 / 권한이 다른 계정에만 → 대상 포함해 재발급 /
다 맞음 → 앱 쪽(비즈니스에 앱 연결·Marketing API 제품·제한 액세스면 토큰 주인이 앱 관리자·개발자인지). 진단 조회 실패는 무시(덧붙이는 정보).
광고비 탭 불러오기에서 난 권한 오류엔 "[연결 테스트]가 원인을 진단" 안내를 붙인다(`_DIAG_HINT`).
- **저장**(`db.replace_ad_api_range`, 한 트랜잭션): API 가 준 날은 `source='api'` 로 덮어씀(직접 입력·업로드 값이 있던 날도),
기간 안에서 API 가 안 준 날(광고 없음)은 **예전 API 값만** 지움 — 직접 입력·업로드 값은 그대로. 화면 초록 숫자 = API 값.
- **언제**: 광고비 탭 **[구글 광고 불러오기]**(설정된 연동만 보임, 지금 보는 기간 → 오늘까지, 모듈 권한자 92일·관리자 366일,