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
@@ -16,6 +16,12 @@ from typing import Any
from ..adapters.base import AdapterContext, CredentialField, NotConfigured
# AdDay.metrics 안의 계정별 값(여러 광고 계정을 합치는 채널 — 메타, 2026-10-16):
# {ACCOUNTS_KEY: {계정 ID: {"name", "amount", "roas", "metrics"}}} — 상세보기 [합계 | 계정…] 탭(ad_spend.detail_tabs).
# "_" 로 시작하는 metrics 키는 일자별 표 열·합계에 넣지 않는다(ad_spend.detail_table).
ACCOUNTS_KEY = "_accounts"
@dataclass
class AdDay:
"""광고 API 가 돌려준 하루치 — 금액은 원 단위 정수, ROAS 는 %(없으면 None), 나머지 항목은 화면 이름 그대로."""
+51 -26
View File
@@ -32,7 +32,7 @@ from typing import Any
import httpx
from ..adapters.base import AdapterContext, AdapterError, ApiError, AuthFailed, CredentialField, NotConfigured, TokenExpired
from .base import AdDay, AdSource
from .base import ACCOUNTS_KEY, AdDay, AdSource
API_BASE = "https://graph.facebook.com"
DEFAULT_VERSION = "v26.0" # 2026-07-29 출시(2026-10 기준 최신)
@@ -41,7 +41,7 @@ MAX_ACCOUNTS = 30
MAX_PAGES = 50 # 계정 하나 페이지 상한(하루 한 줄이라 366일도 몇 쪽)
VAT = Decimal("1.1") # 광고비 = 메타 지출 금액 + 부가세 10%
PURCHASE_TYPES = ("omni_purchase", "purchase", "offsite_conversion.fb_pixel_purchase")
INSIGHT_FIELDS = "date_start,account_currency,spend,impressions,clicks,inline_link_clicks,actions,action_values"
INSIGHT_FIELDS = "date_start,account_id,account_name,account_currency,spend,impressions,clicks,inline_link_clicks,actions,action_values"
# 일자별 표(광고비 탭 메타 머리글) 항목 — 순서 = 열 순서. 클릭률·ROAS 합계는 ad_spend.detail_table 이 이름으로 다시 계산.
M_SPEND, M_COST = "광고비(부가세 포함)", "지출 금액(부가세 별도)"
@@ -295,8 +295,9 @@ class MetaAdsSource(AdSource):
accounts, version, auth = self._setup(ctx)
params = {**auth, "level": "account", "time_increment": 1, "limit": 100, "fields": INSIGHT_FIELDS,
"time_range": json.dumps({"since": start.isoformat(), "until": end.isoformat()})}
keys = ("spend", "impr", "clicks", "link", "purchases", "value")
sums: dict[date, dict[str, Decimal]] = {}
sums: dict[date, dict[str, Decimal]] = {} # 날짜 → 모든 계정 합
per_acc: dict[date, dict[str, dict[str, Decimal]]] = {} # 날짜 → 계정 → 그 계정 값(상세보기 계정별 탭)
names: dict[str, str] = {}
with _http(ctx) as client:
for acc in accounts:
url: str | None = f"{API_BASE}/{version}/act_{acc}/insights"
@@ -311,13 +312,11 @@ class MetaAdsSource(AdSource):
day = date.fromisoformat(str(r.get("date_start")))
except ValueError:
continue
acc_sum = sums.setdefault(day, {k: Decimal(0) for k in keys})
acc_sum["spend"] += _num(r.get("spend"))
acc_sum["impr"] += _num(r.get("impressions"))
acc_sum["clicks"] += _num(r.get("clicks"))
acc_sum["link"] += _num(r.get("inline_link_clicks"))
acc_sum["purchases"] += _purchase(r.get("actions"))
acc_sum["value"] += _purchase(r.get("action_values"))
if r.get("account_name"):
names[acc] = str(r["account_name"])[:100]
one = per_acc.setdefault(day, {}).setdefault(acc, _zero())
_add(one, r)
_add(sums.setdefault(day, _zero()), r)
nxt = ((body.get("paging") or {}).get("next") or "").strip()
if not nxt:
break
@@ -328,20 +327,46 @@ class MetaAdsSource(AdSource):
raise ApiError("메타 API 응답 쪽수가 너무 많습니다. 기간을 줄여 다시 시도하세요.")
out: list[AdDay] = []
for day in sorted(sums):
a = sums[day]
amount = _won(a["spend"] * VAT) # 광고비 = 부가세 포함
roas = (a["value"] / a["spend"] * 100).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP) if a["spend"] > 0 else None
ctr = (a["clicks"] / a["impr"] * 100).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP) if a["impr"] > 0 else None
metrics = {
M_SPEND: amount,
M_COST: _won(a["spend"]),
M_IMPR: int(a["impr"]),
M_CLICKS: int(a["clicks"]),
M_CTR: float(ctr) if ctr is not None else None,
M_LINK: int(a["link"]),
M_PURCHASES: int(a["purchases"]),
M_VALUE: _won(a["value"]),
M_ROAS: float(roas) if roas is not None else None,
}
amount, roas, metrics = _convert(sums[day])
# 계정별 값 — 화면 표 열이 아니라 상세보기 계정별 탭용(ad_spend.detail_tabs, "_" 로 시작하는 키는 표 열에서 빠짐).
# 계정마다 따로 반올림하므로 계정 광고비 합이 합계와 1원 다를 수 있다.
accounts_out: dict[str, Any] = {}
for acc, a in per_acc.get(day, {}).items():
a_amount, a_roas, a_metrics = _convert(a)
accounts_out[acc] = {"name": names.get(acc) or f"act_{acc}", "amount": a_amount,
"roas": float(a_roas) if a_roas is not None else None, "metrics": a_metrics}
metrics[ACCOUNTS_KEY] = accounts_out
out.append(AdDay(day=day, amount=amount, roas=roas, metrics=metrics))
return out
def _zero() -> dict[str, Decimal]:
return {k: Decimal(0) for k in ("spend", "impr", "clicks", "link", "purchases", "value")}
def _add(acc: dict[str, Decimal], r: dict[str, Any]) -> None:
"""insights 한 줄(계정 하나·하루)을 더한다."""
acc["spend"] += _num(r.get("spend"))
acc["impr"] += _num(r.get("impressions"))
acc["clicks"] += _num(r.get("clicks"))
acc["link"] += _num(r.get("inline_link_clicks"))
acc["purchases"] += _purchase(r.get("actions"))
acc["value"] += _purchase(r.get("action_values"))
def _convert(a: dict[str, Decimal]) -> tuple[int, Decimal | None, dict[str, Any]]:
"""더한 값 → (광고비(부가세 포함) 원, ROAS %, 일자별 표 항목)."""
amount = _won(a["spend"] * VAT) # 광고비 = 부가세 포함
roas = (a["value"] / a["spend"] * 100).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP) if a["spend"] > 0 else None
ctr = (a["clicks"] / a["impr"] * 100).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP) if a["impr"] > 0 else None
return amount, roas, {
M_SPEND: amount,
M_COST: _won(a["spend"]),
M_IMPR: int(a["impr"]),
M_CLICKS: int(a["clicks"]),
M_CTR: float(ctr) if ctr is not None else None,
M_LINK: int(a["link"]),
M_PURCHASES: int(a["purchases"]),
M_VALUE: _won(a["value"]),
M_ROAS: float(roas) if roas is not None else None,
}
+34 -2
View File
@@ -27,6 +27,7 @@ from decimal import ROUND_HALF_UP, Decimal, InvalidOperation
from typing import Any, Callable, Mapping, Sequence
from . import calc
from .ad_sources.base import ACCOUNTS_KEY
from .manual_upload import MAX_AMOUNT, MAX_DATA_ROWS, MAX_ERRORS, MAX_FILE_BYTES, UploadError, parse_amount, parse_date
# 채널 — 표 열 순서(2026-10-14 사용자 지정). 쇼핑몰 채널 코드는 실적 쇼핑몰 코드와 같다(쿠팡(윙)만 coupang_wing ↔ 매출 coupang).
@@ -351,11 +352,13 @@ def detail_table(rows: list[dict[str, Any]]) -> dict[str, Any]:
cols: list[str] = []
for r in rows:
for k in (r.get("metrics") or {}):
if k not in cols:
if k not in cols and not k.startswith("_"): # "_" 키 = 표 열이 아닌 내부 값(계정별 등)
cols.append(k)
sums: dict[str, Decimal] = {}
for r in rows:
for k, v in (r.get("metrics") or {}).items():
if k.startswith("_"):
continue
if isinstance(v, (int, float)) and not isinstance(v, bool):
sums[k] = sums.get(k, Decimal(0)) + Decimal(str(v))
total: dict[str, Any] = {k: _json_num(v) for k, v in sums.items()}
@@ -369,10 +372,39 @@ def detail_table(rows: list[dict[str, Any]]) -> dict[str, Any]:
total[k] = float(round(rev / spend, 2)) if spend else None
out_rows = [{"date": r["date"], "amount": int(r.get("amount") or 0),
"roas": float(r["roas"]) if r.get("roas") is not None else None,
"values": r.get("metrics") or {}} for r in rows]
"values": {k: v for k, v in (r.get("metrics") or {}).items() if not k.startswith("_")}} for r in rows]
return {"columns": cols, "rows": out_rows, "total": total}
def detail_tabs(rows: list[dict[str, Any]]) -> dict[str, Any]:
"""상세보기 탭 — 계정별 값(ACCOUNTS_KEY)이 있는 채널(메타, 2026-10-16)은 [합계 | 계정…], 없으면 탭 없음.
계정 탭 = 그 계정이 광고를 낸 날만(그날 행의 계정 값으로 detail_table). 계정 이름은 가장 최근 날의 이름,
순서는 기간 광고비가 큰 계정부터(같으면 이름). accounts_missing = 광고비가 있는데 계정별 값이 없는 날 수
(계정별 저장 전에 가져온 날 — 다시 불러오면 생긴다)."""
per: dict[str, list[dict[str, Any]]] = {}
names: dict[str, str] = {}
missing = 0
for r in rows:
accs = (r.get("metrics") or {}).get(ACCOUNTS_KEY)
if not isinstance(accs, dict):
if int(r.get("amount") or 0):
missing += 1
continue
for acc, a in accs.items():
if not isinstance(a, dict):
continue
names[acc] = str(a.get("name") or f"act_{acc}")
per.setdefault(acc, []).append({"date": r["date"], "amount": int(a.get("amount") or 0),
"roas": a.get("roas"), "metrics": a.get("metrics") or {}})
if not per:
return {"tabs": [], "accounts_missing": 0}
spend = {acc: sum(x["amount"] for x in days) for acc, days in per.items()}
order = sorted(per, key=lambda acc: (-spend[acc], names[acc]))
tabs = [{"key": "total", "label": "합계", **detail_table(rows)}]
tabs += [{"key": acc, "label": names[acc], "account_id": acc, **detail_table(per[acc])} for acc in order]
return {"tabs": tabs, "accounts_missing": missing}
# ════════════════════════════════════════════════════════════
# 화면 데이터
# ════════════════════════════════════════════════════════════
+1 -1
View File
@@ -490,7 +490,7 @@ def api_ad_spend_details(request: Request, channel: str, from_: str = Query(...,
except ad_spend.AdMigrationNeeded as exc:
raise HTTPException(status_code=503, detail=_ad_migration_help(exc)) from None
return JSONResponse({"channel": channel, "name": ad_spend.CHANNEL_NAMES[channel], "from": start.isoformat(),
"to": end.isoformat(), **ad_spend.detail_table(rows)})
"to": end.isoformat(), **ad_spend.detail_table(rows), **ad_spend.detail_tabs(rows)})
@router.post("/api/ad-spend/upload")
@@ -1,6 +1,6 @@
{% extends "erp_base.html" %}
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261015a" />{% endblock %}
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261016a" />{% endblock %}
{#- ROAS 덧붙임 — "광고비(ROAS%)". 광고비가 없으면 아무것도 안 붙는다. -#}
{%- macro roas(p) -%}{%- if p is not none -%}<span class="perf-roas">({{ "{:,}".format(p) }}%)</span>{%- endif -%}{%- endmacro -%}
@@ -224,4 +224,4 @@
} | tojson }}</script>
{% endblock %}
{% block scripts %}<script src="/static/performance.js?v=20261015b" defer></script>{% endblock %}
{% block scripts %}<script src="/static/performance.js?v=20261016a" defer></script>{% endblock %}
@@ -1,6 +1,6 @@
{% extends "erp_base.html" %}
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261015a" />{% endblock %}
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261016a" />{% endblock %}
{%- macro won(v) -%}
{%- if v is none -%}<span class="perf-na"></span>
@@ -255,4 +255,4 @@
} | tojson }}</script>
{% endblock %}
{% block scripts %}<script src="/static/performance.js?v=20261015b" defer></script>{% endblock %}
{% block scripts %}<script src="/static/performance.js?v=20261016a" defer></script>{% endblock %}
@@ -1,6 +1,6 @@
{% extends "erp_base.html" %}
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261015a" />{% endblock %}
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261016a" />{% endblock %}
{%- macro when(v) -%}{{ (v or '')[:16] | replace('T', ' ') or '—' }}{%- endmacro -%}
@@ -249,4 +249,4 @@
</section>
{% endblock %}
{% block scripts %}<script src="/static/performance.js?v=20261015b" defer></script>{% endblock %}
{% block scripts %}<script src="/static/performance.js?v=20261016a" defer></script>{% endblock %}
+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