Merge branch 'feat/perf-manual-upload'
This commit is contained in:
@@ -27,3 +27,6 @@ tests/js/.out/
|
||||
|
||||
# HWiNFO 실물 보고서: 시리얼/MAC/사용자 정보가 포함되어 소스에 보관하지 않음
|
||||
KING-DESKTOP.XML
|
||||
|
||||
# Excel 가 파일을 열 때 만드는 잠금 파일
|
||||
~$*
|
||||
|
||||
@@ -152,6 +152,8 @@ def build_dashboard(store: Any, *, kind: str, anchor: date, today: date,
|
||||
"problems": problems,
|
||||
"manual_codes": manual_codes,
|
||||
"manual_cells": manual_cells,
|
||||
# 엑셀 업로드 대상 — 수동 입력이 켜진 쇼핑몰 전부(쇼핑몰 선택 필터와 무관, 설정 순서)
|
||||
"manual_upload_names": [m["name"] for m in markets if m.get("manual_input")],
|
||||
"last_update_at": store.last_update_at(),
|
||||
"running": store.running_codes(),
|
||||
"no_marketplaces": not all_codes,
|
||||
|
||||
@@ -355,6 +355,24 @@ class PerformanceDBStore:
|
||||
except pg_errors.UndefinedTable:
|
||||
raise ManualMigrationNeeded() from None
|
||||
|
||||
def set_manual_sales_bulk(self, entries: list[tuple[str, date, int]], *, user: str = "") -> int:
|
||||
"""엑셀 업로드 — (쇼핑몰, 날짜, 금액) 여러 개를 한 트랜잭션으로 저장(덮어씀). 하나라도 실패하면 모두 취소."""
|
||||
if not entries:
|
||||
return 0
|
||||
try:
|
||||
with self._pool.connection() as conn:
|
||||
with conn.transaction():
|
||||
with conn.cursor() as cur:
|
||||
cur.executemany(
|
||||
"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) for code, day, amount in entries],
|
||||
)
|
||||
except pg_errors.UndefinedTable:
|
||||
raise ManualMigrationNeeded() from None
|
||||
return len(entries)
|
||||
|
||||
def daily_breakdown(self, code: str, start: date, end: date, *, id_prefix: str = "") -> list[dict[str, Any]]:
|
||||
"""쇼핑몰 화면(일별 매출내역) 대조용 — 날짜별 결제(SALE 합·건수)·환불(그 밖, 양수)·마지막 수집 시각.
|
||||
id_prefix 가 있으면 이 어댑터가 다른 쇼핑몰 열로 보낸 사건까지 합친다(카페24 화면 합계와 같은 범위)."""
|
||||
|
||||
@@ -0,0 +1,203 @@
|
||||
"""수동 입력 매출 엑셀 업로드 — 1열 날짜, 2열부터 쇼핑몰 이름 머리글(샘플: upload_sample.xlsx).
|
||||
|
||||
규칙
|
||||
- 머리글(1행) 2열부터 = 쇼핑몰 이름. 설정의 이름·짧은 이름(네이버/토스)·코드 어느 것이든 되고 띄어쓰기·대소문자는 무시.
|
||||
- 수동 입력이 켜진 쇼핑몰 열만 반영. 꺼진 쇼핑몰·모르는 이름 열은 건너뛰고 알려 준다.
|
||||
- 값이 있는 칸만 반영(빈 칸은 그날 기존 값 그대로 — 지우지 않음). 0 은 값(0원)으로 저장.
|
||||
- 날짜: 엑셀 날짜, 2026-10-12 · 2026.10.12 · 2026/10/12 · 20261012(뒤 요일 표기 무시). 앞으로의 날짜는 안 됨.
|
||||
- 금액: 원 단위 정수(쉼표·"원" 허용, 소수는 반올림).
|
||||
- 잘못된 칸이 하나라도 있으면 아무것도 저장하지 않고 오류 목록을 돌려준다(일부만 들어가 헷갈리지 않게).
|
||||
|
||||
HTTP·DB 와 무관한 순수 함수 — 라우터가 파일 바이트와 쇼핑몰 목록을 넘긴다.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import re
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import date, datetime, timedelta
|
||||
from decimal import ROUND_HALF_UP, Decimal, InvalidOperation
|
||||
from typing import Any, Iterable, Mapping
|
||||
|
||||
MAX_FILE_BYTES = 5 * 1024 * 1024
|
||||
MAX_DATA_ROWS = 2000
|
||||
MAX_ERRORS = 30
|
||||
MAX_AMOUNT = 10 ** 12 # 라우터 MAX_MANUAL_AMOUNT 와 같은 상한(원)
|
||||
|
||||
_EXCEL_EPOCH = date(1899, 12, 30)
|
||||
_DATE_RE = re.compile(r"^(\d{4})\s*[-./년]\s*(\d{1,2})\s*[-./월]\s*(\d{1,2})")
|
||||
_COMPACT_RE = re.compile(r"^(\d{4})(\d{2})(\d{2})(?!\d)")
|
||||
|
||||
|
||||
class UploadError(ValueError):
|
||||
"""파일 자체를 읽을 수 없음(형식·크기·머리글)."""
|
||||
|
||||
|
||||
@dataclass
|
||||
class ParseResult:
|
||||
entries: list[tuple[str, date, int]] = field(default_factory=list) # (쇼핑몰 코드, 날짜, 금액)
|
||||
errors: list[str] = field(default_factory=list)
|
||||
ignored: list[str] = field(default_factory=list) # 건너뛴 열(머리글 + 이유)
|
||||
columns: list[str] = field(default_factory=list) # 반영 대상 쇼핑몰 코드(열 순서)
|
||||
|
||||
|
||||
def _norm(text: Any) -> str:
|
||||
return re.sub(r"\s+", "", str(text or "")).lower()
|
||||
|
||||
|
||||
def _cell_ref(row: int, col: int) -> str:
|
||||
letters = ""
|
||||
n = col
|
||||
while n:
|
||||
n, r = divmod(n - 1, 26)
|
||||
letters = chr(65 + r) + letters
|
||||
return f"{letters}{row}"
|
||||
|
||||
|
||||
def parse_date(value: Any) -> date | None:
|
||||
"""날짜 칸 → date. 읽을 수 없으면 ValueError, 빈 칸이면 None."""
|
||||
if value is None or (isinstance(value, str) and not value.strip()):
|
||||
return None
|
||||
if isinstance(value, datetime):
|
||||
return value.date()
|
||||
if isinstance(value, date):
|
||||
return value
|
||||
if isinstance(value, (int, float)) and not isinstance(value, bool):
|
||||
n = int(value)
|
||||
if 19000101 <= n <= 29991231: # 20261012
|
||||
return parse_date(str(n))
|
||||
if 20000 <= n <= 80000: # 엑셀 날짜 일련번호(서식 없는 날짜)
|
||||
return _EXCEL_EPOCH + timedelta(days=n)
|
||||
raise ValueError
|
||||
text = str(value).strip()
|
||||
m = _DATE_RE.match(text) or _COMPACT_RE.match(text)
|
||||
if not m:
|
||||
raise ValueError
|
||||
return date(int(m.group(1)), int(m.group(2)), int(m.group(3)))
|
||||
|
||||
|
||||
def parse_amount(value: Any) -> int | None:
|
||||
"""금액 칸 → 원 단위 정수. 빈 칸이면 None, 숫자가 아니면 ValueError."""
|
||||
if value is None or isinstance(value, bool):
|
||||
if value is None:
|
||||
return None
|
||||
raise ValueError
|
||||
if isinstance(value, (int, float, Decimal)):
|
||||
num = Decimal(str(value))
|
||||
else:
|
||||
text = re.sub(r"[,\s원₩]", "", str(value))
|
||||
if text == "":
|
||||
return None
|
||||
try:
|
||||
num = Decimal(text)
|
||||
except InvalidOperation:
|
||||
raise ValueError from None
|
||||
if not num.is_finite():
|
||||
raise ValueError
|
||||
return int(num.quantize(Decimal("1"), rounding=ROUND_HALF_UP))
|
||||
|
||||
|
||||
def header_aliases(markets: Iterable[Mapping[str, Any]], extra_names: Mapping[str, Iterable[str]] | None = None) -> dict[str, str]:
|
||||
"""머리글로 쓸 수 있는 이름 → 쇼핑몰 코드. markets: code·name, extra_names: 코드별 다른 이름(어댑터 이름·짧은 이름)."""
|
||||
out: dict[str, str] = {}
|
||||
for m in markets:
|
||||
code = str(m["code"])
|
||||
for alias in (code, m.get("name"), *((extra_names or {}).get(code) or ())):
|
||||
key = _norm(alias)
|
||||
if key:
|
||||
out.setdefault(key, code)
|
||||
return out
|
||||
|
||||
|
||||
def parse_workbook(content: bytes, *, markets: list[Mapping[str, Any]], today: date,
|
||||
extra_names: Mapping[str, Iterable[str]] | None = None) -> ParseResult:
|
||||
"""첫 시트를 읽어 (코드, 날짜, 금액) 목록을 만든다. markets: code·name·manual_input(설정 순서)."""
|
||||
if not content:
|
||||
raise UploadError("빈 파일입니다.")
|
||||
if len(content) > MAX_FILE_BYTES:
|
||||
raise UploadError("파일이 너무 큽니다(5MB 이하).")
|
||||
try:
|
||||
import openpyxl # noqa: WPS433
|
||||
|
||||
wb = openpyxl.load_workbook(io.BytesIO(content), read_only=True, data_only=True)
|
||||
except Exception: # noqa: BLE001 — 형식이 다르면 어떤 오류든 같은 안내
|
||||
raise UploadError("엑셀(.xlsx) 파일을 읽을 수 없습니다. 샘플 파일 양식으로 저장해 올려 주세요.") from None
|
||||
try:
|
||||
ws = wb.worksheets[0]
|
||||
rows = ws.iter_rows(values_only=True)
|
||||
header = next(rows, None)
|
||||
if not header or len(header) < 2:
|
||||
raise UploadError("1행에 날짜와 쇼핑몰 이름 머리글이 없습니다.")
|
||||
|
||||
aliases = header_aliases(markets, extra_names)
|
||||
by_code = {str(m["code"]): m for m in markets}
|
||||
res = ParseResult()
|
||||
col_code: dict[int, str] = {} # 열 번호(0부터) → 반영할 쇼핑몰 코드
|
||||
for idx, title in enumerate(header[1:], start=1):
|
||||
if title is None or not str(title).strip():
|
||||
continue
|
||||
label = str(title).strip()
|
||||
code = aliases.get(_norm(label))
|
||||
if code is None:
|
||||
res.ignored.append(f"{label}(알 수 없는 쇼핑몰)")
|
||||
elif not by_code[code].get("manual_input"):
|
||||
res.ignored.append(f"{label}(수동 입력 꺼짐)")
|
||||
elif code in col_code.values():
|
||||
res.errors.append(f"{_cell_ref(1, idx + 1)} {label}: 같은 쇼핑몰 열이 두 번 있습니다.")
|
||||
else:
|
||||
col_code[idx] = code
|
||||
res.columns.append(code)
|
||||
if not col_code and not res.errors:
|
||||
raise UploadError("반영할 쇼핑몰 열이 없습니다. 머리글을 수동 입력이 켜진 쇼핑몰 이름으로 적어 주세요."
|
||||
+ (f" (건너뛴 열: {', '.join(res.ignored)})" if res.ignored else ""))
|
||||
|
||||
seen: dict[tuple[str, date], str] = {}
|
||||
data_rows = 0
|
||||
for r, row in enumerate(rows, start=2):
|
||||
row = tuple(row or ())
|
||||
cells = {i: (row[i] if i < len(row) else None) for i in col_code}
|
||||
amounts: dict[int, int] = {}
|
||||
for i, raw in cells.items():
|
||||
try:
|
||||
amt = parse_amount(raw)
|
||||
except ValueError:
|
||||
res.errors.append(f"{_cell_ref(r, i + 1)}: 금액이 숫자가 아닙니다({raw}).")
|
||||
continue
|
||||
if amt is None:
|
||||
continue
|
||||
if abs(amt) > MAX_AMOUNT:
|
||||
res.errors.append(f"{_cell_ref(r, i + 1)}: 금액이 너무 큽니다.")
|
||||
continue
|
||||
amounts[i] = amt
|
||||
raw_day = row[0] if row else None
|
||||
try:
|
||||
day = parse_date(raw_day)
|
||||
except ValueError:
|
||||
res.errors.append(f"{_cell_ref(r, 1)}: 날짜를 읽을 수 없습니다({raw_day}).")
|
||||
continue
|
||||
if day is None:
|
||||
if amounts:
|
||||
res.errors.append(f"{r}행: 날짜가 비어 있습니다.")
|
||||
continue
|
||||
if not amounts:
|
||||
continue
|
||||
data_rows += 1
|
||||
if data_rows > MAX_DATA_ROWS:
|
||||
raise UploadError(f"한 번에 {MAX_DATA_ROWS:,}일까지 올릴 수 있습니다.")
|
||||
if day > today:
|
||||
res.errors.append(f"{_cell_ref(r, 1)}: 앞으로의 날짜({day.isoformat()})는 입력할 수 없습니다.")
|
||||
continue
|
||||
for i, amt in amounts.items():
|
||||
code = col_code[i]
|
||||
where = _cell_ref(r, i + 1)
|
||||
if (code, day) in seen:
|
||||
res.errors.append(f"{where}: {by_code[code]['name']} {day.isoformat()} 이 {seen[(code, day)]} 와 겹칩니다.")
|
||||
continue
|
||||
seen[(code, day)] = where
|
||||
res.entries.append((code, day, amt))
|
||||
if len(res.errors) > MAX_ERRORS:
|
||||
break
|
||||
return res
|
||||
finally:
|
||||
wb.close()
|
||||
@@ -11,6 +11,8 @@ JSON API — 모듈 권한
|
||||
POST /performance/api/sync/jobs/{id}/cancel 업데이트 취소(시작한 사람 또는 관리자)
|
||||
GET /performance/api/events 금액 클릭 상세(쇼핑몰+기간)
|
||||
PUT /performance/api/manual-sales/{code}/{day} 수동 입력 매출 저장/지움(그 쇼핑몰 수동 입력이 켜져 있을 때, 오늘까지)
|
||||
GET /performance/api/manual-sales/sample.xlsx 수동 입력 엑셀 업로드 샘플(모듈 폴더 upload_sample.xlsx)
|
||||
POST /performance/api/manual-sales/upload 수동 입력 엑셀 업로드(1열 날짜, 2열부터 쇼핑몰 이름 머리글)
|
||||
JSON API — 관리자
|
||||
PUT /performance/api/marketplaces/{code} 사용/매출 집계/수동 입력 여부
|
||||
POST /performance/api/marketplaces/{code}/rates 수수료율(적용 시작일)
|
||||
@@ -29,10 +31,11 @@ from __future__ import annotations
|
||||
|
||||
from datetime import date
|
||||
from decimal import Decimal, InvalidOperation
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter, Body, HTTPException, Query, Request
|
||||
from fastapi.responses import HTMLResponse, JSONResponse
|
||||
from fastapi import APIRouter, Body, File, HTTPException, Query, Request, UploadFile
|
||||
from fastapi.responses import FileResponse, HTMLResponse, JSONResponse
|
||||
|
||||
from app.timezone import today_kst
|
||||
|
||||
@@ -46,6 +49,7 @@ MAX_CHECK_DAYS = 62 # 쇼핑몰 화면 일별 비교(카페24 일별 매출내
|
||||
MAX_BACKFILL_DAYS = 366
|
||||
MAX_USER_SYNC_DAYS = 92 # 관리자가 아니어도 가져올 수 있는 기간(이번달·직접선택 짧은 기간)
|
||||
MAX_MANUAL_AMOUNT = 10 ** 12 # 수동 입력 한 칸 상한(원)
|
||||
MANUAL_SAMPLE_PATH = Path(__file__).resolve().parent / "upload_sample.xlsx"
|
||||
MANUAL_MIGRATION_HELP = ("수동 입력을 쓰려면 performance_db 마이그레이션 002(scripts/sql/performance_db_002_manual_sales.sql)를 "
|
||||
"먼저 적용해야 합니다.")
|
||||
|
||||
@@ -307,6 +311,53 @@ def api_manual_sale(request: Request, code: str, day: str, payload: dict[str, An
|
||||
"amount": api_amount if amount is None else amount, "api_amount": api_amount})
|
||||
|
||||
|
||||
@router.get("/api/manual-sales/sample.xlsx")
|
||||
def api_manual_sample(request: Request) -> Any:
|
||||
common.require_store(request)
|
||||
if not MANUAL_SAMPLE_PATH.is_file():
|
||||
raise HTTPException(status_code=404, detail="샘플 파일이 없습니다.")
|
||||
return FileResponse(MANUAL_SAMPLE_PATH, filename="upload_sample.xlsx",
|
||||
media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
|
||||
|
||||
|
||||
@router.post("/api/manual-sales/upload")
|
||||
def api_manual_upload(request: Request, file: UploadFile = File(...)) -> JSONResponse:
|
||||
"""수동 입력 엑셀 업로드 — 값이 있는 칸만 반영(덮어씀). 잘못된 칸이 있으면 아무것도 저장하지 않는다."""
|
||||
from . import manual_upload # noqa: WPS433
|
||||
from .dashboard import _short_name # noqa: WPS433
|
||||
from .db import ManualMigrationNeeded # noqa: WPS433
|
||||
|
||||
store, user = common.require_store(request) # 날짜 칸 수동 입력과 같은 권한(모듈 권한자 누구나)
|
||||
content = file.file.read(manual_upload.MAX_FILE_BYTES + 1)
|
||||
known = {a.code: a for a in all_adapters()}
|
||||
markets = [m for m in store.list_marketplaces() if m["code"] in known and m["enabled"]]
|
||||
extra = {m["code"]: (known[m["code"]].name, _short_name(m["name"])) for m in markets}
|
||||
try:
|
||||
res = manual_upload.parse_workbook(content, markets=markets, today=today_kst(), extra_names=extra)
|
||||
except manual_upload.UploadError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from None
|
||||
names = {m["code"]: m["name"] for m in markets}
|
||||
if res.errors:
|
||||
return JSONResponse(status_code=400, content={
|
||||
"detail": f"잘못된 칸이 {len(res.errors)}개{'+' if len(res.errors) > manual_upload.MAX_ERRORS else ''} 있어 "
|
||||
"아무것도 저장하지 않았습니다. 고친 뒤 다시 올려 주세요.",
|
||||
"errors": res.errors[:manual_upload.MAX_ERRORS], "ignored": res.ignored})
|
||||
try:
|
||||
saved = store.set_manual_sales_bulk(res.entries, user=user.get("email", ""))
|
||||
except ManualMigrationNeeded:
|
||||
raise HTTPException(status_code=503, detail=MANUAL_MIGRATION_HELP) from None
|
||||
counts: dict[str, int] = {}
|
||||
for code, _, _ in res.entries:
|
||||
counts[code] = counts.get(code, 0) + 1
|
||||
days = sorted({d for _, d, _ in res.entries})
|
||||
return JSONResponse({
|
||||
"ok": True, "saved": saved,
|
||||
"by_shop": [{"code": c, "name": names.get(c, c), "count": counts[c]} for c in res.columns if counts.get(c)],
|
||||
"from": days[0].isoformat() if days else None, "to": days[-1].isoformat() if days else None,
|
||||
"ignored": res.ignored,
|
||||
})
|
||||
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# JSON API — 설정(수수료율은 모듈 권한자 누구나, 나머지는 관리자)
|
||||
# ════════════════════════════════════════════════════════════
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261012c" />{% endblock %}
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261013a" />{% endblock %}
|
||||
|
||||
{%- macro won(v) -%}
|
||||
{%- if v is none -%}<span class="perf-na"></span>
|
||||
@@ -107,6 +107,10 @@
|
||||
<div class="erp-card perf-card">
|
||||
<div class="perf-card-head">
|
||||
<h2 class="perf-h">{% if period_kind == 'year' %}월별 × 쇼핑몰{% else %}일자별 × 쇼핑몰{% endif %}</h2>
|
||||
{% if manual_upload_names %}
|
||||
<button type="button" class="erp-btn erp-btn-outline erp-btn-sm perf-manual-upload-btn" id="perf-manual-upload"
|
||||
title="수동 입력 쇼핑몰 매출을 엑셀 파일로 한 번에 입력">엑셀 업로드</button>
|
||||
{% endif %}
|
||||
<div class="perf-metric" role="group" aria-label="표시 기준">
|
||||
<button type="button" class="perf-seg" data-metric="gross">총매출</button>
|
||||
<button type="button" class="perf-seg" data-metric="commission">수수료</button>
|
||||
@@ -246,8 +250,9 @@
|
||||
"period_kind": period_kind,
|
||||
"period_start": period.start.isoformat(),
|
||||
"period_end": period.end.isoformat(),
|
||||
"today": today
|
||||
"today": today,
|
||||
"manual_upload_names": manual_upload_names
|
||||
} | tojson }}</script>
|
||||
{% endblock %}
|
||||
|
||||
{% block scripts %}<script src="/static/performance.js?v=20261012b" defer></script>{% endblock %}
|
||||
{% block scripts %}<script src="/static/performance.js?v=20261013a" defer></script>{% endblock %}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261012c" />{% endblock %}
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261013a" />{% endblock %}
|
||||
|
||||
{%- macro when(v) -%}{{ (v or '')[:16] | replace('T', ' ') or '—' }}{%- endmacro -%}
|
||||
|
||||
@@ -204,4 +204,4 @@
|
||||
</section>
|
||||
{% endblock %}
|
||||
|
||||
{% block scripts %}<script src="/static/performance.js?v=20261012b" defer></script>{% endblock %}
|
||||
{% block scripts %}<script src="/static/performance.js?v=20261013a" defer></script>{% endblock %}
|
||||
|
||||
@@ -0,0 +1,143 @@
|
||||
"""수동 입력 엑셀 업로드 — 머리글 매칭·값 있는 칸만·오류 시 전부 거절."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
from datetime import date, datetime
|
||||
from pathlib import Path
|
||||
|
||||
import openpyxl
|
||||
import pytest
|
||||
|
||||
from app.modules.performance import manual_upload as mu
|
||||
|
||||
TODAY = date(2026, 10, 13)
|
||||
MARKETS = [
|
||||
{"code": "naver", "name": "네이버", "manual_input": False},
|
||||
{"code": "coupang_rocket", "name": "쿠팡(로켓)", "manual_input": True},
|
||||
{"code": "ohouse", "name": "오늘의집", "manual_input": True},
|
||||
{"code": "toss", "name": "토스쇼핑", "manual_input": True},
|
||||
{"code": "atomy", "name": "애터미아자몰", "manual_input": True},
|
||||
]
|
||||
EXTRA = {"toss": ("토스쇼핑", "토스")}
|
||||
|
||||
|
||||
def _xlsx(rows):
|
||||
wb = openpyxl.Workbook()
|
||||
ws = wb.active
|
||||
for r in rows:
|
||||
ws.append(list(r))
|
||||
buf = io.BytesIO()
|
||||
wb.save(buf)
|
||||
return buf.getvalue()
|
||||
|
||||
|
||||
def _parse(rows):
|
||||
return mu.parse_workbook(_xlsx(rows), markets=MARKETS, today=TODAY, extra_names=EXTRA)
|
||||
|
||||
|
||||
def test_only_filled_cells_of_manual_shops():
|
||||
res = _parse([
|
||||
("날짜", "쿠팡(로켓)", " 오늘의 집 ", "네이버", "모르는몰", "토스", "애터미아자몰"),
|
||||
(datetime(2026, 10, 12), 1_000, None, 999, 5, "12,300원", ""),
|
||||
("2026.10.13(화)", None, 0, None, None, None, 4500.4),
|
||||
(None, None, None, None, None, None, None), # 빈 줄
|
||||
])
|
||||
assert not res.errors
|
||||
assert res.columns == ["coupang_rocket", "ohouse", "toss", "atomy"]
|
||||
assert sorted(res.entries) == sorted([
|
||||
("coupang_rocket", date(2026, 10, 12), 1000), ("toss", date(2026, 10, 12), 12300),
|
||||
("ohouse", date(2026, 10, 13), 0), ("atomy", date(2026, 10, 13), 4500)])
|
||||
assert res.ignored == ["네이버(수동 입력 꺼짐)", "모르는몰(알 수 없는 쇼핑몰)"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("raw, expect", [
|
||||
("2026-10-01", date(2026, 10, 1)), ("2026/10/1", date(2026, 10, 1)), ("20261001", date(2026, 10, 1)),
|
||||
(20261001, date(2026, 10, 1)), (46296, date(2026, 10, 1)), ("2026년 10월 1일", date(2026, 10, 1)), (None, None),
|
||||
])
|
||||
def test_parse_date(raw, expect):
|
||||
assert mu.parse_date(raw) == expect
|
||||
|
||||
|
||||
def test_errors_reject_everything_with_cell_refs():
|
||||
res = _parse([
|
||||
("날짜", "쿠팡(로켓)", "오늘의집"),
|
||||
("2026-10-10", "abc", 100),
|
||||
("엉터리", 1, None),
|
||||
("2026-10-14", 1, None), # 앞으로의 날짜
|
||||
(None, 5, None), # 날짜 없음
|
||||
("2026-10-11", 7, None),
|
||||
("2026-10-11", 8, None), # 같은 날 두 번
|
||||
])
|
||||
joined = "\n".join(res.errors)
|
||||
assert "B2" in joined and "A3" in joined and "A4" in joined and "5행" in joined and "B7" in joined
|
||||
assert len(res.errors) == 5
|
||||
|
||||
|
||||
def test_header_problems():
|
||||
with pytest.raises(mu.UploadError):
|
||||
_parse([("날짜", "네이버", "모르는몰"), ("2026-10-10", 1, 2)]) # 반영할 열 없음
|
||||
with pytest.raises(mu.UploadError):
|
||||
mu.parse_workbook(b"not an xlsx", markets=MARKETS, today=TODAY)
|
||||
res = _parse([("날짜", "쿠팡(로켓)", "coupang_rocket"), ("2026-10-10", 1, 2)])
|
||||
assert any("두 번" in e for e in res.errors)
|
||||
|
||||
|
||||
def test_sample_file_headers_match_marketplaces():
|
||||
"""모듈 폴더 샘플 파일 머리글 = 수동 입력 쇼핑몰 이름(시드 기준) — 업로드하면 전부 반영 대상이어야 한다."""
|
||||
sample = Path(mu.__file__).resolve().parent / "upload_sample.xlsx"
|
||||
seed = [{"code": c, "name": n, "manual_input": True} for c, n in (
|
||||
("coupang_rocket", "쿠팡(로켓)"), ("ohouse", "오늘의집"), ("gmarket", "G마켓"), ("kakao", "카카오"),
|
||||
("gsshop", "GS샵"), ("lotteon", "롯데ON"), ("atomy", "애터미아자몰"))]
|
||||
wb = openpyxl.load_workbook(sample)
|
||||
ws = wb.active
|
||||
ws.append([date(2026, 10, 1)] + [1] * 7)
|
||||
buf = io.BytesIO()
|
||||
wb.save(buf)
|
||||
res = mu.parse_workbook(buf.getvalue(), markets=seed, today=TODAY)
|
||||
assert not res.errors and not res.ignored and len(res.entries) == 7
|
||||
|
||||
|
||||
def test_upload_endpoint_saves_or_rejects(monkeypatch):
|
||||
"""라우터: 정상 파일은 한 번에 저장, 잘못된 칸이 있으면 400 + 칸 목록, 아무것도 저장 안 함. 샘플 받기."""
|
||||
from fastapi import FastAPI
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
import importlib
|
||||
|
||||
from app.modules.performance import common
|
||||
|
||||
perf_router = importlib.import_module("app.modules.performance.router") # 패키지 속성 router 는 APIRouter
|
||||
|
||||
class Store:
|
||||
saved: list = []
|
||||
|
||||
def list_marketplaces(self):
|
||||
return [{**m, "enabled": True} for m in MARKETS]
|
||||
|
||||
def set_manual_sales_bulk(self, entries, *, user=""):
|
||||
self.saved.extend(entries)
|
||||
return len(entries)
|
||||
|
||||
store = Store()
|
||||
monkeypatch.setattr(common, "require_store", lambda request, admin=False: (store, {"email": "king@x"}))
|
||||
monkeypatch.setattr(perf_router, "today_kst", lambda: TODAY)
|
||||
app = FastAPI()
|
||||
app.include_router(perf_router.router)
|
||||
client = TestClient(app)
|
||||
|
||||
ok = _xlsx([("날짜", "쿠팡(로켓)", "토스"), ("2026-10-12", 1000, None), ("2026-10-13", None, 2000)])
|
||||
r = client.post("/performance/api/manual-sales/upload", files={"file": ("a.xlsx", ok)})
|
||||
assert r.status_code == 200, r.text
|
||||
body = r.json()
|
||||
assert body["saved"] == 2 and body["from"] == "2026-10-12" and body["to"] == "2026-10-13"
|
||||
assert [s["code"] for s in body["by_shop"]] == ["coupang_rocket", "toss"]
|
||||
assert sorted(store.saved) == [("coupang_rocket", date(2026, 10, 12), 1000), ("toss", date(2026, 10, 13), 2000)]
|
||||
|
||||
store.saved.clear()
|
||||
bad = _xlsx([("날짜", "쿠팡(로켓)"), ("2026-10-12", 1000), ("2026-10-13", "x")])
|
||||
r = client.post("/performance/api/manual-sales/upload", files={"file": ("b.xlsx", bad)})
|
||||
assert r.status_code == 400 and r.json()["errors"] and store.saved == []
|
||||
|
||||
r = client.get("/performance/api/manual-sales/sample.xlsx")
|
||||
assert r.status_code == 200 and r.content[:2] == b"PK"
|
||||
Binary file not shown.
@@ -75,6 +75,12 @@ a.perf-seg.is-active, a.perf-seg.is-active:link, a.perf-seg.is-active:visited {
|
||||
.perf-notice[hidden] { display: none; }
|
||||
.perf-notice.is-warn { background: #fff7f5; border-color: #f3d2ca; }
|
||||
.perf-notice.is-ok { background: #f3fbf5; border-color: #cdeccf; }
|
||||
/* 수동 입력 엑셀 업로드 — 버튼은 표시 기준 버튼 바로 왼쪽, 창 안 파일 칸·오류 목록 */
|
||||
.perf-manual-upload-btn { margin-left: auto; }
|
||||
.perf-upload-file { width: 100%; box-sizing: border-box; }
|
||||
.perf-upload-result { margin-top: 10px; }
|
||||
.perf-upload-result .perf-notice { margin: 0; display: block; line-height: 1.6; }
|
||||
.perf-upload-errors { margin: 6px 0 0; padding-left: 18px; max-height: 220px; overflow-y: auto; font-size: 12px; line-height: 1.6; color: #b42318; }
|
||||
.perf-problem { padding: 1px 8px; border-radius: 999px; background: #fbe9e6; color: var(--perf-down); font-weight: 500; }
|
||||
|
||||
/* KPI */
|
||||
|
||||
@@ -253,6 +253,64 @@
|
||||
b.addEventListener("click", function () { setMetric(b.dataset.metric); });
|
||||
});
|
||||
|
||||
// 수동 입력 엑셀 업로드 — 1열 날짜, 2열부터 쇼핑몰 이름 머리글. 값이 있는 칸만 반영(빈 칸은 기존 값 그대로).
|
||||
// 잘못된 칸이 있으면 서버가 아무것도 저장하지 않고 칸 위치 목록을 돌려준다.
|
||||
const uploadBtn = document.getElementById("perf-manual-upload");
|
||||
if (uploadBtn) uploadBtn.addEventListener("click", function () {
|
||||
let saved = false;
|
||||
const m = openModal("수동 입력 엑셀 업로드", { narrow: true, onClose: function () { if (saved) location.reload(); } });
|
||||
const shops = (data.manual_upload_names || []).map(esc).join(", ");
|
||||
m.body.innerHTML =
|
||||
'<p class="perf-muted" style="margin:0 0 8px">1열에 <b>날짜</b>, 2열부터 <b>쇼핑몰 이름</b>을 머리글로 적고 그날 <b>총매출</b>을 넣습니다. ' +
|
||||
"값이 있는 칸만 반영되고(같은 날 값은 덮어씀) 빈 칸은 기존 값 그대로입니다.</p>" +
|
||||
'<p class="perf-muted" style="margin:0 0 10px">입력 가능한 쇼핑몰: ' + (shops || "없음") + "</p>" +
|
||||
'<p style="margin:0 0 12px"><a class="erp-btn erp-btn-outline erp-btn-sm" href="/performance/api/manual-sales/sample.xlsx" download>' +
|
||||
"샘플 파일 받기</a></p>" +
|
||||
'<input type="file" class="erp-input perf-upload-file" accept=".xlsx,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" aria-label="엑셀 파일" />' +
|
||||
'<div class="perf-upload-result"></div>';
|
||||
const fileInput = m.body.querySelector(".perf-upload-file");
|
||||
const out = m.body.querySelector(".perf-upload-result");
|
||||
const go = el("button", { type: "button", class: "erp-btn erp-btn-primary" }, "업로드");
|
||||
const cancel = el("button", { type: "button", class: "erp-btn erp-btn-ghost" }, "닫기");
|
||||
m.foot.appendChild(cancel);
|
||||
m.foot.appendChild(go);
|
||||
cancel.addEventListener("click", m.close);
|
||||
go.addEventListener("click", async function () {
|
||||
const f = fileInput.files && fileInput.files[0];
|
||||
if (!f) { out.innerHTML = '<p class="perf-notice is-warn">엑셀 파일을 고르세요.</p>'; return; }
|
||||
go.disabled = true;
|
||||
out.innerHTML = '<p class="perf-muted">올리는 중…</p>';
|
||||
const fd = new FormData();
|
||||
fd.append("file", f);
|
||||
let res, body = null;
|
||||
try {
|
||||
res = await fetch("/performance/api/manual-sales/upload", { method: "POST", credentials: "same-origin", body: fd });
|
||||
try { body = await res.json(); } catch (_) { body = null; }
|
||||
} catch (err) {
|
||||
out.innerHTML = '<p class="perf-notice is-warn">업로드 실패: ' + esc(err.message) + "</p>";
|
||||
go.disabled = false;
|
||||
return;
|
||||
}
|
||||
go.disabled = false;
|
||||
const ignored = body && body.ignored && body.ignored.length
|
||||
? '<p class="perf-muted" style="margin:6px 0 0">건너뛴 열: ' + esc(body.ignored.join(", ")) + "</p>" : "";
|
||||
if (!res.ok) {
|
||||
const detail = body && typeof body.detail === "string" ? body.detail : "업로드 실패 (" + res.status + ")";
|
||||
const errs = body && body.errors && body.errors.length
|
||||
? '<ul class="perf-upload-errors">' + body.errors.map(function (e) { return "<li>" + esc(e) + "</li>"; }).join("") + "</ul>" : "";
|
||||
out.innerHTML = '<p class="perf-notice is-warn">' + esc(detail) + "</p>" + errs + ignored;
|
||||
return;
|
||||
}
|
||||
saved = body.saved > 0;
|
||||
out.innerHTML = '<p class="perf-notice is-ok">' + (saved
|
||||
? fmt(body.saved) + "칸 반영 (" + esc(body.from === body.to ? body.from : body.from + " ~ " + body.to) + ")<br>" +
|
||||
esc(body.by_shop.map(function (s) { return s.name + " " + fmt(s.count) + "일"; }).join(" · "))
|
||||
: "반영할 값이 없습니다(값이 있는 칸이 없음).") + "</p>" + ignored +
|
||||
(saved ? '<p class="perf-muted" style="margin:6px 0 0">창을 닫으면 표·합계·그래프가 다시 계산됩니다.</p>' : "");
|
||||
fileInput.value = "";
|
||||
});
|
||||
});
|
||||
|
||||
// 직접선택 / 쇼핑몰 필터
|
||||
const customBtn = document.getElementById("perf-custom-btn");
|
||||
const customForm = document.getElementById("perf-custom");
|
||||
|
||||
@@ -215,6 +215,12 @@
|
||||
- **수동 입력 전용 쇼핑몰**(003, `adapters/manual.py` — `manual_only = True`): `쿠팡(로켓)`(`coupang_rocket`)·`애터미아자몰`(`atomy`).
|
||||
API 가 없어 매출 업데이트(`sync_all`)에서 빠지고, 설정 화면에 인증 설정·연결 테스트 버튼이 없으며 연결 상태는 "수동 입력".
|
||||
수동 입력 토글은 늘 켜짐(화면 disabled, API 로 끄면 400). 매출은 일자별 표 날짜 칸에 직접 입력.
|
||||
- **수동 입력 엑셀 업로드**(`manual_upload.py`, 일자별 표 머리 [엑셀 업로드] → 팝업): 샘플 `GET /api/manual-sales/sample.xlsx`
|
||||
(모듈 폴더 `upload_sample.xlsx`), 업로드 `POST /api/manual-sales/upload`(모듈 권한자 누구나 — 날짜 칸 입력과 같은 권한).
|
||||
양식: 첫 시트 1행 머리글, 1열 날짜(엑셀 날짜·2026-10-12·2026.10.12·20261012), 2열부터 쇼핑몰 이름(설정 이름·짧은 이름·코드,
|
||||
띄어쓰기·대소문자 무시). 수동 입력이 켜진 쇼핑몰 열만, **값이 있는 칸만** 반영(같은 날 값 덮어씀, 빈 칸은 기존 값 그대로, 0 은 0원).
|
||||
꺼진 쇼핑몰·모르는 이름 열은 건너뛰고 알려 줌. 숫자 아님·날짜 못 읽음·앞으로의 날짜·같은 쇼핑몰+날짜 두 번이면
|
||||
**아무것도 저장하지 않고** 칸 위치(B3 등) 목록을 돌려준다. 저장은 한 트랜잭션(`set_manual_sales_bulk`). 5MB·2,000일 상한.
|
||||
- 표 열 제목은 가운데·굵게·검정(`.perf-table thead th`).
|
||||
|
||||
### 연동 단계 체크리스트(쇼핑몰마다)
|
||||
|
||||
Reference in New Issue
Block a user