b2710a0831
- 가져올 때 그날 메타 행 metrics 에 계정별 값(_accounts: 이름·광고비·ROAS·항목, insights account_name)을 함께 저장 — 새 마이그레이션 없음. "_" 키는 일자별 표 열·합계·화면 값에서 제외. - ad_spend.detail_tabs: 합계 탭 + 계정 탭(그 계정이 광고 낸 날만, 광고비 큰 계정부터), 계정별 값 없는 날 수 안내. - 상세보기 창: 탭(주황 강조, 계정 ID 말풍선), 계정 탭은 1원 반올림 차이 안내. 네이버·구글은 그대로 표 하나. - 테스트: 계정별 변환·탭 순서/이름/가중 ROAS·옛 자료 안내·API 응답, jsdom 탭 전환. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
77 lines
3.5 KiB
Python
77 lines
3.5 KiB
Python
"""광고 API 연동 — 공통 인터페이스.
|
|
|
|
광고 채널 코드(code)는 광고비 표 채널 코드(ad_spend.CHANNELS)와 같다 — 가져온 값은 그 채널 열로 들어간다.
|
|
인증정보는 쇼핑몰 인증정보와 같은 방식(설정 화면 입력 → 마스터 키로 암호화 → perf_ad_credentials)이고,
|
|
꺼낼 때는 ctx.credentials.get(key) 로만(서버 안에서만 복호화). 오류는 adapters.base 의 AdapterError 계열 —
|
|
status 가 곧 연결 상태 코드(설정 화면 표시)다. 오류 문구에 비밀값을 넣지 않는다.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
from dataclasses import dataclass, field
|
|
from datetime import date
|
|
from decimal import Decimal
|
|
from typing import Any
|
|
|
|
from ..adapters.base import AdapterContext, CredentialField, NotConfigured
|
|
|
|
|
|
# AdDay.metrics 안의 계정별 값(여러 광고 계정을 합치는 채널 — 메타, 2026-10-16):
|
|
# {ACCOUNTS_KEY: {계정 ID: {"name", "amount", "roas", "metrics"}}} — 상세보기 [합계 | 계정…] 탭(ad_spend.detail_tabs).
|
|
# "_" 로 시작하는 metrics 키는 일자별 표 열·합계에 넣지 않는다(ad_spend.detail_table).
|
|
ACCOUNTS_KEY = "_accounts"
|
|
|
|
|
|
@dataclass
|
|
class AdDay:
|
|
"""광고 API 가 돌려준 하루치 — 금액은 원 단위 정수, ROAS 는 %(없으면 None), 나머지 항목은 화면 이름 그대로."""
|
|
|
|
day: date
|
|
amount: int
|
|
roas: Decimal | None = None
|
|
metrics: dict[str, Any] = field(default_factory=dict)
|
|
|
|
|
|
class AdSource:
|
|
code: str = "" # 광고비 채널 코드(google 등)
|
|
name: str = "" # 설정 화면 이름
|
|
docs_url: str = ""
|
|
note: str = "" # 설정 창 맨 위 안내
|
|
|
|
# 인증정보 서비스(credentials.CredentialService)가 쇼핑몰 어댑터와 같은 방식으로 다루게 맞춘 속성
|
|
@property
|
|
def uses_shared_integration(self) -> bool:
|
|
return False
|
|
|
|
def credential_fields(self) -> list[CredentialField]:
|
|
return []
|
|
|
|
def visible_fields(self) -> list[CredentialField]:
|
|
return [f for f in self.credential_fields() if not f.internal]
|
|
|
|
def validate_credentials(self, values: dict[str, str]) -> list[str]:
|
|
"""저장 전 검사. values 의 "__stored__" = 저장된 값이 있음(원문은 꺼내지 않음). 값 자체를 오류 문구에 넣지 않는다."""
|
|
errors: list[str] = []
|
|
for f in self.visible_fields():
|
|
v = (values.get(f.key) or "").strip()
|
|
if f.required and not v:
|
|
errors.append(f"{f.label} 을(를) 입력하세요.")
|
|
elif v and len(v) > 20000:
|
|
errors.append(f"{f.label} 값이 너무 깁니다.")
|
|
return errors
|
|
|
|
def is_configured(self, ctx: AdapterContext) -> bool:
|
|
return all(ctx.credentials.has(f.key) for f in self.visible_fields() if f.required)
|
|
|
|
def require_configured(self, ctx: AdapterContext) -> None:
|
|
if not self.is_configured(ctx):
|
|
raise NotConfigured("필수 인증정보가 입력되지 않았습니다. 실적 설정 → 광고 API 연동에서 입력하세요.")
|
|
|
|
def test_connection(self, ctx: AdapterContext) -> str:
|
|
"""성공하면 사람이 읽을 짧은 문구. 실패는 AdapterError."""
|
|
raise NotImplementedError
|
|
|
|
def fetch_days(self, ctx: AdapterContext, start: date, end: date) -> list[AdDay]:
|
|
"""기간(양 끝 포함)의 날짜별 광고비. 광고가 없던 날은 빠질 수 있다(저장 쪽이 그날의 예전 API 값을 지운다)."""
|
|
raise NotImplementedError
|