diff --git a/app/modules/performance/CLAUDE.md b/app/modules/performance/CLAUDE.md index e43723e..bbf95c2 100644 --- a/app/modules/performance/CLAUDE.md +++ b/app/modules/performance/CLAUDE.md @@ -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`). - 날짜 칸 직접 입력 + 쿠팡(윙)·쿠팡(로켓)·네이버 광고 보고서 업로드. diff --git a/app/modules/performance/ad_spend.py b/app/modules/performance/ad_spend.py index eba51a3..a57785f 100644 --- a/app/modules/performance/ad_spend.py +++ b/app/modules/performance/ad_spend.py @@ -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()}, } diff --git a/app/modules/performance/dashboard.py b/app/modules/performance/dashboard.py index 5d13d0d..418cb38 100644 --- a/app/modules/performance/dashboard.py +++ b/app/modules/performance/dashboard.py @@ -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(), diff --git a/app/modules/performance/db.py b/app/modules/performance/db.py index 85232e5..12358a1 100644 --- a/app/modules/performance/db.py +++ b/app/modules/performance/db.py @@ -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) # ════════════════════════════════════════════════════════════ diff --git a/app/modules/performance/router.py b/app/modules/performance/router.py index 930bc92..60aa8d9 100644 --- a/app/modules/performance/router.py +++ b/app/modules/performance/router.py @@ -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 diff --git a/app/modules/performance/templates/performance/ads.html b/app/modules/performance/templates/performance/ads.html index ee4bcfa..1ea98e3 100644 --- a/app/modules/performance/templates/performance/ads.html +++ b/app/modules/performance/templates/performance/ads.html @@ -1,6 +1,6 @@ {% extends "erp_base.html" %} -{% block head_extra %}{% endblock %} +{% block head_extra %}{% endblock %} {#- ROAS 덧붙임 — "광고비(ROAS%)". 광고비가 없으면 아무것도 안 붙는다. -#} {%- macro roas(p) -%}{%- if p is not none -%}({{ "{:,}".format(p) }}%){%- endif -%}{%- endmacro -%} @@ -97,7 +97,8 @@
| {% if period_kind == 'year' %}월{% else %}날짜{% endif %} | @@ -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 %} -{{ won(v) }}{{ roas(r.roas[c]) }} | {% else %}{{ won(v) }}{{ roas(r.roas[c]) }} | @@ -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 }} {% endblock %} -{% block scripts %}{% endblock %} +{% block scripts %}{% endblock %} diff --git a/app/modules/performance/templates/performance/index.html b/app/modules/performance/templates/performance/index.html index 975b0ae..d6fad4f 100644 --- a/app/modules/performance/templates/performance/index.html +++ b/app/modules/performance/templates/performance/index.html @@ -1,6 +1,6 @@ {% extends "erp_base.html" %} -{% block head_extra %}{% endblock %} +{% block head_extra %}{% endblock %} {%- macro won(v) -%} {%- if v is none -%} @@ -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) %} -{{ gc0 }}{{ m3(m) }}{{ adl(r.ads[c]) }}{{ gc1 }} | {% else %}
{% endblock %}
-{% block scripts %}{% endblock %}
+{% block scripts %}{% endblock %}
diff --git a/app/modules/performance/templates/performance/settings.html b/app/modules/performance/templates/performance/settings.html
index 8f463ae..7029192 100644
--- a/app/modules/performance/templates/performance/settings.html
+++ b/app/modules/performance/templates/performance/settings.html
@@ -1,6 +1,6 @@
{% extends "erp_base.html" %}
-{% block head_extra %}{% endblock %}
+{% block head_extra %}{% endblock %}
{%- macro when(v) -%}{{ (v or '')[:16] | replace('T', ' ') or '—' }}{%- endmacro -%}
@@ -259,4 +259,4 @@
{% endblock %}
-{% block scripts %}{% endblock %}
+{% block scripts %}{% endblock %}
diff --git a/app/modules/performance/tests/test_ad_spend.py b/app/modules/performance/tests/test_ad_spend.py
index 32ab7a2..6416f01 100644
--- a/app/modules/performance/tests/test_ad_spend.py
+++ b/app/modules/performance/tests/test_ad_spend.py
@@ -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
diff --git a/app/modules/performance/tests/test_cell_memos.py b/app/modules/performance/tests/test_cell_memos.py
new file mode 100644
index 0000000..6a52615
--- /dev/null
+++ b/app/modules/performance/tests/test_cell_memos.py
@@ -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) # 매출 탭 광고비 줄에 안 나옴
diff --git a/app/static/performance.css b/app/static/performance.css
index ee05d19..74fcd95 100644
--- a/app/static/performance.css
+++ b/app/static/performance.css
@@ -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); }
diff --git a/app/static/performance.js b/app/static/performance.js
index 0dd1847..70fd6bc 100644
--- a/app/static/performance.js
+++ b/app/static/performance.js
@@ -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) + " 주문 내역";
diff --git a/docs/DEPLOYMENT.md b/docs/DEPLOYMENT.md
index b3a915d..09eb886 100644
--- a/docs/DEPLOYMENT.md
+++ b/docs/DEPLOYMENT.md
@@ -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, 다시 실행 가능).
diff --git a/scripts/sql/performance_db_010_cell_memos.sql b/scripts/sql/performance_db_010_cell_memos.sql
new file mode 100644
index 0000000..3028d43
--- /dev/null
+++ b/scripts/sql/performance_db_010_cell_memos.sql
@@ -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;
diff --git a/tests/js/perf_manual.test.js b/tests/js/perf_manual.test.js
index 89539c4..5620508 100644
--- a/tests/js/perf_manual.test.js
+++ b/tests/js/perf_manual.test.js
@@ -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);
diff --git a/tests/js/perf_memo_ads.browser.test.js b/tests/js/perf_memo_ads.browser.test.js
new file mode 100644
index 0000000..4c22a28
--- /dev/null
+++ b/tests/js/perf_memo_ads.browser.test.js
@@ -0,0 +1,130 @@
+// 실적 — 날짜 칸 메모·광고비 표 모양(2026-10-22) — 실제 브라우저(Chromium).
+// python tests/js/render_performance.py
+// NODE_PATH= |
|---|