581e0cf325
- 업로드 창 채널 = 쿠팡(윙) · 쿠팡(로켓), 1열 날짜 · 19열 청구금액(+부가가치세) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
235 lines
13 KiB
Python
235 lines
13 KiB
Python
"""광고비 — 채널(구글·메타·쿠팡(윙)·쿠팡(로켓))별 일 광고비 + 업로드 파일 읽기 + 화면 데이터 조립.
|
|
|
|
저장: performance_db `perf_ad_spend`(마이그레이션 005) — 채널 × 날짜 하나에 금액 하나(원 단위 정수).
|
|
- 화면 날짜 칸을 눌러 직접 입력(source=manual), 업로드 파일로 한 번에 입력(source=upload, 같은 날 덮어씀).
|
|
- 구글·메타는 지금은 직접 입력만(API 연동은 다음 단계).
|
|
|
|
쿠팡(윙)·쿠팡(로켓) 업로드 양식(2026-10-13·14 사용자 제공 — 둘 다 같은 쿠팡 광고 보고서 CSV/엑셀):
|
|
1행 머리글, 1열 = 날짜("2026년 10월 01일"), 19열 = 청구금액(+부가가치세) → 그날 광고비.
|
|
날짜 줄 아래 캠페인 줄(1열 빈 칸)과 맨 위 "전체" 합계 줄은 건너뛴다.
|
|
|
|
HTTP·DB 와 무관한 순수 함수(읽기·조립) — 라우터가 파일 바이트와 저장소를 넘긴다.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import csv
|
|
import io
|
|
from dataclasses import dataclass, field
|
|
from datetime import date
|
|
from typing import Any, Callable, Mapping, Sequence
|
|
|
|
from . import calc
|
|
from .manual_upload import MAX_AMOUNT, MAX_DATA_ROWS, MAX_ERRORS, MAX_FILE_BYTES, UploadError, parse_amount, parse_date
|
|
|
|
# 채널 — 표 열 순서. upload = 업로드 양식이 정해진 채널(파일 읽기 함수가 있는 채널).
|
|
CHANNELS: tuple[tuple[str, str], ...] = (
|
|
("google", "구글"),
|
|
("meta", "메타"),
|
|
("coupang_wing", "쿠팡(윙)"),
|
|
("coupang_rocket", "쿠팡(로켓)"),
|
|
)
|
|
CHANNEL_NAMES = dict(CHANNELS)
|
|
CHANNEL_CODES = tuple(c for c, _ in CHANNELS)
|
|
|
|
ROCKET_DATE_COL = 0 # 1열 날짜
|
|
ROCKET_AMOUNT_COL = 18 # 19열 청구금액(+부가가치세)
|
|
SKIP_LABELS = frozenset({"전체", "합계", "총계", "날짜"})
|
|
|
|
|
|
class AdMigrationNeeded(Exception):
|
|
"""광고비 표(마이그레이션 005: perf_ad_spend)가 아직 없음."""
|
|
|
|
|
|
@dataclass
|
|
class ParseResult:
|
|
entries: list[tuple[date, int]] = field(default_factory=list) # (날짜, 금액)
|
|
errors: list[str] = field(default_factory=list)
|
|
skipped: int = 0 # 건너뛴 줄(캠페인 줄·합계 줄)
|
|
|
|
|
|
# ════════════════════════════════════════════════════════════
|
|
# 파일 읽기
|
|
# ════════════════════════════════════════════════════════════
|
|
def _decode_csv(content: bytes) -> str:
|
|
for enc in ("utf-8-sig", "cp949"):
|
|
try:
|
|
return content.decode(enc)
|
|
except UnicodeDecodeError:
|
|
continue
|
|
raise UploadError("CSV 글자 인코딩을 읽을 수 없습니다(UTF-8 또는 CP949 로 저장해 주세요).")
|
|
|
|
|
|
def read_rows(content: bytes, filename: str = "") -> list[tuple[Any, ...]]:
|
|
"""CSV 또는 엑셀(.xlsx) 첫 시트 → 줄 목록(값 그대로)."""
|
|
if not content:
|
|
raise UploadError("빈 파일입니다.")
|
|
if len(content) > MAX_FILE_BYTES:
|
|
raise UploadError("파일이 너무 큽니다(5MB 이하).")
|
|
is_xlsx = content[:2] == b"PK" or filename.lower().endswith(".xlsx")
|
|
if not is_xlsx:
|
|
return [tuple(r) for r in csv.reader(io.StringIO(_decode_csv(content)))]
|
|
try:
|
|
import openpyxl # noqa: WPS433
|
|
|
|
wb = openpyxl.load_workbook(io.BytesIO(content), read_only=True, data_only=True)
|
|
except Exception: # noqa: BLE001 — 형식이 다르면 어떤 오류든 같은 안내
|
|
raise UploadError("파일을 읽을 수 없습니다. 쿠팡 광고 보고서 CSV 또는 엑셀(.xlsx) 파일을 올려 주세요.") from None
|
|
try:
|
|
return [tuple(r or ()) for r in wb.worksheets[0].iter_rows(values_only=True)]
|
|
finally:
|
|
wb.close()
|
|
|
|
|
|
def parse_coupang_rocket(content: bytes, *, today: date, filename: str = "") -> ParseResult:
|
|
"""쿠팡(로켓) 광고 보고서 → (날짜, 청구금액(+부가가치세)). 잘못된 줄이 있으면 errors 에 담는다(저장은 라우터가 막음)."""
|
|
rows = read_rows(content, filename)
|
|
res = ParseResult()
|
|
seen: dict[date, int] = {}
|
|
for r, row in enumerate(rows, start=1):
|
|
raw_day = row[ROCKET_DATE_COL] if len(row) > ROCKET_DATE_COL else None
|
|
text = str(raw_day or "").strip()
|
|
if not text or text.replace(" ", "") in SKIP_LABELS:
|
|
res.skipped += 1
|
|
continue
|
|
try:
|
|
day = parse_date(raw_day)
|
|
except ValueError:
|
|
if r == 1: # 머리글
|
|
res.skipped += 1
|
|
continue
|
|
res.errors.append(f"{r}행 1열: 날짜를 읽을 수 없습니다({text[:30]}).")
|
|
continue
|
|
if day is None:
|
|
res.skipped += 1
|
|
continue
|
|
raw_amt = row[ROCKET_AMOUNT_COL] if len(row) > ROCKET_AMOUNT_COL else None
|
|
try:
|
|
amt = parse_amount(raw_amt)
|
|
except ValueError:
|
|
res.errors.append(f"{r}행 19열: 금액이 숫자가 아닙니다({str(raw_amt)[:30]}).")
|
|
continue
|
|
if amt is None:
|
|
res.errors.append(f"{r}행 19열: {day.isoformat()} 청구금액이 비어 있습니다.")
|
|
elif abs(amt) > MAX_AMOUNT:
|
|
res.errors.append(f"{r}행 19열: 금액이 너무 큽니다.")
|
|
elif day > today:
|
|
res.errors.append(f"{r}행: 앞으로의 날짜({day.isoformat()})는 입력할 수 없습니다.")
|
|
elif day in seen:
|
|
res.errors.append(f"{r}행: {day.isoformat()} 이 {seen[day]}행과 겹칩니다.")
|
|
else:
|
|
seen[day] = r
|
|
res.entries.append((day, amt))
|
|
if len(res.entries) > MAX_DATA_ROWS:
|
|
raise UploadError(f"한 번에 {MAX_DATA_ROWS:,}일까지 올릴 수 있습니다.")
|
|
if len(res.errors) > MAX_ERRORS:
|
|
break
|
|
if not res.entries and not res.errors:
|
|
raise UploadError("광고비 날짜 줄이 없습니다. 1열 날짜(예: 2026년 10월 01일), 19열 청구금액(+부가가치세) 양식인지 확인하세요.")
|
|
return res
|
|
|
|
|
|
# 업로드 양식이 정해진 채널 → 파일 읽기 함수(채널 순서 = 업로드 창 선택 순서). 쿠팡(윙)도 로켓과 같은 양식(2026-10-14).
|
|
PARSERS: dict[str, Callable[..., ParseResult]] = {"coupang_wing": parse_coupang_rocket, "coupang_rocket": parse_coupang_rocket}
|
|
_COUPANG_HELP = "쿠팡 광고 보고서(CSV 또는 엑셀) — 1열 날짜, 19열 청구금액(+부가가치세)을 그날 광고비로 넣습니다."
|
|
UPLOAD_HELP = {"coupang_wing": _COUPANG_HELP, "coupang_rocket": _COUPANG_HELP}
|
|
|
|
|
|
# ════════════════════════════════════════════════════════════
|
|
# 화면 데이터
|
|
# ════════════════════════════════════════════════════════════
|
|
def build_ad_dashboard(store: Any, *, kind: str, anchor: date, today: date,
|
|
custom_from: date | None = None, custom_to: date | None = None,
|
|
holidays: Mapping[str, str] | None = None,
|
|
sales_codes: Sequence[str] = ()) -> dict[str, Any]:
|
|
"""광고비 화면 — 매출 실적과 같은 기간 이동·표(일자 × 채널, 연간은 월)·그래프·월/연 누적.
|
|
sales_codes 가 있으면 같은 기간 매출(총매출) 대비 광고비 비율도 보여 준다."""
|
|
codes = list(CHANNEL_CODES)
|
|
period = calc.resolve_period(kind, anchor, custom_from=custom_from, custom_to=custom_to)
|
|
cmp_start, cmp_end, cmp_label = period.compare_range(today)
|
|
ref = period.end if period.end < today else today if period.start <= today else period.start
|
|
month_period = calc.resolve_period("month", ref)
|
|
year_period = calc.resolve_period("year", ref)
|
|
m_cmp_start, m_cmp_end, m_cmp_label = month_period.compare_range(today)
|
|
y_cmp_start, y_cmp_end, y_cmp_label = year_period.compare_range(today)
|
|
q_start = min(period.start, cmp_start, m_cmp_start, y_cmp_start)
|
|
q_end = max(period.end, year_period.end)
|
|
|
|
migration_needed = False
|
|
try:
|
|
amounts, sources = store.ad_amounts(q_start, q_end)
|
|
except AdMigrationNeeded:
|
|
amounts, sources, migration_needed = {}, {}, True
|
|
cells = {k: calc.Money(gross=int(v)) for k, v in amounts.items()}
|
|
|
|
cur = calc.sum_range(cells, codes, period.start, period.end)
|
|
prev = calc.sum_range(cells, codes, cmp_start, cmp_end)
|
|
mtd = calc.sum_range(cells, codes, month_period.start, month_period.end)
|
|
m_prev = calc.sum_range(cells, codes, m_cmp_start, m_cmp_end)
|
|
ytd = calc.sum_range(cells, codes, year_period.start, year_period.end)
|
|
y_prev = calc.sum_range(cells, codes, y_cmp_start, y_cmp_end)
|
|
|
|
sales_total = None
|
|
if sales_codes:
|
|
daily = store.daily_amounts(period.start, period.end, list(sales_codes))
|
|
sales_total = sum(int(v) for v in daily.values())
|
|
ratio = round(cur.gross / sales_total * 100, 1) if sales_total and sales_total > 0 else None
|
|
|
|
word = {"day": "오늘" if period.start == today else "해당일",
|
|
"week": "이번주" if period.start <= today <= period.end else "해당 주",
|
|
"month": "이번달" if period.start <= today <= period.end else "해당 월",
|
|
"year": "올해" if period.start <= today <= period.end else "해당 연도",
|
|
"custom": "선택 기간"}[period.kind]
|
|
kpis = [
|
|
{"key": "spend", "label": f"{word} 광고비", "value": cur.gross, "primary": True,
|
|
"delta": calc.pct_change(cur.gross, prev.gross), "cmp": cmp_label, "invert": True},
|
|
{"key": "ratio", "label": f"{word} 매출 대비 광고비", "pct": ratio,
|
|
"note": f"총매출 ₩{sales_total:,}" if sales_total else "매출 없음"},
|
|
{"key": "mtd", "label": f"{month_period.label} 누적 광고비", "value": mtd.gross,
|
|
"delta": calc.pct_change(mtd.gross, m_prev.gross), "cmp": m_cmp_label, "invert": True},
|
|
{"key": "ytd", "label": f"{year_period.label} 누적 광고비", "value": ytd.gross,
|
|
"delta": calc.pct_change(ytd.gross, y_prev.gross), "cmp": y_cmp_label, "invert": True},
|
|
]
|
|
|
|
def url(k: str, anchor_d: date | None = None, start: date | None = None, end: date | None = None) -> str:
|
|
if k == "custom":
|
|
return f"?period=custom&from={start.isoformat()}&to={end.isoformat()}"
|
|
return f"?period={k}&d={anchor_d.isoformat()}"
|
|
|
|
if period.kind == "custom":
|
|
from datetime import timedelta # noqa: WPS433
|
|
|
|
length = timedelta(days=period.days)
|
|
prev_url = url("custom", start=period.start - length, end=period.start - timedelta(days=1))
|
|
next_url = url("custom", start=period.end + timedelta(days=1), end=period.end + length)
|
|
else:
|
|
prev_url, next_url = url(period.kind, period.prev_anchor), url(period.kind, period.next_anchor)
|
|
nav = {"prev": prev_url, "next": next_url, "quick": [
|
|
{"label": "오늘", "url": url("day", today), "active": period.kind == "day" and period.start == today},
|
|
{"label": "이번주", "url": url("week", today), "active": period.kind == "week" and period.start <= today <= period.end},
|
|
{"label": "이번달", "url": url("month", today), "active": period.kind == "month" and period.start <= today <= period.end},
|
|
{"label": "올해", "url": url("year", today), "active": period.kind == "year" and period.start <= today <= period.end},
|
|
]}
|
|
|
|
share = calc.by_code(cells, codes, period.start, period.end)
|
|
month = calc.month_summary(month_period.start.year, month_period.start.month, codes, cells)
|
|
return {
|
|
"nav": nav,
|
|
"period": period,
|
|
"period_kind": period.kind,
|
|
"today": today.isoformat(),
|
|
"codes": codes,
|
|
"names": dict(CHANNEL_NAMES),
|
|
"kpis": kpis,
|
|
"table": calc.main_table(period, codes, cells, today=today, holidays=holidays),
|
|
"month": month,
|
|
"year": calc.year_months(year_period.start.year, codes, cells, today=today),
|
|
"chart_daily": calc.daily_series(period, codes, cells),
|
|
"chart_share": [{"code": c, "name": CHANNEL_NAMES[c], **share[c].as_dict()} for c in codes],
|
|
# 업로드로 들어온 칸(표시용) — "날짜|채널"
|
|
"upload_cells": sorted(f"{d.isoformat()}|{c}" for (d, c), s in sources.items()
|
|
if s == "upload" and period.start <= d <= period.end),
|
|
"upload_channels": [{"code": c, "name": CHANNEL_NAMES[c], "help": UPLOAD_HELP.get(c, "")} for c in PARSERS],
|
|
"migration_needed": migration_needed,
|
|
}
|