feat(performance): 날짜 칸 메모·광고비 표 열 너비 자동/날짜 열 고정·기타광고비 열

- 매출 실적·광고비 금액 입력 칸 우클릭 → 메모 삽입·수정·삭제(창), 메모 있는 칸 빨간 삼각형·마우스 올리면 메모 상자
  (마이그레이션 010 perf_cell_memos, PUT /api/cell-memos/{kind}/{code}/{date})
- 광고비 표도 열 너비 = 내용 길이, 날짜 열 가로 스크롤 고정(perf-autofit)
- 기타광고비 열(etc, 애터미아자몰 오른쪽) — ROAS 없음
- 테스트: test_cell_memos.py, perf_memo_ads.browser.test.js, 기존 채널 목록 기대값

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-22 12:40:22 +09:00
parent 317cfd2fdd
commit b8564e8f3e
17 changed files with 450 additions and 15 deletions
+10
View File
@@ -66,9 +66,19 @@
- **매출 단위** 원·천원·백만원 — 설정 "보기 설정"(누구나, 이 브라우저 쿠키 `perf_unit`), 서버가 `amount_text`(천원 정수·백만원 소수 한 자리)로 그림(`router._unit_ctx` → 템플릿 `amt`). 광고비 탭은 원 그대로.
- 설정의 진단 카드(쇼핑몰 원본 데이터 확인·카페24 매출 대조·일별 한 번에 비교)는 2026-10-19 화면에서 뺐다(서버 API `marketplaces/{code}/reconcile`·`daily-check` 는 진단용으로 남김).
## 날짜 칸 메모 (2026-10-22, 마이그레이션 010 `perf_cell_memos`)
- 매출 실적·광고비 일자별 표의 **금액 입력 칸**(`td.is-manual-cell`) 우클릭 → [메모 삽입] / [메모 수정]·[메모 삭제](`.perf-ctx` 메뉴, 창에서 입력, Ctrl+Enter 저장).
`PUT /performance/api/cell-memos/{kind}/{코드}/{날짜}` (kind = `sales` 쇼핑몰 / `ad` 광고 채널, 빈 메모 = 지움, 1,000자), 모듈 권한자 누구나.
- 메모 있는 칸 = 오른쪽 위 빨간 삼각형(`has-memo`, 엑셀 메모처럼), 마우스 올리면 노란 메모 상자(`.perf-memo-tip`). 금액과 따로 저장(금액 지워도 남음).
화면 데이터 `memo_cells`("날짜|코드" → 메모, `db.cell_memos`), 010 미적용이면 표시 없음·저장만 503. 표를 스크롤하면 열린 메뉴는 닫힌다.
- 테스트 `test_cell_memos.py`, `tests/js/perf_memo_ads.browser.test.js`.
## 광고비 (`/performance/ads`)
- 탭은 [매출 실적]·[광고비] + 맨 오른쪽 설정 톱니.
- **표 모양(2026-10-22)** — 매출 실적 표와 같은 `perf-autofit`(열 너비 = 내용 길이, 날짜 열 가로 스크롤 고정).
- **기타광고비** 열(`etc`, 애터미아자몰 오른쪽, 2026-10-22) — 쇼핑몰에 딸리지 않은 광고비 직접 입력. 매출 쇼핑몰이 없어(`ad_spend.NO_SALES`) ROAS 없음·매출 탭 광고비 줄에 안 나옴, 광고비 합계·매출 대비 광고비에는 들어감.
- `ad_spend.py`, 마이그레이션 005 `perf_ad_spend`. 구글·메타·네이버·쿠팡(윙)·쿠팡(로켓)·오늘의집·G마켓·카카오·GS샵·11번가·롯데ON·토스·애터미아자몰 일 광고비를 연·월·일로.
- 칸 = "광고비(ROAS%)"(ROAS = 그 쇼핑몰 매출 ÷ 광고비). 구글·메타·네이버는 계산 안 함 — 광고 보고서 ROAS(마이그레이션 006 `roas`·`metrics`).
- 날짜 칸 직접 입력 + 쿠팡(윙)·쿠팡(로켓)·네이버 광고 보고서 업로드.
+6 -1
View File
@@ -45,6 +45,7 @@ CHANNELS: tuple[tuple[str, str], ...] = (
("lotteon", "롯데ON"),
("toss", "토스"),
("atomy", "애터미아자몰"),
("etc", "기타광고비"), # 2026-10-22 — 쇼핑몰에 딸리지 않은 광고비(직접 입력), ROAS 없음
)
CHANNEL_NAMES = dict(CHANNELS)
CHANNEL_CODES = tuple(c for c, _ in CHANNELS)
@@ -53,7 +54,8 @@ CHANNEL_CODES = tuple(c for c, _ in CHANNELS)
# 여러 날(주·월·합계)의 ROAS = Σ(그날 ROAS × 그날 광고비) ÷ Σ광고비(ROAS 가 있는 날만) = 광고 매출 합 ÷ 광고비 합.
FILE_ROAS = frozenset({"google", "meta", "naver"})
NO_ROAS = FILE_ROAS # 예전 이름(계산 안 하는 채널)
ROAS_SALES_CODE: dict[str, str] = {c: c for c in CHANNEL_CODES if c not in FILE_ROAS}
NO_SALES = frozenset({"etc"}) # 매출 쇼핑몰이 없는 채널 — ROAS 를 계산하지 않고 매출 탭 광고비 줄에도 안 나온다
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"
@@ -605,4 +607,7 @@ def build_ad_dashboard(store: Any, *, kind: str, anchor: date, today: date,
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()},
}
+3
View File
@@ -284,6 +284,9 @@ def build_dashboard(store: Any, *, kind: str, anchor: date, today: date,
"manual_codes": manual_codes,
"manual_cells": manual_cells,
"formula_cells": formula_cells,
# 날짜 칸 메모(마이그레이션 010) — "날짜|쇼핑몰" → 메모
"memo_cells": {f"{d.isoformat()}|{c}": m for (d, c), m in
(store.cell_memos("sales", period.start, period.end) if hasattr(store, "cell_memos") else {}).items()},
# 엑셀 업로드 대상 — 수동 입력이 켜진 쇼핑몰 전부(쇼핑몰 선택 필터와 무관, 설정 순서)
"manual_upload_names": [m["name"] for m in markets if m.get("manual_input")],
"last_update_at": store.last_update_at(),
+32
View File
@@ -26,6 +26,10 @@ from app.timezone import to_kst_iso
STALE_RUN_AFTER = timedelta(minutes=30)
class MemoMigrationNeeded(Exception):
"""날짜 칸 메모(마이그레이션 010: perf_cell_memos)가 아직 적용되지 않음."""
class ManualMigrationNeeded(Exception):
"""수동 입력(마이그레이션 002: perf_marketplaces.manual_input · perf_manual_sales)이 아직 적용되지 않음."""
@@ -481,6 +485,34 @@ class PerformanceDBStore:
return {}
return {(r["sales_date"], r["marketplace_code"]): r["formula"] for r in rows}
# ════════════════════════════════════════════════════════════
# 날짜 칸 메모(마이그레이션 010) — kind 'sales'(쇼핑몰)·'ad'(광고 채널). 금액과 따로(금액을 지워도 남음).
# ════════════════════════════════════════════════════════════
def cell_memos(self, kind: str, start: date, end: date) -> dict[tuple[date, str], str]:
"""(날짜, 코드) → 메모. 010 미적용이면 비어 있음."""
try:
with self._pool.connection() as conn:
rows = conn.execute(
"SELECT memo_date, code, memo FROM perf_cell_memos WHERE kind = %s AND memo_date BETWEEN %s AND %s",
(kind, start, end)).fetchall()
except pg_errors.UndefinedTable:
return {}
return {(r["memo_date"], r["code"]): r["memo"] for r in rows}
def set_cell_memo(self, kind: str, code: str, day: date, memo: str | None, *, user: str = "") -> None:
"""메모 저장(빈 값·None = 지움). 010 미적용이면 MemoMigrationNeeded."""
try:
with self._pool.connection() as conn:
if not memo:
conn.execute("DELETE FROM perf_cell_memos WHERE kind = %s AND code = %s AND memo_date = %s", (kind, code, day))
else:
conn.execute(
"INSERT INTO perf_cell_memos (kind, code, memo_date, memo, updated_by) VALUES (%s, %s, %s, %s, %s) "
"ON CONFLICT (kind, code, memo_date) DO UPDATE SET memo = EXCLUDED.memo, updated_by = EXCLUDED.updated_by, "
"updated_at = now()", (kind, code, day, memo, user))
except pg_errors.UndefinedTable:
raise MemoMigrationNeeded() from None
# ════════════════════════════════════════════════════════════
# 광고비(마이그레이션 005)
# ════════════════════════════════════════════════════════════
+32
View File
@@ -498,6 +498,38 @@ def _ad_channel(channel: str) -> str:
return channel
MEMO_MAX = 1000
@router.put("/api/cell-memos/{kind}/{code}/{day}")
def api_cell_memo(request: Request, kind: str, code: str, day: str, payload: dict[str, Any] = Body(...)) -> JSONResponse:
"""날짜 칸 메모(2026-10-22, 마이그레이션 010) — kind = sales(매출 실적, 쇼핑몰) / ad(광고비, 광고 채널).
memo 가 비면 지움. 칸에 금액을 넣을 수 있는 사람(모듈 권한자 누구나)이 쓴다."""
from .ad_spend import CHANNEL_NAMES # noqa: WPS433
from .db import MemoMigrationNeeded # noqa: WPS433
store, user = common.require_store(request)
if kind == "sales":
_code_or_404(store, code)
elif kind == "ad":
if code not in CHANNEL_NAMES:
raise HTTPException(status_code=404, detail="알 수 없는 광고 채널입니다.")
else:
raise HTTPException(status_code=404, detail="알 수 없는 메모 종류입니다.")
d = _parse_date(day)
if d is None:
raise HTTPException(status_code=400, detail="날짜가 필요합니다.")
memo = str(payload.get("memo") or "").replace("\r\n", "\n").strip()
if len(memo) > MEMO_MAX:
raise HTTPException(status_code=400, detail=f"메모는 {MEMO_MAX:,}자까지 쓸 수 있습니다.")
try:
store.set_cell_memo(kind, code, d, memo or None, user=user.get("email", ""))
except MemoMigrationNeeded:
raise HTTPException(status_code=503, detail="메모를 쓰려면 performance_db 마이그레이션 010"
"(scripts/sql/performance_db_010_cell_memos.sql)을 먼저 적용해야 합니다.") from None
return JSONResponse({"ok": True, "kind": kind, "code": code, "date": d.isoformat(), "memo": memo})
@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
@@ -1,6 +1,6 @@
{% extends "erp_base.html" %}
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261022b" />{% endblock %}
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261022c" />{% endblock %}
{#- ROAS 덧붙임 — "광고비(ROAS%)". 광고비가 없으면 아무것도 안 붙는다. -#}
{%- macro roas(p) -%}{%- if p is not none -%}<span class="perf-roas">({{ "{:,}".format(p) }}%)</span>{%- endif -%}{%- endmacro -%}
@@ -97,7 +97,8 @@
</div>
</div>
<div class="erp-table-wrap perf-table-wrap">
<table class="perf-table perf-main">
{#- perf-autofit(2026-10-22) = 열 너비는 내용 길이만큼, 날짜 열은 가로 스크롤해도 고정(매출 실적 표와 같음) -#}
<table class="perf-table perf-main perf-autofit">
<thead>
<tr>
<th class="perf-th-label">{% if period_kind == 'year' %}월{% else %}날짜{% endif %}</th>
@@ -117,8 +118,9 @@
{% set up = (r.date ~ '|' ~ c) in upload_cells %}
{% set ap = (r.date ~ '|' ~ c) in api_cells %}
{% set fx = (formula_cells or {}).get(r.date ~ '|' ~ c) if not up and not ap else none %}
<td class="perf-num is-manual-cell{% if v and not up and not ap %} is-manual{% endif %}{% if fx %} is-formula{% endif %}{% if up %} is-upload{% endif %}{% if ap %} is-api{% endif %}"
data-manual-code="{{ c }}" data-date="{{ r.date }}" data-manual-value="{{ v if v else '' }}"{% if fx %} data-formula="{{ fx }}"{% endif %} tabindex="0"
{% set memo = (memo_cells or {}).get(r.date ~ '|' ~ c) %}{#- 메모(010) -#}
<td class="perf-num is-manual-cell{% if v and not up and not ap %} is-manual{% endif %}{% if fx %} is-formula{% endif %}{% if up %} is-upload{% endif %}{% if ap %} is-api{% endif %}{% if memo %} has-memo{% endif %}"
data-manual-code="{{ c }}" data-date="{{ r.date }}" data-manual-value="{{ v if v else '' }}"{% if fx %} data-formula="{{ fx }}"{% endif %}{% if memo %} data-memo="{{ memo }}"{% endif %} tabindex="0"
title="{% if ap %}광고 API 값 — 눌러 고치기(다음 불러오기 때 다시 API 값으로){% elif up %}파일 업로드 값 — 눌러 고치기{% elif fx %}계산식 {{ fx }} — 눌러 고치기{% else %}눌러 광고비 입력(1000+2000 같은 계산식도 됨, 비우고 저장하면 지움){% endif %}"><span class="v v-gross">{{ won(v) }}</span>{{ roas(r.roas[c]) }}</td>
{% else %}
<td class="perf-num"><span class="v v-gross">{{ won(v) }}</span>{{ roas(r.roas[c]) }}</td>
@@ -226,6 +228,7 @@
"daily": chart_daily,
"share": chart_share,
"period_kind": period_kind,
"memo_kind": "ad",
"today": today,
"manual_api": "/performance/api/ad-spend/",
"manual_word": "광고비",
@@ -238,4 +241,4 @@
} | tojson }}</script>
{% endblock %}
{% block scripts %}<script src="/static/performance.js?v=20261022b" defer></script>{% endblock %}
{% block scripts %}<script src="/static/performance.js?v=20261022c" defer></script>{% endblock %}
@@ -1,6 +1,6 @@
{% extends "erp_base.html" %}
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261022b" />{% endblock %}
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261022c" />{% endblock %}
{%- macro won(v) -%}
{%- if v is none -%}<span class="perf-na"></span>
@@ -167,8 +167,9 @@
{% elif r.kind == 'day' and c in manual_codes %}
{% set is_manual = (r.date ~ '|' ~ c) in manual_cells %}
{% set fx = (formula_cells or {}).get(r.date ~ '|' ~ c) %}
<td class="perf-num is-manual-cell{% if is_manual %} is-manual{% endif %}{% if fx %} is-formula{% endif %}{% if glast %} is-glast{% endif %}"{{ gattr }} data-manual-code="{{ c }}" data-date="{{ r.date }}"
data-manual-value="{{ m.gross if is_manual else '' }}"{% if fx %} data-formula="{{ fx }}"{% endif %} tabindex="0"
{% set memo = (memo_cells or {}).get(r.date ~ '|' ~ c) %}{#- 메모(010) — 우클릭 메모 삽입·수정·삭제, 있으면 칸 오른쪽 위 빨간 삼각형 -#}
<td class="perf-num is-manual-cell{% if is_manual %} is-manual{% endif %}{% if fx %} is-formula{% endif %}{% if glast %} is-glast{% endif %}{% if memo %} has-memo{% endif %}"{{ gattr }} data-manual-code="{{ c }}" data-date="{{ r.date }}"
data-manual-value="{{ m.gross if is_manual else '' }}"{% if fx %} data-formula="{{ fx }}"{% endif %}{% if memo %} data-memo="{{ memo }}"{% endif %} tabindex="0"
title="{% if fx %}계산식 {{ fx }} — 눌러 고치기{% elif is_manual %}수동 입력값 — 눌러 고치기(비우고 저장하면 API 값){% else %}눌러 총매출 직접 입력(1000+2000 같은 계산식도 됨){% endif %}">{{ gc0 }}{{ m3(m) }}{{ adl(r.ads[c]) }}{{ gc1 }}</td>
{% else %}
<td class="perf-num{% if r['from'] and (m.gross or m.commission) %} is-link{% endif %}{% if glast %} is-glast{% endif %}"{{ gattr }}
@@ -279,6 +280,7 @@
"daily": chart_daily,
"share": chart_share,
"period_kind": period_kind,
"memo_kind": "sales",
"period_start": period.start.isoformat(),
"period_end": period.end.isoformat(),
"today": today,
@@ -288,4 +290,4 @@
} | tojson }}</script>
{% endblock %}
{% block scripts %}<script src="/static/performance.js?v=20261022b" defer></script>{% endblock %}
{% block scripts %}<script src="/static/performance.js?v=20261022c" defer></script>{% endblock %}
@@ -1,6 +1,6 @@
{% extends "erp_base.html" %}
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261022b" />{% endblock %}
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261022c" />{% endblock %}
{%- macro when(v) -%}{{ (v or '')[:16] | replace('T', ' ') or '—' }}{%- endmacro -%}
@@ -259,4 +259,4 @@
</section>
{% endblock %}
{% block scripts %}<script src="/static/performance.js?v=20261022b" defer></script>{% endblock %}
{% block scripts %}<script src="/static/performance.js?v=20261022c" defer></script>{% endblock %}
@@ -121,7 +121,8 @@ 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", "naver", "coupang_wing", "coupang_rocket", "ohouse", "gmarket", "kakao",
"gsshop", "elevenst", "lotteon", "toss", "atomy"]
"gsshop", "elevenst", "lotteon", "toss", "atomy", "etc"] # 기타광고비(2026-10-22) = 애터미아자몰 오른쪽
assert ctx["names"]["etc"] == "기타광고비" and ctx["roas_basis"]["etc"] == "" and "etc" not in ads.ROAS_SALES_CODE # 매출 쇼핑몰 없음 = ROAS 없음
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
@@ -0,0 +1,63 @@
"""날짜 칸 메모(2026-10-22, 마이그레이션 010) — API 규칙(종류·코드·길이·지우기·010 미적용 503), 매출·광고비 화면의 메모 표시, 기타광고비 채널."""
from __future__ import annotations
import importlib
from datetime import date
import pytest
from fastapi import FastAPI
from fastapi.testclient import TestClient
from app.modules.performance import ad_spend, common
from app.modules.performance.db import MemoMigrationNeeded
perf_router = importlib.import_module("app.modules.performance.router")
class Store:
def __init__(self, missing=False):
self.saved, self.missing = [], missing
def list_marketplaces(self):
return [{"code": "coupang", "name": "쿠팡", "enabled": True, "include_in_sales": True, "manual_input": True}]
def set_cell_memo(self, kind, code, day, memo, *, user=""):
if self.missing:
raise MemoMigrationNeeded()
self.saved.append((kind, code, day, memo, user))
@pytest.fixture
def client_store(monkeypatch):
st = Store()
monkeypatch.setattr(common, "require_store", lambda request, admin=False: (st, {"email": "me@x"}))
app = FastAPI()
app.include_router(perf_router.router)
return TestClient(app), st
def test_cell_memo_api(client_store):
c, st = client_store
r = c.put("/performance/api/cell-memos/sales/coupang/2026-10-05", json={"memo": " 행사 매출 포함\r\n2차 정산 예정 "})
assert r.status_code == 200 and r.json()["memo"] == "행사 매출 포함\n2차 정산 예정"
assert st.saved[-1] == ("sales", "coupang", date(2026, 10, 5), "행사 매출 포함\n2차 정산 예정", "me@x")
r = c.put("/performance/api/cell-memos/ad/etc/2026-10-30", json={"memo": "전단지"}) # 기타광고비·앞날도 됨
assert r.status_code == 200 and st.saved[-1][:2] == ("ad", "etc")
assert c.put("/performance/api/cell-memos/ad/etc/2026-10-30", json={"memo": " "}).status_code == 200
assert st.saved[-1][3] is None # 빈 메모 = 지움
assert c.put("/performance/api/cell-memos/sales/nope/2026-10-05", json={"memo": "x"}).status_code == 404
assert c.put("/performance/api/cell-memos/ad/cafe24/2026-10-05", json={"memo": "x"}).status_code == 404 # 광고 채널 아님
assert c.put("/performance/api/cell-memos/other/coupang/2026-10-05", json={"memo": "x"}).status_code == 404
assert c.put("/performance/api/cell-memos/sales/coupang/2026-10-05", json={"memo": "가" * 1001}).status_code == 400
st.missing = True
r = c.put("/performance/api/cell-memos/sales/coupang/2026-10-05", json={"memo": "x"})
assert r.status_code == 503 and "010" in r.json()["detail"]
def test_etc_channel_has_no_roas():
assert ad_spend.CHANNEL_CODES[-2:] == ("atomy", "etc") and ad_spend.CHANNEL_NAMES["etc"] == "기타광고비"
assert ad_spend.channel_roas("etc", lambda m: 1_000_000, 50_000) is None
assert ad_spend.roas_basis("etc") == ""
from app.modules.performance.dashboard import sales_ad_channels
assert not any(ch == "etc" for lines in sales_ad_channels().values() for ch, _ in lines) # 매출 탭 광고비 줄에 안 나옴
+16
View File
@@ -441,3 +441,19 @@ body.perf-dragging, body.perf-dragging * { cursor: grabbing !important; user-sel
.perf-main .is-gshut { padding-left: 0 !important; padding-right: 0 !important; }
.perf-main .is-gshut .perf-gc { opacity: 0; }
@media (prefers-reduced-motion: reduce) { .perf-gtoggle .g-v { transition: none; } }
/* ── 날짜 칸 메모(2026-10-22, 010) — 메모 있는 칸 = 오른쪽 위 빨간 삼각형(엑셀 메모처럼), 마우스 올리면 노란 메모 상자, 우클릭 메뉴 ── */
.perf-main td.has-memo { position: relative; }
.perf-main td.has-memo::after { content: ""; position: absolute; top: 0; right: 0; width: 0; height: 0;
border-left: 8px solid transparent; border-top: 8px solid #e03131; pointer-events: none; }
.perf-memo-tip { position: absolute; z-index: 2200; max-width: 280px; padding: 8px 10px; background: #fff9db; color: #3d3418;
border: 1px solid #f2d36b; border-radius: 6px; box-shadow: 0 6px 18px rgba(0, 0, 0, .14); font-size: 12.5px; line-height: 1.5;
white-space: pre-wrap; word-break: break-word; pointer-events: none; }
.perf-ctx { position: absolute; z-index: 2300; min-width: 130px; padding: 4px; background: #fff; border: 1px solid #e2e5e9; border-radius: 10px;
box-shadow: 0 8px 24px rgba(0, 0, 0, .16); display: flex; flex-direction: column; }
.perf-ctx button { all: unset; box-sizing: border-box; padding: 7px 12px; border-radius: 7px; font-size: 13px; cursor: pointer; color: #1e1f21; }
.perf-ctx button:hover, .perf-ctx button:focus-visible { background: #f2f4f6; }
.perf-ctx button.is-danger { color: #c22b10; }
.perf-memo-input { width: 100%; box-sizing: border-box; min-height: 110px; padding: 10px; border: 1px solid #d8dce2; border-radius: 8px;
font: inherit; font-size: 13.5px; line-height: 1.5; resize: vertical; }
.perf-memo-input:focus { outline: none; border-color: #1a56db; box-shadow: 0 0 0 3px rgba(26, 86, 219, .12); }
+87
View File
@@ -774,6 +774,93 @@
const td = e.target.closest && e.target.closest("td.is-manual-cell");
if (td && e.target === td && (e.key === "Enter" || e.key === "F2")) { e.preventDefault(); editManual(td); }
});
// ── 날짜 칸 메모(2026-10-22, 마이그레이션 010) — 금액 입력 칸 우클릭 → 메모 삽입 / 메모 수정·메모 삭제(창에서 입력).
// 메모 있는 칸 = 오른쪽 위 빨간 삼각형(has-memo), 마우스를 올리면 칸 옆에 노란 메모 상자. 금액과 따로 저장(PUT /api/cell-memos/{kind}/{코드}/{날짜}).
const MEMO_KIND = data.memo_kind || "";
let memoMenu = null, memoTip = null;
function closeMemoMenu() { if (memoMenu) { memoMenu.remove(); memoMenu = null; } }
function hideMemoTip() { if (memoTip) { memoTip.remove(); memoTip = null; } }
function memoCellLabel(td) {
const d = td.dataset.date || "";
return ((data.names || {})[td.dataset.manualCode] || td.dataset.manualCode) + " · " + d.replace(/-/g, ".");
}
function setCellMemo(td, memo) {
if (memo) td.dataset.memo = memo; else delete td.dataset.memo;
td.classList.toggle("has-memo", !!memo);
}
async function saveMemo(td, memo) {
const res = await api("PUT", "/performance/api/cell-memos/" + encodeURIComponent(MEMO_KIND) + "/" +
encodeURIComponent(td.dataset.manualCode) + "/" + encodeURIComponent(td.dataset.date), { memo: memo });
setCellMemo(td, res.memo || "");
}
function editMemo(td) {
const had = !!td.dataset.memo;
const m = openModal((had ? "메모 수정" : "메모 삽입") + " · " + memoCellLabel(td), { narrow: true });
const ta = el("textarea", { class: "perf-memo-input", rows: "5", maxlength: "1000", placeholder: "메모를 입력하세요 (Ctrl+Enter 저장)",
"aria-label": memoCellLabel(td) + " 메모" });
ta.value = td.dataset.memo || "";
m.body.appendChild(ta);
const cancel = el("button", { type: "button", class: "erp-btn erp-btn-outline" }, "취소");
const save = el("button", { type: "button", class: "erp-btn erp-btn-primary" }, "저장");
m.foot.appendChild(cancel);
m.foot.appendChild(save);
cancel.addEventListener("click", m.close);
save.addEventListener("click", async function () {
save.disabled = true;
try { await saveMemo(td, ta.value.trim()); m.close(); }
catch (err) { save.disabled = false; alertMsg("메모 저장 실패: " + err.message); }
});
ta.addEventListener("keydown", function (e) {
if (e.key === "Enter" && (e.ctrlKey || e.metaKey)) { e.preventDefault(); save.click(); }
});
setTimeout(function () { ta.focus(); ta.setSelectionRange(ta.value.length, ta.value.length); }, 0);
}
root.addEventListener("contextmenu", function (e) {
const td = MEMO_KIND && e.target.closest("td.is-manual-cell");
if (!td || td.querySelector(".perf-manual-input")) return; // 입력 중인 칸은 브라우저 기본 메뉴(붙여넣기 등)
e.preventDefault();
closeMemoMenu();
hideMemoTip();
const items = td.dataset.memo
? [["메모 수정", function () { editMemo(td); }],
["메모 삭제", async function () {
if (!(await confirmMsg(memoCellLabel(td) + " 칸의 메모를 지울까요?"))) return;
try { await saveMemo(td, ""); } catch (err) { alertMsg("메모 삭제 실패: " + err.message); }
}]]
: [["메모 삽입", function () { editMemo(td); }]];
memoMenu = el("div", { class: "perf-ctx", role: "menu" });
items.forEach(function (it) {
const b = el("button", { type: "button", role: "menuitem", class: it[0] === "메모 삭제" ? "is-danger" : "" }, esc(it[0]));
b.addEventListener("click", function () { closeMemoMenu(); it[1](); });
memoMenu.appendChild(b);
});
document.body.appendChild(memoMenu);
const w = memoMenu.offsetWidth, h = memoMenu.offsetHeight;
memoMenu.style.left = Math.min(e.clientX, window.innerWidth - w - 6) + window.scrollX + "px";
memoMenu.style.top = Math.min(e.clientY, window.innerHeight - h - 6) + window.scrollY + "px";
memoMenu.querySelector("button").focus();
});
document.addEventListener("mousedown", function (e) { if (memoMenu && !memoMenu.contains(e.target)) closeMemoMenu(); });
document.addEventListener("keydown", function (e) { if (e.key === "Escape") closeMemoMenu(); });
window.addEventListener("scroll", function () { closeMemoMenu(); hideMemoTip(); }, true);
root.addEventListener("mouseover", function (e) {
const td = e.target.closest && e.target.closest("td.has-memo");
if (!td || (memoTip && memoTip._td === td) || td.querySelector(".perf-manual-input")) return;
hideMemoTip();
memoTip = el("div", { class: "perf-memo-tip", role: "tooltip", text: td.dataset.memo || "" });
memoTip._td = td;
document.body.appendChild(memoTip);
const r = td.getBoundingClientRect(), w = memoTip.offsetWidth;
const left = r.right + 6 + w > window.innerWidth ? r.left - w - 6 : r.right + 6;
memoTip.style.left = Math.max(6, left) + window.scrollX + "px";
memoTip.style.top = r.top + window.scrollY + "px";
});
root.addEventListener("mouseout", function (e) {
const td = e.target.closest && e.target.closest("td.has-memo");
if (td && !(e.relatedTarget && td.contains(e.relatedTarget))) hideMemoTip();
});
root.addEventListener("click", hideMemoTip, true);
async function openEvents(code, from, to) {
const name = (data.names || {})[code] || code;
const title = name + " · " + (from === to ? from : from + " ~ " + to) + " 주문 내역";
+11
View File
@@ -268,6 +268,17 @@ 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 "ALTER TABLE perf_manual_sales DROP COLUMN formula; ALTER TABLE perf_ad_spend DROP COLUMN formula;"`
## 실적 날짜 칸 메모 마이그레이션 (performance_db 010)
010은 `perf_cell_memos` 표 하나만 만든다(기존 표·값 그대로, 다시 실행 가능). 매출 실적·광고비 일자별 표의 금액 입력 칸 우클릭 → 메모 삽입·수정·삭제.
미적용이어도 화면은 그대로 — 메모 저장만 503 안내. 새 환경변수 없음.
```bash
cd /opt/www/main && git pull && docker exec postgres-db pg_dump -U postgres performance_db > ~/performance_db_before_010_$(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_010_cell_memos.sql && docker compose up --build -d --no-deps web
```
되돌리기(메모만 사라짐): `docker exec postgres-db psql -U postgres -d performance_db -c "DROP TABLE perf_cell_memos;"`
## 실적 직접 추가 쇼핑몰·그룹 마이그레이션 (performance_db 009)
009는 `perf_marketplaces` 에 `is_custom`·`is_group`·`parent_code` 열 세 개만 추가한다(기존 행·값 그대로, 기존 쇼핑몰은 모두 FALSE/NULL, 다시 실행 가능).
@@ -0,0 +1,34 @@
-- =====================================================================
-- performance_db 마이그레이션 010 — 날짜 칸 메모(매출 실적·광고비)(2026-10-22)
-- =====================================================================
-- 멱등(idempotent). 표 하나만 추가(기존 표·값 그대로). 운영: /opt/www/main 에서 기존 performance_db 에 적용(백업 먼저).
-- docker exec -i postgres-db psql -v ON_ERROR_STOP=1 -U postgres -d performance_db < scripts/sql/performance_db_010_cell_memos.sql
--
-- 왜(사용자 요청): 매출 실적·광고비 일자별 표의 금액 입력 칸에서 우클릭 → 메모 삽입·수정·삭제, 메모가 있는 칸은 표시.
-- kind = 'sales'(매출 실적, code = 쇼핑몰 코드) / 'ad'(광고비, code = 광고 채널 코드). 금액과는 따로 저장(금액을 지워도 메모는 남는다).
-- 되돌리기: DROP TABLE perf_cell_memos; (메모만 사라짐 — 실행 전 백업)
-- =====================================================================
BEGIN;
CREATE TABLE IF NOT EXISTS perf_cell_memos (
kind TEXT NOT NULL CHECK (kind IN ('sales', 'ad')),
code TEXT NOT NULL CHECK (char_length(code) BETWEEN 1 AND 64),
memo_date DATE NOT NULL,
memo TEXT NOT NULL CHECK (char_length(memo) BETWEEN 1 AND 1000),
updated_by TEXT NOT NULL DEFAULT '',
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
PRIMARY KEY (kind, code, memo_date)
);
CREATE INDEX IF NOT EXISTS idx_perf_cell_memos_date ON perf_cell_memos (kind, memo_date);
COMMENT ON TABLE perf_cell_memos IS '실적 — 매출 실적·광고비 일자별 표 날짜 칸 메모(우클릭 메모 삽입·수정·삭제)';
DO $$
BEGIN
IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'performance_app') THEN
GRANT SELECT, INSERT, UPDATE, DELETE ON perf_cell_memos TO performance_app;
END IF;
END $$;
COMMIT;
SELECT 'performance_db 010 cell memos ready' AS status;
+2 -2
View File
@@ -162,8 +162,8 @@ function gross(td) { return td.querySelector(".v-gross").textContent.trim(); }
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("✎", "").replace("table_view", "").trim(); });
check("[광고비] 열 = 구글·메타·네이버·쿠팡(윙)·쿠팡(로켓)·오늘의집·G마켓·카카오·GS샵·11번가·롯데ON·토스·애터미아자몰",
heads.join(",") === "날짜,구글,메타,네이버,쿠팡(윙),쿠팡(로켓),오늘의집,G마켓,카카오,GS샵,11번가,롯데ON,토스,애터미아자몰,일 합계", heads);
check("[광고비] 열 = 구글·메타·네이버·쿠팡(윙)·쿠팡(로켓)·오늘의집·G마켓·카카오·GS샵·11번가·롯데ON·토스·애터미아자몰·기타광고비(2026-10-22)",
heads.join(",") === "날짜,구글,메타,네이버,쿠팡(윙),쿠팡(로켓),오늘의집,G마켓,카카오,GS샵,11번가,롯데ON,토스,애터미아자몰,기타광고비,일 합계", heads);
const wing = cell(e, "coupang_wing", "2026-10-05");
check("[광고비] 칸 = 광고비(ROAS%) — 쿠팡(윙) 29,000 · 쿠팡 매출 87,000 → 300%",
wing.textContent.trim() === "29,000(300%)" && !cell(e, "naver", "2026-10-05").querySelector(".perf-roas"), wing.textContent);
+130
View File
@@ -0,0 +1,130 @@
// 실적 — 날짜 칸 메모·광고비 표 모양(2026-10-22) — 실제 브라우저(Chromium).
// python tests/js/render_performance.py
// NODE_PATH=<playwright 경로> PJ_TEST_BROWSER=<Chrome 경로> node tests/js/perf_memo_ads.browser.test.js
// 매출·광고비: 입력 칸 우클릭 → 메모 삽입(창) → 저장(PUT /api/cell-memos/{kind}/{코드}/{날짜}) → 빨간 삼각형, 마우스 올리면 메모 상자,
// 우클릭 → 메모 수정·메모 삭제. 광고비 표: 기타광고비 열(애터미아자몰 오른쪽), 열 너비 = 내용 길이, 날짜 열 고정.
const fs = require("fs"), path = require("path");
const { chromium } = require("playwright");
const ROOT = path.join(__dirname, "..", "..");
const fails = [];
function check(name, cond, extra) {
if (cond) console.log("PASS " + name);
else { console.log("FAIL " + name + (extra !== undefined ? " → " + JSON.stringify(extra) : "")); fails.push(name); }
}
function page(file) {
const css = fs.readFileSync(path.join(ROOT, "app", "static", "performance.css"), "utf8");
const js = fs.readFileSync(path.join(ROOT, "app", "static", "performance.js"), "utf8");
return fs.readFileSync(path.join(__dirname, ".out", file), "utf8")
.replace(/<link rel="stylesheet" href="\/static\/performance\.css[^"]*" \/>/, function () { return "<style>" + css + "</style>"; })
.replace(/<script src="\/static\/performance\.js[^"]*" defer><\/script>/, function () { return "<script>" + js + "</script>"; });
}
async function memoFlow(browser, file, kind, code, day, hasMemo, label) {
const ctx = await browser.newContext({ viewport: { width: 1400, height: 900 } });
const p = await ctx.newPage();
const puts = [];
await p.route("**/*", function (r) {
const req = r.request(), url = new URL(req.url()).pathname;
if (url.startsWith("/performance/api/cell-memos/")) {
const body = JSON.parse(req.postData() || "{}");
puts.push({ url: url, memo: body.memo });
r.fulfill({ status: 200, contentType: "application/json", body: JSON.stringify({ ok: true, memo: (body.memo || "").trim() }) });
return;
}
if (url.startsWith("/performance/api/")) { r.fulfill({ status: 200, contentType: "application/json", body: "{}" }); return; }
r.fulfill({ status: 200, contentType: "text/html; charset=utf-8", body: page(file) });
});
await p.goto("http://perf.test/performance/");
const td = '[data-manual-code="' + code + '"][data-date="' + day + '"]';
// 표를 스크롤하면 열린 메뉴는 닫힌다(사람은 스크롤한 뒤 우클릭) — 오른쪽 끝 열(기타광고비)은 먼저 보이게 스크롤해 둔다
const show = async function (sel) { await p.locator(sel).scrollIntoViewIfNeeded(); await p.waitForTimeout(80); };
const memoed = '[data-manual-code="' + hasMemo[0] + '"][data-date="' + hasMemo[1] + '"]';
// 기존 메모 = 빨간 삼각형 + 마우스 올리면 메모 상자
const mark = await p.evaluate(function (sel) {
const el = document.querySelector(sel);
const after = getComputedStyle(el, "::after");
return { has: el.classList.contains("has-memo"), color: after.borderTopColor, content: after.content };
}, memoed);
check(label + " 메모 있는 칸 = 빨간 삼각형", mark.has && /rgb\(224, 49, 49\)/.test(mark.color) && mark.content === '""', mark);
await p.hover(memoed);
const tip = await p.evaluate(function () { const t = document.querySelector(".perf-memo-tip"); return t ? t.textContent : null; });
check(label + " 마우스 올리면 메모 상자", tip === hasMemo[2], tip);
// 메모 없는 칸 우클릭 → 메모 삽입만
await p.mouse.move(5, 5);
await show(td);
await p.click(td, { button: "right" });
const menu1 = await p.$$eval(".perf-ctx button", function (bs) { return bs.map(function (b) { return b.textContent; }); });
check(label + " 메모 없는 칸 우클릭 = [메모 삽입]", JSON.stringify(menu1) === JSON.stringify(["메모 삽입"]), menu1);
await p.click(".perf-ctx button");
await p.waitForSelector(".perf-memo-input");
const title = await p.textContent(".perf-modal-head h3");
check(label + " 메모 삽입 창(제목에 칸 이름·날짜)", /메모 삽입/.test(title) && title.indexOf(day.replace(/-/g, ".")) >= 0, title);
await p.fill(".perf-memo-input", "첫 메모\n둘째 줄");
await p.click(".perf-modal-foot .erp-btn-primary");
await p.waitForFunction(function (sel) { return document.querySelector(sel).classList.contains("has-memo"); }, td);
const put1 = puts[puts.length - 1];
check(label + " 저장 → PUT /api/cell-memos/" + kind + "/…, 칸에 표시", put1 && put1.url === "/performance/api/cell-memos/" + kind + "/" + code + "/" + day &&
put1.memo === "첫 메모\n둘째 줄" && !(await p.$(".perf-modal")), put1);
// 메모 있는 칸 우클릭 → 메모 수정·메모 삭제
await p.click(td, { button: "right" });
const menu2 = await p.$$eval(".perf-ctx button", function (bs) { return bs.map(function (b) { return b.textContent; }); });
check(label + " 메모 있는 칸 우클릭 = [메모 수정][메모 삭제]", JSON.stringify(menu2) === JSON.stringify(["메모 수정", "메모 삭제"]), menu2);
await p.click(".perf-ctx button:first-child");
const v = await p.inputValue(".perf-memo-input");
check(label + " 메모 수정 창에 지금 메모", v === "첫 메모\n둘째 줄", v);
await p.fill(".perf-memo-input", "고친 메모");
await p.keyboard.press("Control+Enter");
await p.waitForFunction(function (sel) { return document.querySelector(sel).dataset.memo === "고친 메모"; }, td);
check(label + " Ctrl+Enter 로 저장", puts[puts.length - 1].memo === "고친 메모");
p.once("dialog", function (d) { d.accept(); });
await p.click(td, { button: "right" });
await p.click(".perf-ctx button.is-danger");
await p.waitForFunction(function (sel) { return !document.querySelector(sel).classList.contains("has-memo"); }, td);
check(label + " 메모 삭제 → 빈 메모로 저장, 표시 사라짐", puts[puts.length - 1].memo === "");
// 칸 왼쪽 클릭은 예전처럼 금액 입력
await p.click(td);
check(label + " 칸 클릭은 그대로 금액 입력", !!(await p.$(td + " .perf-manual-input")));
await ctx.close();
}
(async function () {
const browser = await chromium.launch(process.env.PJ_TEST_BROWSER ? { executablePath: process.env.PJ_TEST_BROWSER } : {});
try {
await memoFlow(browser, "perf_dash.html", "sales", "coupang", "2026-10-06", ["coupang", "2026-10-05", "행사 매출 포함\n2차 정산 예정"], "[매출]");
await memoFlow(browser, "perf_ads.html", "ad", "etc", "2026-10-06", ["coupang_wing", "2026-10-05", "쿠폰 광고"], "[광고비]");
// 광고비 표 — 기타광고비 열, 열 너비 = 내용, 날짜 열 고정
const p = await browser.newPage({ viewport: { width: 1400, height: 900 } });
await p.route("**/*", function (r) {
if (new URL(r.request().url()).pathname.startsWith("/performance/api/")) { r.fulfill({ status: 200, contentType: "application/json", body: "{}" }); return; }
r.fulfill({ status: 200, contentType: "text/html; charset=utf-8", body: page("perf_ads.html") });
});
await p.goto("http://perf.test/performance/ads");
const heads = await p.$$eval(".perf-main thead th", function (ths) { return ths.map(function (th) { return th.textContent.replace(/[✎\s]+/g, " ").trim(); }); });
const ai = heads.findIndex(function (h) { return h.indexOf("애터미아자몰") === 0; });
check("광고비 표 = 애터미아자몰 오른쪽 기타광고비 열", ai > 0 && heads[ai + 1].indexOf("기타광고비") === 0, heads);
const fit = await p.evaluate(function () {
const t = document.querySelector(".perf-main"), wrap = t.closest(".perf-table-wrap");
return { autofit: t.classList.contains("perf-autofit"), tableW: Math.round(t.getBoundingClientRect().width), wrapW: wrap.clientWidth,
labelW: Math.round(t.querySelector("thead th.perf-th-label").getBoundingClientRect().width) };
});
check("광고비 표 열 너비 = 내용 길이(날짜 열 210px 고정 아님)", fit.autofit && fit.labelW < 200, fit);
const sticky = await p.evaluate(function () {
const wrap = document.querySelector(".perf-table-wrap"), lab = document.querySelector(".perf-row-day .perf-td-label");
wrap.style.width = "420px";
wrap.scrollLeft = 400;
const x = lab.getBoundingClientRect().left, wx = wrap.getBoundingClientRect().left;
const under = document.elementFromPoint(x + 4, lab.getBoundingClientRect().top + 4);
return { scrolled: wrap.scrollLeft, x: x, wx: wx, top: under === lab || lab.contains(under) };
});
check("광고비 표 가로 스크롤해도 날짜 열 고정", sticky.scrolled > 0 && Math.abs(sticky.x - sticky.wx) < 2 && sticky.top, sticky);
await p.locator(".perf-table-wrap").screenshot({ path: path.join(__dirname, ".out", "perf_ads_sticky.png") });
await p.evaluate(function () { const w = document.querySelector(".perf-table-wrap"); w.style.width = ""; w.scrollLeft = 0; });
await p.hover('[data-manual-code="coupang_wing"][data-date="2026-10-05"]');
await p.screenshot({ path: path.join(__dirname, ".out", "perf_ads_memo.png"), clip: { x: 0, y: 200, width: 1400, height: 500 } });
} finally {
await browser.close();
}
console.log(fails.length ? "\n" + fails.length + " FAIL" : "\nALL PASS");
process.exit(fails.length ? 1 : 0);
})();
+6
View File
@@ -68,6 +68,12 @@ class FakeStore:
rows = {(date(2026, 10, 3), "naver"): Decimal("250.5"), (date(2026, 10, 4), "google"): Decimal("500")}
return {k: v for k, v in rows.items() if start <= k[0] <= end}
def cell_memos(self, kind, start, end):
"""날짜 칸 메모(2026-10-22) — 매출: 쿠팡 10/5, 광고비: 쿠팡(윙) 10/5."""
rows = {"sales": {(date(2026, 10, 5), "coupang"): "행사 매출 포함\n2차 정산 예정"},
"ad": {(date(2026, 10, 5), "coupang_wing"): "쿠폰 광고"}}.get(kind, {})
return {k: v for k, v in rows.items() if start <= k[0] <= end}
def env() -> jinja2.Environment:
e = jinja2.Environment(loader=jinja2.ChoiceLoader([