Files
dbx-main/app/modules/performance/tests/test_ad_spend.py
T
king 67001f0a6e feat: 세부 업무 자동 협업자 없음·마감일 아이콘·담당자별 패널 날짜 + 광고비 13채널·ROAS
[Project]
- 세부 업무를 만들 때 만든 사람을 자동 협업자로 넣지 않음(고른 협업자만), 메인 업무는 그대로
- 업무 창 세부 업무 줄의 빈 마감일 아이콘을 협업자 아이콘처럼 늘 옅게
- 대시보드 담당자별 합계 패널 날짜 mm/dd(요일), 마감 지난 미완료는 빨간 굵은 글씨

[실적 — 광고비]
- 열: 구글·메타·네이버·쿠팡(윙)·쿠팡(로켓)·오늘의집·G마켓·카카오·GS샵·11번가·롯데ON·토스·애터미아자몰
- 칸 = 광고비(ROAS%), ROAS = 그 쇼핑몰 매출 ÷ 광고비(구글·메타 = 카페24), 월/연 누적에도 ROAS

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 10:57:30 +09:00

184 lines
11 KiB
Python

"""광고비 — 쿠팡(로켓) 광고 보고서 읽기(CSV·엑셀) · 화면 데이터 조립."""
from __future__ import annotations
import io
from datetime import date
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"]] == ["coupang_wing", "coupang_rocket"]
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"] == 0
total = ctx["table"][-1]
assert total["roas"]["coupang_rocket"] == 300 and total["roas"]["google"] == 5400 # 660,000÷220,000 · 2,700,000÷50,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"] == "카페24(자체몰)" and ctx["roas_basis"]["coupang_wing"] == "쿠팡(윙)"
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=""):
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"]