Files
dbx-main/app/modules/performance/tests/test_manual_upload.py
T
king f79b970056 feat(performance): 앞날 입력·계산식 칸·기간 합계 맨 위
- 매출 수동 입력·광고비 날짜 칸과 엑셀·광고 보고서 업로드에서 오늘 이후 날짜 허용
- 이번달 등 일자별 표의 기간 합계 행을 제목 행 바로 아래로
- 날짜 칸에 = 없이 1000+2000 계산식 입력(formula.parse_amount), 식은
  마이그레이션 008 formula 열에 저장해 파랑 굵은 숫자·다시 누르면 식
- 광고비 탭 직접 입력값은 굵게 해제(굵게는 계산식만)

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

144 lines
5.9 KiB
Python

"""수동 입력 엑셀 업로드 — 머리글 매칭·값 있는 칸만·오류 시 전부 거절."""
from __future__ import annotations
import io
from datetime import date, datetime
from pathlib import Path
import openpyxl
import pytest
from app.modules.performance import manual_upload as mu
TODAY = date(2026, 10, 13)
MARKETS = [
{"code": "naver", "name": "네이버", "manual_input": False},
{"code": "coupang_rocket", "name": "쿠팡(로켓)", "manual_input": True},
{"code": "ohouse", "name": "오늘의집", "manual_input": True},
{"code": "toss", "name": "토스쇼핑", "manual_input": True},
{"code": "atomy", "name": "애터미아자몰", "manual_input": True},
]
EXTRA = {"toss": ("토스쇼핑", "토스")}
def _xlsx(rows):
wb = openpyxl.Workbook()
ws = wb.active
for r in rows:
ws.append(list(r))
buf = io.BytesIO()
wb.save(buf)
return buf.getvalue()
def _parse(rows):
return mu.parse_workbook(_xlsx(rows), markets=MARKETS, today=TODAY, extra_names=EXTRA)
def test_only_filled_cells_of_manual_shops():
res = _parse([
("날짜", "쿠팡(로켓)", " 오늘의 집 ", "네이버", "모르는몰", "토스", "애터미아자몰"),
(datetime(2026, 10, 12), 1_000, None, 999, 5, "12,300원", ""),
("2026.10.13(화)", None, 0, None, None, None, 4500.4),
(None, None, None, None, None, None, None), # 빈 줄
])
assert not res.errors
assert res.columns == ["coupang_rocket", "ohouse", "toss", "atomy"]
assert sorted(res.entries) == sorted([
("coupang_rocket", date(2026, 10, 12), 1000), ("toss", date(2026, 10, 12), 12300),
("ohouse", date(2026, 10, 13), 0), ("atomy", date(2026, 10, 13), 4500)])
assert res.ignored == ["네이버(수동 입력 꺼짐)", "모르는몰(알 수 없는 쇼핑몰)"]
@pytest.mark.parametrize("raw, expect", [
("2026-10-01", date(2026, 10, 1)), ("2026/10/1", date(2026, 10, 1)), ("20261001", date(2026, 10, 1)),
(20261001, date(2026, 10, 1)), (46296, date(2026, 10, 1)), ("2026년 10월 1일", date(2026, 10, 1)), (None, None),
])
def test_parse_date(raw, expect):
assert mu.parse_date(raw) == expect
def test_errors_reject_everything_with_cell_refs():
res = _parse([
("날짜", "쿠팡(로켓)", "오늘의집"),
("2026-10-10", "abc", 100),
("엉터리", 1, None),
("2026-10-14", 1, None), # 앞으로의 날짜 — 됨(2026-10-21)
(None, 5, None), # 날짜 없음
("2026-10-11", 7, None),
("2026-10-11", 8, None), # 같은 날 두 번
])
joined = "\n".join(res.errors)
assert "B2" in joined and "A3" in joined and "A4" not in joined and "5행" in joined and "B7" in joined
assert len(res.errors) == 4
def test_header_problems():
with pytest.raises(mu.UploadError):
_parse([("날짜", "네이버", "모르는몰"), ("2026-10-10", 1, 2)]) # 반영할 열 없음
with pytest.raises(mu.UploadError):
mu.parse_workbook(b"not an xlsx", markets=MARKETS, today=TODAY)
res = _parse([("날짜", "쿠팡(로켓)", "coupang_rocket"), ("2026-10-10", 1, 2)])
assert any("두 번" in e for e in res.errors)
def test_sample_file_headers_match_marketplaces():
"""모듈 폴더 샘플 파일 머리글 = 수동 입력 쇼핑몰 이름(시드 기준) — 업로드하면 전부 반영 대상이어야 한다."""
sample = Path(mu.__file__).resolve().parent / "upload_sample.xlsx"
seed = [{"code": c, "name": n, "manual_input": True} for c, n in (
("coupang_rocket", "쿠팡(로켓)"), ("ohouse", "오늘의집"), ("gmarket", "G마켓"), ("kakao", "카카오"),
("gsshop", "GS샵"), ("lotteon", "롯데ON"), ("atomy", "애터미아자몰"))]
wb = openpyxl.load_workbook(sample)
ws = wb.active
ws.append([date(2026, 10, 1)] + [1] * 7)
buf = io.BytesIO()
wb.save(buf)
res = mu.parse_workbook(buf.getvalue(), markets=seed, today=TODAY)
assert not res.errors and not res.ignored and len(res.entries) == 7
def test_upload_endpoint_saves_or_rejects(monkeypatch):
"""라우터: 정상 파일은 한 번에 저장, 잘못된 칸이 있으면 400 + 칸 목록, 아무것도 저장 안 함. 샘플 받기."""
from fastapi import FastAPI
from fastapi.testclient import TestClient
import importlib
from app.modules.performance import common
perf_router = importlib.import_module("app.modules.performance.router") # 패키지 속성 router 는 APIRouter
class Store:
saved: list = []
def list_marketplaces(self):
return [{**m, "enabled": True} for m in MARKETS]
def set_manual_sales_bulk(self, entries, *, user=""):
self.saved.extend(entries)
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)
ok = _xlsx([("날짜", "쿠팡(로켓)", "토스"), ("2026-10-12", 1000, None), ("2026-10-13", None, 2000)])
r = client.post("/performance/api/manual-sales/upload", files={"file": ("a.xlsx", ok)})
assert r.status_code == 200, r.text
body = r.json()
assert body["saved"] == 2 and body["from"] == "2026-10-12" and body["to"] == "2026-10-13"
assert [s["code"] for s in body["by_shop"]] == ["coupang_rocket", "toss"]
assert sorted(store.saved) == [("coupang_rocket", date(2026, 10, 12), 1000), ("toss", date(2026, 10, 13), 2000)]
store.saved.clear()
bad = _xlsx([("날짜", "쿠팡(로켓)"), ("2026-10-12", 1000), ("2026-10-13", "x")])
r = client.post("/performance/api/manual-sales/upload", files={"file": ("b.xlsx", bad)})
assert r.status_code == 400 and r.json()["errors"] and store.saved == []
r = client.get("/performance/api/manual-sales/sample.xlsx")
assert r.status_code == 200 and r.content[:2] == b"PK"