Files
dbx-main/app/modules/performance/auto_sync.py
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

151 lines
6.4 KiB
Python

"""매출 자동 업데이트 — 웹 프로세스 안 데몬 스레드(프로젝트 마감 알림과 같은 방식).
기본: 매일 09:00 ~ 19:00(KST) 정각·30분마다, 오늘 포함 최근 10일을 [매출 업데이트] 와 같은 방식으로 다시 가져온다.
- 매출이 끝나면 설정된 광고 API(구글 광고)도 같은 기간으로 가져온다(ad_sync, 실패해도 매출과 무관).
- 진행 창 작업(jobs)으로 돌린다 — 그동안 누가 [매출 업데이트] 를 누르면 새로 시작하지 않고 이 진행 상황을 본다.
- 그 시각에 이미 다른 업데이트가 돌고 있으면 그 회차는 건너뛴다(같은 쇼핑몰 동시 실행은 어차피 막혀 있음).
- 한 회차가 30분을 넘기면 지나간 회차는 건너뛰고 다음 정각/30분을 기다린다(밀린 회차를 몰아서 돌리지 않음).
- 서버를 켠 시각의 회차는 돌리지 않고 다음 회차부터.
환경변수(.env)
PERFORMANCE_AUTO_SYNC=false 끄기(기본 켜짐)
PERFORMANCE_AUTO_SYNC_DAYS=10 가져올 기간(오늘 포함 최근 N일, 1~90)
PERFORMANCE_AUTO_SYNC_HOURS=9-19 돌리는 시간대(시작시-마지막시, 마지막 시는 정각 회차까지)
"""
from __future__ import annotations
import logging
import os
import re
import threading
import time
from datetime import datetime, timedelta
from typing import Any
from app.timezone import now_kst
logger = logging.getLogger("performance.auto_sync")
AUTO_USER = "자동 업데이트"
DEFAULT_DAYS = 10
DEFAULT_HOURS = (9, 19)
SLOT_MINUTES = 30
_started = False
_start_lock = threading.Lock()
def _env(name: str) -> str:
return (os.getenv(name, "") or "").strip()
def enabled() -> bool:
return _env("PERFORMANCE_AUTO_SYNC").lower() not in ("0", "false", "no", "off")
def sync_days() -> int:
try:
return max(1, min(90, int(_env("PERFORMANCE_AUTO_SYNC_DAYS") or DEFAULT_DAYS)))
except ValueError:
return DEFAULT_DAYS
def hour_window() -> tuple[int, int]:
m = re.fullmatch(r"(\d{1,2})\s*-\s*(\d{1,2})", _env("PERFORMANCE_AUTO_SYNC_HOURS"))
if not m:
return DEFAULT_HOURS
first, last = int(m.group(1)), int(m.group(2))
if not (0 <= first <= last <= 23):
return DEFAULT_HOURS
return first, last
def is_slot(t: datetime, hours: tuple[int, int]) -> bool:
"""t(분 단위로 자른 시각)가 회차인가 — 정각·30분, first시 정각 ~ last시 정각."""
first, last = hours
if t.minute % SLOT_MINUTES:
return False
return first <= t.hour < last or (t.hour == last and t.minute == 0)
def next_slot(after: datetime, hours: tuple[int, int]) -> datetime:
"""after 보다 뒤의 첫 회차 시각."""
t = after.replace(second=0, microsecond=0)
t += timedelta(minutes=SLOT_MINUTES - t.minute % SLOT_MINUTES)
for _ in range(48 * 2 + 2): # 하루치 회차를 넘기기 전에 반드시 찾는다
if is_slot(t, hours):
return t
t += timedelta(minutes=SLOT_MINUTES)
raise ValueError("회차를 찾을 수 없습니다")
def run_once(store: Any, app_state: Any, *, today: Any, days: int) -> dict[str, Any]:
"""한 회차 — 진행 창 작업으로 오늘 포함 최근 days 일 업데이트. 이미 돌고 있으면 건너뜀."""
from . import common, jobs # noqa: WPS433
from .credentials import CredentialService # noqa: WPS433
from .sync import SyncService # noqa: WPS433
if jobs.running_job() is not None:
return {"skipped": True, "reason": "다른 업데이트 진행 중"}
start, end = today - timedelta(days=days - 1), today
job = jobs.create_job(user=AUTO_USER, start=start, end=end)
sync = SyncService(store, CredentialService(store, common.key_ring), app_state=app_state)
error = ""
results: list[dict[str, Any]] = []
try:
results = sync.sync_all(start=start, end=end, trigger="schedule", user=AUTO_USER, job=job)
except Exception as exc: # noqa: BLE001 — 스레드가 죽지 않게
logger.exception("auto sync failed")
error = f"업데이트 중 오류: {type(exc).__name__}"
last = None
try:
last = store.last_update_at()
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,
"ads": [{"code": a.get("code"), "ok": bool(a.get("ok"))} for a in ads]}
def start_auto_sync_thread(app_state: Any) -> bool:
"""웹 프로세스 시작 시 1번. 저장소가 없거나 꺼져 있거나 이미 돌고 있으면 False."""
global _started # noqa: PLW0603
store = getattr(app_state, "performance_store", None)
if store is None or not enabled():
return False
with _start_lock:
if _started:
return False
_started = True
hours, days = hour_window(), sync_days()
def _loop() -> None:
due = next_slot(now_kst(), hours)
logger.info("매출 자동 업데이트 시작 — %02d~%02d시 30분마다, 최근 %d일, 다음 %s", hours[0], hours[1], days,
due.strftime("%m-%d %H:%M"))
while True:
wait = (due - now_kst()).total_seconds()
if wait > 0:
time.sleep(min(wait, 60)) # 시계 변경·절전에도 1분 안에 다시 확인
continue
try:
res = run_once(store, app_state, today=due.date(), days=days)
logger.info("매출 자동 업데이트 %s: %s", due.strftime("%H:%M"), res)
except Exception: # noqa: BLE001
logger.exception("매출 자동 업데이트 실패 — 다음 회차에 다시")
due = next_slot(max(now_kst(), due), hours)
threading.Thread(target=_loop, name="performance-auto-sync", daemon=True).start()
return True