aea3b5e83a
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
99 lines
5.4 KiB
Python
99 lines
5.4 KiB
Python
"""메타 광고 insights 원본 응답 확인(진단, 읽기 전용) — 실적 설정에 저장된 메타 인증정보로 조회해 원본을 보여 준다.
|
|
|
|
2026-10-21: 광고비 탭 메타 일자별 보고서에서 구매수·링크 클릭·구매 전환값은 들어오는데 지출 금액·노출수·클릭수만 0 →
|
|
메타가 그 칸을 어떤 모양으로 보내는지 원본을 보려고 만듦. DB·메타 설정은 바꾸지 않는다(GET 만). 토큰·appsecret_proof 는 출력하지 않는다.
|
|
|
|
운영 서버(웹 컨테이너 dbx-main 안에서, 호스트의 이 파일을 stdin 으로 넘긴다 — 이미지 다시 빌드 불필요):
|
|
하루 원본 JSON 전체: docker exec -i dbx-main python - 2026-10-20 < scripts/meta_insights_raw.py
|
|
기간(앱과 똑같은 요청): docker exec -i dbx-main python - 2026-10-01 2026-10-21 < scripts/meta_insights_raw.py
|
|
→ 계정·날짜마다 원본의 spend·impressions·clicks·inline_link_clicks·받은 칸 이름 한 줄 + 앱 계산(fetch_days) 결과.
|
|
날짜를 빼면 어제(KST) 하루.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import os
|
|
import re
|
|
import sys
|
|
from datetime import date, timedelta
|
|
|
|
import httpx
|
|
|
|
from app.modules.performance.ad_sources.meta_ads import API_BASE, INSIGHT_FIELDS, MetaAdsSource
|
|
from app.modules.performance.ad_sync import AdSyncService, ad_credentials
|
|
from app.modules.performance.common import key_ring
|
|
from app.modules.performance.db import PerformanceDBStore
|
|
from app.timezone import today_kst
|
|
|
|
|
|
def _redact(obj: object, secrets: list[str]) -> object:
|
|
text = json.dumps(obj, ensure_ascii=False, indent=2)
|
|
for s in secrets:
|
|
if s:
|
|
text = text.replace(s, "***")
|
|
return re.sub(r"(access_token|appsecret_proof)=[^&\"\s]+", r"\1=***", text)
|
|
|
|
|
|
def one_day(client: httpx.Client, accounts: list[str], version: str, auth: dict[str, str], day: date) -> None:
|
|
secrets = [v for v in auth.values() if v]
|
|
tr = json.dumps({"since": day.isoformat(), "until": day.isoformat()})
|
|
print(f"# 메타 insights 원본 — {day} · API {version} · 계정 {len(accounts)}개")
|
|
for acc in accounts:
|
|
url = f"{API_BASE}/{version}/act_{acc}/insights"
|
|
for label, fields in (("앱이 쓰는 요청", INSIGHT_FIELDS), ("지출·노출·클릭만", "spend,impressions,clicks,account_currency")):
|
|
resp = client.get(url, params={**auth, "level": "account", "time_increment": 1, "fields": fields, "time_range": tr})
|
|
try:
|
|
body: object = resp.json()
|
|
except ValueError:
|
|
body = resp.text[:2000]
|
|
print(f"\n## act_{acc} · {label} · HTTP {resp.status_code}")
|
|
print(_redact(body, secrets))
|
|
|
|
|
|
def period(client: httpx.Client, accounts: list[str], version: str, auth: dict[str, str], start: date, end: date) -> None:
|
|
"""앱(fetch_days)과 똑같은 매개변수로 기간 조회 — 쪽 넘김까지. 줄마다 핵심 칸만."""
|
|
tr = json.dumps({"since": start.isoformat(), "until": end.isoformat()})
|
|
print(f"# 메타 insights 기간 원본 — {start} ~ {end} · API {version} · 계정 {len(accounts)}개 (앱과 같은 요청: limit=100)")
|
|
for acc in accounts:
|
|
url: str | None = f"{API_BASE}/{version}/act_{acc}/insights"
|
|
params: dict | None = {**auth, "level": "account", "time_increment": 1, "limit": 100, "fields": INSIGHT_FIELDS, "time_range": tr}
|
|
page = 0
|
|
while url and page < 10:
|
|
page += 1
|
|
resp = client.get(url, params=params)
|
|
body = resp.json() if resp.headers.get("content-type", "").startswith(("application/json", "text/javascript")) else {}
|
|
rows = body.get("data") or []
|
|
print(f"\n## act_{acc} · {page}쪽 · HTTP {resp.status_code} · {len(rows)}줄"
|
|
+ (f" · 오류 {json.dumps(body.get('error'), ensure_ascii=False)[:300]}" if body.get("error") else ""))
|
|
for r in rows:
|
|
print(f" {r.get('date_start')} spend={r.get('spend')!r} impressions={r.get('impressions')!r} clicks={r.get('clicks')!r}"
|
|
f" link={r.get('inline_link_clicks')!r} 칸={','.join(sorted(k for k in r if k not in ('actions', 'action_values')))}")
|
|
nxt = ((body.get("paging") or {}).get("next") or "").strip()
|
|
url, params = (nxt, None) if nxt else (None, None)
|
|
|
|
|
|
def main() -> None:
|
|
args = sys.argv[1:]
|
|
store = PerformanceDBStore(os.environ["PERFORMANCE_DB_URL"])
|
|
try:
|
|
sync = AdSyncService(store, ad_credentials(store, key_ring))
|
|
ctx = sync._ctx("meta")
|
|
src = MetaAdsSource()
|
|
accounts, version, auth = src._setup(ctx)
|
|
with httpx.Client(timeout=30.0) as client:
|
|
if len(args) >= 2:
|
|
start, end = date.fromisoformat(args[0]), date.fromisoformat(args[1])
|
|
period(client, accounts, version, auth, start, end)
|
|
print("\n# 앱 계산(fetch_days — 저장은 안 함): 날짜 · 광고비 · 노출수 · 클릭수 · 링크 클릭 · 구매수")
|
|
for d in src.fetch_days(ctx, start, end):
|
|
m = d.metrics
|
|
print(f" {d.day} {d.amount:,} {m.get('노출수')} {m.get('클릭수')} {m.get('링크 클릭')} {m.get('구매수')}")
|
|
else:
|
|
one_day(client, accounts, version, auth, date.fromisoformat(args[0]) if args else today_kst() - timedelta(days=1))
|
|
finally:
|
|
store.close()
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|