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
+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) {