feat(performance): 네이버 광고 보고서 업로드(ROAS·보고서 항목) + 머리글 클릭 일자별 상세

- 네이버 업로드: 3열 기간·4열 총비용(광고비)·12열 구매완료 광고수익률(ROAS), 나머지 항목은 metrics(JSONB)
- 네이버·구글·메타 칸 ROAS = 보고서 값(여러 날은 광고비 가중 평균), 쇼핑몰 매출로 계산하지 않음
- 네이버 머리글 클릭 → 지금 기간 일자별 보고서 표 + 합계(GET /api/ad-spend/naver/details)
- performance_db 마이그레이션 006: perf_ad_spend.roas·metrics

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-14 17:23:11 +09:00
parent 240d61c903
commit e9fb1c3407
15 changed files with 525 additions and 46 deletions
+1 -1
View File
File diff suppressed because one or more lines are too long
+179 -12
View File
@@ -7,6 +7,10 @@
쿠팡(윙)·쿠팡(로켓) 업로드 양식(2026-10-13·14 사용자 제공 — 둘 다 같은 쿠팡 광고 보고서 CSV/엑셀):
1행 머리글, 1열 = 날짜("2026년 10월 01일"), 19열 = 청구금액(+부가가치세) → 그날 광고비.
날짜 줄 아래 캠페인 줄(1열 빈 칸)과 맨 위 "전체" 합계 줄은 건너뛴다.
네이버 업로드 양식(2026-10-14 사용자 제공 — 네이버 광고 보고서 CSV/엑셀, 하루 한 줄):
1행 머리글, 3열 = 기간(날짜 "2026.09.30."), 4열 = 총비용 → 그날 광고비, 12열 = 구매완료 광고수익률(%) → 그날 ROAS.
나머지 열(노출수·클릭수·클릭률·전환수·구매완료 수·장바구니·총 전환매출액 …)은 머리글 이름 그대로 metrics 에 보관 —
화면에서 네이버 머리글을 누르면 일자별 표(마이그레이션 006: perf_ad_spend.roas·metrics).
HTTP·DB 와 무관한 순수 함수(읽기·조립) — 라우터가 파일 바이트와 저장소를 넘긴다.
"""
@@ -17,7 +21,7 @@ import csv
import io
from dataclasses import dataclass, field
from datetime import date
from decimal import ROUND_HALF_UP, Decimal
from decimal import ROUND_HALF_UP, Decimal, InvalidOperation
from typing import Any, Callable, Mapping, Sequence
from . import calc
@@ -42,9 +46,11 @@ CHANNELS: tuple[tuple[str, str], ...] = (
CHANNEL_NAMES = dict(CHANNELS)
CHANNEL_CODES = tuple(c for c, _ in CHANNELS)
# ROAS(매출 ÷ 광고비 × 100) 의 매출 = 이 쇼핑몰 매출 실적 총매출. 쿠팡(윙)은 매출 쪽 코드가 coupang.
# 구글·메타는 ROAS 를 계산하지 않는다 — ROAS 값을 따로 넣는다(2026-10-14 사용자 요청).
NO_ROAS = frozenset({"google", "meta"})
ROAS_SALES_CODE: dict[str, str] = {c: c for c in CHANNEL_CODES if c not in NO_ROAS}
# 구글·메타·네이버는 ROAS 를 계산하지 않는다 — 광고 보고서의 ROAS 값을 따로 넣는다(perf_ad_spend.roas, 2026-10-14).
# 여러 날(주·월·합계)의 ROAS = Σ(그날 ROAS × 그날 광고비) ÷ Σ광고비(ROAS 가 있는 날만) = 광고 매출 합 ÷ 광고비 합.
FILE_ROAS = frozenset({"google", "meta", "naver"})
NO_ROAS = FILE_ROAS # 예전 이름(계산 안 하는 채널)
ROAS_SALES_CODE: dict[str, str] = {c: c for c in CHANNEL_CODES if c not in FILE_ROAS}
ROAS_SALES_CODE["coupang_wing"] = "coupang"
@@ -56,12 +62,32 @@ def roas(sales: int, spend: int) -> int | None:
def roas_basis(code: str) -> str:
"""머리글 말풍선 — ROAS 에 쓰는 매출(구글·메타는 빈 값 = 계산 안 함)."""
"""머리글 말풍선 — ROAS 에 쓰는 매출(구글·메타·네이버는 빈 값 = 계산 안 함, 보고서 값)."""
return "" if code not in ROAS_SALES_CODE else CHANNEL_NAMES.get(code, code)
def channel_roas(code: str, sales_of: Callable[[str], int], spend: int) -> int | None:
"""채널 칸의 ROAS — 구글·메타는 늘 None(계산 안 함)."""
def file_roas(code: str, file_roas_map: Mapping[tuple[date, str], Any], spends: Mapping[tuple[date, str], int],
s: date, e: date) -> int | None:
"""보고서 ROAS 채널의 기간 ROAS — Σ(ROAS × 광고비) ÷ Σ광고비(ROAS 가 있고 광고비가 있는 날만)."""
rev = Decimal(0)
spend = 0
for (d, c), r in file_roas_map.items():
if c != code or not s <= d <= e or r is None:
continue
amt = int(spends.get((d, c)) or 0)
if amt > 0:
rev += Decimal(str(r)) * amt
spend += amt
if spend <= 0:
return None
return int((rev / spend).quantize(Decimal(1), rounding=ROUND_HALF_UP))
def channel_roas(code: str, sales_of: Callable[[str], int], spend: int,
file_of: Callable[[str], int | None] | None = None) -> int | None:
"""채널 칸의 ROAS — 쇼핑몰 매출 ÷ 광고비. 구글·메타·네이버는 보고서 ROAS(file_of), 없으면 None."""
if code in FILE_ROAS:
return file_of(code) if file_of else None
mcode = ROAS_SALES_CODE.get(code)
return None if mcode is None else roas(sales_of(mcode), spend)
@@ -70,8 +96,14 @@ ROCKET_AMOUNT_COL = 18 # 19열 청구금액(+부가가치세)
SKIP_LABELS = frozenset({"전체", "합계", "총계", "날짜"})
NAVER_DATE_COL = 2 # 3열 기간(날짜)
NAVER_AMOUNT_COL = 3 # 4열 총비용
NAVER_ROAS_COL = 11 # 12열 구매완료 광고수익률(%)
NAVER_SKIP_COLS = (0, 1, 2) # 광고 계정 이름·ID·기간은 metrics 에 넣지 않음
class AdMigrationNeeded(Exception):
"""광고비 표(마이그레이션 005: perf_ad_spend)가 아직 없음."""
"""광고비 표(마이그레이션 005: perf_ad_spend) 또는 ROAS·상세 칸(006)이 아직 없음."""
@dataclass
@@ -79,6 +111,10 @@ class ParseResult:
entries: list[tuple[date, int]] = field(default_factory=list) # (날짜, 금액)
errors: list[str] = field(default_factory=list)
skipped: int = 0 # 건너뛴 줄(캠페인 줄·합계 줄)
# 보고서 ROAS·상세 항목(네이버) — 날짜 → ROAS(%) · {머리글: 값}. 비어 있으면 금액만 저장.
roas: dict[date, Decimal] = field(default_factory=dict)
metrics: dict[date, dict[str, Any]] = field(default_factory=dict)
columns: list[str] = field(default_factory=list) # 상세 항목 머리글(파일 순서)
# ════════════════════════════════════════════════════════════
@@ -162,10 +198,133 @@ def parse_coupang_rocket(content: bytes, *, today: date, filename: str = "") ->
return res
def _number(value: Any) -> Decimal | None:
"""숫자 칸 → Decimal(쉼표·%·원 허용). 빈 칸이면 None, 숫자가 아니면 ValueError."""
if value is None or (isinstance(value, str) and not value.strip()):
return None
if isinstance(value, bool):
raise ValueError
text = str(value).replace(",", "").replace("%", "").replace("원", "").strip()
try:
num = Decimal(text)
except InvalidOperation:
raise ValueError from None
if not num.is_finite():
raise ValueError
return num
def _json_num(num: Decimal | None) -> Any:
if num is None:
return None
return int(num) if num == num.to_integral_value() else float(round(num, 2))
def parse_naver(content: bytes, *, today: date, filename: str = "") -> ParseResult:
"""네이버 광고 보고서 → (날짜, 총비용) + 그날 ROAS(12열) + 나머지 항목. 잘못된 줄이 있으면 errors."""
rows = read_rows(content, filename)
res = ParseResult()
header: tuple[Any, ...] = ()
seen: dict[date, int] = {}
for r, row in enumerate(rows, start=1):
raw_day = row[NAVER_DATE_COL] if len(row) > NAVER_DATE_COL else None
text = str(raw_day or "").strip()
if not text or text.replace(" ", "") in SKIP_LABELS:
res.skipped += 1
continue
try:
day = parse_date(raw_day)
except ValueError:
if not header: # 머리글(1행 "기간")
header = tuple(str(h or "").strip() for h in row)
res.columns = [h for i, h in enumerate(header) if i not in NAVER_SKIP_COLS and h]
res.skipped += 1
continue
res.errors.append(f"{r}행 3열: 날짜를 읽을 수 없습니다({text[:30]}).")
continue
if day is None:
res.skipped += 1
continue
try:
amt = parse_amount(row[NAVER_AMOUNT_COL] if len(row) > NAVER_AMOUNT_COL else None)
except ValueError:
res.errors.append(f"{r}행 4열: 총비용이 숫자가 아닙니다.")
continue
try:
ro = _number(row[NAVER_ROAS_COL] if len(row) > NAVER_ROAS_COL else None)
except ValueError:
res.errors.append(f"{r}행 12열: 광고수익률(ROAS)이 숫자가 아닙니다.")
continue
if amt is None:
res.errors.append(f"{r}행 4열: {day.isoformat()} 총비용이 비어 있습니다.")
elif abs(amt) > MAX_AMOUNT or (ro is not None and abs(ro) > Decimal("10000000")):
res.errors.append(f"{r}행: 금액·ROAS 가 너무 큽니다.")
elif day > today:
res.errors.append(f"{r}행: 앞으로의 날짜({day.isoformat()})는 입력할 수 없습니다.")
elif day in seen:
res.errors.append(f"{r}행: {day.isoformat()} 이 {seen[day]}행과 겹칩니다.")
else:
seen[day] = r
res.entries.append((day, amt))
if ro is not None:
res.roas[day] = ro
m: dict[str, Any] = {}
for i, v in enumerate(row):
name = header[i] if i < len(header) else f"{i + 1}열"
if i in NAVER_SKIP_COLS or not name:
continue
try:
m[name] = _json_num(_number(v))
except ValueError:
m[name] = str(v)[:100]
res.metrics[day] = m
if len(res.entries) > MAX_DATA_ROWS:
raise UploadError(f"한 번에 {MAX_DATA_ROWS:,}일까지 올릴 수 있습니다.")
if len(res.errors) > MAX_ERRORS:
break
if not res.entries and not res.errors:
raise UploadError("광고비 날짜 줄이 없습니다. 3열 기간(예: 2026.09.30.), 4열 총비용, 12열 광고수익률 양식인지 확인하세요.")
return res
# 업로드 양식이 정해진 채널 → 파일 읽기 함수(채널 순서 = 업로드 창 선택 순서). 쿠팡(윙)도 로켓과 같은 양식(2026-10-14).
PARSERS: dict[str, Callable[..., ParseResult]] = {"coupang_wing": parse_coupang_rocket, "coupang_rocket": parse_coupang_rocket}
PARSERS: dict[str, Callable[..., ParseResult]] = {
"naver": parse_naver, "coupang_wing": parse_coupang_rocket, "coupang_rocket": parse_coupang_rocket}
_COUPANG_HELP = "쿠팡 광고 보고서(CSV 또는 엑셀) — 1열 날짜, 19열 청구금액(+부가가치세)을 그날 광고비로 넣습니다."
UPLOAD_HELP = {"coupang_wing": _COUPANG_HELP, "coupang_rocket": _COUPANG_HELP}
UPLOAD_HELP = {
"naver": "네이버 광고 보고서(CSV 또는 엑셀) — 3열 기간(날짜), 4열 총비용 = 그날 광고비, 12열 구매완료 광고수익률 = ROAS. "
"나머지 항목은 네이버 머리글을 누르면 일자별로 볼 수 있습니다.",
"coupang_wing": _COUPANG_HELP, "coupang_rocket": _COUPANG_HELP}
# 머리글을 누르면 일자별 상세 표가 열리는 채널(보고서 항목을 보관하는 채널)
DETAIL_CHANNELS = frozenset({"naver"})
def detail_table(rows: list[dict[str, Any]]) -> dict[str, Any]:
"""일자별 상세(GET /api/ad-spend/{channel}/details) — rows: date·amount·roas·metrics(저장소).
열 = 파일 머리글 순서(처음 나온 순), 합계 = 숫자 열 합 + 클릭률·ROAS 는 가중 평균."""
cols: list[str] = []
for r in rows:
for k in (r.get("metrics") or {}):
if k not in cols:
cols.append(k)
sums: dict[str, Decimal] = {}
for r in rows:
for k, v in (r.get("metrics") or {}).items():
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()}
for k in cols:
if "클릭률" in k and sums.get("노출수"):
total[k] = float(round(sums.get("클릭수", Decimal(0)) * 100 / sums["노출수"], 2))
elif ("수익률" in k or "ROAS" in k.upper()):
spend = sum(int(r.get("amount") or 0) for r in rows if r.get("roas") is not None and int(r.get("amount") or 0) > 0)
rev = sum(Decimal(str(r["roas"])) * int(r.get("amount") or 0) for r in rows
if r.get("roas") is not None and int(r.get("amount") or 0) > 0)
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]
return {"columns": cols, "rows": out_rows, "total": total}
# ════════════════════════════════════════════════════════════
@@ -194,6 +353,11 @@ def build_ad_dashboard(store: Any, *, kind: str, anchor: date, today: date,
except AdMigrationNeeded:
amounts, sources, migration_needed = {}, {}, True
cells = {k: calc.Money(gross=int(v)) for k, v in amounts.items()}
roas_reader = getattr(store, "ad_roas", None)
try:
roas_map = roas_reader(q_start, q_end) if roas_reader and not migration_needed else {}
except AdMigrationNeeded:
roas_map = {}
cur = calc.sum_range(cells, codes, period.start, period.end)
prev = calc.sum_range(cells, codes, cmp_start, cmp_end)
@@ -257,11 +421,13 @@ def build_ad_dashboard(store: Any, *, kind: str, anchor: date, today: date,
for row in table:
s = date.fromisoformat(row["from"]) if row.get("from") else period.start
e = date.fromisoformat(row["to"]) if row.get("to") else period.end
row["roas"] = {c: channel_roas(c, lambda m: sales_sum([m], s, e), row["cells"][c]["gross"]) for c in codes}
row["roas"] = {c: channel_roas(c, lambda m: sales_sum([m], s, e), row["cells"][c]["gross"],
lambda f: file_roas(f, roas_map, amounts, s, e)) for c in codes}
row["roas_total"] = roas(sales_sum(total_codes, s, e), row["total"]["gross"]) if total_codes else None
m_s, m_e = month_period.start, month_period.end
for r in month["rows"]:
r["roas"] = channel_roas(r["code"], lambda m: sales_sum([m], m_s, m_e), r["gross"])
r["roas"] = channel_roas(r["code"], lambda m: sales_sum([m], m_s, m_e), r["gross"],
lambda f: file_roas(f, roas_map, amounts, m_s, m_e))
month["total"]["roas"] = roas(sales_sum(total_codes, m_s, m_e), month["total"]["gross"]) if total_codes else None
year = calc.year_months(year_period.start.year, codes, cells, today=today)
for i, r in enumerate(year["rows"], start=1):
@@ -280,6 +446,7 @@ def build_ad_dashboard(store: Any, *, kind: str, anchor: date, today: date,
"month": month,
"year": year,
"roas_basis": {c: roas_basis(c) for c in codes},
"detail_channels": sorted(DETAIL_CHANNELS),
"chart_daily": calc.daily_series(period, codes, cells),
"chart_share": [{"code": c, "name": CHANNEL_NAMES[c], **share[c].as_dict()} for c in codes],
# 업로드로 들어온 칸(표시용) — "날짜|채널"
+59 -11
View File
@@ -396,31 +396,79 @@ class PerformanceDBStore:
self.set_ad_spend_bulk(code, [(day, amount)], source=source, user=user)
def set_ad_spend_bulk(self, code: str, entries: list[tuple[date, int | None]], *, source: str = "manual",
user: str = "") -> int:
"""여러 날을 한 트랜잭션으로(같은 날은 덮어씀, 금액 None 은 지움). 하나라도 실패하면 모두 취소."""
user: str = "", roas: dict[date, Any] | None = None,
metrics: dict[date, dict[str, Any]] | None = None) -> int:
"""여러 날을 한 트랜잭션으로(같은 날은 덮어씀, 금액 None 은 지움). 하나라도 실패하면 모두 취소.
roas·metrics 를 주면(보고서 업로드, 마이그레이션 006) 그 날의 ROAS·상세 항목도 덮어쓴다 — 안 주면(직접 입력) 그대로 둔다."""
from .ad_spend import AdMigrationNeeded # noqa: WPS433
if not entries:
return 0
report = roas is not None or metrics is not None
try:
with self._pool.connection() as conn:
with conn.transaction():
with conn.cursor() as cur:
gone = [(code, d) for d, a in entries if a is None]
keep = [(code, d, int(a), source, user) for d, a in entries if a is not None]
if gone:
cur.executemany("DELETE FROM perf_ad_spend WHERE channel_code = %s AND spend_date = %s", gone)
if keep:
cur.executemany(
"INSERT INTO perf_ad_spend (channel_code, spend_date, amount, source, updated_by) "
"VALUES (%s, %s, %s, %s, %s) ON CONFLICT (channel_code, spend_date) DO UPDATE "
"SET amount = EXCLUDED.amount, source = EXCLUDED.source, updated_by = EXCLUDED.updated_by",
keep,
)
if report:
keep6 = [(code, d, int(a), source, user, (roas or {}).get(d),
Jsonb((metrics or {}).get(d)) if (metrics or {}).get(d) is not None else None)
for d, a in entries if a is not None]
if keep6:
cur.executemany(
"INSERT INTO perf_ad_spend (channel_code, spend_date, amount, source, updated_by, roas, metrics) "
"VALUES (%s, %s, %s, %s, %s, %s, %s) ON CONFLICT (channel_code, spend_date) DO UPDATE "
"SET amount = EXCLUDED.amount, source = EXCLUDED.source, updated_by = EXCLUDED.updated_by, "
"roas = EXCLUDED.roas, metrics = EXCLUDED.metrics",
keep6,
)
else:
keep = [(code, d, int(a), source, user) for d, a in entries if a is not None]
if keep:
cur.executemany(
"INSERT INTO perf_ad_spend (channel_code, spend_date, amount, source, updated_by) "
"VALUES (%s, %s, %s, %s, %s) ON CONFLICT (channel_code, spend_date) DO UPDATE "
"SET amount = EXCLUDED.amount, source = EXCLUDED.source, updated_by = EXCLUDED.updated_by",
keep,
)
except pg_errors.UndefinedTable:
raise AdMigrationNeeded() from None
raise AdMigrationNeeded("005") from None
except pg_errors.UndefinedColumn:
raise AdMigrationNeeded("006") from None
return len(entries)
def ad_roas(self, start: date, end: date) -> dict[tuple[date, str], Decimal]:
"""(날짜, 채널) → 보고서 ROAS(%) — 값이 있는 칸만. 005·006 미적용이면 빈 값(화면은 ROAS 없이)."""
try:
with self._pool.connection() as conn:
rows = conn.execute(
"SELECT spend_date, channel_code, roas FROM perf_ad_spend "
"WHERE spend_date BETWEEN %s AND %s AND roas IS NOT NULL", (start, end),
).fetchall()
except (pg_errors.UndefinedTable, pg_errors.UndefinedColumn):
return {}
return {(r["spend_date"], r["channel_code"]): r["roas"] for r in rows}
def ad_details(self, code: str, start: date, end: date) -> list[dict[str, Any]]:
"""한 채널의 일자별 광고비·ROAS·보고서 항목(날짜 순). 006 미적용이면 AdMigrationNeeded."""
from .ad_spend import AdMigrationNeeded # noqa: WPS433
try:
with self._pool.connection() as conn:
rows = conn.execute(
"SELECT spend_date, amount, roas, metrics, source FROM perf_ad_spend "
"WHERE channel_code = %s AND spend_date BETWEEN %s AND %s ORDER BY spend_date",
(code, start, end),
).fetchall()
except pg_errors.UndefinedTable:
raise AdMigrationNeeded("005") from None
except pg_errors.UndefinedColumn:
raise AdMigrationNeeded("006") from None
return [{"date": r["spend_date"].isoformat(), "amount": int(r["amount"]), "roas": r["roas"],
"metrics": r["metrics"] or {}, "source": r["source"]} for r in rows]
def daily_breakdown(self, code: str, start: date, end: date, *, id_prefix: str = "") -> list[dict[str, Any]]:
"""쇼핑몰 화면(일별 매출내역) 대조용 — 날짜별 결제(SALE 합·건수)·환불(그 밖, 양수)·마지막 수집 시각.
id_prefix 가 있으면 이 어댑터가 다른 쇼핑몰 열로 보낸 사건까지 합친다(카페24 화면 합계와 같은 범위)."""
+35 -6
View File
@@ -15,7 +15,9 @@ JSON API — 모듈 권한
GET /performance/api/manual-sales/sample.xlsx 수동 입력 엑셀 업로드 샘플(모듈 폴더 upload_sample.xlsx)
POST /performance/api/manual-sales/upload 수동 입력 엑셀 업로드(1열 날짜, 2열부터 쇼핑몰 이름 머리글)
PUT /performance/api/ad-spend/{channel}/{day} 광고비 한 칸 저장/지움(오늘까지)
POST /performance/api/ad-spend/upload?channel= 광고비 파일 업로드(쿠팡(로켓) 광고 보고서 — 1열 날짜, 19열 청구금액)
POST /performance/api/ad-spend/upload?channel= 광고비 파일 업로드(쿠팡 윙·로켓 광고 보고서 1열 날짜·19열 청구금액,
네이버 광고 보고서 3열 기간·4열 총비용·12열 ROAS + 나머지 항목)
GET /performance/api/ad-spend/{channel}/details?from=&to= 일자별 보고서 항목(네이버 머리글 클릭)
JSON API — 관리자
PUT /performance/api/marketplaces/{code} 사용/매출 집계/수동 입력 여부
POST /performance/api/marketplaces/{code}/rates 수수료율(적용 시작일)
@@ -55,6 +57,12 @@ MAX_MANUAL_AMOUNT = 10 ** 12 # 수동 입력 한 칸 상한(원)
MANUAL_SAMPLE_PATH = Path(__file__).resolve().parent / "upload_sample.xlsx"
AD_MIGRATION_HELP = ("광고비를 쓰려면 performance_db 마이그레이션 005(scripts/sql/performance_db_005_ad_spend.sql)를 "
"먼저 적용해야 합니다.")
AD_MIGRATION_HELP_006 = ("광고 보고서 ROAS·상세 항목을 쓰려면 performance_db 마이그레이션 006"
"(scripts/sql/performance_db_006_ad_roas_metrics.sql)을 먼저 적용해야 합니다.")
def _ad_migration_help(exc: Exception) -> str:
return AD_MIGRATION_HELP_006 if "006" in str(exc) else AD_MIGRATION_HELP
MANUAL_MIGRATION_HELP = ("수동 입력을 쓰려면 performance_db 마이그레이션 002(scripts/sql/performance_db_002_manual_sales.sql)를 "
"먼저 적용해야 합니다.")
@@ -425,12 +433,32 @@ def api_ad_spend(request: Request, channel: str, day: str, payload: dict[str, An
raise HTTPException(status_code=400, detail="금액이 너무 큽니다.")
try:
store.set_ad_spend(channel, d, amount, source="manual", user=user.get("email", ""))
except AdMigrationNeeded:
raise HTTPException(status_code=503, detail=AD_MIGRATION_HELP) from None
except AdMigrationNeeded as exc:
raise HTTPException(status_code=503, detail=_ad_migration_help(exc)) from None
return JSONResponse({"ok": True, "channel": channel, "date": d.isoformat(), "manual": amount,
"amount": amount or 0})
@router.get("/api/ad-spend/{channel}/details")
def api_ad_spend_details(request: Request, channel: str, from_: str = Query(..., alias="from"), to: str = Query(...)) -> JSONResponse:
"""일자별 보고서 항목(네이버 — 노출수·클릭수·전환수 …) + 광고비·ROAS. 최대 366일."""
from . import ad_spend # noqa: WPS433
store, _ = common.require_store(request)
_ad_channel(channel)
if channel not in ad_spend.DETAIL_CHANNELS:
raise HTTPException(status_code=400, detail="이 채널은 일자별 상세 자료가 없습니다.")
start, end = _parse_date(from_, field="시작일"), _parse_date(to, field="종료일")
if start is None or end is None or end < start or (end - start).days > 365:
raise HTTPException(status_code=400, detail="기간을 확인하세요(최대 366일).")
try:
rows = store.ad_details(channel, start, end)
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)})
@router.post("/api/ad-spend/upload")
def api_ad_spend_upload(request: Request, channel: str = Query(...), file: UploadFile = File(...)) -> JSONResponse:
"""광고비 파일 업로드 — 파일에 있는 날만 덮어쓴다. 잘못된 줄이 있으면 아무것도 저장하지 않는다."""
@@ -451,10 +479,11 @@ def api_ad_spend_upload(request: Request, channel: str = Query(...), file: Uploa
return JSONResponse(status_code=400, content={
"detail": f"잘못된 줄이 {len(res.errors)}개 있어 아무것도 저장하지 않았습니다. 고친 뒤 다시 올려 주세요.",
"errors": res.errors})
report = {"roas": res.roas, "metrics": res.metrics} if (res.roas or res.metrics) else {}
try:
saved = store.set_ad_spend_bulk(channel, list(res.entries), source="upload", user=user.get("email", ""))
except ad_spend.AdMigrationNeeded:
raise HTTPException(status_code=503, detail=AD_MIGRATION_HELP) from None
saved = store.set_ad_spend_bulk(channel, list(res.entries), source="upload", user=user.get("email", ""), **report)
except ad_spend.AdMigrationNeeded as exc:
raise HTTPException(status_code=503, detail=_ad_migration_help(exc)) from None
days = sorted(d for d, _ in res.entries)
return JSONResponse({"ok": True, "saved": saved, "channel": channel, "name": ad_spend.CHANNEL_NAMES[channel],
"total": sum(a for _, a in res.entries), "skipped": res.skipped,
@@ -1,6 +1,6 @@
{% extends "erp_base.html" %}
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261014a" />{% endblock %}
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261014b" />{% endblock %}
{#- ROAS 덧붙임 — "광고비(ROAS%)". 광고비가 없으면 아무것도 안 붙는다. -#}
{%- macro roas(p) -%}{%- if p is not none -%}<span class="perf-roas">({{ "{:,}".format(p) }}%)</span>{%- endif -%}{%- endmacro -%}
@@ -82,7 +82,7 @@
<thead>
<tr>
<th class="perf-th-label">{% if period_kind == 'year' %}월{% else %}날짜{% endif %}</th>
{% for c in codes %}<th title="{{ names[c] }} — 날짜 칸을 눌러 광고비 입력.{% if roas_basis[c] %} 괄호 = ROAS({{ roas_basis[c] }} 매출 ÷ 광고비){% else %} ROAS 는 계산하지 않음(따로 입력){% endif %}">{{ names[c] }} <span class="perf-manual-mark" aria-hidden="true">✎</span></th>{% endfor %}
{% for c in codes %}{% if c in detail_channels %}<th class="perf-th-detail" title="{{ names[c] }} — 눌러 일자별 광고 보고서 항목 보기. 괄호 = 보고서 ROAS(구매완료 광고수익률)"><button type="button" class="perf-detail-btn" data-detail-channel="{{ c }}">{{ names[c] }} <span class="material-symbols-outlined" aria-hidden="true">table_view</span></button></th>{% else %}<th title="{{ names[c] }} — 날짜 칸을 눌러 광고비 입력.{% if roas_basis[c] %} 괄호 = ROAS({{ roas_basis[c] }} 매출 ÷ 광고비){% else %} ROAS 는 계산하지 않음(따로 입력){% endif %}">{{ names[c] }} <span class="perf-manual-mark" aria-hidden="true">✎</span></th>{% endif %}{% endfor %}
<th class="perf-th-total">{% if period_kind == 'year' %}월 합계{% else %}일 합계{% endif %}</th>
</tr>
</thead>
@@ -111,7 +111,8 @@
</div>
{% if period_kind != 'year' %}
<p class="perf-muted perf-manual-help">날짜 칸을 눌러 그날 <b>광고비</b>를 직접 입력합니다 — Enter 저장 후 아래 칸, Esc 취소, 비우고 저장하면 지움.
칸은 <b>광고비(ROAS%)</b> — ROAS = 그 쇼핑몰 매출 실적 총매출 ÷ 광고비(합계 열은 전체 매출). 구글·메타는 ROAS 를 계산하지 않습니다.
칸은 <b>광고비(ROAS%)</b> — ROAS = 그 쇼핑몰 매출 실적 총매출 ÷ 광고비(합계 열은 전체 매출). 구글·메타는 ROAS 를 계산하지 않고,
네이버는 광고 보고서의 ROAS(구매완료 광고수익률)를 씁니다 — 네이버 머리글을 누르면 일자별 보고서 항목.
파란 숫자 = 직접 입력, 주황 숫자 = 파일 업로드 값. 쿠팡(윙)·쿠팡(로켓)은 [파일 업로드]로 광고 보고서를 올리면 날짜별로 한 번에 들어갑니다.</p>
{% endif %}
</div>
@@ -190,7 +191,7 @@
</div>
<p class="perf-foot perf-muted">
광고비 기준: 쿠팡(윙)·쿠팡(로켓)은 광고 보고서의 청구금액(+부가가치세). ROAS = 그 쇼핑몰 매출 ÷ 광고비 × 100(구글·메타는 계산 안 함).
광고비 기준: 쿠팡(윙)·쿠팡(로켓)은 광고 보고서의 청구금액(+부가가치세). ROAS = 그 쇼핑몰 매출 ÷ 광고비 × 100(구글·메타는 계산 안 함, 네이버는 보고서 값).
매출 대비 광고비 = 같은 기간 광고비 ÷ 매출 실적 총매출.
구글·메타는 지금은 직접 입력합니다.
</p>
@@ -205,9 +206,12 @@
"today": today,
"manual_api": "/performance/api/ad-spend/",
"manual_word": "광고비",
"period_start": period.start.isoformat(),
"period_end": period.end.isoformat(),
"period_label": period.label,
"empty_text": "기간 내 광고비가 없습니다.",
"upload_channels": upload_channels
} | tojson }}</script>
{% endblock %}
{% block scripts %}<script src="/static/performance.js?v=20261014a" defer></script>{% endblock %}
{% block scripts %}<script src="/static/performance.js?v=20261014b" defer></script>{% endblock %}
@@ -1,6 +1,6 @@
{% extends "erp_base.html" %}
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261014a" />{% endblock %}
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261014b" />{% 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=20261014a" defer></script>{% endblock %}
{% block scripts %}<script src="/static/performance.js?v=20261014b" defer></script>{% endblock %}
@@ -1,6 +1,6 @@
{% extends "erp_base.html" %}
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261014a" />{% endblock %}
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261014b" />{% endblock %}
{%- macro when(v) -%}{{ (v or '')[:16] | replace('T', ' ') or '—' }}{%- endmacro -%}
@@ -204,4 +204,4 @@
</section>
{% endblock %}
{% block scripts %}<script src="/static/performance.js?v=20261014a" defer></script>{% endblock %}
{% block scripts %}<script src="/static/performance.js?v=20261014b" defer></script>{% endblock %}
+123 -2
View File
@@ -4,6 +4,7 @@ from __future__ import annotations
import io
from datetime import date
from decimal import Decimal
import openpyxl
import pytest
@@ -97,7 +98,8 @@ def test_ad_dashboard_month():
assert k["spend"]["value"] == 270000 and k["ratio"]["pct"] == 10.0 # 270,000 ÷ 2,700,000
assert k["ytd"]["value"] == 370000 and k["mtd"]["value"] == 270000
assert ctx["upload_cells"] == ["2026-10-01|coupang_rocket"]
assert [c["code"] for c in ctx["upload_channels"]] == ["coupang_wing", "coupang_rocket"]
assert [c["code"] for c in ctx["upload_channels"]] == ["naver", "coupang_wing", "coupang_rocket"]
assert ctx["detail_channels"] == ["naver"]
day1 = next(r for r in ctx["table"] if r.get("date") == "2026-10-01")
assert day1["cells"]["coupang_rocket"]["gross"] == 220000 and day1["total"]["gross"] == 220000
assert ctx["table"][-1]["kind"] == "total" and ctx["table"][-1]["total"]["gross"] == 270000
@@ -142,7 +144,8 @@ def test_ad_spend_endpoints(monkeypatch):
def __init__(self):
self.saved, self.missing = [], False
def set_ad_spend_bulk(self, code, entries, *, source="manual", user=""):
def set_ad_spend_bulk(self, code, entries, *, source="manual", user="", roas=None, metrics=None):
self.report = (roas, metrics)
if self.missing:
raise ads.AdMigrationNeeded()
self.saved.extend((code, d, a, source) for d, a in entries)
@@ -182,3 +185,121 @@ def test_ad_spend_endpoints(monkeypatch):
store.missing = True
r = client.put("/performance/api/ad-spend/meta/2026-10-12", json={"amount": 1})
assert r.status_code == 503 and "005" in r.json()["detail"]
# 사용자 제공 네이버 광고 보고서(2026-10-14) — 앞 9줄 + 머리글
NAVER_CSV = """광고 계정 이름,광고 계정 ID,기간,총비용,노출수,클릭수,클릭률(%),총 전환수,구매완료 수,장바구니 담기 수,총 전환매출액,구매완료 광고수익률(%)
0_미라네주방,38461,2026.09.30.,0,0,0,0.00,46,6,40,8218000,0.00
0_미라네주방,38461,2026.09.24.,0,0,0,0.00,36,6,30,6331500,0.00
0_미라네주방,38461,2026.09.23.,300672,30043,461,1.53,71,13,58,7830100,67.58
0_미라네주방,38461,2026.09.22.,299817,31061,441,1.42,125,20,105,15040200,198.79
0_미라네주방,38461,2026.09.21.,299199,25641,416,1.62,159,44,115,19878020,501.11
"""
def test_naver_report_reads_date_cost_roas_and_metrics():
for content, name in ((NAVER_CSV.encode("utf-8-sig"), "n.csv"), (NAVER_CSV.encode("cp949"), "n.csv"), (_xlsx(NAVER_CSV), "n.xlsx")):
res = ads.parse_naver(content, today=TODAY, filename=name)
assert not res.errors, res.errors
assert res.entries[:3] == [(date(2026, 9, 30), 0), (date(2026, 9, 24), 0), (date(2026, 9, 23), 300672)]
assert str(res.roas[date(2026, 9, 23)]) == "67.58" and res.roas[date(2026, 9, 30)] == 0
m = res.metrics[date(2026, 9, 21)]
assert m["노출수"] == 25641 and m["클릭률(%)"] == 1.62 and m["총 전환매출액"] == 19878020
assert m["구매완료 광고수익률(%)"] == 501.11 and "광고 계정 이름" not in m and "기간" not in m
assert res.columns[0] == "총비용" and res.columns[-1] == "구매완료 광고수익률(%)"
bad = NAVER_CSV + "0_미라네주방,38461,2026.09.22.,1,0,0,0,0,0,0,0,1\n0_미라네주방,38461,2026.09.20.,abc,0,0,0,0,0,0,0,1\n"
bad += "0_미라네주방,38461,2026.09.19.,5,0,0,0,0,0,0,0,x\n0_미라네주방,38461,2026.10.20.,5,0,0,0,0,0,0,0,1\n"
errs = " / ".join(ads.parse_naver(bad.encode("utf-8"), today=TODAY).errors)
assert "겹칩니다" in errs and "총비용이 숫자가 아닙니다" in errs and "ROAS" in errs and "앞으로의 날짜" in errs
def test_naver_roas_from_report_weighted():
"""네이버 칸 ROAS = 보고서 값(계산 안 함), 여러 날 = Σ(ROAS×광고비)÷Σ광고비, 광고비 0 인 날은 빼고."""
class S(_Store):
def ad_amounts(self, start, end):
rows = {(date(2026, 9, 22), "naver"): 299817, (date(2026, 9, 23), "naver"): 300672,
(date(2026, 9, 24), "naver"): 0}
rows = {k: v for k, v in rows.items() if start <= k[0] <= end}
return rows, {k: "upload" for k in rows}
def ad_roas(self, start, end):
rows = {(date(2026, 9, 22), "naver"): Decimal("198.79"), (date(2026, 9, 23), "naver"): Decimal("67.58"),
(date(2026, 9, 24), "naver"): Decimal("0")}
return {k: v for k, v in rows.items() if start <= k[0] <= end}
def daily_amounts(self, start, end, codes):
return {(date(2026, 9, 22), "naver"): 9_999_999} if "naver" in codes else {}
ctx = ads.build_ad_dashboard(S(), kind="week", anchor=date(2026, 9, 23), today=TODAY, sales_codes=["naver"])
by = {r.get("date"): r for r in ctx["table"]}
assert by["2026-09-22"]["roas"]["naver"] == 199 and by["2026-09-23"]["roas"]["naver"] == 68
assert by["2026-09-24"]["roas"]["naver"] is None # 광고비 0
week = next(r for r in ctx["table"] if r["kind"] == "week")
want = round((Decimal("198.79") * 299817 + Decimal("67.58") * 300672) / (299817 + 300672))
assert week["roas"]["naver"] == want == 133 # 매출 실적(9,999,999)으로 계산하지 않음
assert ctx["roas_basis"]["naver"] == ""
assert {r["code"]: r for r in ctx["month"]["rows"]}["naver"]["roas"] == 133
def test_naver_detail_table_totals():
rows = [{"date": "2026-09-22", "amount": 299817, "roas": Decimal("198.79"),
"metrics": {"총비용": 299817, "노출수": 31061, "클릭수": 441, "클릭률(%)": 1.42, "구매완료 광고수익률(%)": 198.79}},
{"date": "2026-09-23", "amount": 300672, "roas": Decimal("67.58"),
"metrics": {"총비용": 300672, "노출수": 30043, "클릭수": 461, "클릭률(%)": 1.53, "구매완료 광고수익률(%)": 67.58}},
{"date": "2026-09-24", "amount": 0, "roas": Decimal("0"), "metrics": {"총비용": 0, "노출수": 0, "클릭수": 0,
"클릭률(%)": 0.0, "구매완료 광고수익률(%)": 0}}]
t = ads.detail_table(rows)
assert t["columns"] == ["총비용", "노출수", "클릭수", "클릭률(%)", "구매완료 광고수익률(%)"]
assert t["total"]["총비용"] == 600489 and t["total"]["노출수"] == 61104 and t["total"]["클릭수"] == 902
assert t["total"]["클릭률(%)"] == round(902 * 100 / 61104, 2) # 가중: 클릭수 ÷ 노출수
assert t["total"]["구매완료 광고수익률(%)"] == 133.09 # 광고비 가중 평균 (198.79×299,817 + 67.58×300,672) ÷ 600,489
assert t["rows"][0]["values"]["노출수"] == 31061 and t["rows"][1]["roas"] == 67.58
def test_naver_upload_and_details_endpoints(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")
class Store:
def __init__(self):
self.saved, self.kw, self.missing = [], {}, ""
def set_ad_spend_bulk(self, code, entries, *, source="manual", user="", roas=None, metrics=None):
if self.missing:
raise ads.AdMigrationNeeded(self.missing)
self.saved.extend((code, d, a, source) for d, a in entries)
self.kw = {"roas": roas, "metrics": metrics}
return len(entries)
def ad_details(self, code, start, end):
if self.missing:
raise ads.AdMigrationNeeded(self.missing)
return [{"date": "2026-09-23", "amount": 300672, "roas": Decimal("67.58"), "metrics": {"노출수": 30043}}]
store = Store()
monkeypatch.setattr(common, "require_store", lambda request, admin=False: (store, {"email": "king@x"}))
monkeypatch.setattr(perf_router, "today_kst", lambda: TODAY)
app = FastAPI()
app.include_router(perf_router.router)
client = TestClient(app)
r = client.post("/performance/api/ad-spend/upload?channel=naver", files={"file": ("n.csv", NAVER_CSV.encode("utf-8-sig"))})
assert r.status_code == 200, r.text
assert r.json()["saved"] == 5 and r.json()["total"] == 300672 + 299817 + 299199
assert store.saved[2] == ("naver", date(2026, 9, 23), 300672, "upload")
assert str(store.kw["roas"][date(2026, 9, 23)]) == "67.58" and store.kw["metrics"][date(2026, 9, 21)]["클릭수"] == 416
store.saved.clear()
r = client.post("/performance/api/ad-spend/upload?channel=coupang_rocket", files={"file": ("r.csv", ROCKET_CSV.encode("utf-8-sig"))})
assert r.status_code == 200 and store.kw == {"roas": None, "metrics": None} # 쿠팡은 금액만
d = client.get("/performance/api/ad-spend/naver/details?from=2026-09-01&to=2026-09-30").json()
assert d["name"] == "네이버" and d["columns"] == ["노출수"] and d["rows"][0]["roas"] == 67.58
assert client.get("/performance/api/ad-spend/coupang_rocket/details?from=2026-09-01&to=2026-09-30").status_code == 400
assert client.get("/performance/api/ad-spend/naver/details?from=2026-09-30&to=2026-09-01").status_code == 400
store.missing = "006"
r = client.post("/performance/api/ad-spend/upload?channel=naver", files={"file": ("n.csv", NAVER_CSV.encode("utf-8"))})
assert r.status_code == 503 and "006" in r.json()["detail"]
assert "006" in client.get("/performance/api/ad-spend/naver/details?from=2026-09-01&to=2026-09-30").json()["detail"]
+6
View File
@@ -62,6 +62,12 @@ a.perf-tab.is-active:link, a.perf-tab.is-active:visited { color: #fff; }
.perf-roas { margin-left: 2px; font-size: 11px; font-weight: 500; color: var(--color-midtone-gray); }
.perf-row-total .perf-roas { color: #bbb; }
.perf .perf-main td.is-editing .perf-roas { visibility: hidden; }
/* 네이버 머리글 = 일자별 보고서 항목 보기 버튼 */
.perf-detail-btn { display: inline-flex; align-items: center; gap: 3px; border: 0; background: transparent; font: inherit;
font-weight: 600; color: var(--perf-ad); cursor: pointer; padding: 2px 4px; border-radius: 6px; }
.perf-detail-btn .material-symbols-outlined { font-size: 16px; }
.perf-detail-btn:hover { background: #fff1ea; text-decoration: underline; }
.perf-detail-table th, .perf-detail-table td { white-space: nowrap; }
.perf-ad-upload-btn { margin-left: auto; }
.perf-kpi-pct { font-size: 26px; font-weight: 700; }
+36
View File
@@ -379,6 +379,42 @@
});
});
// 광고 보고서 일자별 상세(네이버 머리글) — 지금 보는 기간의 날마다 광고비·ROAS·보고서 항목, 맨 아래 합계.
root.addEventListener("click", async function (e) {
const btn = e.target.closest("[data-detail-channel]");
if (!btn) return;
const code = btn.dataset.detailChannel;
const name = (data.names || {})[code] || code;
const m = openModal(name + " 광고 보고서 · " + (data.period_label || ""), { wide: true });
m.body.innerHTML = '<p class="perf-muted">불러오는 중…</p>';
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; }
const cols = res.columns || [];
const cell = function (v) {
if (v == null || v === "") return '<span class="perf-zero">–</span>';
return typeof v === "number" ? (Number.isInteger(v) ? fmt(v) : v.toLocaleString("ko-KR", { minimumFractionDigits: 2, maximumFractionDigits: 2 })) : esc(v);
};
const WD = ["일", "월", "화", "수", "목", "금", "토"];
const day = function (iso) {
const d = new Date(iso + "T00:00:00");
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>' +
cols.map(function (c) { return "<th>" + esc(c) + "</th>"; }).join("") + "</tr></thead><tbody>" +
res.rows.map(function (r) {
return '<tr><th class="perf-td-label" scope="row">' + esc(day(r.date)) + "</th>" +
cols.map(function (c) { return '<td class="perf-num">' + cell((r.values || {})[c]) + "</td>"; }).join("") + "</tr>";
}).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>';
} catch (err) {
m.body.innerHTML = '<p class="perf-notice is-warn">' + esc(err.message) + "</p>";
}
});
// 직접선택 / 쇼핑몰 필터
const customBtn = document.getElementById("perf-custom-btn");
const customForm = document.getElementById("perf-custom");
+14
View File
@@ -197,6 +197,20 @@ docker exec postgres-db psql -U postgres -d performance_db -c "\d perf_ad_spend"
되돌리기(광고비 데이터만 사라짐): `docker exec postgres-db psql -U postgres -d performance_db -c "DROP TABLE perf_ad_spend;"`
## 실적 광고비 ROAS·보고서 항목 마이그레이션 (performance_db 006)
006은 `perf_ad_spend` 에 `roas`·`metrics` 열 두 개만 더한다(기존 값 그대로, 다시 실행 가능). 005 다음에 적용한다.
미적용이면 네이버 보고서 업로드·네이버 일자별 상세만 503 안내, 나머지 광고비 화면은 그대로.
```bash
cd /opt/www/main
docker exec postgres-db pg_dump -U postgres performance_db > ~/performance_db_before_006_$(date +%Y%m%d%H%M).sql
docker exec -i postgres-db psql -v ON_ERROR_STOP=1 -U postgres -d performance_db < scripts/sql/performance_db_006_ad_roas_metrics.sql
docker exec postgres-db psql -U postgres -d performance_db -c "\d perf_ad_spend"
```
되돌리기(보고서 ROAS·상세만 사라짐): `docker exec postgres-db psql -U postgres -d performance_db -c "ALTER TABLE perf_ad_spend DROP COLUMN metrics, DROP COLUMN roas;"`
## 회의록 작업 등록 표 — 작업 칸 마이그레이션 (026)
026은 `goal_meeting_tasks.parent_task_id` 열만 추가한다(기존 값 그대로, 다시 실행 가능). 025 뒤에 적용한다. 미적용이면 작업 칸을 고를 때만 503 안내.
+7 -1
View File
@@ -345,7 +345,8 @@
연간은 월)·일별 추이·채널 비중·월/연 누적. 채널(2026-10-14) = 구글·메타·네이버·쿠팡(윙)·쿠팡(로켓)·오늘의집·G마켓·카카오·GS샵·11번가·롯데ON·토스·애터미아자몰
(`ad_spend.CHANNELS`, 앱이 정함 — 쇼핑몰 채널 코드는 실적 쇼핑몰 코드와 같고 쿠팡(윙)만 `coupang_wing`).
모든 칸 직접 입력 가능, 칸 표시 = **광고비(ROAS%)** — ROAS = 그 칸 기간의 매출 실적 총매출 ÷ 광고비 × 100(정수 반올림,
`ad_spend.roas`). 매출 쇼핑몰 = `ROAS_SALES_CODE`(같은 쇼핑몰, 쿠팡(윙) = `coupang`). **구글·메타는 ROAS 계산 안 함**(`NO_ROAS` — ROAS 값을 따로 넣을 예정, 2026-10-14),
`ad_spend.roas`). 매출 쇼핑몰 = `ROAS_SALES_CODE`(같은 쇼핑몰, 쿠팡(윙) = `coupang`). **구글·메타·네이버는 ROAS 계산 안 함**(`FILE_ROAS` — 광고 보고서의 ROAS 값, `perf_ad_spend.roas`, 마이그레이션 006;
여러 날 = Σ(그날 ROAS × 광고비) ÷ Σ광고비, 광고비 0 인 날 제외 — `file_roas`),
합계 열·월/연 누적 = 매출 실적에 들어가는 쇼핑몰 전체 매출. 광고비가 없는 칸은 ROAS 없음. 광고비를 고치면 옛 ROAS 는 지우고 새로고침 때 다시 계산.
KPI: 기간 광고비(전기간 대비), 매출 대비 광고비(같은 기간 광고비 ÷ 매출 실적 총매출), 월·연 누적.
저장 `perf_ad_spend`(마이그레이션 005 — 채널 × 날짜 하나에 금액, `source` manual/upload/api), 미적용이면 화면에 안내·API 503.
@@ -353,6 +354,11 @@
- [파일 업로드](`POST /api/ad-spend/upload?channel=`) — 양식이 정해진 채널만(`ad_spend.PARSERS`). 파일에 있는 날만 덮어쓰고(주황 숫자),
잘못된 줄이 하나라도 있으면 아무것도 저장하지 않는다. **쿠팡(윙)·쿠팡(로켓)**(같은 양식, 윙은 2026-10-14) = 쿠팡 광고 보고서 CSV(UTF-8/CP949)·엑셀:
1열 날짜(`2026년 10월 01일`), 19열 청구금액(+부가가치세). "전체" 합계 줄·머리글·캠페인 줄(1열 빈 칸)은 건너뜀.
- **네이버**(2026-10-14) = 네이버 광고 보고서 CSV·엑셀(하루 한 줄): 3열 기간(`2026.09.30.`), 4열 총비용 = 광고비,
12열 구매완료 광고수익률(%) = 그날 ROAS(`roas`), 나머지 항목(노출수·클릭수·클릭률·전환수·구매완료 수·장바구니·총 전환매출액 …)은
머리글 이름 그대로 `metrics`(JSONB). 광고 계정 이름·ID 는 넣지 않음. 직접 입력으로 광고비를 고쳐도 ROAS·상세는 그대로.
- **네이버 머리글 클릭** → 지금 보는 기간의 일자별 보고서 표(`GET /api/ad-spend/naver/details?from=&to=`, `ad_spend.detail_table`):
열 = 파일 머리글 순서, 맨 아래 합계(숫자 항목은 합, 클릭률 = 클릭수 ÷ 노출수, 광고수익률 = 총비용 가중 평균). `DETAIL_CHANNELS`.
- 구글·메타 업로드 양식/API 는 아직 — 지금은 직접 입력.
- **대시보드** `/performance/?period=day|week|month|year|custom&d=&from=&to=&m=<쇼핑몰>…`
기간 버튼(오늘/이번주/이번달/올해/직접선택) + 이전/다음, 쇼핑몰 필터, KPI 5개, 일자×쇼핑몰 표(주간합계·기간합계, 연간은 월 행),
@@ -0,0 +1,21 @@
-- =====================================================================
-- performance_db 마이그레이션 006 — 광고비 ROAS·보고서 상세 항목
-- =====================================================================
-- 멱등(idempotent). perf_ad_spend 에 열 두 개만 추가(기존 행·값 그대로). 005 다음에 적용.
-- docker exec -i postgres-db psql -v ON_ERROR_STOP=1 -U postgres -d performance_db \
-- < scripts/sql/performance_db_006_ad_roas_metrics.sql
--
-- 왜(2026-10-14 사용자 요청): 네이버 광고 보고서 업로드 — 12열 구매완료 광고수익률(%)을 그날 ROAS 로(roas),
-- 나머지 항목(노출수·클릭수·클릭률·전환수·구매완료 수·장바구니·총 전환매출액 …)은 머리글 이름 그대로(metrics)
-- 보관해 네이버 머리글을 누르면 일자별 표로 본다. 구글·메타도 나중에 같은 칸에 ROAS 를 넣는다.
-- 되돌리기: ALTER TABLE perf_ad_spend DROP COLUMN metrics, DROP COLUMN roas; (보고서 ROAS·상세만 사라짐 — 실행 전 백업)
-- =====================================================================
BEGIN;
ALTER TABLE perf_ad_spend ADD COLUMN IF NOT EXISTS roas NUMERIC(14, 2);
ALTER TABLE perf_ad_spend ADD COLUMN IF NOT EXISTS metrics JSONB;
COMMENT ON COLUMN perf_ad_spend.roas IS '광고 보고서의 ROAS(%) — 구글·메타·네이버(계산하지 않고 보고서 값). NULL = 없음';
COMMENT ON COLUMN perf_ad_spend.metrics IS '광고 보고서 그날 나머지 항목 {머리글: 값} — 네이버 노출수·클릭수·전환수 등';
COMMIT;
SELECT 'performance_db 006 ad roas/metrics ready' AS status;
+26 -3
View File
@@ -23,6 +23,11 @@ async function env(file) {
const isForm = o && o.body && typeof o.body !== "string";
const body = o && o.body && !isForm ? JSON.parse(o.body) : null;
e.calls.push({ method: method, url: url, body: body, form: isForm ? o.body : null });
if (/^\/performance\/api\/ad-spend\/naver\/details/.test(url)) {
return { ok: true, status: 200, json: async function () {
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 } }] }; } };
}
if (/^\/performance\/api\/ad-spend\/upload/.test(url)) {
return { ok: true, status: 200, json: async function () {
return { ok: true, saved: 12, name: "쿠팡(로켓)", total: 2636494, from: "2026-10-01", to: "2026-10-12" }; } };
@@ -143,7 +148,7 @@ function gross(td) { return td.querySelector(".v-gross").textContent.trim(); }
{
const e = await env("perf_ads.html");
check("[광고비] 광고비 탭이 고른 탭", e.d.querySelector(".perf-tab-ads").classList.contains("is-active"));
const heads = Array.from(e.d.querySelectorAll(".perf-main thead th")).map(function (th) { return th.textContent.replace("✎", "").trim(); });
const heads = Array.from(e.d.querySelectorAll(".perf-main thead th")).map(function (th) { return th.textContent.replace("✎", "").replace("table_view", "").trim(); });
check("[광고비] 열 = 구글·메타·네이버·쿠팡(윙)·쿠팡(로켓)·오늘의집·G마켓·카카오·GS샵·11번가·롯데ON·토스·애터미아자몰",
heads.join(",") === "날짜,구글,메타,네이버,쿠팡(윙),쿠팡(로켓),오늘의집,G마켓,카카오,GS샵,11번가,롯데ON,토스,애터미아자몰,일 합계", heads);
const wing = cell(e, "coupang_wing", "2026-10-05");
@@ -154,7 +159,7 @@ function gross(td) { return td.querySelector(".v-gross").textContent.trim(); }
!up.classList.contains("is-manual") && man.classList.contains("is-manual") && gross(up) === "220,000");
check("[광고비] 앞으로의 날은 입력 칸 아님", !cell(e, "google", "2026-10-08") && !!cell(e, "google", "2026-10-07"));
const kpi = Array.from(e.d.querySelectorAll(".perf-kpi-value")).map(function (n) { return n.textContent.trim(); });
check("[광고비] KPI — 이번달 광고비 299,000 · 매출 대비 비율", kpi[0] === "₩299,000" && /%$/.test(kpi[1]), kpi);
check("[광고비] KPI — 이번달 광고비 599,000(네이버 300,000 포함) · 매출 대비 비율", kpi[0] === "₩599,000" && /%$/.test(kpi[1]), kpi);
wing.click();
const wi = wing.querySelector(".perf-manual-input");
wi.value = "30000";
@@ -182,7 +187,8 @@ function gross(td) { return td.querySelector(".v-gross").textContent.trim(); }
e.d.getElementById("perf-ad-upload").click();
const modal = e.d.querySelector(".perf-modal");
const opts = Array.from(modal.querySelectorAll(".perf-ad-channel option")).map(function (o) { return o.value; });
check("[업로드] 채널 선택 = 양식이 정해진 쿠팡(윙)·쿠팡(로켓)", opts.join(",") === "coupang_wing,coupang_rocket", opts);
check("[업로드] 채널 선택 = 양식이 정해진 네이버·쿠팡(윙)·쿠팡(로켓)", opts.join(",") === "naver,coupang_wing,coupang_rocket", opts);
check("[업로드] 네이버 안내 = 3열 기간·4열 총비용·12열 ROAS", /3열 기간.*4열 총비용.*12열/.test(modal.querySelector(".perf-ad-help").textContent));
modal.querySelector(".perf-ad-channel").value = "coupang_rocket";
modal.querySelector(".perf-ad-channel").dispatchEvent(new e.w.Event("change"));
check("[업로드] 양식 안내(19열 청구금액)", /19열/.test(modal.querySelector(".perf-ad-help").textContent));
@@ -195,6 +201,23 @@ function gross(td) { return td.querySelector(".v-gross").textContent.trim(); }
check("[업로드] POST /api/ad-spend/upload?channel=coupang_rocket (파일)", post && post.url === "/performance/api/ad-spend/upload?channel=coupang_rocket" && !!post.form, e.calls);
check("[업로드] 결과 안내(12일 반영)", /12일 반영/.test(modal.querySelector(".perf-upload-result").textContent));
}
// ── 네이버 — 보고서 ROAS 표시 · 머리글 → 일자별 보고서 항목 ──
{
const e = await env("perf_ads.html");
const nv = cell(e, "naver", "2026-10-03");
check("[네이버] 칸 = 광고비(보고서 ROAS 반올림)", nv.textContent.trim() === "300,000(251%)", nv.textContent);
const hb = e.d.querySelector('.perf-main thead [data-detail-channel="naver"]');
check("[네이버] 머리글 = 상세 보기 버튼(다른 채널은 아님)", !!hb && e.d.querySelectorAll(".perf-main thead [data-detail-channel]").length === 1);
hb.click(); await settle();
const call = e.calls.find(function (c) { return /\/details/.test(c.url); });
check("[네이버] 지금 기간으로 상세 요청", call && call.url === "/performance/api/ad-spend/naver/details?from=2026-10-01&to=2026-10-31", e.calls);
const modal = e.d.querySelector(".perf-modal");
const ths = Array.from(modal.querySelectorAll("thead th")).map(function (t) { return t.textContent; });
const row = Array.from(modal.querySelectorAll("tbody tr")[0].children).map(function (t) { return t.textContent; });
check("[네이버] 상세 표 = 날짜 + 보고서 항목(파일 순서), 날짜 mm/dd(요일)", ths.join(",") === "날짜,총비용,노출수,클릭률(%),구매완료 광고수익률(%)" &&
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));
}
// ── 설정: 수동 입력 토글 ──
{
const e = await env("perf_settings.html");
+5 -1
View File
@@ -59,10 +59,14 @@ class FakeStore:
def ad_amounts(self, start, end):
rows = {(date(2026, 10, 1), "coupang_rocket"): (220000, "upload"), (date(2026, 10, 2), "google"): (50000, "manual"),
(date(2026, 10, 5), "coupang_wing"): (29000, "manual")}
(date(2026, 10, 5), "coupang_wing"): (29000, "manual"), (date(2026, 10, 3), "naver"): (300000, "upload")}
rows = {k: v for k, v in rows.items() if start <= k[0] <= end}
return {k: v[0] for k, v in rows.items()}, {k: v[1] for k, v in rows.items()}
def ad_roas(self, start, end):
rows = {(date(2026, 10, 3), "naver"): Decimal("250.5")}
return {k: v for k, v in rows.items() if start <= k[0] <= end}
def env() -> jinja2.Environment:
e = jinja2.Environment(loader=jinja2.ChoiceLoader([