feat(performance): 광고비 탭 [광고비 업데이트] 진행 창·자동 업데이트·업데이트 시각
- 채널별 [구글/메타 광고 불러오기] 버튼을 없애고 매출 탭과 같은 모양으로 마지막 업데이트 · 다음 업데이트까지(카운트다운) · [광고비 업데이트] - 진행 창 작업에 종류(sales/ads) 추가 — 광고 채널별 진행 막대(수집 → 저장 → 완료), 채널별 중지·전체 취소는 저장 직전까지, 진행 중이면 합류 - POST /api/ad-sync, GET /api/ad-sync/current - 자동 업데이트 회차에서 매출과 광고비를 동시에 각각 진행 창 작업으로 - 마지막 광고비 업데이트 = 광고 API 마지막 성공 가져오기 시각 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
"""광고 API 가져오기 — 인증정보(perf_ad_credentials) → 광고 연동(ad_sources) → perf_ad_spend(source='api').
|
||||
|
||||
- 광고비 탭 [구글 광고 불러오기](보고 있는 기간) · 매출 자동 업데이트 회차(최근 N일, auto_sync) · 실적 설정 연결 테스트가 쓴다.
|
||||
- 광고비 탭 [광고비 업데이트](보고 있는 기간, 진행 창 — jobs kind="ads", 2026-10-20) · 매출 자동 업데이트와 같은 회차
|
||||
(최근 N일, auto_sync) · 실적 설정 연결 테스트가 쓴다. 진행 창에서 채널별 [중지]·[업데이트 취소] = 저장 직전까지 받아들임.
|
||||
- 같은 광고 채널은 동시에 한 번만(프로세스 안 잠금) — 두 번째 요청은 바로 "진행 중" 오류.
|
||||
- 저장은 기간 단위 한 트랜잭션(db.replace_ad_api_range): API 가 준 날은 덮어쓰고, 안 준 날은 예전 API 값만 지운다.
|
||||
- 오류 문구는 저장된 비밀값을 가린 뒤 기록·반환한다(security.redact).
|
||||
@@ -14,7 +15,7 @@ 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 .adapters.base import STATUS_LABELS, AdapterContext, AdapterError, Cancelled
|
||||
from .credentials import CredentialService
|
||||
from .db import AdCredentialTable
|
||||
from .security.redact import redact_text
|
||||
@@ -84,8 +85,9 @@ class AdSyncService:
|
||||
return {"ok": ok, "status": status, "label": STATUS_LABELS.get(status, status), "message": msg,
|
||||
"unsaved": trial}
|
||||
|
||||
def sync(self, code: str, start: date, end: date, *, user: str = "") -> dict[str, Any]:
|
||||
"""기간 가져오기 → 저장. 결과 {ok, days, total, from, to} 또는 {ok: False, status, message}. 진행 중이면 AdSyncBusy."""
|
||||
def sync(self, code: str, start: date, end: date, *, user: str = "", progress: Any = None) -> dict[str, Any]:
|
||||
"""기간 가져오기 → 저장. 결과 {ok, days, total, from, to} 또는 {ok: False, status, message}. 진행 중이면 AdSyncBusy.
|
||||
progress(jobs.ShopProgress) 를 주면 수집(절반) → 저장 → 완료로 알리고, 저장 직전 중지·취소를 받아 Cancelled."""
|
||||
src = get_source(code)
|
||||
if src is None:
|
||||
raise KeyError(code)
|
||||
@@ -96,7 +98,14 @@ class AdSyncService:
|
||||
ctx = self._ctx(code, user=user)
|
||||
try:
|
||||
src.require_configured(ctx)
|
||||
if progress is not None:
|
||||
progress.plan(2, "단계")
|
||||
days = src.fetch_days(ctx, start, end)
|
||||
if progress is not None:
|
||||
progress.step(1, items=len(days))
|
||||
progress.begin_saving() # 여기까지 받은 [중지]·[취소]는 저장하지 않고 멈춤
|
||||
except Cancelled:
|
||||
raise # 오류가 아니다 — 상태 기록 없이 sync_all 이 "중지됨/취소됨"
|
||||
except AdapterError as exc:
|
||||
msg = self._message(exc, ctx)
|
||||
self._store.record_ad_status(code, status=exc.status, ok=False, error=msg, kind="sync")
|
||||
@@ -110,17 +119,65 @@ class AdSyncService:
|
||||
finally:
|
||||
lock.release()
|
||||
|
||||
def sync_all(self, start: date, end: date, *, user: str = "") -> list[dict[str, Any]]:
|
||||
"""설정이 끝난 광고 연동 전부(자동 업데이트 회차). 채널별로 실패를 격리한다."""
|
||||
def sync_all(self, start: date, end: date, *, user: str = "", job: Any = None) -> list[dict[str, Any]]:
|
||||
"""설정이 끝난 광고 연동 전부([광고비 업데이트]·자동 업데이트 회차). 채널별로 실패를 격리한다.
|
||||
job(jobs.SyncJob kind="ads") 을 주면 채널별 진행 막대로 알린다."""
|
||||
codes = [c for c, ok in self.configured().items() if ok]
|
||||
shops = job.set_targets([(c, get_source(c).name, True) for c in codes], start, end) if job is not None else {}
|
||||
out = []
|
||||
for code, ok in self.configured().items():
|
||||
if not ok:
|
||||
for code in codes:
|
||||
prog = shops.get(code)
|
||||
if prog is not None and prog.cancel_requested: # 차례가 오기 전에 중지·취소됨
|
||||
prog.cancelled()
|
||||
out.append({"ok": False, "code": code, "cancelled": True})
|
||||
continue
|
||||
if prog is not None:
|
||||
prog.start()
|
||||
try:
|
||||
out.append(self.sync(code, start, end, user=user))
|
||||
res = self.sync(code, start, end, user=user, progress=prog)
|
||||
except Cancelled:
|
||||
if prog is not None:
|
||||
prog.cancelled()
|
||||
out.append({"ok": False, "code": code, "cancelled": True})
|
||||
continue
|
||||
except AdSyncBusy as exc:
|
||||
out.append({"ok": False, "code": code, "skipped": True, "message": str(exc)})
|
||||
res = {"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__}"})
|
||||
res = {"ok": False, "code": code, "status": "api_error", "label": STATUS_LABELS["api_error"],
|
||||
"message": f"가져오기 중 오류: {type(exc).__name__}"}
|
||||
if prog is not None:
|
||||
if res.get("ok"):
|
||||
prog.finish(upserted=int(res.get("days") or 0),
|
||||
message=f"광고비 ₩{int(res.get('total') or 0):,}")
|
||||
elif res.get("skipped"):
|
||||
prog.skip(str(res.get("message") or ""))
|
||||
else:
|
||||
prog.fail(status=str(res.get("status") or "api_error"), label=str(res.get("label") or ""),
|
||||
message=str(res.get("message") or ""))
|
||||
out.append(res)
|
||||
return out
|
||||
|
||||
|
||||
def run_ad_job(store: Any, ring_loader: Callable[[], Any], job: Any, start: date, end: date, *,
|
||||
user: str = "") -> list[dict[str, Any]]:
|
||||
"""광고비 업데이트 작업 하나를 끝까지 돌리고 job.finish — [광고비 업데이트] 스레드·자동 업데이트 회차가 쓴다."""
|
||||
error, results = "", []
|
||||
try:
|
||||
results = AdSyncService(store, ad_credentials(store, ring_loader)).sync_all(start, end, user=user, job=job)
|
||||
except Exception as exc: # noqa: BLE001 — 스레드 밖으로 새지 않게, 화면에는 "오류"로
|
||||
logger.exception("ad sync job failed")
|
||||
error = f"광고비 업데이트 중 오류: {type(exc).__name__}"
|
||||
if job is not None:
|
||||
job.finish(error=error, last_update_at=last_ad_update_at(store))
|
||||
return results
|
||||
|
||||
|
||||
def last_ad_update_at(store: Any) -> str | None:
|
||||
"""광고비 마지막 업데이트 — 광고 API 채널의 마지막 성공 가져오기 시각 중 가장 최근(없으면 None)."""
|
||||
try:
|
||||
rows = store.ad_source_statuses()
|
||||
except Exception: # noqa: BLE001 — 007 미적용 등
|
||||
return None
|
||||
times = [str(r.get("last_success_sync_at")) for r in rows.values() if r.get("last_success_sync_at")]
|
||||
return max(times) if times else None
|
||||
|
||||
Reference in New Issue
Block a user