diff --git a/app/modules/performance/CLAUDE.md b/app/modules/performance/CLAUDE.md index 6ca204c..de677c4 100644 --- a/app/modules/performance/CLAUDE.md +++ b/app/modules/performance/CLAUDE.md @@ -39,6 +39,11 @@ - 설정의 쇼핑몰별 **수동 입력** 토글(마이그레이션 002 `manual_input`·`perf_manual_sales`) — 켜면 일자별 표 날짜 칸에 총매출 직접 입력, 넣은 날은 API 값 대신(`daily_amounts` 한 곳). 수동 입력 켠 쇼핑몰은 **API 가 설정돼 있어도 매출 업데이트(수동·자동·과거 매출 가져오기)에서 빠진다**(2026-10-21, `sync.sync_all` 대상 고르기 한 곳) — 예전에 받은 API 값은 그대로 남음. - 일자별 표 [엑셀 업로드] 팝업(`manual_upload.py`, `POST /performance/api/manual-sales/upload`) — 1열 날짜·2열부터 쇼핑몰 이름 머리글, 수동 입력 켜진 쇼핑몰 열의 값 있는 칸만 반영(덮어씀, 빈 칸 그대로), 잘못된 칸이 하나라도 있으면 전부 저장 안 함, 샘플 = 모듈 폴더 `upload_sample.xlsx`. +- **앞으로의 날짜도 입력·업로드 가능**(2026-10-21) — 매출 수동 입력·광고비 날짜 칸, 매출 엑셀 업로드, 광고 보고서 업로드 모두(가져오기 API 는 여전히 오늘까지). +- **계산식 입력**(2026-10-21, `formula.py` `parse_amount`, 마이그레이션 008 `formula` 열) — 매출·광고비 날짜 칸에 = 없이 `1000+2000`(+ - * / 괄호, ×·÷)을 넣으면 + 서버가 계산(원 반올림)해 금액으로, 식은 `formula` 열에 저장 → 칸 `is-formula` 파랑 굵은 숫자, 다시 누르면 식. 숫자 입력·업로드·광고 API 로 덮으면 식 지움(`db._set_formulas`, 008 미적용이면 조용히 건너뜀). + 광고비 탭 직접 입력값은 파랑 **보통 굵기**(굵게는 계산식만), 매출 탭 수동 입력값은 예전처럼 파랑 굵게. +- 일자별 표 **기간 합계 행은 맨 위**(제목 행 바로 아래, 2026-10-21 `calc.main_table`) — 매출·광고비 공통, 연간 보기 "연간 합계"는 그대로 맨 아래. - 열 순서 카페24·네이버·쿠팡(윙)·쿠팡(로켓)·오늘의집·G마켓·카카오·GS샵·11번가·롯데ON·토스·애터미아자몰(마이그레이션 003). - 쿠팡(로켓)·애터미아자몰은 **수동 입력 전용**(`adapters/manual.py`, `manual_only` — 매출 업데이트에서 빠지고 인증 설정·연결 테스트 없음, 수동 입력 늘 켜짐). diff --git a/app/modules/performance/ad_spend.py b/app/modules/performance/ad_spend.py index b62bb01..eba51a3 100644 --- a/app/modules/performance/ad_spend.py +++ b/app/modules/performance/ad_spend.py @@ -189,8 +189,6 @@ def parse_coupang_rocket(content: bytes, *, today: date, filename: str = "") -> res.skipped += 1 # 날짜는 있지만 19열이 빈 줄(캠페인 줄 등) — 건너뜀 elif abs(amt) > MAX_AMOUNT: res.errors.append(f"{r}행 19열: 금액이 너무 큽니다.") - elif day > today: - res.errors.append(f"{r}행: 앞으로의 날짜({day.isoformat()})는 입력할 수 없습니다.") else: sums[day] = sums.get(day, 0) + amt # 같은 날짜에 값이 있는 줄이 여럿이면 더한다 if len(sums) > MAX_DATA_ROWS: @@ -307,8 +305,6 @@ def parse_naver(content: bytes, *, today: date, filename: str = "") -> ParseResu res.errors.append(f"{r}행 {amount_col + 1}열: {day.isoformat()} 총비용이 비어 있습니다.") elif abs(amt) > MAX_AMOUNT or (ro is not None and abs(ro) > Decimal("10000000")): res.errors.append(f"{r}행: 금액·ROAS 가 너무 큽니다.") - elif day > today: - res.errors.append(f"{r}행: 앞으로의 날짜({day.isoformat()})는 입력할 수 없습니다.") elif day in seen: res.errors.append(f"{r}행: {day.isoformat()} 이 {seen[day]}행과 겹칩니다.") else: @@ -603,6 +599,10 @@ def build_ad_dashboard(store: Any, *, kind: str, anchor: date, today: date, # 광고 API(구글 광고 등)로 가져온 칸 — 표시용(초록 숫자) "api_cells": sorted(f"{d.isoformat()}|{c}" for (d, c), s in sources.items() if s == "api" and period.start <= d <= period.end), + # 계산식으로 입력한 칸(마이그레이션 008) — "날짜|채널" → 식(파랑 굵은 숫자, 누르면 식) + "formula_cells": {f"{d.isoformat()}|{c}": f for (d, c), f in + (store.ad_formulas(period.start, period.end) if hasattr(store, "ad_formulas") + and not migration_needed else {}).items()}, "upload_channels": [{"code": c, "name": CHANNEL_NAMES[c], "help": UPLOAD_HELP.get(c, "")} for c in PARSERS], "migration_needed": migration_needed, } diff --git a/app/modules/performance/calc.py b/app/modules/performance/calc.py index c430e3e..a6b7848 100644 --- a/app/modules/performance/calc.py +++ b/app/modules/performance/calc.py @@ -234,7 +234,7 @@ def _row(kind: str, label: str, per_code: dict[str, Money], **extra) -> dict: def main_table(period: Period, codes: Sequence[str], cells: Mapping[tuple[date, str], Money], *, today: date, holidays: Mapping[str, str] | None = None) -> list[dict]: - """일자 × 쇼핑몰 표. 일 행 + 주간합계(일요일 뒤 / 기간 끝) + 기간 합계. + """일자 × 쇼핑몰 표. 기간 합계(맨 위 — 제목 행 바로 아래, 2026-10-21) + 일 행 + 주간합계(일요일 뒤 / 기간 끝). 연간 보기는 일 대신 월 행(1~12월)으로 줄인다. """ @@ -264,7 +264,7 @@ def main_table(period: Period, codes: Sequence[str], cells: Mapping[tuple[date, 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))) + rows.insert(0, _row("total", "기간 합계", by_code(cells, codes, period.start, period.end))) return rows diff --git a/app/modules/performance/dashboard.py b/app/modules/performance/dashboard.py index 98fcf2f..7a510d3 100644 --- a/app/modules/performance/dashboard.py +++ b/app/modules/performance/dashboard.py @@ -152,6 +152,11 @@ def build_dashboard(store: Any, *, kind: str, anchor: date, today: date, 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 {})) + # 계산식으로 입력한 수동 칸(마이그레이션 008) — "날짜|쇼핑몰" → 식 + manual_formulas = getattr(store, "manual_formulas", None) + formula_cells = {f"{d.isoformat()}|{c}": f for (d, c), f in + (manual_formulas(period.start, period.end, manual_codes) if manual_formulas and manual_codes else {}).items() + if f"{d.isoformat()}|{c}" in manual_cells} cur = calc.sum_range(cells, codes, period.start, period.end) prev = calc.sum_range(cells, codes, cmp_start, cmp_end) @@ -229,6 +234,7 @@ def build_dashboard(store: Any, *, kind: str, anchor: date, today: date, "problems": problems, "manual_codes": manual_codes, "manual_cells": manual_cells, + "formula_cells": formula_cells, # 엑셀 업로드 대상 — 수동 입력이 켜진 쇼핑몰 전부(쇼핑몰 선택 필터와 무관, 설정 순서) "manual_upload_names": [m["name"] for m in markets if m.get("manual_input")], "last_update_at": store.last_update_at(), diff --git a/app/modules/performance/db.py b/app/modules/performance/db.py index 0589c4a..0aeb3e5 100644 --- a/app/modules/performance/db.py +++ b/app/modules/performance/db.py @@ -30,6 +30,24 @@ class ManualMigrationNeeded(Exception): """수동 입력(마이그레이션 002: perf_marketplaces.manual_input · perf_manual_sales)이 아직 적용되지 않음.""" +def _set_formulas(conn: Any, table: str, key_col: str, date_col: str, + rows: list[tuple[str, date, str | None]]) -> None: + """날짜 칸 계산식(마이그레이션 008) 덮어쓰기 — 식이 없으면 지움. 008 미적용이면 조용히 건너뛴다 + (savepoint 라 바깥 트랜잭션은 그대로, 금액은 저장된다). table·열 이름은 코드 상수만 넘긴다.""" + if not rows: + return + try: + with conn.transaction(): + with conn.cursor() as cur: + cur.executemany( + f"UPDATE {table} SET formula = %s WHERE {key_col} = %s AND {date_col} = %s " + "AND formula IS DISTINCT FROM %s", + [(f, k, d, f) for k, d, f in rows], + ) + except pg_errors.UndefinedColumn: + pass + + def _iso(v: Any) -> Any: if isinstance(v, datetime): return to_kst_iso(v) @@ -338,8 +356,9 @@ class PerformanceDBStore: ).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 값).""" + def set_manual_sale(self, code: str, day: date, amount: int | None, *, user: str = "", + formula: str | None = None) -> None: + """수동 값 저장(amount None = 지움 → 그날은 다시 API 값). formula = 계산식(008, 없으면 숫자 입력).""" try: with self._pool.connection() as conn: if amount is None: @@ -352,6 +371,7 @@ class PerformanceDBStore: "SET amount = EXCLUDED.amount, updated_by = EXCLUDED.updated_by", (code, day, int(amount), user), ) + _set_formulas(conn, "perf_manual_sales", "marketplace_code", "sales_date", [(code, day, formula)]) except pg_errors.UndefinedTable: raise ManualMigrationNeeded() from None @@ -369,10 +389,28 @@ class PerformanceDBStore: "SET amount = EXCLUDED.amount, updated_by = EXCLUDED.updated_by", [(code, day, int(amount), user) for code, day, amount in entries], ) + # 업로드 값은 숫자 — 예전에 넣은 계산식은 지운다 + _set_formulas(conn, "perf_manual_sales", "marketplace_code", "sales_date", + [(code, day, None) for code, day, _ in entries]) except pg_errors.UndefinedTable: raise ManualMigrationNeeded() from None return len(entries) + def manual_formulas(self, start: date, end: date, codes: list[str]) -> dict[tuple[date, str], str]: + """계산식으로 입력한 수동 칸 (날짜, 쇼핑몰) → 식. 008 미적용이면 비어 있음.""" + if not codes: + return {} + try: + with self._pool.connection() as conn: + rows = conn.execute( + "SELECT sales_date, marketplace_code, formula FROM perf_manual_sales " + "WHERE sales_date BETWEEN %s AND %s AND marketplace_code = ANY(%s) AND formula IS NOT NULL", + (start, end, codes), + ).fetchall() + except (pg_errors.UndefinedTable, pg_errors.UndefinedColumn): + return {} + return {(r["sales_date"], r["marketplace_code"]): r["formula"] for r in rows} + # ════════════════════════════════════════════════════════════ # 광고비(마이그레이션 005) # ════════════════════════════════════════════════════════════ @@ -391,15 +429,19 @@ class PerformanceDBStore: return ({(r["spend_date"], r["channel_code"]): int(r["amount"]) for r in rows}, {(r["spend_date"], r["channel_code"]): r["source"] for r in rows}) - def set_ad_spend(self, code: str, day: date, amount: int | None, *, source: str = "manual", user: str = "") -> None: - """광고비 한 칸 저장(amount None = 지움).""" - self.set_ad_spend_bulk(code, [(day, amount)], source=source, user=user) + def set_ad_spend(self, code: str, day: date, amount: int | None, *, source: str = "manual", user: str = "", + formula: str | None = None) -> None: + """광고비 한 칸 저장(amount None = 지움). formula = 계산식(008, 없으면 숫자 입력).""" + self.set_ad_spend_bulk(code, [(day, amount)], source=source, user=user, + formulas={day: formula} if formula else None) def set_ad_spend_bulk(self, code: str, entries: list[tuple[date, int | None]], *, source: str = "manual", user: str = "", roas: dict[date, Any] | None = None, - metrics: dict[date, dict[str, Any]] | None = None) -> int: + metrics: dict[date, dict[str, Any]] | None = None, + formulas: dict[date, str] | None = None) -> int: """여러 날을 한 트랜잭션으로(같은 날은 덮어씀, 금액 None 은 지움). 하나라도 실패하면 모두 취소. - roas·metrics 를 주면(보고서 업로드, 마이그레이션 006) 그 날의 ROAS·상세 항목도 덮어쓴다 — 안 주면(직접 입력) 그대로 둔다.""" + roas·metrics 를 주면(보고서 업로드, 마이그레이션 006) 그 날의 ROAS·상세 항목도 덮어쓴다 — 안 주면(직접 입력) 그대로 둔다. + formulas = 날짜 칸 계산식(008) — 저장하는 날 중 없는 날은 계산식을 지운다(업로드·API·숫자 입력).""" from .ad_spend import AdMigrationNeeded # noqa: WPS433 if not entries: @@ -433,12 +475,26 @@ class PerformanceDBStore: "SET amount = EXCLUDED.amount, source = EXCLUDED.source, updated_by = EXCLUDED.updated_by", keep, ) + _set_formulas(conn, "perf_ad_spend", "channel_code", "spend_date", + [(code, d, (formulas or {}).get(d)) for d, a in entries if a is not None]) except pg_errors.UndefinedTable: raise AdMigrationNeeded("005") from None except pg_errors.UndefinedColumn: raise AdMigrationNeeded("006") from None return len(entries) + def ad_formulas(self, start: date, end: date) -> dict[tuple[date, str], str]: + """계산식으로 입력한 광고비 칸 (날짜, 채널) → 식. 005·008 미적용이면 비어 있음.""" + try: + with self._pool.connection() as conn: + rows = conn.execute( + "SELECT spend_date, channel_code, formula FROM perf_ad_spend " + "WHERE spend_date BETWEEN %s AND %s AND formula IS NOT NULL", (start, end), + ).fetchall() + except (pg_errors.UndefinedTable, pg_errors.UndefinedColumn): + return {} + return {(r["spend_date"], r["channel_code"]): r["formula"] for r in rows} + def ad_roas(self, start: date, end: date) -> dict[tuple[date, str], Decimal]: """(날짜, 채널) → 보고서 ROAS(%) — 값이 있는 칸만. 005·006 미적용이면 빈 값(화면은 ROAS 없이). roas 가 비었어도 보관된 보고서 항목(metrics)에 광고수익률·전환매출액이 있으면 그것으로 구한다 @@ -726,6 +782,8 @@ class PerformanceDBStore: "roas = EXCLUDED.roas, metrics = EXCLUDED.metrics", rows, ) + _set_formulas(conn, "perf_ad_spend", "channel_code", "spend_date", + [(code, d, None) for d, _, _, _ in days]) except pg_errors.UndefinedTable: raise AdMigrationNeeded("005") from None except pg_errors.UndefinedColumn: diff --git a/app/modules/performance/formula.py b/app/modules/performance/formula.py new file mode 100644 index 0000000..e6b8aec --- /dev/null +++ b/app/modules/performance/formula.py @@ -0,0 +1,106 @@ +"""매출·광고비 날짜 칸 입력 — 숫자 또는 엑셀 같은 계산식(= 없이 바로 `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) diff --git a/app/modules/performance/manual_upload.py b/app/modules/performance/manual_upload.py index 18ee5c4..34a1692 100644 --- a/app/modules/performance/manual_upload.py +++ b/app/modules/performance/manual_upload.py @@ -4,7 +4,7 @@ - 머리글(1행) 2열부터 = 쇼핑몰 이름. 설정의 이름·짧은 이름(네이버/토스)·코드 어느 것이든 되고 띄어쓰기·대소문자는 무시. - 수동 입력이 켜진 쇼핑몰 열만 반영. 꺼진 쇼핑몰·모르는 이름 열은 건너뛰고 알려 준다. - 값이 있는 칸만 반영(빈 칸은 그날 기존 값 그대로 — 지우지 않음). 0 은 값(0원)으로 저장. - - 날짜: 엑셀 날짜, 2026-10-12 · 2026.10.12 · 2026/10/12 · 20261012(뒤 요일 표기 무시). 앞으로의 날짜는 안 됨. + - 날짜: 엑셀 날짜, 2026-10-12 · 2026.10.12 · 2026/10/12 · 20261012(뒤 요일 표기 무시). 앞으로의 날짜도 됨(2026-10-21). - 금액: 원 단위 정수(쉼표·"원" 허용, 소수는 반올림). - 잘못된 칸이 하나라도 있으면 아무것도 저장하지 않고 오류 목록을 돌려준다(일부만 들어가 헷갈리지 않게). @@ -185,9 +185,6 @@ def parse_workbook(content: bytes, *, markets: list[Mapping[str, Any]], today: d 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) diff --git a/app/modules/performance/router.py b/app/modules/performance/router.py index 990fd41..b408c55 100644 --- a/app/modules/performance/router.py +++ b/app/modules/performance/router.py @@ -393,36 +393,38 @@ def api_events(request: Request, code: str, from_: str = Query(..., alias="from" return JSONResponse({"rows": rows, "truncated": len(rows) >= 500}) +def _cell_amount(raw: Any) -> tuple[int | None, str | None]: + """날짜 칸 입력(매출 수동 입력·광고비) → (금액, 계산식). 빈 칸 = 지움.""" + from .formula import FormulaError, parse_amount # noqa: WPS433 + + try: + amount, formula = parse_amount(raw) + except FormulaError as exc: + raise HTTPException(status_code=400, detail=f"{exc} (숫자 또는 1000+2000 같은 계산식)") from None + if amount is not None and abs(amount) > MAX_MANUAL_AMOUNT: + raise HTTPException(status_code=400, detail="금액이 너무 큽니다.") + return amount, formula + + @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 값).""" + """수동 입력 — 그 쇼핑몰 수동 입력이 켜져 있을 때만, 앞으로의 날도 가능(2026-10-21). amount 가 비면 지움(그날은 다시 API 값). + amount 는 숫자 또는 계산식(1000+2000 — formula.parse_amount).""" 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="금액이 너무 큽니다.") + amount, formula = _cell_amount(payload.get("amount")) try: - store.set_manual_sale(code, d, amount, user=user.get("email", "")) + store.set_manual_sale(code, d, amount, user=user.get("email", ""), formula=formula) 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, + return JSONResponse({"ok": True, "code": code, "date": d.isoformat(), "manual": amount, "formula": formula, "amount": api_amount if amount is None else amount, "api_amount": api_amount}) @@ -493,24 +495,12 @@ def api_ad_spend(request: Request, channel: str, day: str, payload: dict[str, An d = _parse_date(day) if d is None: raise HTTPException(status_code=400, detail="날짜가 필요합니다.") - if d > today_kst(): - 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="금액이 너무 큽니다.") + amount, formula = _cell_amount(payload.get("amount")) try: - store.set_ad_spend(channel, d, amount, source="manual", user=user.get("email", "")) + store.set_ad_spend(channel, d, amount, source="manual", user=user.get("email", ""), formula=formula) except AdMigrationNeeded as exc: raise HTTPException(status_code=503, detail=_ad_migration_help(exc)) from None - return JSONResponse({"ok": True, "channel": channel, "date": d.isoformat(), "manual": amount, + return JSONResponse({"ok": True, "channel": channel, "date": d.isoformat(), "manual": amount, "formula": formula, "amount": amount or 0}) diff --git a/app/modules/performance/templates/performance/ads.html b/app/modules/performance/templates/performance/ads.html index f8768d7..9b1e7ee 100644 --- a/app/modules/performance/templates/performance/ads.html +++ b/app/modules/performance/templates/performance/ads.html @@ -1,6 +1,6 @@ {% extends "erp_base.html" %} -{% block head_extra %}{% endblock %} +{% block head_extra %}{% endblock %} {#- ROAS 덧붙임 — "광고비(ROAS%)". 광고비가 없으면 아무것도 안 붙는다. -#} {%- macro roas(p) -%}{%- if p is not none -%}({{ "{:,}".format(p) }}%){%- endif -%}{%- endmacro -%} @@ -113,12 +113,13 @@ {% for c in codes %} {% set v = r.cells[c].gross %} - {% if r.kind == 'day' and not r.future and not migration_needed %} + {% if r.kind == 'day' and not migration_needed %} {% set up = (r.date ~ '|' ~ c) in upload_cells %} {% set ap = (r.date ~ '|' ~ c) in api_cells %} - {{ won(v) }}{{ roas(r.roas[c]) }} + {% set fx = (formula_cells or {}).get(r.date ~ '|' ~ c) if not up and not ap else none %} + {{ won(v) }}{{ roas(r.roas[c]) }} {% else %} {{ won(v) }}{{ roas(r.roas[c]) }} {% endif %} @@ -133,7 +134,7 @@

날짜 칸을 눌러 그날 광고비를 직접 입력합니다 — Enter 저장 후 아래 칸, Esc 취소, 비우고 저장하면 지움. 칸은 광고비(ROAS%) — ROAS = 그 쇼핑몰 매출 실적 총매출 ÷ 광고비(합계 열은 전체 매출). 메타는 메타 광고 API 의 구매 ROAS(구매 전환값 ÷ 지출 금액), 네이버는 광고 보고서의 ROAS(구매완료 광고수익률), 구글은 구글 광고 API 의 ROAS(전환 가치 ÷ 비용)를 씁니다 — 네이버·구글·메타 머리글을 누르면 일자별 보고서 항목. - 파란 숫자 = 직접 입력, 주황 숫자 = 파일 업로드 값, 초록 숫자 = 광고 API 값. 쿠팡(윙)·쿠팡(로켓)·네이버는 [파일 업로드]로 광고 보고서를 올리면 날짜별로 한 번에 들어갑니다. + 파란 숫자 = 직접 입력, 파랑 굵은 숫자 = 계산식(1000+2000 처럼 = 없이 입력하면 바로 계산), 주황 숫자 = 파일 업로드 값, 초록 숫자 = 광고 API 값. 쿠팡(윙)·쿠팡(로켓)·네이버는 [파일 업로드]로 광고 보고서를 올리면 날짜별로 한 번에 들어갑니다. 구글·메타는 [구글 광고 불러오기]·[메타 광고 불러오기](관리자가 실적 설정 → 광고 API 연동을 마친 뒤) 또는 매출 자동 업데이트 때 들어옵니다.

{% endif %} @@ -237,4 +238,4 @@ } | tojson }} {% endblock %} -{% block scripts %}{% endblock %} +{% block scripts %}{% endblock %} diff --git a/app/modules/performance/templates/performance/index.html b/app/modules/performance/templates/performance/index.html index f14e4ae..7a0de33 100644 --- a/app/modules/performance/templates/performance/index.html +++ b/app/modules/performance/templates/performance/index.html @@ -1,6 +1,6 @@ {% extends "erp_base.html" %} -{% block head_extra %}{% endblock %} +{% block head_extra %}{% endblock %} {%- macro won(v) -%} {%- if v is none -%} @@ -151,11 +151,12 @@ {% for c in codes %} {% set m = r.cells[c] %} - {% if r.kind == 'day' and c in manual_codes and not r.future %} + {% if r.kind == 'day' and c in manual_codes %} {% set is_manual = (r.date ~ '|' ~ c) in manual_cells %} - {{ m3(m) }}{{ adl(r.ads[c]) }} + {% set fx = (formula_cells or {}).get(r.date ~ '|' ~ c) %} + {{ m3(m) }}{{ adl(r.ads[c]) }} {% else %} {{ m3(m) }}{{ adl(r.ads[c]) }} @@ -169,7 +170,7 @@ {% if manual_codes and period_kind != 'year' %}

✎ 표시 쇼핑몰은 날짜 칸을 눌러 총매출을 직접 입력합니다 — Enter 저장 후 아래 칸, Esc 취소, - 비우고 저장하면 다시 API 수집값. 파란 숫자 = 수동 입력값. 수수료는 그날 수수료율로 계산되고, 입력을 마치면 합계·그래프가 다시 계산됩니다.

+ 비우고 저장하면 다시 API 수집값. 1000+2000 처럼 = 없이 계산식을 넣으면 바로 계산됩니다. 파란 숫자 = 수동 입력값, 파랑 굵은 숫자 = 계산식. 수수료는 그날 수수료율로 계산되고, 입력을 마치면 합계·그래프가 다시 계산됩니다.

{% endif %} @@ -274,4 +275,4 @@ } | tojson }} {% endblock %} -{% block scripts %}{% endblock %} +{% block scripts %}{% endblock %} diff --git a/app/modules/performance/templates/performance/settings.html b/app/modules/performance/templates/performance/settings.html index 0659123..752ab2e 100644 --- a/app/modules/performance/templates/performance/settings.html +++ b/app/modules/performance/templates/performance/settings.html @@ -1,6 +1,6 @@ {% extends "erp_base.html" %} -{% block head_extra %}{% endblock %} +{% block head_extra %}{% endblock %} {%- macro when(v) -%}{{ (v or '')[:16] | replace('T', ' ') or '—' }}{%- endmacro -%} @@ -219,4 +219,4 @@ {% endblock %} -{% block scripts %}{% endblock %} +{% block scripts %}{% endblock %} diff --git a/app/modules/performance/tests/test_ad_spend.py b/app/modules/performance/tests/test_ad_spend.py index 4af00f2..32ab7a2 100644 --- a/app/modules/performance/tests/test_ad_spend.py +++ b/app/modules/performance/tests/test_ad_spend.py @@ -51,11 +51,12 @@ def test_rocket_report_reads_date_and_col19(content, name): def test_rocket_report_errors_block_everything(): bad = ROCKET_CSV + "2026년 13월 40일,RETAIL,,,,,,,,,,,1,0,1,1,1,0,1\n" # 날짜 오류 bad += "2026년 10월 08일,RETAIL,,,,,,,,,,,1,0,1,1,1,0,abc\n" # 금액이 숫자 아님 - bad += "2026년 10월 20일,RETAIL,,,,,,,,,,,1,0,1,1,1,0,5\n" # 앞으로의 날짜 + bad += "2026년 10월 20일,RETAIL,,,,,,,,,,,1,0,1,1,1,0,5\n" # 앞으로의 날짜 — 됨(2026-10-21) res = ads.parse_coupang_rocket(bad.encode("utf-8"), today=TODAY) joined = " / ".join(res.errors) - assert len(res.errors) == 3, res.errors - assert "날짜를 읽을 수 없습니다" in joined and "숫자가 아닙니다" in joined and "앞으로의 날짜" in joined + assert len(res.errors) == 2, res.errors + assert "날짜를 읽을 수 없습니다" in joined and "숫자가 아닙니다" in joined and "앞으로의 날짜" not in joined + assert (date(2026, 10, 20), 5) in res.entries def test_coupang_report_date_rows_col19_summed_empty_skipped(): @@ -130,12 +131,12 @@ def test_ad_dashboard_month(): assert ctx["api_cells"] == [] day1 = next(r for r in ctx["table"] if r.get("date") == "2026-10-01") assert day1["cells"]["coupang_rocket"]["gross"] == 220000 and day1["total"]["gross"] == 220000 - assert ctx["table"][-1]["kind"] == "total" and ctx["table"][-1]["total"]["gross"] == 270000 + assert ctx["table"][0]["kind"] == "total" and ctx["table"][0]["total"]["gross"] == 270000 # 기간 합계 = 맨 위 # ROAS = 그 쇼핑몰 매출 ÷ 광고비 — 로켓 10/1: 550,000 ÷ 220,000 = 250%, 구글 10/2: 카페24 그날 매출 0 → 0% assert day1["roas"]["coupang_rocket"] == 250 and day1["roas"]["google"] is None day2 = next(r for r in ctx["table"] if r.get("date") == "2026-10-02") assert day2["roas"]["google"] is None # 구글·메타는 ROAS 계산 안 함(따로 입력) - total = ctx["table"][-1] + total = ctx["table"][0] assert total["roas"]["coupang_rocket"] == 300 and total["roas"]["google"] is None # 660,000÷220,000 assert total["roas_total"] == 1000 # 2,700,000 ÷ 270,000 (합계 = sales_codes) m = {r["code"]: r for r in ctx["month"]["rows"]} @@ -158,7 +159,7 @@ def test_ad_dashboard_year_and_missing_table(): def test_ad_spend_endpoints(monkeypatch): """라우터: 업로드 정상 → 한 번에 저장(source=upload), 잘못된 줄 → 400 + 목록·저장 안 함, 양식 없는 채널 400, - 칸 저장(source=manual)·지우기, 모르는 채널 404, 앞으로의 날 400, 005 미적용 503.""" + 칸 저장(source=manual)·지우기·계산식, 모르는 채널 404, 앞으로의 날도 됨, 005 미적용 503.""" import importlib from fastapi import FastAPI @@ -179,7 +180,8 @@ def test_ad_spend_endpoints(monkeypatch): self.saved.extend((code, d, a, source) for d, a in entries) return len(entries) - def set_ad_spend(self, code, day, amount, *, source="manual", user=""): + def set_ad_spend(self, code, day, amount, *, source="manual", user="", formula=None): + self.formula = formula self.set_ad_spend_bulk(code, [(day, amount)], source=source, user=user) store = Store() @@ -208,7 +210,10 @@ def test_ad_spend_endpoints(monkeypatch): assert client.put("/performance/api/ad-spend/meta/2026-10-11", json={"amount": ""}).status_code == 200 assert store.saved == [("meta", date(2026, 10, 12), 33000, "manual"), ("meta", date(2026, 10, 11), None, "manual")] assert client.put("/performance/api/ad-spend/cafe24/2026-10-12", json={"amount": 1}).status_code == 404 - assert client.put("/performance/api/ad-spend/meta/2026-10-14", json={"amount": 1}).status_code == 400 + assert client.put("/performance/api/ad-spend/meta/2026-10-14", json={"amount": 1}).status_code == 200 # 앞날도 됨 + store.saved.clear() + r = client.put("/performance/api/ad-spend/meta/2026-10-12", json={"amount": "(10000+5000)×2"}) + assert r.json()["amount"] == 30000 and r.json()["formula"] == "(10000+5000)*2" and store.formula == "(10000+5000)*2" assert client.put("/performance/api/ad-spend/meta/2026-10-12", json={"amount": "abc"}).status_code == 400 store.missing = True r = client.put("/performance/api/ad-spend/meta/2026-10-12", json={"amount": 1}) @@ -237,7 +242,7 @@ def test_naver_report_reads_date_cost_roas_and_metrics(): bad = NAVER_CSV + "0_미라네주방,38461,2026.09.22.,1,0,0,0,0,0,0,0,1\n0_미라네주방,38461,2026.09.20.,abc,0,0,0,0,0,0,0,1\n" bad += "0_미라네주방,38461,2026.09.19.,5,0,0,0,0,0,0,0,x\n0_미라네주방,38461,2026.10.20.,5,0,0,0,0,0,0,0,1\n" errs = " / ".join(ads.parse_naver(bad.encode("utf-8"), today=TODAY).errors) - assert "겹칩니다" in errs and "총비용이 숫자가 아닙니다" in errs and "ROAS" in errs and "앞으로의 날짜" in errs + assert "겹칩니다" in errs and "총비용이 숫자가 아닙니다" in errs and "ROAS" in errs and "앞으로의 날짜" not in errs def test_naver_report_finds_columns_by_header(): diff --git a/app/modules/performance/tests/test_dashboard_ads_units.py b/app/modules/performance/tests/test_dashboard_ads_units.py index ecdae4b..f3c988c 100644 --- a/app/modules/performance/tests/test_dashboard_ads_units.py +++ b/app/modules/performance/tests/test_dashboard_ads_units.py @@ -151,3 +151,50 @@ def test_kpi_is_net_only(): ctx = dashboard.build_dashboard(_Store(), kind="week", anchor=TODAY, today=TODAY) assert [k["key"] for k in ctx["kpis"]] == ["net"] assert ctx["kpis"][0]["value"] == 2_600_000 + 1_234_567 + + +def test_pages_render_formula_cells_future_inputs_and_total_on_top(monkeypatch): + """2026-10-21 — 계산식 칸(is-formula·data-formula), 오늘 뒤 날짜도 입력 칸, 이번달 기간 합계 = 제목 행 바로 아래.""" + import importlib + + from fastapi import FastAPI + from fastapi.testclient import TestClient + + from app.modules.performance import common + + perf_router = importlib.import_module("app.modules.performance.router") + + class _S(_Store): + def list_marketplaces(self): + return [{**m, "manual_input": m["code"] == "coupang"} for m in super().list_marketplaces()] + + def manual_amounts(self, start, end, codes, *, active_only=True): + return {(date(2026, 10, 5), "coupang"): 600_000} + + def manual_formulas(self, start, end, codes): + return {(date(2026, 10, 5), "coupang"): "500000+100000"} + + def ad_formulas(self, start, end): + return {(date(2026, 10, 5), "meta"): "20000+30000"} + + class _Creds: + def configured_codes(self, adapters): + return {} + + store = _S() + monkeypatch.setattr(common, "guard", lambda request, admin=False: (store, {"email": "king@x", "name": "King", "is_admin": True})) + monkeypatch.setattr(common, "services", lambda request, st: (_Creds(), None)) + monkeypatch.setattr(perf_router, "today_kst", lambda: TODAY) + app = FastAPI() + app.include_router(perf_router.router) + client = TestClient(app) + + for url, code, fx in (("/performance/?period=month&d=2026-10-07", "coupang", "500000+100000"), + ("/performance/ads?period=month&d=2026-10-07", "meta", "20000+30000")): + r = client.get(url) + assert r.status_code == 200, r.text + body = r.text.split("", 1)[1].split("", 1)[0] + assert body.lstrip().startswith('", 1)[0] + cell = body.split(f'data-manual-code="{code}" data-date="2026-10-05"', 1) + assert len(cell) == 2 and "is-formula" in cell[0].rsplit("", 1)[0] + assert f'data-manual-code="{code}" data-date="2026-10-20"' in body # 오늘(10/7) 뒤 날짜도 입력 칸 diff --git a/app/modules/performance/tests/test_formula.py b/app/modules/performance/tests/test_formula.py new file mode 100644 index 0000000..dcd929e --- /dev/null +++ b/app/modules/performance/tests/test_formula.py @@ -0,0 +1,28 @@ +"""날짜 칸 계산식(formula.parse_amount) — = 없이 1000+2000 을 바로 계산(2026-10-21).""" +from __future__ import annotations + +import pytest + +from app.modules.performance.formula import FormulaError, parse_amount + + +@pytest.mark.parametrize("raw, expected", [ + ("", (None, None)), (None, (None, None)), (" ", (None, None)), + ("12,000", (12000, None)), (87000, (87000, None)), ("-5000", (-5000, None)), ("1,234원", (1234, None)), + ("1000+2000", (3000, "1000+2000")), + ("1,000 + 2,000 * 2", (5000, "1000+2000*2")), + ("(10000+5000)×2", (30000, "(10000+5000)*2")), + ("10000÷3", (3333, "10000/3")), + ("10001/2", (5001, "10001/2")), # 반올림 + ("=500-200", (300, "500-200")), # 엑셀 버릇 = 도 됨 + ("-100+50", (-50, "-100+50")), + ("1.5*1000", (1500, "1.5*1000")), +]) +def test_parse_amount(raw, expected): + assert parse_amount(raw) == expected + + +@pytest.mark.parametrize("raw", ["abc", "1000+", "*5", "(1+2", "1+2)", "5/0", "1e5", "1000+2000a", "1" * 201]) +def test_parse_amount_errors(raw): + with pytest.raises(FormulaError): + parse_amount(raw) diff --git a/app/modules/performance/tests/test_manual_upload.py b/app/modules/performance/tests/test_manual_upload.py index 192745a..053135a 100644 --- a/app/modules/performance/tests/test_manual_upload.py +++ b/app/modules/performance/tests/test_manual_upload.py @@ -64,14 +64,14 @@ def test_errors_reject_everything_with_cell_refs(): ("날짜", "쿠팡(로켓)", "오늘의집"), ("2026-10-10", "abc", 100), ("엉터리", 1, None), - ("2026-10-14", 1, None), # 앞으로의 날짜 + ("2026-10-14", 1, None), # 앞으로의 날짜 — 됨(2026-10-21) (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 + assert "B2" in joined and "A3" in joined and "A4" not in joined and "5행" in joined and "B7" in joined + assert len(res.errors) == 4 def test_header_problems(): diff --git a/app/modules/performance/tests/test_performance.py b/app/modules/performance/tests/test_performance.py index 3c3a323..85dbfaa 100644 --- a/app/modules/performance/tests/test_performance.py +++ b/app/modules/performance/tests/test_performance.py @@ -187,7 +187,8 @@ def test_main_table_month_and_year(): cells = _cells_for(list(calc.daterange(p.start, p.end)), ["a"]) rows = calc.main_table(p, ["a"], cells, today=date(2026, 9, 30)) weeks = [r for r in rows if r["kind"] == "week"] - assert rows[-1]["kind"] == "total" and rows[-1]["total"]["gross"] == 300_000 + assert rows[0]["kind"] == "total" and rows[0]["total"]["gross"] == 300_000 # 기간 합계 = 맨 위(2026-10-21) + assert rows[1]["kind"] == "day" and rows[-1]["kind"] == "week" assert sum(w["total"]["gross"] for w in weeks) == 300_000 assert weeks[0]["from"] == "2026-09-01" and weeks[0]["to"] == "2026-09-06" # 첫 주는 월 시작부터 y = calc.resolve_period("year", date(2026, 9, 10)) @@ -2095,7 +2096,7 @@ def test_manual_input_marketplaces_skip_sync_even_with_api(): def test_manual_sale_api_rules(): - """수동 입력 API — 그 쇼핑몰 수동 입력이 켜져 있을 때만, 오늘까지, 숫자(쉼표 허용), 비우면 지움, 002 미적용이면 503. + """수동 입력 API — 그 쇼핑몰 수동 입력이 켜져 있을 때만, 앞날도 됨, 숫자(쉼표 허용)·계산식, 비우면 지움, 002 미적용이면 503. 켜고 끄기(PUT marketplaces)는 관리자 전용 그대로, manual_input 도 받는다.""" from fastapi import HTTPException @@ -2113,10 +2114,11 @@ def test_manual_sale_api_rules(): def list_marketplaces(self): return [{"code": "coupang", "manual_input": True}, {"code": "naver", "manual_input": False}] - def set_manual_sale(self, code, day, amount, *, user=""): + def set_manual_sale(self, code, day, amount, *, user="", formula=None): if self.missing: raise ManualMigrationNeeded() self.saved.append((code, day, amount, user)) + self.formula = formula def api_amount(self, code, day): return 50000 @@ -2150,7 +2152,11 @@ def test_manual_sale_api_rules(): 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 # 앞날 + assert status_of(lambda: router.api_manual_sale(None, "coupang", "2026-10-13", {"amount": 1}))[0] == 200 # 앞날도 됨 + assert st.formula is None + body = __import__("json").loads(router.api_manual_sale(None, "coupang", "2026-10-12", {"amount": "1,000+2000*2"}).body) + assert st.saved[-1][2] == 5000 and st.formula == "1000+2000*2" and body["formula"] == "1000+2000*2" + assert status_of(lambda: router.api_manual_sale(None, "coupang", "2026-10-12", {"amount": "1/0"}))[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 diff --git a/app/static/performance.css b/app/static/performance.css index 8884833..b5efe20 100644 --- a/app/static/performance.css +++ b/app/static/performance.css @@ -196,6 +196,10 @@ td.is-link:hover { background: #eef2ff; text-decoration: underline; } .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; } +/* 광고비 탭 직접 입력값은 파랑 보통 굵기(2026-10-21) — 굵게는 계산식 칸만 */ +.perf-ads td.is-manual .v-gross { font-weight: 400; } +/* 계산식(1000+2000)으로 입력한 칸 — 파랑 굵은 숫자(매출 실적은 보기 기준 금액 모두) */ +.perf-main td.is-manual.is-formula .v { color: #1a56db; font-weight: 700; } .perf-main td.is-stale .v-commission, .perf-main td.is-stale .v-net { opacity: .4; } /* 입력칸은 칸 위에 겹쳐 띄운다(표 배치에서 빠짐) — 숫자는 자리만 남기고 숨겨 열 너비가 그대로 */ .perf .perf-main td.is-editing .v { visibility: hidden; } diff --git a/app/static/performance.js b/app/static/performance.js index 2366dd4..b02002a 100644 --- a/app/static/performance.js +++ b/app/static/performance.js @@ -628,12 +628,15 @@ // ── 수동 입력(설정에서 켠 쇼핑몰) — 날짜 칸을 눌러 총매출 입력. Enter 저장 후 아래 칸 · Shift+Enter 위 칸 · Esc 취소. // 비우고 저장하면 그날은 다시 API 값. 저장은 칸마다 차례로, 입력을 마치면(다른 칸으로 안 넘어가면) 새로고침해 // 합계·수수료·그래프를 서버 계산으로 다시 그린다. + // 엑셀처럼 계산식도 됨(= 없이 1000+2000, + - * / 괄호) — 서버가 계산해 금액과 식을 저장(formula.parse_amount), + // 식으로 넣은 칸은 is-formula(파랑 굵게)이고 다시 누르면 식이 보인다. 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 inputOf(td) { return td.dataset.formula || digitsOf(td); } // 편집 칸에 보일 값(식이 있으면 식) function finishManual() { setTimeout(function () { if (root.querySelector(".perf-manual-input")) return; // 다른 칸으로 넘어감 @@ -641,21 +644,25 @@ }, 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 raw = String(text || "").replace(/[,\s원]/g, "").replace(/^=/, ""); + if (raw !== "" && !/^[-+*/().\d×÷xX]+$/.test(raw)) { + return Promise.reject(new Error("숫자 또는 1000+2000 같은 계산식만 입력하세요.")); + } + if (raw === inputOf(td)) return Promise.resolve(false); // 바뀐 것 없음(빈 칸 그대로 포함) const job = manualChain.then(function () { return api("PUT", MANUAL_API + encodeURIComponent(td.dataset.manualCode) + "/" + - encodeURIComponent(td.dataset.date), { amount: raw === "" ? null : Number(raw) }); + encodeURIComponent(td.dataset.date), { amount: raw === "" ? null : raw }); }).then(function (res) { const manual = res.manual == null ? "" : String(res.manual); td.dataset.manualValue = manual; + if (res.formula) td.dataset.formula = res.formula; else delete td.dataset.formula; td.classList.toggle("is-manual", manual !== ""); - td.classList.remove("is-upload"); + td.classList.toggle("is-formula", !!res.formula); + td.classList.remove("is-upload", "is-api"); const ro = td.querySelector(".perf-roas"); // 광고비가 바뀌면 ROAS 는 새로고침 때 다시 계산 if (ro) ro.remove(); - td.title = manual !== "" ? "직접 입력값 — 눌러 고치기(비우고 저장하면 " + (FIXED_METRIC ? "지움" : "API 값") + ")" + td.title = res.formula ? "계산식 " + res.formula + " — 눌러 고치기" + : manual !== "" ? "직접 입력값 — 눌러 고치기(비우고 저장하면 " + (FIXED_METRIC ? "지움" : "API 값") + ")" : "눌러 " + MANUAL_WORD + " 직접 입력"; const g = td.querySelector(".v-gross"); if (g) g.innerHTML = unitWon(res.amount, data.unit); @@ -668,9 +675,9 @@ } function editManual(td) { if (td.querySelector(".perf-manual-input")) return; - const input = el("input", { type: "text", inputmode: "numeric", class: "perf-manual-input", + const input = el("input", { type: "text", class: "perf-manual-input", "aria-label": ((data.names || {})[td.dataset.manualCode] || "") + " " + td.dataset.date + " " + MANUAL_WORD }); - input.value = digitsOf(td); + input.value = inputOf(td); const g = td.querySelector(".v-gross"); input.placeholder = digitsOf(td) ? "" : (g ? g.textContent.trim().replace(/[–-]/, "") : "") || MANUAL_WORD; td.classList.add("is-editing"); diff --git a/docs/DEPLOYMENT.md b/docs/DEPLOYMENT.md index afc8ea8..a81f8ee 100644 --- a/docs/DEPLOYMENT.md +++ b/docs/DEPLOYMENT.md @@ -252,6 +252,22 @@ docker exec postgres-db psql -U postgres -d performance_db -c "\dt perf_ad_*" 되돌리기(광고 API 인증정보·상태만 사라짐, 가져온 광고비는 perf_ad_spend 에 남음): `docker exec postgres-db psql -U postgres -d performance_db -c "DROP TABLE perf_ad_source_status, perf_ad_credentials;"` +## 실적 날짜 칸 계산식 마이그레이션 (performance_db 008) + +008은 `perf_manual_sales.formula`·`perf_ad_spend.formula` 열 두 개만 추가한다(기존 행·값 그대로, 다시 실행 가능). 002·005 다음에 적용한다. +날짜 칸에 `1000+2000` 같은 계산식을 넣으면 금액은 계산 결과로 저장되고 식은 이 열에 남는다(다시 누르면 식, 파랑 굵은 숫자). +미적용이어도 앱은 그대로 동작한다 — 계산 결과만 저장되고 식·굵은 표시는 남지 않는다. + +```bash +cd /opt/www/main +docker exec postgres-db pg_dump -U postgres performance_db > ~/performance_db_before_008_$(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_008_cell_formula.sql +docker exec postgres-db psql -U postgres -d performance_db -c "\d perf_ad_spend" -c "\d perf_manual_sales" +``` + +되돌리기(계산식 표시만 사라짐, 금액 그대로): +`docker exec postgres-db psql -U postgres -d performance_db -c "ALTER TABLE perf_manual_sales DROP COLUMN formula; ALTER TABLE perf_ad_spend DROP COLUMN formula;"` + ## 회의록 작업 등록 표 — 작업 칸 마이그레이션 (026) 026은 `goal_meeting_tasks.parent_task_id` 열만 추가한다(기존 값 그대로, 다시 실행 가능). 025 뒤에 적용한다. 미적용이면 작업 칸을 고를 때만 503 안내. diff --git a/scripts/sql/performance_db_008_cell_formula.sql b/scripts/sql/performance_db_008_cell_formula.sql new file mode 100644 index 0000000..74ef231 --- /dev/null +++ b/scripts/sql/performance_db_008_cell_formula.sql @@ -0,0 +1,22 @@ +-- ===================================================================== +-- performance_db 마이그레이션 008 — 날짜 칸 계산식(매출 수동 입력·광고비) +-- ===================================================================== +-- 멱등(idempotent). 열 두 개만 추가(기존 행·값 그대로). 002·005 다음에 적용. +-- docker exec -i postgres-db psql -v ON_ERROR_STOP=1 -U postgres -d performance_db \ +-- < scripts/sql/performance_db_008_cell_formula.sql +-- +-- 왜(2026-10-21 사용자 요청): 날짜 칸에 엑셀처럼 계산식(= 없이 1000+2000)을 넣으면 바로 계산해 금액으로 저장하고, +-- 식도 함께 남겨 다시 누르면 식이 보이고 화면에서는 파랑 굵은 숫자로 구분한다. 금액(amount)은 계산 결과 그대로라 +-- 집계·합계는 이 열을 보지 않는다. 미적용이면 계산 결과만 저장되고 식은 남지 않는다(앱은 그대로 동작). +-- 되돌리기: ALTER TABLE perf_manual_sales DROP COLUMN formula; ALTER TABLE perf_ad_spend DROP COLUMN formula; +-- (계산식 표시만 사라짐 — 실행 전 백업) +-- ===================================================================== +BEGIN; + +ALTER TABLE perf_manual_sales ADD COLUMN IF NOT EXISTS formula TEXT; +ALTER TABLE perf_ad_spend ADD COLUMN IF NOT EXISTS formula TEXT; +COMMENT ON COLUMN perf_manual_sales.formula IS '날짜 칸에 입력한 계산식(예: 1000+2000) — amount 는 계산 결과. NULL = 숫자 입력·업로드'; +COMMENT ON COLUMN perf_ad_spend.formula IS '날짜 칸에 입력한 계산식(예: 1000+2000) — amount 는 계산 결과. NULL = 숫자 입력·업로드·API'; + +COMMIT; +SELECT 'performance_db 008 cell formula ready' AS status;