Files
dbx-main/app/modules/performance/ad_sync.py
T
king e7b1e17579 feat(performance): 광고비 탭 구글 광고비·ROAS 를 Google Ads API 로 가져오기 + 설정에서 키 입력
- 실적 설정 "광고 API 연동" 카드: 개발자 토큰·고객 ID·로그인 고객 ID(MCC)·서비스 계정 JSON·API 버전(기본 v26)
  → 쇼핑몰과 같은 마스터 키로 암호화(perf_ad_credentials, AAD perf:ad:…), 연결 테스트·상태(perf_ad_source_status)
- ad_sources/(채널 하나 = 파일 하나) + google_ads.py: 서비스 계정 JWT 토큰(httpx) → REST searchStream GAQL,
  비용(cost_micros 원 반올림, 부가세 별도)·ROAS(전환 가치÷비용)·노출·클릭·전환 항목, KRW 계정만, 오류 코드별 안내
- ad_sync.py: 기간 한 트랜잭션 저장(source='api', 안 준 날은 예전 API 값만 지움), 같은 채널 동시 실행 차단, 비밀값 가림
- 광고비 탭 [구글 광고 불러오기](보는 기간, 92일 넘으면 관리자) + 매출 자동 업데이트 회차에 함께, API 값 초록 숫자,
  구글 머리글 = 일자별 항목 표
- 마이그레이션 007, 테스트 test_google_ads.py(가짜 구글 서버) — performance 테스트 83개 통과

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 15:10:03 +09:00

120 lines
6.0 KiB
Python

"""광고 API 가져오기 — 인증정보(perf_ad_credentials) → 광고 연동(ad_sources) → perf_ad_spend(source='api').
- 광고비 탭 [구글 광고 불러오기](보고 있는 기간) · 매출 자동 업데이트 회차(최근 N일, auto_sync) · 실적 설정 연결 테스트가 쓴다.
- 같은 광고 채널은 동시에 한 번만(프로세스 안 잠금) — 두 번째 요청은 바로 "진행 중" 오류.
- 저장은 기간 단위 한 트랜잭션(db.replace_ad_api_range): API 가 준 날은 덮어쓰고, 안 준 날은 예전 API 값만 지운다.
- 오류 문구는 저장된 비밀값을 가린 뒤 기록·반환한다(security.redact).
"""
from __future__ import annotations
import logging
import threading
from datetime import date
from typing import Any, Callable
from .ad_sources.registry import all_sources, get_source
from .adapters.base import STATUS_LABELS, AdapterContext, AdapterError
from .credentials import CredentialService
from .db import AdCredentialTable
from .security.redact import redact_text
logger = logging.getLogger("performance.ad_sync")
AD_NS = "ad:" # 광고 인증정보 암호문 이름 공간(credentials.aad_for)
_locks: dict[str, threading.Lock] = {}
_locks_guard = threading.Lock()
def _lock(code: str) -> threading.Lock:
with _locks_guard:
return _locks.setdefault(code, threading.Lock())
class AdSyncBusy(Exception):
"""같은 광고 채널 가져오기가 이미 진행 중."""
def ad_credentials(store: Any, ring_loader: Callable[[], Any]) -> CredentialService:
"""광고 API 인증정보 서비스 — 쇼핑몰과 같은 서비스, 저장소만 광고 표."""
return CredentialService(AdCredentialTable(store), ring_loader, aad_ns=AD_NS)
class AdSyncService:
def __init__(self, store: Any, creds: CredentialService) -> None:
self._store = store
self._creds = creds
def configured(self) -> dict[str, bool]:
return self._creds.configured_codes(list(all_sources()))
def _ctx(self, code: str, *, values: dict[str, str] | None = None, user: str = "") -> AdapterContext:
acc = self._creds.accessor(code, overrides=values, persist=values is None, user=user)
return AdapterContext(code=code, credentials=acc, timeout_sec=30.0)
@staticmethod
def _message(exc: Exception, ctx: AdapterContext) -> str:
known = getattr(ctx.credentials, "known_secrets", lambda: [])()
return redact_text(str(getattr(exc, "message", "") or exc), known)
def test_connection(self, code: str, *, values: dict[str, str] | None = None, user: str = "") -> dict[str, Any]:
"""values 가 있으면 저장하지 않은 새 입력값(빈 칸은 저장값)으로 시험 — 그때는 상태를 기록하지 않는다."""
src = get_source(code)
if src is None:
return {"ok": False, "status": "api_error", "label": STATUS_LABELS["api_error"], "message": "알 수 없는 광고 연동입니다."}
ctx = self._ctx(code, values=values, user=user)
try:
src.require_configured(ctx)
msg = src.test_connection(ctx)
ok, status = True, "ok"
except AdapterError as exc:
ok, status, msg = False, exc.status, self._message(exc, ctx)
except Exception as exc: # noqa: BLE001 — 예상 못 한 오류도 화면에는 짧게
logger.exception("ad test failed: %s", code)
ok, status, msg = False, "api_error", f"연결 테스트 중 오류: {type(exc).__name__}"
if not values:
self._store.record_ad_status(code, status=status, ok=ok, error="" if ok else msg, kind="test")
return {"ok": ok, "status": status, "label": STATUS_LABELS.get(status, status), "message": msg,
"unsaved": bool(values)}
def sync(self, code: str, start: date, end: date, *, user: str = "") -> dict[str, Any]:
"""기간 가져오기 → 저장. 결과 {ok, days, total, from, to} 또는 {ok: False, status, message}. 진행 중이면 AdSyncBusy."""
src = get_source(code)
if src is None:
raise KeyError(code)
lock = _lock(code)
if not lock.acquire(blocking=False):
raise AdSyncBusy(f"{src.name} 가져오기가 이미 진행 중입니다. 잠시 뒤 다시 누르세요.")
try:
ctx = self._ctx(code, user=user)
try:
src.require_configured(ctx)
days = src.fetch_days(ctx, start, end)
except AdapterError as exc:
msg = self._message(exc, ctx)
self._store.record_ad_status(code, status=exc.status, ok=False, error=msg, kind="sync")
return {"ok": False, "code": code, "name": src.name, "status": exc.status,
"label": STATUS_LABELS.get(exc.status, exc.status), "message": msg}
saved = self._store.replace_ad_api_range(
code, start, end, [(d.day, d.amount, d.roas, d.metrics) for d in days], user=user or "광고 API")
self._store.record_ad_status(code, status="ok", ok=True, kind="sync")
return {"ok": True, "code": code, "name": src.name, "days": saved, "total": sum(d.amount for d in days),
"from": start.isoformat(), "to": end.isoformat()}
finally:
lock.release()
def sync_all(self, start: date, end: date, *, user: str = "") -> list[dict[str, Any]]:
"""설정이 끝난 광고 연동 전부(자동 업데이트 회차). 채널별로 실패를 격리한다."""
out = []
for code, ok in self.configured().items():
if not ok:
continue
try:
out.append(self.sync(code, start, end, user=user))
except AdSyncBusy as exc:
out.append({"ok": False, "code": code, "skipped": True, "message": str(exc)})
except Exception as exc: # noqa: BLE001 — 다음 채널은 계속
logger.exception("ad sync failed: %s", code)
out.append({"ok": False, "code": code, "message": f"가져오기 중 오류: {type(exc).__name__}"})
return out