91fd454b2c
- 매출 실적 KPI 줄에 전월 대비 옆 "전년 같은 기간 대비" % (연 보기 제외) - 광고비 탭 카톡 플친(kakao_pf) 열 — 직접 입력, ROAS 없음 - 매출 탭 카페24 칸 광고비 줄에 구글·메타 다음 카톡 플친 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
669 lines
37 KiB
Python
669 lines
37 KiB
Python
"""광고비 — 채널(구글·메타·쿠팡(윙)·쿠팡(로켓))별 일 광고비 + 업로드 파일 읽기 + 화면 데이터 조립.
|
||
|
||
저장: performance_db `perf_ad_spend`(마이그레이션 005) — 채널 × 날짜 하나에 금액 하나(원 단위 정수).
|
||
- 화면 날짜 칸을 눌러 직접 입력(source=manual), 업로드 파일로 한 번에 입력(source=upload, 같은 날 덮어씀).
|
||
- 구글은 광고 API 로 가져온다(source=api, ad_sync.py — 2026-10-15). 메타는 지금은 직접 입력만.
|
||
|
||
쿠팡(윙)·쿠팡(로켓) 업로드 양식(2026-10-13·14 사용자 제공 — 둘 다 같은 쿠팡 광고 보고서 CSV/엑셀):
|
||
1행 머리글, 1열 = 날짜("2026년 10월 01일"), 19열 = 청구금액(+부가가치세) → 그날 광고비.
|
||
규칙(2026-10-14 사용자 확인): **1열에 날짜가 있는 줄의 19열 값**을 가져온다 — 19열이 빈 줄은 건너뛰고(윙 보고서는
|
||
캠페인 줄에도 날짜가 있고 19열이 비어 있다), 같은 날짜에 값이 있는 줄이 여럿이면 더한다.
|
||
1열이 빈 캠페인 줄·맨 위 "전체" 합계 줄은 건너뛴다. 날짜는 있는데 19열 값이 한 줄도 없는 날은 empty_days 로 알려 준다.
|
||
네이버 업로드 양식(2026-10-14 사용자 제공 — 네이버 광고 보고서 CSV/엑셀, 하루 한 줄):
|
||
1행 머리글, 3열 = 기간(날짜 "2026.09.30."), 4열 = 총비용 → 그날 광고비, 12열 = 구매완료 광고수익률(%) → 그날 ROAS.
|
||
나머지 열(노출수·클릭수·클릭률·전환수·구매완료 수·장바구니·총 전환매출액 …)은 머리글 이름 그대로 metrics 에 보관 —
|
||
화면에서 네이버 머리글을 누르면 일자별 표(마이그레이션 006: perf_ad_spend.roas·metrics).
|
||
|
||
HTTP·DB 와 무관한 순수 함수(읽기·조립) — 라우터가 파일 바이트와 저장소를 넘긴다.
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import csv
|
||
import io
|
||
from dataclasses import dataclass, field
|
||
from datetime import date, timedelta
|
||
from decimal import ROUND_HALF_UP, Decimal, InvalidOperation
|
||
from typing import Any, Callable, Mapping, Sequence
|
||
|
||
from . import calc
|
||
from .ad_sources.base import ACCOUNTS_KEY
|
||
from .ad_sources.tiktok_ads import M_REVENUE as TIKTOK_REVENUE_KEY
|
||
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", "메타"),
|
||
("kakao_pf", "카톡 플친"), # 2026-11-16 — 카카오톡 플러스친구(자사몰 광고, 직접 입력), ROAS 없음, 매출 탭 카페24 줄에 구글·메타 아래
|
||
("naver", "네이버"),
|
||
("coupang_wing", "쿠팡(윙)"),
|
||
("coupang_rocket", "쿠팡(로켓)"),
|
||
("ohouse", "오늘의집"),
|
||
("gmarket", "G마켓"),
|
||
("kakao", "카카오"),
|
||
("gsshop", "GS샵"),
|
||
("elevenst", "11번가"),
|
||
("lotteon", "롯데ON"),
|
||
("toss", "토스"),
|
||
("atomy", "애터미아자몰"),
|
||
("etc", "기타광고비"), # 2026-10-22 — 쇼핑몰에 딸리지 않은 광고비(직접 입력), ROAS 없음
|
||
)
|
||
CHANNEL_NAMES = dict(CHANNELS)
|
||
CHANNEL_CODES = tuple(c for c, _ in CHANNELS)
|
||
# ROAS(매출 ÷ 광고비 × 100) 의 매출 = 이 쇼핑몰 매출 실적 총매출. 쿠팡(윙)은 매출 쪽 코드가 coupang.
|
||
# 구글·메타·네이버는 ROAS 를 계산하지 않는다 — 광고 보고서의 ROAS 값을 따로 넣는다(perf_ad_spend.roas, 2026-10-14).
|
||
# 여러 날(주·월·합계)의 ROAS = Σ(그날 ROAS × 그날 광고비) ÷ Σ광고비(ROAS 가 있는 날만) = 광고 매출 합 ÷ 광고비 합.
|
||
FILE_ROAS = frozenset({"google", "meta", "naver"})
|
||
NO_ROAS = FILE_ROAS # 예전 이름(계산 안 하는 채널)
|
||
NO_SALES = frozenset({"etc", "kakao_pf"}) # ROAS 를 계산하지 않는 채널 — 매출 탭 광고비 줄은 sales_ad_channels 에 적은 것만(카톡 플친 = 카페24)
|
||
ROAS_SALES_CODE: dict[str, str] = {c: c for c in CHANNEL_CODES if c not in FILE_ROAS and c not in NO_SALES}
|
||
ROAS_SALES_CODE["coupang_wing"] = "coupang"
|
||
TIKTOK = "tiktok" # 광고 API 채널이지만 CHANNELS 에 없다 — 틱톡 탭(build_tiktok_dashboard)에서만 보인다
|
||
|
||
|
||
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 에 쓰는 매출(구글·메타·네이버는 빈 값 = 계산 안 함, 보고서 값)."""
|
||
return "" if code not in ROAS_SALES_CODE else CHANNEL_NAMES.get(code, code)
|
||
|
||
|
||
def file_roas(code: str, file_roas_map: Mapping[tuple[date, str], Any], spends: Mapping[tuple[date, str], int],
|
||
s: date, e: date) -> int | None:
|
||
"""보고서 ROAS 채널의 기간 ROAS — Σ(ROAS × 광고비) ÷ Σ광고비(ROAS 가 있고 광고비가 있는 날만)."""
|
||
rev = Decimal(0)
|
||
spend = 0
|
||
for (d, c), r in file_roas_map.items():
|
||
if c != code or not s <= d <= e or r is None:
|
||
continue
|
||
amt = int(spends.get((d, c)) or 0)
|
||
if amt > 0:
|
||
rev += Decimal(str(r)) * amt
|
||
spend += amt
|
||
if spend <= 0:
|
||
return None
|
||
return int((rev / spend).quantize(Decimal(1), rounding=ROUND_HALF_UP))
|
||
|
||
|
||
def channel_roas(code: str, sales_of: Callable[[str], int], spend: int,
|
||
file_of: Callable[[str], int | None] | None = None) -> int | None:
|
||
"""채널 칸의 ROAS — 쇼핑몰 매출 ÷ 광고비. 구글·메타·네이버는 보고서 ROAS(file_of), 없으면 None."""
|
||
if code in FILE_ROAS:
|
||
return file_of(code) if file_of else None
|
||
mcode = ROAS_SALES_CODE.get(code)
|
||
return None if mcode is None else roas(sales_of(mcode), spend)
|
||
|
||
ROCKET_DATE_COL = 0 # 1열 날짜
|
||
ROCKET_AMOUNT_COL = 18 # 19열 청구금액(+부가가치세)
|
||
SKIP_LABELS = frozenset({"전체", "합계", "총계", "날짜"})
|
||
|
||
|
||
NAVER_DATE_COL = 2 # 3열 기간(날짜)
|
||
NAVER_AMOUNT_COL = 3 # 4열 총비용
|
||
NAVER_ROAS_COL = 11 # 12열 구매완료 광고수익률(%)
|
||
NAVER_SKIP_COLS = (0, 1, 2) # 광고 계정 이름·ID·기간은 metrics 에 넣지 않음
|
||
|
||
|
||
class AdMigrationNeeded(Exception):
|
||
"""광고비 표(마이그레이션 005: perf_ad_spend) 또는 ROAS·상세 칸(006)이 아직 없음."""
|
||
|
||
|
||
@dataclass
|
||
class ParseResult:
|
||
entries: list[tuple[date, int]] = field(default_factory=list) # (날짜, 금액)
|
||
errors: list[str] = field(default_factory=list)
|
||
skipped: int = 0 # 건너뛴 줄(캠페인 줄·합계 줄)
|
||
# 보고서 ROAS·상세 항목(네이버) — 날짜 → ROAS(%) · {머리글: 값}. 비어 있으면 금액만 저장.
|
||
roas: dict[date, Decimal] = field(default_factory=dict)
|
||
metrics: dict[date, dict[str, Any]] = field(default_factory=dict)
|
||
columns: list[str] = field(default_factory=list) # 상세 항목 머리글(파일 순서)
|
||
empty_days: list[date] = field(default_factory=list) # 날짜 줄은 있는데 금액이 한 줄도 없던 날(저장 안 함)
|
||
|
||
|
||
# ════════════════════════════════════════════════════════════
|
||
# 파일 읽기
|
||
# ════════════════════════════════════════════════════════════
|
||
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:
|
||
"""쿠팡(윙·로켓) 광고 보고서 → (날짜, 그날 19열 청구금액(+부가가치세) 합). 1열에 날짜가 있고 19열에 값이 있는 줄만,
|
||
같은 날짜는 더한다. 잘못된 줄이 있으면 errors 에 담는다(저장은 라우터가 막음)."""
|
||
rows = read_rows(content, filename)
|
||
res = ParseResult()
|
||
sums: dict[date, int] = {}
|
||
dated: set[date] = set()
|
||
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
|
||
dated.add(day)
|
||
if amt is None:
|
||
res.skipped += 1 # 날짜는 있지만 19열이 빈 줄(캠페인 줄 등) — 건너뜀
|
||
elif abs(amt) > MAX_AMOUNT:
|
||
res.errors.append(f"{r}행 19열: 금액이 너무 큽니다.")
|
||
else:
|
||
sums[day] = sums.get(day, 0) + amt # 같은 날짜에 값이 있는 줄이 여럿이면 더한다
|
||
if len(sums) > MAX_DATA_ROWS:
|
||
raise UploadError(f"한 번에 {MAX_DATA_ROWS:,}일까지 올릴 수 있습니다.")
|
||
if len(res.errors) > MAX_ERRORS:
|
||
break
|
||
res.entries = sorted(sums.items())
|
||
res.empty_days = sorted(d for d in dated if d not in sums and d <= today)
|
||
# 날짜 줄은 있는데 청구금액이 한 줄도 없는 파일(그 달 광고비 0 등)은 오류가 아니라 넘어간다(2026-10-14 사용자 요청).
|
||
# 날짜 줄 자체가 없을 때만 양식 오류.
|
||
if not dated and not res.errors:
|
||
raise UploadError("광고비 날짜 줄이 없습니다. 1열 날짜(예: 2026년 10월 01일), 19열 청구금액(+부가가치세) 양식인지 확인하세요.")
|
||
return res
|
||
|
||
|
||
def _number(value: Any) -> Decimal | None:
|
||
"""숫자 칸 → Decimal(쉼표·%·원 허용). 빈 칸이면 None, 숫자가 아니면 ValueError."""
|
||
if value is None or (isinstance(value, str) and not value.strip()):
|
||
return None
|
||
if isinstance(value, bool):
|
||
raise ValueError
|
||
text = str(value).replace(",", "").replace("%", "").replace("원", "").strip()
|
||
try:
|
||
num = Decimal(text)
|
||
except InvalidOperation:
|
||
raise ValueError from None
|
||
if not num.is_finite():
|
||
raise ValueError
|
||
return num
|
||
|
||
|
||
def _json_num(num: Decimal | None) -> Any:
|
||
if num is None:
|
||
return None
|
||
return int(num) if num == num.to_integral_value() else float(round(num, 2))
|
||
|
||
|
||
def _norm(name: Any) -> str:
|
||
return str(name or "").replace(" ", "")
|
||
|
||
|
||
# 네이버 보고서 ROAS = "구매완료 광고수익률(%)"(2026-10-20 사용자 확인). 그 칸이 없거나 비면
|
||
# 구매완료 전환매출액 ÷ 총비용 × 100 으로 계산한다(같은 정의 — 총 전환매출액은 정의가 달라 쓰지 않음).
|
||
NAVER_ROAS_KEY = "구매완료광고수익률"
|
||
NAVER_REVENUE_KEY = "구매완료전환매출액"
|
||
|
||
|
||
def roas_from_metrics(metrics: Mapping[str, Any] | None, amount: int | None) -> Decimal | None:
|
||
"""보고서 항목(머리글 → 값)에서 ROAS(%) — 광고수익률 칸, 없으면 전환매출액 ÷ 광고비. 못 구하면 None.
|
||
저장된 roas 가 빈 예전 업로드(열 위치가 달라 12열이 비었던 파일)도 이것으로 다시 구한다(db.ad_roas)."""
|
||
if not isinstance(metrics, Mapping):
|
||
return None
|
||
for key in (NAVER_ROAS_KEY, NAVER_REVENUE_KEY):
|
||
for k, v in metrics.items():
|
||
if key not in _norm(k) or isinstance(v, bool) or not isinstance(v, (int, float, Decimal)):
|
||
continue
|
||
if key == NAVER_ROAS_KEY:
|
||
return Decimal(str(v))
|
||
if amount and int(amount) > 0:
|
||
return (Decimal(str(v)) * 100 / int(amount)).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
|
||
return None
|
||
|
||
|
||
def _naver_cols(header: tuple[str, ...]) -> tuple[int, int | None]:
|
||
"""머리글로 (총비용 열, ROAS 열) 찾기 — 네이버 보고서는 열 구성을 바꿀 수 있어 고정 위치(4열·12열)가 어긋난다.
|
||
머리글에 없으면 예전 고정 위치. ROAS 는 머리글은 있는데 광고수익률 칸이 없으면 None(전환매출액으로 계산)."""
|
||
names = [_norm(h) for h in header]
|
||
amount = next((i for i, n in enumerate(names) if n.startswith("총비용")), NAVER_AMOUNT_COL)
|
||
roas_col = next((i for i, n in enumerate(names) if NAVER_ROAS_KEY in n), None)
|
||
if roas_col is None and not any(names):
|
||
roas_col = NAVER_ROAS_COL
|
||
return amount, roas_col
|
||
|
||
|
||
def parse_naver(content: bytes, *, today: date, filename: str = "") -> ParseResult:
|
||
"""네이버 광고 보고서 → (날짜, 총비용) + 그날 ROAS(구매완료 광고수익률) + 나머지 항목. 잘못된 줄이 있으면 errors.
|
||
총비용·ROAS 열은 머리글 이름으로 찾는다(없으면 4열·12열)."""
|
||
rows = read_rows(content, filename)
|
||
res = ParseResult()
|
||
header: tuple[Any, ...] = ()
|
||
amount_col, roas_col = NAVER_AMOUNT_COL, NAVER_ROAS_COL
|
||
seen: dict[date, int] = {}
|
||
for r, row in enumerate(rows, start=1):
|
||
raw_day = row[NAVER_DATE_COL] if len(row) > NAVER_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 not header: # 머리글(1행 "기간")
|
||
header = tuple(str(h or "").strip() for h in row)
|
||
amount_col, roas_col = _naver_cols(header)
|
||
res.columns = [h for i, h in enumerate(header) if i not in NAVER_SKIP_COLS and h]
|
||
res.skipped += 1
|
||
continue
|
||
res.errors.append(f"{r}행 3열: 날짜를 읽을 수 없습니다({text[:30]}).")
|
||
continue
|
||
if day is None:
|
||
res.skipped += 1
|
||
continue
|
||
try:
|
||
amt = parse_amount(row[amount_col] if len(row) > amount_col else None)
|
||
except ValueError:
|
||
res.errors.append(f"{r}행 {amount_col + 1}열: 총비용이 숫자가 아닙니다.")
|
||
continue
|
||
try:
|
||
ro = _number(row[roas_col] if roas_col is not None and len(row) > roas_col else None)
|
||
except ValueError:
|
||
res.errors.append(f"{r}행 {(roas_col or 0) + 1}열: 광고수익률(ROAS)이 숫자가 아닙니다.")
|
||
continue
|
||
if amt is None:
|
||
res.errors.append(f"{r}행 {amount_col + 1}열: {day.isoformat()} 총비용이 비어 있습니다.")
|
||
elif abs(amt) > MAX_AMOUNT or (ro is not None and abs(ro) > Decimal("10000000")):
|
||
res.errors.append(f"{r}행: 금액·ROAS 가 너무 큽니다.")
|
||
elif day in seen:
|
||
res.errors.append(f"{r}행: {day.isoformat()} 이 {seen[day]}행과 겹칩니다.")
|
||
else:
|
||
seen[day] = r
|
||
res.entries.append((day, amt))
|
||
m: dict[str, Any] = {}
|
||
for i, v in enumerate(row):
|
||
name = header[i] if i < len(header) else f"{i + 1}열"
|
||
if i in NAVER_SKIP_COLS or not name:
|
||
continue
|
||
try:
|
||
m[name] = _json_num(_number(v))
|
||
except ValueError:
|
||
m[name] = str(v)[:100]
|
||
res.metrics[day] = m
|
||
if ro is None:
|
||
ro = roas_from_metrics(m, amt) # 광고수익률 칸이 없거나 빈 파일 — 전환매출액 ÷ 총비용
|
||
if ro is not None:
|
||
res.roas[day] = ro
|
||
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("광고비 날짜 줄이 없습니다. 3열 기간(예: 2026.09.30.), 4열 총비용, 12열 광고수익률 양식인지 확인하세요.")
|
||
return res
|
||
|
||
|
||
# 업로드 양식이 정해진 채널 → 파일 읽기 함수(채널 순서 = 업로드 창 선택 순서). 쿠팡(윙)도 로켓과 같은 양식(2026-10-14).
|
||
PARSERS: dict[str, Callable[..., ParseResult]] = {
|
||
"naver": parse_naver, "coupang_wing": parse_coupang_rocket, "coupang_rocket": parse_coupang_rocket}
|
||
_COUPANG_HELP = "쿠팡 광고 보고서(CSV 또는 엑셀) — 1열 날짜, 19열 청구금액(+부가가치세)을 그날 광고비로 넣습니다."
|
||
UPLOAD_HELP = {
|
||
"naver": "네이버 광고 보고서(CSV 또는 엑셀) — 3열 기간(날짜), 4열 총비용 = 그날 광고비, 12열 구매완료 광고수익률 = ROAS. "
|
||
"나머지 항목은 네이버 머리글을 누르면 일자별로 볼 수 있습니다.",
|
||
"coupang_wing": _COUPANG_HELP, "coupang_rocket": _COUPANG_HELP}
|
||
MAX_UPLOAD_FILES = 30
|
||
|
||
|
||
def merge_results(parsed: list[tuple[str, float, ParseResult]]) -> tuple[ParseResult, list[date]]:
|
||
"""여러 파일(이름, 파일 수정 시각, 읽은 결과)을 하나로 — 같은 날짜가 여러 파일에 있으면 **파일 날짜(수정 시각)가 최신인
|
||
파일** 값(같으면 나중에 올린 파일). 돌려주는 값: (합친 결과, 여러 파일에 겹친 날짜). 오류는 파일 이름을 앞에 붙여 모은다."""
|
||
merged = ParseResult()
|
||
owner: dict[date, tuple[float, int]] = {}
|
||
overlap: set[date] = set()
|
||
empty: set[date] = set()
|
||
for idx, (name, modified, res) in enumerate(parsed):
|
||
merged.errors.extend(f"[{name}] {e}" for e in res.errors)
|
||
empty.update(res.empty_days)
|
||
merged.skipped += res.skipped
|
||
for c in res.columns:
|
||
if c not in merged.columns:
|
||
merged.columns.append(c)
|
||
picked: dict[date, tuple[int, int]] = {}
|
||
for idx, (name, modified, res) in enumerate(parsed):
|
||
for day, amt in res.entries:
|
||
key = (float(modified or 0), idx)
|
||
if day in owner:
|
||
overlap.add(day)
|
||
if key < owner[day]:
|
||
continue
|
||
owner[day] = key
|
||
picked[day] = (idx, amt)
|
||
for day in sorted(picked):
|
||
idx, amt = picked[day]
|
||
res = parsed[idx][2]
|
||
merged.entries.append((day, amt))
|
||
if day in res.roas:
|
||
merged.roas[day] = res.roas[day]
|
||
if day in res.metrics:
|
||
merged.metrics[day] = res.metrics[day]
|
||
merged.empty_days = sorted(d for d in empty if d not in picked) # 어느 파일에도 값이 없던 날
|
||
return merged, sorted(overlap)
|
||
|
||
|
||
# 머리글을 누르면 일자별 상세 표가 열리는 채널(보고서 항목을 보관하는 채널) — 구글(2026-10-15)·메타(2026-10-16)는 광고 API 로 가져온 항목
|
||
DETAIL_CHANNELS = frozenset({"naver", "google", "meta"})
|
||
|
||
|
||
def detail_table(rows: list[dict[str, Any]]) -> dict[str, Any]:
|
||
"""일자별 상세(GET /api/ad-spend/{channel}/details) — rows: date·amount·roas·metrics(저장소).
|
||
열 = 파일 머리글 순서(처음 나온 순), 합계 = 숫자 열 합 + 클릭률·ROAS 는 가중 평균."""
|
||
cols: list[str] = []
|
||
for r in rows:
|
||
for k in (r.get("metrics") or {}):
|
||
if k not in cols and not k.startswith("_"): # "_" 키 = 표 열이 아닌 내부 값(계정별 등)
|
||
cols.append(k)
|
||
sums: dict[str, Decimal] = {}
|
||
for r in rows:
|
||
for k, v in (r.get("metrics") or {}).items():
|
||
if k.startswith("_"):
|
||
continue
|
||
if isinstance(v, (int, float)) and not isinstance(v, bool):
|
||
sums[k] = sums.get(k, Decimal(0)) + Decimal(str(v))
|
||
total: dict[str, Any] = {k: _json_num(v) for k, v in sums.items()}
|
||
for k in cols:
|
||
if "클릭률" in k and sums.get("노출수"):
|
||
total[k] = float(round(sums.get("클릭수", Decimal(0)) * 100 / sums["노출수"], 2))
|
||
elif ("수익률" in k or "ROAS" in k.upper()):
|
||
spend = sum(int(r.get("amount") or 0) for r in rows if r.get("roas") is not None and int(r.get("amount") or 0) > 0)
|
||
rev = sum(Decimal(str(r["roas"])) * int(r.get("amount") or 0) for r in rows
|
||
if r.get("roas") is not None and int(r.get("amount") or 0) > 0)
|
||
total[k] = float(round(rev / spend, 2)) if spend else None
|
||
elif "환율" in k: # 외화 광고 계정 적용 환율(메타 USD 계정, 2026-10-16) — 더하지 않고 광고비 가중 평균
|
||
pairs = [(Decimal(str((r.get("metrics") or {})[k])), int(r.get("amount") or 0)) for r in rows
|
||
if isinstance((r.get("metrics") or {}).get(k), (int, float)) and int(r.get("amount") or 0) > 0]
|
||
weight = sum(w for _v, w in pairs)
|
||
total[k] = float(round(sum(v * w for v, w in pairs) / weight, 2)) if weight else None
|
||
out_rows = [{"date": r["date"], "amount": int(r.get("amount") or 0),
|
||
"roas": float(r["roas"]) if r.get("roas") is not None else None,
|
||
"values": {k: v for k, v in (r.get("metrics") or {}).items() if not k.startswith("_")}} for r in rows]
|
||
cols, labels = _roas_next_to_spend(cols)
|
||
return {"columns": cols, "labels": labels, "rows": out_rows, "total": total}
|
||
|
||
|
||
# 상세 표의 광고비 열 — 네이버 "총비용"(4열), 구글 "광고비(부가세 포함)", 메타 "지출 금액(부가세 포함)"
|
||
_SPEND_COL_MARKS = ("총비용", "광고비(", "지출 금액(부가세")
|
||
|
||
|
||
def _roas_next_to_spend(cols: list[str]) -> tuple[list[str], dict[str, str]]:
|
||
"""ROAS 열을 광고비 열 바로 오른쪽으로 옮긴다(2026-10-20 사용자 요청 — 네이버 파일은 12열이라 멀리 떨어져 있었다).
|
||
네이버 "구매완료 광고수익률(%)" 은 머리글을 "ROAS(%)" 로 보여 준다(값·키는 파일 머리글 그대로, labels 로만).
|
||
반환: (열 순서, {열: 화면 머리글})."""
|
||
roas_col = next((k for k in cols if "수익률" in k or "ROAS" in k.upper()), None)
|
||
spend_col = next((k for k in cols if any(m in k for m in _SPEND_COL_MARKS)), None)
|
||
labels: dict[str, str] = {}
|
||
if roas_col is None:
|
||
return cols, labels
|
||
if "ROAS" not in roas_col.upper():
|
||
labels[roas_col] = "ROAS(%)"
|
||
if spend_col is None:
|
||
return cols, labels
|
||
out = [k for k in cols if k != roas_col]
|
||
out.insert(out.index(spend_col) + 1, roas_col)
|
||
return out, labels
|
||
|
||
|
||
def detail_tabs(rows: list[dict[str, Any]]) -> dict[str, Any]:
|
||
"""상세보기 탭 — 계정별 값(ACCOUNTS_KEY)이 있는 채널(메타, 2026-10-16)은 [합계 | 계정…], 없으면 탭 없음.
|
||
계정 탭 = 그 계정이 광고를 낸 날만(그날 행의 계정 값으로 detail_table). 계정 이름은 가장 최근 날의 이름,
|
||
순서는 기간 광고비가 큰 계정부터(같으면 이름). accounts_missing = 광고비가 있는데 계정별 값이 없는 날 수
|
||
(계정별 저장 전에 가져온 날 — 다시 불러오면 생긴다)."""
|
||
per: dict[str, list[dict[str, Any]]] = {}
|
||
names: dict[str, str] = {}
|
||
missing = 0
|
||
for r in rows:
|
||
accs = (r.get("metrics") or {}).get(ACCOUNTS_KEY)
|
||
if not isinstance(accs, dict):
|
||
if int(r.get("amount") or 0):
|
||
missing += 1
|
||
continue
|
||
for acc, a in accs.items():
|
||
if not isinstance(a, dict):
|
||
continue
|
||
names[acc] = str(a.get("name") or f"act_{acc}")
|
||
per.setdefault(acc, []).append({"date": r["date"], "amount": int(a.get("amount") or 0),
|
||
"roas": a.get("roas"), "metrics": a.get("metrics") or {}})
|
||
if not per:
|
||
return {"tabs": [], "accounts_missing": 0}
|
||
spend = {acc: sum(x["amount"] for x in days) for acc, days in per.items()}
|
||
order = sorted(per, key=lambda acc: (-spend[acc], names[acc]))
|
||
tabs = [{"key": "total", "label": "합계", **detail_table(rows)}]
|
||
tabs += [{"key": acc, "label": names[acc], "account_id": acc, **detail_table(per[acc])} for acc in order]
|
||
return {"tabs": tabs, "accounts_missing": missing}
|
||
|
||
|
||
# ════════════════════════════════════════════════════════════
|
||
# 화면 데이터
|
||
# ════════════════════════════════════════════════════════════
|
||
def _period_word(period: Any, today: date) -> str:
|
||
"""KPI 이름 앞 말 — 이번달·해당 월 등."""
|
||
return {"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]
|
||
|
||
|
||
def _period_nav(period: Any, today: date) -> dict[str, Any]:
|
||
"""기간 이동 화살표·빠른 선택(이번달·올해만 — 2026-10-26 오늘·이번주 버튼 삭제, 매출 실적과 같게)."""
|
||
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":
|
||
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)
|
||
return {"prev": prev_url, "next": next_url, "quick": [
|
||
{"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},
|
||
]}
|
||
|
||
|
||
def build_tiktok_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) -> dict[str, Any]:
|
||
"""틱톡 탭(2026-11-05) — 광고비 탭과 같은 기간 이동·표·그래프, 열 = ROAS·광고비·매출. 광고 API 가 저장한 perf_ad_spend 만 읽는다.
|
||
CHANNELS 에 없어 광고비 탭·매출 실적 합계에는 들어가지 않는다."""
|
||
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
|
||
year_period = calc.resolve_period("year", ref)
|
||
migration_needed = False
|
||
try:
|
||
rows = store.ad_details(TIKTOK, min(period.start, cmp_start, year_period.start), max(period.end, year_period.end))
|
||
except AdMigrationNeeded:
|
||
rows, migration_needed = [], True
|
||
cells: dict[tuple[date, str], calc.Money] = {}
|
||
for r in rows:
|
||
d = date.fromisoformat(r["date"])
|
||
cells[(d, "spend")] = calc.Money(gross=int(r["amount"] or 0))
|
||
cells[(d, "sales")] = calc.Money(gross=int((r["metrics"] or {}).get(TIKTOK_REVENUE_KEY) or 0))
|
||
|
||
table = calc.main_table(period, ("spend", "sales"), cells, today=today, holidays=holidays)
|
||
for row in table:
|
||
row["roas"] = roas(row["cells"]["sales"]["gross"], row["cells"]["spend"]["gross"])
|
||
cur = {c: calc.sum_range(cells, [c], period.start, period.end).gross for c in ("spend", "sales")}
|
||
prev = {c: calc.sum_range(cells, [c], cmp_start, cmp_end).gross for c in ("spend", "sales")}
|
||
word = _period_word(period, today)
|
||
spend_y = calc.year_months(year_period.start.year, ["spend"], cells, today=today)
|
||
sales_y = calc.year_months(year_period.start.year, ["sales"], cells, today=today)
|
||
year_rows = [{"label": a["label"], "future": a["future"], "spend": a["gross"], "sales": b["gross"],
|
||
"roas": None if a["future"] else roas(b["gross"], a["gross"])}
|
||
for a, b in zip(spend_y["rows"], sales_y["rows"])]
|
||
return {
|
||
"nav": _period_nav(period, today),
|
||
"period": period,
|
||
"period_kind": period.kind,
|
||
"today": today.isoformat(),
|
||
"kpis": [
|
||
{"key": "spend", "label": f"{word} 광고비", "value": cur["spend"], "primary": True,
|
||
"delta": calc.pct_change(cur["spend"], prev["spend"]), "cmp": cmp_label, "invert": True},
|
||
{"key": "sales", "label": f"{word} 매출", "value": cur["sales"],
|
||
"delta": calc.pct_change(cur["sales"], prev["sales"]), "cmp": cmp_label},
|
||
{"key": "roas", "label": f"{word} ROAS", "pct": roas(cur["sales"], cur["spend"])},
|
||
],
|
||
"table": table,
|
||
"chart_sales": calc.daily_series(period, ["sales"], cells),
|
||
"chart_spend": calc.daily_series(period, ["spend"], cells),
|
||
"year": {"year": year_period.start.year, "rows": year_rows, "spend": spend_y["total"]["gross"], "sales": sales_y["total"]["gross"],
|
||
"roas": roas(sales_y["total"]["gross"], spend_y["total"]["gross"])},
|
||
"migration_needed": migration_needed,
|
||
}
|
||
|
||
|
||
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()}
|
||
roas_reader = getattr(store, "ad_roas", None)
|
||
try:
|
||
roas_map = roas_reader(q_start, q_end) if roas_reader and not migration_needed else {}
|
||
except AdMigrationNeeded:
|
||
roas_map = {}
|
||
|
||
cur = calc.sum_range(cells, codes, period.start, period.end)
|
||
prev = calc.sum_range(cells, codes, cmp_start, 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 = _period_word(period, today)
|
||
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": "ytd", "label": f"{year_period.label} 누적 광고비", "value": ytd.gross,
|
||
"delta": calc.pct_change(ytd.gross, y_prev.gross), "cmp": y_cmp_label, "invert": True},
|
||
]
|
||
|
||
nav = _period_nav(period, today)
|
||
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: channel_roas(c, lambda m: sales_sum([m], s, e), row["cells"][c]["gross"],
|
||
lambda f: file_roas(f, roas_map, amounts, s, e)) 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"] = channel_roas(r["code"], lambda m: sales_sum([m], m_s, m_e), r["gross"],
|
||
lambda f: file_roas(f, roas_map, amounts, m_s, m_e))
|
||
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},
|
||
"detail_channels": sorted(DETAIL_CHANNELS),
|
||
"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),
|
||
# 광고 API(구글 광고 등)로 가져온 칸 — 표시용(초록 숫자)
|
||
"api_cells": sorted(f"{d.isoformat()}|{c}" for (d, c), s in sources.items()
|
||
if s == "api" and period.start <= d <= period.end),
|
||
# 계산식으로 입력한 칸(마이그레이션 008) — "날짜|채널" → 식(파랑 굵은 숫자, 누르면 식)
|
||
"formula_cells": {f"{d.isoformat()}|{c}": f for (d, c), f in
|
||
(store.ad_formulas(period.start, period.end) if hasattr(store, "ad_formulas")
|
||
and not migration_needed else {}).items()},
|
||
"upload_channels": [{"code": c, "name": CHANNEL_NAMES[c], "help": UPLOAD_HELP.get(c, "")} for c in PARSERS],
|
||
"migration_needed": migration_needed,
|
||
# 날짜 칸 메모(마이그레이션 010) — "날짜|채널" → 메모
|
||
"memo_cells": {f"{d.isoformat()}|{c}": m for (d, c), m in
|
||
(store.cell_memos("ad", period.start, period.end) if hasattr(store, "cell_memos") else {}).items()},
|
||
}
|