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>
This commit is contained in:
2026-10-15 15:10:03 +09:00
parent cd33c67df9
commit e7b1e17579
24 changed files with 1379 additions and 60 deletions
+1 -1
View File
File diff suppressed because one or more lines are too long
@@ -0,0 +1,5 @@
"""광고 API 연동(구글 광고 등) — 광고 채널 하나 = 파일 하나 + registry.py 한 줄.
쇼핑몰 어댑터(adapters/)와 같은 모양(입력칸·연결 테스트·인증정보 접근자)을 따르되, 돌려주는 것은 매출 사건이 아니라
"날짜별 광고비·ROAS·보고서 항목"(AdDay)이다. 저장은 ad_sync.py 가 perf_ad_spend(source='api')에.
"""
@@ -0,0 +1,70 @@
"""광고 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
@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
@@ -0,0 +1,293 @@
"""구글 광고(Google Ads API) — 날짜별 광고비·ROAS·보고서 항목.
인증(2026-10-15 사용자: 서비스 계정 + 개발자 토큰 Explorer 승인)
- 서비스 계정 JSON 키로 OAuth 액세스 토큰(scope adwords)을 받는다 — JWT 를 google-auth 로 서명하고 토큰 교환은 httpx.
서비스 계정 이메일을 구글 광고 계정(또는 관리자 MCC 계정) → 관리 → 액세스 및 보안 → 사용자에 추가해 두어야 한다
(2024-11 부터 도메인 전체 위임 없이 직접 추가 가능).
- 요청 머리글: Authorization(Bearer) · developer-token · login-customer-id(MCC 를 거쳐 들어갈 때만).
- 개발자 토큰 Explorer 등급은 운영 계정 조회(보고서)가 되고 하루 작업 수 한도가 있다 — 우리는 가져오기 한 번에 요청 1~2개.
조회(REST googleAds:searchStream, GAQL)
SELECT customer.currency_code, segments.date, metrics.cost_micros, metrics.impressions, metrics.clicks,
metrics.conversions, metrics.conversions_value FROM customer WHERE segments.date BETWEEN 'from' AND 'to'
- 날짜는 광고 계정 시간대 기준(한국 계정이면 KST). 광고가 없던 날은 행이 없을 수 있다.
- 금액 = cost_micros ÷ 1,000,000 을 원 단위로 반올림(구글 광고 비용은 부가세 별도). 계정 통화가 KRW 가 아니면 저장하지 않는다.
- ROAS(%) = 전환 가치 ÷ 비용 × 100(구글 광고 "전환 가치/비용"과 같은 값), 비용이 0 이면 없음.
- 나머지 항목(노출수·클릭수·클릭률·전환수·전환 가치)은 광고비 탭 구글 머리글 → 일자별 표.
API 버전은 설정 칸(기본 DEFAULT_VERSION) — 구글은 버전을 약 1년 뒤 종료하므로 종료 안내가 오면 설정에서 올린다.
"""
from __future__ import annotations
import json
import re
import threading
import time
from datetime import date
from decimal import ROUND_HALF_UP, Decimal
from typing import Any
import httpx
from ..adapters.base import AdapterContext, ApiError, AuthFailed, CredentialField, NotConfigured
from .base import AdDay, AdSource
SCOPE = "https://www.googleapis.com/auth/adwords"
API_BASE = "https://googleads.googleapis.com"
DEFAULT_VERSION = "v26" # 2026-10 기준 최신(구글 광고 API 는 매월 부 버전·분기마다 새 버전)
TOKEN_URI = "https://oauth2.googleapis.com/token"
MAX_DAYS = 366
# 일자별 표(광고비 탭 구글 머리글) 항목 — 순서 = 열 순서. 클릭률·ROAS 합계는 ad_spend.detail_table 이 이름으로 다시 계산.
M_COST, M_IMPR, M_CLICKS, M_CTR, M_CONV, M_VALUE, M_ROAS = "비용", "노출수", "클릭수", "클릭률(%)", "전환수", "전환 가치", "ROAS(%)"
# 구글 오류 코드 → 고칠 곳 안내(오류 문구 뒤에 붙임)
_HINTS = {
"DEVELOPER_TOKEN_NOT_APPROVED": "개발자 토큰이 테스트 계정 전용입니다. API 센터에서 Explorer 이상 승인을 받은 토큰인지 확인하세요.",
"DEVELOPER_TOKEN_PROHIBITED": "이 개발자 토큰은 이 Google Cloud 프로젝트에서 쓸 수 없습니다(토큰을 받은 MCC·프로젝트 확인).",
"DEVELOPER_TOKEN_INVALID": "개발자 토큰이 올바르지 않습니다.",
"USER_PERMISSION_DENIED": "서비스 계정이 이 광고 계정에 권한이 없습니다. 구글 광고 → 관리 → 액세스 및 보안에 서비스 계정 이메일을 "
"사용자로 추가했는지, 관리자(MCC) 계정에 추가했다면 [로그인 고객 ID]에 MCC 번호를 넣었는지 확인하세요.",
"CUSTOMER_NOT_ENABLED": "광고 계정이 사용 중지(취소·미완료) 상태입니다.",
"NOT_ADS_USER": "서비스 계정이 구글 광고 사용자로 등록돼 있지 않습니다(액세스 및 보안에서 추가).",
"INVALID_CUSTOMER_ID": "고객 ID 가 올바르지 않습니다(광고 계정 오른쪽 위 123-456-7890 형태 번호).",
"CUSTOMER_NOT_FOUND": "고객 ID 의 광고 계정을 찾을 수 없습니다.",
"SERVICE_ACCOUNT_NOT_ALLOWED": "이 계정은 서비스 계정 접근을 허용하지 않습니다.",
}
_token_lock = threading.Lock()
_token_cache: dict[str, tuple[str, float]] = {} # (서비스 계정 이메일, 키 ID) → (액세스 토큰, 만료 시각)
def _digits(value: str) -> str:
return re.sub(r"[\s\-]", "", value or "")
def _http(ctx: AdapterContext) -> httpx.Client:
"""HTTP 클라이언트 — 테스트가 바꿔 끼운다."""
return httpx.Client(timeout=ctx.timeout_sec)
def parse_service_account(raw: str) -> dict[str, Any]:
"""서비스 계정 JSON 키 → dict. 형식이 틀리면 ValueError(문구에 키 내용을 넣지 않는다)."""
try:
info = json.loads(raw)
except (TypeError, ValueError):
raise ValueError("서비스 계정 키가 JSON 형식이 아닙니다(구글 클라우드에서 내려받은 .json 파일 내용을 통째로 붙여 넣으세요).") from None
if not isinstance(info, dict) or info.get("type") != "service_account":
raise ValueError("서비스 계정 키가 아닙니다(\"type\": \"service_account\" 인 JSON 이어야 합니다).")
for k in ("client_email", "private_key"):
if not str(info.get(k) or "").strip():
raise ValueError(f"서비스 계정 키에 {k} 가 없습니다.")
return info
def _won(micros: int) -> int:
return int((Decimal(int(micros)) / Decimal(1_000_000)).quantize(Decimal(1), rounding=ROUND_HALF_UP))
def _num(v: Any) -> Decimal:
"""REST 응답 숫자(int64 는 문자열, double 은 숫자, 0 은 아예 빠짐) → Decimal."""
if v is None or v == "":
return Decimal(0)
return Decimal(str(v))
def _google_error(resp: httpx.Response) -> tuple[str, str]:
"""구글 오류 응답 → (오류 코드 이름, 사람이 읽을 문구). searchStream 오류는 배열에 싸여 올 수 있다."""
try:
body = resp.json()
except ValueError:
return "", f"HTTP {resp.status_code}"
if isinstance(body, list):
body = next((b for b in body if isinstance(b, dict) and b.get("error")), body[0] if body else {})
err = (body or {}).get("error") or {}
if isinstance(err, str): # 토큰 교환 오류 {"error": "invalid_grant", "error_description": "..."}
return err, str((body or {}).get("error_description") or err)
code_name, message = "", str(err.get("message") or f"HTTP {resp.status_code}")
for d in err.get("details") or []:
for e in (d or {}).get("errors") or []:
ec = e.get("errorCode") or {}
if ec:
code_name = str(next(iter(ec.values())))
if e.get("message"):
message = str(e["message"])
break
if code_name:
break
return code_name, message
class GoogleAdsSource(AdSource):
code = "google"
name = "구글 광고"
docs_url = "https://developers.google.com/google-ads/api/docs/oauth/service-accounts"
note = ("구글 광고 API 로 날짜별 광고비(비용)·ROAS(전환 가치 ÷ 비용)·노출수·클릭수·전환을 가져옵니다. "
"준비: ① Google Cloud 서비스 계정 JSON 키 ② 구글 광고 API 센터의 개발자 토큰(Explorer 이상) "
"③ 구글 광고 → 관리 → 액세스 및 보안 → 사용자에 서비스 계정 이메일 추가(읽기 권한이면 충분).")
def credential_fields(self) -> list[CredentialField]:
return [
CredentialField("developer_token", "개발자 토큰", secret=True,
help="구글 광고 관리자(MCC) → 도구 → API 센터의 개발자 토큰. Explorer 이상 승인이어야 운영 계정을 조회할 수 있습니다."),
CredentialField("customer_id", "고객 ID(광고 계정)", placeholder="123-456-7890",
help="광고비를 가져올 광고 계정 번호(구글 광고 화면 오른쪽 위). 하이픈은 있어도 됩니다."),
CredentialField("login_customer_id", "로그인 고객 ID(MCC)", required=False, placeholder="비워 두면 광고 계정에 직접 접근",
help="서비스 계정을 관리자(MCC) 계정에 추가해 그 아래 광고 계정을 볼 때만 MCC 번호를 넣습니다."),
CredentialField("service_account_json", "서비스 계정 키(JSON)", secret=True, multiline=True,
help="Google Cloud → IAM → 서비스 계정 → 키 → JSON 으로 받은 파일 내용을 통째로 붙여 넣습니다. "
"저장 후에는 화면에 다시 보이지 않습니다."),
CredentialField("api_version", "API 버전", required=False, placeholder=DEFAULT_VERSION,
help=f"비워 두면 {DEFAULT_VERSION}. 구글이 버전 종료를 알리면 새 버전(예: v27)으로 바꿉니다."),
]
def validate_credentials(self, values: dict[str, str]) -> list[str]:
errors = super().validate_credentials(values)
for key, label in (("customer_id", "고객 ID"), ("login_customer_id", "로그인 고객 ID")):
v = (values.get(key) or "").strip()
if v and v != "__stored__" and not re.fullmatch(r"\d{10}", _digits(v)):
errors.append(f"{label}는 숫자 10자리여야 합니다(예: 123-456-7890).")
sa = (values.get("service_account_json") or "").strip()
if sa and sa != "__stored__":
try:
parse_service_account(sa)
except ValueError as exc:
errors.append(str(exc))
ver = (values.get("api_version") or "").strip()
if ver and ver != "__stored__" and not re.fullmatch(r"v\d{2,3}", ver):
errors.append("API 버전은 v26 처럼 v 뒤에 숫자로 입력하세요.")
return errors
# ── 인증 ──────────────────────────────────────────────
def _access_token(self, ctx: AdapterContext, client: httpx.Client) -> str:
try:
info = parse_service_account(ctx.credentials.get("service_account_json"))
except ValueError as exc:
raise NotConfigured(str(exc)) from None
cache_key = f"{info['client_email']}|{info.get('private_key_id', '')}"
with _token_lock:
hit = _token_cache.get(cache_key)
if hit and hit[1] > time.time() + 120:
return hit[0]
from google.auth import crypt, jwt # noqa: WPS433 — google-auth(requirements)
try:
signer = crypt.RSASigner.from_service_account_info(info)
except Exception: # noqa: BLE001 — 키 내용은 문구에 넣지 않는다
raise AuthFailed("서비스 계정 키의 private_key 를 읽을 수 없습니다(JSON 파일 내용을 그대로 붙여 넣었는지 확인).") from None
now = int(time.time())
token_uri = str(info.get("token_uri") or TOKEN_URI)
assertion = jwt.encode(signer, {"iss": info["client_email"], "scope": SCOPE, "aud": token_uri,
"iat": now, "exp": now + 3600})
try:
resp = client.post(token_uri, data={"grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer",
"assertion": assertion.decode() if isinstance(assertion, bytes) else assertion})
except httpx.HTTPError as exc:
raise ApiError(f"구글 인증 서버에 연결하지 못했습니다({type(exc).__name__}).") from None
if resp.status_code != 200:
name, msg = _google_error(resp)
raise AuthFailed(f"서비스 계정 인증 실패({name or resp.status_code}): {msg[:200]} — 키가 삭제·사용 중지되지 않았는지 확인하세요.")
body = resp.json()
token = str(body.get("access_token") or "")
if not token:
raise AuthFailed("구글 인증 서버가 액세스 토큰을 주지 않았습니다.")
with _token_lock:
_token_cache[cache_key] = (token, time.time() + int(body.get("expires_in") or 3600))
return token
def _search(self, ctx: AdapterContext, query: str) -> list[dict[str, Any]]:
"""GAQL 한 번 — searchStream 응답(묶음 배열)의 results 를 이어 붙여 돌려준다."""
self.require_configured(ctx)
cid = _digits(ctx.credentials.get("customer_id"))
if not re.fullmatch(r"\d{10}", cid):
raise NotConfigured("고객 ID 는 숫자 10자리여야 합니다.")
version = (ctx.credentials.get("api_version") or "").strip() or DEFAULT_VERSION
with _http(ctx) as client:
token = self._access_token(ctx, client)
headers = {"Authorization": f"Bearer {token}", "developer-token": ctx.credentials.get("developer_token").strip(),
"Content-Type": "application/json"}
login = _digits(ctx.credentials.get("login_customer_id"))
if login:
headers["login-customer-id"] = login
ctx.progress.check()
try:
resp = client.post(f"{API_BASE}/{version}/customers/{cid}/googleAds:searchStream",
headers=headers, json={"query": query})
except httpx.HTTPError as exc:
raise ApiError(f"구글 광고 API 에 연결하지 못했습니다({type(exc).__name__}).") from None
if resp.status_code == 404:
raise ApiError(f"구글 광고 API 버전 {version} 을(를) 쓸 수 없습니다(종료됐을 수 있음) — 실적 설정에서 API 버전을 최신으로 바꾸세요.")
if resp.status_code != 200:
name, msg = _google_error(resp)
hint = _HINTS.get(name, "")
text = f"구글 광고 API 오류({name or resp.status_code}): {msg[:200]}" + (f" — {hint}" if hint else "")
raise (AuthFailed if resp.status_code in (401, 403) else ApiError)(text)
try:
batches = resp.json()
except ValueError:
raise ApiError("구글 광고 API 응답을 읽을 수 없습니다.") from None
if isinstance(batches, dict):
batches = [batches]
out: list[dict[str, Any]] = []
for b in batches or []:
out.extend((b or {}).get("results") or [])
return out
# ── 연결 테스트 · 가져오기 ─────────────────────────────
def test_connection(self, ctx: AdapterContext) -> str:
rows = self._search(ctx, "SELECT customer.id, customer.descriptive_name, customer.currency_code, "
"customer.time_zone FROM customer LIMIT 1")
c = (rows[0].get("customer") if rows else None) or {}
currency = c.get("currencyCode") or "?"
msg = f"연결됨 — {c.get('descriptiveName') or '광고 계정'} · 통화 {currency} · 시간대 {c.get('timeZone') or '?'}"
if currency != "KRW":
msg += " (원화 계정이 아니라 광고비를 가져올 수 없습니다)"
return msg
def fetch_days(self, ctx: AdapterContext, start: date, end: date) -> list[AdDay]:
if end < start:
start, end = end, start
if (end - start).days + 1 > MAX_DAYS:
raise ApiError(f"한 번에 {MAX_DAYS}일까지 가져올 수 있습니다.")
rows = self._search(
ctx,
"SELECT customer.currency_code, segments.date, metrics.cost_micros, metrics.impressions, metrics.clicks, "
"metrics.conversions, metrics.conversions_value FROM customer "
f"WHERE segments.date BETWEEN '{start.isoformat()}' AND '{end.isoformat()}'",
)
sums: dict[date, dict[str, Decimal]] = {}
for r in rows:
cur = ((r.get("customer") or {}).get("currencyCode") or "").upper()
if cur and cur != "KRW":
raise ApiError(f"광고 계정 통화가 {cur} 입니다 — 원화(KRW) 계정만 광고비로 가져옵니다.")
raw_day = (r.get("segments") or {}).get("date")
try:
day = date.fromisoformat(str(raw_day))
except ValueError:
continue
m = r.get("metrics") or {}
acc = sums.setdefault(day, {"cost": Decimal(0), "impr": Decimal(0), "clicks": Decimal(0),
"conv": Decimal(0), "value": Decimal(0)})
acc["cost"] += _num(m.get("costMicros"))
acc["impr"] += _num(m.get("impressions"))
acc["clicks"] += _num(m.get("clicks"))
acc["conv"] += _num(m.get("conversions"))
acc["value"] += _num(m.get("conversionsValue"))
out: list[AdDay] = []
for day in sorted(sums):
a = sums[day]
amount = _won(int(a["cost"]))
cost = a["cost"] / Decimal(1_000_000)
roas = (a["value"] / cost * 100).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP) if cost > 0 else None
ctr = (a["clicks"] / a["impr"] * 100).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP) if a["impr"] > 0 else None
metrics = {
M_COST: amount,
M_IMPR: int(a["impr"]),
M_CLICKS: int(a["clicks"]),
M_CTR: float(ctr) if ctr is not None else None,
M_CONV: float(a["conv"].quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)),
M_VALUE: int(a["value"].quantize(Decimal(1), rounding=ROUND_HALF_UP)),
M_ROAS: float(roas) if roas is not None else None,
}
out.append(AdDay(day=day, amount=amount, roas=roas, metrics=metrics))
return out
@@ -0,0 +1,17 @@
"""광고 API 연동 목록 — 새 광고 채널은 파일 하나 + 여기 한 줄(채널 코드는 ad_spend.CHANNELS 와 같아야 한다)."""
from __future__ import annotations
from .base import AdSource
from .google_ads import GoogleAdsSource
_SOURCES: tuple[AdSource, ...] = (GoogleAdsSource(),)
_BY_CODE = {s.code: s for s in _SOURCES}
def all_sources() -> tuple[AdSource, ...]:
return _SOURCES
def get_source(code: str) -> AdSource | None:
return _BY_CODE.get(code)
+6 -3
View File
@@ -2,7 +2,7 @@
저장: performance_db `perf_ad_spend`(마이그레이션 005) — 채널 × 날짜 하나에 금액 하나(원 단위 정수).
- 화면 날짜 칸을 눌러 직접 입력(source=manual), 업로드 파일로 한 번에 입력(source=upload, 같은 날 덮어씀).
- 구글·메타는 지금은 직접 입력만(API 연동은 다음 단계).
- 구글은 광고 API 로 가져온다(source=api, ad_sync.py — 2026-10-15). 메타는 지금은 직접 입력만.
쿠팡(윙)·쿠팡(로켓) 업로드 양식(2026-10-13·14 사용자 제공 — 둘 다 같은 쿠팡 광고 보고서 CSV/엑셀):
1행 머리글, 1열 = 날짜("2026년 10월 01일"), 19열 = 청구금액(+부가가치세) → 그날 광고비.
@@ -341,8 +341,8 @@ def merge_results(parsed: list[tuple[str, float, ParseResult]]) -> tuple[ParseRe
return merged, sorted(overlap)
# 머리글을 누르면 일자별 상세 표가 열리는 채널(보고서 항목을 보관하는 채널)
DETAIL_CHANNELS = frozenset({"naver"})
# 머리글을 누르면 일자별 상세 표가 열리는 채널(보고서 항목을 보관하는 채널) — 구글은 광고 API 로 가져온 항목(2026-10-15)
DETAIL_CHANNELS = frozenset({"naver", "google"})
def detail_table(rows: list[dict[str, Any]]) -> dict[str, Any]:
@@ -498,6 +498,9 @@ def build_ad_dashboard(store: Any, *, kind: str, anchor: date, today: date,
# 업로드로 들어온 칸(표시용) — "날짜|채널"
"upload_cells": sorted(f"{d.isoformat()}|{c}" for (d, c), s in sources.items()
if s == "upload" and period.start <= d <= period.end),
# 광고 API(구글 광고 등)로 가져온 칸 — 표시용(초록 숫자)
"api_cells": sorted(f"{d.isoformat()}|{c}" for (d, c), s in sources.items()
if s == "api" and period.start <= d <= period.end),
"upload_channels": [{"code": c, "name": CHANNEL_NAMES[c], "help": UPLOAD_HELP.get(c, "")} for c in PARSERS],
"migration_needed": migration_needed,
}
+119
View File
@@ -0,0 +1,119 @@
"""광고 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
+2
View File
@@ -83,6 +83,7 @@ class CredentialField:
"""설정 화면 입력칸 하나. secret=True 면 저장 후 값을 화면으로 다시 보내지 않는다.
internal=True 는 화면에 안 보이는 내부 값(access/refresh token 등) — 어댑터가 직접 저장.
multiline=True 면 여러 줄 입력칸(서비스 계정 JSON 키 등).
"""
key: str
@@ -92,6 +93,7 @@ class CredentialField:
help: str = ""
placeholder: str = ""
internal: bool = False
multiline: bool = False
@dataclass
+11 -1
View File
@@ -1,6 +1,7 @@
"""매출 자동 업데이트 — 웹 프로세스 안 데몬 스레드(프로젝트 마감 알림과 같은 방식).
기본: 매일 09:00 ~ 19:00(KST) 정각·30분마다, 오늘 포함 최근 10일을 [매출 업데이트] 와 같은 방식으로 다시 가져온다.
- 매출이 끝나면 설정된 광고 API(구글 광고)도 같은 기간으로 가져온다(ad_sync, 실패해도 매출과 무관).
- 진행 창 작업(jobs)으로 돌린다 — 그동안 누가 [매출 업데이트] 를 누르면 새로 시작하지 않고 이 진행 상황을 본다.
- 그 시각에 이미 다른 업데이트가 돌고 있으면 그 회차는 건너뛴다(같은 쇼핑몰 동시 실행은 어차피 막혀 있음).
- 한 회차가 30분을 넘기면 지나간 회차는 건너뛰고 다음 정각/30분을 기다린다(밀린 회차를 몰아서 돌리지 않음).
@@ -103,9 +104,18 @@ def run_once(store: Any, app_state: Any, *, today: Any, days: int) -> dict[str,
except Exception: # noqa: BLE001
pass
job.finish(error=error, last_update_at=last)
# 광고 API(구글 광고 등)도 같은 회차·같은 기간으로 — 설정된 연동만, 실패해도 매출 업데이트와 무관(2026-10-15)
ads: list[dict[str, Any]] = []
try:
from .ad_sync import AdSyncService, ad_credentials # noqa: WPS433
ads = AdSyncService(store, ad_credentials(store, common.key_ring)).sync_all(start, end, user=AUTO_USER)
except Exception: # noqa: BLE001 — 스레드가 죽지 않게
logger.exception("auto ad sync failed")
ok = sum(1 for r in results if r.get("ok"))
return {"skipped": False, "from": start.isoformat(), "to": end.isoformat(), "ok": ok,
"failed": [r.get("code") for r in results if not r.get("ok") and not r.get("skipped")], "error": error}
"failed": [r.get("code") for r in results if not r.get("ok") and not r.get("skipped")], "error": error,
"ads": [{"code": a.get("code"), "ok": bool(a.get("ok"))} for a in ads]}
def start_auto_sync_thread(app_state: Any) -> bool:
+19 -12
View File
@@ -16,18 +16,21 @@ from .adapters.base import MarketplaceAdapter
from .security.crypto import KeyRing, decrypt, encrypt, needs_reencrypt
def aad_for(code: str, key: str) -> str:
"""암호문을 (쇼핑몰, 항목)에 묶는 추가 인증 데이터."""
return f"perf:{code}:{key}"
def aad_for(code: str, key: str, ns: str = "") -> str:
"""암호문을 (쇼핑몰, 항목)에 묶는 추가 인증 데이터. ns = 이름 공간(광고 API 인증정보는 "ad:") —
쇼핑몰 암호문과 광고 암호문을 서로 바꿔 넣어도 복호화되지 않는다."""
return f"perf:{ns}{code}:{key}"
class CredentialAccessor:
"""어댑터 전용 — 서버 안에서만 복호화. 값은 처음 꺼낼 때 한 번 복호화해 둔다."""
def __init__(self, store: Any, code: str, ring_loader: Callable[[], KeyRing], *,
overrides: dict[str, str] | None = None, persist: bool = True, user: str = "") -> None:
overrides: dict[str, str] | None = None, persist: bool = True, user: str = "",
aad_ns: str = "") -> None:
self._store = store
self._code = code
self._ns = aad_ns
self._ring_loader = ring_loader
self._rows = store.credential_rows(code) if store is not None else {}
self._cache: dict[str, str] = {}
@@ -46,7 +49,7 @@ class CredentialAccessor:
row = self._rows.get(key)
if not row:
return ""
value = decrypt(row["encrypted_value"], aad=aad_for(self._code, key), ring=self._ring_loader())
value = decrypt(row["encrypted_value"], aad=aad_for(self._code, key, self._ns), ring=self._ring_loader())
self._cache[key] = value
return value
@@ -57,7 +60,7 @@ class CredentialAccessor:
return
ring = self._ring_loader()
self._store.upsert_credential(
self._code, key, encrypted_value=encrypt(value, aad=aad_for(self._code, key), ring=ring),
self._code, key, encrypted_value=encrypt(value, aad=aad_for(self._code, key, self._ns), ring=ring),
key_version=ring.current_version, user=self._user or "system",
)
self._rows[key] = {"encrypted_value": "", "key_version": ring.current_version}
@@ -68,14 +71,17 @@ class CredentialAccessor:
class CredentialService:
def __init__(self, store: Any, ring_loader: Callable[[], KeyRing]) -> None:
"""store = 인증정보 저장소(쇼핑몰: PerformanceStore, 광고 API: db.AdCredentialTable). aad_ns = 암호문 이름 공간."""
def __init__(self, store: Any, ring_loader: Callable[[], KeyRing], *, aad_ns: str = "") -> None:
self._store = store
self._ring_loader = ring_loader
self._ns = aad_ns
def accessor(self, code: str, *, overrides: dict[str, str] | None = None, persist: bool = True,
user: str = "") -> CredentialAccessor:
return CredentialAccessor(self._store, code, self._ring_loader, overrides=overrides,
persist=persist, user=user)
persist=persist, user=user, aad_ns=self._ns)
# ── 화면용 요약(비밀 원문 없음) ─────────────────────────
def describe(self, adapter: MarketplaceAdapter) -> dict[str, Any]:
@@ -87,11 +93,12 @@ class CredentialService:
item: dict[str, Any] = {
"key": f.key, "label": f.label, "secret": f.secret, "required": f.required,
"help": f.help, "placeholder": f.placeholder, "has_value": row is not None,
"multiline": bool(getattr(f, "multiline", False)),
"updated_at": row["updated_at"].isoformat(timespec="seconds") if row and row.get("updated_at") else "",
}
if row is not None and not f.secret:
try:
item["value"] = decrypt(row["encrypted_value"], aad=aad_for(adapter.code, f.key),
item["value"] = decrypt(row["encrypted_value"], aad=aad_for(adapter.code, f.key, self._ns),
ring=self._ring_loader())
except Exception as exc: # noqa: BLE001 — 키 없음/손상: 값 없이 안내만
item["value"] = ""
@@ -135,7 +142,7 @@ class CredentialService:
if not v:
continue
self._store.upsert_credential(
adapter.code, key, encrypted_value=encrypt(v, aad=aad_for(adapter.code, key), ring=ring),
adapter.code, key, encrypted_value=encrypt(v, aad=aad_for(adapter.code, key, self._ns), ring=ring),
key_version=ring.current_version, user=user,
)
saved.append(key)
@@ -155,12 +162,12 @@ class CredentialService:
continue
code, key = row["marketplace_code"], row["credential_key"]
try:
plain = decrypt(token, aad=aad_for(code, key), ring=ring)
plain = decrypt(token, aad=aad_for(code, key, self._ns), ring=ring)
except Exception: # noqa: BLE001
failed += 1
continue
self._store.upsert_credential(
code, key, encrypted_value=encrypt(plain, aad=aad_for(code, key), ring=ring),
code, key, encrypted_value=encrypt(plain, aad=aad_for(code, key, self._ns), ring=ring),
key_version=ring.current_version, user="rekey",
)
done += 1
+164
View File
@@ -560,3 +560,167 @@ class PerformanceDBStore:
(STALE_RUN_AFTER,),
).fetchall()
return [r["marketplace_code"] for r in rows]
# ════════════════════════════════════════════════════════════
# 광고 API 연동(마이그레이션 007) — 인증정보(암호문)·연결 상태·가져온 광고비
# 읽기는 007 미적용이면 빈 값(설정 화면은 안내만), 쓰기는 AdMigrationNeeded("007").
# ════════════════════════════════════════════════════════════
def ad_api_ready(self) -> bool:
try:
with self._pool.connection() as conn:
conn.execute("SELECT 1 FROM perf_ad_credentials LIMIT 1").fetchall()
except pg_errors.UndefinedTable:
return False
return True
def ad_credential_rows(self, code: str) -> dict[str, dict[str, Any]]:
try:
with self._pool.connection() as conn:
rows = conn.execute(
"SELECT credential_key, encrypted_value, key_version, updated_at, updated_by "
"FROM perf_ad_credentials WHERE channel_code = %s", (code,),
).fetchall()
except pg_errors.UndefinedTable:
return {}
return {r["credential_key"]: r for r in rows}
def ad_credential_keys_by_code(self) -> dict[str, set[str]]:
try:
with self._pool.connection() as conn:
rows = conn.execute("SELECT channel_code, credential_key FROM perf_ad_credentials").fetchall()
except pg_errors.UndefinedTable:
return {}
out: dict[str, set[str]] = {}
for r in rows:
out.setdefault(r["channel_code"], set()).add(r["credential_key"])
return out
def upsert_ad_credential(self, code: str, key: str, *, encrypted_value: str, key_version: int, user: str = "") -> None:
from .ad_spend import AdMigrationNeeded # noqa: WPS433
try:
with self._pool.connection() as conn:
conn.execute(
"""
INSERT INTO perf_ad_credentials (channel_code, credential_key, encrypted_value, key_version, updated_by)
VALUES (%s, %s, %s, %s, %s)
ON CONFLICT (channel_code, credential_key) DO UPDATE
SET encrypted_value = EXCLUDED.encrypted_value, key_version = EXCLUDED.key_version,
updated_by = EXCLUDED.updated_by
""",
(code, key, encrypted_value, key_version, user),
)
except pg_errors.UndefinedTable:
raise AdMigrationNeeded("007") from None
def delete_ad_credential(self, code: str, key: str) -> None:
from .ad_spend import AdMigrationNeeded # noqa: WPS433
try:
with self._pool.connection() as conn:
conn.execute("DELETE FROM perf_ad_credentials WHERE channel_code = %s AND credential_key = %s", (code, key))
except pg_errors.UndefinedTable:
raise AdMigrationNeeded("007") from None
def all_ad_credential_rows(self) -> list[dict[str, Any]]:
try:
with self._pool.connection() as conn:
return conn.execute(
"SELECT channel_code AS marketplace_code, credential_key, encrypted_value, key_version "
"FROM perf_ad_credentials"
).fetchall()
except pg_errors.UndefinedTable:
return []
def ad_source_statuses(self) -> dict[str, dict[str, Any]]:
try:
with self._pool.connection() as conn:
rows = conn.execute("SELECT * FROM perf_ad_source_status").fetchall()
except pg_errors.UndefinedTable:
return {}
return {r["channel_code"]: {k: _iso(v) for k, v in r.items()} for r in rows}
def record_ad_status(self, code: str, *, status: str, ok: bool, error: str = "", kind: str = "test") -> None:
"""연결 테스트(kind=test) 또는 가져오기(kind=sync) 결과. 오류가 없으면 예전 오류 문구는 그대로 둔다."""
if kind == "sync":
sql = """
INSERT INTO perf_ad_source_status (channel_code, status, last_sync_at, last_success_sync_at, last_error, last_error_at)
VALUES (%(c)s, %(s)s, now(), CASE WHEN %(ok)s THEN now() END, %(e)s, CASE WHEN %(e)s = '' THEN NULL ELSE now() END)
ON CONFLICT (channel_code) DO UPDATE
SET status = EXCLUDED.status, last_sync_at = now(),
last_success_sync_at = CASE WHEN %(ok)s THEN now() ELSE perf_ad_source_status.last_success_sync_at END,
last_error = CASE WHEN %(e)s = '' THEN perf_ad_source_status.last_error ELSE %(e)s END,
last_error_at = CASE WHEN %(e)s = '' THEN perf_ad_source_status.last_error_at ELSE now() END
"""
else:
sql = """
INSERT INTO perf_ad_source_status (channel_code, status, last_test_at, last_test_ok, last_error, last_error_at)
VALUES (%(c)s, %(s)s, now(), %(ok)s, %(e)s, CASE WHEN %(e)s = '' THEN NULL ELSE now() END)
ON CONFLICT (channel_code) DO UPDATE
SET status = EXCLUDED.status, last_test_at = now(), last_test_ok = %(ok)s,
last_error = CASE WHEN %(e)s = '' THEN perf_ad_source_status.last_error ELSE %(e)s END,
last_error_at = CASE WHEN %(e)s = '' THEN perf_ad_source_status.last_error_at ELSE now() END
"""
try:
with self._pool.connection() as conn:
conn.execute(sql, {"c": code, "s": status, "ok": ok, "e": error})
except pg_errors.UndefinedTable:
return # 007 미적용 — 상태 기록만 못 함(가져오기 자체는 막지 않음)
def replace_ad_api_range(self, code: str, start: date, end: date,
days: list[tuple[date, int, Any, dict[str, Any] | None]], *, user: str = "") -> int:
"""광고 API 로 가져온 기간을 한 트랜잭션으로 반영 — days 의 날은 덮어쓰고(source='api', ROAS·보고서 항목 포함,
직접 입력·업로드 값이 있던 날도 API 값으로), 기간 안에서 API 가 돌려주지 않은 날은 **예전 API 값만** 지운다
(직접 입력·업로드 값은 그대로). days = [(날짜, 금액, ROAS, 항목)]. 반영한 날 수."""
from .ad_spend import AdMigrationNeeded # noqa: WPS433
keep = {d for d, _, _, _ in days}
try:
with self._pool.connection() as conn:
with conn.transaction():
with conn.cursor() as cur:
old = cur.execute(
"SELECT spend_date FROM perf_ad_spend WHERE channel_code = %s AND source = 'api' "
"AND spend_date BETWEEN %s AND %s", (code, start, end),
).fetchall()
gone = [(code, r["spend_date"]) for r in old if r["spend_date"] not in keep]
if gone:
cur.executemany("DELETE FROM perf_ad_spend WHERE channel_code = %s AND spend_date = %s "
"AND source = 'api'", gone)
rows = [(code, d, int(a), "api", user, r, Jsonb(m) if m is not None else None) for d, a, r, m in days]
if rows:
cur.executemany(
"INSERT INTO perf_ad_spend (channel_code, spend_date, amount, source, updated_by, roas, metrics) "
"VALUES (%s, %s, %s, %s, %s, %s, %s) ON CONFLICT (channel_code, spend_date) DO UPDATE "
"SET amount = EXCLUDED.amount, source = EXCLUDED.source, updated_by = EXCLUDED.updated_by, "
"roas = EXCLUDED.roas, metrics = EXCLUDED.metrics",
rows,
)
except pg_errors.UndefinedTable:
raise AdMigrationNeeded("005") from None
except pg_errors.UndefinedColumn:
raise AdMigrationNeeded("006") from None
return len(days)
class AdCredentialTable:
"""광고 API 인증정보 표(perf_ad_credentials)를 쇼핑몰 인증정보 저장소와 같은 이름으로 — credentials.CredentialService 가
그대로 쓴다(저장·요약·재암호화). 채널 코드가 쇼핑몰 코드 자리에 들어간다."""
def __init__(self, store: Any) -> None:
self._store = store
def credential_rows(self, code: str) -> dict[str, dict[str, Any]]:
return self._store.ad_credential_rows(code)
def credential_keys_by_code(self) -> dict[str, set[str]]:
return self._store.ad_credential_keys_by_code()
def upsert_credential(self, code: str, key: str, *, encrypted_value: str, key_version: int, user: str = "") -> None:
self._store.upsert_ad_credential(code, key, encrypted_value=encrypted_value, key_version=key_version, user=user)
def delete_credential(self, code: str, key: str) -> None:
self._store.delete_ad_credential(code, key)
def all_credential_rows(self) -> list[dict[str, Any]]:
return self._store.all_ad_credential_rows()
+152 -5
View File
@@ -17,8 +17,11 @@ JSON API — 모듈 권한
PUT /performance/api/ad-spend/{channel}/{day} 광고비 한 칸 저장/지움(오늘까지)
POST /performance/api/ad-spend/upload?channel= 광고비 파일 업로드(쿠팡 윙·로켓 광고 보고서 1열 날짜·19열 청구금액,
네이버 광고 보고서 3열 기간·4열 총비용·12열 ROAS + 나머지 항목)
GET /performance/api/ad-spend/{channel}/details?from=&to= 일자별 보고서 항목(네이버 머리글 클릭)
GET /performance/api/ad-spend/{channel}/details?from=&to= 일자별 보고서 항목(네이버·구글 머리글 클릭)
POST /performance/api/ad-sources/{code}/sync 광고 API(구글 광고) 가져오기 — 보는 기간(오늘까지), 92일 넘으면 관리자
JSON API — 관리자
GET|PUT /performance/api/ad-sources/{code}/credentials 광고 API 인증정보(마이그레이션 007, 암호화 저장·비밀 원문 없음)
POST /performance/api/ad-sources/{code}/test 광고 API 연결 테스트(저장값 또는 새 입력값)
PUT /performance/api/marketplaces/{code} 사용/매출 집계/수동 입력 여부
POST /performance/api/marketplaces/{code}/rates 수수료율(적용 시작일)
DELETE /performance/api/marketplaces/{code}/rates/{id}
@@ -34,7 +37,7 @@ JSON API — 관리자
from __future__ import annotations
from datetime import date
from datetime import date, timedelta
from decimal import Decimal, InvalidOperation
from pathlib import Path
from typing import Any
@@ -59,10 +62,13 @@ AD_MIGRATION_HELP = ("광고비를 쓰려면 performance_db 마이그레이션 0
"먼저 적용해야 합니다.")
AD_MIGRATION_HELP_006 = ("광고 보고서 ROAS·상세 항목을 쓰려면 performance_db 마이그레이션 006"
"(scripts/sql/performance_db_006_ad_roas_metrics.sql)을 먼저 적용해야 합니다.")
AD_MIGRATION_HELP_007 = ("광고 API 연동(구글 광고) 인증정보를 저장하려면 performance_db 마이그레이션 007"
"(scripts/sql/performance_db_007_ad_api.sql)을 먼저 적용해야 합니다.")
def _ad_migration_help(exc: Exception) -> str:
return AD_MIGRATION_HELP_006 if "006" in str(exc) else AD_MIGRATION_HELP
text = str(exc)
return AD_MIGRATION_HELP_007 if "007" in text else AD_MIGRATION_HELP_006 if "006" in text else AD_MIGRATION_HELP
MANUAL_MIGRATION_HELP = ("수동 입력을 쓰려면 performance_db 마이그레이션 002(scripts/sql/performance_db_002_manual_sales.sql)를 "
"먼저 적용해야 합니다.")
@@ -155,6 +161,11 @@ def ads_page(
custom_from=_parse_date(from_), custom_to=_parse_date(to), holidays=_holidays(),
sales_codes=[m["code"] for m in _sales_marketplaces(store)],
)
# [구글 광고 불러오기] — 관리자가 실적 설정에서 인증정보를 넣은 광고 연동만
from .ad_sources.registry import get_source # noqa: WPS433
_, ad_sync = _ad_services(store)
ctx["ad_sync_sources"] = [{"code": c, "name": get_source(c).name} for c, ok in ad_sync.configured().items() if ok]
return render_template(request, "performance/ads.html",
{**common.base_ctx(user, active_tab="ads", page_title="광고비"), **ctx})
@@ -171,14 +182,37 @@ def settings_page(request: Request):
from .dashboard import build_settings # noqa: WPS433
creds, _ = common.services(request, store)
ad_creds, ad_sync = _ad_services(store)
versions = creds.key_versions_in_use()
for v, n in ad_creds.key_versions_in_use().items(): # 광고 API 인증정보도 같은 마스터 키
versions[v] = versions.get(v, 0) + n
ctx = build_settings(
store, configured=creds.configured_codes(list(all_adapters())), key_info=common.key_status(),
key_versions_in_use=creds.key_versions_in_use(), sample_count=store.sample_count(),
key_versions_in_use=versions, sample_count=store.sample_count(),
)
ctx["ad_sources"] = _ad_source_rows(store, ad_sync.configured())
ctx["ad_api_ready"] = store.ad_api_ready()
return render_template(request, "performance/settings.html",
{**common.base_ctx(user, active_tab="settings", page_title="실적 설정"), **ctx})
def _ad_source_rows(store: Any, configured: dict[str, bool]) -> list[dict[str, Any]]:
"""실적 설정 "광고 API 연동" 표 — 연동마다 설정 여부·연결 상태·마지막 가져오기."""
from .ad_sources.registry import all_sources # noqa: WPS433
from .adapters.base import STATUS_LABELS # noqa: WPS433
statuses = store.ad_source_statuses()
rows = []
for s in all_sources():
st = statuses.get(s.code, {})
status = st.get("status") or ("unknown" if configured.get(s.code) else "not_configured")
rows.append({"code": s.code, "name": s.name, "configured": bool(configured.get(s.code)), "status": status,
"status_label": STATUS_LABELS.get(status, status), "last_test_at": st.get("last_test_at"),
"last_error": st.get("last_error") or "", "last_error_at": st.get("last_error_at"),
"last_sync_at": st.get("last_sync_at"), "last_success_sync_at": st.get("last_success_sync_at")})
return rows
# ════════════════════════════════════════════════════════════
# JSON API — 모듈 권한
# ════════════════════════════════════════════════════════════
@@ -510,6 +544,113 @@ def api_ad_spend_upload(
"from": days[0].isoformat() if days else None, "to": days[-1].isoformat() if days else None})
# ════════════════════════════════════════════════════════════
# JSON API — 광고 API 연동(구글 광고). 인증정보·연결 테스트는 관리자, 가져오기는 모듈 권한자(92일 넘으면 관리자)
# ════════════════════════════════════════════════════════════
def _ad_services(store: Any):
"""(광고 인증정보 서비스, 광고 가져오기 서비스)."""
from .ad_sync import AdSyncService, ad_credentials # noqa: WPS433
creds = ad_credentials(store, common.key_ring)
return creds, AdSyncService(store, creds)
def _ad_source_or_404(code: str):
from .ad_sources.registry import get_source # noqa: WPS433
src = get_source(code)
if src is None:
raise HTTPException(status_code=404, detail="알 수 없는 광고 연동입니다.")
return src
@router.get("/api/ad-sources/{code}/credentials")
def api_ad_source_credentials(request: Request, code: str) -> JSONResponse:
"""입력칸 + 저장 여부만(비밀 원문 없음) — 쇼핑몰 API 설정 창과 같은 모양."""
store, _ = common.require_store(request, admin=True)
src = _ad_source_or_404(code)
creds, _ = _ad_services(store)
info = creds.describe(src)
if not store.ad_api_ready():
info["decrypt_error"] = AD_MIGRATION_HELP_007
return JSONResponse({"code": code, "name": src.name, "shared": False, "note": src.note, "docs_url": src.docs_url,
"key": common.key_status(), **info})
@router.put("/api/ad-sources/{code}/credentials")
def api_ad_source_save(request: Request, code: str, payload: dict[str, Any] = Body(...)) -> JSONResponse:
from .ad_spend import AdMigrationNeeded # noqa: WPS433
store, user = common.require_store(request, admin=True)
src = _ad_source_or_404(code)
if not common.key_status()["ok"]:
raise HTTPException(status_code=503, detail=common.key_status()["message"])
creds, _ = _ad_services(store)
values = _clean_values(src, payload)
clear = [str(k) for k in (payload.get("clear") or [])]
merged = creds.merged_values(src, values)
for k in clear:
if k in merged and not values.get(k):
merged[k] = ""
errors = src.validate_credentials(merged)
if errors:
raise HTTPException(status_code=400, detail=" ".join(errors))
try:
saved = creds.save(src, values, clear=clear, user=user["email"])
except AdMigrationNeeded as exc:
raise HTTPException(status_code=503, detail=_ad_migration_help(exc)) from None
return JSONResponse({"saved": saved, **creds.describe(src)})
@router.post("/api/ad-sources/{code}/test")
def api_ad_source_test(request: Request, code: str, payload: dict[str, Any] = Body(default={})) -> JSONResponse:
"""values 가 있으면 저장하지 않은 새 입력값으로 시험(빈 칸은 저장된 값)."""
store, user = common.require_store(request, admin=True)
src = _ad_source_or_404(code)
_, ad_sync = _ad_services(store)
values = {k: v for k, v in _clean_values(src, payload).items() if v.strip()}
return JSONResponse(ad_sync.test_connection(code, values=values or None, user=user["email"]))
@router.post("/api/ad-sources/{code}/sync")
def api_ad_source_sync(request: Request, code: str, payload: dict[str, Any] = Body(default={})) -> JSONResponse:
"""광고비 탭 [구글 광고 불러오기] — 기간(from·to, 없으면 최근 N일)을 가져와 저장. 오늘 뒤는 잘라낸다.
모듈 권한자는 92일까지, 그보다 길면(최대 366일) 관리자만."""
from app.store import is_admin # noqa: WPS433
from .ad_spend import AdMigrationNeeded # noqa: WPS433
from .ad_sync import AdSyncBusy # noqa: WPS433
from .auto_sync import sync_days # noqa: WPS433
store, user = common.require_store(request)
src = _ad_source_or_404(code)
today = today_kst()
end = _parse_date(payload.get("to"), field="종료일") or today
start = _parse_date(payload.get("from"), field="시작일") or (end - timedelta(days=sync_days() - 1))
if end < start:
start, end = end, start
end = min(end, today)
if start > end:
raise HTTPException(status_code=400, detail="앞으로의 기간은 가져올 수 없습니다.")
days = (end - start).days + 1
if days > MAX_BACKFILL_DAYS:
raise HTTPException(status_code=400, detail=f"한 번에 {MAX_BACKFILL_DAYS}일까지 가져올 수 있습니다.")
if days > MAX_USER_SYNC_DAYS and not is_admin(user):
raise HTTPException(status_code=403, detail=f"{MAX_USER_SYNC_DAYS}일보다 긴 기간은 관리자만 가져올 수 있습니다.")
_, ad_sync = _ad_services(store)
if not ad_sync.configured().get(code):
raise HTTPException(status_code=400, detail=f"{src.name} API 가 설정되지 않았습니다. 관리자가 실적 설정 → 광고 API 연동에서 입력해야 합니다.")
try:
res = ad_sync.sync(code, start, end, user=user["email"])
except AdSyncBusy as exc:
raise HTTPException(status_code=409, detail=str(exc)) from None
except AdMigrationNeeded as exc:
raise HTTPException(status_code=503, detail=_ad_migration_help(exc)) from None
if not res.get("ok"):
return JSONResponse(status_code=502, content={"detail": f"{src.name} 가져오기 실패 — {res.get('message')}", **res})
return JSONResponse(res)
# ════════════════════════════════════════════════════════════
# JSON API — 설정(수수료율은 모듈 권한자 누구나, 나머지는 관리자)
# ════════════════════════════════════════════════════════════
@@ -678,4 +819,10 @@ def api_rekey(request: Request) -> JSONResponse:
if not common.key_status()["ok"]:
raise HTTPException(status_code=503, detail=common.key_status()["message"])
creds, _ = common.services(request, store)
return JSONResponse({**creds.reencrypt_all(), "versions_in_use": creds.key_versions_in_use()})
ad_creds, _ = _ad_services(store)
shop, ad = creds.reencrypt_all(), ad_creds.reencrypt_all() # 광고 API 인증정보도 같은 마스터 키
versions = creds.key_versions_in_use()
for v, n in ad_creds.key_versions_in_use().items():
versions[v] = versions.get(v, 0) + n
return JSONResponse({"reencrypted": shop["reencrypted"] + ad["reencrypted"], "failed": shop["failed"] + ad["failed"],
"versions_in_use": versions})
@@ -1,6 +1,6 @@
{% extends "erp_base.html" %}
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261014b" />{% endblock %}
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261015a" />{% endblock %}
{#- ROAS 덧붙임 — "광고비(ROAS%)". 광고비가 없으면 아무것도 안 붙는다. -#}
{%- macro roas(p) -%}{%- if p is not none -%}<span class="perf-roas">({{ "{:,}".format(p) }}%)</span>{%- endif -%}{%- endmacro -%}
@@ -72,17 +72,24 @@
<div class="erp-card perf-card">
<div class="perf-card-head">
<h2 class="perf-h">{% if period_kind == 'year' %}월별 × 광고 채널{% else %}일자별 × 광고 채널{% endif %}</h2>
<div class="perf-ad-actions">
{% for s in ad_sync_sources %}
<button type="button" class="erp-btn erp-btn-outline erp-btn-sm perf-ad-sync-btn" data-ad-sync="{{ s.code }}"
title="{{ s.name }} API 로 지금 보는 기간(오늘까지)의 광고비·ROAS 를 가져옵니다 — 같은 날은 덮어씀">
<span class="material-symbols-outlined" aria-hidden="true">sync</span>{{ s.name }} 불러오기</button>
{% endfor %}
{% if upload_channels %}
<button type="button" class="erp-btn erp-btn-outline erp-btn-sm perf-manual-upload-btn perf-ad-upload-btn" id="perf-ad-upload"
title="광고 보고서 파일로 일별 광고비를 한 번에 입력">파일 업로드</button>
{% endif %}
</div>
</div>
<div class="erp-table-wrap perf-table-wrap">
<table class="perf-table perf-main">
<thead>
<tr>
<th class="perf-th-label">{% if period_kind == 'year' %}월{% else %}날짜{% endif %}</th>
{% for c in codes %}{% if c in detail_channels %}<th class="perf-th-detail" title="{{ names[c] }} — 눌러 일자별 광고 보고서 항목 보기. 괄호 = 보고서 ROAS(구매완료 광고수익률)"><button type="button" class="perf-detail-btn" data-detail-channel="{{ c }}">{{ names[c] }} <span class="material-symbols-outlined" aria-hidden="true">table_view</span></button></th>{% else %}<th title="{{ names[c] }} — 날짜 칸을 눌러 광고비 입력.{% if roas_basis[c] %} 괄호 = ROAS({{ roas_basis[c] }} 매출 ÷ 광고비){% else %} ROAS 는 계산하지 않음(따로 입력){% endif %}">{{ names[c] }} <span class="perf-manual-mark" aria-hidden="true">✎</span></th>{% endif %}{% endfor %}
{% for c in codes %}{% if c in detail_channels %}<th class="perf-th-detail" title="{{ names[c] }} — 눌러 일자별 광고 보고서 항목 보기. 괄호 = {% if c == 'google' %}구글 광고 ROAS(전환 가치 ÷ 비용){% else %}보고서 ROAS(구매완료 광고수익률){% endif %}"><button type="button" class="perf-detail-btn" data-detail-channel="{{ c }}">{{ names[c] }} <span class="material-symbols-outlined" aria-hidden="true">table_view</span></button></th>{% else %}<th title="{{ names[c] }} — 날짜 칸을 눌러 광고비 입력.{% if roas_basis[c] %} 괄호 = ROAS({{ roas_basis[c] }} 매출 ÷ 광고비){% else %} ROAS 는 계산하지 않음(따로 입력){% endif %}">{{ names[c] }} <span class="perf-manual-mark" aria-hidden="true">✎</span></th>{% endif %}{% endfor %}
<th class="perf-th-total">{% if period_kind == 'year' %}월 합계{% else %}일 합계{% endif %}</th>
</tr>
</thead>
@@ -96,9 +103,10 @@
{% set v = r.cells[c].gross %}
{% if r.kind == 'day' and not r.future and not migration_needed %}
{% set up = (r.date ~ '|' ~ c) in upload_cells %}
<td class="perf-num is-manual-cell{% if v and not up %} is-manual{% endif %}{% if up %} is-upload{% endif %}"
{% set ap = (r.date ~ '|' ~ c) in api_cells %}
<td class="perf-num is-manual-cell{% if v and not up and not ap %} is-manual{% endif %}{% if up %} is-upload{% endif %}{% if ap %} is-api{% endif %}"
data-manual-code="{{ c }}" data-date="{{ r.date }}" data-manual-value="{{ v if v else '' }}" tabindex="0"
title="{% if up %}파일 업로드 값 — 눌러 고치기{% else %}눌러 광고비 입력(비우고 저장하면 지움){% endif %}"><span class="v v-gross">{{ won(v) }}</span>{{ roas(r.roas[c]) }}</td>
title="{% if ap %}광고 API 값 — 눌러 고치기(다음 불러오기 때 다시 API 값으로){% elif up %}파일 업로드 값 — 눌러 고치기{% else %}눌러 광고비 입력(비우고 저장하면 지움){% endif %}"><span class="v v-gross">{{ won(v) }}</span>{{ roas(r.roas[c]) }}</td>
{% else %}
<td class="perf-num"><span class="v v-gross">{{ won(v) }}</span>{{ roas(r.roas[c]) }}</td>
{% endif %}
@@ -111,9 +119,10 @@
</div>
{% if period_kind != 'year' %}
<p class="perf-muted perf-manual-help">날짜 칸을 눌러 그날 <b>광고비</b>를 직접 입력합니다 — Enter 저장 후 아래 칸, Esc 취소, 비우고 저장하면 지움.
칸은 <b>광고비(ROAS%)</b> — ROAS = 그 쇼핑몰 매출 실적 총매출 ÷ 광고비(합계 열은 전체 매출). 구글·메타는 ROAS 를 계산하지 않고,
네이버는 광고 보고서의 ROAS(구매완료 광고수익률)를 씁니다 — 네이버 머리글을 누르면 일자별 보고서 항목.
파란 숫자 = 직접 입력, 주황 숫자 = 파일 업로드 값. 쿠팡(윙)·쿠팡(로켓)은 [파일 업로드]로 광고 보고서를 올리면 날짜별로 한 번에 들어갑니다.</p>
칸은 <b>광고비(ROAS%)</b> — ROAS = 그 쇼핑몰 매출 실적 총매출 ÷ 광고비(합계 열은 전체 매출). 메타는 ROAS 를 계산하지 않고,
네이버는 광고 보고서의 ROAS(구매완료 광고수익률), 구글은 구글 광고 API 의 ROAS(전환 가치 ÷ 비용)를 씁니다 — 네이버·구글 머리글을 누르면 일자별 보고서 항목.
파란 숫자 = 직접 입력, 주황 숫자 = 파일 업로드 값, 초록 숫자 = 광고 API 값. 쿠팡(윙)·쿠팡(로켓)·네이버는 [파일 업로드]로 광고 보고서를 올리면 날짜별로 한 번에 들어갑니다.
구글은 [구글 광고 불러오기](관리자가 실적 설정 → 광고 API 연동을 마친 뒤) 또는 매출 자동 업데이트 때 들어옵니다.</p>
{% endif %}
</div>
@@ -191,9 +200,10 @@
</div>
<p class="perf-foot perf-muted">
광고비 기준: 쿠팡(윙)·쿠팡(로켓)은 광고 보고서의 청구금액(+부가가치세). ROAS = 그 쇼핑몰 매출 ÷ 광고비 × 100(구글·메타는 계산 안 함, 네이버는 보고서 값).
광고비 기준: 쿠팡(윙)·쿠팡(로켓)은 광고 보고서의 청구금액(+부가가치세), 구글은 구글 광고 비용(부가세 별도).
ROAS = 그 쇼핑몰 매출 ÷ 광고비 × 100(메타는 계산 안 함, 네이버·구글은 광고 쪽 값).
매출 대비 광고비 = 같은 기간 광고비 ÷ 매출 실적 총매출.
구글·메타는 지금은 직접 입력합니다.
메타는 지금은 직접 입력합니다.
</p>
</section>
@@ -214,4 +224,4 @@
} | tojson }}</script>
{% endblock %}
{% block scripts %}<script src="/static/performance.js?v=20261014e" defer></script>{% endblock %}
{% block scripts %}<script src="/static/performance.js?v=20261015a" defer></script>{% endblock %}
@@ -1,6 +1,6 @@
{% extends "erp_base.html" %}
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261014b" />{% endblock %}
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261015a" />{% endblock %}
{%- macro won(v) -%}
{%- if v is none -%}<span class="perf-na"></span>
@@ -255,4 +255,4 @@
} | tojson }}</script>
{% endblock %}
{% block scripts %}<script src="/static/performance.js?v=20261014e" defer></script>{% endblock %}
{% block scripts %}<script src="/static/performance.js?v=20261015a" defer></script>{% endblock %}
@@ -1,6 +1,6 @@
{% extends "erp_base.html" %}
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261014b" />{% endblock %}
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261015a" />{% endblock %}
{%- macro when(v) -%}{{ (v or '')[:16] | replace('T', ' ') or '—' }}{%- endmacro -%}
@@ -103,6 +103,50 @@
</div>
{% if is_admin %}
{# 광고 API 연동(2026-10-15, 마이그레이션 007) — 구글 광고 등. 인증정보는 쇼핑몰과 같은 마스터 키로 암호화 저장.
가져온 광고비·ROAS 는 광고비 탭(초록 숫자). [설정]·[연결 테스트]는 쇼핑몰 표와 같은 창(/api/ad-sources/…). #}
<div class="erp-card perf-card" id="perf-ad-sources">
<div class="perf-card-head">
<h2 class="perf-h">광고 API 연동</h2>
<span class="perf-muted">광고비 탭의 광고비·ROAS 를 광고 API 로 가져옵니다. 인증정보는 [설정]에서 입력하면 암호화해 저장합니다.
설정이 끝나면 광고비 탭 [구글 광고 불러오기]와 매출 자동 업데이트(30분마다 최근 며칠) 때 함께 가져옵니다.</span>
</div>
{% if not ad_api_ready %}
<div class="perf-notice is-warn">광고 API 인증정보 저장 표가 아직 없습니다. performance_db 마이그레이션 007
(scripts/sql/performance_db_007_ad_api.sql)을 적용해야 저장할 수 있습니다.</div>
{% endif %}
<div class="erp-table-wrap">
<table class="perf-table perf-set-table">
<thead>
<tr><th class="perf-th-label">광고</th><th>API 설정</th><th>연결 상태</th><th>마지막 가져오기</th><th></th></tr>
</thead>
<tbody>
{% for a in ad_sources %}
<tr data-code="{{ a.code }}" data-name="{{ a.name }}" data-api="ad-sources">
<th class="perf-td-label" scope="row">{{ a.name }}</th>
<td>{% if a.configured %}<span class="perf-pill is-ok">설정완료</span>{% else %}<span class="perf-pill">미설정</span>{% endif %}</td>
<td>
<span class="perf-status st-{{ a.status }}"
title="마지막 연결 테스트: {{ when(a.last_test_at) }}{% if a.last_error %}&#10;최근 오류({{ when(a.last_error_at) }}): {{ a.last_error }}{% endif %}">
<i></i>{{ a.status_label }}</span>
{% if a.last_error and a.status not in ('ok',) %}<div class="perf-err">{{ a.last_error }}</div>{% endif %}
</td>
<td class="perf-muted perf-nowrap" title="마지막 시도: {{ when(a.last_sync_at) }}">{{ when(a.last_success_sync_at) }}</td>
<td class="perf-nowrap">
<button type="button" class="erp-btn erp-btn-outline erp-btn-sm" data-act="creds">설정</button>
<button type="button" class="erp-btn erp-btn-outline erp-btn-sm" data-act="test">연결 테스트</button>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
<p class="perf-foot perf-muted">
구글 광고: 비용은 구글 광고 화면의 "비용"(부가세 별도), ROAS = 전환 가치 ÷ 비용. 날짜는 광고 계정 시간대 기준이며 원화(KRW) 계정만 가져옵니다.
가져온 날은 직접 입력·업로드 값보다 우선해 덮어씁니다.
</p>
</div>
<div class="perf-grid2">
<div class="erp-card perf-card">
<div class="perf-card-head"><h2 class="perf-h">인증정보 암호화</h2></div>
@@ -120,7 +164,7 @@
<button type="button" class="erp-btn erp-btn-outline erp-btn-sm" id="perf-rekey">현재 키로 다시 암호화</button></p>
{% endif %}
<p class="perf-foot perf-muted">
API 인증정보는 서버에서 AES-256-GCM 으로 암호화해 DB 에 저장합니다. 마스터 키(APP_ENCRYPTION_KEY)는 DB 가 아닌
API 인증정보(쇼핑몰·광고)는 서버에서 AES-256-GCM 으로 암호화해 DB 에 저장합니다. 마스터 키(APP_ENCRYPTION_KEY)는 DB 가 아닌
서버 환경변수에만 있으며, 키를 잃으면 저장된 인증정보를 복구할 수 없으니 별도로 안전하게 보관하세요.
</p>
</div>
@@ -204,4 +248,4 @@
</section>
{% endblock %}
{% block scripts %}<script src="/static/performance.js?v=20261014e" defer></script>{% endblock %}
{% block scripts %}<script src="/static/performance.js?v=20261015a" defer></script>{% endblock %}
@@ -126,7 +126,8 @@ def test_ad_dashboard_month():
assert k["ytd"]["value"] == 370000 and k["mtd"]["value"] == 270000
assert ctx["upload_cells"] == ["2026-10-01|coupang_rocket"]
assert [c["code"] for c in ctx["upload_channels"]] == ["naver", "coupang_wing", "coupang_rocket"]
assert ctx["detail_channels"] == ["naver"]
assert ctx["detail_channels"] == ["google", "naver"] # 구글 = 광고 API 로 가져온 항목(2026-10-15)
assert ctx["api_cells"] == []
day1 = next(r for r in ctx["table"] if r.get("date") == "2026-10-01")
assert day1["cells"]["coupang_rocket"]["gross"] == 220000 and day1["total"]["gross"] == 220000
assert ctx["table"][-1]["kind"] == "total" and ctx["table"][-1]["total"]["gross"] == 270000
@@ -60,7 +60,9 @@ def test_run_once_uses_job_and_skips_when_busy(monkeypatch):
monkeypatch.setattr(jobs, "running_job", lambda: None)
res = au.run_once(Store(), None, today=date(2026, 10, 13), days=10)
assert calls == [(date(2026, 10, 4), date(2026, 10, 13), "schedule", au.AUTO_USER, True)]
assert res == {"skipped": False, "from": "2026-10-04", "to": "2026-10-13", "ok": 1, "failed": ["toss"], "error": ""}
# 광고 API 저장소 메서드가 없는 가짜 저장소 — 광고 가져오기는 조용히 빠지고 매출 결과는 그대로
assert res == {"skipped": False, "from": "2026-10-04", "to": "2026-10-13", "ok": 1, "failed": ["toss"], "error": "",
"ads": []}
monkeypatch.setattr(jobs, "running_job", lambda: object())
assert au.run_once(Store(), None, today=date(2026, 10, 13), days=10)["skipped"]
@@ -0,0 +1,292 @@
"""구글 광고 API 연동(2026-10-15) — 입력 검사·토큰·조회·변환·오류 안내·저장 서비스·라우터. 구글 서버는 가짜(httpx MockTransport)."""
from __future__ import annotations
import json
from datetime import date
from decimal import Decimal
from urllib.parse import parse_qs
import httpx
import pytest
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import rsa
from app.modules.performance import ad_sync
from app.modules.performance.ad_sources import google_ads as ga
from app.modules.performance.adapters.base import AdapterContext, ApiError, AuthFailed, NotConfigured
from app.modules.performance.credentials import CredentialService, aad_for
from app.modules.performance.security import crypto
KEY1 = "11" * 32
def _sa_json() -> str:
key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
pem = key.private_bytes(serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8,
serialization.NoEncryption()).decode()
return json.dumps({"type": "service_account", "client_email": "erp@proj.iam.gserviceaccount.com",
"private_key_id": "kid1", "private_key": pem, "token_uri": "https://oauth2.googleapis.com/token"})
SA = _sa_json()
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 v in self.values.values() if v]
def _ctx(**over):
values = {"developer_token": "DEVTOKEN", "customer_id": "123-456-7890", "service_account_json": SA}
values.update(over)
return AdapterContext(code="google", credentials=Creds(values))
def _install(monkeypatch, handler):
"""구글(토큰·광고 API) 가짜 서버 — handler(request) 가 searchStream 응답을 만든다. 보낸 요청을 돌려준다."""
ga._token_cache.clear()
seen = []
def route(request: httpx.Request) -> httpx.Response:
seen.append(request)
if request.url.host == "oauth2.googleapis.com":
form = parse_qs(request.content.decode())
assert form["grant_type"] == ["urn:ietf:params:oauth:grant-type:jwt-bearer"] and form["assertion"][0].count(".") == 2
return httpx.Response(200, json={"access_token": "ya29.TOKEN", "expires_in": 3600})
return handler(request)
monkeypatch.setattr(ga, "_http", lambda ctx: httpx.Client(transport=httpx.MockTransport(route)))
return seen
ROWS = [{"results": [
{"customer": {"currencyCode": "KRW"}, "segments": {"date": "2026-10-01"},
"metrics": {"costMicros": "123456500000", "impressions": "20000", "clicks": "400", "conversions": 12.5,
"conversionsValue": 617282.5}},
{"customer": {"currencyCode": "KRW"}, "segments": {"date": "2026-10-02"},
"metrics": {"impressions": "50"}}, # 비용 0(값이 빠진 칸)
]}, {"results": [
{"customer": {"currencyCode": "KRW"}, "segments": {"date": "2026-10-03"},
"metrics": {"costMicros": "1000000", "clicks": "1", "impressions": "10", "conversionsValue": 3000}},
]}]
def test_validate_credentials():
src = ga.GoogleAdsSource()
ok = {"developer_token": "x", "customer_id": "123-456-7890", "service_account_json": SA}
assert src.validate_credentials(ok) == []
assert src.validate_credentials({**ok, "service_account_json": "__stored__", "developer_token": "__stored__"}) == []
errs = src.validate_credentials({**ok, "customer_id": "12345", "login_customer_id": "abc", "api_version": "26",
"service_account_json": '{"type": "authorized_user"}'})
assert len(errs) == 4 and not any("BEGIN" in e for e in errs) # 키 내용은 문구에 없음
assert "입력하세요" in " ".join(src.validate_credentials({}))
assert "JSON" in " ".join(src.validate_credentials({**ok, "service_account_json": "not json"}))
def test_fetch_days_converts_and_sends_headers(monkeypatch):
seen = _install(monkeypatch, lambda req: httpx.Response(200, json=ROWS))
days = ga.GoogleAdsSource().fetch_days(_ctx(login_customer_id="999-888-7777", api_version="v27"),
date(2026, 10, 1), date(2026, 10, 3))
api = seen[-1]
assert str(api.url) == "https://googleads.googleapis.com/v27/customers/1234567890/googleAds:searchStream"
assert api.headers["Authorization"] == "Bearer ya29.TOKEN" and api.headers["developer-token"] == "DEVTOKEN"
assert api.headers["login-customer-id"] == "9998887777"
q = json.loads(api.content)["query"]
assert "segments.date BETWEEN '2026-10-01' AND '2026-10-03'" in q and "metrics.conversions_value" in q
d1, d2, d3 = days
assert (d1.day, d1.amount, d1.roas) == (date(2026, 10, 1), 123457, Decimal("500.00")) # 123,456.5원 → 반올림, 617,282.5 ÷ 123,456.5
assert d1.metrics == {"비용": 123457, "노출수": 20000, "클릭수": 400, "클릭률(%)": 2.0, "전환수": 12.5,
"전환 가치": 617283, "ROAS(%)": 500.0}
assert (d2.amount, d2.roas, d2.metrics["클릭률(%)"]) == (0, None, 0.0) # 비용 0 → ROAS 없음
assert (d3.amount, d3.roas) == (1, Decimal("300000.00"))
# 토큰은 한 번만 받아 두고 다시 쓴다
ga.GoogleAdsSource().fetch_days(_ctx(), date(2026, 10, 1), date(2026, 10, 1))
assert sum(1 for r in seen if r.url.host == "oauth2.googleapis.com") == 1
assert "login-customer-id" not in seen[-1].headers and "/v26/" in str(seen[-1].url) # 비우면 MCC 없음·기본 버전
def test_errors_are_explained(monkeypatch):
src = ga.GoogleAdsSource()
denied = [{"error": {"code": 403, "message": "The caller does not have permission", "status": "PERMISSION_DENIED",
"details": [{"errors": [{"errorCode": {"authorizationError": "USER_PERMISSION_DENIED"},
"message": "User doesn't have permission to access customer."}]}]}}]
_install(monkeypatch, lambda req: httpx.Response(403, json=denied))
with pytest.raises(AuthFailed) as e:
src.fetch_days(_ctx(), date(2026, 10, 1), date(2026, 10, 1))
assert "USER_PERMISSION_DENIED" in e.value.message and "액세스 및 보안" in e.value.message
_install(monkeypatch, lambda req: httpx.Response(404, text="Not Found"))
with pytest.raises(ApiError) as e:
src.fetch_days(_ctx(api_version="v19"), date(2026, 10, 1), date(2026, 10, 1))
assert "v19" in e.value.message and "API 버전" in e.value.message
usd = [{"results": [{"customer": {"currencyCode": "USD"}, "segments": {"date": "2026-10-01"}, "metrics": {}}]}]
_install(monkeypatch, lambda req: httpx.Response(200, json=usd))
with pytest.raises(ApiError, match="USD"):
src.fetch_days(_ctx(), date(2026, 10, 1), date(2026, 10, 1))
with pytest.raises(NotConfigured):
src.fetch_days(_ctx(customer_id=""), date(2026, 10, 1), date(2026, 10, 1))
ga._token_cache.clear()
def bad_token(request):
return httpx.Response(400, json={"error": "invalid_grant", "error_description": "Invalid JWT Signature."})
monkeypatch.setattr(ga, "_http", lambda ctx: httpx.Client(transport=httpx.MockTransport(bad_token)))
with pytest.raises(AuthFailed, match="invalid_grant"):
src.fetch_days(_ctx(), date(2026, 10, 1), date(2026, 10, 1))
def test_connection_message(monkeypatch):
body = [{"results": [{"customer": {"id": "1234567890", "descriptiveName": "미라네주방", "currencyCode": "KRW",
"timeZone": "Asia/Seoul"}}]}]
_install(monkeypatch, lambda req: httpx.Response(200, json=body))
assert ga.GoogleAdsSource().test_connection(_ctx()) == "연결됨 — 미라네주방 · 통화 KRW · 시간대 Asia/Seoul"
def test_ad_credentials_use_own_namespace():
"""광고 인증정보 암호문은 "perf:ad:{채널}:{항목}" 에 묶인다 — 쇼핑몰 암호문과 바꿔 넣으면 복호화되지 않는다."""
ring = crypto.KeyRing.from_env({"APP_ENCRYPTION_KEY": KEY1})
class Table:
def __init__(self):
self.rows = {}
def credential_rows(self, code):
return {k: {"encrypted_value": v, "key_version": 1} for (c, k), v in self.rows.items() if c == code}
def upsert_credential(self, code, key, *, encrypted_value, key_version, user=""):
self.rows[(code, key)] = encrypted_value
t = Table()
svc = CredentialService(t, lambda: ring, aad_ns=ad_sync.AD_NS)
svc.save(ga.GoogleAdsSource(), {"developer_token": "DEV", "customer_id": "1234567890"}, user="king")
assert svc.accessor("google").get("developer_token") == "DEV"
assert aad_for("google", "developer_token", "ad:") == "perf:ad:google:developer_token"
with pytest.raises(Exception):
crypto.decrypt(t.rows[("google", "developer_token")], aad=aad_for("google", "developer_token"), ring=ring)
class FakeStore:
def __init__(self):
self.replaced, self.status = [], []
def ad_credential_keys_by_code(self):
return {"google": {"developer_token", "customer_id", "service_account_json"}}
def ad_credential_rows(self, code):
return {}
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 _service(store, source):
svc = ad_sync.AdSyncService(store, CredentialService(None, lambda: None))
svc.configured = lambda: {"google": True}
svc._ctx = lambda code, values=None, user="": _ctx()
return svc
def test_sync_service_saves_and_records(monkeypatch):
store = FakeStore()
from app.modules.performance.ad_sources.base import AdDay
src = ga.GoogleAdsSource()
monkeypatch.setattr(src, "fetch_days", lambda ctx, s, e: [AdDay(date(2026, 10, 1), 1000, Decimal("250.00"), {"비용": 1000})])
monkeypatch.setattr(ad_sync, "get_source", lambda code: src)
svc = _service(store, src)
res = svc.sync("google", date(2026, 10, 1), date(2026, 10, 3), user="king@x")
assert res["ok"] and res["days"] == 1 and res["total"] == 1000
assert store.replaced == [("google", date(2026, 10, 1), date(2026, 10, 3),
[(date(2026, 10, 1), 1000, Decimal("250.00"), {"비용": 1000})], "king@x")]
assert store.status[-1] == ("google", "ok", True, "", "sync")
# 실패: 저장 안 하고 상태에 오류(저장된 비밀값은 가림)
def boom(ctx, s, e):
raise AuthFailed("토큰 DEVTOKEN 거부")
monkeypatch.setattr(src, "fetch_days", boom)
res = svc.sync("google", date(2026, 10, 1), date(2026, 10, 1))
assert not res["ok"] and res["status"] == "auth_failed" and "DEVTOKEN" not in res["message"]
assert len(store.replaced) == 1 and store.status[-1][1:3] == ("auth_failed", False)
# 같은 채널 동시 실행 막기
lock = ad_sync._lock("google")
lock.acquire()
try:
with pytest.raises(ad_sync.AdSyncBusy):
svc.sync("google", date(2026, 10, 1), date(2026, 10, 1))
assert svc.sync_all(date(2026, 10, 1), date(2026, 10, 1))[0]["skipped"]
finally:
lock.release()
def test_sync_endpoint(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")
calls, admin = [], {"v": False}
class Svc:
def __init__(self):
self.result = {"ok": True, "code": "google", "name": "구글 광고", "days": 3, "total": 9000}
self.conf = {"google": True}
def configured(self):
return self.conf
def sync(self, code, start, end, *, user=""):
calls.append((code, start, end, user))
return {**self.result, "from": start.isoformat(), "to": end.isoformat()}
svc = Svc()
monkeypatch.setattr(common, "require_store", lambda request, admin=False: (object(), {"email": "king@x"}))
monkeypatch.setattr(perf_router, "today_kst", lambda: date(2026, 10, 15))
monkeypatch.setattr(perf_router, "_ad_services", lambda store: (None, svc))
import app.store as app_store
monkeypatch.setattr(app_store, "is_admin", lambda user: admin["v"])
app = FastAPI()
app.include_router(perf_router.router)
client = TestClient(app)
r = client.post("/performance/api/ad-sources/google/sync", json={"from": "2026-10-01", "to": "2026-10-31"})
assert r.status_code == 200 and r.json()["to"] == "2026-10-15" # 오늘 뒤는 잘라냄
assert calls[-1] == ("google", date(2026, 10, 1), date(2026, 10, 15), "king@x")
r = client.post("/performance/api/ad-sources/google/sync", json={})
assert r.status_code == 200 and calls[-1][1] == date(2026, 10, 6) # 기본 = 최근 10일
r = client.post("/performance/api/ad-sources/google/sync", json={"from": "2026-01-01", "to": "2026-10-15"})
assert r.status_code == 403 # 92일 넘으면 관리자만
admin["v"] = True
assert client.post("/performance/api/ad-sources/google/sync", json={"from": "2026-01-01", "to": "2026-10-15"}).status_code == 200
assert client.post("/performance/api/ad-sources/meta/sync", json={}).status_code == 404
svc.result = {"ok": False, "code": "google", "name": "구글 광고", "status": "auth_failed", "message": "권한 없음"}
r = client.post("/performance/api/ad-sources/google/sync", json={})
assert r.status_code == 502 and "권한 없음" in r.json()["detail"]
svc.conf = {"google": False}
r = client.post("/performance/api/ad-sources/google/sync", json={})
assert r.status_code == 400 and "설정" in r.json()["detail"]
+7
View File
@@ -58,6 +58,13 @@ a.perf-tab.is-active:link, a.perf-tab.is-active:visited { color: #fff; }
.perf-ads .perf-quick .perf-seg.is-active { background: var(--perf-ad); }
.perf-ads .perf-chart .bar { fill: var(--perf-ad); }
.perf-ads td.is-upload .v-gross { color: var(--perf-ad); }
/* 광고 API(구글 광고 등)로 가져온 칸 — 초록 숫자 */
.perf-ads td.is-api .v-gross { color: #1e8e3e; }
.perf-ad-actions { margin-left: auto; display: inline-flex; align-items: center; gap: 6px; flex-wrap: wrap; }
.perf-ad-sync-btn { display: inline-flex; align-items: center; gap: 4px; }
.perf-ad-sync-btn .material-symbols-outlined { font-size: 16px; color: #1e8e3e; }
/* 광고 API 설정 창 — 서비스 계정 JSON 같은 여러 줄 항목 */
.perf-cred-multi { width: 100%; font-family: ui-monospace, Consolas, monospace; font-size: 12px; resize: vertical; }
/* "광고비(ROAS%)" — ROAS 는 작게 옅게 붙인다. 입력 중엔 숫자처럼 자리만 남기고 숨김 */
.perf-roas { margin-left: 2px; font-size: 11px; font-weight: 500; color: var(--color-midtone-gray); }
.perf-row-total .perf-roas { color: #bbb; }
+45 -16
View File
@@ -383,7 +383,27 @@
});
});
// 광고 보고서 일자별 상세(네이버 머리글) — 지금 보는 기간의 날마다 광고비·ROAS·보고서 항목, 맨 아래 합계.
// [구글 광고 불러오기] — 광고 API 로 지금 보는 기간(오늘까지)을 가져와 저장(같은 날 덮어씀) → 새로고침.
root.addEventListener("click", async function (e) {
const btn = e.target.closest("[data-ad-sync]");
if (!btn || btn.disabled) return;
const label = btn.textContent;
btn.disabled = true;
btn.textContent = "불러오는 중…";
try {
const res = await api("POST", "/performance/api/ad-sources/" + encodeURIComponent(btn.dataset.adSync) + "/sync",
{ from: data.period_start, to: data.period_end });
await alertMsg(res.name + " — " + res.from + " ~ " + res.to + "\n" + (res.days ? res.days + "일, 광고비 ₩" + fmt(res.total) + " 반영" : "이 기간 광고비가 없습니다."),
{ tone: "ok" });
location.reload();
} catch (err) {
alertMsg(err.message);
btn.disabled = false;
btn.textContent = label;
}
});
// 광고 보고서 일자별 상세(네이버·구글 머리글) — 지금 보는 기간의 날마다 광고비·ROAS·보고서 항목, 맨 아래 합계.
root.addEventListener("click", async function (e) {
const btn = e.target.closest("[data-detail-channel]");
if (!btn) return;
@@ -394,7 +414,7 @@
try {
const res = await api("GET", "/performance/api/ad-spend/" + encodeURIComponent(code) + "/details?from=" +
encodeURIComponent(data.period_start) + "&to=" + encodeURIComponent(data.period_end));
if (!res.rows || !res.rows.length) { m.body.innerHTML = '<p class="perf-muted">이 기간에 올린 보고서 자료가 없습니다.</p>'; return; }
if (!res.rows || !res.rows.length) { m.body.innerHTML = '<p class="perf-muted">이 기간 보고서 자료가 없습니다(파일 업로드 또는 광고 API 불러오기).</p>'; return; }
const cols = res.columns || [];
const cell = function (v) {
if (v == null || v === "") return '<span class="perf-zero">–</span>';
@@ -413,7 +433,7 @@
}).join("") + '</tbody><tfoot><tr class="perf-row-total"><th class="perf-td-label" scope="row">합계</th>' +
cols.map(function (c) { return '<td class="perf-num">' + cell((res.total || {})[c]) + "</td>"; }).join("") +
"</tr></tfoot></table></div>" +
'<p class="perf-muted">합계: 숫자 항목은 더한 값, 클릭률 = 클릭수 ÷ 노출수, 광고수익률 = 날짜별 광고수익률을 총비용으로 가중 평균.</p>';
'<p class="perf-muted">합계: 숫자 항목은 더한 값, 클릭률 = 클릭수 ÷ 노출수, 광고수익률·ROAS = 날짜별 값을 광고비로 가중 평균.</p>';
} catch (err) {
m.body.innerHTML = '<p class="perf-notice is-warn">' + esc(err.message) + "</p>";
}
@@ -717,9 +737,11 @@
if (!btn) return;
const tr = btn.closest("tr");
const code = tr.dataset.code, name = tr.dataset.name;
// 광고 API 연동 줄(data-api="ad-sources")은 /performance/api/ad-sources/…, 나머지는 쇼핑몰
const base = "/performance/api/" + (tr.dataset.api || "marketplaces") + "/";
if (btn.dataset.act === "rate") openRate(code, name, btn.dataset.hasHistory === "1");
else if (btn.dataset.act === "creds") openCreds(code, name);
else if (btn.dataset.act === "test") runTest(code, name, btn);
else if (btn.dataset.act === "creds") openCreds(code, name, base);
else if (btn.dataset.act === "test") runTest(code, name, btn, base);
});
function today() {
@@ -790,11 +812,12 @@
}
// ── API 인증정보 ──
async function openCreds(code, name) {
async function openCreds(code, name, base) {
base = base || "/performance/api/marketplaces/";
const m = openModal(name + " API 설정", { narrow: true, onClose: function () { if (m.changed) location.reload(); } });
m.body.innerHTML = '<p class="perf-muted">불러오는 중…</p>';
let info;
try { info = await api("GET", "/performance/api/marketplaces/" + code + "/credentials"); }
try { info = await api("GET", base + code + "/credentials"); }
catch (err) { m.body.innerHTML = '<p class="perf-notice is-warn">' + esc(err.message) + "</p>"; return; }
const result = el("span", { class: "perf-test-result" });
@@ -818,10 +841,16 @@
? '<span class="perf-secret-state">현재 값: •••••••• (저장됨' + (f.updated_at ? ", " + esc(f.updated_at.slice(0, 16).replace("T", " ")) : "") + ")</span>"
: '<span class="perf-secret-state is-empty">저장된 값 없음</span>';
}
// 여러 줄 항목(서비스 계정 JSON 키 등)은 textarea — 비밀값이면 저장 후 내용은 다시 보이지 않는다
const field = f.multiline
? '<textarea class="erp-input perf-cred-multi" id="' + id + '" data-key="' + esc(f.key) + '" rows="6" spellcheck="false" ' +
'autocomplete="off" placeholder="' + (f.secret && f.has_value ? "변경할 때만 새 값 붙여넣기" : esc(f.placeholder || "붙여넣기")) + '">' +
(f.secret ? "" : esc(f.value || "")) + "</textarea>"
: '<input class="erp-input" id="' + id + '" data-key="' + esc(f.key) + '" ' +
(f.secret ? 'type="password" autocomplete="new-password" placeholder="' + (f.has_value ? "변경할 때만 새 값 입력" : "입력") + '"'
: 'type="text" value="' + esc(f.value || "") + '" placeholder="' + esc(f.placeholder || "") + '"') + " />";
return '<div class="perf-form-row"><label for="' + id + '">' + esc(f.label) + (f.required ? " *" : "") + "</label>" + state +
'<input class="erp-input" id="' + id + '" data-key="' + esc(f.key) + '" ' +
(f.secret ? 'type="password" autocomplete="new-password" placeholder="' + (f.has_value ? "변경할 때만 새 값 입력" : "입력") + '"'
: 'type="text" value="' + esc(f.value || "") + '" placeholder="' + esc(f.placeholder || "") + '"') + " />" +
field +
(f.help ? '<div class="perf-form-help">' + esc(f.help) + "</div>" : "") +
(f.secret && f.has_value && !f.required ? '<label class="perf-check"><input type="checkbox" data-clear="' + esc(f.key) + '" /> 저장된 값 지우기</label>' : "") +
"</div>";
@@ -835,9 +864,9 @@
saveBtn.addEventListener("click", async function () {
saveBtn.disabled = true;
try {
await api("PUT", "/performance/api/marketplaces/" + code + "/credentials", { values: typed(), clear: cleared() });
await api("PUT", base + code + "/credentials", { values: typed(), clear: cleared() });
m.changed = true;
m.body.querySelectorAll("input[type=password]").forEach(function (i) { i.value = ""; });
m.body.querySelectorAll("input[type=password], textarea.perf-cred-multi").forEach(function (i) { i.value = ""; });
result.className = "perf-test-result";
result.textContent = "저장했습니다. 연결 확인 중…";
await test(false);
@@ -850,7 +879,7 @@
function typed() {
const out = {};
m.body.querySelectorAll("input[data-key]").forEach(function (i) { if (i.value.trim()) out[i.dataset.key] = i.value.trim(); });
m.body.querySelectorAll("input[data-key], textarea[data-key]").forEach(function (i) { if (i.value.trim()) out[i.dataset.key] = i.value.trim(); });
return out;
}
function cleared() {
@@ -862,7 +891,7 @@
result.className = "perf-test-result";
result.textContent = "연결 확인 중…";
try {
const res = await api("POST", "/performance/api/marketplaces/" + code + "/test", withTyped ? { values: typed() } : {});
const res = await api("POST", base + code + "/test", withTyped ? { values: typed() } : {});
result.className = "perf-test-result " + (res.ok ? "is-ok" : "is-bad");
result.textContent = (res.ok ? "● " : "● " + res.label + " — ") + res.message + (res.unsaved ? " (저장 안 한 값으로 시험)" : "");
if (!res.unsaved) m.changed = true;
@@ -874,12 +903,12 @@
testBtn.addEventListener("click", function () { test(true); });
}
async function runTest(code, name, btn) {
async function runTest(code, name, btn, base) {
btn.disabled = true;
const label = btn.textContent;
btn.textContent = "확인 중…";
try {
const res = await api("POST", "/performance/api/marketplaces/" + code + "/test", {});
const res = await api("POST", (base || "/performance/api/marketplaces/") + code + "/test", {});
await alertMsg(name + " — " + (res.ok ? "정상 연결\n" : res.label + "\n") + res.message, res.ok ? { tone: "ok" } : undefined);
location.reload();
} catch (err) {
+16
View File
@@ -211,6 +211,22 @@ docker exec postgres-db psql -U postgres -d performance_db -c "\d perf_ad_spend"
되돌리기(보고서 ROAS·상세만 사라짐): `docker exec postgres-db psql -U postgres -d performance_db -c "ALTER TABLE perf_ad_spend DROP COLUMN metrics, DROP COLUMN roas;"`
## 실적 광고 API 연동 마이그레이션 (performance_db 007)
007은 광고 API(구글 광고) 인증정보 표 `perf_ad_credentials`·연결 상태 표 `perf_ad_source_status` 두 개만 만든다(기존 표·데이터 그대로,
다시 실행 가능). 005·006 다음에 적용한다. 미적용이면 실적 설정 → 광고 API 연동 카드에 안내가 나오고 저장이 503, 광고비 탭은 그대로.
새 환경변수 없음 — 인증정보는 설정 화면에서 입력하고 기존 `APP_ENCRYPTION_KEY` 로 암호화된다.
```bash
cd /opt/www/main
docker exec postgres-db pg_dump -U postgres performance_db > ~/performance_db_before_007_$(date +%Y%m%d%H%M).sql
docker exec -i postgres-db psql -v ON_ERROR_STOP=1 -U postgres -d performance_db < scripts/sql/performance_db_007_ad_api.sql
docker exec postgres-db psql -U postgres -d performance_db -c "\dt perf_ad_*"
```
되돌리기(광고 API 인증정보·상태만 사라짐, 가져온 광고비는 perf_ad_spend 에 남음):
`docker exec postgres-db psql -U postgres -d performance_db -c "DROP TABLE perf_ad_source_status, perf_ad_credentials;"`
## 회의록 작업 등록 표 — 작업 칸 마이그레이션 (026)
026은 `goal_meeting_tasks.parent_task_id` 열만 추가한다(기존 값 그대로, 다시 실행 가능). 025 뒤에 적용한다. 미적용이면 작업 칸을 고를 때만 503 안내.
+25 -3
View File
@@ -365,14 +365,34 @@
머리글 이름 그대로 `metrics`(JSONB). 광고 계정 이름·ID 는 넣지 않음. 직접 입력으로 광고비를 고쳐도 ROAS·상세는 그대로.
- **네이버 머리글 클릭** → 지금 보는 기간의 일자별 보고서 표(`GET /api/ad-spend/naver/details?from=&to=`, `ad_spend.detail_table`):
열 = 파일 머리글 순서, 맨 아래 합계(숫자 항목은 합, 클릭률 = 클릭수 ÷ 노출수, 광고수익률 = 총비용 가중 평균). `DETAIL_CHANNELS`.
- 구글·메타 업로드 양식/API 는 아직 — 지금은 직접 입력.
- **구글 = 구글 광고 API**(2026-10-15, 마이그레이션 007) — 아래 "광고 API 연동". 메타는 아직 직접 입력.
- **광고 API 연동**(2026-10-15) — 구조: `ad_sources/`(채널 하나 = 파일 하나 + `registry.py` 한 줄, 쇼핑몰 어댑터와 같은 입력칸·연결 테스트 모양,
돌려주는 것은 날짜별 `AdDay`(금액·ROAS·항목)) + `ad_sync.py`(가져오기·저장·상태, 같은 채널 동시 실행 차단).
- **인증정보**: 실적 설정 → **광고 API 연동** 카드 [설정](관리자). 쇼핑몰과 같은 마스터 키·AES-256-GCM, 표만 따로
`perf_ad_credentials`(쇼핑몰 표는 `perf_marketplaces` 에 FK 로 묶여 있음), 암호문 AAD 이름 공간 `perf:ad:{채널}:{항목}`
(`credentials.aad_for(…, ns)` — 쇼핑몰 암호문과 바꿔 넣어도 복호화 안 됨). 비밀 원문은 화면으로 다시 보내지 않음.
[현재 키로 다시 암호화]·저장된 항목 수에 광고 인증정보도 포함. 연결 상태·마지막 가져오기는 `perf_ad_source_status`.
- **구글 광고**(`ad_sources/google_ads.py`): 입력 = 개발자 토큰(Explorer 이상, 비밀) · 고객 ID(광고 계정 10자리) ·
로그인 고객 ID(MCC 를 거칠 때만) · 서비스 계정 키 JSON(비밀, 여러 줄) · API 버전(기본 `v26`, 구글이 종료 알리면 설정에서 올림).
서비스 계정 이메일을 구글 광고 → 관리 → 액세스 및 보안 → 사용자에 추가해 두어야 한다(도메인 위임 불필요, 2024-11~).
토큰 = 서비스 계정 JWT(google-auth 서명) → `oauth2.googleapis.com/token`(httpx), 프로세스 안 캐시(만료 2분 전까지).
조회 = REST `googleAds:searchStream` GAQL `FROM customer` + `segments.date BETWEEN`(계정 시간대), 요청 1번.
금액 = `cost_micros ÷ 10⁶` 원 반올림(**부가세 별도** — 쿠팡은 부가세 포함이라 기준이 다름), ROAS = 전환 가치 ÷ 비용 × 100(소수 둘째),
항목 `metrics` = 비용·노출수·클릭수·클릭률(%)·전환수·전환 가치·ROAS(%) → 구글 머리글 클릭 = 일자별 표(`DETAIL_CHANNELS`).
통화가 KRW 가 아니면 저장 안 함. 구글 오류 코드는 고칠 곳 안내를 붙여 보여 줌(`_HINTS`: 권한 없음·토큰 미승인 등), 404 = API 버전 종료 안내.
- **저장**(`db.replace_ad_api_range`, 한 트랜잭션): API 가 준 날은 `source='api'` 로 덮어씀(직접 입력·업로드 값이 있던 날도),
기간 안에서 API 가 안 준 날(광고 없음)은 **예전 API 값만** 지움 — 직접 입력·업로드 값은 그대로. 화면 초록 숫자 = API 값.
- **언제**: 광고비 탭 **[구글 광고 불러오기]**(설정된 연동만 보임, 지금 보는 기간 → 오늘까지, 모듈 권한자 92일·관리자 366일,
`POST /api/ad-sources/{code}/sync`) + **매출 자동 업데이트 회차**(같은 최근 N일, 매출 다음에, 실패해도 매출과 무관 — `auto_sync.run_once`).
- API: `GET|PUT /api/ad-sources/{code}/credentials`·`POST /api/ad-sources/{code}/test`(관리자), `POST /api/ad-sources/{code}/sync`(모듈 권한).
- 007 미적용: 설정 카드에 안내, 저장은 503(안내 문구), 광고비 탭은 그대로(불러오기 버튼만 안 보임).
- **대시보드** `/performance/?period=day|week|month|year|custom&d=&from=&to=&m=<쇼핑몰>…`
기간 버튼(오늘/이번주/이번달/올해/직접선택) + 이전/다음, 쇼핑몰 필터, KPI 5개, 일자×쇼핑몰 표(주간합계·기간합계, 연간은 월 행),
[총매출|수수료|수수료 차감 매출] 전환(서버가 세 값을 다 그리고 CSS 로 전환, 선택은 localStorage), 일별 추이·쇼핑몰 비중(SVG),
월 누적(비중), 연간 누적(월별, 지나지 않은 달 빈칸). 금액 클릭 → 주문 상세(`GET /api/events`, 31일 이내).
- **설정** `/performance/settings` — 사용/매출 집계 토글, 수수료율(적용 시작일·이력), API 설정 창, 연결 상태
(정상/미설정/인증 실패/Token 만료/API 오류/연동 준비 중/사용 중지, 마지막 테스트·동기화, 최근 오류), 마스터 키 상태·재암호화,
테스트 데이터 생성/삭제(`is_sample`).
(정상/미설정/인증 실패/Token 만료/API 오류/연동 준비 중/사용 중지, 마지막 테스트·동기화, 최근 오류), **광고 API 연동**(구글 광고 —
설정·연결 테스트·연결 상태·마지막 가져오기, 관리자), 마스터 키 상태·재암호화, 테스트 데이터 생성/삭제(`is_sample`).
## 8. 테스트
@@ -382,3 +402,5 @@ python -m app.modules.performance.tests.test_performance # 또는 pytest
암호화(왕복·AAD·변조·키 교체), 가리기, 수수료 반올림·요율 이력, 기간/주 계산, 표·누적 합계, 인증정보 비노출·재암호화,
동기화 격리·가리기·중복 방지·매출 기준일, 모의 데이터를 DB/네트워크 없이 검증한다.
`tests/test_google_ads.py` — 구글 광고 입력 검사, 토큰 교환·머리글·GAQL 기간·버전, 금액 반올림·ROAS·항목 변환, 오류 안내(권한·버전·통화·키),
광고 인증정보 AAD 이름 공간, 가져오기 저장·상태·비밀값 가림·동시 실행 차단, 불러오기 API(오늘까지 자름·92일 권한·미설정)를 가짜 구글 서버로 검증.
+53
View File
@@ -0,0 +1,53 @@
-- =====================================================================
-- performance_db 마이그레이션 007 — 광고 API 연동(구글 광고) 인증정보·연결 상태
-- =====================================================================
-- 멱등(idempotent). 새 표 두 개만 만든다(기존 표·데이터 그대로). 005·006 다음에 적용.
-- docker exec -i postgres-db psql -v ON_ERROR_STOP=1 -U postgres -d performance_db \
-- < scripts/sql/performance_db_007_ad_api.sql
--
-- 왜(2026-10-15 사용자 요청): 광고비 탭에 구글 광고비·ROAS 를 Google Ads API 로 가져온다.
-- 인증정보(개발자 토큰·서비스 계정 키 등)는 실적 설정 화면에서 입력 → 쇼핑몰 인증정보와 같은 마스터 키
-- (APP_ENCRYPTION_KEY, AES-256-GCM)로 암호화해 저장한다. 쇼핑몰 인증정보 표(perf_credentials)는
-- 쇼핑몰 목록(perf_marketplaces)에 묶여 있어 광고 채널용 표를 따로 둔다.
-- 가져온 광고비·ROAS 는 기존 perf_ad_spend 에 source='api' 로 들어간다(005 에 이미 허용된 값).
-- 되돌리기: DROP TABLE perf_ad_source_status, perf_ad_credentials; (광고 API 인증정보·상태만 사라짐 — 실행 전 백업)
-- =====================================================================
BEGIN;
CREATE TABLE IF NOT EXISTS perf_ad_credentials (
channel_code TEXT NOT NULL,
credential_key TEXT NOT NULL,
encrypted_value TEXT NOT NULL,
key_version INTEGER NOT NULL,
updated_by TEXT NOT NULL DEFAULT '',
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
PRIMARY KEY (channel_code, credential_key)
);
COMMENT ON TABLE perf_ad_credentials IS '광고 API 인증정보(암호문만) — 채널(google 등) × 항목. 원문은 서버 안에서만 복호화';
DROP TRIGGER IF EXISTS trg_perf_ad_credentials_updated ON perf_ad_credentials;
CREATE TRIGGER trg_perf_ad_credentials_updated
BEFORE UPDATE ON perf_ad_credentials
FOR EACH ROW EXECUTE FUNCTION perf_set_updated_at();
CREATE TABLE IF NOT EXISTS perf_ad_source_status (
channel_code TEXT PRIMARY KEY,
status TEXT NOT NULL DEFAULT 'unknown',
last_test_at TIMESTAMPTZ,
last_test_ok BOOLEAN,
last_sync_at TIMESTAMPTZ,
last_success_sync_at TIMESTAMPTZ,
last_error TEXT NOT NULL DEFAULT '',
last_error_at TIMESTAMPTZ,
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
COMMENT ON TABLE perf_ad_source_status IS '광고 API 연결 상태 — 마지막 연결 테스트·가져오기·오류(비밀값 가린 문구)';
DROP TRIGGER IF EXISTS trg_perf_ad_source_status_updated ON perf_ad_source_status;
CREATE TRIGGER trg_perf_ad_source_status_updated
BEFORE UPDATE ON perf_ad_source_status
FOR EACH ROW EXECUTE FUNCTION perf_set_updated_at();
GRANT SELECT, INSERT, UPDATE, DELETE ON perf_ad_credentials, perf_ad_source_status TO performance_app;
COMMIT;
SELECT 'performance_db 007 ad api ready' AS status;
+8 -2
View File
@@ -59,12 +59,13 @@ class FakeStore:
def ad_amounts(self, start, end):
rows = {(date(2026, 10, 1), "coupang_rocket"): (220000, "upload"), (date(2026, 10, 2), "google"): (50000, "manual"),
(date(2026, 10, 5), "coupang_wing"): (29000, "manual"), (date(2026, 10, 3), "naver"): (300000, "upload")}
(date(2026, 10, 5), "coupang_wing"): (29000, "manual"), (date(2026, 10, 3), "naver"): (300000, "upload"),
(date(2026, 10, 4), "google"): (123457, "api")} # 구글 광고 API 값(초록 숫자)
rows = {k: v for k, v in rows.items() if start <= k[0] <= end}
return {k: v[0] for k, v in rows.items()}, {k: v[1] for k, v in rows.items()}
def ad_roas(self, start, end):
rows = {(date(2026, 10, 3), "naver"): Decimal("250.5")}
rows = {(date(2026, 10, 3), "naver"): Decimal("250.5"), (date(2026, 10, 4), "google"): Decimal("500")}
return {k: v for k, v in rows.items() if start <= k[0] <= end}
@@ -86,10 +87,15 @@ def main() -> None:
f.write(html)
actx = build_ad_dashboard(FakeStore(), kind="month", anchor=date(2026, 10, 7), today=date(2026, 10, 7),
sales_codes=["cafe24", "coupang"])
actx["ad_sync_sources"] = [{"code": "google", "name": "구글 광고"}] # [구글 광고 불러오기]
html = e.get_template("performance/ads.html").render(**base, active_tab="ads", **actx)
with open(os.path.join(OUT_DIR, "perf_ads.html"), "w", encoding="utf-8") as f:
f.write(html)
sctx = build_settings(FakeStore(), configured={}, key_info={}, key_versions_in_use={}, sample_count=0)
sctx["ad_api_ready"] = True # 광고 API 연동 표(마이그레이션 007)
sctx["ad_sources"] = [{"code": "google", "name": "구글 광고", "configured": True, "status": "ok", "status_label": "정상 연결",
"last_test_at": "2026-10-15T10:00:00+09:00", "last_error": "", "last_error_at": None,
"last_sync_at": "2026-10-15T10:30:02+09:00", "last_success_sync_at": "2026-10-15T10:30:02+09:00"}]
html = e.get_template("performance/settings.html").render(**base, active_tab="settings", **sctx)
with open(os.path.join(OUT_DIR, "perf_settings.html"), "w", encoding="utf-8") as f:
f.write(html)