Files
dbx-main/app/modules/performance/manual_upload.py
T
king 1d3573a44a feat(performance): upload manual-input sales from an Excel file
- [엑셀 업로드] button on the daily x marketplace table opens a popup with
  a sample download (module upload_sample.xlsx) and a file picker
- Format: column 1 = date, columns 2+ = marketplace names as headers
  (setting name / short name / code, spaces and case ignored)
- Only filled cells of marketplaces with manual input ON are saved
  (overwrite same day, blank cells keep existing values); other columns
  are skipped and reported
- Any bad cell (not a number, unreadable/future date, duplicate day) rejects
  the whole file with cell references; saving is one transaction
- Ignore Excel lock files (~$*)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 04:58:00 +09:00

204 lines
8.9 KiB
Python

"""수동 입력 매출 엑셀 업로드 — 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()