Files
dbx-main/app/modules/performance/tests/test_ad_spend.py
T
king e9fb1c3407 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>
2026-10-14 17:23:11 +09:00

306 lines
19 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""광고비 — 쿠팡(로켓) 광고 보고서 읽기(CSV·엑셀) · 화면 데이터 조립."""
from __future__ import annotations
import io
from datetime import date
from decimal import Decimal
import openpyxl
import pytest
from app.modules.performance import ad_spend as ads
from app.modules.performance.manual_upload import UploadError
TODAY = date(2026, 10, 13)
# 사용자 제공 양식(2026-10-13) 그대로 — 머리글, "전체" 합계 줄, 날짜 줄 + 그 아래 캠페인 줄
ROCKET_CSV = """날짜,배송유형,부가세 유형,생성자,담당자,광고 유형,광고 목표,캠페인 ID,캠페인명,청구가능 금액 유형,예산 유형,광고 예산,소진 광고비,소진 광고비 중 조정 금액,조정 후 소진 광고비,초과 소진 금액,청구 가능 광고비,부가가치세,청구금액(+부가가치세)
전체,RETAIL,,,,,,,,,,,2400506,0,2400506,2396813,2396813,239681,2636494
2026년 10월 01일,RETAIL,Taxable,,,,,,,,,,200404,0,200404,200000,200000,20000,220000
,,,,VENDOR,PA,매출 성장,103529103,[쿠팡로켓] 스마트AI,Adcost,DAILY_SOFT,200000,200404,0,200404,200000,200000,,
2026년 10월 06일,RETAIL,Taxable,,,,,,,,,,196997,0,196997,196997,196997,19700,216697
,,,,VENDOR,PA,매출 성장,103529103,[쿠팡로켓] 스마트AI,Adcost,DAILY_SOFT,200000,196997,0,196997,196997,196997,,
2026년 10월 12일,RETAIL,Taxable,,,,,,,,,,200210,0,200210,200210,200210,20021,220231
,,,,VENDOR,PA,매출 성장,103529103,[쿠팡로켓] 스마트AI,Adcost,DAILY_SOFT,200000,200210,0,200210,200210,200210,,
"""
def _xlsx(text: str) -> bytes:
wb = openpyxl.Workbook()
ws = wb.active
for line in text.strip().splitlines():
ws.append([int(v) if v.isdigit() else (v or None) for v in line.split(",")])
buf = io.BytesIO()
wb.save(buf)
return buf.getvalue()
@pytest.mark.parametrize("content,name", [
(ROCKET_CSV.encode("utf-8-sig"), "report.csv"),
(ROCKET_CSV.encode("cp949"), "report.csv"),
(_xlsx(ROCKET_CSV), "report.xlsx"),
])
def test_rocket_report_reads_date_and_col19(content, name):
res = ads.parse_coupang_rocket(content, today=TODAY, filename=name)
assert not res.errors
assert res.entries == [(date(2026, 10, 1), 220000), (date(2026, 10, 6), 216697), (date(2026, 10, 12), 220231)]
assert res.skipped == 5 # 머리글 + 전체 + 캠페인 줄 3개
def test_rocket_report_errors_block_everything():
bad = ROCKET_CSV + "2026년 10월 06일,RETAIL,Taxable,,,,,,,,,,1,0,1,1,1,0,9\n" # 같은 날 두 번
bad += "2026년 13월 40일,RETAIL,,,,,,,,,,,1,0,1,1,1,0,1\n" # 날짜 오류
bad += "2026년 10월 07일,RETAIL,,,,,,,,,,,1,0,1,1,1,0,\n" # 금액 빈 칸
bad += "2026년 10월 20일,RETAIL,,,,,,,,,,,1,0,1,1,1,0,5\n" # 앞으로의 날짜
res = ads.parse_coupang_rocket(bad.encode("utf-8"), today=TODAY)
joined = " / ".join(res.errors)
assert len(res.errors) == 4, res.errors
assert "겹칩니다" in joined and "날짜를 읽을 수 없습니다" in joined and "비어 있습니다" in joined and "앞으로의 날짜" in joined
def test_rocket_report_wrong_file():
with pytest.raises(UploadError):
ads.parse_coupang_rocket(b"", today=TODAY)
with pytest.raises(UploadError): # 날짜 줄이 하나도 없음
ads.parse_coupang_rocket("날짜,금액\n전체,3\n".encode("utf-8"), today=TODAY)
other = ads.parse_coupang_rocket("이름,금액\n홍길동,3\n".encode("utf-8"), today=TODAY) # 다른 양식 → 줄 오류
assert not other.entries and "날짜를 읽을 수 없습니다" in other.errors[0]
with pytest.raises(UploadError):
ads.parse_coupang_rocket(b"PK\x03\x04broken", today=TODAY, filename="x.xlsx")
class _Store:
def __init__(self, missing=False):
self.missing = missing
def ad_amounts(self, start, end):
if self.missing:
raise ads.AdMigrationNeeded()
rows = {(date(2026, 10, 1), "coupang_rocket"): (220000, "upload"),
(date(2026, 10, 2), "google"): (50000, "manual"),
(date(2026, 9, 1), "meta"): (100000, "manual")}
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 daily_amounts(self, start, end, codes):
rows = {(date(2026, 10, 5), "cafe24"): 2_700_000, (date(2026, 10, 1), "coupang_rocket"): 550_000,
(date(2026, 10, 3), "coupang_rocket"): 110_000}
return {k: v for k, v in rows.items() if start <= k[0] <= end and k[1] in codes}
def test_ad_dashboard_month():
ctx = ads.build_ad_dashboard(_Store(), kind="month", anchor=date(2026, 10, 7), today=date(2026, 10, 7),
sales_codes=["cafe24"])
assert ctx["codes"] == ["google", "meta", "naver", "coupang_wing", "coupang_rocket", "ohouse", "gmarket", "kakao",
"gsshop", "elevenst", "lotteon", "toss", "atomy"]
k = {x["key"]: x for x in ctx["kpis"]}
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"]] == ["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
# ROAS = 그 쇼핑몰 매출 ÷ 광고비 — 로켓 10/1: 550,000 ÷ 220,000 = 250%, 구글 10/2: 카페24 그날 매출 0 → 0%
assert day1["roas"]["coupang_rocket"] == 250 and day1["roas"]["google"] is None
day2 = next(r for r in ctx["table"] if r.get("date") == "2026-10-02")
assert day2["roas"]["google"] is None # 구글·메타는 ROAS 계산 안 함(따로 입력)
total = ctx["table"][-1]
assert total["roas"]["coupang_rocket"] == 300 and total["roas"]["google"] is None # 660,000÷220,000
assert total["roas_total"] == 1000 # 2,700,000 ÷ 270,000 (합계 = sales_codes)
m = {r["code"]: r for r in ctx["month"]["rows"]}
assert m["coupang_rocket"]["roas"] == 300 and m["naver"]["roas"] is None and ctx["month"]["total"]["roas"] == 1000
assert ctx["year"]["rows"][9]["roas"] == 1000 and ctx["year"]["rows"][10]["roas"] is None # 11월 = 앞으로
assert ctx["roas_basis"]["google"] == "" and ctx["roas_basis"]["coupang_wing"] == "쿠팡(윙)"
assert {r["code"]: r for r in ctx["month"]["rows"]}["google"]["roas"] is None
assert ads.roas(1, 3) == 33 and ads.roas(1, 200) == 1 and ads.roas(5, 0) is None # 0.5% 반올림 → 1
assert ctx["nav"]["quick"][2]["active"] # 이번달
def test_ad_dashboard_year_and_missing_table():
ctx = ads.build_ad_dashboard(_Store(), kind="year", anchor=date(2026, 10, 7), today=date(2026, 10, 7))
rows = {r["label"]: r for r in ctx["table"]}
assert rows["9월"]["total"]["gross"] == 100000 and rows["10월"]["total"]["gross"] == 270000
assert {x["key"]: x for x in ctx["kpis"]}["ratio"]["pct"] is None # 매출 없음
miss = ads.build_ad_dashboard(_Store(missing=True), kind="week", anchor=date(2026, 10, 7), today=date(2026, 10, 7))
assert miss["migration_needed"] and miss["kpis"][0]["value"] == 0
def test_ad_spend_endpoints(monkeypatch):
"""라우터: 업로드 정상 → 한 번에 저장(source=upload), 잘못된 줄 → 400 + 목록·저장 안 함, 양식 없는 채널 400,
칸 저장(source=manual)·지우기, 모르는 채널 404, 앞으로의 날 400, 005 미적용 503."""
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.missing = [], False
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)
return len(entries)
def set_ad_spend(self, code, day, amount, *, source="manual", user=""):
self.set_ad_spend_bulk(code, [(day, amount)], source=source, user=user)
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=coupang_rocket", files={"file": ("r.csv", ROCKET_CSV.encode("utf-8-sig"))})
assert r.status_code == 200, r.text
assert r.json()["saved"] == 3 and r.json()["total"] == 220000 + 216697 + 220231 and r.json()["to"] == "2026-10-12"
assert store.saved[0] == ("coupang_rocket", date(2026, 10, 1), 220000, "upload")
store.saved.clear()
r = client.post("/performance/api/ad-spend/upload?channel=coupang_wing", files={"file": ("w.csv", ROCKET_CSV.encode("utf-8-sig"))})
assert r.status_code == 200 and r.json()["name"] == "쿠팡(윙)" # 윙도 같은 양식
assert store.saved[0] == ("coupang_wing", date(2026, 10, 1), 220000, "upload") and len(store.saved) == 3
store.saved.clear()
bad = ROCKET_CSV + "2026년 10월 06일,RETAIL,,,,,,,,,,,1,0,1,1,1,0,9\n"
r = client.post("/performance/api/ad-spend/upload?channel=coupang_rocket", files={"file": ("r.csv", bad.encode("utf-8"))})
assert r.status_code == 400 and r.json()["errors"] and store.saved == []
r = client.post("/performance/api/ad-spend/upload?channel=google", files={"file": ("r.csv", b"x")})
assert r.status_code == 400 and "양식" in r.json()["detail"]
assert client.put("/performance/api/ad-spend/meta/2026-10-12", json={"amount": "33,000"}).json()["amount"] == 33000
assert client.put("/performance/api/ad-spend/meta/2026-10-11", json={"amount": ""}).status_code == 200
assert store.saved == [("meta", date(2026, 10, 12), 33000, "manual"), ("meta", date(2026, 10, 11), None, "manual")]
assert client.put("/performance/api/ad-spend/cafe24/2026-10-12", json={"amount": 1}).status_code == 404
assert client.put("/performance/api/ad-spend/meta/2026-10-14", json={"amount": 1}).status_code == 400
assert client.put("/performance/api/ad-spend/meta/2026-10-12", json={"amount": "abc"}).status_code == 400
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"]