fix(performance): 구글 광고 INVALID_LOGIN_CUSTOMER_ID 안내 + 저장된 일반 칸을 비우면 지워지게
- 로그인 고객 ID(MCC) 오류에 "직접 추가했다면 칸을 비우고, MCC 면 서비스 계정을 추가한 그 MCC 번호" 안내 - API 설정 창: 저장값이 보이던 일반(비밀 아님) 선택 칸을 비우면 [저장] 때 지우고(clear), [연결 테스트]도 빈 값으로 시험 (예전엔 빈 칸 = 기존 값 유지라 한 번 넣은 MCC 번호를 지울 수 없었음) - performance.js 20261015b Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -49,6 +49,9 @@ _HINTS = {
|
||||
"CLOUD_PROJECT_NOT_APPROVED_FOR_PRODUCTION": "서비스 계정이 속한 Google Cloud 프로젝트에 운영 계정 접근 승인이 없습니다. "
|
||||
"Cloud Console → Google Ads API Overview 에서 그 프로젝트의 Explorer 이상 승인을 확인하세요.",
|
||||
"AUTHORIZATION_ERROR": "API 접근 승인 문제입니다. 서비스 계정이 속한 Cloud 프로젝트의 Google Ads API 승인 상태를 확인하세요.",
|
||||
"INVALID_LOGIN_CUSTOMER_ID": "[로그인 고객 ID(MCC)] 칸 문제입니다. 서비스 계정을 광고 계정에 직접 추가했다면 이 칸을 비우세요"
|
||||
"(칸을 지우고 [연결 테스트] → [저장]). MCC 에 추가했다면 서비스 계정을 추가한 그 MCC 번호여야 하고, "
|
||||
"고객 ID 의 광고 계정이 그 MCC 아래에 있어야 합니다.",
|
||||
"USER_PERMISSION_DENIED": "서비스 계정이 이 광고 계정에 권한이 없습니다. 구글 광고 → 관리 → 액세스 및 보안에 서비스 계정 이메일을 "
|
||||
"사용자로 추가했는지, 관리자(MCC) 계정에 추가했다면 [로그인 고객 ID]에 MCC 번호를 넣었는지 확인하세요.",
|
||||
"CUSTOMER_NOT_ENABLED": "광고 계정이 사용 중지(취소·미완료) 상태입니다.",
|
||||
|
||||
@@ -48,8 +48,10 @@ class AdSyncService:
|
||||
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)
|
||||
def _ctx(self, code: str, *, values: dict[str, str] | None = None, user: str = "",
|
||||
cleared: set[str] | None = None) -> AdapterContext:
|
||||
trial = values is not None or bool(cleared)
|
||||
acc = self._creds.accessor(code, overrides=values, persist=not trial, user=user, cleared=cleared)
|
||||
return AdapterContext(code=code, credentials=acc, timeout_sec=30.0)
|
||||
|
||||
@staticmethod
|
||||
@@ -57,12 +59,15 @@ class AdSyncService:
|
||||
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 가 있으면 저장하지 않은 새 입력값(빈 칸은 저장값)으로 시험 — 그때는 상태를 기록하지 않는다."""
|
||||
def test_connection(self, code: str, *, values: dict[str, str] | None = None, user: str = "",
|
||||
cleared: set[str] | None = None) -> dict[str, Any]:
|
||||
"""values 가 있으면 저장하지 않은 새 입력값(빈 칸은 저장값)으로 시험, cleared = 화면에서 비운 항목(빈 값으로) —
|
||||
그때는 상태를 기록하지 않는다."""
|
||||
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)
|
||||
ctx = self._ctx(code, values=values, user=user, cleared=cleared)
|
||||
trial = bool(values) or bool(cleared)
|
||||
try:
|
||||
src.require_configured(ctx)
|
||||
msg = src.test_connection(ctx)
|
||||
@@ -72,10 +77,10 @@ class AdSyncService:
|
||||
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:
|
||||
if not trial:
|
||||
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)}
|
||||
"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."""
|
||||
|
||||
@@ -27,7 +27,7 @@ class CredentialAccessor:
|
||||
|
||||
def __init__(self, store: Any, code: str, ring_loader: Callable[[], KeyRing], *,
|
||||
overrides: dict[str, str] | None = None, persist: bool = True, user: str = "",
|
||||
aad_ns: str = "") -> None:
|
||||
aad_ns: str = "", cleared: set[str] | None = None) -> None:
|
||||
self._store = store
|
||||
self._code = code
|
||||
self._ns = aad_ns
|
||||
@@ -35,13 +35,19 @@ class CredentialAccessor:
|
||||
self._rows = store.credential_rows(code) if store is not None else {}
|
||||
self._cache: dict[str, str] = {}
|
||||
self._overrides = {k: v for k, v in (overrides or {}).items() if v}
|
||||
# 연결 테스트에서 화면 칸을 비운 항목 — 저장값이 있어도 빈 값으로(저장하지 않음)
|
||||
self._cleared = {k for k in (cleared or set()) if k not in self._overrides}
|
||||
self._persist = persist
|
||||
self._user = user
|
||||
|
||||
def has(self, key: str) -> bool:
|
||||
if key in self._cleared:
|
||||
return False
|
||||
return bool(self._overrides.get(key)) or key in self._rows
|
||||
|
||||
def get(self, key: str) -> str:
|
||||
if key in self._cleared:
|
||||
return ""
|
||||
if key in self._overrides:
|
||||
return self._overrides[key]
|
||||
if key in self._cache:
|
||||
@@ -79,9 +85,9 @@ class CredentialService:
|
||||
self._ns = aad_ns
|
||||
|
||||
def accessor(self, code: str, *, overrides: dict[str, str] | None = None, persist: bool = True,
|
||||
user: str = "") -> CredentialAccessor:
|
||||
user: str = "", cleared: set[str] | None = None) -> CredentialAccessor:
|
||||
return CredentialAccessor(self._store, code, self._ring_loader, overrides=overrides,
|
||||
persist=persist, user=user, aad_ns=self._ns)
|
||||
persist=persist, user=user, aad_ns=self._ns, cleared=cleared)
|
||||
|
||||
# ── 화면용 요약(비밀 원문 없음) ─────────────────────────
|
||||
def describe(self, adapter: MarketplaceAdapter) -> dict[str, Any]:
|
||||
|
||||
@@ -609,7 +609,9 @@ def api_ad_source_test(request: Request, code: str, payload: dict[str, Any] = Bo
|
||||
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"]))
|
||||
allowed = {f.key for f in src.visible_fields()}
|
||||
cleared = {str(k) for k in (payload.get("clear") or []) if str(k) in allowed and str(k) not in values}
|
||||
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")
|
||||
|
||||
@@ -224,4 +224,4 @@
|
||||
} | tojson }}</script>
|
||||
{% endblock %}
|
||||
|
||||
{% block scripts %}<script src="/static/performance.js?v=20261015a" defer></script>{% endblock %}
|
||||
{% block scripts %}<script src="/static/performance.js?v=20261015b" defer></script>{% endblock %}
|
||||
|
||||
@@ -255,4 +255,4 @@
|
||||
} | tojson }}</script>
|
||||
{% endblock %}
|
||||
|
||||
{% block scripts %}<script src="/static/performance.js?v=20261015a" defer></script>{% endblock %}
|
||||
{% block scripts %}<script src="/static/performance.js?v=20261015b" defer></script>{% endblock %}
|
||||
|
||||
@@ -248,4 +248,4 @@
|
||||
</section>
|
||||
{% endblock %}
|
||||
|
||||
{% block scripts %}<script src="/static/performance.js?v=20261015a" defer></script>{% endblock %}
|
||||
{% block scripts %}<script src="/static/performance.js?v=20261015b" defer></script>{% endblock %}
|
||||
|
||||
@@ -129,6 +129,15 @@ def test_errors_are_explained(monkeypatch):
|
||||
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
|
||||
|
||||
# 사용자 화면 오류(2026-10-15): 로그인 고객 ID(MCC) 칸에 권한 없는 번호 → 칸을 비우라는 안내
|
||||
bad_login = [{"error": {"code": 403, "message": "PERMISSION_DENIED", "details": [{"errors": [
|
||||
{"errorCode": {"authorizationError": "INVALID_LOGIN_CUSTOMER_ID"},
|
||||
"message": "The login customer id header 'Optional[9998887777]' could not be validated."}]}]}}]
|
||||
_install(monkeypatch, lambda req: httpx.Response(403, json=bad_login))
|
||||
with pytest.raises(AuthFailed) as e:
|
||||
src.fetch_days(_ctx(login_customer_id="999-888-7777"), date(2026, 10, 1), date(2026, 10, 1))
|
||||
assert "INVALID_LOGIN_CUSTOMER_ID" 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))
|
||||
@@ -180,6 +189,17 @@ def test_ad_credentials_use_own_namespace():
|
||||
assert aad_for("google", "service_account_json", "ad:") == "perf:ad:google:service_account_json"
|
||||
with pytest.raises(Exception):
|
||||
crypto.decrypt(t.rows[("google", "service_account_json")], aad=aad_for("google", "service_account_json"), ring=ring)
|
||||
# 저장된 일반 항목을 화면에서 비우고 [연결 테스트] → 그 항목은 빈 값으로(저장값 무시), 새 입력값이 있으면 그 값
|
||||
svc.save(ga.GoogleAdsSource(), {"login_customer_id": "999-888-7777"}, user="king")
|
||||
acc = svc.accessor("google", cleared={"login_customer_id"})
|
||||
assert acc.get("login_customer_id") == "" and not acc.has("login_customer_id") and acc.get("customer_id") == "1234567890"
|
||||
assert svc.accessor("google").get("login_customer_id") == "999-888-7777"
|
||||
acc = svc.accessor("google", overrides={"login_customer_id": "111-222-3333"}, cleared={"login_customer_id"})
|
||||
assert acc.get("login_customer_id") == "111-222-3333"
|
||||
# [저장] 때 clear 로 보내면 지워진다(빈 칸 = 유지가 아니라 지움)
|
||||
t.delete_credential = lambda code, key: t.rows.pop((code, key))
|
||||
svc.save(ga.GoogleAdsSource(), {}, clear=["login_customer_id"], user="king")
|
||||
assert ("google", "login_customer_id") not in t.rows
|
||||
|
||||
|
||||
class FakeStore:
|
||||
|
||||
@@ -841,12 +841,14 @@
|
||||
? '<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>';
|
||||
}
|
||||
// 저장된 일반(비밀 아님) 선택 항목 — 칸을 비우면 저장된 값을 지운다(data-had, cleared())
|
||||
const had = !f.secret && f.has_value && !f.required ? ' data-had="1"' : "";
|
||||
// 여러 줄 항목(서비스 계정 JSON 키 등)은 textarea — 비밀값이면 저장 후 내용은 다시 보이지 않는다
|
||||
const field = f.multiline
|
||||
? '<textarea class="erp-input perf-cred-multi" id="' + id + '" data-key="' + esc(f.key) + '" rows="6" spellcheck="false" ' +
|
||||
? '<textarea class="erp-input perf-cred-multi" id="' + id + '" data-key="' + esc(f.key) + '"' + had + ' 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) + '" ' +
|
||||
: '<input class="erp-input" id="' + id + '" data-key="' + esc(f.key) + '"' + had + " " +
|
||||
(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 +
|
||||
@@ -855,7 +857,7 @@
|
||||
(f.secret && f.has_value && !f.required ? '<label class="perf-check"><input type="checkbox" data-clear="' + esc(f.key) + '" /> 저장된 값 지우기</label>' : "") +
|
||||
"</div>";
|
||||
}).join("") + "</form>" +
|
||||
'<p class="perf-foot perf-muted">[연결 테스트]는 입력한 새 값으로 시험하며 저장하지 않습니다(빈 칸은 저장된 값 사용). ' +
|
||||
'<p class="perf-foot perf-muted">[연결 테스트]는 입력한 새 값으로 시험하며 저장하지 않습니다(빈 비밀 칸은 저장된 값 사용, 값이 보이던 칸을 비우면 빈 값으로 시험). ' +
|
||||
"[저장]은 연결 테스트 결과와 관계없이 저장합니다 — 쇼핑몰의 일시 장애로 테스트가 실패할 수 있기 때문입니다. " +
|
||||
"저장 후 자동으로 한 번 더 연결 테스트를 합니다.</p>";
|
||||
m.body.innerHTML = html;
|
||||
@@ -883,15 +885,18 @@
|
||||
return out;
|
||||
}
|
||||
function cleared() {
|
||||
return Array.prototype.filter.call(m.body.querySelectorAll("input[data-clear]"), function (c) { return c.checked; })
|
||||
const out = Array.prototype.filter.call(m.body.querySelectorAll("input[data-clear]"), function (c) { return c.checked; })
|
||||
.map(function (c) { return c.dataset.clear; });
|
||||
// 저장값이 보이던 일반 칸을 비웠으면 지우기(예: 구글 광고 로그인 고객 ID)
|
||||
m.body.querySelectorAll("[data-had]").forEach(function (i) { if (!i.value.trim() && out.indexOf(i.dataset.key) < 0) out.push(i.dataset.key); });
|
||||
return out;
|
||||
}
|
||||
async function test(withTyped) {
|
||||
testBtn.disabled = true;
|
||||
result.className = "perf-test-result";
|
||||
result.textContent = "연결 확인 중…";
|
||||
try {
|
||||
const res = await api("POST", base + code + "/test", withTyped ? { values: typed() } : {});
|
||||
const res = await api("POST", base + code + "/test", withTyped ? { values: typed(), clear: cleared() } : {});
|
||||
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;
|
||||
|
||||
Reference in New Issue
Block a user