Merge branch 'feat/perf-manual-input'
This commit is contained in:
@@ -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}
|
||||
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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 합·건수)·환불(그 밖, 양수)·마지막 수집 시각.
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -102,11 +102,12 @@ a.perf-seg.is-active, a.perf-seg.is-active:link, a.perf-seg.is-active:visited {
|
||||
.perf-table-wrap { overflow-x: auto; }
|
||||
.perf-table { width: 100%; border-collapse: collapse; font-size: 12.5px; }
|
||||
.perf-table th, .perf-table td { padding: 6px 8px; border-bottom: 1px solid #efefef; white-space: nowrap; }
|
||||
/* 열 제목 — 가운데·굵게·검정(2026-10-12) */
|
||||
.perf-table thead th {
|
||||
font-size: 12px; font-weight: 500; color: var(--color-midtone-gray); text-align: right;
|
||||
font-size: 12px; font-weight: 700; color: #000; text-align: center;
|
||||
background: var(--perf-soft); border-bottom: 1px solid var(--perf-line); position: sticky; top: 0;
|
||||
}
|
||||
.perf-table thead th.perf-th-label { text-align: left; }
|
||||
.perf-table thead th.perf-th-label { text-align: center; }
|
||||
.perf-td-label { text-align: left; font-weight: 500; }
|
||||
.perf-num { text-align: right; }
|
||||
.perf-zero { color: #c9c9c9; }
|
||||
@@ -128,6 +129,18 @@ td.is-link:hover { background: #eef2ff; text-decoration: underline; }
|
||||
|
||||
/* 표시 기준 전환 — 한 칸에 3값, data-metric 으로 하나만 보인다 */
|
||||
.perf .v { display: none; }
|
||||
/* 수동 입력 칸 — 설정에서 켠 쇼핑몰의 날짜 칸. 파란 숫자 = 수동 입력값, 입력 중엔 숫자 대신 입력칸 */
|
||||
.perf-manual-mark { font-size: 11px; color: #1a56db; font-weight: 400; }
|
||||
.perf-main td.is-manual-cell { cursor: text; position: relative; }
|
||||
.perf-main td.is-manual-cell:hover { background: #eef3ff; box-shadow: inset 0 0 0 1px #c7d6fb; }
|
||||
.perf-main td.is-manual-cell:focus { outline: 2px solid #1a56db; outline-offset: -2px; }
|
||||
.perf-main td.is-manual .v-gross { color: #1a56db; font-weight: 600; }
|
||||
.perf-main td.is-stale .v-commission, .perf-main td.is-stale .v-net { opacity: .4; }
|
||||
.perf-main td.is-editing { padding: 2px 4px; }
|
||||
.perf .perf-main td.is-editing .v { display: none; }
|
||||
.perf-manual-input { width: 100%; min-width: 90px; box-sizing: border-box; padding: 3px 6px; border: 1px solid #1a56db; border-radius: 4px;
|
||||
font: inherit; text-align: right; background: #fff; outline: none; }
|
||||
.perf-manual-help { margin: 8px 2px 0; font-size: 12px; }
|
||||
.perf[data-metric="gross"] .v-gross,
|
||||
.perf[data-metric="commission"] .v-commission,
|
||||
.perf[data-metric="net"] .v-net { display: inline; }
|
||||
|
||||
@@ -333,6 +333,89 @@
|
||||
if (!td) return;
|
||||
openEvents(td.dataset.code, td.dataset.from, td.dataset.to);
|
||||
});
|
||||
|
||||
// ── 수동 입력(설정에서 켠 쇼핑몰) — 날짜 칸을 눌러 총매출 입력. Enter 저장 후 아래 칸 · Shift+Enter 위 칸 · Esc 취소.
|
||||
// 비우고 저장하면 그날은 다시 API 값. 저장은 칸마다 차례로, 입력을 마치면(다른 칸으로 안 넘어가면) 새로고침해
|
||||
// 합계·수수료·그래프를 서버 계산으로 다시 그린다.
|
||||
let manualDirty = false;
|
||||
let manualChain = Promise.resolve();
|
||||
function manualCells(code) {
|
||||
return Array.prototype.slice.call(root.querySelectorAll('td.is-manual-cell[data-manual-code="' + code + '"]'));
|
||||
}
|
||||
function digitsOf(td) { return td.dataset.manualValue || ""; }
|
||||
function finishManual() {
|
||||
setTimeout(function () {
|
||||
if (root.querySelector(".perf-manual-input")) return; // 다른 칸으로 넘어감
|
||||
manualChain.then(function () { if (manualDirty) location.reload(); });
|
||||
}, 120);
|
||||
}
|
||||
function saveManual(td, text) {
|
||||
const raw = String(text || "").replace(/[,\s원]/g, "");
|
||||
const was = digitsOf(td);
|
||||
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) + "/" +
|
||||
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 값)" : "눌러 총매출 직접 입력";
|
||||
const g = td.querySelector(".v-gross");
|
||||
if (g) g.innerHTML = won(res.amount);
|
||||
td.classList.add("is-stale"); // 수수료·차감 매출은 새로고침 때 다시 계산
|
||||
manualDirty = true;
|
||||
return true;
|
||||
});
|
||||
manualChain = job.catch(function () {});
|
||||
return job;
|
||||
}
|
||||
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 + " 총매출" });
|
||||
input.value = digitsOf(td);
|
||||
const g = td.querySelector(".v-gross");
|
||||
input.placeholder = digitsOf(td) ? "" : (g ? g.textContent.trim().replace(/[–-]/, "") : "") || "총매출";
|
||||
td.classList.add("is-editing");
|
||||
td.appendChild(input);
|
||||
input.focus();
|
||||
input.select();
|
||||
let done = false;
|
||||
function close() {
|
||||
if (done) return;
|
||||
done = true;
|
||||
input.remove();
|
||||
td.classList.remove("is-editing");
|
||||
}
|
||||
function commit(step) {
|
||||
if (done) return;
|
||||
const val = input.value;
|
||||
close();
|
||||
const cells = manualCells(td.dataset.manualCode);
|
||||
const next = step ? cells[cells.indexOf(td) + step] : null;
|
||||
if (next) editManual(next);
|
||||
saveManual(td, val).catch(function (err) {
|
||||
alertMsg("저장 실패(" + td.dataset.date + "): " + err.message);
|
||||
}).then(finishManual);
|
||||
}
|
||||
input.addEventListener("keydown", function (e) {
|
||||
if (e.isComposing) return;
|
||||
if (e.key === "Enter" || e.key === "Tab") { e.preventDefault(); commit(e.shiftKey ? -1 : 1); }
|
||||
else if (e.key === "ArrowDown" || e.key === "ArrowUp") { e.preventDefault(); commit(e.key === "ArrowUp" ? -1 : 1); }
|
||||
else if (e.key === "Escape") { e.preventDefault(); close(); td.focus(); finishManual(); }
|
||||
});
|
||||
input.addEventListener("blur", function () { commit(0); });
|
||||
}
|
||||
root.addEventListener("click", function (e) {
|
||||
const td = e.target.closest("td.is-manual-cell");
|
||||
if (td && !e.target.closest(".perf-manual-input")) editManual(td);
|
||||
});
|
||||
root.addEventListener("keydown", function (e) {
|
||||
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); }
|
||||
});
|
||||
async function openEvents(code, from, to) {
|
||||
const name = (data.names || {})[code] || code;
|
||||
const title = name + " · " + (from === to ? from : from + " ~ " + to) + " 주문 내역";
|
||||
|
||||
@@ -125,6 +125,19 @@ docker exec postgres-db psql -U postgres -d project_db -c "SELECT to_regclass('g
|
||||
|
||||
설정이 없거나 권한이 모자라면 버튼을 눌렀을 때 사유가 안내되고(503), 회의록 다른 기능은 그대로 동작한다.
|
||||
|
||||
## 실적 수동 입력·열 순서 마이그레이션 (performance_db 002)
|
||||
|
||||
002는 `perf_marketplaces.manual_input` 열(기본 꺼짐) + `perf_manual_sales` 표를 추가하고, 쇼핑몰 순서(`sort_order`)를
|
||||
카페24·네이버·쿠팡·토스·GS샵·11번가·오늘의집·G마켓·카카오·롯데ON 으로 바꾼다(기존 매출·인증정보 그대로, 다시 실행 가능).
|
||||
미적용이면 수동 입력 토글·저장만 503 안내, 나머지 실적 화면은 그대로 동작한다.
|
||||
|
||||
```bash
|
||||
cd /opt/www/main
|
||||
docker exec postgres-db pg_dump -U postgres performance_db > ~/performance_db_before_002_$(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_002_manual_sales.sql
|
||||
docker exec postgres-db psql -U postgres -d performance_db -c "SELECT code, sort_order, manual_input FROM perf_marketplaces ORDER BY sort_order;"
|
||||
```
|
||||
|
||||
## 회의록 작업 등록 표 — 작업 칸 마이그레이션 (026)
|
||||
|
||||
026은 `goal_meeting_tasks.parent_task_id` 열만 추가한다(기존 값 그대로, 다시 실행 가능). 025 뒤에 적용한다. 미적용이면 작업 칸을 고를 때만 503 안내.
|
||||
|
||||
@@ -200,6 +200,19 @@
|
||||
④ 취소분 뺀 값 ⑤ 로켓그로스 + 판매량 — 를 WING 판매분석의 같은 날 "매출(원)"·"판매량" 과 비교해 규칙을 확정한다(`candidates_title`).
|
||||
로켓그로스만 거부돼도 판매자배송 결과는 보인다.
|
||||
|
||||
### 수동 입력(마이그레이션 002, 2026-10-12)
|
||||
|
||||
- 설정 → 쇼핑몰 표 **수동 입력** 토글(관리자, `perf_marketplaces.manual_input`, 기본 꺼짐). 켜면 실적 일자별 표에서 그 쇼핑몰의
|
||||
**오늘까지 날짜 칸**을 눌러 총매출을 입력한다(제목 ✎, 수동 값은 파란 숫자). Enter·Tab·↓ 저장 후 아래 칸, Shift+Enter·↑ 위 칸, Esc 취소,
|
||||
칸을 벗어나면 저장. 입력을 마치면 새로고침해 합계·수수료·그래프를 서버 계산으로 다시 그린다. 입력은 모듈 권한자 누구나
|
||||
(`PUT /performance/api/manual-sales/{code}/{day}`, `{amount}` — 비우면 지움, 쉼표·"원" 허용, ±1조 이내, 앞날·꺼진 쇼핑몰은 400).
|
||||
- 값은 `perf_manual_sales`(쇼핑몰 × 날짜 하나, `updated_by`). **넣은 날은 그 값이 API 수집값을 대신**하고(합산 아님), 넣지 않은 날은
|
||||
API 값. 대체는 `PerformanceDBStore.daily_amounts` 한 곳에서 해 실적 화면·회의록 머리 카드가 같은 숫자를 본다. 수수료는 그날 요율로 계산.
|
||||
토글을 끄면 값은 남지만 집계에 쓰지 않는다. 매출 업데이트(동기화)는 수동 값을 지우지 않는다.
|
||||
- 002 미적용: 읽기는 수동 값 없음으로 조용히 동작, 토글·저장은 503 안내.
|
||||
- 열 순서(002 + `registry.py`): 카페24 · 네이버 · 쿠팡 · 토스 · GS샵 · 11번가 · 오늘의집 · G마켓 · 카카오 · 롯데ON.
|
||||
- 표 열 제목은 가운데·굵게·검정(`.perf-table thead th`).
|
||||
|
||||
### 연동 단계 체크리스트(쇼핑몰마다)
|
||||
|
||||
- 공식 문서로 인증 방식·호출 제한·페이지네이션·주문 상태 코드·취소/반품 API·날짜 필드 확인
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
-- =====================================================================
|
||||
-- performance_db 마이그레이션 002 — 쇼핑몰별 수동 입력 + 열 순서
|
||||
-- =====================================================================
|
||||
-- 멱등(idempotent). 기존 데이터 삭제 없음. 운영: /opt/www/main 에서 기존 performance_db 에 superuser 로 적용.
|
||||
-- docker exec -i postgres-db psql -v ON_ERROR_STOP=1 -U postgres -d performance_db \
|
||||
-- < scripts/sql/performance_db_002_manual_sales.sql
|
||||
--
|
||||
-- 왜(2026-10-12 사용자 요청):
|
||||
-- 1) 설정 → 쇼핑몰마다 "수동 입력" 사용 여부(perf_marketplaces.manual_input). 켜면 실적 일자별 표의 그 쇼핑몰
|
||||
-- 날짜 칸에 매출(총매출)을 직접 넣는다 — 넣은 날은 그 값이 API 수집값을 대신한다(비우면 다시 API 값).
|
||||
-- 끄면 넣어 둔 값은 남지만 집계에 쓰지 않는다.
|
||||
-- 2) 열 순서: 카페24 · 네이버 · 쿠팡 · 토스 · GS샵 · 11번가 · 오늘의집 · G마켓 · 카카오 · 롯데ON (sort_order 만 바꿈).
|
||||
-- =====================================================================
|
||||
BEGIN;
|
||||
|
||||
ALTER TABLE perf_marketplaces ADD COLUMN IF NOT EXISTS manual_input BOOLEAN NOT NULL DEFAULT FALSE;
|
||||
COMMENT ON COLUMN perf_marketplaces.manual_input IS '수동 입력 사용 — 켜면 perf_manual_sales 값이 그날 API 수집값을 대신한다';
|
||||
|
||||
-- 수동 입력 매출 — 쇼핑몰 × 날짜 하나에 값 하나(원 단위 정수, 총매출). 수수료는 다른 매출처럼 요율로 계산.
|
||||
CREATE TABLE IF NOT EXISTS perf_manual_sales (
|
||||
marketplace_code TEXT NOT NULL REFERENCES perf_marketplaces(code),
|
||||
sales_date DATE NOT NULL,
|
||||
amount BIGINT NOT NULL,
|
||||
updated_by TEXT NOT NULL DEFAULT '',
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (marketplace_code, sales_date)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_perf_manual_sales_date ON perf_manual_sales (sales_date);
|
||||
DROP TRIGGER IF EXISTS trg_perf_manual_sales_updated ON perf_manual_sales;
|
||||
CREATE TRIGGER trg_perf_manual_sales_updated
|
||||
BEFORE UPDATE ON perf_manual_sales
|
||||
FOR EACH ROW EXECUTE FUNCTION perf_set_updated_at();
|
||||
|
||||
GRANT SELECT, INSERT, UPDATE, DELETE ON perf_manual_sales TO performance_app;
|
||||
|
||||
-- 열 순서(설정·실적 표 공통)
|
||||
UPDATE perf_marketplaces AS m SET sort_order = v.sort_order
|
||||
FROM (VALUES ('cafe24', 10), ('naver', 20), ('coupang', 30), ('toss', 40), ('gsshop', 50), ('elevenst', 60),
|
||||
('ohouse', 70), ('gmarket', 80), ('kakao', 90), ('lotteon', 100)) AS v(code, sort_order)
|
||||
WHERE m.code = v.code AND m.sort_order <> v.sort_order;
|
||||
|
||||
COMMIT;
|
||||
SELECT 'performance_db 002 manual sales ready' AS status;
|
||||
@@ -62,9 +62,11 @@ CREATE TABLE IF NOT EXISTS perf_marketplaces (
|
||||
enabled BOOLEAN NOT NULL DEFAULT TRUE,
|
||||
include_in_sales BOOLEAN NOT NULL DEFAULT TRUE,
|
||||
sort_order INTEGER NOT NULL DEFAULT 0,
|
||||
manual_input BOOLEAN NOT NULL DEFAULT FALSE, -- 수동 입력 사용(002) — perf_manual_sales 값이 그날 API 값을 대신
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
ALTER TABLE perf_marketplaces ADD COLUMN IF NOT EXISTS manual_input BOOLEAN NOT NULL DEFAULT FALSE;
|
||||
DROP TRIGGER IF EXISTS trg_perf_marketplaces_updated ON perf_marketplaces;
|
||||
CREATE TRIGGER trg_perf_marketplaces_updated
|
||||
BEFORE UPDATE ON perf_marketplaces
|
||||
@@ -74,13 +76,13 @@ INSERT INTO perf_marketplaces (code, name, sort_order) VALUES
|
||||
('cafe24', '카페24', 10),
|
||||
('naver', '네이버 스마트스토어', 20),
|
||||
('coupang', '쿠팡', 30),
|
||||
('ohouse', '오늘의집', 40),
|
||||
('gmarket', 'G마켓', 50),
|
||||
('kakao', '카카오', 60),
|
||||
('gsshop', 'GS샵', 70),
|
||||
('elevenst', '11번가', 80),
|
||||
('lotteon', '롯데ON', 90),
|
||||
('toss', '토스쇼핑', 100)
|
||||
('toss', '토스쇼핑', 40),
|
||||
('gsshop', 'GS샵', 50),
|
||||
('elevenst', '11번가', 60),
|
||||
('ohouse', '오늘의집', 70),
|
||||
('gmarket', 'G마켓', 80),
|
||||
('kakao', '카카오', 90),
|
||||
('lotteon', '롯데ON', 100)
|
||||
ON CONFLICT (code) DO NOTHING;
|
||||
|
||||
-- ════════════════════════════════════════════════════════════
|
||||
@@ -208,13 +210,31 @@ CREATE UNIQUE INDEX IF NOT EXISTS uq_perf_sync_running
|
||||
ON perf_sync_runs (marketplace_code) WHERE status = 'running';
|
||||
CREATE INDEX IF NOT EXISTS idx_perf_sync_runs_code ON perf_sync_runs (marketplace_code, started_at DESC);
|
||||
|
||||
-- ════════════════════════════════════════════════════════════
|
||||
-- 7) 수동 입력 매출(002) — 쇼핑몰 × 날짜 하나에 총매출 하나. 그 쇼핑몰 수동 입력이 켜져 있을 때만 집계에 쓴다.
|
||||
-- ════════════════════════════════════════════════════════════
|
||||
CREATE TABLE IF NOT EXISTS perf_manual_sales (
|
||||
marketplace_code TEXT NOT NULL REFERENCES perf_marketplaces(code),
|
||||
sales_date DATE NOT NULL,
|
||||
amount BIGINT NOT NULL,
|
||||
updated_by TEXT NOT NULL DEFAULT '',
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (marketplace_code, sales_date)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_perf_manual_sales_date ON perf_manual_sales (sales_date);
|
||||
DROP TRIGGER IF EXISTS trg_perf_manual_sales_updated ON perf_manual_sales;
|
||||
CREATE TRIGGER trg_perf_manual_sales_updated
|
||||
BEFORE UPDATE ON perf_manual_sales
|
||||
FOR EACH ROW EXECUTE FUNCTION perf_set_updated_at();
|
||||
|
||||
-- ════════════════════════════════════════════════════════════
|
||||
-- 권한 — 앱 계정은 DML 만
|
||||
-- ════════════════════════════════════════════════════════════
|
||||
GRANT USAGE ON SCHEMA public TO performance_app;
|
||||
GRANT SELECT, INSERT, UPDATE, DELETE ON
|
||||
perf_marketplaces, perf_commission_rates, perf_credentials,
|
||||
perf_connection_status, perf_sales_events, perf_sync_runs
|
||||
perf_connection_status, perf_sales_events, perf_sync_runs, perf_manual_sales
|
||||
TO performance_app;
|
||||
GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA public TO performance_app;
|
||||
ALTER DEFAULT PRIVILEGES IN SCHEMA public
|
||||
|
||||
@@ -0,0 +1,145 @@
|
||||
// 실적 — 수동 입력(static/performance.js) · 열 순서 · 설정 토글 — jsdom.
|
||||
// python tests/js/render_performance.py && NODE_PATH=<jsdom 경로> node tests/js/perf_manual.test.js
|
||||
const fs = require("fs"), path = require("path");
|
||||
const { JSDOM } = require("jsdom");
|
||||
const OUT = path.join(__dirname, ".out");
|
||||
const JS = fs.readFileSync(path.join(__dirname, "..", "..", "app", "static", "performance.js"), "utf8");
|
||||
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); }
|
||||
}
|
||||
const settle = function () { return new Promise(function (r) { let i = 0; (function s() { if (i++ > 40) return r(); setImmediate(s); })(); }); };
|
||||
const wait = function (ms) { return new Promise(function (r) { setTimeout(r, ms); }); };
|
||||
|
||||
async function env(file) {
|
||||
const html = fs.readFileSync(path.join(OUT, file), "utf8").replace(/<script src="\/static\/performance\.js[^"]*" defer><\/script>/, "");
|
||||
const dom = new JSDOM(html, { runScripts: "dangerously", pretendToBeVisual: true, url: "http://localhost/performance/" });
|
||||
const w = dom.window;
|
||||
const e = { w: w, d: w.document, calls: [], status: 200, alerts: [] };
|
||||
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 });
|
||||
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) {
|
||||
const api = m[1] === "coupang" && m[2] === "2026-10-05" ? 50000 : m[1] === "coupang" && m[2] === "2026-10-06" ? 7000 : 0;
|
||||
const manual = body.amount == null ? null : body.amount;
|
||||
return { ok: true, status: 200, json: async function () { return { ok: true, manual: manual, amount: manual == null ? api : manual, api_amount: api }; } };
|
||||
}
|
||||
return { ok: true, status: 200, json: async function () { return {}; } };
|
||||
};
|
||||
w.eval(JS);
|
||||
// jsdom 이 문서를 다 읽은 뒤 DOMContentLoaded 를 스스로 보낸다(직접 보내면 초기화가 두 번 됨)
|
||||
if (w.document.readyState !== "loading") w.document.dispatchEvent(new w.Event("DOMContentLoaded"));
|
||||
await settle();
|
||||
return e;
|
||||
}
|
||||
function key(e, el, k, extra) { el.dispatchEvent(new e.w.KeyboardEvent("keydown", Object.assign({ key: k, bubbles: true, cancelable: true }, extra || {}))); }
|
||||
function cell(e, code, day) { return e.d.querySelector('td.is-manual-cell[data-manual-code="' + code + '"][data-date="' + day + '"]'); }
|
||||
function gross(td) { return td.querySelector(".v-gross").textContent.trim(); }
|
||||
|
||||
(async function () {
|
||||
// ── 열 순서·제목 ──
|
||||
{
|
||||
const e = await env("perf_dash.html");
|
||||
const heads = Array.from(e.d.querySelectorAll(".perf-main thead th")).map(function (th) { return th.textContent.replace("✎", "").trim(); });
|
||||
check("[순서] 카페24·네이버·쿠팡·토스·GS샵·11번가 다음 나머지", heads.join(",") ===
|
||||
"날짜,카페24,네이버,쿠팡,토스,GS샵,11번가,오늘의집,G마켓,카카오,롯데ON,일 합계", heads);
|
||||
check("[수동] 수동 입력 쇼핑몰 제목에 ✎ 표시", /✎/.test(e.d.querySelectorAll(".perf-main thead th")[3].textContent) &&
|
||||
!/✎/.test(e.d.querySelectorAll(".perf-main thead th")[1].textContent));
|
||||
check("[수동] 오늘까지 날짜 칸만 입력 칸(앞으로의 날·주간합계 아님), 수동 값 칸은 파란 표시",
|
||||
!!cell(e, "coupang", "2026-10-07") && !cell(e, "coupang", "2026-10-08") && cell(e, "coupang", "2026-10-05").classList.contains("is-manual") &&
|
||||
!cell(e, "coupang", "2026-10-06").classList.contains("is-manual") && !e.d.querySelector(".perf-row-week td.is-manual-cell"));
|
||||
check("[수동] 입력 칸은 주문 상세 링크가 아님", !cell(e, "coupang", "2026-10-06").classList.contains("is-link") &&
|
||||
e.d.querySelector('td.is-link[data-code="cafe24"]') !== null);
|
||||
check("[수동] 표 아래 사용법 안내", /직접 입력/.test((e.d.querySelector(".perf-manual-help") || {}).textContent || ""));
|
||||
}
|
||||
// ── 입력 → Enter 저장 후 아래 칸 → Esc 끝 ──
|
||||
{
|
||||
const e = await env("perf_dash.html");
|
||||
let reloaded = 0;
|
||||
const td5 = cell(e, "coupang", "2026-10-05");
|
||||
td5.click();
|
||||
const in5 = td5.querySelector(".perf-manual-input");
|
||||
check("[입력] 칸을 누르면 입력칸(수동 값이 들어 있음)", !!in5 && in5.value === "87000" && e.d.activeElement === in5);
|
||||
in5.value = "90,000원";
|
||||
key(e, in5, "Enter");
|
||||
await settle();
|
||||
const put = e.calls.find(function (c) { return c.method === "PUT"; });
|
||||
check("[입력] Enter → 그 칸 저장(쉼표·원 빼고 숫자)", put && put.url === "/performance/api/manual-sales/coupang/2026-10-05" && put.body.amount === 90000, e.calls);
|
||||
check("[입력] 저장한 값 표시 + 아래 칸(10/6)으로 입력칸 이동", gross(td5) === "90,000" && !td5.querySelector(".perf-manual-input") &&
|
||||
!!cell(e, "coupang", "2026-10-06").querySelector(".perf-manual-input"));
|
||||
const in6 = cell(e, "coupang", "2026-10-06").querySelector(".perf-manual-input");
|
||||
check("[입력] 수동 값 없는 칸은 비어 있고 API 값이 흐리게(placeholder)", in6.value === "" && in6.placeholder === "7,000", in6.placeholder);
|
||||
key(e, in6, "Enter"); // 아무것도 안 넣고 Enter — 저장 안 함
|
||||
await settle();
|
||||
check("[입력] 빈 칸 그대로 Enter → 저장 요청 없음", e.calls.filter(function (c) { return c.method === "PUT"; }).length === 1);
|
||||
const in7 = cell(e, "coupang", "2026-10-07").querySelector(".perf-manual-input");
|
||||
check("[입력] 마지막 입력 칸(오늘)까지 이동", !!in7);
|
||||
in7.value = "abc";
|
||||
key(e, in7, "Enter");
|
||||
await settle(); await wait(200); await settle();
|
||||
check("[입력] 숫자가 아니면 저장 안 하고 안내", e.alerts.some(function (m) { return /숫자/.test(m); }) &&
|
||||
e.calls.filter(function (c) { return c.method === "PUT"; }).length === 1, e.alerts);
|
||||
}
|
||||
// ── 수동 값 지우기(비우고 저장) → API 값, 실패 시 안내 ──
|
||||
{
|
||||
const e = await env("perf_dash.html");
|
||||
const td5 = cell(e, "coupang", "2026-10-05");
|
||||
td5.click();
|
||||
const inp = td5.querySelector(".perf-manual-input");
|
||||
inp.value = "";
|
||||
key(e, inp, "Escape");
|
||||
check("[지우기] Esc → 저장 없이 닫힘", !td5.querySelector(".perf-manual-input") && !e.calls.some(function (c) { return c.method === "PUT"; }));
|
||||
td5.click();
|
||||
const inp2 = td5.querySelector(".perf-manual-input");
|
||||
inp2.value = "";
|
||||
inp2.dispatchEvent(new e.w.FocusEvent("blur"));
|
||||
await settle();
|
||||
const put = e.calls.find(function (c) { return c.method === "PUT"; });
|
||||
check("[지우기] 비우고 칸을 떠나면 amount=null(그날 API 값)", put && put.body.amount === null);
|
||||
check("[지우기] API 값(50,000) 표시·파란 표시 해제", gross(td5) === "50,000" && !td5.classList.contains("is-manual"));
|
||||
e.status = 503;
|
||||
const td6 = cell(e, "coupang", "2026-10-06");
|
||||
td6.click();
|
||||
const i6 = td6.querySelector(".perf-manual-input");
|
||||
i6.value = "100";
|
||||
i6.dispatchEvent(new e.w.FocusEvent("blur"));
|
||||
await settle();
|
||||
check("[실패] 저장 실패 → 안내(마이그레이션), 값은 그대로", e.alerts.some(function (m) { return /마이그레이션 002/.test(m); }) && gross(td6) === "7,000", e.alerts);
|
||||
}
|
||||
// ── 키보드: 칸에서 Enter 로 입력 시작 ──
|
||||
{
|
||||
const e = await env("perf_dash.html");
|
||||
const td = cell(e, "kakao", "2026-10-06");
|
||||
td.focus();
|
||||
key(e, td, "Enter");
|
||||
check("[키보드] 칸에 포커스 후 Enter → 입력칸", !!td.querySelector(".perf-manual-input"));
|
||||
}
|
||||
// ── 설정: 수동 입력 토글 ──
|
||||
{
|
||||
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);
|
||||
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;
|
||||
box.dispatchEvent(new e.w.Event("change", { bubbles: true }));
|
||||
await settle();
|
||||
const put = e.calls.find(function (c) { return c.method === "PUT"; });
|
||||
check("[설정] 토글 → 바로 저장(manual_input)", put && put.url === "/performance/api/marketplaces/coupang" && put.body.manual_input === false, e.calls);
|
||||
e.status = 503;
|
||||
const box2 = e.d.querySelector('tr[data-code="naver"] input[data-field="manual_input"]');
|
||||
box2.checked = true;
|
||||
box2.dispatchEvent(new e.w.Event("change", { bubbles: true }));
|
||||
await settle();
|
||||
check("[설정] 저장 실패(002 미적용) → 되돌리고 안내", !box2.checked && e.alerts.some(function (m) { return /마이그레이션/.test(m); }), e.alerts);
|
||||
}
|
||||
console.log(fails.length ? "\n" + fails.length + " FAILED" : "\nALL PASS");
|
||||
process.exit(fails.length ? 1 : 0);
|
||||
})();
|
||||
@@ -0,0 +1,84 @@
|
||||
"""실적 대시보드(index.html)·설정(settings.html)을 테스트용 HTML 로 렌더한다(erp_base.html 은 최소 스텁, 가상의 데이터).
|
||||
|
||||
python tests/js/render_performance.py # → tests/js/.out/perf_dash.html · perf_settings.html
|
||||
|
||||
화면 데이터는 실제 build_dashboard·build_settings 로 만든다(저장소만 가짜). DB·쇼핑몰 API 는 쓰지 않는다.
|
||||
쿠팡은 수동 입력 켬(10/5 수동 값 87,000, 10/6 은 API 값만), 카카오도 켬(값 없음), 나머지는 끔.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import sys
|
||||
from datetime import date
|
||||
from decimal import Decimal
|
||||
|
||||
import jinja2
|
||||
|
||||
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.dashboard import build_dashboard, build_settings # noqa: E402
|
||||
|
||||
BASE_STUB = ("{% block head_extra %}{% endblock %}<body><main class='erp-page'>{% block content %}{% endblock %}</main>"
|
||||
"{% block scripts %}{% endblock %}</body>")
|
||||
ORDER = ["cafe24", "naver", "coupang", "toss", "gsshop", "elevenst", "ohouse", "gmarket", "kakao", "lotteon"]
|
||||
NAMES = {"cafe24": "카페24", "naver": "네이버 스마트스토어", "coupang": "쿠팡", "toss": "토스쇼핑", "gsshop": "GS샵",
|
||||
"elevenst": "11번가", "ohouse": "오늘의집", "gmarket": "G마켓", "kakao": "카카오", "lotteon": "롯데ON"}
|
||||
|
||||
|
||||
class FakeStore:
|
||||
def list_marketplaces(self):
|
||||
return [{"code": c, "name": NAMES[c], "enabled": True, "include_in_sales": True, "sort_order": i * 10,
|
||||
"manual_input": c in ("coupang", "kakao")} for i, c in enumerate(ORDER, 1)]
|
||||
|
||||
def daily_amounts(self, start, end, codes):
|
||||
api = {(date(2026, 10, 5), "coupang"): 50000, (date(2026, 10, 6), "coupang"): 7000,
|
||||
(date(2026, 10, 5), "cafe24"): 100000}
|
||||
out = {k: v for k, v in api.items() if start <= k[0] <= end and k[1] in codes}
|
||||
out.update(self.manual_amounts(start, end, codes))
|
||||
return out
|
||||
|
||||
def manual_amounts(self, start, end, codes, *, active_only=True):
|
||||
manual = {(date(2026, 10, 5), "coupang"): 87000}
|
||||
return {k: v for k, v in manual.items() if start <= k[0] <= end and k[1] in codes}
|
||||
|
||||
def rate_table(self):
|
||||
return {"coupang": [(date(2026, 1, 1), Decimal("12"))]}
|
||||
|
||||
def statuses(self):
|
||||
return {}
|
||||
|
||||
def last_update_at(self):
|
||||
return None
|
||||
|
||||
def running_codes(self):
|
||||
return []
|
||||
|
||||
|
||||
def env() -> jinja2.Environment:
|
||||
e = jinja2.Environment(loader=jinja2.ChoiceLoader([
|
||||
jinja2.DictLoader({"erp_base.html": BASE_STUB}),
|
||||
jinja2.FileSystemLoader(os.path.join(ROOT, "app", "modules", "performance", "templates")),
|
||||
]), autoescape=True)
|
||||
return e
|
||||
|
||||
|
||||
def main() -> None:
|
||||
os.makedirs(OUT_DIR, exist_ok=True)
|
||||
e = env()
|
||||
base = {"user": {"email": "me@test.local"}, "is_admin": True, "nav_items": [], "page_title": "실적", "page_subtitle": ""}
|
||||
ctx = build_dashboard(FakeStore(), kind="week", anchor=date(2026, 10, 7), today=date(2026, 10, 7))
|
||||
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)
|
||||
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:
|
||||
f.write(html)
|
||||
print("ok")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user