Files
dbx-main/app/modules/performance/calc.py
T
king aa669553db feat(performance): 실적(쇼핑몰 통합 매출) 모듈 1단계 — 대시보드·설정·보안·어댑터 구조
- 네 영역 분리: ① 수집(adapters/ 쇼핑몰 10곳 + sync.py) ② 보안(security/ + credentials.py)
  ③ 계산·저장(calc.py + db.py) ④ 화면(dashboard.py, router.py, templates, performance.css/js)
- 대시보드: 기간(오늘/이번주/이번달/올해/직접선택, 이전·다음), 쇼핑몰 필터, KPI 5개(진행 중 기간은
  직전 기간 같은 경과일 대비), 일자×쇼핑몰 표(주간합계, 총매출/수수료/차감매출 전환), 일별 추이·
  쇼핑몰 비중(SVG), 월 누적(비중)·연간 누적, 금액 클릭 → 주문 상세
- 설정(관리자): 사용/매출 집계, 수수료율 이력(적용 시작일), 쇼핑몰별 API 인증정보 입력·연결 테스트·
  연결 상태, 마스터 키 상태·재암호화, 테스트(모의) 데이터 생성/삭제
- 인증정보: 설정 화면 입력 → AES-256-GCM(키 버전, AAD=쇼핑몰+항목) 암호화 저장, secret 원문은
  화면으로 다시 보내지 않음, 오류·로그·raw 는 비밀값 가린 뒤 저장. 마스터 키는 APP_ENCRYPTION_KEY(.env)
- 매출 기준일: 결제=결제일, 취소·반품=발생일. 금액 원 단위 정수, 수수료 반올림은 calc.commission 한 곳
- 동기화: 같은 쇼핑몰 동시 실행 차단(running 부분 유니크), 쇼핑몰별 실패 격리, 중복 방지 UNIQUE+UPSERT
- 카페24 어댑터는 기존 app/integrations/cafe24 OAuth 토큰 재사용, 나머지는 입력칸만(수집은 다음 단계)
- performance_db 초기화 스크립트, 권한키 performance(설정은 is_admin), 문서·.env.example

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 16:07:46 +09:00

306 lines
12 KiB
Python

"""③ 매출 계산 — 기간/주 계산, 수수료·반올림, 표·KPI 집계. DB·HTTP 와 무관한 순수 함수.
금액 규칙
- 모든 금액은 원 단위 정수(int). 부동소수점을 쓰지 않는다(수수료율만 Decimal).
- 수수료 = round_half_up(해당 일 쇼핑몰 매출 합계 × 그날 유효한 수수료율 / 100).
반올림은 `commission()` 한 곳에서만 한다. 취소/반품(음수)도 같은 규칙(0 에서 먼 쪽).
- 수수료 차감 매출 = 총매출 − 수수료.
- 수수료율은 이력(적용 시작일)으로 관리한다. 어떤 날의 요율 = 그날 이전(포함) 가장 최근
적용 시작일의 요율. 첫 요율보다 이전 날짜는 0%.
주 = 월요일 ~ 일요일.
"""
from __future__ import annotations
import calendar
from dataclasses import dataclass
from datetime import date, timedelta
from decimal import ROUND_HALF_UP, Decimal
from typing import Iterable, Mapping, Sequence
WEEKDAYS_KO = ("월", "화", "수", "목", "금", "토", "일")
PERIOD_KINDS = ("day", "week", "month", "year", "custom")
MAX_CUSTOM_DAYS = 366
# ════════════════════════════════════════════════════════════
# 금액
# ════════════════════════════════════════════════════════════
def commission(amount: int, rate_percent: Decimal) -> int:
"""수수료(원). 반올림 기준은 이 함수 한 곳 — ROUND_HALF_UP(0.5 는 0 에서 먼 쪽)."""
if not amount or not rate_percent:
return 0
value = Decimal(int(amount)) * Decimal(rate_percent) / Decimal(100)
return int(value.quantize(Decimal(1), rounding=ROUND_HALF_UP))
@dataclass
class Money:
gross: int = 0
commission: int = 0
@property
def net(self) -> int:
return self.gross - self.commission
def add(self, other: "Money") -> "Money":
self.gross += other.gross
self.commission += other.commission
return self
def as_dict(self) -> dict[str, int]:
return {"gross": self.gross, "commission": self.commission, "net": self.net}
def total(items: Iterable[Money]) -> Money:
out = Money()
for m in items:
out.add(m)
return out
RateTable = Mapping[str, Sequence[tuple[date, Decimal]]] # 쇼핑몰 → [(적용 시작일, 요율%)] 오름차순
def rate_on(rates: RateTable, code: str, d: date) -> Decimal:
current = Decimal(0)
for eff, rate in rates.get(code, ()):
if eff <= d:
current = Decimal(rate)
else:
break
return current
def build_cells(daily_amounts: Mapping[tuple[date, str], int], rates: RateTable) -> dict[tuple[date, str], Money]:
"""(날짜, 쇼핑몰) → 그날 매출 합계로 Money 를 만든다(수수료는 그날 요율)."""
return {
(d, code): Money(gross=int(amt), commission=commission(int(amt), rate_on(rates, code, d)))
for (d, code), amt in daily_amounts.items()
}
def pct_change(current: int, previous: int) -> float | None:
"""증감률(%). 비교 대상이 0 이하이면 의미 없는 값 대신 None."""
if previous <= 0:
return None
return round((current - previous) / previous * 100, 1)
# ════════════════════════════════════════════════════════════
# 기간
# ════════════════════════════════════════════════════════════
def week_start(d: date) -> date:
return d - timedelta(days=d.weekday())
def month_end(d: date) -> date:
return d.replace(day=calendar.monthrange(d.year, d.month)[1])
def _add_months(d: date, n: int) -> date:
y, m = divmod(d.month - 1 + n, 12)
year, month = d.year + y, m + 1
return date(year, month, min(d.day, calendar.monthrange(year, month)[1]))
def fmt_md(d: date) -> str:
return f"{d.month}/{d.day}"
def day_label(d: date) -> str:
return f"{WEEKDAYS_KO[d.weekday()]} {fmt_md(d)}"
@dataclass
class Period:
kind: str
anchor: date
start: date
end: date
label: str
prev_anchor: date
next_anchor: date
prev_label: str
next_label: str
@property
def days(self) -> int:
return (self.end - self.start).days + 1
def compare_range(self, today: date) -> tuple[date, date, str]:
"""직전 같은 길이 기간. 진행 중인 기간이면 같은 경과일수까지만(공정한 비교)."""
length = self.days
prev_start = self.start - timedelta(days=length)
if self.kind == "month":
prev_start = _add_months(self.start, -1)
elif self.kind == "year":
prev_start = self.start.replace(year=self.start.year - 1)
in_progress = self.start <= today < self.end
if in_progress:
elapsed = (today - self.start).days
prev_end = prev_start + timedelta(days=elapsed)
if self.kind == "month":
prev_end = min(prev_end, month_end(prev_start))
note = "같은 기간"
else:
if self.kind == "month":
prev_end = month_end(prev_start)
elif self.kind == "year":
prev_end = prev_start.replace(month=12, day=31)
else:
prev_end = self.start - timedelta(days=1)
note = ""
unit = {"day": "전일", "week": "전주", "month": "전월", "year": "전년"}.get(self.kind, "직전 기간")
return prev_start, prev_end, f"{unit} {note}".strip()
def resolve_period(
kind: str,
anchor: date,
*,
custom_from: date | None = None,
custom_to: date | None = None,
) -> Period:
kind = kind if kind in PERIOD_KINDS else "week"
if kind == "day":
return Period(kind, anchor, anchor, anchor,
f"{anchor.year}년 {anchor.month}월 {anchor.day}일 ({WEEKDAYS_KO[anchor.weekday()]})",
anchor - timedelta(days=1), anchor + timedelta(days=1), "전일", "다음날")
if kind == "week":
s = week_start(anchor)
e = s + timedelta(days=6)
label = (f"{s.year}년 {s.month}월 {s.day}일 ~ "
+ (f"{e.year}년 " if e.year != s.year else "") + f"{e.month}월 {e.day}일")
return Period(kind, anchor, s, e, label, s - timedelta(days=7), s + timedelta(days=7), "이전주", "다음주")
if kind == "month":
s = anchor.replace(day=1)
return Period(kind, anchor, s, month_end(s), f"{s.year}년 {s.month}월",
_add_months(s, -1), _add_months(s, 1), "이전달", "다음달")
if kind == "year":
s = date(anchor.year, 1, 1)
return Period(kind, anchor, s, date(anchor.year, 12, 31), f"{anchor.year}년",
date(anchor.year - 1, 1, 1), date(anchor.year + 1, 1, 1), "이전해", "다음해")
# custom
s = custom_from or anchor
e = custom_to or s
if e < s:
s, e = e, s
if (e - s).days + 1 > MAX_CUSTOM_DAYS:
e = s + timedelta(days=MAX_CUSTOM_DAYS - 1)
length = (e - s).days + 1
return Period("custom", s, s, e, f"{s.isoformat()} ~ {e.isoformat()}",
s - timedelta(days=length), e + timedelta(days=1), "이전", "다음")
def daterange(start: date, end: date) -> Iterable[date]:
d = start
while d <= end:
yield d
d += timedelta(days=1)
# ════════════════════════════════════════════════════════════
# 집계
# ════════════════════════════════════════════════════════════
def sum_range(cells: Mapping[tuple[date, str], Money], codes: Sequence[str], start: date, end: date) -> Money:
wanted = set(codes)
out = Money()
for (d, code), m in cells.items():
if code in wanted and start <= d <= end:
out.add(m)
return out
def by_code(cells: Mapping[tuple[date, str], Money], codes: Sequence[str], start: date, end: date) -> dict[str, Money]:
out = {c: Money() for c in codes}
for (d, code), m in cells.items():
if code in out and start <= d <= end:
out[code].add(m)
return out
def _row(kind: str, label: str, per_code: dict[str, Money], **extra) -> dict:
return {
"kind": kind,
"label": label,
"cells": {c: m.as_dict() for c, m in per_code.items()},
"total": total(per_code.values()).as_dict(),
**extra,
}
def main_table(period: Period, codes: Sequence[str], cells: Mapping[tuple[date, str], Money],
*, today: date, holidays: Mapping[str, str] | None = None) -> list[dict]:
"""일자 × 쇼핑몰 표. 일 행 + 주간합계(일요일 뒤 / 기간 끝) + 기간 합계.
연간 보기는 일 대신 월 행(1~12월)으로 줄인다.
"""
holidays = holidays or {}
rows: list[dict] = []
if period.kind == "year":
for m in range(1, 13):
s = date(period.start.year, m, 1)
e = month_end(s)
rows.append(_row("month", f"{m}월", by_code(cells, codes, s, e), future=s > today,
**{"from": s.isoformat(), "to": e.isoformat()}))
rows.append(_row("total", "연간 합계", by_code(cells, codes, period.start, period.end)))
return rows
week_codes: dict[str, Money] = {c: Money() for c in codes}
for d in daterange(period.start, period.end):
per_code = {c: cells.get((d, c), Money()) for c in codes}
iso = d.isoformat()
rows.append(_row("day", day_label(d), per_code, date=iso, weekday=d.weekday(),
holiday=holidays.get(iso, ""), future=d > today, today=d == today,
**{"from": iso, "to": iso}))
for c in codes:
week_codes[c].add(per_code[c])
if period.days > 1 and (d.weekday() == 6 or d == period.end):
ws = max(week_start(d), period.start)
label = "주간합계" if period.kind == "week" else f"주간합계 ({fmt_md(ws)}~{fmt_md(d)})"
rows.append(_row("week", label, week_codes, **{"from": ws.isoformat(), "to": d.isoformat()}))
week_codes = {c: Money() for c in codes}
if period.kind != "week" and period.days > 1:
rows.append(_row("total", "기간 합계", by_code(cells, codes, period.start, period.end)))
return rows
def month_summary(year: int, month: int, codes: Sequence[str], cells: Mapping[tuple[date, str], Money]) -> dict:
s = date(year, month, 1)
per = by_code(cells, codes, s, month_end(s))
tot = total(per.values())
rows = []
for c in codes:
m = per[c]
share = round(m.gross / tot.gross * 100, 1) if tot.gross > 0 else None
rows.append({"code": c, **m.as_dict(), "share": share})
rows.sort(key=lambda r: r["gross"], reverse=True)
return {"label": f"{year}년 {month}월", "rows": rows,
"total": {**tot.as_dict(), "share": 100.0 if tot.gross > 0 else None}}
def year_months(year: int, codes: Sequence[str], cells: Mapping[tuple[date, str], Money], *, today: date) -> dict:
rows = []
for m in range(1, 13):
s = date(year, m, 1)
future = s > today
money = sum_range(cells, codes, s, month_end(s))
rows.append({"month": m, "label": f"{m}월", "future": future,
**({"gross": None, "commission": None, "net": None} if future else money.as_dict())})
tot = sum_range(cells, codes, date(year, 1, 1), date(year, 12, 31))
return {"year": year, "rows": rows, "total": tot.as_dict()}
def daily_series(period: Period, codes: Sequence[str], cells: Mapping[tuple[date, str], Money]) -> list[dict]:
"""일별 추이 그래프용. 연간은 월별."""
if period.kind == "year":
out = []
for m in range(1, 13):
s = date(period.start.year, m, 1)
out.append({"label": f"{m}월", **sum_range(cells, codes, s, month_end(s)).as_dict()})
return out
return [{"label": fmt_md(d), "date": d.isoformat(), **sum_range(cells, codes, d, d).as_dict()}
for d in daterange(period.start, period.end)]