Merge branch 'feat/perf-ad-update-button'
This commit is contained in:
@@ -62,6 +62,11 @@
|
||||
총비용·광고수익률은 **머리글 이름으로 찾음**(열 구성 바뀐 보고서 — 고정 12열이 비어 ROAS 누락됐던 문제, 2026-10-20). 광고수익률 칸이 없거나 비면 구매완료 전환매출액 ÷ 총비용. 저장된 `roas` 가 빈 예전 행은 `db.ad_roas` 가 metrics 에서 다시 구함(`ad_spend.roas_from_metrics`).
|
||||
- 일자별 보고서 창: ROAS 열은 **광고비 열 바로 오른쪽**, 네이버 "구매완료 광고수익률(%)" 머리글은 "ROAS(%)"로 표기(`ad_spend._roas_next_to_spend` → `labels`, 저장 키는 파일 머리글 그대로 — 예전 업로드도 그대로 적용).
|
||||
- 매출 대비 광고비 KPI.
|
||||
- 광고 API 연동(마이그레이션 007 `perf_ad_credentials`·`perf_ad_source_status`) — 실적 설정 **광고 API 연동** 카드, 쇼핑몰과 같은 마스터 키로 암호화(AAD `perf:ad:…`), `ad_sources/`(채널 하나 = 파일 하나) + `ad_sync.py`, 매출 자동 업데이트 회차에 함께. 결과는 `perf_ad_spend` `source='api'`(초록 숫자, API 가 안 준 날은 예전 API 값만 지움).
|
||||
- **구글 = Google Ads API**(2026-10-15) — 고객 ID·(MCC)·서비스 계정 JSON·API 버전(기본 v26). 개발자 토큰은 2026-09-09 구글 폐지 — 접근 등급은 서비스 계정의 Cloud 프로젝트, 머리글 안 보냄. 광고비 탭 [구글 광고 불러오기](보는 기간). 광고비 = 비용 × 1.1(부가세 포함)·ROAS(전환 가치 ÷ 비용, 구글 값 그대로)·항목.
|
||||
- **메타 = 메타 마케팅 API**(2026-10-16, `ad_sources/meta_ads.py`, 새 마이그레이션 없음) — 광고 계정 ID(여러 개, 날짜별 합산)·액세스 토큰(ads_read, 시스템 사용자 토큰 권장)·앱 시크릿(선택)·API 버전(기본 v26.0). 광고비 = 지출 금액 그대로(메타는 이미 부가세 포함 — × 1.1 은 구글만)·ROAS = 구매 전환값 ÷ 지출 금액(광고 관리자 구매 ROAS). USD 등 외화 계정은 그날 환율로 원화 환산(`fx.py`, Frankfurter 중앙은행 고시 환율 종합, 키 없음). 상세보기 [합계 | 계정별] 탭, [메타 광고 불러오기]·자동 업데이트 회차.
|
||||
- 광고 API 연동(마이그레이션 007 `perf_ad_credentials`·`perf_ad_source_status`) — 실적 설정 **광고 API 연동** 카드, 쇼핑몰과 같은 마스터 키로 암호화(AAD `perf:ad:…`), `ad_sources/`(채널 하나 = 파일 하나) + `ad_sync.py`, 매출 자동 업데이트 회차에 함께.
|
||||
- **[광고비 업데이트]**(2026-10-20, 예전 채널별 [구글/메타 광고 불러오기] 버튼 삭제) — 광고비 탭 오른쪽 위, 매출 탭과 같은 모양:
|
||||
마지막 업데이트(광고 API 마지막 성공 가져오기 `ad_sync.last_ad_update_at`) · 다음 업데이트까지(매출과 같은 회차 카운트다운) · 버튼.
|
||||
설정된 광고 API 전부를 진행 창 작업으로(`POST /api/ad-sync` → `jobs` kind="ads", 채널별 막대 수집 50% → 저장 → 완료, 채널별 [중지]·[업데이트 취소]는
|
||||
저장 직전까지, 진행·취소·중지 API 는 매출과 같은 `/api/sync/jobs/…`). 진행 중이면 새로 시작 안 하고 합류(`GET /api/ad-sync/current`, 매출 업데이트와 별개).
|
||||
자동 업데이트 회차(`auto_sync.run_once`)는 매출과 광고비를 **동시에** 각각 진행 창 작업으로, 이미 돌고 있는 종류만 그 회차 건너뜀. 결과는 `perf_ad_spend` `source='api'`(초록 숫자, API 가 안 준 날은 예전 API 값만 지움).
|
||||
- **구글 = Google Ads API**(2026-10-15) — 고객 ID·(MCC)·서비스 계정 JSON·API 버전(기본 v26). 개발자 토큰은 2026-09-09 구글 폐지 — 접근 등급은 서비스 계정의 Cloud 프로젝트, 머리글 안 보냄. [광고비 업데이트]·자동 업데이트. 광고비 = 비용 × 1.1(부가세 포함)·ROAS(전환 가치 ÷ 비용, 구글 값 그대로)·항목.
|
||||
- **메타 = 메타 마케팅 API**(2026-10-16, `ad_sources/meta_ads.py`, 새 마이그레이션 없음) — 광고 계정 ID(여러 개, 날짜별 합산)·액세스 토큰(ads_read, 시스템 사용자 토큰 권장)·앱 시크릿(선택)·API 버전(기본 v26.0). 광고비 = 지출 금액 그대로(메타는 이미 부가세 포함 — × 1.1 은 구글만)·ROAS = 구매 전환값 ÷ 지출 금액(광고 관리자 구매 ROAS). USD 등 외화 계정은 그날 환율로 원화 환산(`fx.py`, Frankfurter 중앙은행 고시 환율 종합, 키 없음). 상세보기 [합계 | 계정별] 탭, [광고비 업데이트]·자동 업데이트 회차.
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
"""매출 자동 업데이트 — 웹 프로세스 안 데몬 스레드(프로젝트 마감 알림과 같은 방식).
|
||||
|
||||
기본: 매일 09:00 ~ 19:00(KST) 정각·30분마다, 오늘 포함 최근 10일을 [매출 업데이트] 와 같은 방식으로 다시 가져온다.
|
||||
- 매출이 끝나면 설정된 광고 API(구글 광고)도 같은 기간으로 가져온다(ad_sync, 실패해도 매출과 무관).
|
||||
- 같은 회차에 광고비(설정된 광고 API — 구글·메타)도 같은 기간으로 **동시에** 가져온다(2026-10-20, 광고비 진행 창 작업
|
||||
jobs kind="ads", 실패해도 매출과 무관). 광고비 탭 [광고비 업데이트]를 누르면 새로 시작하지 않고 이 진행 상황을 본다.
|
||||
- 진행 창 작업(jobs)으로 돌린다 — 그동안 누가 [매출 업데이트] 를 누르면 새로 시작하지 않고 이 진행 상황을 본다.
|
||||
- 그 시각에 이미 다른 업데이트가 돌고 있으면 그 회차는 건너뛴다(같은 쇼핑몰 동시 실행은 어차피 막혀 있음).
|
||||
- 그 시각에 이미 같은 종류 업데이트가 돌고 있으면 그 종류는 그 회차를 건너뛴다(같은 쇼핑몰 동시 실행은 어차피 막혀 있음).
|
||||
- 한 회차가 30분을 넘기면 지나간 회차는 건너뛰고 다음 정각/30분을 기다린다(밀린 회차를 몰아서 돌리지 않음).
|
||||
- 서버를 켠 시각의 회차는 돌리지 않고 다음 회차부터.
|
||||
|
||||
@@ -81,39 +82,50 @@ def next_slot(after: datetime, hours: tuple[int, int]) -> datetime:
|
||||
|
||||
|
||||
def run_once(store: Any, app_state: Any, *, today: Any, days: int) -> dict[str, Any]:
|
||||
"""한 회차 — 진행 창 작업으로 오늘 포함 최근 days 일 업데이트. 이미 돌고 있으면 건너뜀."""
|
||||
"""한 회차 — 오늘 포함 최근 days 일. 매출(진행 창 작업)과 광고비(광고 진행 창 작업)를 동시에.
|
||||
각각 이미 돌고 있으면 그 종류만 건너뜀."""
|
||||
from . import common, jobs # noqa: WPS433
|
||||
from .ad_sync import run_ad_job # 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)
|
||||
ads: list[dict[str, Any]] = []
|
||||
ad_thread = None
|
||||
ads_skipped = jobs.running_job("ads") is not None
|
||||
if not ads_skipped:
|
||||
ad_job = jobs.create_job(user=AUTO_USER, start=start, end=end, kind="ads")
|
||||
|
||||
def _ads() -> None:
|
||||
ads.extend(run_ad_job(store, common.key_ring, ad_job, start, end, user=AUTO_USER))
|
||||
|
||||
ad_thread = threading.Thread(target=_ads, name=f"perf-auto-ads-{ad_job.id}", daemon=True)
|
||||
ad_thread.start()
|
||||
|
||||
sales_skipped = jobs.running_job("sales") is not None
|
||||
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")
|
||||
if not sales_skipped:
|
||||
job = jobs.create_job(user=AUTO_USER, start=start, end=end)
|
||||
sync = SyncService(store, CredentialService(store, common.key_ring), app_state=app_state)
|
||||
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)
|
||||
if ad_thread is not None:
|
||||
ad_thread.join()
|
||||
if sales_skipped and ads_skipped:
|
||||
return {"skipped": True, "reason": "다른 업데이트 진행 중"}
|
||||
ok = sum(1 for r in results if r.get("ok"))
|
||||
return {"skipped": False, "from": start.isoformat(), "to": end.isoformat(), "ok": ok,
|
||||
return {"skipped": False, "sales_skipped": sales_skipped, "ads_skipped": ads_skipped,
|
||||
"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]}
|
||||
|
||||
|
||||
@@ -153,9 +153,15 @@ class ShopProgress(Progress):
|
||||
}
|
||||
|
||||
|
||||
# 작업 종류 — 매출 업데이트(sales, 쇼핑몰별) · 광고비 업데이트(ads, 광고 채널별, 2026-10-20). 진행 창·취소·중지 API 는 같고
|
||||
# "지금 돌고 있는 작업"은 종류별로 따로 본다(매출 업데이트 중에도 광고비 업데이트는 따로 시작·합류).
|
||||
KINDS = ("sales", "ads")
|
||||
|
||||
|
||||
class SyncJob:
|
||||
def __init__(self, *, user: str, start: date | None, end: date | None) -> None:
|
||||
def __init__(self, *, user: str, start: date | None, end: date | None, kind: str = "sales") -> None:
|
||||
self.id = uuid.uuid4().hex[:12]
|
||||
self.kind = kind if kind in KINDS else "sales"
|
||||
self.user, self.start, self.end = user, start, end
|
||||
self.created_at = time.time()
|
||||
self.finished_at = 0.0
|
||||
@@ -199,7 +205,7 @@ class SyncJob:
|
||||
shops = [s.snapshot() for s in self.shops]
|
||||
active = [s for s in shops if s["active"]]
|
||||
return {
|
||||
"id": self.id, "finished": self.finished, "error": self.error, "user": self.user,
|
||||
"id": self.id, "kind": self.kind, "finished": self.finished, "error": self.error, "user": self.user,
|
||||
"cancel_requested": self.cancel_requested,
|
||||
"from": self.start.isoformat() if self.start else None, "to": self.end.isoformat() if self.end else None,
|
||||
"elapsed": round((self.finished_at or time.time()) - self.created_at, 1),
|
||||
@@ -214,8 +220,8 @@ class SyncJob:
|
||||
}
|
||||
|
||||
|
||||
def create_job(*, user: str, start: date | None, end: date | None) -> SyncJob:
|
||||
job = SyncJob(user=user, start=start, end=end)
|
||||
def create_job(*, user: str, start: date | None, end: date | None, kind: str = "sales") -> SyncJob:
|
||||
job = SyncJob(user=user, start=start, end=end, kind=kind)
|
||||
with _LOCK:
|
||||
_JOBS[job.id] = job
|
||||
if len(_JOBS) > MAX_JOBS: # 오래된 끝난 작업부터 정리
|
||||
@@ -232,8 +238,8 @@ def get_job(job_id: str) -> SyncJob | None:
|
||||
return _JOBS.get(job_id)
|
||||
|
||||
|
||||
def running_job() -> SyncJob | None:
|
||||
"""지금 돌고 있는 작업(가장 최근). 없으면 None — 다른 사람이 누른 업데이트도 같이 보여 주려고."""
|
||||
def running_job(kind: str = "sales") -> SyncJob | None:
|
||||
"""지금 돌고 있는 그 종류의 작업(가장 최근). 없으면 None — 다른 사람이 누른 업데이트도 같이 보여 주려고."""
|
||||
with _LOCK:
|
||||
live = [j for j in _JOBS.values() if not j.finished]
|
||||
live = [j for j in _JOBS.values() if not j.finished and j.kind == kind]
|
||||
return max(live, key=lambda j: j.created_at) if live else None
|
||||
|
||||
@@ -18,7 +18,10 @@ JSON API — 모듈 권한
|
||||
POST /performance/api/ad-spend/upload?channel= 광고비 파일 업로드(쿠팡 윙·로켓 광고 보고서 1열 날짜·19열 청구금액,
|
||||
네이버 광고 보고서 3열 기간·4열 총비용·12열 ROAS + 나머지 항목)
|
||||
GET /performance/api/ad-spend/{channel}/details?from=&to= 일자별 보고서 항목(네이버·구글·메타 머리글 클릭)
|
||||
POST /performance/api/ad-sources/{code}/sync 광고 API(구글·메타 광고) 가져오기 — 보는 기간(오늘까지), 92일 넘으면 관리자
|
||||
POST /performance/api/ad-sync [광고비 업데이트] — 설정된 광고 API 전부, 보는 기간(오늘까지), 진행 창 작업
|
||||
(jobs kind="ads", 진행·취소·중지는 /api/sync/jobs/… 그대로), 92일 넘으면 관리자
|
||||
GET /performance/api/ad-sync/current 진행 중인 광고비 업데이트(수동·자동) — 버튼이 진행 창을 다시 연다
|
||||
POST /performance/api/ad-sources/{code}/sync 광고 API 채널 하나 가져오기(예전 [구글/메타 광고 불러오기], 화면 버튼은 2026-10-20 삭제)
|
||||
JSON API — 관리자
|
||||
GET|PUT /performance/api/ad-sources/{code}/credentials 광고 API 인증정보(마이그레이션 007, 암호화 저장·비밀 원문 없음)
|
||||
POST /performance/api/ad-sources/{code}/test 광고 API 연결 테스트(저장값 또는 새 입력값)
|
||||
@@ -188,11 +191,21 @@ 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)],
|
||||
)
|
||||
# [구글 광고 불러오기] — 관리자가 실적 설정에서 인증정보를 넣은 광고 연동만
|
||||
# [광고비 업데이트](2026-10-20) — 관리자가 실적 설정에서 인증정보를 넣은 광고 연동 전부를 진행 창으로.
|
||||
# 마지막 업데이트 = 광고 API 마지막 성공 가져오기, 다음 업데이트 = 매출 자동 업데이트와 같은 회차.
|
||||
from . import jobs # noqa: WPS433
|
||||
from .ad_sources.registry import get_source # noqa: WPS433
|
||||
from .ad_sync import last_ad_update_at # 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]
|
||||
try:
|
||||
configured = ad_sync.configured()
|
||||
except Exception: # noqa: BLE001 — 007 미적용 등: 버튼만 숨김
|
||||
configured = {}
|
||||
ctx["ad_sync_sources"] = [{"code": c, "name": get_source(c).name} for c, ok in configured.items() if ok]
|
||||
ctx["ad_last_update_at"] = last_ad_update_at(store)
|
||||
ctx["ad_running"] = jobs.running_job("ads") is not None
|
||||
ctx["auto_sync"] = _auto_sync_ctx()
|
||||
return render_template(request, "performance/ads.html",
|
||||
{**common.base_ctx(user, active_tab="ads", page_title="광고비"), **ctx})
|
||||
|
||||
@@ -641,18 +654,12 @@ def api_ad_source_test(request: Request, code: str, payload: dict[str, Any] = Bo
|
||||
return JSONResponse(ad_sync.test_connection(code, values=values or None, user=user["email"], cleared=cleared or None))
|
||||
|
||||
|
||||
@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일) 관리자만."""
|
||||
def _ad_sync_period(payload: dict[str, Any], user: dict[str, Any]) -> tuple[date, date]:
|
||||
"""광고 가져오기 기간 — 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))
|
||||
@@ -666,6 +673,51 @@ def api_ad_source_sync(request: Request, code: str, payload: dict[str, Any] = Bo
|
||||
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}일보다 긴 기간은 관리자만 가져올 수 있습니다.")
|
||||
return start, end
|
||||
|
||||
|
||||
@router.post("/api/ad-sync")
|
||||
def api_ad_sync(request: Request, payload: dict[str, Any] = Body(default={})) -> JSONResponse:
|
||||
"""[광고비 업데이트](2026-10-20) — 설정된 광고 API 전부를 백그라운드 진행 창 작업으로. 이미 돌고 있는 광고비 업데이트
|
||||
(다른 사람·자동 업데이트)가 있으면 새로 시작하지 않고 그 작업을 돌려준다(joined)."""
|
||||
import threading # noqa: WPS433
|
||||
|
||||
from . import jobs # noqa: WPS433
|
||||
from .ad_sync import run_ad_job # noqa: WPS433
|
||||
|
||||
store, user = common.require_store(request)
|
||||
live = jobs.running_job("ads")
|
||||
if live is not None:
|
||||
return JSONResponse({"job": live.snapshot(), "joined": True})
|
||||
start, end = _ad_sync_period(payload, user)
|
||||
_, ad_sync = _ad_services(store)
|
||||
if not any(ad_sync.configured().values()):
|
||||
raise HTTPException(status_code=400, detail="설정된 광고 API 가 없습니다. 관리자가 실적 설정 → 광고 API 연동에서 입력해야 합니다.")
|
||||
job = jobs.create_job(user=user["email"], start=start, end=end, kind="ads")
|
||||
threading.Thread(target=run_ad_job, args=(store, common.key_ring, job, start, end),
|
||||
kwargs={"user": user["email"]}, name=f"perf-ad-sync-{job.id}", daemon=True).start()
|
||||
return JSONResponse({"job": job.snapshot(), "joined": False})
|
||||
|
||||
|
||||
@router.get("/api/ad-sync/current")
|
||||
def api_ad_sync_current(request: Request) -> JSONResponse:
|
||||
common.require_store(request)
|
||||
from . import jobs # noqa: WPS433
|
||||
|
||||
job = jobs.running_job("ads")
|
||||
return JSONResponse({"job": job.snapshot() if job else None})
|
||||
|
||||
|
||||
@router.post("/api/ad-sources/{code}/sync")
|
||||
def api_ad_source_sync(request: Request, code: str, payload: dict[str, Any] = Body(default={})) -> JSONResponse:
|
||||
"""광고 API 채널 하나 가져오기(진행 창 없이) — 기간(from·to, 없으면 최근 N일). 오늘 뒤는 잘라낸다.
|
||||
모듈 권한자는 92일까지, 그보다 길면(최대 366일) 관리자만. 화면은 [광고비 업데이트](/api/ad-sync)를 쓴다."""
|
||||
from .ad_spend import AdMigrationNeeded # noqa: WPS433
|
||||
from .ad_sync import AdSyncBusy # noqa: WPS433
|
||||
|
||||
store, user = common.require_store(request)
|
||||
src = _ad_source_or_404(code)
|
||||
start, end = _ad_sync_period(payload, user)
|
||||
_, ad_sync = _ad_services(store)
|
||||
if not ad_sync.configured().get(code):
|
||||
raise HTTPException(status_code=400, detail=f"{src.name} API 가 설정되지 않았습니다. 관리자가 실적 설정 → 광고 API 연동에서 입력해야 합니다.")
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261019f" />{% endblock %}
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261020a" />{% endblock %}
|
||||
|
||||
{#- ROAS 덧붙임 — "광고비(ROAS%)". 광고비가 없으면 아무것도 안 붙는다. -#}
|
||||
{%- macro roas(p) -%}{%- if p is not none -%}<span class="perf-roas">({{ "{:,}".format(p) }}%)</span>{%- endif -%}{%- endmacro -%}
|
||||
@@ -37,7 +37,24 @@
|
||||
<input class="erp-input perf-date" type="date" name="to" value="{{ period.end.isoformat() }}" required />
|
||||
<button class="erp-btn erp-btn-outline" type="submit">조회</button>
|
||||
</form>
|
||||
|
||||
{# 광고비 업데이트(2026-10-20) — 매출 탭과 같은 모양: 마지막 업데이트(광고 API 마지막 성공) · 다음 자동 업데이트(매출과 같은 회차)
|
||||
· [광고비 업데이트](설정된 광고 API 전부, 진행 창). 업데이트 중에도 누르면 진행 창을 다시 연다. #}
|
||||
{% if ad_sync_sources %}
|
||||
<div class="perf-update">
|
||||
<span class="perf-muted" id="perf-last-update" title="광고 API({{ ad_sync_sources | map(attribute='name') | join('·') }}) 마지막 업데이트">마지막 업데이트
|
||||
<b>{{ (ad_last_update_at or '')[:16] | replace('T', ' ') or '—' }}</b></span>
|
||||
{% if auto_sync %}
|
||||
<span class="perf-muted perf-next-update" id="perf-next-update" title="자동 업데이트: 매일 {{ auto_sync.hours[0] }}~{{ auto_sync.hours[1] }}시 {{ auto_sync.slot }}분마다(매출과 같은 시각)">다음 업데이트까지 <b>—</b></span>
|
||||
{% endif %}
|
||||
<button type="button" class="erp-btn erp-btn-primary{% if ad_running %} is-running{% endif %}" id="perf-ad-sync-btn"
|
||||
title="{% if ad_running %}업데이트 진행 상황 보기{% else %}지금 보고 있는 기간({{ period.label }}, 오늘까지)의 광고비·ROAS 를 광고 API({{ ad_sync_sources | map(attribute='name') | join('·') }})에서 다시 가져옵니다{% endif %}">
|
||||
{% if ad_running %}업데이트 중 · 진행 보기{% else %}광고비 업데이트{% endif %}
|
||||
</button>
|
||||
</div>
|
||||
{% endif %}
|
||||
</div>
|
||||
<div class="perf-notice" id="perf-sync-result" hidden></div>
|
||||
|
||||
{% if migration_needed %}
|
||||
<div class="perf-notice is-warn">광고비 저장 표가 아직 없습니다. 관리자가 performance_db 마이그레이션 005
|
||||
@@ -73,11 +90,6 @@
|
||||
<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>
|
||||
@@ -203,7 +215,7 @@
|
||||
광고비 기준: 쿠팡(윙)·쿠팡(로켓)은 광고 보고서의 청구금액(+부가가치세), 구글은 구글 광고 비용 + 부가세 10%(부가세 포함), 메타는 지출 금액 그대로(이미 부가세 포함).
|
||||
ROAS = 그 쇼핑몰 매출 ÷ 광고비 × 100(네이버·구글·메타는 광고 쪽 값).
|
||||
매출 대비 광고비 = 같은 기간 광고비 ÷ 매출 실적 총매출.
|
||||
메타는 지금은 직접 입력합니다.
|
||||
구글·메타는 [광고비 업데이트]·자동 업데이트(매출과 같은 시각)로 광고 API 에서 가져옵니다.
|
||||
</p>
|
||||
</section>
|
||||
|
||||
@@ -220,8 +232,9 @@
|
||||
"period_end": period.end.isoformat(),
|
||||
"period_label": period.label,
|
||||
"empty_text": "기간 내 광고비가 없습니다.",
|
||||
"upload_channels": upload_channels
|
||||
"upload_channels": upload_channels,
|
||||
"auto_sync": auto_sync
|
||||
} | tojson }}</script>
|
||||
{% endblock %}
|
||||
|
||||
{% block scripts %}<script src="/static/performance.js?v=20261020a" defer></script>{% endblock %}
|
||||
{% block scripts %}<script src="/static/performance.js?v=20261020b" defer></script>{% endblock %}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261019f" />{% endblock %}
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261020a" />{% endblock %}
|
||||
|
||||
{%- macro won(v) -%}
|
||||
{%- if v is none -%}<span class="perf-na"></span>
|
||||
@@ -274,4 +274,4 @@
|
||||
} | tojson }}</script>
|
||||
{% endblock %}
|
||||
|
||||
{% block scripts %}<script src="/static/performance.js?v=20261020a" defer></script>{% endblock %}
|
||||
{% block scripts %}<script src="/static/performance.js?v=20261020b" defer></script>{% endblock %}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261019f" />{% endblock %}
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261020a" />{% endblock %}
|
||||
|
||||
{%- macro when(v) -%}{{ (v or '')[:16] | replace('T', ' ') or '—' }}{%- endmacro -%}
|
||||
|
||||
@@ -219,4 +219,4 @@
|
||||
</section>
|
||||
{% endblock %}
|
||||
|
||||
{% block scripts %}<script src="/static/performance.js?v=20261020a" defer></script>{% endblock %}
|
||||
{% block scripts %}<script src="/static/performance.js?v=20261020b" defer></script>{% endblock %}
|
||||
|
||||
@@ -57,16 +57,49 @@ def test_run_once_uses_job_and_skips_when_busy(monkeypatch):
|
||||
return "2026-10-13T09:00:05+09:00"
|
||||
|
||||
monkeypatch.setattr(SyncService, "sync_all", fake_sync_all)
|
||||
monkeypatch.setattr(jobs, "running_job", lambda: None)
|
||||
monkeypatch.setattr(jobs, "running_job", lambda kind="sales": 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)]
|
||||
# 광고 API 저장소 메서드가 없는 가짜 저장소 — 광고 가져오기는 조용히 빠지고 매출 결과는 그대로
|
||||
assert res == {"skipped": False, "from": "2026-10-04", "to": "2026-10-13", "ok": 1, "failed": ["toss"], "error": "",
|
||||
"ads": []}
|
||||
assert res == {"skipped": False, "sales_skipped": False, "ads_skipped": False, "from": "2026-10-04",
|
||||
"to": "2026-10-13", "ok": 1, "failed": ["toss"], "error": "", "ads": []}
|
||||
|
||||
monkeypatch.setattr(jobs, "running_job", lambda: object())
|
||||
monkeypatch.setattr(jobs, "running_job", lambda kind="sales": object())
|
||||
assert au.run_once(Store(), None, today=date(2026, 10, 13), days=10)["skipped"]
|
||||
assert len(calls) == 1
|
||||
# 광고비 업데이트만 돌고 있으면 매출은 그 회차에 그대로 돈다(종류별로 따로)
|
||||
monkeypatch.setattr(jobs, "running_job", lambda kind="sales": object() if kind == "ads" else None)
|
||||
res = au.run_once(Store(), None, today=date(2026, 10, 13), days=10)
|
||||
assert res["ads_skipped"] and not res["sales_skipped"] and len(calls) == 2
|
||||
|
||||
|
||||
def test_run_once_runs_ads_as_progress_job(monkeypatch):
|
||||
"""자동 회차의 광고비 = 광고비 진행 창 작업(kind=ads) — 채널별 진행·마지막 업데이트 시각."""
|
||||
from app.modules.performance import ad_sync, jobs
|
||||
from app.modules.performance.sync import SyncService
|
||||
|
||||
monkeypatch.setattr(SyncService, "sync_all", lambda self, **kw: [])
|
||||
seen = {}
|
||||
|
||||
def fake_all(self, start, end, *, user="", job=None):
|
||||
seen["job"] = job
|
||||
return [{"code": "google", "ok": True, "days": 10, "total": 1000}]
|
||||
|
||||
monkeypatch.setattr(ad_sync.AdSyncService, "sync_all", fake_all)
|
||||
|
||||
class Store:
|
||||
def last_update_at(self):
|
||||
return None
|
||||
|
||||
def ad_source_statuses(self):
|
||||
return {"google": {"last_success_sync_at": "2026-10-13T09:00:07+09:00"},
|
||||
"meta": {"last_success_sync_at": "2026-10-13T08:30:02+09:00"}}
|
||||
|
||||
monkeypatch.setattr(ad_sync, "ad_credentials", lambda store, ring: None)
|
||||
res = au.run_once(Store(), None, today=date(2026, 10, 13), days=10)
|
||||
job = seen["job"]
|
||||
assert job.kind == "ads" and job.finished and job.last_update_at == "2026-10-13T09:00:07+09:00"
|
||||
assert res["ads"] == [{"code": "google", "ok": True}] and jobs.running_job("ads") is None
|
||||
|
||||
|
||||
def test_startup_clears_orphan_running_runs(monkeypatch):
|
||||
|
||||
@@ -315,3 +315,93 @@ def test_sync_endpoint(monkeypatch):
|
||||
svc.conf = {"google": False}
|
||||
r = client.post("/performance/api/ad-sources/google/sync", json={})
|
||||
assert r.status_code == 400 and "설정" in r.json()["detail"]
|
||||
|
||||
|
||||
def test_sync_all_with_job_reports_channel_progress(monkeypatch):
|
||||
"""[광고비 업데이트](2026-10-20) — 채널별 진행 막대: 완료(일·광고비)·실패·중지(저장 안 함)."""
|
||||
from app.modules.performance import jobs
|
||||
from app.modules.performance.ad_sources.base import AdDay
|
||||
|
||||
store = FakeStore()
|
||||
src = ga.GoogleAdsSource()
|
||||
monkeypatch.setattr(src, "fetch_days", lambda ctx, s, e: [AdDay(date(2026, 10, 1), 1000, None, {}),
|
||||
AdDay(date(2026, 10, 2), 2000, None, {})])
|
||||
monkeypatch.setattr(ad_sync, "get_source", lambda code: src)
|
||||
svc = _service(store, src)
|
||||
job = jobs.create_job(user="king@x", start=None, end=None, kind="ads")
|
||||
res = svc.sync_all(date(2026, 10, 1), date(2026, 10, 2), user="king@x", job=job)
|
||||
assert res[0]["ok"] and job.kind == "ads"
|
||||
shop = job.snapshot()["shops"][0]
|
||||
assert shop["state"] == "done" and shop["upserted"] == 2 and shop["message"] == "광고비 ₩3,000" and shop["fraction"] == 1.0
|
||||
|
||||
# 수집 뒤 저장 직전에 [중지] → 저장하지 않음
|
||||
job2 = jobs.create_job(user="king@x", start=None, end=None, kind="ads")
|
||||
|
||||
def fetch_then_stop(ctx, s, e):
|
||||
job2.stop_shop("google")
|
||||
return [AdDay(date(2026, 10, 1), 1000, None, {})]
|
||||
|
||||
monkeypatch.setattr(src, "fetch_days", fetch_then_stop)
|
||||
before = len(store.replaced)
|
||||
res = svc.sync_all(date(2026, 10, 1), date(2026, 10, 1), job=job2)
|
||||
assert res[0].get("cancelled") and len(store.replaced) == before
|
||||
assert job2.snapshot()["shops"][0]["state"] == "cancelled"
|
||||
|
||||
# 실패 → 막대에 오류(상태·문구)
|
||||
def boom(ctx, s, e):
|
||||
raise AuthFailed("거부")
|
||||
|
||||
monkeypatch.setattr(src, "fetch_days", boom)
|
||||
job3 = jobs.create_job(user="king@x", start=None, end=None, kind="ads")
|
||||
svc.sync_all(date(2026, 10, 1), date(2026, 10, 1), job=job3)
|
||||
s3 = job3.snapshot()["shops"][0]
|
||||
assert s3["state"] == "error" and s3["status"] == "auth_failed"
|
||||
for j in (job, job2, job3):
|
||||
j.finish()
|
||||
|
||||
|
||||
def test_ad_sync_job_endpoint(monkeypatch):
|
||||
import importlib
|
||||
|
||||
from fastapi import FastAPI
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from app.modules.performance import common, jobs
|
||||
|
||||
perf_router = importlib.import_module("app.modules.performance.router")
|
||||
ran = []
|
||||
|
||||
class Svc:
|
||||
conf = {"google": True, "meta": False}
|
||||
|
||||
def configured(self):
|
||||
return self.conf
|
||||
|
||||
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()))
|
||||
monkeypatch.setattr(ad_sync, "run_ad_job", lambda store, ring, job, s, e, user="": ran.append((job.id, s, e, user)))
|
||||
app = FastAPI()
|
||||
app.include_router(perf_router.router)
|
||||
client = TestClient(app)
|
||||
|
||||
assert client.get("/performance/api/ad-sync/current").json() == {"job": None}
|
||||
r = client.post("/performance/api/ad-sync", json={"from": "2026-10-01", "to": "2026-10-31"})
|
||||
body = r.json()
|
||||
assert r.status_code == 200 and not body["joined"] and body["job"]["kind"] == "ads"
|
||||
assert body["job"]["to"] == "2026-10-15" # 오늘 뒤는 잘라냄
|
||||
import time
|
||||
for _ in range(50):
|
||||
if ran:
|
||||
break
|
||||
time.sleep(0.02)
|
||||
assert ran and ran[0][1:] == (date(2026, 10, 1), date(2026, 10, 15), "king@x")
|
||||
# 진행 중이면 새로 시작하지 않고 합류(매출 업데이트와 별개)
|
||||
r = client.post("/performance/api/ad-sync", json={})
|
||||
assert r.json()["joined"] and r.json()["job"]["id"] == body["job"]["id"]
|
||||
assert client.get("/performance/api/ad-sync/current").json()["job"]["id"] == body["job"]["id"]
|
||||
assert jobs.running_job("sales") is None or jobs.running_job("sales").kind == "sales"
|
||||
jobs.get_job(body["job"]["id"]).finish()
|
||||
Svc.conf = {"google": False}
|
||||
r = client.post("/performance/api/ad-sync", json={})
|
||||
assert r.status_code == 400 and "광고 API" in r.json()["detail"]
|
||||
|
||||
@@ -61,8 +61,6 @@ a.perf-tab.is-active:link, a.perf-tab.is-active:visited { color: #fff; }
|
||||
/* 광고 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 는 작게 옅게 붙인다. 입력 중엔 숫자처럼 자리만 남기고 숨김 */
|
||||
@@ -381,5 +379,5 @@ td.is-link:hover { background: #eef2ff; text-decoration: underline; }
|
||||
.perf-ev-table tfoot .perf-ev-x, .perf-ev-table tfoot .perf-ev-x b { color: #fff; } /* 검은 합계 줄 — 흰 글자 */
|
||||
.perf-ev-table tfoot .perf-ev-xsub { color: #c9c9c9; }
|
||||
/* [매출 업데이트] — 업데이트 중이면 "업데이트 중 · 진행 보기"(눌러서 진행 창 다시 열기), 살짝 깜박임 */
|
||||
#perf-sync-btn.is-running { animation: perf-sync-pulse 1.6s ease-in-out infinite; }
|
||||
#perf-sync-btn.is-running, #perf-ad-sync-btn.is-running { animation: perf-sync-pulse 1.6s ease-in-out infinite; }
|
||||
@keyframes perf-sync-pulse { 0%, 100% { opacity: 1; } 50% { opacity: .72; } }
|
||||
|
||||
+78
-27
@@ -102,14 +102,20 @@
|
||||
'<div class="perf-prog-pct">' + pct + "%</div>" +
|
||||
'<div class="perf-prog-text">' + text + "</div></div>";
|
||||
}
|
||||
function shopText(s) {
|
||||
// 작업 종류별 말 — 매출 업데이트(쇼핑몰별) · 광고비 업데이트(광고 채널별, job.kind="ads", 2026-10-20)
|
||||
function jobWords(job) {
|
||||
return job && job.kind === "ads"
|
||||
? { what: "광고비", unit: "채널", rows: "일", keep: "기존 광고비 그대로" }
|
||||
: { what: "매출", unit: "쇼핑몰", rows: "건", keep: "기존 매출 그대로" };
|
||||
}
|
||||
function shopText(s, w) {
|
||||
let t = SHOP_STATE[s.state] || s.state;
|
||||
if (s.state === "running" && s.total) t += " " + fmt(s.done) + "/" + fmt(s.total) + s.unit;
|
||||
if (s.items && s.state !== "done") t += " · 받은 자료 " + fmt(s.items) + "건";
|
||||
if (s.state === "done") t += " · " + fmt(s.upserted) + "건 반영";
|
||||
if (s.state === "running" && s.total && w.unit === "쇼핑몰") t += " " + fmt(s.done) + "/" + fmt(s.total) + s.unit;
|
||||
if (s.items && s.state !== "done") t += " · 받은 자료 " + fmt(s.items) + (w.unit === "채널" ? "일" : "건");
|
||||
if (s.state === "done") t += " · " + fmt(s.upserted) + w.rows + " 반영" + (w.unit === "채널" && s.message ? " · " + s.message : "");
|
||||
if (s.state === "error") t += " · " + (s.label ? s.label + " — " : "") + (s.message || "");
|
||||
if (s.state === "skipped") t += " · " + (s.message || "");
|
||||
if (s.state === "cancelled") t = (s.message === "중지됨" ? "중지됨" : t) + " · 저장하지 않음(기존 매출 그대로)";
|
||||
if (s.state === "cancelled") t = (s.message === "중지됨" ? "중지됨" : t) + " · 저장하지 않음(" + w.keep + ")";
|
||||
if (s.state === "running" && s.cancel_pending) t += " · 취소하는 중…";
|
||||
else if (s.state === "running" && s.stop_requested) t += " · 중지하는 중…";
|
||||
if (s.state === "waiting" && s.stop_requested) t += " · 중지 — 차례가 오면 건너뜀";
|
||||
@@ -121,6 +127,7 @@
|
||||
const active = job.shops.filter(function (s) { return s.active; });
|
||||
const passive = job.shops.filter(function (s) { return !s.active; });
|
||||
const o = job.overall;
|
||||
const w = jobWords(job);
|
||||
let html = joined ? '<p class="perf-notice">이미 진행 중인 업데이트를 보여 줍니다.</p>' : "";
|
||||
html += '<p class="perf-muted" style="margin:0 0 10px">기간 ' + esc(job.from || "") + " ~ " + esc(job.to || "") +
|
||||
" · 경과 " + fmtSec(job.elapsed) + (job.finished ? "" : " · 창을 닫아도 서버에서 계속 진행됩니다") + "</p>";
|
||||
@@ -132,13 +139,14 @@
|
||||
const stoppable = !job.finished && !job.cancel_requested && !s.stop_requested &&
|
||||
(s.state === "waiting" || s.state === "running");
|
||||
const stopBtn = stoppable ? '<button type="button" class="perf-prog-stop" data-stop="' + esc(s.code) + '" title="' +
|
||||
esc(s.name) + ' 업데이트만 멈추고 다음 쇼핑몰로 넘어갑니다(이 쇼핑몰은 저장하지 않음)">중지</button>' : "";
|
||||
return progressRow(s.name, s.fraction, shopText(s), cls, stopBtn);
|
||||
esc(s.name) + " 업데이트만 멈추고 다음 " + w.unit + "로 넘어갑니다(이 " + w.unit + '은 저장하지 않음)">중지</button>' : "";
|
||||
return progressRow(s.name, s.fraction, shopText(s, w), cls, stopBtn);
|
||||
}).join("");
|
||||
html += progressRow("전체", o.fraction,
|
||||
esc((job.cancel_requested ? (job.finished ? "업데이트 취소됨 · " : "취소하는 중 · ") : "") +
|
||||
fmt(o.finished) + "/" + fmt(o.shops) + " 쇼핑몰 완료" +
|
||||
(o.items ? " · 받은 자료 " + fmt(o.items) + "건" : "") + (job.finished ? " · " + fmt(o.upserted) + "건 반영" : "")),
|
||||
fmt(o.finished) + "/" + fmt(o.shops) + " " + w.unit + " 완료" +
|
||||
(o.items ? " · 받은 자료 " + fmt(o.items) + (w.unit === "채널" ? "일" : "건") : "") +
|
||||
(job.finished ? " · " + fmt(o.upserted) + w.rows + " 반영" : "")),
|
||||
"is-total" + (job.finished ? (job.cancel_requested ? " is-skip" : " is-done") : ""));
|
||||
if (passive.length) {
|
||||
html += '<p class="perf-muted" style="margin:10px 0 0">건너뜀: ' + esc(passive.map(function (s) {
|
||||
@@ -149,7 +157,8 @@
|
||||
box.innerHTML = html;
|
||||
}
|
||||
// existing = 이미 돌고 있는 작업(GET /api/sync/current) — 주면 새로 시작하지 않고 그 진행 창만 다시 연다(2026-10-19)
|
||||
function runSyncWithProgress(payload, title, existing) {
|
||||
// startUrl = 새로 시작할 API(기본 매출 /api/sync, 광고비 /api/ad-sync — 2026-10-20). 진행·취소·중지 API 는 같다.
|
||||
function runSyncWithProgress(payload, title, existing, startUrl) {
|
||||
return new Promise(function (resolve, reject) {
|
||||
let timer = null, closed = false, last = null;
|
||||
const m = openModal(title || "매출 업데이트", { narrow: true, onClose: function () { closed = true; clearTimeout(timer); if (last) resolve(last); } });
|
||||
@@ -182,7 +191,9 @@
|
||||
});
|
||||
cancelBtn.addEventListener("click", async function () {
|
||||
if (!jobId) return;
|
||||
if (!(await confirmMsg("매출 업데이트를 취소할까요?\n수집 중인 쇼핑몰은 저장하지 않고 멈추고, 이미 끝난 쇼핑몰 결과는 그대로 남습니다."))) return;
|
||||
const w = jobWords(last);
|
||||
if (!(await confirmMsg(w.what + " 업데이트를 취소할까요?\n수집 중인 " + w.unit + "은 저장하지 않고 멈추고, 이미 끝난 " + w.unit +
|
||||
" 결과는 그대로 남습니다."))) return;
|
||||
cancelBtn.disabled = true;
|
||||
cancelBtn.textContent = "취소하는 중…";
|
||||
try {
|
||||
@@ -196,7 +207,7 @@
|
||||
}
|
||||
});
|
||||
(existing ? Promise.resolve({ job: existing, joined: true })
|
||||
: api("POST", "/performance/api/sync", Object.assign({ background: true }, payload))).then(function (res) {
|
||||
: api("POST", startUrl || "/performance/api/sync", Object.assign({ background: true }, payload))).then(function (res) {
|
||||
last = res.job;
|
||||
jobId = res.job.id;
|
||||
const joined = res.joined;
|
||||
@@ -390,23 +401,63 @@
|
||||
});
|
||||
});
|
||||
|
||||
// [구글 광고 불러오기] — 광고 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 = "불러오는 중…";
|
||||
// [광고비 업데이트](2026-10-20) — 매출 업데이트처럼 진행 창(광고 채널별·전체 막대). 설정된 광고 API(구글·메타) 전부,
|
||||
// 지금 보는 기간(오늘까지). 이미 돌고 있는 광고비 업데이트(다른 사람·자동 업데이트)가 있으면 그 진행 창을 다시 연다.
|
||||
const adSyncBtn = document.getElementById("perf-ad-sync-btn");
|
||||
if (adSyncBtn) adSyncBtn.addEventListener("click", async function () {
|
||||
if (adSyncBtn.dataset.busy === "1") return;
|
||||
adSyncBtn.dataset.busy = "1";
|
||||
adSyncBtn.textContent = "업데이트 중 · 진행 보기";
|
||||
adSyncBtn.classList.add("is-running");
|
||||
const box = document.getElementById("perf-sync-result");
|
||||
let running = false;
|
||||
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();
|
||||
let cur = null;
|
||||
try { cur = (await api("GET", "/performance/api/ad-sync/current")).job; } catch (_) { cur = null; }
|
||||
let job;
|
||||
if (cur && !cur.finished) {
|
||||
job = await runSyncWithProgress(null, "광고비 업데이트 진행 상황 " + (cur.from || "") + " ~ " + (cur.to || ""), cur);
|
||||
} else {
|
||||
const from = data.period_start, to = data.period_end < data.today ? data.period_end : data.today;
|
||||
if (from > data.today) throw new Error("앞으로의 기간은 가져올 수 없습니다.");
|
||||
job = await runSyncWithProgress({ from: from, to: to }, "광고비 업데이트 " + from + " ~ " + to, null,
|
||||
"/performance/api/ad-sync");
|
||||
}
|
||||
running = !!(job && !job.finished);
|
||||
const ok = [], bad = [], other = [];
|
||||
let changed = 0;
|
||||
jobResults(job).filter(function (r) { return r.finished; }).forEach(function (r) {
|
||||
if (r.ok) { ok.push(r.name + " " + fmt(r.upserted) + "일"); changed += r.upserted; }
|
||||
else if (r.stopped || r.cancelled || r.skipped) {
|
||||
other.push(r.name + "(" + (r.stopped ? "중지됨" : r.cancelled ? "취소됨" : r.message || "건너뜀") + ")");
|
||||
} else bad.push(r.name + "(" + (r.label || r.status) + (r.message ? ": " + r.message : "") + ")");
|
||||
});
|
||||
const parts = [];
|
||||
if (running) parts.push("<b>업데이트가 아직 진행 중입니다</b> — [업데이트 중 · 진행 보기]를 누르면 진행 창을 다시 볼 수 있습니다");
|
||||
if (ok.length) parts.push("<b>반영</b> " + esc(ok.join(", ")));
|
||||
if (bad.length) parts.push("<b>실패</b> " + esc(bad.join(", ")));
|
||||
if (other.length) parts.push('<span class="perf-muted">' + esc(other.join(", ")) + "</span>");
|
||||
if (box) {
|
||||
box.innerHTML = parts.join(" · ") || "업데이트할 광고 채널이 없습니다.";
|
||||
box.className = "perf-notice" + (bad.length ? " is-warn" : " is-ok");
|
||||
box.hidden = false;
|
||||
}
|
||||
if (job && job.last_update_at) {
|
||||
const lu = document.querySelector("#perf-last-update b");
|
||||
if (lu) lu.textContent = job.last_update_at.slice(0, 16).replace("T", " ");
|
||||
}
|
||||
if (changed > 0 && !running) setTimeout(function () { location.reload(); }, 800);
|
||||
} catch (err) {
|
||||
alertMsg(err.message);
|
||||
btn.disabled = false;
|
||||
btn.textContent = label;
|
||||
if (box) {
|
||||
box.textContent = "광고비 업데이트 실패: " + err.message;
|
||||
box.className = "perf-notice is-warn";
|
||||
box.hidden = false;
|
||||
}
|
||||
} finally {
|
||||
adSyncBtn.dataset.busy = "";
|
||||
adSyncBtn.textContent = running ? "업데이트 중 · 진행 보기" : "광고비 업데이트";
|
||||
adSyncBtn.classList.toggle("is-running", running);
|
||||
adSyncBtn.title = running ? "업데이트 진행 상황 보기" : "지금 보고 있는 기간의 광고비·ROAS 를 광고 API 에서 다시 가져옵니다";
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
Reference in New Issue
Block a user