Merge branch 'feat/performance-ad-spend'
This commit is contained in:
@@ -0,0 +1,235 @@
|
||||
"""광고비 — 채널(구글·메타·쿠팡(윙)·쿠팡(로켓))별 일 광고비 + 업로드 파일 읽기 + 화면 데이터 조립.
|
||||
|
||||
저장: performance_db `perf_ad_spend`(마이그레이션 005) — 채널 × 날짜 하나에 금액 하나(원 단위 정수).
|
||||
- 화면 날짜 칸을 눌러 직접 입력(source=manual), 업로드 파일로 한 번에 입력(source=upload, 같은 날 덮어씀).
|
||||
- 구글·메타는 지금은 직접 입력만(API 연동은 다음 단계).
|
||||
|
||||
쿠팡(로켓) 업로드 양식(2026-10-13 사용자 제공 — 쿠팡 광고 보고서 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
|
||||
|
||||
|
||||
# 업로드 양식이 정해진 채널 → 파일 읽기 함수
|
||||
PARSERS: dict[str, Callable[..., ParseResult]] = {"coupang_rocket": parse_coupang_rocket}
|
||||
UPLOAD_HELP = {
|
||||
"coupang_rocket": "쿠팡 광고 보고서(CSV 또는 엑셀) — 1열 날짜, 19열 청구금액(+부가가치세)을 그날 광고비로 넣습니다.",
|
||||
}
|
||||
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# 화면 데이터
|
||||
# ════════════════════════════════════════════════════════════
|
||||
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,
|
||||
}
|
||||
@@ -373,6 +373,54 @@ class PerformanceDBStore:
|
||||
raise ManualMigrationNeeded() from None
|
||||
return len(entries)
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# 광고비(마이그레이션 005)
|
||||
# ════════════════════════════════════════════════════════════
|
||||
def ad_amounts(self, start: date, end: date) -> tuple[dict[tuple[date, str], int], dict[tuple[date, str], str]]:
|
||||
"""(날짜, 채널) → 금액, (날짜, 채널) → 입력 방식(manual/upload/api). 005 미적용이면 AdMigrationNeeded."""
|
||||
from .ad_spend import AdMigrationNeeded # noqa: WPS433
|
||||
|
||||
try:
|
||||
with self._pool.connection() as conn:
|
||||
rows = conn.execute(
|
||||
"SELECT spend_date, channel_code, amount, source FROM perf_ad_spend "
|
||||
"WHERE spend_date BETWEEN %s AND %s", (start, end),
|
||||
).fetchall()
|
||||
except pg_errors.UndefinedTable:
|
||||
raise AdMigrationNeeded() from None
|
||||
return ({(r["spend_date"], r["channel_code"]): int(r["amount"]) for r in rows},
|
||||
{(r["spend_date"], r["channel_code"]): r["source"] for r in rows})
|
||||
|
||||
def set_ad_spend(self, code: str, day: date, amount: int | None, *, source: str = "manual", user: str = "") -> None:
|
||||
"""광고비 한 칸 저장(amount None = 지움)."""
|
||||
self.set_ad_spend_bulk(code, [(day, amount)], source=source, user=user)
|
||||
|
||||
def set_ad_spend_bulk(self, code: str, entries: list[tuple[date, int | None]], *, source: str = "manual",
|
||||
user: str = "") -> int:
|
||||
"""여러 날을 한 트랜잭션으로(같은 날은 덮어씀, 금액 None 은 지움). 하나라도 실패하면 모두 취소."""
|
||||
from .ad_spend import AdMigrationNeeded # noqa: WPS433
|
||||
|
||||
if not entries:
|
||||
return 0
|
||||
try:
|
||||
with self._pool.connection() as conn:
|
||||
with conn.transaction():
|
||||
with conn.cursor() as cur:
|
||||
gone = [(code, d) for d, a in entries if a is None]
|
||||
keep = [(code, d, int(a), source, user) for d, a in entries if a is not None]
|
||||
if gone:
|
||||
cur.executemany("DELETE FROM perf_ad_spend WHERE channel_code = %s AND spend_date = %s", gone)
|
||||
if keep:
|
||||
cur.executemany(
|
||||
"INSERT INTO perf_ad_spend (channel_code, spend_date, amount, source, updated_by) "
|
||||
"VALUES (%s, %s, %s, %s, %s) ON CONFLICT (channel_code, spend_date) DO UPDATE "
|
||||
"SET amount = EXCLUDED.amount, source = EXCLUDED.source, updated_by = EXCLUDED.updated_by",
|
||||
keep,
|
||||
)
|
||||
except pg_errors.UndefinedTable:
|
||||
raise AdMigrationNeeded() from None
|
||||
return len(entries)
|
||||
|
||||
def daily_breakdown(self, code: str, start: date, end: date, *, id_prefix: str = "") -> list[dict[str, Any]]:
|
||||
"""쇼핑몰 화면(일별 매출내역) 대조용 — 날짜별 결제(SALE 합·건수)·환불(그 밖, 양수)·마지막 수집 시각.
|
||||
id_prefix 가 있으면 이 어댑터가 다른 쇼핑몰 열로 보낸 사건까지 합친다(카페24 화면 합계와 같은 범위)."""
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
화면
|
||||
GET /performance/ 대시보드(모듈 권한)
|
||||
GET /performance/ads 광고비(모듈 권한) — 구글·메타·쿠팡(윙)·쿠팡(로켓) 연·월·일
|
||||
GET /performance/settings 실적 설정(관리자)
|
||||
JSON API — 모듈 권한
|
||||
POST /performance/api/sync 매출 업데이트(사용 중인 쇼핑몰 전부, 쇼핑몰별 실패 격리)
|
||||
@@ -13,6 +14,8 @@ JSON API — 모듈 권한
|
||||
PUT /performance/api/manual-sales/{code}/{day} 수동 입력 매출 저장/지움(그 쇼핑몰 수동 입력이 켜져 있을 때, 오늘까지)
|
||||
GET /performance/api/manual-sales/sample.xlsx 수동 입력 엑셀 업로드 샘플(모듈 폴더 upload_sample.xlsx)
|
||||
POST /performance/api/manual-sales/upload 수동 입력 엑셀 업로드(1열 날짜, 2열부터 쇼핑몰 이름 머리글)
|
||||
PUT /performance/api/ad-spend/{channel}/{day} 광고비 한 칸 저장/지움(오늘까지)
|
||||
POST /performance/api/ad-spend/upload?channel= 광고비 파일 업로드(쿠팡(로켓) 광고 보고서 — 1열 날짜, 19열 청구금액)
|
||||
JSON API — 관리자
|
||||
PUT /performance/api/marketplaces/{code} 사용/매출 집계/수동 입력 여부
|
||||
POST /performance/api/marketplaces/{code}/rates 수수료율(적용 시작일)
|
||||
@@ -50,6 +53,8 @@ MAX_BACKFILL_DAYS = 366
|
||||
MAX_USER_SYNC_DAYS = 92 # 관리자가 아니어도 가져올 수 있는 기간(이번달·직접선택 짧은 기간)
|
||||
MAX_MANUAL_AMOUNT = 10 ** 12 # 수동 입력 한 칸 상한(원)
|
||||
MANUAL_SAMPLE_PATH = Path(__file__).resolve().parent / "upload_sample.xlsx"
|
||||
AD_MIGRATION_HELP = ("광고비를 쓰려면 performance_db 마이그레이션 005(scripts/sql/performance_db_005_ad_spend.sql)를 "
|
||||
"먼저 적용해야 합니다.")
|
||||
MANUAL_MIGRATION_HELP = ("수동 입력을 쓰려면 performance_db 마이그레이션 002(scripts/sql/performance_db_002_manual_sales.sql)를 "
|
||||
"먼저 적용해야 합니다.")
|
||||
|
||||
@@ -119,6 +124,33 @@ def dashboard_page(
|
||||
return render_template(request, "performance/index.html", {**common.base_ctx(user, active_tab="dashboard"), **ctx})
|
||||
|
||||
|
||||
@router.get("/ads", response_class=HTMLResponse)
|
||||
def ads_page(
|
||||
request: Request,
|
||||
period: str = "month",
|
||||
d: str | None = None,
|
||||
from_: str | None = Query(None, alias="from"),
|
||||
to: str | None = None,
|
||||
):
|
||||
from app.main import render_template # noqa: WPS433
|
||||
|
||||
g = common.guard(request)
|
||||
if not isinstance(g, tuple):
|
||||
return g
|
||||
store, user = g
|
||||
from .ad_spend import build_ad_dashboard # noqa: WPS433
|
||||
from .dashboard import _sales_marketplaces # noqa: WPS433
|
||||
|
||||
today = today_kst()
|
||||
ctx = build_ad_dashboard(
|
||||
store, kind=period, anchor=_parse_date(d) or today, today=today,
|
||||
custom_from=_parse_date(from_), custom_to=_parse_date(to), holidays=_holidays(),
|
||||
sales_codes=[m["code"] for m in _sales_marketplaces(store)],
|
||||
)
|
||||
return render_template(request, "performance/ads.html",
|
||||
{**common.base_ctx(user, active_tab="ads", page_title="광고비"), **ctx})
|
||||
|
||||
|
||||
@router.get("/settings", response_class=HTMLResponse)
|
||||
def settings_page(request: Request):
|
||||
from app.main import render_template # noqa: WPS433
|
||||
@@ -358,6 +390,77 @@ def api_manual_upload(request: Request, file: UploadFile = File(...)) -> JSONRes
|
||||
})
|
||||
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# JSON API — 광고비(모듈 권한자 누구나)
|
||||
# ════════════════════════════════════════════════════════════
|
||||
def _ad_channel(channel: str) -> str:
|
||||
from .ad_spend import CHANNEL_NAMES # noqa: WPS433
|
||||
|
||||
if channel not in CHANNEL_NAMES:
|
||||
raise HTTPException(status_code=404, detail="알 수 없는 광고 채널입니다.")
|
||||
return channel
|
||||
|
||||
|
||||
@router.put("/api/ad-spend/{channel}/{day}")
|
||||
def api_ad_spend(request: Request, channel: str, day: str, payload: dict[str, Any] = Body(...)) -> JSONResponse:
|
||||
from .ad_spend import AdMigrationNeeded # noqa: WPS433
|
||||
|
||||
store, user = common.require_store(request)
|
||||
_ad_channel(channel)
|
||||
d = _parse_date(day)
|
||||
if d is None:
|
||||
raise HTTPException(status_code=400, detail="날짜가 필요합니다.")
|
||||
if d > today_kst():
|
||||
raise HTTPException(status_code=400, detail="앞으로의 날짜는 입력할 수 없습니다.")
|
||||
raw = payload.get("amount")
|
||||
amount: int | None
|
||||
if raw in (None, ""):
|
||||
amount = None
|
||||
else:
|
||||
try:
|
||||
amount = int(Decimal(str(raw).replace(",", "").strip()))
|
||||
except (InvalidOperation, ValueError):
|
||||
raise HTTPException(status_code=400, detail="금액은 숫자(원)로 입력하세요.") from None
|
||||
if abs(amount) > MAX_MANUAL_AMOUNT:
|
||||
raise HTTPException(status_code=400, detail="금액이 너무 큽니다.")
|
||||
try:
|
||||
store.set_ad_spend(channel, d, amount, source="manual", user=user.get("email", ""))
|
||||
except AdMigrationNeeded:
|
||||
raise HTTPException(status_code=503, detail=AD_MIGRATION_HELP) from None
|
||||
return JSONResponse({"ok": True, "channel": channel, "date": d.isoformat(), "manual": amount,
|
||||
"amount": amount or 0})
|
||||
|
||||
|
||||
@router.post("/api/ad-spend/upload")
|
||||
def api_ad_spend_upload(request: Request, channel: str = Query(...), file: UploadFile = File(...)) -> JSONResponse:
|
||||
"""광고비 파일 업로드 — 파일에 있는 날만 덮어쓴다. 잘못된 줄이 있으면 아무것도 저장하지 않는다."""
|
||||
from . import ad_spend # noqa: WPS433
|
||||
from .manual_upload import MAX_FILE_BYTES, UploadError # noqa: WPS433
|
||||
|
||||
store, user = common.require_store(request)
|
||||
_ad_channel(channel)
|
||||
parser = ad_spend.PARSERS.get(channel)
|
||||
if parser is None:
|
||||
raise HTTPException(status_code=400, detail=f"{ad_spend.CHANNEL_NAMES[channel]} 업로드 양식은 아직 정해지지 않았습니다.")
|
||||
content = file.file.read(MAX_FILE_BYTES + 1)
|
||||
try:
|
||||
res = parser(content, today=today_kst(), filename=file.filename or "")
|
||||
except UploadError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from None
|
||||
if res.errors:
|
||||
return JSONResponse(status_code=400, content={
|
||||
"detail": f"잘못된 줄이 {len(res.errors)}개 있어 아무것도 저장하지 않았습니다. 고친 뒤 다시 올려 주세요.",
|
||||
"errors": res.errors})
|
||||
try:
|
||||
saved = store.set_ad_spend_bulk(channel, list(res.entries), source="upload", user=user.get("email", ""))
|
||||
except ad_spend.AdMigrationNeeded:
|
||||
raise HTTPException(status_code=503, detail=AD_MIGRATION_HELP) from None
|
||||
days = sorted(d for d, _ in res.entries)
|
||||
return JSONResponse({"ok": True, "saved": saved, "channel": channel, "name": ad_spend.CHANNEL_NAMES[channel],
|
||||
"total": sum(a for _, a in res.entries), "skipped": res.skipped,
|
||||
"from": days[0].isoformat() if days else None, "to": days[-1].isoformat() if days else None})
|
||||
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# JSON API — 설정(수수료율은 모듈 권한자 누구나, 나머지는 관리자)
|
||||
# ════════════════════════════════════════════════════════════
|
||||
|
||||
@@ -1,5 +1,16 @@
|
||||
{# 실적 모듈 탭 — 설정 탭은 모듈 권한자 모두(일반 사용자 화면은 수수료율만, 나머지는 관리자). #}
|
||||
{# 실적 모듈 탭 — [매출 실적] [광고비] 큰 탭 둘(아이콘 + 색으로 구분) + 맨 오른쪽 설정 톱니(프로젝트 모듈과 같은 아이콘).
|
||||
설정은 모듈 권한자 모두(일반 사용자 화면은 수수료율만, 나머지는 관리자). #}
|
||||
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||
<nav class="perf-tabs" aria-label="실적 메뉴">
|
||||
<a class="perf-tab{% if active_tab == 'dashboard' %} is-active{% endif %}" href="/performance/">실적</a>
|
||||
<a class="perf-tab{% if active_tab == 'settings' %} is-active{% endif %}" href="/performance/settings">{{ '설정' if is_admin else '수수료 설정' }}</a>
|
||||
<div class="perf-tabs-main" role="tablist">
|
||||
<a class="perf-tab perf-tab-sales{% if active_tab == 'dashboard' %} is-active{% endif %}" href="/performance/"
|
||||
role="tab" aria-selected="{{ 'true' if active_tab == 'dashboard' else 'false' }}">
|
||||
<span class="material-symbols-outlined" aria-hidden="true">monitoring</span>매출 실적</a>
|
||||
<a class="perf-tab perf-tab-ads{% if active_tab == 'ads' %} is-active{% endif %}" href="/performance/ads"
|
||||
role="tab" aria-selected="{{ 'true' if active_tab == 'ads' else 'false' }}">
|
||||
<span class="material-symbols-outlined" aria-hidden="true">campaign</span>광고비</a>
|
||||
</div>
|
||||
<a class="perf-tab-gear{% if active_tab == 'settings' %} is-active{% endif %}" href="/performance/settings"
|
||||
title="{{ '실적 설정' if is_admin else '수수료 설정' }}" aria-label="{{ '실적 설정' if is_admin else '수수료 설정' }}">
|
||||
<span class="material-symbols-outlined" aria-hidden="true">settings</span></a>
|
||||
</nav>
|
||||
|
||||
@@ -0,0 +1,204 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261013d" />{% endblock %}
|
||||
|
||||
{%- macro won(v) -%}
|
||||
{%- if v is none -%}<span class="perf-na"></span>
|
||||
{%- elif v == 0 -%}<span class="perf-zero">–</span>
|
||||
{%- else -%}{{ "{:,}".format(v) }}{%- endif -%}
|
||||
{%- endmacro -%}
|
||||
|
||||
{% block content %}
|
||||
{#- 광고비 — 매출 실적과 같은 기간 이동·표·그래프. 날짜 칸을 눌러 직접 입력(파란 숫자), 업로드로 들어온 값은 주황 숫자. -#}
|
||||
<section class="perf perf-ads" id="perf-dash" data-metric="gross" data-fixed-metric="gross">
|
||||
{% include "performance/_tabs.html" %}
|
||||
|
||||
<div class="perf-toolbar">
|
||||
<div class="perf-quick" role="group" aria-label="기간 선택">
|
||||
{% for q in nav.quick %}
|
||||
<a class="perf-seg{% if q.active %} is-active{% endif %}" href="{{ q.url }}">{{ q.label }}</a>
|
||||
{% endfor %}
|
||||
<button type="button" class="perf-seg{% if period_kind == 'custom' %} is-active{% endif %}" id="perf-custom-btn">직접선택</button>
|
||||
</div>
|
||||
|
||||
<div class="perf-nav">
|
||||
<a class="perf-nav-btn" href="{{ nav.prev }}" title="{{ period.prev_label }}">‹ {{ period.prev_label }}</a>
|
||||
<span class="perf-nav-label">{{ period.label }}</span>
|
||||
<a class="perf-nav-btn" href="{{ nav.next }}" title="{{ period.next_label }}">{{ period.next_label }} ›</a>
|
||||
</div>
|
||||
|
||||
<form class="perf-custom" id="perf-custom" method="get" action="/performance/ads"{% if period_kind != 'custom' %} hidden{% endif %}>
|
||||
<input type="hidden" name="period" value="custom" />
|
||||
<input class="erp-input perf-date" type="date" name="from" value="{{ period.start.isoformat() }}" required />
|
||||
<span class="perf-muted">~</span>
|
||||
<input class="erp-input perf-date" type="date" name="to" value="{{ period.end.isoformat() }}" required />
|
||||
<button class="erp-btn erp-btn-outline" type="submit">조회</button>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
{% if migration_needed %}
|
||||
<div class="perf-notice is-warn">광고비 저장 표가 아직 없습니다. 관리자가 performance_db 마이그레이션 005
|
||||
(scripts/sql/performance_db_005_ad_spend.sql)를 적용하면 입력할 수 있습니다.</div>
|
||||
{% endif %}
|
||||
|
||||
<!-- ── KPI ── -->
|
||||
<div class="perf-kpis">
|
||||
{% for k in kpis %}
|
||||
<div class="perf-kpi{% if k.primary %} is-primary{% endif %}">
|
||||
<div class="perf-kpi-label">{{ k.label }}</div>
|
||||
{% if k.key == 'ratio' %}
|
||||
<div class="perf-kpi-value">{% if k.pct is none %}–{% else %}{{ "%.1f" | format(k.pct) }}%{% endif %}</div>
|
||||
<div class="perf-kpi-delta"><span class="perf-muted">{{ k.note }}</span></div>
|
||||
{% else %}
|
||||
<div class="perf-kpi-value">₩{{ "{:,}".format(k.value) }}</div>
|
||||
<div class="perf-kpi-delta">
|
||||
{% if k.delta is none %}<span class="perf-muted">{{ k.cmp }} 비교 없음</span>
|
||||
{% else %}
|
||||
{% set up = k.delta > 0 %}
|
||||
<span class="perf-delta {% if k.delta == 0 %}is-flat{% elif up != (k.invert or false) %}is-up{% else %}is-down{% endif %}">
|
||||
{% if k.delta > 0 %}▲{% elif k.delta < 0 %}▼{% else %}–{% endif %} {{ "%.1f" | format(k.delta | abs) }}%</span>
|
||||
<span class="perf-muted">{{ k.cmp }} 대비</span>
|
||||
{% endif %}
|
||||
</div>
|
||||
{% endif %}
|
||||
</div>
|
||||
{% endfor %}
|
||||
</div>
|
||||
|
||||
<!-- ── 일자 × 채널 ── -->
|
||||
<div class="erp-card perf-card">
|
||||
<div class="perf-card-head">
|
||||
<h2 class="perf-h">{% if period_kind == 'year' %}월별 × 광고 채널{% else %}일자별 × 광고 채널{% endif %}</h2>
|
||||
{% if upload_channels %}
|
||||
<button type="button" class="erp-btn erp-btn-outline erp-btn-sm perf-manual-upload-btn perf-ad-upload-btn" id="perf-ad-upload"
|
||||
title="광고 보고서 파일로 일별 광고비를 한 번에 입력">파일 업로드</button>
|
||||
{% endif %}
|
||||
</div>
|
||||
<div class="erp-table-wrap perf-table-wrap">
|
||||
<table class="perf-table perf-main">
|
||||
<thead>
|
||||
<tr>
|
||||
<th class="perf-th-label">{% if period_kind == 'year' %}월{% else %}날짜{% endif %}</th>
|
||||
{% for c in codes %}<th title="{{ names[c] }} — 날짜 칸을 눌러 입력">{{ names[c] }} <span class="perf-manual-mark" aria-hidden="true">✎</span></th>{% endfor %}
|
||||
<th class="perf-th-total">{% if period_kind == 'year' %}월 합계{% else %}일 합계{% endif %}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for r in table %}
|
||||
<tr class="perf-row-{{ r.kind }}{% if r.weekday == 5 %} is-sat{% endif %}{% if r.weekday == 6 or r.holiday %} is-sun{% endif %}{% if r.today %} is-today{% endif %}{% if r.future %} is-future{% endif %}">
|
||||
<th class="perf-td-label" scope="row"{% if r.holiday %} title="{{ r.holiday }}"{% endif %}>
|
||||
{{ r.label }}{% if r.holiday %}<small class="perf-hol">{{ r.holiday }}</small>{% endif %}
|
||||
</th>
|
||||
{% for c in codes %}
|
||||
{% set v = r.cells[c].gross %}
|
||||
{% if r.kind == 'day' and not r.future and not migration_needed %}
|
||||
{% set up = (r.date ~ '|' ~ c) in upload_cells %}
|
||||
<td class="perf-num is-manual-cell{% if v and not up %} is-manual{% endif %}{% if up %} is-upload{% endif %}"
|
||||
data-manual-code="{{ c }}" data-date="{{ r.date }}" data-manual-value="{{ v if v else '' }}" tabindex="0"
|
||||
title="{% if up %}파일 업로드 값 — 눌러 고치기{% else %}눌러 광고비 입력(비우고 저장하면 지움){% endif %}"><span class="v v-gross">{{ won(v) }}</span></td>
|
||||
{% else %}
|
||||
<td class="perf-num"><span class="v v-gross">{{ won(v) }}</span></td>
|
||||
{% endif %}
|
||||
{% endfor %}
|
||||
<td class="perf-num perf-td-total"><span class="v v-gross">{{ won(r.total.gross) }}</span></td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
{% if period_kind != 'year' %}
|
||||
<p class="perf-muted perf-manual-help">날짜 칸을 눌러 그날 <b>광고비</b>를 직접 입력합니다 — Enter 저장 후 아래 칸, Esc 취소, 비우고 저장하면 지움.
|
||||
파란 숫자 = 직접 입력, 주황 숫자 = 파일 업로드 값. 쿠팡(로켓)은 [파일 업로드]로 광고 보고서를 올리면 날짜별로 한 번에 들어갑니다.</p>
|
||||
{% endif %}
|
||||
</div>
|
||||
|
||||
<!-- ── 그래프 ── -->
|
||||
<div class="perf-grid2">
|
||||
<div class="erp-card perf-card">
|
||||
<div class="perf-card-head"><h2 class="perf-h">{% if period_kind == 'year' %}월별{% else %}일별{% endif %} 광고비 추이</h2></div>
|
||||
<div class="perf-chart" id="perf-chart-daily"></div>
|
||||
</div>
|
||||
<div class="erp-card perf-card">
|
||||
<div class="perf-card-head"><h2 class="perf-h">채널별 비중</h2>
|
||||
<span class="perf-muted">{{ period.label }}</span></div>
|
||||
<div class="perf-chart" id="perf-chart-share"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ── 월 누적 · 연간 누적 ── -->
|
||||
<div class="perf-grid2">
|
||||
<div class="erp-card perf-card">
|
||||
<div class="perf-card-head"><h2 class="perf-h">{{ month.label }} 채널별 광고비</h2></div>
|
||||
<div class="erp-table-wrap">
|
||||
<table class="perf-table">
|
||||
<thead><tr><th class="perf-th-label">채널</th><th>광고비</th><th>비중</th></tr></thead>
|
||||
<tbody>
|
||||
{% for r in month.rows %}
|
||||
<tr>
|
||||
<th class="perf-td-label" scope="row">{{ names[r.code] }}</th>
|
||||
<td class="perf-num">{{ won(r.gross) }}</td>
|
||||
<td class="perf-num perf-share">
|
||||
{% if r.share is not none %}<span class="perf-bar" style="--w: {{ [r.share, 0] | max }}%"></span>{{ "%.1f" | format(r.share) }}%{% else %}<span class="perf-zero">–</span>{% endif %}
|
||||
</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
<tfoot>
|
||||
<tr class="perf-row-total">
|
||||
<th class="perf-td-label" scope="row">합계</th>
|
||||
<td class="perf-num">{{ won(month.total.gross) }}</td>
|
||||
<td class="perf-num">{% if month.total.share is not none %}100%{% else %}<span class="perf-zero">–</span>{% endif %}</td>
|
||||
</tr>
|
||||
</tfoot>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="erp-card perf-card">
|
||||
<div class="perf-card-head"><h2 class="perf-h">{{ year.year }}년 누적 광고비</h2></div>
|
||||
<div class="perf-year-sum">
|
||||
<div><span>광고비</span><b>₩{{ "{:,}".format(year.total.gross) }}</b></div>
|
||||
</div>
|
||||
<div class="erp-table-wrap">
|
||||
<table class="perf-table perf-year">
|
||||
<thead><tr><th class="perf-th-label">월</th><th>광고비</th></tr></thead>
|
||||
<tbody>
|
||||
{% for r in year.rows %}
|
||||
<tr class="{% if r.future %}is-future{% endif %}">
|
||||
<th class="perf-td-label" scope="row">{{ r.label }}</th>
|
||||
<td class="perf-num">{{ won(r.gross) }}</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
<tfoot>
|
||||
<tr class="perf-row-total">
|
||||
<th class="perf-td-label" scope="row">합계</th>
|
||||
<td class="perf-num">{{ won(year.total.gross) }}</td>
|
||||
</tr>
|
||||
</tfoot>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p class="perf-foot perf-muted">
|
||||
광고비 기준: 쿠팡(로켓)은 광고 보고서의 청구금액(+부가가치세). 매출 대비 광고비 = 같은 기간 광고비 ÷ 매출 실적 총매출.
|
||||
구글·메타·쿠팡(윙)은 지금은 직접 입력합니다.
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<script type="application/json" id="perf-data">{{ {
|
||||
"names": names,
|
||||
"codes": codes,
|
||||
"daily": chart_daily,
|
||||
"share": chart_share,
|
||||
"period_kind": period_kind,
|
||||
"today": today,
|
||||
"manual_api": "/performance/api/ad-spend/",
|
||||
"manual_word": "광고비",
|
||||
"empty_text": "기간 내 광고비가 없습니다.",
|
||||
"upload_channels": upload_channels
|
||||
} | tojson }}</script>
|
||||
{% endblock %}
|
||||
|
||||
{% block scripts %}<script src="/static/performance.js?v=20261013d" defer></script>{% endblock %}
|
||||
@@ -1,6 +1,6 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261013c" />{% endblock %}
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261013d" />{% endblock %}
|
||||
|
||||
{%- macro won(v) -%}
|
||||
{%- if v is none -%}<span class="perf-na"></span>
|
||||
@@ -255,4 +255,4 @@
|
||||
} | tojson }}</script>
|
||||
{% endblock %}
|
||||
|
||||
{% block scripts %}<script src="/static/performance.js?v=20261013b" defer></script>{% endblock %}
|
||||
{% block scripts %}<script src="/static/performance.js?v=20261013d" defer></script>{% endblock %}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261013c" />{% endblock %}
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261013d" />{% endblock %}
|
||||
|
||||
{%- macro when(v) -%}{{ (v or '')[:16] | replace('T', ' ') or '—' }}{%- endmacro -%}
|
||||
|
||||
@@ -204,4 +204,4 @@
|
||||
</section>
|
||||
{% endblock %}
|
||||
|
||||
{% block scripts %}<script src="/static/performance.js?v=20261013b" defer></script>{% endblock %}
|
||||
{% block scripts %}<script src="/static/performance.js?v=20261013d" defer></script>{% endblock %}
|
||||
|
||||
@@ -0,0 +1,164 @@
|
||||
"""광고비 — 쿠팡(로켓) 광고 보고서 읽기(CSV·엑셀) · 화면 데이터 조립."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
from datetime import date
|
||||
|
||||
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년 10월 06일,RETAIL,Taxable,,,,,,,,,,1,0,1,1,1,0,9\n" # 같은 날 두 번
|
||||
bad += "2026년 13월 40일,RETAIL,,,,,,,,,,,1,0,1,1,1,0,1\n" # 날짜 오류
|
||||
bad += "2026년 10월 07일,RETAIL,,,,,,,,,,,1,0,1,1,1,0,\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) == 4, res.errors
|
||||
assert "겹칩니다" in joined and "날짜를 읽을 수 없습니다" in joined and "비어 있습니다" in joined and "앞으로의 날짜" in joined
|
||||
|
||||
|
||||
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):
|
||||
return {(date(2026, 10, 5), "cafe24"): 2_700_000}
|
||||
|
||||
|
||||
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", "coupang_wing", "coupang_rocket"]
|
||||
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"]] == ["coupang_rocket"]
|
||||
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
|
||||
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=""):
|
||||
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()
|
||||
bad = ROCKET_CSV + "2026년 10월 06일,RETAIL,,,,,,,,,,,1,0,1,1,1,0,9\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/naver/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"]
|
||||
@@ -25,13 +25,41 @@
|
||||
.perf-center { text-align: center; }
|
||||
|
||||
/* 탭 */
|
||||
.perf-tabs { display: flex; gap: 4px; border-bottom: 1px solid var(--perf-line); }
|
||||
.perf-tab {
|
||||
padding: 8px 14px; font-size: 13px; font-weight: 500; color: var(--color-midtone-gray);
|
||||
border-bottom: 2px solid transparent; margin-bottom: -1px;
|
||||
/* [매출 실적] [광고비] — 큰 알약 탭 둘, 고른 탭은 채운 색(매출 = 검정, 광고비 = 주황)으로 한눈에 구분.
|
||||
설정은 맨 오른쪽 톱니 아이콘(프로젝트 모듈과 같은 Material Symbols "settings"). */
|
||||
.perf-tabs {
|
||||
display: flex; align-items: center; gap: 8px; padding-bottom: 10px; border-bottom: 1px solid var(--perf-line);
|
||||
}
|
||||
.perf-tab:hover { color: var(--color-rich-black); }
|
||||
.perf-tab.is-active { color: var(--color-rich-black); border-bottom-color: var(--color-rich-black); }
|
||||
.perf-tabs-main {
|
||||
display: inline-flex; gap: 4px; padding: 4px; border-radius: 12px; background: var(--color-ghost-gray, #f3f3f3);
|
||||
}
|
||||
.perf-tab {
|
||||
display: inline-flex; align-items: center; gap: 6px; padding: 7px 16px; border-radius: 9px;
|
||||
font-size: 14px; font-weight: 600; color: var(--color-midtone-gray); text-decoration: none;
|
||||
transition: background .15s, color .15s, box-shadow .15s;
|
||||
}
|
||||
.perf-tab .material-symbols-outlined { font-size: 19px; }
|
||||
.perf-tab:hover { color: var(--color-rich-black); background: rgba(255, 255, 255, .7); }
|
||||
.perf-tab.is-active { color: #fff; box-shadow: 0 1px 3px rgba(0, 0, 0, .18); }
|
||||
.perf-tab-sales.is-active, .perf-tab-sales.is-active:hover { background: var(--color-deep-black, #1e1f21); }
|
||||
.perf-tab-ads.is-active, .perf-tab-ads.is-active:hover { background: var(--perf-ad, #d9480f); }
|
||||
a.perf-tab.is-active:link, a.perf-tab.is-active:visited { color: #fff; }
|
||||
.perf-tab-gear {
|
||||
margin-left: auto; display: inline-flex; align-items: center; justify-content: center; width: 36px; height: 36px;
|
||||
border-radius: 50%; color: var(--color-midtone-gray); text-decoration: none;
|
||||
}
|
||||
.perf-tab-gear .material-symbols-outlined { font-size: 22px; }
|
||||
.perf-tab-gear:hover { color: var(--color-rich-black); background: var(--color-ghost-gray, #f3f3f3); }
|
||||
.perf-tab-gear.is-active { color: #fff; background: var(--color-deep-black, #1e1f21); }
|
||||
|
||||
/* 광고비 화면 — 주황 강조(매출 실적과 구분) */
|
||||
.perf, .perf-modal { --perf-ad: #d9480f; }
|
||||
.perf-ads .perf-kpi.is-primary { border-color: var(--perf-ad); box-shadow: inset 4px 0 0 var(--perf-ad); }
|
||||
.perf-ads .perf-quick .perf-seg.is-active { background: var(--perf-ad); }
|
||||
.perf-ads .perf-chart .bar { fill: var(--perf-ad); }
|
||||
.perf-ads td.is-upload .v-gross { color: var(--perf-ad); }
|
||||
.perf-ad-upload-btn { margin-left: auto; }
|
||||
.perf-kpi-pct { font-size: 26px; font-weight: 700; }
|
||||
|
||||
/* 도구 막대 */
|
||||
.perf-toolbar { display: flex; flex-wrap: wrap; align-items: center; gap: 8px 12px; }
|
||||
@@ -229,6 +257,9 @@ td.is-link:hover { background: #eef2ff; text-decoration: underline; }
|
||||
.perf-test-result.is-ok { color: #0f8a3a; }
|
||||
.perf-test-result.is-bad { color: var(--perf-down); }
|
||||
|
||||
@media (min-width: 1281px) {
|
||||
.perf-ads .perf-kpis { grid-template-columns: repeat(4, minmax(0, 1fr)); } /* 광고비 KPI 4개 */
|
||||
}
|
||||
@media (max-width: 1280px) {
|
||||
.perf-kpis { grid-template-columns: repeat(3, minmax(0, 1fr)); }
|
||||
}
|
||||
|
||||
@@ -236,15 +236,20 @@
|
||||
const data = JSON.parse((document.getElementById("perf-data") || {}).textContent || "{}");
|
||||
const METRIC_NAMES = { gross: "총매출", commission: "수수료", net: "수수료 차감 매출" };
|
||||
const KEY = "perf_metric";
|
||||
const FIXED_METRIC = root.dataset.fixedMetric || ""; // 광고비 화면 = 금액 하나(gross)뿐
|
||||
const MANUAL_API = data.manual_api || "/performance/api/manual-sales/";
|
||||
const MANUAL_WORD = data.manual_word || "총매출";
|
||||
const EMPTY_TEXT = data.empty_text || "기간 내 매출이 없습니다.";
|
||||
|
||||
// 표시 기준 전환 — 서버가 세 값을 다 그려 두었고 CSS 가 하나만 보인다.
|
||||
function setMetric(m) {
|
||||
if (FIXED_METRIC) m = FIXED_METRIC;
|
||||
if (!METRIC_NAMES[m]) m = "gross";
|
||||
root.dataset.metric = m;
|
||||
root.querySelectorAll(".perf-metric .perf-seg").forEach(function (b) {
|
||||
b.classList.toggle("is-active", b.dataset.metric === m);
|
||||
});
|
||||
try { localStorage.setItem(KEY, m); } catch (_) {}
|
||||
if (!FIXED_METRIC) { try { localStorage.setItem(KEY, m); } catch (_) {} }
|
||||
drawDaily(m);
|
||||
drawShare(m);
|
||||
root.querySelectorAll(".perf-metric-name").forEach(function (n) { n.textContent = METRIC_NAMES[m]; });
|
||||
@@ -311,6 +316,69 @@
|
||||
});
|
||||
});
|
||||
|
||||
// 광고비 파일 업로드 — 채널(양식이 정해진 채널만)을 고르고 파일을 올리면 파일에 있는 날만 덮어쓴다.
|
||||
// 잘못된 줄이 있으면 서버가 아무것도 저장하지 않고 줄 위치 목록을 돌려준다.
|
||||
const adUploadBtn = document.getElementById("perf-ad-upload");
|
||||
if (adUploadBtn) adUploadBtn.addEventListener("click", function () {
|
||||
let saved = false;
|
||||
const chans = data.upload_channels || [];
|
||||
const m = openModal("광고비 파일 업로드", { narrow: true, onClose: function () { if (saved) location.reload(); } });
|
||||
m.body.innerHTML =
|
||||
'<label class="perf-muted" style="display:block;margin:0 0 4px">채널</label>' +
|
||||
'<select class="erp-input perf-ad-channel" style="width:100%;margin:0 0 6px">' + chans.map(function (c) {
|
||||
return '<option value="' + esc(c.code) + '">' + esc(c.name) + "</option>";
|
||||
}).join("") + "</select>" +
|
||||
'<p class="perf-muted perf-ad-help" style="margin:0 0 10px"></p>' +
|
||||
'<input type="file" class="erp-input perf-upload-file" accept=".csv,.xlsx,text/csv,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" aria-label="광고 보고서 파일" />' +
|
||||
'<div class="perf-upload-result"></div>';
|
||||
const sel = m.body.querySelector(".perf-ad-channel");
|
||||
const help = m.body.querySelector(".perf-ad-help");
|
||||
function showHelp() {
|
||||
const c = chans.filter(function (x) { return x.code === sel.value; })[0];
|
||||
help.textContent = c ? c.help : "";
|
||||
}
|
||||
sel.addEventListener("change", showHelp);
|
||||
showHelp();
|
||||
const fileInput = m.body.querySelector(".perf-upload-file");
|
||||
const out = m.body.querySelector(".perf-upload-result");
|
||||
const go = el("button", { type: "button", class: "erp-btn erp-btn-primary" }, "업로드");
|
||||
const cancel = el("button", { type: "button", class: "erp-btn erp-btn-ghost" }, "닫기");
|
||||
m.foot.appendChild(cancel);
|
||||
m.foot.appendChild(go);
|
||||
cancel.addEventListener("click", m.close);
|
||||
go.addEventListener("click", async function () {
|
||||
const f = fileInput.files && fileInput.files[0];
|
||||
if (!f) { out.innerHTML = '<p class="perf-notice is-warn">파일을 고르세요.</p>'; return; }
|
||||
go.disabled = true;
|
||||
out.innerHTML = '<p class="perf-muted">올리는 중…</p>';
|
||||
const fd = new FormData();
|
||||
fd.append("file", f);
|
||||
let res, body = null;
|
||||
try {
|
||||
res = await fetch("/performance/api/ad-spend/upload?channel=" + encodeURIComponent(sel.value),
|
||||
{ method: "POST", credentials: "same-origin", body: fd });
|
||||
try { body = await res.json(); } catch (_) { body = null; }
|
||||
} catch (err) {
|
||||
out.innerHTML = '<p class="perf-notice is-warn">업로드 실패: ' + esc(err.message) + "</p>";
|
||||
go.disabled = false;
|
||||
return;
|
||||
}
|
||||
go.disabled = false;
|
||||
if (!res.ok) {
|
||||
const detail = body && typeof body.detail === "string" ? body.detail : "업로드 실패 (" + res.status + ")";
|
||||
const errs = body && body.errors && body.errors.length
|
||||
? '<ul class="perf-upload-errors">' + body.errors.map(function (e) { return "<li>" + esc(e) + "</li>"; }).join("") + "</ul>" : "";
|
||||
out.innerHTML = '<p class="perf-notice is-warn">' + esc(detail) + "</p>" + errs;
|
||||
return;
|
||||
}
|
||||
saved = body.saved > 0;
|
||||
out.innerHTML = '<p class="perf-notice is-ok">' + esc(body.name) + " " + fmt(body.saved) + "일 반영 (" +
|
||||
esc(body.from === body.to ? body.from : body.from + " ~ " + body.to) + ") · 합계 " + fmt(body.total) + "원</p>" +
|
||||
'<p class="perf-muted" style="margin:6px 0 0">창을 닫으면 표·합계·그래프가 다시 계산됩니다.</p>';
|
||||
fileInput.value = "";
|
||||
});
|
||||
});
|
||||
|
||||
// 직접선택 / 쇼핑몰 필터
|
||||
const customBtn = document.getElementById("perf-custom-btn");
|
||||
const customForm = document.getElementById("perf-custom");
|
||||
@@ -413,13 +481,15 @@
|
||||
if (raw !== "" && !/^-?\d+$/.test(raw)) return Promise.reject(new Error("숫자(원)만 입력하세요."));
|
||||
if (raw === was) return Promise.resolve(false); // 바뀐 것 없음(빈 칸 그대로 포함)
|
||||
const job = manualChain.then(function () {
|
||||
return api("PUT", "/performance/api/manual-sales/" + encodeURIComponent(td.dataset.manualCode) + "/" +
|
||||
return api("PUT", MANUAL_API + encodeURIComponent(td.dataset.manualCode) + "/" +
|
||||
encodeURIComponent(td.dataset.date), { amount: raw === "" ? null : Number(raw) });
|
||||
}).then(function (res) {
|
||||
const manual = res.manual == null ? "" : String(res.manual);
|
||||
td.dataset.manualValue = manual;
|
||||
td.classList.toggle("is-manual", manual !== "");
|
||||
td.title = manual !== "" ? "수동 입력값 — 눌러 고치기(비우고 저장하면 API 값)" : "눌러 총매출 직접 입력";
|
||||
td.classList.remove("is-upload");
|
||||
td.title = manual !== "" ? "직접 입력값 — 눌러 고치기(비우고 저장하면 " + (FIXED_METRIC ? "지움" : "API 값") + ")"
|
||||
: "눌러 " + MANUAL_WORD + " 직접 입력";
|
||||
const g = td.querySelector(".v-gross");
|
||||
if (g) g.innerHTML = won(res.amount);
|
||||
td.classList.add("is-stale"); // 수수료·차감 매출은 새로고침 때 다시 계산
|
||||
@@ -432,10 +502,10 @@
|
||||
function editManual(td) {
|
||||
if (td.querySelector(".perf-manual-input")) return;
|
||||
const input = el("input", { type: "text", inputmode: "numeric", class: "perf-manual-input",
|
||||
"aria-label": ((data.names || {})[td.dataset.manualCode] || "") + " " + td.dataset.date + " 총매출" });
|
||||
"aria-label": ((data.names || {})[td.dataset.manualCode] || "") + " " + td.dataset.date + " " + MANUAL_WORD });
|
||||
input.value = digitsOf(td);
|
||||
const g = td.querySelector(".v-gross");
|
||||
input.placeholder = digitsOf(td) ? "" : (g ? g.textContent.trim().replace(/[–-]/, "") : "") || "총매출";
|
||||
input.placeholder = digitsOf(td) ? "" : (g ? g.textContent.trim().replace(/[–-]/, "") : "") || MANUAL_WORD;
|
||||
td.classList.add("is-editing");
|
||||
td.appendChild(input);
|
||||
input.focus();
|
||||
@@ -529,7 +599,7 @@
|
||||
const pts = data.daily || [];
|
||||
const vals = pts.map(function (p) { return p[metric] || 0; });
|
||||
if (!pts.length || vals.every(function (v) { return !v; })) {
|
||||
box.innerHTML = '<div class="perf-chart-empty">기간 내 매출이 없습니다.</div>';
|
||||
box.innerHTML = '<div class="perf-chart-empty">' + esc(EMPTY_TEXT) + "</div>";
|
||||
return;
|
||||
}
|
||||
const W = 640, H = 230, L = 48, R = 8, T = 10, B = 26;
|
||||
@@ -560,7 +630,7 @@
|
||||
if (!box) return;
|
||||
const rows = (data.share || []).slice().sort(function (a, b) { return (b[metric] || 0) - (a[metric] || 0); });
|
||||
const total = rows.reduce(function (s, r) { return s + Math.max(0, r[metric] || 0); }, 0);
|
||||
if (!rows.length || total <= 0) { box.innerHTML = '<div class="perf-chart-empty">기간 내 매출이 없습니다.</div>'; return; }
|
||||
if (!rows.length || total <= 0) { box.innerHTML = '<div class="perf-chart-empty">' + esc(EMPTY_TEXT) + "</div>"; return; }
|
||||
const W = 640, rowH = 22, L = 120, R = 150, H = rows.length * rowH + 6;
|
||||
const maxV = Math.max.apply(null, rows.map(function (r) { return Math.max(0, r[metric] || 0); })) || 1;
|
||||
let g = "";
|
||||
|
||||
@@ -184,6 +184,19 @@ cd /opt/www/main
|
||||
docker exec -i postgres-db psql -v ON_ERROR_STOP=1 -U postgres -d performance_db < scripts/sql/performance_db_004_naver_name.sql
|
||||
```
|
||||
|
||||
## 실적 광고비 마이그레이션 (performance_db 005)
|
||||
|
||||
005는 광고비 표 `perf_ad_spend` 하나만 만든다(기존 표·데이터 그대로, 다시 실행 가능). 미적용이면 광고비 탭에 안내가 나오고 입력·업로드가 503.
|
||||
|
||||
```bash
|
||||
cd /opt/www/main
|
||||
docker exec postgres-db pg_dump -U postgres performance_db > ~/performance_db_before_005_$(date +%Y%m%d%H%M).sql
|
||||
docker exec -i postgres-db psql -v ON_ERROR_STOP=1 -U postgres -d performance_db < scripts/sql/performance_db_005_ad_spend.sql
|
||||
docker exec postgres-db psql -U postgres -d performance_db -c "\d perf_ad_spend"
|
||||
```
|
||||
|
||||
되돌리기(광고비 데이터만 사라짐): `docker exec postgres-db psql -U postgres -d performance_db -c "DROP TABLE perf_ad_spend;"`
|
||||
|
||||
## 회의록 작업 등록 표 — 작업 칸 마이그레이션 (026)
|
||||
|
||||
026은 `goal_meeting_tasks.parent_task_id` 열만 추가한다(기존 값 그대로, 다시 실행 가능). 025 뒤에 적용한다. 미적용이면 작업 칸을 고를 때만 503 안내.
|
||||
|
||||
@@ -339,6 +339,17 @@
|
||||
|
||||
## 7. 화면
|
||||
|
||||
- **탭**(2026-10-13): 왼쪽 위 큰 탭 둘 — [매출 실적](검정, `/performance/`) · [광고비](주황, `/performance/ads`) — 아이콘 + 고른 탭 색으로 구분,
|
||||
설정은 맨 오른쪽 톱니 아이콘(프로젝트 모듈과 같은 Material Symbols `settings`, `/performance/settings`). `_tabs.html`.
|
||||
- **광고비** `/performance/ads?period=…`(기본 이번달) — 매출 실적과 같은 기간 이동(오늘/이번주/이번달/올해/직접선택)·표(일자 × 채널,
|
||||
연간은 월)·일별 추이·채널 비중·월/연 누적. 채널 = 구글·메타·쿠팡(윙)·쿠팡(로켓)(`ad_spend.CHANNELS`, 앱이 정함).
|
||||
KPI: 기간 광고비(전기간 대비), 매출 대비 광고비(같은 기간 광고비 ÷ 매출 실적 총매출), 월·연 누적.
|
||||
저장 `perf_ad_spend`(마이그레이션 005 — 채널 × 날짜 하나에 금액, `source` manual/upload/api), 미적용이면 화면에 안내·API 503.
|
||||
- 날짜 칸을 눌러 직접 입력(`PUT /api/ad-spend/{channel}/{day}`, 비우면 지움, 오늘까지) — 파란 숫자. 매출 수동 입력과 같은 JS(`MANUAL_API`).
|
||||
- [파일 업로드](`POST /api/ad-spend/upload?channel=`) — 양식이 정해진 채널만(`ad_spend.PARSERS`). 파일에 있는 날만 덮어쓰고(주황 숫자),
|
||||
잘못된 줄이 하나라도 있으면 아무것도 저장하지 않는다. **쿠팡(로켓)** = 쿠팡 광고 보고서 CSV(UTF-8/CP949)·엑셀:
|
||||
1열 날짜(`2026년 10월 01일`), 19열 청구금액(+부가가치세). "전체" 합계 줄·머리글·캠페인 줄(1열 빈 칸)은 건너뜀.
|
||||
- 쿠팡(윙)·구글·메타 업로드 양식/API 는 아직 — 지금은 직접 입력.
|
||||
- **대시보드** `/performance/?period=day|week|month|year|custom&d=&from=&to=&m=<쇼핑몰>…`
|
||||
기간 버튼(오늘/이번주/이번달/올해/직접선택) + 이전/다음, 쇼핑몰 필터, KPI 5개, 일자×쇼핑몰 표(주간합계·기간합계, 연간은 월 행),
|
||||
[총매출|수수료|수수료 차감 매출] 전환(서버가 세 값을 다 그리고 CSS 로 전환, 선택은 localStorage), 일별 추이·쇼핑몰 비중(SVG),
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
-- =====================================================================
|
||||
-- performance_db 마이그레이션 005 — 광고비(채널 × 날짜)
|
||||
-- =====================================================================
|
||||
-- 멱등(idempotent). 새 표 하나만 만든다(기존 표·데이터 그대로). 운영: /opt/www/main 에서 superuser 로 적용.
|
||||
-- docker exec -i postgres-db psql -v ON_ERROR_STOP=1 -U postgres -d performance_db \
|
||||
-- < scripts/sql/performance_db_005_ad_spend.sql
|
||||
--
|
||||
-- 왜(2026-10-13 사용자 요청): 실적 모듈 "광고비" 탭 — 구글·메타·쿠팡(윙)·쿠팡(로켓) 광고비를 연·월·일로.
|
||||
-- 쿠팡(로켓)은 광고 보고서 파일 업로드(1열 날짜, 19열 청구금액(+부가가치세)), 나머지는 날짜 칸 직접 입력.
|
||||
-- 채널 목록은 앱(app/modules/performance/ad_spend.py CHANNELS)이 정한다 — 채널을 늘려도 이 표는 그대로.
|
||||
-- 되돌리기: DROP TABLE perf_ad_spend; (광고비 데이터만 사라짐 — 실행 전 백업)
|
||||
-- =====================================================================
|
||||
BEGIN;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS perf_ad_spend (
|
||||
channel_code TEXT NOT NULL,
|
||||
spend_date DATE NOT NULL,
|
||||
amount BIGINT NOT NULL,
|
||||
source TEXT NOT NULL DEFAULT 'manual' CHECK (source IN ('manual', 'upload', 'api')),
|
||||
updated_by TEXT NOT NULL DEFAULT '',
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (channel_code, spend_date)
|
||||
);
|
||||
COMMENT ON TABLE perf_ad_spend IS '광고비 — 채널(google·meta·coupang_wing·coupang_rocket) × 날짜 하나에 금액 하나(원)';
|
||||
COMMENT ON COLUMN perf_ad_spend.source IS 'manual=화면 직접 입력, upload=파일 업로드, api=광고 API 수집';
|
||||
CREATE INDEX IF NOT EXISTS idx_perf_ad_spend_date ON perf_ad_spend (spend_date);
|
||||
DROP TRIGGER IF EXISTS trg_perf_ad_spend_updated ON perf_ad_spend;
|
||||
CREATE TRIGGER trg_perf_ad_spend_updated
|
||||
BEFORE UPDATE ON perf_ad_spend
|
||||
FOR EACH ROW EXECUTE FUNCTION perf_set_updated_at();
|
||||
|
||||
GRANT SELECT, INSERT, UPDATE, DELETE ON perf_ad_spend TO performance_app;
|
||||
|
||||
COMMIT;
|
||||
SELECT 'performance_db 005 ad spend ready' AS status;
|
||||
@@ -20,8 +20,17 @@ async function env(file) {
|
||||
w.erpAlert = function (m) { e.alerts.push(m); return Promise.resolve(); };
|
||||
w.fetch = async function (url, o) {
|
||||
const method = (o && o.method) || "GET";
|
||||
const body = o && o.body ? JSON.parse(o.body) : null;
|
||||
e.calls.push({ method: method, url: url, body: body });
|
||||
const isForm = o && o.body && typeof o.body !== "string";
|
||||
const body = o && o.body && !isForm ? JSON.parse(o.body) : null;
|
||||
e.calls.push({ method: method, url: url, body: body, form: isForm ? o.body : null });
|
||||
if (/^\/performance\/api\/ad-spend\/upload/.test(url)) {
|
||||
return { ok: true, status: 200, json: async function () {
|
||||
return { ok: true, saved: 12, name: "쿠팡(로켓)", total: 2636494, from: "2026-10-01", to: "2026-10-12" }; } };
|
||||
}
|
||||
const ad = /^\/performance\/api\/ad-spend\/([^/]+)\/([\d-]+)$/.exec(url);
|
||||
if (ad) {
|
||||
return { ok: true, status: 200, json: async function () { return { ok: true, manual: body.amount, amount: body.amount || 0 }; } };
|
||||
}
|
||||
if (e.status >= 400) return { ok: false, status: e.status, json: async function () { return { detail: "수동 입력을 쓰려면 마이그레이션 002" }; } };
|
||||
const m = /^\/performance\/api\/manual-sales\/([^/]+)\/([\d-]+)$/.exec(url);
|
||||
if (m) {
|
||||
@@ -119,13 +128,67 @@ function gross(td) { return td.querySelector(".v-gross").textContent.trim(); }
|
||||
key(e, td, "Enter");
|
||||
check("[키보드] 칸에 포커스 후 Enter → 입력칸", !!td.querySelector(".perf-manual-input"));
|
||||
}
|
||||
// ── 탭: [매출 실적] [광고비] + 맨 오른쪽 설정 톱니 ──
|
||||
{
|
||||
const e = await env("perf_dash.html");
|
||||
const tabs = Array.from(e.d.querySelectorAll(".perf-tabs-main .perf-tab")).map(function (a) { return a.textContent.replace(/monitoring|campaign/, "").trim(); });
|
||||
check("[탭] 매출 실적 · 광고비", tabs.join(",") === "매출 실적,광고비", tabs);
|
||||
check("[탭] 매출 실적이 고른 탭", e.d.querySelector(".perf-tab-sales").classList.contains("is-active") &&
|
||||
!e.d.querySelector(".perf-tab-ads").classList.contains("is-active"));
|
||||
const gear = e.d.querySelector(".perf-tabs > .perf-tab-gear");
|
||||
check("[탭] 설정 = 맨 오른쪽 톱니 아이콘(settings)", gear && gear === e.d.querySelector(".perf-tabs").lastElementChild &&
|
||||
gear.getAttribute("href") === "/performance/settings" && gear.textContent.trim() === "settings" && !!gear.title);
|
||||
}
|
||||
// ── 광고비 화면 ──
|
||||
{
|
||||
const e = await env("perf_ads.html");
|
||||
check("[광고비] 광고비 탭이 고른 탭", e.d.querySelector(".perf-tab-ads").classList.contains("is-active"));
|
||||
const heads = Array.from(e.d.querySelectorAll(".perf-main thead th")).map(function (th) { return th.textContent.replace("✎", "").trim(); });
|
||||
check("[광고비] 열 = 구글·메타·쿠팡(윙)·쿠팡(로켓)", heads.join(",") === "날짜,구글,메타,쿠팡(윙),쿠팡(로켓),일 합계", heads);
|
||||
const up = cell(e, "coupang_rocket", "2026-10-01"), man = cell(e, "google", "2026-10-02");
|
||||
check("[광고비] 업로드 값 = 주황(is-upload), 직접 입력 = 파랑(is-manual)", up.classList.contains("is-upload") &&
|
||||
!up.classList.contains("is-manual") && man.classList.contains("is-manual") && gross(up) === "220,000");
|
||||
check("[광고비] 앞으로의 날은 입력 칸 아님", !cell(e, "google", "2026-10-08") && !!cell(e, "google", "2026-10-07"));
|
||||
const kpi = Array.from(e.d.querySelectorAll(".perf-kpi-value")).map(function (n) { return n.textContent.trim(); });
|
||||
check("[광고비] KPI — 이번달 광고비 270,000 · 매출 대비 비율", kpi[0] === "₩270,000" && /%$/.test(kpi[1]), kpi);
|
||||
check("[광고비] 매출 실적의 수수료 전환 없음", !e.d.querySelector(".perf-metric") && e.d.getElementById("perf-dash").dataset.metric === "gross");
|
||||
const td = cell(e, "meta", "2026-10-03");
|
||||
td.click();
|
||||
const inp = td.querySelector(".perf-manual-input");
|
||||
check("[광고비] 칸을 누르면 입력칸(광고비)", !!inp && /광고비/.test(inp.getAttribute("aria-label")));
|
||||
inp.value = "33,000";
|
||||
key(e, inp, "Escape");
|
||||
td.click();
|
||||
const inp2 = td.querySelector(".perf-manual-input");
|
||||
inp2.value = "33,000";
|
||||
inp2.dispatchEvent(new e.w.FocusEvent("blur"));
|
||||
await settle();
|
||||
const put = e.calls.find(function (c) { return c.method === "PUT"; });
|
||||
check("[광고비] 저장 → /api/ad-spend/meta/2026-10-03 (33000)", put && put.url === "/performance/api/ad-spend/meta/2026-10-03" &&
|
||||
put.body.amount === 33000, e.calls);
|
||||
check("[광고비] 저장 후 파란 표시", gross(td) === "33,000" && td.classList.contains("is-manual"));
|
||||
// 파일 업로드 창
|
||||
e.d.getElementById("perf-ad-upload").click();
|
||||
const modal = e.d.querySelector(".perf-modal");
|
||||
const opts = Array.from(modal.querySelectorAll(".perf-ad-channel option")).map(function (o) { return o.value; });
|
||||
check("[업로드] 채널 선택 = 양식이 정해진 쿠팡(로켓)", opts.join(",") === "coupang_rocket", opts);
|
||||
check("[업로드] 양식 안내(19열 청구금액)", /19열/.test(modal.querySelector(".perf-ad-help").textContent));
|
||||
const fileInput = modal.querySelector(".perf-upload-file");
|
||||
const f = new e.w.File(["날짜"], "rocket.csv", { type: "text/csv" });
|
||||
Object.defineProperty(fileInput, "files", { value: [f] });
|
||||
Array.from(modal.querySelectorAll(".perf-modal-foot button, button")).filter(function (b) { return b.textContent === "업로드"; })[0].click();
|
||||
await settle();
|
||||
const post = e.calls.find(function (c) { return c.method === "POST"; });
|
||||
check("[업로드] POST /api/ad-spend/upload?channel=coupang_rocket (파일)", post && post.url === "/performance/api/ad-spend/upload?channel=coupang_rocket" && !!post.form, e.calls);
|
||||
check("[업로드] 결과 안내(12일 반영)", /12일 반영/.test(modal.querySelector(".perf-upload-result").textContent));
|
||||
}
|
||||
// ── 설정: 수동 입력 토글 ──
|
||||
{
|
||||
const e = await env("perf_settings.html");
|
||||
const heads = Array.from(e.d.querySelectorAll(".perf-set-table thead th")).map(function (th) { return th.textContent.trim(); });
|
||||
check("[설정] '수동 입력' 열(매출 집계 다음)", heads.indexOf("수동 입력") === heads.indexOf("매출 집계") + 1, heads);
|
||||
const rows = Array.from(e.d.querySelectorAll(".perf-set-table tbody tr")).map(function (tr) { return tr.dataset.code; });
|
||||
check("[설정] 쇼핑몰 순서 = 표 순서", rows.join(",") === "cafe24,naver,coupang,toss,gsshop,elevenst,ohouse,gmarket,kakao,lotteon", rows);
|
||||
check("[설정] 쇼핑몰 순서 = 어댑터 등록 순서(003 열 순서)", rows.join(",") === "cafe24,naver,coupang,ohouse,gmarket,kakao,gsshop,elevenst,lotteon,toss", rows);
|
||||
const box = e.d.querySelector('tr[data-code="coupang"] input[data-field="manual_input"]');
|
||||
check("[설정] 켜진 쇼핑몰은 체크", box && box.checked && !e.d.querySelector('tr[data-code="cafe24"] input[data-field="manual_input"]').checked);
|
||||
box.checked = false;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"""실적 대시보드(index.html)·설정(settings.html)을 테스트용 HTML 로 렌더한다(erp_base.html 은 최소 스텁, 가상의 데이터).
|
||||
"""실적 대시보드(index.html)·광고비(ads.html)·설정(settings.html)을 테스트용 HTML 로 렌더한다(erp_base.html 은 최소 스텁, 가상의 데이터).
|
||||
|
||||
python tests/js/render_performance.py # → tests/js/.out/perf_dash.html · perf_settings.html
|
||||
python tests/js/render_performance.py # → tests/js/.out/perf_dash.html · perf_ads.html · perf_settings.html
|
||||
|
||||
화면 데이터는 실제 build_dashboard·build_settings 로 만든다(저장소만 가짜). DB·쇼핑몰 API 는 쓰지 않는다.
|
||||
쿠팡은 수동 입력 켬(10/5 수동 값 87,000, 10/6 은 API 값만), 카카오도 켬(값 없음), 나머지는 끔.
|
||||
@@ -19,6 +19,7 @@ ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)
|
||||
sys.path.insert(0, ROOT)
|
||||
OUT_DIR = os.path.join(ROOT, "tests", "js", ".out")
|
||||
|
||||
from app.modules.performance.ad_spend import build_ad_dashboard # noqa: E402
|
||||
from app.modules.performance.dashboard import build_dashboard, build_settings # noqa: E402
|
||||
|
||||
BASE_STUB = ("{% block head_extra %}{% endblock %}<body><main class='erp-page'>{% block content %}{% endblock %}</main>"
|
||||
@@ -56,6 +57,11 @@ class FakeStore:
|
||||
def running_codes(self):
|
||||
return []
|
||||
|
||||
def ad_amounts(self, start, end):
|
||||
rows = {(date(2026, 10, 1), "coupang_rocket"): (220000, "upload"), (date(2026, 10, 2), "google"): (50000, "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 env() -> jinja2.Environment:
|
||||
e = jinja2.Environment(loader=jinja2.ChoiceLoader([
|
||||
@@ -73,6 +79,11 @@ def main() -> None:
|
||||
html = e.get_template("performance/index.html").render(**base, active_tab="dashboard", metric="gross", **ctx)
|
||||
with open(os.path.join(OUT_DIR, "perf_dash.html"), "w", encoding="utf-8") as f:
|
||||
f.write(html)
|
||||
actx = build_ad_dashboard(FakeStore(), kind="month", anchor=date(2026, 10, 7), today=date(2026, 10, 7),
|
||||
sales_codes=["cafe24", "coupang"])
|
||||
html = e.get_template("performance/ads.html").render(**base, active_tab="ads", **actx)
|
||||
with open(os.path.join(OUT_DIR, "perf_ads.html"), "w", encoding="utf-8") as f:
|
||||
f.write(html)
|
||||
sctx = build_settings(FakeStore(), configured={}, key_info={}, key_versions_in_use={}, sample_count=0)
|
||||
html = e.get_template("performance/settings.html").render(**base, active_tab="settings", **sctx)
|
||||
with open(os.path.join(OUT_DIR, "perf_settings.html"), "w", encoding="utf-8") as f:
|
||||
|
||||
Reference in New Issue
Block a user