Files
dbx-main/app/modules/performance/tests/test_ad_spend.py
T
king b397bdf83b feat(performance): 메타 광고 API 연동 — 광고비·구매 ROAS 자동 가져오기
- ad_sources/meta_ads.py + registry 한 줄: Meta Marketing API Insights(기본 v26.0),
  level=account·하루 단위, 광고 계정 여러 개를 날짜별로 합산, paging.next 따라감(graph.facebook.com 밖 주소 거부).
- 설정(실적 설정 → 광고 API 연동): 광고 계정 ID(여러 개)·액세스 토큰(암호화)·앱 시크릿(선택, appsecret_proof)·API 버전.
- 광고비 = 지출 금액 × 1.1(부가세 포함, 구글과 같은 기준), ROAS = 구매 전환값 ÷ 지출 금액(광고 관리자 구매 ROAS).
  구매 값은 omni_purchase → purchase → 픽셀 구매 중 처음 있는 것 하나(겹친 값 더하지 않음). 원화 계정만.
- 메타 오류 코드 안내(토큰 만료 190·권한 200·계정 ID 100·호출 한도), 오류 문구에 토큰·주소 미포함.
- 메타 머리글 = 일자별 보고서 표(DETAIL_CHANNELS), 화면 안내 문구·문서 갱신. 새 마이그레이션·환경변수 없음.
- 테스트: test_meta_ads.py(가짜 메타 서버, 실제 fetch_days → AdSyncService), 메타 연동 반영해 기존 테스트 기대값 갱신.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 13:09:43 +09:00

394 lines
25 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년 13월 40일,RETAIL,,,,,,,,,,,1,0,1,1,1,0,1\n" # 날짜 오류
bad += "2026년 10월 08일,RETAIL,,,,,,,,,,,1,0,1,1,1,0,abc\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) == 3, res.errors
assert "날짜를 읽을 수 없습니다" in joined and "숫자가 아닙니다" in joined and "앞으로의 날짜" in joined
def test_coupang_report_date_rows_col19_summed_empty_skipped():
"""쿠팡(윙) 보고서처럼 캠페인 줄에도 1열 날짜가 있고 19열이 비어 있어도 — 날짜가 있는 줄의 19열 값만, 같은 날은 더한다
(2026-10-14 사용자 확인: "쿠팡은 모두 1열에서 날짜가 있는 행의 19열 값"). 값이 한 줄도 없는 날은 empty_days."""
head = ROCKET_CSV.splitlines()[0]
wing = "\n".join([
head,
"2026-03-01,,,,VENDOR,PA,매출 성장,1,캠페인A,Adcost,DAILY_SOFT,1000,10,0,10,0,10,,", # 날짜 있고 19열 빈 줄
"2026-03-01,,,,VENDOR,PA,매출 성장,2,캠페인B,Adcost,DAILY_SOFT,1000,20,0,20,0,20,,",
"2026-03-01,RETAIL,Taxable,,,,,,,,,,30,0,30,30,30,3,33", # 값 있는 줄
"2026-03-01,RETAIL,Tax-free,,,,,,,,,,5,0,5,5,5,0,5", # 같은 날 값 한 줄 더 → 더함
"2026-03-02,,,,VENDOR,PA,매출 성장,1,캠페인A,Adcost,DAILY_SOFT,1000,10,0,10,0,10,,", # 값 없는 날
"2026-03-03,RETAIL,Taxable,,,,,,,,,,1,0,1,1,1,0,1,100", # 19열 = 1 (20열은 무시)
]) + "\n"
for content, name in ((wing.encode("utf-8"), "w.csv"), (_xlsx(wing), "w.xlsx")):
res = ads.parse_coupang_rocket(content, today=TODAY, filename=name)
assert not res.errors, res.errors
assert res.entries == [(date(2026, 3, 1), 38), (date(2026, 3, 3), 1)]
assert res.empty_days == [date(2026, 3, 2)]
# 청구금액이 한 줄도 없는 파일(날짜 줄만) — 오류 없이 넘어감(반영할 날 없음)
none = "\n".join([head, "2026-03-01,,,,VENDOR,PA,매출 성장,1,캠페인A,Adcost,DAILY_SOFT,1000,0,0,0,0,0,,",
"2026-03-02,,,,VENDOR,PA,매출 성장,1,캠페인A,Adcost,DAILY_SOFT,1000,0,0,0,0,0,,"]) + "\n"
r0 = ads.parse_coupang_rocket(_xlsx(none), today=TODAY, filename="march.xlsx")
assert r0.entries == [] and not r0.errors and r0.empty_days == [date(2026, 3, 1), date(2026, 3, 2)]
m, _ = ads.merge_results([("a.xlsx", 1.0, ads.parse_coupang_rocket(wing.encode("utf-8"), today=TODAY)),
("b.csv", 2.0, ads.ParseResult(entries=[(date(2026, 3, 2), 7)]))])
assert m.empty_days == [] and dict(m.entries)[date(2026, 3, 2)] == 7 # 다른 파일에 값이 있으면 빈 날 아님
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"] == ["google", "meta", "naver"] # 구글(2026-10-15)·메타(2026-10-16) = 광고 API 로 가져온 항목
assert ctx["api_cells"] == []
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,abc\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"]
def test_merge_results_newest_file_wins():
"""여러 파일 — 같은 날짜는 파일 날짜(수정 시각)가 최신인 파일 값, 같으면 나중 파일. ROAS·상세도 그 파일 것."""
a = ads.ParseResult(entries=[(date(2026, 9, 1), 100), (date(2026, 9, 2), 200)],
roas={date(2026, 9, 2): Decimal("10")}, metrics={date(2026, 9, 2): {"노출수": 1}}, columns=["노출수"])
b = ads.ParseResult(entries=[(date(2026, 9, 2), 999), (date(2026, 9, 3), 300)],
roas={date(2026, 9, 2): Decimal("99")}, metrics={date(2026, 9, 2): {"노출수": 9}}, columns=["노출수", "클릭수"])
m, overlap = ads.merge_results([("new.csv", 2000.0, a), ("old.csv", 1000.0, b)]) # a 가 최신
assert m.entries == [(date(2026, 9, 1), 100), (date(2026, 9, 2), 200), (date(2026, 9, 3), 300)]
assert m.roas[date(2026, 9, 2)] == Decimal("10") and m.metrics[date(2026, 9, 2)] == {"노출수": 1}
assert overlap == [date(2026, 9, 2)] and m.columns == ["노출수", "클릭수"]
m2, _ = ads.merge_results([("a.csv", 1000.0, a), ("b.csv", 1000.0, b)]) # 같은 시각 → 나중 파일
assert dict(m2.entries)[date(2026, 9, 2)] == 999
bad = ads.ParseResult(errors=["3행: 오류"])
m3, _ = ads.merge_results([("a.csv", 1.0, a), ("bad.csv", 2.0, bad)])
assert m3.errors == ["[bad.csv] 3행: 오류"]
def test_upload_multiple_files_endpoint(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:
saved: list = []
def set_ad_spend_bulk(self, code, entries, *, source="manual", user="", roas=None, metrics=None):
self.saved = list(entries)
self.roas = roas
return len(entries)
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)
old = NAVER_CSV
new = NAVER_CSV.replace("2026.09.23.,300672", "2026.09.23.,111111").replace(",67.58", ",12.34")
files = [("files", ("new.csv", new.encode("utf-8"))), ("files", ("old.csv", old.encode("utf-8")))]
r = client.post("/performance/api/ad-spend/upload?channel=naver", files=files, data={"modified": ["2000", "1000"]})
assert r.status_code == 200, r.text
body = r.json()
assert body["files"] == 2 and body["overlap_days"] == 5 and body["saved"] == 5
assert dict(store.saved)[date(2026, 9, 23)] == 111111 and str(store.roas[date(2026, 9, 23)]) == "12.34" # 최신 파일
r = client.post("/performance/api/ad-spend/upload?channel=naver", files=files, data={"modified": ["1000", "2000"]})
assert dict(store.saved)[date(2026, 9, 23)] == 300672 # 이번엔 old 가 최신
bad = NAVER_CSV + "0_미라네주방,38461,2026.09.20.,abc,0,0,0,0,0,0,0,1\n"
r = client.post("/performance/api/ad-spend/upload?channel=naver",
files=[("files", ("ok.csv", old.encode("utf-8"))), ("files", ("bad.csv", bad.encode("utf-8")))])
assert r.status_code == 400 and r.json()["errors"][0].startswith("[bad.csv]")
r = client.post("/performance/api/ad-spend/upload?channel=naver", files={"file": ("one.csv", old.encode("utf-8"))})
assert r.status_code == 200 and r.json()["files"] == 1 # 예전 file 한 개도
assert client.post("/performance/api/ad-spend/upload?channel=naver").status_code in (400, 422)