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 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 @dataclass
class AdDay: class AdDay:
"""광고 API 가 돌려준 하루치 — 금액은 원 단위 정수, ROAS 는 %(없으면 None), 나머지 항목은 화면 이름 그대로.""" """광고 API 가 돌려준 하루치 — 금액은 원 단위 정수, ROAS 는 %(없으면 None), 나머지 항목은 화면 이름 그대로."""
+51 -26
View File
@@ -32,7 +32,7 @@ from typing import Any
import httpx import httpx
from ..adapters.base import AdapterContext, AdapterError, ApiError, AuthFailed, CredentialField, NotConfigured, TokenExpired 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" API_BASE = "https://graph.facebook.com"
DEFAULT_VERSION = "v26.0" # 2026-07-29 출시(2026-10 기준 최신) DEFAULT_VERSION = "v26.0" # 2026-07-29 출시(2026-10 기준 최신)
@@ -41,7 +41,7 @@ MAX_ACCOUNTS = 30
MAX_PAGES = 50 # 계정 하나 페이지 상한(하루 한 줄이라 366일도 몇 쪽) MAX_PAGES = 50 # 계정 하나 페이지 상한(하루 한 줄이라 366일도 몇 쪽)
VAT = Decimal("1.1") # 광고비 = 메타 지출 금액 + 부가세 10% VAT = Decimal("1.1") # 광고비 = 메타 지출 금액 + 부가세 10%
PURCHASE_TYPES = ("omni_purchase", "purchase", "offsite_conversion.fb_pixel_purchase") 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 이 이름으로 다시 계산. # 일자별 표(광고비 탭 메타 머리글) 항목 — 순서 = 열 순서. 클릭률·ROAS 합계는 ad_spend.detail_table 이 이름으로 다시 계산.
M_SPEND, M_COST = "광고비(부가세 포함)", "지출 금액(부가세 별도)" M_SPEND, M_COST = "광고비(부가세 포함)", "지출 금액(부가세 별도)"
@@ -295,8 +295,9 @@ class MetaAdsSource(AdSource):
accounts, version, auth = self._setup(ctx) accounts, version, auth = self._setup(ctx)
params = {**auth, "level": "account", "time_increment": 1, "limit": 100, "fields": INSIGHT_FIELDS, params = {**auth, "level": "account", "time_increment": 1, "limit": 100, "fields": INSIGHT_FIELDS,
"time_range": json.dumps({"since": start.isoformat(), "until": end.isoformat()})} "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: with _http(ctx) as client:
for acc in accounts: for acc in accounts:
url: str | None = f"{API_BASE}/{version}/act_{acc}/insights" 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"))) day = date.fromisoformat(str(r.get("date_start")))
except ValueError: except ValueError:
continue continue
acc_sum = sums.setdefault(day, {k: Decimal(0) for k in keys}) if r.get("account_name"):
acc_sum["spend"] += _num(r.get("spend")) names[acc] = str(r["account_name"])[:100]
acc_sum["impr"] += _num(r.get("impressions")) one = per_acc.setdefault(day, {}).setdefault(acc, _zero())
acc_sum["clicks"] += _num(r.get("clicks")) _add(one, r)
acc_sum["link"] += _num(r.get("inline_link_clicks")) _add(sums.setdefault(day, _zero()), r)
acc_sum["purchases"] += _purchase(r.get("actions"))
acc_sum["value"] += _purchase(r.get("action_values"))
nxt = ((body.get("paging") or {}).get("next") or "").strip() nxt = ((body.get("paging") or {}).get("next") or "").strip()
if not nxt: if not nxt:
break break
@@ -328,20 +327,46 @@ class MetaAdsSource(AdSource):
raise ApiError("메타 API 응답 쪽수가 너무 많습니다. 기간을 줄여 다시 시도하세요.") raise ApiError("메타 API 응답 쪽수가 너무 많습니다. 기간을 줄여 다시 시도하세요.")
out: list[AdDay] = [] out: list[AdDay] = []
for day in sorted(sums): for day in sorted(sums):
a = sums[day] amount, roas, metrics = _convert(sums[day])
amount = _won(a["spend"] * VAT) # 광고비 = 부가세 포함 # 계정별 값 — 화면 표 열이 아니라 상세보기 계정별 탭용(ad_spend.detail_tabs, "_" 로 시작하는 키는 표 열에서 빠짐).
roas = (a["value"] / a["spend"] * 100).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP) if a["spend"] > 0 else None # 계정마다 따로 반올림하므로 계정 광고비 합이 합계와 1원 다를 수 있다.
ctr = (a["clicks"] / a["impr"] * 100).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP) if a["impr"] > 0 else None accounts_out: dict[str, Any] = {}
metrics = { for acc, a in per_acc.get(day, {}).items():
M_SPEND: amount, a_amount, a_roas, a_metrics = _convert(a)
M_COST: _won(a["spend"]), accounts_out[acc] = {"name": names.get(acc) or f"act_{acc}", "amount": a_amount,
M_IMPR: int(a["impr"]), "roas": float(a_roas) if a_roas is not None else None, "metrics": a_metrics}
M_CLICKS: int(a["clicks"]), metrics[ACCOUNTS_KEY] = accounts_out
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,
}
out.append(AdDay(day=day, amount=amount, roas=roas, metrics=metrics)) out.append(AdDay(day=day, amount=amount, roas=roas, metrics=metrics))
return out 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 typing import Any, Callable, Mapping, Sequence
from . import calc 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 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). # 채널 — 표 열 순서(2026-10-14 사용자 지정). 쇼핑몰 채널 코드는 실적 쇼핑몰 코드와 같다(쿠팡(윙)만 coupang_wing ↔ 매출 coupang).
@@ -351,11 +352,13 @@ def detail_table(rows: list[dict[str, Any]]) -> dict[str, Any]:
cols: list[str] = [] cols: list[str] = []
for r in rows: for r in rows:
for k in (r.get("metrics") or {}): for k in (r.get("metrics") or {}):
if k not in cols: if k not in cols and not k.startswith("_"): # "_" 키 = 표 열이 아닌 내부 값(계정별 등)
cols.append(k) cols.append(k)
sums: dict[str, Decimal] = {} sums: dict[str, Decimal] = {}
for r in rows: for r in rows:
for k, v in (r.get("metrics") or {}).items(): for k, v in (r.get("metrics") or {}).items():
if k.startswith("_"):
continue
if isinstance(v, (int, float)) and not isinstance(v, bool): if isinstance(v, (int, float)) and not isinstance(v, bool):
sums[k] = sums.get(k, Decimal(0)) + Decimal(str(v)) sums[k] = sums.get(k, Decimal(0)) + Decimal(str(v))
total: dict[str, Any] = {k: _json_num(v) for k, v in sums.items()} 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 total[k] = float(round(rev / spend, 2)) if spend else None
out_rows = [{"date": r["date"], "amount": int(r.get("amount") or 0), 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, "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} 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: except ad_spend.AdMigrationNeeded as exc:
raise HTTPException(status_code=503, detail=_ad_migration_help(exc)) from None 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(), 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") @router.post("/api/ad-spend/upload")
@@ -1,6 +1,6 @@
{% extends "erp_base.html" %} {% 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%)". 광고비가 없으면 아무것도 안 붙는다. -#} {#- ROAS 덧붙임 — "광고비(ROAS%)". 광고비가 없으면 아무것도 안 붙는다. -#}
{%- macro roas(p) -%}{%- if p is not none -%}<span class="perf-roas">({{ "{:,}".format(p) }}%)</span>{%- endif -%}{%- endmacro -%} {%- macro roas(p) -%}{%- if p is not none -%}<span class="perf-roas">({{ "{:,}".format(p) }}%)</span>{%- endif -%}{%- endmacro -%}
@@ -224,4 +224,4 @@
} | tojson }}</script> } | tojson }}</script>
{% endblock %} {% 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" %} {% 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) -%} {%- macro won(v) -%}
{%- if v is none -%}<span class="perf-na"></span> {%- if v is none -%}<span class="perf-na"></span>
@@ -255,4 +255,4 @@
} | tojson }}</script> } | tojson }}</script>
{% endblock %} {% 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" %} {% 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 -%} {%- macro when(v) -%}{{ (v or '')[:16] | replace('T', ' ') or '—' }}{%- endmacro -%}
@@ -249,4 +249,4 @@
</section> </section>
{% endblock %} {% 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 은 두 계정 모두 있음 → 날짜별 합산. # 계정 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"}, actions=[{"action_type": "omni_purchase", "value": "10"}, {"action_type": "purchase", "value": "10"},
{"action_type": "offsite_conversion.fb_pixel_purchase", "value": "10"}, {"action_type": "offsite_conversion.fb_pixel_purchase", "value": "10"},
{"action_type": "link_click", "value": "300"}], {"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"}])], {"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}} "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": {}} 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"}], actions=[{"action_type": "offsite_conversion.fb_pixel_purchase", "value": "2"}],
action_values=[{"action_type": "offsite_conversion.fb_pixel_purchase", "value": "150000"}])]} 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 # 구매 전환값 = 계정1 omni_purchase 450,000(겹친 purchase·픽셀 값은 더하지 않음) + 계정2 픽셀 150,000 = 600,000
# ROAS = 600,000 ÷ 150,000.5 × 100 = 399.998... → 400.00 # 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.day, d1.amount, d1.roas) == (date(2026, 10, 1), 165001, Decimal("400.00"))
assert d1.metrics == {"광고비(부가세 포함)": 165001, "지출 금액(부가세 별도)": 150001, "노출수": 25000, "클릭수": 500, total_metrics = {k: v for k, v in d1.metrics.items() if k != "_accounts"}
"클릭률(%)": 2.0, "링크 클릭": 380, "구매수": 12, "구매 전환값": 600000, "ROAS(%)": 400.0} assert total_metrics == {"광고비(부가세 포함)": 165001, "지출 금액(부가세 별도)": 150001, "노출수": 25000, "클릭수": 500,
"클릭률(%)": 2.0, "링크 클릭": 380, "구매수": 12, "구매 전환값": 600000, "ROAS(%)": 400.0}
assert list(d1.metrics)[:2] == ["광고비(부가세 포함)", "지출 금액(부가세 별도)"] # 일자별 표 열 순서 assert list(d1.metrics)[:2] == ["광고비(부가세 포함)", "지출 금액(부가세 별도)"] # 일자별 표 열 순서
assert (d2.day, d2.amount, d2.roas, d2.metrics["클릭률(%)"]) == (date(2026, 10, 2), 0, None, 0.0) # 지출 0 → ROAS 없음 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): 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 "배정되지 않은 계정: act_1111111111, act_2222222222" in msg and "자산 할당" in msg
assert "(메타 원문: 메타 API 오류(200): (#200) Ad account owner has NOT grant" 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 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
+3
View File
@@ -75,6 +75,9 @@ a.perf-tab.is-active:link, a.perf-tab.is-active:visited { color: #fff; }
.perf-detail-btn .material-symbols-outlined { font-size: 16px; } .perf-detail-btn .material-symbols-outlined { font-size: 16px; }
.perf-detail-btn:hover { background: #fff1ea; text-decoration: underline; } .perf-detail-btn:hover { background: #fff1ea; text-decoration: underline; }
.perf-detail-table th, .perf-detail-table td { white-space: nowrap; } .perf-detail-table th, .perf-detail-table td { white-space: nowrap; }
/* 상세보기 [합계 | 계정…] 탭(메타 — 여러 광고 계정) */
.perf-detail-tabs { flex-wrap: wrap; margin-bottom: 10px; }
.perf-detail-tabs .perf-seg.is-active { background: var(--perf-ad); }
.perf-ad-upload-btn { margin-left: auto; } .perf-ad-upload-btn { margin-left: auto; }
.perf-kpi-pct { font-size: 26px; font-weight: 700; } .perf-kpi-pct { font-size: 26px; font-weight: 700; }
+39 -10
View File
@@ -403,7 +403,7 @@
} }
}); });
// 광고 보고서 일자별 상세(네이버·구글 머리글) — 지금 보는 기간의 날마다 광고비·ROAS·보고서 항목, 맨 아래 합계. // 광고 보고서 일자별 상세(네이버·구글·메타 머리글) — 지금 보는 기간의 날마다 광고비·ROAS·보고서 항목, 맨 아래 합계.
root.addEventListener("click", async function (e) { root.addEventListener("click", async function (e) {
const btn = e.target.closest("[data-detail-channel]"); const btn = e.target.closest("[data-detail-channel]");
if (!btn) return; if (!btn) return;
@@ -425,15 +425,44 @@
const d = new Date(iso + "T00:00:00"); const d = new Date(iso + "T00:00:00");
return iso.slice(5, 7) + "/" + iso.slice(8, 10) + "(" + WD[d.getDay()] + ")"; return iso.slice(5, 7) + "/" + iso.slice(8, 10) + "(" + WD[d.getDay()] + ")";
}; };
m.body.innerHTML = '<div class="perf-ev-wrap"><table class="perf-table perf-detail-table"><thead><tr><th class="perf-th-label">날짜</th>' + const table = function (t) {
cols.map(function (c) { return "<th>" + esc(c) + "</th>"; }).join("") + "</tr></thead><tbody>" + const tcols = t.columns || cols;
res.rows.map(function (r) { return '<div class="perf-ev-wrap"><table class="perf-table perf-detail-table"><thead><tr><th class="perf-th-label">날짜</th>' +
return '<tr><th class="perf-td-label" scope="row">' + esc(day(r.date)) + "</th>" + tcols.map(function (c) { return "<th>" + esc(c) + "</th>"; }).join("") + "</tr></thead><tbody>" +
cols.map(function (c) { return '<td class="perf-num">' + cell((r.values || {})[c]) + "</td>"; }).join("") + "</tr>"; (t.rows || []).map(function (r) {
}).join("") + '</tbody><tfoot><tr class="perf-row-total"><th class="perf-td-label" scope="row">합계</th>' + return '<tr><th class="perf-td-label" scope="row">' + esc(day(r.date)) + "</th>" +
cols.map(function (c) { return '<td class="perf-num">' + cell((res.total || {})[c]) + "</td>"; }).join("") + tcols.map(function (c) { return '<td class="perf-num">' + cell((r.values || {})[c]) + "</td>"; }).join("") + "</tr>";
"</tr></tfoot></table></div>" + }).join("") + '</tbody><tfoot><tr class="perf-row-total"><th class="perf-td-label" scope="row">합계</th>' +
'<p class="perf-muted">합계: 숫자 항목은 더한 값, 클릭률 = 클릭수 ÷ 노출수, 광고수익률·ROAS = 날짜별 값을 광고비로 가중 평균.</p>'; tcols.map(function (c) { return '<td class="perf-num">' + cell((t.total || {})[c]) + "</td>"; }).join("") +
"</tr></tfoot></table></div>";
};
const foot = '<p class="perf-muted">합계: 숫자 항목은 더한 값, 클릭률 = 클릭수 ÷ 노출수, 광고수익률·ROAS = 날짜별 값을 광고비로 가중 평균.</p>';
const tabs = res.tabs || [];
if (tabs.length < 2) { m.body.innerHTML = table(res) + foot; return; }
// 여러 광고 계정을 합치는 채널(메타) — [합계 | 계정…] 탭. 계정 탭 = 그 계정이 광고를 낸 날만.
const missing = res.accounts_missing
? '<p class="perf-notice">' + fmt(res.accounts_missing) + "일은 계정별 자료가 없어 합계 탭에만 있습니다 — [" + esc(name) +
" 광고 불러오기]로 그 기간을 다시 가져오면 계정별로 나뉩니다.</p>"
: "";
m.body.innerHTML = '<div class="perf-quick perf-detail-tabs" role="tablist" aria-label="계정">' +
tabs.map(function (t, i) {
return '<button type="button" class="perf-seg' + (i ? "" : " is-active") + '" role="tab" aria-selected="' + (i ? "false" : "true") +
'" data-tab="' + i + '"' + (t.account_id ? ' title="act_' + esc(t.account_id) + '"' : "") + ">" + esc(t.label) + "</button>";
}).join("") + '</div><div class="perf-detail-tab-body"></div>' + missing + foot;
const bodyEl = m.body.querySelector(".perf-detail-tab-body");
const show = function (i) {
m.body.querySelectorAll(".perf-detail-tabs [data-tab]").forEach(function (b) {
const on = Number(b.dataset.tab) === i;
b.classList.toggle("is-active", on);
b.setAttribute("aria-selected", on ? "true" : "false");
});
bodyEl.innerHTML = table(tabs[i]) + (i ? '<p class="perf-muted">계정마다 따로 반올림해 계정 광고비의 합이 합계 탭과 1원 다를 수 있습니다.</p>' : "");
};
m.body.querySelector(".perf-detail-tabs").addEventListener("click", function (ev) {
const b = ev.target.closest("[data-tab]");
if (b) show(Number(b.dataset.tab));
});
show(0);
} catch (err) { } catch (err) {
m.body.innerHTML = '<p class="perf-notice is-warn">' + esc(err.message) + "</p>"; m.body.innerHTML = '<p class="perf-notice is-warn">' + esc(err.message) + "</p>";
} }
+6
View File
@@ -415,6 +415,12 @@
② `me/adaccounts`(이 토큰으로 보이는 계정)를 물어 원인 하나를 짚는다(`_diagnose`): ads_read 없음 → 토큰 재발급 / ② `me/adaccounts`(이 토큰으로 보이는 계정)를 물어 원인 하나를 짚는다(`_diagnose`): ads_read 없음 → 토큰 재발급 /
입력한 계정이 안 보임 → 시스템 사용자 [자산 할당]에서 광고 계정 배정 후 토큰 재발급 / 권한이 다른 계정에만 → 대상 포함해 재발급 / 입력한 계정이 안 보임 → 시스템 사용자 [자산 할당]에서 광고 계정 배정 후 토큰 재발급 / 권한이 다른 계정에만 → 대상 포함해 재발급 /
다 맞음 → 앱 쪽(비즈니스에 앱 연결·Marketing API 제품·제한 액세스면 토큰 주인이 앱 관리자·개발자인지). 진단 조회 실패는 무시(덧붙이는 정보). 다 맞음 → 앱 쪽(비즈니스에 앱 연결·Marketing API 제품·제한 액세스면 토큰 주인이 앱 관리자·개발자인지). 진단 조회 실패는 무시(덧붙이는 정보).
**상세보기 계정별 탭**(2026-10-16): 메타 머리글 상세보기 = [합계 | 계정…] 탭. 가져올 때 그날 메타 행 `metrics` 에 계정별 값을
예약 키 `_accounts`(`ad_sources.base.ACCOUNTS_KEY` — `{계정 ID: {name, amount, roas, metrics}}`, 이름 = insights `account_name`)로 함께 저장
(새 마이그레이션 없음). `ad_spend.detail_table` 은 `_` 로 시작하는 키를 표 열·합계·화면 값에서 뺀다. `ad_spend.detail_tabs` = 합계 탭 +
계정 탭(그 계정이 광고를 낸 날만, 이름 = 가장 최근 날 이름, 순서 = 기간 광고비 큰 계정부터) + `accounts_missing`(계정별 값 없이 광고비만 있는 날 —
계정별 저장 전에 가져온 날, 다시 불러오면 생김, 화면 안내). 계정마다 따로 반올림해 계정 광고비 합이 합계와 1원 다를 수 있다.
계정별 값이 없는 채널(네이버·구글)은 `tabs: []` → 예전 그대로 표 하나.
광고비 탭 불러오기에서 난 권한 오류엔 "[연결 테스트]가 원인을 진단" 안내를 붙인다(`_DIAG_HINT`). 광고비 탭 불러오기에서 난 권한 오류엔 "[연결 테스트]가 원인을 진단" 안내를 붙인다(`_DIAG_HINT`).
연결 테스트 문구는 **[진단]을 맨 앞에**, 메타 원문은 짧게(긴 안내 주소 뺌) 뒤에. 광고 연동 오류 문구 길이 한도는 `ad_sync.AD_MESSAGE_MAX`(1200자, 연결 테스트 문구는 **[진단]을 맨 앞에**, 메타 원문은 짧게(긴 안내 주소 뺌) 뒤에. 광고 연동 오류 문구 길이 한도는 `ad_sync.AD_MESSAGE_MAX`(1200자,
비밀값 가린 뒤) — 예전엔 공용 기본 300자에서 잘려 진단이 "[진…" 으로 끊겼다. 비밀값 가린 뒤) — 예전엔 공용 기본 300자에서 잘려 진단이 "[진…" 으로 끊겼다.
+29
View File
@@ -28,6 +28,17 @@ async function env(file) {
return { columns: ["총비용", "노출수", "클릭률(%)", "구매완료 광고수익률(%)"], total: { "총비용": 300000, "노출수": 30043, "클릭률(%)": 1.53, "구매완료 광고수익률(%)": 250.5 }, return { columns: ["총비용", "노출수", "클릭률(%)", "구매완료 광고수익률(%)"], total: { "총비용": 300000, "노출수": 30043, "클릭률(%)": 1.53, "구매완료 광고수익률(%)": 250.5 },
rows: [{ date: "2026-10-03", amount: 300000, roas: 250.5, values: { "총비용": 300000, "노출수": 30043, "클릭률(%)": 1.53, "구매완료 광고수익률(%)": 250.5 } }] }; } }; rows: [{ date: "2026-10-03", amount: 300000, roas: 250.5, values: { "총비용": 300000, "노출수": 30043, "클릭률(%)": 1.53, "구매완료 광고수익률(%)": 250.5 } }] }; } };
} }
if (/^\/performance\/api\/ad-spend\/meta\/details/.test(url)) { // 메타 — [합계 | 계정…] 탭(2026-10-16)
const tbl = function (amount, roas) {
return { columns: ["광고비(부가세 포함)", "ROAS(%)"], total: { "광고비(부가세 포함)": amount, "ROAS(%)": roas },
rows: [{ date: "2026-10-03", amount: amount, roas: roas, values: { "광고비(부가세 포함)": amount, "ROAS(%)": roas } }] };
};
return { ok: true, status: 200, json: async function () {
return Object.assign(tbl(165001, 400), { accounts_missing: e.metaMissing || 0, tabs: [
Object.assign({ key: "total", label: "합계" }, tbl(165001, 400)),
Object.assign({ key: "111", label: "본계정", account_id: "111" }, tbl(110000, 450)),
Object.assign({ key: "222", label: "서브<계정>", account_id: "222" }, tbl(55001, 300))] }); } };
}
if (/^\/performance\/api\/ad-spend\/upload/.test(url)) { if (/^\/performance\/api\/ad-spend\/upload/.test(url)) {
return { ok: true, status: 200, json: async function () { return { ok: true, status: 200, json: async function () {
return { ok: true, saved: 12, name: "쿠팡(로켓)", total: 2636494, from: "2026-10-01", to: "2026-10-12", empty_days: e.uploadEmpty || [] }; } }; return { ok: true, saved: 12, name: "쿠팡(로켓)", total: 2636494, from: "2026-10-01", to: "2026-10-12", empty_days: e.uploadEmpty || [] }; } };
@@ -235,6 +246,24 @@ function gross(td) { return td.querySelector(".v-gross").textContent.trim(); }
check("[네이버] 상세 표 = 날짜 + 보고서 항목(파일 순서), 날짜 mm/dd(요일)", ths.join(",") === "날짜,총비용,노출수,클릭률(%),구매완료 광고수익률(%)" && check("[네이버] 상세 표 = 날짜 + 보고서 항목(파일 순서), 날짜 mm/dd(요일)", ths.join(",") === "날짜,총비용,노출수,클릭률(%),구매완료 광고수익률(%)" &&
row.join(",") === "10/03(토),300,000,30,043,1.53,250.50", [ths, row]); row.join(",") === "10/03(토),300,000,30,043,1.53,250.50", [ths, row]);
check("[네이버] 맨 아래 합계 줄", /합계/.test(modal.querySelector("tfoot").textContent) && /30,043/.test(modal.querySelector("tfoot").textContent)); check("[네이버] 맨 아래 합계 줄", /합계/.test(modal.querySelector("tfoot").textContent) && /30,043/.test(modal.querySelector("tfoot").textContent));
check("[네이버] 계정 탭 없음(탭 자료 없는 채널)", !modal.querySelector(".perf-detail-tabs"));
}
// ── 메타 — 상세보기 [합계 | 계정…] 탭(2026-10-16) ──
{
const e = await env("perf_ads.html");
e.metaMissing = 2;
e.d.querySelector('.perf-main thead [data-detail-channel="meta"]').click(); await settle();
const modal = e.d.querySelector(".perf-modal");
const tabs = Array.from(modal.querySelectorAll(".perf-detail-tabs [data-tab]"));
const foot = function () { return modal.querySelector(".perf-detail-tab-body tfoot").textContent; };
check("[메타] 탭 = 합계 + 계정(이름은 글자 그대로, 계정 ID 는 말풍선)", tabs.map(function (b) { return b.textContent; }).join("|") === "합계|본계정|서브<계정>" &&
tabs[1].getAttribute("title") === "act_111" && !tabs[0].hasAttribute("title"), tabs.map(function (b) { return b.outerHTML; }));
check("[메타] 처음엔 합계 탭", tabs[0].classList.contains("is-active") && tabs[0].getAttribute("aria-selected") === "true" && /165,001/.test(foot()) &&
modal.querySelectorAll(".perf-detail-tab-body table").length === 1);
tabs[2].click();
check("[메타] 계정 탭 누르면 그 계정 표", tabs[2].classList.contains("is-active") && !tabs[0].classList.contains("is-active") &&
/55,001/.test(foot()) && /1원 다를 수/.test(modal.textContent));
check("[메타] 계정별 자료 없는 날 안내", /2일은 계정별 자료가 없어/.test(modal.textContent) && modal.textContent.indexOf("[메타 광고 불러오기]") >= 0);
} }
// ── 설정: 수동 입력 토글 ── // ── 설정: 수동 입력 토글 ──
{ {