feat(performance): 메타 광고 상세보기 [합계 | 계정별] 탭

- 가져올 때 그날 메타 행 metrics 에 계정별 값(_accounts: 이름·광고비·ROAS·항목, insights account_name)을 함께 저장
  — 새 마이그레이션 없음. "_" 키는 일자별 표 열·합계·화면 값에서 제외.
- ad_spend.detail_tabs: 합계 탭 + 계정 탭(그 계정이 광고 낸 날만, 광고비 큰 계정부터), 계정별 값 없는 날 수 안내.
- 상세보기 창: 탭(주황 강조, 계정 ID 말풍선), 계정 탭은 1원 반올림 차이 안내. 네이버·구글은 그대로 표 하나.
- 테스트: 계정별 변환·탭 순서/이름/가중 ROAS·옛 자료 안내·API 응답, jsdom 탭 전환.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-16 13:38:17 +09:00
parent 8bbb1f9ab2
commit b2710a0831
12 changed files with 251 additions and 49 deletions
+76 -4
View File
@@ -63,7 +63,7 @@ def _row(day, spend, **extra):
# 계정 1: 두 쪽(paging.next), 계정 2: 한 쪽. 10-01 은 두 계정 모두 있음 → 날짜별 합산.
PAGE1 = {"data": [_row("2026-10-01", "100000", impressions="20000", clicks="400", inline_link_clicks="300",
PAGE1 = {"data": [_row("2026-10-01", "100000", account_name="본계정", impressions="20000", clicks="400", inline_link_clicks="300",
actions=[{"action_type": "omni_purchase", "value": "10"}, {"action_type": "purchase", "value": "10"},
{"action_type": "offsite_conversion.fb_pixel_purchase", "value": "10"},
{"action_type": "link_click", "value": "300"}],
@@ -72,7 +72,7 @@ PAGE1 = {"data": [_row("2026-10-01", "100000", impressions="20000", clicks="400"
{"action_type": "offsite_conversion.fb_pixel_purchase", "value": "450000"}])],
"paging": {"next": "https://graph.facebook.com/v26.0/act_1111111111/insights?after=CUR&access_token=" + TOKEN}}
PAGE2 = {"data": [_row("2026-10-02", "0", impressions="10")], "paging": {}}
ACC2 = {"data": [_row("2026-10-01", "50000.5", impressions="5000", clicks="100", inline_link_clicks="80",
ACC2 = {"data": [_row("2026-10-01", "50000.5", account_name="서브계정", impressions="5000", clicks="100", inline_link_clicks="80",
actions=[{"action_type": "offsite_conversion.fb_pixel_purchase", "value": "2"}],
action_values=[{"action_type": "offsite_conversion.fb_pixel_purchase", "value": "150000"}])]}
@@ -129,10 +129,18 @@ def test_fetch_days_sums_accounts_pages_and_converts(monkeypatch):
# 구매 전환값 = 계정1 omni_purchase 450,000(겹친 purchase·픽셀 값은 더하지 않음) + 계정2 픽셀 150,000 = 600,000
# ROAS = 600,000 ÷ 150,000.5 × 100 = 399.998... → 400.00
assert (d1.day, d1.amount, d1.roas) == (date(2026, 10, 1), 165001, Decimal("400.00"))
assert d1.metrics == {"광고비(부가세 포함)": 165001, "지출 금액(부가세 별도)": 150001, "노출수": 25000, "클릭수": 500,
"클릭률(%)": 2.0, "링크 클릭": 380, "구매수": 12, "구매 전환값": 600000, "ROAS(%)": 400.0}
total_metrics = {k: v for k, v in d1.metrics.items() if k != "_accounts"}
assert total_metrics == {"광고비(부가세 포함)": 165001, "지출 금액(부가세 별도)": 150001, "노출수": 25000, "클릭수": 500,
"클릭률(%)": 2.0, "링크 클릭": 380, "구매수": 12, "구매 전환값": 600000, "ROAS(%)": 400.0}
assert list(d1.metrics)[:2] == ["광고비(부가세 포함)", "지출 금액(부가세 별도)"] # 일자별 표 열 순서
assert (d2.day, d2.amount, d2.roas, d2.metrics["클릭률(%)"]) == (date(2026, 10, 2), 0, None, 0.0) # 지출 0 → ROAS 없음
# 계정별(상세보기 탭, 2026-10-16) — 계정마다 따로 변환. 이름은 insights 의 account_name(없는 쪽은 같은 계정 앞 줄 이름)
a1, a2 = d1.metrics["_accounts"]["1111111111"], d1.metrics["_accounts"]["2222222222"]
assert (a1["name"], a1["amount"], a1["roas"]) == ("본계정", 110000, 450.0) # 100,000 × 1.1, 450,000 ÷ 100,000
assert (a2["name"], a2["amount"], a2["roas"]) == ("서브계정", 55001, 300.0) # 50,000.5 × 1.1 = 55,000.55 → 55,001, 150,000 ÷ 50,000.5 = 299.997 → 300.00
assert a1["metrics"]["구매수"] == 10 and a2["metrics"]["구매 전환값"] == 150000 and a2["metrics"]["링크 클릭"] == 80
assert list(d2.metrics["_accounts"]) == ["1111111111"] and d2.metrics["_accounts"]["1111111111"]["name"] == "본계정"
assert "account_name" in seen[0].url.params["fields"].split(",")
def test_app_secret_proof_and_version(monkeypatch):
@@ -330,3 +338,67 @@ def test_connection_test_shows_full_diagnosis_first(monkeypatch):
assert "배정되지 않은 계정: act_1111111111, act_2222222222" in msg and "자산 할당" in msg
assert "(메타 원문: 메타 API 오류(200): (#200) Ad account owner has NOT grant" in msg
assert "https://" not in msg and ma._DIAG_HINT not in msg and TOKEN not in msg
# ── 상세보기 [합계 | 계정…] 탭(2026-10-16) ──
def _stored(day, amount, roas, metrics):
"""저장소 ad_details 행 모양."""
return {"date": day, "amount": amount, "roas": roas, "metrics": metrics, "source": "api"}
def test_detail_tabs_total_and_accounts():
def acc(name, amount, roas, spend_metric):
return {"name": name, "amount": amount, "roas": roas,
"metrics": {"광고비(부가세 포함)": amount, "노출수": spend_metric, "클릭수": spend_metric // 100, "클릭률(%)": 1.0,
"ROAS(%)": roas}}
rows = [
_stored("2026-10-01", 300, 200.0, {"광고비(부가세 포함)": 300, "노출수": 3000, "클릭수": 30, "클릭률(%)": 1.0, "ROAS(%)": 200.0,
"_accounts": {"1": acc("작은계정", 100, 100.0, 1000), "2": acc("큰계정", 200, 250.0, 2000)}}),
_stored("2026-10-02", 500, 300.0, {"광고비(부가세 포함)": 500, "노출수": 5000, "클릭수": 50, "클릭률(%)": 1.0, "ROAS(%)": 300.0,
"_accounts": {"2": acc("큰계정(새 이름)", 500, 300.0, 5000)}}),
_stored("2026-10-03", 70, None, {"광고비(부가세 포함)": 70}), # 계정별 저장 전에 가져온 날
]
t = ad_spend.detail_table(rows)
assert "_accounts" not in t["columns"] and "_accounts" not in t["total"] # "_" 키는 표 열·합계에 없음
assert all("_accounts" not in r["values"] for r in t["rows"]) # 화면으로도 보내지 않음
out = ad_spend.detail_tabs(rows)
tabs = out["tabs"]
assert [x["key"] for x in tabs] == ["total", "2", "1"] # 합계 → 광고비 큰 계정부터
assert [x["label"] for x in tabs] == ["합계", "큰계정(새 이름)", "작은계정"] # 이름 = 최근 날 이름
assert tabs[0]["total"] == t["total"] and len(tabs[0]["rows"]) == 3
big = tabs[1]
assert big["account_id"] == "2" and [r["date"] for r in big["rows"]] == ["2026-10-01", "2026-10-02"]
assert big["total"]["광고비(부가세 포함)"] == 700 and big["total"]["노출수"] == 7000
assert big["total"]["ROAS(%)"] == round((200 * 250 + 500 * 300) / 700, 2) # 광고비 가중 평균
assert [r["date"] for r in tabs[2]["rows"]] == ["2026-10-01"] # 광고를 낸 날만
assert out["accounts_missing"] == 1
def test_detail_tabs_absent_without_accounts():
rows = [_stored("2026-10-01", 100, 150.0, {"광고비(부가세 포함)": 100, "ROAS(%)": 150.0})]
assert ad_spend.detail_tabs(rows) == {"tabs": [], "accounts_missing": 0} # 네이버·구글·옛 메타 자료 = 탭 없음
def test_details_endpoint_returns_tabs(monkeypatch):
import importlib
from fastapi import FastAPI
from fastapi.testclient import TestClient
from app.modules.performance import common
perf_router = importlib.import_module("app.modules.performance.router")
rows = [_stored("2026-10-01", 110, 450.0, {"광고비(부가세 포함)": 110, "_accounts": {
"1": {"name": "본계정", "amount": 110, "roas": 450.0, "metrics": {"광고비(부가세 포함)": 110}}}})]
class Store:
def ad_details(self, code, start, end):
assert code == "meta"
return rows
monkeypatch.setattr(common, "require_store", lambda request: (Store(), {"email": "a@x"}))
app = FastAPI()
app.include_router(perf_router.router)
d = TestClient(app).get("/performance/api/ad-spend/meta/details?from=2026-10-01&to=2026-10-31").json()
assert d["columns"] == ["광고비(부가세 포함)"] and [t["label"] for t in d["tabs"]] == ["합계", "본계정"]
assert d["accounts_missing"] == 0