Files
dbx-main/app/modules/performance/formula.py
T
king f79b970056 feat(performance): 앞날 입력·계산식 칸·기간 합계 맨 위
- 매출 수동 입력·광고비 날짜 칸과 엑셀·광고 보고서 업로드에서 오늘 이후 날짜 허용
- 이번달 등 일자별 표의 기간 합계 행을 제목 행 바로 아래로
- 날짜 칸에 = 없이 1000+2000 계산식 입력(formula.parse_amount), 식은
  마이그레이션 008 formula 열에 저장해 파랑 굵은 숫자·다시 누르면 식
- 광고비 탭 직접 입력값은 굵게 해제(굵게는 계산식만)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 11:30:11 +09:00

107 lines
3.7 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""매출·광고비 날짜 칸 입력 — 숫자 또는 엑셀 같은 계산식(= 없이 바로 `1000+2000`).
parse_amount("12,000") → (12000, None) 숫자 그대로
parse_amount("1000+2000*2") → (5000, "1000+2000*2") 계산식 — 결과(원, 반올림)와 식을 함께 저장해 다시 누르면 식이 보인다
쓸 수 있는 것: 숫자(쉼표·소수), + - * / ( ), ×·÷·x 는 곱하기·나누기로. 그 밖의 글자는 오류.
"""
from __future__ import annotations
import re
from decimal import ROUND_HALF_UP, Decimal, DivisionByZero, InvalidOperation
MAX_FORMULA_LEN = 200
_OPS = {"×": "*", "x": "*", "X": "*", "÷": "/"}
_TOKEN = re.compile(r"\d+(?:\.\d+)?|\.\d+|[-+*/()]")
class FormulaError(ValueError):
pass
def _tokens(text: str) -> list[str]:
out: list[str] = []
pos = 0
while pos < len(text):
m = _TOKEN.match(text, pos)
if not m:
raise FormulaError("숫자와 + - * / ( ) 만 입력할 수 있습니다.")
out.append(m.group())
pos = m.end()
return out
class _Parser:
"""식 := 항 (('+'|'-') 항)* · 항 := 인자 (('*'|'/') 인자)* · 인자 := ('+'|'-') 인자 | 숫자 | '(' 식 ')'"""
def __init__(self, tokens: list[str]):
self.t = tokens
self.i = 0
def peek(self) -> str | None:
return self.t[self.i] if self.i < len(self.t) else None
def take(self) -> str:
tok = self.peek()
if tok is None:
raise FormulaError("계산식이 끝나지 않았습니다.")
self.i += 1
return tok
def expr(self) -> Decimal:
v = self.term()
while self.peek() in ("+", "-"):
v = v + self.term() if self.take() == "+" else v - self.term()
return v
def term(self) -> Decimal:
v = self.factor()
while self.peek() in ("*", "/"):
if self.take() == "*":
v = v * self.factor()
else:
d = self.factor()
if d == 0:
raise FormulaError("0으로 나눌 수 없습니다.")
v = v / d
return v
def factor(self) -> Decimal:
tok = self.take()
if tok in ("+", "-"):
v = self.factor()
return v if tok == "+" else -v
if tok == "(":
v = self.expr()
if self.take() != ")":
raise FormulaError("괄호가 맞지 않습니다.")
return v
if tok in ("*", "/", ")"):
raise FormulaError("계산식이 올바르지 않습니다.")
return Decimal(tok)
def parse_amount(raw: object) -> tuple[int | None, str | None]:
"""칸 입력 → (원 단위 금액, 계산식). 빈 칸 = (None, None)(지움). 숫자 하나(부호 포함)면 계산식 없음."""
text = str(raw if raw is not None else "").strip()
for a, b in _OPS.items():
text = text.replace(a, b)
text = re.sub(r"[,\s원]", "", text)
if text.startswith("="): # 엑셀 버릇으로 = 를 붙여도 된다
text = text[1:]
if text == "":
return None, None
if len(text) > MAX_FORMULA_LEN:
raise FormulaError("계산식이 너무 깁니다.")
tokens = _tokens(text)
p = _Parser(tokens)
try:
value = p.expr()
except (InvalidOperation, DivisionByZero):
raise FormulaError("계산할 수 없는 식입니다.") from None
if p.peek() is not None:
raise FormulaError("계산식이 올바르지 않습니다.")
amount = int(value.quantize(Decimal("1"), rounding=ROUND_HALF_UP))
# 숫자 하나(앞 부호만 있는 것 포함)는 계산식이 아니다
is_formula = any(t in "+-*/()" for t in tokens[1:]) or (tokens[0] == "(")
return amount, (text if is_formula else None)