feat(performance): per-shop manual sales input, column order, bold centered table headers (migration 002)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-12 17:26:57 +09:00
parent dd1bc310dc
commit 454b3cc700
16 changed files with 690 additions and 34 deletions
+4 -3
View File
@@ -19,16 +19,17 @@ from .ohouse import OhouseAdapter
from .toss import TossAdapter
_ADAPTERS: tuple[MarketplaceAdapter, ...] = (
# 화면 순서와 같게(DB sort_order 도 같은 순서 — 마이그레이션 002)
Cafe24Adapter(),
NaverAdapter(),
CoupangAdapter(),
TossAdapter(),
GsshopAdapter(),
ElevenstAdapter(),
OhouseAdapter(),
GmarketAdapter(),
KakaoAdapter(),
GsshopAdapter(),
ElevenstAdapter(),
LotteonAdapter(),
TossAdapter(),
)
_BY_CODE = {a.code: a for a in _ADAPTERS}
+8 -1
View File
@@ -58,6 +58,11 @@ def build_dashboard(store: Any, *, kind: str, anchor: date, today: date,
q_start = min(period.start, cmp_start, m_cmp_start, y_cmp_start)
q_end = max(period.end, year_period.end)
cells = calc.build_cells(store.daily_amounts(q_start, q_end, codes), store.rate_table())
# 수동 입력(설정에서 켠 쇼핑몰) — 일자별 표의 날짜 칸을 눌러 입력. 값이 있는 칸은 표시(API 값 대신 쓰는 중)
manual_codes = [m["code"] for m in markets if m.get("manual_input") and m["code"] in codes]
manual_amounts = getattr(store, "manual_amounts", None)
manual_cells = sorted(f"{d.isoformat()}|{c}" for d, c in
(manual_amounts(period.start, period.end, manual_codes) if manual_amounts and manual_codes else {}))
cur = calc.sum_range(cells, codes, period.start, period.end)
prev = calc.sum_range(cells, codes, cmp_start, cmp_end)
@@ -143,6 +148,8 @@ def build_dashboard(store: Any, *, kind: str, anchor: date, today: date,
"chart_daily": calc.daily_series(period, codes, cells),
"chart_share": [{"code": c, "name": names[c], **share[c].as_dict()} for c in codes],
"problems": problems,
"manual_codes": manual_codes,
"manual_cells": manual_cells,
"last_update_at": store.last_update_at(),
"running": store.running_codes(),
"no_marketplaces": not all_codes,
@@ -175,7 +182,7 @@ def build_settings(store: Any, *, configured: Mapping[str, bool], key_info: Mapp
has_rate = bool(rates.get(adapter.code))
rows.append({
"code": adapter.code, "name": m["name"], "enabled": m["enabled"],
"include_in_sales": m["include_in_sales"],
"include_in_sales": m["include_in_sales"], "manual_input": bool(m.get("manual_input")),
"rate": _fmt_rate(cur_rate) if has_rate else "",
"rate_history": len(rates.get(adapter.code, ())),
"auth_type": adapter.auth_type, "shared": adapter.uses_shared_integration,
+69 -6
View File
@@ -15,6 +15,7 @@ from datetime import date, datetime, timedelta
from decimal import Decimal
from typing import Any, Iterable
from psycopg import errors as pg_errors
from psycopg.rows import dict_row
from psycopg.types.json import Jsonb
from psycopg_pool import ConnectionPool
@@ -25,6 +26,10 @@ from app.timezone import to_kst_iso
STALE_RUN_AFTER = timedelta(minutes=30)
class ManualMigrationNeeded(Exception):
"""수동 입력(마이그레이션 002: perf_marketplaces.manual_input · perf_manual_sales)이 아직 적용되지 않음."""
def _iso(v: Any) -> Any:
if isinstance(v, datetime):
return to_kst_iso(v)
@@ -56,8 +61,12 @@ class PerformanceDBStore:
return [{k: _iso(v) for k, v in r.items()} for r in rows]
def update_marketplace(self, code: str, *, enabled: bool | None = None,
include_in_sales: bool | None = None) -> dict[str, Any] | None:
include_in_sales: bool | None = None,
manual_input: bool | None = None) -> dict[str, Any] | None:
sets, params = [], []
if manual_input is not None:
sets.append("manual_input = %s")
params.append(bool(manual_input))
if enabled is not None:
sets.append("enabled = %s")
params.append(bool(enabled))
@@ -67,10 +76,13 @@ class PerformanceDBStore:
if not sets:
return None
params.append(code)
with self._pool.connection() as conn:
row = conn.execute(
f"UPDATE perf_marketplaces SET {', '.join(sets)} WHERE code = %s RETURNING *", params
).fetchone()
try:
with self._pool.connection() as conn:
row = conn.execute(
f"UPDATE perf_marketplaces SET {', '.join(sets)} WHERE code = %s RETURNING *", params
).fetchone()
except pg_errors.UndefinedColumn:
raise ManualMigrationNeeded() from None
return {k: _iso(v) for k, v in row.items()} if row else None
# ════════════════════════════════════════════════════════════
@@ -281,6 +293,8 @@ class PerformanceDBStore:
"""
def daily_amounts(self, start: date, end: date, codes: list[str]) -> dict[tuple[date, str], int]:
"""날짜 × 쇼핑몰 총매출. 수동 입력이 켜진 쇼핑몰은 수동 값을 넣은 날 그 값이 API 수집값을 대신한다
(실적 화면·회의록 머리 카드가 같은 숫자를 보게 여기서 합친다)."""
if not codes:
return {}
with self._pool.connection() as conn:
@@ -290,7 +304,56 @@ class PerformanceDBStore:
"GROUP BY sales_date, marketplace_code",
(start, end, codes),
).fetchall()
return {(r["sales_date"], r["marketplace_code"]): int(r["amount"] or 0) for r in rows}
out = {(r["sales_date"], r["marketplace_code"]): int(r["amount"] or 0) for r in rows}
out.update(self.manual_amounts(start, end, codes))
return out
# ════════════════════════════════════════════════════════════
# 수동 입력 매출(마이그레이션 002)
# ════════════════════════════════════════════════════════════
def manual_amounts(self, start: date, end: date, codes: list[str], *,
active_only: bool = True) -> dict[tuple[date, str], int]:
"""수동 입력 값. active_only = 그 쇼핑몰 수동 입력이 켜진 것만(집계에 쓰는 값). 002 미적용이면 비어 있음."""
if not codes:
return {}
try:
with self._pool.connection() as conn:
rows = conn.execute(
"SELECT s.sales_date, s.marketplace_code, s.amount FROM perf_manual_sales s "
"JOIN perf_marketplaces m ON m.code = s.marketplace_code "
"WHERE s.sales_date BETWEEN %s AND %s AND s.marketplace_code = ANY(%s)"
+ (" AND m.manual_input" if active_only else ""),
(start, end, codes),
).fetchall()
except (pg_errors.UndefinedTable, pg_errors.UndefinedColumn):
return {}
return {(r["sales_date"], r["marketplace_code"]): int(r["amount"]) for r in rows}
def api_amount(self, code: str, day: date) -> int:
"""그날 API 수집 합계(수동 값과 무관) — 수동 입력 칸에 참고로 보여 준다."""
with self._pool.connection() as conn:
row = conn.execute(
"SELECT COALESCE(SUM(amount), 0)::BIGINT AS amount FROM perf_sales_events "
"WHERE marketplace_code = %s AND sales_date = %s", (code, day),
).fetchone()
return int(row["amount"] or 0)
def set_manual_sale(self, code: str, day: date, amount: int | None, *, user: str = "") -> None:
"""수동 값 저장(amount None = 지움 → 그날은 다시 API 값)."""
try:
with self._pool.connection() as conn:
if amount is None:
conn.execute("DELETE FROM perf_manual_sales WHERE marketplace_code = %s AND sales_date = %s",
(code, day))
else:
conn.execute(
"INSERT INTO perf_manual_sales (marketplace_code, sales_date, amount, updated_by) "
"VALUES (%s, %s, %s, %s) ON CONFLICT (marketplace_code, sales_date) DO UPDATE "
"SET amount = EXCLUDED.amount, updated_by = EXCLUDED.updated_by",
(code, day, int(amount), user),
)
except pg_errors.UndefinedTable:
raise ManualMigrationNeeded() from None
def daily_breakdown(self, code: str, start: date, end: date, *, id_prefix: str = "") -> list[dict[str, Any]]:
"""쇼핑몰 화면(일별 매출내역) 대조용 — 날짜별 결제(SALE 합·건수)·환불(그 밖, 양수)·마지막 수집 시각.
+49 -6
View File
@@ -10,8 +10,9 @@ JSON API — 모듈 권한
GET /performance/api/sync/current 지금 돌고 있는 업데이트(없으면 null)
POST /performance/api/sync/jobs/{id}/cancel 업데이트 취소(시작한 사람 또는 관리자)
GET /performance/api/events 금액 클릭 상세(쇼핑몰+기간)
PUT /performance/api/manual-sales/{code}/{day} 수동 입력 매출 저장/지움(그 쇼핑몰 수동 입력이 켜져 있을 때, 오늘까지)
JSON API — 관리자
PUT /performance/api/marketplaces/{code} 사용/매출 집계 여부
PUT /performance/api/marketplaces/{code} 사용/매출 집계/수동 입력 여부
POST /performance/api/marketplaces/{code}/rates 수수료율(적용 시작일)
DELETE /performance/api/marketplaces/{code}/rates/{id}
GET /performance/api/marketplaces/{code}/credentials 입력칸 + 저장 여부(비밀 원문 없음)
@@ -44,6 +45,9 @@ MAX_EVENT_DAYS = 31
MAX_CHECK_DAYS = 62 # 쇼핑몰 화면 일별 비교(카페24 일별 매출내역 붙여넣기)
MAX_BACKFILL_DAYS = 366
MAX_USER_SYNC_DAYS = 92 # 관리자가 아니어도 가져올 수 있는 기간(이번달·직접선택 짧은 기간)
MAX_MANUAL_AMOUNT = 10 ** 12 # 수동 입력 한 칸 상한(원)
MANUAL_MIGRATION_HELP = ("수동 입력을 쓰려면 performance_db 마이그레이션 002(scripts/sql/performance_db_002_manual_sales.sql)를 "
"먼저 적용해야 합니다.")
def _parse_date(value: Any, *, field: str = "날짜") -> date | None:
@@ -270,6 +274,39 @@ def api_events(request: Request, code: str, from_: str = Query(..., alias="from"
return JSONResponse({"rows": rows, "truncated": len(rows) >= 500})
@router.put("/api/manual-sales/{code}/{day}")
def api_manual_sale(request: Request, code: str, day: str, payload: dict[str, Any] = Body(...)) -> JSONResponse:
"""수동 입력 — 그 쇼핑몰 수동 입력이 켜져 있을 때만, 오늘까지. amount 가 비면 지움(그날은 다시 API 값)."""
from .db import ManualMigrationNeeded # noqa: WPS433
store, user = common.require_store(request) # 모듈 권한자 누구나(켜고 끄기는 관리자 설정)
_code_or_404(store, code)
d = _parse_date(day)
if d > today_kst():
raise HTTPException(status_code=400, detail="앞으로의 날짜는 입력할 수 없습니다.")
m = next((x for x in store.list_marketplaces() if x["code"] == code), {})
if not m.get("manual_input"):
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_manual_sale(code, d, amount, user=user.get("email", ""))
except ManualMigrationNeeded:
raise HTTPException(status_code=503, detail=MANUAL_MIGRATION_HELP) from None
api_amount = store.api_amount(code, d)
return JSONResponse({"ok": True, "code": code, "date": d.isoformat(), "manual": amount,
"amount": api_amount if amount is None else amount, "api_amount": api_amount})
# ════════════════════════════════════════════════════════════
# JSON API — 설정(수수료율은 모듈 권한자 누구나, 나머지는 관리자)
# ════════════════════════════════════════════════════════════
@@ -277,11 +314,17 @@ def api_events(request: Request, code: str, from_: str = Query(..., alias="from"
def api_update_marketplace(request: Request, code: str, payload: dict[str, Any] = Body(...)) -> JSONResponse:
store, _ = common.require_store(request, admin=True)
_code_or_404(store, code)
row = store.update_marketplace(
code,
enabled=bool(payload["enabled"]) if "enabled" in payload else None,
include_in_sales=bool(payload["include_in_sales"]) if "include_in_sales" in payload else None,
)
from .db import ManualMigrationNeeded # noqa: WPS433
try:
row = store.update_marketplace(
code,
enabled=bool(payload["enabled"]) if "enabled" in payload else None,
include_in_sales=bool(payload["include_in_sales"]) if "include_in_sales" in payload else None,
manual_input=bool(payload["manual_input"]) if "manual_input" in payload else None,
)
except ManualMigrationNeeded:
raise HTTPException(status_code=503, detail=MANUAL_MIGRATION_HELP) from None
return JSONResponse({"marketplace": row})
@@ -1,6 +1,6 @@
{% extends "erp_base.html" %}
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261001b" />{% endblock %}
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261012b" />{% endblock %}
{%- macro won(v) -%}
{%- if v is none -%}<span class="perf-na"></span>
@@ -118,7 +118,7 @@
<thead>
<tr>
<th class="perf-th-label">{% if period_kind == 'year' %}월{% else %}날짜{% endif %}</th>
{% for c in codes %}<th title="{{ names[c] }}">{{ short_names[c] }}</th>{% endfor %}
{% for c in codes %}<th title="{{ names[c] }}{% if c in manual_codes %} — 수동 입력(날짜 칸을 눌러 입력){% endif %}">{{ short_names[c] }}{% if c in manual_codes %} <span class="perf-manual-mark" aria-label="수동 입력">✎</span>{% endif %}</th>{% endfor %}
<th class="perf-th-total">{% if period_kind == 'year' %}월 합계{% else %}일 합계{% endif %}</th>
</tr>
</thead>
@@ -130,8 +130,15 @@
</th>
{% for c in codes %}
{% set m = r.cells[c] %}
{% if r.kind == 'day' and c in manual_codes and not r.future %}
{% set is_manual = (r.date ~ '|' ~ c) in manual_cells %}
<td class="perf-num is-manual-cell{% if is_manual %} is-manual{% endif %}" data-manual-code="{{ c }}" data-date="{{ r.date }}"
data-manual-value="{{ m.gross if is_manual else '' }}" tabindex="0"
title="{% if is_manual %}수동 입력값 — 눌러 고치기(비우고 저장하면 API 값){% else %}눌러 총매출 직접 입력{% endif %}">{{ m3(m) }}</td>
{% else %}
<td class="perf-num{% if r['from'] and (m.gross or m.commission) %} is-link{% endif %}"
{% if r['from'] %}data-code="{{ c }}" data-from="{{ r['from'] }}" data-to="{{ r['to'] }}"{% endif %}>{{ m3(m) }}</td>
{% endif %}
{% endfor %}
<td class="perf-num perf-td-total">{{ m3(r.total) }}</td>
</tr>
@@ -139,6 +146,10 @@
</tbody>
</table>
</div>
{% if manual_codes and period_kind != 'year' %}
<p class="perf-muted perf-manual-help">✎ 표시 쇼핑몰은 날짜 칸을 눌러 <b>총매출</b>을 직접 입력합니다 — Enter 저장 후 아래 칸, Esc 취소,
비우고 저장하면 다시 API 수집값. 파란 숫자 = 수동 입력값. 수수료는 그날 수수료율로 계산되고, 입력을 마치면 합계·그래프가 다시 계산됩니다.</p>
{% endif %}
</div>
<!-- ── 그래프 ── -->
@@ -239,4 +250,4 @@
} | tojson }}</script>
{% endblock %}
{% block scripts %}<script src="/static/performance.js?v=20261012a" defer></script>{% endblock %}
{% block scripts %}<script src="/static/performance.js?v=20261012b" defer></script>{% endblock %}
@@ -1,6 +1,6 @@
{% extends "erp_base.html" %}
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261001b" />{% endblock %}
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261012b" />{% endblock %}
{%- macro when(v) -%}{{ (v or '')[:16] | replace('T', ' ') or '—' }}{%- endmacro -%}
@@ -20,7 +20,8 @@
<div class="perf-card-head">
<h2 class="perf-h">쇼핑몰 설정</h2>
{% if is_admin %}
<span class="perf-muted">사용 · 매출 집계 · 수수료율은 바로 저장됩니다. API 인증정보는 [설정]에서 입력합니다.</span>
<span class="perf-muted">사용 · 매출 집계 · 수동 입력 · 수수료율은 바로 저장됩니다. API 인증정보는 [설정]에서 입력합니다.
수동 입력을 켜면 실적 일자별 표에서 그 쇼핑몰 날짜 칸에 매출을 직접 넣을 수 있습니다.</span>
{% else %}
<span class="perf-muted">쇼핑몰별 수수료율을 설정합니다. 바로 저장되며 실적 화면의 수수료·수수료 차감 매출에 반영됩니다.</span>
{% endif %}
@@ -31,7 +32,8 @@
<tr>
<th class="perf-th-label">쇼핑몰</th>
{% if is_admin %}<th>사용</th>
<th>매출 집계</th>{% endif %}
<th>매출 집계</th>
<th>수동 입력</th>{% endif %}
<th>수수료율</th>
{% if is_admin %}<th>API 설정</th>
<th>연결 상태</th>{% endif %}
@@ -54,6 +56,11 @@
<input type="checkbox" data-field="include_in_sales"{% if r.include_in_sales %} checked{% endif %} /><span></span>
</label>
</td>
<td class="perf-center">
<label class="perf-switch" title="수동 입력 사용 — 켜면 실적 일자별 표에서 날짜 칸에 매출을 직접 입력(입력한 날은 API 값 대신)">
<input type="checkbox" data-field="manual_input"{% if r.manual_input %} checked{% endif %} /><span></span>
</label>
</td>
{% endif %}
<td class="perf-rate-cell">
<span class="perf-rate">{% if r.rate %}{{ r.rate }}%{% else %}<span class="perf-muted">미설정</span>{% endif %}</span>
@@ -194,4 +201,4 @@
</section>
{% endblock %}
{% block scripts %}<script src="/static/performance.js?v=20261012a" defer></script>{% endblock %}
{% block scripts %}<script src="/static/performance.js?v=20261012b" defer></script>{% endblock %}
@@ -1883,3 +1883,112 @@ if __name__ == "__main__":
n += 1
print("ok", name)
print(f"{n} tests passed")
def test_manual_sale_api_rules():
"""수동 입력 API — 그 쇼핑몰 수동 입력이 켜져 있을 때만, 오늘까지, 숫자(쉼표 허용), 비우면 지움, 002 미적용이면 503.
켜고 끄기(PUT marketplaces)는 관리자 전용 그대로, manual_input 도 받는다."""
from fastapi import HTTPException
import importlib
from app.modules.performance import common
from app.modules.performance.db import ManualMigrationNeeded
router = importlib.import_module("app.modules.performance.router") # 패키지의 router 는 APIRouter 객체
class St:
def __init__(self):
self.saved, self.updated, self.missing = [], [], False
def list_marketplaces(self):
return [{"code": "coupang", "manual_input": True}, {"code": "naver", "manual_input": False}]
def set_manual_sale(self, code, day, amount, *, user=""):
if self.missing:
raise ManualMigrationNeeded()
self.saved.append((code, day, amount, user))
def api_amount(self, code, day):
return 50000
def update_marketplace(self, code, **kw):
if self.missing and kw.get("manual_input") is not None:
raise ManualMigrationNeeded()
self.updated.append((code, kw))
return {"code": code}
st = St()
seen = {}
def fake_require(request, *, admin=False):
seen["admin"] = admin
return st, {"email": "me@test.local"}
def status_of(fn):
try:
fn()
except HTTPException as exc:
return exc.status_code, exc.detail
return 200, ""
orig = (common.require_store, router.today_kst)
common.require_store, router.today_kst = fake_require, (lambda: date(2026, 10, 12))
try:
r = router.api_manual_sale(None, "coupang", "2026-10-12", {"amount": "87,000"})
body = __import__("json").loads(r.body)
assert st.saved[-1] == ("coupang", date(2026, 10, 12), 87000, "me@test.local") and seen["admin"] is False
assert body["manual"] == 87000 and body["amount"] == 87000 and body["api_amount"] == 50000
body = __import__("json").loads(router.api_manual_sale(None, "coupang", "2026-10-11", {"amount": ""}).body)
assert st.saved[-1][2] is None and body["manual"] is None and body["amount"] == 50000 # 지움 → API 값
assert status_of(lambda: router.api_manual_sale(None, "coupang", "2026-10-13", {"amount": 1}))[0] == 400 # 앞날
code, msg = status_of(lambda: router.api_manual_sale(None, "naver", "2026-10-12", {"amount": 1}))
assert code == 400 and "수동 입력" in msg # 꺼진 쇼핑몰
assert status_of(lambda: router.api_manual_sale(None, "coupang", "2026-10-12", {"amount": "abc"}))[0] == 400
assert status_of(lambda: router.api_manual_sale(None, "coupang", "2026-10-12", {"amount": 10 ** 13}))[0] == 400
assert status_of(lambda: router.api_manual_sale(None, "nope", "2026-10-12", {"amount": 1}))[0] == 404
router.api_update_marketplace(None, "coupang", {"manual_input": True})
assert seen["admin"] is True and st.updated[-1] == ("coupang", {"enabled": None, "include_in_sales": None, "manual_input": True})
st.missing = True
code, msg = status_of(lambda: router.api_manual_sale(None, "coupang", "2026-10-12", {"amount": 1}))
assert code == 503 and "002" in msg
assert status_of(lambda: router.api_update_marketplace(None, "coupang", {"manual_input": False}))[0] == 503
finally:
common.require_store, router.today_kst = orig
def test_dashboard_manual_cells_and_order():
"""대시보드 — 수동 입력 켠 쇼핑몰만 manual_codes, 값이 있는 칸만 manual_cells, 수동 값이 그날 금액(수수료도 그 값으로)."""
from decimal import Decimal
from app.modules.performance.dashboard import build_dashboard
class St:
def list_marketplaces(self):
return [{"code": c, "name": c, "enabled": True, "include_in_sales": True, "manual_input": c == "coupang"}
for c in ("cafe24", "naver", "coupang", "toss")]
def daily_amounts(self, start, end, codes):
return {(date(2026, 10, 5), "coupang"): 87000} # 저장소가 이미 수동 값으로 바꿔 돌려준다
def manual_amounts(self, start, end, codes, *, active_only=True):
assert codes == ["coupang"]
return {(date(2026, 10, 5), "coupang"): 87000} if start <= date(2026, 10, 5) <= end else {}
def rate_table(self):
return {"coupang": [(date(2026, 1, 1), Decimal("10"))]}
def statuses(self):
return {}
def last_update_at(self):
return None
def running_codes(self):
return []
ctx = build_dashboard(St(), kind="week", anchor=date(2026, 10, 7), today=date(2026, 10, 7))
assert ctx["codes"] == ["cafe24", "naver", "coupang", "toss"]
assert ctx["manual_codes"] == ["coupang"] and ctx["manual_cells"] == ["2026-10-05|coupang"]
day5 = next(r for r in ctx["table"] if r.get("date") == "2026-10-05")
assert day5["cells"]["coupang"]["gross"] == 87000 and day5["cells"]["coupang"]["commission"] == 8700