ef38140673
- 탭: [매출 실적](검정) · [광고비](주황) 큰 탭 + 맨 오른쪽 설정 톱니(Material Symbols settings)
- /performance/ads: 연·월·일 표(채널 × 날짜)·추이·비중·월/연 누적, 매출 대비 광고비 KPI
- 날짜 칸 직접 입력(PUT /api/ad-spend/{channel}/{day}), 쿠팡(로켓) 광고 보고서 업로드
(CSV/엑셀, 1열 날짜·19열 청구금액(+부가가치세), 잘못된 줄 있으면 전부 거절)
- performance_db 마이그레이션 005 perf_ad_spend
- 설정 화면 쇼핑몰 순서 jsdom 기대값을 003 열 순서로 갱신(기존 실패)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
165 lines
8.9 KiB
Python
165 lines
8.9 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):
|
|
return {(date(2026, 10, 5), "cafe24"): 2_700_000}
|
|
|
|
|
|
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", "coupang_wing", "coupang_rocket"]
|
|
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_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
|
|
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()
|
|
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/naver/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"]
|