Files
dbx-main/app/modules/performance/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

284 lines
15 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 decimal import ROUND_HALF_UP, Decimal
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
# 채널 — 표 열 순서(2026-10-14 사용자 지정). 쇼핑몰 채널 코드는 실적 쇼핑몰 코드와 같다(쿠팡(윙)만 coupang_wing ↔ 매출 coupang).
CHANNELS: tuple[tuple[str, str], ...] = (
("google", "구글"),
("meta", "메타"),
("naver", "네이버"),
("coupang_wing", "쿠팡(윙)"),
("coupang_rocket", "쿠팡(로켓)"),
("ohouse", "오늘의집"),
("gmarket", "G마켓"),
("kakao", "카카오"),
("gsshop", "GS샵"),
("elevenst", "11번가"),
("lotteon", "롯데ON"),
("toss", "토스"),
("atomy", "애터미아자몰"),
)
CHANNEL_NAMES = dict(CHANNELS)
CHANNEL_CODES = tuple(c for c, _ in CHANNELS)
# ROAS(매출 ÷ 광고비 × 100) 의 매출 = 이 쇼핑몰 매출 실적 총매출. 구글·메타는 자체몰(카페24)로 보내는 광고라 카페24 매출.
ROAS_SALES_CODE: dict[str, str] = {c: c for c in CHANNEL_CODES}
ROAS_SALES_CODE.update({"google": "cafe24", "meta": "cafe24", "coupang_wing": "coupang"})
def roas(sales: int, spend: int) -> int | None:
"""ROAS(%) = 매출 ÷ 광고비 × 100, 정수로 반올림. 광고비가 없으면 None."""
if not spend or spend <= 0:
return None
return int((Decimal(int(sales)) * 100 / Decimal(int(spend))).quantize(Decimal(1), rounding=ROUND_HALF_UP))
def roas_basis(code: str) -> str:
"""머리글 말풍선 — ROAS 에 쓰는 매출."""
sales = ROAS_SALES_CODE[code]
return "카페24(자체몰)" if sales == "cafe24" else CHANNEL_NAMES.get(code, code)
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)
# 매출(ROAS 용) — 채널별 매출 쇼핑몰 + 매출 실적에 들어가는 쇼핑몰 전부(합계 열 ROAS·매출 대비 광고비)
total_codes = list(sales_codes)
need = sorted(set(ROAS_SALES_CODE.values()) | set(total_codes))
sales = {(d, c): int(v) for (d, c), v in store.daily_amounts(q_start, q_end, need).items()}
def sales_sum(mcodes: Sequence[str], s: date, e: date) -> int:
want = set(mcodes)
return sum(v for (d, c), v in sales.items() if c in want and s <= d <= e)
sales_total = sales_sum(total_codes, period.start, period.end) if total_codes else None
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)
table = calc.main_table(period, codes, cells, today=today, holidays=holidays)
# 칸마다 ROAS — "광고비(ROAS%)" 로 보인다. 행 기간 = 그 날·주·월(합계 행은 선택 기간)
for row in table:
s = date.fromisoformat(row["from"]) if row.get("from") else period.start
e = date.fromisoformat(row["to"]) if row.get("to") else period.end
row["roas"] = {c: roas(sales_sum([ROAS_SALES_CODE[c]], s, e), row["cells"][c]["gross"]) for c in codes}
row["roas_total"] = roas(sales_sum(total_codes, s, e), row["total"]["gross"]) if total_codes else None
m_s, m_e = month_period.start, month_period.end
for r in month["rows"]:
r["roas"] = roas(sales_sum([ROAS_SALES_CODE[r["code"]]], m_s, m_e), r["gross"])
month["total"]["roas"] = roas(sales_sum(total_codes, m_s, m_e), month["total"]["gross"]) if total_codes else None
year = calc.year_months(year_period.start.year, codes, cells, today=today)
for i, r in enumerate(year["rows"], start=1):
s = date(year_period.start.year, i, 1)
r["roas"] = None if r.get("future") or not total_codes else roas(sales_sum(total_codes, s, calc.month_end(s)), r["gross"] or 0)
year["total"]["roas"] = roas(sales_sum(total_codes, year_period.start, year_period.end), year["total"]["gross"]) if total_codes else None
return {
"nav": nav,
"period": period,
"period_kind": period.kind,
"today": today.isoformat(),
"codes": codes,
"names": dict(CHANNEL_NAMES),
"kpis": kpis,
"table": table,
"month": month,
"year": year,
"roas_basis": {c: roas_basis(c) for c in codes},
"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,
}